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
9f2e60ea742c1b18c8fd078db20b5f1a4e8f410d
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/universal/comma_categories.lean
b7790b80a03203a84b826440e2f70f9f3dc3f67b
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
4,467
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 ..discrete_category import ..graph import .initial open tqft.categories open tqft.categories.isomorphism open tqft.categories.graph open tqft.categories.functor open tqft.categories.natural_transformation open tqft.categories.initial namespace tqft.categories.comma -- The diagonal functor sends X to the constant functor that sends everything to X. definition DiagonalFunctor ( J C : Category ) : Functor C (FunctorCategory J C) := { onObjects := λ X : C.Obj, { onObjects := λ _, X, onMorphisms := λ _ _ _, C.identity X, identities := ♮, functoriality := ♮ }, onMorphisms := λ X Y f, { components := λ _, f, naturality := ♮ }, identities := ♮, functoriality := ♮ } -- unfortunately one can't coerce along subtype.val open subtype local attribute [ematch] subtype.property -- The elaborator has some trouble understanding what p.2.2 and q.2.2 mean below. -- Leo suggested the following work-around, at <https://groups.google.com/d/msg/lean-user/8jW4BIUFl24/MOtgbpfqCAAJ>. local attribute [elab_simple] sigma.snd definition CommaCategory { A B C : Category } ( S : Functor A C ) ( T : Functor B C ) : Category := { Obj := Σ a : A.Obj, Σ b : B.Obj, C.Hom (S a) (T b), Hom := λ p q, { gh : (A.Hom p.1 q.1) × (B.Hom p.2.1 q.2.1) // C.compose (S.onMorphisms gh.1) q.2.2 = C.compose p.2.2 (T.onMorphisms gh.2) }, identity := λ p, ⟨ (A.identity p.1, B.identity p.2.1), ♮ ⟩, compose := λ p q r f g, ⟨ (A.compose (val f).1 (val g).1, B.compose (val f).2 (val g).2), ♮ ⟩, left_identity := ♯, right_identity := ♯, associativity := ♮ } definition ObjectAsFunctor { C : Category } ( X : C.Obj ) : Functor (DiscreteCategory unit) C := { onObjects := λ _, X, onMorphisms := λ _ _ _, C.identity X, identities := ♮, functoriality := ♮ } definition SliceCategory { C : Category } ( X : C.Obj ) := CommaCategory (IdentityFunctor C) (ObjectAsFunctor X) definition CosliceCategory { C : Category } ( X : C.Obj ) := CommaCategory (ObjectAsFunctor X) (IdentityFunctor C) -- In Cones, we have -- A = C -- B = . -- C = FunctorCategory J C definition Cones { J C : Category } ( F : Functor J C ) := CommaCategory (DiagonalFunctor J C) (ObjectAsFunctor F) definition Cocones { J C : Category } ( F : Functor J C ) := CommaCategory (@ObjectAsFunctor (FunctorCategory J C) F) (DiagonalFunctor J C) definition Limit { J C : Category } ( F: Functor J C ) := TerminalObject (Cones F) definition Colimit { J C : Category } ( F: Functor J C ) := InitialObject (Cocones F) inductive Two : Type | _0 : Two | _1 : Two open Two definition WalkingPair : Graph := { vertices := Two, edges := λ X Y, empty } definition WalkingParallelPair : Graph := { vertices := Two, edges := λ X Y, match X, Y with | _0, _1 := Two | _, _ := empty end } definition Pair_homomorphism { C : Category } ( α β : C.Obj ) : GraphHomomorphism WalkingPair C := { onVertices := λ X, match X with | _0 := α | _1 := β end, onEdges := λ X Y e, match X, Y, e with end } definition ParallelPair_homomorphism { C : Category } { α β : C.Obj } ( f g : C.Hom α β ) : GraphHomomorphism WalkingParallelPair C := { onVertices := λ X, match X with | _0 := α | _1 := β end, onEdges := λ X Y e, match X, Y, e with | _0, _1, _0 := f | _0, _1, _1 := g end } definition Product { C : Category } ( α β : C.Obj ) := Limit (Functor.from_GraphHomomorphism (Pair_homomorphism α β)) definition Coproduct { C : Category } ( α β : C.Obj ) := Colimit (Functor.from_GraphHomomorphism (Pair_homomorphism α β)) definition Equalizer { C : Category } { α β : C.Obj } ( f g : C.Hom α β ) := Limit (Functor.from_GraphHomomorphism (ParallelPair_homomorphism f g)) definition Coequalizer { C : Category } { α β : C.Obj } ( f g : C.Hom α β ) := Colimit (Functor.from_GraphHomomorphism (ParallelPair_homomorphism f g)) end tqft.categories.comma
47dc97db77c5d94b2ab91eec16c988428f579e42
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/175.lean
b5353fb7a796e01a36717758726b6436e36869aa
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
468
lean
import Lean namespace Foo open Lean.Elab.Term syntax[fooKind] "foo!" term : term @[termElab fooKind] def elabFoo : TermElab := fun stx expectedType? => elabTerm (stx.getArg 1) expectedType? #check foo! 10 end Foo namespace Lean namespace Elab namespace Tactic open Meta @[builtinTactic clear] def myEvalClear : Tactic := -- this fails in the old-frontend because it eagerly resolves `clear` as `Lean.Meta.clear`. fun _ => pure () end Tactic end Elab end Lean
ef6f82f4e6f9b41a78c32f2da45526e00bd94b27
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/category_theory/limits/preserves/functor_category.lean
1620fd098ed4d8bf59542aa6d912b551f81fcce2
[ "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
2,566
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.presheaf import category_theory.limits.functor_category import category_theory.limits.shapes.constructions.preserve_binary_products /-! # Preservation of (co)limits in the functor category Show that if `X ⨯ -` preserves colimits in `D` for any `X : D`, then the product functor `F ⨯ -` for `F : C ⥤ D` preserves colimits. The idea of the proof is simply that products and colimits in the functor category are computed pointwise, so pointwise preservation implies general preservation. # References https://ncatlab.org/nlab/show/commutativity+of+limits+and+colimits#preservation_by_functor_categories_and_localizations -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open category limits variables {C : Type v₂} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] /-- If `X × -` preserves colimits in `D` for any `X : D`, then the product functor `F ⨯ -` for `F : C ⥤ D` also preserves colimits. Note this is (mathematically) a special case of the statement that "if limits commute with colimits in `D`, then they do as well in `C ⥤ D`" but the story in Lean is a bit more complex, and this statement isn't directly a special case. That is, even with a formalised proof of the general statement, there would still need to be some work to convert to this version: namely, the natural isomorphism `(evaluation C D).obj k ⋙ prod.functor.obj (F.obj k) ≅ prod.functor.obj F ⋙ (evaluation C D).obj k` -/ def functor_category.prod_preserves_colimits [has_binary_products D] [has_colimits D] [∀ (X : D), preserves_colimits (prod.functor.obj X)] (F : C ⥤ D) : preserves_colimits (prod.functor.obj F) := { preserves_colimits_of_shape := λ J 𝒥, by exactI { preserves_colimit := λ K, { preserves := λ c t, begin apply evaluation_jointly_reflects_colimits _ (λ k, _), change is_colimit ((prod.functor.obj F ⋙ (evaluation _ _).obj k).map_cocone c), let := is_colimit_of_preserves ((evaluation C D).obj k ⋙ prod.functor.obj (F.obj k)) t, apply is_colimit.map_cocone_equiv _ this, apply (nat_iso.of_components _ _).symm, { intro G, apply as_iso (prod_comparison ((evaluation C D).obj k) F G) }, { intros G G', apply prod_comparison_natural ((evaluation C D).obj k) (𝟙 F) }, end } } } end category_theory
8d4e6b2c99d147d9e0b4e3d7e6fdd55c9a787f21
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/topology/algebra/monoid.lean
0029c24c058f285538221d8d006b4f0179d23e28
[ "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
12,430
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.basic import algebra.group.prod import algebra.pointwise /-! # 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 {α β M N : Type*} /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `α`, for example, is obtained by requiring both the instances `add_monoid α` and `has_continuous_add α`. -/ 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 `α`, for example, is obtained by requiring both the instances `monoid α` and `has_continuous_mul α`. -/ @[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 [topological_space α] {f : α → M} {g : α → 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 [topological_space α] {f : α → M} {g : α → M} {s : set α} (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 : α → M} {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 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 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 [topological_space α] {f : α → M} {g : α → M} {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 [topological_space α] {f : α → M} {g : α → M} {s : set α} {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))⟩ @[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⟩ } 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, mem_nhds_sets 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 β, (∀c∈l, tendsto (f c) x (𝓝 (a c))) → 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 [topological_space α] {f : β → α → M} (l : list β) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c 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) := show continuous (λ (a : M), a * a ^ k), from continuous_id.mul (continuous_pow _) @[continuity] lemma continuous.pow {f : α → M} [topological_space α] (h : continuous f) (n : ℕ) : continuous (λ b, (f b) ^ n) := continuous.comp (continuous_pow n) h end has_continuous_mul 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) := mem_nhds_sets oS S.one_mem variable [has_continuous_mul M] @[to_additive] lemma tendsto_multiset_prod {f : β → α → M} {x : filter α} {a : β → M} (s : multiset β) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : β → α → M} {x : filter α} {a : β → M} (s : finset β) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := tendsto_multiset_prod _ @[to_additive, continuity] lemma continuous_multiset_prod [topological_space α] {f : β → α → M} (s : multiset β) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } attribute [continuity] continuous_multiset_sum @[continuity, to_additive] lemma continuous_finset_prod [topological_space α] {f : β → α → M} (s : finset β) : (∀c∈s, continuous (f c)) → continuous (λa, ∏ c in s, f c a) := continuous_multiset_prod _ -- should `to_additive` be doing this? attribute [continuity] continuous_finset_sum 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 _ _ _ }
31826ee6e8fc8998cdf0f8911f95c6ac869c365a
66a6486e19b71391cc438afee5f081a4257564ec
/pointed.hlean
7ee1e9806dcfce9d0581e107ec14f34324a4a289
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
13,409
hlean
/- equalities between pointed homotopies and other facts about pointed types/functions/homotopies -/ -- Author: Floris van Doorn import types.pointed2 .move_to_lib open pointed eq equiv function is_equiv unit is_trunc trunc nat algebra sigma group lift option namespace pointed -- /- the pointed type of (unpointed) dependent maps -/ -- definition pupi [constructor] {A : Type} (P : A → Type*) : Type* := -- pointed.mk' (Πa, P a) -- definition loop_pupi_commute {A : Type} (B : A → Type*) : Ω(pupi B) ≃* pupi (λa, Ω (B a)) := -- pequiv_of_equiv eq_equiv_homotopy rfl -- definition equiv_pupi_right {A : Type} {P Q : A → Type*} (g : Πa, P a ≃* Q a) -- : pupi P ≃* pupi Q := -- pequiv_of_equiv (pi_equiv_pi_right g) -- begin esimp, apply eq_of_homotopy, intros a, esimp, exact (respect_pt (g a)) end -- definition pmap_eq_equiv {X Y : Type*} (f g : X →* Y) : (f = g) ≃ (f ~* g) := -- begin -- refine eq_equiv_fn_eq_of_equiv (@pmap.sigma_char X Y) f g ⬝e _, -- refine !sigma_eq_equiv ⬝e _, -- refine _ ⬝e (phomotopy.sigma_char f g)⁻¹ᵉ, -- fapply sigma_equiv_sigma, -- { esimp, apply eq_equiv_homotopy }, -- { induction g with g gp, induction Y with Y y0, esimp, intro p, induction p, esimp at *, -- refine !pathover_idp ⬝e _, refine _ ⬝e !eq_equiv_eq_symm, -- apply equiv_eq_closed_right, exact !idp_con⁻¹ } -- end definition ppcompose_left_pid [constructor] (A B : Type*) : ppcompose_left (pid B) ~* pid (ppmap A B) := phomotopy_mk_ppmap (λf, pid_pcompose f) (!trans_refl ⬝ !phomotopy_of_eq_of_phomotopy⁻¹) definition ppcompose_right_pid [constructor] (A B : Type*) : ppcompose_right (pid A) ~* pid (ppmap A B) := phomotopy_mk_ppmap (λf, pcompose_pid f) (!trans_refl ⬝ !phomotopy_of_eq_of_phomotopy⁻¹) /- remove some duplicates: loop_ppmap_commute, loop_ppmap_pequiv, loop_ppmap_pequiv', pfunext -/ definition pfunext (X Y : Type*) : ppmap X (Ω Y) ≃* Ω (ppmap X Y) := (loop_ppmap_commute X Y)⁻¹ᵉ* definition loop_phomotopy [constructor] {A B : Type*} (f : A →* B) : Type* := pointed.MK (f ~* f) phomotopy.rfl definition ppcompose_left_loop_phomotopy [constructor] {A B C : Type*} (g : B →* C) {f : A →* B} {h : A →* C} (p : g ∘* f ~* h) : loop_phomotopy f →* loop_phomotopy h := pmap.mk (λq, p⁻¹* ⬝* pwhisker_left g q ⬝* p) (idp ◾** !pwhisker_left_refl ◾** idp ⬝ !trans_refl ◾** idp ⬝ !trans_left_inv) definition ppcompose_left_loop_phomotopy' [constructor] {A B C : Type*} (g : B →* C) (f : A →* B) : loop_phomotopy f →* loop_phomotopy (g ∘* f) := pmap.mk (λq, pwhisker_left g q) !pwhisker_left_refl definition loop_ppmap_pequiv' [constructor] (A B : Type*) : Ω(ppmap A B) ≃* loop_phomotopy (pconst A B) := pequiv_of_equiv (pmap_eq_equiv _ _) idp definition ppmap_loop_pequiv' [constructor] (A B : Type*) : loop_phomotopy (pconst A B) ≃* ppmap A (Ω B) := pequiv_of_equiv (!phomotopy.sigma_char ⬝e !pmap.sigma_char⁻¹ᵉ) idp definition loop_ppmap_pequiv [constructor] (A B : Type*) : Ω(ppmap A B) ≃* ppmap A (Ω B) := loop_ppmap_pequiv' A B ⬝e* ppmap_loop_pequiv' A B definition loop_ppmap_pequiv'_natural_right' {X X' : Type} (x₀ : X) (A : Type*) (f : X → X') : psquare (loop_ppmap_pequiv' A _) (loop_ppmap_pequiv' A _) (Ω→ (ppcompose_left (pmap_of_map f x₀))) (ppcompose_left_loop_phomotopy' (pmap_of_map f x₀) !pconst) := begin fapply phomotopy.mk, { esimp, intro p, refine _ ⬝ ap011 (λx y, phomotopy_of_eq (ap1_gen _ x y _)) proof !eq_of_phomotopy_refl⁻¹ qed proof !eq_of_phomotopy_refl⁻¹ qed, refine _ ⬝ ap phomotopy_of_eq !ap1_gen_idp_left⁻¹, exact !phomotopy_of_eq_pcompose_left⁻¹ }, { refine _ ⬝ !idp_con⁻¹, exact sorry } end definition loop_ppmap_pequiv'_natural_right {X X' : Type*} (A : Type*) (f : X →* X') : psquare (loop_ppmap_pequiv' A X) (loop_ppmap_pequiv' A X') (Ω→ (ppcompose_left f)) (ppcompose_left_loop_phomotopy f !pcompose_pconst) := begin induction X' with X' x₀', induction f with f f₀, esimp at f, esimp at f₀, induction f₀, apply psquare_of_phomotopy, exact sorry end definition ppmap_loop_pequiv'_natural_right {X X' : Type*} (A : Type*) (f : X →* X') : psquare (ppmap_loop_pequiv' A X) (ppmap_loop_pequiv' A X') (ppcompose_left_loop_phomotopy f !pcompose_pconst) (ppcompose_left (Ω→ f)) := begin exact sorry end definition loop_pmap_commute_natural_right_direct {X X' : Type*} (A : Type*) (f : X →* X') : psquare (loop_ppmap_pequiv A X) (loop_ppmap_pequiv A X') (Ω→ (ppcompose_left f)) (ppcompose_left (Ω→ f)) := begin induction X' with X' x₀', induction f with f f₀, esimp at f, esimp at f₀, induction f₀, -- refine _ ⬝* _ ◾* _, rotate 4, fapply phomotopy.mk, { intro p, esimp, esimp [pmap_eq_equiv, pcompose_pconst], exact sorry }, { exact sorry } end definition loop_pmap_commute_natural_left {A A' : Type*} (X : Type*) (f : A' →* A) : psquare (loop_ppmap_commute A X) (loop_ppmap_commute A' X) (Ω→ (ppcompose_right f)) (ppcompose_right f) := sorry definition loop_pmap_commute_natural_right {X X' : Type*} (A : Type*) (f : X →* X') : psquare (loop_ppmap_commute A X) (loop_ppmap_commute A X') (Ω→ (ppcompose_left f)) (ppcompose_left (Ω→ f)) := loop_ppmap_pequiv'_natural_right A f ⬝h* ppmap_loop_pequiv'_natural_right A f /- Do we want to use a structure of homotopies between pointed homotopies? Or are equalities fine? If we set up things more generally, we could define this as "pointed homotopies between the dependent pointed maps p and q" -/ structure phomotopy2 {A B : Type*} {f g : A →* B} (p q : f ~* g) : Type := (homotopy_eq : p ~ q) (homotopy_pt_eq : whisker_right (respect_pt g) (homotopy_eq pt) ⬝ to_homotopy_pt q = to_homotopy_pt p) /- this sets it up more generally, for illustrative purposes -/ structure ppi' (A : Type*) (P : A → Type) (p : P pt) := (to_fun : Π a : A, P a) (resp_pt : to_fun (Point A) = p) attribute ppi'.to_fun [coercion] definition phomotopy' {A : Type*} {P : A → Type} {x : P pt} (f g : ppi' A P x) : Type := ppi' A (λa, f a = g a) (ppi'.resp_pt f ⬝ (ppi'.resp_pt g)⁻¹) definition phomotopy2' {A : Type*} {P : A → Type} {x : P pt} {f g : ppi' A P x} (p q : phomotopy' f g) : Type := phomotopy' p q -- infix ` ~*2 `:50 := phomotopy2 -- variables {A B : Type*} {f g : A →* B} (p q : f ~* g) -- definition phomotopy_eq_equiv_phomotopy2 : p = q ≃ p ~*2 q := -- sorry /- Homotopy between a function and its eta expansion -/ definition pmap_eta {X Y : Type*} (f : X →* Y) : f ~* pmap.mk f (respect_pt f) := begin fapply phomotopy.mk, reflexivity, esimp, exact !idp_con end -- this should replace pnatural_square definition pnatural_square2 {A B : Type} (X : B → Type*) (Y : B → Type*) {f g : A → B} (h : Πa, X (f a) →* Y (g a)) {a a' : A} (p : a = a') : h a' ∘* ptransport X (ap f p) ~* ptransport Y (ap g p) ∘* h a := by induction p; exact !pcompose_pid ⬝* !pid_pcompose⁻¹* definition ptransport_ap {A B : Type} (X : B → Type*) (f : A → B) {a a' : A} (p : a = a') : ptransport X (ap f p) ~* ptransport (X ∘ f) p := by induction p; reflexivity definition ptransport_constant (A : Type) (B : Type*) {a a' : A} (p : a = a') : ptransport (λ(a : A), B) p ~* pid B := by induction p; reflexivity definition ptransport_natural {A : Type} (X : A → Type*) (Y : A → Type*) (h : Πa, X a →* Y a) {a a' : A} (p : a = a') : h a' ∘* ptransport X p ~* ptransport Y p ∘* h a := by induction p; exact !pcompose_pid ⬝* !pid_pcompose⁻¹* section psquare variables {A A' A₀₀ A₂₀ A₄₀ A₀₂ A₂₂ A₄₂ A₀₄ A₂₄ A₄₄ : Type*} {f₁₀ f₁₀' : A₀₀ →* A₂₀} {f₃₀ : A₂₀ →* A₄₀} {f₀₁ f₀₁' : A₀₀ →* A₀₂} {f₂₁ f₂₁' : A₂₀ →* A₂₂} {f₄₁ : A₄₀ →* A₄₂} {f₁₂ f₁₂' : A₀₂ →* A₂₂} {f₃₂ : A₂₂ →* A₄₂} {f₀₃ : A₀₂ →* A₀₄} {f₂₃ : A₂₂ →* A₂₄} {f₄₃ : A₄₂ →* A₄₄} {f₁₄ : A₀₄ →* A₂₄} {f₃₄ : A₂₄ →* A₄₄} definition ptranspose (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : psquare f₀₁ f₂₁ f₁₀ f₁₂ := p⁻¹* definition hsquare_of_psquare (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : hsquare f₁₀ f₁₂ f₀₁ f₂₁ := p definition homotopy_group_functor_hsquare (n : ℕ) (h : psquare f₁₀ f₁₂ f₀₁ f₂₁) : psquare (π→[n] f₁₀) (π→[n] f₁₂) (π→[n] f₀₁) (π→[n] f₂₁) := sorry end psquare definition ap1_pequiv_ap {A : Type} (B : A → Type*) {a a' : A} (p : a = a') : Ω→ (pequiv_ap B p) ~* pequiv_ap (Ω ∘ B) p := begin induction p, apply ap1_pid end definition pequiv_ap_natural {A : Type} (B C : A → Type*) {a a' : A} (p : a = a') (f : Πa, B a →* C a) : psquare (pequiv_ap B p) (pequiv_ap C p) (f a) (f a') := begin induction p, exact phrfl end definition is_contr_loop (A : Type*) [is_set A] : is_contr (Ω A) := is_contr.mk idp (λa, !is_prop.elim) definition is_contr_loop_of_is_contr {A : Type*} (H : is_contr A) : is_contr (Ω A) := is_contr_loop A definition is_contr_punit [instance] : is_contr punit := is_contr_unit definition pequiv_of_is_contr (A B : Type*) (HA : is_contr A) (HB : is_contr B) : A ≃* B := pequiv_punit_of_is_contr A _ ⬝e* (pequiv_punit_of_is_contr B _)⁻¹ᵉ* definition loop_pequiv_punit_of_is_set (X : Type*) [is_set X] : Ω X ≃* punit := pequiv_punit_of_is_contr _ (is_contr_loop X) definition loop_punit : Ω punit ≃* punit := loop_pequiv_punit_of_is_set punit definition add_point_functor' [unfold 4] {A B : Type} (e : A → B) (a : A₊) : B₊ := begin induction a with a, exact none, exact some (e a) end definition add_point_functor [constructor] {A B : Type} (e : A → B) : A₊ →* B₊ := pmap.mk (add_point_functor' e) idp definition add_point_functor_compose {A B C : Type} (f : B → C) (e : A → B) : add_point_functor (f ∘ e) ~* add_point_functor f ∘* add_point_functor e := begin fapply phomotopy.mk, { intro x, induction x: reflexivity }, reflexivity end definition add_point_functor_id (A : Type) : add_point_functor id ~* pid A₊ := begin fapply phomotopy.mk, { intro x, induction x: reflexivity }, reflexivity end definition add_point_functor_phomotopy {A B : Type} {e e' : A → B} (p : e ~ e') : add_point_functor e ~* add_point_functor e' := begin fapply phomotopy.mk, { intro x, induction x with a, reflexivity, exact ap some (p a) }, reflexivity end definition add_point_pequiv {A B : Type} (e : A ≃ B) : A₊ ≃* B₊ := pequiv.MK (add_point_functor e) (add_point_functor e⁻¹ᵉ) abstract !add_point_functor_compose⁻¹* ⬝* add_point_functor_phomotopy (left_inv e) ⬝* !add_point_functor_id end abstract !add_point_functor_compose⁻¹* ⬝* add_point_functor_phomotopy (right_inv e) ⬝* !add_point_functor_id end definition add_point_over [unfold 3] {A : Type} (B : A → Type*) : A₊ → Type* | (some a) := B a | none := plift punit definition add_point_over_pequiv {A : Type} {B B' : A → Type*} (e : Πa, B a ≃* B' a) : Π(a : A₊), add_point_over B a ≃* add_point_over B' a | (some a) := e a | none := pequiv.rfl definition phomotopy_group_plift_punit.{u} (n : ℕ) [H : is_at_least_two n] : πag[n] (plift.{0 u} punit) ≃g trivial_ab_group_lift.{u} := begin induction H with n, have H : 0 <[ℕ] n+2, from !zero_lt_succ, have is_set unit, from _, have is_trunc (trunc_index.of_nat 0) punit, from this, exact isomorphism_of_is_contr (@trivial_homotopy_group_of_is_trunc _ _ _ !is_trunc_lift H) !is_trunc_lift end definition pmap_of_map_pt [constructor] {A : Type*} {B : Type} (f : A → B) : A →* pointed.MK B (f pt) := pmap.mk f idp /- TODO: computation rule -/ open pi definition fiberwise_pointed_map_rec {A : Type} {B : A → Type*} (P : Π(C : A → Type*) (g : Πa, B a →* C a), Type) (H : Π(C : A → Type) (g : Πa, B a → C a), P _ (λa, pmap_of_map_pt (g a))) : Π⦃C : A → Type*⦄ (g : Πa, B a →* C a), P C g := begin refine equiv_rect (!sigma_pi_equiv_pi_sigma ⬝e arrow_equiv_arrow_right A !pType.sigma_char⁻¹ᵉ) _ _, intro R, cases R with R r₀, refine equiv_rect (!sigma_pi_equiv_pi_sigma ⬝e pi_equiv_pi_right (λa, !pmap.sigma_char⁻¹ᵉ)) _ _, intro g, cases g with g g₀, esimp at (g, g₀), revert g₀, change (Π(g : (λa, g a (Point (B a))) ~ r₀), _), refine homotopy.rec_idp _ _, esimp, apply H end definition ap1_gen_idp_eq {A B : Type} (f : A → B) {a : A} (q : f a = f a) (r : q = idp) : ap1_gen_idp f q = ap (λx, ap1_gen f x x idp) r := begin cases r, reflexivity end end pointed
390ee8d3d0bef9d581d3fcf3cb0ce73a03e40535
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/category_theory/opposites.lean
1ccdaf14731bbb7e2b8a48f3de9c4b6ec0151d35
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
2,177
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import category_theory.functor import category_theory.products import category_theory.types namespace category_theory universes u₁ v₁ u₂ v₂ def op (C : Type u₁) : Type u₁ := C notation C `ᵒᵖ` := op C variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] include 𝒞 instance opposite : category.{u₁ v₁} (Cᵒᵖ) := { hom := λ X Y : C, Y ⟶ X, comp := λ _ _ _ f g, g ≫ f, id := λ X, 𝟙 X, id_comp' := begin /- `obviously'` says: -/ intros, simp end, comp_id' := begin /- `obviously'` says: -/ intros, simp end, assoc' := begin /- `obviously'` says: -/ intros, simp end } namespace functor section variables {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒟 protected definition op (F : C ↝ D) : (Cᵒᵖ) ↝ (Dᵒᵖ) := { obj := λ X, F X, map' := λ X Y f, F.map f, map_id' := begin /- `obviously'` says: -/ intros, erw [map_id], refl, end, map_comp' := begin /- `obviously'` says: -/ intros, erw [map_comp], refl end } @[simp] lemma opposite_obj (F : C ↝ D) (X : C) : (F.op) X = F X := rfl @[simp] lemma opposite_map (F : C ↝ D) {X Y : C} (f : X ⟶ Y) : (F.op).map f = F.map f := rfl end variable (C) /-- `functor.hom` is the hom-pairing, sending (X,Y) to X → Y, contravariant in X and covariant in Y. -/ definition hom : (Cᵒᵖ × C) ↝ (Type v₁) := { obj := λ p, @category.hom C _ p.1 p.2, map' := λ X Y f, λ h, f.1 ≫ h ≫ f.2, map_id' := begin /- `obviously'` says: -/ intros, ext, intros, cases X, dsimp at *, simp, erw [category.id_comp] end, map_comp' := begin /- `obviously'` says: -/ intros, ext, intros, cases f, cases g, cases X, cases Y, cases Z, dsimp at *, simp, erw [category.assoc] end } @[simp] lemma hom_obj (X : Cᵒᵖ × C) : (functor.hom C) X = @category.hom C _ X.1 X.2 := rfl @[simp] lemma hom_pairing_map {X Y : Cᵒᵖ × C} (f : X ⟶ Y) : (functor.hom C).map f = λ h, f.1 ≫ h ≫ f.2 := rfl end functor end category_theory
9c839fd31935732d81fc7edd6ca63adf96322ad3
75c54c8946bb4203e0aaf196f918424a17b0de99
/src/parse_formula.lean
992eb01e19c4a932d7d019af53845b12346b5137
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
4,044
lean
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Jesse Michael Han, Floris van Doorn Parsing formulas from Lean expressions. -/ import .abel .fol tactic data.list universe u /- toy example by Mario -/ section fmla @[derive has_reflect] inductive fmla | var : nat → fmla | pi : fmla → fmla meta def to_fmla : pexpr → option fmla | (expr.var n) := some (fmla.var n) | (expr.pi _ _ _ e) := fmla.pi <$> to_fmla e | _ := none end fmla namespace tactic namespace interactive section parse_fmla open interactive interactive.types expr meta def parse_fmla (e : parse texpr) : tactic unit := do f <- to_fmla e, tactic.exact `(f) end parse_fmla end interactive end tactic def foo : fmla := by parse_fmla (∀ x : ℕ, x) -- #print foo -- fmla.pi (fmla.var 0) /- end toy example -/ open fol meta instance preterm.reflect {L : Language.{0}} [reflected L] [∀ n, has_reflect (L.functions n)] : ∀{n}, has_reflect (preterm L n) | _ &k := `(&k) | _ (func f) := `(func f) | _ (app t₁ t₂) := (`(λ x y, app x y).subst (preterm.reflect t₁)).subst (preterm.reflect t₂) meta instance preformula.reflect {L : Language.{0}} [reflected L] [∀ n, has_reflect (L.functions n)] [∀ n, has_reflect (L.relations n)] : ∀{n}, has_reflect (preformula L n) | _ falsum := `(falsum) | _ (equal t₁ t₂) := (`(λ x₁ x₂, equal x₁ x₂).subst (preterm.reflect t₁)).subst (preterm.reflect t₂) | _ (rel R) := `(λ x, preformula.rel x).subst `(R) | _ (apprel f t) := (`(λ x₁ x₂, apprel x₁ x₂).subst (preformula.reflect f)).subst (preterm.reflect t) | _ (imp f₁ f₂) := (`(λ x₁ x₂, imp x₁ x₂).subst (preformula.reflect f₁)).subst (preformula.reflect f₂) | _ (all f) := `(λ x, all x).subst (preformula.reflect f) meta instance L_empty.reflect : reflected L_empty := by apply_instance meta instance L_empty_functions_reflect : ∀ n, has_reflect (L_empty.functions n) := λ _ _, empty.elim ‹_› meta instance L_empty_relations_reflect : ∀ n, has_reflect (L_empty.relations n) := λ _ _, empty.elim ‹_› section L_empty_parse meta def to_term_empty : Π {n : ℕ}, expr → option (preterm L_empty n) | 0 (expr.var k) := some (var k) | _ _ := none -- TODO(jesse) insert a case analysis on whether e' : Prop to determine whether or not to use imp meta def to_formula_empty : Π {n : ℕ}, expr → option (preformula L_empty n) | 0 (expr.pi _ _ e' e) := ((to_formula_empty e) >>= (λ f, return (all f))) | 0 `(%%a = %%b) := do e₁ <- to_term_empty a, e₂ <- to_term_empty b, return $ equal e₁ e₂ -- | 0 `(%%a → %%b) := do e₁ <- to_formula_empty a, e₂ <- to_formula_empty b, -- return $ imp e₁ e₂ -- equation compiler thinks this case -- is redundant since a → b compiles to Π _ : a, b | 0 `(false) := return (falsum) | 0 _ := none | (n+1) _ := none end L_empty_parse namespace tactic namespace interactive open interactive interactive.types expr meta def parse_formula (t : parse texpr) : tactic unit := do f <- ((@to_formula_empty 0) <$> (to_expr t)), match f with | (some ϕ) := tactic.exact `(ϕ) | none := tactic.fail "to_formula_empty failed to parse" end end interactive end tactic -- meta def test : expr := `(true → true) -- meta def test' : expr := `(∀ x : ℕ, x = 0) -- #eval (@expr.to_raw_fmt tt test).to_string -- #eval (@expr.to_raw_fmt tt test').to_string constant α : Type def my_little_formula : preformula L_empty 0 := by parse_formula (∀ x : α, x = x) def my_larger_formula : preformula L_empty 0 := by parse_formula (∀ x y : α, (x = y)) -- #reduce my_little_formula -- it works! -- ∀'(&0 ≃ &0) -- #print my_larger_formula -- it still works! -- ∀'∀'(&1 ≃ &0)
fbc1fe623ae96b82022ac0563f00b9371cfcd696
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/src/Lean/Declaration.lean
71d9f8c902db56c00f3234a519199f92afbff2db
[ "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
13,516
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean /-- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` Constructor are: the definitional height and the flag `selfOpt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during Type checking. Remark: the ReducibilityHints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the Elaborator. The ReducibilityHints are used by the kernel (and Elaborator). Moreover, the ReducibilityHints cannot be changed after a declaration is added to the kernel. -/ inductive ReducibilityHints where | opaque : ReducibilityHints | «abbrev» : ReducibilityHints | regular : UInt32 → ReducibilityHints deriving Inhabited @[export lean_mk_reducibility_hints_regular] def mkReducibilityHintsRegularEx (h : UInt32) : ReducibilityHints := ReducibilityHints.regular h @[export lean_reducibility_hints_get_height] def ReducibilityHints.getHeightEx (h : ReducibilityHints) : UInt32 := match h with | ReducibilityHints.regular h => h | _ => 0 namespace ReducibilityHints def lt : ReducibilityHints → ReducibilityHints → Bool | «abbrev», «abbrev» => false | «abbrev», _ => true | regular d₁, regular d₂ => d₁ < d₂ | regular _, opaque => true | _, _ => false end ReducibilityHints /-- Base structure for `AxiomVal`, `DefinitionVal`, `TheoremVal`, `InductiveVal`, `ConstructorVal`, `RecursorVal` and `QuotVal`. -/ structure ConstantVal where name : Name lparams : List Name type : Expr deriving Inhabited structure AxiomVal extends ConstantVal where isUnsafe : Bool @[export lean_mk_axiom_val] def mkAxiomValEx (name : Name) (lparams : List Name) (type : Expr) (isUnsafe : Bool) : AxiomVal := { name := name, lparams := lparams, type := type, isUnsafe := isUnsafe } @[export lean_axiom_val_is_unsafe] def AxiomVal.isUnsafeEx (v : AxiomVal) : Bool := v.isUnsafe inductive DefinitionSafety where | «unsafe» | safe | «partial» deriving Inhabited, BEq, Repr structure DefinitionVal extends ConstantVal where value : Expr hints : ReducibilityHints safety : DefinitionSafety deriving Inhabited @[export lean_mk_definition_val] def mkDefinitionValEx (name : Name) (lparams : List Name) (type : Expr) (val : Expr) (hints : ReducibilityHints) (safety : DefinitionSafety) : DefinitionVal := { name := name, lparams := lparams, type := type, value := val, hints := hints, safety := safety } @[export lean_definition_val_get_safety] def DefinitionVal.getSafetyEx (v : DefinitionVal) : DefinitionSafety := v.safety structure TheoremVal extends ConstantVal where value : Expr /- Value for an opaque constant declaration `constant x : t := e` -/ structure OpaqueVal extends ConstantVal where value : Expr isUnsafe : Bool @[export lean_mk_opaque_val] def mkOpaqueValEx (name : Name) (lparams : List Name) (type : Expr) (val : Expr) (isUnsafe : Bool) : OpaqueVal := { name := name, lparams := lparams, type := type, value := val, isUnsafe := isUnsafe } @[export lean_opaque_val_is_unsafe] def OpaqueVal.isUnsafeEx (v : OpaqueVal) : Bool := v.isUnsafe structure Constructor where name : Name type : Expr structure InductiveType where name : Name type : Expr ctors : List Constructor /-- Declaration object that can be sent to the kernel. -/ inductive Declaration where | axiomDecl (val : AxiomVal) | defnDecl (val : DefinitionVal) | thmDecl (val : TheoremVal) | opaqueDecl (val : OpaqueVal) | quotDecl | mutualDefnDecl (defns : List DefinitionVal) -- All definitions must be marked as `unsafe` or `partial` | inductDecl (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) deriving Inhabited @[export lean_mk_inductive_decl] def mkInductiveDeclEs (lparams : List Name) (nparams : Nat) (types : List InductiveType) (isUnsafe : Bool) : Declaration := Declaration.inductDecl lparams nparams types isUnsafe @[export lean_is_unsafe_inductive_decl] def Declaration.isUnsafeInductiveDeclEx : Declaration → Bool | Declaration.inductDecl _ _ _ isUnsafe => isUnsafe | _ => false @[specialize] def Declaration.foldExprM {α} {m : Type → Type} [Monad m] (d : Declaration) (f : α → Expr → m α) (a : α) : m α := match d with | Declaration.quotDecl => pure a | Declaration.axiomDecl { type := type, .. } => f a type | Declaration.defnDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.opaqueDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.thmDecl { type := type, value := value, .. } => do let a ← f a type; f a value | Declaration.mutualDefnDecl vals => vals.foldlM (fun a v => do let a ← f a v.type; f a v.value) a | Declaration.inductDecl _ _ inductTypes _ => inductTypes.foldlM (fun a inductType => do let a ← f a inductType.type inductType.ctors.foldlM (fun a ctor => f a ctor.type) a) a @[inline] def Declaration.forExprM {m : Type → Type} [Monad m] (d : Declaration) (f : Expr → m Unit) : m Unit := d.foldExprM (fun _ a => f a) () /-- The kernel compiles (mutual) inductive declarations (see `inductiveDecls`) into a set of - `Declaration.inductDecl` (for each inductive datatype in the mutual Declaration), - `Declaration.ctorDecl` (for each Constructor in the mutual Declaration), - `Declaration.recDecl` (automatically generated recursors). This data is used to implement iota-reduction efficiently and compile nested inductive declarations. A series of checks are performed by the kernel to check whether a `inductiveDecls` is valid or not. -/ structure InductiveVal extends ConstantVal where nparams : Nat -- Number of parameters nindices : Nat -- Number of indices all : List Name -- List of all (including this one) inductive datatypes in the mutual declaration containing this one ctors : List Name -- List of all constructors for this inductive datatype isRec : Bool -- `true` Iff it is recursive isUnsafe : Bool isReflexive : Bool isNested : Bool deriving Inhabited @[export lean_mk_inductive_val] def mkInductiveValEx (name : Name) (lparams : List Name) (type : Expr) (nparams nindices : Nat) (all ctors : List Name) (isRec isUnsafe isReflexive isNested : Bool) : InductiveVal := { name := name lparams := lparams type := type nparams := nparams nindices := nindices all := all ctors := ctors isRec := isRec isUnsafe := isUnsafe isReflexive := isReflexive isNested := isNested } @[export lean_inductive_val_is_rec] def InductiveVal.isRecEx (v : InductiveVal) : Bool := v.isRec @[export lean_inductive_val_is_unsafe] def InductiveVal.isUnsafeEx (v : InductiveVal) : Bool := v.isUnsafe @[export lean_inductive_val_is_reflexive] def InductiveVal.isReflexiveEx (v : InductiveVal) : Bool := v.isReflexive @[export lean_inductive_val_is_nested] def InductiveVal.isNestedEx (v : InductiveVal) : Bool := v.isNested def InductiveVal.nctors (v : InductiveVal) : Nat := v.ctors.length structure ConstructorVal extends ConstantVal where induct : Name -- Inductive Type this Constructor is a member of cidx : Nat -- Constructor index (i.e., Position in the inductive declaration) nparams : Nat -- Number of parameters in inductive datatype `induct` nfields : Nat -- Number of fields (i.e., arity - nparams) isUnsafe : Bool deriving Inhabited @[export lean_mk_constructor_val] def mkConstructorValEx (name : Name) (lparams : List Name) (type : Expr) (induct : Name) (cidx nparams nfields : Nat) (isUnsafe : Bool) : ConstructorVal := { name := name, lparams := lparams, type := type, induct := induct, cidx := cidx, nparams := nparams, nfields := nfields, isUnsafe := isUnsafe } @[export lean_constructor_val_is_unsafe] def ConstructorVal.isUnsafeEx (v : ConstructorVal) : Bool := v.isUnsafe /-- Information for reducing a recursor -/ structure RecursorRule where ctor : Name -- Reduction rule for this Constructor nfields : Nat -- Number of fields (i.e., without counting inductive datatype parameters) rhs : Expr -- Right hand side of the reduction rule structure RecursorVal extends ConstantVal where all : List Name -- List of all inductive datatypes in the mutual declaration that generated this recursor nparams : Nat -- Number of parameters nindices : Nat -- Number of indices nmotives : Nat -- Number of motives nminors : Nat -- Number of minor premises rules : List RecursorRule -- A reduction for each Constructor k : Bool -- It supports K-like reduction isUnsafe : Bool @[export lean_mk_recursor_val] def mkRecursorValEx (name : Name) (lparams : List Name) (type : Expr) (all : List Name) (nparams nindices nmotives nminors : Nat) (rules : List RecursorRule) (k isUnsafe : Bool) : RecursorVal := { name := name, lparams := lparams, type := type, all := all, nparams := nparams, nindices := nindices, nmotives := nmotives, nminors := nminors, rules := rules, k := k, isUnsafe := isUnsafe } @[export lean_recursor_k] def RecursorVal.kEx (v : RecursorVal) : Bool := v.k @[export lean_recursor_is_unsafe] def RecursorVal.isUnsafeEx (v : RecursorVal) : Bool := v.isUnsafe def RecursorVal.getMajorIdx (v : RecursorVal) : Nat := v.nparams + v.nmotives + v.nminors + v.nindices def RecursorVal.getInduct (v : RecursorVal) : Name := v.name.getPrefix inductive QuotKind where | type -- `Quot` | ctor -- `Quot.mk` | lift -- `Quot.lift` | ind -- `Quot.ind` structure QuotVal extends ConstantVal where kind : QuotKind @[export lean_mk_quot_val] def mkQuotValEx (name : Name) (lparams : List Name) (type : Expr) (kind : QuotKind) : QuotVal := { name := name, lparams := lparams, type := type, kind := kind } @[export lean_quot_val_kind] def QuotVal.kindEx (v : QuotVal) : QuotKind := v.kind /-- Information associated with constant declarations. -/ inductive ConstantInfo where | axiomInfo (val : AxiomVal) | defnInfo (val : DefinitionVal) | thmInfo (val : TheoremVal) | opaqueInfo (val : OpaqueVal) | quotInfo (val : QuotVal) | inductInfo (val : InductiveVal) | ctorInfo (val : ConstructorVal) | recInfo (val : RecursorVal) namespace ConstantInfo def toConstantVal : ConstantInfo → ConstantVal | defnInfo {toConstantVal := d, ..} => d | axiomInfo {toConstantVal := d, ..} => d | thmInfo {toConstantVal := d, ..} => d | opaqueInfo {toConstantVal := d, ..} => d | quotInfo {toConstantVal := d, ..} => d | inductInfo {toConstantVal := d, ..} => d | ctorInfo {toConstantVal := d, ..} => d | recInfo {toConstantVal := d, ..} => d def isUnsafe : ConstantInfo → Bool | defnInfo v => v.safety == DefinitionSafety.unsafe | axiomInfo v => v.isUnsafe | thmInfo v => false | opaqueInfo v => v.isUnsafe | quotInfo v => false | inductInfo v => v.isUnsafe | ctorInfo v => v.isUnsafe | recInfo v => v.isUnsafe def name (d : ConstantInfo) : Name := d.toConstantVal.name def lparams (d : ConstantInfo) : List Name := d.toConstantVal.lparams def type (d : ConstantInfo) : Expr := d.toConstantVal.type def value? : ConstantInfo → Option Expr | defnInfo {value := r, ..} => some r | thmInfo {value := r, ..} => some r | _ => none def hasValue : ConstantInfo → Bool | defnInfo {value := r, ..} => true | thmInfo {value := r, ..} => true | _ => false def value! : ConstantInfo → Expr | defnInfo {value := r, ..} => r | thmInfo {value := r, ..} => r | _ => panic! "declaration with value expected" def hints : ConstantInfo → ReducibilityHints | defnInfo {hints := r, ..} => r | _ => ReducibilityHints.opaque def isCtor : ConstantInfo → Bool | ctorInfo _ => true | _ => false @[extern "lean_instantiate_type_lparams"] constant instantiateTypeLevelParams (c : @& ConstantInfo) (ls : @& List Level) : Expr @[extern "lean_instantiate_value_lparams"] constant instantiateValueLevelParams (c : @& ConstantInfo) (ls : @& List Level) : Expr end ConstantInfo def mkRecName (declName : Name) : Name := Name.mkStr declName "rec" end Lean
11f8b602bf54f0766ec0daa819a93f24b9a7a28c
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/1442.lean
d22c036f19240d0a75416d12ebdb52f7c0cddc8f
[ "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
573
lean
protected def rel : ℤ × ℤ → ℤ × ℤ → Prop | ⟨n₁, d₁⟩ ⟨n₂, d₂⟩ := n₁ * d₂ = n₂ * d₁ private def mul' : ℤ × ℤ → ℤ × ℤ → ℤ × ℤ | ⟨n₁, d₁⟩ ⟨n₂, d₂⟩ := ⟨n₁ * n₂, d₁ * d₂⟩ example : ∀(a b c d : ℤ × ℤ), rel a c → rel b d → rel (mul' a b) (mul' c d) := λ⟨n₁, d₁⟩ ⟨n₂, d₂⟩ ⟨n₃, d₃⟩ ⟨n₄, d₄⟩, assume (h₁ : n₁ * d₃ = n₃ * d₁) (h₂ : n₂ * d₄ = n₄ * d₂), show (n₁ * n₂) * (d₃ * d₄) = (n₃ * n₄) * (d₁ * d₂), by cc
e3b101920c0c66b3f44ea522f8f3ecdc39795355
8ba901cf307a2677c194984e82644023b5d8f5d8
/mm0-lean/x86/matching.lean
5302a8df7ac2a995b3fc25bacf75e64c2ffff028
[ "CC0-1.0" ]
permissive
julian-becker/mm0
af57d3043477e1f17bdedcb29d4099bb8a25f692
79e2755dec1e6ee238e23e3494e84f82b6c138ac
refs/heads/master
1,598,672,691,658
1,572,192,390,000
1,572,192,390,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,099
lean
import x86.x86 data.set.lattice data.list.basic data.pfun data.list.alist namespace x86 inductive flag_place | CFP | ZFP | SFP | OFP def flag_place.read (f : flags) : flag_place → bool | flag_place.CFP := f.CF | flag_place.ZFP := f.ZF | flag_place.SFP := f.SF | flag_place.OFP := f.OF def flag_place.write (f : flags) (b : bool) : flag_place → flags | flag_place.CFP := {CF := b, ..f} | flag_place.ZFP := {ZF := b, ..f} | flag_place.SFP := {SF := b, ..f} | flag_place.OFP := {OF := b, ..f} inductive place | flag : flag_place → place | reg : regnum → place | rip : place | mem : qword → place inductive place.read (k : config) : place → ∀ {n}, bitvec n → Prop | flag {f} : place.read (place.flag f) (bitvec.singleton (f.read k.flags)) | reg {r} : place.read (place.reg r) (k.regs r) | rip : place.read place.rip k.rip | mem {a b} : k.mem.read1 perm.R a b → place.read (place.mem a) b inductive place.write (k : config) : place → ∀ {n}, bitvec n → config → Prop | flag {f b} : place.write (place.flag f) (bitvec.singleton b) {flags := f.write k.flags b, ..k} | reg {r n q} : place.write (place.reg r) q (k.write_reg r n q) | rip {q} : place.write place.rip q {rip := q, ..k} | mem {a b m'} : k.mem.write1 a b m' → place.write (place.mem a) b {mem := m', ..k} def place.stable (k k' : config) : place → Prop | (place.flag f) := f.read k.flags = f.read k'.flags | (place.reg r) := k.regs r = k'.regs r | place.rip := k.rip = k'.rip | (place.mem a) := roption.mk (k.mem.valid a) (λ h, (k.mem.mem a h, k.mem.perm a h)) = roption.mk (k'.mem.valid a) (λ h, (k'.mem.mem a h, k'.mem.perm a h)) def stability (k k' : config) : set place := {p | place.stable k k' p} def split (H h₁ h₂ : set place) : Prop := H = h₁ ∪ h₂ ∧ disjoint h₁ h₂ def sProp := config → Prop def sProp.reserve (S : set place) : sProp := λ k, ∀ p ∈ S, ∃ n v, @place.read k p n v def mProp := config → config → Prop def mProp.exterior (P : mProp) : set place := {p | ∀ k k', P k k' → place.stable k k' p} def stable_at (D : set place) : mProp := λ k k', D ⊆ stability k k' def mProp.initial (Q : mProp) (P : sProp) : mProp := λ k k', Q k k' ∧ P k def mProp.final (Q : mProp) (P : sProp) : mProp := λ k k', Q k k' ∧ P k' def mProp.apply (Q : mProp) (P : sProp) : sProp := λ k', ∃ k, P k ∧ Q k k' def mProp.id : mProp := eq def mProp.comp (P Q : mProp) : mProp := λ k k₂, ∃ k₁, P k k₁ ∧ Q k₁ k₂ def slift (p : Prop) : sProp := λ _, p def mlift (p : Prop) : mProp := λ _ _, p def sProp.and (P Q : sProp) : sProp := λ k, P k ∧ Q k def mProp.and (P Q : mProp) : mProp := λ k k', P k k' ∧ Q k k' def sProp.or (P Q : sProp) : sProp := λ k, P k ∨ Q k def mProp.or (P Q : mProp) : mProp := λ k k', P k k' ∨ Q k k' instance lattice.has_inf.sProp : lattice.has_inf sProp := ⟨sProp.and⟩ instance lattice.has_inf.mProp : lattice.has_inf mProp := ⟨mProp.and⟩ instance lattice.has_sup.sProp : lattice.has_sup sProp := ⟨sProp.or⟩ instance lattice.has_sup.mProp : lattice.has_sup mProp := ⟨mProp.or⟩ instance lattice.has_top.sProp : lattice.has_top sProp := ⟨λ _, true⟩ instance lattice.has_top.mProp : lattice.has_top mProp := ⟨λ _ _, true⟩ instance lattice.has_bot.sProp : lattice.has_bot sProp := ⟨λ _, false⟩ instance lattice.has_bot.mProp : lattice.has_bot mProp := ⟨λ _ _, false⟩ def sProp.with (p : sProp) (q : Prop) : sProp := p ⊓ slift q def mProp.with (p : mProp) (q : Prop) : mProp := p ⊓ mlift q def sProp.ex {α} (p : α → sProp) : sProp := λ k, ∃ a, p a k def mProp.ex {α} (p : α → mProp) : mProp := λ k k', ∃ a, p a k k' def sProp.al {α} (p : α → sProp) : sProp := λ k, ∀ a, p a k def mProp.al {α} (p : α → mProp) : mProp := λ k k', ∀ a, p a k k' def sProp.sn (p : place) {n} (v : bitvec n) : sProp := λ k, p.read k v def mProp.write (p : place) {n} (v' : bitvec n) : mProp := λ k k', p.write k v' k' def mProp.sn (p : place) {n} (v v' : bitvec n) : mProp := (mProp.write p v').initial (sProp.sn p v) def mProp.clob (p : place) {n} (v : bitvec n) : mProp := mProp.ex $ λ v', mProp.sn p v v' def sProp.flags (f : flags) : sProp := sProp.al $ λ p : flag_place, sProp.sn (place.flag p) (bitvec.singleton $ p.read f) inductive block | reg : regnum → wsize → block | mem : qword → qword → block | const : list byte → block def block.size : block → qword | (block.reg _ sz) := (sz.to_nat / 8 : ℕ) | (block.mem _ sz) := sz | (block.const l) := l.length inductive block.places : block → set place | reg {r sz} : block.places (block.reg r sz) (place.reg r) | mem {a b sz : qword} : (bitvec.sub b a).to_nat ≤ sz.to_nat → block.places (block.mem a sz) (place.mem b) def block.disj (b1 b2 : block) := disjoint b1.places b2.places def sProp.mem_block (p : perm) (a : qword) (v : list byte) : sProp := λ k, k.mem.read' p a v def block.read : block → list byte → sProp | (block.reg r sz) v := (sProp.reserve (block.reg r sz).places).and $ λ k, read_full_imm sz (k.regs r) v | (block.mem a sz) v := (sProp.reserve (block.mem a sz).places).and $ λ k, k.mem.read a v ∧ v.length = sz.to_nat | (block.const l) v := slift $ v = l def block.writable : block → sProp | (block.reg r sz) := sProp.reserve (block.reg r sz).places | (block.mem a sz) := (sProp.reserve (block.mem a sz).places).and $ λ k, ∃ v, k.mem.read' perm.W a v ∧ v.length = sz.to_nat | (block.const _) := slift false def block.write : block → list byte → mProp | (block.reg r sz) l k k' := ∃ v, @bits_to_byte (sz.to_nat * 8) sz.to_nat v l ∧ mProp.write (place.reg r) v k k' | (block.mem a sz) l k k' := ∃ m', k.mem.write a l m' ∧ k' = {mem := m', ..k} | (block.const _) _ _ _ := false theorem block.read.size : ∀ {b v k}, block.read b v k → v.length = b.size.to_nat := sorry theorem block.write.size : ∀ {b v k k'}, block.write b v k k' → v.length = b.size.to_nat := sorry theorem block.read_write : ∀ {b v k k'}, block.write b v k k' → block.read b v k' := sorry theorem block.read.stable {l v k k'} (h₁ : block.read l v k) (ss : places l ⊆ stability k k') : block.read l v k' := sorry def locals_ctx := alist (λ _ : ℕ, block) def locals_ctx.get (Γ : locals_ctx) (n : ℕ) : option block := Γ.lookup n def labels_ctx := qword × list qword def labels_ctx.cons (q : qword) (L : labels_ctx) : labels_ctx := ⟨L.1, q :: L.2⟩ inductive hoare_p (Q : kcfg → Prop) : kcfg → Prop | zero {{k}} : Q k → hoare_p k | step {{k}} : (∃ k', kcfg.step k k') → (∀ k', k.step k' → hoare_p k') → hoare_p k | exit (k : kcfg) (ret) : k.k.exit ret → (ret = 0 → Q k) → hoare_p k def hoare (P : kcfg → Prop) (Q : kcfg → kcfg → Prop) := ∀ {{k}}, P k → hoare_p (Q k) k def mHoareIO (P : sProp) (Q : list byte → list byte → mProp) := ∀ {{i o}}, hoare (λ k, P k.k ∧ k.input = i ∧ k.output = o) (λ k k', ∃ i' o', i = i' ++ k.input ∧ o = k.output ++ o' ∧ (Q i' o') k.k k'.k) def noIO (Q : mProp) (i o : list byte) : mProp := Q.with (i = [] ∧ o = []) def mHoare (P : sProp) (Q : mProp) := mHoareIO P (noIO Q) inductive exit_kind | straight | label (n : ℕ) def exit_kind.result (L : labels_ctx) (pos : qword) : exit_kind → mProp | exit_kind.straight := mProp.write place.rip pos | (exit_kind.label n) := mProp.ex $ λ h, mProp.write place.rip (L.2.nth_le n h) def stmt : Type := labels_ctx → locals_ctx → set place → ∀ rip : qword, list byte → Prop def stmt.hoareIO (P : sProp) (C : stmt) (Q : exit_kind → list byte → list byte → mProp) : Prop := ∀ L Γ D rip l, C L Γ D rip l → mHoareIO (P ⊓ sProp.sn place.rip rip ⊓ sProp.mem_block (perm.R + perm.X) rip l) (λ i o, stable_at D ⊓ (mProp.write place.rip L.1 ⊔ mProp.ex (λ e, Q e i o ⊓ e.result L (rip + l.length)))) def stmt.hoare (P : sProp) (C : stmt) (Q : exit_kind → mProp) : Prop := stmt.hoareIO P C (λ e, noIO (Q e)) def hstmt (P : sProp) (Q : mProp) : stmt := λ L Γ D rip v, mHoare (sProp.sn place.rip rip ⊓ sProp.mem_block (perm.R + perm.X) rip v) (Q ⊓ mProp.write place.rip (rip + v.length)) def stmt.all {α} (s : α → stmt) : stmt := λ L Γ D rip v, ∀ a, s a L Γ D rip v def stmt.ex {α} (s : α → stmt) : stmt := λ L Γ D rip v, ∃ a, s a L Γ D rip v def stmt.with (p : Prop) (s : stmt) : stmt := stmt.ex $ λ h : p, s def stmt.or (s₁ s₂ : stmt) : stmt := λ L Γ D rip v, s₁ L Γ D rip v ∨ s₂ L Γ D rip v def stmt.stabilize (S : set place) (s : stmt) : stmt := λ L Γ D, s L Γ (D ∪ S) def expr (α : Type) := block → stmt def expr.hoareIO {α} (P : sProp) (E : expr α) (Q : block → list byte → list byte → mProp) : Prop := ∀ b, (E b).hoareIO P $ λ e i o, exit_kind.cases_on e (Q b i o) (λ n, mlift false) def expr.hoare {α} (P : sProp) (E : expr α) (Q : block → mProp) : Prop := expr.hoareIO P E (λ ret, noIO (Q ret)) def expr.stabilize {α} (S : set place) (s : expr α) : expr α := λ b, (s b).stabilize S class value (α : Type*) := (size : ℕ) (eval : α → list byte → Prop) (eval_eq : ∀ {{a l}}, eval a l → l.length = size) def value.evalB {α} [value α] (x : α) (b : block) : sProp := λ k, ∃ l, block.read b l k ∧ value.eval x l def value.read_sized {α} [value α] (a : qword) (x : α) (b : block) : sProp := value.evalB x b ⊓ slift (b = block.mem a (value.size α)) class type (α : Type*) := (size : ℕ) (read : α → block → set place → sProp) (write : α → block → mProp) (read_eq : ∀ {{a l s k}}, read a l s k → l.size.to_nat = size) (write_eq : ∀ {{a l k k'}}, write a l k k' → l.size.to_nat = size) (read_write : ∀ {{a l k k'}}, write a l k k' → ∃ s, read a l s k') (read_stable : ∀ {{a l s k k'}}, read a l s k → s ⊆ stability k k' → read a l s k') def type.read' {α} [type α] (a : α) (b : block) : sProp := sProp.ex $ type.read a b instance (α) [value α] : type α := ⟨value.size α, λ a b s, sProp.ex $ λ v, block.read b v ⊓ slift (value.eval a v ∧ s = b.places), λ a b, mProp.ex $ λ v, block.write b v ⊓ mlift (value.eval a v), λ a b s k ⟨v, h₁, h₂, _⟩, by rw [← h₁.size, @value.eval_eq α _ a v h₂], λ a b k k' ⟨v, h₁, h₂⟩, by rw [← h₁.size, @value.eval_eq α _ a v h₂], λ a v k k' ⟨s, h₁, h₂⟩, ⟨_, _, block.read_write h₁, h₂, rfl⟩, λ a l s k k' ⟨v, h₁, h₂, e⟩ ss, ⟨v, h₁.stable (e ▸ ss), h₂, e⟩⟩ theorem bits_to_byte_length {n m w v} : @bits_to_byte n m w v → v.length = m := by rintro ⟨bs⟩; exact bs.2 def bits.value {n} (m : ℕ) : value (bitvec n) := ⟨m, bits_to_byte m, λ a v h, bits_to_byte_length h⟩ instance unit.value : value unit := ⟨0, λ _ v, v = [], by rintro _ _ ⟨⟩; refl⟩ instance byte.value : value byte := ⟨1, λ b v, v = [b], by rintro _ _ ⟨⟩; refl⟩ instance word.value : value word := bits.value 4 instance qword.value : value qword := bits.value 8 class box (α) [type α] := (deref : α) instance box.type (α) [type α] : type (box α) := ⟨8, λ x b s k, ∃ a l s', block.read b l k ∧ qword.to_list_byte a l ∧ type.read x.deref (block.mem a (type.size α)) s' k ∧ s = b.places ∪ s', λ x b k k', ∃ a l s', block.write b l k k' ∧ qword.to_list_byte a l ∧ type.read x.deref (block.mem a (type.size α)) s' k', λ x b s k ⟨a, l, s', h₁, h₂, _⟩, by rw [← h₁.size, bits_to_byte_length h₂], λ x b k k' ⟨a, l, s', h₁, h₂, _⟩, by rw [← h₁.size, bits_to_byte_length h₂], λ x b k k' ⟨a, l, s', h₁, h₂, h₃⟩, ⟨_, _, _, _, block.read_write h₁, h₂, h₃, rfl⟩, λ x b s k k' ⟨a, l, s', h₁, h₂, h₃, e⟩ ss, let ⟨ss₁, ss₂⟩ := set.union_subset_iff.1 (by rwa e at ss) in ⟨a, l, s', h₁.stable ss₁, h₂, type.read_stable h₃ ss₂, e⟩⟩ def ret (α) (b : block) : expr α := λ bl L Γ D a v, bl = b ∧ v = [] def const (α) (l : list byte) : expr α := ret α (block.const l) def name (α : Type) := ℕ def var {α} (i : name α) : expr α := λ bl L Γ D a v, bl ∈ Γ.get i ∧ v = [] def hexpr {α} (P : sProp) (Q : block → mProp) : expr α := λ ret, hstmt P (Q ret) def expr.all {α β} (e : α → expr β) : expr β := λ ret, stmt.all $ λ a, e a ret def expr.ex {α β} (e : α → expr β) : expr β := λ ret, stmt.ex $ λ a, e a ret def expr.with {α} (p : Prop) (s : expr α) : expr α := expr.ex $ λ h : p, s def const' {α} [type α] (a : α) : expr α := hexpr ⊤ $ λ b, mProp.final mProp.id (type.read' a b) inductive stmt.seq (s₁ : stmt) (s₂ : stmt) : stmt | mk {L Γ D rip v₁ v₂} : s₁ L Γ D rip v₁ → s₂ L Γ D (rip + v₁.length) v₂ → stmt.seq L Γ D rip (v₁ ++ v₂) inductive expr.bindS {α} (e₁ : expr α) (s₂ : block → stmt) : stmt | mk {b L Γ D rip v₁ v₂} : e₁ b L Γ D rip v₁ → s₂ b L Γ D (rip + v₁.length) v₂ → expr.bindS L Γ D rip (v₁ ++ v₂) def expr.bind {α β} (e₁ : expr α) (e₂ : block → expr β) : expr β := λ b₂, expr.bindS e₁ $ λ b₁, e₂ b₁ b₂ def block.mov (dst src : block) : stmt := stmt.with (dst.size = src.size) $ stmt.all $ λ val, hstmt (block.read src val) (block.write dst val) def expr.set {α} (e₁ e₂ : expr α) : stmt := expr.bindS e₁ $ λ dst, expr.bindS e₂ $ λ src, block.mov dst src inductive label | fail | label (n : ℕ) inductive label.loc (L : labels_ctx) : label → qword → Prop | fail : label.loc label.fail L.1 | label (n h) : label.loc (label.label n) (L.2.nth_le n h) def stmt.jump_cc (p : flags → bool) (l : label) : stmt := λ L Γ D rip v, ∀ tgt, l.loc L tgt → mHoare (sProp.sn place.rip rip ⊓ sProp.mem_block (perm.R + perm.X) rip v) (λ k k', stable_at D k k' ∧ mProp.write place.rip (cond (p k.flags) tgt (rip + v.length)) k k') def stmt.jump : label → stmt := stmt.jump_cc (λ _, tt) def boolexpr := (flags → bool) → stmt def boolexpr.hoare (P : sProp) (E : boolexpr) (Q : bool → mProp) : Prop := ∃ p, stmt.hoare P (E p) (λ e k k', e = exit_kind.straight ∧ Q (p k'.flags) k k') def boolexpr.not (c : boolexpr) : boolexpr := λ p, c (bnot ∘ p) def boolexpr.jump_if (c : boolexpr) (l : label) : stmt := stmt.ex $ λ p, (c p).seq $ stmt.jump_cc p l def stmt.nop : stmt := λ L Γ D rip v, v = [] def if_stmt (c : boolexpr) (s₁ s₂ : stmt) : stmt := stmt.ex $ λ p, stmt.seq (c p) $ λ L Γ D rip v, ∃ v₁ v₂ v₃, v = v₁ ++ v₂ ++ v₃ ∧ let q₁ := rip + v₁.length, q₂ := q₁ + v₂.length in stmt.jump_cc (bnot ∘ p) (label.label 0) (L.cons q₁) Γ D rip v₁ ∧ s₁.seq (stmt.jump (label.label 0)) (L.cons q₂) Γ D q₁ v₂ ∧ s₂.seq (stmt.jump (label.label 0)) (L.cons q₂) Γ D q₂ v₃ def loop (s : stmt) : stmt := λ L Γ D rip, s (L.cons rip) Γ D rip def block_stmt (s : stmt) : stmt := λ L Γ D rip v, s (L.cons (rip + v.length)) Γ D rip v def while (c : boolexpr) (s : stmt) : stmt := block_stmt $ loop $ (c.not.jump_if (label.label 1)).seq $ s.seq $ stmt.jump (label.label 0) def decl_block {α} (b : block) (s : name α → stmt) : stmt := λ L Γ D rip v, ∃ i, s i L (Γ.insert i b) D rip v def decl {α} (sz : qword) (s : name α → stmt) : stmt := stmt.ex $ λ b, stmt.with (block.size b = sz) $ decl_block b s def init {α} (e : expr α) (s : name α → stmt) : stmt := e.bindS $ λ b, decl_block b s def binop_expr {α β γ} [type α] [type β] [type γ] (f : α → β → γ) (e₁ : expr α) (e₂ : expr β) : expr γ := e₁.bind $ λ b₁, e₂.bind $ λ b₂ b, stmt.ex $ λ x, stmt.ex $ λ y, hstmt (type.read' x b₁ ⊓ type.read' y b₂) (type.write (f x y) b) def asn_binop {α β} [type α] [type β] (f : α → β → α) (e₁ : expr α) (e₂ : expr β) : stmt := e₁.bindS $ λ b₁, (ret α b₁).set (binop_expr f (ret α b₁) e₂) def unop_expr {α β} [type α] [type β] (f : α → β) (e : expr α) : expr β := e.bind $ λ b₁ b, stmt.ex $ λ x, hstmt (type.read' x b₁) (type.write (f x) b) def asn_unop {α} [type α] (f : α → α) (e : expr α) : stmt := e.bindS $ λ b, (ret α b).set (unop_expr f (ret α b)) def for {α} (start : expr α) (test : name α → boolexpr) (incr body : name α → stmt) : stmt := init start $ λ i, while (test i) $ (body i).seq (incr i) def incr {α} [type α] [has_add α] [has_one α] : expr α → stmt := asn_unop (+ 1) def bool_binop {α β} [type α] [type β] (f : α → β → bool) (e₁ : expr α) (e₂ : expr β) : boolexpr := λ p, e₁.bindS $ λ b₁, e₂.bindS $ λ b₂, stmt.ex $ λ x, stmt.ex $ λ y, hstmt (type.read' x b₁ ⊓ type.read' y b₂) (mProp.final mProp.id (λ k, p k.flags = f x y)) def ltq (e₁ e₂ : expr qword) : boolexpr := bool_binop (λ a b : qword, a.to_nat < b.to_nat) e₁ e₂ def for_seq (sz : qword) (max : expr qword) (body : name qword → stmt) : stmt := for (const' (0 : qword)) (λ i, ltq (const' 0) max) (λ i, incr (var i)) body ---------------------------------------- -- Assembly ---------------------------------------- theorem hoare_p.mono {P P' : kcfg → Prop} (H : ∀ {{k}}, P k → P' k) {k} : hoare_p P k → hoare_p P' k := begin intro h, induction h, exact hoare_p.zero (H h_a), exact hoare_p.step h_a (λ k', h_ih _), exact hoare_p.exit _ _ h_a (λ e, H (h_a_1 e)), end theorem hoare.zero {P : kcfg → Prop} {Q : kcfg → kcfg → Prop} (H : ∀ {{k}}, P k → Q k k) : hoare P Q := λ k p, hoare_p.zero (H p) theorem hoare.step {P P' : kcfg → Prop} {Q Q' : kcfg → kcfg → Prop} (h₁ : ∀ {{k}}, P k → ∃ k', k.step k') (h₂ : ∀ {{k}}, P k → ∀ {{k'}}, k.step k' → P' k' ∧ ∀ {{k''}}, Q' k' k'' → Q k k'') (h₃ : hoare P' Q') : hoare P Q := λ k p, hoare_p.step (h₁ p) (λ k' s, hoare_p.mono (h₂ p s).2 (h₃ (h₂ p s).1)) theorem hoare.mono_l {P P' : kcfg → Prop} {Q : kcfg → kcfg → Prop} (H : ∀ {{k}}, P k → P' k) : hoare P' Q → hoare P Q := λ H' k h, H' (H h) theorem hoare.mono_r {P : kcfg → Prop} {Q Q' : kcfg → kcfg → Prop} (H : ∀ {{k k'}}, Q k k' → Q' k k') : hoare P Q → hoare P Q' := λ H' k h, hoare_p.mono (@H _) (H' h) theorem mHoareIO.zero {P : sProp} {Q : list byte → list byte → mProp} (H : ∀ {{k}}, P k → Q [] [] k k) : mHoareIO P Q := λ i o, hoare.zero $ by rintro k ⟨h, rfl, rfl⟩; exact ⟨[], [], rfl, (list.append_nil _).symm, H h⟩ theorem mHoareIO.mono_l {P P' : sProp} {Q : list byte → list byte → mProp} (H : ∀ {{k}}, P k → P' k) : mHoareIO P' Q → mHoareIO P Q := λ h i o, hoare.mono_l (by exact λ k ⟨h₁, h₂⟩, ⟨H h₁, h₂⟩) (@h i o) theorem mHoareIO.mono_r {P : sProp} {Q Q' : list byte → list byte → mProp} (H : ∀ {{i o k k'}}, Q i o k k' → Q' i o k k') : mHoareIO P Q → mHoareIO P Q' := λ h i o, hoare.mono_r (by exact λ k k' ⟨i', o', h₁, h₂, h₃⟩, ⟨i', o', h₁, h₂, H h₃⟩) (@h i o) theorem mHoareIO.step {P P' : sProp} {Q Q' : list byte → list byte → mProp} (H₁ : ∀ ⦃k i o⦄, P k → ∃ k', kcfg.step ⟨i, o, k⟩ k') (H₂ : ∀ {{k₁ i₁ o₁ k₂ i₂ o₂}}, P k₁ → kcfg.step ⟨i₁, o₁, k₁⟩ ⟨i₂, o₂, k₂⟩ → P' k₂ ∧ i₂ = i₁ ∧ o₂ = o₁ ∧ ∀ {{k₃}}, Q' [] [] k₂ k₃ → Q [] [] k₁ k₃) (H₃ : mHoareIO P' Q') : mHoareIO P Q := λ i o, begin refine hoare.step (λ ⟨i', o', k⟩ h, H₁ h.1) _ (@H₃ i o), rintro ⟨i₁, o₁, k₁⟩ ⟨h, rfl, rfl⟩ ⟨i₂, o₂, k₂⟩ h', rcases @H₂ k₁ i₁ o₁ k₂ i₂ o₂ h h' with ⟨h₁, rfl, rfl, h₄⟩, refine ⟨⟨h₁, rfl, rfl⟩, _⟩, rintro k₃ ⟨i', o', e₁, e₂, h₅⟩, refine ⟨i', o', e₁, e₂, _⟩, cases ((list.append_right_inj _).1 e₁ : [] = i'), cases ((list.append_left_inj _).1 ((list.append_nil _).trans e₂) : [] = o'), exact h₄ h₅ end theorem mHoareIO.asm (P : sProp) (Q : list byte → list byte → mProp) : mHoareIO P Q := λ i o, sorry theorem sHoare.mono {P Q : sProp} (H : ∀ {{k}}, P k → Q k) : sHoare P Q := sHoareIO.mono $ λ k S h, ⟨H h, rfl, rfl⟩ theorem sHoare.mono_l {P P' Q : sProp} (H : ∀ {{k S}}, P k S → P' k S) : sHoare P' Q → sHoare P Q := sHoareIO.mono_l H theorem sHoare.mono_r {P Q Q' : sProp} (H : ∀ {{k S}}, Q k S → Q' k S) : sHoare P Q → sHoare P Q' := sHoareIO.mono_r $ λ i o k S ⟨h₁, h₂⟩, ⟨H h₁, h₂⟩ theorem config.isIO_terminal {k} : (∃ k', config.step k k') → ¬ ∃ k', k.isIO k' := sorry theorem sHoare.step {P P' Q : sProp} (h₁ : ∀ ⦃k S⦄, P k S → ∃ k', config.step k k') (h₂ : ∀ ⦃k S⦄, P k S → ∀ k', config.step k k' → P' k' S) : sHoare P' Q → sHoare P Q := sHoareIO.step (λ k i o S h, let ⟨k', h'⟩ := h₁ h in ⟨_, kcfg.step.noio h'⟩) (λ k₁ i₁ o₁ k₂ i₂ o₂ S h h', begin cases h', exact ⟨h₂ h _ h'_a, rfl, rfl⟩, cases config.isIO_terminal (h₁ h) ⟨_, h'_a⟩ end) def stmt.asm {n} (s : stmt n) := Π L Γ rip, ∃ v, s L Γ rip v theorem hstmt.step {n} {P P' Q : sProp} (h₁ : ∀ (L : labels_ctx) (Γ : locals_ctx n) rip, ∃ l, ∀ v k S, (P * sProp.sn place.rip rip * sProp.mem_block (perm.R + perm.X) rip (l ++ v)) k S → ∃ a k', decode a l ∧ (write_rip (k.rip + bitvec.of_nat 64 l.length) k).P () k' ∧ (execute a k').P () k ∧ ∀ H, P k H → P' k' H) (h₂ : (@hstmt n P' Q).asm) : (@hstmt n P Q).asm := λ L Γ rip, let ⟨l, H⟩ := h₁ L Γ rip, ⟨v, H₂⟩ := h₂ L Γ rip in ⟨l ++ v, begin refine sHoare.step (λ k S h, _) (λ k S h k', _) (sHoare.mono_r _ H₂), { rcases H v k S h with ⟨a, k', h₃, h₄, h₅, h₆⟩, have : mem.readX (k.mem) (k.rip) l, sorry, exact ⟨k, this, h₃, (), k', h₄, h₅⟩ }, { rintro ⟨l, a, _, m, d, h⟩, sorry }, sorry, end⟩ theorem hstmt.asm {n} (P : sProp) (Q : sProp) : (@hstmt n P Q).asm := sorry end x86
7c1586cbca5e3f09671783e5fec3a68f499bee39
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/linear_combination.lean
c1f0921b46dee78a20488a75e3caed5e2c5219f4
[ "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
8,416
lean
import tactic.linear_combination import data.real.basic /-! ### Simple Cases with ℤ and two or less equations -/ example (x y : ℤ) (h1 : 3*x + 2*y = 10): 3*x + 2*y = 10 := by linear_combination 1*h1 example (x y : ℤ) (h1 : 3*x + 2*y = 10): 3*x + 2*y = 10 := by linear_combination (h1) example (x y : ℤ) (h1 : x + 2 = -3) (h2 : y = 10) : 2*x + 4 = -6 := by linear_combination 2*h1 example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by linear_combination 1*h1 - 2*h2 example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by linear_combination -2*h2 + h1 example (x y : ℤ) (h1 : x + 2 = -3) (h2 : y = 10) : 2*x + 4 - y = -16 := by linear_combination 2*h1 + -1*h2 example (x y : ℤ) (h1 : x + 2 = -3) (h2 : y = 10) : -y + 2*x + 4 = -16 := by linear_combination -h2 + 2*h1 example (x y : ℤ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : 11*y = -11 := by linear_combination -2*h1 + 3*h2 example (x y : ℤ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y = 11 := by linear_combination 2*h1 - 3*h2 example (x y : ℤ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y = 11 + 1 - 1 := by linear_combination 2*h1 + -3*h2 example (x y : ℤ) (h1 : 10 = 3*x + 2*y) (h2 : 3 = 2*x + 5*y) : 11 + 1 - 1 = -11*y := by linear_combination 2*h1 - 3*h2 /-! ### More complicated cases with two equations -/ example (x y : ℤ) (h1 : x + 2 = -3) (h2 : y = 10) : -y + 2*x + 4 = -16 := by linear_combination 2*h1 - h2 example (x y : ℚ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y + 1 = 11 + 1 := by linear_combination 2*h1 - 3*h2 example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) : b = 2 / 3 := by linear_combination ha/6 + hab/3 /-! ### Cases with more than 2 equations -/ example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) (hignore : 3 = a + b) : b = 2 / 3 := by linear_combination 1/6 * ha + 1/3 * hab + 0 * hignore example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : -3*x - 3*y - 4*z = 2 := by linear_combination ha - hb - 2*hc example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : 6*x = -10 := by linear_combination 1*ha + 4*hb - 3*hc example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : 10 = 6*-x := by linear_combination ha + 4*hb - 3*hc example (w x y z : ℝ) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5) (h3 : x + y + 5*z + 5*w = 3) : x + 2.2*y + 2*z - 5*w = -8.5 := by linear_combination 2*h1 + 1*h2 - 2*h3 example (w x y z : ℝ) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5) (h3 : x + y + 5*z + 5*w = 3) : x + 2.2*y + 2*z - 5*w = -8.5 := by linear_combination 2*h1 + h2 - 2*h3 example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : 2*a - 3 + 9*c + 3*d = 8 - b + 3*d - 3*a := by linear_combination 2*h1 -1*h2 +3*h3 -3*h4 example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : 6 - 3*c + 3*a + 3*d = 2*b - d + 12 - 3*a := by linear_combination 2*h2 -h3 +3*h1 -3*h4 /-! ### Cases with non-hypothesis inputs -/ constants (qc : ℚ) (hqc : qc = 2*qc) example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by linear_combination 3 * h a b + hqc constant bad (q : ℚ) : q = 0 example (a b : ℚ) : a + b^3 = 0 := by linear_combination bad a + b * bad (b*b) /-! ### Cases with arbitrary coefficients -/ example (a b : ℤ) (h : a = b) : a * a = a * b := by linear_combination a*h example (a b c : ℤ) (h : a = b) : a * c = b * c := by linear_combination c*h example (a b c : ℤ) (h1 : a = b) (h2 : b = 1) : c * a + b = c * b + 1 := by linear_combination c*h1 + h2 example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : x*x*y + y*x*y + 6*x = 3*x*y + 14 := by linear_combination x*y*h1 + 2*h2 example {α} [h : comm_ring α] {a b c d e f : α} (h1 : a*d = b*c) (h2 : c*f = e*d) : c * (a*f - b*e) = 0 := by linear_combination e*h1 + a*h2 example (x y z w : ℚ) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w := by linear_combination (x + 2*y)*hzw /-! ### Cases that explicitly use a linear_combination_config -/ example (x y : ℚ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y + 1 = 11 + 1 := by linear_combination 2*h1 -3*h2 with {normalization_tactic := `[ring]} example (x y : ℚ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y + 1 = 11 + 1 := by linear_combination 2*h1 + -3*h2 with {normalization_tactic := `[ring1]} example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) : b = 2 / 3 := by linear_combination 1/6*ha + 1/3*hab with {normalization_tactic := `[ring_nf]} example (x y : ℤ) (h1 : 3*x + 2*y = 10): 3*x + 2*y = 10 := by linear_combination h1 with {normalization_tactic := `[simp]} /-! ### Cases that have linear_combination skip normalization -/ example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) : b = 2 / 3 := begin linear_combination 1/6*ha + 1/3*hab with {normalize := ff}, linarith end example (x y : ℤ) (h1 : x = -3) (h2 : y = 10) : 2*x = -6 := begin linear_combination 2*h1 with {normalize := ff}, simp, norm_cast end /-! ### Cases without any arguments provided -/ -- the corner case is "just apply the normalization procedure". -- an empty `linear_combination` at the end of a declaration is a bad edge case for the parser. example {x y z w : ℤ} (h₁ : 3 * x = 4 + y) (h₂ : x + 2 * y = 1) : z + w = w + z := by linear_combination . -- this interacts as expected with options example {x y z w : ℤ} (h₁ : 3 * x = 4 + y) (h₂ : x + 2 * y = 1) : z + w = w + z := begin linear_combination with {normalize := ff}, guard_target' z + w - (w + z) - (0 - 0) = 0, simp [add_comm] end example {x y z w : ℤ} (h₁ : 3 * x = 4 + y) (h₂ : x + 2 * y = 1) : z + w = w + z := by linear_combination with {normalization_tactic := `[simp [add_comm]]} /-! ### Cases with exponent -/ example (x y z : ℚ) (h : x = y) (h2 : x * y = 0) : x + y*z = 0 := by linear_combination (-y * z ^ 2 + x) * h + (z ^ 2 + 2 * z + 1) * h2 with {exponent := 2} example (x y z : ℚ) (h : x = y) (h2 : x * y = 0) : y*z = -x := begin linear_combination (-y * z ^ 2 + x) * h + (z ^ 2 + 2 * z + 1) * h2 with {exponent := 2, normalize := ff}, ring end example (K : Type) [field K] [char_zero K] {x y z : K} (h₂ : y ^ 3 + x * (3 * z ^ 2) = 0) (h₁ : x ^ 3 + z * (3 * y ^ 2) = 0) (h₀ : y * (3 * x ^ 2) + z ^ 3 = 0) (h : x ^ 3 * y + y ^ 3 * z + z ^ 3 * x = 0) : x = 0 := by linear_combination 2 * y * z ^ 2 * h₂ / 7 + (x ^ 3 - y ^ 2 * z / 7) * h₁ - x * y * z * h₀ + y * z * h / 7 with {exponent := 6} /-! ### Cases where the goal is not closed -/ example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : x*x*y + y*x*y + 6*x = 3*x*y + 14 := begin linear_combination x*y*h1 + h2, guard_target' (x * 3 - 7 = 0), linear_combination h2 end example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : 6 - 3*c + 3*a + 3*d = 2*b - d + 12 - 3*a := begin linear_combination 2*h2, linear_combination -h3, linear_combination 3*h1, linear_combination -3*h4, end example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := begin linear_combination, linear_combination h1 - 2 * h2, end /-! ### Cases that should fail -/ -- This should fail because the second coefficient has a different type than -- the equations it is being combined with. This was a design choice for the -- sake of simplicity, but the tactic could potentially be modified to allow -- this behavior. example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y + 2*x = 1 := begin success_if_fail_with_msg {linear_combination h1 + (0 : ℝ) * h2} "invalid type ascription, term has type ℝ but is expected to have type ℤ", linear_combination h1 end -- This fails because the linear_combination tactic requires the equations -- and coefficients to use a type that fulfills the add_group condition, -- and ℕ does not. example (a b : ℕ) (h1 : a = 3) : a = 3 := begin success_if_fail {linear_combination h1}, exact h1 end example (a b : ℤ) (x y : ℝ) (hab : a = b) (hxy : x = y) : 2*x = 2*y := begin success_if_fail_with_msg {linear_combination 2*hab} "hab is an equality between terms of type ℤ, but is expected to be between terms of type ℝ", linear_combination 2*hxy end
3ad1ccee72f68e590d6abaf5754dfce03dcef132
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/playground/webserver/Webserver.lean
71e716b6b56583297366ef6e45c82a9054e9d273
[ "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
5,057
lean
-- -*- origami-fold-style: triple-braces -*- import Lean -- namespace Webserver {{{ namespace Webserver structure State := (verb : String) (path : String) (status := "200 OK") (outHeaders : Array String := #[]) (out : String := "") (tryNextHandler := false) abbrev HandlerM := StateT State IO abbrev Handler := HandlerM Unit def checkVerb (verb : String) : Handler := do st ← get; when (st.verb != verb) $ throw $ IO.userError "invalid verb" def checkPathLiteral (p : String) : Handler := do st ← get; if p.isPrefixOf st.path then set { st with path := st.path.extract p.bsize st.path.bsize } else throw $ IO.userError "invalid path" def getPathPart : HandlerM String := do st ← get; let stop := st.path.posOf '/'; set { st with path := st.path.extract stop st.path.bsize }; pure $ st.path.extract 0 stop def checkPathConsumed : Handler := do st ← get; when (st.path != "") $ throw $ IO.userError "invalid path" def write (out : String) : Handler := do modify fun st => { st with out := st.out ++ out } def redirect (url : String) : Handler := do modify fun st => { st with status := "307 Temporary Redirect", outHeaders := #["Location: " ++ url] } def notFound : Handler := do modify fun st => { st with status := "404 Not Found" }; write "whoops" def mkHandlersRef : IO (IO.Ref (List Handler)) := IO.mkRef ∅ @[init mkHandlersRef] constant handlersRef : IO.Ref (List Handler) := arbitrary _ def registerHandler (h : Handler) : IO Unit := do handlersRef.modify fun hs => h::hs partial def parseHeaders : IO.FS.Handle → IO Unit | hIn => do line ← hIn.getLine; if line == "" || line == "\r\n" then pure () else parseHeaders hIn partial def run : IO.FS.Handle → IO.FS.Handle → IO Unit | hIn, hOut => do line ← hIn.getLine; when (line != "") do [verb, path, proto] ← pure $ line.splitOn " " | panic! "failed to parse request: " ++ line; stderr ← IO.stderr; stderr.putStrLn $ "=> " ++ verb ++ " " ++ path; headers ← parseHeaders hIn; handlers ← handlersRef.get | panic! "no handlers"; (_, st) ← handlers.foldr (fun h₁ h₂ => h₁ <|> h₂) notFound { verb := verb, path := path }; stderr ← IO.stderr; stderr.putStrLn $ "<= " ++ st.status; hOut.putStrLn $ "HTTP/1.1 " ++ st.status; hOut.putStrLn "Content-Type: text/html"; hOut.putStrLn $ "Content-Length: " ++ toString st.out.bsize; st.outHeaders.forM hOut.putStrLn; hOut.putStrLn ""; hOut.putStr st.out; hOut.flush; run hIn hOut end Webserver --}}} open Lean open Lean.Parser -- declare_syntax_cat element {{{ declare_syntax_cat element declare_syntax_cat child syntax "<" ident "/>" : element syntax "<" ident ">" child* "</" ident ">" : element -- "JSXTextCharacter : SourceCharacter but not one of {, <, > or }" def text : Parser := -- {{{ withAntiquot (mkAntiquot "text" `LX.text) { fn := fun c s => let startPos := s.pos; let s := takeWhile1Fn (not ∘ "{<>}$".contains) "HTML text" c s; mkNodeToken `LX.text startPos c s } -- }}} syntax text : child syntax "{" term "}" : child syntax element : child syntax element : term macro_rules | `(<$n/>) => mkStxStrLit ("<" ++ toString n.getId ++ ">") | `(<$n>$cs*</$m>) => -- {{{ if n.getId == m.getId then do cs ← cs.mapM fun c => match_syntax c with | `(child|$t:text) => pure $ mkStxStrLit (t.getArg 0).getAtomVal! | `(child|{$t}) => pure t | `(child|$e:element) => `($e:element) | _ => unreachable!; let cs := cs.push (mkStxStrLit ("</" ++ toString m.getId ++ ">")); cs.foldlM (fun s e => `($s ++ $e)) (mkStxStrLit ("<" ++ toString n.getId ++ ">")) else Macro.throwError m ("expected </" ++ toString n.getId ++ ">") -- }}} -- }}} -- open Webserver {{{ open Webserver def pathLiteral : Parser := -- {{{ withAntiquot (mkAntiquot "pathLiteral" `pathLiteral) { fn := fun c s => let startPos := s.pos; let s := takeWhile1Fn (fun c => c == '/' || c.isAlphanum) "URL path" c s; mkNodeToken `pathLiteral startPos c s } -- }}} declare_syntax_cat pathItem syntax pathLiteral : pathItem syntax "{" ident "}" : pathItem syntax path := pathItem* declare_syntax_cat verb syntax "GET" : verb syntax "POST" : verb macro v:verb p:path " => " t:term : command => do -- {{{ t ← `(do checkPathConsumed; $t:term); t ← p.getArgs.foldrM (fun pi t => match_syntax pi with | `(pathItem|$l:pathLiteral) => `(do checkPathLiteral $(mkStxStrLit (l.getArg 0).getAtomVal!); $t:term) | `(pathItem|{$id}) => `(do $id:ident ← getPathPart; $t:term) | _ => unreachable!) t; `(def handler : Handler := do checkVerb $(mkStxStrLit (v.getArg 0).getAtomVal!); $t:term @[init] def reg : IO Unit := registerHandler handler) -- }}} GET / => redirect "/greet/stranger" GET /greet/{name} => write <html> <h1>Hello, {name}!</h1> </html> def main : IO Unit := do hIn ← IO.stdin; hOut ← IO.stdout; Webserver.run hIn hOut -- }}} #check let name := "PLDI"; <h1>Hello, {name}!<br/></h1>
c0f3e4c34b53221cf51fc8d63702cdd00edb9e0d
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex21.lean
6107d13b86b0f9bf302876ad2a9f70781daffeba
[ "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
416
lean
/- Namespaces -/ namespace foo def a : ℕ := 5 def f (x : ℕ) : ℕ := x + 7 def fa : ℕ := f a def ffa : ℕ := f (f a) print "inside foo" check a check f check fa check ffa check foo.fa end foo print "outside the namespace" -- check a -- error -- check f -- error check foo.a check foo.f check foo.fa check foo.ffa open foo print "opened foo" check a check f check fa check foo.fa
ac36b0f50822879a93bb9d6e56ed213d1c8c5d96
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_632.lean
d1ac7ce1edeab6216fa7f7a663b2aebc634ba16e
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
106
lean
import data.real.basic -- BEGIN example : ∃ x : ℝ, 2 < x ∧ x < 3 := ⟨5 / 2, by norm_num⟩ -- END
facd5768210a84a48a42c763b135ed53d6e2539c
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/analysis/complex/polynomial.lean
5d13cfcf7a5c2d36eb19088af335b03b88199976
[ "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
6,027
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.polynomial topology.instances.polynomial analysis.complex.exponential open complex polynomial metric filter is_absolute_value set lattice namespace complex lemma exists_forall_abs_polynomial_eval_le (p : polynomial ℂ) : ∃ x, ∀ y, (p.eval x).abs ≤ (p.eval y).abs := if hp0 : 0 < degree p then let ⟨r, hr0, hr⟩ := polynomial.tendsto_infinity complex.abs hp0 ((p.eval 0).abs) in let ⟨x, hx₁, hx₂⟩ := exists_forall_le_of_compact_of_continuous (λ y, (p.eval y).abs) (p.continuous_eval.comp continuous_abs) (closed_ball 0 r) (proper_space.compact_ball _ _) (set.ne_empty_iff_exists_mem.2 ⟨0, by simp [le_of_lt hr0]⟩) in ⟨x, λ y, if hy : y.abs ≤ r then hx₂ y $ by simpa [complex.dist_eq] using hy else le_trans (hx₂ _ (by simp [le_of_lt hr0])) (le_of_lt (hr y (lt_of_not_ge hy)))⟩ else ⟨p.coeff 0, by rw [eq_C_of_degree_le_zero (le_of_not_gt hp0)]; simp⟩ /- The following proof uses the method given at https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus -/ /-- The fundamental theorem of algebra. Every non constant complex polynomial has a root -/ lemma exists_root {f : polynomial ℂ} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z := let ⟨z₀, hz₀⟩ := exists_forall_abs_polynomial_eval_le f in exists.intro z₀ $ by_contradiction $ λ hf0, have hfX : f - C (f.eval z₀) ≠ 0, from mt sub_eq_zero.1 (λ h, not_le_of_gt hf (h.symm ▸ degree_C_le)), let n := root_multiplicity z₀ (f - C (f.eval z₀)) in let g := (f - C (f.eval z₀)) /ₘ ((X - C z₀) ^ n) in have hg0 : g.eval z₀ ≠ 0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX, have hg : g * (X - C z₀) ^ n = f - C (f.eval z₀), from div_by_monic_mul_pow_root_multiplicity_eq _ _, have hn0 : 0 < n, from nat.pos_of_ne_zero $ λ hn0, by simpa [g, hn0] using hg0, let ⟨δ', hδ'₁, hδ'₂⟩ := continuous_iff.1 (polynomial.continuous_eval g) z₀ ((g.eval z₀).abs) (complex.abs_pos.2 hg0) in let δ := min (min (δ' / 2) 1) (((f.eval z₀).abs / (g.eval z₀).abs) / 2) in have hf0' : 0 < (f.eval z₀).abs, from complex.abs_pos.2 hf0, have hfg0 : 0 < abs (eval z₀ f) * (abs (eval z₀ g))⁻¹, from div_pos hf0' (complex.abs_pos.2 hg0), have hδ0 : 0 < δ, from lt_min (lt_min (half_pos hδ'₁) (by norm_num)) (half_pos hfg0), have hδ : ∀ z : ℂ, abs (z - z₀) = δ → abs (g.eval z - g.eval z₀) < (g.eval z₀).abs, from λ z hz, hδ'₂ z (by rw [complex.dist_eq, hz]; exact lt_of_le_of_lt (le_trans (min_le_left _ _) (min_le_left _ _)) (half_lt_self hδ'₁)), have hδ1 : δ ≤ 1, from le_trans (min_le_left _ _) (min_le_right _ _), let F : polynomial ℂ := C (f.eval z₀) + C (g.eval z₀) * (X - C z₀) ^ n in let z' := (-f.eval z₀ * (g.eval z₀).abs * δ ^ n / ((f.eval z₀).abs * g.eval z₀)) ^ (n⁻¹ : ℂ) + z₀ in have hF₁ : F.eval z' = f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs, by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval z₀), mul_left_comm (g.eval z₀), mul_left_comm (g.eval z₀)⁻¹, mul_inv', inv_mul_cancel hg0, eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right, neg_mul_eq_neg_mul_symm, mul_one, div_eq_mul_inv]; simp only [mul_comm, mul_left_comm, mul_assoc], have hδs : (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs < 1, by rw [div_eq_mul_inv, mul_right_comm, mul_comm, ← @inv_inv' _ _ (complex.abs _ * _), mul_inv', inv_inv', ← div_eq_mul_inv, div_lt_iff hfg0, one_mul]; calc δ ^ n ≤ δ ^ 1 : pow_le_pow_of_le_one (le_of_lt hδ0) hδ1 hn0 ... = δ : pow_one _ ... ≤ ((f.eval z₀).abs / (g.eval z₀).abs) / 2 : min_le_right _ _ ... < _ : half_lt_self hfg0, have hF₂ : (F.eval z').abs = (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n, from calc (F.eval z').abs = (f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs).abs : congr_arg abs hF₁ ... = abs (f.eval z₀) * complex.abs (1 - (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs : ℝ) : by rw [← complex.abs_mul]; exact congr_arg complex.abs (by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv]) ... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hδs)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one], have hef0 : abs (eval z₀ g) * (eval z₀ f).abs ≠ 0, from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0), have hz'z₀ : abs (z' - z₀) = δ, by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n), mul_comm (eval z₀ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul, neg_mul_eq_neg_mul_symm, neg_div, is_absolute_value.abv_pow complex.abs, complex.abs_of_nonneg (le_of_lt hδ0), real.pow_nat_rpow_nat_inv (le_of_lt hδ0) hn0], have hF₃ : (f.eval z' - F.eval z').abs < (g.eval z₀).abs * δ ^ n, from calc (f.eval z' - F.eval z').abs = (g.eval z' - g.eval z₀).abs * (z' - z₀).abs ^ n : by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs, ← complex.abs_mul, sub_mul]; simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel] ... = (g.eval z' - g.eval z₀).abs * δ ^ n : by rw hz'z₀ ... < _ : (mul_lt_mul_right (pow_pos hδ0 _)).2 (hδ _ hz'z₀), lt_irrefl (f.eval z₀).abs $ calc (f.eval z₀).abs ≤ (f.eval z').abs : hz₀ _ ... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp ... ≤ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _ ... < (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n + (g.eval z₀).abs * δ ^ n : add_lt_add_of_le_of_lt (by rw hF₂) hF₃ ... = (f.eval z₀).abs : sub_add_cancel _ _ end complex
876ade83c2f809d3ac7797f5af75c6242c9adf6f
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Init/Meta.lean
533fc8f80902f950c62d4ebdd3958c1f821ac4e3
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
46,885
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 and Sebastian Ullrich Additional goodies for writing macros -/ prelude import Init.Data.Array.Basic import Init.Data.Option.BasicAux namespace Lean @[extern c inline "lean_box(LEAN_VERSION_MAJOR)"] private opaque version.getMajor (u : Unit) : Nat def version.major : Nat := version.getMajor () @[extern c inline "lean_box(LEAN_VERSION_MINOR)"] private opaque version.getMinor (u : Unit) : Nat def version.minor : Nat := version.getMinor () @[extern c inline "lean_box(LEAN_VERSION_PATCH)"] private opaque version.getPatch (u : Unit) : Nat def version.patch : Nat := version.getPatch () @[extern "lean_get_githash"] opaque getGithash (u : Unit) : String def githash : String := getGithash () @[extern c inline "LEAN_VERSION_IS_RELEASE"] opaque version.getIsRelease (u : Unit) : Bool def version.isRelease : Bool := version.getIsRelease () /-- Additional version description like "nightly-2018-03-11" -/ @[extern c inline "lean_mk_string(LEAN_SPECIAL_VERSION_DESC)"] opaque version.getSpecialDesc (u : Unit) : String def version.specialDesc : String := version.getSpecialDesc () def versionStringCore := toString version.major ++ "." ++ toString version.minor ++ "." ++ toString version.patch def versionString := if version.specialDesc ≠ "" then versionStringCore ++ "-" ++ version.specialDesc else if version.isRelease then versionStringCore else versionStringCore ++ ", commit " ++ githash def origin := "leanprover/lean4" def toolchain := if version.specialDesc ≠ "" then if version.isRelease then origin ++ ":" ++ versionStringCore ++ "-" ++ version.specialDesc else origin ++ ":" ++ version.specialDesc else if version.isRelease then origin ++ ":" ++ versionStringCore else "" @[extern c inline "LEAN_IS_STAGE0"] opaque Internal.isStage0 (u : Unit) : Bool /-- Valid identifier names -/ def isGreek (c : Char) : Bool := 0x391 ≤ c.val && c.val ≤ 0x3dd def isLetterLike (c : Char) : Bool := (0x3b1 ≤ c.val && c.val ≤ 0x3c9 && c.val ≠ 0x3bb) || -- Lower greek, but lambda (0x391 ≤ c.val && c.val ≤ 0x3A9 && c.val ≠ 0x3A0 && c.val ≠ 0x3A3) || -- Upper greek, but Pi and Sigma (0x3ca ≤ c.val && c.val ≤ 0x3fb) || -- Coptic letters (0x1f00 ≤ c.val && c.val ≤ 0x1ffe) || -- Polytonic Greek Extended Character Set (0x2100 ≤ c.val && c.val ≤ 0x214f) || -- Letter like block (0x1d49c ≤ c.val && c.val ≤ 0x1d59f) -- Latin letters, Script, Double-struck, Fractur def isNumericSubscript (c : Char) : Bool := 0x2080 ≤ c.val && c.val ≤ 0x2089 def isSubScriptAlnum (c : Char) : Bool := isNumericSubscript c || (0x2090 ≤ c.val && c.val ≤ 0x209c) || (0x1d62 ≤ c.val && c.val ≤ 0x1d6a) def isIdFirst (c : Char) : Bool := c.isAlpha || c = '_' || isLetterLike c def isIdRest (c : Char) : Bool := c.isAlphanum || c = '_' || c = '\'' || c == '!' || c == '?' || isLetterLike c || isSubScriptAlnum c def idBeginEscape := '«' def idEndEscape := '»' def isIdBeginEscape (c : Char) : Bool := c = idBeginEscape def isIdEndEscape (c : Char) : Bool := c = idEndEscape namespace Name def getRoot : Name → Name | anonymous => anonymous | n@(str anonymous _) => n | n@(num anonymous _) => n | str n _ => getRoot n | num n _ => getRoot n @[export lean_is_inaccessible_user_name] def isInaccessibleUserName : Name → Bool | Name.str _ s => s.contains '✝' || s == "_inaccessible" | Name.num p _ => isInaccessibleUserName p | _ => false def escapePart (s : String) : Option String := if s.length > 0 && isIdFirst (s.get 0) && (s.toSubstring.drop 1).all isIdRest then s else if s.any isIdEndEscape then none else some <| idBeginEscape.toString ++ s ++ idEndEscape.toString -- NOTE: does not roundtrip even with `escape = true` if name is anonymous or contains numeric part or `idEndEscape` variable (sep : String) (escape : Bool) def toStringWithSep : Name → String | anonymous => "[anonymous]" | str anonymous s => maybeEscape s | num anonymous v => toString v | str n s => toStringWithSep n ++ sep ++ maybeEscape s | num n v => toStringWithSep n ++ sep ++ Nat.repr v where maybeEscape s := if escape then escapePart s |>.getD s else s protected def toString (n : Name) (escape := true) : String := -- never escape "prettified" inaccessible names or macro scopes or pseudo-syntax introduced by the delaborator toStringWithSep "." (escape && !n.isInaccessibleUserName && !n.hasMacroScopes && !maybePseudoSyntax) n where maybePseudoSyntax := if let .str _ s := n.getRoot then -- could be pseudo-syntax for loose bvar or universe mvar, output as is "#".isPrefixOf s || "?".isPrefixOf s else false instance : ToString Name where toString n := n.toString private def hasNum : Name → Bool | anonymous => false | num .. => true | str p .. => hasNum p protected def reprPrec (n : Name) (prec : Nat) : Std.Format := match n with | anonymous => Std.Format.text "Lean.Name.anonymous" | num p i => Repr.addAppParen ("Lean.Name.mkNum " ++ Name.reprPrec p max_prec ++ " " ++ repr i) prec | str p s => if p.hasNum then Repr.addAppParen ("Lean.Name.mkStr " ++ Name.reprPrec p max_prec ++ " " ++ repr s) prec else Std.Format.text "`" ++ n.toString instance : Repr Name where reprPrec := Name.reprPrec def capitalize : Name → Name | .str p s => .str p s.capitalize | n => n def replacePrefix : Name → Name → Name → Name | anonymous, anonymous, newP => newP | anonymous, _, _ => anonymous | n@(str p s), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s | n@(num p s), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s /-- `eraseSuffix? n s` return `n'` if `n` is of the form `n == n' ++ s`. -/ def eraseSuffix? : Name → Name → Option Name | n, anonymous => some n | str p s, str p' s' => if s == s' then eraseSuffix? p p' else none | num p s, num p' s' => if s == s' then eraseSuffix? p p' else none | _, _ => none /-- Remove macros scopes, apply `f`, and put them back -/ @[inline] def modifyBase (n : Name) (f : Name → Name) : Name := if n.hasMacroScopes then let view := extractMacroScopes n { view with name := f view.name }.review else f n @[export lean_name_append_after] def appendAfter (n : Name) (suffix : String) : Name := n.modifyBase fun | str p s => Name.mkStr p (s ++ suffix) | n => Name.mkStr n suffix @[export lean_name_append_index_after] def appendIndexAfter (n : Name) (idx : Nat) : Name := n.modifyBase fun | str p s => Name.mkStr p (s ++ "_" ++ toString idx) | n => Name.mkStr n ("_" ++ toString idx) @[export lean_name_append_before] def appendBefore (n : Name) (pre : String) : Name := n.modifyBase fun | anonymous => Name.mkStr anonymous pre | str p s => Name.mkStr p (pre ++ s) | num p n => Name.mkNum (Name.mkStr p pre) n protected theorem beq_iff_eq {m n : Name} : m == n ↔ m = n := by show m.beq n ↔ _ induction m generalizing n <;> cases n <;> simp_all [Name.beq, And.comm] instance : LawfulBEq Name where eq_of_beq := Name.beq_iff_eq.1 rfl := Name.beq_iff_eq.2 rfl instance : DecidableEq Name := fun a b => if h : a == b then .isTrue (by simp_all) else .isFalse (by simp_all) end Name structure NameGenerator where namePrefix : Name := `_uniq idx : Nat := 1 deriving Inhabited namespace NameGenerator @[inline] def curr (g : NameGenerator) : Name := Name.mkNum g.namePrefix g.idx @[inline] def next (g : NameGenerator) : NameGenerator := { g with idx := g.idx + 1 } @[inline] def mkChild (g : NameGenerator) : NameGenerator × NameGenerator := ({ namePrefix := Name.mkNum g.namePrefix g.idx, idx := 1 }, { g with idx := g.idx + 1 }) end NameGenerator class MonadNameGenerator (m : Type → Type) where getNGen : m NameGenerator setNGen : NameGenerator → m Unit export MonadNameGenerator (getNGen setNGen) def mkFreshId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m Name := do let ngen ← getNGen let r := ngen.curr setNGen ngen.next pure r instance monadNameGeneratorLift (m n : Type → Type) [MonadLift m n] [MonadNameGenerator m] : MonadNameGenerator n := { getNGen := liftM (getNGen : m _), setNGen := fun ngen => liftM (setNGen ngen : m _) } namespace Syntax deriving instance Repr for Syntax.Preresolved deriving instance Repr for Syntax deriving instance Repr for TSyntax abbrev Term := TSyntax `term abbrev Command := TSyntax `command protected abbrev Level := TSyntax `level protected abbrev Tactic := TSyntax `tactic abbrev Prec := TSyntax `prec abbrev Prio := TSyntax `prio abbrev Ident := TSyntax identKind abbrev StrLit := TSyntax strLitKind abbrev CharLit := TSyntax charLitKind abbrev NameLit := TSyntax nameLitKind abbrev ScientificLit := TSyntax scientificLitKind abbrev NumLit := TSyntax numLitKind end Syntax export Syntax (Term Command Prec Prio Ident StrLit CharLit NameLit ScientificLit NumLit) namespace TSyntax instance : Coe (TSyntax [k]) (TSyntax (k :: ks)) where coe stx := ⟨stx⟩ instance : Coe (TSyntax ks) (TSyntax (k' :: ks)) where coe stx := ⟨stx⟩ instance : Coe Ident Term where coe s := ⟨s.raw⟩ instance : CoeDep Term ⟨Syntax.ident info ss n res⟩ Ident where coe := ⟨Syntax.ident info ss n res⟩ instance : Coe StrLit Term where coe s := ⟨s.raw⟩ instance : Coe NameLit Term where coe s := ⟨s.raw⟩ instance : Coe ScientificLit Term where coe s := ⟨s.raw⟩ instance : Coe NumLit Term where coe s := ⟨s.raw⟩ instance : Coe CharLit Term where coe s := ⟨s.raw⟩ instance : Coe Ident Syntax.Level where coe s := ⟨s.raw⟩ instance : Coe NumLit Prio where coe s := ⟨s.raw⟩ instance : Coe NumLit Prec where coe s := ⟨s.raw⟩ namespace Compat scoped instance : CoeTail Syntax (TSyntax k) where coe s := ⟨s⟩ scoped instance : CoeTail (Array Syntax) (TSyntaxArray k) where coe := .mk end Compat end TSyntax namespace Syntax deriving instance BEq for Syntax.Preresolved /-- Compare syntax structures modulo source info. -/ partial def structEq : Syntax → Syntax → Bool | Syntax.missing, Syntax.missing => true | Syntax.node _ k args, Syntax.node _ k' args' => k == k' && args.isEqv args' structEq | Syntax.atom _ val, Syntax.atom _ val' => val == val' | Syntax.ident _ rawVal val preresolved, Syntax.ident _ rawVal' val' preresolved' => rawVal == rawVal' && val == val' && preresolved == preresolved' | _, _ => false instance : BEq Lean.Syntax := ⟨structEq⟩ instance : BEq (Lean.TSyntax k) := ⟨(·.raw == ·.raw)⟩ partial def getTailInfo? : Syntax → Option SourceInfo | atom info _ => info | ident info .. => info | node SourceInfo.none _ args => args.findSomeRev? getTailInfo? | node info _ _ => info | _ => none def getTailInfo (stx : Syntax) : SourceInfo := stx.getTailInfo?.getD SourceInfo.none def getTrailingSize (stx : Syntax) : Nat := match stx.getTailInfo? with | some (SourceInfo.original (trailing := trailing) ..) => trailing.bsize | _ => 0 /-- Return substring of original input covering `stx`. Result is meaningful only if all involved `SourceInfo.original`s refer to the same string (as is the case after parsing). -/ def getSubstring? (stx : Syntax) (withLeading := true) (withTrailing := true) : Option Substring := match stx.getHeadInfo, stx.getTailInfo with | SourceInfo.original lead startPos _ _, SourceInfo.original _ _ trail stopPos => some { str := lead.str startPos := if withLeading then lead.startPos else startPos stopPos := if withTrailing then trail.stopPos else stopPos } | _, _ => none @[specialize] private partial def updateLast {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if i == 0 then none else let i := i - 1 let v := a[i]! match f v with | some v => some <| a.set! i v | none => updateLast a f i partial def setTailInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node info k args => match updateLast args (setTailInfoAux info) args.size with | some args => some <| node info k args | none => none | _ => none def setTailInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setTailInfoAux info stx with | some stx => stx | none => stx def unsetTrailing (stx : Syntax) : Syntax := match stx.getTailInfo with | SourceInfo.original lead pos _ endPos => stx.setTailInfo (SourceInfo.original lead pos "".toSubstring endPos) | _ => stx @[specialize] private partial def updateFirst {α} [Inhabited α] (a : Array α) (f : α → Option α) (i : Nat) : Option (Array α) := if h : i < a.size then let v := a[i] match f v with | some v => some <| a.set ⟨i, h⟩ v | none => updateFirst a f (i+1) else none partial def setHeadInfoAux (info : SourceInfo) : Syntax → Option Syntax | atom _ val => some <| atom info val | ident _ rawVal val pre => some <| ident info rawVal val pre | node i k args => match updateFirst args (setHeadInfoAux info) 0 with | some args => some <| node i k args | _ => none | _ => none def setHeadInfo (stx : Syntax) (info : SourceInfo) : Syntax := match setHeadInfoAux info stx with | some stx => stx | none => stx def setInfo (info : SourceInfo) : Syntax → Syntax | atom _ val => atom info val | ident _ rawVal val pre => ident info rawVal val pre | node _ kind args => node info kind args | missing => missing /-- Return the first atom/identifier that has position information -/ partial def getHead? : Syntax → Option Syntax | stx@(atom info ..) => info.getPos?.map fun _ => stx | stx@(ident info ..) => info.getPos?.map fun _ => stx | node SourceInfo.none _ args => args.findSome? getHead? | stx@(node ..) => stx | _ => none def copyHeadTailInfoFrom (target source : Syntax) : Syntax := target.setHeadInfo source.getHeadInfo |>.setTailInfo source.getTailInfo /-- Ensure head position is synthetic. The server regards syntax as "original" only if both head and tail info are `original`. -/ def mkSynthetic (stx : Syntax) : Syntax := stx.setHeadInfo (SourceInfo.fromRef stx) end Syntax /-- Use the head atom/identifier of the current `ref` as the `ref` -/ @[inline] def withHeadRefOnly {m : Type → Type} [Monad m] [MonadRef m] {α} (x : m α) : m α := do match (← getRef).getHead? with | none => x | some ref => withRef ref x @[inline] def mkNode (k : SyntaxNodeKind) (args : Array Syntax) : TSyntax k := ⟨Syntax.node SourceInfo.none k args⟩ /-- Syntax objects for a Lean module. -/ structure Module where header : Syntax commands : Array Syntax /-- Expand macros in the given syntax. A node with kind `k` is visited only if `p k` is true. Note that the default value for `p` returns false for `by ...` nodes. This is a "hack". The tactic framework abuses the macro system to implement extensible tactics. For example, one can define ```lean syntax "my_trivial" : tactic -- extensible tactic macro_rules | `(tactic| my_trivial) => `(tactic| decide) macro_rules | `(tactic| my_trivial) => `(tactic| assumption) ``` When the tactic evaluator finds the tactic `my_trivial`, it tries to evaluate the `macro_rule` expansions until one "works", i.e., the macro expansion is evaluated without producing an exception. We say this solution is a bit hackish because the term elaborator may invoke `expandMacros` with `(p := fun _ => true)`, and expand the tactic macros as just macros. In the example above, `my_trivial` would be replaced with `assumption`, `decide` would not be tried if `assumption` fails at tactic evaluation time. We are considering two possible solutions for this issue: 1- A proper extensible tactic feature that does not rely on the macro system. 2- Typed macros that know the syntax categories they're working in. Then, we would be able to select which syntatic categories are expanded by `expandMacros`. -/ partial def expandMacros (stx : Syntax) (p : SyntaxNodeKind → Bool := fun k => k != `Lean.Parser.Term.byTactic) : MacroM Syntax := withRef stx do match stx with | .node info k args => do if p k then match (← expandMacro? stx) with | some stxNew => expandMacros stxNew | none => do let args ← Macro.withIncRecDepth stx <| args.mapM expandMacros return .node info k args else return stx | stx => return stx /-! # Helper functions for processing Syntax programmatically -/ /-- Create an identifier copying the position from `src`. To refer to a specific constant, use `mkCIdentFrom` instead. -/ def mkIdentFrom (src : Syntax) (val : Name) (canonical := false) : Ident := ⟨Syntax.ident (SourceInfo.fromRef src canonical) (toString val).toSubstring val []⟩ def mkIdentFromRef [Monad m] [MonadRef m] (val : Name) (canonical := false) : m Ident := do return mkIdentFrom (← getRef) val canonical /-- Create an identifier referring to a constant `c` copying the position from `src`. This variant of `mkIdentFrom` makes sure that the identifier cannot accidentally be captured. -/ def mkCIdentFrom (src : Syntax) (c : Name) (canonical := false) : Ident := -- Remark: We use the reserved macro scope to make sure there are no accidental collision with our frontend let id := addMacroScope `_internal c reservedMacroScope ⟨Syntax.ident (SourceInfo.fromRef src canonical) (toString id).toSubstring id [.decl c []]⟩ def mkCIdentFromRef [Monad m] [MonadRef m] (c : Name) (canonical := false) : m Syntax := do return mkCIdentFrom (← getRef) c canonical def mkCIdent (c : Name) : Ident := mkCIdentFrom Syntax.missing c @[export lean_mk_syntax_ident] def mkIdent (val : Name) : Ident := ⟨Syntax.ident SourceInfo.none (toString val).toSubstring val []⟩ @[inline] def mkNullNode (args : Array Syntax := #[]) : Syntax := mkNode nullKind args @[inline] def mkGroupNode (args : Array Syntax := #[]) : Syntax := mkNode groupKind args def mkSepArray (as : Array Syntax) (sep : Syntax) : Array Syntax := Id.run do let mut i := 0 let mut r := #[] for a in as do if i > 0 then r := r.push sep |>.push a else r := r.push a i := i + 1 return r def mkOptionalNode (arg : Option Syntax) : Syntax := match arg with | some arg => mkNullNode #[arg] | none => mkNullNode #[] def mkHole (ref : Syntax) (canonical := false) : Syntax := mkNode `Lean.Parser.Term.hole #[mkAtomFrom ref "_" canonical] namespace Syntax def mkSep (a : Array Syntax) (sep : Syntax) : Syntax := mkNullNode <| mkSepArray a sep def SepArray.ofElems {sep} (elems : Array Syntax) : SepArray sep := ⟨mkSepArray elems (if sep.isEmpty then mkNullNode else mkAtom sep)⟩ def SepArray.ofElemsUsingRef [Monad m] [MonadRef m] {sep} (elems : Array Syntax) : m (SepArray sep) := do let ref ← getRef; return ⟨mkSepArray elems (if sep.isEmpty then mkNullNode else mkAtomFrom ref sep)⟩ instance : Coe (Array Syntax) (SepArray sep) where coe := SepArray.ofElems instance : Coe (TSyntaxArray k) (TSepArray k sep) where coe a := ⟨mkSepArray a.raw (mkAtom sep)⟩ /-- Create syntax representing a Lean term application, but avoid degenerate empty applications. -/ def mkApp (fn : Term) : (args : TSyntaxArray `term) → Term | #[] => fn | args => ⟨mkNode `Lean.Parser.Term.app #[fn, mkNullNode args.raw]⟩ def mkCApp (fn : Name) (args : TSyntaxArray `term) : Term := mkApp (mkCIdent fn) args def mkLit (kind : SyntaxNodeKind) (val : String) (info := SourceInfo.none) : TSyntax kind := let atom : Syntax := Syntax.atom info val mkNode kind #[atom] def mkStrLit (val : String) (info := SourceInfo.none) : StrLit := mkLit strLitKind (String.quote val) info def mkNumLit (val : String) (info := SourceInfo.none) : NumLit := mkLit numLitKind val info def mkScientificLit (val : String) (info := SourceInfo.none) : TSyntax scientificLitKind := mkLit scientificLitKind val info def mkNameLit (val : String) (info := SourceInfo.none) : NameLit := mkLit nameLitKind val info /-! Recall that we don't have special Syntax constructors for storing numeric and string atoms. The idea is to have an extensible approach where embedded DSLs may have new kind of atoms and/or different ways of representing them. So, our atoms contain just the parsed string. The main Lean parser uses the kind `numLitKind` for storing natural numbers that can be encoded in binary, octal, decimal and hexadecimal format. `isNatLit` implements a "decoder" for Syntax objects representing these numerals. -/ private partial def decodeBinLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if c == '0' then decodeBinLitAux s (s.next i) (2*val) else if c == '1' then decodeBinLitAux s (s.next i) (2*val + 1) else none private partial def decodeOctalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '7' then decodeOctalLitAux s (s.next i) (8*val + c.toNat - '0'.toNat) else none private def decodeHexDigit (s : String) (i : String.Pos) : Option (Nat × String.Pos) := let c := s.get i let i := s.next i if '0' ≤ c && c ≤ '9' then some (c.toNat - '0'.toNat, i) else if 'a' ≤ c && c ≤ 'f' then some (10 + c.toNat - 'a'.toNat, i) else if 'A' ≤ c && c ≤ 'F' then some (10 + c.toNat - 'A'.toNat, i) else none private partial def decodeHexLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else match decodeHexDigit s i with | some (d, i) => decodeHexLitAux s i (16*val + d) | none => none private partial def decodeDecimalLitAux (s : String) (i : String.Pos) (val : Nat) : Option Nat := if s.atEnd i then some val else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeDecimalLitAux s (s.next i) (10*val + c.toNat - '0'.toNat) else none def decodeNatLitVal? (s : String) : Option Nat := let len := s.length if len == 0 then none else let c := s.get 0 if c == '0' then if len == 1 then some 0 else let c := s.get ⟨1⟩ if c == 'x' || c == 'X' then decodeHexLitAux s ⟨2⟩ 0 else if c == 'b' || c == 'B' then decodeBinLitAux s ⟨2⟩ 0 else if c == 'o' || c == 'O' then decodeOctalLitAux s ⟨2⟩ 0 else if c.isDigit then decodeDecimalLitAux s 0 0 else none else if c.isDigit then decodeDecimalLitAux s 0 0 else none def isLit? (litKind : SyntaxNodeKind) (stx : Syntax) : Option String := match stx with | Syntax.node _ k args => if k == litKind && args.size == 1 then match args.get! 0 with | (Syntax.atom _ val) => some val | _ => none else none | _ => none private def isNatLitAux (litKind : SyntaxNodeKind) (stx : Syntax) : Option Nat := match isLit? litKind stx with | some val => decodeNatLitVal? val | _ => none def isNatLit? (s : Syntax) : Option Nat := isNatLitAux numLitKind s def isFieldIdx? (s : Syntax) : Option Nat := isNatLitAux fieldIdxKind s /-- Decodes a 'scientific number' string which is consumed by the `OfScientific` class. Takes as input a string such as `123`, `123.456e7` and returns a triple `(n, sign, e)` with value given by `n * 10^-e` if `sign` else `n * 10^e`. -/ partial def decodeScientificLitVal? (s : String) : Option (Nat × Bool × Nat) := let len := s.length if len == 0 then none else let c := s.get 0 if c.isDigit then decode 0 0 else none where decodeAfterExp (i : String.Pos) (val : Nat) (e : Nat) (sign : Bool) (exp : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then if sign then some (val, sign, exp + e) else if exp >= e then some (val, sign, exp - e) else some (val, true, e - exp) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterExp (s.next i) val e sign (10*exp + c.toNat - '0'.toNat) else none decodeExp (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if c == '-' then decodeAfterExp (s.next i) val e true 0 else if c == '+' then decodeAfterExp (s.next i) val e false 0 else decodeAfterExp i val e false 0 decodeAfterDot (i : String.Pos) (val : Nat) (e : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then some (val, true, e) else let c := s.get i if '0' ≤ c && c ≤ '9' then decodeAfterDot (s.next i) (10*val + c.toNat - '0'.toNat) (e+1) else if c == 'e' || c == 'E' then decodeExp (s.next i) val e else none decode (i : String.Pos) (val : Nat) : Option (Nat × Bool × Nat) := if s.atEnd i then none else let c := s.get i if '0' ≤ c && c ≤ '9' then decode (s.next i) (10*val + c.toNat - '0'.toNat) else if c == '.' then decodeAfterDot (s.next i) val 0 else if c == 'e' || c == 'E' then decodeExp (s.next i) val 0 else none def isScientificLit? (stx : Syntax) : Option (Nat × Bool × Nat) := match isLit? scientificLitKind stx with | some val => decodeScientificLitVal? val | _ => none def isIdOrAtom? : Syntax → Option String | Syntax.atom _ val => some val | Syntax.ident _ rawVal _ _ => some rawVal.toString | _ => none def toNat (stx : Syntax) : Nat := match stx.isNatLit? with | some val => val | none => 0 def decodeQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := do let c := s.get i let i := s.next i if c == '\\' then pure ('\\', i) else if c = '\"' then pure ('\"', i) else if c = '\'' then pure ('\'', i) else if c = 'r' then pure ('\r', i) else if c = 'n' then pure ('\n', i) else if c = 't' then pure ('\t', i) else if c = 'x' then let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i pure (Char.ofNat (16*d₁ + d₂), i) else if c = 'u' then do let (d₁, i) ← decodeHexDigit s i let (d₂, i) ← decodeHexDigit s i let (d₃, i) ← decodeHexDigit s i let (d₄, i) ← decodeHexDigit s i pure (Char.ofNat (16*(16*(16*d₁ + d₂) + d₃) + d₄), i) else none partial def decodeStrLitAux (s : String) (i : String.Pos) (acc : String) : Option String := do let c := s.get i let i := s.next i if c == '\"' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeQuotedChar s i decodeStrLitAux s i (acc.push c) else decodeStrLitAux s i (acc.push c) def decodeStrLit (s : String) : Option String := decodeStrLitAux s ⟨1⟩ "" def isStrLit? (stx : Syntax) : Option String := match isLit? strLitKind stx with | some val => decodeStrLit val | _ => none def decodeCharLit (s : String) : Option Char := do let c := s.get ⟨1⟩ if c == '\\' then do let (c, _) ← decodeQuotedChar s ⟨2⟩ pure c else pure c def isCharLit? (stx : Syntax) : Option Char := match isLit? charLitKind stx with | some val => decodeCharLit val | _ => none private partial def splitNameLitAux (ss : Substring) (acc : List Substring) : List Substring := let splitRest (ss : Substring) (acc : List Substring) : List Substring := if ss.front == '.' then splitNameLitAux (ss.drop 1) acc else if ss.isEmpty then acc else [] if ss.isEmpty then [] else let curr := ss.front if isIdBeginEscape curr then let escapedPart := ss.takeWhile (!isIdEndEscape ·) let escapedPart := { escapedPart with stopPos := ss.stopPos.min (escapedPart.str.next escapedPart.stopPos) } if !isIdEndEscape (escapedPart.get <| escapedPart.prev ⟨escapedPart.bsize⟩) then [] else splitRest (ss.extract ⟨escapedPart.bsize⟩ ⟨ss.bsize⟩) (escapedPart :: acc) else if isIdFirst curr then let idPart := ss.takeWhile isIdRest splitRest (ss.extract ⟨idPart.bsize⟩ ⟨ss.bsize⟩) (idPart :: acc) else if curr.isDigit then let idPart := ss.takeWhile Char.isDigit splitRest (ss.extract ⟨idPart.bsize⟩ ⟨ss.bsize⟩) (idPart :: acc) else [] /-- Split a name literal (without the backtick) into its dot-separated components. For example, `foo.bla.«bo.o»` ↦ `["foo", "bla", "«bo.o»"]`. If the literal cannot be parsed, return `[]`. -/ def splitNameLit (ss : Substring) : List Substring := splitNameLitAux ss [] |>.reverse def decodeNameLit (s : String) : Option Name := if s.get 0 == '`' then match splitNameLitAux (s.toSubstring.drop 1) [] with | [] => none | comps => some <| comps.foldr (init := Name.anonymous) fun comp n => let comp := comp.toString if isIdBeginEscape comp.front then Name.mkStr n (comp.drop 1 |>.dropRight 1) else if comp.front.isDigit then if let some k := decodeNatLitVal? comp then Name.mkNum n k else unreachable! else Name.mkStr n comp else none def isNameLit? (stx : Syntax) : Option Name := match isLit? nameLitKind stx with | some val => decodeNameLit val | _ => none def hasArgs : Syntax → Bool | Syntax.node _ _ args => args.size > 0 | _ => false def isAtom : Syntax → Bool | atom _ _ => true | _ => false def isToken (token : String) : Syntax → Bool | atom _ val => val.trim == token.trim | _ => false def isNone (stx : Syntax) : Bool := match stx with | Syntax.node _ k args => k == nullKind && args.size == 0 -- when elaborating partial syntax trees, it's reasonable to interpret missing parts as `none` | Syntax.missing => true | _ => false def getOptionalIdent? (stx : Syntax) : Option Name := match stx.getOptional? with | some stx => some stx.getId | none => none partial def findAux (p : Syntax → Bool) : Syntax → Option Syntax | stx@(Syntax.node _ _ args) => if p stx then some stx else args.findSome? (findAux p) | stx => if p stx then some stx else none def find? (stx : Syntax) (p : Syntax → Bool) : Option Syntax := findAux p stx end Syntax namespace TSyntax def getNat (s : NumLit) : Nat := s.raw.isNatLit?.getD 0 def getId (s : Ident) : Name := s.raw.getId def getScientific (s : ScientificLit) : Nat × Bool × Nat := s.raw.isScientificLit?.getD (0, false, 0) def getString (s : StrLit) : String := s.raw.isStrLit?.getD "" def getChar (s : CharLit) : Char := s.raw.isCharLit?.getD default def getName (s : NameLit) : Name := s.raw.isNameLit?.getD .anonymous namespace Compat scoped instance : CoeTail (Array Syntax) (Syntax.TSepArray k sep) where coe a := (a : TSyntaxArray k) end Compat end TSyntax /-- Reflect a runtime datum back to surface syntax (best-effort). -/ class Quote (α : Type) (k : SyntaxNodeKind := `term) where quote : α → TSyntax k export Quote (quote) instance [Quote α k] [CoeHTCT (TSyntax k) (TSyntax [k'])] : Quote α k' := ⟨fun a => quote (k := k) a⟩ instance : Quote Term := ⟨id⟩ instance : Quote Bool := ⟨fun | true => mkCIdent ``Bool.true | false => mkCIdent ``Bool.false⟩ instance : Quote String strLitKind := ⟨Syntax.mkStrLit⟩ instance : Quote Nat numLitKind := ⟨fun n => Syntax.mkNumLit <| toString n⟩ instance : Quote Substring := ⟨fun s => Syntax.mkCApp ``String.toSubstring' #[quote s.toString]⟩ -- in contrast to `Name.toString`, we can, and want to be, precise here private def getEscapedNameParts? (acc : List String) : Name → Option (List String) | Name.anonymous => if acc.isEmpty then none else some acc | Name.str n s => do let s ← Name.escapePart s getEscapedNameParts? (s::acc) n | Name.num _ _ => none def quoteNameMk : Name → Term | .anonymous => mkCIdent ``Name.anonymous | .str n s => Syntax.mkCApp ``Name.mkStr #[quoteNameMk n, quote s] | .num n i => Syntax.mkCApp ``Name.mkNum #[quoteNameMk n, quote i] instance : Quote Name `term where quote n := match getEscapedNameParts? [] n with | some ss => ⟨mkNode `Lean.Parser.Term.quotedName #[Syntax.mkNameLit ("`" ++ ".".intercalate ss)]⟩ | none => ⟨quoteNameMk n⟩ instance [Quote α `term] [Quote β `term] : Quote (α × β) `term where quote | ⟨a, b⟩ => Syntax.mkCApp ``Prod.mk #[quote a, quote b] private def quoteList [Quote α `term] : List α → Term | [] => mkCIdent ``List.nil | (x::xs) => Syntax.mkCApp ``List.cons #[quote x, quoteList xs] instance [Quote α `term] : Quote (List α) `term where quote := quoteList private def quoteArray [Quote α `term] (xs : Array α) : Term := if xs.size <= 8 then go 0 #[] else Syntax.mkCApp ``List.toArray #[quote xs.toList] where go (i : Nat) (args : Array Term) : Term := if h : i < xs.size then go (i+1) (args.push (quote xs[i])) else Syntax.mkCApp (Name.mkStr2 "Array" ("mkArray" ++ toString xs.size)) args termination_by go i _ => xs.size - i instance [Quote α `term] : Quote (Array α) `term where quote := quoteArray instance Option.hasQuote {α : Type} [Quote α `term] : Quote (Option α) `term where quote | none => mkIdent ``none | (some x) => Syntax.mkCApp ``some #[quote x] /-- Evaluator for `prec` DSL -/ def evalPrec (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prec| $num:num) => return num.getNat | _ => Macro.throwErrorAt stx "unexpected precedence" macro_rules | `(prec| $a + $b) => do `(prec| $(quote <| (← evalPrec a) + (← evalPrec b)):num) macro_rules | `(prec| $a - $b) => do `(prec| $(quote <| (← evalPrec a) - (← evalPrec b)):num) macro "eval_prec " p:prec:max : term => return quote (k := `term) (← evalPrec p) /-- Evaluator for `prio` DSL -/ def evalPrio (stx : Syntax) : MacroM Nat := Macro.withIncRecDepth stx do let stx ← expandMacros stx match stx with | `(prio| $num:num) => return num.getNat | _ => Macro.throwErrorAt stx "unexpected priority" macro_rules | `(prio| $a + $b) => do `(prio| $(quote <| (← evalPrio a) + (← evalPrio b)):num) macro_rules | `(prio| $a - $b) => do `(prio| $(quote <| (← evalPrio a) - (← evalPrio b)):num) macro "eval_prio " p:prio:max : term => return quote (k := `term) (← evalPrio p) def evalOptPrio : Option (TSyntax `prio) → MacroM Nat | some prio => evalPrio prio | none => return 1000 -- TODO: FIX back eval_prio default end Lean namespace Array abbrev getSepElems := @getEvenElems open Lean private partial def filterSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a[i] if (← p stx) then if acc.isEmpty then filterSepElemsMAux a p (i+2) (acc.push stx) else if hz : i ≠ 0 then have : i.pred < i := Nat.pred_lt hz have : i.pred < a.size := Nat.lt_trans this h let sepStx := a[i.pred] filterSepElemsMAux a p (i+2) ((acc.push sepStx).push stx) else filterSepElemsMAux a p (i+2) (acc.push stx) else filterSepElemsMAux a p (i+2) acc else pure acc def filterSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (p : Syntax → m Bool) : m (Array Syntax) := filterSepElemsMAux a p 0 #[] def filterSepElems (a : Array Syntax) (p : Syntax → Bool) : Array Syntax := Id.run <| a.filterSepElemsM p private partial def mapSepElemsMAux {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) (i : Nat) (acc : Array Syntax) : m (Array Syntax) := do if h : i < a.size then let stx := a[i] if i % 2 == 0 then do let stx ← f stx mapSepElemsMAux a f (i+1) (acc.push stx) else mapSepElemsMAux a f (i+1) (acc.push stx) else pure acc def mapSepElemsM {m : Type → Type} [Monad m] (a : Array Syntax) (f : Syntax → m Syntax) : m (Array Syntax) := mapSepElemsMAux a f 0 #[] def mapSepElems (a : Array Syntax) (f : Syntax → Syntax) : Array Syntax := Id.run <| a.mapSepElemsM f end Array namespace Lean.Syntax def SepArray.getElems (sa : SepArray sep) : Array Syntax := sa.elemsAndSeps.getSepElems def TSepArray.getElems (sa : TSepArray k sep) : TSyntaxArray k := .mk sa.elemsAndSeps.getSepElems def TSepArray.push (sa : TSepArray k sep) (e : TSyntax k) : TSepArray k sep := if sa.elemsAndSeps.isEmpty then { elemsAndSeps := #[e] } else { elemsAndSeps := sa.elemsAndSeps.push (mkAtom sep) |>.push e } instance : EmptyCollection (SepArray sep) where emptyCollection := ⟨∅⟩ instance : EmptyCollection (TSepArray sep k) where emptyCollection := ⟨∅⟩ /- We use `CoeTail` here instead of `Coe` to avoid a "loop" when computing `CoeTC`. The "loop" is interrupted using the maximum instance size threshold, but it is a performance bottleneck. The loop occurs because the predicate `isNewAnswer` is too imprecise. -/ instance : CoeTail (SepArray sep) (Array Syntax) where coe := SepArray.getElems instance : Coe (TSepArray k sep) (TSyntaxArray k) where coe := TSepArray.getElems instance [Coe (TSyntax k) (TSyntax k')] : Coe (TSyntaxArray k) (TSyntaxArray k') where coe a := a.map Coe.coe instance : Coe (TSyntaxArray k) (Array Syntax) where coe a := a.raw instance : Coe Ident (TSyntax `Lean.Parser.Command.declId) where coe id := mkNode _ #[id, mkNullNode #[]] instance : Coe (Lean.Term) (Lean.TSyntax `Lean.Parser.Term.funBinder) where coe stx := ⟨stx⟩ end Lean.Syntax set_option linter.unusedVariables.funArgs false in /-- Gadget for automatic parameter support. This is similar to the `optParam` gadget, but it uses the given tactic. Like `optParam`, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ abbrev autoParam.{u} (α : Sort u) (tactic : Lean.Syntax) : Sort u := α /-! # Helper functions for manipulating interpolated strings -/ namespace Lean.Syntax private def decodeInterpStrQuotedChar (s : String) (i : String.Pos) : Option (Char × String.Pos) := do match decodeQuotedChar s i with | some r => some r | none => let c := s.get i let i := s.next i if c == '{' then pure ('{', i) else none private partial def decodeInterpStrLit (s : String) : Option String := let rec loop (i : String.Pos) (acc : String) : Option String := let c := s.get i let i := s.next i if c == '\"' || c == '{' then pure acc else if s.atEnd i then none else if c == '\\' then do let (c, i) ← decodeInterpStrQuotedChar s i loop i (acc.push c) else loop i (acc.push c) loop ⟨1⟩ "" partial def isInterpolatedStrLit? (stx : Syntax) : Option String := match isLit? interpolatedStrLitKind stx with | none => none | some val => decodeInterpStrLit val def getSepArgs (stx : Syntax) : Array Syntax := stx.getArgs.getSepElems end Syntax namespace TSyntax def expandInterpolatedStrChunks (chunks : Array Syntax) (mkAppend : Syntax → Syntax → MacroM Syntax) (mkElem : Syntax → MacroM Syntax) : MacroM Syntax := do let mut i := 0 let mut result := Syntax.missing for elem in chunks do let elem ← match elem.isInterpolatedStrLit? with | none => mkElem elem | some str => mkElem (Syntax.mkStrLit str) if i == 0 then result := elem else result ← mkAppend result elem i := i+1 return result open TSyntax.Compat in def expandInterpolatedStr (interpStr : TSyntax interpolatedStrKind) (type : Term) (toTypeFn : Term) : MacroM Term := do let r ← expandInterpolatedStrChunks interpStr.raw.getArgs (fun a b => `($a ++ $b)) (fun a => `($toTypeFn $a)) `(($r : $type)) end TSyntax namespace Meta inductive TransparencyMode where | all | default | reducible | instances deriving Inhabited, BEq, Repr inductive EtaStructMode where /-- Enable eta for structure and classes. -/ | all /-- Enable eta only for structures that are not classes. -/ | notClasses /-- Disable eta for structures and classes. -/ | none deriving Inhabited, BEq, Repr namespace DSimp structure Config where zeta : Bool := true beta : Bool := true eta : Bool := true etaStruct : EtaStructMode := .all iota : Bool := true proj : Bool := true decide : Bool := true autoUnfold : Bool := false deriving Inhabited, BEq, Repr end DSimp namespace Simp def defaultMaxSteps := 100000 structure Config where maxSteps : Nat := defaultMaxSteps maxDischargeDepth : Nat := 2 contextual : Bool := false memoize : Bool := true singlePass : Bool := false zeta : Bool := true beta : Bool := true eta : Bool := true etaStruct : EtaStructMode := .all iota : Bool := true proj : Bool := true decide : Bool := true arith : Bool := false autoUnfold : Bool := false /-- If `dsimp := true`, then switches to `dsimp` on dependent arguments where there is no congruence theorem that allows `simp` to visit them. If `dsimp := false`, then argument is not visited. -/ dsimp : Bool := true deriving Inhabited, BEq, Repr -- Configuration object for `simp_all` structure ConfigCtx extends Config where contextual := true def neutralConfig : Simp.Config := { zeta := false beta := false eta := false iota := false proj := false decide := false arith := false autoUnfold := false } end Simp namespace Rewrite structure Config where transparency : TransparencyMode := TransparencyMode.reducible offsetCnstrs : Bool := true end Rewrite end Meta namespace Parser.Tactic /-- `erw [rules]` is a shorthand for `rw (config := { transparency := .default }) [rules]`. This does rewriting up to unfolding of regular definitions (by comparison to regular `rw` which only unfolds `@[reducible]` definitions). -/ macro "erw " s:rwRuleSeq loc:(location)? : tactic => `(tactic| rw (config := { transparency := .default }) $s $(loc)?) syntax simpAllKind := atomic("(" &"all") " := " &"true" ")" syntax dsimpKind := atomic("(" &"dsimp") " := " &"true" ")" macro (name := declareSimpLikeTactic) doc?:(docComment)? "declare_simp_like_tactic" opt:((simpAllKind <|> dsimpKind)?) tacName:ident tacToken:str updateCfg:term : command => do let (kind, tkn, stx) ← if opt.raw.isNone then pure (← `(``simp), ← `("simp"), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&" only")? (" [" (simpStar <|> simpErase <|> simpLemma),* "]")? (location)? : tactic)) else if opt.raw[0].getKind == ``simpAllKind then pure (← `(``simpAll), ← `("simp_all"), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&" only")? (" [" (simpErase <|> simpLemma),* "]")? : tactic)) else pure (← `(``dsimp), ← `("dsimp"), ← `($[$doc?:docComment]? syntax (name := $tacName) $tacToken:str (config)? (discharger)? (&" only")? (" [" (simpErase <|> simpLemma),* "]")? (location)? : tactic)) `($stx:command @[macro $tacName] def expandSimp : Macro := fun s => do let c ← match s[1][0] with | `(config| (config := $$c)) => `(config| (config := $updateCfg $$c)) | _ => `(config| (config := $updateCfg {})) let s := s.setKind $kind let s := s.setArg 0 (mkAtomFrom s[0] $tkn (canonical := true)) let r := s.setArg 1 (mkNullNode #[c]) return r) /-- `simp!` is shorthand for `simp` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic simpAutoUnfold "simp! " fun (c : Lean.Meta.Simp.Config) => { c with autoUnfold := true } /-- `simp_arith` is shorthand for `simp` with `arith := true`. This enables the use of normalization by linear arithmetic. -/ declare_simp_like_tactic simpArith "simp_arith " fun (c : Lean.Meta.Simp.Config) => { c with arith := true } /-- `simp_arith!` is shorthand for `simp_arith` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic simpArithAutoUnfold "simp_arith! " fun (c : Lean.Meta.Simp.Config) => { c with arith := true, autoUnfold := true } /-- `simp_all!` is shorthand for `simp_all` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic (all := true) simpAllAutoUnfold "simp_all! " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with autoUnfold := true } /-- `simp_all_arith` combines the effects of `simp_all` and `simp_arith`. -/ declare_simp_like_tactic (all := true) simpAllArith "simp_all_arith " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with arith := true } /-- `simp_all_arith!` combines the effects of `simp_all`, `simp_arith` and `simp!`. -/ declare_simp_like_tactic (all := true) simpAllArithAutoUnfold "simp_all_arith! " fun (c : Lean.Meta.Simp.ConfigCtx) => { c with arith := true, autoUnfold := true } /-- `dsimp!` is shorthand for `dsimp` with `autoUnfold := true`. This will rewrite with all equation lemmas, which can be used to partially evaluate many definitions. -/ declare_simp_like_tactic (dsimp := true) dsimpAutoUnfold "dsimp! " fun (c : Lean.Meta.DSimp.Config) => { c with autoUnfold := true } end Parser.Tactic end Lean
3906668fd4dd1e192785fac5aa9cefb661afc79a
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/cpdt.lean
086c8b7f501dd4573acd3889c892134b82d89b04
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
1,075
lean
/- "Proving in the Large" chapter of CPDT -/ inductive exp : Type | Const (n : nat) : exp | Plus (e1 e2 : exp) : exp | Mult (e1 e2 : exp) : exp open exp def eeval : exp → nat | (Const n) := n | (Plus e1 e2) := eeval e1 + eeval e2 | (Mult e1 e2) := eeval e1 * eeval e2 def times (k : nat) : exp → exp | (Const n) := Const (k * n) | (Plus e1 e2) := Plus (times e1) (times e2) | (Mult e1 e2) := Mult (times e1) e2 def reassoc : exp → exp | (Const n) := (Const n) | (Plus e1 e2) := let e1' := reassoc e1 in let e2' := reassoc e2 in match e2' with | (Plus e21 e22) := Plus (Plus e1' e21) e22 | _ := Plus e1' e2' end | (Mult e1 e2) := let e1' := reassoc e1 in let e2' := reassoc e2 in match e2' with | (Mult e21 e22) := Mult (Mult e1' e21) e22 | _ := Mult e1' e2' end attribute [simp] mul_add times reassoc eeval theorem eeval_times (k e) : eeval (times k e) = k * eeval e := by induction e; simph theorem reassoc_correct (e) : eeval (reassoc e) = eeval e := by induction e; simph; cases (reassoc e2); rsimp
f0a405822706ab4524198f859b575e1498df00b9
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/algebra/char_zero.lean
227874cf64fa955bfb5adc30c48683acdf1b170c
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
3,106
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import data.nat.cast algebra.group algebra.field /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) -/ class char_zero (α : Type*) [add_monoid α] [has_one α] : Prop := (cast_inj : ∀ {m n : ℕ}, (m : α) = n ↔ m = n) theorem char_zero_of_inj_zero {α : Type*} [add_monoid α] [has_one α] (add_left_cancel : ∀ a b c : α, a + b = a + c → b = c) (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := ⟨λ m n, ⟨suffices ∀ {m n : ℕ}, (m:α) = n → m ≤ n, from λ h, le_antisymm (this h) (this h.symm), λ m n h, (le_total m n).elim id $ λ h2, le_of_eq $ begin cases nat.le.dest h2 with k e, suffices : k = 0, {rw [← e, this, add_zero]}, apply H, apply add_left_cancel n, rw [← nat.cast_add, e, add_zero, h] end, congr_arg _⟩⟩ theorem add_group.char_zero_of_inj_zero {α : Type*} [add_group α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H theorem ordered_cancel_comm_monoid.char_zero_of_inj_zero {α : Type*} [ordered_cancel_comm_monoid α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H instance linear_ordered_semiring.to_char_zero {α : Type*} [linear_ordered_semiring α] : char_zero α := ordered_cancel_comm_monoid.char_zero_of_inj_zero $ λ n h, nat.eq_zero_of_le_zero $ (@nat.cast_le α _ _ _).1 (le_of_eq h) namespace nat variables {α : Type*} [add_monoid α] [has_one α] [char_zero α] @[simp] theorem cast_inj {m n : ℕ} : (m : α) = n ↔ m = n := char_zero.cast_inj _ theorem cast_injective : function.injective (coe : ℕ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero {n : ℕ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[simp] theorem cast_ne_zero {n : ℕ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero end nat lemma two_ne_zero' {α : Type*} [add_monoid α] [has_one α] [char_zero α] : (2:α) ≠ 0 := have ((2:ℕ):α) ≠ 0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_succ, nat.cast_one] at this section variables {α : Type*} [domain α] [char_zero α] lemma add_self_eq_zero {a : α} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] lemma bit0_eq_zero {a : α} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero end section variables {α : Type*} [division_ring α] [char_zero α] @[simp] lemma half_add_self (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : α) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : α) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : α) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end
67b1a07c44bbbb978ec7a4772a418f4030190f25
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category/fold.lean
847a097012844420a6de6f4b25a7a449e1e08c4a
[ "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
14,624
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Sean Leather List folds generalized to `traversable`. Informally, we can think of `foldl` as a special case of `traverse` where we do not care about the reconstructed data structure and, in a state monad, we care about the final state. The obvious way to define `foldl` would be to use the state monad but it is nicer to reason about a more abstract interface with `fold_map` as a primitive and `fold_map_hom` as a defining property. def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := ... lemma fold_map_hom (α β) [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] (g : γ → α) (x : t γ) : f (fold_map g x) = fold_map (f ∘ g) x := ... `fold_map` uses a monoid ω to accumulate a value for every element of a data structure and `fold_map_hom` uses a monoid homomorphism to substitute the monoid used by `fold_map`. The two are sufficient to define `foldl`, `foldr` and `to_list`. `to_list` permits the formulation of specifications in terms of operations on lists. Each fold function can be defined using a specialized monoid. `to_list` uses a free monoid represented as a list with concatenation while `foldl` uses endofunctions together with function composition. The definition through monoids uses `traverse` together with the applicative functor `const m` (where `m` is the monoid). As an implementation, `const` guarantees that no resource is spent on reconstructing the structure during traversal. A special class could be defined for `foldable`, similarly to Haskell, but the author cannot think of instances of `foldable` that are not also `traversable`. -/ import tactic.squeeze import algebra.group algebra.opposites import data.list.basic import category.traversable.instances category.traversable.lemmas import category_theory.category category_theory.endomorphism category_theory.types category_theory.instances.kleisli import category.applicative universes u v open ulift category_theory opposite namespace monoid variables {m : Type u → Type u} [monad m] variables {α β : Type u} /-- For a list, foldl f x [y₀,y₁] reduces as follows calc foldl f x [y₀,y₁] = foldl f (f x y₀) [y₁] : rfl ... = foldl f (f (f x y₀) y₁) [] : rfl ... = f (f x y₀) y₁ : rfl with f : α → β → α x : α [y₀,y₁] : list β We can view the above as a composition of functions: ... = f (f x y₀) y₁ : rfl ... = flip f y₁ (flip f y₀ x) : rfl ... = (flip f y₁ ∘ flip f y₀) x : rfl We can use traverse and const to construct this composition: calc const.run (traverse (λ y, const.mk' (flip f y)) [y₀,y₁]) x = const.run ((::) <$> const.mk' (flip f y₀) <*> traverse (λ y, const.mk' (flip f y)) [y₁]) x ... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> traverse (λ y, const.mk' (flip f y)) [] )) x ... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x ... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘ ((::) <$> const.mk' (flip f y₀)) ) x ... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x ... = const.run ( flip f y₁ ∘ flip f y₀ ) x ... = f (f x y₀) y₁ And this is how `const` turns a monoid into an applicative functor and how the monoid of endofunctions define `foldl`. -/ @[reducible] def foldl (α : Type u) : Type u := (End α)ᵒᵖ def foldl.mk (f : α → α) : foldl α := op f def foldl.get (x : foldl α) : α → α := unop x def foldl.of_free_monoid (f : β → α → β) (xs : free_monoid α) : monoid.foldl β := op $ flip (list.foldl f) xs @[reducible] def foldr (α : Type u) : Type u := End α def foldr.mk (f : α → α) : foldr α := f def foldr.get (x : foldr α) : α → α := x def foldr.of_free_monoid (f : α → β → β) (xs : free_monoid α) : monoid.foldr β := flip (list.foldr f) xs @[reducible] def mfoldl (m : Type u → Type u) [monad m] (α : Type u) : Type u := opposite $ End $ Kleisli.mk m α def mfoldl.mk (f : α → m α) : mfoldl m α := op f def mfoldl.get (x : mfoldl m α) : α → m α := unop x def mfoldl.of_free_monoid (f : β → α → m β) (xs : free_monoid α) : monoid.mfoldl m β := op $ flip (list.mfoldl f) xs @[reducible] def mfoldr (m : Type u → Type u) [monad m] (α : Type u) : Type u := End $ Kleisli.mk m α def mfoldr.mk (f : α → m α) : mfoldr m α := f def mfoldr.get (x : mfoldr m α) : α → m α := x def mfoldr.of_free_monoid (f : α → β → m β) (xs : free_monoid α) : monoid.mfoldr m β := flip (list.mfoldr f) xs end monoid namespace traversable open monoid functor section defs variables {α β : Type u} {t : Type u → Type u} [traversable t] def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := traverse (const.mk' ∘ f) def foldl (f : α → β → α) (x : α) (xs : t β) : α := (fold_map (foldl.mk ∘ flip f) xs).get x def foldr (f : α → β → β) (x : β) (xs : t α) : β := (fold_map (foldr.mk ∘ f) xs).get x /-- Conceptually, `to_list` collects all the elements of a collection in a list. This idea is formalized by `lemma to_list_spec (x : t α) : to_list x = fold_map free_monoid.mk x`. The definition of `to_list` is based on `foldl` and `list.cons` for speed. It is faster than using `fold_map free_monoid.mk` because, by using `foldl` and `list.cons`, each insertion is done in constant time. As a consequence, `to_list` performs in linear. On the other hand, `fold_map free_monoid.mk` creates a singleton list around each element and concatenates all the resulting lists. In `xs ++ ys`, concatenation takes a time proportional to `length xs`. Since the order in which concatenation is evaluated is unspecified, nothing prevents each element of the traversable to be appended at the end `xs ++ [x]` which would yield a `O(n²)` run time. -/ def to_list : t α → list α := list.reverse ∘ foldl (flip list.cons) [] def length (xs : t α) : ℕ := down $ foldl (λ l _, up $ l.down + 1) (up 0) xs variables {m : Type u → Type u} [monad m] def mfoldl (f : α → β → m α) (x : α) (xs : t β) : m α := (fold_map (mfoldl.mk ∘ flip f) xs).get x def mfoldr (f : α → β → m β) (x : β) (xs : t α) : m β := (fold_map (mfoldr.mk ∘ f) xs).get x end defs section applicative_transformation variables {α β γ : Type u} open function (hiding const) is_monoid_hom def map_fold [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] : applicative_transformation (const α) (const β) := { app := λ x, f, preserves_seq' := by { intros, simp only [map_mul f], }, preserves_pure' := by { intros, simp only [map_one f] } } def free.mk : α → free_monoid α := list.ret def free.map (f : α → β) : free_monoid α → free_monoid β := list.map f lemma free.map_eq_map (f : α → β) (xs : list α) : f <$> xs = free.map f xs := rfl instance (f : α → β) : is_monoid_hom (free.map f) := { map_mul := λ x y, by simp only [free.map, list.map_append, free_add_monoid.add_def], map_one := by simp only [free.map, list.map, free_add_monoid.zero_def] } instance fold_foldl (f : β → α → β) : is_monoid_hom (foldl.of_free_monoid f) := { map_one := rfl, map_mul := by intros; simp only [free_monoid.mul_def, foldl.of_free_monoid, flip, unop_op, list.foldl_append, op_inj_iff]; refl } lemma foldl.unop_of_free_monoid (f : β → α → β) (xs : free_monoid α) (a : β) : unop (foldl.of_free_monoid f xs) a = list.foldl f a xs := rfl instance fold_foldr (f : α → β → β) : is_monoid_hom (foldr.of_free_monoid f) := { map_one := rfl, map_mul := by intros; simp only [free_monoid.mul_def, foldr.of_free_monoid, list.foldr_append, flip]; refl } variables (m : Type u → Type u) [monad m] [is_lawful_monad m] @[simp] lemma mfoldl.unop_of_free_monoid (f : β → α → m β) (xs : free_monoid α) (a : β) : unop (mfoldl.of_free_monoid f xs) a = list.mfoldl f a xs := rfl instance fold_mfoldl (f : β → α → m β) : is_monoid_hom (mfoldl.of_free_monoid f) := { map_one := rfl, map_mul := by intros; apply unop_inj; ext; apply list.mfoldl_append } instance fold_mfoldr (f : α → β → m β) : is_monoid_hom (mfoldr.of_free_monoid f) := { map_one := rfl, map_mul := by intros; ext; apply list.mfoldr_append } variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t] open is_lawful_traversable lemma fold_map_hom [monoid α] [monoid β] (f : α → β) [is_monoid_hom f] (g : γ → α) (x : t γ) : f (fold_map g x) = fold_map (f ∘ g) x := calc f (fold_map g x) = f (traverse (const.mk' ∘ g) x) : rfl ... = (map_fold f).app _ (traverse (const.mk' ∘ g) x) : rfl ... = traverse ((map_fold f).app _ ∘ (const.mk' ∘ g)) x : naturality (map_fold f) _ _ ... = fold_map (f ∘ g) x : rfl lemma fold_map_hom_free [monoid β] (f : free_monoid α → β) [is_monoid_hom f] (x : t α) : f (fold_map free.mk x) = fold_map (f ∘ free.mk) x := fold_map_hom _ _ x variable {m} lemma fold_mfoldl_cons (f : α → β → m α) (x : β) (y : α) : list.mfoldl f y (free.mk x) = f y x := by simp only [free.mk, list.ret, list.mfoldl, bind_pure] lemma fold_mfoldr_cons (f : β → α → m α) (x : β) (y : α) : list.mfoldr f y (free.mk x) = f x y := by simp only [free.mk, list.ret, list.mfoldr, pure_bind] end applicative_transformation section equalities open is_lawful_traversable list (cons) variables {α β γ : Type u} variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t] @[simp] lemma foldl.of_free_monoid_comp_free_mk (f : α → β → α) : foldl.of_free_monoid f ∘ free.mk = foldl.mk ∘ flip f := rfl @[simp] lemma foldr.of_free_monoid_comp_free_mk (f : β → α → α) : foldr.of_free_monoid f ∘ free.mk = foldr.mk ∘ f := rfl @[simp] lemma mfoldl.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : α → β → m α) : mfoldl.of_free_monoid f ∘ free.mk = mfoldl.mk ∘ flip f := by ext; simp only [(∘), mfoldl.of_free_monoid, mfoldl.mk, flip, fold_mfoldl_cons]; refl @[simp] lemma mfoldr.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : β → α → m α) : mfoldr.of_free_monoid f ∘ free.mk = mfoldr.mk ∘ f := by { ext, simp only [(∘), mfoldr.of_free_monoid, mfoldr.mk, flip, fold_mfoldr_cons] } lemma to_list_spec (xs : t α) : to_list xs = (fold_map free.mk xs : free_monoid _) := eq.symm $ calc fold_map free.mk xs = (fold_map free.mk xs).reverse.reverse : by simp only [list.reverse_reverse] ... = (list.foldr cons [] (fold_map free.mk xs).reverse).reverse : by simp only [list.foldr_eta] ... = (unop (foldl.of_free_monoid (flip cons) (fold_map free.mk xs)) []).reverse : by simp only [flip,list.foldr_reverse,foldl.of_free_monoid, unop_op] ... = to_list xs : begin rw fold_map_hom_free (foldl.of_free_monoid (flip cons)), simp only [to_list, foldl, list.reverse_inj, foldl.get, foldl.of_free_monoid_comp_free_mk], all_goals { apply_instance } end lemma fold_map_map [monoid γ] (f : α → β) (g : β → γ) (xs : t α) : fold_map g (f <$> xs) = fold_map (g ∘ f) xs := by simp only [fold_map,traverse_map] lemma foldl_to_list (f : α → β → α) (xs : t β) (x : α) : foldl f x xs = list.foldl f x (to_list xs) := by { rw ← foldl.unop_of_free_monoid, simp only [foldl, to_list_spec, fold_map_hom_free (foldl.of_free_monoid f), foldl.of_free_monoid_comp_free_mk, foldl.get] } lemma foldr_to_list (f : α → β → β) (xs : t α) (x : β) : foldr f x xs = list.foldr f x (to_list xs) := by { change _ = foldr.of_free_monoid _ _ _, simp only [foldr, to_list_spec, fold_map_hom_free (foldr.of_free_monoid f), foldr.of_free_monoid_comp_free_mk, foldr.get] } lemma to_list_map (f : α → β) (xs : t α) : to_list (f <$> xs) = f <$> to_list xs := by simp only [to_list_spec,free.map_eq_map,fold_map_hom (free.map f), fold_map_map]; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : t β) : foldl f a (g <$> l) = foldl (λ x y, f x (g y)) a l := by simp only [foldl, fold_map_map, (∘), flip] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : t β) : foldr f a (g <$> l) = foldr (f ∘ g) a l := by simp only [foldr, fold_map_map, (∘), flip] @[simp] theorem to_list_eq_self {xs : list α} : to_list xs = xs := begin simp only [to_list_spec, fold_map, traverse], induction xs, case list.nil { refl }, case list.cons : _ _ ih { unfold list.traverse list.ret, rw ih, refl } end theorem length_to_list {xs : t α} : length xs = list.length (to_list xs) := begin unfold length, rw foldl_to_list, generalize : to_list xs = ys, let f := λ (n : ℕ) (a : α), n + 1, transitivity list.foldl f 0 ys, { generalize : 0 = n, induction ys with _ _ ih generalizing n, { simp only [list.foldl_nil] }, { simp only [list.foldl, ih (n+1)] } }, { induction ys with _ tl ih, { simp only [list.length, list.foldl_nil] }, { simp only [list.foldl, list.length], transitivity list.foldl f 0 tl + 1, { exact eq.symm (list.foldl_hom (+1) f f 0 (λ _ _, rfl) _) }, { rw ih } } } end variables {m : Type u → Type u} [monad m] [is_lawful_monad m] lemma mfoldl_to_list {f : α → β → m α} {x : α} {xs : t β} : mfoldl f x xs = list.mfoldl f x (to_list xs) := by { change _ = unop (mfoldl.of_free_monoid f (to_list xs)) x, simp only [mfoldl, to_list_spec, fold_map_hom_free (mfoldl.of_free_monoid f), mfoldl.of_free_monoid_comp_free_mk, mfoldl.get] } lemma mfoldr_to_list (f : α → β → m β) (x : β) (xs : t α) : mfoldr f x xs = list.mfoldr f x (to_list xs) := by { change _ = mfoldr.of_free_monoid f (to_list xs) x, simp only [mfoldr, to_list_spec, fold_map_hom_free (mfoldr.of_free_monoid f), mfoldr.of_free_monoid_comp_free_mk, mfoldr.get] } @[simp] theorem mfoldl_map (g : β → γ) (f : α → γ → m α) (a : α) (l : t β) : mfoldl f a (g <$> l) = mfoldl (λ x y, f x (g y)) a l := by simp only [mfoldl, fold_map_map, (∘), flip] @[simp] theorem mfoldr_map (g : β → γ) (f : γ → α → m α) (a : α) (l : t β) : mfoldr f a (g <$> l) = mfoldr (f ∘ g) a l := by simp only [mfoldr, fold_map_map, (∘), flip] end equalities end traversable
b815f045a599b815ac35b925d3041e74fe0b60d5
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/analysis/normed_space/bounded_linear_maps.lean
3c9e109a0e4ab21493c29cedc30f3fad4124ecea
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,326
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import analysis.normed_space.multilinear import analysis.normed_space.units import analysis.asymptotics.asymptotics /-! # Bounded linear maps This file defines a class stating that a map between normed vector spaces is (bi)linear and continuous. Instead of asking for continuity, the definition takes the equivalent condition (because the space is normed) that `∥f x∥` is bounded by a multiple of `∥x∥`. Hence the "bounded" in the name refers to `∥f x∥/∥x∥` rather than `∥f x∥` itself. ## Main definitions * `is_bounded_linear_map`: Class stating that a map `f : E → F` is linear and has `∥f x∥` bounded by a multiple of `∥x∥`. * `is_bounded_bilinear_map`: Class stating that a map `f : E × F → G` is bilinear and continuous, but through the simpler to provide statement that `∥f (x, y)∥` is bounded by a multiple of `∥x∥ * ∥y∥` * `is_bounded_bilinear_map.linear_deriv`: Derivative of a continuous bilinear map as a linear map. * `is_bounded_bilinear_map.deriv`: Derivative of a continuous bilinear map as a continuous linear map. The proof that it is indeed the derivative is `is_bounded_bilinear_map.has_fderiv_at` in `analysis.calculus.fderiv`. ## Main theorems * `is_bounded_bilinear_map.continuous`: A bounded bilinear map is continuous. * `linear_map.norm_apply_of_isometry`: A linear isometry preserves the norm. * `continuous_linear_equiv.is_open`: The continuous linear equivalences are an open subset of the set of continuous linear maps between a pair of Banach spaces. Placed in this file because its proof uses `is_bounded_bilinear_map.continuous`. ## Notes The main use of this file is `is_bounded_bilinear_map`. The file `analysis.normed_space.multilinear` already expounds the theory of multilinear maps, but the `2`-variables case is sufficiently simpler to currently deserve its own treatment. `is_bounded_linear_map` is effectively an unbundled version of `continuous_linear_map` (defined in `topology.algebra.module`, theory over normed spaces developed in `analysis.normed_space.operator_norm`), albeit the name disparity. A bundled `continuous_linear_map` is to be preferred over a `is_bounded_linear_map` hypothesis. Historical artifact, really. -/ noncomputable theory open_locale classical big_operators topological_space open filter (tendsto) metric variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] /-- A function `f` satisfies `is_bounded_linear_map 𝕜 f` if it is linear and satisfies the inequality `∥f x∥ ≤ M * ∥x∥` for some positive constant `M`. -/ structure is_bounded_linear_map (𝕜 : Type*) [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] (f : E → F) extends is_linear_map 𝕜 f : Prop := (bound : ∃ M, 0 < M ∧ ∀ x : E, ∥f x∥ ≤ M * ∥x∥) lemma is_linear_map.with_bound {f : E → F} (hf : is_linear_map 𝕜 f) (M : ℝ) (h : ∀ x : E, ∥f x∥ ≤ M * ∥x∥) : is_bounded_linear_map 𝕜 f := ⟨ hf, classical.by_cases (assume : M ≤ 0, ⟨1, zero_lt_one, λ x, (h x).trans $ mul_le_mul_of_nonneg_right (this.trans zero_le_one) (norm_nonneg x)⟩) (assume : ¬ M ≤ 0, ⟨M, lt_of_not_ge this, h⟩)⟩ /-- A continuous linear map satisfies `is_bounded_linear_map` -/ lemma continuous_linear_map.is_bounded_linear_map (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 f := { bound := f.bound, ..f.to_linear_map.is_linear } namespace is_bounded_linear_map /-- Construct a linear map from a function `f` satisfying `is_bounded_linear_map 𝕜 f`. -/ def to_linear_map (f : E → F) (h : is_bounded_linear_map 𝕜 f) : E →ₗ[𝕜] F := (is_linear_map.mk' _ h.to_is_linear_map) /-- Construct a continuous linear map from is_bounded_linear_map -/ def to_continuous_linear_map {f : E → F} (hf : is_bounded_linear_map 𝕜 f) : E →L[𝕜] F := { cont := let ⟨C, Cpos, hC⟩ := hf.bound in linear_map.continuous_of_bound _ C hC, ..to_linear_map f hf} lemma zero : is_bounded_linear_map 𝕜 (λ (x:E), (0:F)) := (0 : E →ₗ[𝕜] F).is_linear.with_bound 0 $ by simp [le_refl] lemma id : is_bounded_linear_map 𝕜 (λ (x:E), x) := linear_map.id.is_linear.with_bound 1 $ by simp [le_refl] lemma fst : is_bounded_linear_map 𝕜 (λ x : E × F, x.1) := begin refine (linear_map.fst 𝕜 E F).is_linear.with_bound 1 (λ x, _), rw one_mul, exact le_max_left _ _ end lemma snd : is_bounded_linear_map 𝕜 (λ x : E × F, x.2) := begin refine (linear_map.snd 𝕜 E F).is_linear.with_bound 1 (λ x, _), rw one_mul, exact le_max_right _ _ end variables {f g : E → F} lemma smul (c : 𝕜) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (c • f) := let ⟨hlf, M, hMp, hM⟩ := hf in (c • hlf.mk' f).is_linear.with_bound (∥c∥ * M) $ λ x, calc ∥c • f x∥ = ∥c∥ * ∥f x∥ : norm_smul c (f x) ... ≤ ∥c∥ * (M * ∥x∥) : mul_le_mul_of_nonneg_left (hM _) (norm_nonneg _) ... = (∥c∥ * M) * ∥x∥ : (mul_assoc _ _ _).symm lemma neg (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ e, -f e) := begin rw show (λ e, -f e) = (λ e, (-1 : 𝕜) • f e), { funext, simp }, exact smul (-1) hf end lemma add (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e + g e) := let ⟨hlf, Mf, hMfp, hMf⟩ := hf in let ⟨hlg, Mg, hMgp, hMg⟩ := hg in (hlf.mk' _ + hlg.mk' _).is_linear.with_bound (Mf + Mg) $ λ x, calc ∥f x + g x∥ ≤ Mf * ∥x∥ + Mg * ∥x∥ : norm_add_le_of_le (hMf x) (hMg x) ... ≤ (Mf + Mg) * ∥x∥ : by rw add_mul lemma sub (hf : is_bounded_linear_map 𝕜 f) (hg : is_bounded_linear_map 𝕜 g) : is_bounded_linear_map 𝕜 (λ e, f e - g e) := by simpa [sub_eq_add_neg] using add hf (neg hg) lemma comp {g : F → G} (hg : is_bounded_linear_map 𝕜 g) (hf : is_bounded_linear_map 𝕜 f) : is_bounded_linear_map 𝕜 (g ∘ f) := (hg.to_continuous_linear_map.comp hf.to_continuous_linear_map).is_bounded_linear_map protected lemma tendsto (x : E) (hf : is_bounded_linear_map 𝕜 f) : tendsto f (𝓝 x) (𝓝 (f x)) := let ⟨hf, M, hMp, hM⟩ := hf in tendsto_iff_norm_tendsto_zero.2 $ squeeze_zero (λ e, norm_nonneg _) (λ e, calc ∥f e - f x∥ = ∥hf.mk' f (e - x)∥ : by rw (hf.mk' _).map_sub e x; refl ... ≤ M * ∥e - x∥ : hM (e - x)) (suffices tendsto (λ (e : E), M * ∥e - x∥) (𝓝 x) (𝓝 (M * 0)), by simpa, tendsto_const_nhds.mul (tendsto_norm_sub_self _)) lemma continuous (hf : is_bounded_linear_map 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λ _, hf.tendsto _ lemma lim_zero_bounded_linear_map (hf : is_bounded_linear_map 𝕜 f) : tendsto f (𝓝 0) (𝓝 0) := (hf.1.mk' _).map_zero ▸ continuous_iff_continuous_at.1 hf.continuous 0 section open asymptotics filter theorem is_O_id {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := h.bound in is_O.of_bound _ (mem_of_superset univ_mem (λ x _, hM x)) theorem is_O_comp {E : Type*} {g : F → G} (hg : is_bounded_linear_map 𝕜 g) {f : E → F} (l : filter E) : is_O (λ x', g (f x')) f l := (hg.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub {f : E → F} (h : is_bounded_linear_map 𝕜 f) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := is_O_comp h l end end is_bounded_linear_map section variables {ι : Type*} [decidable_eq ι] [fintype ι] /-- Taking the cartesian product of two continuous multilinear maps is a bounded linear operation. -/ lemma is_bounded_linear_map_prod_multilinear {E : ι → Type*} [∀ i, normed_group (E i)] [∀ i, normed_space 𝕜 (E i)] : is_bounded_linear_map 𝕜 (λ p : (continuous_multilinear_map 𝕜 E F) × (continuous_multilinear_map 𝕜 E G), p.1.prod p.2) := { map_add := λ p₁ p₂, by { ext1 m, refl }, map_smul := λ c p, by { ext1 m, refl }, bound := ⟨1, zero_lt_one, λ p, begin rw one_mul, apply continuous_multilinear_map.op_norm_le_bound _ (norm_nonneg _) (λ m, _), rw [continuous_multilinear_map.prod_apply, norm_prod_le_iff], split, { exact (p.1.le_op_norm m).trans (mul_le_mul_of_nonneg_right (norm_fst_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) }, { exact (p.2.le_op_norm m).trans (mul_le_mul_of_nonneg_right (norm_snd_le p) (finset.prod_nonneg (λ i hi, norm_nonneg _))) }, end⟩ } /-- Given a fixed continuous linear map `g`, associating to a continuous multilinear map `f` the continuous multilinear map `f (g m₁, ..., g mₙ)` is a bounded linear operation. -/ lemma is_bounded_linear_map_continuous_multilinear_map_comp_linear (g : G →L[𝕜] E) : is_bounded_linear_map 𝕜 (λ f : continuous_multilinear_map 𝕜 (λ (i : ι), E) F, f.comp_continuous_linear_map (λ _, g)) := begin refine is_linear_map.with_bound ⟨λ f₁ f₂, by { ext m, refl }, λ c f, by { ext m, refl }⟩ (∥g∥ ^ (fintype.card ι)) (λ f, _), apply continuous_multilinear_map.op_norm_le_bound _ _ (λ m, _), { apply_rules [mul_nonneg, pow_nonneg, norm_nonneg] }, calc ∥f (g ∘ m)∥ ≤ ∥f∥ * ∏ i, ∥g (m i)∥ : f.le_op_norm _ ... ≤ ∥f∥ * ∏ i, (∥g∥ * ∥m i∥) : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), exact finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, g.le_op_norm _) end ... = ∥g∥ ^ fintype.card ι * ∥f∥ * ∏ i, ∥m i∥ : by { simp [finset.prod_mul_distrib, finset.card_univ], ring } end end section bilinear_map variable (𝕜) /-- A map `f : E × F → G` satisfies `is_bounded_bilinear_map 𝕜 f` if it is bilinear and continuous. -/ structure is_bounded_bilinear_map (f : E × F → G) : Prop := (add_left : ∀ (x₁ x₂ : E) (y : F), f (x₁ + x₂, y) = f (x₁, y) + f (x₂, y)) (smul_left : ∀ (c : 𝕜) (x : E) (y : F), f (c • x, y) = c • f (x, y)) (add_right : ∀ (x : E) (y₁ y₂ : F), f (x, y₁ + y₂) = f (x, y₁) + f (x, y₂)) (smul_right : ∀ (c : 𝕜) (x : E) (y : F), f (x, c • y) = c • f (x,y)) (bound : ∃ C > 0, ∀ (x : E) (y : F), ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥) variable {𝕜} variable {f : E × F → G} lemma continuous_linear_map.is_bounded_bilinear_map (f : E →L[𝕜] F →L[𝕜] G) : is_bounded_bilinear_map 𝕜 (λ x : E × F, f x.1 x.2) := { add_left := λ x₁ x₂ y, by rw [f.map_add, continuous_linear_map.add_apply], smul_left := λ c x y, by rw [f.map_smul _, continuous_linear_map.smul_apply], add_right := λ x, (f x).map_add, smul_right := λ c x y, (f x).map_smul c y, bound := ⟨max ∥f∥ 1, zero_lt_one.trans_le (le_max_right _ _), λ x y, (f.le_op_norm₂ x y).trans $ by apply_rules [mul_le_mul_of_nonneg_right, norm_nonneg, le_max_left]⟩ } protected lemma is_bounded_bilinear_map.is_O (h : is_bounded_bilinear_map 𝕜 f) : asymptotics.is_O f (λ p : E × F, ∥p.1∥ * ∥p.2∥) ⊤ := let ⟨C, Cpos, hC⟩ := h.bound in asymptotics.is_O.of_bound _ $ filter.eventually_of_forall $ λ ⟨x, y⟩, by simpa [mul_assoc] using hC x y lemma is_bounded_bilinear_map.is_O_comp {α : Type*} (H : is_bounded_bilinear_map 𝕜 f) {g : α → E} {h : α → F} {l : filter α} : asymptotics.is_O (λ x, f (g x, h x)) (λ x, ∥g x∥ * ∥h x∥) l := H.is_O.comp_tendsto le_top protected lemma is_bounded_bilinear_map.is_O' (h : is_bounded_bilinear_map 𝕜 f) : asymptotics.is_O f (λ p : E × F, ∥p∥ * ∥p∥) ⊤ := h.is_O.trans (asymptotics.is_O_fst_prod'.norm_norm.mul asymptotics.is_O_snd_prod'.norm_norm) lemma is_bounded_bilinear_map.map_sub_left (h : is_bounded_bilinear_map 𝕜 f) {x y : E} {z : F} : f (x - y, z) = f (x, z) - f(y, z) := calc f (x - y, z) = f (x + (-1 : 𝕜) • y, z) : by simp [sub_eq_add_neg] ... = f (x, z) + (-1 : 𝕜) • f (y, z) : by simp only [h.add_left, h.smul_left] ... = f (x, z) - f (y, z) : by simp [sub_eq_add_neg] lemma is_bounded_bilinear_map.map_sub_right (h : is_bounded_bilinear_map 𝕜 f) {x : E} {y z : F} : f (x, y - z) = f (x, y) - f (x, z) := calc f (x, y - z) = f (x, y + (-1 : 𝕜) • z) : by simp [sub_eq_add_neg] ... = f (x, y) + (-1 : 𝕜) • f (x, z) : by simp only [h.add_right, h.smul_right] ... = f (x, y) - f (x, z) : by simp [sub_eq_add_neg] lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 f) : continuous f := begin have one_ne : (1:ℝ) ≠ 0 := by simp, obtain ⟨C, (Cpos : 0 < C), hC⟩ := h.bound, rw continuous_iff_continuous_at, intros x, have H : ∀ (a:E) (b:F), ∥f (a, b)∥ ≤ C * ∥∥a∥ * ∥b∥∥, { intros a b, simpa [mul_assoc] using hC a b }, have h₁ : asymptotics.is_o (λ e : E × F, f (e.1 - x.1, e.2)) (λ e, (1:ℝ)) (𝓝 x), { refine (asymptotics.is_O_of_le' (𝓝 x) (λ e, H (e.1 - x.1) e.2)).trans_is_o _, rw asymptotics.is_o_const_iff one_ne, convert ((continuous_fst.sub continuous_const).norm.mul continuous_snd.norm).continuous_at, { simp }, apply_instance }, have h₂ : asymptotics.is_o (λ e : E × F, f (x.1, e.2 - x.2)) (λ e, (1:ℝ)) (𝓝 x), { refine (asymptotics.is_O_of_le' (𝓝 x) (λ e, H x.1 (e.2 - x.2))).trans_is_o _, rw asymptotics.is_o_const_iff one_ne, convert (continuous_const.mul (continuous_snd.sub continuous_const).norm).continuous_at, { simp }, apply_instance }, have := h₁.add h₂, rw asymptotics.is_o_const_iff one_ne at this, change tendsto _ _ _, convert this.add_const (f x), { ext e, simp [h.map_sub_left, h.map_sub_right], }, { simp } end lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 f) {e₂ : F} : continuous (λe₁, f (e₁, e₂)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 f) {e₁ : E} : continuous (λe₂, f (e₁, e₂)) := h.continuous.comp (continuous_const.prod_mk continuous_id) lemma is_bounded_bilinear_map.is_bounded_linear_map_left (h : is_bounded_bilinear_map 𝕜 f) (y : F) : is_bounded_linear_map 𝕜 (λ x, f (x, y)) := { map_add := λ x x', h.add_left _ _ _, map_smul := λ c x, h.smul_left _ _ _, bound := begin rcases h.bound with ⟨C, C_pos, hC⟩, refine ⟨C * (∥y∥ + 1), mul_pos C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ x, _⟩, have : ∥y∥ ≤ ∥y∥ + 1, by simp [zero_le_one], calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y ... ≤ C * ∥x∥ * (∥y∥ + 1) : by apply_rules [norm_nonneg, mul_le_mul_of_nonneg_left, le_of_lt C_pos, mul_nonneg] ... = C * (∥y∥ + 1) * ∥x∥ : by ring end } lemma is_bounded_bilinear_map.is_bounded_linear_map_right (h : is_bounded_bilinear_map 𝕜 f) (x : E) : is_bounded_linear_map 𝕜 (λ y, f (x, y)) := { map_add := λ y y', h.add_right _ _ _, map_smul := λ c y, h.smul_right _ _ _, bound := begin rcases h.bound with ⟨C, C_pos, hC⟩, refine ⟨C * (∥x∥ + 1), mul_pos C_pos (lt_of_lt_of_le (zero_lt_one) (by simp)), λ y, _⟩, have : ∥x∥ ≤ ∥x∥ + 1, by simp [zero_le_one], calc ∥f (x, y)∥ ≤ C * ∥x∥ * ∥y∥ : hC x y ... ≤ C * (∥x∥ + 1) * ∥y∥ : by apply_rules [mul_le_mul_of_nonneg_right, norm_nonneg, mul_le_mul_of_nonneg_left, le_of_lt C_pos] end } lemma is_bounded_bilinear_map_smul {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜 E] [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜' × E), p.1 • p.2) := { add_left := add_smul, smul_left := λ c x y, by simp [smul_assoc], add_right := smul_add, smul_right := λ c x y, by simp [smul_assoc, smul_algebra_smul_comm], bound := ⟨1, zero_lt_one, λ x y, by simp [norm_smul] ⟩ } lemma is_bounded_bilinear_map_mul : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := by simp_rw ← smul_eq_mul; exact is_bounded_bilinear_map_smul lemma is_bounded_bilinear_map_comp : is_bounded_bilinear_map 𝕜 (λ (p : (E →L[𝕜] F) × (F →L[𝕜] G)), p.2.comp p.1) := { add_left := λ x₁ x₂ y, begin ext z, change y (x₁ z + x₂ z) = y (x₁ z) + y (x₂ z), rw y.map_add end, smul_left := λ c x y, begin ext z, change y (c • (x z)) = c • y (x z), rw continuous_linear_map.map_smul end, add_right := λ x y₁ y₂, rfl, smul_right := λ c x y, rfl, bound := ⟨1, zero_lt_one, λ x y, calc ∥continuous_linear_map.comp ((x, y).snd) ((x, y).fst)∥ ≤ ∥y∥ * ∥x∥ : continuous_linear_map.op_norm_comp_le _ _ ... = 1 * ∥x∥ * ∥ y∥ : by ring ⟩ } lemma continuous_linear_map.is_bounded_linear_map_comp_left (g : F →L[𝕜] G) : is_bounded_linear_map 𝕜 (λ (f : E →L[𝕜] F), continuous_linear_map.comp g f) := is_bounded_bilinear_map_comp.is_bounded_linear_map_left _ lemma continuous_linear_map.is_bounded_linear_map_comp_right (f : E →L[𝕜] F) : is_bounded_linear_map 𝕜 (λ (g : F →L[𝕜] G), continuous_linear_map.comp g f) := is_bounded_bilinear_map_comp.is_bounded_linear_map_right _ lemma is_bounded_bilinear_map_apply : is_bounded_bilinear_map 𝕜 (λ p : (E →L[𝕜] F) × E, p.1 p.2) := { add_left := by simp, smul_left := by simp, add_right := by simp, smul_right := by simp, bound := ⟨1, zero_lt_one, by simp [continuous_linear_map.le_op_norm]⟩ } /-- The function `continuous_linear_map.smul_right`, associating to a continuous linear map `f : E → 𝕜` and a scalar `c : F` the tensor product `f ⊗ c` as a continuous linear map from `E` to `F`, is a bounded bilinear map. -/ lemma is_bounded_bilinear_map_smul_right : is_bounded_bilinear_map 𝕜 (λ p, (continuous_linear_map.smul_right : (E →L[𝕜] 𝕜) → F → (E →L[𝕜] F)) p.1 p.2) := { add_left := λ m₁ m₂ f, by { ext z, simp [add_smul] }, smul_left := λ c m f, by { ext z, simp [mul_smul] }, add_right := λ m f₁ f₂, by { ext z, simp [smul_add] }, smul_right := λ c m f, by { ext z, simp [smul_smul, mul_comm] }, bound := ⟨1, zero_lt_one, λ m f, by simp⟩ } /-- The composition of a continuous linear map with a continuous multilinear map is a bounded bilinear operation. -/ lemma is_bounded_bilinear_map_comp_multilinear {ι : Type*} {E : ι → Type*} [decidable_eq ι] [fintype ι] [∀ i, normed_group (E i)] [∀ i, normed_space 𝕜 (E i)] : is_bounded_bilinear_map 𝕜 (λ p : (F →L[𝕜] G) × (continuous_multilinear_map 𝕜 E F), p.1.comp_continuous_multilinear_map p.2) := { add_left := λ g₁ g₂ f, by { ext m, refl }, smul_left := λ c g f, by { ext m, refl }, add_right := λ g f₁ f₂, by { ext m, simp }, smul_right := λ c g f, by { ext m, simp }, bound := ⟨1, zero_lt_one, λ g f, begin apply continuous_multilinear_map.op_norm_le_bound _ _ (λ m, _), { apply_rules [mul_nonneg, zero_le_one, norm_nonneg] }, calc ∥g (f m)∥ ≤ ∥g∥ * ∥f m∥ : g.le_op_norm _ ... ≤ ∥g∥ * (∥f∥ * ∏ i, ∥m i∥) : mul_le_mul_of_nonneg_left (f.le_op_norm _) (norm_nonneg _) ... = 1 * ∥g∥ * ∥f∥ * ∏ i, ∥m i∥ : by ring end⟩ } /-- Definition of the derivative of a bilinear map `f`, given at a point `p` by `q ↦ f(p.1, q.2) + f(q.1, p.2)` as in the standard formula for the derivative of a product. We define this function here as a linear map `E × F →ₗ[𝕜] G`, then `is_bounded_bilinear_map.deriv` strengthens it to a continuous linear map `E × F →L[𝕜] G`. ``. -/ def is_bounded_bilinear_map.linear_deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : E × F →ₗ[𝕜] G := { to_fun := λ q, f (p.1, q.2) + f (q.1, p.2), map_add' := λ q₁ q₂, begin change f (p.1, q₁.2 + q₂.2) + f (q₁.1 + q₂.1, p.2) = f (p.1, q₁.2) + f (q₁.1, p.2) + (f (p.1, q₂.2) + f (q₂.1, p.2)), simp [h.add_left, h.add_right], abel end, map_smul' := λ c q, begin change f (p.1, c • q.2) + f (c • q.1, p.2) = c • (f (p.1, q.2) + f (q.1, p.2)), simp [h.smul_left, h.smul_right, smul_add] end } /-- The derivative of a bounded bilinear map at a point `p : E × F`, as a continuous linear map from `E × F` to `G`. The statement that this is indeed the derivative of `f` is `is_bounded_bilinear_map.has_fderiv_at` in `analysis.calculus.fderiv`. -/ def is_bounded_bilinear_map.deriv (h : is_bounded_bilinear_map 𝕜 f) (p : E × F) : E × F →L[𝕜] G := (h.linear_deriv p).mk_continuous_of_exists_bound $ begin rcases h.bound with ⟨C, Cpos, hC⟩, refine ⟨C * ∥p.1∥ + C * ∥p.2∥, λ q, _⟩, calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _) ... ≤ C * ∥p.1∥ * ∥q∥ + C * ∥q∥ * ∥p.2∥ : begin apply add_le_add, exact mul_le_mul_of_nonneg_left (le_max_right _ _) (mul_nonneg (le_of_lt Cpos) (norm_nonneg _)), apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), exact mul_le_mul_of_nonneg_left (le_max_left _ _) (le_of_lt Cpos), end ... = (C * ∥p.1∥ + C * ∥p.2∥) * ∥q∥ : by ring end @[simp] lemma is_bounded_bilinear_map_deriv_coe (h : is_bounded_bilinear_map 𝕜 f) (p q : E × F) : h.deriv p q = f (p.1, q.2) + f (q.1, p.2) := rfl variables (𝕜) /-- The function `lmul_left_right : 𝕜' × 𝕜' → (𝕜' →L[𝕜] 𝕜')` is a bounded bilinear map. -/ lemma continuous_linear_map.lmul_left_right_is_bounded_bilinear (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : is_bounded_bilinear_map 𝕜 (λ p : 𝕜' × 𝕜', continuous_linear_map.lmul_left_right 𝕜 𝕜' p.1 p.2) := (continuous_linear_map.lmul_left_right 𝕜 𝕜').is_bounded_bilinear_map variables {𝕜} /-- Given a bounded bilinear map `f`, the map associating to a point `p` the derivative of `f` at `p` is itself a bounded linear map. -/ lemma is_bounded_bilinear_map.is_bounded_linear_map_deriv (h : is_bounded_bilinear_map 𝕜 f) : is_bounded_linear_map 𝕜 (λ p : E × F, h.deriv p) := begin rcases h.bound with ⟨C, Cpos : 0 < C, hC⟩, refine is_linear_map.with_bound ⟨λ p₁ p₂, _, λ c p, _⟩ (C + C) (λ p, _), { ext; simp [h.add_left, h.add_right]; abel }, { ext; simp [h.smul_left, h.smul_right, smul_add] }, { refine continuous_linear_map.op_norm_le_bound _ (mul_nonneg (add_nonneg Cpos.le Cpos.le) (norm_nonneg _)) (λ q, _), calc ∥f (p.1, q.2) + f (q.1, p.2)∥ ≤ C * ∥p.1∥ * ∥q.2∥ + C * ∥q.1∥ * ∥p.2∥ : norm_add_le_of_le (hC _ _) (hC _ _) ... ≤ C * ∥p∥ * ∥q∥ + C * ∥q∥ * ∥p∥ : by apply_rules [add_le_add, mul_le_mul, norm_nonneg, Cpos.le, le_refl, le_max_left, le_max_right, mul_nonneg] ... = (C + C) * ∥p∥ * ∥q∥ : by ring }, end end bilinear_map /-- A linear isometry preserves the norm. -/ lemma linear_map.norm_apply_of_isometry (f : E →ₗ[𝕜] F) {x : E} (hf : isometry f) : ∥f x∥ = ∥x∥ := by { simp_rw [←dist_zero_right, ←f.map_zero], exact isometry.dist_eq hf _ _ } /-- Construct a continuous linear equiv from a linear map that is also an isometry with full range. -/ def continuous_linear_equiv.of_isometry (f : E →ₗ[𝕜] F) (hf : isometry f) (hfr : f.range = ⊤) : E ≃L[𝕜] F := continuous_linear_equiv.of_homothety (linear_equiv.of_bijective f (isometry.injective hf) (linear_map.range_eq_top.mp hfr)) 1 zero_lt_one (λ _, by simp [one_mul, f.norm_apply_of_isometry hf]) namespace continuous_linear_equiv open set /-! ### The set of continuous linear equivalences between two Banach spaces is open In this section we establish that the set of continuous linear equivalences between two Banach spaces is an open subset of the space of linear maps between them. -/ protected lemma is_open [complete_space E] : is_open (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) := begin nontriviality E, rw [is_open_iff_mem_nhds, forall_range_iff], refine λ e, is_open.mem_nhds _ (mem_range_self _), let O : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : F →L[𝕜] E).comp f, have h_O : continuous O := is_bounded_bilinear_map_comp.continuous_left, convert units.is_open.preimage h_O using 1, ext f', split, { rintros ⟨e', rfl⟩, exact ⟨(e'.trans e.symm).to_unit, rfl⟩ }, { rintros ⟨w, hw⟩, use (units_equiv 𝕜 E w).trans e, ext x, simp [hw] } end protected lemma nhds [complete_space E] (e : E ≃L[𝕜] F) : (range (coe : (E ≃L[𝕜] F) → (E →L[𝕜] F))) ∈ 𝓝 (e : E →L[𝕜] F) := is_open.mem_nhds continuous_linear_equiv.is_open (by simp) end continuous_linear_equiv
a7ee846c526d2549284f6e2234cdb157730f3686
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/arrow.lean
5b7d246712a6188933f220dd683a5ccc085dbe22
[ "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
130
lean
import Int. print (Int -> Int) -> Int print Int -> Int -> Int print Int -> (Int -> Int) print (Int -> Int) -> (Int -> Int) -> Int
821cb5bd8ed62850ac628d0b6f53541ac0ed1bad
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/implicitTypesRecCoe.lean
b24ad0cce69eca6de559efdd75720521f352c50e
[ "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,215
lean
unsafe def f (n : Nat) := let rec g (x : Nat) := if x > 0 then /- This example relies on the instance `coeId {α} (a : α) : CoeT α a α`, The type of `g` is not provided. Thus, the expected type is `?m x` since the elaborator assumes it may depend on `x`. Thus, the expected type for the addition is `?m x`. The type of `g (x-1)` is `?m (x-1)`. So, we have the unification problem ``` ?m (x-1) =?= ?m x ``` and it is rejected by the unifier. Thus, the elaborator inserts a coercion from `?m (x-1)` to `?m x` around `g (x-1)` which creates the pending TC problem: ``` CoeT (?m (x-1)) (g (x-1)) (?m x) ``` Remark: in principle, we could solve it using a heuristic: assume `?m` is a constant function. Later, when we elaborate the else branch `0`, we have that ``` ?m x =?= Nat ``` which is solved using `?m := (fun _ => Nat)`. Then, `@coeId Nat (g (x-1))` is used to synthesize ``` CoeT (?m (x-1)) (g (x-1)) (?m x) ``` which is ``` CoeT Nat (g (x-1)) Nat ``` after we apply the assignment `?m := (fun _ => Nat)` -/ g (x-1) + n else 0; g n #eval f 10
212018587dcf5435cbe59e382a99816086a398f3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/polynomial/div.lean
76cb1fda0b61071a5de73b4fb51068204eacaabf
[ "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
25,839
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.monic import ring_theory.euclidean_domain import ring_theory.multiplicity /-! # Division of univariate polynomials The main defs are `div_by_monic` and `mod_by_monic`. The compatibility between these is given by `mod_by_monic_add_div`. We also define `root_multiplicity`. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section semiring variables [semiring R] {p q : polynomial R} section /-- The coercion turning a `polynomial` into the function which reports the coefficient of a given monomial `X^n` -/ -- TODO we would like to completely remove this, but this requires fixing some proofs def coeff_coe_to_fun : has_coe_to_fun (polynomial R) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun lemma apply_eq_coeff : p n = coeff p n := rfl end /-- `div_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : polynomial R) : polynomial R := { to_fun := λ n, p.coeff (n + 1), support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1), multiset.nodup_map_on begin simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter], assume x hx y hy hxy, rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2, nat.sub_add_cancel hy.2] at hxy end (p.support.filter (> 0)).2⟩, mem_support_to_fun := λ n, suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔ ¬coeff p (n + 1) = 0, by simpa [finset.mem_def.symm], ⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1, λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ } lemma div_X_mul_X_add (p : polynomial R) : div_X p * X + C (p.coeff 0) = p := ext $ λ n, nat.cases_on n (by simp) (by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X]) @[simp] lemma div_X_C (a : R) : div_X (C a) = 0 := ext $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := ext $ by simp [div_X] lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by haveI := nontrivial.of_polynomial_ne hp0; calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : polynomial R) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul' this]; exact add_le_add (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [add_comm, degree_add_eq_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : by rw div_X_mul_X_add /-- An induction principle for polynomials, valued in Sort* instead of Prop. -/ @[elab_as_eliminator] noncomputable def rec_on_horner {M : polynomial R → Sort*} : Π (p : polynomial R), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial R → Prop} (p : polynomial R) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, nat.not_lt_zero] using h0')) h0 end semiring section comm_semiring variables [comm_semiring R] theorem X_dvd_iff {α : Type u} [comm_semiring α] {f : polynomial α} : X ∣ f ↔ f.coeff 0 = 0 := ⟨λ ⟨g, hfg⟩, by rw [hfg, mul_comm, coeff_mul_X_zero], λ hf, ⟨f.div_X, by rw [mul_comm, ← add_zero (f.div_X * X), ← C_0, ← hf, div_X_mul_X_add]⟩⟩ end comm_semiring section comm_semiring variables [comm_semiring R] {p q : polynomial R} lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : R) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hpn0 : p ^ (nat_degree q + 1) ≠ 0, from mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul' hpnr0, nat_degree_pow' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section ring variables [ring R] {p q : polynomial R} lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := hq.ne_zero_of_polynomial_ne h.2, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul' hpq, degree_C_mul_X_pow _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) /-- See `div_by_monic`. -/ noncomputable def div_mod_by_monic_aux : Π (p : polynomial R) {q : polynomial R}, monic q → polynomial R × polynomial R | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} @[simp] lemma zero_mod_by_monic (p : polynomial R) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial R) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial R) : p %ₘ 0 = p := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial R) : p /ₘ 0 = 0 := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ theorem degree_mod_by_monic_le (p : polynomial R) {q : polynomial R} (hq : monic q) : degree (p %ₘ q) ≤ degree q := decidable.by_cases (assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq; have : (0:polynomial R) = 1 := (by rw [← C_0, ← C_1, hq]); exact le_of_eq (congr_arg _ $ eq_of_zero_eq_one this (p %ₘ q) q)) (assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H) end ring section comm_ring variables [comm_ring R] {p q : polynomial R} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial R) {q : polynomial R} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial R), p = 0, from λ p, (@subsingleton_of_monic_zero R _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial R) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then have hq0 : q ≠ 0 := hq.ne_zero_of_polynomial_ne hp0, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial R) {q : polynomial R} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := hq.ne_zero_of_polynomial_ne hp0, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end theorem nat_degree_div_by_monic {R : Type u} [comm_ring R] (f : polynomial R) {g : polynomial R} (hg : g.monic) : nat_degree (f /ₘ g) = nat_degree f - nat_degree g := begin by_cases h01 : (0 : R) = 1, { haveI := subsingleton_of_zero_eq_one h01, rw [subsingleton.elim (f /ₘ g) 0, subsingleton.elim f 0, subsingleton.elim g 0, nat_degree_zero] }, haveI : nontrivial R := ⟨⟨0, 1, h01⟩⟩, by_cases hfg : f /ₘ g = 0, { rw [hfg, nat_degree_zero], rw div_by_monic_eq_zero_iff hg hg.ne_zero at hfg, rw nat.sub_eq_zero_of_le (nat_degree_le_nat_degree $ le_of_lt hfg) }, have hgf := hfg, rw div_by_monic_eq_zero_iff hg hg.ne_zero at hgf, push_neg at hgf, have := degree_add_div_by_monic hg hgf, have hf : f ≠ 0, { intro hf, apply hfg, rw [hf, zero_div_by_monic] }, rw [degree_eq_nat_degree hf, degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hfg, ← with_bot.coe_add, with_bot.coe_eq_coe] at this, rw [← this, nat.add_sub_cancel_left] end lemma div_mod_by_monic_unique {f g} (q r : polynomial R) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero (hg0 ▸ hg : monic (0 : polynomial R))).1 _ _ else have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) : degree_add_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul']; simpa [monic.def.1 hg]), ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := if h01 : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one h01; exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩ else have h01R : (0 : R) ≠ 1, from mt (congr_arg f) (by rwa [f.map_one, f.map_zero]), have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ ... < degree q : degree_mod_by_monic_lt _ hq $ (hq.ne_zero_of_ne h01R) ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, f.map_one]; exact ne.symm h01)⟩), ⟨this.1.symm, this.2.symm⟩ lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ theorem map_dvd_map [comm_ring S] (f : R →+* S) (hf : function.injective f) {x y : polynomial R} (hx : x.monic) : x.map f ∣ y.map f ↔ x ∣ y := begin rw [← dvd_iff_mod_by_monic_eq_zero hx, ← dvd_iff_mod_by_monic_eq_zero (monic_map f hx), ← map_mod_by_monic f hx], exact ⟨λ H, map_injective f hf $ by rw [H, map_zero], λ H, by rw [H, map_zero]⟩ end @[simp] lemma mod_by_monic_one (p : polynomial R) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero (by convert monic_one)).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial R) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p %ₘ (X - C a) = C (p.eval a) := if h0 : (0 : R) = 1 then by letI := subsingleton_of_zero_eq_one h0; exact subsingleton.elim _ _ else by haveI : nontrivial R := nontrivial_of_ne 0 1 h0; exact have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial R) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] section multiplicity /-- An algorithm for deciding polynomial divisibility. The algorithm is "compute `p %ₘ q` and compare to `0`". ` See `polynomial.mod_by_monic` for the algorithm that computes `%ₘ`. -/ def decidable_dvd_monic (p : polynomial R) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) open_locale classical lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : R) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one h; exact h0 (subsingleton.elim _ _)), by haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 /-- The largest power of `X - C a` which divides `p`. This is computable via the divisibility algorithm `decidable_dvd_monic`. -/ def root_multiplicity (a : R) (p : polynomial R) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial R) (a : R) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, roption.dom]; congr; funext; congr lemma pow_root_multiplicity_dvd (p : polynomial R) (a : R) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial R) (a : R) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial R} (a : R) (hp : p ≠ 0) : eval a (p /ₘ ((X - C a) ^ root_multiplicity a p)) ≠ 0 := begin haveI : nontrivial R := nontrivial.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring end polynomial
2daa256990bed640032ab693fcf1e0c8fc521268
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/star/pointwise.lean
4885c23b117cb9d45397c4babcf2019b703c0869
[ "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
4,381
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.star.basic import data.set.finite import data.set.pointwise.basic /-! # Pointwise star operation on sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the star operation pointwise on sets and provides the basic API. Besides basic facts about about how the star operation acts on sets (e.g., `(s ∩ t)⋆ = s⋆ ∩ t⋆`), if `s t : set α`, then under suitable assumption on `α`, it is shown * `(s + t)⋆ = s⋆ + t⋆` * `(s * t)⋆ = t⋆ + s⋆` * `(s⁻¹)⋆ = (s⋆)⁻¹` -/ namespace set open_locale pointwise local postfix `⋆`:std.prec.max_plus := star variables {α : Type*} {s t : set α} {a : α} /-- The set `(star s : set α)` is defined as `{x | star x ∈ s}` in locale `pointwise`. In the usual case where `star` is involutive, it is equal to `{star s | x ∈ s}`, see `set.image_star`. -/ protected def has_star [has_star α] : has_star (set α) := ⟨preimage has_star.star⟩ localized "attribute [instance] set.has_star" in pointwise @[simp] lemma star_empty [has_star α] : (∅ : set α)⋆ = ∅ := rfl @[simp] lemma star_univ [has_star α] : (univ : set α)⋆ = univ := rfl @[simp] lemma nonempty_star [has_involutive_star α] {s : set α} : (s⋆).nonempty ↔ s.nonempty := star_involutive.surjective.nonempty_preimage lemma nonempty.star [has_involutive_star α] {s : set α} (h : s.nonempty) : (s⋆).nonempty := nonempty_star.2 h @[simp] lemma mem_star [has_star α] : a ∈ s⋆ ↔ a⋆ ∈ s := iff.rfl lemma star_mem_star [has_involutive_star α] : a⋆ ∈ s⋆ ↔ a ∈ s := by simp only [mem_star, star_star] @[simp] lemma star_preimage [has_star α] : has_star.star ⁻¹' s = s⋆ := rfl @[simp] lemma image_star [has_involutive_star α] : has_star.star '' s = s⋆ := by { simp only [← star_preimage], rw [image_eq_preimage_of_inverse]; intro; simp only [star_star] } @[simp] lemma inter_star [has_star α] : (s ∩ t)⋆ = s⋆ ∩ t⋆ := preimage_inter @[simp] lemma union_star [has_star α] : (s ∪ t)⋆ = s⋆ ∪ t⋆ := preimage_union @[simp] lemma Inter_star {ι : Sort*} [has_star α] (s : ι → set α) : (⋂ i, s i)⋆ = ⋂ i, (s i)⋆ := preimage_Inter @[simp] lemma Union_star {ι : Sort*} [has_star α] (s : ι → set α) : (⋃ i, s i)⋆ = ⋃ i, (s i)⋆ := preimage_Union @[simp] lemma compl_star [has_star α] : (sᶜ)⋆ = (s⋆)ᶜ := preimage_compl @[simp] instance [has_involutive_star α] : has_involutive_star (set α) := { star := has_star.star, star_involutive := λ s, by { simp only [← star_preimage, preimage_preimage, star_star, preimage_id'] } } @[simp] lemma star_subset_star [has_involutive_star α] {s t : set α} : s⋆ ⊆ t⋆ ↔ s ⊆ t := equiv.star.surjective.preimage_subset_preimage_iff lemma star_subset [has_involutive_star α] {s t : set α} : s⋆ ⊆ t ↔ s ⊆ t⋆ := by { rw [← star_subset_star, star_star] } lemma finite.star [has_involutive_star α] {s : set α} (hs : s.finite) : s⋆.finite := hs.preimage $ star_injective.inj_on _ lemma star_singleton {β : Type*} [has_involutive_star β] (x : β) : ({x} : set β)⋆ = {x⋆} := by { ext1 y, rw [mem_star, mem_singleton_iff, mem_singleton_iff, star_eq_iff_star_eq, eq_comm], } protected lemma star_mul [monoid α] [star_semigroup α] (s t : set α) : (s * t)⋆ = t⋆ * s⋆ := by simp_rw [←image_star, ←image2_mul, image_image2, image2_image_left, image2_image_right, star_mul, image2_swap _ s t] protected lemma star_add [add_monoid α] [star_add_monoid α] (s t : set α) : (s + t)⋆ = s⋆ + t⋆ := by simp_rw [←image_star, ←image2_add, image_image2, image2_image_left, image2_image_right, star_add] @[simp] instance [has_star α] [has_trivial_star α] : has_trivial_star (set α) := { star_trivial := λ s, by { rw [←star_preimage], ext1, simp [star_trivial] } } protected lemma star_inv [group α] [star_semigroup α] (s : set α) : (s⁻¹)⋆ = (s⋆)⁻¹ := by { ext, simp only [mem_star, mem_inv, star_inv] } protected lemma star_inv' [division_semiring α] [star_ring α] (s : set α) : (s⁻¹)⋆ = (s⋆)⁻¹ := by { ext, simp only [mem_star, mem_inv, star_inv'] } end set
3a856ad7f5785e13640948def52b93010dc72fa6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finset/prod.lean
9bca2f43adcf705812e4653b9cf2e3d9c15ab4f1
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
12,988
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Oliver Nash -/ import data.finset.card /-! # Finsets in product types This file defines finset constructions on the product type `α × β`. Beware not to confuse with the `finset.prod` operation which computes the multiplicative product. ## Main declarations * `finset.product`: Turns `s : finset α`, `t : finset β` into their product in `finset (α × β)`. * `finset.diag`: For `s : finset α`, `s.diag` is the `finset (α × α)` of pairs `(a, a)` with `a ∈ s`. * `finset.off_diag`: For `s : finset α`, `s.off_diag` is the `finset (α × α)` of pairs `(a, b)` with `a, b ∈ s` and `a ≠ b`. -/ open multiset variables {α β γ : Type*} namespace finset /-! ### prod -/ section prod variables {s s' : finset α} {t t' : finset β} {a : α} {b : β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, s.nodup.product t.nodup⟩ /- This notation binds more strongly than (pre)images, unions and intersections. -/ infixr (name := finset.product) ` ×ˢ `:82 := finset.product @[simp] lemma product_val : (s ×ˢ t).1 = s.1 ×ˢ t.1 := rfl @[simp] lemma mem_product {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product lemma mk_mem_product (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := mem_product.2 ⟨ha, hb⟩ @[simp, norm_cast] lemma coe_product (s : finset α) (t : finset β) : (↑(s ×ˢ t) : set (α × β)) = s ×ˢ t := set.ext $ λ x, finset.mem_product lemma subset_product_image_fst [decidable_eq α] : (s ×ˢ t).image prod.fst ⊆ s := λ i, by simp [mem_image] {contextual := tt} lemma subset_product_image_snd [decidable_eq β] : (s ×ˢ t).image prod.snd ⊆ t := λ i, by simp [mem_image] {contextual := tt} lemma product_image_fst [decidable_eq α] (ht : t.nonempty) : (s ×ˢ t).image prod.fst = s := by { ext i, simp [mem_image, ht.bex] } lemma product_image_snd [decidable_eq β] (ht : s.nonempty) : (s ×ˢ t).image prod.snd = t := by { ext i, simp [mem_image, ht.bex] } lemma subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} : s ⊆ s.image prod.fst ×ˢ s.image prod.snd := λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩ lemma product_subset_product (hs : s ⊆ s') (ht : t ⊆ t') : s ×ˢ t ⊆ s' ×ˢ t' := λ ⟨x,y⟩ h, mem_product.2 ⟨hs (mem_product.1 h).1, ht (mem_product.1 h).2⟩ lemma product_subset_product_left (hs : s ⊆ s') : s ×ˢ t ⊆ s' ×ˢ t := product_subset_product hs (subset.refl _) lemma product_subset_product_right (ht : t ⊆ t') : s ×ˢ t ⊆ s ×ˢ t' := product_subset_product (subset.refl _) ht lemma map_swap_product (s : finset α) (t : finset β) : (t ×ˢ s).map ⟨prod.swap, prod.swap_injective⟩ = s ×ˢ t := coe_injective $ by { push_cast, exact set.image_swap_prod _ _ } @[simp] lemma image_swap_product [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : (t ×ˢ s).image prod.swap = s ×ˢ t := coe_injective $ by { push_cast, exact set.image_swap_prod _ _ } lemma product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s ×ˢ t = s.bUnion (λa, t.image $ λb, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] lemma product_eq_bUnion_right [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s ×ˢ t = t.bUnion (λ b, s.image $ λ a, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] /-- See also `finset.sup_product_left`. -/ @[simp] lemma product_bUnion [decidable_eq γ] (s : finset α) (t : finset β) (f : α × β → finset γ) : (s ×ˢ t).bUnion f = s.bUnion (λ a, t.bUnion (λ b, f (a, b))) := by { classical, simp_rw [product_eq_bUnion, bUnion_bUnion, image_bUnion] } @[simp] lemma card_product (s : finset α) (t : finset β) : card (s ×ˢ t) = card s * card t := multiset.card_product _ _ lemma filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : (s ×ˢ t).filter (λ (x : α × β), p x.1 ∧ q x.2) = s.filter p ×ˢ t.filter q := by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], exact and_and_and_comm (a ∈ s) (b ∈ t) (p a) (q b) } lemma filter_product_left (p : α → Prop) [decidable_pred p] : (s ×ˢ t).filter (λ (x : α × β), p x.1) = s.filter p ×ˢ t := by simpa using filter_product p (λ _, true) lemma filter_product_right (q : β → Prop) [decidable_pred q] : (s ×ˢ t).filter (λ (x : α × β), q x.2) = s ×ˢ t.filter q := by simpa using filter_product (λ _ : α, true) q lemma filter_product_card (s : finset α) (t : finset β) (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : ((s ×ˢ t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card = (s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card := begin classical, rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq], { apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product], split; intros h; use h.1, simp only [function.comp_app, and_self, h.2, em (q b)], cases h.2; { try { simp at h_1 }, simp [h_1] } }, { apply finset.disjoint_filter_filter', exact (disjoint_compl_right.inf_left _).inf_right _ } end lemma empty_product (t : finset β) : (∅ : finset α) ×ˢ t = ∅ := rfl lemma product_empty (s : finset α) : s ×ˢ (∅ : finset β) = ∅ := eq_empty_of_forall_not_mem (λ x h, (finset.mem_product.1 h).2) lemma nonempty.product (hs : s.nonempty) (ht : t.nonempty) : (s ×ˢ t).nonempty := let ⟨x, hx⟩ := hs, ⟨y, hy⟩ := ht in ⟨(x, y), mem_product.2 ⟨hx, hy⟩⟩ lemma nonempty.fst (h : (s ×ˢ t).nonempty) : s.nonempty := let ⟨xy, hxy⟩ := h in ⟨xy.1, (mem_product.1 hxy).1⟩ lemma nonempty.snd (h : (s ×ˢ t).nonempty) : t.nonempty := let ⟨xy, hxy⟩ := h in ⟨xy.2, (mem_product.1 hxy).2⟩ @[simp] lemma nonempty_product : (s ×ˢ t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.product h.2⟩ @[simp] lemma product_eq_empty {s : finset α} {t : finset β} : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ := by rw [←not_nonempty_iff_eq_empty, nonempty_product, not_and_distrib, not_nonempty_iff_eq_empty, not_nonempty_iff_eq_empty] @[simp] lemma singleton_product {a : α} : ({a} : finset α) ×ˢ t = t.map ⟨prod.mk a, prod.mk.inj_left _⟩ := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } @[simp] lemma product_singleton {b : β} : s ×ˢ {b} = s.map ⟨λ i, (i, b), prod.mk.inj_right _⟩ := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } lemma singleton_product_singleton {a : α} {b : β} : ({a} : finset α) ×ˢ ({b} : finset β) = {(a, b)} := by simp only [product_singleton, function.embedding.coe_fn_mk, map_singleton] @[simp] lemma union_product [decidable_eq α] [decidable_eq β] : (s ∪ s') ×ˢ t = s ×ˢ t ∪ s' ×ˢ t := by { ext ⟨x, y⟩, simp only [or_and_distrib_right, mem_union, mem_product] } @[simp] lemma product_union [decidable_eq α] [decidable_eq β] : s ×ˢ (t ∪ t') = s ×ˢ t ∪ s ×ˢ t' := by { ext ⟨x, y⟩, simp only [and_or_distrib_left, mem_union, mem_product] } lemma inter_product [decidable_eq α] [decidable_eq β] : (s ∩ s') ×ˢ t = s ×ˢ t ∩ s' ×ˢ t := by { ext ⟨x, y⟩, simp only [←and_and_distrib_right, mem_inter, mem_product] } lemma product_inter [decidable_eq α] [decidable_eq β] : s ×ˢ (t ∩ t') = s ×ˢ t ∩ s ×ˢ t' := by { ext ⟨x, y⟩, simp only [←and_and_distrib_left, mem_inter, mem_product] } lemma product_inter_product [decidable_eq α] [decidable_eq β] : s ×ˢ t ∩ s' ×ˢ t' = (s ∩ s') ×ˢ (t ∩ t') := by { ext ⟨x, y⟩, simp only [and_assoc, and.left_comm, mem_inter, mem_product] } lemma disjoint_product : disjoint (s ×ˢ t) (s' ×ˢ t') ↔ disjoint s s' ∨ disjoint t t' := by simp_rw [←disjoint_coe, coe_product, set.disjoint_prod] @[simp] lemma disj_union_product (hs : disjoint s s') : s.disj_union s' hs ×ˢ t = (s ×ˢ t).disj_union (s' ×ˢ t) (disjoint_product.mpr $ or.inl hs) := eq_of_veq $ multiset.add_product _ _ _ @[simp] lemma product_disj_union (ht : disjoint t t') : s ×ˢ t.disj_union t' ht = (s ×ˢ t).disj_union (s ×ˢ t') (disjoint_product.mpr $ or.inr ht) := eq_of_veq $ multiset.product_add _ _ _ end prod section diag variables [decidable_eq α] (s t : finset α) /-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for `a ∈ s`. -/ def diag := (s ×ˢ s).filter (λ a : α × α, a.fst = a.snd) /-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. -/ def off_diag := (s ×ˢ s).filter (λ (a : α × α), a.fst ≠ a.snd) variables {s} {x : α × α} @[simp] lemma mem_diag : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by { simp only [diag, mem_filter, mem_product], split; intros h; simp only [h, and_true, eq_self_iff_true, and_self], rw ←h.2, exact h.1 } @[simp] lemma mem_off_diag : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by { simp only [off_diag, mem_filter, mem_product], split; intros h; simp only [h, ne.def, not_false_iff, and_self] } variables (s) @[simp, norm_cast] lemma coe_off_diag : (s.off_diag : set (α × α)) = (s : set α).off_diag := set.ext $ λ _, mem_off_diag @[simp] lemma diag_card : (diag s).card = s.card := begin suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, exact λ x1 h1 x2 h2 h3, (prod.mk.inj h3).1 }, ext ⟨a₁, a₂⟩, rw mem_diag, split; intros h; rw finset.mem_image at *, { use [a₁, h.1, prod.mk.inj_iff.mpr ⟨rfl, h.2⟩] }, { rcases h with ⟨a, h1, h2⟩, have h := prod.mk.inj h2, rw [←h.1, ←h.2], use h1 }, end @[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card := begin suffices : (diag s).card + (off_diag s).card = s.card * s.card, { nth_rewrite 2 ← s.diag_card, simp only [diag_card] at *, rw tsub_eq_of_eq_add_rev, rw this }, rw ← card_product, apply filter_card_add_filter_neg_card_eq_card, end @[mono] lemma diag_mono : monotone (diag : finset α → finset (α × α)) := λ s t h x hx, mem_diag.2 $ and.imp_left (@h _) $ mem_diag.1 hx @[mono] lemma off_diag_mono : monotone (off_diag : finset α → finset (α × α)) := λ s t h x hx, mem_off_diag.2 $ and.imp (@h _) (and.imp_left $ @h _) $ mem_off_diag.1 hx @[simp] lemma diag_empty : (∅ : finset α).diag = ∅ := rfl @[simp] lemma off_diag_empty : (∅ : finset α).off_diag = ∅ := rfl @[simp] lemma diag_union_off_diag : s.diag ∪ s.off_diag = s ×ˢ s := filter_union_filter_neg_eq _ _ @[simp] lemma disjoint_diag_off_diag : disjoint s.diag s.off_diag := disjoint_filter_filter_neg _ _ _ lemma product_sdiff_diag : s ×ˢ s \ s.diag = s.off_diag := by rw [←diag_union_off_diag, union_comm, union_sdiff_self, sdiff_eq_self_of_disjoint (disjoint_diag_off_diag _).symm] lemma product_sdiff_off_diag : s ×ˢ s \ s.off_diag = s.diag := by rw [←diag_union_off_diag, union_sdiff_self, sdiff_eq_self_of_disjoint (disjoint_diag_off_diag _)] lemma diag_inter : (s ∩ t).diag = s.diag ∩ t.diag := ext $ λ x, by simpa only [mem_diag, mem_inter] using and_and_distrib_right _ _ _ lemma off_diag_inter : (s ∩ t).off_diag = s.off_diag ∩ t.off_diag := coe_injective $ by { push_cast, exact set.off_diag_inter _ _ } lemma diag_union : (s ∪ t).diag = s.diag ∪ t.diag := by { ext ⟨i, j⟩, simp only [mem_diag, mem_union, or_and_distrib_right] } variables {s t} lemma off_diag_union (h : disjoint s t) : (s ∪ t).off_diag = s.off_diag ∪ t.off_diag ∪ s ×ˢ t ∪ t ×ˢ s := coe_injective $ by { push_cast, exact set.off_diag_union (disjoint_coe.2 h) } variables (a : α) @[simp] lemma off_diag_singleton : ({a} : finset α).off_diag = ∅ := by simp [←finset.card_eq_zero] lemma diag_singleton : ({a} : finset α).diag = {(a, a)} := by rw [←product_sdiff_off_diag, off_diag_singleton, sdiff_empty, singleton_product_singleton] lemma diag_insert : (insert a s).diag = insert (a, a) s.diag := by rw [insert_eq, insert_eq, diag_union, diag_singleton] lemma off_diag_insert (has : a ∉ s) : (insert a s).off_diag = s.off_diag ∪ {a} ×ˢ s ∪ s ×ˢ {a} := by rw [insert_eq, union_comm, off_diag_union (disjoint_singleton_right.2 has), off_diag_singleton, union_empty, union_right_comm] end diag end finset
57240b4dc409a530bc42eb794d4a309655409ce3
4727251e0cd73359b15b664c3170e5d754078599
/src/order/complete_lattice.lean
e67a577f6f81fa018908521da6fc878850e26910
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
53,728
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 data.bool.set import data.nat.basic import order.bounds /-! # Theory of complete lattices ## Main definitions * `Sup` and `Inf` are the supremum and the infimum of a set; * `supr (f : ι → α)` and `infi (f : ι → α)` are indexed supremum and infimum of a function, defined as `Sup` and `Inf` of the range of this function; * `class complete_lattice`: a bounded lattice such that `Sup s` is always the least upper boundary of `s` and `Inf s` is always the greatest lower boundary of `s`; * `class complete_linear_order`: a linear ordered complete lattice. ## Naming conventions In lemma names, * `Sup` is called `Sup` * `Inf` is called `Inf` * `⨆ i, s i` is called `supr` * `⨅ i, s i` is called `infi` * `⨆ i j, s i j` is called `supr₂`. This is a `supr` inside a `supr`. * `⨅ i j, s i j` is called `infi₂`. This is an `infi` inside an `infi`. * `⨆ i ∈ s, t i` is called `bsupr` for "bounded `supr`". This is the special case of `supr₂` where `j : i ∈ s`. * `⨅ i ∈ s, t i` is called `binfi` for "bounded `infi`". This is the special case of `infi₂` where `j : i ∈ s`. ## Notation * `⨆ i, f i` : `supr f`, the supremum of the range of `f`; * `⨅ i, f i` : `infi f`, the infimum of the range of `f`. -/ set_option old_structure_cmd true open set function variables {α β β₂ : Type*} {ι ι' : Sort*} {κ : ι → Sort*} {κ' : ι' → Sort*} /-- class for the `Sup` operator -/ class has_Sup (α : Type*) := (Sup : set α → α) /-- class for the `Inf` operator -/ class has_Inf (α : Type*) := (Inf : set α → α) export has_Sup (Sup) has_Inf (Inf) /-- Supremum of a set -/ add_decl_doc has_Sup.Sup /-- Infimum of a set -/ add_decl_doc has_Inf.Inf /-- Indexed supremum -/ def supr [has_Sup α] {ι} (s : ι → α) : α := Sup (range s) /-- Indexed infimum -/ def infi [has_Inf α] {ι} (s : ι → α) : α := Inf (range s) @[priority 50] instance has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩ @[priority 50] instance has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩ notation `⨆` binders `, ` r:(scoped f, supr f) := r notation `⨅` binders `, ` r:(scoped f, infi f) := r instance (α) [has_Inf α] : has_Sup αᵒᵈ := ⟨(Inf : set α → α)⟩ instance (α) [has_Sup α] : has_Inf αᵒᵈ := ⟨(Sup : set α → α)⟩ /-- Note that we rarely use `complete_semilattice_Sup` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ @[ancestor partial_order has_Sup] class complete_semilattice_Sup (α : Type*) extends partial_order α, has_Sup α := (le_Sup : ∀ s, ∀ a ∈ s, a ≤ Sup s) (Sup_le : ∀ s a, (∀ b ∈ s, b ≤ a) → Sup s ≤ a) section variables [complete_semilattice_Sup α] {s t : set α} {a b : α} @[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_semilattice_Sup.le_Sup s a theorem Sup_le : (∀ b ∈ s, b ≤ a) → Sup s ≤ a := complete_semilattice_Sup.Sup_le s a lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨λ x, le_Sup, λ x, Sup_le⟩ lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s := le_trans h (le_Sup hb) theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t := (is_lub_Sup s).mono (is_lub_Sup t) h @[simp] theorem Sup_le_iff : Sup s ≤ a ↔ ∀ b ∈ s, b ≤ a := is_lub_le_iff (is_lub_Sup s) lemma le_Sup_iff : a ≤ Sup s ↔ ∀ b ∈ upper_bounds s, a ≤ b := ⟨λ h b hb, le_trans h (Sup_le hb), λ hb, hb _ (λ x, le_Sup)⟩ lemma le_supr_iff {s : ι → α} : a ≤ supr s ↔ ∀ b, (∀ i, s i ≤ b) → a ≤ b := by simp [supr, le_Sup_iff, upper_bounds] theorem Sup_le_Sup_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, x ≤ y) : Sup s ≤ Sup t := le_Sup_iff.2 $ λ b hb, Sup_le $ λ a ha, let ⟨c, hct, hac⟩ := h a ha in hac.trans (hb hct) -- We will generalize this to conditionally complete lattices in `cSup_singleton`. theorem Sup_singleton {a : α} : Sup {a} = a := is_lub_singleton.Sup_eq end /-- Note that we rarely use `complete_semilattice_Inf` (in fact, any such object is always a `complete_lattice`, so it's usually best to start there). Nevertheless it is sometimes a useful intermediate step in constructions. -/ @[ancestor partial_order has_Inf] class complete_semilattice_Inf (α : Type*) extends partial_order α, has_Inf α := (Inf_le : ∀ s, ∀ a ∈ s, Inf s ≤ a) (le_Inf : ∀ s a, (∀ b ∈ s, a ≤ b) → a ≤ Inf s) section variables [complete_semilattice_Inf α] {s t : set α} {a b : α} @[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_semilattice_Inf.Inf_le s a theorem le_Inf : (∀ b ∈ s, a ≤ b) → a ≤ Inf s := complete_semilattice_Inf.le_Inf s a lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨λ a, Inf_le, λ a, le_Inf⟩ lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a := le_trans (Inf_le hb) h theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s := (is_glb_Inf s).mono (is_glb_Inf t) h @[simp] theorem le_Inf_iff : a ≤ Inf s ↔ ∀ b ∈ s, a ≤ b := le_is_glb_iff (is_glb_Inf s) lemma Inf_le_iff : Inf s ≤ a ↔ ∀ b ∈ lower_bounds s, b ≤ a := ⟨λ h b hb, le_trans (le_Inf hb) h, λ hb, hb _ (λ x, Inf_le)⟩ lemma infi_le_iff {s : ι → α} : infi s ≤ a ↔ ∀ b, (∀ i, b ≤ s i) → b ≤ a := by simp [infi, Inf_le_iff, lower_bounds] theorem Inf_le_Inf_of_forall_exists_le (h : ∀ x ∈ s, ∃ y ∈ t, y ≤ x) : Inf t ≤ Inf s := le_of_forall_le begin simp only [le_Inf_iff], introv h₀ h₁, rcases h _ h₁ with ⟨y, hy, hy'⟩, solve_by_elim [le_trans _ hy'] end -- We will generalize this to conditionally complete lattices in `cInf_singleton`. theorem Inf_singleton {a : α} : Inf {a} = a := is_glb_singleton.Inf_eq end /-- A complete lattice is a bounded lattice which has suprema and infima for every subset. -/ @[protect_proj, ancestor lattice complete_semilattice_Sup complete_semilattice_Inf has_top has_bot] class complete_lattice (α : Type*) extends lattice α, complete_semilattice_Sup α, complete_semilattice_Inf α, has_top α, has_bot α := (le_top : ∀ x : α, x ≤ ⊤) (bot_le : ∀ x : α, ⊥ ≤ x) @[priority 100] -- see Note [lower instance priority] instance complete_lattice.to_bounded_order [h : complete_lattice α] : bounded_order α := { ..h } /-- Create a `complete_lattice` from a `partial_order` and `Inf` function that returns the greatest lower bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Sup, bot, top ..complete_lattice_of_Inf my_T _ } ``` -/ def complete_lattice_of_Inf (α : Type*) [H1 : partial_order α] [H2 : has_Inf α] (is_glb_Inf : ∀ s : set α, is_glb s (Inf s)) : complete_lattice α := { bot := Inf univ, bot_le := λ x, (is_glb_Inf univ).1 trivial, top := Inf ∅, le_top := λ a, (is_glb_Inf ∅).2 $ by simp, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, inf := λ a b, Inf {a, b}, le_inf := λ a b c hab hac, by { apply (is_glb_Inf _).2, simp [*] }, inf_le_right := λ a b, (is_glb_Inf _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf_le_left := λ a b, (is_glb_Inf _).1 $ mem_insert _ _, sup_le := λ a b c hac hbc, (is_glb_Inf _).1 $ by simp [*], le_sup_left := λ a b, (is_glb_Inf _).2 $ λ x, and.left, le_sup_right := λ a b, (is_glb_Inf _).2 $ λ x, and.right, le_Inf := λ s a ha, (is_glb_Inf s).2 ha, Inf_le := λ s a ha, (is_glb_Inf s).1 ha, Sup := λ s, Inf (upper_bounds s), le_Sup := λ s a ha, (is_glb_Inf (upper_bounds s)).2 $ λ b hb, hb ha, Sup_le := λ s a ha, (is_glb_Inf (upper_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Inf` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Inf`. -/ def complete_lattice_of_complete_semilattice_Inf (α : Type*) [complete_semilattice_Inf α] : complete_lattice α := complete_lattice_of_Inf α (λ s, is_glb_Inf s) /-- Create a `complete_lattice` from a `partial_order` and `Sup` function that returns the least upper bound of a set. Usually this constructor provides poor definitional equalities. If other fields are known explicitly, they should be provided; for example, if `inf` is known explicitly, construct the `complete_lattice` instance as ``` instance : complete_lattice my_T := { inf := better_inf, le_inf := ..., inf_le_right := ..., inf_le_left := ... -- don't care to fix sup, Inf, bot, top ..complete_lattice_of_Sup my_T _ } ``` -/ def complete_lattice_of_Sup (α : Type*) [H1 : partial_order α] [H2 : has_Sup α] (is_lub_Sup : ∀ s : set α, is_lub s (Sup s)) : complete_lattice α := { top := Sup univ, le_top := λ x, (is_lub_Sup univ).1 trivial, bot := Sup ∅, bot_le := λ x, (is_lub_Sup ∅).2 $ by simp, sup := λ a b, Sup {a, b}, sup_le := λ a b c hac hbc, (is_lub_Sup _).2 (by simp [*]), le_sup_left := λ a b, (is_lub_Sup _).1 $ mem_insert _ _, le_sup_right := λ a b, (is_lub_Sup _).1 $ mem_insert_of_mem _ $ mem_singleton _, inf := λ a b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := λ a b c hab hac, (is_lub_Sup _).1 $ by simp [*], inf_le_left := λ a b, (is_lub_Sup _).2 (λ x, and.left), inf_le_right := λ a b, (is_lub_Sup _).2 (λ x, and.right), Inf := λ s, Sup (lower_bounds s), Sup_le := λ s a ha, (is_lub_Sup s).2 ha, le_Sup := λ s a ha, (is_lub_Sup s).1 ha, Inf_le := λ s a ha, (is_lub_Sup (lower_bounds s)).2 (λ b hb, hb ha), le_Inf := λ s a ha, (is_lub_Sup (lower_bounds s)).1 ha, .. H1, .. H2 } /-- Any `complete_semilattice_Sup` is in fact a `complete_lattice`. Note that this construction has bad definitional properties: see the doc-string on `complete_lattice_of_Sup`. -/ def complete_lattice_of_complete_semilattice_Sup (α : Type*) [complete_semilattice_Sup α] : complete_lattice α := complete_lattice_of_Sup α (λ s, is_lub_Sup s) /-- A complete linear order is a linear order whose lattice structure is complete. -/ class complete_linear_order (α : Type*) extends complete_lattice α, linear_order α renaming max → sup min → inf namespace order_dual variable (α) instance [complete_lattice α] : complete_lattice αᵒᵈ := { 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.lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α, .. order_dual.bounded_order α } instance [complete_linear_order α] : complete_linear_order αᵒᵈ := { .. order_dual.complete_lattice α, .. order_dual.linear_order α } end order_dual section variables [complete_lattice α] {s t : set α} {a b : α} theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s := is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t := ((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t := Sup_le $ λ b hb, le_inf (le_Sup hb.1) (le_Sup hb.2) /- Sup_le (λ a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t)) -/ theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t := ((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) := @Sup_inter_le αᵒᵈ _ _ _ @[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) := (@is_lub_empty α _ _).Sup_eq @[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) := (@is_glb_empty α _ _).Inf_eq @[simp] theorem Sup_univ : Sup univ = (⊤ : α) := (@is_lub_univ α _ _).Sup_eq @[simp] theorem Inf_univ : Inf univ = (⊥ : α) := (@is_glb_univ α _ _).Inf_eq -- TODO(Jeremy): get this automatically @[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s := ((is_lub_Sup s).insert a).Sup_eq @[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s := ((is_glb_Inf s).insert a).Inf_eq theorem Sup_le_Sup_of_subset_insert_bot (h : s ⊆ insert ⊥ t) : Sup s ≤ Sup t := le_trans (Sup_le_Sup h) (le_of_eq (trans Sup_insert bot_sup_eq)) theorem Inf_le_Inf_of_subset_insert_top (h : s ⊆ insert ⊤ t) : Inf t ≤ Inf s := le_trans (le_of_eq (trans top_inf_eq.symm Inf_insert.symm)) (Inf_le_Inf h) theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b := (@is_lub_pair α _ a b).Sup_eq theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b := (@is_glb_pair α _ a b).Inf_eq @[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀ a ∈ s, a = ⊤) := iff.intro (λ h a ha, top_unique $ h ▸ Inf_le ha) (λ h, top_unique $ le_Inf $ λ a ha, top_le_iff.2 $ h a ha) lemma eq_singleton_top_of_Inf_eq_top_of_nonempty {s : set α} (h_inf : Inf s = ⊤) (hne : s.nonempty) : s = {⊤} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Inf_eq_top at h_inf, exact ⟨hne, h_inf⟩, } @[simp] lemma Sup_eq_bot : Sup s = ⊥ ↔ ∀ a ∈ s, a = ⊥ := @Inf_eq_top αᵒᵈ _ _ lemma eq_singleton_bot_of_Sup_eq_bot_of_nonempty {s : set α} (h_sup : Sup s = ⊥) (hne : s.nonempty) : s = {⊥} := by { rw set.eq_singleton_iff_nonempty_unique_mem, rw Sup_eq_bot at h_sup, exact ⟨hne, h_sup⟩, } /--Introduction rule to prove that `b` is the supremum of `s`: it suffices to check that `b` is larger than all elements of `s`, and that this is not the case of any `w < b`. See `cSup_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem Sup_eq_of_forall_le_of_forall_lt_exists_gt (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b := have h : (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (Sup_le ‹∀a∈s, a ≤ b›), have ¬(Sup s < b) := λ hb, let ⟨a, ha, ha'⟩ := H (Sup s) hb in /- a ∈ s, Sup s < a-/ have Sup s < Sup s := lt_of_lt_of_le ha' (le_Sup ha), show false, from lt_irrefl _ this, show Sup s = b, from or.resolve_left h this /--Introduction rule to prove that `b` is the infimum of `s`: it suffices to check that `b` is smaller than all elements of `s`, and that this is not the case of any `w > b`. See `cInf_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem Inf_eq_of_forall_ge_of_forall_gt_exists_lt : (∀ a ∈ s, b ≤ a) → (∀ w, b < w → (∃ a ∈ s, a < w)) → Inf s = b := @Sup_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ ‹_› 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 (λ (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb) (λ h, top_unique $ le_of_not_gt $ λ h', let ⟨a, ha, h⟩ := h _ h' in lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h) lemma Inf_eq_bot : Inf s = ⊥ ↔ ∀ b > ⊥, ∃ a ∈ s, a < b := @Sup_eq_top αᵒᵈ _ _ lemma lt_supr_iff {f : ι → α} : a < supr f ↔ ∃ i, a < f i := lt_Sup_iff.trans exists_range_iff lemma infi_lt_iff {f : ι → α} : infi f < a ↔ ∃ i, f i < a := Inf_lt_iff.trans exists_range_iff end complete_linear_order /- ### supr & infi -/ section has_Sup variables [has_Sup α] {f g : ι → α} lemma Sup_range : Sup (range f) = supr f := rfl lemma Sup_eq_supr' (s : set α) : Sup s = ⨆ a : s, a := by rw [supr, subtype.range_coe] lemma supr_congr (h : ∀ i, f i = g i) : (⨆ i, f i) = ⨆ i, g i := congr_arg _ $ funext h lemma function.surjective.supr_comp {f : ι → ι'} (hf : surjective f) (g : ι' → α) : (⨆ x, g (f x)) = ⨆ y, g y := by simp only [supr, hf.range_comp] protected lemma function.surjective.supr_congr {g : ι' → α} (h : ι → ι') (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⨆ x, f x) = ⨆ y, g y := by { convert h1.supr_comp g, exact (funext h2).symm } @[congr] lemma supr_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀ x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ := begin obtain rfl := propext pq, congr' with x, apply f end lemma supr_range' (g : β → α) (f : ι → β) : (⨆ b : range f, g b) = ⨆ i, g (f i) := by rw [supr, supr, ← image_eq_range, ← range_comp] lemma Sup_image' {s : set β} {f : β → α} : Sup (f '' s) = ⨆ a : s, f a := by rw [supr, image_eq_range] end has_Sup section has_Inf variables [has_Inf α] {f g : ι → α} lemma Inf_range : Inf (range f) = infi f := rfl lemma Inf_eq_infi' (s : set α) : Inf s = ⨅ a : s, a := @Sup_eq_supr' αᵒᵈ _ _ lemma infi_congr (h : ∀ i, f i = g i) : (⨅ i, f i) = ⨅ i, g i := congr_arg _ $ funext h lemma function.surjective.infi_comp {f : ι → ι'} (hf : surjective f) (g : ι' → α) : (⨅ x, g (f x)) = ⨅ y, g y := @function.surjective.supr_comp αᵒᵈ _ _ _ f hf g lemma function.surjective.infi_congr {g : ι' → α} (h : ι → ι') (h1 : surjective h) (h2 : ∀ x, g (h x) = f x) : (⨅ x, f x) = ⨅ y, g y := @function.surjective.supr_congr αᵒᵈ _ _ _ _ _ h h1 h2 @[congr]lemma infi_congr_Prop {p q : Prop} {f₁ : p → α} {f₂ : q → α} (pq : p ↔ q) (f : ∀ x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ := @supr_congr_Prop αᵒᵈ _ p q f₁ f₂ pq f lemma infi_range' (g : β → α) (f : ι → β) : (⨅ b : range f, g b) = ⨅ i, g (f i) := @supr_range' αᵒᵈ _ _ _ _ _ lemma Inf_image' {s : set β} {f : β → α} : Inf (f '' s) = ⨅ a : s, f a := @Sup_image' αᵒᵈ _ _ _ _ end has_Inf section variables [complete_lattice α] {f g s t : ι → α} {a b : α} -- TODO: this declaration gives error when starting smt state --@[ematch] lemma le_supr (f : ι → α) (i : ι) : f i ≤ supr f := le_Sup ⟨i, rfl⟩ lemma infi_le (f : ι → α) (i : ι) : infi f ≤ f i := Inf_le ⟨i, rfl⟩ @[ematch] lemma le_supr' (f : ι → α) (i : ι) : (: f i ≤ supr f :) := le_Sup ⟨i, rfl⟩ @[ematch] lemma infi_le' (f : ι → α) (i : ι) : (: infi f ≤ f i :) := Inf_le ⟨i, rfl⟩ /- TODO: this version would be more powerful, but, alas, the pattern matcher doesn't accept it. @[ematch] lemma le_supr' (f : ι → α) (i : ι) : (: f i :) ≤ (: supr f :) := le_Sup ⟨i, rfl⟩ -/ lemma is_lub_supr : is_lub (range f) (⨆ j, f j) := is_lub_Sup _ lemma is_glb_infi : is_glb (range f) (⨅ j, f j) := is_glb_Inf _ lemma is_lub.supr_eq (h : is_lub (range f) a) : (⨆ j, f j) = a := h.Sup_eq lemma is_glb.infi_eq (h : is_glb (range f) a) : (⨅ j, f j) = a := h.Inf_eq lemma le_supr_of_le (i : ι) (h : a ≤ f i) : a ≤ supr f := h.trans $ le_supr _ i lemma infi_le_of_le (i : ι) (h : f i ≤ a) : infi f ≤ a := (infi_le _ i).trans h lemma le_supr₂ {f : Π i, κ i → α} (i : ι) (j : κ i) : f i j ≤ ⨆ i j, f i j := le_supr_of_le i $ le_supr (f i) j lemma infi₂_le {f : Π i, κ i → α} (i : ι) (j : κ i) : (⨅ i j, f i j) ≤ f i j := infi_le_of_le i $ infi_le (f i) j lemma le_supr₂_of_le {f : Π i, κ i → α} (i : ι) (j : κ i) (h : a ≤ f i j) : a ≤ ⨆ i j, f i j := h.trans $ le_supr₂ i j lemma infi₂_le_of_le {f : Π i, κ i → α} (i : ι) (j : κ i) (h : f i j ≤ a) : (⨅ i j, f i j) ≤ a := (infi₂_le i j).trans h lemma supr_le (h : ∀ i, f i ≤ a) : supr f ≤ a := Sup_le $ λ b ⟨i, eq⟩, eq ▸ h i lemma le_infi (h : ∀ i, a ≤ f i) : a ≤ infi f := le_Inf $ λ b ⟨i, eq⟩, eq ▸ h i lemma supr₂_le {f : Π i, κ i → α} (h : ∀ i j, f i j ≤ a) : (⨆ i j, f i j) ≤ a := supr_le $ λ i, supr_le $ h i lemma le_infi₂ {f : Π i, κ i → α} (h : ∀ i j, a ≤ f i j) : a ≤ ⨅ i j, f i j := le_infi $ λ i, le_infi $ h i lemma supr₂_le_supr (κ : ι → Sort*) (f : ι → α) : (⨆ i (j : κ i), f i) ≤ ⨆ i, f i := supr₂_le $ λ i j, le_supr f i lemma infi_le_infi₂ (κ : ι → Sort*) (f : ι → α) : (⨅ i, f i) ≤ ⨅ i (j : κ i), f i := le_infi₂ $ λ i j, infi_le f i lemma supr_mono (h : ∀ i, f i ≤ g i) : supr f ≤ supr g := supr_le $ λ i, le_supr_of_le i $ h i lemma infi_mono (h : ∀ i, f i ≤ g i) : infi f ≤ infi g := le_infi $ λ i, infi_le_of_le i $ h i lemma supr₂_mono {f g : Π i, κ i → α} (h : ∀ i j, f i j ≤ g i j) : (⨆ i j, f i j) ≤ ⨆ i j, g i j := supr_mono $ λ i, supr_mono $ h i lemma infi₂_mono {f g : Π i, κ i → α} (h : ∀ i j, f i j ≤ g i j) : (⨅ i j, f i j) ≤ ⨅ i j, g i j := infi_mono $ λ i, infi_mono $ h i lemma supr_mono' {g : ι' → α} (h : ∀ i, ∃ i', f i ≤ g i') : supr f ≤ supr g := supr_le $ λ i, exists.elim (h i) le_supr_of_le lemma infi_mono' {g : ι' → α} (h : ∀ i', ∃ i, f i ≤ g i') : infi f ≤ infi g := le_infi $ λ i', exists.elim (h i') infi_le_of_le lemma supr₂_mono' {f : Π i, κ i → α} {g : Π i', κ' i' → α} (h : ∀ i j, ∃ i' j', f i j ≤ g i' j') : (⨆ i j, f i j) ≤ ⨆ i j, g i j := supr₂_le $ λ i j, let ⟨i', j', h⟩ := h i j in le_supr₂_of_le i' j' h lemma infi₂_mono' {f : Π i, κ i → α} {g : Π i', κ' i' → α} (h : ∀ i j, ∃ i' j', f i' j' ≤ g i j) : (⨅ i j, f i j) ≤ ⨅ i j, g i j := le_infi₂ $ λ i j, let ⟨i', j', h⟩ := h i j in infi₂_le_of_le i' j' h lemma supr_const_mono (h : ι → ι') : (⨆ i : ι, a) ≤ ⨆ j : ι', a := supr_le $ le_supr _ ∘ h lemma infi_const_mono (h : ι' → ι) : (⨅ i : ι, a) ≤ ⨅ j : ι', a := le_infi $ infi_le _ ∘ h lemma bsupr_mono {p q : ι → Prop} (hpq : ∀ i, p i → q i) : (⨆ i (h : p i), f i) ≤ ⨆ i (h : q i), f i := supr_mono $ λ i, supr_const_mono (hpq i) lemma binfi_mono {p q : ι → Prop} (hpq : ∀ i, p i → q i) : (⨅ i (h : q i), f i) ≤ ⨅ i (h : p i), f i := infi_mono $ λ i, infi_const_mono (hpq i) @[simp] lemma supr_le_iff : supr f ≤ a ↔ ∀ i, f i ≤ a := (is_lub_le_iff is_lub_supr).trans forall_range_iff @[simp] lemma le_infi_iff : a ≤ infi f ↔ ∀ i, a ≤ f i := (le_is_glb_iff is_glb_infi).trans forall_range_iff @[simp] lemma supr₂_le_iff {f : Π i, κ i → α} : (⨆ i j, f i j) ≤ a ↔ ∀ i j, f i j ≤ a := by simp_rw supr_le_iff @[simp] lemma le_infi₂_iff {f : Π i, κ i → α} : a ≤ (⨅ i j, f i j) ↔ ∀ i j, a ≤ f i j := by simp_rw le_infi_iff lemma supr_lt_iff : supr f < a ↔ ∃ b, b < a ∧ ∀ i, f i ≤ b := ⟨λ h, ⟨supr f, h, le_supr f⟩, λ ⟨b, h, hb⟩, (supr_le hb).trans_lt h⟩ lemma lt_infi_iff : a < infi f ↔ ∃ b, a < b ∧ ∀ i, b ≤ f i := ⟨λ h, ⟨infi f, h, infi_le f⟩, λ ⟨b, h, hb⟩, h.trans_le $ le_infi hb⟩ lemma Sup_eq_supr {s : set α} : Sup s = ⨆ a ∈ s, a := le_antisymm (Sup_le le_supr₂) (supr₂_le $ λ b, le_Sup) lemma Inf_eq_infi {s : set α} : Inf s = ⨅ a ∈ s, a := @Sup_eq_supr αᵒᵈ _ _ lemma Sup_sUnion (s : set (set α)) : Sup (⋃₀ s) = ⨆ t ∈ s, Sup t := begin apply le_antisymm, { apply Sup_le (λ b hb, _), rcases hb with ⟨t, ts, bt⟩, apply le_trans _ (le_supr _ t), exact le_trans (le_Sup bt) (le_supr _ ts), }, { apply supr_le (λ t, _), exact supr_le (λ ts, Sup_le_Sup (λ x xt, ⟨t, ts, xt⟩)) } end lemma Inf_sUnion (s : set (set α)) : Inf (⋃₀ s) = ⨅ t ∈ s, Inf t := @Sup_sUnion αᵒᵈ _ _ lemma monotone.le_map_supr [complete_lattice β] {f : α → β} (hf : monotone f) : (⨆ i, f (s i)) ≤ f (supr s) := supr_le $ λ i, hf $ le_supr _ _ lemma monotone.le_map_supr₂ [complete_lattice β] {f : α → β} (hf : monotone f) (s : Π i, κ i → α) : (⨆ i j, f (s i j)) ≤ f (⨆ i j, s i j) := calc (⨆ i j, f (s i j)) ≤ (⨆ i, f (⨆ j, s i j)) : supr_mono $ λ i, hf.le_map_supr ... ≤ f (⨆ i j, s i j) : hf.le_map_supr lemma monotone.le_map_Sup [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : (⨆ a ∈ s, f a) ≤ f (Sup s) := by rw [Sup_eq_supr]; exact hf.le_map_supr₂ _ lemma antitone.le_map_infi [complete_lattice β] {f : α → β} (hf : antitone f) : (⨆ i, f (s i)) ≤ f (infi s) := hf.dual_left.le_map_supr lemma antitone.le_map_infi₂ [complete_lattice β] {f : α → β} (hf : antitone f) (s : Π i, κ i → α) : (⨆ i j, f (s i j)) ≤ f (⨅ i j, s i j) := hf.dual_left.le_map_supr₂ _ lemma antitone.le_map_Inf [complete_lattice β] {s : set α} {f : α → β} (hf : antitone f) : (⨆ a ∈ s, f a) ≤ f (Inf s) := hf.dual_left.le_map_Sup lemma order_iso.map_supr [complete_lattice β] (f : α ≃o β) (x : ι → α) : f (⨆ i, x i) = ⨆ i, f (x i) := eq_of_forall_ge_iff $ f.surjective.forall.2 $ λ x, by simp only [f.le_iff_le, supr_le_iff] lemma order_iso.map_Sup [complete_lattice β] (f : α ≃o β) (s : set α) : f (Sup s) = ⨆ a ∈ s, f a := by simp only [Sup_eq_supr, order_iso.map_supr] lemma supr_comp_le {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨆ x, f (g x)) ≤ ⨆ y, f y := supr_mono' $ λ x, ⟨_, le_rfl⟩ lemma monotone.supr_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, x ≤ s i) : (⨆ x, f (s x)) = ⨆ y, f y := le_antisymm (supr_comp_le _ _) (supr_mono' $ λ x, (hs x).imp $ λ i hi, hf hi) 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_infi₂_le [complete_lattice β] {f : α → β} (hf : monotone f) (s : Π i, κ i → α) : f (⨅ i j, s i j) ≤ ⨅ i j, f (s i j) := hf.dual.le_map_supr₂ _ lemma monotone.map_Inf_le [complete_lattice β] {s : set α} {f : α → β} (hf : monotone f) : f (Inf s) ≤ ⨅ a ∈ s, f a := by rw [Inf_eq_infi]; exact hf.map_infi₂_le _ lemma antitone.map_supr_le [complete_lattice β] {f : α → β} (hf : antitone f) : f (supr s) ≤ ⨅ i, f (s i) := hf.dual_left.map_infi_le lemma antitone.map_supr₂_le [complete_lattice β] {f : α → β} (hf : antitone f) (s : Π i, κ i → α) : f (⨆ i j, s i j) ≤ ⨅ i j, f (s i j) := hf.dual_left.map_infi₂_le _ lemma antitone.map_Sup_le [complete_lattice β] {s : set α} {f : α → β} (hf : antitone f) : f (Sup s) ≤ ⨅ a ∈ s, f a := hf.dual_left.map_Inf_le lemma order_iso.map_infi [complete_lattice β] (f : α ≃o β) (x : ι → α) : f (⨅ i, x i) = ⨅ i, f (x i) := order_iso.map_supr f.dual _ lemma order_iso.map_Inf [complete_lattice β] (f : α ≃o β) (s : set α) : f (Inf s) = ⨅ a ∈ s, f a := order_iso.map_Sup f.dual _ lemma le_infi_comp {ι' : Sort*} (f : ι' → α) (g : ι → ι') : (⨅ y, f y) ≤ ⨅ x, f (g x) := infi_mono' $ λ x, ⟨_, le_rfl⟩ lemma monotone.infi_comp_eq [preorder β] {f : β → α} (hf : monotone f) {s : ι → β} (hs : ∀ x, ∃ i, s i ≤ x) : (⨅ x, f (s x)) = ⨅ y, f y := le_antisymm (infi_mono' $ λ x, (hs x).imp $ λ i hi, hf hi) (le_infi_comp _ _) lemma supr_const_le {x : α} : (⨆ (h : ι), x) ≤ x := supr_le (λ _, le_rfl) lemma le_infi_const {x : α} : x ≤ (⨅ (h : ι), x) := le_infi (λ _, le_rfl) -- We will generalize this to conditionally complete lattices in `cinfi_const`. theorem infi_const [nonempty ι] {a : α} : (⨅ b : ι, a) = a := by rw [infi, range_const, Inf_singleton] -- We will generalize this to conditionally complete lattices in `csupr_const`. theorem supr_const [nonempty ι] {a : α} : (⨆ b : ι, a) = a := @infi_const αᵒᵈ _ _ _ _ @[simp] lemma infi_top : (⨅ i:ι, ⊤ : α) = ⊤ := top_unique $ le_infi $ λ i, le_rfl @[simp] lemma supr_bot : (⨆ i:ι, ⊥ : α) = ⊥ := @infi_top αᵒᵈ _ _ @[simp] lemma supr_eq_bot : supr s = ⊥ ↔ ∀ i, s i = ⊥ := Sup_eq_bot.trans forall_range_iff @[simp] lemma infi_eq_top : infi s = ⊤ ↔ ∀ i, s i = ⊤ := Inf_eq_top.trans forall_range_iff @[simp] lemma supr₂_eq_bot {f : Π i, κ i → α} : (⨆ i j, f i j) = ⊥ ↔ ∀ i j, f i j = ⊥ := by simp_rw supr_eq_bot @[simp] lemma infi₂_eq_top {f : Π i, κ i → α} : (⨅ i j, f i j) = ⊤ ↔ ∀ i j, f i j = ⊤ := by simp_rw infi_eq_top @[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp := le_antisymm (supr_le $ λ h, le_rfl) (le_supr _ _) @[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp := le_antisymm (infi_le _ _) (le_infi $ λ h, le_rfl) @[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ := le_antisymm (supr_le $ λ h, (hp h).elim) bot_le @[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ := le_antisymm le_top $ le_infi $ λ h, (hp h).elim /--Introduction rule to prove that `b` is the supremum of `f`: it suffices to check that `b` is larger than `f i` for all `i`, and that this is not the case of any `w<b`. See `csupr_eq_of_forall_le_of_forall_lt_exists_gt` for a version in conditionally complete lattices. -/ theorem supr_eq_of_forall_le_of_forall_lt_exists_gt {f : ι → α} (h₁ : ∀ i, f i ≤ b) (h₂ : ∀ w, w < b → (∃ i, w < f i)) : (⨆ (i : ι), f i) = b := Sup_eq_of_forall_le_of_forall_lt_exists_gt (forall_range_iff.mpr h₁) (λ w hw, exists_range_iff.mpr $ h₂ w hw) /--Introduction rule to prove that `b` is the infimum of `f`: it suffices to check that `b` is smaller than `f i` for all `i`, and that this is not the case of any `w>b`. See `cinfi_eq_of_forall_ge_of_forall_gt_exists_lt` for a version in conditionally complete lattices. -/ theorem infi_eq_of_forall_ge_of_forall_gt_exists_lt {f : ι → α} (h₁ : ∀ i, b ≤ f i) (h₂ : ∀ w, b < w → (∃ i, f i < w)) : (⨅ (i : ι), f i) = b := @supr_eq_of_forall_le_of_forall_lt_exists_gt αᵒᵈ _ _ _ ‹_› ‹_› ‹_› lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨆ h : p, a h) = if h : p then a h else ⊥ := by by_cases p; simp [h] lemma supr_eq_if {p : Prop} [decidable p] (a : α) : (⨆ h : p, a) = if p then a else ⊥ := supr_eq_dif (λ _, a) lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) : (⨅ h : p, a h) = if h : p then a h else ⊤ := @supr_eq_dif αᵒᵈ _ _ _ _ lemma infi_eq_if {p : Prop} [decidable p] (a : α) : (⨅ h : p, a) = if p then a else ⊤ := infi_eq_dif (λ _, a) -- TODO: should this be @[simp]? lemma supr_comm {f : ι → ι' → α} : (⨆ i j, f i j) = ⨆ j i, f i j := le_antisymm (supr_le $ λ i, supr_mono $ λ j, le_supr _ i) (supr_le $ λ j, supr_mono $ λ i, le_supr _ _) -- TODO: should this be @[simp]? lemma infi_comm {f : ι → ι' → α} : (⨅ i j, f i j) = ⨅ j i, f i j := @supr_comm αᵒᵈ _ _ _ _ /- 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 -/ @[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 _ rfl) (le_infi $ λ b', le_infi $ λ eq, match b', eq with ._, rfl := le_rfl 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 _ rfl) (le_infi₂ $ λ b' eq, match b', eq with ._, rfl := le_rfl end) @[simp] theorem supr_supr_eq_left {b : β} {f : Π x : β, x = b → α} : (⨆ x, ⨆ h : x = b, f x h) = f b rfl := @infi_infi_eq_left αᵒᵈ _ _ _ _ @[simp] theorem supr_supr_eq_right {b : β} {f : Π x : β, b = x → α} : (⨆ x, ⨆ h : b = x, f x h) = f b rfl := @infi_infi_eq_right αᵒᵈ _ _ _ _ attribute [ematch] le_refl theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h : p i), f ⟨i, h⟩) := le_antisymm (le_infi₂ $ λ i h, infi_le _ _) (le_infi $ λ ⟨i, h⟩, infi₂_le _ _) lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x x.property) := (@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma infi_subtype'' {ι} (s : set ι) (f : ι → α) : (⨅ i : s, f i) = ⨅ (t : ι) (H : t ∈ s), f t := infi_subtype theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) := le_antisymm (le_inf (infi_mono $ λ i, inf_le_left) $ infi_mono $ λ i, inf_le_right) (le_infi $ λ i, inf_le_inf (infi_le _ _) $ infi_le _ _) /- TODO: here is another example where more flexible pattern matching might help. begin apply @le_antisymm, safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end end -/ lemma infi_inf [h : nonempty ι] {f : ι → α} {a : α} : (⨅ x, f x) ⊓ a = (⨅ x, f x ⊓ a) := by rw [infi_inf_eq, infi_const] lemma inf_infi [nonempty ι] {f : ι → α} {a : α} : a ⊓ (⨅ x, f x) = (⨅ x, a ⊓ f x) := by rw [inf_comm, infi_inf]; simp [inf_comm] lemma binfi_inf {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : (⨅ i (h : p i), f i h) ⊓ a = ⨅ i (h : p i), f i h ⊓ a := by haveI : nonempty {i // p i} := (let ⟨i, hi⟩ := h in ⟨⟨i, hi⟩⟩); rw [infi_subtype', infi_subtype', infi_inf] lemma inf_binfi {p : ι → Prop} {f : Π i (hi : p i), α} {a : α} (h : ∃ i, p i) : a ⊓ (⨅ i (h : p i), f i h) = ⨅ i (h : p i), a ⊓ f i h := by simpa only [inf_comm] using binfi_inf h theorem supr_sup_eq {f g : ι → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) := @infi_inf_eq αᵒᵈ ι _ _ _ lemma supr_sup [h : nonempty ι] {f : ι → α} {a : α} : (⨆ x, f x) ⊔ a = (⨆ x, f x ⊔ a) := @infi_inf αᵒᵈ _ _ _ _ _ lemma sup_supr [nonempty ι] {f : ι → α} {a : α} : a ⊔ (⨆ x, f x) = (⨆ x, a ⊔ f x) := @inf_infi αᵒᵈ _ _ _ _ _ /-! ### `supr` and `infi` under `Prop` -/ @[simp] theorem infi_false {s : false → α} : infi s = ⊤ := le_antisymm le_top (le_infi $ λ i, false.elim i) @[simp] theorem supr_false {s : false → α} : supr s = ⊥ := le_antisymm (supr_le $ λ i, false.elim i) bot_le lemma supr_true {s : true → α} : supr s = s trivial := supr_pos trivial lemma infi_true {s : true → α} : infi s = s trivial := infi_pos trivial @[simp] lemma infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = ⨅ i h, f ⟨i, h⟩ := le_antisymm (le_infi₂ $ λ i h, infi_le _ _) (le_infi $ λ ⟨i, h⟩, infi₂_le _ _) @[simp] lemma supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = ⨆ i h, f ⟨i, h⟩ := @infi_exists αᵒᵈ _ _ _ _ lemma infi_and {p q : Prop} {s : p ∧ q → α} : infi s = ⨅ h₁ h₂, s ⟨h₁, h₂⟩ := le_antisymm (le_infi₂ $ λ i j, infi_le _ _) (le_infi $ λ ⟨i, h⟩, infi₂_le _ _) /-- The symmetric case of `infi_and`, useful for rewriting into a infimum over a conjunction -/ lemma infi_and' {p q : Prop} {s : p → q → α} : (⨅ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨅ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact infi_and } lemma supr_and {p q : Prop} {s : p ∧ q → α} : supr s = ⨆ h₁ h₂, s ⟨h₁, h₂⟩ := @infi_and αᵒᵈ _ _ _ _ /-- The symmetric case of `supr_and`, useful for rewriting into a supremum over a conjunction -/ lemma supr_and' {p q : Prop} {s : p → q → α} : (⨆ (h₁ : p) (h₂ : q), s h₁ h₂) = ⨆ (h : p ∧ q), s h.1 h.2 := by { symmetry, exact supr_and } theorem infi_or {p q : Prop} {s : p ∨ q → α} : infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) := le_antisymm (le_inf (le_infi_comp _ _) $ le_infi_comp _ _) (le_infi $ λ i, match i with | or.inl i := inf_le_of_left_le $ infi_le _ _ | or.inr j := inf_le_of_right_le $ infi_le _ _ end) theorem supr_or {p q : Prop} {s : p ∨ q → α} : (⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) := @infi_or αᵒᵈ _ _ _ _ section variables (p : ι → Prop) [decidable_pred p] lemma supr_dite (f : Π i, p i → α) (g : Π i, ¬p i → α) : (⨆ i, if h : p i then f i h else g i h) = (⨆ i (h : p i), f i h) ⊔ (⨆ i (h : ¬ p i), g i h) := begin rw ←supr_sup_eq, congr' 1 with i, split_ifs with h; simp [h], end lemma supr_ite (f g : ι → α) : (⨆ i, if p i then f i else g i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), g i) := supr_dite _ _ _ lemma infi_dite (f : Π i, p i → α) (g : Π i, ¬p i → α) : (⨅ i, if h : p i then f i h else g i h) = (⨅ i (h : p i), f i h) ⊓ (⨅ i (h : ¬ p i), g i h) := supr_dite p (show Π i, p i → αᵒᵈ, from f) g lemma infi_ite (f g : ι → α) : (⨅ i, if p i then f i else g i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), g i) := infi_dite _ _ _ end lemma infi_range {g : β → α} {f : ι → β} : (⨅ b ∈ range f, g b) = ⨅ i, g (f i) := by rw [← infi_subtype'', infi_range'] lemma supr_range {g : β → α} {f : ι → β} : (⨆ b ∈ range f, g b) = ⨆ i, g (f i) := @infi_range αᵒᵈ _ _ _ _ _ theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = ⨅ a ∈ s, f a := by rw [← infi_subtype'', Inf_image'] theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = ⨆ a ∈ s, f a := @Inf_image αᵒᵈ _ _ _ _ /- ### supr and infi under set constructions -/ theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ := by simp theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ := by simp theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) := by simp theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) := by simp theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) := by simp only [← infi_inf_eq, infi_or] lemma infi_split (f : β → α) (p : β → Prop) : (⨅ i, f i) = (⨅ i (h : p i), f i) ⊓ (⨅ i (h : ¬ p i), f i) := by simpa [classical.em] using @infi_union _ _ _ f {i | p i} {i | ¬ p i} lemma infi_split_single (f : β → α) (i₀ : β) : (⨅ i, f i) = f i₀ ⊓ (⨅ i (h : i ≠ i₀), f i) := by convert infi_split _ _; simp theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) := by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆ x ∈ s, f x) ⊔ (⨆ x ∈ t, f x) := @infi_union αᵒᵈ _ _ _ _ _ lemma supr_split (f : β → α) (p : β → Prop) : (⨆ i, f i) = (⨆ i (h : p i), f i) ⊔ (⨆ i (h : ¬ p i), f i) := @infi_split αᵒᵈ _ _ _ _ lemma supr_split_single (f : β → α) (i₀ : β) : (⨆ i, f i) = f i₀ ⊔ (⨆ i (h : i ≠ i₀), f i) := @infi_split_single αᵒᵈ _ _ _ _ theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) : (⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) := @infi_le_infi_of_subset αᵒᵈ _ _ _ _ _ h theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅ x ∈ s, f x) := eq.trans infi_union $ congr_arg (λ x, x ⊓ (⨅ x ∈ s, f x)) infi_infi_eq_left theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆ x ∈ s, f x) := eq.trans supr_union $ congr_arg (λ x, x ⊔ (⨆ x ∈ s, f x)) supr_supr_eq_left theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b := by simp theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b := by rw [infi_insert, infi_singleton] theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b := @infi_singleton αᵒᵈ _ _ _ _ theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b := by rw [supr_insert, supr_singleton] lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) := by rw [← Inf_image, ← Inf_image, ← image_comp] lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} : (⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) := @infi_image αᵒᵈ _ _ _ _ _ _ theorem supr_extend_bot {e : ι → β} (he : injective e) (f : ι → α) : (⨆ j, extend e f ⊥ j) = ⨆ i, f i := begin rw supr_split _ (λ j, ∃ i, e i = j), simp [extend_apply he, extend_apply', @supr_comm _ β ι] { contextual := tt } end /-! ### `supr` and `infi` under `Type` -/ theorem supr_of_empty' {α ι} [has_Sup α] [is_empty ι] (f : ι → α) : supr f = Sup (∅ : set α) := congr_arg Sup (range_eq_empty f) theorem supr_of_empty [is_empty ι] (f : ι → α) : supr f = ⊥ := (supr_of_empty' f).trans Sup_empty theorem infi_of_empty' {α ι} [has_Inf α] [is_empty ι] (f : ι → α) : infi f = Inf (∅ : set α) := congr_arg Inf (range_eq_empty f) theorem infi_of_empty [is_empty ι] (f : ι → α) : infi f = ⊤ := @supr_of_empty αᵒᵈ _ _ _ f lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff := by rw [supr, bool.range_eq, Sup_pair, sup_comm] lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff := @supr_bool_eq αᵒᵈ _ _ lemma sup_eq_supr (x y : α) : x ⊔ y = ⨆ b : bool, cond b x y := by rw [supr_bool_eq, bool.cond_tt, bool.cond_ff] lemma inf_eq_infi (x y : α) : x ⊓ y = ⨅ b : bool, cond b x y := @sup_eq_supr αᵒᵈ _ _ _ lemma is_glb_binfi {s : set β} {f : β → α} : is_glb (f '' s) (⨅ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, infi_subtype'] using @is_glb_infi α s _ (f ∘ coe) theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) := @infi_subtype αᵒᵈ _ _ _ _ lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} : (⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x x.property) := (@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm lemma supr_subtype'' {ι} (s : set ι) (f : ι → α) : (⨆ i : s, f i) = ⨆ (t : ι) (H : t ∈ s), f t := supr_subtype lemma is_lub_bsupr {s : set β} {f : β → α} : is_lub (f '' s) (⨆ x ∈ s, f x) := by simpa only [range_comp, subtype.range_coe, supr_subtype'] using @is_lub_supr α s _ (f ∘ coe) theorem infi_sigma {p : β → Type*} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h : p i), f ⟨i, h⟩) := eq_of_forall_le_iff $ λ c, by simp only [le_infi_iff, sigma.forall] theorem supr_sigma {p : β → Type*} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h : p i), f ⟨i, h⟩) := @infi_sigma αᵒᵈ _ _ _ _ theorem infi_prod {γ : Type*} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) := eq_of_forall_le_iff $ λ c, by simp only [le_infi_iff, prod.forall] theorem supr_prod {γ : Type*} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) := @infi_prod αᵒᵈ _ _ _ _ theorem infi_sum {γ : Type*} {f : β ⊕ γ → α} : (⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) := eq_of_forall_le_iff $ λ c, by simp only [le_inf_iff, le_infi_iff, sum.forall] theorem supr_sum {γ : Type*} {f : β ⊕ γ → α} : (⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) := @infi_sum αᵒᵈ _ _ _ _ theorem supr_option (f : option β → α) : (⨆ o, f o) = f none ⊔ ⨆ b, f (option.some b) := eq_of_forall_ge_iff $ λ c, by simp only [supr_le_iff, sup_le_iff, option.forall] theorem infi_option (f : option β → α) : (⨅ o, f o) = f none ⊓ ⨅ b, f (option.some b) := @supr_option αᵒᵈ _ _ _ /-- A version of `supr_option` useful for rewriting right-to-left. -/ lemma supr_option_elim (a : α) (f : β → α) : (⨆ o : option β, o.elim a f) = a ⊔ ⨆ b, f b := by simp [supr_option] /-- A version of `infi_option` useful for rewriting right-to-left. -/ lemma infi_option_elim (a : α) (f : β → α) : (⨅ o : option β, o.elim a f) = a ⊓ ⨅ b, f b := @supr_option_elim αᵒᵈ _ _ _ _ /-- When taking the supremum of `f : ι → α`, the elements of `ι` on which `f` gives `⊥` can be dropped, without changing the result. -/ lemma supr_ne_bot_subtype (f : ι → α) : (⨆ i : {i // f i ≠ ⊥}, f i) = ⨆ i, f i := begin by_cases htriv : ∀ i, f i = ⊥, { simp only [htriv, supr_bot] }, refine le_antisymm (supr_comp_le f _) (supr_mono' _), intros i, by_cases hi : f i = ⊥, { rw hi, obtain ⟨i₀, hi₀⟩ := not_forall.mp htriv, exact ⟨⟨i₀, hi₀⟩, bot_le⟩ }, { exact ⟨⟨i, hi⟩, rfl.le⟩ }, end /-- When taking the infimum of `f : ι → α`, the elements of `ι` on which `f` gives `⊤` can be dropped, without changing the result. -/ lemma infi_ne_top_subtype (f : ι → α) : (⨅ i : {i // f i ≠ ⊤}, f i) = ⨅ i, f i := @supr_ne_bot_subtype αᵒᵈ ι _ f /-! ### `supr` and `infi` under `ℕ` -/ lemma supr_ge_eq_supr_nat_add {u : ℕ → α} (n : ℕ) : (⨆ i ≥ n, u i) = ⨆ i, u (i + n) := begin apply le_antisymm; simp only [supr_le_iff], { exact λ i hi, le_Sup ⟨i - n, by { dsimp only, rw tsub_add_cancel_of_le hi }⟩ }, { exact λ i, le_Sup ⟨i + n, supr_pos (nat.le_add_left _ _)⟩ } end lemma infi_ge_eq_infi_nat_add {u : ℕ → α} (n : ℕ) : (⨅ i ≥ n, u i) = ⨅ i, u (i + n) := @supr_ge_eq_supr_nat_add αᵒᵈ _ _ _ lemma monotone.supr_nat_add {f : ℕ → α} (hf : monotone f) (k : ℕ) : (⨆ n, f (n + k)) = ⨆ n, f n := le_antisymm (supr_le $ λ i, le_supr _ (i + k)) $ supr_mono $ λ i, hf $ nat.le_add_right i k @[simp] lemma supr_infi_ge_nat_add (f : ℕ → α) (k : ℕ) : (⨆ n, ⨅ i ≥ n, f (i + k)) = ⨆ n, ⨅ i ≥ n, f i := begin have hf : monotone (λ n, ⨅ i ≥ n, f i) := λ n m h, binfi_mono (λ i, h.trans), rw ←monotone.supr_nat_add hf k, { simp_rw [infi_ge_eq_infi_nat_add, ←nat.add_assoc], }, end lemma sup_supr_nat_succ (u : ℕ → α) : u 0 ⊔ (⨆ i, u (i + 1)) = ⨆ i, u i := begin refine eq_of_forall_ge_iff (λ c, _), simp only [sup_le_iff, supr_le_iff], refine ⟨λ h, _, λ h, ⟨h _, λ i, h _⟩⟩, rintro (_|i), exacts [h.1, h.2 i] end lemma inf_infi_nat_succ (u : ℕ → α) : u 0 ⊓ (⨅ i, u (i + 1)) = ⨅ i, u i := @sup_supr_nat_succ αᵒᵈ _ u end section complete_linear_order variables [complete_linear_order α] lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀ b <⊤, ∃ i, b < f i) := by simp only [← Sup_range, Sup_eq_top, set.exists_range_iff] lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀ b > ⊥, ∃ i, f i < b) := by simp only [← Inf_range, Inf_eq_bot, set.exists_range_iff] end complete_linear_order /-! ### Instances -/ instance Prop.complete_lattice : complete_lattice Prop := { Sup := λ s, ∃ a ∈ s, a, le_Sup := λ s a h p, ⟨a, h, p⟩, Sup_le := λ s a h ⟨b, h', p⟩, h b h' p, Inf := λ s, ∀ a, a ∈ s → a, Inf_le := λ s a h p, p a h, le_Inf := λ s a h p b hb, h b hb p, .. Prop.bounded_order, .. Prop.distrib_lattice } noncomputable instance Prop.complete_linear_order : complete_linear_order Prop := { ..Prop.complete_lattice, ..Prop.linear_order } @[simp] lemma Sup_Prop_eq {s : set Prop} : Sup s = ∃ p ∈ s, p := rfl @[simp] lemma Inf_Prop_eq {s : set Prop} : Inf s = ∀ p ∈ s, p := rfl @[simp] lemma infi_Prop_eq {p : ι → Prop} : (⨅ i, p i) = ∀ i, p i := le_antisymm (λ h i, h _ ⟨i, rfl⟩ ) (λ h p ⟨i, eq⟩, eq ▸ h i) @[simp] lemma supr_Prop_eq {p : ι → Prop} : (⨆ i, p i) = ∃ i, p i := le_antisymm (λ ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (λ ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩) instance pi.has_Sup {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] : has_Sup (Π i, β i) := ⟨λ s i, ⨆ f : s, (f : Π i, β i) i⟩ instance pi.has_Inf {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] : has_Inf (Π i, β i) := ⟨λ s i, ⨅ f : s, (f : Π i, β i) i⟩ instance pi.complete_lattice {α : Type*} {β : α → Type*} [∀ i, complete_lattice (β i)] : complete_lattice (Π i, β i) := { Sup := Sup, Inf := Inf, le_Sup := λ s f hf i, le_supr (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Inf_le := λ s f hf i, infi_le (λ f : s, (f : Π i, β i) i) ⟨f, hf⟩, Sup_le := λ s f hf i, supr_le $ λ g, hf g g.2 i, le_Inf := λ s f hf i, le_infi $ λ g, hf g g.2 i, .. pi.bounded_order, .. pi.lattice } lemma Inf_apply {α : Type*} {β : α → Type*} [Π i, has_Inf (β i)] {s : set (Π a, β a)} {a : α} : (Inf s) a = (⨅ f : s, (f : Π a, β a) a) := rfl @[simp] lemma infi_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Inf (β i)] {f : ι → Π a, β a} {a : α} : (⨅ i, f i) a = ⨅ i, f i a := by rw [infi, Inf_apply, infi, infi, ← image_eq_range (λ f : Π i, β i, f a) (range f), ← range_comp] lemma Sup_apply {α : Type*} {β : α → Type*} [Π i, has_Sup (β i)] {s : set (Πa, β a)} {a : α} : (Sup s) a = (⨆ f : s, (f : Π a, β a) a) := rfl lemma unary_relation_Sup_iff {α : Type*} (s : set (α → Prop)) {a : α} : Sup s a ↔ ∃ (r : α → Prop), r ∈ s ∧ r a := by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] } lemma binary_relation_Sup_iff {α β : Type*} (s : set (α → β → Prop)) {a : α} {b : β} : Sup s a b ↔ ∃ (r : α → β → Prop), r ∈ s ∧ r a b := by { change (∃ _, _) ↔ _, simp [-eq_iff_iff] } @[simp] lemma supr_apply {α : Type*} {β : α → Type*} {ι : Sort*} [Π i, has_Sup (β i)] {f : ι → Π a, β a} {a : α} : (⨆ i, f i) a = (⨆ i, f i a) := @infi_apply α (λ i, (β i)ᵒᵈ) _ _ f a section complete_lattice variables [preorder α] [complete_lattice β] theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀ f ∈ s, monotone f) : monotone (Sup s) := λ x y h, supr_mono $ λ f, m_s f f.2 h theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀ f ∈ s, monotone f) : monotone (Inf s) := λ x y h, infi_mono $ λ f, m_s f f.2 h end complete_lattice namespace prod variables (α β) instance [has_Inf α] [has_Inf β] : has_Inf (α × β) := ⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩ instance [has_Sup α] [has_Sup β] : has_Sup (α × β) := ⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩ instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) := { le_Sup := λ s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩, Sup_le := λ s p h, ⟨ Sup_le $ ball_image_of_ball $ λ p hp, (h p hp).1, Sup_le $ ball_image_of_ball $ λ p hp, (h p hp).2⟩, Inf_le := λ s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩, le_Inf := λ s p h, ⟨ le_Inf $ ball_image_of_ball $ λ p hp, (h p hp).1, le_Inf $ ball_image_of_ball $ λ p hp, (h p hp).2⟩, .. prod.lattice α β, .. prod.bounded_order α β, .. prod.has_Sup α β, .. prod.has_Inf α β } end prod section complete_lattice variables [complete_lattice α] {a : α} {s : set α} /-- This is a weaker version of `sup_Inf_eq` -/ lemma sup_Inf_le_infi_sup : a ⊔ Inf s ≤ ⨅ b ∈ s, a ⊔ b := le_infi₂ $ λ i h, sup_le_sup_left (Inf_le h) _ /-- This is a weaker version of `Inf_sup_eq` -/ lemma Inf_sup_le_infi_sup : Inf s ⊔ a ≤ ⨅ b ∈ s, b ⊔ a := le_infi₂ $ λ i h, sup_le_sup_right (Inf_le h) _ /-- This is a weaker version of `inf_Sup_eq` -/ lemma supr_inf_le_inf_Sup : (⨆ b ∈ s, a ⊓ b) ≤ a ⊓ Sup s := supr₂_le $ λ i h, inf_le_inf_left _ (le_Sup h) /-- This is a weaker version of `Sup_inf_eq` -/ lemma supr_inf_le_Sup_inf : (⨆ b ∈ s, b ⊓ a) ≤ Sup s ⊓ a := supr₂_le $ λ i h, inf_le_inf_right _ (le_Sup h) lemma disjoint_Sup_left {a : set α} {b : α} (d : disjoint (Sup a) b) {i} (hi : i ∈ a) : disjoint i b := (supr₂_le_iff.1 (supr_inf_le_Sup_inf.trans d) i hi : _) lemma disjoint_Sup_right {a : set α} {b : α} (d : disjoint b (Sup a)) {i} (hi : i ∈ a) : disjoint b i := (supr₂_le_iff.mp (supr_inf_le_inf_Sup.trans d) i hi : _) end complete_lattice /-- Pullback a `complete_lattice` along an injection. -/ @[reducible] -- See note [reducible non-instances] protected def function.injective.complete_lattice [has_sup α] [has_inf α] [has_Sup α] [has_Inf α] [has_top α] [has_bot α] [complete_lattice β] (f : α → β) (hf : function.injective f) (map_sup : ∀ a b, f (a ⊔ b) = f a ⊔ f b) (map_inf : ∀ a b, f (a ⊓ b) = f a ⊓ f b) (map_Sup : ∀ s, f (Sup s) = ⨆ a ∈ s, f a) (map_Inf : ∀ s, f (Inf s) = ⨅ a ∈ s, f a) (map_top : f ⊤ = ⊤) (map_bot : f ⊥ = ⊥) : complete_lattice α := { Sup := Sup, le_Sup := λ s a h, (le_supr₂ a h).trans (map_Sup _).ge, Sup_le := λ s a h, (map_Sup _).trans_le $ supr₂_le h, Inf := Inf, Inf_le := λ s a h, (map_Inf _).trans_le $ infi₂_le a h, le_Inf := λ s a h, (le_infi₂ h).trans (map_Inf _).ge, -- we cannot use bounded_order.lift here as the `has_le` instance doesn't exist yet top := ⊤, le_top := λ a, (@le_top β _ _ _).trans map_top.ge, bot := ⊥, bot_le := λ a, map_bot.le.trans bot_le, ..hf.lattice f map_sup map_inf }
3df0c06ee8c8f3062994ee9e3ded6e89c89d9da7
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/linear_algebra/linear_independent.lean
e8878eca6ff359ca58e9de1ec2ef80fe4b87c5a1
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
56,533
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp, Anne Baanen -/ import linear_algebra.finsupp import linear_algebra.prod import data.equiv.fin import set_theory.cardinal /-! # Linear independence This file defines linear independence in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define `linear_independent R v` as `ker (finsupp.total ι M R v) = ⊥`. Here `finsupp.total` is the linear map sending a function `f : ι →₀ R` with finite support to the linear combination of vectors from `v` with these coefficients. Then we prove that several other statements are equivalent to this one, including injectivity of `finsupp.total ι M R v` and some versions with explicitly written linear combinations. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. ## Main statements We prove several specialized tests for linear independence of families of vectors and of sets of vectors. * `fintype.linear_independent_iff`: if `ι` is a finite type, then any function `f : ι → R` has finite support, so we can reformulate the statement using `∑ i : ι, f i • v i` instead of a sum over an auxiliary `s : finset ι`; * `linear_independent_empty_type`: a family indexed by an empty type is linearly independent; * `linear_independent_unique_iff`: if `ι` is a singleton, then `linear_independent K v` is equivalent to `v (default ι) ≠ 0`; * linear_independent_option`, `linear_independent_sum`, `linear_independent_fin_cons`, `linear_independent_fin_succ`: type-specific tests for linear independence of families of vector fields; * `linear_independent_insert`, `linear_independent_union`, `linear_independent_pair`, `linear_independent_singleton`: linear independence tests for set operations. In many cases we additionally provide dot-style operations (e.g., `linear_independent.union`) to make the linear independence tests usable as `hv.insert ha` etc. We also prove that, when working over a field, any family of vectors includes a linear independent subfamily spanning the same subspace. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence -/ noncomputable theory open function set submodule open_locale classical big_operators universes u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [semiring R] [add_comm_monoid M] [add_comm_monoid M'] [add_comm_monoid M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} variables (R) (v) /-- `linear_independent R v` states the family of vectors `v` is linearly independent over `R`. -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, (∑ i in s, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, not_forall], end theorem fintype.linear_independent_iff [fintype ι] : linear_independent R v ↔ ∀ g : ι → R, ∑ i, g i • v i = 0 → ∀ i, g i = 0 := begin refine ⟨λ H g, by simpa using linear_independent_iff'.1 H finset.univ g, λ H, linear_independent_iff''.2 $ λ s g hg hs i, H _ _ _⟩, rw ← hs, refine (finset.sum_subset (finset.subset_univ _) (λ i _ hi, _)).symm, rw [hg i hi, zero_smul] end /-- A finite family of vectors `v i` is linear independent iff the linear map that sends `c : ι → R` to `∑ i, c i • v i` has the trivial kernel. -/ theorem fintype.linear_independent_iff' [fintype ι] : linear_independent R v ↔ (linear_map.lsum R (λ i : ι, R) ℕ (λ i, linear_map.id.smul_right (v i))).ker = ⊥ := by simp [fintype.linear_independent_iff, linear_map.ker_eq_bot', funext_iff] lemma linear_independent_empty_type [is_empty ι] : linear_independent R v := linear_independent_iff.mpr $ λ v hv, subsingleton.elim v 0 lemma linear_independent.ne_zero [nontrivial R] (i : ι) (hv : linear_independent R v) : v i ≠ 0 := λ h, @zero_ne_one R _ _ $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), { simp }, { simp [h] } end /-- A subfamily of a linearly independent family (i.e., a composition with an injective map) is a linearly independent family. -/ lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext x, convert h_map_domain x, rw [finsupp.map_domain_apply hf] end lemma linear_independent.coe_range (i : linear_independent R v) : linear_independent R (coe : range v → M) := by simpa using i.comp _ (range_splitting_injective v) /-- If `v` is a linearly independent family of vectors and the kernel of a linear map `f` is disjoint with the submodule spanned by the vectors of `v`, then `f ∘ v` is a linearly independent family of vectors. See also `linear_independent.map'` for a special case assuming `ker f = ⊥`. -/ lemma linear_independent.map (hv : linear_independent R v) {f : M →ₗ[R] M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_image_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv ⊢, rw [hv, le_bot_iff] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [finsupp.total_comp, @finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, linear_map.ker_comp, hf_inj], exact λ _, rfl, end /-- An injective linear map sends linearly independent families of vectors to linearly independent families of vectors. See also `linear_independent.map` for a more general statement. -/ lemma linear_independent.map' (hv : linear_independent R v) (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) := hv.map $ by simp [hf_inj] /-- If the image of a family of vectors under a linear map is linearly independent, then so is the original family. -/ lemma linear_independent.of_comp (f : M →ₗ[R] M') (hfv : linear_independent R (f ∘ v)) : linear_independent R v := linear_independent_iff'.2 $ λ s g hg i his, have ∑ (i : ι) in s, g i • f (v i) = 0, by simp_rw [← f.map_smul, ← f.map_sum, hg, f.map_zero], linear_independent_iff'.1 hfv s g this i his /-- If `f` is an injective linear map, then the family `f ∘ v` is linearly independent if and only if the family `v` is linearly independent. -/ protected lemma linear_map.linear_independent_iff (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) ↔ linear_independent R v := ⟨λ h, h.of_comp f, λ h, h.map $ by simp only [hf_inj, disjoint_bot_right]⟩ @[nontriviality] lemma linear_independent_of_subsingleton [subsingleton R] : linear_independent R v := linear_independent_iff.2 (λ l hl, subsingleton.elim _ _) theorem linear_independent_equiv (e : ι ≃ ι') {f : ι' → M} : linear_independent R (f ∘ e) ↔ linear_independent R f := ⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, λ h, h.comp _ e.injective⟩ theorem linear_independent_equiv' (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ e = g) : linear_independent R g ↔ linear_independent R f := h ▸ linear_independent_equiv e theorem linear_independent_subtype_range {ι} {f : ι → M} (hf : injective f) : linear_independent R (coe : range f → M) ↔ linear_independent R f := iff.symm $ linear_independent_equiv' (equiv.of_injective f hf) rfl alias linear_independent_subtype_range ↔ linear_independent.of_subtype_range _ theorem linear_independent_image {ι} {s : set ι} {f : ι → M} (hf : set.inj_on f s) : linear_independent R (λ x : s, f x) ↔ linear_independent R (λ x : f '' s, (x : M)) := linear_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := linear_independent.of_comp (span R (range v)).subtype hs /-- See `linear_independent.fin_cons` for a family of elements in a vector space. -/ lemma linear_independent.fin_cons' {m : ℕ} (x : M) (v : fin m → M) (hli : linear_independent R v) (x_ortho : (∀ (c : R) (y : submodule.span R (set.range v)), c • x + y = (0 : M) → c = 0)) : linear_independent R (fin.cons x v : fin m.succ → M) := begin rw fintype.linear_independent_iff at hli ⊢, rintros g total_eq j, have zero_not_mem : (0 : fin m.succ) ∉ finset.univ.image (fin.succ : fin m → fin m.succ), { rw finset.mem_image, rintro ⟨x, hx, succ_eq⟩, exact fin.succ_ne_zero _ succ_eq }, simp only [submodule.coe_mk, fin.univ_succ, finset.sum_insert zero_not_mem, fin.cons_zero, fin.cons_succ, forall_true_iff, imp_self, fin.succ_inj, finset.sum_image] at total_eq, have : g 0 = 0, { refine x_ortho (g 0) ⟨∑ (i : fin m), g i.succ • v i, _⟩ total_eq, exact sum_mem _ (λ i _, smul_mem _ _ (subset_span ⟨i, rfl⟩)) }, refine fin.cases this (λ j, _) j, apply hli (λ i, g i.succ), simpa only [this, zero_smul, zero_add] using total_eq end /-- A set of linearly independent vectors in a module `M` over a semiring `K` is also linearly independent over a subring `R` of `K`. The implementation uses minimal assumptions about the relationship between `R`, `K` and `M`. The version where `K` is an `R`-algebra is `linear_independent.restrict_scalars_algebras`. -/ lemma linear_independent.restrict_scalars [semiring K] [smul_with_zero R K] [module K M] [is_scalar_tower R K M] (hinj : function.injective (λ r : R, r • (1 : K))) (li : linear_independent K v) : linear_independent R v := begin refine linear_independent_iff'.mpr (λ s g hg i hi, hinj (eq.trans _ (zero_smul _ _).symm)), refine (linear_independent_iff'.mp li : _) _ _ _ i hi, simp_rw [smul_assoc, one_smul], exact hg, end /-- Every finite subset of a linearly independent set is linearly independent. -/ lemma linear_independent_finset_map_embedding_subtype (s : set M) (li : linear_independent R (coe : s → M)) (t : finset s) : linear_independent R (coe : (finset.map (embedding.subtype s) t) → M) := begin let f : t.map (embedding.subtype s) → s := λ x, ⟨x.1, begin obtain ⟨x, h⟩ := x, rw [finset.mem_map] at h, obtain ⟨a, ha, rfl⟩ := h, simp only [subtype.coe_prop, embedding.coe_subtype], end⟩, convert linear_independent.comp li f _, rintros ⟨x, hx⟩ ⟨y, hy⟩, rw [finset.mem_map] at hx hy, obtain ⟨a, ha, rfl⟩ := hx, obtain ⟨b, hb, rfl⟩ := hy, simp only [imp_self, subtype.mk_eq_mk], end /-- If every finite set of linearly independent vectors has cardinality at most `n`, then the same is true for arbitrary sets of linearly independent vectors. -/ lemma linear_independent_bounded_of_finset_linear_independent_bounded {n : ℕ} (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) : ∀ s : set M, linear_independent R (coe : s → M) → cardinal.mk s ≤ n := begin intros s li, apply cardinal.card_le_of, intro t, rw ← finset.card_map (embedding.subtype s), apply H, apply linear_independent_finset_map_embedding_subtype _ li, end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin simp only [linear_independent_iff, (∘), finsupp.mem_supported, finsupp.total_apply, set.subset_def, finset.mem_coe], split, { intros h l hl₁ hl₂, have := h (l.subtype_domain s) ((finsupp.sum_subtype_domain_index hl₁).trans hl₂), exact (finsupp.subtype_domain_eq_zero_iff hl₁).1 this }, { intros h l hl, refine finsupp.emb_domain_eq_zero.1 (h (l.emb_domain $ function.embedding.subtype s) _ _), { suffices : ∀ i hi, ¬l ⟨i, hi⟩ = 0 → i ∈ s, by simpa, intros, assumption }, { rwa [finsupp.emb_domain_eq_map_domain, finsupp.sum_map_domain_index], exacts [λ _, zero_smul _ _, λ _ _ _, add_smul _ _ _] } } end lemma linear_dependent_comp_subtype' {s : set ι} : ¬ linear_independent R (v ∘ coe : s → M) ↔ ∃ f : ι →₀ R, f ∈ finsupp.supported R R s ∧ finsupp.total ι M R v f = 0 ∧ f ≠ 0 := by simp [linear_independent_comp_subtype] /-- A version of `linear_dependent_comp_subtype'` with `finsupp.total` unfolded. -/ lemma linear_dependent_comp_subtype {s : set ι} : ¬ linear_independent R (v ∘ coe : s → M) ↔ ∃ f : ι →₀ R, f ∈ finsupp.supported R R s ∧ ∑ i in f.support, f i • v i = 0 ∧ f ≠ 0 := linear_dependent_comp_subtype' theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := hs variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { resetI, refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) end subtype end module /-! ### Properties which require `ring R` -/ section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} theorem linear_independent_iff_injective_total : linear_independent R v ↔ function.injective (finsupp.total ι M R v) := linear_independent_iff.trans (finsupp.total ι M R v).to_add_monoid_hom.injective_iff.symm alias linear_independent_iff_injective_total ↔ linear_independent.injective_total _ lemma linear_independent.injective [nontrivial R] (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [hij] }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, simpa [finsupp.single_eq_single_iff] using h_single_eq end theorem linear_independent.to_subtype_range {ι} {f : ι → M} (hf : linear_independent R f) : linear_independent R (coe : range f → M) := begin nontriviality R, exact (linear_independent_subtype_range hf.injective).2 hf end theorem linear_independent.to_subtype_range' {ι} {f : ι → M} (hf : linear_independent R f) {t} (ht : range f = t) : linear_independent R (coe : t → M) := ht ▸ hf.to_subtype_range theorem linear_independent.image_of_comp {ι ι'} (s : set ι) (f : ι → ι') (g : ι' → M) (hs : linear_independent R (λ x : s, g (f x))) : linear_independent R (λ x : f '' s, g x) := begin nontriviality R, have : inj_on f s, from inj_on_iff_injective.2 hs.injective.of_comp, exact (linear_independent_equiv' (equiv.set.image_of_inj_on f s this) rfl).1 hs end theorem linear_independent.image {ι} {s : set ι} {f : ι → M} (hs : linear_independent R (λ x : s, f x)) : linear_independent R (λ x : f '' s, (x : M)) := by convert linear_independent.image_of_comp s f id hs lemma linear_independent.group_smul {G : Type*} [hG : group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] {v : ι → M} (hv : linear_independent R v) (w : ι → G) : linear_independent R (w • v) := begin rw linear_independent_iff'' at hv ⊢, intros s g hgs hsum i, refine (smul_eq_zero_iff_eq (w i)).1 _, refine hv s (λ i, w i • g i) (λ i hi, _) _ i, { dsimp only, exact (hgs i hi).symm ▸ smul_zero _ }, { rw [← hsum, finset.sum_congr rfl _], intros, erw [pi.smul_apply, smul_assoc, smul_comm] }, end -- This lemma cannot be proved with `linear_independent.group_smul` since the action of -- `units R` on `R` is not commutative. lemma linear_independent.units_smul {v : ι → M} (hv : linear_independent R v) (w : ι → units R) : linear_independent R (w • v) := begin rw linear_independent_iff'' at hv ⊢, intros s g hgs hsum i, rw ← (w i).mul_left_eq_zero, refine hv s (λ i, g i • w i) (λ i hi, _) _ i, { dsimp only, exact (hgs i hi).symm ▸ zero_smul _ _ }, { rw [← hsum, finset.sum_congr rfl _], intros, erw [pi.smul_apply, smul_assoc], refl } end section maximal universes v w /-- A linearly independent family is maximal if there is no strictly larger linearly independent family. -/ @[nolint unused_arguments] def linear_independent.maximal {ι : Type w} {R : Type u} [semiring R] {M : Type v} [add_comm_monoid M] [module R M] {v : ι → M} (i : linear_independent R v) : Prop := ∀ (s : set M) (i' : linear_independent R (coe : s → M)) (h : range v ≤ s), range v = s /-- An alternative characterization of a maximal linearly independent family, quantifying over types (in the same universe as `M`) into which the indexing family injects. -/ lemma linear_independent.maximal_iff {ι : Type w} {R : Type u} [ring R] [nontrivial R] {M : Type v} [add_comm_group M] [module R M] {v : ι → M} (i : linear_independent R v) : i.maximal ↔ ∀ (κ : Type v) (w : κ → M) (i' : linear_independent R w) (j : ι → κ) (h : w ∘ j = v), surjective j := begin fsplit, { rintros p κ w i' j rfl, specialize p (range w) i'.coe_range (range_comp_subset_range _ _), rw [range_comp, ←@image_univ _ _ w] at p, exact range_iff_surjective.mp (image_injective.mpr i'.injective p), }, { intros p w i' h, specialize p w (coe : w → M) i' (λ i, ⟨v i, range_subset_iff.mp h i⟩) (by { ext, simp, }), have q := congr_arg (λ s, (coe : w → M) '' s) p.range_eq, dsimp at q, rw [←image_univ, image_image] at q, simpa using q, }, end end maximal /-- Linear independent families are injective, even if you multiply either side. -/ lemma linear_independent.eq_of_smul_apply_eq_smul_apply {M : Type*} [add_comm_group M] [module R M] {v : ι → M} (li : linear_independent R v) (c d : R) (i j : ι) (hc : c ≠ 0) (h : c • v i = d • v j) : i = j := begin let l : ι →₀ R := finsupp.single i c - finsupp.single j d, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [h] }, have h_single_eq : finsupp.single i c = finsupp.single j d, { rw linear_independent_iff at li, simp [eq_add_of_sub_eq' (li l h_total)] }, rcases (finsupp.single_eq_single_iff _ _ _ _).mp h_single_eq with ⟨this, _⟩ | ⟨hc, _⟩, { exact this }, { contradiction }, end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ lemma linear_independent.disjoint_span_image (hv : linear_independent R v) {s t : set ι} (hs : disjoint s t) : disjoint (submodule.span R $ v '' s) (submodule.span R $ v '' t) := begin simp only [disjoint_def, finsupp.mem_span_image_iff_total], rintros _ ⟨l₁, hl₁, rfl⟩ ⟨l₂, hl₂, H⟩, rw [hv.injective_total.eq_iff] at H, subst l₂, have : l₁ = 0 := finsupp.disjoint_supported_supported hs (submodule.mem_inf.2 ⟨hl₁, hl₂⟩), simp [this] end lemma linear_independent.not_mem_span_image [nontrivial R] (hv : linear_independent R v) {s : set ι} {x : ι} (h : x ∉ s) : v x ∉ submodule.span R (v '' s) := begin have h' : v x ∈ submodule.span R (v '' {x}), { rw set.image_singleton, exact mem_span_singleton_self (v x), }, intro w, apply linear_independent.ne_zero x hv, refine disjoint_def.1 (hv.disjoint_span_image _) (v x) h' w, simpa using h, end lemma linear_independent.total_ne_of_not_mem_support [nontrivial R] (hv : linear_independent R v) {x : ι} (f : ι →₀ R) (h : x ∉ f.support) : finsupp.total ι M R v f ≠ v x := begin replace h : x ∉ (f.support : set ι) := h, have p := hv.not_mem_span_image h, intro w, rw ←w at p, rw finsupp.span_image_eq_map_total at p, simp only [not_exists, not_and, mem_map] at p, exact p f (f.mem_supported_support R) rfl, end lemma linear_independent_sum {v : ι ⊕ ι' → M} : linear_independent R v ↔ linear_independent R (v ∘ sum.inl) ∧ linear_independent R (v ∘ sum.inr) ∧ disjoint (submodule.span R (range (v ∘ sum.inl))) (submodule.span R (range (v ∘ sum.inr))) := begin rw [range_comp v, range_comp v], refine ⟨λ h, ⟨h.comp _ sum.inl_injective, h.comp _ sum.inr_injective, h.disjoint_span_image is_compl_range_inl_range_inr.1⟩, _⟩, rintro ⟨hl, hr, hlr⟩, rw [linear_independent_iff'] at *, intros s g hg i hi, have : ∑ i in s.preimage sum.inl (sum.inl_injective.inj_on _), (λ x, g x • v x) (sum.inl i) + ∑ i in s.preimage sum.inr (sum.inr_injective.inj_on _), (λ x, g x • v x) (sum.inr i) = 0, { rw [finset.sum_preimage', finset.sum_preimage', ← finset.sum_union, ← finset.filter_or], { simpa only [← mem_union, range_inl_union_range_inr, mem_univ, finset.filter_true] }, { exact finset.disjoint_filter.2 (λ x hx, disjoint_left.1 is_compl_range_inl_range_inr.1) } }, { rw ← eq_neg_iff_add_eq_zero at this, rw [disjoint_def'] at hlr, have A := hlr _ (sum_mem _ $ λ i hi, _) _ (neg_mem _ $ sum_mem _ $ λ i hi, _) this, { cases i with i i, { exact hl _ _ A i (finset.mem_preimage.2 hi) }, { rw [this, neg_eq_zero] at A, exact hr _ _ A i (finset.mem_preimage.2 hi) } }, { exact smul_mem _ _ (subset_span ⟨sum.inl i, mem_range_self _, rfl⟩) }, { exact smul_mem _ _ (subset_span ⟨sum.inr i, mem_range_self _, rfl⟩) } } end lemma linear_independent.sum_type {v' : ι' → M} (hv : linear_independent R v) (hv' : linear_independent R v') (h : disjoint (submodule.span R (range v)) (submodule.span R (range v'))) : linear_independent R (sum.elim v v') := linear_independent_sum.2 ⟨hv, hv', h⟩ lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := (hs.sum_type ht $ by simpa).to_subtype_range' $ by simp lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, { apply directed_of_sup, exact (λ t₁ t₂ ht, Union_subset_Union $ λ i, Union_subset_Union_const $ λ h, ht h) }, assume t, induction t using finset.induction_on with i s his ih, { refine (linear_independent_empty _ _).mono _, simp }, { rw [finset.set_bUnion_insert], refine (hl _).union ih _, refine (hd i s s.finite_to_set his).mono_right _, simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), exact λ i, ⟨i, le_rfl⟩ } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin nontriviality R, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero _ h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ @[simps] def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range_eq_map, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm @[simp] lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end lemma linear_independent.span_repr_eq [nontrivial R] (x) : span.repr R (set.range v) x = (hv.repr x).equiv_map_domain (equiv.of_injective _ hv.injective) := begin have p : (span.repr R (set.range v) x).equiv_map_domain (equiv.of_injective _ hv.injective).symm = hv.repr x, { apply (linear_independent.total_equiv hv).injective, ext, simp, }, ext ⟨_, ⟨i, rfl⟩⟩, simp [←p], end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_image_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_image_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ variable (R) lemma exists_maximal_independent' (s : ι → M) : ∃ I : set ι, linear_independent R (λ x : I, s x) ∧ ∀ J : set ι, I ⊆ J → linear_independent R (λ x : J, s x) → I = J := begin let indep : set ι → Prop := λ I, linear_independent R (s ∘ coe : I → M), let X := { I : set ι // indep I }, let r : X → X → Prop := λ I J, I.1 ⊆ J.1, have key : ∀ c : set X, zorn.chain r c → indep (⋃ (I : X) (H : I ∈ c), I), { intros c hc, dsimp [indep], rw [linear_independent_comp_subtype], intros f hsupport hsum, rcases eq_empty_or_nonempty c with rfl | ⟨a, hac⟩, { simpa using hsupport }, haveI : is_refl X r := ⟨λ _, set.subset.refl _⟩, obtain ⟨I, I_mem, hI⟩ : ∃ I ∈ c, (f.support : set ι) ⊆ I := finset.exists_mem_subset_of_subset_bUnion_of_directed_on hac hc.directed_on hsupport, exact linear_independent_comp_subtype.mp I.2 f hI hsum }, have trans : transitive r := λ I J K, set.subset.trans, obtain ⟨⟨I, hli : indep I⟩, hmax : ∀ a, r ⟨I, hli⟩ a → r a ⟨I, hli⟩⟩ := @zorn.exists_maximal_of_chains_bounded _ r (λ c hc, ⟨⟨⋃ I ∈ c, (I : set ι), key c hc⟩, λ I, set.subset_bUnion_of_mem⟩) trans, exact ⟨I, hli, λ J hsub hli, set.subset.antisymm hsub (hmax ⟨J, hli⟩ hsub)⟩, end lemma exists_maximal_independent (s : ι → M) : ∃ I : set ι, linear_independent R (λ x : I, s x) ∧ ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I) := begin classical, rcases exists_maximal_independent' R s with ⟨I, hIlinind, hImaximal⟩, use [I, hIlinind], intros i hi, specialize hImaximal (I ∪ {i}) (by simp), set J := I ∪ {i} with hJ, have memJ : ∀ {x}, x ∈ J ↔ x = i ∨ x ∈ I, by simp [hJ], have hiJ : i ∈ J := by simp, have h := mt hImaximal _, swap, { intro h2, rw h2 at hi, exact absurd hiJ hi }, obtain ⟨f, supp_f, sum_f, f_ne⟩ := linear_dependent_comp_subtype.mp h, have hfi : f i ≠ 0, { contrapose hIlinind, refine linear_dependent_comp_subtype.mpr ⟨f, _, sum_f, f_ne⟩, simp only [finsupp.mem_supported, hJ] at ⊢ supp_f, rintro x hx, refine (memJ.mp (supp_f hx)).resolve_left _, rintro rfl, exact hIlinind (finsupp.mem_support_iff.mp hx) }, use [f i, hfi], have hfi' : i ∈ f.support := finsupp.mem_support_iff.mpr hfi, rw [← finset.insert_erase hfi', finset.sum_insert (finset.not_mem_erase _ _), add_eq_zero_iff_eq_neg] at sum_f, rw sum_f, refine neg_mem _ (sum_mem _ (λ c hc, smul_mem _ _ (subset_span ⟨c, _, rfl⟩))), exact (memJ.mp (supp_f (finset.erase_subset _ _ hc))).resolve_left (finset.ne_of_mem_erase hc), end end repr lemma surjective_of_linear_independent_of_span [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) : surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype [nontrivial R] {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [← @subtype.range_coe _ s] at hf_inj, refine (hs.map hf_inj).to_subtype_range' _, simp [set.range_comp f] end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := (hv.map' (inl R M M') ker_inl).sum_type (hv'.map' (inr R M M') ker_inr) $ begin refine is_compl_range_inl_inr.disjoint.mono _ _; simp only [span_le, range_coe, range_comp_subset_range], end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note -- <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [comm_ring L] [no_zero_divisors L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the -- monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : finset.sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [finset.sum_apply, finset.sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element -- of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span hl hsu htu, span_mono⟩ end module section nontrivial variables [ring R] [nontrivial R] [add_comm_group M] [add_comm_group M'] variables [module R M] [no_zero_smul_divisors R M] [module R M'] variables {v : ι → M} {s t : set M} {x y z : M} lemma linear_independent_unique_iff (v : ι → M) [unique ι] : linear_independent R v ↔ v (default ι) ≠ 0 := begin simp only [linear_independent_iff, finsupp.total_unique, smul_eq_zero], refine ⟨λ h hv, _, λ hv l hl, finsupp.unique_ext $ hl.resolve_right hv⟩, have := h (finsupp.single (default ι) 1) (or.inr hv), exact one_ne_zero (finsupp.single_eq_zero.1 this) end alias linear_independent_unique_iff ↔ _ linear_independent_unique lemma linear_independent_singleton {x : M} (hx : x ≠ 0) : linear_independent R (λ x, x : ({x} : set M) → M) := linear_independent_unique coe hx end nontrivial /-! ### Properties which require `division_ring K` These can be considered generalizations of properties of linear independence in vector spaces. -/ section module variables [division_ring K] [add_comm_group V] [add_comm_group V'] variables [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton' x0] end lemma linear_independent_option' : linear_independent K (λ o, option.cases_on' o x v : option ι → V) ↔ linear_independent K v ∧ (x ∉ submodule.span K (range v)) := begin rw [← linear_independent_equiv (equiv.option_equiv_sum_punit ι).symm, linear_independent_sum, @range_unique _ punit, @linear_independent_unique_iff punit, disjoint_span_singleton], dsimp [(∘)], refine ⟨λ h, ⟨h.1, λ hx, h.2.1 $ h.2.2 hx⟩, λ h, ⟨h.1, _, λ hx, (h.2 hx).elim⟩⟩, rintro rfl, exact h.2 (zero_mem _) end lemma linear_independent.option (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (λ o, option.cases_on' o x v : option ι → V) := linear_independent_option'.2 ⟨hv, hx⟩ lemma linear_independent_option {v : option ι → V} : linear_independent K v ↔ linear_independent K (v ∘ coe : ι → V) ∧ v none ∉ submodule.span K (range (v ∘ coe : ι → V)) := by simp only [← linear_independent_option', option.cases_on'_none_coe] theorem linear_independent_insert' {ι} {s : set ι} {a : ι} {f : ι → V} (has : a ∉ s) : linear_independent K (λ x : insert a s, f x) ↔ linear_independent K (λ x : s, f x) ∧ f a ∉ submodule.span K (f '' s) := by { rw [← linear_independent_equiv ((equiv.option_equiv_sum_punit _).trans (equiv.set.insert has).symm), linear_independent_option], simp [(∘), range_comp f] } theorem linear_independent_insert (hxs : x ∉ s) : linear_independent K (λ b : insert x s, (b : V)) ↔ linear_independent K (λ b : s, (b : V)) ∧ x ∉ submodule.span K s := (@linear_independent_insert' _ _ _ _ _ _ _ _ id hxs).trans $ by simp lemma linear_independent_pair {x y : V} (hx : x ≠ 0) (hy : ∀ a : K, a • x ≠ y) : linear_independent K (coe : ({x, y} : set V) → V) := pair_comm y x ▸ (linear_independent_singleton hx).insert $ mt mem_span_singleton.1 (not_exists.2 hy) lemma linear_independent_fin_cons {n} {v : fin n → V} : linear_independent K (fin.cons x v : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := begin rw [← linear_independent_equiv (fin_succ_equiv n).symm, linear_independent_option], convert iff.rfl, { ext, -- TODO: why doesn't simp use `fin_succ_equiv_symm_coe` here? rw [comp_app, comp_app, fin_succ_equiv_symm_coe, fin.cons_succ] }, { rw [comp_app, fin_succ_equiv_symm_none, fin.cons_zero] }, { ext, rw [comp_app, comp_app, fin_succ_equiv_symm_coe, fin.cons_succ] } end lemma linear_independent_fin_snoc {n} {v : fin n → V} : linear_independent K (fin.snoc v x : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := by rw [fin.snoc_eq_cons_rotate, linear_independent_equiv, linear_independent_fin_cons] /-- See `linear_independent.fin_cons'` for an uglier version that works if you only have a module over a semiring. -/ lemma linear_independent.fin_cons {n} {v : fin n → V} (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (fin.cons x v : fin (n + 1) → V) := linear_independent_fin_cons.2 ⟨hv, hx⟩ lemma linear_independent_fin_succ {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.tail v) ∧ v 0 ∉ submodule.span K (range $ fin.tail v) := by rw [← linear_independent_fin_cons, fin.cons_self_tail] lemma linear_independent_fin_succ' {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.init v) ∧ v (fin.last _) ∉ submodule.span K (range $ fin.init v) := by rw [← linear_independent_fin_snoc, fin.snoc_init_self] lemma linear_independent_fin2 {f : fin 2 → V} : linear_independent K f ↔ f 1 ≠ 0 ∧ ∀ a : K, a • f 1 ≠ f 0 := by rw [linear_independent_fin_succ, linear_independent_unique_iff, range_unique, mem_span_singleton, not_exists, show fin.tail f (default (fin 1)) = f 1, by rw ← fin.succ_zero_eq_one; refl] lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset_nonempty {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end /-- `linear_independent.extend` adds vectors to a linear independent set `s ⊆ t` until it spans all elements of `t`. -/ noncomputable def linear_independent.extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : set V := classical.some (exists_linear_independent hs hst) lemma linear_independent.extend_subset (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : hs.extend hst ⊆ t := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hbt lemma linear_independent.subset_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : s ⊆ hs.extend hst := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hsb lemma linear_independent.subset_span_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : t ⊆ span K (hs.extend hst) := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in htb lemma linear_independent.linear_independent_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : linear_independent K (coe : hs.extend hst → V) := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hli variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ end module
ff1d9a7223933a71d8e9dc07dc49b2e701dd9848
618003631150032a5676f229d13a079ac875ff77
/src/group_theory/subgroup.lean
5a576958413f8aa59b083900e71e4a5e8e7dc2ae
[ "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
29,236
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, Mitchell Rowett, Scott Morrison, Johan Commelin, Mario Carneiro, Michael Howes -/ import group_theory.submonoid open set function variables {G : Type*} {H : Type*} {A : Type*} {a a₁ a₂ b c: G} section group variables [group G] [add_group A] @[to_additive] lemma injective_mul {a : G} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this section prio set_option default_priority 100 -- see Note [default priority] /-- `s` is an additive subgroup: a set containing 0 and closed under addition and negation. -/ class is_add_subgroup (s : set A) extends is_add_submonoid s : Prop := (neg_mem {a} : a ∈ s → -a ∈ s) /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ @[to_additive is_add_subgroup] class is_subgroup (s : set G) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) end prio lemma additive.is_add_subgroup (s : set G) [is_subgroup s] : @is_add_subgroup (additive G) _ s := @is_add_subgroup.mk (additive G) _ _ (additive.is_add_submonoid _) (@is_subgroup.inv_mem _ _ _ _) theorem additive.is_add_subgroup_iff {s : set G} : @is_add_subgroup (additive G) _ s ↔ is_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_subgroup.mk G _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by exactI additive.is_add_subgroup _⟩ lemma multiplicative.is_subgroup (s : set A) [is_add_subgroup s] : @is_subgroup (multiplicative A) _ s := @is_subgroup.mk (multiplicative A) _ _ (multiplicative.is_submonoid _) (@is_add_subgroup.neg_mem _ _ _ _) theorem multiplicative.is_subgroup_iff {s : set A} : @is_subgroup (multiplicative A) _ s ↔ is_add_subgroup s := ⟨by rintro ⟨⟨h₁, h₂⟩, h₃⟩; exact @is_add_subgroup.mk A _ _ ⟨h₁, @h₂⟩ @h₃, λ h, by exactI multiplicative.is_subgroup _⟩ @[to_additive add_group] instance subtype.group {s : set G} [is_subgroup s] : group s := { inv := λ x, ⟨(x:G)⁻¹, is_subgroup.inv_mem x.2⟩, mul_left_inv := λ x, subtype.eq $ mul_left_inv x.1, .. subtype.monoid } @[to_additive add_comm_group] instance subtype.comm_group {G : Type*} [comm_group G] {s : set G} [is_subgroup s] : comm_group s := { .. subtype.group, .. subtype.comm_monoid } @[simp, norm_cast, to_additive] lemma is_subgroup.coe_inv {s : set G} [is_subgroup s] (a : s) : ((a⁻¹ : s) : G) = a⁻¹ := rfl attribute [norm_cast] is_add_subgroup.coe_neg @[simp, norm_cast] lemma is_subgroup.coe_gpow {s : set G} [is_subgroup s] (a : s) (n : ℤ) : ((a ^ n : s) : G) = a ^ n := by induction n; simp [is_submonoid.coe_pow a] @[simp, norm_cast] lemma is_add_subgroup.gsmul_coe {s : set A} [is_add_subgroup s] (a : s) (n : ℤ) : ((gsmul n a : s) : A) = gsmul n a := by induction n; simp [is_add_submonoid.smul_coe a] attribute [to_additive gsmul_coe] is_subgroup.coe_gpow @[to_additive of_add_neg] theorem is_subgroup.of_div (s : set G) (one_mem : (1:G) ∈ s) (div_mem : ∀{a b:G}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s) : is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } theorem is_add_subgroup.of_sub (s : set A) (zero_mem : (0:A) ∈ s) (sub_mem : ∀{a b:A}, a ∈ s → b ∈ s → a - b ∈ s) : is_add_subgroup s := is_add_subgroup.of_add_neg s zero_mem (λ x y hx hy, sub_mem hx hy) @[to_additive] instance is_subgroup.inter (s₁ s₂ : set G) [is_subgroup s₁] [is_subgroup s₂] : is_subgroup (s₁ ∩ s₂) := { inv_mem := λ x hx, ⟨is_subgroup.inv_mem hx.1, is_subgroup.inv_mem hx.2⟩ } @[to_additive] instance is_subgroup.Inter {ι : Sort*} (s : ι → set G) [h : ∀ y : ι, is_subgroup (s y)] : is_subgroup (set.Inter s) := { inv_mem := λ x h, set.mem_Inter.2 $ λ y, is_subgroup.inv_mem (set.mem_Inter.1 h y) } @[to_additive is_add_subgroup_Union_of_directed] lemma is_subgroup_Union_of_directed {ι : Type*} [hι : nonempty ι] (s : ι → set G) [∀ i, is_subgroup (s i)] (directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) : is_subgroup (⋃i, s i) := { inv_mem := λ a ha, let ⟨i, hi⟩ := set.mem_Union.1 ha in set.mem_Union.2 ⟨i, is_subgroup.inv_mem hi⟩, to_is_submonoid := is_submonoid_Union_of_directed s directed } def gpowers (x : G) : set G := set.range ((^) x : ℤ → G) def gmultiples (x : A) : set A := set.range (λ i, gsmul i x) attribute [to_additive gmultiples] gpowers instance gpowers.is_subgroup (x : G) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } instance gmultiples.is_add_subgroup (x : A) : is_add_subgroup (gmultiples x) := multiplicative.is_subgroup_iff.1 $ gpowers.is_subgroup _ attribute [to_additive is_add_subgroup] gpowers.is_subgroup lemma is_subgroup.gpow_mem {a : G} {s : set G} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma is_add_subgroup.gsmul_mem {a : A} {s : set A} [is_add_subgroup s] : a ∈ s → ∀{i:ℤ}, gsmul i a ∈ s := @is_subgroup.gpow_mem (multiplicative A) _ _ _ (multiplicative.is_subgroup _) lemma gpowers_subset {a : G} {s : set G} [is_subgroup s] (h : a ∈ s) : gpowers a ⊆ s := λ x hx, match x, hx with _, ⟨i, rfl⟩ := is_subgroup.gpow_mem h end lemma gmultiples_subset {a : A} {s : set A} [is_add_subgroup s] (h : a ∈ s) : gmultiples a ⊆ s := @gpowers_subset (multiplicative A) _ _ _ (multiplicative.is_subgroup _) h attribute [to_additive gmultiples_subset] gpowers_subset lemma mem_gpowers {a : G} : a ∈ gpowers a := ⟨1, by simp⟩ lemma mem_gmultiples {a : A} : a ∈ gmultiples a := ⟨1, by simp⟩ attribute [to_additive mem_gmultiples] mem_gpowers end group namespace is_subgroup open is_submonoid variables [group G] (s : set G) [is_subgroup s] @[to_additive] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := ⟨λ h, by simpa using inv_mem h, inv_mem⟩ @[to_additive] lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := ⟨λ hba, by simpa using mul_mem hba (inv_mem h), λ hb, mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := ⟨λ hab, by simpa using mul_mem (inv_mem h) hab, mul_mem h⟩ end is_subgroup theorem is_add_subgroup.sub_mem {A} [add_group A] (s : set A) [is_add_subgroup s] (a b : A) (ha : a ∈ s) (hb : b ∈ s) : a - b ∈ s := is_add_submonoid.add_mem ha (is_add_subgroup.neg_mem hb) section prio set_option default_priority 100 -- see Note [default priority] class normal_add_subgroup [add_group A] (s : set A) extends is_add_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : A, g + n - g ∈ s) @[to_additive normal_add_subgroup] class normal_subgroup [group G] (s : set G) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : G, g * n * g⁻¹ ∈ s) end prio @[to_additive normal_add_subgroup_of_add_comm_group] lemma normal_subgroup_of_comm_group [comm_group G] (s : set G) [hs : is_subgroup s] : normal_subgroup s := { normal := λ n hn g, by rwa [mul_right_comm, mul_right_inv, one_mul], ..hs } lemma additive.normal_add_subgroup [group G] (s : set G) [normal_subgroup s] : @normal_add_subgroup (additive G) _ s := @normal_add_subgroup.mk (additive G) _ _ (@additive.is_add_subgroup G _ _ _) (@normal_subgroup.normal _ _ _ _) theorem additive.normal_add_subgroup_iff [group G] {s : set G} : @normal_add_subgroup (additive G) _ s ↔ normal_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_subgroup.mk G _ _ (additive.is_add_subgroup_iff.1 h₁) @h₂, λ h, by exactI additive.normal_add_subgroup _⟩ lemma multiplicative.normal_subgroup [add_group A] (s : set A) [normal_add_subgroup s] : @normal_subgroup (multiplicative A) _ s := @normal_subgroup.mk (multiplicative A) _ _ (@multiplicative.is_subgroup A _ _ _) (@normal_add_subgroup.normal _ _ _ _) theorem multiplicative.normal_subgroup_iff [add_group A] {s : set A} : @normal_subgroup (multiplicative A) _ s ↔ normal_add_subgroup s := ⟨by rintro ⟨h₁, h₂⟩; exact @normal_add_subgroup.mk A _ _ (multiplicative.is_subgroup_iff.1 h₁) @h₂, λ h, by exactI multiplicative.normal_subgroup _⟩ namespace is_subgroup variable [group G] -- Normal subgroup properties @[to_additive] lemma mem_norm_comm {s : set G} [normal_subgroup s] {a b : G} (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h @[to_additive] lemma mem_norm_comm_iff {s : set G} [normal_subgroup s] {a b : G} : a * b ∈ s ↔ b * a ∈ s := ⟨mem_norm_comm, mem_norm_comm⟩ /-- The trivial subgroup -/ @[to_additive] def trivial (G : Type*) [group G] : set G := {1} @[simp, to_additive] lemma mem_trivial {g : G} : g ∈ trivial G ↔ g = 1 := mem_singleton_iff @[to_additive] instance trivial_normal : normal_subgroup (trivial G) := by refine {..}; simp [trivial] {contextual := tt} @[to_additive] lemma eq_trivial_iff {s : set G} [is_subgroup s] : s = trivial G ↔ (∀ x ∈ s, x = (1 : G)) := by simp only [set.ext_iff, is_subgroup.mem_trivial]; exact ⟨λ h x, (h x).1, λ h x, ⟨h x, λ hx, hx.symm ▸ is_submonoid.one_mem⟩⟩ @[to_additive] instance univ_subgroup : normal_subgroup (@univ G) := by refine {..}; simp @[to_additive add_center] def center (G : Type*) [group G] : set G := {z | ∀ g, g * z = z * g} @[to_additive mem_add_center] lemma mem_center {a : G} : a ∈ center G ↔ ∀g, g * a = a * g := iff.rfl @[to_additive add_center_normal] instance center_normal : normal_subgroup (center G) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } @[to_additive add_normalizer] def normalizer (s : set G) : set G := {g : G | ∀ n, n ∈ s ↔ g * n * g⁻¹ ∈ s} @[to_additive normalizer_is_add_subgroup] instance normalizer_is_subgroup (s : set G) : is_subgroup (normalizer s) := { one_mem := by simp [normalizer], mul_mem := λ a b (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) (hb : ∀ n, n ∈ s ↔ b * n * b⁻¹ ∈ s) n, by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb], inv_mem := λ a (ha : ∀ n, n ∈ s ↔ a * n * a⁻¹ ∈ s) n, by rw [ha (a⁻¹ * n * a⁻¹⁻¹)]; simp [mul_assoc] } @[to_additive subset_add_normalizer] lemma subset_normalizer (s : set G) [is_subgroup s] : s ⊆ normalizer s := λ g hg n, by rw [is_subgroup.mul_mem_cancel_left _ ((is_subgroup.inv_mem_iff _).2 hg), is_subgroup.mul_mem_cancel_right _ hg] /-- Every subgroup is a normal subgroup of its normalizer -/ @[to_additive add_normal_in_add_normalizer] instance normal_in_normalizer (s : set G) [is_subgroup s] : normal_subgroup (subtype.val ⁻¹' s : set (normalizer s)) := { one_mem := show (1 : G) ∈ s, from is_submonoid.one_mem, mul_mem := λ a b ha hb, show (a * b : G) ∈ s, from is_submonoid.mul_mem ha hb, inv_mem := λ a ha, show (a⁻¹ : G) ∈ s, from is_subgroup.inv_mem ha, normal := λ a ha ⟨m, hm⟩, (hm a).1 ha } end is_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup open is_mul_hom (map_mul) @[to_additive] def ker [group H] (f : G → H) : set G := preimage f (trivial H) @[to_additive] lemma mem_ker [group H] (f : G → H) {x : G} : x ∈ ker f ↔ f x = 1 := mem_trivial variables [group G] [group H] @[to_additive] lemma one_ker_inv (f : G → H) [is_group_hom f] {a b : G} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [map_mul f, map_inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end @[to_additive] lemma one_ker_inv' (f : G → H) [is_group_hom f] {a b : G} (h : f (a⁻¹ * b) = 1) : f a = f b := begin rw [map_mul f, map_inv f] at h, apply eq_of_inv_eq_inv, rw eq_inv_of_mul_eq_one h end @[to_additive] lemma inv_ker_one (f : G → H) [is_group_hom f] {a b : G} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←map_inv f, ←map_mul f] at this @[to_additive] lemma inv_ker_one' (f : G → H) [is_group_hom f] {a b : G} (h : f a = f b) : f (a⁻¹ * b) = 1 := have (f a)⁻¹ * f b = 1, by rw [h, mul_left_inv], by rwa [←map_inv f, ←map_mul f] at this @[to_additive] lemma one_iff_ker_inv (f : G → H) [is_group_hom f] (a b : G) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ @[to_additive] lemma one_iff_ker_inv' (f : G → H) [is_group_hom f] (a b : G) : f a = f b ↔ f (a⁻¹ * b) = 1 := ⟨inv_ker_one' f, one_ker_inv' f⟩ @[to_additive] lemma inv_iff_ker (f : G → H) [w : is_group_hom f] (a b : G) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ @[to_additive] lemma inv_iff_ker' (f : G → H) [w : is_group_hom f] (a b : G) : f a = f b ↔ a⁻¹ * b ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv' _ _ _ @[to_additive image_add_subgroup] instance image_subgroup (f : G → H) [is_group_hom f] (s : set G) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, map_mul f]⟩, one_mem := ⟨1, one_mem, map_one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw map_inv f; simp *⟩ } @[to_additive range_add_subgroup] instance range_subgroup (f : G → H) [is_group_hom f] : is_subgroup (set.range f) := @set.image_univ _ _ f ▸ is_group_hom.image_subgroup f set.univ local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal @[to_additive] instance preimage (f : G → H) [is_group_hom f] (s : set H) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [map_mul f, map_one f, map_inv f, @inv_mem H _ s] {contextual:=tt} @[to_additive] instance preimage_normal (f : G → H) [is_group_hom f] (s : set H) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [map_mul f, map_inv f] {contextual:=tt}⟩ @[to_additive] instance normal_subgroup_ker (f : G → H) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial H) @[to_additive] lemma inj_of_trivial_ker (f : G → H) [is_group_hom f] (h : ker f = trivial G) : function.injective f := begin intros a₁ a₂ hfa, simp [ext_iff, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end @[to_additive] lemma trivial_ker_of_inj (f : G → H) [is_group_hom f] (h : function.injective f) : ker f = trivial G := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [map_one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.map_one f] {contextual := tt}) @[to_additive] lemma inj_iff_trivial_ker (f : G → H) [is_group_hom f] : function.injective f ↔ ker f = trivial G := ⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩ @[to_additive] lemma trivial_ker_iff_eq_one (f : G → H) [is_group_hom f] : ker f = trivial G ↔ ∀ x, f x = 1 → x = 1 := by rw set.ext_iff; simp [ker]; exact ⟨λ h x hx, (h x).1 hx, λ h x, ⟨h x, λ hx, by rw [hx, map_one f]⟩⟩ end is_group_hom @[to_additive is_add_group_hom] instance subtype_val.is_group_hom [group G] {s : set G} [is_subgroup s] : is_group_hom (subtype.val : s → G) := { ..subtype_val.is_monoid_hom } @[to_additive is_add_group_hom] instance coe.is_group_hom [group G] {s : set G} [is_subgroup s] : is_group_hom (coe : s → G) := { ..subtype_val.is_monoid_hom } @[to_additive is_add_group_hom] instance subtype_mk.is_group_hom [group G] [group H] {s : set G} [is_subgroup s] (f : H → G) [is_group_hom f] (h : ∀ x, f x ∈ s) : is_group_hom (λ x, (⟨f x, h x⟩ : s)) := { ..subtype_mk.is_monoid_hom f h } @[to_additive is_add_group_hom] instance set_inclusion.is_group_hom [group G] {s t : set G} [is_subgroup s] [is_subgroup t] (h : s ⊆ t) : is_group_hom (set.inclusion h) := subtype_mk.is_group_hom _ _ /-- `subtype.val : set.range f → H` as a monoid homomorphism, when `f` is a monoid homomorphism. -/ @[to_additive "`subtype.val : set.range f → H` as an additive monoid homomorphism, when `f` is an additive monoid homomorphism."] def monoid_hom.range_subtype_val [monoid G] [monoid H] (f : G →* H) : (set.range f) →* H := monoid_hom.of subtype.val /-- `set.range_factorization f : G → set.range f` as a monoid homomorphism, when `f` is a monoid homomorphism. -/ @[to_additive "`set.range_factorization f : G → set.range f` as an additive monoid homomorphism, when `f` is an additive monoid homomorphism."] def monoid_hom.range_factorization [monoid G] [monoid H] (f : G →* H) : G →* (set.range f) := { to_fun := set.range_factorization f, map_one' := by { dsimp [set.range_factorization], simp, refl, }, map_mul' := by { intros, dsimp [set.range_factorization], simp, refl, } } namespace add_group variables [add_group A] inductive in_closure (s : set A) : A → Prop | basic {a : A} : a ∈ s → in_closure a | zero : in_closure 0 | neg {a : A} : in_closure a → in_closure (-a) | add {a b : A} : in_closure a → in_closure b → in_closure (a + b) end add_group namespace group open is_submonoid is_subgroup variables [group G] {s : set G} @[to_additive] inductive in_closure (s : set G) : G → Prop | basic {a : G} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : G} : in_closure a → in_closure a⁻¹ | mul {a b : G} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ @[to_additive] def closure (s : set G) : set G := {a | in_closure s a } @[to_additive] lemma mem_closure {a : G} : a ∈ s → a ∈ closure s := in_closure.basic @[to_additive is_add_subgroup] instance closure.is_subgroup (s : set G) : is_subgroup (closure s) := { one_mem := in_closure.one, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } @[to_additive] theorem subset_closure {s : set G} : s ⊆ closure s := λ a, mem_closure @[to_additive] theorem closure_subset {s t : set G} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] @[to_additive] lemma closure_subset_iff (s t : set G) [is_subgroup t] : closure s ⊆ t ↔ s ⊆ t := ⟨assume h b ha, h (mem_closure ha), assume h b ha, closure_subset h ha⟩ @[to_additive] theorem closure_mono {s t : set G} (h : s ⊆ t) : closure s ⊆ closure t := closure_subset $ set.subset.trans h subset_closure @[simp, to_additive closure_add_subgroup] lemma closure_subgroup (s : set G) [is_subgroup s] : closure s = s := set.subset.antisymm (closure_subset $ set.subset.refl s) subset_closure @[to_additive] theorem exists_list_of_mem_closure {s : set G} {a : G} (h : a ∈ closure s) : (∃l:list G, (∀x∈l, x ∈ s ∨ x⁻¹ ∈ s) ∧ l.prod = a) := in_closure.rec_on h (λ x hxs, ⟨[x], list.forall_mem_singleton.2 $ or.inl hxs, one_mul _⟩) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x _ ⟨L, HL1, HL2⟩, ⟨L.reverse.map has_inv.inv, λ x hx, let ⟨y, hy1, hy2⟩ := list.exists_of_mem_map hx in hy2 ▸ or.imp id (by rw [inv_inv]; exact id) (HL1 _ $ list.mem_reverse.1 hy1).symm, HL2 ▸ list.rec_on L one_inv.symm (λ hd tl ih, by rw [list.reverse_cons, list.map_append, list.prod_append, ih, list.map_singleton, list.prod_cons, list.prod_nil, mul_one, list.prod_cons, mul_inv_rev])⟩) (λ x y hx hy ⟨L1, HL1, HL2⟩ ⟨L2, HL3, HL4⟩, ⟨L1 ++ L2, list.forall_mem_append.2 ⟨HL1, HL3⟩, by rw [list.prod_append, HL2, HL4]⟩) @[to_additive] lemma image_closure [group H] (f : G → H) [is_group_hom f] (s : set G) : f '' closure s = closure (f '' s) := le_antisymm begin rintros _ ⟨x, hx, rfl⟩, apply in_closure.rec_on hx; intros, { solve_by_elim [subset_closure, set.mem_image_of_mem] }, { rw [is_monoid_hom.map_one f], apply is_submonoid.one_mem }, { rw [is_group_hom.map_inv f], apply is_subgroup.inv_mem, assumption }, { rw [is_monoid_hom.map_mul f], solve_by_elim [is_submonoid.mul_mem] } end (closure_subset $ set.image_subset _ subset_closure) @[to_additive] theorem mclosure_subset {s : set G} : monoid.closure s ⊆ closure s := monoid.closure_subset $ subset_closure @[to_additive] theorem mclosure_inv_subset {s : set G} : monoid.closure (has_inv.inv ⁻¹' s) ⊆ closure s := monoid.closure_subset $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx) @[to_additive] theorem closure_eq_mclosure {s : set G} : closure s = monoid.closure (s ∪ has_inv.inv ⁻¹' s) := set.subset.antisymm (@closure_subset _ _ _ (monoid.closure (s ∪ has_inv.inv ⁻¹' s)) { inv_mem := λ x hx, monoid.in_closure.rec_on hx (λ x hx, or.cases_on hx (λ hx, monoid.subset_closure $ or.inr $ show x⁻¹⁻¹ ∈ s, from (inv_inv x).symm ▸ hx) (λ hx, monoid.subset_closure $ or.inl hx)) ((@one_inv G _).symm ▸ is_submonoid.one_mem) (λ x y hx hy ihx ihy, (mul_inv_rev x y).symm ▸ is_submonoid.mul_mem ihy ihx) } (set.subset.trans (set.subset_union_left _ _) monoid.subset_closure)) (monoid.closure_subset $ set.union_subset subset_closure $ λ x hx, inv_inv x ▸ (is_subgroup.inv_mem $ subset_closure hx)) @[to_additive] theorem mem_closure_union_iff {G : Type*} [comm_group G] {s t : set G} {x : G} : x ∈ closure (s ∪ t) ↔ ∃ y ∈ closure s, ∃ z ∈ closure t, y * z = x := begin simp only [closure_eq_mclosure, monoid.mem_closure_union_iff, exists_prop, preimage_union], split, { rintro ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, rfl⟩, refine ⟨_, ⟨_, hys, _, hzs, rfl⟩, _, ⟨_, hyt, _, hzt, rfl⟩, _⟩, rw [mul_assoc, mul_assoc, mul_left_comm zs] }, { rintro ⟨_, ⟨ys, hys, zs, hzs, rfl⟩, _, ⟨yt, hyt, zt, hzt, rfl⟩, rfl⟩, refine ⟨_, ⟨ys, hys, yt, hyt, rfl⟩, _, ⟨zs, hzs, zt, hzt, rfl⟩, _⟩, rw [mul_assoc, mul_assoc, mul_left_comm yt] } end @[to_additive gmultiples_eq_closure] theorem gpowers_eq_closure {a : G} : gpowers a = closure {a} := subset.antisymm (gpowers_subset $ mem_closure $ by simp) (closure_subset $ by simp [mem_gpowers]) end group namespace is_subgroup variable [group G] @[to_additive] lemma trivial_eq_closure : trivial G = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) end is_subgroup /-The normal closure of a set s is the subgroup closure of all the conjugates of elements of s. It is the smallest normal subgroup containing s. -/ namespace group variables {s : set G} [group G] /-- Given an element a, conjugates a is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set s, conjugates_of_set s is the set of all conjugates of the elements of s. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset {t : set G} [normal_subgroup t] {a : G} (h : a ∈ t) : conjugates a ⊆ t := λ x ⟨c,w⟩, begin have H := normal_subgroup.normal a h c, rwa ←w, end theorem conjugates_of_set_subset {s t : set G} [normal_subgroup t] (h : s ⊆ t) : conjugates_of_set s ⊆ t := set.bUnion_subset (λ x H, conjugates_subset (h H)) /-- The set of conjugates of s is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end /-- The normal closure of a set s is the subgroup closure of all the conjugates of elements of s. It is the smallest normal subgroup containing s. -/ def normal_closure (s : set G) : set G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure /-- The normal closure of a set is a subgroup. -/ instance normal_closure.is_subgroup (s : set G) : is_subgroup (normal_closure s) := closure.is_subgroup (conjugates_of_set s) /-- The normal closure of s is a normal subgroup. -/ instance normal_closure.is_normal : normal_subgroup (normal_closure s) := ⟨ λ n h g, begin induction h with x hx x hx ihx x y hx hy ihx ihy, {exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx))}, {simpa using (normal_closure.is_subgroup s).one_mem}, {rw ←conj_inv, exact (is_subgroup.inv_mem ihx)}, {rw ←conj_mul, exact (is_submonoid.mul_mem ihx ihy)}, end ⟩ /-- The normal closure of s is the smallest normal subgroup containing s. -/ theorem normal_closure_subset {s t : set G} [normal_subgroup t] (h : s ⊆ t) : normal_closure s ⊆ t := λ a w, begin induction w with x hx x hx ihx x y hx hy ihx ihy, {exact (conjugates_of_set_subset h $ hx)}, {exact is_submonoid.one_mem}, {exact is_subgroup.inv_mem ihx}, {exact is_submonoid.mul_mem ihx ihy} end lemma normal_closure_subset_iff {s t : set G} [normal_subgroup t] : s ⊆ t ↔ normal_closure s ⊆ t := ⟨normal_closure_subset, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} : s ⊆ t → normal_closure s ⊆ normal_closure t := λ h, normal_closure_subset (set.subset.trans h (subset_normal_closure)) end group section simple_group class simple_group (G : Type*) [group G] : Prop := (simple : ∀ (N : set G) [normal_subgroup N], N = is_subgroup.trivial G ∨ N = set.univ) class simple_add_group (A : Type*) [add_group A] : Prop := (simple : ∀ (N : set A) [normal_add_subgroup N], N = is_add_subgroup.trivial A ∨ N = set.univ) attribute [to_additive simple_add_group] simple_group theorem additive.simple_add_group_iff [group G] : simple_add_group (additive G) ↔ simple_group G := ⟨λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.2 h)⟩, λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI additive.normal_add_subgroup_iff.1 h)⟩⟩ instance additive.simple_add_group [group G] [simple_group G] : simple_add_group (additive G) := additive.simple_add_group_iff.2 (by apply_instance) theorem multiplicative.simple_group_iff [add_group A] : simple_group (multiplicative A) ↔ simple_add_group A := ⟨λ hs, ⟨λ N h, @simple_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.2 h)⟩, λ hs, ⟨λ N h, @simple_add_group.simple _ _ hs _ (by exactI multiplicative.normal_subgroup_iff.1 h)⟩⟩ instance multiplicative.simple_group [add_group A] [simple_add_group A] : simple_group (multiplicative A) := multiplicative.simple_group_iff.2 (by apply_instance) @[to_additive simple_add_group_of_surjective] lemma simple_group_of_surjective [group G] [group H] [simple_group G] (f : G → H) [is_group_hom f] (hf : function.surjective f) : simple_group H := ⟨λ H iH, have normal_subgroup (f ⁻¹' H), by resetI; apply_instance, begin resetI, cases simple_group.simple (f ⁻¹' H) with h h, { refine or.inl (is_subgroup.eq_trivial_iff.2 (λ x hx, _)), cases hf x with y hy, rw ← hy at hx, rw [← hy, is_subgroup.eq_trivial_iff.1 h y hx, is_group_hom.map_one f] }, { refine or.inr (set.eq_univ_of_forall (λ x, _)), cases hf x with y hy, rw set.eq_univ_iff_forall at h, rw ← hy, exact h y } end⟩ end simple_group
337097de44a0ee5d03aba2c35374370854c73619
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/measure_theory/measure_space.lean
2e77d56cac02e890da1f3fbeafd8d873c8e19573
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
77,198
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 measure_theory.outer_measure import order.filter.countable_Inter import data.set.accumulate /-! # Measure spaces Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the extended nonnegative reals that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint sets is equal to the measure of the individual sets. Every measure can be canonically extended to an outer measure, so that it assigns values to all subsets, not just the measurable subsets. On the other hand, a measure that is countably additive on measurable sets can be restricted to measurable sets to obtain a measure. In this file a measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ennreal`. We introduce the following typeclasses for measures: * `probability_measure μ`: `μ univ = 1`; * `finite_measure μ`: `μ univ < ⊤`; * `sigma_finite μ`: there exists a countable collection of measurable sets that cover `univ` where `μ` is finite; * `locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ⊤`; * `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as `∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`. Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0` on the null sets. ## Main statements * `completion` is the completion of a measure to all null measurable sets. * `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure. ## Implementation notes Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`. This conveniently allows us to apply the measure to sets without proving that they are measurable. We get countable subadditivity for all sets, but only countable additivity for measurable sets. You often don't want to define a measure via its constructor. Two ways that are sometimes more convenient: * `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets and proving the properties (1) and (2) mentioned above. * `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that all measurable sets in the measurable space are Carathéodory measurable. To prove that two measures are equal, there are multiple options: * `ext`: two measures are equal if they are equal on all measurable sets. * `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating the measurable sets, if the π-system contains a spanning increasing sequence of sets where the measures take finite value (in particular the measures are σ-finite). This is a special case of the more general `ext_of_generate_from_of_cover` * `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using `C ∪ {univ}`, but is easier to work with. A `measure_space` is a class that is a measurable space with a canonical measure. The measure is denoted `volume`. ## References * <https://en.wikipedia.org/wiki/Measure_(mathematics)> * <https://en.wikipedia.org/wiki/Complete_measure> * <https://en.wikipedia.org/wiki/Almost_everywhere> ## Tags measure, almost everywhere, measure space, completion, null set, null measurable set -/ noncomputable theory open classical set filter function open_locale classical topological_space big_operators filter universes u v w x namespace measure_theory /-- A measure is defined to be an outer measure that is countably additive on measurable sets, with the additional assumption that the outer measure is the canonical extension of the restricted measure. -/ structure measure (α : Type*) [measurable_space α] extends outer_measure α := (m_Union ⦃f : ℕ → set α⦄ : (∀i, is_measurable (f i)) → pairwise (disjoint on f) → measure_of (⋃i, f i) = (∑'i, measure_of (f i))) (trimmed : to_outer_measure.trim = to_outer_measure) /-- Measure projections for a measure space. For measurable sets this returns the measure assigned by the `measure_of` field in `measure`. But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and subadditivity for all sets. -/ instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) := ⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩ namespace measure /-! ### General facts about measures -/ /-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/ def of_measurable {α} [measurable_space α] (m : Π (s : set α), is_measurable s → ennreal) (m0 : m ∅ is_measurable.empty = 0) (mU : ∀ {{f : ℕ → set α}} (h : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))) : measure α := { m_Union := λ f hf hd, show induced_outer_measure m _ m0 (Union f) = ∑' i, induced_outer_measure m _ m0 (f i), begin rw [induced_outer_measure_eq m0 mU, mU hf hd], congr, funext n, rw induced_outer_measure_eq m0 mU end, trimmed := show (induced_outer_measure m _ m0).trim = induced_outer_measure m _ m0, begin unfold outer_measure.trim, congr, funext s hs, exact induced_outer_measure_eq m0 mU hs end, ..induced_outer_measure m _ m0 } lemma of_measurable_apply {α} [measurable_space α] {m : Π (s : set α), is_measurable s → ennreal} {m0 : m ∅ is_measurable.empty = 0} {mU : ∀ {{f : ℕ → set α}} (h : ∀i, is_measurable (f i)), pairwise (disjoint on f) → m (⋃i, f i) (is_measurable.Union h) = (∑'i, m (f i) (h i))} (s : set α) (hs : is_measurable s) : of_measurable m m0 mU s = m s hs := induced_outer_measure_eq m0 mU hs lemma to_outer_measure_injective {α} [measurable_space α] : injective (to_outer_measure : measure α → outer_measure α) := λ ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h, by { congr, exact h } @[ext] lemma ext {α} [measurable_space α] {μ₁ μ₂ : measure α} (h : ∀s, is_measurable s → μ₁ s = μ₂ s) : μ₁ = μ₂ := to_outer_measure_injective $ by rw [← trimmed, outer_measure.trim_congr h, trimmed] lemma ext_iff {α} [measurable_space α] {μ₁ μ₂ : measure α} : μ₁ = μ₂ ↔ ∀s, is_measurable s → μ₁ s = μ₂ s := ⟨by { rintro rfl s hs, refl }, measure.ext⟩ end measure section variables {α : Type*} {β : Type*} {ι : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ : set α} @[simp] lemma coe_to_outer_measure : ⇑μ.to_outer_measure = μ := rfl lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s := by rw μ.trimmed; refl lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t := by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl lemma measure_eq_induced_outer_measure : μ s = induced_outer_measure (λ s _, μ s) is_measurable.empty μ.empty s := measure_eq_trim _ lemma to_outer_measure_eq_induced_outer_measure : μ.to_outer_measure = induced_outer_measure (λ s _, μ s) is_measurable.empty μ.empty := μ.trimmed.symm lemma measure_eq_extend (hs : is_measurable s) : μ s = extend (λ t (ht : is_measurable t), μ t) s := by { rw [measure_eq_induced_outer_measure, induced_outer_measure_eq_extend _ _ hs], exact μ.m_Union } @[simp] lemma measure_empty : μ ∅ = 0 := μ.empty lemma nonempty_of_measure_ne_zero (h : μ s ≠ 0) : s.nonempty := ne_empty_iff_nonempty.1 $ λ h', h $ h'.symm ▸ measure_empty lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 := le_zero_iff_eq.1 $ h₂ ▸ measure_mono h lemma measure_mono_top (h : s₁ ⊆ s₂) (h₁ : μ s₁ = ⊤) : μ s₂ = ⊤ := top_unique $ h₁ ▸ measure_mono h lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) : ∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 := outer_measure.exists_is_measurable_superset_of_trim_eq_zero (by rw [← measure_eq_trim, h]) lemma exists_is_measurable_superset_iff_measure_eq_zero {s : set α} : (∃ t, s ⊆ t ∧ is_measurable t ∧ μ t = 0) ↔ μ s = 0 := ⟨λ ⟨t, hst, _, ht⟩, measure_mono_null hst ht, exists_is_measurable_superset_of_measure_eq_zero⟩ theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑'i, μ (s i)) := μ.to_outer_measure.Union _ lemma measure_bUnion_le {s : set β} (hs : countable s) (f : β → set α) : μ (⋃b∈s, f b) ≤ ∑'p:s, μ (f p) := begin haveI := hs.to_encodable, rw [bUnion_eq_Union], apply measure_Union_le end lemma measure_bUnion_finset_le (s : finset β) (f : β → set α) : μ (⋃b∈s, f b) ≤ ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion_le s.countable_to_set f end lemma measure_bUnion_lt_top {s : set β} {f : β → set α} (hs : finite s) (hfin : ∀ i ∈ s, μ (f i) < ⊤) : μ (⋃ i ∈ s, f i) < ⊤ := begin convert (measure_bUnion_finset_le hs.to_finset f).trans_lt _, { ext, rw [finite.mem_to_finset] }, apply ennreal.sum_lt_top, simpa only [finite.mem_to_finset] end lemma measure_Union_null {β} [encodable β] {s : β → set α} : (∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 := μ.to_outer_measure.Union_null theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ := μ.to_outer_measure.union _ _ lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 := μ.to_outer_measure.union_null lemma measure_Union {β} [encodable β] {f : β → set α} (hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) : μ (⋃i, f i) = (∑'i, μ (f i)) := begin rw [measure_eq_extend (is_measurable.Union h), extend_Union is_measurable.empty _ is_measurable.Union _ hn h], { simp [measure_eq_extend, h] }, { exact μ.empty }, { exact μ.m_Union } end lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : μ (s₁ ∪ s₂) = μ s₁ + μ s₂ := begin rw [union_eq_Union, measure_Union, tsum_fintype, fintype.sum_bool, cond, cond], exacts [pairwise_disjoint_on_bool.2 hd, λ b, bool.cases_on b h₂ h₁] end lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s) (hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) : μ (⋃b∈s, f b) = ∑'p:s, μ (f p) := begin haveI := hs.to_encodable, rw [← measure_Union, bUnion_eq_Union], { rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩, exact hd i hi j hj (mt subtype.ext_val ij:_) ⟨h₁, h₂⟩ }, { simpa } end lemma measure_sUnion {S : set (set α)} (hs : countable S) (hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) : μ (⋃₀ S) = ∑' s:S, μ s := by rw [sUnion_eq_bUnion, measure_bUnion hs hd h] lemma measure_bUnion_finset {s : finset ι} {f : ι → set α} (hd : pairwise_on ↑s (disjoint on f)) (hm : ∀b∈s, is_measurable (f b)) : μ (⋃b∈s, f b) = ∑ p in s, μ (f p) := begin rw [← finset.sum_attach, finset.attach_eq_univ, ← tsum_fintype], exact measure_bUnion s.countable_to_set hd hm end /-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma tsum_measure_preimage_singleton {s : set β} (hs : countable s) {f : α → β} (hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) : (∑' b : s, μ (f ⁻¹' {↑b})) = μ (f ⁻¹' s) := by rw [← set.bUnion_preimage_singleton, measure_bUnion hs (pairwise_on_disjoint_fiber _ _) hf] /-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures of the fibers `f ⁻¹' {y}`. -/ lemma sum_measure_preimage_singleton (s : finset β) {f : α → β} (hf : ∀ y ∈ s, is_measurable (f ⁻¹' {y})) : ∑ b in s, μ (f ⁻¹' {b}) = μ (f ⁻¹' ↑s) := by simp only [← measure_bUnion_finset (pairwise_on_disjoint_fiber _ _) hf, finset.bUnion_preimage_singleton] lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) (h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ := begin refine (ennreal.add_sub_self' h_fin).symm.trans _, rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h] end lemma measure_compl {μ : measure α} {s : set α} (h₁ : is_measurable s) (h_fin : μ s < ⊤) : μ (sᶜ) = μ univ - μ s := by { rw compl_eq_univ_diff, exact measure_diff (subset_univ s) is_measurable.univ h₁ h_fin } lemma sum_measure_le_measure_univ {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : pairwise_on ↑s (disjoint on t)) : ∑ i in s, μ (t i) ≤ μ (univ : set α) := by { rw ← measure_bUnion_finset H h, exact measure_mono (subset_univ _) } lemma tsum_measure_le_measure_univ {s : ι → set α} (hs : ∀ i, is_measurable (s i)) (H : pairwise (disjoint on s)) : (∑' i, μ (s i)) ≤ μ (univ : set α) := begin rw [ennreal.tsum_eq_supr_sum], exact supr_le (λ s, sum_measure_le_measure_univ (λ i hi, hs i) (λ i hi j hj hij, H i j hij)) end /-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then one of the intersections `s i ∩ s j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_tsum_measure (μ : measure α) {s : ι → set α} (hs : ∀ i, is_measurable (s i)) (H : μ (univ : set α) < ∑' i, μ (s i)) : ∃ i j (h : i ≠ j), (s i ∩ s j).nonempty := begin contrapose! H, apply tsum_measure_le_measure_univ hs, exact λ i j hij x hx, H i j hij ⟨x, hx⟩ end /-- Pigeonhole principle for measure spaces: if `s` is a `finset` and `∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/ lemma exists_nonempty_inter_of_measure_univ_lt_sum_measure (μ : measure α) {s : finset ι} {t : ι → set α} (h : ∀ i ∈ s, is_measurable (t i)) (H : μ (univ : set α) < ∑ i in s, μ (t i)) : ∃ (i ∈ s) (j ∈ s) (h : i ≠ j), (t i ∩ t j).nonempty := begin contrapose! H, apply sum_measure_le_measure_univ h, exact λ i hi j hj hij x hx, H i hi j hj hij ⟨x, hx⟩ end /-- Continuity from below: the measure of the union of a directed sequence of measurable sets is the supremum of the measures. -/ lemma measure_Union_eq_supr [encodable ι] {s : ι → set α} (h : ∀ i, is_measurable (s i)) (hd : directed (⊆) s) : μ (⋃ i, s i) = ⨆ i, μ (s i) := begin by_cases hι : nonempty ι, swap, { simp only [supr_of_empty hι, Union], exact measure_empty }, resetI, refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _), have : ∀ n, is_measurable (disjointed (λ n, ⋃ b ∈ encodable.decode2 ι n, s b) n) := is_measurable.disjointed (is_measurable.bUnion_decode2 h), rw [← encodable.Union_decode2, ← Union_disjointed, measure_Union disjoint_disjointed this, ennreal.tsum_eq_supr_nat], simp only [← measure_bUnion_finset (disjoint_disjointed.pairwise_on _) (λ n _, this n)], refine supr_le (λ n, _), refine le_trans (_ : _ ≤ μ (⋃ (k ∈ finset.range n) (i ∈ encodable.decode2 ι k), s i)) _, exact measure_mono (bUnion_subset_bUnion_right (λ k hk, disjointed_subset)), simp only [← finset.bUnion_option_to_finset, ← finset.bUnion_bind], generalize : (finset.range n).bind (λ k, (encodable.decode2 ι k).to_finset) = t, rcases hd.finset_le t with ⟨i, hi⟩, exact le_supr_of_le i (measure_mono $ bUnion_subset hi) end lemma measure_bUnion_eq_supr {s : ι → set α} {t : set ι} (ht : countable t) (h : ∀ i ∈ t, is_measurable (s i)) (hd : directed_on ((⊆) on s) t) : μ (⋃ i ∈ t, s i) = ⨆ i ∈ t, μ (s i) := begin haveI := ht.to_encodable, rw [bUnion_eq_Union, measure_Union_eq_supr (set_coe.forall'.1 h) hd.directed_coe, supr_subtype'], refl end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the infimum of the measures. -/ lemma measure_Inter_eq_infi [encodable ι] {s : ι → set α} (h : ∀i, is_measurable (s i)) (hd : directed (⊇) s) (hfin : ∃i, μ (s i) < ⊤) : μ (⋂i, s i) = (⨅i, μ (s i)) := begin rcases hfin with ⟨k, hk⟩, rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k), ennreal.sub_infi, ← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)), ← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h) (lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk), diff_Inter, measure_Union_eq_supr], { congr' 1, refine le_antisymm (supr_le_supr2 $ λ i, _) (supr_le_supr $ λ i, _), { rcases hd i k with ⟨j, hji, hjk⟩, use j, rw [← measure_diff hjk (h _) (h _) ((measure_mono hjk).trans_lt hk)], exact measure_mono (diff_subset_diff_right hji) }, { rw [ennreal.sub_le_iff_le_add, ← measure_union disjoint_diff.symm ((h k).diff (h i)) (h i), set.union_comm], exact measure_mono (diff_subset_iff.1 $ subset.refl _) } }, { exact λ i, (h k).diff (h i) }, { exact hd.mono_comp _ (λ _ _, diff_subset_diff_right) } end lemma measure_eq_inter_diff {s t : set α} (hs : is_measurable s) (ht : is_measurable t) : μ s = μ (s ∩ t) + μ (s \ t) := have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs , by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t] lemma measure_union_add_inter {s t : set α} (hs : is_measurable s) (ht : is_measurable t) : μ (s ∪ t) + μ (s ∩ t) = μ s + μ t := by { rw [measure_eq_inter_diff (hs.union ht) ht, set.union_inter_cancel_right, union_diff_right, measure_eq_inter_diff hs ht], ac_refl } /-- Continuity from below: the measure of the union of an increasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α} (hs : ∀n, is_measurable (s n)) (hm : monotone s) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋃n, s n))) := begin rw measure_Union_eq_supr hs (directed_of_sup hm), exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm hnm) end /-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable sets is the limit of the measures. -/ lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α} (hs : ∀n, is_measurable (s n)) (hm : ∀ ⦃n m⦄, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) : tendsto (μ ∘ s) at_top (𝓝 (μ (⋂n, s n))) := begin rw measure_Inter_eq_infi hs (directed_of_sup hm) hf, exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm hnm), end /-- One direction of the Borel-Cantelli lemma: if (sᵢ) is a sequence of measurable sets such that ∑ μ sᵢ exists, then the limit superior of the sᵢ is a null set. -/ lemma measure_limsup_eq_zero {s : ℕ → set α} (hs : ∀ i, is_measurable (s i)) (hs' : (∑' i, μ (s i)) ≠ ⊤) : μ (limsup at_top s) = 0 := begin rw limsup_eq_infi_supr_of_nat', -- We will show that both `μ (⨅ n, ⨆ i, s (i + n))` and `0` are the limit of `μ (⊔ i, s (i + n))` -- as `n` tends to infinity. For the former, we use continuity from above. refine tendsto_nhds_unique (tendsto_measure_Inter (λ i, is_measurable.Union (λ b, hs (b + i))) _ ⟨0, lt_of_le_of_lt (measure_Union_le s) (ennreal.lt_top_iff_ne_top.2 hs')⟩) _, { intros n m hnm x, simp only [set.mem_Union], exact λ ⟨i, hi⟩, ⟨i + (m - n), by simpa only [add_assoc, nat.sub_add_cancel hnm] using hi⟩ }, { -- For the latter, notice that, `μ (⨆ i, s (i + n)) ≤ ∑' s (i + n)`. Since the right hand side -- converges to `0` by hypothesis, so does the former and the proof is complete. exact (tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (ennreal.tendsto_sum_nat_add (μ ∘ s) hs') (eventually_of_forall (by simp only [forall_const, zero_le])) (eventually_of_forall (λ i, measure_Union_le _))) } end end /-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are Carathéodory measurable. -/ def outer_measure.to_measure {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) : measure α := measure.of_measurable (λ s _, m s) m.empty (λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd) lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α] (μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory := begin assume s hs, rw to_outer_measure_eq_induced_outer_measure, refine outer_measure.of_function_caratheodory (λ t, le_infi $ λ ht, _), rw [← measure_eq_extend (ht.inter hs), ← measure_eq_extend (ht.diff hs), ← measure_union _ (ht.inter hs) (ht.diff hs), inter_union_diff], exact le_refl _, exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁ end @[simp] lemma to_measure_to_outer_measure {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) : (m.to_measure h).to_outer_measure = m.trim := rfl @[simp] lemma to_measure_apply {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) {s : set α} (hs : is_measurable s) : m.to_measure h s = m s := m.trim_eq hs lemma le_to_measure_apply {α} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) (s : set α) : m s ≤ m.to_measure h s := m.le_trim s @[simp] lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} : μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ := measure.ext $ λ s, μ.to_outer_measure.trim_eq namespace measure variables {α : Type*} {β : Type*} {γ : Type*} [measurable_space α] [measurable_space β] [measurable_space γ] /-! ### The `ennreal`-module of measures -/ instance : has_zero (measure α) := ⟨{ to_outer_measure := 0, m_Union := λ f hf hd, tsum_zero.symm, trimmed := outer_measure.trim_zero }⟩ @[simp] theorem zero_to_outer_measure : (0 : measure α).to_outer_measure = 0 := rfl @[simp, norm_cast] theorem coe_zero : ⇑(0 : measure α) = 0 := rfl lemma eq_zero_of_not_nonempty (h : ¬nonempty α) (μ : measure α) : μ = 0 := ext $ λ s hs, by simp only [eq_empty_of_not_nonempty h s, measure_empty] instance : inhabited (measure α) := ⟨0⟩ instance : has_add (measure α) := ⟨λμ₁ μ₂, { to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure, m_Union := λs hs hd, show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑' i, μ₁ (s i) + μ₂ (s i), by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs], trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩ @[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) : (μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl @[simp, norm_cast] theorem coe_add (μ₁ μ₂ : measure α) : ⇑(μ₁ + μ₂) = μ₁ + μ₂ := rfl theorem add_apply (μ₁ μ₂ : measure α) (s) : (μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl instance add_comm_monoid : add_comm_monoid (measure α) := to_outer_measure_injective.add_comm_monoid to_outer_measure zero_to_outer_measure add_to_outer_measure instance : has_scalar ennreal (measure α) := ⟨λ c μ, { to_outer_measure := c • μ.to_outer_measure, m_Union := λ s hs hd, by simp [measure_Union, *, ennreal.tsum_mul_left], trimmed := by rw [outer_measure.trim_smul, μ.trimmed] }⟩ @[simp] theorem smul_to_outer_measure (c : ennreal) (μ : measure α) : (c • μ).to_outer_measure = c • μ.to_outer_measure := rfl @[simp, norm_cast] theorem coe_smul (c : ennreal) (μ : measure α) : ⇑(c • μ) = c • μ := rfl theorem smul_apply (c : ennreal) (μ : measure α) (s : set α) : (c • μ) s = c * μ s := rfl instance : semimodule ennreal (measure α) := injective.semimodule ennreal ⟨to_outer_measure, zero_to_outer_measure, add_to_outer_measure⟩ to_outer_measure_injective smul_to_outer_measure /-! ### The complete lattice of measures -/ instance : partial_order (measure α) := { le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s, le_refl := assume m s hs, le_refl _, le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs), le_antisymm := assume m₁ m₂ h₁ h₂, ext $ assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) } theorem le_iff {μ₁ μ₂ : measure α} : μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl theorem to_outer_measure_le {μ₁ μ₂ : measure α} : μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ := by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl theorem le_iff' {μ₁ μ₂ : measure α} : μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s := to_outer_measure_le.symm theorem lt_iff {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, is_measurable s ∧ μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff, not_forall, not_le, exists_prop] theorem lt_iff' {μ ν : measure α} : μ < ν ↔ μ ≤ ν ∧ ∃ s, μ s < ν s := lt_iff_le_not_le.trans $ and_congr iff.rfl $ by simp only [le_iff', not_forall, not_le] section variables {m : set (measure α)} {μ : measure α} lemma Inf_caratheodory (s : set α) (hs : is_measurable s) : (Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable' s := begin rw [outer_measure.Inf_eq_of_function_Inf_gen], refine outer_measure.of_function_caratheodory (assume t, _), cases t.eq_empty_or_nonempty with ht ht, by simp [ht], simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff, coe_to_outer_measure, measure_eq_infi t], assume μ hμ u htu hu, have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t, { assume s t hst, rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)], refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _), rw [to_outer_measure_apply], refine measure_mono hst }, rw [measure_eq_inter_diff hu hs], refine add_le_add (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu) end instance : has_Inf (measure α) := ⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩ lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) : Inf m s = Inf (to_outer_measure '' m) s := to_measure_apply _ _ hs private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ := have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h), assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m := have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) := le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ, assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s instance : complete_lattice (measure α) := { bot := 0, bot_le := assume a s hs, by exact bot_le, /- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top), le_top := assume a s hs, by cases s.eq_empty_or_nonempty with h h; simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply], -/ .. complete_lattice_of_Inf (measure α) (λ ms, ⟨λ _, Inf_le, λ _, le_Inf⟩) } @[simp] lemma measure_univ_eq_zero {μ : measure α} : μ univ = 0 ↔ μ = 0 := ⟨λ h, bot_unique $ λ s hs, trans_rel_left (≤) (measure_mono (subset_univ s)) h, λ h, h.symm ▸ rfl⟩ -- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)` protected lemma add_le_add_left {μ₁ μ₂ : measure α} (ν : measure α) (hμ : μ₁ ≤ μ₂) : ν + μ₁ ≤ ν + μ₂ := λ s hs, add_le_add_left (hμ s hs) _ protected lemma add_le_add_right {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) (ν : measure α) : μ₁ + ν ≤ μ₂ + ν := λ s hs, add_le_add_right (hμ s hs) _ protected lemma add_le_add {μ₁ μ₂ : measure α} (hμ : μ₁ ≤ μ₂) {ν₁ ν₂ : measure α} (hν : ν₁ ≤ ν₂) : μ₁ + ν₁ ≤ μ₂ + ν₂ := λ s hs, add_le_add (hμ s hs) (hν s hs) protected lemma zero_le (μ : measure α) : 0 ≤ μ := bot_le protected lemma le_add_left {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν' + ν := λ s hs, le_add_left (h s hs) protected lemma le_add_right {ν ν' : measure α} (h : μ ≤ ν) : μ ≤ ν + ν' := λ s hs, le_add_right (h s hs) end /-! ### Pushforward and pullback -/ /-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/ def lift_linear (f : outer_measure α →ₗ[ennreal] outer_measure β) (hf : ∀ μ : measure α, ‹_› ≤ (f μ.to_outer_measure).caratheodory) : measure α →ₗ[ennreal] measure β := { to_fun := λ μ, (f μ.to_outer_measure).to_measure (hf μ), map_add' := λ μ₁ μ₂, ext $ λ s hs, by simp [hs], map_smul' := λ c μ, ext $ λ s hs, by simp [hs] } @[simp] lemma lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf) {μ : measure α} {s : set β} (hs : is_measurable s) : lift_linear f hf μ s = f μ.to_outer_measure s := to_measure_apply _ _ hs lemma le_lift_linear_apply {f : outer_measure α →ₗ[ennreal] outer_measure β} (hf) {μ : measure α} (s : set β) : f μ.to_outer_measure s ≤ lift_linear f hf μ s := le_to_measure_apply _ _ s /-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/ def map (f : α → β) : measure α →ₗ[ennreal] measure β := if hf : measurable f then lift_linear (outer_measure.map f) $ λ μ s hs t, le_to_outer_measure_caratheodory μ _ (hf hs) (f ⁻¹' t) else 0 variables {μ ν : measure α} @[simp] theorem map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : map f μ s = μ (f ⁻¹' s) := by simp [map, dif_pos hf, hs] @[simp] lemma map_id : map id μ = μ := ext $ λ s, map_apply measurable_id lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : map g (map f μ) = map (g ∘ f) μ := ext $ λ s hs, by simp [hf, hg, hs, hg hs, hg.comp hf, ← preimage_comp] /-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each measurable set `s` we have `comap f μ s = μ (f '' s)`. -/ def comap (f : α → β) : measure β →ₗ[ennreal] measure α := if hf : injective f ∧ ∀ s, is_measurable s → is_measurable (f '' s) then lift_linear (outer_measure.comap f) $ λ μ s hs t, begin simp only [coe_to_outer_measure, outer_measure.comap_apply, ← image_inter hf.1, image_diff hf.1], apply le_to_outer_measure_caratheodory, exact hf.2 s hs end else 0 lemma comap_apply (f : α → β) (hfi : injective f) (hf : ∀ s, is_measurable s → is_measurable (f '' s)) (μ : measure β) {s : set α} (hs : is_measurable s) : comap f μ s = μ (f '' s) := begin rw [comap, dif_pos, lift_linear_apply _ hs, outer_measure.comap_apply, coe_to_outer_measure], exact ⟨hfi, hf⟩ end /-! ### Restricting a measure -/ /-- Restrict a measure `μ` to a set `s` as an `ennreal`-linear map. -/ def restrictₗ (s : set α) : measure α →ₗ[ennreal] measure α := lift_linear (outer_measure.restrict s) $ λ μ s' hs' t, begin suffices : μ (s ∩ t) = μ (s ∩ t ∩ s') + μ (s ∩ t \ s'), { simpa [← set.inter_assoc, set.inter_comm _ s, ← inter_diff_assoc] }, exact le_to_outer_measure_caratheodory _ _ hs' _, end /-- Restrict a measure `μ` to a set `s`. -/ def restrict (μ : measure α) (s : set α) : measure α := restrictₗ s μ @[simp] lemma restrictₗ_apply (s : set α) (μ : measure α) : restrictₗ s μ = μ.restrict s := rfl @[simp] lemma restrict_apply {s t : set α} (ht : is_measurable t) : μ.restrict s t = μ (t ∩ s) := by simp [← restrictₗ_apply, restrictₗ, ht] lemma restrict_apply_univ (s : set α) : μ.restrict s univ = μ s := by rw [restrict_apply is_measurable.univ, set.univ_inter] lemma le_restrict_apply (s t : set α) : μ (t ∩ s) ≤ μ.restrict s t := by { rw [restrict, restrictₗ], convert le_lift_linear_apply _ t, simp } @[simp] lemma restrict_add (μ ν : measure α) (s : set α) : (μ + ν).restrict s = μ.restrict s + ν.restrict s := (restrictₗ s).map_add μ ν @[simp] lemma restrict_zero (s : set α) : (0 : measure α).restrict s = 0 := (restrictₗ s).map_zero @[simp] lemma restrict_smul (c : ennreal) (μ : measure α) (s : set α) : (c • μ).restrict s = c • μ.restrict s := (restrictₗ s).map_smul c μ @[simp] lemma restrict_restrict {s t : set α} (hs : is_measurable s) : (μ.restrict t).restrict s = μ.restrict (s ∩ t) := ext $ λ u hu, by simp [*, set.inter_assoc] lemma restrict_apply_eq_zero {s t : set α} (ht : is_measurable t) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := by rw [restrict_apply ht] lemma restrict_apply_eq_zero' {s t : set α} (hs : is_measurable s) : μ.restrict s t = 0 ↔ μ (t ∩ s) = 0 := begin refine ⟨λ h, le_zero_iff_eq.1 (h ▸ le_restrict_apply _ _), λ h, _⟩, rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t', htt', ht', ht'0⟩, apply measure_mono_null ((inter_subset _ _ _).1 htt'), rw [restrict_apply (hs.compl.union ht'), union_inter_distrib_right, compl_inter_self, set.empty_union], exact measure_mono_null (inter_subset_left _ _) ht'0 end @[simp] lemma restrict_eq_zero {s} : μ.restrict s = 0 ↔ μ s = 0 := by rw [← measure_univ_eq_zero, restrict_apply_univ] @[simp] lemma restrict_empty : μ.restrict ∅ = 0 := ext $ λ s hs, by simp [hs] @[simp] lemma restrict_univ : μ.restrict univ = μ := ext $ λ s hs, by simp [hs] lemma restrict_union_apply {s s' t : set α} (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s) (hs' : is_measurable s') (ht : is_measurable t) : μ.restrict (s ∪ s') t = μ.restrict s t + μ.restrict s' t := begin simp only [restrict_apply, ht, set.inter_union_distrib_left], exact measure_union h (ht.inter hs) (ht.inter hs'), end lemma restrict_union {s t : set α} (h : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) : μ.restrict (s ∪ t) = μ.restrict s + μ.restrict t := ext $ λ t' ht', restrict_union_apply (h.mono inf_le_right inf_le_right) hs ht ht' lemma restrict_union_add_inter {s t : set α} (hs : is_measurable s) (ht : is_measurable t) : μ.restrict (s ∪ t) + μ.restrict (s ∩ t) = μ.restrict s + μ.restrict t := begin ext1 u hu, simp only [add_apply, restrict_apply hu, inter_union_distrib_left], convert measure_union_add_inter (hu.inter hs) (hu.inter ht) using 3, rw [set.inter_left_comm (u ∩ s), set.inter_assoc, ← set.inter_assoc u u, set.inter_self] end @[simp] lemma restrict_add_restrict_compl {s : set α} (hs : is_measurable s) : μ.restrict s + μ.restrict sᶜ = μ := by rw [← restrict_union (disjoint_compl_right _) hs hs.compl, union_compl_self, restrict_univ] @[simp] lemma restrict_compl_add_restrict {s : set α} (hs : is_measurable s) : μ.restrict sᶜ + μ.restrict s = μ := by rw [add_comm, restrict_add_restrict_compl hs] lemma restrict_union_le (s s' : set α) : μ.restrict (s ∪ s') ≤ μ.restrict s + μ.restrict s' := begin intros t ht, suffices : μ (t ∩ s ∪ t ∩ s') ≤ μ (t ∩ s) + μ (t ∩ s'), by simpa [ht, inter_union_distrib_left], apply measure_union_le end lemma restrict_Union_apply {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, is_measurable (s i)) {t : set α} (ht : is_measurable t) : μ.restrict (⋃ i, s i) t = ∑' i, μ.restrict (s i) t := begin simp only [restrict_apply, ht, inter_Union], exact measure_Union (λ i j hij, (hd i j hij).mono inf_le_right inf_le_right) (λ i, ht.inter (hm i)) end lemma restrict_Union_apply_eq_supr {ι} [encodable ι] {s : ι → set α} (hm : ∀ i, is_measurable (s i)) (hd : directed (⊆) s) {t : set α} (ht : is_measurable t) : μ.restrict (⋃ i, s i) t = ⨆ i, μ.restrict (s i) t := begin simp only [restrict_apply ht, inter_Union], rw [measure_Union_eq_supr], exacts [λ i, ht.inter (hm i), hd.mono_comp _ (λ s₁ s₂, inter_subset_inter_right _)] end lemma restrict_map {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : (map f μ).restrict s = map f (μ.restrict $ f ⁻¹' s) := ext $ λ t ht, by simp [*, hf ht] lemma map_comap_subtype_coe {s : set α} (hs : is_measurable s) : (map (coe : s → α)).comp (comap coe) = restrictₗ s := linear_map.ext $ λ μ, ext $ λ t ht, by rw [restrictₗ_apply, restrict_apply ht, linear_map.comp_apply, map_apply measurable_subtype_coe ht, comap_apply (coe : s → α) subtype.val_injective (λ _, hs.subtype_image) _ (measurable_subtype_coe ht), subtype.image_preimage_coe] /-- Restriction of a measure to a subset is monotone both in set and in measure. -/ @[mono] lemma restrict_mono ⦃s s' : set α⦄ (hs : s ⊆ s') ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) : μ.restrict s ≤ ν.restrict s' := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ (t ∩ s') : measure_mono $ inter_subset_inter_right _ hs ... ≤ ν (t ∩ s') : le_iff'.1 hμν (t ∩ s') ... = ν.restrict s' t : (restrict_apply ht).symm lemma restrict_le_self {s} : μ.restrict s ≤ μ := assume t ht, calc μ.restrict s t = μ (t ∩ s) : restrict_apply ht ... ≤ μ t : measure_mono $ inter_subset_left t s lemma restrict_congr_meas {s} (hs : is_measurable s) : μ.restrict s = ν.restrict s ↔ ∀ t ⊆ s, is_measurable t → μ t = ν t := ⟨λ H t hts ht, by rw [← inter_eq_self_of_subset_left hts, ← restrict_apply ht, H, restrict_apply ht], λ H, ext $ λ t ht, by rw [restrict_apply ht, restrict_apply ht, H _ (inter_subset_right _ _) (ht.inter hs)]⟩ lemma restrict_congr_mono {s t} (hs : s ⊆ t) (hm : is_measurable s) (h : μ.restrict t = ν.restrict t) : μ.restrict s = ν.restrict s := by rw [← inter_eq_self_of_subset_left hs, ← restrict_restrict hm, h, restrict_restrict hm] /-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all measurable subsets of `s ∪ t`. -/ lemma restrict_union_congr {s t : set α} (hsm : is_measurable s) (htm : is_measurable t) : μ.restrict (s ∪ t) = ν.restrict (s ∪ t) ↔ μ.restrict s = ν.restrict s ∧ μ.restrict t = ν.restrict t := begin refine ⟨λ h, ⟨restrict_congr_mono (subset_union_left _ _) hsm h, restrict_congr_mono (subset_union_right _ _) htm h⟩, _⟩, simp only [restrict_congr_meas, hsm, htm, hsm.union htm], rintros ⟨hs, ht⟩ u hu hum, rw [measure_eq_inter_diff hum hsm, measure_eq_inter_diff hum hsm, hs _ (inter_subset_right _ _) (hum.inter hsm), ht _ (diff_subset_iff.2 hu) (hum.diff hsm)] end variables {ι : Type*} lemma restrict_finset_bUnion_congr {s : finset ι} {t : ι → set α} (htm : ∀ i ∈ s, is_measurable (t i)) : μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔ ∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := begin induction s using finset.induction_on with i s hi hs, { simp }, simp only [finset.mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at htm ⊢, simp only [finset.bUnion_insert, ← hs htm.2], exact restrict_union_congr htm.1 (is_measurable.bUnion s.countable_to_set htm.2) end lemma restrict_Union_congr [encodable ι] {s : ι → set α} (hm : ∀ i, is_measurable (s i)) : μ.restrict (⋃ i, s i) = ν.restrict (⋃ i, s i) ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := begin refine ⟨λ h i, restrict_congr_mono (subset_Union _ _) (hm i) h, λ h, _⟩, ext1 t ht, have M : ∀ t : finset ι, is_measurable (⋃ i ∈ t, s i) := λ t, is_measurable.bUnion t.countable_to_set (λ i _, hm i), have D : directed (⊆) (λ t : finset ι, ⋃ i ∈ t, s i) := directed_of_sup (λ t₁ t₂ ht, bUnion_subset_bUnion_left ht), rw [Union_eq_Union_finset], simp only [restrict_Union_apply_eq_supr M D ht, (restrict_finset_bUnion_congr (λ i hi, hm i)).2 (λ i hi, h i)], end lemma restrict_bUnion_congr {s : set ι} {t : ι → set α} (hc : countable s) (htm : ∀ i ∈ s, is_measurable (t i)) : μ.restrict (⋃ i ∈ s, t i) = ν.restrict (⋃ i ∈ s, t i) ↔ ∀ i ∈ s, μ.restrict (t i) = ν.restrict (t i) := begin simp only [bUnion_eq_Union, set_coe.forall'] at htm ⊢, haveI := hc.to_encodable, exact restrict_Union_congr htm end lemma restrict_sUnion_congr {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, is_measurable s) : μ.restrict (⋃₀ S) = ν.restrict (⋃₀ S) ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := by rw [sUnion_eq_bUnion, restrict_bUnion_congr hc hm] /-! ### Extensionality results -/ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `Union`). -/ lemma ext_iff_of_Union_eq_univ [encodable ι] {s : ι → set α} (hm : ∀ i, is_measurable (s i)) (hs : (⋃ i, s i) = univ) : μ = ν ↔ ∀ i, μ.restrict (s i) = ν.restrict (s i) := by rw [← restrict_Union_congr hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_Union_eq_univ ↔ _ measure_theory.measure.ext_of_Union_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `bUnion`). -/ lemma ext_iff_of_bUnion_eq_univ {S : set ι} {s : ι → set α} (hc : countable S) (hm : ∀ i ∈ S, is_measurable (s i)) (hs : (⋃ i ∈ S, s i) = univ) : μ = ν ↔ ∀ i ∈ S, μ.restrict (s i) = ν.restrict (s i) := by rw [← restrict_bUnion_congr hc hm, hs, restrict_univ, restrict_univ] alias ext_iff_of_bUnion_eq_univ ↔ _ measure_theory.measure.ext_of_bUnion_eq_univ /-- Two measures are equal if they have equal restrictions on a spanning collection of sets (formulated using `sUnion`). -/ lemma ext_iff_of_sUnion_eq_univ {S : set (set α)} (hc : countable S) (hm : ∀ s ∈ S, is_measurable s) (hs : (⋃₀ S) = univ) : μ = ν ↔ ∀ s ∈ S, μ.restrict s = ν.restrict s := ext_iff_of_bUnion_eq_univ hc hm $ by rwa ← sUnion_eq_bUnion alias ext_iff_of_sUnion_eq_univ ↔ _ measure_theory.measure.ext_of_sUnion_eq_univ open measurable_space lemma ext_of_generate_from_of_cover {S T : set (set α)} (h_gen : ‹_› = generate_from S) (hc : countable T) (h_inter : is_pi_system S) (hm : ∀ t ∈ T, is_measurable t) (hU : ⋃₀ T = univ) (htop : ∀ t ∈ T, μ t < ⊤) (ST_eq : ∀ (t ∈ T) (s ∈ S), μ (s ∩ t) = ν (s ∩ t)) (T_eq : ∀ t ∈ T, μ t = ν t) : μ = ν := begin refine ext_of_sUnion_eq_univ hc hm hU (λ t ht, _), ext1 u hu, simp only [restrict_apply hu], refine induction_on_inter h_gen h_inter _ (ST_eq t ht) _ _ hu, { simp only [set.empty_inter, measure_empty] }, { intros v hv hvt, have := T_eq t ht, rw [set.inter_comm] at hvt ⊢, rwa [measure_eq_inter_diff (hm _ ht) hv, measure_eq_inter_diff (hm _ ht) hv, ← hvt, ennreal.add_right_inj] at this, exact (measure_mono $ set.inter_subset_left _ _).trans_lt (htop t ht) }, { intros f hfd hfm h_eq, have : pairwise (disjoint on λ n, f n ∩ t) := λ m n hmn, (hfd m n hmn).mono (inter_subset_left _ _) (inter_subset_left _ _), simp only [Union_inter, measure_Union this (λ n, is_measurable.inter (hfm n) (hm t ht)), h_eq] } end /-- Two measures are equal if they are equal on the π-system generating the σ-algebra, and they are both finite on a increasing spanning sequence of sets in the π-system. This lemma is formulated using `sUnion`. -/ lemma ext_of_generate_from_of_cover_subset {S T : set (set α)} (h_gen : ‹_› = generate_from S) (h_inter : is_pi_system S) (h_sub : T ⊆ S) (hc : countable T) (hU : ⋃₀ T = univ) (htop : ∀ s ∈ T, μ s < ⊤) (h_eq : ∀ s ∈ S, μ s = ν s) : μ = ν := begin refine ext_of_generate_from_of_cover h_gen hc h_inter _ hU htop _ (λ t ht, h_eq t (h_sub ht)), { intros t ht, rw [h_gen], exact generate_measurable.basic _ (h_sub ht) }, { intros t ht s hs, cases (s ∩ t).eq_empty_or_nonempty with H H, { simp only [H, measure_empty] }, { exact h_eq _ (h_inter _ _ hs (h_sub ht) H) } } end /-- Two measures are equal if they are equal on the π-system generating the σ-algebra, and they are both finite on a increasing spanning sequence of sets in the π-system. This lemma is formulated using `Union`. -/ lemma ext_of_generate_from_of_Union (C : set (set α)) (B : ℕ → set α) (hA : ‹_› = generate_from C) (hC : is_pi_system C) (h1B : (⋃ i, B i) = univ) (h2B : ∀ i, B i ∈ C) (hμB : ∀ i, μ (B i) < ⊤) (h_eq : ∀ s ∈ C, μ s = ν s) : μ = ν := begin refine measure.ext_of_generate_from_of_cover_subset hA hC _ (countable_range B) h1B _ h_eq, { rintro _ ⟨i, rfl⟩, apply h2B }, { rintro _ ⟨i, rfl⟩, apply hμB } end /-- The dirac measure. -/ def dirac (a : α) : measure α := (outer_measure.dirac a).to_measure (by simp) lemma dirac_apply' (a : α) {s : set α} (hs : is_measurable s) : dirac a s = ⨆ h : a ∈ s, 1 := to_measure_apply _ _ hs @[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) : dirac a s = s.indicator 1 a := (dirac_apply' a hs).trans $ by { by_cases h : a ∈ s; simp [h] } lemma dirac_apply_of_mem {a : α} {s : set α} (h : a ∈ s) : dirac a s = 1 := begin rw [measure_eq_infi, infi_subtype', infi_subtype'], convert infi_const, { ext1 ⟨⟨t, hst⟩, ht⟩, dsimp only [subtype.coe_mk] at *, simp only [dirac_apply _ ht, indicator_of_mem (hst h), pi.one_apply] }, { exact ⟨⟨⟨set.univ, subset_univ _⟩, is_measurable.univ⟩⟩ } end /-- Sum of an indexed family of measures. -/ def sum {ι : Type*} (f : ι → measure α) : measure α := (outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $ le_trans (by exact le_infi (λ i, le_to_outer_measure_caratheodory _)) (outer_measure.le_sum_caratheodory _) @[simp] lemma sum_apply {ι : Type*} (f : ι → measure α) {s : set α} (hs : is_measurable s) : sum f s = ∑' i, f i s := to_measure_apply _ _ hs lemma le_sum {ι : Type*} (μ : ι → measure α) (i : ι) : μ i ≤ sum μ := λ s hs, by simp only [sum_apply μ hs, ennreal.le_tsum i] lemma restrict_Union {ι} [encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s)) (hm : ∀ i, is_measurable (s i)) : μ.restrict (⋃ i, s i) = sum (λ i, μ.restrict (s i)) := ext $ λ t ht, by simp only [sum_apply _ ht, restrict_Union_apply hd hm ht] lemma restrict_Union_le {ι} [encodable ι] {s : ι → set α} : μ.restrict (⋃ i, s i) ≤ sum (λ i, μ.restrict (s i)) := begin intros t ht, suffices : μ (⋃ i, t ∩ s i) ≤ ∑' i, μ (t ∩ s i), by simpa [ht, inter_Union], apply measure_Union_le end @[simp] lemma sum_bool (f : bool → measure α) : sum f = f tt + f ff := ext $ λ s hs, by simp [hs, tsum_fintype] @[simp] lemma restrict_sum {ι : Type*} (μ : ι → measure α) {s : set α} (hs : is_measurable s) : (sum μ).restrict s = sum (λ i, (μ i).restrict s) := ext $ λ t ht, by simp only [sum_apply, restrict_apply, ht, ht.inter hs] /-- Counting measure on any measurable space. -/ def count : measure α := sum dirac lemma count_apply {s : set α} (hs : is_measurable s) : count s = ∑' i : s, 1 := by simp only [count, sum_apply, hs, dirac_apply, ← tsum_subtype s 1, pi.one_apply] @[simp] lemma count_apply_finset [measurable_singleton_class α] (s : finset α) : count (↑s : set α) = s.card := calc count (↑s : set α) = ∑' i : (↑s : set α), (1 : α → ennreal) i : count_apply s.is_measurable ... = ∑ i in s, 1 : s.tsum_subtype 1 ... = s.card : by simp lemma count_apply_finite [measurable_singleton_class α] (s : set α) (hs : finite s) : count s = hs.to_finset.card := by rw [← count_apply_finset, finite.coe_to_finset] /-- `count` measure evaluates to infinity at infinite sets. -/ lemma count_apply_infinite [measurable_singleton_class α] {s : set α} (hs : s.infinite) : count s = ⊤ := begin by_contra H, rcases ennreal.exists_nat_gt H with ⟨n, hn⟩, rcases hs.exists_subset_card_eq n with ⟨t, ht, rfl⟩, have := lt_of_le_of_lt (measure_mono ht) hn, simpa [lt_irrefl] using this end @[simp] lemma count_apply_eq_top [measurable_singleton_class α] {s : set α} : count s = ⊤ ↔ s.infinite := begin by_cases hs : s.finite, { simp [set.infinite, hs, count_apply_finite] }, { change s.infinite at hs, simp [hs, count_apply_infinite] } end @[simp] lemma count_apply_lt_top [measurable_singleton_class α] {s : set α} : count s < ⊤ ↔ s.finite := calc count s < ⊤ ↔ count s ≠ ⊤ : lt_top_iff_ne_top ... ↔ ¬s.infinite : not_congr count_apply_eq_top ... ↔ s.finite : not_not open measurable_space /-! ### The almost everywhere filter -/ /-- The “almost everywhere” filter of co-null sets. -/ def ae (μ : measure α) : filter α := { sets := {s | μ sᶜ = 0}, univ_sets := by simp, inter_sets := λ s t hs ht, by simp only [compl_inter, mem_set_of_eq]; exact measure_union_null hs ht, sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs } /-- The filter of sets `s` such that `sᶜ` has finite measure. -/ def cofinite (μ : measure α) : filter α := { sets := {s | μ sᶜ < ⊤}, univ_sets := by simp, inter_sets := λ s t hs ht, by { simp only [compl_inter, mem_set_of_eq], calc μ (sᶜ ∪ tᶜ) ≤ μ sᶜ + μ tᶜ : measure_union_le _ _ ... < ⊤ : ennreal.add_lt_top.2 ⟨hs, ht⟩ }, sets_of_superset := λ s t hs hst, lt_of_le_of_lt (measure_mono $ compl_subset_compl.2 hst) hs } lemma mem_cofinite {s : set α} : s ∈ μ.cofinite ↔ μ sᶜ < ⊤ := iff.rfl lemma compl_mem_cofinite {s : set α} : sᶜ ∈ μ.cofinite ↔ μ s < ⊤ := by rw [mem_cofinite, compl_compl] lemma eventually_cofinite {p : α → Prop} : (∀ᶠ x in μ.cofinite, p x) ↔ μ {x | ¬p x} < ⊤ := iff.rfl end measure variables {α : Type*} {β : Type*} [measurable_space α] {μ : measure α} notation `∀ᵐ` binders ` ∂` μ `, ` r:(scoped P, filter.eventually P (measure.ae μ)) := r notation f ` =ᵐ[`:50 μ:50 `] `:0 g:50 := f =ᶠ[measure.ae μ] g notation f ` ≤ᵐ[`:50 μ:50 `] `:0 g:50 := f ≤ᶠ[measure.ae μ] g lemma mem_ae_iff {s : set α} : s ∈ μ.ae ↔ μ sᶜ = 0 := iff.rfl lemma ae_iff {p : α → Prop} : (∀ᵐ a ∂ μ, p a) ↔ μ { a | ¬ p a } = 0 := iff.rfl lemma compl_mem_ae_iff {s : set α} : sᶜ ∈ μ.ae ↔ μ s = 0 := by simp only [mem_ae_iff, compl_compl] lemma measure_zero_iff_ae_nmem {s : set α} : μ s = 0 ↔ ∀ᵐ a ∂ μ, a ∉ s := compl_mem_ae_iff.symm @[simp] lemma ae_eq_bot : μ.ae = ⊥ ↔ μ = 0 := by rw [← empty_in_sets_eq_bot, mem_ae_iff, compl_empty, measure.measure_univ_eq_zero] lemma ae_of_all {p : α → Prop} (μ : measure α) : (∀a, p a) → ∀ᵐ a ∂ μ, p a := eventually_of_forall @[mono] lemma ae_mono {μ ν : measure α} (h : μ ≤ ν) : μ.ae ≤ ν.ae := λ s hs, bot_unique $ trans_rel_left (≤) (measure.le_iff'.1 h _) hs instance : countable_Inter_filter μ.ae := ⟨begin intros S hSc hS, simp only [mem_ae_iff, compl_sInter, sUnion_image, bUnion_eq_Union] at hS ⊢, haveI := hSc.to_encodable, exact measure_Union_null (subtype.forall.2 hS) end⟩ instance ae_is_measurably_generated : is_measurably_generated μ.ae := ⟨λ s hs, let ⟨t, hst, htm, htμ⟩ := exists_is_measurable_superset_of_measure_eq_zero hs in ⟨tᶜ, compl_mem_ae_iff.2 htμ, htm.compl, compl_subset_comm.1 hst⟩⟩ lemma ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} : (∀ᵐ a ∂ μ, ∀i, p a i) ↔ (∀i, ∀ᵐ a ∂ μ, p a i) := eventually_countable_forall lemma ae_ball_iff {ι} {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} : (∀ᵐ x ∂ μ, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᵐ x ∂ μ, p x i ‹_› := eventually_countable_ball hS lemma ae_eq_refl (f : α → β) : f =ᵐ[μ] f := eventually_eq.refl _ _ lemma ae_eq_symm {f g : α → β} (h : f =ᵐ[μ] g) : g =ᵐ[μ] f := h.symm lemma ae_eq_trans {f g h: α → β} (h₁ : f =ᵐ[μ] g) (h₂ : g =ᵐ[μ] h) : f =ᵐ[μ] h := h₁.trans h₂ lemma ae_eq_empty {s : set α} : s =ᵐ[μ] (∅ : set α) ↔ μ s = 0 := eventually_eq_empty.trans $ by simp [ae_iff] lemma ae_le_set {s t : set α} : s ≤ᵐ[μ] t ↔ μ (s \ t) = 0 := calc s ≤ᵐ[μ] t ↔ ∀ᵐ x ∂μ, x ∈ s → x ∈ t : iff.rfl ... ↔ μ (s \ t) = 0 : by simp [ae_iff]; refl lemma union_ae_eq_right {s t : set α} : (s ∪ t : set α) =ᵐ[μ] t ↔ μ (s \ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, union_diff_right, diff_eq_empty.2 (set.subset_union_right _ _)] lemma diff_ae_eq_self {s t : set α} : (s \ t : set α) =ᵐ[μ] s ↔ μ (s ∩ t) = 0 := by simp [eventually_le_antisymm_iff, ae_le_set, diff_diff_right, diff_diff, diff_eq_empty.2 (set.subset_union_right _ _)] lemma mem_ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) : s ∈ (measure.map f μ).ae ↔ (f ⁻¹' s) ∈ μ.ae := by simp only [mem_ae_iff, measure.map_apply hf hs.compl, preimage_compl] lemma ae_map_iff [measurable_space β] {f : α → β} (hf : measurable f) {p : β → Prop} (hp : is_measurable {x | p x}) : (∀ᵐ y ∂ (measure.map f μ), p y) ↔ ∀ᵐ x ∂ μ, p (f x) := mem_ae_map_iff hf hp lemma ae_restrict_iff {s : set α} {p : α → Prop} (hp : is_measurable {x | p x}) : (∀ᵐ x ∂(μ.restrict s), p x) ↔ ∀ᵐ x ∂μ, x ∈ s → p x := begin simp only [ae_iff, ← compl_set_of, measure.restrict_apply hp.compl], congr' with x, simp [and_comm] end lemma ae_smul_measure {p : α → Prop} (h : ∀ᵐ x ∂μ, p x) (c : ennreal) : ∀ᵐ x ∂(c • μ), p x := ae_iff.2 $ by rw [measure.smul_apply, ae_iff.1 h, mul_zero] lemma ae_add_measure_iff {p : α → Prop} {ν} : (∀ᵐ x ∂μ + ν, p x) ↔ (∀ᵐ x ∂μ, p x) ∧ ∀ᵐ x ∂ν, p x := add_eq_zero_iff @[simp] lemma ae_restrict_eq {s : set α} (hs : is_measurable s): (μ.restrict s).ae = μ.ae ⊓ 𝓟 s := begin ext t, simp only [mem_inf_principal, mem_ae_iff, measure.restrict_apply_eq_zero' hs, compl_set_of, not_imp, and_comm (_ ∈ s)], refl end @[simp] lemma ae_restrict_eq_bot {s} : (μ.restrict s).ae = ⊥ ↔ μ s = 0 := ae_eq_bot.trans measure.restrict_eq_zero @[simp] lemma ae_restrict_ne_bot {s} : (μ.restrict s).ae.ne_bot ↔ 0 < μ s := (not_congr ae_restrict_eq_bot).trans zero_lt_iff_ne_zero.symm /-- A version of the Borel-Cantelli lemma: if sᵢ is a sequence of measurable sets such that ∑ μ sᵢ exists, then for almost all x, x does not belong to almost all sᵢ. -/ lemma ae_eventually_not_mem {s : ℕ → set α} (hs : ∀ i, is_measurable (s i)) (hs' : (∑' i, μ (s i)) ≠ ⊤) : ∀ᵐ x ∂ μ, ∀ᶠ n in at_top, x ∉ s n := begin refine measure_mono_null _ (measure_limsup_eq_zero hs hs'), rw ←set.le_eq_subset, refine le_Inf (λ t ht x hx, _), simp only [le_eq_subset, not_exists, eventually_map, exists_prop, ge_iff_le, mem_set_of_eq, eventually_at_top, mem_compl_eq, not_forall, not_not_mem] at hx ht, rcases ht with ⟨i, hi⟩, rcases hx i with ⟨j, ⟨hj, hj'⟩⟩, exact hi j hj hj' end lemma mem_dirac_ae_iff {a : α} {s : set α} (hs : is_measurable s) : s ∈ (measure.dirac a).ae ↔ a ∈ s := by by_cases a ∈ s; simp [mem_ae_iff, measure.dirac_apply, hs.compl, indicator_apply, *] lemma eventually_dirac {a : α} {p : α → Prop} (hp : is_measurable {x | p x}) : (∀ᵐ x ∂(measure.dirac a), p x) ↔ p a := mem_dirac_ae_iff hp lemma eventually_eq_dirac [measurable_space β] [measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) : f =ᵐ[measure.dirac a] const α (f a) := (eventually_dirac $ show is_measurable (f ⁻¹' {f a}), from hf $ is_measurable_singleton _).2 rfl lemma dirac_ae_eq [measurable_singleton_class α] (a : α) : (measure.dirac a).ae = pure a := begin ext s, simp only [mem_ae_iff, mem_pure_sets], by_cases ha : a ∈ s, { simp only [ha, iff_true], rw [← set.singleton_subset_iff, ← compl_subset_compl] at ha, refine measure_mono_null ha _, simp [measure.dirac_apply a (is_measurable_singleton a).compl] }, { simp only [ha, iff_false, measure.dirac_apply_of_mem (mem_compl ha)], exact one_ne_zero } end lemma eventually_eq_dirac' [measurable_singleton_class α] {a : α} (f : α → β) : f =ᵐ[measure.dirac a] const α (f a) := by { rw [dirac_ae_eq], show f a = f a, refl } lemma measure_diff_of_ae_le {s t : set α} (H : s ≤ᵐ[μ] t) : μ (s \ t) = 0 := flip measure_mono_null H $ λ x hx H, hx.2 (H hx.1) /-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/ lemma measure_mono_ae {s t : set α} (H : s ≤ᵐ[μ] t) : μ s ≤ μ t := calc μ s ≤ μ (s ∪ t) : measure_mono $ subset_union_left s t ... = μ (t ∪ s \ t) : by rw [union_diff_self, set.union_comm] ... ≤ μ t + μ (s \ t) : measure_union_le _ _ ... = μ t : by rw [measure_diff_of_ae_le H, add_zero] alias measure_mono_ae ← filter.eventually_le.measure_le /-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/ lemma measure_congr {s t : set α} (H : s =ᵐ[μ] t) : μ s = μ t := le_antisymm H.le.measure_le H.symm.le.measure_le lemma restrict_mono_ae {s t : set α} (h : s ≤ᵐ[μ] t) : μ.restrict s ≤ μ.restrict t := begin intros u hu, simp only [measure.restrict_apply hu], exact measure_mono_ae (h.mono $ λ x hx, and.imp id hx) end lemma restrict_congr_set {s t : set α} (H : s =ᵐ[μ] t) : μ.restrict s = μ.restrict t := le_antisymm (restrict_mono_ae H.le) (restrict_mono_ae H.symm.le) /-- A measure `μ` is called a probability measure if `μ univ = 1`. -/ class probability_measure (μ : measure α) : Prop := (measure_univ : μ univ = 1) /-- A measure `μ` is called finite if `μ univ < ⊤`. -/ class finite_measure (μ : measure α) : Prop := (measure_univ_lt_top : μ univ < ⊤) instance restrict.finite_measure (μ : measure α) {s : set α} [hs : fact (μ s < ⊤)] : finite_measure (μ.restrict s) := ⟨by simp [hs.elim]⟩ /-- Measure `μ` *has no atoms* if the measure of each singleton is zero. NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure, there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`, the converse is not true. -/ class has_no_atoms (μ : measure α) : Prop := (measure_singleton : ∀ x, μ {x} = 0) export probability_measure (measure_univ) has_no_atoms (measure_singleton) attribute [simp] measure_singleton lemma measure_lt_top (μ : measure α) [finite_measure μ] (s : set α) : μ s < ⊤ := (measure_mono (subset_univ s)).trans_lt finite_measure.measure_univ_lt_top lemma measure_ne_top (μ : measure α) [finite_measure μ] (s : set α) : μ s ≠ ⊤ := ne_of_lt (measure_lt_top μ s) @[priority 100] instance probability_measure.to_finite_measure (μ : measure α) [probability_measure μ] : finite_measure μ := ⟨by simp only [measure_univ, ennreal.one_lt_top]⟩ lemma probability_measure.ne_zero (μ : measure α) [probability_measure μ] : μ ≠ 0 := mt measure.measure_univ_eq_zero.2 $ by simp [measure_univ] section no_atoms variables [has_no_atoms μ] lemma measure_countable {s : set α} (h : countable s) : μ s = 0 := begin rw [← bUnion_of_singleton s, ← le_zero_iff_eq], refine le_trans (measure_bUnion_le h _) _, simp end lemma measure_finite {s : set α} (h : s.finite) : μ s = 0 := measure_countable h.countable lemma measure_finset (s : finset α) : μ ↑s = 0 := measure_finite s.finite_to_set lemma insert_ae_eq_self (a : α) (s : set α) : (insert a s : set α) =ᵐ[μ] s := union_ae_eq_right.2 $ measure_mono_null (diff_subset _ _) (measure_singleton _) variables [partial_order α] {a b : α} lemma Iio_ae_eq_Iic : Iio a =ᵐ[μ] Iic a := by simp only [← Iic_diff_right, diff_ae_eq_self, measure_mono_null (set.inter_subset_right _ _) (measure_singleton a)] lemma Ioi_ae_eq_Ici : Ioi a =ᵐ[μ] Ici a := @Iio_ae_eq_Iic (order_dual α) ‹_› ‹_› _ _ _ lemma Ioo_ae_eq_Ioc : Ioo a b =ᵐ[μ] Ioc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ioc_ae_eq_Icc : Ioc a b =ᵐ[μ] Icc a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Ico : Ioo a b =ᵐ[μ] Ico a b := Ioi_ae_eq_Ici.inter (ae_eq_refl _) lemma Ioo_ae_eq_Icc : Ioo a b =ᵐ[μ] Icc a b := Ioi_ae_eq_Ici.inter Iio_ae_eq_Iic lemma Ico_ae_eq_Icc : Ico a b =ᵐ[μ] Icc a b := (ae_eq_refl _).inter Iio_ae_eq_Iic lemma Ico_ae_eq_Ioc : Ico a b =ᵐ[μ] Ioc a b := Ioo_ae_eq_Ico.symm.trans Ioo_ae_eq_Ioc end no_atoms /-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`. Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/ def measure.finite_at_filter (μ : measure α) (f : filter α) : Prop := ∃ s ∈ f, μ s < ⊤ lemma finite_at_filter_of_finite (μ : measure α) [finite_measure μ] (f : filter α) : μ.finite_at_filter f := ⟨univ, univ_mem_sets, measure_lt_top μ univ⟩ lemma measure.finite_at_bot (μ : measure α) : μ.finite_at_filter ⊥ := ⟨∅, mem_bot_sets, by simp only [measure_empty, with_top.zero_lt_top]⟩ /-- A measure `μ` is called σ-finite if there is a countable collection of sets `{ A i | i ∈ ℕ }` such that `μ (A i) < ⊤` and `⋃ i, A i = s`. -/ class sigma_finite (μ : measure α) : Prop := (exists_finite_spanning_sets : ∃ s : ℕ → set α, (∀ i, is_measurable (s i)) ∧ (∀ i, μ (s i) < ⊤) ∧ (⋃ i, s i) = univ) lemma exists_finite_spanning_sets (μ : measure α) [sigma_finite μ] : ∃ s : ℕ → set α, (∀ i, is_measurable (s i)) ∧ (∀ i, μ (s i) < ⊤) ∧ (⋃ i, s i) = univ := sigma_finite.exists_finite_spanning_sets /-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite measure using `classical.some`. This definition satisfies monotonicity in addition to all other properties in `sigma_finite`. -/ def spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : set α := accumulate (classical.some $ exists_finite_spanning_sets μ) i lemma monotone_spanning_sets (μ : measure α) [sigma_finite μ] : monotone (spanning_sets μ) := monotone_accumulate lemma is_measurable_spanning_sets (μ : measure α) [sigma_finite μ] (i : ℕ) : is_measurable (spanning_sets μ i) := is_measurable.Union $ λ j, is_measurable.Union_Prop $ λ hij, (classical.some_spec $ exists_finite_spanning_sets μ).1 j lemma measure_spanning_sets_lt_top (μ : measure α) [sigma_finite μ] (i : ℕ) : μ (spanning_sets μ i) < ⊤ := measure_bUnion_lt_top (finite_le_nat i) $ λ j _, (classical.some_spec $ exists_finite_spanning_sets μ).2.1 j lemma Union_spanning_sets (μ : measure α) [sigma_finite μ] : (⋃ i : ℕ, spanning_sets μ i) = univ := by simp_rw [spanning_sets, Union_accumulate, (classical.some_spec $ exists_finite_spanning_sets μ).2.2] namespace measure lemma supr_restrict_spanning_sets {μ : measure α} [sigma_finite μ] {s : set α} (hs : is_measurable s) : (⨆ i, μ.restrict (spanning_sets μ i) s) = μ s := begin convert (restrict_Union_apply_eq_supr (is_measurable_spanning_sets μ) _ hs).symm, { simp [Union_spanning_sets] }, { exact directed_of_sup (monotone_spanning_sets μ) } end end measure open measure /-- Every finite measure is σ-finite. -/ @[priority 100] instance finite_measure.to_sigma_finite (μ : measure α) [finite_measure μ] : sigma_finite μ := ⟨⟨λ _, univ, λ _, is_measurable.univ, λ _, measure_lt_top μ _, Union_const _⟩⟩ instance restrict.sigma_finite (μ : measure α) [sigma_finite μ] (s : set α) : sigma_finite (μ.restrict s) := begin refine ⟨⟨spanning_sets μ, is_measurable_spanning_sets μ, λ i, _, Union_spanning_sets μ⟩⟩, rw [restrict_apply (is_measurable_spanning_sets μ i)], exact (measure_mono $ inter_subset_left _ _).trans_lt (measure_spanning_sets_lt_top μ i) end /-- A measure is called locally finite if it is finite in some neighborhood of each point. -/ class locally_finite_measure [topological_space α] (μ : measure α) : Prop := (finite_at_nhds : ∀ x, μ.finite_at_filter (𝓝 x)) @[priority 100] instance finite_measure.to_locally_finite_measure [topological_space α] (μ : measure α) [finite_measure μ] : locally_finite_measure μ := ⟨λ x, finite_at_filter_of_finite _ _⟩ lemma measure.finite_at_nhds [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) : μ.finite_at_filter (𝓝 x) := locally_finite_measure.finite_at_nhds x open measurable_space /-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra (and `univ`). -/ lemma ext_of_generate_finite (C : set (set α)) (hA : _inst_1 = generate_from C) (hC : is_pi_system C) {μ ν : measure α} [finite_measure μ] [finite_measure ν] (hμν : ∀ s ∈ C, μ s = ν s) (h_univ : μ univ = ν univ) : μ = ν := begin ext1 s hs, refine induction_on_inter hA hC (by simp) hμν _ _ hs, { rintros t h1t h2t, change is_measurable t at h1t, simp [measure_compl, measure_lt_top, *] }, { rintros f h1f h2f h3f, simp [measure_Union, is_measurable.Union, *] } end namespace measure namespace finite_at_filter variables {ν : measure α} {f g : filter α} lemma filter_mono (h : f ≤ g) : μ.finite_at_filter g → μ.finite_at_filter f := λ ⟨s, hs, hμ⟩, ⟨s, h hs, hμ⟩ lemma inf_of_left (h : μ.finite_at_filter f) : μ.finite_at_filter (f ⊓ g) := h.filter_mono inf_le_left lemma inf_of_right (h : μ.finite_at_filter g) : μ.finite_at_filter (f ⊓ g) := h.filter_mono inf_le_right @[simp] lemma inf_ae_iff : μ.finite_at_filter (f ⊓ μ.ae) ↔ μ.finite_at_filter f := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hμ⟩, suffices : μ t ≤ μ s, from ⟨t, ht, this.trans_lt hμ⟩, exact measure_mono_ae (mem_sets_of_superset hu (λ x hu ht, hs ⟨ht, hu⟩)) end alias inf_ae_iff ↔ measure_theory.measure.finite_at_filter.of_inf_ae _ lemma filter_mono_ae (h : f ⊓ μ.ae ≤ g) (hg : μ.finite_at_filter g) : μ.finite_at_filter f := inf_ae_iff.1 (hg.filter_mono h) protected lemma measure_mono (h : μ ≤ ν) : ν.finite_at_filter f → μ.finite_at_filter f := λ ⟨s, hs, hν⟩, ⟨s, hs, (measure.le_iff'.1 h s).trans_lt hν⟩ @[mono] protected lemma mono (hf : f ≤ g) (hμ : μ ≤ ν) : ν.finite_at_filter g → μ.finite_at_filter f := λ h, (h.filter_mono hf).measure_mono hμ protected lemma eventually (h : μ.finite_at_filter f) : ∀ᶠ s in f.lift' powerset, μ s < ⊤ := (eventually_lift'_powerset' $ λ s t hst ht, (measure_mono hst).trans_lt ht).2 h lemma filter_sup : μ.finite_at_filter f → μ.finite_at_filter g → μ.finite_at_filter (f ⊔ g) := λ ⟨s, hsf, hsμ⟩ ⟨t, htg, htμ⟩, ⟨s ∪ t, union_mem_sup hsf htg, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hsμ, htμ⟩)⟩ end finite_at_filter lemma finite_at_nhds_within [topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) (s : set α) : μ.finite_at_filter (𝓝[s] x) := (finite_at_nhds μ x).inf_of_left @[simp] lemma finite_at_principal {s : set α} : μ.finite_at_filter (𝓟 s) ↔ μ s < ⊤ := ⟨λ ⟨t, ht, hμ⟩, (measure_mono ht).trans_lt hμ, λ h, ⟨s, mem_principal_self s, h⟩⟩ end measure end measure_theory section is_complete open measure_theory measure_theory.measure /-- A measure is complete if every null set is also measurable. A null set is a subset of a measurable set with measure `0`. Since every measure is defined as a special case of an outer measure, we can more simply state that a set `s` is null if `μ s = 0`. -/ @[class] def measure_theory.measure.is_complete {α} {_:measurable_space α} (μ : measure α) : Prop := ∀ s, μ s = 0 → is_measurable s variables {α : Type*} [measurable_space α] (μ : measure α) /-- A set is null measurable if it is the union of a null set and a measurable set. -/ def is_null_measurable (s : set α) : Prop := ∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0 theorem is_null_measurable_iff {μ : measure α} {s : set α} : is_null_measurable μ s ↔ ∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 := begin split, { rintro ⟨t, z, rfl, ht, hz⟩, refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩, simp [union_diff_left, diff_subset] }, { rintro ⟨t, st, ht, hz⟩, exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ } end theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α} (st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t := begin refine le_antisymm _ (measure_mono st), have := measure_union_le t (s \ t), rw [union_diff_cancel st, hz] at this, simpa end theorem is_measurable.is_null_measurable {s : set α} (hs : is_measurable s) : is_null_measurable μ s := ⟨s, ∅, by simp, hs, μ.empty⟩ theorem is_null_measurable_of_complete [c : μ.is_complete] {s : set α} : is_null_measurable μ s ↔ is_measurable s := ⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact is_measurable.union ht (c _ hz), λ h, h.is_null_measurable _⟩ variables {μ} theorem is_null_measurable.union_null {s z : set α} (hs : is_null_measurable μ s) (hz : μ z = 0) : is_null_measurable μ (s ∪ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1 (le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩ end theorem null_is_null_measurable {z : set α} (hz : μ z = 0) : is_null_measurable μ z := by simpa using (is_measurable.empty.is_null_measurable _).union_null hz theorem is_null_measurable.Union_nat {s : ℕ → set α} (hs : ∀ i, is_null_measurable μ (s i)) : is_null_measurable μ (Union s) := begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, refine is_null_measurable_iff.2 ⟨Union t, Union_subset_Union st, is_measurable.Union ht, measure_mono_null _ (measure_Union_null hz)⟩, rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) end theorem is_measurable.diff_null {s z : set α} (hs : is_measurable s) (hz : μ z = 0) : is_null_measurable μ (s \ z) := begin rw measure_eq_infi at hz, choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α, z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal), { rintro ⟨ε, ε0⟩, have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 }, rw ← hz at this, simpa [infi_lt_iff] }, refine is_null_measurable_iff.2 ⟨s \ Inter f, diff_subset_diff_right (subset_Inter (λ i, (hf i).1)), hs.diff (is_measurable.Inter (λ i, (hf i).2.1)), measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩, { exact Inter f }, { rw [diff_subset_iff, diff_union_self], exact subset.trans (diff_subset _ _) (subset_union_left _ _) }, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩, simp at ε0, apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h), exact measure_mono (Inter_subset _ _) end theorem is_null_measurable.diff_null {s z : set α} (hs : is_null_measurable μ s) (hz : μ z = 0) : is_null_measurable μ (s \ z) := begin rcases hs with ⟨t, z', rfl, ht, hz'⟩, rw [set.union_diff_distrib], exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz') end theorem is_null_measurable.compl {s : set α} (hs : is_null_measurable μ s) : is_null_measurable μ sᶜ := begin rcases hs with ⟨t, z, rfl, ht, hz⟩, rw compl_union, exact ht.compl.diff_null hz end /-- The measurable space of all null measurable sets. -/ def null_measurable {α : Type u} [measurable_space α] (μ : measure α) : measurable_space α := { is_measurable' := is_null_measurable μ, is_measurable_empty := is_measurable.empty.is_null_measurable _, is_measurable_compl := λ s hs, hs.compl, is_measurable_Union := λ f, is_null_measurable.Union_nat } /-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/ def completion {α : Type u} [measurable_space α] (μ : measure α) : @measure_theory.measure α (null_measurable μ) := { to_outer_measure := μ.to_outer_measure, m_Union := λ s hs hd, show μ (Union s) = ∑' i, μ (s i), begin choose t ht using assume i, is_null_measurable_iff.1 (hs i), simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩, rw is_null_measurable_measure_eq (Union_subset_Union st), { rw measure_Union _ ht, { congr, funext i, exact (is_null_measurable_measure_eq (st i) (hz i)).symm }, { rintro i j ij x ⟨h₁, h₂⟩, exact hd i j ij ⟨st i h₁, st j h₂⟩ } }, { refine measure_mono_null _ (measure_Union_null hz), rw [diff_subset_iff, ← Union_union_distrib], exact Union_subset_Union (λ i, by rw ← diff_subset_iff) } end, trimmed := begin letI := null_measurable μ, refine le_antisymm (λ s, _) (outer_measure.le_trim _), rw outer_measure.trim_eq_infi, dsimp, clear _inst, resetI, rw measure_eq_infi s, exact infi_le_infi (λ t, infi_le_infi $ λ st, infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩) end } instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) : (completion μ).is_complete := λ z hz, null_is_null_measurable hz end is_complete namespace measure_theory /-- A measure space is a measurable space equipped with a measure, referred to as `volume`. -/ class measure_space (α : Type*) extends measurable_space α := (volume : measure α) export measure_space (volume) /-- `volume` is the canonical measure on `α`. -/ add_decl_doc volume section measure_space variables {α : Type*} {ι : Type*} [measure_space α] {s₁ s₂ : set α} notation `∀ᵐ` binders `, ` r:(scoped P, filter.eventually P (measure.ae volume)) := r /-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/ meta def volume_tac : tactic unit := `[exact measure_theory.measure_space.volume] end measure_space end measure_theory open measure_theory namespace is_compact variables {α : Type*} [topological_space α] [measurable_space α] {μ : measure α} {s : set α} lemma finite_measure_of_nhds_within (hs : is_compact s) : (∀ a ∈ s, μ.finite_at_filter (𝓝[s] a)) → μ s < ⊤ := by simpa only [← measure.compl_mem_cofinite, measure.finite_at_filter] using hs.compl_mem_sets_of_nhds_within lemma finite_measure [locally_finite_measure μ] (hs : is_compact s) : μ s < ⊤ := hs.finite_measure_of_nhds_within $ λ a ha, μ.finite_at_nhds_within _ _ lemma measure_zero_of_nhds_within (hs : is_compact s) : (∀ a ∈ s, ∃ t ∈ 𝓝[s] a, μ t = 0) → μ s = 0 := by simpa only [← compl_mem_ae_iff] using hs.compl_mem_sets_of_nhds_within end is_compact lemma metric.bounded.finite_measure {α : Type*} [metric_space α] [proper_space α] [measurable_space α] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : metric.bounded s) : μ s < ⊤ := (measure_mono subset_closure).trans_lt (metric.compact_iff_closed_bounded.2 ⟨is_closed_closure, metric.bounded_closure_of_bounded hs⟩).finite_measure
62bc2b7737874bf032a40886712d98e4e8ccf71e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/rewriter16.lean
596fb7a470c468d6a9c1b9120fc733e891daf08c
[ "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
124
lean
import data.nat open nat algebra theorem tst (x : nat) (H1 : x = 0) : x = 0 := begin rewrite *add_zero, rewrite H1 end
c8dba7abc574cf689b513718818736814b0a6fd7
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/real/default.lean
21e4a435fdfe8195337a46f0dfa4b80c1a224b29
[ "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
202
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import .basic .order .division .complete
5c8a1b38f1e4bd509c407e001e0a2a824e75e138
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1025.lean
74d5023bceacc512cb0be7698e638bb572913b31
[ "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
774
lean
inductive Vector (α : Type u): Nat → Type u where | nil : Vector α 0 | cons (head : α) (tail : Vector α n) : Vector α (n+1) class Order (α : Type u) extends LE α, LT α, Max α where ltDecidable : DecidableRel (@LT.lt α _) max_def x y : max x y = if x < y then x else y namespace Vector def mem (a : α) : Vector α n → Prop | nil => False | cons b l => a = b ∨ mem a l def foldr (f : α → β → β) (init : β) : Vector α n → β | nil => init | cons a l => f a (foldr f init l) theorem foldr_max [Order β] {v: Vector α n} (f : α → β) (init : β) (h: v.mem y): f y ≤ v.foldr (λ x acc => max (f x) acc) init := by induction v <;> simp only[foldr,Order.max_def] · admit · split <;> admit end Vector
213478321511b5daa49ed7ace9800213146f1cff
61ccc57f9d72048e493dd6969b56ebd7f0a8f9e8
/src/analysis/analytic/composition.lean
277d860c275381b18a1f1a7cde587987c2498b33
[ "Apache-2.0" ]
permissive
jtristan/mathlib
375b3c8682975df28f79f53efcb7c88840118467
8fa8f175271320d675277a672f59ec53abd62f10
refs/heads/master
1,651,072,765,551
1,588,255,641,000
1,588,255,641,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,946
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.analytic.basic import combinatorics.composition /-! # Composition of analytic functions in this file we prove that the composition of analytic functions is analytic. The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then `g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y)) = ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`. For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping `(y₀, ..., y_{i₁ + ... + iₙ - 1})` to `qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`. Then `g ∘ f` is obtained by summing all these multilinear functions. To formalize this, we use compositions of an integer `N`, i.e., its decompositions into a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these terms over all `c : composition N`. To complete the proof, we need to show that this power series has a positive radius of convergence. This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to `g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it corresponds to a part of the whole sum, on a subset that increases to the whole space. By summability of the norms, this implies the overall convergence. ## Main results * `q.comp p` is the formal composition of the formal multilinear series `q` and `p`. * `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions `q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`. * `analytic_at.comp` states that the composition of analytic functions is analytic. ## Implementation details The main technical difficulty is to write down things. In particular, we need to define precisely `q.comp_along_composition p c` and to show that it is indeed a continuous multilinear function. This requires a whole interface built on the class `composition`. Once this is set, the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection, running over difficulties due to the dependent nature of the types under consideration, that are controlled thanks to the interface for `composition`. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open filter open_locale topological_space classical /-! ### Composing formal multilinear series -/ namespace formal_multilinear_series /-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block of `n`, and applying the corresponding coefficient of `p` to these variables. This function is called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/ def apply_composition (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) : (fin n → E) → (fin (c.length) → F) := λ v i, p (c.blocks_fun i) (v ∘ (c.embedding i)) /-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This will be the key point to show that functions constructed from `apply_composition` retain multilinearity. -/ lemma apply_composition_update (p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) (j : fin n) (v : fin n → E) (z : E) : p.apply_composition c (function.update v j z) = function.update (p.apply_composition c v) (c.index j) (p (c.blocks_fun (c.index j)) (function.update (v ∘ (c.embedding (c.index j))) (c.inv_embedding j) z)) := begin ext k, by_cases h : k = c.index j, { rw h, let r : fin (c.blocks_fun (c.index j)) → fin n := c.embedding (c.index j), simp only [function.update_same], change p (c.blocks_fun (c.index j)) ((function.update v j z) ∘ r) = _, let j' := c.inv_embedding j, suffices B : (function.update v j z) ∘ r = function.update (v ∘ r) j' z, by rw B, suffices C : (function.update v (r j') z) ∘ r = function.update (v ∘ r) j' z, by { convert C, exact c.embedding_comp_inv j }, exact function.update_comp_eq_of_injective _ (c.embedding_inj _) _ _ }, { simp only [h, function.update_eq_self, function.update_noteq, ne.def, not_false_iff], let r : fin (c.blocks_fun k) → fin n := c.embedding k, change p (c.blocks_fun k) ((function.update v j z) ∘ r) = p (c.blocks_fun k) (v ∘ r), suffices B : (function.update v j z) ∘ r = v ∘ r, by rw B, apply function.update_comp_eq_of_not_mem_range, rwa c.mem_range_embedding_iff' } end /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition_multilinear p c`. This function admits a version as a continuous multilinear map, called `q.comp_along_composition p c` below. -/ def comp_along_composition_multilinear {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : multilinear_map 𝕜 (λ i : fin n, E) G := { to_fun := λ v, q c.length (p.apply_composition c v), add := λ v i x y, by simp [apply_composition_update], smul := λ v i c x, by simp [apply_composition_update] } /-- The norm of `q.comp_along_composition_multilinear p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_multilinear_bound {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) (v : fin n → E) : ∥q.comp_along_composition_multilinear p c v∥ ≤ ∥q c.length∥ * finset.univ.prod (λ i, ∥p (c.blocks_fun i)∥) * (finset.univ : finset (fin n)).prod (λ i, ∥v i∥) := begin -- main point: taking the product of the `∥v i∥` along each block, and then along all the blocks, -- gives the product of all the `∥v i∥`, as the blocks form a partition of the indices. have A : finset.univ.prod (λ (i : fin c.length), finset.univ.prod (λ (j : fin (c.blocks_fun i)), ∥(v ∘ c.embedding i) j∥)) = finset.prod finset.univ (λ (i : fin n), ∥v i∥), { -- The fact that a product over a partition gives the whole product is `finset.prod_bind`. -- We just need to check its disjointness and totality assumptions. have : (∀ (i : fin c.length), i ∈ finset.univ → ∀ (j : fin c.length), j ∈ finset.univ → i ≠ j → disjoint (finset.univ.image (c.embedding i)) (finset.univ.image (c.embedding j))), { assume i hi j hj i_ne_j, rw finset.disjoint_iff_disjoint_coe, convert c.disjoint_range i_ne_j; apply fintype.coe_image_univ }, have Z := @finset.prod_bind _ _ _ (λ j, ∥v j∥) _ _ finset.univ (λ (i : fin c.length), finset.univ.image (c.embedding i)) this, have : (finset.bind finset.univ (λ (i : fin c.length), finset.univ.image (c.embedding i))) = finset.univ, { ext j, simp only [finset.mem_univ, finset.mem_bind, iff_true, exists_prop_of_true, finset.mem_image], refine ⟨c.index j, by simpa using c.mem_range_embedding j⟩ }, rw this at Z, rw Z, congr, ext i, rw finset.prod_image, assume a ha b hb hab, exact c.embedding_inj i hab }, -- Now that the main point is proved, write down the estimates using the definition of the norm -- of a multilinear map calc ∥q.comp_along_composition_multilinear p c v∥ = ∥q c.length (p.apply_composition c v)∥ : rfl ... ≤ ∥q c.length∥ * finset.univ.prod (λ i, ∥p.apply_composition c v i∥) : continuous_multilinear_map.le_op_norm _ _ ... ≤ ∥q c.length∥ * finset.univ.prod (λ i, ∥p (c.blocks_fun i)∥ * (finset.univ : finset (fin (c.blocks_fun i))).prod (λ j, ∥(v ∘ (c.embedding i)) j∥)) : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), refine finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, _), apply continuous_multilinear_map.le_op_norm, end ... = ∥q c.length∥ * finset.univ.prod (λ i, ∥p (c.blocks_fun i)∥) * finset.univ.prod (λ i, (finset.univ : finset (fin (c.blocks_fun i))).prod (λ j, ∥(v ∘ (c.embedding i)) j∥)) : by rw [finset.prod_mul_distrib, mul_assoc] ... = ∥q c.length∥ * finset.univ.prod (λ i, ∥p (c.blocks_fun i)∥) * (finset.univ : finset (fin n)).prod (λ i, ∥v i∥) : by rw A end /-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each block of the composition, and then applying `q c.length` to the resulting vector. It is called `q.comp_along_composition p c`. It is constructed from the analogous multilinear function `q.comp_along_composition_multilinear p c`, together with a norm control to get the continuity. -/ def comp_along_composition {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G := (q.comp_along_composition_multilinear p c).mk_continuous _ (q.comp_along_composition_multilinear_bound p c) /-- The norm of `q.comp_along_composition p c` is controlled by the product of the norms of the relevant bits of `q` and `p`. -/ lemma comp_along_composition_norm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : ∥q.comp_along_composition p c∥ ≤ ∥q c.length∥ * finset.univ.prod (λ i, ∥p (c.blocks_fun i)∥) := multilinear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (finset.prod_nonneg (λ i hi, norm_nonneg _))) _ lemma comp_along_composition_nnnorm {n : ℕ} (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (c : composition n) : nnnorm (q.comp_along_composition p c) ≤ nnnorm (q c.length) * finset.univ.prod (λ i, nnnorm (p (c.blocks_fun i))) := begin simp only [← nnreal.coe_le_coe, coe_nnnorm, nnreal.coe_mul, coe_nnnorm, nnreal.coe_prod, coe_nnnorm], exact q.comp_along_composition_norm p c end /-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition is defined to be the sum of `q.comp_along_composition p c` over all compositions of `n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is `∑'_{k} ∑'_{i₁ + ... + iₖ = n} pₖ (q_{i_1} (...), ..., q_{i_k} (...))`, where one puts all variables `v_0, ..., v_{n-1}` in increasing order in the dots.-/ protected def comp (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) : formal_multilinear_series 𝕜 E G := λ n, (finset.univ : finset (composition n)).sum (λ c, q.comp_along_composition p c) /-- If two formal multilinear series have positive radius of convergence, then the terms appearing in the definition of their composition are also summable (when multiplied by a suitable positive geometric term). -/ theorem comp_summable_nnreal (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (hq : 0 < q.radius) (hp : 0 < p.radius) : ∃ (r : nnreal), 0 < r ∧ summable (λ i, nnnorm (q.comp_along_composition p i.2) * r ^ i.1 : (Σ n, composition n) → nnreal) := begin /- This follows from the fact that the growth rate of `∥qₙ∥` and `∥pₙ∥` is at most geometric, giving a geometric bound on each `∥q.comp_along_composition p op∥`, together with the fact that there are `2^(n-1)` compositions of `n`, giving at most a geometric loss. -/ rcases ennreal.lt_iff_exists_nnreal_btwn.1 hq with ⟨rq, rq_pos, hrq⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hp with ⟨rp, rp_pos, hrp⟩, obtain ⟨Cq, hCq⟩ : ∃ (Cq : nnreal), ∀ n, nnnorm (q n) * rq^n ≤ Cq := q.bound_of_lt_radius hrq, obtain ⟨Cp, hCp⟩ : ∃ (Cp : nnreal), ∀ n, nnnorm (p n) * rp^n ≤ Cp := p.bound_of_lt_radius hrp, let r0 : nnreal := (4 * max Cp 1)⁻¹, set r := min rp 1 * min rq 1 * r0, have r_pos : 0 < r, { apply mul_pos' (mul_pos' _ _), { rw [nnreal.inv_pos], apply mul_pos', { norm_num }, { exact lt_of_lt_of_le zero_lt_one (le_max_right _ _) } }, { rw ennreal.coe_pos at rp_pos, simp [rp_pos, zero_lt_one] }, { rw ennreal.coe_pos at rq_pos, simp [rq_pos, zero_lt_one] } }, let a : ennreal := ((4 : nnreal) ⁻¹ : nnreal), have two_a : 2 * a < 1, { change ((2 : nnreal) : ennreal) * ((4 : nnreal) ⁻¹ : nnreal) < (1 : nnreal), rw [← ennreal.coe_mul, ennreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_mul], change (2 : ℝ) * (4 : ℝ)⁻¹ < 1, norm_num }, have I : ∀ (i : Σ (n : ℕ), composition n), ↑(nnnorm (q.comp_along_composition p i.2) * r ^ i.1) ≤ (Cq : ennreal) * a ^ i.1, { rintros ⟨n, c⟩, rw [← ennreal.coe_pow, ← ennreal.coe_mul, ennreal.coe_le_coe], calc nnnorm (q.comp_along_composition p c) * r ^ n ≤ (nnnorm (q c.length) * (finset.univ : finset (fin (c.length))).prod (λ i, nnnorm (p (c.blocks_fun i)))) * r ^ n : mul_le_mul_of_nonneg_right (q.comp_along_composition_nnnorm p c) (bot_le) ... = (nnnorm (q c.length) * (min rq 1)^n) * ((finset.univ : finset (fin (c.length))).prod (λ i, nnnorm (p (c.blocks_fun i))) * (min rp 1) ^ n) * r0 ^ n : by { dsimp [r], ring_exp } ... ≤ (nnnorm (q c.length) * (min rq 1) ^ c.length) * ((finset.univ : finset (fin c.length)).prod (λ i, nnnorm (p (c.blocks_fun i)) * (min rp 1) ^ (c.blocks_fun i))) * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_refl, pow_le_pow_of_le_one, min_le_right, c.length_le], apply le_of_eq, rw finset.prod_mul_distrib, congr' 1, conv_lhs { rw [← c.sum_blocks_fun, ← finset.prod_pow_eq_pow_sum] }, end ... ≤ Cq * ((finset.univ : finset (fin c.length)).prod (λ i, Cp)) * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_trans _ (hCq c.length), le_refl, finset.prod_le_prod'], { assume i hi, refine le_trans (mul_le_mul (le_refl _) _ bot_le bot_le) (hCp (c.blocks_fun i)), exact pow_le_pow_of_le_left bot_le (min_le_left _ _) _ }, { refine mul_le_mul (le_refl _) _ bot_le bot_le, exact pow_le_pow_of_le_left bot_le (min_le_left _ _) _ } end ... ≤ Cq * (max Cp 1) ^ n * r0 ^ n : begin apply_rules [mul_le_mul, bot_le, le_refl], simp only [finset.card_fin, finset.prod_const], refine le_trans (pow_le_pow_of_le_left bot_le (le_max_left Cp 1) c.length) _, apply pow_le_pow (le_max_right Cp 1) c.length_le, end ... = Cq * 4⁻¹ ^ n : begin dsimp [r0], have A : (4 : nnreal) ≠ 0, by norm_num, have B : max Cp 1 ≠ 0 := ne_of_gt (lt_of_lt_of_le zero_lt_one (le_max_right Cp 1)), field_simp [A, B], ring_exp end }, refine ⟨r, r_pos, _⟩, rw [← ennreal.tsum_coe_ne_top_iff_summable], apply ne_of_lt, calc (∑' (i : Σ (n : ℕ), composition n), ↑(nnnorm (q.comp_along_composition p i.2) * r ^ i.1)) ≤ (∑' (i : Σ (n : ℕ), composition n), (Cq : ennreal) * a ^ i.1) : ennreal.tsum_le_tsum I ... = (∑' (n : ℕ), (∑' (c : composition n), (Cq : ennreal) * a ^ n)) : ennreal.tsum_sigma' _ ... = (∑' (n : ℕ), ↑(fintype.card (composition n)) * (Cq : ennreal) * a ^ n) : begin congr' 1, ext1 n, rw [tsum_fintype, finset.sum_const, add_monoid.smul_eq_mul, finset.card_univ, mul_assoc] end ... ≤ (∑' (n : ℕ), (2 : ennreal) ^ n * (Cq : ennreal) * a ^ n) : begin apply ennreal.tsum_le_tsum (λ n, _), apply ennreal.mul_le_mul (ennreal.mul_le_mul _ (le_refl _)) (le_refl _), rw composition_card, simp only [nat.cast_bit0, nat.cast_one, nat.cast_pow], apply ennreal.pow_le_pow _ (nat.sub_le n 1), have : (1 : nnreal) ≤ (2 : nnreal), by norm_num, rw ← ennreal.coe_le_coe at this, exact this end ... = (∑' (n : ℕ), (Cq : ennreal) * (2 * a) ^ n) : by { congr' 1, ext1 n, rw mul_pow, ring } ... = (Cq : ennreal) * (1 - 2 * a) ⁻¹ : by rw [ennreal.tsum_mul_left, ennreal.tsum_geometric] ... < ⊤ : by simp [lt_top_iff_ne_top, ennreal.mul_eq_top, two_a] end /-- Bounding below the radius of the composition of two formal multilinear series assuming summability over all compositions. -/ theorem le_comp_radius_of_summable (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : nnreal) (hr : summable (λ i, nnnorm (q.comp_along_composition p i.2) * r ^ i.1 : (Σ n, composition n) → nnreal)) : (r : ennreal) ≤ (q.comp p).radius := begin apply le_radius_of_bound _ (tsum (λ (i : Σ (n : ℕ), composition n), (nnnorm (comp_along_composition q p i.snd) * r ^ i.fst))), assume n, calc nnnorm (formal_multilinear_series.comp q p n) * r ^ n ≤ ∑' (c : composition n), nnnorm (comp_along_composition q p c) * r ^ n : begin rw [tsum_fintype, ← finset.sum_mul], exact mul_le_mul_of_nonneg_right (nnnorm_sum_le _ _) bot_le end ... ≤ ∑' (i : Σ (n : ℕ), composition n), nnnorm (comp_along_composition q p i.snd) * r ^ i.fst : begin let f : composition n → (Σ (n : ℕ), composition n) := λ c, ⟨n, c⟩, have : function.injective f, by tidy, convert nnreal.tsum_comp_le_tsum_of_inj hr this end end /-! Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for `g` and `p` is a power series for `f`. This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first the source of the change of variables (`comp_partial_source`), its target (`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before giving the main statement in `comp_partial_sum`. -/ /-- Source set in the change of variables to compute the composition of partial sums of formal power series -/ def comp_partial_sum_source (N : ℕ) : finset (Σ n, (fin n) → ℕ) := finset.sigma (finset.range N) (λ (n : ℕ), fintype.pi_finset (λ (i : fin n), finset.Ico 1 N) : _) @[simp] lemma mem_comp_partial_sum_source_iff (N : ℕ) (i : Σ n, (fin n) → ℕ) : i ∈ comp_partial_sum_source N ↔ i.1 < N ∧ ∀ (a : fin i.1), 1 ≤ i.2 a ∧ i.2 a < N := by simp [comp_partial_sum_source] /-- Change of variables appearing to compute the composition of partial sums of formal power series -/ def comp_change_of_variables (N : ℕ) (i : Σ n, (fin n) → ℕ) (hi : i ∈ comp_partial_sum_source N) : (Σn, composition n) := begin rcases i with ⟨n, f⟩, rw mem_comp_partial_sum_source_iff at hi, exact ⟨finset.univ.sum f, list.of_fn (λ a, ⟨f a, (hi.2 a).1⟩), by simp [list.sum_of_fn]⟩ end @[simp] lemma comp_change_of_variables_length (N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source N) : composition.length (comp_change_of_variables N i hi).2 = i.1 := begin rcases i with ⟨k, blocks_fun⟩, dsimp [comp_change_of_variables], simp only [composition.length, composition.blocks, list.map_of_fn, list.length_of_fn] end lemma comp_change_of_variables_blocks_fun (N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source N) (j : fin i.1) : (comp_change_of_variables N i hi).2.blocks_fun ⟨j.val, (comp_change_of_variables_length N hi).symm ▸ j.2⟩ = i.2 j := begin rcases i with ⟨n, f⟩, dsimp [composition.blocks_fun, composition.blocks, comp_change_of_variables], simp only [list.map_of_fn, pnat.mk_coe, list.nth_le_of_fn', function.comp_app], apply congr_arg, rw fin.ext_iff end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a set. -/ def comp_partial_sum_target_set (N : ℕ) : set (Σ n, composition n) := {i | (i.2.length < N) ∧ (∀ (j : fin i.2.length), i.2.blocks_fun j < N)} lemma comp_partial_sum_target_subset_image_comp_partial_sum_source (N : ℕ) (i : Σ n, composition n) (hi : i ∈ comp_partial_sum_target_set N) : ∃ j (hj : j ∈ comp_partial_sum_source N), i = comp_change_of_variables N j hj := begin rcases i with ⟨n, c⟩, simp [comp_partial_sum_target_set] at hi, refine ⟨⟨c.length, c.blocks_fun⟩, _, _⟩, { simp only [mem_comp_partial_sum_source_iff, hi.left, hi.right, true_and, and_true], exact λ a, c.one_le_blocks' _ }, { dsimp [comp_change_of_variables], rw composition.sigma_eq_iff_blocks_eq, simp only [composition.blocks_fun, composition.blocks, subtype.coe_eta, list.nth_le_map'], conv_lhs { rw ← list.of_fn_nth_le c.blocks_pnat }, congr' 2, { exact c.blocks_pnat_length }, { exact (fin.heq_fun_iff c.blocks_pnat_length).2 (λ i, rfl) } } end /-- Target set in the change of variables to compute the composition of partial sums of formal power series, here given a a finset. -/ def comp_partial_sum_target (N : ℕ) : finset (Σ n, composition n) := set.finite.to_finset $ set.finite_dependent_image (finset.finite_to_set _) (comp_partial_sum_target_subset_image_comp_partial_sum_source N) @[simp] lemma mem_comp_partial_sum_target_iff {N : ℕ} {a : Σ n, composition n} : a ∈ comp_partial_sum_target N ↔ a.2.length < N ∧ (∀ (j : fin a.2.length), a.2.blocks_fun j < N) := by simp [comp_partial_sum_target, comp_partial_sum_target_set] /-- The auxiliary set corresponding to the composition of partial sums asymptotically contains all possible compositions. -/ lemma comp_partial_sum_target_tendsto_at_top : tendsto comp_partial_sum_target at_top at_top := begin apply monotone.tendsto_at_top_finset, { assume m n hmn a ha, have : ∀ i, i < m → i < n := λ i hi, lt_of_lt_of_le hi hmn, tidy }, { rintros ⟨n, c⟩, simp only [mem_comp_partial_sum_target_iff], have : bdd_above ↑(finset.univ.image (λ (i : fin c.length), c.blocks_fun i)) := finset.bdd_above _, rcases this with ⟨n, hn⟩, refine ⟨max n c.length + 1, lt_of_le_of_lt (le_max_right n c.length) (lt_add_one _), λ j, lt_of_le_of_lt (le_trans _ (le_max_left _ _)) (lt_add_one _)⟩, apply hn, simp only [finset.mem_image_of_mem, finset.mem_coe, finset.mem_univ] } end /-- Composing the partial sums of two multilinear series coincides with the sum over all compositions in `comp_partial_sum_target N`. This is precisely the motivation for the definition of `comp_partial_sum_target N`. -/ lemma comp_partial_sum (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) : q.partial_sum N ((finset.Ico 1 N).sum (λ a, p a (λ b, z))) = (comp_partial_sum_target N).sum (λ i, q.comp_along_composition_multilinear p i.2 (λ j, z)) := begin -- we expand the composition, using the multilinearity of `q` to expand along each coordinate. suffices H : (finset.range N).sum (λ (n : ℕ), (fintype.pi_finset (λ (i : fin n), finset.Ico 1 N)).sum (λ (r : fin n → ℕ), q n (λ (i : fin n), p (r i) (λ (i : fin (r i)), z)))) = (comp_partial_sum_target N).sum (λ i, q.comp_along_composition_multilinear p i.2 (λ j, z)), by simpa only [formal_multilinear_series.partial_sum, continuous_multilinear_map.map_sum_finset] using H, -- rewrite the first sum as a big sum over a sigma type rw ← @finset.sum_sigma _ _ _ _ (finset.range N) (λ (n : ℕ), (fintype.pi_finset (λ (i : fin n), finset.Ico 1 N)) : _) (λ i, q i.1 (λ (j : fin i.1), p (i.2 j) (λ (k : fin (i.2 j)), z))), -- show that the two sums correspond to each other by reindexing the variables. This is the -- content of `finset.sum_bij`, for which we spell out all parameters of the bijection -- explicitly as the setting is complicated. apply @finset.sum_bij _ _ _ _ (comp_partial_sum_source N) (comp_partial_sum_target N) (λ i, q i.1 (λ (j : fin i.1), p (i.2 j) (λ (k : fin (i.2 j)), z))) (λ i, q.comp_along_composition_multilinear p i.2 (λ j, z)) (comp_change_of_variables N), -- To conclude, we should show that the correspondance we have set up is indeed a bijection -- between the index sets of the two sums. -- 1 - show that the image belongs to `comp_partial_sum_target N` { rintros ⟨k, blocks_fun⟩ H, rw mem_comp_partial_sum_source_iff at H, simp only [mem_comp_partial_sum_target_iff, composition.length, composition.blocks, H.left, list.map_of_fn, list.length_of_fn, true_and, comp_change_of_variables], assume j, simp only [composition.blocks_fun, composition.blocks, (H.right _).right, pnat.mk_coe, list.map_of_fn, list.nth_le_of_fn', function.comp_app] }, -- 2 - show that the composition gives the `comp_along_composition` application { rintros ⟨k, blocks_fun⟩ H, have L := comp_change_of_variables_length N H, have B := comp_change_of_variables_blocks_fun N H, rw mem_comp_partial_sum_source_iff at H, dsimp [formal_multilinear_series.comp_along_composition_multilinear, formal_multilinear_series.apply_composition, comp_change_of_variables] at L B ⊢, unfold_coes, congr' 1; try { rw L }, apply (fin.heq_fun_iff L.symm).2 (λ j, _), rw ← B }, -- 3 - show that the map is injective { assume i i' H H' heq, have B := comp_change_of_variables_blocks_fun N H, have B' := comp_change_of_variables_blocks_fun N H', have A : i.1 = i'.1, { rw [← comp_change_of_variables_length N H, ← comp_change_of_variables_length _ H', heq] }, rcases i with ⟨k, blocks_fun⟩, rcases i' with ⟨k', blocks_fun'⟩, dsimp at A B B', simp only [A, fin.heq_fun_iff, true_and, eq_self_iff_true], assume i, rw [← B, ← B'], congr' 1; try { rw heq }, rw fin.heq_ext_iff, rw heq }, -- 4 - show that the map is surjective { assume i hi, apply comp_partial_sum_target_subset_image_comp_partial_sum_source N i, simpa [comp_partial_sum_target] using hi } end end formal_multilinear_series open formal_multilinear_series /-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then `g ∘ f` admits the power series `q.comp p` at `x`. -/ theorem has_fpower_series_at.comp {g : F → G} {f : E → F} {q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E} (hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) : has_fpower_series_at (g ∘ f) (q.comp p) x := begin /- Consider `rf` and `rg` such that `f` and `g` have power series expansion on the disks of radius `rf` and `rg`. -/ rcases hg with ⟨rg, Hg⟩, rcases hf with ⟨rf, Hf⟩, /- The terms defining `q.comp p` are geometrically summable in a disk of some radius `r`. -/ rcases q.comp_summable_nnreal p Hg.radius_pos Hf.radius_pos with ⟨r, r_pos, hr⟩, /- We will consider `y` which is smaller than `r` and `rf`, and also small enough that `f (x + y)` is close enough to `f x` to be in the disk where `g` is well behaved. Let `min (r, rf, δ)` be this new radius.-/ have : continuous_at f x := Hf.analytic_at.continuous_at, obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ennreal) (H : 0 < δ), ∀ {z : E}, z ∈ emetric.ball x δ → f z ∈ emetric.ball (f x) rg, { have : emetric.ball (f x) rg ∈ 𝓝 (f x) := emetric.ball_mem_nhds _ Hg.r_pos, rcases emetric.mem_nhds_iff.1 (Hf.analytic_at.continuous_at this) with ⟨δ, δpos, Hδ⟩, exact ⟨δ, δpos, λ z hz, Hδ hz⟩ }, let rf' := min rf δ, have rf'_pos : 0 < rf', by simp [rf', Hf.r_pos, δpos], have min_pos : 0 < min rf' r, by simp [r_pos, rf'_pos], /- We will show that `g ∘ f` admits the power series `q.comp p` in the disk of radius `min (r, rf', δ)`. -/ refine ⟨min rf' r, _⟩, refine ⟨le_trans (min_le_right rf' r) (formal_multilinear_series.le_comp_radius_of_summable q p r hr), min_pos, λ y hy, _⟩, /- Let `y` satisfy `∥y∥ < min (r, rf', δ)`. We want to show that `g (f (x + y))` is the sum of `q.comp p` applied to `y`. -/ -- First, check that `y` is small enough so that estimates for `f` and `g` apply. have y_mem : y ∈ emetric.ball (0 : E) rf := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_left _ _))) hy, have fy_mem : f (x + y) ∈ emetric.ball (f x) rg, { apply hδ, have : y ∈ emetric.ball (0 : E) δ := (emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_right _ _))) hy, simpa [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm] }, /- Now starts the proof. To show that the sum of `q.comp p` at `y` is `g (f (x + y))`, we will write `q.comp p` applied to `y` as a big sum over all compositions. Since the sum is summable, to get its convergence it suffices to get the convergence along some increasing sequence of sets. We will use the sequence of sets `comp_partial_sum_target n`, along which the sum is exactly the composition of the partial sums of `q` and `p`, by design. To show that it converges to `g (f (x + y))`, pointwise convergence would not be enough, but we have uniform convergence to save the day. -/ -- First step: the partial sum of `p` converges to `f (x + y)`. have A : tendsto (λ n, (finset.Ico 1 n).sum (λ a, p a (λ b, y))) at_top (𝓝 (f (x + y) - f x)), { have L : ∀ᶠ n in at_top, (finset.range n).sum (λ a, p a (λ b, y)) - f x = (finset.Ico 1 n).sum (λ a, p a (λ b, y)), { rw eventually_at_top, refine ⟨1, λ n hn, _⟩, symmetry, rw [eq_sub_iff_add_eq', finset.range_eq_Ico, ← Hf.coeff_zero (λi, y), finset.sum_eq_sum_Ico_succ_bot hn] }, have : tendsto (λ n, (finset.range n).sum (λ a, p a (λ b, y)) - f x) at_top (𝓝 (f (x + y) - f x)) := (Hf.has_sum y_mem).tendsto_sum_nat.sub tendsto_const_nhds, exact tendsto.congr' L this }, -- Second step: the composition of the partial sums of `q` and `p` converges to `g (f (x + y))`. have B : tendsto (λ n, q.partial_sum n ((finset.Ico 1 n).sum (λ a, p a (λ b, y)))) at_top (𝓝 (g (f (x + y)))), { -- we use the fact that the partial sums of `q` converge locally uniformly to `g`, and that -- composition passes to the limit under locally uniform convergence. have B₁ : continuous_at (λ (z : F), g (f x + z)) (f (x + y) - f x), { refine continuous_at.comp _ (continuous_const.add continuous_id).continuous_at, simp only [add_sub_cancel'_right, id.def], exact Hg.continuous_on.continuous_at (mem_nhds_sets (emetric.is_open_ball) fy_mem) }, have B₂ : f (x + y) - f x ∈ emetric.ball (0 : F) rg, by simpa [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] using fy_mem, rw [← nhds_within_eq_of_open B₂ emetric.is_open_ball] at A, convert Hg.tendsto_locally_uniformly_on.tendsto_comp B₁.continuous_within_at B₂ A, simp only [add_sub_cancel'_right] }, -- Third step: the sum over all compositions in `comp_partial_sum_target n` converges to -- `g (f (x + y))`. As this sum is exactly the composition of the partial sum, this is a direct -- consequence of the second step have C : tendsto (λ n, (comp_partial_sum_target n).sum (λ i, q.comp_along_composition_multilinear p i.2 (λ j, y))) at_top (𝓝 (g (f (x + y)))), by simpa [comp_partial_sum] using B, -- Fourth step: the sum over all compositions is `g (f (x + y))`. This follows from the -- convergence along a subsequence proved in the third step, and the fact that the sum is Cauchy -- thanks to the summability properties. have D : has_sum (λ i : (Σ n, composition n), q.comp_along_composition_multilinear p i.2 (λ j, y)) (g (f (x + y))), { have cau : cauchy_seq (λ (s : finset (Σ n, composition n)), s.sum (λ i, q.comp_along_composition_multilinear p i.2 (λ j, y))), { apply cauchy_seq_finset_of_norm_bounded _ (nnreal.summable_coe.2 hr) _, simp only [coe_nnnorm, nnreal.coe_mul, nnreal.coe_pow], rintros ⟨n, c⟩, calc ∥(comp_along_composition q p c) (λ (j : fin n), y)∥ ≤ ∥comp_along_composition q p c∥ * finset.univ.prod (λ (j : fin n), ∥y∥) : by apply continuous_multilinear_map.le_op_norm ... ≤ ∥comp_along_composition q p c∥ * (r : ℝ) ^ n : begin apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), simp only [finset.card_fin, finset.prod_const], apply pow_le_pow_of_le_left (norm_nonneg _), rw [emetric.mem_ball, edist_eq_coe_nnnorm] at hy, have := (le_trans (le_of_lt hy) (min_le_right _ _)), rwa [ennreal.coe_le_coe, ← nnreal.coe_le_coe, coe_nnnorm] at this end }, exact tendsto_nhds_of_cauchy_seq_of_subseq cau at_top_ne_bot comp_partial_sum_target_tendsto_at_top C }, -- Fifth step: the sum over `n` of `q.comp p n` can be expressed as a particular resummation of -- the sum over all compositions, by grouping together the compositions of the same -- integer `n`. The convergence of the whole sum therefore implies the converence of the sum -- of `q.comp p n` have E : has_sum (λ n, (q.comp p) n (λ j, y)) (g (f (x + y))), { apply D.sigma, assume n, dsimp [formal_multilinear_series.comp], convert has_sum_fintype _, simp only [continuous_multilinear_map.sum_apply], refl }, exact E end /-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is analytic at `x`. -/ theorem analytic_at.comp {g : F → G} {f : E → F} {x : E} (hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x := let ⟨q, hq⟩ := hg, ⟨p, hp⟩ := hf in (hq.comp hp).analytic_at
300894a82d9de902286b2441e01d2cbd3379efcd
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/deps/galois_stdlib/src/Galois/Data/ParserComb.lean
3813e0136596ad0da24888d7e4a7ac0e3af169eb
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
3,049
lean
-- Parsing combinators import Init.System.IO import Init.Control.State import Init.Control.Id import Init.Control.Option -- Single-valued, backtracking on failure structure Parser (tok : Type) (a : Type) := ( run : StateT (List tok) (OptionT Id) a ) namespace Parser variables {tok a b : Type} instance : HasOrelse (Parser tok a) := { orelse := fun x y => Parser.mk (x.run <|> y.run) } instance : Monad (Parser tok) := { bind := fun _ _ x f => Parser.mk (x.run >>= fun v => (f v).run) , pure := fun _ x => Parser.mk (pure x) } instance : MonadState (List tok) (Parser tok) := { set := fun s => Parser.mk (set s) , get := Parser.mk get , modifyGet := fun _ f => Parser.mk (modifyGet f) } instance : MonadExcept Unit (Parser tok) := { throw := fun _ e => Parser.mk (throw e) , catch := fun _ m f => Parser.mk (catch (m.run) (fun x => (f x).run)) } protected partial def many0 (p : Parser tok a) : Unit -> Parser tok (List a) | _ => (do v <- p; vs <- many0 (); pure (v :: vs)) <|> pure [] def optional {a : Type} (f : tok -> Option a) : Parser tok a := do tks <- get; match tks with | [] => throw () | (t :: tks') => match f t with | none => throw () | some r => (do set tks'; pure r) def token (f : tok -> Bool) : Parser tok tok := optional (fun t => if f t then some t else none) def exact [DecidableEq tok] (t : tok) : Parser tok tok := token (fun x => x = t) def many (p : Parser tok a) : Parser tok (List a) := Parser.many0 p () def many1 (p : Parser tok a) : Parser tok (List a) := do v <- p; vs <- many p; pure (v :: vs) def sepBy (s : Parser tok b) (p : Parser tok a) : Parser tok (List a) := (do rs <- many (do x <- p; discard s; pure x); -- p <* s -- rs <- pure []; r <- p; pure (List.append rs [r])) <|> pure [] def first (ps : List (Parser tok a)) : Parser tok a := List.foldl (fun p m => p <|> m) (throw ()) ps def runParser (p : Parser tok a) (tks : List tok) : Option a := (p.run.run' tks).run.run end Parser @[reducible] def CharParser := Parser Char namespace CharParser open Parser def digitP : CharParser Nat := optional (fun c => if c.isDigit then some (c.toNat - '0'.toNat) else none) def natP : CharParser Nat := do ds <- many1 digitP; pure (ds.foldl (fun acc d => acc * 10 + d) 0) def intP : CharParser Int := (do discard $ exact '-'; n <- natP; pure (Int.negOfNat n)) <|> (Int.ofNat <$> natP) def stringP (f : Char -> Bool) : CharParser String := List.asString <$> many (token f) def string1P (f : Char -> Bool) : CharParser String := List.asString <$> many1 (token f) def nonWSP : CharParser String := string1P (fun c => not (Char.isWhitespace c)) def whitespaceP : CharParser Unit := do _ <-token Char.isWhitespace; pure () def parseFile {a : Type} {m : Type → Type} [Monad m] [MonadIO m] (p : CharParser a) (fname : String) : m (Option a) := do s <- IO.FS.readFile fname; pure (runParser p s.toList) end CharParser
028062009a957908e12af17cffb68fca83e1dc9c
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Elab/Quotation.lean
426a1c549a88e7d15bd744e71dcb1f699fd301b0
[ "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
20,822
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic hygiene workings and data types. -/ prelude import Init.Lean.Syntax import Init.Lean.Elab.ResolveName import Init.Lean.Elab.Term import Init.Lean.Parser -- TODO: remove after removing old elaborator /- TODO Quotations are currently integrated hackily into the old frontend. This implies the following restrictions: * quotations have to fit in a single line, because that's how the old scanner works :) * `open` commands are not respected (but `export`, `namespace` are) * antiquotation terms have to be trivial (locals, consts (w/ projections), and apps, basically) After removing the old frontend, quotations in this and other files should be cleaned up. -/ namespace Lean namespace Elab namespace Term namespace Quotation -- antiquotation node kinds are formed from the original node kind (if any) plus "antiquot" def isAntiquot : Syntax → Bool | Syntax.node (Name.str _ "antiquot" _) _ => true | _ => false -- Antiquotations can be escaped as in `$$x`, which is useful for nesting macros. def isEscapedAntiquot (stx : Syntax) : Bool := !(stx.getArg 1).getArgs.isEmpty def unescapeAntiquot (stx : Syntax) : Syntax := if isAntiquot stx then stx.setArg 1 $ mkNullNode (stx.getArg 1).getArgs.pop else stx def getAntiquotTerm (stx : Syntax) : Syntax := let e := stx.getArg 2; if e.isIdent then mkTermIdFromIdent e else -- `e` is from `"(" >> termParser >> ")"` e.getArg 1 def antiquotKind? : Syntax → Option SyntaxNodeKind | Syntax.node (Name.str k "antiquot" _) args => -- we treat all antiquotations where the kind was left implicit (`$e`) the same (see `elimAntiquotChoices`) if (args.get! 3).isNone then some Name.anonymous else some k | _ => none -- `$e*` is an antiquotation "splice" matching an arbitrary number of syntax nodes def isAntiquotSplice (stx : Syntax) : Bool := isAntiquot stx && (stx.getArg 5).getOptional?.isSome -- If any item of a `many` node is an antiquotation splice, its result should -- be substituted into the `many` node's children def isAntiquotSplicePat (stx : Syntax) : Bool := stx.isOfKind nullKind && stx.getArgs.any (fun arg => isAntiquotSplice arg && !isEscapedAntiquot arg) /-- A term like `($e) is actually ambiguous: the antiquotation could be of kind `term`, or `ident`, or ... . But it shouldn't really matter because antiquotations without explicit kinds behave the same at runtime. So we replace `choice` nodes that contain at least one implicit antiquotation with that antiquotation. -/ private partial def elimAntiquotChoices : Syntax → Syntax | Syntax.node `choice args => match args.find? (fun arg => antiquotKind? arg == Name.anonymous) with | some anti => anti | none => Syntax.node `choice $ args.map elimAntiquotChoices | Syntax.node k args => Syntax.node k $ args.map elimAntiquotChoices | stx => stx -- Elaborate the content of a syntax quotation term private partial def quoteSyntax : Syntax → TermElabM Syntax | Syntax.ident info rawVal val preresolved => do -- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation). -- See the paper for details. r ← resolveGlobalName val; let preresolved := r ++ preresolved; let val := quote val; -- `scp` is bound in stxQuot.expand `(Syntax.ident none $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved)) -- if antiquotation, insert contents as-is, else recurse | stx@(Syntax.node k _) => if isAntiquot stx && !isEscapedAntiquot stx then -- splices must occur in a `many` node if isAntiquotSplice stx then throwError stx "unexpected antiquotation splice" else pure $ getAntiquotTerm stx else do empty ← `(Array.empty); -- if escaped antiquotation, decrement by one escape level let stx := unescapeAntiquot stx; args ← stx.getArgs.foldlM (fun args arg => if k == nullKind && isAntiquotSplice arg then -- antiquotation splice pattern: inject args array `(Array.append $args $(getAntiquotTerm arg)) else do arg ← quoteSyntax arg; `(Array.push $args $arg)) empty; `(Syntax.node $(quote k) $args) | Syntax.atom info val => `(Syntax.atom none $(quote val)) | Syntax.missing => unreachable! def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do let quoted := stx.getArg 1; /- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind the macro scope once for each quotation, then build the syntax tree in a completely pure computation depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e. we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by including it literally in a syntax quotation. -/ -- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted)) stx ← quoteSyntax (elimAntiquotChoices quoted); `(bind getCurrMacroScope (fun scp => bind getMainModule (fun mainModule => pure $stx))) /- NOTE: It may seem like the newly introduced binding `scp` may accidentally capture identifiers in an antiquotation introduced by `quoteSyntax`. However, note that the syntax quotation above enjoys the same hygiene guarantees as anywhere else in Lean; that is, we implement hygienic quotations by making use of the hygienic quotation support of the bootstrapped Lean compiler! Aside: While this might sound "dangerous", it is in fact less reliant on a "chain of trust" than other bootstrapping parts of Lean: because this implementation itself never uses `scp` (or any other identifier) both inside and outside quotations, it can actually correctly be compiled by an unhygienic (but otherwise correct) implementation of syntax quotations. As long as it is then compiled again with the resulting executable (i.e. up to stage 2), the result is a correct hygienic implementation. In this sense the implementation is "self-stabilizing". It was in fact originally compiled by an unhygienic prototype implementation. -/ @[builtinTermElab stxQuot] def elabStxQuot : TermElab := adaptExpander stxQuot.expand /- match_syntax -/ -- an "alternative" of patterns plus right-hand side private abbrev Alt := List Syntax × Syntax /-- Information on a pattern's head that influences the compilation of a single match step. -/ structure HeadInfo := -- Node kind to match, if any (kind : Option SyntaxNodeKind := none) -- Nested patterns for each argument, if any. In a single match step, we only -- check that the arity matches. The arity is usually implied by the node kind, -- but not in the case of `many` nodes. (argPats : Option (Array Syntax) := none) -- Function to apply to the right-hand side in case the match succeeds. Used to -- bind pattern variables. (rhsFn : Syntax → TermElabM Syntax := pure) instance HeadInfo.Inhabited : Inhabited HeadInfo := ⟨{}⟩ /-- `h1.generalizes h2` iff h1 is equal to or more general than h2, i.e. it matches all nodes h2 matches. This induces a partial ordering. -/ def HeadInfo.generalizes : HeadInfo → HeadInfo → Bool | { kind := none, .. }, _ => true | { kind := some k1, argPats := none, .. }, { kind := some k2, .. } => k1 == k2 | { kind := some k1, argPats := some ps1, .. }, { kind := some k2, argPats := some ps2, .. } => k1 == k2 && ps1.size == ps2.size | _, _ => false private def getHeadInfo (alt : Alt) : HeadInfo := let pat := alt.fst.head!; let unconditional (rhsFn) := { HeadInfo . rhsFn := rhsFn }; -- variable pattern if pat.isOfKind `Lean.Parser.Term.id then unconditional $ fun rhs => `(let $pat := discr; $rhs) -- wildcard pattern else if pat.isOfKind `Lean.Parser.Term.hole then unconditional pure -- quotation pattern else if pat.isOfKind `Lean.Parser.Term.stxQuot then let quoted := pat.getArg 1; if quoted.isAtom then -- We assume that atoms are uniquely determined by the node kind and never have to be checked unconditional pure else if isAntiquot quoted && !isEscapedAntiquot quoted then -- quotation contains a single antiquotation let k := antiquotKind? quoted; -- Antiquotation kinds like `$id:id` influence the parser, but also need to be considered by -- match_syntax (but not by quotation terms). For example, `($id:id) and `($e) are not -- distinguishable without checking the kind of the node to be captured. Note that some -- antiquotations like the latter one for terms do not correspond to any actual node kind -- (signified by `k == Name.anonymous`), so we would only check for `Term.id` here. -- -- if stx.isOfKind `Lean.Parser.Term.id then -- let id := stx; ... -- else -- let e := stx; ... let kind := if k == Name.anonymous then none else k; let anti := getAntiquotTerm quoted; -- Splices should only appear inside a nullKind node, see next case if isAntiquotSplice quoted then unconditional $ fun _ => throwError quoted "unexpected antiquotation splice" else if anti.isOfKind `Lean.Parser.Term.id then { kind := kind, rhsFn := fun rhs => `(let $anti := discr; $rhs) } else unconditional $ fun _ => throwError anti ("match_syntax: antiquotation must be variable " ++ toString anti) else if isAntiquotSplicePat quoted && quoted.getArgs.size == 1 then -- quotation is a single antiquotation splice => bind args array let anti := getAntiquotTerm (quoted.getArg 0); unconditional $ fun rhs => `(let $anti := Syntax.getArgs discr; $rhs) -- TODO: support for more complex antiquotation splices else -- not an antiquotation or escaped antiquotation: match head shape let quoted := unescapeAntiquot quoted; let argPats := quoted.getArgs.map $ fun arg => Syntax.node `Lean.Parser.Term.stxQuot #[mkAtom "`(", arg, mkAtom ")"]; { kind := quoted.getKind, argPats := argPats } else unconditional $ fun _ => throwError pat ("match_syntax: unexpected pattern kind " ++ toString pat) -- Assuming that the first pattern of the alternative is taken, replace it with patterns (if any) for its -- child nodes. -- Ex: `($a + (- $b)) => `($a), `(+), `(- $b) -- Note: The atom pattern `(+) will be discarded in a later step private def explodeHeadPat (numArgs : Nat) : HeadInfo × Alt → TermElabM Alt | (info, (pat::pats, rhs)) => do let newPats := match info.argPats with | some argPats => argPats.toList | none => List.replicate numArgs $ Unhygienic.run `(_); rhs ← info.rhsFn rhs; pure (newPats ++ pats, rhs) | _ => unreachable! private partial def compileStxMatch (ref : Syntax) : List Syntax → List Alt → TermElabM Syntax | [], ([], rhs)::_ => pure rhs -- nothing left to match | _, [] => throwError ref "non-exhaustive 'match_syntax'" | discr::discrs, alts => do let alts := (alts.map getHeadInfo).zip alts; -- Choose a most specific pattern, ie. a minimal element according to `generalizes`. -- If there are multiple minimal elements, the choice does not matter. let (info, alt) := alts.tail!.foldl (fun (min : HeadInfo × Alt) (alt : HeadInfo × Alt) => if min.1.generalizes alt.1 then alt else min) alts.head!; -- introduce pattern matches on the discriminant's children if there are any nested patterns newDiscrs ← match info.argPats with | some pats => (List.range pats.size).mapM $ fun i => `(Syntax.getArg discr $(quote i)) | none => pure []; -- collect matching alternatives and explode them let yesAlts := alts.filter $ fun (alt : HeadInfo × Alt) => alt.1.generalizes info; yesAlts ← yesAlts.mapM $ explodeHeadPat newDiscrs.length; -- NOTE: use fresh macro scopes for recursive call so that different `discr`s introduced by the quotations below do not collide yes ← withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts; some kind ← pure info.kind -- unconditional match step | `(let discr := $discr; $yes); -- conditional match step let noAlts := (alts.filter $ fun (alt : HeadInfo × Alt) => !info.generalizes alt.1).map Prod.snd; no ← withFreshMacroScope $ compileStxMatch (discr::discrs) noAlts; cond ← match info.argPats with | some pats => `(Syntax.isOfKind discr $(quote kind) && Array.size (Syntax.getArgs discr) == $(quote pats.size)) | none => `(Syntax.isOfKind discr $(quote kind)); `(let discr := $discr; if $cond = true then $yes else $no) | _, _ => unreachable! private partial def getPatternVarsAux : Syntax → List Syntax | stx@(Syntax.node k args) => if isAntiquot stx && !isEscapedAntiquot stx then let anti := getAntiquotTerm stx; if anti.isOfKind `Lean.Parser.Term.id then [anti] else [] else List.join $ args.toList.map getPatternVarsAux | _ => [] -- Get all pattern vars (as Term.id nodes) in `stx` partial def getPatternVars (stx : Syntax) : List Syntax := if stx.isOfKind `Lean.Parser.Term.stxQuot then do let quoted := stx.getArg 1; getPatternVarsAux stx else if stx.isOfKind `Lean.Parser.Term.id then [stx] else [] -- Transform alternatives by binding all right-hand sides to outside the match_syntax in order to prevent -- code duplication during match_syntax compilation private def letBindRhss (cont : List Alt → TermElabM Syntax) : List Alt → List Alt → TermElabM Syntax | [], altsRev' => cont altsRev'.reverse | (pats, rhs)::alts, altsRev' => do let vars := List.join $ pats.map getPatternVars; match vars with -- no antiquotations => introduce Unit parameter to preserve evaluation order | [] => do -- NOTE: references binding below rhs' ← `(rhs ()); -- NOTE: new macro scope so that introduced bindings do not collide stx ← withFreshMacroScope $ letBindRhss alts ((pats, rhs')::altsRev'); `(let rhs := fun _ => $rhs; $stx) | _ => do -- rhs ← `(fun $vars* => $rhs) let rhs := Syntax.node `Lean.Parser.Term.fun #[mkAtom "fun", Syntax.node `null vars.toArray, mkAtom "=>", rhs]; rhs' ← `(rhs); stx ← withFreshMacroScope $ letBindRhss alts ((pats, rhs')::altsRev'); `(let rhs := $rhs; $stx) def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do let discr := stx.getArg 1; let alts := stx.getArg 4; alts ← alts.getArgs.getSepElems.mapM $ fun alt => do { let pats := alt.getArg 0; pat ← if pats.getArgs.size == 1 then pure $ pats.getArg 0 else throwError stx "match_syntax: expected exactly one pattern per alternative"; let pat := if pat.isOfKind `Lean.Parser.Term.stxQuot then pat.setArg 1 $ elimAntiquotChoices $ pat.getArg 1 else pat; match pat.find? $ fun stx => stx.getKind == choiceKind with | some choiceStx => throwError choiceStx "invalid pattern, nested syntax has multiple interpretations" | none => let rhs := alt.getArg 2; pure ([pat], rhs) }; -- letBindRhss (compileStxMatch stx [discr]) alts.toList [] compileStxMatch stx [discr] alts.toList @[builtinTermElab «match_syntax»] def elabMatchSyntax : TermElab := adaptExpander match_syntax.expand -- REMOVE with old frontend private def exprPlaceholder := mkMVar Name.anonymous private unsafe partial def toPreterm : Syntax → TermElabM Expr | stx => let args := stx.getArgs; match stx.getKind with | `Lean.Parser.Term.id => match args.get! 0 with | Syntax.ident _ _ val preresolved => do resolved ← resolveName stx val preresolved []; match resolved with | (pre,projs)::_ => let pre := match pre with | Expr.const c _ _ => Lean.mkConst c -- remove universes confusing the old frontend | _ => pre; pure $ projs.foldl (fun e proj => mkMData (MData.empty.setName `fieldNotation proj) e) pre | [] => unreachable! | _ => unreachable! | `Lean.Parser.Term.fun => do let params := (args.get! 1).getArgs; let body := args.get! 3; if params.size == 0 then toPreterm body else do let param := params.get! 0; (n, ty) ← if param.isOfKind `Lean.Parser.Term.id then pure (param.getIdAt 0, exprPlaceholder) else if param.isOfKind `Lean.Parser.Term.hole then pure (`_a, exprPlaceholder) else do { let n := ((param.getArg 1).getArg 0).getIdAt 0; ty ← toPreterm $ (((param.getArg 1).getArg 1).getArg 0).getArg 1; pure (n, ty) }; lctx ← getLCtx; let lctx := lctx.mkLocalDecl n n ty; let params := params.eraseIdx 0; stx ← `(fun $params* => $body); adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ do e ← toPreterm stx; pure $ lctx.mkLambda #[mkFVar n] e | `Lean.Parser.Term.let => do let decl := args.get! 1; let n := if (decl.getArg 0).isIdent then (decl.getArg 0).getId else (decl.getArg 0).getIdAt 0; let val := decl.getArg 4; let body := args.get! 3; val ← toPreterm val; lctx ← getLCtx; let lctx := lctx.mkLetDecl n n exprPlaceholder val; adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ do e ← toPreterm $ body; pure $ lctx.mkLambda #[mkFVar n] e | `Lean.Parser.Term.app => do fn ← toPreterm $ args.get! 0; as ← (args.get! 1).getArgs.mapM toPreterm; pure $ mkAppN fn as | `Lean.Parser.Term.if => do let con := args.get! 2; let yes := args.get! 4; let no := args.get! 6; toPreterm $ Unhygienic.run `(ite $con $yes $no) | `Lean.Parser.Term.paren => let inner := (args.get! 1).getArgs; if inner.size == 0 then pure $ Lean.mkConst `Unit.unit else toPreterm $ inner.get! 0 | `Lean.Parser.Term.band => let lhs := args.get! 0; let rhs := args.get! 2; toPreterm $ Unhygienic.run `(and $lhs $rhs) | `Lean.Parser.Term.beq => let lhs := args.get! 0; let rhs := args.get! 2; toPreterm $ Unhygienic.run `(HasBeq.beq $lhs $rhs) | `Lean.Parser.Term.eq => let lhs := args.get! 0; let rhs := args.get! 2; toPreterm $ Unhygienic.run `(Eq $lhs $rhs) | `Lean.Parser.Term.str => pure $ mkStrLit $ (stx.getArg 0).isStrLit?.getD "" | `Lean.Parser.Term.num => pure $ mkNatLit $ (stx.getArg 0).isNatLit?.getD 0 | `expr => pure $ unsafeCast $ stx.getArg 0 -- HACK: see below | k => throwError stx $ "stxQuot: unimplemented kind " ++ toString k @[export lean_parse_expr] def oldParseExpr (env : Environment) (input : String) (pos : String.Pos) : Except String (Syntax × String.Pos) := do let c := Parser.mkParserContext env (Parser.mkInputContext input "<foo>"); let s := Parser.mkParserState c.input; let s := s.setPos pos; let s := (Parser.termParser Parser.appPrec : Parser.Parser).fn { rbp := Parser.appPrec, .. c } s; let stx := s.stxStack.back; match s.errorMsg with | some errorMsg => Except.error $ toString errorMsg | none => Except.ok (stx, s.pos) structure OldContext := (env : Environment) (locals : List Name) (open_nss : List Name) private def oldRunTermElabM {α} (ctx : OldContext) (x : TermElabM α) : Except String α := do match x {fileName := "foo", fileMap := FileMap.ofString "", cmdPos := 0, currNamespace := ctx.env.getNamespace, currRecDepth := 0, maxRecDepth := 10000, openDecls := ctx.open_nss.map $ fun n => OpenDecl.simple n [], lctx := ctx.locals.foldl (fun lctx l => LocalContext.mkLocalDecl lctx l l exprPlaceholder) $ LocalContext.mkEmpty ()} {env := ctx.env} with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error msg _ => Except.error $ toString msg @[export lean_expand_stx_quot] unsafe def oldExpandStxQuot (ctx : OldContext) (stx : Syntax) : Except String Expr := oldRunTermElabM ctx $ do stx ← stxQuot.expand stx; toPreterm stx @[export lean_get_antiquot_vars] def oldGetPatternVars (ctx : OldContext) (pats : List Syntax) : Except String (List Name) := oldRunTermElabM ctx $ do let vars := List.join $ pats.map getPatternVars; pure $ vars.map $ fun var => var.getIdAt 0 @[export lean_expand_match_syntax] unsafe def oldExpandMatchSyntax (ctx : OldContext) (discr : Syntax) (alts : List (List Syntax × Syntax)) : Except String Expr := oldRunTermElabM ctx $ do -- HACK: discr and the RHSs are actually `Expr` let discr := Syntax.node `expr #[discr]; let alts := alts.map $ fun alt => let pats := alt.1.map elimAntiquotChoices; (pats, Syntax.node `expr #[alt.2]); -- letBindRhss (compileStxMatch Syntax.missing [discr]) alts [] stx ← compileStxMatch Syntax.missing [discr] alts; toPreterm stx end Quotation end Term end Elab end Lean
5ea6fe218611c9eb1ffb61a47b70cf46693e77c4
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/Match/CaseArraySizes.lean
f83391fa4838884524841f7a5119b1b51a921e4a
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
3,842
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.Assert import Lean.Meta.Match.CaseValues namespace Lean.Meta structure CaseArraySizesSubgoal where mvarId : MVarId elems : Array FVarId := #[] diseqs : Array FVarId := #[] subst : FVarSubst := {} instance : Inhabited CaseArraySizesSubgoal := ⟨{ mvarId := arbitrary }⟩ def getArrayArgType (a : Expr) : MetaM Expr := do let aType ← inferType a let aType ← whnfD aType unless aType.isAppOfArity `Array 1 do throwError "array expected{indentExpr a}" pure aType.appArg! private def mkArrayGetLit (a : Expr) (i : Nat) (n : Nat) (h : Expr) : MetaM Expr := do let lt ← mkLt (mkRawNatLit i) (mkRawNatLit n) let ltPrf ← mkDecideProof lt mkAppM `Array.getLit #[a, mkRawNatLit i, h, ltPrf] private partial def introArrayLit (mvarId : MVarId) (a : Expr) (n : Nat) (xNamePrefix : Name) (aSizeEqN : Expr) : MetaM MVarId := do let α ← getArrayArgType a let rec loop (i : Nat) (xs : Array Expr) (args : Array Expr) := do if i < n then withLocalDeclD (xNamePrefix.appendIndexAfter (i+1)) α fun xi => do let xs := xs.push xi let ai ← mkArrayGetLit a i n aSizeEqN let args := args.push ai loop (i+1) xs args else let xsLit ← mkArrayLit α xs.toList let aEqXsLit ← mkEq a xsLit let aEqLitPrf ← mkAppM ``Array.toArrayLit_eq #[a, mkRawNatLit n, aSizeEqN] withLocalDeclD `hEqALit aEqXsLit fun heq => do let target ← getMVarType mvarId let newTarget ← mkForallFVars (xs.push heq) target pure (newTarget, args.push aEqLitPrf) let (newTarget, args) ← loop 0 #[] #[] let tag ← getMVarTag mvarId let newMVar ← mkFreshExprSyntheticOpaqueMVar newTarget tag assignExprMVar mvarId (mkAppN newMVar args) pure newMVar.mvarId! /-- Split goal `... |- C a` into sizes.size + 1 subgoals 1) `..., x_1 ... x_{sizes[0]} |- C #[x_1, ... x_{sizes[0]}]` ... n) `..., x_1 ... x_{sizes[n-1]} |- C #[x_1, ..., x_{sizes[n-1]}]` n+1) `..., (h_1 : a.size != sizes[0]), ..., (h_n : a.size != sizes[n-1]) |- C a` where `n = sizes.size` -/ def caseArraySizes (mvarId : MVarId) (fvarId : FVarId) (sizes : Array Nat) (xNamePrefix := `x) (hNamePrefix := `h) : MetaM (Array CaseArraySizesSubgoal) := withMVarContext mvarId do let a := mkFVar fvarId let α ← getArrayArgType a let aSize ← mkAppM `Array.size #[a] let mvarId ← assertExt mvarId `aSize (mkConst `Nat) aSize let (aSizeFVarId, mvarId) ← intro1 mvarId let (hEq, mvarId) ← intro1 mvarId let subgoals ← caseValues mvarId aSizeFVarId (sizes.map mkRawNatLit) hNamePrefix subgoals.mapIdxM fun i subgoal => do let subst := subgoal.subst let mvarId := subgoal.mvarId let hEqSz := (subst.get hEq).fvarId! if h : i.val < sizes.size then let n := sizes.get ⟨i, h⟩ let mvarId ← clear mvarId subgoal.newHs[0] let mvarId ← clear mvarId (subst.get aSizeFVarId).fvarId! withMVarContext mvarId do let hEqSzSymm ← mkEqSymm (mkFVar hEqSz) let mvarId ← introArrayLit mvarId a n xNamePrefix hEqSzSymm let (xs, mvarId) ← introN mvarId n let (hEqLit, mvarId) ← intro1 mvarId let mvarId ← clear mvarId hEqSz let (subst, mvarId) ← substCore mvarId hEqLit false subst pure { mvarId := mvarId, elems := xs, subst := subst } else let (subst, mvarId) ← substCore mvarId hEq false subst let diseqs := subgoal.newHs.map fun fvarId => (subst.get fvarId).fvarId! pure { mvarId := mvarId, diseqs := diseqs, subst := subst } end Lean.Meta
3396f63ee76d5c63b6cc3e02f9b149b0590dda66
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/convex/simplicial_complex/basic.lean
f29d4b338165830a4729f24a28f5515ad8304a7c
[ "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
9,921
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.hull import linear_algebra.affine_space.independent /-! # Simplicial complexes > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we define simplicial complexes in `𝕜`-modules. A simplicial complex is a collection of simplices closed by inclusion (of vertices) and intersection (of underlying sets). We model them by a downward-closed set of affine independent finite sets whose convex hulls "glue nicely", each finite set and its convex hull corresponding respectively to the vertices and the underlying set of a simplex. ## Main declarations * `simplicial_complex 𝕜 E`: A simplicial complex in the `𝕜`-module `E`. * `simplicial_complex.vertices`: The zero dimensional faces of a simplicial complex. * `simplicial_complex.facets`: The maximal faces of a simplicial complex. ## Notation `s ∈ K` means that `s` is a face of `K`. `K ≤ L` means that the faces of `K` are faces of `L`. ## Implementation notes "glue nicely" usually means that the intersection of two faces (as sets in the ambient space) is a face. Given that we store the vertices, not the faces, this would be a bit awkward to spell. Instead, `simplicial_complex.inter_subset_convex_hull` is an equivalent condition which works on the vertices. ## TODO Simplicial complexes can be generalized to affine spaces once `convex_hull` has been ported. -/ open finset set variables (𝕜 E : Type*) {ι : Type*} [ordered_ring 𝕜] [add_comm_group E] [module 𝕜 E] namespace geometry /-- A simplicial complex in a `𝕜`-module is a collection of simplices which glue nicely together. Note that the textbook meaning of "glue nicely" is given in `geometry.simplicial_complex.disjoint_or_exists_inter_eq_convex_hull`. It is mostly useless, as `geometry.simplicial_complex.convex_hull_inter_convex_hull` is enough for all purposes. -/ -- TODO: update to new binder order? not sure what binder order is correct for `down_closed`. @[ext] structure simplicial_complex := (faces : set (finset E)) (not_empty_mem : ∅ ∉ faces) (indep : ∀ {s}, s ∈ faces → affine_independent 𝕜 (coe : (s : set E) → E)) (down_closed : ∀ {s t}, s ∈ faces → t ⊆ s → t ≠ ∅ → t ∈ faces) (inter_subset_convex_hull : ∀ {s t}, s ∈ faces → t ∈ faces → convex_hull 𝕜 ↑s ∩ convex_hull 𝕜 ↑t ⊆ convex_hull 𝕜 (s ∩ t : set E)) namespace simplicial_complex variables {𝕜 E} {K : simplicial_complex 𝕜 E} {s t : finset E} {x : E} /-- A `finset` belongs to a `simplicial_complex` if it's a face of it. -/ instance : has_mem (finset E) (simplicial_complex 𝕜 E) := ⟨λ s K, s ∈ K.faces⟩ /-- The underlying space of a simplicial complex is the union of its faces. -/ def space (K : simplicial_complex 𝕜 E) : set E := ⋃ s ∈ K.faces, convex_hull 𝕜 (s : set E) lemma mem_space_iff : x ∈ K.space ↔ ∃ s ∈ K.faces, x ∈ convex_hull 𝕜 (s : set E) := mem_Union₂ lemma convex_hull_subset_space (hs : s ∈ K.faces) : convex_hull 𝕜 ↑s ⊆ K.space := subset_bUnion_of_mem hs protected lemma subset_space (hs : s ∈ K.faces) : (s : set E) ⊆ K.space := (subset_convex_hull 𝕜 _).trans $ convex_hull_subset_space hs lemma convex_hull_inter_convex_hull (hs : s ∈ K.faces) (ht : t ∈ K.faces) : convex_hull 𝕜 ↑s ∩ convex_hull 𝕜 ↑t = convex_hull 𝕜 (s ∩ t : set E) := (K.inter_subset_convex_hull hs ht).antisymm $ subset_inter (convex_hull_mono $ set.inter_subset_left _ _) $ convex_hull_mono $ set.inter_subset_right _ _ /-- The conclusion is the usual meaning of "glue nicely" in textbooks. It turns out to be quite unusable, as it's about faces as sets in space rather than simplices. Further, additional structure on `𝕜` means the only choice of `u` is `s ∩ t` (but it's hard to prove). -/ lemma disjoint_or_exists_inter_eq_convex_hull (hs : s ∈ K.faces) (ht : t ∈ K.faces) : disjoint (convex_hull 𝕜 (s : set E)) (convex_hull 𝕜 ↑t) ∨ ∃ u ∈ K.faces, convex_hull 𝕜 (s : set E) ∩ convex_hull 𝕜 ↑t = convex_hull 𝕜 ↑u := begin classical, by_contra' h, refine h.2 (s ∩ t) (K.down_closed hs (inter_subset_left _ _) $ λ hst, h.1 $ disjoint_iff_inf_le.mpr $ (K.inter_subset_convex_hull hs ht).trans _) _, { rw [←coe_inter, hst, coe_empty, convex_hull_empty], refl }, { rw [coe_inter, convex_hull_inter_convex_hull hs ht] } end /-- Construct a simplicial complex by removing the empty face for you. -/ @[simps] def of_erase (faces : set (finset E)) (indep : ∀ s ∈ faces, affine_independent 𝕜 (coe : (s : set E) → E)) (down_closed : ∀ s ∈ faces, ∀ t ⊆ s, t ∈ faces) (inter_subset_convex_hull : ∀ s t ∈ faces, convex_hull 𝕜 ↑s ∩ convex_hull 𝕜 ↑t ⊆ convex_hull 𝕜 (s ∩ t : set E)) : simplicial_complex 𝕜 E := { faces := faces \ {∅}, not_empty_mem := λ h, h.2 (mem_singleton _), indep := λ s hs, indep _ hs.1, down_closed := λ s t hs hts ht, ⟨down_closed _ hs.1 _ hts, ht⟩, inter_subset_convex_hull := λ s t hs ht, inter_subset_convex_hull _ hs.1 _ ht.1 } /-- Construct a simplicial complex as a subset of a given simplicial complex. -/ @[simps] def of_subcomplex (K : simplicial_complex 𝕜 E) (faces : set (finset E)) (subset : faces ⊆ K.faces) (down_closed : ∀ {s t}, s ∈ faces → t ⊆ s → t ∈ faces) : simplicial_complex 𝕜 E := { faces := faces, not_empty_mem := λ h, K.not_empty_mem (subset h), indep := λ s hs, K.indep (subset hs), down_closed := λ s t hs hts _, down_closed hs hts, inter_subset_convex_hull := λ s t hs ht, K.inter_subset_convex_hull (subset hs) (subset ht) } /-! ### Vertices -/ /-- The vertices of a simplicial complex are its zero dimensional faces. -/ def vertices (K : simplicial_complex 𝕜 E) : set E := {x | {x} ∈ K.faces} lemma mem_vertices : x ∈ K.vertices ↔ {x} ∈ K.faces := iff.rfl lemma vertices_eq : K.vertices = ⋃ k ∈ K.faces, (k : set E) := begin ext x, refine ⟨λ h, mem_bUnion h $ mem_coe.2 $ mem_singleton_self x, λ h, _⟩, obtain ⟨s, hs, hx⟩ := mem_Union₂.1 h, exact K.down_closed hs (finset.singleton_subset_iff.2 $ mem_coe.1 hx) (singleton_ne_empty _), end lemma vertices_subset_space : K.vertices ⊆ K.space := vertices_eq.subset.trans $ Union₂_mono $ λ x hx, subset_convex_hull 𝕜 x lemma vertex_mem_convex_hull_iff (hx : x ∈ K.vertices) (hs : s ∈ K.faces) : x ∈ convex_hull 𝕜 (s : set E) ↔ x ∈ s := begin refine ⟨λ h, _, λ h, subset_convex_hull _ _ h⟩, classical, have h := K.inter_subset_convex_hull hx hs ⟨by simp, h⟩, by_contra H, rwa [←coe_inter, finset.disjoint_iff_inter_eq_empty.1 (finset.disjoint_singleton_right.2 H).symm, coe_empty, convex_hull_empty] at h, end /-- A face is a subset of another one iff its vertices are. -/ lemma face_subset_face_iff (hs : s ∈ K.faces) (ht : t ∈ K.faces) : convex_hull 𝕜 (s : set E) ⊆ convex_hull 𝕜 ↑t ↔ s ⊆ t := ⟨λ h x hxs, (vertex_mem_convex_hull_iff (K.down_closed hs (finset.singleton_subset_iff.2 hxs) $ singleton_ne_empty _) ht).1 (h (subset_convex_hull 𝕜 ↑s hxs)), convex_hull_mono⟩ /-! ### Facets -/ /-- A facet of a simplicial complex is a maximal face. -/ def facets (K : simplicial_complex 𝕜 E) : set (finset E) := {s ∈ K.faces | ∀ ⦃t⦄, t ∈ K.faces → s ⊆ t → s = t} lemma mem_facets : s ∈ K.facets ↔ s ∈ K.faces ∧ ∀ t ∈ K.faces, s ⊆ t → s = t := mem_sep_iff lemma facets_subset : K.facets ⊆ K.faces := λ s hs, hs.1 lemma not_facet_iff_subface (hs : s ∈ K.faces) : (s ∉ K.facets ↔ ∃ t, t ∈ K.faces ∧ s ⊂ t) := begin refine ⟨λ (hs' : ¬ (_ ∧ _)), _, _⟩, { push_neg at hs', obtain ⟨t, ht⟩ := hs' hs, exact ⟨t, ht.1, ⟨ht.2.1, (λ hts, ht.2.2 (subset.antisymm ht.2.1 hts))⟩⟩ }, { rintro ⟨t, ht⟩ ⟨hs, hs'⟩, have := hs' ht.1 ht.2.1, rw this at ht, exact ht.2.2 (subset.refl t) } -- `has_ssubset.ssubset.ne` would be handy here end /-! ### The semilattice of simplicial complexes `K ≤ L` means that `K.faces ⊆ L.faces`. -/ variables (𝕜 E) /-- The complex consisting of only the faces present in both of its arguments. -/ instance : has_inf (simplicial_complex 𝕜 E) := ⟨λ K L, { faces := K.faces ∩ L.faces, not_empty_mem := λ h, K.not_empty_mem (set.inter_subset_left _ _ h), indep := λ s hs, K.indep hs.1, down_closed := λ s t hs hst ht, ⟨K.down_closed hs.1 hst ht, L.down_closed hs.2 hst ht⟩, inter_subset_convex_hull := λ s t hs ht, K.inter_subset_convex_hull hs.1 ht.1 }⟩ instance : semilattice_inf (simplicial_complex 𝕜 E) := { inf := (⊓), inf_le_left := λ K L s hs, hs.1, inf_le_right := λ K L s hs, hs.2, le_inf := λ K L M hKL hKM s hs, ⟨hKL hs, hKM hs⟩, .. (partial_order.lift faces $ λ x y, ext _ _) } instance : has_bot (simplicial_complex 𝕜 E) := ⟨{ faces := ∅, not_empty_mem := set.not_mem_empty ∅, indep := λ s hs, (set.not_mem_empty _ hs).elim, down_closed := λ s _ hs, (set.not_mem_empty _ hs).elim, inter_subset_convex_hull := λ s _ hs, (set.not_mem_empty _ hs).elim }⟩ instance : order_bot (simplicial_complex 𝕜 E) := { bot_le := λ K, set.empty_subset _, .. simplicial_complex.has_bot 𝕜 E } instance : inhabited (simplicial_complex 𝕜 E) := ⟨⊥⟩ variables {𝕜 E} lemma faces_bot : (⊥ : simplicial_complex 𝕜 E).faces = ∅ := rfl lemma space_bot : (⊥ : simplicial_complex 𝕜 E).space = ∅ := set.bUnion_empty _ lemma facets_bot : (⊥ : simplicial_complex 𝕜 E).facets = ∅ := eq_empty_of_subset_empty facets_subset end simplicial_complex end geometry
1e5dc1ac9abe1da7fd629bd8355ce1f40040daa1
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/measure_theory/category/Meas.lean
a1edbaafd86dae82add0e907625f85aecd3da35b
[ "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
4,316
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 -/ import topology.category.Top.basic import measure_theory.giry_monad import category_theory.monad.algebra /-! # The category of measurable spaces Measurable spaces and measurable functions form a (concrete) category `Meas`. ## Main definitions * `Measure : Meas ⥤ Meas`: the functor which sends a measurable space `X` to the space of measures on `X`; it is a monad (the "Giry monad"). * `Borel : Top ⥤ Meas`: sends a topological space `X` to `X` equipped with the `σ`-algebra of Borel sets (the `σ`-algebra generated by the open subsets of `X`). ## Tags measurable space, giry monad, borel -/ noncomputable theory open category_theory measure_theory open_locale ennreal universes u v /-- The category of measurable spaces and measurable functions. -/ @[derive has_coe_to_sort] def Meas : Type (u+1) := bundled measurable_space namespace Meas instance (X : Meas) : measurable_space X := X.str /-- Construct a bundled `Meas` from the underlying type and the typeclass. -/ def of (α : Type u) [measurable_space α] : Meas := ⟨α⟩ @[simp] lemma coe_of (X : Type u) [measurable_space X] : (of X : Type u) = X := rfl instance unbundled_hom : unbundled_hom @measurable := ⟨@measurable_id, @measurable.comp⟩ attribute [derive [large_category, concrete_category]] Meas instance : inhabited Meas := ⟨Meas.of empty⟩ /-- `Measure X` is the measurable space of measures over the measurable space `X`. It is the weakest measurable space, s.t. λμ, μ s is measurable for all measurable sets `s` in `X`. An important purpose is to assign a monadic structure on it, the Giry monad. In the Giry monad, the pure values are the Dirac measure, and the bind operation maps to the integral: `(μ >>= ν) s = ∫ x. (ν x) s dμ`. In probability theory, the `Meas`-morphisms `X → Prob X` are (sub-)Markov kernels (here `Prob` is the restriction of `Measure` to (sub-)probability space.) -/ def Measure : Meas ⥤ Meas := { obj := λX, ⟨@measure_theory.measure X.1 X.2⟩, map := λX Y f, ⟨measure.map (f : X → Y), measure.measurable_map f f.2⟩, map_id' := assume ⟨α, I⟩, subtype.eq $ funext $ assume μ, @measure.map_id α I μ, map_comp':= assume X Y Z ⟨f, hf⟩ ⟨g, hg⟩, subtype.eq $ funext $ assume μ, (measure.map_map hg hf).symm } /-- The Giry monad, i.e. the monadic structure associated with `Measure`. -/ def Giry : category_theory.monad Meas := { to_functor := Measure, η' := { app := λX, ⟨@measure.dirac X.1 X.2, measure.measurable_dirac⟩, naturality' := assume X Y ⟨f, hf⟩, subtype.eq $ funext $ assume a, (measure.map_dirac hf a).symm }, μ' := { app := λX, ⟨@measure.join X.1 X.2, measure.measurable_join⟩, naturality' := assume X Y ⟨f, hf⟩, subtype.eq $ funext $ assume μ, measure.join_map_map hf μ }, assoc' := assume α, subtype.eq $ funext $ assume μ, @measure.join_map_join _ _ _, left_unit' := assume α, subtype.eq $ funext $ assume μ, @measure.join_dirac _ _ _, right_unit' := assume α, subtype.eq $ funext $ assume μ, @measure.join_map_dirac _ _ _ } /-- An example for an algebra on `Measure`: the nonnegative Lebesgue integral is a hom, behaving nicely under the monad operations. -/ def Integral : Giry.algebra := { A := Meas.of ℝ≥0∞ , a := ⟨λm:measure ℝ≥0∞, ∫⁻ x, x ∂m, measure.measurable_lintegral measurable_id ⟩, unit' := subtype.eq $ funext $ assume r:ℝ≥0∞, lintegral_dirac' _ measurable_id, assoc' := subtype.eq $ funext $ assume μ : measure (measure ℝ≥0∞), show ∫⁻ x, x ∂ μ.join = ∫⁻ x, x ∂ (measure.map (λm:measure ℝ≥0∞, ∫⁻ x, x ∂m) μ), by rw [measure.lintegral_join, lintegral_map]; apply_rules [measurable_id, measure.measurable_lintegral] } end Meas instance Top.has_forget_to_Meas : has_forget₂ Top.{u} Meas.{u} := bundled_hom.mk_has_forget₂ borel (λ X Y f, ⟨f.1, f.2.borel_measurable⟩) (by intros; refl) /-- The Borel functor, the canonical embedding of topological spaces into measurable spaces. -/ @[reducible] def Borel : Top.{u} ⥤ Meas.{u} := forget₂ Top.{u} Meas.{u}
df4ad57aafa5b64ce68bf4eac0ab6a7a1d2a3f34
db7384d2e2fd918ae6383e28c1e441b390107ab9
/examples/category/monoidal.hlean
7449c1bf5bc6f697733b83050049ff0692a5b41a
[]
no_license
minfuk/leanprover
f08a8ec10d9e210d4f1bf388c61201a68588faaf
d51a8eb4e829ecef546e86f3915a58762cc7d3b9
refs/heads/master
1,585,996,825,236
1,459,673,617,000
1,459,673,617,000
55,336,710
0
0
null
null
null
null
UTF-8
Lean
false
false
316
hlean
import algebra.category.precategory algebra.category.category algebra.category.functor.basic algebra.category.functor.equivalence algebra.category.nat_trans algebra.category.constructions.product algebra.category.constructions.functor open eq prod category functor iso prod.ops nat_trans category.hom
3e94450274656826dc44b62810893b299d5840f8
c19879c147c0dff0a7348a8264e74b58a37969c4
/src/01_basics.lean
64a961d9754511e657db240f5e3124303347674b
[]
no_license
gebner/leantogether2019_tutorial
f2aac98f2097bd6ac8ce396abc9a676f0eda71bd
21b4dc890f964fc98837129094b8bab68363349f
refs/heads/master
1,586,899,127,009
1,546,796,548,000
1,546,796,548,000
164,124,225
0
0
null
null
null
null
UTF-8
Lean
false
false
8,319
lean
/- Definitions -/ def square (m : ℕ) : ℕ := m * m -- We can write the same function as a lambda def square' : ℕ → ℕ := λ (m : ℕ), m * m -- ... or using pattern matching def square'' : ℕ → ℕ | 0 := 0 | (m+1) := square'' m + 2 * m + 1 /- Interactive commands -/ #print square' #eval square' 12 #check square #check λ x, square (string.length x) example (x : ℕ) : ℕ := square'' (2*x) #check ℕ → ℕ #check ∀ x : ℕ, x = x #check Π n : ℕ, array n ℕ /- Polymorphic definitions -/ #check ℕ #check Type #check Type 1 #check Type 2 universes u v #check Type u -- polymorphic functions take the type as an extra argument def injective (α : Type u) (β : Type v) (f : α → β) : Prop := ∀ x y, f x = f y → x = y #check injective ℕ ℕ nat.succ -- using curly braces, Lean will fill in the type automatically ("implicit argument") def injective' {α : Type u} {β : Type v} (f : α → β) : Prop := injective α β f #check injective ℕ ℕ nat.succ #check injective' nat.succ /- Inductive types (≃ free algebras) -/ -- "Let mynat be the smallest set containing zero and succ x for every x ∈ mynat" inductive mynat : Type | zero : mynat | succ (x : mynat) : mynat #check mynat #check mynat.zero #check mynat.succ #check mynat.rec /- Inductive predicates -/ -- The same mechanism can also define predicates -- "Let le be the smallest relation containg ..." inductive mynat.le : mynat → mynat → Prop | refl {a} : mynat.le a a | step {a b} : mynat.le a b → mynat.le a (mynat.succ b) /- Recursion -/ def mynat.add (m : mynat) : mynat → mynat -- pattern matching only applies to the arguments after the colon | mynat.zero := m | (mynat.succ x) := mynat.succ (mynat.add x) /- Namespaces -/ -- names in lean are separated by . (like / for file names) #check mynat.add -- after open, we no longer need to write the prefix open mynat #check add #eval add (succ zero) (succ zero) -- adds the prefix to all definitions namespace mynat.foo namespace bar def baz := succ zero end bar end mynat.foo #check mynat.foo.bar.baz #print prefix mynat /- Structures -/ structure point (α : Type u) := (x : α) (y : α) def pt : point ℕ := { y := 1, x := 2 } #eval pt.y #eval point.y pt example : point ℕ := point.mk 1 2 example : point ℕ := ⟨1, 2⟩ example := { point . x := 1, y := 2 } example : point ℕ := { x := 1, y := 2 } example := { pt with x := 5 } structure point3 (α : Type u) extends point α := (z : α) example : point3 ℕ := { pt with z := 3 } /- Type classes -/ -- type classes allow us to define 0, 1, +, etc. for arbitrary objects #check (0 : mynat) #check (1 : mynat) #check zero + zero -- type class instances are just structures: instance : has_zero mynat := { zero := mynat.zero } #print instances has_zero #check (0 : mynat) instance : has_add mynat := { add := mynat.add } #check (0 + 0 : mynat) @[instance] -- instances are just definitions with the [instance] "attribute" def mynat.has_one : has_one mynat := ⟨succ zero⟩ -- any structure instance syntax works -- now numerals work! #check (7 : mynat) -- type class arguments are written in square brackets def double {α : Type u} [has_add α] (x : α) := x + x #check double (7 : mynat) /- Logical connectives -/ section -- Variables in a section are implicitly added -- to all definitions/theorems/etc. (as needed) variables (p q : Prop) (r : mynat → Prop) #check p → q #check ∀ x, r x #check true #check false #check 0 = 1 #check 0 = (1 : mynat) #check p ∨ q #check ¬q #check p ∧ q #check p ↔ q #check ∃ x, r x #check ∀ x < 100, ∃ y > 20, ∃ z ∈ {0,1,2,3}, ∃ w, x+y = z+w end /- Tactics produce either a single new tactic state, or fail. A tactic state is essentially a list of goals. -/ lemma p1_1 {a b : Prop} : a → b → b ∧ a := begin intros ha hb, apply and.intro, assumption, assumption, end -- we can freely mix tactics and expressions #check fin.mk -- (fin n) are the natural numbers less than n example (n : ℕ) : fin (2*n + 7) := fin.mk n (begin end) -- failing tactics are underlined in red lemma p1_2 {a b : Prop} : a → b → b ∧ a := begin intros ha hb, apply and.intro, -- repeats a tactic until it fails repeat { assumption }, end lemma p1_6 {a b : Prop} : a → b → b ∧ a := -- ; executes the right tactic on all new goals by intros ha hb; apply and.intro; assumption lemma p2 (x : ℕ) : true ∧ x = x := -- the orelse (<|>) operator allows backtracking by constructor; trivial <|> refl /- Rewriting -/ lemma p3 (f : ℕ → ℕ) (a b : ℕ) (h : f (1 * (0 + a)) = f b) : f a = f (0 + b) := begin -- The `rw` tactic takes a (quantified) equation and rewrites the goal using it rw zero_add, -- You can also pass it multiple equations, and/or rewrite hypotheses rw [zero_add, one_mul] at h, assumption, end /- Induction -/ lemma mynat.zero_add {a : mynat} : 0 + a = a := begin induction a, end /- Theorems -/ lemma mynat.add_comm (a b : mynat) : a + b = b + a := begin end lemma mynat.add_assoc (a b c : mynat) : a + b + c = a + (b + c) := begin end -- It's boring to write (a b c : mynat) every time. section variables (a b c : mynat) lemma mynat.eq_iff_succ_eq_succ : succ a = succ b → a = b := begin end lemma mynat.add_cancel_right : a + c = b + c → a = b := begin end end /- Notations -/ notation `ℕ'` := mynat #check (5 : ℕ') -- supports various fancy stuff, e.g. mixfix operators and binders def mysum {α} [has_add α] : mynat → (mynat → α) → α | 0 f := f 0 | (succ a) f := mysum a f + f (succ a) local notation `sum` binder `until` b `of` f:(scoped x, x) := mysum b f #check sum i until 10 of i+20 #eval sum i until 10 of i+20 /- There are two different kinds of "truth values": - Prop: types, erased at runtime ^^^^ this is what you use to state theorems - bool: inductive type with values tt/ff, computable -/ #check true ∧ false ∨ true #check tt && ff || tt -- Lean automatically converts ("coerces") bools into Props -- x is coerced into x = tt example : (tt : Prop) := rfl -- We can convert a Prop p into a bool if it is "decidable", -- i.e. there is a function that computes whether p is true or not #eval (∀ x ∈ [1,2,3,4], x^2 < x + 10 : bool) -- decidable is implemented as a typeclass, and you can add your own instances #print instances decidable -- Many definitions in Lean use decidable propositions instead of bool: #eval if ∀ x ∈ [1,2,3,4], x^2 < x + 10 then "ok" else "ko" #check guard $ ∀ x ∈ [1,2,3,4], x^2 < x + 10 #check list.filter (λ x, x^2 < x + 10) -- Choice implies that all propositions are decidable. -- If we mark `classical.prop_decidable` as a type-class instance, -- then if-then-else works on all propositions. local attribute [instance, priority 0] classical.prop_decidable -- However we cannot execute definitions that use choice to -- construct data, such definitions are then marked as "noncomputable". noncomputable def find_zero (f : ℕ → ℕ) : ℕ := if h : ∃ i, f i = 0 then classical.some h else 0 #eval find_zero (λ x, 1) /- Definitional equality -/ -- the free monoid generated by ℕ' #check list mynat #check ([1,4,3] : list mynat) -- the free monoid generated by the carrier of the free monoid generated by ℕ' #check list (list mynat) def nested_list (α : Type u) : ℕ → Type u | 0 := α -- recursive calls only have arguments from after the colon | (n+1) := list (nested_list n) #reduce nested_list ℕ' 5 -- Why does this work? example (n : ℕ) (xs : nested_list ℕ' (n+1)) := list.length xs -- xs needs to be a (list _) here, but it's a nested_list! -- (nested_list _ (n+1)) reduces to a (list _): #reduce λ n, nested_list ℕ' (n+1) -- This is called "definitional equality". -- In the underlying logic of Lean, both terms can be used interchangeably*. #reduce λ n, n+1 #reduce λ n, 1+n -- We can of course write functions that return nested_list def n_singleton {α : Type u} : ∀ n, α → nested_list α n -- in the base case, the return type is (nested_list α 0) =def= α | 0 a := a -- in the step case, the return type is -- (nested_list α (n+1)) =def= (list (nested_list α n)) | (n+1) a := [n_singleton n a]
f6b4bdcec21b48a2403050300e31de91d6b8a357
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Std/Data/PersistentHashMap.lean
33f8b67367031dedd6831ed80cf8fbb1b06c369a
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,382
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 -/ namespace Std universes u v w w' namespace PersistentHashMap inductive Entry (α : Type u) (β : Type v) (σ : Type w) := | entry (key : α) (val : β) : Entry α β σ | ref (node : σ) : Entry α β σ | null : Entry α β σ instance {α β σ} : Inhabited (Entry α β σ) := ⟨Entry.null⟩ inductive Node (α : Type u) (β : Type v) : Type (max u v) := | entries (es : Array (Entry α β (Node α β))) : Node α β | collision (ks : Array α) (vs : Array β) (h : ks.size = vs.size) : Node α β instance {α β} : Inhabited (Node α β) := ⟨Node.entries #[]⟩ abbrev shift : USize := 5 abbrev branching : USize := USize.ofNat (2 ^ shift.toNat) abbrev maxDepth : USize := 7 abbrev maxCollisions : Nat := 4 def mkEmptyEntriesArray {α β} : Array (Entry α β (Node α β)) := (Array.mkArray PersistentHashMap.branching.toNat PersistentHashMap.Entry.null) end PersistentHashMap structure PersistentHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := (root : PersistentHashMap.Node α β := PersistentHashMap.Node.entries PersistentHashMap.mkEmptyEntriesArray) (size : Nat := 0) abbrev PHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := PersistentHashMap α β namespace PersistentHashMap variables {α : Type u} {β : Type v} def empty [BEq α] [Hashable α] : PersistentHashMap α β := {} def isEmpty [BEq α] [Hashable α] (m : PersistentHashMap α β) : Bool := m.size == 0 instance [BEq α] [Hashable α] : Inhabited (PersistentHashMap α β) := ⟨{}⟩ def mkEmptyEntries {α β} : Node α β := Node.entries mkEmptyEntriesArray abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) inductive IsCollisionNode : Node α β → Prop := | mk (keys : Array α) (vals : Array β) (h : keys.size = vals.size) : IsCollisionNode (Node.collision keys vals h) abbrev CollisionNode (α β) := { n : Node α β // IsCollisionNode n } inductive IsEntriesNode : Node α β → Prop := | mk (entries : Array (Entry α β (Node α β))) : IsEntriesNode (Node.entries entries) abbrev EntriesNode (α β) := { n : Node α β // IsEntriesNode n } private theorem setSizeEq {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (i : Fin ks.size) (j : Fin vs.size) (k : α) (v : β) : (ks.set i k).size = (vs.set j v).size := by rw [Array.sizeSetEq, Array.sizeSetEq vs, h] rfl private theorem pushSizeEq {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (k : α) (v : β) : (ks.push k).size = (vs.push v).size := by rw [Array.sizePushEq, Array.sizePushEq, h] rfl partial def insertAtCollisionNodeAux [BEq α] : CollisionNode α β → Nat → α → β → CollisionNode α β | n@⟨Node.collision keys vals heq, _⟩, i, k, v => if h : i < keys.size then let idx : Fin keys.size := ⟨i, h⟩; let k' := keys.get idx; if k == k' then let j : Fin vals.size := ⟨i, by rw [←heq]; assumption⟩ ⟨Node.collision (keys.set idx k) (vals.set j v) (setSizeEq heq idx j k v), IsCollisionNode.mk _ _ _⟩ else insertAtCollisionNodeAux n (i+1) k v else ⟨Node.collision (keys.push k) (vals.push v) (pushSizeEq heq k v), IsCollisionNode.mk _ _ _⟩ | ⟨Node.entries _, h⟩, _, _, _ => False.elim (nomatch h) def insertAtCollisionNode [BEq α] : CollisionNode α β → α → β → CollisionNode α β := fun n k v => insertAtCollisionNodeAux n 0 k v def getCollisionNodeSize : CollisionNode α β → Nat | ⟨Node.collision keys _ _, _⟩ => keys.size | ⟨Node.entries _, h⟩ => False.elim (nomatch h) def mkCollisionNode (k₁ : α) (v₁ : β) (k₂ : α) (v₂ : β) : Node α β := let ks : Array α := Array.mkEmpty maxCollisions let ks := (ks.push k₁).push k₂ let vs : Array β := Array.mkEmpty maxCollisions let vs := (vs.push v₁).push v₂ Node.collision ks vs rfl partial def insertAux [BEq α] [Hashable α] : Node α β → USize → USize → α → β → Node α β | Node.collision keys vals heq, _, depth, k, v => let newNode := insertAtCollisionNode ⟨Node.collision keys vals heq, IsCollisionNode.mk _ _ _⟩ k v if depth >= maxDepth || getCollisionNodeSize newNode < maxCollisions then newNode.val else match newNode with | ⟨Node.entries _, h⟩ => False.elim (nomatch h) | ⟨Node.collision keys vals heq, _⟩ => let rec traverse (i : Nat) (entries : Node α β) : Node α β := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ let h := hash k let h := div2Shift h (shift * (depth - 1)) traverse (i+1) (insertAux entries h depth k v) else entries traverse 0 mkEmptyEntries | Node.entries entries, h, depth, k, v => let j := (mod2Shift h shift).toNat Node.entries $ entries.modify j fun entry => match entry with | Entry.null => Entry.entry k v | Entry.ref node => Entry.ref $ insertAux node (div2Shift h shift) (depth+1) k v | Entry.entry k' v' => if k == k' then Entry.entry k v else Entry.ref $ mkCollisionNode k' v' k v def insert [BEq α] [Hashable α] : PersistentHashMap α β → α → β → PersistentHashMap α β | { root := n, size := sz }, k, v => { root := insertAux n (hash k) 1 k v, size := sz + 1 } partial def findAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option β := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then some (vals.get ⟨i, by rw [←heq]; assumption⟩) else findAtAux keys vals heq (i+1) k else none partial def findAux [BEq α] : Node α β → USize → α → Option β | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some v else none | Node.collision keys vals heq, _, k => findAtAux keys vals heq 0 k def find? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option β | { root := n, .. }, k => findAux n (hash k) k @[inline] def getOp [BEq α] [Hashable α] (self : PersistentHashMap α β) (idx : α) : Option β := self.find? idx @[inline] def findD [BEq α] [Hashable α] (m : PersistentHashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [BEq α] [Hashable α] [Inhabited β] (m : PersistentHashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" partial def findEntryAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option (α × β) := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then some (k', vals.get ⟨i, by rw [←heq]; assumption⟩) else findEntryAtAux keys vals heq (i+1) k else none partial def findEntryAux [BEq α] : Node α β → USize → α → Option (α × β) | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => none | Entry.ref node => findEntryAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some (k', v) else none | Node.collision keys vals heq, _, k => findEntryAtAux keys vals heq 0 k def findEntry? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option (α × β) | { root := n, .. }, k => findEntryAux n (hash k) k partial def containsAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Bool := if h : i < keys.size then let k' := keys.get ⟨i, h⟩ if k == k' then true else containsAtAux keys vals heq (i+1) k else false partial def containsAux [BEq α] : Node α β → USize → α → Bool | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat match entries.get! j with | Entry.null => false | Entry.ref node => containsAux node (div2Shift h shift) k | Entry.entry k' v => k == k' | Node.collision keys vals heq, _, k => containsAtAux keys vals heq 0 k def contains [BEq α] [Hashable α] : PersistentHashMap α β → α → Bool | { root := n, .. }, k => containsAux n (hash k) k partial def isUnaryEntries (a : Array (Entry α β (Node α β))) (i : Nat) (acc : Option (α × β)) : Option (α × β) := if h : i < a.size then match a.get ⟨i, h⟩ with | Entry.null => isUnaryEntries a (i+1) acc | Entry.ref _ => none | Entry.entry k v => match acc with | none => isUnaryEntries a (i+1) (some (k, v)) | some _ => none else acc def isUnaryNode : Node α β → Option (α × β) | Node.entries entries => isUnaryEntries entries 0 none | Node.collision keys vals heq => if h : 1 = keys.size then have 0 < keys.size by rw [←h]; decide! some (keys.get ⟨0, this⟩, vals.get ⟨0, by rw [←heq]; assumption⟩) else none partial def eraseAux [BEq α] : Node α β → USize → α → Node α β × Bool | n@(Node.collision keys vals heq), _, k => match keys.indexOf? k with | some idx => let ⟨keys', keq⟩ := keys.eraseIdx' idx let ⟨vals', veq⟩ := vals.eraseIdx' (Eq.ndrec idx heq) have keys.size - 1 = vals.size - 1 by rw [heq]; rfl (Node.collision keys' vals' (keq.trans (this.trans veq.symm)), true) | none => (n, false) | n@(Node.entries entries), h, k => let j := (mod2Shift h shift).toNat let entry := entries.get! j match entry with | Entry.null => (n, false) | Entry.entry k' v => if k == k' then (Node.entries (entries.set! j Entry.null), true) else (n, false) | Entry.ref node => let entries := entries.set! j Entry.null let (newNode, deleted) := eraseAux node (div2Shift h shift) k if !deleted then (n, false) else match isUnaryNode newNode with | none => (Node.entries (entries.set! j (Entry.ref newNode)), true) | some (k, v) => (Node.entries (entries.set! j (Entry.entry k v)), true) def erase [BEq α] [Hashable α] : PersistentHashMap α β → α → PersistentHashMap α β | { root := n, size := sz }, k => let h := hash k let (n, del) := eraseAux n h k { root := n, size := if del then sz - 1 else sz } section variables {m : Type w → Type w'} [Monad m] variables {σ : Type w} @[specialize] partial def foldlMAux (f : σ → α → β → m σ) : Node α β → σ → m σ | Node.collision keys vals heq, acc => let rec traverse (i : Nat) (acc : σ) : m σ := do if h : i < keys.size then let k := keys.get ⟨i, h⟩ let v := vals.get ⟨i, heq ▸ h⟩ traverse (i+1) (← f acc k v) else pure acc traverse 0 acc | Node.entries entries, acc => entries.foldlM (fun acc entry => match entry with | Entry.null => pure acc | Entry.entry k v => f acc k v | Entry.ref node => foldlMAux f node acc) acc @[specialize] def foldlM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → m σ) (init : σ) : m σ := foldlMAux f map.root init @[specialize] def forM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : α → β → m PUnit) : m PUnit := map.foldlM (fun _ => f) ⟨⟩ @[specialize] def foldl [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → σ) (init : σ) : σ := Id.run $ map.foldlM f init end def toList [BEq α] [Hashable α] (m : PersistentHashMap α β) : List (α × β) := m.foldl (init := []) fun ps k v => (k, v) :: ps structure Stats := (numNodes : Nat := 0) (numNull : Nat := 0) (numCollisions : Nat := 0) (maxDepth : Nat := 0) partial def collectStats : Node α β → Stats → Nat → Stats | Node.collision keys _ _, stats, depth => { stats with numNodes := stats.numNodes + 1, numCollisions := stats.numCollisions + keys.size - 1, maxDepth := Nat.max stats.maxDepth depth } | Node.entries entries, stats, depth => let stats := { stats with numNodes := stats.numNodes + 1, maxDepth := Nat.max stats.maxDepth depth } entries.foldl (fun stats entry => match entry with | Entry.null => { stats with numNull := stats.numNull + 1 } | Entry.ref node => collectStats node stats (depth + 1) | Entry.entry _ _ => stats) stats def stats [BEq α] [Hashable α] (m : PersistentHashMap α β) : Stats := collectStats m.root {} 1 def Stats.toString (s : Stats) : String := s!"\{ nodes := {s.numNodes}, null := {s.numNull}, collisions := {s.numCollisions}, depth := {s.maxDepth}}" instance : ToString Stats := ⟨Stats.toString⟩ end PersistentHashMap end Std
95a385a70d16f5396100c35e42d5f05e9f8a89ae
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/sigma/lex_auto.lean
50ca1760b44ec9e9059373daa5e2491fe6093cda
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,352
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.sigma.basic import Mathlib.Lean3Lib.init.meta.default universes u v namespace Mathlib namespace psigma inductive lex {α : Sort u} {β : α → Sort v} (r : α → α → Prop) (s : (a : α) → β a → β a → Prop) : psigma β → psigma β → Prop where | left : ∀ {a₁ : α} (b₁ : β a₁) {a₂ : α} (b₂ : β a₂), r a₁ a₂ → lex r s (mk a₁ b₁) (mk a₂ b₂) | right : ∀ (a : α) {b₁ b₂ : β a}, s a b₁ b₂ → lex r s (mk a b₁) (mk a b₂) def lex_accessible {α : Sort u} {β : α → Sort v} {r : α → α → Prop} {s : (a : α) → β a → β a → Prop} {a : α} (aca : acc r a) (acb : ∀ (a : α), well_founded (s a)) (b : β a) : acc (lex r s) (mk a b) := sorry def lex_wf {α : Sort u} {β : α → Sort v} {r : α → α → Prop} {s : (a : α) → β a → β a → Prop} (ha : well_founded r) (hb : ∀ (x : α), well_founded (s x)) : well_founded (lex r s) := well_founded.intro fun (_x : psigma fun (a : α) => β a) => sorry def lex_ndep {α : Sort u} {β : Sort v} (r : α → α → Prop) (s : β → β → Prop) : (psigma fun (a : α) => β) → (psigma fun (a : α) => β) → Prop := lex r fun (a : α) => s def lex_ndep_wf {α : Sort u} {β : Sort v} {r : α → α → Prop} {s : β → β → Prop} (ha : well_founded r) (hb : well_founded s) : well_founded (lex_ndep r s) := well_founded.intro fun (_x : psigma fun (a : α) => β) => sorry inductive rev_lex {α : Sort u} {β : Sort v} (r : α → α → Prop) (s : β → β → Prop) : (psigma fun (a : α) => β) → (psigma fun (a : α) => β) → Prop where | left : ∀ {a₁ a₂ : α} (b : β), r a₁ a₂ → rev_lex r s (mk a₁ b) (mk a₂ b) | right : ∀ (a₁ : α) {b₁ : β} (a₂ : α) {b₂ : β}, s b₁ b₂ → rev_lex r s (mk a₁ b₁) (mk a₂ b₂) def rev_lex_accessible {α : Sort u} {β : Sort v} {r : α → α → Prop} {s : β → β → Prop} {b : β} (acb : acc s b) (aca : ∀ (a : α), acc r a) (a : α) : acc (rev_lex r s) (mk a b) := sorry def rev_lex_wf {α : Sort u} {β : Sort v} {r : α → α → Prop} {s : β → β → Prop} (ha : well_founded r) (hb : well_founded s) : well_founded (rev_lex r s) := well_founded.intro fun (_x : psigma fun (a : α) => β) => sorry def skip_left (α : Type u) {β : Type v} (s : β → β → Prop) : (psigma fun (a : α) => β) → (psigma fun (a : α) => β) → Prop := rev_lex empty_relation s def skip_left_wf (α : Type u) {β : Type v} {s : β → β → Prop} (hb : well_founded s) : well_founded (skip_left α s) := rev_lex_wf empty_wf hb def mk_skip_left {α : Type u} {β : Type v} {b₁ : β} {b₂ : β} {s : β → β → Prop} (a₁ : α) (a₂ : α) (h : s b₁ b₂) : skip_left α s (mk a₁ b₁) (mk a₂ b₂) := rev_lex.right a₁ a₂ h protected instance has_well_founded {α : Type u} {β : α → Type v} [s₁ : has_well_founded α] [s₂ : (a : α) → has_well_founded (β a)] : has_well_founded (psigma β) := has_well_founded.mk (lex has_well_founded.r fun (a : α) => has_well_founded.r) sorry end Mathlib
ff61d4a63424d4cc96596718150c3ec879e8664b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/general_commutator.lean
40b8af50f46d00906ec827d0671102073687b132
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,393
lean
/- Copyright (c) 2021 Jordan Brown, Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jordan Brown, Thomas Browning, Patrick Lutz -/ import data.bracket import group_theory.subgroup.basic import tactic.group /-! # General commutators. If `G` is a group and `H₁ H₂ : subgroup G` then the general commutator `⁅H₁, H₂⁆ : subgroup G` is the subgroup of `G` generated by the commutators `h₁ * h₂ * h₁⁻¹ * h₂⁻¹`. ## Main definitions * `general_commutator H₁ H₂` : the commutator of the subgroups `H₁` and `H₂` -/ open subgroup variables {G G' : Type*} [group G] [group G'] {f : G →* G'} /-- The commutator of two subgroups `H₁` and `H₂`. -/ instance general_commutator : has_bracket (subgroup G) (subgroup G) := ⟨λ H₁ H₂, closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x}⟩ lemma general_commutator_def (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x} := rfl instance general_commutator_normal (H₁ H₂ : subgroup G) [h₁ : H₁.normal] [h₂ : H₂.normal] : normal ⁅H₁, H₂⁆ := begin let base : set G := {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x}, suffices h_base : base = group.conjugates_of_set base, { dsimp only [general_commutator_def, ←base], rw h_base, exact subgroup.normal_closure_normal }, apply set.subset.antisymm group.subset_conjugates_of_set, intros a h, simp_rw [group.mem_conjugates_of_set_iff, is_conj_iff] at h, rcases h with ⟨b, ⟨c, hc, e, he, rfl⟩, d, rfl⟩, exact ⟨d * c * d⁻¹, h₁.conj_mem c hc d, d * e * d⁻¹, h₂.conj_mem e he d, by group⟩, end lemma general_commutator_mono {H₁ H₂ K₁ K₂ : subgroup G} (h₁ : H₁ ≤ K₁) (h₂ : H₂ ≤ K₂) : ⁅H₁, H₂⁆ ≤ ⁅K₁, K₂⁆ := begin apply closure_mono, rintros x ⟨p, hp, q, hq, rfl⟩, exact ⟨p, h₁ hp, q, h₂ hq, rfl⟩, end lemma general_commutator_def' (H₁ H₂ : subgroup G) [H₁.normal] [H₂.normal] : ⁅H₁, H₂⁆ = normal_closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x} := by rw [← normal_closure_eq_self ⁅H₁, H₂⁆, general_commutator_def, normal_closure_closure_eq_normal_closure] lemma general_commutator_le (H₁ H₂ : subgroup G) (K : subgroup G) : ⁅H₁, H₂⁆ ≤ K ↔ ∀ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ ∈ K := begin rw [general_commutator, closure_le], split, { intros h p hp q hq, exact h ⟨p, hp, q, hq, rfl⟩, }, { rintros h x ⟨p, hp, q, hq, rfl⟩, exact h p hp q hq, } end lemma general_commutator_containment (H₁ H₂ : subgroup G) {p q : G} (hp : p ∈ H₁) (hq : q ∈ H₂) : p * q * p⁻¹ * q⁻¹ ∈ ⁅H₁, H₂⁆ := (general_commutator_le H₁ H₂ ⁅H₁, H₂⁆).mp (le_refl ⁅H₁, H₂⁆) p hp q hq lemma general_commutator_comm (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = ⁅H₂, H₁⁆ := begin suffices : ∀ H₁ H₂ : subgroup G, ⁅H₁, H₂⁆ ≤ ⁅H₂, H₁⁆, { exact le_antisymm (this _ _) (this _ _) }, intros H₁ H₂, rw general_commutator_le, intros p hp q hq, have h : (p * q * p⁻¹ * q⁻¹)⁻¹ ∈ ⁅H₂, H₁⁆ := subset_closure ⟨q, hq, p, hp, by group⟩, convert inv_mem ⁅H₂, H₁⁆ h, group, end lemma general_commutator_le_right (H₁ H₂ : subgroup G) [h : normal H₂] : ⁅H₁, H₂⁆ ≤ H₂ := begin rw general_commutator_le, intros p hp q hq, exact mul_mem H₂ (h.conj_mem q hq p) (inv_mem H₂ hq), end lemma general_commutator_le_left (H₁ H₂ : subgroup G) [h : normal H₁] : ⁅H₁, H₂⁆ ≤ H₁ := begin rw general_commutator_comm, exact general_commutator_le_right H₂ H₁, end @[simp] lemma general_commutator_bot (H : subgroup G) : ⁅H, ⊥⁆ = (⊥ : subgroup G) := by { rw eq_bot_iff, exact general_commutator_le_right H ⊥ } @[simp] lemma bot_general_commutator (H : subgroup G) : ⁅(⊥ : subgroup G), H⁆ = (⊥ : subgroup G) := by { rw eq_bot_iff, exact general_commutator_le_left ⊥ H } lemma general_commutator_le_inf (H₁ H₂ : subgroup G) [normal H₁] [normal H₂] : ⁅H₁, H₂⁆ ≤ H₁ ⊓ H₂ := by simp only [general_commutator_le_left, general_commutator_le_right, le_inf_iff, and_self]
06a543ebf1b8d1f2916e73addffedb56bcb46902
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/list/perm.lean
0d13540ac5fb45225b9319808660e4f8802245e4
[ "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
41,626
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura List permutations. -/ import data.list.basic data.list.set open list setoid nat binary variables {A B : Type} inductive perm : list A → list A → Prop := | nil : perm [] [] | skip : Π (x : A) {l₁ l₂ : list A}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : A) (l : list A), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list A}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ namespace perm infix ~ := perm theorem eq_nil_of_perm_nil {l₁ : list A} (p : [] ~ l₁) : l₁ = [] := sorry /- have gen : ∀ (l₂ : list A) (p : l₂ ~ l₁), l₂ = [] → l₁ = [], from take l₂ p, perm.induction_on p (λ h, h) (by contradiction) (by contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e, r₂ (r₁ e)), gen [] p rfl -/ theorem not_perm_nil_cons (x : A) (l : list A) : ¬ [] ~ (x::l) := sorry /- have gen : ∀ (l₁ l₂ : list A) (p : l₁ ~ l₂), l₁ = [] → l₂ = (x::l) → false, from take l₁ l₂ p, perm.induction_on p (by contradiction) (by contradiction) (by contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e₁ e₂, begin rewrite [e₂ at *, e₁ at *], have e₃ : l₂ = [], from eq_nil_of_perm_nil p₁, exact (r₂ e₃ rfl) end), assume p, gen [] (x::l) p rfl rfl -/ attribute [refl] protected theorem refl : ∀ (l : list A), l ~ l | [] := nil | (x::xs) := skip x (refl xs) attribute [symm] protected theorem symm : ∀ {l₁ l₂ : list A}, l₁ ~ l₂ → l₂ ~ l₁ := take l₁ l₂ p, perm.induction_on p nil (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁) attribute perm.trans [trans] theorem eqv (A : Type) : equivalence (@perm A) := mk_equivalence (@perm A) (@perm.refl A) (@perm.symm A) (@perm.trans A) attribute [instance] protected definition is_setoid (A : Type) : setoid (list A) := setoid.mk (@perm A) (perm.eqv A) theorem mem_perm {a : A} {l₁ l₂ : list A} : l₁ ~ l₂ → a ∈ l₁ → a ∈ l₂ := sorry /- assume p, perm.induction_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim (eq_or_mem_of_mem_cons i) (suppose a = x, by rewrite this; apply !mem_cons) (suppose a ∈ l₁, or.inr (r₁ this))) (λ x y l ainyxl, or.elim (eq_or_mem_of_mem_cons ainyxl) (suppose a = y, by rewrite this; exact (or.inr !mem_cons)) (suppose a ∈ x::l, or.elim (eq_or_mem_of_mem_cons this) (suppose a = x, or.inl this) (suppose a ∈ l, or.inr (or.inr this)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) -/ theorem not_mem_perm {a : A} {l₁ l₂ : list A} : l₁ ~ l₂ → a ∉ l₁ → a ∉ l₂ := assume p nainl₁ ainl₂, absurd (mem_perm (perm.symm p) ainl₂) nainl₁ theorem perm_app_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (l₁++t₁) ~ (l₂++t₁) := assume p, perm.induction_on p (perm.refl (list.nil ++ t₁)) (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_app_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (l++t₁) ~ (l++t₂) := list.induction_on l (λ p, p) (λ x xs r p, skip x (r p)) theorem perm_app {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁++t₁) ~ (l₂++t₂) := assume p₁ p₂, trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂) theorem perm_app_cons (a : A) {h₁ h₂ t₁ t₂ : list A} : h₁ ~ h₂ → t₁ ~ t₂ → (h₁ ++ (a::t₁)) ~ (h₂ ++ (a::t₂)) := assume p₁ p₂, perm_app p₁ (skip a p₂) theorem perm_cons_app (a : A) : ∀ (l : list A), (a::l) ~ (l ++ [a]) | [] := perm.refl _ | (x::xs) := calc a::x::xs ~ x::a::xs : swap x a xs ... ~ x::(xs++[a]) : skip x (perm_cons_app xs) attribute [simp] theorem perm_cons_app_simp (a : A) : ∀ (l : list A), (l ++ [a]) ~ (a::l) := take l, perm.symm (perm_cons_app a l) attribute [simp] theorem perm_app_comm {l₁ l₂ : list A} : (l₁++l₂) ~ (l₂++l₁) := sorry /- list.induction_on l₁ (by rewrite [append_nil_right, append_nil_left]) (λ a t r, calc a::(t++l₂) ~ a::(l₂++t) : skip a r ... ~ l₂++t++[a] : !perm_cons_app ... = l₂++(t++[a]) : !append.assoc ... ~ l₂++(a::t) : perm_app_right l₂ (perm.symm (perm_cons_app a t))) -/ theorem length_eq_length_of_perm {l₁ l₂ : list A} : l₁ ~ l₂ → length l₁ = length l₂ := sorry /- assume p, perm.induction_on p rfl (λ x l₁ l₂ p r, by rewrite [*length_cons, r]) (λ x y l, by rewrite *length_cons) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) -/ theorem eq_singleton_of_perm_inv (a : A) {l : list A} : [a] ~ l → l = [a] := sorry /- have gen : ∀ l₂, perm l₂ l → l₂ = [a] → l = [a], from take l₂, assume p, perm.induction_on p (λ e, e) (λ x l₁ l₂ p r e, begin injection e with e₁ e₂, rewrite [e₁, e₂ at p], have h₁ : l₂ = [], from eq_nil_of_perm_nil p, substvars end) (λ x y l e, by injection e; contradiction) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ e, r₂ (r₁ e)), assume p, gen [a] p rfl -/ theorem eq_singleton_of_perm (a b : A) : [a] ~ [b] → a = b := sorry /- assume p, begin injection eq_singleton_of_perm_inv a p with e₁, rewrite e₁ end -/ theorem perm_rev : ∀ (l : list A), l ~ (reverse l) := sorry /- | [] := nil | (x::xs) := calc x::xs ~ xs++[x] : perm_cons_app x xs ... ~ reverse xs ++ [x] : perm_app_left [x] (perm_rev xs) ... = reverse (x::xs) : by rewrite [reverse_cons, concat_eq_append] -/ attribute [simp] theorem perm_rev_simp : ∀ (l : list A), (reverse l) ~ l := take l, perm.symm (perm_rev l) theorem perm_middle (a : A) (l₁ l₂ : list A) : (a::l₁)++l₂ ~ l₁++(a::l₂) := calc (a::l₁) ++ l₂ = a::(l₁++l₂) : rfl ... ~ l₁++l₂++[a] : perm_cons_app a (l₁ ++ l₂) ... = l₁++(l₂++[a]) : append.assoc l₁ l₂ [a] ... ~ l₁++(a::l₂) : perm_app_right l₁ (perm.symm (perm_cons_app a l₂)) attribute [simp] theorem perm_middle_simp (a : A) (l₁ l₂ : list A) : l₁++(a::l₂) ~ (a::l₁)++l₂ := perm.symm $ perm_middle a l₁ l₂ theorem perm_cons_app_cons {l l₁ l₂ : list A} (a : A) : l ~ l₁++l₂ → a::l ~ l₁++(a::l₂) := assume p, calc a::l ~ l++[a] : perm_cons_app a l ... ~ l₁++l₂++[a] : perm_app_left [a] p ... = l₁++(l₂++[a]) : append.assoc l₁ l₂ [a] ... ~ l₁++(a::l₂) : perm_app_right l₁ (perm.symm (perm_cons_app a l₂)) open decidable theorem perm_erase [decidable_eq A] {a : A} : ∀ {l : list A}, a ∈ l → l ~ a::(erase a l) := sorry /- | [] h := absurd h !not_mem_nil | (x::t) h := by_cases (assume aeqx : a = x, by rewrite [aeqx, erase_cons_head]) (assume naeqx : a ≠ x, have aint : a ∈ t, from mem_of_ne_of_mem naeqx h, have aux : t ~ a :: erase a t, from perm_erase aint, calc x::t ~ x::a::(erase a t) : skip x aux ... ~ a::x::(erase a t) : !swap ... = a::(erase a (x::t)) : by rewrite [!erase_cons_tail naeqx]) -/ attribute [congr] theorem erase_perm_erase_of_perm [decidable_eq A] (a : A) {l₁ l₂ : list A} : l₁ ~ l₂ → erase a l₁ ~ erase a l₂ := sorry /- assume p, perm.induction_on p nil (λ x t₁ t₂ p r, by_cases (assume aeqx : a = x, by rewrite [aeqx, *erase_cons_head]; exact p) (assume naeqx : a ≠ x, by rewrite [*erase_cons_tail _ naeqx]; exact (skip x r))) (λ x y l, by_cases (assume aeqx : a = x, by_cases (assume aeqy : a = y, by rewrite [-aeqx, -aeqy]) (assume naeqy : a ≠ y, by rewrite [-aeqx, erase_cons_tail _ naeqy, *erase_cons_head])) (assume naeqx : a ≠ x, by_cases (assume aeqy : a = y, by rewrite [-aeqy, erase_cons_tail _ naeqx, *erase_cons_head]) (assume naeqy : a ≠ y, by rewrite[erase_cons_tail _ naeqx, *erase_cons_tail _ naeqy, erase_cons_tail _ naeqx]; exact !swap))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) -/ theorem perm_induction_on {P : list A → list A → Prop} {l₁ l₂ : list A} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l | [] := h₁ | (x::xs) := h₂ x xs xs (perm.refl xs) (P_refl xs), perm.induction_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ theorem xswap {l₁ l₂ : list A} (x y : A) : l₁ ~ l₂ → x::y::l₁ ~ y::x::l₂ := assume p, calc x::y::l₁ ~ y::x::l₁ : swap y x l₁ ... ~ y::x::l₂ : skip y (skip x p) attribute [congr] theorem perm_map (f : A → B) {l₁ l₂ : list A} : l₁ ~ l₂ → map f l₁ ~ map f l₂ := assume p, perm_induction_on p nil (λ x l₁ l₂ p r, skip (f x) r) (λ x y l₁ l₂ p r, xswap (f y) (f x) r) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) lemma perm_of_qeq {a : A} {l₁ l₂ : list A} : l₁≈a|l₂ → l₁~a::l₂ := assume q, qeq.induction_on q (λ h, perm.refl (a :: h)) (λ b t₁ t₂ q₁ r₁, calc b::t₂ ~ b::a::t₁ : skip b r₁ ... ~ a::b::t₁ : swap a b t₁) /- permutation is decidable if A has decidable equality -/ section dec open decidable variable [Ha : decidable_eq A] include Ha definition decidable_perm_aux : ∀ (n : nat) (l₁ l₂ : list A), length l₁ = n → length l₂ = n → decidable (l₁ ~ l₂) := sorry /- | 0 l₁ l₂ H₁ H₂ := have l₁n : l₁ = [], from eq_nil_of_length_eq_zero H₁, have l₂n : l₂ = [], from eq_nil_of_length_eq_zero H₂, by rewrite [l₁n, l₂n]; exact (inl perm.nil) | (n+1) (x::t₁) l₂ H₁ H₂ := by_cases (assume xinl₂ : x ∈ l₂, let t₂ : list A := erase x l₂ in have len_t₁ : length t₁ = n, begin injection H₁ with e, exact e end, have length t₂ = pred (length l₂), from length_erase_of_mem xinl₂, have length t₂ = n, by rewrite [this, H₂], match decidable_perm_aux n t₁ t₂ len_t₁ this with | inl p := inl (calc x::t₁ ~ x::(erase x l₂) : skip x p ... ~ l₂ : perm.symm (perm_erase xinl₂)) | inr np := inr (λ p : x::t₁ ~ l₂, have erase x (x::t₁) ~ erase x l₂, from erase_perm_erase_of_perm x p, have t₁ ~ erase x l₂, by rewrite [erase_cons_head at this]; exact this, absurd this np) end) (assume nxinl₂ : x ∉ l₂, inr (λ p : x::t₁ ~ l₂, absurd (mem_perm p !mem_cons) nxinl₂)) -/ attribute [instance] definition decidable_perm : ∀ (l₁ l₂ : list A), decidable (l₁ ~ l₂) := λ l₁ l₂, by_cases (assume eql : length l₁ = length l₂, decidable_perm_aux (length l₂) l₁ l₂ eql rfl) (assume neql : length l₁ ≠ length l₂, ff (λ p : l₁ ~ l₂, absurd (length_eq_length_of_perm p) neql)) end dec -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr {P : Prop} {a b : A} {l₁ l₂ l₃ : list A} : a::l₁ = l₂++(b::l₃) → (l₂ = [] → a = b → l₁ = l₃ → P) → (∀ t, l₂ = a::t → l₁ = t++(b::l₃) → P) → P := sorry /- match l₂ with | [] := λ e h₁ h₂, by injection e with e₁ e₂; exact h₁ rfl e₁ e₂ | h::t := λ e h₁ h₂, begin injection e with e₁ e₂, rewrite e₁ at h₂, exact h₂ t rfl e₂ end end -/ -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr₂ {P : Prop} {a b c : A} {l₁ l₂ l₃ : list A} : a::b::l₁ = l₂++(c::l₃) → (l₂ = [] → l₃ = b::l₁ → a = c → P) → (l₂ = [a] → b = c → l₁ = l₃ → P) → (∀ t, l₂ = a::b::t → l₁ = t++(c::l₃) → P) → P := sorry /- match l₂ with | [] := λ e H₁ H₂ H₃, begin injection e with a_eq_c b_l₁_eq_l₃, exact H₁ rfl (eq.symm b_l₁_eq_l₃) a_eq_c end | [h₁] := λ e H₁ H₂ H₃, begin rewrite [append_cons at e, append_nil_left at e], injection e with a_eq_h₁ b_eq_c l₁_eq_l₃, rewrite [a_eq_h₁ at H₂, b_eq_c at H₂, l₁_eq_l₃ at H₂], exact H₂ rfl rfl rfl end | h₁::h₂::t₂ := λ e H₁ H₂ H₃, begin injection e with a_eq_h₁ b_eq_h₂ l₁_eq, rewrite [a_eq_h₁ at H₃, b_eq_h₂ at H₃], exact H₃ t₂ rfl l₁_eq end end -/ /- permutation inversion -/ theorem perm_inv_core {l₁ l₂ : list A} (p' : l₁ ~ l₂) : ∀ {a s₁ s₂}, l₁≈a|s₁ → l₂≈a|s₂ → s₁ ~ s₂ := sorry /- perm_induction_on p' (λ a s₁ s₂ e₁ e₂, have innil : a ∈ [], from mem_head_of_qeq e₁, absurd innil !not_mem_nil) (λ x t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, obtain (s₁₁ s₁₂ : list A) (C₁₁ : s₁ = s₁₁ ++ s₁₂) (C₁₂ : x::t₁ = s₁₁++(a::s₁₂)), from qeq_split e₁, obtain (s₂₁ s₂₂ : list A) (C₂₁ : s₂ = s₂₁ ++ s₂₂) (C₂₂ : x::t₂ = s₂₁++(a::s₂₂)), from qeq_split e₂, discr C₁₂ (λ (s₁₁_eq : s₁₁ = []) (x_eq_a : x = a) (t₁_eq : t₁ = s₁₂), have s₁_p : s₁ ~ t₂, from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = t₁ : by rewrite [-t₁_eq, s₁₁_eq, append_nil_left] ... ~ t₂ : p, discr C₂₂ (λ (s₂₁_eq : s₂₁ = []) (x_eq_a : x = a) (t₂_eq: t₂ = s₂₂), proof calc s₁ ~ t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [-t₂_eq, s₂₁_eq, append_nil_left] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ t₂ : s₁_p ... = ts₂₁++(a::s₂₂) : t₂_eq ... ~ (a::ts₂₁)++s₂₂ : perm.symm !perm_middle ... = s₂₁ ++ s₂₂ : by rewrite [-x_eq_a, -s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed)) (λ (ts₁₁ : list A) (s₁₁_eq : s₁₁ = x::ts₁₁) (t₁_eq : t₁ = ts₁₁++(a::s₁₂)), have t₁_qeq : t₁ ≈ a|(ts₁₁++s₁₂), by rewrite t₁_eq; exact !qeq_app, have s₁_eq : s₁ = x::(ts₁₁++s₁₂), from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = x::(ts₁₁++ s₁₂) : by rewrite s₁₁_eq, discr C₂₂ (λ (s₂₁_eq : s₂₁ = []) (x_eq_a : x = a) (t₂_eq: t₂ = s₂₂), proof calc s₁ = a::(ts₁₁++s₁₂) : by rewrite [s₁_eq, x_eq_a] ... ~ ts₁₁++(a::s₁₂) : !perm_middle ... = t₁ : eq.symm t₁_eq ... ~ t₂ : p ... = s₂ : by rewrite [t₂_eq, C₂₁, s₂₁_eq, append_nil_left] qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), have t₂_qeq : t₂ ≈ a|(ts₂₁++s₂₂), by rewrite t₂_eq; exact !qeq_app, proof calc s₁ = x::(ts₁₁++s₁₂) : s₁_eq ... ~ x::(ts₂₁++s₂₂) : skip x (r t₁_qeq t₂_qeq) ... = s₂ : by rewrite [-append_cons, -s₂₁_eq, C₂₁] qed))) (λ x y t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, obtain (s₁₁ s₁₂ : list A) (C₁₁ : s₁ = s₁₁ ++ s₁₂) (C₁₂ : y::x::t₁ = s₁₁++(a::s₁₂)), from qeq_split e₁, obtain (s₂₁ s₂₂ : list A) (C₂₁ : s₂ = s₂₁ ++ s₂₂) (C₂₂ : x::y::t₂ = s₂₁++(a::s₂₂)), from qeq_split e₂, discr₂ C₁₂ (λ (s₁₁_eq : s₁₁ = []) (s₁₂_eq : s₁₂ = x::t₁) (y_eq_a : y = a), have s₁_p : s₁ ~ x::t₂, from calc s₁ = s₁₁ ++ s₁₂ : C₁₁ ... = x::t₁ : by rewrite [s₁₂_eq, s₁₁_eq, append_nil_left] ... ~ x::t₂ : skip x p, discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ ~ x::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [x_eq_a, -y_eq_a, -s₂₂_eq, s₂₁_eq, append_nil_left] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ ~ x::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [t₂_eq, s₂₁_eq, append_cons] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ x::t₂ : s₁_p ... = x::(ts₂₁++(y::s₂₂)) : by rewrite [t₂_eq, -y_eq_a] ... ~ x::y::(ts₂₁++s₂₂) : perm.symm (skip x (perm_middle _ _ _)) -- !perm_middle ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, append_cons] ... = s₂ : by rewrite C₂₁ qed)) (λ (s₁₁_eq : s₁₁ = [y]) (x_eq_a : x = a) (t₁_eq : t₁ = s₁₂), have s₁_p : s₁ ~ y::t₂, from calc s₁ = y::t₁ : by rewrite [C₁₁, s₁₁_eq, t₁_eq] ... ~ y::t₂ : skip y p, discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ ~ y::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, s₂₂_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ ~ y::t₂ : s₁_p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, t₂_eq, y_eq_a, -x_eq_a] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), proof calc s₁ ~ y::t₂ : s₁_p ... = y::(ts₂₁++(x::s₂₂)) : by rewrite [t₂_eq, -x_eq_a] ... ~ y::x::(ts₂₁++s₂₂) : perm.symm (skip y (perm_middle _ _ _)) ... ~ x::y::(ts₂₁++s₂₂) : !swap ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed)) (λ (ts₁₁ : list A) (s₁₁_eq : s₁₁ = y::x::ts₁₁) (t₁_eq : t₁ = ts₁₁++(a::s₁₂)), have s₁_eq : s₁ = y::x::(ts₁₁++s₁₂), by rewrite [C₁₁, s₁₁_eq], discr₂ C₂₂ (λ (s₂₁_eq : s₂₁ = []) (s₂₂_eq : s₂₂ = y::t₂) (x_eq_a : x = a), proof calc s₁ = y::a::(ts₁₁++s₁₂) : by rewrite [s₁_eq, x_eq_a] ... ~ y::(ts₁₁++(a::s₁₂)) : skip y !perm_middle ... = y::t₁ : by rewrite t₁_eq ... ~ y::t₂ : skip y p ... = s₂₁ ++ s₂₂ : by rewrite [s₂₁_eq, s₂₂_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (s₂₁_eq : s₂₁ = [x]) (y_eq_a : y = a) (t₂_eq : t₂ = s₂₂), proof calc s₁ = y::x::(ts₁₁++s₁₂) : by rewrite s₁_eq ... ~ x::y::(ts₁₁++s₁₂) : !swap ... = x::a::(ts₁₁++s₁₂) : by rewrite y_eq_a ... ~ x::(ts₁₁++(a::s₁₂)) : skip x (perm_middle _ _ _) ... = x::t₁ : by rewrite t₁_eq ... ~ x::t₂ : skip x p ... = s₂₁ ++ s₂₂ : by rewrite [t₂_eq, s₂₁_eq] ... = s₂ : by rewrite C₂₁ qed) (λ (ts₂₁ : list A) (s₂₁_eq : s₂₁ = x::y::ts₂₁) (t₂_eq : t₂ = ts₂₁++(a::s₂₂)), have t₁_qeq : t₁ ≈ a|(ts₁₁++s₁₂), by rewrite t₁_eq; exact !qeq_app, have t₂_qeq : t₂ ≈ a|(ts₂₁++s₂₂), by rewrite t₂_eq; exact !qeq_app, have p_aux : ts₁₁++s₁₂ ~ ts₂₁++s₂₂, from r t₁_qeq t₂_qeq, proof calc s₁ = y::x::(ts₁₁++s₁₂) : by rewrite s₁_eq ... ~ y::x::(ts₂₁++s₂₂) : skip y (skip x p_aux) ... ~ x::y::(ts₂₁++s₂₂) : !swap ... = s₂₁ ++ s₂₂ : by rewrite s₂₁_eq ... = s₂ : by rewrite C₂₁ qed))) (λ t₁ t₂ t₃ p₁ p₂ (r₁ : ∀{a s₁ s₂}, t₁ ≈ a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) (r₂ : ∀{a s₁ s₂}, t₂ ≈ a|s₁ → t₃≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, have a ∈ t₁, from mem_head_of_qeq e₁, have a ∈ t₂, from mem_perm p₁ this, obtain (t₂' : list A) (e₂' : t₂≈a|t₂'), from qeq_of_mem this, calc s₁ ~ t₂' : r₁ e₁ e₂' ... ~ s₂ : r₂ e₂' e₂) -/ theorem perm_cons_inv {a : A} {l₁ l₂ : list A} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := assume p, perm_inv_core p (qeq.qhead a l₁) (qeq.qhead a l₂) theorem perm_app_inv {a : A} {l₁ l₂ l₃ l₄ : list A} : l₁++(a::l₂) ~ l₃++(a::l₄) → l₁++l₂ ~ l₃++l₄ := assume p : l₁++(a::l₂) ~ l₃++(a::l₄), have p' : a::(l₁++l₂) ~ a::(l₃++l₄), from calc a::(l₁++l₂) ~ l₁++(a::l₂) : perm_middle a l₁ l₂ ... ~ l₃++(a::l₄) : p ... ~ a::(l₃++l₄) : perm.symm (perm_middle a l₃ l₄), perm_cons_inv p' section foldl variables {f : B → A → B} {l₁ l₂ : list A} variable rcomm : right_commutative f include rcomm theorem foldl_eq_of_perm : l₁ ~ l₂ → ∀ b, foldl f b l₁ = foldl f b l₂ := sorry /- assume p, perm_induction_on p (λ b, by rewrite *foldl_nil) (λ x t₁ t₂ p r b, calc foldl f b (x::t₁) = foldl f (f b x) t₁ : !foldl_cons ... = foldl f (f b x) t₂ : by rewrite (r (f b x)) ... = foldl f b (x::t₂) : eq.symm !foldl_cons) (λ x y t₁ t₂ p r b, calc foldl f b (y :: x :: t₁) = foldl f (f (f b y) x) t₁ : by rewrite foldl_cons ... = foldl f (f (f b x) y) t₁ : by rewrite rcomm ... = foldl f (f (f b x) y) t₂ : r (f (f b x) y) ... = foldl f b (x :: y :: t₂) : by rewrite foldl_cons) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b)) -/ end foldl section foldr variables {f : A → B → B} {l₁ l₂ : list A} variable lcomm : left_commutative f include lcomm theorem foldr_eq_of_perm : l₁ ~ l₂ → ∀ b, foldr f b l₁ = foldr f b l₂ := sorry /- assume p, perm_induction_on p (λ b, by rewrite *foldl_nil) (λ x t₁ t₂ p r b, calc foldr f b (x::t₁) = f x (foldr f b t₁) : !foldr_cons ... = f x (foldr f b t₂) : by rewrite [r b] ... = foldr f b (x::t₂) : eq.symm !foldr_cons) (λ x y t₁ t₂ p r b, calc foldr f b (y :: x :: t₁) = f y (f x (foldr f b t₁)) : by rewrite foldr_cons ... = f x (f y (foldr f b t₁)) : by rewrite lcomm ... = f x (f y (foldr f b t₂)) : by rewrite [r b] ... = foldr f b (x :: y :: t₂) : by rewrite foldr_cons) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) -/ end foldr attribute [congr] theorem perm_erase_dup_of_perm [H : decidable_eq A] {l₁ l₂ : list A} : l₁ ~ l₂ → erase_dup l₁ ~ erase_dup l₂ := sorry /- assume p, perm_induction_on p nil (λ x t₁ t₂ p r, by_cases (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup xint₁)), by rewrite [erase_dup_cons_of_mem xint₁, erase_dup_cons_of_mem xint₂]; exact r) (λ nxint₁ : x ∉ t₁, have nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, by rewrite [erase_dup_cons_of_not_mem nxint₂, erase_dup_cons_of_not_mem nxint₁]; exact (skip x r))) (λ y x t₁ t₂ p r, by_cases (λ xinyt₁ : x ∈ y::t₁, by_cases (λ yint₁ : y ∈ t₁, have yint₂ : y ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup yint₁)), have yinxt₂ : y ∈ x::t₂, from or.inr (yint₂), or.elim (eq_or_mem_of_mem_cons xinyt₁) (λ xeqy : x = y, have xint₂ : x ∈ t₂, by rewrite [-xeqy at yint₂]; exact yint₂, begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end) (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup xint₁)), begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end)) (λ nyint₁ : y ∉ t₁, have nyint₂ : y ∉ t₂, from assume yint₂ : y ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup yint₂))) nyint₁, by_cases (λ xeqy : x = y, have nxint₂ : x ∉ t₂, by rewrite [-xeqy at nyint₂]; exact nyint₂, have yinxt₂ : y ∈ x::t₂, by rewrite [xeqy]; exact !mem_cons, begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂, xeqy], exact skip y r end) (λ xney : x ≠ y, have x ∈ t₁, from or_resolve_right xinyt₁ xney, have x ∈ t₂, from mem_of_mem_erase_dup (mem_perm r (mem_erase_dup this)), have y ∉ x::t₂, from suppose y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons this) (λ h, absurd h (ne.symm xney)) (λ h, absurd h nyint₂), begin rewrite [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_not_mem `y ∉ x::t₂`, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_mem `x ∈ t₂`], exact skip y r end))) (λ nxinyt₁ : x ∉ y::t₁, have xney : x ≠ y, from ne_of_not_mem_cons nxinyt₁, have nxint₁ : x ∉ t₁, from not_mem_of_not_mem_cons nxinyt₁, have nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, by_cases (λ yint₁ : y ∈ t₁, have yinxt₂ : y ∈ x::t₂, from or.inr (mem_of_mem_erase_dup (mem_perm r (mem_erase_dup yint₁))), begin rewrite [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_not_mem nxint₂], exact skip x r end) (λ nyint₁ : y ∉ t₁, have nyinxt₂ : y ∉ x::t₂, from assume yinxt₂ : y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons yinxt₂) (λ h, absurd h (ne.symm xney)) (λ h, absurd (mem_of_mem_erase_dup (mem_perm (perm.symm r) (mem_erase_dup h))) nyint₁), begin rewrite [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_not_mem nyinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂], exact xswap x y r end))) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂, trans r₁ r₂) -/ section perm_union variable [H : decidable_eq A] include H theorem perm_union_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (union l₁ t₁) ~ (union l₂ t₁) := sorry /- assume p, perm.induction_on p (by rewrite [nil_union]) (λ x l₁ l₂ p₁ r₁, by_cases (λ xint₁ : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint₁]; exact r₁) (λ nxint₁ : x ∉ t₁, by rewrite [*union_cons_of_not_mem _ nxint₁]; exact (skip _ r₁))) (λ x y l, by_cases (λ yint : y ∈ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint, *union_cons_of_mem _ yint, *union_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*union_cons_of_mem _ yint, *union_cons_of_not_mem _ nxint, union_cons_of_mem _ yint])) (λ nyint : y ∉ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*union_cons_of_mem _ xint, *union_cons_of_not_mem _ nyint, union_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*union_cons_of_not_mem _ nxint, *union_cons_of_not_mem _ nyint, union_cons_of_not_mem _ nxint]; exact !swap))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) -/ theorem perm_union_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (union l t₁) ~ (union l t₂) := sorry /- list.induction_on l (λ p, by rewrite [*union_nil]; exact p) (λ x xs r p, by_cases (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_perm p xint₁, by rewrite [union_cons_of_mem _ xint₁, union_cons_of_mem _ xint₂]; exact (r p)) (λ nxint₁ : x ∉ t₁, have nxint₂ : x ∉ t₂, from not_mem_perm p nxint₁, by rewrite [union_cons_of_not_mem _ nxint₁, union_cons_of_not_mem _ nxint₂]; exact (skip _ (r p)))) -/ attribute [congr] theorem perm_union {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (union l₁ t₁) ~ (union l₂ t₂) := assume p₁ p₂, trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂) end perm_union section perm_insert variable [H : decidable_eq A] include H attribute [congr] theorem perm_insert (a : A) {l₁ l₂ : list A} : l₁ ~ l₂ → (insert a l₁) ~ (insert a l₂) := sorry /- assume p, by_cases (λ ainl₁ : a ∈ l₁, have ainl₂ : a ∈ l₂, from mem_perm p ainl₁, by rewrite [insert_eq_of_mem ainl₁, insert_eq_of_mem ainl₂]; exact p) (λ nainl₁ : a ∉ l₁, have nainl₂ : a ∉ l₂, from not_mem_perm p nainl₁, by rewrite [insert_eq_of_not_mem nainl₁, insert_eq_of_not_mem nainl₂]; exact (skip _ p)) -/ end perm_insert section perm_inter variable [H : decidable_eq A] include H theorem perm_inter_left {l₁ l₂ : list A} (t₁ : list A) : l₁ ~ l₂ → (inter l₁ t₁) ~ (inter l₂ t₁) := sorry /- assume p, perm.induction_on p !perm.refl (λ x l₁ l₂ p₁ r₁, by_cases (λ xint₁ : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint₁]; exact (skip x r₁)) (λ nxint₁ : x ∉ t₁, by rewrite [*inter_cons_of_not_mem _ nxint₁]; exact r₁)) (λ x y l, by_cases (λ yint : y ∈ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint, *inter_cons_of_mem _ yint, *inter_cons_of_mem _ xint]; exact !swap) (λ nxint : x ∉ t₁, by rewrite [*inter_cons_of_mem _ yint, *inter_cons_of_not_mem _ nxint, inter_cons_of_mem _ yint])) (λ nyint : y ∉ t₁, by_cases (λ xint : x ∈ t₁, by rewrite [*inter_cons_of_mem _ xint, *inter_cons_of_not_mem _ nyint, inter_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rewrite [*inter_cons_of_not_mem _ nxint, *inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nxint]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) -/ theorem perm_inter_right (l : list A) {t₁ t₂ : list A} : t₁ ~ t₂ → (inter l t₁) ~ (inter l t₂) := sorry /- list.induction_on l (λ p, by rewrite [*inter_nil]) (λ x xs r p, by_cases (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_perm p xint₁, by rewrite [inter_cons_of_mem _ xint₁, inter_cons_of_mem _ xint₂]; exact (skip _ (r p))) (λ nxint₁ : x ∉ t₁, have nxint₂ : x ∉ t₂, from not_mem_perm p nxint₁, by rewrite [inter_cons_of_not_mem _ nxint₁, inter_cons_of_not_mem _ nxint₂]; exact (r p))) -/ attribute [congr] theorem perm_inter {l₁ l₂ t₁ t₂ : list A} : l₁ ~ l₂ → t₁ ~ t₂ → (inter l₁ t₁) ~ (inter l₂ t₂) := assume p₁ p₂, trans (perm_inter_left t₁ p₁) (perm_inter_right l₂ p₂) end perm_inter /- extensionality -/ section ext theorem perm_ext : ∀ {l₁ l₂ : list A}, nodup l₁ → nodup l₂ → (∀a, a ∈ l₁ ↔ a ∈ l₂) → l₁ ~ l₂ := sorry /- | [] [] d₁ d₂ e := !perm.nil | [] (a₂::t₂) d₁ d₂ e := absurd (iff.mpr (e a₂) !mem_cons) (not_mem_nil a₂) | (a₁::t₁) [] d₁ d₂ e := absurd (iff.mp (e a₁) !mem_cons) (not_mem_nil a₁) | (a₁::t₁) (a₂::t₂) d₁ d₂ e := have a₁ ∈ a₂::t₂, from iff.mp (e a₁) !mem_cons, have ∃ s₁ s₂, a₂::t₂ = s₁++(a₁::s₂), from mem_split this, obtain (s₁ s₂ : list A) (t₂_eq : a₂::t₂ = s₁++(a₁::s₂)), from this, have dt₂' : nodup (a₁::(s₁++s₂)), from nodup_head (by rewrite [t₂_eq at d₂]; exact d₂), have eqv : ∀a, a ∈ t₁ ↔ a ∈ s₁++s₂, from take a, iff.intro (suppose a ∈ t₁, have a ∈ a₂::t₂, from iff.mp (e a) (mem_cons_of_mem _ this), have a ∈ s₁++(a₁::s₂), by rewrite [t₂_eq at this]; exact this, or.elim (mem_or_mem_of_mem_append this) (suppose a ∈ s₁, mem_append_left s₂ this) (suppose a ∈ a₁::s₂, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, have a₁ ∉ t₁, from not_mem_of_nodup_cons d₁, by subst a; contradiction) (suppose a ∈ s₂, mem_append_right s₁ this))) (suppose a ∈ s₁ ++ s₂, or.elim (mem_or_mem_of_mem_append this) (suppose a ∈ s₁, have a ∈ a₂::t₂, from by rewrite [t₂_eq]; exact (mem_append_left _ this), have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', have a₁ ∉ s₁, from not_mem_of_not_mem_append_left this, by subst a; contradiction) (suppose a ∈ t₁, this)) (suppose a ∈ s₂, have a ∈ a₂::t₂, from by rewrite [t₂_eq]; exact (mem_append_right _ (mem_cons_of_mem _ this)), have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (suppose a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', have a₁ ∉ s₂, from not_mem_of_not_mem_append_right this, by subst a; contradiction) (suppose a ∈ t₁, this))), have ds₁s₂ : nodup (s₁++s₂), from nodup_of_nodup_cons dt₂', have nodup t₁, from nodup_of_nodup_cons d₁, calc a₁::t₁ ~ a₁::(s₁++s₂) : skip a₁ (perm_ext this ds₁s₂ eqv) ... ~ s₁++(a₁::s₂) : !perm_middle ... = a₂::t₂ : by rewrite t₂_eq -/ end ext theorem nodup_of_perm_of_nodup {l₁ l₂ : list A} : l₁ ~ l₂ → nodup l₁ → nodup l₂ := sorry /- assume h, perm.induction_on h (λ h, h) (λ a l₁ l₂ p ih nd, have nodup l₁, from nodup_of_nodup_cons nd, have nodup l₂, from ih this, have a ∉ l₁, from not_mem_of_nodup_cons nd, have a ∉ l₂, from suppose a ∈ l₂, absurd (mem_perm (perm.symm p) this) `a ∉ l₁`, nodup_cons `a ∉ l₂` `nodup l₂`) (λ x y l₁ nd, have nodup (x::l₁), from nodup_of_nodup_cons nd, have nodup l₁, from nodup_of_nodup_cons this, have x ∉ l₁, from not_mem_of_nodup_cons `nodup (x::l₁)`, have y ∉ x::l₁, from not_mem_of_nodup_cons nd, have x ≠ y, from suppose x = y, begin subst x, exact absurd !mem_cons `y ∉ y::l₁` end, have y ∉ l₁, from not_mem_of_not_mem_cons `y ∉ x::l₁`, have x ∉ y::l₁, from not_mem_cons_of_ne_of_not_mem `x ≠ y` `x ∉ l₁`, have nodup (y::l₁), from nodup_cons `y ∉ l₁` `nodup l₁`, show nodup (x::y::l₁), from nodup_cons `x ∉ y::l₁` `nodup (y::l₁)`) (λ l₁ l₂ l₃ p₁ p₂ ih₁ ih₂ nd, ih₂ (ih₁ nd)) -/ /- product -/ section product theorem perm_product_left {l₁ l₂ : list A} (t₁ : list B) : l₁ ~ l₂ → (product l₁ t₁) ~ (product l₂ t₁) := sorry /- assume p : l₁ ~ l₂, perm.induction_on p !perm.refl (λ x l₁ l₂ p r, perm_app (perm.refl (map _ t₁)) r) (λ x y l, let m₁ := map (λ b, (x, b)) t₁ in let m₂ := map (λ b, (y, b)) t₁ in let c := product l t₁ in calc m₂ ++ (m₁ ++ c) = (m₂ ++ m₁) ++ c : by rewrite append.assoc ... ~ (m₁ ++ m₂) ++ c : perm_app !perm_app_comm !perm.refl ... = m₁ ++ (m₂ ++ c) : by rewrite append.assoc) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) -/ theorem perm_product_right (l : list A) {t₁ t₂ : list B} : t₁ ~ t₂ → (product l t₁) ~ (product l t₂) := sorry /- list.induction_on l (λ p, by rewrite [*nil_product]) (λ a t r p, perm_app (perm_map _ p) (r p)) -/ attribute [congr] theorem perm_product {l₁ l₂ : list A} {t₁ t₂ : list B} : l₁ ~ l₂ → t₁ ~ t₂ → (product l₁ t₁) ~ (product l₂ t₂) := assume p₁ p₂, trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂) end product /- filter -/ attribute [congr] theorem perm_filter {l₁ l₂ : list A} {p : A → Prop} [decidable_pred p] : l₁ ~ l₂ → (filter p l₁) ~ (filter p l₂) := sorry /- assume u, perm.induction_on u perm.nil (take x l₁' l₂', assume u' : l₁' ~ l₂', assume u'' : filter p l₁' ~ filter p l₂', decidable.by_cases (suppose p x, by rewrite [*filter_cons_of_pos _ this]; apply perm.skip; apply u'') (suppose ¬ p x, by rewrite [*filter_cons_of_neg _ this]; apply u'')) (take x y l, decidable.by_cases (assume H1 : p x, decidable.by_cases (assume H2 : p y, begin rewrite [filter_cons_of_pos _ H1, *filter_cons_of_pos _ H2, filter_cons_of_pos _ H1], apply perm.swap end) (assume H2 : ¬ p y, by rewrite [filter_cons_of_pos _ H1, *filter_cons_of_neg _ H2, filter_cons_of_pos _ H1])) (assume H1 : ¬ p x, decidable.by_cases (assume H2 : p y, by rewrite [filter_cons_of_neg _ H1, *filter_cons_of_pos _ H2, filter_cons_of_neg _ H1]) (assume H2 : ¬ p y, by rewrite [filter_cons_of_neg _ H1, *filter_cons_of_neg _ H2, filter_cons_of_neg _ H1]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) -/ section count variable [decA : decidable_eq A] include decA theorem count_eq_of_perm {l₁ l₂ : list A} : l₁ ~ l₂ → ∀ a, count a l₁ = count a l₂ := sorry /- suppose l₁ ~ l₂, perm.induction_on this (λ a, rfl) (λ x l₁ l₂ p h a, by rewrite [*count_cons, *h a]) (λ x y l a, by_cases (suppose a = x, by_cases (suppose a = y, begin subst x, subst y end) (suppose a ≠ y, begin subst x, rewrite [count_cons_of_ne this, *count_cons_eq, count_cons_of_ne this] end)) (suppose a ≠ x, by_cases (suppose a = y, begin subst y, rewrite [count_cons_of_ne this, *count_cons_eq, count_cons_of_ne this] end) (suppose a ≠ y, begin rewrite [count_cons_of_ne `a≠x`, *count_cons_of_ne `a≠y`, count_cons_of_ne `a≠x`] end))) (λ l₁ l₂ l₃ p₁ p₂ h₁ h₂ a, eq.trans (h₁ a) (h₂ a)) -/ end count end perm
2d1970a634711725befbf403dc1cc69901326598
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/field_theory/splitting_field.lean
facc9f4764d6493723e950d1cef8b3ab5269c2a6
[ "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
35,465
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import ring_theory.adjoin_root import ring_theory.algebra_tower import ring_theory.algebraic import ring_theory.polynomial import field_theory.minpoly import linear_algebra.finite_dimensional import tactic.field_simp noncomputable theory open_locale classical big_operators universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial variables [field α] [field β] [field γ] open polynomial section splits variables (i : α →+* β) /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_of_splits_of_dvd {f g : polynomial α} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) : splits i g := by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 } lemma splits_of_splits_gcd_left {f g : polynomial α} (hf0 : f ≠ 0) (hf : splits i f) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g) lemma splits_of_splits_gcd_right {f g : polynomial α} (hg0 : g ≠ 0) (hg : splits i g) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g) lemma splits_map_iff (j : β →+* γ) {f : polynomial α} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_of_is_unit {u : polynomial α} (hu : is_unit u) : u.splits i := splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu theorem splits_X_sub_C {x : α} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_X : X.splits i := splits_of_degree_eq_one _ $ degree_X theorem splits_id_iff_splits {f : polynomial α} : (f.map i).splits (ring_hom.id β) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : polynomial α} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end theorem splits_prod_iff {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma degree_eq_one_of_irreducible_of_splits {p : polynomial β} (h_nz : p ≠ 0) (hp : irreducible p) (hp_splits : splits (ring_hom.id β) p) : p.degree = 1 := begin rcases hp_splits, { contradiction }, { apply hp_splits hp, simp } end lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (map_ne_zero hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, wf_dvd_monoid.induction_on_irreducible (f.map i) (λ _, ⟨{37}, by simp [i.map_zero]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 ::ₘ s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, mul_left_inj' hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit_of_ne_zero hp.ne_zero, mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 hp.ne_zero), one_mul], end⟩) /-- Pick a root of a polynomial that splits. -/ def root_of_splits {f : polynomial α} (hf : f.splits i) (hfd : f.degree ≠ 0) : β := classical.some $ exists_root_of_splits i hf hfd theorem map_root_of_splits {f : polynomial α} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits i hf hfd) = 0 := classical.some_spec $ exists_root_of_splits i hf hfd theorem roots_map {f : polynomial α} (hf : f.splits $ ring_hom.id α) : (f.map i).roots = (f.roots).map i := if hf0 : f = 0 then by rw [hf0, map_zero, roots_zero, roots_zero, multiset.map_zero] else have hmf0 : f.map i ≠ 0 := map_ne_zero hf0, let ⟨m, hm⟩ := exists_multiset_of_splits _ hf in have h1 : ∀ p ∈ m.map (λ r, X - C r), (p : _) ≠ 0, from multiset.forall_mem_map_iff.2 $ λ _ _, X_sub_C_ne_zero _, have h2 : ∀ p ∈ m.map (λ r, X - C (i r)), (p : _) ≠ 0, from multiset.forall_mem_map_iff.2 $ λ _ _, X_sub_C_ne_zero _, begin rw map_id at hm, rw hm at hf0 hmf0 ⊢, rw map_mul at hmf0 ⊢, rw [roots_mul hf0, roots_mul hmf0, map_C, roots_C, zero_add, roots_C, zero_add, map_multiset_prod, multiset.map_map], simp_rw [(∘), map_sub, map_X, map_C], rw [roots_multiset_prod _ h2, multiset.bind_map, roots_multiset_prod _ h1, multiset.bind_map], simp_rw roots_X_sub_C, rw [multiset.bind_cons, multiset.bind_zero, add_zero, multiset.bind_cons, multiset.bind_zero, add_zero, multiset.map_id'] end lemma eq_prod_roots_of_splits {p : polynomial α} {i : α →+* β} (hsplit : splits i p) : p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, map_zero, leading_coeff_zero, i.map_zero, C.map_zero, zero_mul] }, obtain ⟨s, hs⟩ := exists_multiset_of_splits i hsplit, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), have prod_ne_zero : C (i p.leading_coeff) * (multiset.map (λ a, X - C a) s).prod ≠ 0 := by rwa hs at map_ne_zero, have ne_zero_of_mem : ∀ (p : polynomial β), p ∈ s.map (λ a, X - C a) → p ≠ 0, { intros p mem, obtain ⟨a, _, rfl⟩ := multiset.mem_map.mp mem, apply X_sub_C_ne_zero }, have map_bind_roots_eq : (s.map (λ a, X - C a)).bind (λ a, a.roots) = s, { refine multiset.induction_on s (by rw [multiset.map_zero, multiset.zero_bind]) _, intros a s ih, rw [multiset.map_cons, multiset.cons_bind, ih, roots_X_sub_C, multiset.cons_add, zero_add] }, rw [hs, roots_mul prod_ne_zero, roots_C, zero_add, roots_multiset_prod _ ne_zero_of_mem, map_bind_roots_eq] end lemma eq_X_sub_C_of_splits_of_single_root {x : α} {h : polynomial α} (h_splits : splits i h) (h_roots : (h.map i).roots = {i x}) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.map_injective _ i.injective, rw [eq_prod_roots_of_splits h_splits, h_roots], simp, end lemma nat_degree_multiset_prod {R : Type*} [integral_domain R] {s : multiset (polynomial R)} (h : ∀ p ∈ s, p ≠ (0 : polynomial R)) : nat_degree s.prod = (s.map nat_degree).sum := begin revert h, refine s.induction_on _ _, { simp }, intros p s ih h, have hs : ∀ p ∈ s, p ≠ (0 : polynomial R) := λ p hp, h p (multiset.mem_cons_of_mem hp), have hprod : s.prod ≠ 0 := multiset.prod_ne_zero (λ p hp, hs p hp), rw [multiset.prod_cons, nat_degree_mul (h p (multiset.mem_cons_self _ _)) hprod, ih hs, multiset.map_cons, multiset.sum_cons], end lemma nat_degree_eq_card_roots {p : polynomial α} {i : α →+* β} (hsplit : splits i p) : p.nat_degree = (p.map i).roots.card := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, nat_degree_zero, map_zero, roots_zero, multiset.card_zero] }, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), rw eq_prod_roots_of_splits hsplit at map_ne_zero, conv_lhs { rw [← nat_degree_map i, eq_prod_roots_of_splits hsplit] }, have : ∀ p' ∈ (map i p).roots.map (λ a, X - C a), p' ≠ (0 : polynomial β), { intros p hp, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.mp hp, exact X_sub_C_ne_zero _ }, simp [nat_degree_mul (left_ne_zero_of_mul map_ne_zero) (right_ne_zero_of_mul map_ne_zero), nat_degree_multiset_prod this] end lemma degree_eq_card_roots {p : polynomial α} {i : α →+* β} (p_ne_zero : p ≠ 0) (hsplit : splits i p) : p.degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit] section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid local infix ` ~ᵤ ` : 50 := associated open unique_factorization_monoid associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := factors_unique (λ p hp, irreducible_of_factor _ hp) (λ p' m, begin obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m, exact irreducible_of_degree_eq_one (degree_X_sub_C _), end) (associated.symm $ calc _ ~ᵤ f.map i : ⟨(units.map' C : units β →* units (polynomial β)) (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (map_ne_zero hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_monoid.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits (ring_hom.id _) f → splits i f := unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β →+* γ) {f : polynomial α} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end /-- A monic polynomial `p` that has as much roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq {p : polynomial α} (hmonic : p.monic) (hroots : p.roots.card = p.nat_degree) : (multiset.map (λ (a : α), X - C a) p.roots).prod = p := begin have hprodmonic : (multiset.map (λ (a : α), X - C a) p.roots).prod.monic, { simp only [prod_multiset_root_eq_finset_root (ne_zero_of_monic hmonic), monic_prod_of_monic, monic_X_sub_C, monic_pow, forall_true_iff] }, have hdegree : (multiset.map (λ (a : α), X - C a) p.roots).prod.nat_degree = p.nat_degree, { rw [← hroots, nat_degree_multiset_prod], simp only [eq_self_iff_true, mul_one, nat.cast_id, nsmul_eq_mul, multiset.sum_repeat, multiset.map_const,nat_degree_X_sub_C, function.comp, multiset.map_map], intros x y, simp only [multiset.mem_map] at y, rcases y with ⟨a, ha, rfl⟩, exact X_sub_C_ne_zero a }, obtain ⟨q, hq⟩ := prod_multiset_X_sub_C_dvd p, have qzero : q ≠ 0, { rintro rfl, apply hmonic.ne_zero, simpa only [mul_zero] using hq }, have degp : p.nat_degree = (multiset.map (λ (a : α), X - C a) p.roots).prod.nat_degree + q.nat_degree, { nth_rewrite 0 [hq], simp only [nat_degree_mul (ne_zero_of_monic hprodmonic) qzero] }, have degq : q.nat_degree = 0, { rw hdegree at degp, exact (add_right_inj p.nat_degree).mp (tactic.ring_exp.add_pf_sum_z degp rfl).symm }, obtain ⟨u, hu⟩ := is_unit_iff_degree_eq_zero.2 ((degree_eq_iff_nat_degree_eq qzero).2 degq), have hassoc : associated (multiset.map (λ (a : α), X - C a) p.roots).prod p, { rw associated, use u, rw [hu, ← hq] }, exact eq_of_monic_of_associated hprodmonic hmonic hassoc end /-- A polynomial `p` that has as much roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C {p : polynomial α} (hroots : p.roots.card = p.nat_degree) : (C p.leading_coeff) * (multiset.map (λ (a : α), X - C a) p.roots).prod = p := begin by_cases hzero : p = 0, { rw [hzero, leading_coeff_zero, ring_hom.map_zero, zero_mul], }, { have hcoeff : p.leading_coeff ≠ 0, { intro h, exact hzero (leading_coeff_eq_zero.1 h) }, have hrootsnorm : (normalize p).roots.card = (normalize p).nat_degree, { rw [roots_normalize, normalize_apply, nat_degree_mul hzero (units.ne_zero _), hroots, coe_norm_unit, nat_degree_C, add_zero], }, have hprod := prod_multiset_X_sub_C_of_monic_of_roots_card_eq (monic_normalize hzero) hrootsnorm, rw [roots_normalize, normalize_apply, coe_norm_unit_of_ne_zero hzero] at hprod, calc (C p.leading_coeff) * (multiset.map (λ (a : α), X - C a) p.roots).prod = p * C ((p.leading_coeff)⁻¹ * p.leading_coeff) : by rw [hprod, mul_comm, mul_assoc, ← C_mul] ... = p * C 1 : by field_simp ... = p : by simp only [mul_one, ring_hom.map_one], }, end /-- A polynomial splits if and only if it has as much roots as its degree. -/ lemma splits_iff_card_roots {p : polynomial α} : splits (ring_hom.id α) p ↔ p.roots.card = p.nat_degree := begin split, { intro H, rw [nat_degree_eq_card_roots H, map_id] }, { intro hroots, apply (splits_iff_exists_multiset (ring_hom.id α)).2, use p.roots, simp only [ring_hom.id_apply, map_id], exact (C_leading_coeff_mul_prod_multiset_X_sub_C hroots).symm }, end end splits end polynomial section embeddings variables (F : Type*) [field F] /-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/ def alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly {R : Type*} [comm_ring R] [algebra F R] (x : R) : algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minpoly F x) := alg_equiv.symm $ alg_equiv.of_bijective (alg_hom.cod_restrict (adjoin_root.lift_hom _ x $ minpoly.aeval F x) _ (λ p, adjoin_root.induction_on _ p $ λ p, (algebra.adjoin_singleton_eq_range F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩)) ⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (alg_hom.injective_iff _).2 $ λ p, adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ minpoly.dvd F x hp, λ y, let ⟨p, _, hp⟩ := (subalgebra.ext_iff.1 (algebra.adjoin_singleton_eq_range F x) y).1 y.2 in ⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩ open finset -- Speed up the following proof. local attribute [irreducible] minpoly -- TODO: Why is this so slow? /-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/ theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L] [algebra F K] [algebra F L] (s : finset K) : (∀ x ∈ s, is_integral F x ∧ polynomial.splits (algebra_map F L) (minpoly F x)) → nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) := begin refine finset.induction_on s (λ H, _) (λ a s has ih H, _), { rw [coe_empty, algebra.adjoin_empty], exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ }, rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f, choose H3 H4 using H3, rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union], letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra, haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) := (submodule.fg_iff_finite_dimensional _).1 (fg_adjoin_of_finite (set.finite_mem_finset s) H3), letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)), have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1, have H6 : (minpoly (algebra.adjoin F (↑s : set K)) a).splits (algebra_map (algebra.adjoin F (↑s : set K)) L), { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero $ minpoly.ne_zero H1 : polynomial.map (algebra_map _ _) _ ≠ 0) ((polynomial.splits_map_iff _ _).2 _) (minpoly.dvd _ _ _), { rw ← is_scalar_tower.algebra_map_eq, exact H2 }, { rw [← is_scalar_tower.aeval_apply, minpoly.aeval] } }, obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (ne_of_lt (minpoly.degree_pos H5)).symm, refine ⟨subalgebra.of_under _ _ _⟩, refine (adjoin_root.lift_hom (minpoly (algebra.adjoin F (↑s : set K)) a) y hy).comp _, exact alg_equiv.adjoin_singleton_equiv_adjoin_root_minpoly (algebra.adjoin F (↑s : set K)) a end end embeddings namespace polynomial variables [field α] [field β] [field γ] open polynomial section splitting_field /-- Non-computably choose an irreducible factor from a polynomial. -/ def factor (f : polynomial α) : polynomial α := if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X instance irreducible_factor (f : polynomial α) : irreducible (factor f) := begin rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X } end theorem factor_dvd_of_not_is_unit {f : polynomial α} (hf1 : ¬is_unit f) : factor f ∣ f := begin by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ }, rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)], exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2 end theorem factor_dvd_of_degree_ne_zero {f : polynomial α} (hf : f.degree ≠ 0) : factor f ∣ f := factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf) theorem factor_dvd_of_nat_degree_ne_zero {f : polynomial α} (hf : f.nat_degree ≠ 0) : factor f ∣ f := factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf) /-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/ def remove_factor (f : polynomial α) : polynomial (adjoin_root $ factor f) := map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor)) theorem X_sub_C_mul_remove_factor (f : polynomial α) (hf : f.nat_degree ≠ 0) : (X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f := let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg, adjoin_root.eval₂_root, zero_mul] theorem nat_degree_remove_factor (f : polynomial α) : f.remove_factor.nat_degree = f.nat_degree - 1 := by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map, nat_degree_X_sub_C] theorem nat_degree_remove_factor' {f : polynomial α} {n : ℕ} (hfn : f.nat_degree = n+1) : f.remove_factor.nat_degree = n := by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel] /-- Auxiliary construction to a splitting field of a polynomial. Uses induction on the degree. -/ def splitting_field_aux (n : ℕ) : Π {α : Type u} [field α], by exactI Π (f : polynomial α), f.nat_degree = n → Type u := nat.rec_on n (λ α _ _ _, α) $ λ n ih α _ f hf, by exactI ih f.remove_factor (nat_degree_remove_factor' hf) namespace splitting_field_aux theorem succ (n : ℕ) (f : polynomial α) (hfn : f.nat_degree = n + 1) : splitting_field_aux (n+1) f hfn = splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn) := rfl instance field (n : ℕ) : Π {α : Type u} [field α], by exactI Π {f : polynomial α} (hfn : f.nat_degree = n), field (splitting_field_aux n f hfn) := nat.rec_on n (λ α _ _ _, ‹field α›) $ λ n ih α _ f hf, ih _ instance inhabited {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n) : inhabited (splitting_field_aux n f hfn) := ⟨37⟩ instance algebra (n : ℕ) : Π {α : Type u} [field α], by exactI Π {f : polynomial α} (hfn : f.nat_degree = n), algebra α (splitting_field_aux n f hfn) := nat.rec_on n (λ α _ _ _, by exactI algebra.id α) $ λ n ih α _ f hfn, by exactI @@algebra.comap.algebra _ _ _ _ _ _ _ (ih _) instance algebra' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := splitting_field_aux.algebra n _ instance algebra'' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra α (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra (n+1) hfn instance algebra''' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra n _ instance scalar_tower {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : is_scalar_tower α (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl instance scalar_tower' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : is_scalar_tower α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl theorem algebra_map_succ (n : ℕ) (f : polynomial α) (hfn : f.nat_degree = n + 1) : by exact algebra_map α (splitting_field_aux _ _ hfn) = (algebra_map (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn))).comp (adjoin_root.of f.factor) := rfl protected theorem splits (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n), splits (algebra_map α $ splitting_field_aux n f hfn) f := nat.rec_on n (λ α _ _ hf, by exactI splits_of_degree_le_one _ (le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih α _ f hf, by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits, ← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })], exact splits_mul _ (splits_X_sub_C _) (ih _ _) } theorem exists_lift (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n) {β : Type*} [field β], by exactI ∀ (j : α →+* β) (hf : splits j f), ∃ k : splitting_field_aux n f hfn →+* β, k.comp (algebra_map _ _) = j := nat.rec_on n (λ α _ _ _ β _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih α _ f hf β _ j hj, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj (factor_dvd_of_nat_degree_ne_zero hndf)) (mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0, have hsf : splits (adjoin_root.lift j r hr) f.remove_factor, by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2, rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of, splits_id_iff_splits] }, let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in ⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩ theorem adjoin_roots (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n), algebra.adjoin α (↑(f.map $ algebra_map α $ splitting_field_aux n f hfn).roots.to_finset : set (splitting_field_aux n f hfn)) = ⊤ := nat.rec_on n (λ α _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $ λ n ih α _ f hfn, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, have hmf0 : map (algebra_map α (splitting_field_aux n.succ f hfn)) f ≠ 0 := map_ne_zero hfn0, by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, map_mul] at hmf0 ⊢, rw [roots_mul hmf0, map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union, multiset.to_finset_cons, multiset.to_finset_zero, insert_emptyc_eq, finset.coe_singleton, algebra.adjoin_union, ← set.image_singleton, algebra.adjoin_algebra_map α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), adjoin_root.adjoin_root_eq_top, algebra.map_top, is_scalar_tower.range_under_adjoin α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), ih, subalgebra.res_top] } end splitting_field_aux /-- A splitting field of a polynomial. -/ def splitting_field (f : polynomial α) := splitting_field_aux _ f rfl namespace splitting_field variables (f : polynomial α) instance : field (splitting_field f) := splitting_field_aux.field _ _ instance inhabited : inhabited (splitting_field f) := ⟨37⟩ instance : algebra α (splitting_field f) := splitting_field_aux.algebra _ _ protected theorem splits : splits (algebra_map α (splitting_field f)) f := splitting_field_aux.splits _ _ _ variables [algebra α β] (hb : splits (algebra_map α β) f) /-- Embeds the splitting field into any other field that splits the polynomial. -/ def lift : splitting_field f →ₐ[α] β := { commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ _ _ hb), exact ring_hom.ext_iff.1 this r }, .. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) } theorem adjoin_roots : algebra.adjoin α (↑(f.map (algebra_map α $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ := splitting_field_aux.adjoin_roots _ _ _ end splitting_field variables (α β) [algebra α β] /-- Typeclass characterising splitting fields. -/ class is_splitting_field (f : polynomial α) : Prop := (splits [] : splits (algebra_map α β) f) (adjoin_roots [] : algebra.adjoin α (↑(f.map (algebra_map α β)).roots.to_finset : set β) = ⊤) namespace is_splitting_field variables {α} instance splitting_field (f : polynomial α) : is_splitting_field α (splitting_field f) f := ⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩ section scalar_tower variables {α β γ} [algebra β γ] [algebra α γ] [is_scalar_tower α β γ] variables {α} instance map (f : polynomial α) [is_splitting_field α γ f] : is_splitting_field β γ (f.map $ algebra_map α β) := ⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits γ f }, subalgebra.res_inj α $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.res_top, eq_top_iff, ← adjoin_roots γ f, algebra.adjoin_le_iff], exact λ x hx, @algebra.subset_adjoin β _ _ _ _ _ _ hx }⟩ variables {α} (β) theorem splits_iff (f : polynomial α) [is_splitting_field α β f] : polynomial.splits (ring_hom.id α) f ↔ (⊤ : subalgebra α β) = ⊥ := ⟨λ h, eq_bot_iff.2 $ adjoin_roots β f ▸ (roots_map (algebra_map α β) h).symm ▸ algebra.adjoin_le_iff.2 (λ y hy, let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in hxy ▸ subalgebra.algebra_map_mem _ _), λ h, @ring_equiv.to_ring_hom_refl α _ ▸ ring_equiv.trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸ by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits β f) }⟩ theorem mul (f g : polynomial α) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field α β f] [is_splitting_field β γ (g.map $ algebra_map α β)] : is_splitting_field α γ (f * g) := ⟨(is_scalar_tower.algebra_map_eq α β γ).symm ▸ splits_mul _ (splits_comp_of_splits _ _ (splits β f)) ((splits_map_iff _ _).1 (splits γ $ g.map $ algebra_map α β)), by rw [map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map α γ) ≠ 0) (map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union, is_scalar_tower.algebra_map_eq α β γ, ← map_map, roots_map (algebra_map β γ) ((splits_id_iff_splits $ algebra_map α β).2 $ splits β f), multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots, algebra.map_top, is_scalar_tower.range_under_adjoin, ← map_map, adjoin_roots, subalgebra.res_top]⟩ end scalar_tower /-- Splitting field of `f` embeds into any field that splits `f`. -/ def lift [algebra α γ] (f : polynomial α) [is_splitting_field α β f] (hf : polynomial.splits (algebra_map α γ) f) : β →ₐ[α] γ := if hf0 : f = 0 then (algebra.of_id α γ).comp $ (algebra.bot_equiv α β : (⊥ : subalgebra α β) →ₐ[α] α).comp $ by { rw ← (splits_iff β f).1 (show f.splits (ring_hom.id α), from hf0.symm ▸ splits_zero _), exact algebra.to_top } else alg_hom.comp (by { rw ← adjoin_roots β f, exact classical.choice (lift_of_splits _ $ λ y hy, have aeval y f = 0, from (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy), ⟨(is_algebraic_iff_is_integral _).1 ⟨f, hf0, this⟩, splits_of_splits_of_dvd _ hf0 hf $ minpoly.dvd _ _ this⟩) }) algebra.to_top theorem finite_dimensional (f : polynomial α) [is_splitting_field α β f] : finite_dimensional α β := finite_dimensional.iff_fg.2 $ @algebra.coe_top α β _ _ _ ▸ adjoin_roots β f ▸ fg_adjoin_of_finite (set.finite_mem_finset _) (λ y hy, if hf : f = 0 then by { rw [hf, map_zero, roots_zero] at hy, cases hy } else (is_algebraic_iff_is_integral _).1 ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩) /-- Any splitting field is isomorphic to `splitting_field f`. -/ def alg_equiv (f : polynomial α) [is_splitting_field α β f] : β ≃ₐ[α] splitting_field f := begin refine alg_equiv.of_bijective (lift β f $ splits (splitting_field f) f) ⟨ring_hom.injective (lift β f $ splits (splitting_field f) f).to_ring_hom, _⟩, haveI := finite_dimensional (splitting_field f) f, haveI := finite_dimensional β f, have : finite_dimensional.findim α β = finite_dimensional.findim α (splitting_field f) := le_antisymm (linear_map.findim_le_findim_of_injective (show function.injective (lift β f $ splits (splitting_field f) f).to_linear_map, from ring_hom.injective (lift β f $ splits (splitting_field f) f : β →+* f.splitting_field))) (linear_map.findim_le_findim_of_injective (show function.injective (lift (splitting_field f) f $ splits β f).to_linear_map, from ring_hom.injective (lift (splitting_field f) f $ splits β f : f.splitting_field →+* β))), change function.surjective (lift β f $ splits (splitting_field f) f).to_linear_map, refine (linear_map.injective_iff_surjective_of_findim_eq_findim this).1 _, exact ring_hom.injective (lift β f $ splits (splitting_field f) f : β →+* f.splitting_field) end end is_splitting_field end splitting_field end polynomial
2ae93b800e97c2fb4c0ac8f3f9bf8b0f79b768a6
43390109ab88557e6090f3245c47479c123ee500
/src/Topology/Material/topology_thoughts.lean
eba37101492b0d0dfc1030fa4526f89bdd93dcf0
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
977
lean
import analysis.metric_space import tactic.norm_num local attribute [instance, priority 0] classical.prop_decidable noncomputable theory def discrete_metric_space' (α : Type*) : metric_space α := { dist := λ a b, if a = b then 0 else 1, dist_self := begin intro x, unfold ite, rw eq_true_intro (eq.refl x), exact if_true 0 1, end, eq_of_dist_eq_zero := begin intros x y, dsimp, split_ifs, intro _,exact h, norm_num, end, dist_comm := begin intros x y, dsimp, split_ifs, refl, cases (h_1 h.symm), cases (h h_1.symm), refl end, dist_triangle := begin intros, dsimp, split_ifs, right,refl, left,show (0 : ℝ) < 0 + 1,norm_num, left,show (0 : ℝ) < 1 + 0,norm_num, left,show (0 : ℝ) < 1 + 1,norm_num, exfalso,apply h,rwa h_1, right,refl, right,refl, left, show (1 : ℝ) < 1 + 1, norm_num, end }
aefa06a4309f20d792ba3d7d27ade013c78c23ce
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/hott/init/equiv.hlean
3e291149301feb814450d4a400ab9aef018d6b0f
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,801
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.equiv Author: Jeremy Avigad, Jakob von Raumer Ported from Coq HoTT -/ prelude import .path .function open eq function /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A → B) := (inv : B → A) (retr : (f ∘ inv) ∼ id) (sect : (inv ∘ f) ∼ id) (adj : Πx, retr (f x) = ap f (sect x)) attribute is_equiv.inv [quasireducible] -- A more bundled version of equivalence structure equiv (A B : Type) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix `⁻¹` := inv --a second notation for the inverse, which is not overloaded postfix [parsing-only] `⁻¹ᵉ`:std.prec.max_plus := inv section variables {A B C : Type} (f : A → B) (g : B → C) {f' : A → B} -- The identity function is an equivalence. -- TODO: make A explicit definition is_equiv_id : (@is_equiv A A id) := is_equiv.mk id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. definition is_equiv_compose [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk ((inv f) ∘ (inv g)) (λc, ap g (retr f (g⁻¹ c)) ⬝ retr g c) (λa, ap (inv f) (sect g (f a)) ⬝ sect f a) (λa, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (retr f) (sect g (f a)))⁻¹ ⬝ (ap_compose (inv f) f _ ◾ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose f g _)⁻¹ ) -- Any function equal to an equivalence is an equivlance as well. definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : (is_equiv f') := eq.rec_on Heq Hf -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [Hf : is_equiv f] (Hty : f ∼ f') : (is_equiv f') := let sect' := (λ b, (Hty (inv f b))⁻¹ ⬝ retr f b) in let retr' := (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ sect f a) in let adj' := (λ (a : A), let ff'a := Hty a in let invf := inv f in let secta := sect f a in let retrfa := retr f (f a) in let retrf'a := retr f (f' a) in have eq1 : _ = _, from calc ap f secta ⬝ ff'a = retrfa ⬝ ff'a : by rewrite adj ... = ap (f ∘ invf) ff'a ⬝ retrf'a : by rewrite ap_con_eq_con ... = ap f (ap invf ff'a) ⬝ retrf'a : by rewrite ap_compose, have eq2 : _ = _, from calc retrf'a = (ap f (ap invf ff'a))⁻¹ ⬝ (ap f secta ⬝ ff'a) : eq_inv_con_of_con_eq _ _ _ eq1⁻¹ ... = (ap f (ap invf ff'a))⁻¹ ⬝ (ap f secta ⬝ Hty a) : ap_inv invf ff'a ... = (ap f (ap invf ff'a))⁻¹ ⬝ (Hty (invf (f a)) ⬝ ap f' secta) : by rewrite ap_con_eq_con_ap ... = ((ap f (ap invf ff'a))⁻¹ ⬝ Hty (invf (f a))) ⬝ ap f' secta : by rewrite con.assoc ... = (ap f (ap invf ff'a)⁻¹ ⬝ Hty (invf (f a))) ⬝ ap f' secta : by rewrite ap_inv ... = (Hty (invf (f' a)) ⬝ ap f' (ap invf ff'a)⁻¹) ⬝ ap f' secta : by rewrite ap_con_eq_con_ap ... = (Hty (invf (f' a)) ⬝ (ap f' (ap invf ff'a))⁻¹) ⬝ ap f' secta : by rewrite ap_inv ... = Hty (invf (f' a)) ⬝ ((ap f' (ap invf ff'a))⁻¹ ⬝ ap f' secta) : by rewrite con.assoc, have eq3 : _ = _, from calc (Hty (invf (f' a)))⁻¹ ⬝ retrf'a = (ap f' (ap invf ff'a))⁻¹ ⬝ ap f' secta : inv_con_eq_of_eq_con _ _ _ eq2 ... = (ap f' (ap invf ff'a)⁻¹) ⬝ ap f' secta : by rewrite ap_inv ... = ap f' ((ap invf ff'a)⁻¹ ⬝ secta) : by rewrite ap_con, eq3) in is_equiv.mk (inv f) sect' retr' adj' end context parameters {A B : Type} (f : A → B) (g : B → A) (ret : f ∘ g ∼ id) (sec : g ∘ f ∼ id) private definition adjointify_sect' : g ∘ f ∼ id := (λx, ap g (ap f (inverse (sec x))) ⬝ ap g (ret (f x)) ⬝ sec x) private definition adjointify_adj' : Π (x : A), ret (f x) = ap f (adjointify_sect' x) := (λ (a : A), let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rewrite idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !con_idp ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq _ _ _ eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con, have eq4 : ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con _ _ eq3, eq4) definition adjointify : is_equiv f := is_equiv.mk g ret adjointify_sect' adjointify_adj' end section variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C) include Hf --The inverse of an equivalence is, again, an equivalence. definition is_equiv_inv [instance] : (is_equiv f⁻¹) := adjointify f⁻¹ f (sect f) (retr f) definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv [visible] : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (g ∘ f)) (λb, ap g (@retr _ _ f _ b)) definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv [visible] : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (f ∘ g) f⁻¹) (λa, sect f (g a)) definition is_equiv_ap [instance] (x y : A) : is_equiv (ap f) := adjointify (ap f) (λq, (inverse (sect f x)) ⬝ ap f⁻¹ q ⬝ sect f y) (λq, !ap_con ⬝ whisker_right !ap_con _ ⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹) ◾ (inverse (ap_compose f⁻¹ f _)) ◾ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (retr f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) (λp, whisker_right (whisker_left _ (ap_compose f f⁻¹ _)⁻¹) _ ⬝ con_ap_con_eq_con_con (sect f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition equiv_rect (P : B → Type) : (Πx, P (f x)) → (Πy, P y) := (λg y, eq.transport _ (retr f y) (g (f⁻¹ y))) definition equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = transport P (retr f (f x)) (df (f⁻¹ (f x))) : by esimp ... = transport P (eq.ap f (sect f x)) (df (f⁻¹ (f x))) : by rewrite adj ... = transport (P ∘ f) (sect f x) (df (f⁻¹ (f x))) : by rewrite -transport_compose ... = df x : by rewrite (apD df (sect f x)) end section variables {A B : Type} {f : A → B} [Hf : is_equiv f] {a : A} {b : B} include Hf --Rewrite rules definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ retr f b definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ sect f a definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end --Transporting is an equivalence definition is_equiv_tr [instance] {A : Type} (P : A → Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk (transport P p⁻¹) (tr_inv_tr P p) (inv_tr_tr P p) (tr_inv_tr_lemma P p) end is_equiv open is_equiv namespace equiv namespace ops attribute to_fun [coercion] end ops open equiv.ops attribute to_is_equiv [instance] infix `≃`:25 := equiv variables {A B C : Type} protected definition MK [reducible] (f : A → B) (g : B → A) (retr : f ∘ g ∼ id) (sect : g ∘ f ∼ id) : A ≃ B := equiv.mk f (adjointify f g retr sect) definition to_inv [reducible] (f : A ≃ B) : B → A := f⁻¹ protected definition refl : A ≃ A := equiv.mk id !is_equiv_id protected definition symm (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ !is_equiv_inv protected definition trans (f : A ≃ B) (g: B ≃ C) : A ≃ C := equiv.mk (g ∘ f) !is_equiv_compose definition equiv_of_eq_fn_of_equiv (f : A ≃ B) (f' : A → B) (Heq : f = f') : A ≃ B := equiv.mk f' (is_equiv_eq_closed f Heq) definition eq_equiv_fn_eq (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition eq_equiv_fn_eq_of_equiv (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition equiv_ap (P : A → Type) {a b : A} (p : a = b) : (P a) ≃ (P b) := equiv.mk (transport P p) !is_equiv_tr --we need this theorem for the funext_of_ua proof theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ := eq.rec_on p idp -- calc enviroment -- Note: Calculating with substitutions needs univalence definition equiv_of_equiv_of_eq {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C := p⁻¹ ▹ q definition equiv_of_eq_of_equiv {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C := q ▹ p calc_trans equiv.trans calc_refl equiv.refl calc_symm equiv.symm calc_trans equiv_of_equiv_of_eq calc_trans equiv_of_eq_of_equiv end equiv
f1420988e4c416a9f19885ab3477f585f7f9c498
217bb195841a8be2d1b4edd2084d6b69ccd62f50
/tests/playground/parser/test1.lean
34327e632c55291b046eb5bcba7751ce8ef0147a
[ "Apache-2.0" ]
permissive
frank-lesser/lean4
717f56c9bacd5bf3a67542d2f5cea721d4743a30
79e2abe33f73162f773ea731265e456dbfe822f9
refs/heads/master
1,589,741,267,933
1,556,424,200,000
1,556,424,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,613
lean
import parser open Parser def mkNumPairKind : IO SyntaxNodeKind := nextKind `numPair @[init mkNumPairKind] constant numPairKind : SyntaxNodeKind := default _ def mkNumSetKind : IO SyntaxNodeKind := nextKind `numSet @[init mkNumSetKind] constant numSetKind : SyntaxNodeKind := default _ def mkParenIdentKind : IO SyntaxNodeKind := nextKind `parenIdent @[init mkParenIdentKind] constant parenIdentKind : SyntaxNodeKind := default _ def mkQualifiedKind : IO SyntaxNodeKind := nextKind `qualified @[init mkQualifiedKind] constant qualifiedKind : SyntaxNodeKind := default _ def mkSeqKind : IO SyntaxNodeKind := nextKind `seq @[init mkSeqKind] constant seqKind : SyntaxNodeKind := default _ def mkSetCompKind : IO SyntaxNodeKind := nextKind `setComp @[init mkSetCompKind] constant setCompKind : SyntaxNodeKind := default _ -- set_option pp.implicit true -- set_option trace.compiler.boxed true def numPairP : TermParser := node numPairKind $ "("; number; ","; number; ")" def numSetP : TermParser := node numSetKind $ "{"; sepBy number ","; "}" def testParser1 : TermParser := many (numPairP <|> numSetP) def parenIdentP : TermParser := node parenIdentKind $ "("; ident; ")" def qualifiedP : TermParser := node qualifiedKind $ "("; ident; ":"; ident; ")" def seqP : TermParser := node seqKind $ "("; sepBy ident ":"; ")" def setCompP : TermParser := node setCompKind $ "{"; ident; ":"; ident; "|"; ident; "}" def testParser2 : TermParser := many (longestMatch [qualifiedP, parenIdentP, seqP, setCompP]) def testParser3 : TermParser := many (longestMatch [qualifiedP, seqP]) @[noinline] def test (p : TermParser) (s : String) : IO Unit := match p.test s with | Except.error msg := IO.println msg | Except.ok stx := IO.println "ok" -- IO.println stx -- IO.println "ok" def mkTestString1 : Nat → String → String | 0 s := s | (n+1) s := mkTestString1 n $ s ++ "{} /- /- comment2 -/ -/ " ++ "{" ++ toString n ++ "," ++ toString (n+1) ++ ", " ++ toString (n+2) ++ "}" ++ "(" ++ toString n ++ ", " ++ toString n ++ ") -- comment\n" def test1 (n : Nat) : IO Unit := let s := mkTestString1 n "" in test testParser1 s def mkTestString2 : Nat → String → String | 0 s := s | (n+1) s := mkTestString2 n $ s ++ "(xyz) /- /- comment2 -/ -/ " ++ "(x:y:z) -- comment1 \n" ++ "(x:y)" def test2 (n : Nat) : IO Unit := let s := mkTestString2 n "" in test testParser2 s def test3 (n : Nat) : IO Unit := let s := mkTestString2 n "" in test testParser3 s def main (xs : List String) : IO Unit := timeit "test2" (test2 xs.head.toNat) *> timeit "test3" (test3 xs.head.toNat)
0e8cf2de03d196e8cd0b1af788623641de66c11b
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/hott/types/bool.hlean
c25d5f1388b2d0825755e8529fe1a7d7198beb47
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,921
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Floris van Doorn Partially ported from the standard library -/ open eq eq.ops decidable namespace bool local attribute bor [reducible] local attribute band [reducible] theorem dichotomy (b : bool) : b = ff ⊎ b = tt := bool.cases_on b (sum.inl rfl) (sum.inr rfl) theorem cond_ff {A : Type} (t e : A) : cond ff t e = e := rfl theorem cond_tt {A : Type} (t e : A) : cond tt t e = t := rfl theorem eq_tt_of_ne_ff : Π {a : bool}, a ≠ ff → a = tt | @eq_tt_of_ne_ff tt H := rfl | @eq_tt_of_ne_ff ff H := absurd rfl H theorem eq_ff_of_ne_tt : Π {a : bool}, a ≠ tt → a = ff | @eq_ff_of_ne_tt tt H := absurd rfl H | @eq_ff_of_ne_tt ff H := rfl theorem absurd_of_eq_ff_of_eq_tt {B : Type} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B := absurd (H₁⁻¹ ⬝ H₂) ff_ne_tt theorem tt_bor (a : bool) : bor tt a = tt := rfl notation a || b := bor a b theorem bor_tt (a : bool) : a || tt = tt := bool.cases_on a rfl rfl theorem ff_bor (a : bool) : ff || a = a := bool.cases_on a rfl rfl theorem bor_ff (a : bool) : a || ff = a := bool.cases_on a rfl rfl theorem bor_self (a : bool) : a || a = a := bool.cases_on a rfl rfl theorem bor.comm (a b : bool) : a || b = b || a := by cases a; repeat (cases b | reflexivity) theorem bor.assoc (a b c : bool) : (a || b) || c = a || (b || c) := match a with | ff := by rewrite *ff_bor | tt := by rewrite *tt_bor end theorem or_of_bor_eq {a b : bool} : a || b = tt → a = tt ⊎ b = tt := bool.rec_on a (suppose ff || b = tt, have b = tt, from !ff_bor ▸ this, sum.inr this) (suppose tt || b = tt, sum.inl rfl) theorem bor_inl {a b : bool} (H : a = tt) : a || b = tt := by rewrite H theorem bor_inr {a b : bool} (H : b = tt) : a || b = tt := bool.rec_on a (by rewrite H) (by rewrite H) theorem ff_band (a : bool) : ff && a = ff := rfl theorem tt_band (a : bool) : tt && a = a := bool.cases_on a rfl rfl theorem band_ff (a : bool) : a && ff = ff := bool.cases_on a rfl rfl theorem band_tt (a : bool) : a && tt = a := bool.cases_on a rfl rfl theorem band_self (a : bool) : a && a = a := bool.cases_on a rfl rfl theorem band.comm (a b : bool) : a && b = b && a := bool.cases_on a (bool.cases_on b rfl rfl) (bool.cases_on b rfl rfl) theorem band.assoc (a b c : bool) : (a && b) && c = a && (b && c) := match a with | ff := by rewrite *ff_band | tt := by rewrite *tt_band end theorem band_elim_left {a b : bool} (H : a && b = tt) : a = tt := sum.elim (dichotomy a) (suppose a = ff, absurd (calc ff = ff && b : ff_band ... = a && b : this ... = tt : H) ff_ne_tt) (suppose a = tt, this) theorem band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt := by rewrite [H₁, H₂] theorem band_elim_right {a b : bool} (H : a && b = tt) : b = tt := band_elim_left (!band.comm ⬝ H) theorem bnot_bnot (a : bool) : bnot (bnot a) = a := bool.cases_on a rfl rfl theorem bnot_empty : bnot ff = tt := rfl theorem bnot_unit : bnot tt = ff := rfl theorem eq_tt_of_bnot_eq_ff {a : bool} : bnot a = ff → a = tt := bool.cases_on a (by contradiction) (λ h, rfl) theorem eq_ff_of_bnot_eq_tt {a : bool} : bnot a = tt → a = ff := bool.cases_on a (λ h, rfl) (by contradiction) definition bxor (x:bool) (y:bool) := cond x (bnot y) y /- HoTT-related stuff -/ open is_equiv equiv function is_trunc option unit decidable definition is_equiv_bnot [constructor] [instance] [priority 500] : is_equiv bnot := begin fapply is_equiv.mk, exact bnot, all_goals (intro b;cases b), do 6 reflexivity -- all_goals (focus (intro b;cases b;all_goals reflexivity)), end definition bnot_ne : Π(b : bool), bnot b ≠ b | bnot_ne tt := ff_ne_tt | bnot_ne ff := ne.symm ff_ne_tt definition equiv_bnot [constructor] : bool ≃ bool := equiv.mk bnot _ definition eq_bnot : bool = bool := ua equiv_bnot definition eq_bnot_ne_idp : eq_bnot ≠ idp := assume H : eq_bnot = idp, assert H2 : bnot = id, from !cast_ua_fn⁻¹ ⬝ ap cast H, absurd (ap10 H2 tt) ff_ne_tt theorem is_set_bool : is_set bool := _ theorem not_is_prop_bool_eq_bool : ¬ is_prop (bool = bool) := λ H, eq_bnot_ne_idp !is_prop.elim definition bool_equiv_option_unit [constructor] : bool ≃ option unit := begin fapply equiv.MK, { intro b, cases b, exact none, exact some star}, { intro u, cases u, exact ff, exact tt}, { intro u, cases u with u, reflexivity, cases u, reflexivity}, { intro b, cases b, reflexivity, reflexivity}, end definition tbool [constructor] : Set := trunctype.mk bool _ end bool
ea36135937b1993583074ce81d0f9b3449c9d89f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/pempty_auto.lean
2d2cdecb28d941db328b0ee9369a3ae5f6315e74
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,502
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.discrete_category import Mathlib.PostPort universes v u namespace Mathlib /-! # The empty category Defines a category structure on `pempty`, and the unique functor `pempty ⥤ C` for any category `C`. -/ namespace category_theory namespace functor /-- The canonical functor out of the empty category. -/ def empty (C : Type u) [category C] : discrete pempty ⥤ C := discrete.functor pempty.elim /-- Any two functors out of the empty category are isomorphic. -/ def empty_ext {C : Type u} [category C] (F : discrete pempty ⥤ C) (G : discrete pempty ⥤ C) : F ≅ G := discrete.nat_iso fun (x : discrete pempty) => pempty.elim x /-- Any functor out of the empty category is isomorphic to the canonical functor from the empty category. -/ def unique_from_empty {C : Type u} [category C] (F : discrete pempty ⥤ C) : F ≅ empty C := empty_ext F (empty C) /-- Any two functors out of the empty category are *equal*. You probably want to use `empty_ext` instead of this. -/ theorem empty_ext' {C : Type u} [category C] (F : discrete pempty ⥤ C) (G : discrete pempty ⥤ C) : F = G := ext (fun (x : discrete pempty) => pempty.elim x) fun (x _x : discrete pempty) (_x_1 : x ⟶ _x) => pempty.elim x end Mathlib
5412edb2a0bfcac73bedf0c2d772d6220bda24f8
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/specialize1.lean
8f473d397a8712f973ad1a1778eb0afb7e6f2b35
[ "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
668
lean
example (x y z : Prop) (f : x → y → z) (xp : x) (yp : y) : z := by specialize f xp yp assumption example (B C : Prop) (f : forall (A : Prop), A → C) (x : B) : C := by specialize f _ x exact f example (B C : Prop) (f : forall {A : Prop}, A → C) (x : B) : C := by specialize f x exact f example (B C : Prop) (f : forall {A : Prop}, A → C) (x : B) : C := by specialize @f _ x exact f example (X : Type) [Add X] (f : forall {A : Type} [Add A], A → A → A) (x : X) : X := by specialize f x x assumption def ex (f : Nat → Nat → Nat) : Nat := by specialize f _ _ exact f exact 10 exact 2 example : ex (· - ·) = 8 := rfl
b74ca54742cff1c0c89786a3f22f7452d02fc5e5
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/order/bounded_lattice.lean
82c56da92482b4d34a165b8acbfb4a3fbd9fac05
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
49,031
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 data.option.basic import logic.nontrivial import order.lattice import tactic.pi_instances /-! # ⊤ and ⊥, bounded lattices and variants This file defines top and bottom elements (greatest and least elements) of a type, the bounded variants of different kinds of lattices, sets up the typeclass hierarchy between them and provides instances for `Prop` and `fun`. ## Main declarations * `has_<top/bot> α`: Typeclasses to declare the `⊤`/`⊥` notation. * `order_<top/bot> α`: Order with a top/bottom element. * `with_<top/bot> α`: Equips `option α` with the order on `α` plus `none` as the top/bottom element. * `semilattice_<sup/inf>_<top/bot>`: Semilattice with a join/meet and a top/bottom element (all four combinations). Typical examples include `ℕ`. * `bounded_lattice α`: Lattice with a top and bottom element. * `distrib_lattice_bot α`: Distributive lattice with a bottom element. It captures the properties of `disjoint` that are common to `generalized_boolean_algebra` and `bounded_distrib_lattice`. * `bounded_distrib_lattice α`: Bounded and distributive lattice. Typical examples include `Prop` and `set α`. * `is_compl x y`: In a bounded lattice, predicate for "`x` is a complement of `y`". Note that in a non distributive lattice, an element can have several complements. * `is_complemented α`: Typeclass stating that any element of a lattice has a complement. ## Implementation notes We didn't define `distrib_lattice_top` because the dual notion of `disjoint` isn't really used anywhere. -/ /-! ### Top, bottom element -/ set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ @[notation_class] class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ @[notation_class] class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot @[priority 100] instance has_top_nonempty (α : Type u) [has_top α] : nonempty α := ⟨⊤⟩ @[priority 100] instance has_bot_nonempty (α : Type u) [has_bot α] : nonempty α := ⟨⊥⟩ attribute [pattern] has_bot.bot has_top.top /-- An `order_top` is a partial order with a greatest element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_top.antisymm h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨λ eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := λ h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := le_top.lt_iff_ne lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := λ ha, hb $ top_unique $ ha ▸ hab lemma eq_top_of_maximal (h : ∀ b, ¬ a < b) : a = ⊤ := or.elim (lt_or_eq_of_le le_top) (λ hlt, absurd hlt (h ⊤)) (λ he, he) end order_top lemma strict_mono.top_preimage_top' [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end /-- An `order_bot` is a partial order with a least element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := h.antisymm bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨λ eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, λ h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := λ h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := λ ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp only [lt_iff_le_not_le, not_iff_not.mpr le_bot_iff, true_and, bot_le], end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h lemma eq_bot_of_minimal (h : ∀ b, ¬ b < a) : a = ⊥ := or.elim (lt_or_eq_of_le bot_le) (λ hlt, absurd hlt (h ⊥)) (λ he, he.symm) end order_bot lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /-! ### Bounded lattice -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := λ x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := λ x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := λ x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := λ x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end /-- A `distrib_lattice_bot` is a distributive lattice with a least element. -/ class distrib_lattice_bot α extends distrib_lattice α, semilattice_inf_bot α, semilattice_sup_bot α /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice_bot α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨λ h, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [h, inf_le_right], λ h, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw inf_comm, exact inf_le_inf_left _ h } ... = ⊥ : h₂⟩ /-- Propositions form a bounded distributive lattice. -/ instance Prop.bounded_distrib_lattice : bounded_distrib_lattice Prop := { le := λ a b, a → b, le_refl := λ _, id, le_trans := λ a b c f g, g ∘ f, le_antisymm := λ a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := λ a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := λ a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := λ a b c H, or_iff_not_imp_left.2 $ λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩, top := true, le_top := λ a Ha, true.intro, bot := false, bot_le := @false.elim } noncomputable instance Prop.linear_order : linear_order Prop := { le_total := by intros p q; change (p → q) ∨ (q → p); tauto!, decidable_le := classical.dec_rel _, .. (_ : partial_order Prop) } @[simp] lemma le_Prop_eq : ((≤) : Prop → Prop → Prop) = (→) := rfl @[simp] lemma sup_Prop_eq : (⊔) = (∨) := rfl @[simp] lemma inf_Prop_eq : (⊓) = (∧) := rfl section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λ x, p x ∧ q x) := λ a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λ x, p x ∨ q x) := λ a b h, or.imp (m_p h) (m_q h) end logic instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) := { bot := λ _, ⊥, bot_le := λ x a, bot_le, .. pi.partial_order } /-! ### Function lattices -/ instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) : (⊥ : Π i, α i) i = ⊥ := rfl instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) : (⊤ : Π i, α i) i = ⊤ := rfl instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] : semilattice_sup (Π i, α i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] : semilattice_inf (Π i, α i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] : semilattice_inf_bot (Π i, α i) := by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] : semilattice_inf_top (Π i, α i) := by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] : semilattice_sup_bot (Π i, α i) := by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] : semilattice_sup_top (Π i, α i) := by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance pi.distrib_lattice {ι : Type*} {α : ι → Type*} [Π i, distrib_lattice (α i)] : distrib_lattice (Π i, α i) := by refine_struct { .. pi.lattice }; tactic.pi_instance_derive_field instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] : bounded_lattice (Π i, α i) := { .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot } instance pi.distrib_lattice_bot {ι : Type*} {α : ι → Type*} [Π i, distrib_lattice_bot (α i)] : distrib_lattice_bot (Π i, α i) := { .. pi.distrib_lattice, .. pi.order_bot } instance pi.bounded_distrib_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_distrib_lattice (α i)] : bounded_distrib_lattice (Π i, α i) := { .. pi.bounded_lattice, .. pi.distrib_lattice } lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊥ : α) := eq_bot_mono le_top (eq.symm hα) lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊤ : α) := eq_top_mono bot_le hα lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) : subsingleton α := ⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩ lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) : subsingleton α := subsingleton_of_top_le_bot (ge_of_eq hα) lemma subsingleton_iff_bot_eq_top {α : Type*} [bounded_lattice α] : (⊥ : α) = (⊤ : α) ↔ subsingleton α := ⟨subsingleton_of_bot_eq_top, λ h, by exactI subsingleton.elim ⊥ ⊤⟩ /-! ### `with_bot`, `with_top` -/ /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl @[simp] theorem bot_ne_coe (a : α) : ⊥ ≠ (a : with_bot α) . @[simp] theorem coe_ne_bot (a : α) : (a : with_bot α) ≠ ⊥ . /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_eliminator] def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) : Π (n : with_bot α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance : can_lift (with_bot α) α := { coe := coe, cond := λ r, r ≠ ⊥, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [preorder α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h @[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} : a.get_or_else ⊥ ≤ b ↔ a ≤ b := by cases a; simp [none_eq_bot, some_eq_coe] instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤) | none x := is_true $ λ a h, option.no_confusion h | (some x) (some y) := if h : x ≤ y then is_true (some_le_some.2 h) else is_false $ by simp * | (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩ instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance [partial_order α] [is_total α (≤)] : is_total (with_bot α) (≤) := { total := λ a b, match a, b with | none , _ := or.inl bot_le | _ , none := or.inr bot_le | some x, some y := by simp only [some_le_some, total_of] end } instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, decidable_le := with_bot.decidable_le, decidable_lt := with_bot.decidable_lt, ..with_bot.partial_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_bot α) = a ⊔ b := rfl instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_bot α) = a ⊓ b := rfl instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] @[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_bot α) = min x y := by simp [min, ite_cast] @[norm_cast] -- this is not marked simp because the corresponding with_top lemmas are used lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_bot α) = max x y := by simp [max, ite_cast] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ λ a b, match a, b with | a, none := λ h : a < ⊥, (not_lt_bot h).elim | none, some b := λ h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_eliminator] def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) : Π (n : with_top α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem le_none [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem some_lt_none [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance : can_lift (with_top α) α := { coe := coe, cond := λ r, r ≠ ⊤, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none theorem coe_lt_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b) | (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe] | none := by simp [none_eq_top, coe_lt_top] lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := λ h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) := λ x y, @with_bot.decidable_le (order_dual α) _ _ y x instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) := λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x instance [partial_order α] [is_total α (≤)] : is_total (with_top α) (≤) := { total := λ a b, match a, b with | none , _ := or.inr le_top | _ , none := or.inl le_top | some x, some y := by simp only [some_le_some, total_of] end } instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, decidable_le := with_top.decidable_le, decidable_lt := with_top.decidable_lt, ..with_top.partial_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] @[simp, norm_cast] lemma coe_min [linear_order α] (x y : α) : ((min x y : α) : with_top α) = min x y := by simp [min, ite_cast] @[simp, norm_cast] lemma coe_max [linear_order α] (x y : α) : ((max x y : α) : with_top α) = max x y := by simp [max, ite_cast] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ λ a b, match a, b with | none, a := λ h : ⊤ < a, (not_top_lt h).elim | some a, none := λ h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := λ h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top /-! ### Subtype, order dual, product lattices -/ namespace subtype /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a `⊔`-`⊤`-semilattice if `⊤` and `⊔` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_sup_top [semilattice_sup_top α] {P : α → Prop} (Ptop : P ⊤) (Psup : ∀{{x y}}, P x → P y → P (x ⊔ y)) : semilattice_sup_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. See note [reducible non-instances]. -/ @[reducible] protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_inf Pinf } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } /- If you define `distrib_lattice_top`, add the `order_dual` instances between `distrib_lattice_bot` and `distrib_lattice_top` here -/ instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := λ a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := λ a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [distrib_lattice_bot α] [distrib_lattice_bot β] : distrib_lattice_bot (α × β) := { .. prod.distrib_lattice α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod /-! ### Disjointness and complements -/ section disjoint section semilattice_inf_bot variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } lemma disjoint.eq_bot_of_le {a b : α} (hab : disjoint a b) (h : a ≤ b) : a = ⊥ := eq_bot_iff.2 (by rwa ←inf_eq_left.2 h) lemma disjoint.of_disjoint_inf_of_le {a b c : α} (h : disjoint (a ⊓ b) c) (hle : a ≤ c) : disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_left.trans hle)] lemma disjoint.of_disjoint_inf_of_le' {a b c : α} (h : disjoint (a ⊓ b) c) (hle : b ≤ c) : disjoint a b := by rw [disjoint_iff, h.eq_bot_of_le (inf_le_right.trans hle)] end semilattice_inf_bot section bounded_lattice variables [bounded_lattice α] {a : α} @[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff] @[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff] lemma eq_bot_of_disjoint_absorbs {a b : α} (w : disjoint a b) (h : a ⊔ b = a) : b = ⊥ := begin rw disjoint_iff at w, rw [←w, right_eq_inf], rwa sup_eq_left at h, end end bounded_lattice section distrib_lattice_bot variables [distrib_lattice_bot α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b := (λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le) lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b := @le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le) ((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left)) end distrib_lattice_bot section semilattice_inf_bot variables [semilattice_inf_bot α] {a b : α} (c : α) lemma disjoint.inf_left (h : disjoint a b) : disjoint (a ⊓ c) b := h.mono_left inf_le_left lemma disjoint.inf_left' (h : disjoint a b) : disjoint (c ⊓ a) b := h.mono_left inf_le_right lemma disjoint.inf_right (h : disjoint a b) : disjoint a (b ⊓ c) := h.mono_right inf_le_left lemma disjoint.inf_right' (h : disjoint a b) : disjoint a (c ⊓ b) := h.mono_right inf_le_right end semilattice_inf_bot end disjoint section is_compl /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := by { rw disjoint_iff, exact h.inf_left_eq_bot_iff } lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := h.disjoint_right_iff.symm lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq section variables [bounded_lattice α] {x : α} lemma eq_top_of_is_compl_bot (h : is_compl x ⊥) : x = ⊤ := sup_bot_eq.symm.trans h.sup_eq_top lemma eq_top_of_bot_is_compl (h : is_compl ⊥ x) : x = ⊤ := eq_top_of_is_compl_bot h.symm lemma eq_bot_of_is_compl_top (h : is_compl x ⊤) : x = ⊥ := eq_top_of_is_compl_bot h.to_order_dual lemma eq_bot_of_top_is_compl (h : is_compl ⊤ x) : x = ⊥ := eq_top_of_bot_is_compl h.to_order_dual end /-- A complemented bounded lattice is one where every element has a (not necessarily unique) complement. -/ class is_complemented (α) [bounded_lattice α] : Prop := (exists_is_compl : ∀ (a : α), ∃ (b : α), is_compl a b) export is_complemented (exists_is_compl) namespace is_complemented variables [bounded_lattice α] [is_complemented α] instance : is_complemented (order_dual α) := ⟨λ a, let ⟨b, hb⟩ := exists_is_compl (show α, from a) in ⟨b, hb.to_order_dual⟩⟩ end is_complemented end is_compl section nontrivial variables [bounded_lattice α] [nontrivial α] lemma bot_ne_top : (⊥ : α) ≠ ⊤ := λ H, not_nontrivial_iff_subsingleton.mpr (subsingleton_of_bot_eq_top H) ‹_› lemma top_ne_bot : (⊤ : α) ≠ ⊥ := ne.symm bot_ne_top end nontrivial namespace bool -- Could be generalised to `bounded_distrib_lattice` and `is_complemented` instance : bounded_lattice bool := { top := tt, le_top := λ x, le_tt, bot := ff, bot_le := λ x, ff_le, .. (infer_instance : lattice bool)} end bool section bool @[simp] lemma top_eq_tt : ⊤ = tt := rfl @[simp] lemma bot_eq_ff : ⊥ = ff := rfl end bool
8df75e6deb13d6e642d8399e8b1737f710d6cdd0
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world05/level04.lean
75f7874cbe10b809582172983c1e0b1dc1a8d74f
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
159
lean
example (P Q R S T U: Type) (p : P) (h : P → Q) (i : Q → R) (j : Q → T) (k : S → T) (l : T → U) : U := begin apply l, apply j, apply h, exact p, end
1de6ae31af8d467ba161d9f0a517add1c47b1452
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Tactic/Mathlib/Squeeze.lean
5035ee2dff1f008794b070acdec9655051a09546
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
2,105
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathport.Syntax.Translate.Tactic.Basic import Mathport.Syntax.Translate.Tactic.Lean3 open Lean namespace Mathport.Translate.Tactic open Mathport.Translate.Parser -- # tactic.simpa def trSimpaCore (autoUnfold trace : Bool) (parseCfg : TacM (Option (Spanned AST3.Expr))) : TacM Syntax.Tactic := do let o := optTk (← parse onlyFlag) let hs ← trSimpArgs (← parse simpArgList) let attrs := (← parse (tk "with" *> ident*)?).getD #[] let hs := (hs ++ attrs.map trSimpExt).asNonempty let e ← liftM $ (← parse (tk "using" *> pExpr)?).mapM trExpr let (cfg, disch) ← parseSimpConfig (← parseCfg) let cfg ← mkConfigStx? (cfg.bind quoteSimpConfig) let rest ← `(Std.Tactic.Simpa.simpaArgsRest| $[$cfg:config]? $(disch)? $[only%$o]? $[[$hs,*]]? $[using $e]?) match autoUnfold, trace with | true, true => `(tactic| simpa?! $rest) | false, true => `(tactic| simpa? $rest) | true, false => `(tactic| simpa! $rest) | false, false => `(tactic| simpa $rest) @[tr_tactic simpa] def trSimpa : TacM Syntax.Tactic := do let unfold ← parse (tk "!")?; let squeeze ← parse (tk "?")? trSimpaCore unfold.isSome squeeze.isSome expr? -- # tactic.squeeze @[tr_tactic squeeze_scope] def trSqueezeScope : TacM Syntax.Tactic := do `(tactic| squeeze_scope $(← trBlock (← itactic)):tacticSeq) @[tr_tactic squeeze_simp] def trSqueezeSimp : TacM Syntax.Tactic := do let _ques ← parse (pure ()) <* parse (tk "?")?; let bang ← parse (tk "!")? trSimpCore bang.isSome true @[tr_tactic squeeze_simpa] def trSqueezeSimpa : TacM Syntax.Tactic := do let _ques ← parse (pure ()) <* parse (tk "?")?; let bang ← parse (tk "!")? trSimpaCore bang.isSome true expr? @[tr_tactic squeeze_dsimp] def trSqueezeDSimp : TacM Syntax.Tactic := do let _ques ← parse (pure ()) <* parse (tk "?")?; let bang ← parse (tk "!")? trDSimpCore bang.isSome true (return (← parse (structInst)?).map .dummy)
c42492f1ef8b53b53de0f1ee73c55f71fc4256be
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/916.lean
7223b859ab955e7da587edaaaa46d2196cf4984a
[ "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
64
lean
example : Id Nat := do let mut x := 1 have x : Nat := 2 x
da3897debdba03d73f5a95f3e4f8d23793f2444b
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/cubical/pathover2.hlean
e0a41b123f96c321347d7fe7cf9d59465b7e3752
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
5,975
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 Coherence conditions for operations on pathovers -/ open function equiv namespace eq variables {A A' A'' : Type} {B B' : A → Type} {B'' : A' → Type} {C : Π⦃a⦄, B a → Type} {a a₂ a₃ a₄ : A} {p p' p'' : a = a₂} {p₂ p₂' : a₂ = a₃} {p₃ : a₃ = a₄} {p₁₃ : a = a₃} {a' : A'} {b b' : B a} {b₂ b₂' : B a₂} {b₃ : B a₃} {b₄ : B a₄} {c : C b} {c₂ : C b₂} definition pathover_ap_id (q : b =[p] b₂) : pathover_ap B id q = change_path (ap_id p)⁻¹ q := by induction q; reflexivity definition pathover_ap_compose (B : A'' → Type) (g : A' → A'') (f : A → A') {b : B (g (f a))} {b₂ : B (g (f a₂))} (q : b =[p] b₂) : pathover_ap B (g ∘ f) q = change_path (ap_compose g f p)⁻¹ (pathover_ap B g (pathover_ap (B ∘ g) f q)) := by induction q; reflexivity definition pathover_ap_compose_rev (B : A'' → Type) (g : A' → A'') (f : A → A') {b : B (g (f a))} {b₂ : B (g (f a₂))} (q : b =[p] b₂) : pathover_ap B g (pathover_ap (B ∘ g) f q) = change_path (ap_compose g f p) (pathover_ap B (g ∘ f) q) := by induction q; reflexivity definition pathover_of_tr_eq_idp (r : b = b') : pathover_of_tr_eq r = pathover_idp_of_eq r := idp definition pathover_of_tr_eq_eq_concato (r : p ▸ b = b₂) : pathover_of_tr_eq r = pathover_tr p b ⬝o pathover_idp_of_eq r := by induction r; induction p; reflexivity definition apo011_eq_apo11_apd (f : Πa, B a → A') (p : a = a₂) (q : b =[p] b₂) : apo011 f p q = eq_of_pathover (apo11 (apd f p) q) := by induction q; reflexivity definition change_path_con (q : p = p') (q' : p' = p'') (r : b =[p] b₂) : change_path (q ⬝ q') r = change_path q' (change_path q r) := by induction q; induction q'; reflexivity definition change_path_invo (q : p = p') (r : b =[p] b₂) : change_path (inverse2 q) r⁻¹ᵒ = (change_path q r)⁻¹ᵒ := by induction q; reflexivity definition change_path_cono (q : p = p') (q₂ : p₂ = p₂') (r : b =[p] b₂) (r₂ : b₂ =[p₂] b₃): change_path (q ◾ q₂) (r ⬝o r₂) = change_path q r ⬝o change_path q₂ r₂ := by induction q; induction q₂; reflexivity definition pathover_of_pathover_ap_invo (B' : A' → Type) (f : A → A') {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[ap f p] b₂) : pathover_of_pathover_ap B' f (change_path (ap_inv f p)⁻¹ q⁻¹ᵒ) = (pathover_of_pathover_ap B' f q)⁻¹ᵒ:= by induction p; eapply idp_rec_on q; reflexivity definition pathover_of_pathover_ap_cono (B' : A' → Type) (f : A → A') {b : B' (f a)} {b₂ : B' (f a₂)} {b₃ : B' (f a₃)} (q : b =[ap f p] b₂) (q₂ : b₂ =[ap f p₂] b₃) : pathover_of_pathover_ap B' f (change_path (ap_con f p p₂)⁻¹ (q ⬝o q₂)) = pathover_of_pathover_ap B' f q ⬝o pathover_of_pathover_ap B' f q₂ := by induction p; induction p₂; eapply idp_rec_on q; eapply idp_rec_on q₂; reflexivity definition pathover_ap_pathover_of_pathover_ap (P : A'' → Type) (g : A' → A'') (f : A → A') {p : a = a₂} {b : P (g (f a))} {b₂ : P (g (f a₂))} (q : b =[ap f p] b₂) : pathover_ap P (g ∘ f) (pathover_of_pathover_ap (P ∘ g) f q) = change_path (ap_compose g f p)⁻¹ (pathover_ap P g q) := by induction p; eapply (idp_rec_on q); reflexivity definition change_path_pathover_of_pathover_ap (B' : A' → Type) (f : A → A') {p p' : a = a₂} (r : p = p') {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[ap f p] b₂) : change_path r (pathover_of_pathover_ap B' f q) = pathover_of_pathover_ap B' f (change_path (ap02 f r) q) := by induction r; reflexivity definition pathover_ap_change_path (B' : A' → Type) (f : A → A') {p p' : a = a₂} (r : p = p') {b : B' (f a)} {b₂ : B' (f a₂)} (q : b =[p] b₂) : pathover_ap B' f (change_path r q) = change_path (ap02 f r) (pathover_ap B' f q) := by induction r; reflexivity definition change_path_equiv [constructor] (b : B a) (b₂ : B a₂) (q : p = p') : (b =[p] b₂) ≃ (b =[p'] b₂) := begin fapply equiv.MK, { exact change_path q}, { exact change_path q⁻¹}, { intro r, induction q, reflexivity}, { intro r, induction q, reflexivity}, end definition apd_ap {B : A' → Type} (g : Πb, B b) (f : A → A') (p : a = a₂) : apd g (ap f p) = pathover_ap B f (apd (λx, g (f x)) p) := by induction p; reflexivity definition apd_eq_apd_ap {B : A' → Type} (g : Πb, B b) (f : A → A') (p : a = a₂) : apd (λx, g (f x)) p = pathover_of_pathover_ap B f (apd g (ap f p)) := by induction p; reflexivity definition ap_compose_ap02_constant {A B C : Type} {a a' : A} (p : a = a') (b : B) (c : C) : ap_compose (λc, b) (λa, c) p ⬝ ap02 (λc, b) (ap_constant p c) = ap_constant p b := by induction p; reflexivity theorem apd_constant (b : B'' a') (p : a = a) : pathover_ap B'' (λa, a') (apd (λa, b) p) = change_path (ap_constant p a')⁻¹ idpo := begin rewrite [apd_eq_apd_ap _ _ p], let y := !change_path_of_pathover (apd (apd id) (ap_constant p b))⁻¹ᵒ, rewrite -y, esimp, refine !pathover_ap_pathover_of_pathover_ap ⬝ _, rewrite pathover_ap_change_path, rewrite -change_path_con, apply ap (λx, change_path x idpo), unfold ap02, rewrite [ap_inv,-con_inv], apply inverse2, apply ap_compose_ap02_constant end definition apd_change_path {B : A → Type} {a a₂ : A} (f : Πa, B a) {p p' : a = a₂} (s : p = p') : apd f p' = change_path s (apd f p) := by induction s; reflexivity definition cono_invo_eq_idpo {q q' : b =[p] b₂} (r : q = q') : change_path (con.right_inv p) (q ⬝o q'⁻¹ᵒ) = idpo := by induction r; induction q; reflexivity end eq
3abb5de7f3f20351a26c52c36da1bcf7f3d5c9f0
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/analysis/calculus/parametric_integral.lean
be34d75e7fda7ea2068f4bf4a24e615c6cbe9844
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,566
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import measure_theory.integral.set_integral import analysis.calculus.mean_value /-! # Derivatives of integrals depending on parameters A parametric integral is a function with shape `f = λ x : H, ∫ a : α, F x a ∂μ` for some `F : H → α → E`, where `H` and `E` are normed spaces and `α` is a measured space with measure `μ`. We already know from `continuous_of_dominated` in `measure_theory.integral.bochner` how to guarantee that `f` is continuous using the dominated convergence theorem. In this file, we want to express the derivative of `f` as the integral of the derivative of `F` with respect to `x`. ## Main results As explained above, all results express the derivative of a parametric integral as the integral of a derivative. The variations come from the assumptions and from the different ways of expressing derivative, especially Fréchet derivatives vs elementary derivative of function of one real variable. * `has_fderiv_at_of_dominated_loc_of_lip`: this version assumes `F x` is ae-measurable for x near `x₀`, `F x₀` is integrable, `λ x, F x a` has derivative `F' a : H →L[ℝ] E` at `x₀` which is ae-measurable, `λ x, F x a` is locally Lipschitz near `x₀` for almost every `a`, with a Lipschitz bound which is integrable with respect to `a`. A subtle point is that the "near x₀" in the last condition has to be uniform in `a`. This is controlled by a positive number `ε`. * `has_fderiv_at_of_dominated_of_fderiv_le`: this version assume `λ x, F x a` has derivative `F' x a` for `x` near `x₀` and `F' x` is bounded by an integrable function independent from `x` near `x₀`. `has_deriv_at_of_dominated_loc_of_lip` and `has_deriv_at_of_dominated_loc_of_deriv_le ` are versions of the above two results that assume `H = ℝ` and use the high-school derivative `deriv` instead of Fréchet derivative `fderiv`. -/ noncomputable theory open topological_space measure_theory filter metric open_locale topological_space filter variables {α : Type*} [measurable_space α] {μ : measure α} {E : Type*} [normed_group E] [normed_space ℝ E] [complete_space E] [second_countable_topology E] [measurable_space E] [borel_space E] {H : Type*} [normed_group H] [normed_space ℝ H] [second_countable_topology $ H →L[ℝ] E] /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` with integrable Lipschitz bound (with a ball radius independent of `a`), and `F x` is ae-measurable for `x` in the same ball. See `has_fderiv_at_of_dominated_loc_of_lip` for a slightly more general version. -/ lemma has_fderiv_at_of_dominated_loc_of_lip' {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ x ∈ ball x₀ ε, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have nneg : ∀ x, 0 ≤ ∥x - x₀∥⁻¹ := λ x, inv_nonneg.mpr (norm_nonneg _) , set b : α → ℝ := λ a, |bound a|, have b_int : integrable b μ := bound_integrable.norm, have b_nonneg : ∀ a, 0 ≤ b a := λ a, abs_nonneg _, have hF_int' : ∀ x ∈ ball x₀ ε, integrable (F x) μ, { intros x x_in, have : ∀ᵐ a ∂μ, ∥F x₀ a - F x a∥ ≤ ε * ∥(bound a : ℝ)∥, { apply h_lipsch.mono, intros a ha, rw lipschitz_on_with_iff_norm_sub_le at ha, apply (ha x₀ x₀_in x x_in).trans, rw [mul_comm, real.coe_nnabs, real.norm_eq_abs], rw [mem_ball, dist_eq_norm, norm_sub_rev] at x_in, exact mul_le_mul_of_nonneg_right (le_of_lt x_in) (abs_nonneg _) }, exact integrable_of_norm_sub_le (hF_meas x x_in) hF_int (integrable.const_mul bound_integrable.norm ε) this }, have hF'_int : integrable F' μ, { have : ∀ᵐ a ∂μ, ∥F' a∥ ≤ b a, { apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_diff, ha_lip⟩, exact ha_diff.le_of_lip (ball_mem_nhds _ ε_pos) ha_lip }, exact b_int.mono' hF'_meas this }, refine ⟨hF'_int, _⟩, have h_ball: ball x₀ ε ∈ 𝓝 x₀ := ball_mem_nhds x₀ ε_pos, have : ∀ᶠ x in 𝓝 x₀, ∥x - x₀∥⁻¹ * ∥∫ a, F x a ∂μ - ∫ a, F x₀ a ∂μ - (∫ a, F' a ∂μ) (x - x₀)∥ = ∥∫ a, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀)) ∂μ∥, { apply mem_of_superset (ball_mem_nhds _ ε_pos), intros x x_in, rw [set.mem_set_of_eq, ← norm_smul_of_nonneg (nneg _), integral_smul, integral_sub, integral_sub, ← continuous_linear_map.integral_apply hF'_int], exacts [hF_int' x x_in, hF_int, (hF_int' x x_in).sub hF_int, hF'_int.apply_continuous_linear_map _] }, rw [has_fderiv_at_iff_tendsto, tendsto_congr' this, ← tendsto_zero_iff_norm_tendsto_zero, ← show ∫ (a : α), ∥x₀ - x₀∥⁻¹ • (F x₀ a - F x₀ a - (F' a) (x₀ - x₀)) ∂μ = 0, by simp], apply tendsto_integral_filter_of_dominated_convergence, { apply is_countably_generated_nhds }, { filter_upwards [h_ball], intros x x_in, apply ae_measurable.const_smul, exact ((hF_meas _ x_in).sub (hF_meas _ x₀_in)).sub (hF'_meas.apply_continuous_linear_map _) }, { simp [measurable_const] }, { apply mem_of_superset h_ball, intros x hx, apply (h_diff.and h_lipsch).mono, rintros a ⟨ha_deriv, ha_bound⟩, show ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ ≤ b a + ∥F' a∥, replace ha_bound : ∥F x a - F x₀ a∥ ≤ b a * ∥x - x₀∥, { rw lipschitz_on_with_iff_norm_sub_le at ha_bound, exact ha_bound _ hx _ x₀_in }, calc ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥ = ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a) - ∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : by rw smul_sub ... ≤ ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a)∥ + ∥∥x - x₀∥⁻¹ • F' a (x - x₀)∥ : norm_sub_le _ _ ... = ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a∥ + ∥x - x₀∥⁻¹ * ∥F' a (x - x₀)∥ : by { rw [norm_smul_of_nonneg, norm_smul_of_nonneg] ; exact nneg _} ... ≤ ∥x - x₀∥⁻¹ * (b a * ∥x - x₀∥) + ∥x - x₀∥⁻¹ * (∥F' a∥ * ∥x - x₀∥) : add_le_add _ _ ... ≤ b a + ∥F' a∥ : _, exact mul_le_mul_of_nonneg_left ha_bound (nneg _), apply mul_le_mul_of_nonneg_left ((F' a).le_op_norm _) (nneg _), by_cases h : ∥x - x₀∥ = 0, { simpa [h] using add_nonneg (b_nonneg a) (norm_nonneg (F' a)) }, { field_simp [h] } }, { exact b_int.add hF'_int.norm }, { apply h_diff.mono, intros a ha, suffices : tendsto (λ x, ∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))) (𝓝 x₀) (𝓝 0), by simpa, rw tendsto_zero_iff_norm_tendsto_zero, have : (λ x, ∥x - x₀∥⁻¹ * ∥F x a - F x₀ a - F' a (x - x₀)∥) = λ x, ∥∥x - x₀∥⁻¹ • (F x a - F x₀ a - F' a (x - x₀))∥, { ext x, rw norm_smul_of_nonneg (nneg _) }, rwa [has_fderiv_at_iff_tendsto, this] at ha }, end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on a ball around `x₀` for ae `a` (with a ball radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_loc_of_lip {F : H → α → E} {F' : α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) (h_lip : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' a) x₀) : integrable F' μ ∧ has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin obtain ⟨ε', ε'_pos, h'⟩ : ∃ ε' > 0, ∀ x ∈ ball x₀ ε', ae_measurable (F x) μ, by simpa using nhds_basis_ball.eventually_iff.mp hF_meas, set δ := min ε ε', have δ_pos : 0 < δ := lt_min ε_pos ε'_pos, replace h' : ∀ x, x ∈ ball x₀ δ → ae_measurable (F x) μ, { intros x x_in, exact h' _ (ball_subset_ball (min_le_right ε ε') x_in) }, replace h_lip : ∀ᵐ (a : α) ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ δ), { apply h_lip.mono, intros a lip, exact lip.mono (ball_subset_ball $ min_le_left ε ε') }, apply has_fderiv_at_of_dominated_loc_of_lip' δ_pos ; assumption end /-- Differentiation under integral of `x ↦ ∫ F x a` at a given point `x₀`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on a ball around `x₀` for ae `a` with derivative norm uniformly bounded by an integrable function (the ball radius is independent of `a`), and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_fderiv_at_of_dominated_of_fderiv_le {F : H → α → E} {F' : H → α → (H →L[ℝ] E)} {x₀ : H} {bound : α → ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_fderiv_at (λ x, F x a) (F' x a) x) : has_fderiv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_fderiv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ x, F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, refine (convex_ball _ _).lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x x_in, (ha_deriv x x_in).has_fderiv_within_at) (λ x x_in, _), rw [← nnreal.coe_le_coe, coe_nnnorm, real.coe_nnabs], exact (ha_bound x x_in).trans (le_abs_self _) }, exact (has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀).2 end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is locally Lipschitz on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with integrable Lipschitz bound, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_lip {F : ℝ → α → E} {F' : α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable F' μ) {bound : α → ℝ} (h_lipsch : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs $ bound a) (λ x, F x a) (ball x₀ ε)) (bound_integrable : integrable (bound : α → ℝ) μ) (h_diff : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' a) x₀) : (integrable F' μ) ∧ has_deriv_at (λ x, ∫ a, F x a ∂μ) (∫ a, F' a ∂μ) x₀ := begin have hm := (continuous_linear_map.smul_rightL ℝ ℝ E 1).continuous.measurable.comp_ae_measurable hF'_meas, cases has_fderiv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hm h_lipsch bound_integrable h_diff with hF'_int key, replace hF'_int : integrable F' μ, { rw [← integrable_norm_iff hm] at hF'_int, simpa only [integrable_norm_iff, hF'_meas, one_mul, norm_one, continuous_linear_map.norm_smul_rightL_apply] using hF'_int}, refine ⟨hF'_int, _⟩, simp_rw has_deriv_at_iff_has_fderiv_at at h_diff ⊢, rwa continuous_linear_map.integral_comp_comm _ hF'_int at key, all_goals { apply_instance, }, end /-- Derivative under integral of `x ↦ ∫ F x a` at a given point `x₀ : ℝ`, assuming `F x₀` is integrable, `x ↦ F x a` is differentiable on an interval around `x₀` for ae `a` (with interval radius independent of `a`) with derivative uniformly bounded by an integrable function, and `F x` is ae-measurable for `x` in a possibly smaller neighborhood of `x₀`. -/ lemma has_deriv_at_of_dominated_loc_of_deriv_le {F : ℝ → α → E} {F' : ℝ → α → E} {x₀ : ℝ} {ε : ℝ} (ε_pos : 0 < ε) (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (hF_int : integrable (F x₀) μ) (hF'_meas : ae_measurable (F' x₀) μ) {bound : α → ℝ} (h_bound : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, ∥F' x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_diff : ∀ᵐ a ∂μ, ∀ x ∈ ball x₀ ε, has_deriv_at (λ x, F x a) (F' x a) x) : (integrable (F' x₀) μ) ∧ has_deriv_at (λn, ∫ a, F n a ∂μ) (∫ a, F' x₀ a ∂μ) x₀ := begin have x₀_in : x₀ ∈ ball x₀ ε := mem_ball_self ε_pos, have diff_x₀ : ∀ᵐ a ∂μ, has_deriv_at (λ x, F x a) (F' x₀ a) x₀ := h_diff.mono (λ a ha, ha x₀ x₀_in), have : ∀ᵐ a ∂μ, lipschitz_on_with (real.nnabs (bound a)) (λ (x : ℝ), F x a) (ball x₀ ε), { apply (h_diff.and h_bound).mono, rintros a ⟨ha_deriv, ha_bound⟩, refine (convex_ball _ _).lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x x_in, (ha_deriv x x_in).has_deriv_within_at) (λ x x_in, _), rw [← nnreal.coe_le_coe, coe_nnnorm, real.coe_nnabs], exact (ha_bound x x_in).trans (le_abs_self _) }, exact has_deriv_at_of_dominated_loc_of_lip ε_pos hF_meas hF_int hF'_meas this bound_integrable diff_x₀ end
3539c505069b85e24747816b943894f3ef95a6eb
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/sig6.lean
620d7b1be9f8fa1516ce0c257cd2c6dde48ca47e
[ "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
510
lean
variables A B : (Type U) variables t1 t2 : A ⨯ B axiom pair_Ax {A : (Type U)} {B : A → (Type U)} (p : sig x, B x) : (pair (proj1 p) (proj2 p) : sig x, B x) = p theorem spairext {A B : (Type U)} {p1 p2 : A ⨯ B} (H1 : proj1 p1 = proj1 p2) (H2 : proj2 p1 = proj2 p2) : p1 = p2 := calc p1 = (pair (proj1 p1) (proj2 p1)) : symm (pair_Ax p1) ... = (pair (proj1 p2) (proj2 p1)) : { H1 } ... = (pair (proj1 p2) (proj2 p2)) : { H2 } ... = p2 : pair_Ax p2
a39632f81dc9dd5571d572df644e69459801c2dd
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/calcBug.lean
f04caf586bac34bdb682b86d9eb6061ab4573018
[ "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
328
lean
namespace Hidden open Nat theorem zero_add (n : Nat) : 0 + n = n := Nat.recOn (motive := fun x => 0 + x = x) n (show 0 + 0 = 0 from rfl) (fun (n : Nat) (ih : 0 + n = n) => show 0 + succ n = succ n from calc 0 + succ n = succ (0 + n) := rfl _ = succ n := by rw [ih]) end Hidden
cebbf1141ff1c2402bb3d81a433ee394c2b99590
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/group_action/prod.lean
22232fa2d0a0fc49c6b628b11e737b7d4cfac8db
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,242
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import algebra.group.prod import group_theory.group_action.defs /-! # Prod instances for additive and multiplicative actions This file defines instances for binary product of additive and multiplicative actions and provides scalar multiplication as a homomorphism from `α × β` to `β`. ## Main declarations * `smul_mul_hom`/`smul_monoid_hom`: Scalar multiplication bundled as a multiplicative/monoid homomorphism. ## See also * `group_theory.group_action.option` * `group_theory.group_action.pi` * `group_theory.group_action.sigma` * `group_theory.group_action.sum` -/ variables {M N P E α β : Type*} namespace prod section variables [has_smul M α] [has_smul M β] [has_smul N α] [has_smul N β] (a : M) (x : α × β) @[to_additive prod.has_vadd] instance : has_smul M (α × β) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp, to_additive] theorem smul_fst : (a • x).1 = a • x.1 := rfl @[simp, to_additive] theorem smul_snd : (a • x).2 = a • x.2 := rfl @[simp, to_additive] theorem smul_mk (a : M) (b : α) (c : β) : a • (b, c) = (a • b, a • c) := rfl @[to_additive] theorem smul_def (a : M) (x : α × β) : a • x = (a • x.1, a • x.2) := rfl @[simp, to_additive] theorem smul_swap : (a • x).swap = a • x.swap := rfl lemma smul_zero_mk {α : Type*} [monoid M] [add_monoid α] [distrib_mul_action M α] (a : M) (c : β) : a • ((0 : α), c) = (0, a • c) := by rw [prod.smul_mk, smul_zero] lemma smul_mk_zero {β : Type*} [monoid M] [add_monoid β] [distrib_mul_action M β] (a : M) (b : α) : a • (b, (0 : β)) = (a • b, 0) := by rw [prod.smul_mk, smul_zero] variables [has_pow α E] [has_pow β E] @[to_additive has_smul] instance has_pow : has_pow (α × β) E := { pow := λ p c, (p.1 ^ c, p.2 ^ c) } @[simp, to_additive smul_snd, to_additive_reorder 6] lemma pow_fst (p : α × β) (c : E) : (p ^ c).fst = p.fst ^ c := rfl @[simp, to_additive smul_snd, to_additive_reorder 6] lemma pow_snd (p : α × β) (c : E) : (p ^ c).snd = p.snd ^ c := rfl /- Note that the `c` arguments to this lemmas cannot be in the more natural right-most positions due to limitations in `to_additive` and `to_additive_reorder`, which will silently fail to reorder more than two adjacent arguments -/ @[simp, to_additive smul_mk, to_additive_reorder 6] lemma pow_mk (c : E) (a : α) (b : β) : (prod.mk a b) ^ c = prod.mk (a ^ c) (b ^ c) := rfl @[to_additive smul_def, to_additive_reorder 6] lemma pow_def (p : α × β) (c : E) : p ^ c = (p.1 ^ c, p.2 ^ c) := rfl @[simp, to_additive smul_swap, to_additive_reorder 6] lemma pow_swap (p : α × β) (c : E) : (p ^ c).swap = p.swap ^ c := rfl @[to_additive] instance [has_smul M N] [is_scalar_tower M N α] [is_scalar_tower M N β] : is_scalar_tower M N (α × β) := ⟨λ x y z, mk.inj_iff.mpr ⟨smul_assoc _ _ _, smul_assoc _ _ _⟩⟩ @[to_additive] instance [smul_comm_class M N α] [smul_comm_class M N β] : smul_comm_class M N (α × β) := { smul_comm := λ r s x, mk.inj_iff.mpr ⟨smul_comm _ _ _, smul_comm _ _ _⟩ } @[to_additive] instance [has_smul Mᵐᵒᵖ α] [has_smul Mᵐᵒᵖ β] [is_central_scalar M α] [is_central_scalar M β] : is_central_scalar M (α × β) := ⟨λ r m, prod.ext (op_smul_eq_smul _ _) (op_smul_eq_smul _ _)⟩ @[to_additive] instance has_faithful_smul_left [has_faithful_smul M α] [nonempty β] : has_faithful_smul M (α × β) := ⟨λ x y h, let ⟨b⟩ := ‹nonempty β› in eq_of_smul_eq_smul $ λ a : α, by injection h (a, b)⟩ @[to_additive] instance has_faithful_smul_right [nonempty α] [has_faithful_smul M β] : has_faithful_smul M (α × β) := ⟨λ x y h, let ⟨a⟩ := ‹nonempty α› in eq_of_smul_eq_smul $ λ b : β, by injection h (a, b)⟩ end @[to_additive] instance smul_comm_class_both [has_mul N] [has_mul P] [has_smul M N] [has_smul M P] [smul_comm_class M N N] [smul_comm_class M P P] : smul_comm_class M (N × P) (N × P) := ⟨λ c x y, by simp [smul_def, mul_def, mul_smul_comm]⟩ instance is_scalar_tower_both [has_mul N] [has_mul P] [has_smul M N] [has_smul M P] [is_scalar_tower M N N] [is_scalar_tower M P P] : is_scalar_tower M (N × P) (N × P) := ⟨λ c x y, by simp [smul_def, mul_def, smul_mul_assoc]⟩ @[to_additive] instance {m : monoid M} [mul_action M α] [mul_action M β] : mul_action M (α × β) := { mul_smul := λ a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := λ ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩ } instance {R M N : Type*} [has_zero M] [has_zero N] [smul_zero_class R M] [smul_zero_class R N] : smul_zero_class R (M × N) := { smul_zero := λ a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩ } instance {R M N : Type*} [add_zero_class M] [add_zero_class N] [distrib_smul R M] [distrib_smul R N] : distrib_smul R (M × N) := { smul_add := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩ } instance {R M N : Type*} {r : monoid R} [add_monoid M] [add_monoid N] [distrib_mul_action R M] [distrib_mul_action R N] : distrib_mul_action R (M × N) := { ..prod.distrib_smul } instance {R M N : Type*} {r : monoid R} [monoid M] [monoid N] [mul_distrib_mul_action R M] [mul_distrib_mul_action R N] : mul_distrib_mul_action R (M × N) := { smul_mul := λ a p₁ p₂, mk.inj_iff.mpr ⟨smul_mul' _ _ _, smul_mul' _ _ _⟩, smul_one := λ a, mk.inj_iff.mpr ⟨smul_one _, smul_one _⟩ } end prod /-! ### Scalar multiplication as a homomorphism -/ section bundled_smul /-- Scalar multiplication as a multiplicative homomorphism. -/ @[simps] def smul_mul_hom [monoid α] [has_mul β] [mul_action α β] [is_scalar_tower α β β] [smul_comm_class α β β] : (α × β) →ₙ* β := { to_fun := λ a, a.1 • a.2, map_mul' := λ a b, (smul_mul_smul _ _ _ _).symm } /-- Scalar multiplication as a monoid homomorphism. -/ @[simps] def smul_monoid_hom [monoid α] [mul_one_class β] [mul_action α β] [is_scalar_tower α β β] [smul_comm_class α β β] : α × β →* β := { map_one' := one_smul _ _, .. smul_mul_hom } end bundled_smul
1139766dd2e9cd7c78c341b283f876f3c1492688
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/pythagorean_triples.lean
05eb3f7193fc8df26550f70161d10028639b4ce3
[ "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,775
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Paul van Wamelen -/ import algebra.field.basic import ring_theory.int.basic import algebra.group_with_zero.power import tactic.ring import tactic.ring_exp import tactic.field_simp import data.zmod.basic /-! # Pythagorean Triples The main result is the classification of Pythagorean triples. The final result is for general Pythagorean triples. It follows from the more interesting relatively prime case. We use the "rational parametrization of the circle" method for the proof. The parametrization maps the point `(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where `m / n` is the slope. In order to identify numerators and denominators we now need results showing that these are coprime. This is easy except for the prime 2. In order to deal with that we have to analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up the bulk of the proof below. -/ lemma sq_ne_two_fin_zmod_four (z : zmod 4) : z * z ≠ 2 := begin change fin 4 at z, fin_cases z; norm_num [fin.ext_iff, fin.coe_bit0, fin.coe_bit1] end lemma int.sq_ne_two_mod_four (z : ℤ) : (z * z) % 4 ≠ 2 := suffices ¬ (z * z) % (4 : ℕ) = 2 % (4 : ℕ), by norm_num at this, begin rw ← zmod.int_coe_eq_int_coe_iff', simpa using sq_ne_two_fin_zmod_four _ end noncomputable theory open_locale classical /-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/ def pythagorean_triple (x y z : ℤ) : Prop := x * x + y * y = z * z /-- Pythagorean triples are interchangable, i.e `x * x + y * y = y * y + x * x = z * z`. This comes from additive commutativity. -/ lemma pythagorean_triple_comm {x y z : ℤ} : (pythagorean_triple x y z) ↔ (pythagorean_triple y x z) := by { delta pythagorean_triple, rw add_comm } /-- The zeroth Pythagorean triple is all zeros. -/ lemma pythagorean_triple.zero : pythagorean_triple 0 0 0 := by simp only [pythagorean_triple, zero_mul, zero_add] namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma eq : x * x + y * y = z * z := h @[symm] lemma symm : pythagorean_triple y x z := by rwa [pythagorean_triple_comm] /-- A triple is still a triple if you multiply `x`, `y` and `z` by a constant `k`. -/ lemma mul (k : ℤ) : pythagorean_triple (k * x) (k * y) (k * z) := calc (k * x) * (k * x) + (k * y) * (k * y) = k ^ 2 * (x * x + y * y) : by ring ... = k ^ 2 * (z * z) : by rw h.eq ... = (k * z) * (k * z) : by ring omit h /-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if `(x, y, z)` is also a triple. -/ lemma mul_iff (k : ℤ) (hk : k ≠ 0) : pythagorean_triple (k * x) (k * y) (k * z) ↔ pythagorean_triple x y z := begin refine ⟨_, λ h, h.mul k⟩, simp only [pythagorean_triple], intro h, rw ← mul_left_inj' (mul_ne_zero hk hk), convert h using 1; ring, end include h /-- A Pythagorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that either * `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or * `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/ @[nolint unused_arguments] def is_classified := ∃ (k m n : ℤ), ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ int.gcd m n = 1 /-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime. Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either * `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or * `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`. -/ @[nolint unused_arguments] def is_primitive_classified := ∃ (m n : ℤ), ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) lemma mul_is_classified (k : ℤ) (hc : h.is_classified) : (h.mul k).is_classified := begin obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc, { use [k * l, m, n], apply and.intro _ co, left, split; ring }, { use [k * l, m, n], apply and.intro _ co, right, split; ring }, end lemma even_odd_of_coprime (hc : int.gcd x y = 1) : (x % 2 = 0 ∧ y % 2 = 1) ∨ (x % 2 = 1 ∧ y % 2 = 0) := begin cases int.mod_two_eq_zero_or_one x with hx hx; cases int.mod_two_eq_zero_or_one y with hy hy, { -- x even, y even exfalso, apply nat.not_coprime_of_dvd_of_dvd (dec_trivial : 1 < 2) _ _ hc, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hx }, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hy } }, { left, exact ⟨hx, hy⟩ }, -- x even, y odd { right, exact ⟨hx, hy⟩ }, -- x odd, y even { -- x odd, y odd exfalso, obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0* 2 + 1 ∧ y = y0 * 2 + 1, { cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hx) with x0 hx2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hy) with y0 hy2, rw sub_eq_iff_eq_add at hx2 hy2, exact ⟨x0, y0, hx2, hy2⟩ }, apply int.sq_ne_two_mod_four z, rw show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2, by { rw ← h.eq, ring }, norm_num [int.add_mod] } end lemma gcd_dvd : (int.gcd x y : ℤ) ∣ z := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hz, dvd_zero], }, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul], rw [← int.pow_dvd_pow_iff (dec_trivial : 0 < 2), sq z, ← h.eq], rw (by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = k ^ 2 * (x0 * x0 + y0 * y0)), exact dvd_mul_right _ _ end lemma normalize : pythagorean_triple (x / int.gcd x y) (y / int.gcd x y) (z / int.gcd x y) := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hx, hy, hz, int.zero_div], exact zero }, rcases h.gcd_dvd with ⟨z0, rfl⟩, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), have hk : (k : ℤ) ≠ 0, { norm_cast, rwa pos_iff_ne_zero at k0 }, rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul] at h ⊢, rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h, rwa [int.mul_div_cancel _ hk, int.mul_div_cancel _ hk, int.mul_div_cancel_left _ hk], end lemma is_classified_of_is_primitive_classified (hp : h.is_primitive_classified) : h.is_classified := begin obtain ⟨m, n, H⟩ := hp, use [1, m, n], rcases H with ⟨t, co, pp⟩, rw [one_mul, one_mul], exact ⟨t, co⟩, end lemma is_classified_of_normalize_is_primitive_classified (hc : h.normalize.is_primitive_classified) : h.is_classified := begin convert h.normalize.mul_is_classified (int.gcd x y) (is_classified_of_is_primitive_classified h.normalize hc); rw int.mul_div_cancel', { exact int.gcd_dvd_left x y }, { exact int.gcd_dvd_right x y }, { exact h.gcd_dvd } end lemma ne_zero_of_coprime (hc : int.gcd x y = 1) : z ≠ 0 := begin suffices : 0 < z * z, { rintro rfl, norm_num at this }, rw [← h.eq, ← sq, ← sq], have hc' : int.gcd x y ≠ 0, { rw hc, exact one_ne_zero }, cases int.ne_zero_of_gcd hc' with hxz hyz, { apply lt_add_of_pos_of_le (sq_pos_of_ne_zero x hxz) (sq_nonneg y) }, { apply lt_add_of_le_of_pos (sq_nonneg x) (sq_pos_of_ne_zero y hyz) } end lemma is_primitive_classified_of_coprime_of_zero_left (hc : int.gcd x y = 1) (hx : x = 0) : h.is_primitive_classified := begin subst x, change nat.gcd 0 (int.nat_abs y) = 1 at hc, rw [nat.gcd_zero_left (int.nat_abs y)] at hc, cases int.nat_abs_eq y with hy hy, { use [1, 0], rw [hy, hc, int.gcd_zero_right], norm_num }, { use [0, 1], rw [hy, hc, int.gcd_zero_left], norm_num } end lemma coprime_of_coprime (hc : int.gcd x y = 1) : int.gcd y z = 1 := begin by_contradiction H, obtain ⟨p, hp, hpy, hpz⟩ := nat.prime.not_coprime_iff_dvd.mp H, apply hp.not_dvd_one, rw [← hc], apply nat.dvd_gcd (int.prime.dvd_nat_abs_of_coe_dvd_sq hp _ _) hpy, rw [sq, eq_sub_of_add_eq h], rw [← int.coe_nat_dvd_left] at hpy hpz, exact dvd_sub ((hpz).mul_right _) ((hpy).mul_right _), end end pythagorean_triple section circle_equiv_gen /-! ### A parametrization of the unit circle For the classification of pythogorean triples, we will use a parametrization of the unit circle. -/ variables {K : Type*} [field K] /-- A parameterization of the unit circle that is useful for classifying Pythagorean triples. (To be applied in the case where `K = ℚ`.) -/ def circle_equiv_gen (hk : ∀ x : K, 1 + x^2 ≠ 0) : K ≃ {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := { to_fun := λ x, ⟨⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩, by { field_simp [hk x, div_pow], ring }, begin simp only [ne.def, div_eq_iff (hk x), ←neg_mul_eq_neg_mul, one_mul, neg_add, sub_eq_add_neg, add_left_inj], simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1, end⟩, inv_fun := λ p, (p : K × K).1 / ((p : K × K).2 + 1), left_inv := λ x, begin have h2 : (1 + 1 : K) = 2 := rfl, have h3 : (2 : K) ≠ 0, { convert hk 1, rw [one_pow 2, h2] }, field_simp [hk x, h2, add_assoc, add_comm, add_sub_cancel'_right, mul_comm], end, right_inv := λ ⟨⟨x, y⟩, hxy, hy⟩, begin change x ^ 2 + y ^ 2 = 1 at hxy, have h2 : y + 1 ≠ 0, { apply mt eq_neg_of_add_eq_zero, exact hy }, have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1), { rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm], ring }, have h4 : (2 : K) ≠ 0, { convert hk 1, rw one_pow 2, refl }, simp only [prod.mk.inj_iff, subtype.mk_eq_mk], split, { field_simp [h3], ring }, { field_simp [h3], rw [← add_neg_eq_iff_eq_add.mpr hxy.symm], ring } end } @[simp] lemma circle_equiv_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (x : K) : (circle_equiv_gen hk x : K × K) = ⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩ := rfl @[simp] lemma circle_equiv_symm_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (v : {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1}) : (circle_equiv_gen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) := rfl end circle_equiv_gen private lemma coprime_sq_sub_sq_add_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have h2m : (p : ℤ) ∣ 2 * m ^ 2, { convert dvd_add hp2 hp1, ring }, have h2n : (p : ℤ) ∣ 2 * n ^ 2, { convert dvd_sub hp2 hp1, ring }, have hmc : p = 2 ∨ p ∣ int.nat_abs m := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m, have hnc : p = 2 ∨ p ∣ int.nat_abs n := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n, by_cases h2 : p = 2, { have h3 : (m ^ 2 + n ^ 2) % 2 = 1, { norm_num [sq, int.add_mod, int.mul_mod, hm, hn] }, have h4 : (m ^ 2 + n ^ 2) % 2 = 0, { apply int.mod_eq_zero_of_dvd, rwa h2 at hp2 }, rw h4 at h3, exact zero_ne_one h3 }, { apply hp.not_dvd_one, rw ← h, exact nat.dvd_gcd (or.resolve_left hmc h2) (or.resolve_left hnc h2), } end private lemma coprime_sq_sub_sq_add_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0): int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm], apply coprime_sq_sub_sq_add_of_even_odd _ hn hm, rwa [int.gcd_comm], end private lemma coprime_sq_sub_mul_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have hnp : ¬ (p : ℤ) ∣ int.gcd m n, { rw h, norm_cast, exact mt nat.dvd_one.mp (nat.prime.ne_one hp) }, cases int.prime.dvd_mul hp hp2 with hp2m hpn, { rw int.nat_abs_mul at hp2m, cases (nat.prime.dvd_mul hp).mp hp2m with hp2 hpm, { have hp2' : p = 2 := (nat.le_of_dvd zero_lt_two hp2).antisymm hp.two_le, revert hp1, rw hp2', apply mt int.mod_eq_zero_of_dvd, norm_num [sq, int.sub_mod, int.mul_mod, hm, hn] }, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpm)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : n * n = - (m ^ 2 - n ^ 2) + m * m), apply dvd_add (dvd_neg_of_dvd hp1), exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpm) m }, rw int.gcd_comm at hnp, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpn)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : m * m = (m ^ 2 - n ^ 2) + n * n), apply dvd_add hp1, exact (int.coe_nat_dvd_left.mpr hpn).mul_right n end private lemma coprime_sq_sub_mul_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)], apply coprime_sq_sub_mul_of_even_odd _ hn hm, rwa [int.gcd_comm] end private lemma coprime_sq_sub_mul {m n : ℤ} (h : int.gcd m n = 1) (hmn : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin cases hmn with h1 h2, { exact coprime_sq_sub_mul_of_even_odd h h1.left h1.right }, { exact coprime_sq_sub_mul_of_odd_even h h2.left h2.right } end private lemma coprime_sq_sub_sq_sum_of_odd_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 1) : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 := begin cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hm) with m0 hm2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hn) with n0 hn2, rw sub_eq_iff_eq_add at hm2 hn2, subst m, subst n, have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1), by ring_exp, have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)), by ring_exp, have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0, { rw [h2, int.mul_div_cancel_left, int.mul_mod_right], exact dec_trivial }, refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩, have h20 : (2:ℤ) ≠ 0 := dec_trivial, rw [h1, h2, int.mul_div_cancel_left _ h20, int.mul_div_cancel_left _ h20], by_contra h4, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp h4, apply hp.not_dvd_one, rw ← h, rw ← int.coe_nat_dvd_left at hp1 hp2, apply nat.dvd_gcd, { apply int.prime.dvd_nat_abs_of_coe_dvd_sq hp, convert dvd_add hp1 hp2, ring_exp }, { apply int.prime.dvd_nat_abs_of_coe_dvd_sq hp, convert dvd_sub hp2 hp1, ring_exp }, end namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma is_primitive_classified_aux (hc : x.gcd y = 1) (hzpos : 0 < z) {m n : ℤ} (hm2n2 : 0 < m ^ 2 + n ^ 2) (hv2 : (x : ℚ) / z = 2 * m * n / (m ^ 2 + n ^ 2)) (hw2 : (y : ℚ) / z = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2)) (H : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1) (co : int.gcd m n = 1) (pp : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)): h.is_primitive_classified := begin have hz : z ≠ 0, apply ne_of_gt hzpos, have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2, { apply rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H, rw [hw2], norm_cast }, use [m, n], apply and.intro _ (and.intro co pp), right, refine ⟨_, h2.left⟩, rw [← rat.coe_int_inj _ _, ← div_left_inj' ((mt (rat.coe_int_inj z 0).mp) hz), hv2, h2.right], norm_cast end theorem is_primitive_classified_of_coprime_of_odd_of_pos (hc : int.gcd x y = 1) (hyo : y % 2 = 1) (hzpos : 0 < z) : h.is_primitive_classified := begin by_cases h0 : x = 0, { exact h.is_primitive_classified_of_coprime_of_zero_left hc h0 }, let v := (x : ℚ) / z, let w := (y : ℚ) / z, have hz : z ≠ 0, apply ne_of_gt hzpos, have hq : v ^ 2 + w ^ 2 = 1, { field_simp [hz, sq], norm_cast, exact h }, have hvz : v ≠ 0, { field_simp [hz], exact h0 }, have hw1 : w ≠ -1, { contrapose! hvz with hw1, rw [hw1, neg_sq, one_pow, add_left_eq_self] at hq, exact pow_eq_zero hq, }, have hQ : ∀ x : ℚ, 1 + x^2 ≠ 0, { intro q, apply ne_of_gt, exact lt_add_of_pos_of_le zero_lt_one (sq_nonneg q) }, have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ {p : ℚ × ℚ | p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := ⟨hq, hw1⟩, let q := (circle_equiv_gen hQ).symm ⟨⟨v, w⟩, hp⟩, have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2), { apply prod.mk.inj, have := ((circle_equiv_gen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm, exact congr_arg subtype.val this, }, let m := (q.denom : ℤ), let n := q.num, have hm0 : m ≠ 0, { norm_cast, apply rat.denom_ne_zero q }, have hq2 : q = n / m := (rat.num_div_denom q).symm, have hm2n2 : 0 < m ^ 2 + n ^ 2, { apply lt_add_of_pos_of_le _ (sq_nonneg n), exact lt_of_le_of_ne (sq_nonneg m) (ne.symm (pow_ne_zero 2 hm0)) }, have hw2 : w = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2), { rw [ht4.2, hq2], field_simp [hm2n2, rat.denom_ne_zero q, -rat.num_div_denom] }, have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0, { norm_cast, simpa only [int.coe_nat_pow] using ne_of_gt hm2n2 }, have hv2 : v = 2 * m * n / (m ^ 2 + n ^ 2), { apply eq.symm, apply (div_eq_iff hm2n20).mpr, rw [ht4.1], field_simp [hQ q], rw [hq2] {occs := occurrences.pos [2, 3]}, field_simp [rat.denom_ne_zero q, -rat.num_div_denom], ring }, have hnmcp : int.gcd n m = 1 := q.cop, have hmncp : int.gcd m n = 1, { rw int.gcd_comm, exact hnmcp }, cases int.mod_two_eq_zero_or_one m with hm2 hm2; cases int.mod_two_eq_zero_or_one n with hn2 hn2, { -- m even, n even exfalso, have h1 : 2 ∣ (int.gcd n m : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hn2) (int.dvd_of_mod_eq_zero hm2) }, rw hnmcp at h1, revert h1, norm_num }, { -- m even, n odd apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_left, exact and.intro hm2 hn2 }, { apply coprime_sq_sub_sq_add_of_even_odd hmncp hm2 hn2 } }, { -- m odd, n even apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_right, exact and.intro hm2 hn2 }, apply coprime_sq_sub_sq_add_of_odd_even hmncp hm2 hn2 }, { -- m odd, n odd exfalso, have h1 : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1, { exact coprime_sq_sub_sq_sum_of_odd_odd hmncp hm2 hn2 }, have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2, { apply rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2, { show w = _, rw [←rat.mk_eq_div, ←(rat.div_mk_div_cancel_left (by norm_num : (2 : ℤ) ≠ 0))], rw [int.div_mul_cancel h1.1, int.div_mul_cancel h1.2.1, hw2], norm_cast }, { apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp, rw [int.div_mul_cancel h1.1, zero_mul], exact hm2n2 } }, rw [h2.1, h1.2.2.1] at hyo, revert hyo, norm_num } end theorem is_primitive_classified_of_coprime_of_pos (hc : int.gcd x y = 1) (hzpos : 0 < z): h.is_primitive_classified := begin cases h.even_odd_of_coprime hc with h1 h2, { exact (h.is_primitive_classified_of_coprime_of_odd_of_pos hc h1.right hzpos) }, rw int.gcd_comm at hc, obtain ⟨m, n, H⟩ := (h.symm.is_primitive_classified_of_coprime_of_odd_of_pos hc h2.left hzpos), use [m, n], tauto end theorem is_primitive_classified_of_coprime (hc : int.gcd x y = 1) : h.is_primitive_classified := begin by_cases hz : 0 < z, { exact h.is_primitive_classified_of_coprime_of_pos hc hz }, have h' : pythagorean_triple x y (-z), { simpa [pythagorean_triple, neg_mul_neg] using h.eq, }, apply h'.is_primitive_classified_of_coprime_of_pos hc, apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm, exact le_neg.mp (not_lt.mp hz) end theorem classified : h.is_classified := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, use [0, 1, 0], norm_num [hx, hy], }, apply h.is_classified_of_normalize_is_primitive_classified, apply h.normalize.is_primitive_classified_of_coprime, apply int.gcd_div_gcd_div_gcd (nat.pos_of_ne_zero h0), end omit h theorem coprime_classification : pythagorean_triple x y z ∧ int.gcd x y = 1 ↔ ∃ m n, ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ (z = m ^ 2 + n ^ 2 ∨ z = - (m ^ 2 + n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) := begin split, { intro h, obtain ⟨m, n, H⟩ := h.left.is_primitive_classified_of_coprime h.right, use [m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [sq, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [sq, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this } }, { delta pythagorean_triple, rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩; { split, { ring }, exact coprime_sq_sub_mul co pp } <|> { split, { ring }, rw int.gcd_comm, exact coprime_sq_sub_mul co pp } } end /-- by assuming `x` is odd and `z` is positive we get a slightly more precise classification of the pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`-/ theorem coprime_classification' {x y z : ℤ} (h : pythagorean_triple x y z) (h_coprime : int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) : ∃ m n, x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∧ z = m ^ 2 + n ^ 2 ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) ∧ 0 ≤ m := begin obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ := pythagorean_triple.coprime_classification.mp (and.intro h h_coprime), cases le_or_lt 0 m with hm hm, { use [m, n], cases ht1 with h_odd h_even, { apply and.intro h_odd.1, apply and.intro h_odd.2, cases ht2 with h_pos h_neg, { apply and.intro h_pos (and.intro ht3 (and.intro ht4 hm)) }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (sq_nonneg m) (sq_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity }, { use [-m, -n], cases ht1 with h_odd h_even, { rw [neg_sq m], rw [neg_sq n], apply and.intro h_odd.1, split, { rw h_odd.2, ring }, cases ht2 with h_pos h_neg, { apply and.intro h_pos, split, { delta int.gcd, rw [int.nat_abs_neg, int.nat_abs_neg], exact ht3 }, { rw [int.neg_mod_two, int.neg_mod_two], apply and.intro ht4, linarith } }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (sq_nonneg m) (sq_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity } end /-- **Formula for Pythagorean Triples** -/ theorem classification : pythagorean_triple x y z ↔ ∃ k m n, ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ (z = k * (m ^ 2 + n ^ 2) ∨ z = - k * (m ^ 2 + n ^ 2)) := begin split, { intro h, obtain ⟨k, m, n, H⟩ := h.classified, use [k, m, n], rcases H with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [sq, ← h.eq], ring }, simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [sq, ← h.eq], ring }, simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this } }, { rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩; delta pythagorean_triple; ring } end end pythagorean_triple
212387112ec7a2d91f150a6bea5e86a7adcab16c
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/locally_convex/with_seminorms.lean
3f1cba49ad904110c2987b79d953980d077c0ab1
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
20,682
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll, Anatole Dedecker -/ import analysis.seminorm import analysis.locally_convex.bounded /-! # Topology induced by a family of seminorms ## Main definitions * `seminorm_family.basis_sets`: The set of open seminorm balls for a family of seminorms. * `seminorm_family.module_filter_basis`: A module filter basis formed by the open balls. * `seminorm.is_bounded`: A linear map `f : E →ₗ[𝕜] F` is bounded iff every seminorm in `F` can be bounded by a finite number of seminorms in `E`. ## Main statements * `continuous_from_bounded`: A bounded linear map `f : E →ₗ[𝕜] F` is continuous. * `seminorm_family.to_locally_convex_space`: A space equipped with a family of seminorms is locally convex. ## TODO Show that for any locally convex space there exist seminorms that induce the topology. ## Tags seminorm, locally convex -/ open normed_field set seminorm topological_space open_locale big_operators nnreal pointwise topological_space variables {𝕜 E F G ι ι' : Type*} section filter_basis variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables (𝕜 E ι) /-- An abbreviation for indexed families of seminorms. This is mainly to allow for dot-notation. -/ abbreviation seminorm_family := ι → seminorm 𝕜 E variables {𝕜 E ι} namespace seminorm_family /-- The sets of a filter basis for the neighborhood filter of 0. -/ def basis_sets (p : seminorm_family 𝕜 E ι) : set (set E) := ⋃ (s : finset ι) r (hr : 0 < r), singleton $ ball (s.sup p) (0 : E) r variables (p : seminorm_family 𝕜 E ι) lemma basis_sets_iff {U : set E} : U ∈ p.basis_sets ↔ ∃ (i : finset ι) r (hr : 0 < r), U = ball (i.sup p) 0 r := by simp only [basis_sets, mem_Union, mem_singleton_iff] lemma basis_sets_mem (i : finset ι) {r : ℝ} (hr : 0 < r) : (i.sup p).ball 0 r ∈ p.basis_sets := (basis_sets_iff _).mpr ⟨i,_,hr,rfl⟩ lemma basis_sets_singleton_mem (i : ι) {r : ℝ} (hr : 0 < r) : (p i).ball 0 r ∈ p.basis_sets := (basis_sets_iff _).mpr ⟨{i},_,hr, by rw finset.sup_singleton⟩ lemma basis_sets_nonempty [nonempty ι] : p.basis_sets.nonempty := begin let i := classical.arbitrary ι, refine set.nonempty_def.mpr ⟨(p i).ball 0 1, _⟩, exact p.basis_sets_singleton_mem i zero_lt_one, end lemma basis_sets_intersect (U V : set E) (hU : U ∈ p.basis_sets) (hV : V ∈ p.basis_sets) : ∃ (z : set E) (H : z ∈ p.basis_sets), z ⊆ U ∩ V := begin classical, rcases p.basis_sets_iff.mp hU with ⟨s, r₁, hr₁, hU⟩, rcases p.basis_sets_iff.mp hV with ⟨t, r₂, hr₂, hV⟩, use ((s ∪ t).sup p).ball 0 (min r₁ r₂), refine ⟨p.basis_sets_mem (s ∪ t) (lt_min_iff.mpr ⟨hr₁, hr₂⟩), _⟩, rw [hU, hV, ball_finset_sup_eq_Inter _ _ _ (lt_min_iff.mpr ⟨hr₁, hr₂⟩), ball_finset_sup_eq_Inter _ _ _ hr₁, ball_finset_sup_eq_Inter _ _ _ hr₂], exact set.subset_inter (set.Inter₂_mono' $ λ i hi, ⟨i, finset.subset_union_left _ _ hi, ball_mono $ min_le_left _ _⟩) (set.Inter₂_mono' $ λ i hi, ⟨i, finset.subset_union_right _ _ hi, ball_mono $ min_le_right _ _⟩), end lemma basis_sets_zero (U) (hU : U ∈ p.basis_sets) : (0 : E) ∈ U := begin rcases p.basis_sets_iff.mp hU with ⟨ι', r, hr, hU⟩, rw [hU, mem_ball_zero, map_zero], exact hr, end lemma basis_sets_add (U) (hU : U ∈ p.basis_sets) : ∃ (V : set E) (H : V ∈ p.basis_sets), V + V ⊆ U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, use (s.sup p).ball 0 (r/2), refine ⟨p.basis_sets_mem s (div_pos hr zero_lt_two), _⟩, refine set.subset.trans (ball_add_ball_subset (s.sup p) (r/2) (r/2) 0 0) _, rw [hU, add_zero, add_halves'], end lemma basis_sets_neg (U) (hU' : U ∈ p.basis_sets) : ∃ (V : set E) (H : V ∈ p.basis_sets), V ⊆ (λ (x : E), -x) ⁻¹' U := begin rcases p.basis_sets_iff.mp hU' with ⟨s, r, hr, hU⟩, rw [hU, neg_preimage, neg_ball (s.sup p), neg_zero], exact ⟨U, hU', eq.subset hU⟩, end /-- The `add_group_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/ protected def add_group_filter_basis [nonempty ι] : add_group_filter_basis E := add_group_filter_basis_of_comm p.basis_sets p.basis_sets_nonempty p.basis_sets_intersect p.basis_sets_zero p.basis_sets_add p.basis_sets_neg lemma basis_sets_smul_right (v : E) (U : set E) (hU : U ∈ p.basis_sets) : ∀ᶠ (x : 𝕜) in 𝓝 0, x • v ∈ U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, rw [hU, filter.eventually_iff], simp_rw [(s.sup p).mem_ball_zero, (s.sup p).smul], by_cases h : 0 < (s.sup p) v, { simp_rw (lt_div_iff h).symm, rw ←_root_.ball_zero_eq, exact metric.ball_mem_nhds 0 (div_pos hr h) }, simp_rw [le_antisymm (not_lt.mp h) ((s.sup p).nonneg v), mul_zero, hr], exact is_open.mem_nhds is_open_univ (mem_univ 0), end variables [nonempty ι] lemma basis_sets_smul (U) (hU : U ∈ p.basis_sets) : ∃ (V : set 𝕜) (H : V ∈ 𝓝 (0 : 𝕜)) (W : set E) (H : W ∈ p.add_group_filter_basis.sets), V • W ⊆ U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, refine ⟨metric.ball 0 r.sqrt, metric.ball_mem_nhds 0 (real.sqrt_pos.mpr hr), _⟩, refine ⟨(s.sup p).ball 0 r.sqrt, p.basis_sets_mem s (real.sqrt_pos.mpr hr), _⟩, refine set.subset.trans (ball_smul_ball (s.sup p) r.sqrt r.sqrt) _, rw [hU, real.mul_self_sqrt (le_of_lt hr)], end lemma basis_sets_smul_left (x : 𝕜) (U : set E) (hU : U ∈ p.basis_sets) : ∃ (V : set E) (H : V ∈ p.add_group_filter_basis.sets), V ⊆ (λ (y : E), x • y) ⁻¹' U := begin rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, rw hU, by_cases h : x ≠ 0, { rw [(s.sup p).smul_ball_preimage 0 r x h, smul_zero], use (s.sup p).ball 0 (r / ∥x∥), exact ⟨p.basis_sets_mem s (div_pos hr (norm_pos_iff.mpr h)), subset.rfl⟩ }, refine ⟨(s.sup p).ball 0 r, p.basis_sets_mem s hr, _⟩, simp only [not_ne_iff.mp h, subset_def, mem_ball_zero, hr, mem_univ, map_zero, implies_true_iff, preimage_const_of_mem, zero_smul], end /-- The `module_filter_basis` induced by the filter basis `seminorm_basis_zero`. -/ protected def module_filter_basis : module_filter_basis 𝕜 E := { to_add_group_filter_basis := p.add_group_filter_basis, smul' := p.basis_sets_smul, smul_left' := p.basis_sets_smul_left, smul_right' := p.basis_sets_smul_right } lemma filter_eq_infi (p : seminorm_family 𝕜 E ι) : p.module_filter_basis.to_filter_basis.filter = ⨅ i, (𝓝 0).comap (p i) := begin refine le_antisymm (le_infi $ λ i, _) _, { rw p.module_filter_basis.to_filter_basis.has_basis.le_basis_iff (metric.nhds_basis_ball.comap _), intros ε hε, refine ⟨(p i).ball 0 ε, _, _⟩, { rw ← (finset.sup_singleton : _ = p i), exact p.basis_sets_mem {i} hε, }, { rw [id, (p i).ball_zero_eq_preimage_ball] } }, { rw p.module_filter_basis.to_filter_basis.has_basis.ge_iff, rintros U (hU : U ∈ p.basis_sets), rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, rfl⟩, rw [id, seminorm.ball_finset_sup_eq_Inter _ _ _ hr, s.Inter_mem_sets], exact λ i hi, filter.mem_infi_of_mem i ⟨metric.ball 0 r, metric.ball_mem_nhds 0 hr, eq.subset ((p i).ball_zero_eq_preimage_ball).symm⟩, }, end end seminorm_family end filter_basis section bounded namespace seminorm variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] -- Todo: This should be phrased entirely in terms of the von Neumann bornology. /-- The proposition that a linear map is bounded between spaces with families of seminorms. -/ def is_bounded (p : ι → seminorm 𝕜 E) (q : ι' → seminorm 𝕜 F) (f : E →ₗ[𝕜] F) : Prop := ∀ i, ∃ s : finset ι, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • s.sup p lemma is_bounded_const (ι' : Type*) [nonempty ι'] {p : ι → seminorm 𝕜 E} {q : seminorm 𝕜 F} (f : E →ₗ[𝕜] F) : is_bounded p (λ _ : ι', q) f ↔ ∃ (s : finset ι) C : ℝ≥0, C ≠ 0 ∧ q.comp f ≤ C • s.sup p := by simp only [is_bounded, forall_const] lemma const_is_bounded (ι : Type*) [nonempty ι] {p : seminorm 𝕜 E} {q : ι' → seminorm 𝕜 F} (f : E →ₗ[𝕜] F) : is_bounded (λ _ : ι, p) q f ↔ ∀ i, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • p := begin split; intros h i, { rcases h i with ⟨s, C, hC, h⟩, exact ⟨C, hC, le_trans h (smul_le_smul (finset.sup_le (λ _ _, le_rfl)) le_rfl)⟩ }, use [{classical.arbitrary ι}], simp only [h, finset.sup_singleton], end lemma is_bounded_sup {p : ι → seminorm 𝕜 E} {q : ι' → seminorm 𝕜 F} {f : E →ₗ[𝕜] F} (hf : is_bounded p q f) (s' : finset ι') : ∃ (C : ℝ≥0) (s : finset ι), 0 < C ∧ (s'.sup q).comp f ≤ C • (s.sup p) := begin classical, by_cases hs' : ¬s'.nonempty, { refine ⟨1, ∅, zero_lt_one, _⟩, rw [finset.not_nonempty_iff_eq_empty.mp hs', finset.sup_empty, seminorm.bot_eq_zero, zero_comp], exact seminorm.nonneg _ }, rw not_not at hs', choose fₛ fC hf using hf, use [s'.card • s'.sup fC, finset.bUnion s' fₛ], split, { refine nsmul_pos _ (ne_of_gt (finset.nonempty.card_pos hs')), cases finset.nonempty.bex hs' with j hj, exact lt_of_lt_of_le (zero_lt_iff.mpr (and.elim_left (hf j))) (finset.le_sup hj) }, have hs : ∀ i : ι', i ∈ s' → (q i).comp f ≤ s'.sup fC • ((finset.bUnion s' fₛ).sup p) := begin intros i hi, refine le_trans (and.elim_right (hf i)) (smul_le_smul _ (finset.le_sup hi)), exact finset.sup_mono (finset.subset_bUnion_of_mem fₛ hi), end, refine le_trans (comp_mono f (finset_sup_le_sum q s')) _, simp_rw [←pullback_apply, add_monoid_hom.map_sum, pullback_apply], refine le_trans (finset.sum_le_sum hs) _, rw [finset.sum_const, smul_assoc], exact le_rfl, end end seminorm end bounded section topology variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [nonempty ι] /-- The proposition that the topology of `E` is induced by a family of seminorms `p`. -/ structure with_seminorms (p : seminorm_family 𝕜 E ι) [t : topological_space E] : Prop := (topology_eq_with_seminorms : t = p.module_filter_basis.topology) lemma seminorm_family.with_seminorms_eq {p : seminorm_family 𝕜 E ι} [t : topological_space E] (hp : with_seminorms p) : t = p.module_filter_basis.topology := hp.1 variables [topological_space E] variables {p : seminorm_family 𝕜 E ι} lemma with_seminorms.has_basis (hp : with_seminorms p) : (𝓝 (0 : E)).has_basis (λ (s : set E), s ∈ p.basis_sets) id := begin rw (congr_fun (congr_arg (@nhds E) hp.1) 0), exact add_group_filter_basis.nhds_zero_has_basis _, end end topology section topological_add_group variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] variables [topological_space E] [topological_add_group E] variables [nonempty ι] lemma seminorm_family.with_seminorms_of_nhds (p : seminorm_family 𝕜 E ι) (h : 𝓝 (0 : E) = p.module_filter_basis.to_filter_basis.filter) : with_seminorms p := begin refine ⟨topological_add_group.ext (by apply_instance) (p.add_group_filter_basis.is_topological_add_group) _⟩, rw add_group_filter_basis.nhds_zero_eq, exact h, end lemma seminorm_family.with_seminorms_of_has_basis (p : seminorm_family 𝕜 E ι) (h : (𝓝 (0 : E)).has_basis (λ (s : set E), s ∈ p.basis_sets) id) : with_seminorms p := p.with_seminorms_of_nhds $ filter.has_basis.eq_of_same_basis h p.add_group_filter_basis.to_filter_basis.has_basis lemma seminorm_family.with_seminorms_iff_nhds_eq_infi (p : seminorm_family 𝕜 E ι) : with_seminorms p ↔ (𝓝 0 : filter E) = ⨅ i, (𝓝 0).comap (p i) := begin rw ← p.filter_eq_infi, refine ⟨λ h, _, p.with_seminorms_of_nhds⟩, rw h.topology_eq_with_seminorms, exact add_group_filter_basis.nhds_zero_eq _, end end topological_add_group section normed_space /-- The topology of a `normed_space 𝕜 E` is induced by the seminorm `norm_seminorm 𝕜 E`. -/ lemma norm_with_seminorms (𝕜 E) [normed_field 𝕜] [seminormed_add_comm_group E] [normed_space 𝕜 E] : with_seminorms (λ (_ : fin 1), norm_seminorm 𝕜 E) := begin let p : seminorm_family 𝕜 E (fin 1) := λ _, norm_seminorm 𝕜 E, refine ⟨topological_add_group.ext normed_top_group (p.add_group_filter_basis.is_topological_add_group) _⟩, refine filter.has_basis.eq_of_same_basis metric.nhds_basis_ball _, rw ←ball_norm_seminorm 𝕜 E, refine filter.has_basis.to_has_basis p.add_group_filter_basis.nhds_zero_has_basis _ (λ r hr, ⟨(norm_seminorm 𝕜 E).ball 0 r, p.basis_sets_singleton_mem 0 hr, rfl.subset⟩), rintros U (hU : U ∈ p.basis_sets), rcases p.basis_sets_iff.mp hU with ⟨s, r, hr, hU⟩, use [r, hr], rw [hU, id.def], by_cases h : s.nonempty, { rw finset.sup_const h }, rw [finset.not_nonempty_iff_eq_empty.mp h, finset.sup_empty, ball_bot _ hr], exact set.subset_univ _, end end normed_space section nontrivially_normed_field variables [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [nonempty ι] variables {p : seminorm_family 𝕜 E ι} variables [topological_space E] lemma with_seminorms.is_vonN_bounded_iff_finset_seminorm_bounded {s : set E} (hp : with_seminorms p) : bornology.is_vonN_bounded 𝕜 s ↔ ∀ I : finset ι, ∃ r (hr : 0 < r), ∀ (x ∈ s), I.sup p x < r := begin rw (hp.has_basis).is_vonN_bounded_basis_iff, split, { intros h I, simp only [id.def] at h, specialize h ((I.sup p).ball 0 1) (p.basis_sets_mem I zero_lt_one), rcases h with ⟨r, hr, h⟩, cases normed_field.exists_lt_norm 𝕜 r with a ha, specialize h a (le_of_lt ha), rw [seminorm.smul_ball_zero (lt_trans hr ha), mul_one] at h, refine ⟨∥a∥, lt_trans hr ha, _⟩, intros x hx, specialize h hx, exact (finset.sup I p).mem_ball_zero.mp h }, intros h s' hs', rcases p.basis_sets_iff.mp hs' with ⟨I, r, hr, hs'⟩, rw [id.def, hs'], rcases h I with ⟨r', hr', h'⟩, simp_rw ←(I.sup p).mem_ball_zero at h', refine absorbs.mono_right _ h', exact (finset.sup I p).ball_zero_absorbs_ball_zero hr, end lemma bornology.is_vonN_bounded_iff_seminorm_bounded {s : set E} (hp : with_seminorms p) : bornology.is_vonN_bounded 𝕜 s ↔ ∀ i : ι, ∃ r (hr : 0 < r), ∀ (x ∈ s), p i x < r := begin rw hp.is_vonN_bounded_iff_finset_seminorm_bounded, split, { intros hI i, convert hI {i}, rw [finset.sup_singleton] }, intros hi I, by_cases hI : I.nonempty, { choose r hr h using hi, have h' : 0 < I.sup' hI r := by { rcases hI.bex with ⟨i, hi⟩, exact lt_of_lt_of_le (hr i) (finset.le_sup' r hi) }, refine ⟨I.sup' hI r, h', λ x hx, finset_sup_apply_lt h' (λ i hi, _)⟩, refine lt_of_lt_of_le (h i x hx) _, simp only [finset.le_sup'_iff, exists_prop], exact ⟨i, hi, (eq.refl _).le⟩ }, simp only [finset.not_nonempty_iff_eq_empty.mp hI, finset.sup_empty, coe_bot, pi.zero_apply, exists_prop], exact ⟨1, zero_lt_one, λ _ _, zero_lt_one⟩, end end nontrivially_normed_field section continuous_bounded namespace seminorm variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E] [add_comm_group F] [module 𝕜 F] variables [nonempty ι] [nonempty ι'] lemma continuous_from_bounded {p : seminorm_family 𝕜 E ι} {q : seminorm_family 𝕜 F ι'} [uniform_space E] [uniform_add_group E] (hp : with_seminorms p) [uniform_space F] [uniform_add_group F] (hq : with_seminorms q) (f : E →ₗ[𝕜] F) (hf : seminorm.is_bounded p q f) : continuous f := begin refine continuous_of_continuous_at_zero f _, rw [continuous_at_def, f.map_zero, hp.1], intros U hU, rw [hq.1, add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff] at hU, rcases hU with ⟨V, hV : V ∈ q.basis_sets, hU⟩, rcases q.basis_sets_iff.mp hV with ⟨s₂, r, hr, hV⟩, rw hV at hU, rw [p.add_group_filter_basis.nhds_zero_eq, filter_basis.mem_filter_iff], rcases (seminorm.is_bounded_sup hf s₂) with ⟨C, s₁, hC, hf⟩, refine ⟨(s₁.sup p).ball 0 (r/C), p.basis_sets_mem _ (div_pos hr (nnreal.coe_pos.mpr hC)), _⟩, refine subset.trans _ (preimage_mono hU), simp_rw [←linear_map.map_zero f, ←ball_comp], refine subset.trans _ (ball_antitone hf), rw ball_smul (s₁.sup p) hC, end lemma cont_with_seminorms_normed_space (F) [seminormed_add_comm_group F] [normed_space 𝕜 F] [uniform_space E] [uniform_add_group E] {p : ι → seminorm 𝕜 E} (hp : with_seminorms p) (f : E →ₗ[𝕜] F) (hf : ∃ (s : finset ι) C : ℝ≥0, C ≠ 0 ∧ (norm_seminorm 𝕜 F).comp f ≤ C • s.sup p) : continuous f := begin rw ←seminorm.is_bounded_const (fin 1) at hf, exact continuous_from_bounded hp (norm_with_seminorms 𝕜 F) f hf, end lemma cont_normed_space_to_with_seminorms (E) [seminormed_add_comm_group E] [normed_space 𝕜 E] [uniform_space F] [uniform_add_group F] {q : ι → seminorm 𝕜 F} (hq : with_seminorms q) (f : E →ₗ[𝕜] F) (hf : ∀ i : ι, ∃ C : ℝ≥0, C ≠ 0 ∧ (q i).comp f ≤ C • (norm_seminorm 𝕜 E)) : continuous f := begin rw ←seminorm.const_is_bounded (fin 1) at hf, exact continuous_from_bounded (norm_with_seminorms 𝕜 E) hq f hf, end end seminorm end continuous_bounded section locally_convex_space open locally_convex_space variables [nonempty ι] [normed_field 𝕜] [normed_space ℝ 𝕜] [add_comm_group E] [module 𝕜 E] [module ℝ E] [is_scalar_tower ℝ 𝕜 E] [topological_space E] [topological_add_group E] lemma seminorm_family.to_locally_convex_space {p : seminorm_family 𝕜 E ι} (hp : with_seminorms p) : locally_convex_space ℝ E := begin apply of_basis_zero ℝ E id (λ s, s ∈ p.basis_sets), { rw [hp.1, add_group_filter_basis.nhds_eq _, add_group_filter_basis.N_zero], exact filter_basis.has_basis _ }, { intros s hs, change s ∈ set.Union _ at hs, simp_rw [set.mem_Union, set.mem_singleton_iff] at hs, rcases hs with ⟨I, r, hr, rfl⟩, exact convex_ball _ _ _ } end end locally_convex_space section normed_space variables (𝕜) [normed_field 𝕜] [normed_space ℝ 𝕜] [seminormed_add_comm_group E] /-- Not an instance since `𝕜` can't be inferred. See `normed_space.to_locally_convex_space` for a slightly weaker instance version. -/ lemma normed_space.to_locally_convex_space' [normed_space 𝕜 E] [module ℝ E] [is_scalar_tower ℝ 𝕜 E] : locally_convex_space ℝ E := seminorm_family.to_locally_convex_space (norm_with_seminorms 𝕜 E) /-- See `normed_space.to_locally_convex_space'` for a slightly stronger version which is not an instance. -/ instance normed_space.to_locally_convex_space [normed_space ℝ E] : locally_convex_space ℝ E := normed_space.to_locally_convex_space' ℝ end normed_space section topological_constructions variables [normed_field 𝕜] [add_comm_group F] [module 𝕜 F] [add_comm_group E] [module 𝕜 E] /-- The family of seminorms obtained by composing each seminorm by a linear map. -/ def seminorm_family.comp (q : seminorm_family 𝕜 F ι) (f : E →ₗ[𝕜] F) : seminorm_family 𝕜 E ι := λ i, (q i).comp f lemma seminorm_family.comp_apply (q : seminorm_family 𝕜 F ι) (i : ι) (f : E →ₗ[𝕜] F) : q.comp f i = (q i).comp f := rfl lemma seminorm_family.finset_sup_comp (q : seminorm_family 𝕜 F ι) (s : finset ι) (f : E →ₗ[𝕜] F) : (s.sup q).comp f = s.sup (q.comp f) := begin ext x, rw [seminorm.comp_apply, seminorm.finset_sup_apply, seminorm.finset_sup_apply], refl end variables [topological_space F] [topological_add_group F] lemma linear_map.with_seminorms_induced [hι : nonempty ι] {q : seminorm_family 𝕜 F ι} (hq : with_seminorms q) (f : E →ₗ[𝕜] F) : @with_seminorms 𝕜 E ι _ _ _ _ (q.comp f) (induced f infer_instance) := begin letI : topological_space E := induced f infer_instance, letI : topological_add_group E := topological_add_group_induced f, rw [(q.comp f).with_seminorms_iff_nhds_eq_infi, nhds_induced, map_zero, q.with_seminorms_iff_nhds_eq_infi.mp hq, filter.comap_infi], refine infi_congr (λ i, _), exact filter.comap_comap end lemma inducing.with_seminorms [hι : nonempty ι] {q : seminorm_family 𝕜 F ι} (hq : with_seminorms q) [topological_space E] {f : E →ₗ[𝕜] F} (hf : inducing f) : with_seminorms (q.comp f) := begin rw hf.induced, exact f.with_seminorms_induced hq end end topological_constructions
0ddd5bed2cfd0f90c1a27a487cc320e7d0f6df61
4fa161becb8ce7378a709f5992a594764699e268
/src/set_theory/cardinal.lean
3d1bbe1465d23c8dc029cb7f8214cefce63d427c
[ "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
45,509
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic: addition, multiplication, power, cardinal successor, minimum, supremum, infinitary sums and products ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. There is a lift operation lifting cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/ordinal.lean`, because concepts from that file are used in the proof. ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total } noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _ noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nonzero cardinal.{u} := { zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) @[simp] lemma pow_cast_right (κ : cardinal.{u}) : ∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_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 le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } instance : canonically_ordered_add_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.injective h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [←le_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (le_add_right _ _) h, lt_of_le_of_lt (le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} : mk α = 1 ↔ (subsingleton α ∧ nonempty α) := calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, classical.not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : mk (subtype p) ≤ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ := begin split, { intro h, have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union H⟩ lemma mk_sum_compl {α} (s : set α) : #s + #(-s : set α) = #α := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := mk_subtype_le s lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : mk {a : α // p (e a)} = mk {b : β // p b} := quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact 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.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal
f5cbf757640ea0e6c10fd4b88e67a4118eed9caf
a721fe7446524f18ba361625fc01033d9c8b7a78
/elaborate/append_init_last_nat.lean
1fb9d286a15d1cbdcecbf0133c95b2eff9624ca9
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
39,023
lean
λ {lst : mylist mynat} (h : lst = empty → false), mylist.rec (λ (h : empty = empty → false), false.rec (false.rec (mylist mynat) (h (eq.refl empty)) ++ false.rec mynat (h (eq.refl empty)) :: empty = empty) (h (eq.refl empty))) (λ (lst_head : mynat) (lst_tail : mylist mynat) (lst_ih : ∀ (h : lst_tail = empty → false), init lst_tail h ++ last lst_tail h :: empty = lst_tail) (h : lst_head :: lst_tail = empty → false), mylist.rec (λ (lst_ih : ∀ (h : empty = empty → false), false.rec (mylist mynat) (h (eq.refl empty)) ++ false.rec mynat (h (eq.refl empty)) :: empty = empty) (h : lst_head :: empty = empty → false), eq.rec true.intro (eq.rec (eq.refl (lst_head :: empty = lst_head :: empty)) (eq.rec (eq.rec (eq.rec (eq.refl (lst_head :: empty = lst_head :: empty)) (propext {mp := λ (h : lst_head :: empty = lst_head :: empty), ⟨eq.refl lst_head, eq.refl empty⟩, mpr := λ (a : lst_head = lst_head ∧ empty = empty), and.rec (λ (left : lst_head = lst_head) (right : empty = empty) («_» : lst_head = lst_head ∧ empty = empty), eq.refl (lst_head :: empty)) a a})) (eq.rec (eq.rec (eq.refl (lst_head = lst_head ∧ empty = empty)) (propext {mp := λ (hl : empty = empty), true.intro, mpr := λ (hr : true), eq.refl empty})) (eq.rec (eq.refl (and (lst_head = lst_head))) (propext {mp := λ (hl : lst_head = lst_head), true.intro, mpr := λ (hr : true), eq.refl lst_head})))) (propext {mp := and.left true, mpr := λ (h : true), ⟨h, h⟩})))) (λ (head : mynat) (tail : mylist mynat) (ih : (∀ (h : tail = empty → false), init tail h ++ last tail h :: empty = tail) → ∀ (h : lst_head :: tail = empty → false), init (lst_head :: tail) h ++ last (lst_head :: tail) h :: empty = lst_head :: tail) (lst_ih : ∀ (h : head :: tail = empty → false), init (head :: tail) h ++ last (head :: tail) h :: empty = head :: tail) (h : lst_head :: head :: tail = empty → false), eq.rec (lst_ih (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h))) (eq.rec (eq.refl (lst_head :: (init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty) = lst_head :: head :: tail)) (eq.rec (eq.rec (eq.rec (eq.refl (lst_head :: (init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty) = lst_head :: head :: tail)) (propext {mp := λ (h : lst_head :: (init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty) = lst_head :: head :: tail), eq.rec (λ (h11 : lst_head :: (init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty) = lst_head :: (init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty)) (a : lst_head = lst_head → init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty = init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty → lst_head = lst_head ∧ init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty = head :: tail), a (eq.refl lst_head) (eq.refl (init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty))) h h (λ (head_eq : lst_head = lst_head) (tail_eq : init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty = head :: tail), ⟨head_eq, tail_eq⟩), mpr := λ (a : lst_head = lst_head ∧ init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty = head :: tail), and.rec (λ (left : lst_head = lst_head) (right : init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty = head :: tail) («_» : lst_head = lst_head ∧ init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty = head :: tail), eq.rec (eq.refl (lst_head :: (init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty))) right) a a})) (eq.rec (eq.refl (lst_head = lst_head ∧ init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty = head :: tail)) (eq.rec (eq.refl (and (lst_head = lst_head))) (propext {mp := λ (hl : lst_head = lst_head), true.intro, mpr := λ (hr : true), eq.refl lst_head})))) (propext {mp := and.right (init (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) ++ last (head :: tail) (λ (h : head :: tail = empty), eq.rec (λ («_» : head :: tail = head :: tail) (H_1 : empty = head :: tail), eq.rec (λ (h11 : empty = empty) (a : h == eq.refl (head :: tail) → false), a) H_1 H_1) h h (eq.refl empty) (heq.refl h)) :: empty = head :: tail), mpr := and.intro true.intro})))) lst_tail lst_ih h) lst h
a7d62cc4894cb5d780f5ffdd751acb2b8605a696
9dc8cecdf3c4634764a18254e94d43da07142918
/src/geometry/euclidean/inversion.lean
0ad5c99bb4357a18e2f97ca749056afc5d44c7e2
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
5,370
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import geometry.euclidean.basic /-! # Inversion in an affine space In this file we define inversion in a sphere in an affine space. This map sends each point `x` to the point `y` such that `y -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c)`, where `c` and `R` are the center and the radius the sphere. In many applications, it is convenient to assume that the inversions swaps the center and the point at infinity. In order to stay in the original affine space, we define the map so that it sends center to itself. Currently, we prove only a few basic lemmas needed to prove Ptolemy's inequality, see `euclidean_geometry.mul_dist_le_mul_dist_add_mul_dist`. -/ noncomputable theory open metric real function namespace euclidean_geometry variables {V P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {a b c d x y z : P} {R : ℝ} include V /-- Inversion in a sphere in an affine space. This map sends each point `x` to the point `y` such that `y -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c)`, where `c` and `R` are the center and the radius the sphere. -/ def inversion (c : P) (R : ℝ) (x : P) : P := (R / dist x c) ^ 2 • (x -ᵥ c) +ᵥ c lemma inversion_vsub_center (c : P) (R : ℝ) (x : P) : inversion c R x -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c) := vadd_vsub _ _ @[simp] lemma inversion_self (c : P) (R : ℝ) : inversion c R c = c := by simp [inversion] @[simp] lemma inversion_dist_center (c x : P) : inversion c (dist x c) x = x := begin rcases eq_or_ne x c with rfl|hne, { apply inversion_self }, { rw [inversion, div_self, one_pow, one_smul, vsub_vadd], rwa [dist_ne_zero] } end lemma inversion_of_mem_sphere (h : x ∈ sphere c R) : inversion c R x = x := h.out ▸ inversion_dist_center c x /-- Distance from the image of a point under inversion to the center. This formula accidentally works for `x = c`. -/ lemma dist_inversion_center (c x : P) (R : ℝ) : dist (inversion c R x) c = R ^ 2 / dist x c := begin rcases eq_or_ne x c with (rfl|hx), { simp }, have : dist x c ≠ 0, from dist_ne_zero.2 hx, field_simp [inversion, norm_smul, abs_div, ← dist_eq_norm_vsub, sq, mul_assoc] end /-- Distance from the center of an inversion to the image of a point under the inversion. This formula accidentally works for `x = c`. -/ lemma dist_center_inversion (c x : P) (R : ℝ) : dist c (inversion c R x) = R ^ 2 / dist c x := by rw [dist_comm c, dist_comm c, dist_inversion_center] @[simp] lemma inversion_inversion (c : P) {R : ℝ} (hR : R ≠ 0) (x : P) : inversion c R (inversion c R x) = x := begin rcases eq_or_ne x c with rfl|hne, { rw [inversion_self, inversion_self] }, { rw [inversion, dist_inversion_center, inversion_vsub_center, smul_smul, ← mul_pow, div_mul_div_comm, div_mul_cancel _ (dist_ne_zero.2 hne), ← sq, div_self, one_pow, one_smul, vsub_vadd], exact pow_ne_zero _ hR } end lemma inversion_involutive (c : P) {R : ℝ} (hR : R ≠ 0) : involutive (inversion c R) := inversion_inversion c hR lemma inversion_surjective (c : P) {R : ℝ} (hR : R ≠ 0) : surjective (inversion c R) := (inversion_involutive c hR).surjective lemma inversion_injective (c : P) {R : ℝ} (hR : R ≠ 0) : injective (inversion c R) := (inversion_involutive c hR).injective lemma inversion_bijective (c : P) {R : ℝ} (hR : R ≠ 0) : bijective (inversion c R) := (inversion_involutive c hR).bijective /-- Distance between the images of two points under an inversion. -/ lemma dist_inversion_inversion (hx : x ≠ c) (hy : y ≠ c) (R : ℝ) : dist (inversion c R x) (inversion c R y) = (R ^ 2 / (dist x c * dist y c)) * dist x y := begin dunfold inversion, simp_rw [dist_vadd_cancel_right, dist_eq_norm_vsub V _ c], simpa only [dist_vsub_cancel_right] using dist_div_norm_sq_smul (vsub_ne_zero.2 hx) (vsub_ne_zero.2 hy) R end /-- **Ptolemy's inequality**: in a quadrangle `ABCD`, `|AC| * |BD| ≤ |AB| * |CD| + |BC| * |AD|`. If `ABCD` is a convex cyclic polygon, then this inequality becomes an equality, see `euclidean_geometry.mul_dist_add_mul_dist_eq_mul_dist_of_cospherical`. -/ lemma mul_dist_le_mul_dist_add_mul_dist (a b c d : P) : dist a c * dist b d ≤ dist a b * dist c d + dist b c * dist a d := begin -- If one of the points `b`, `c`, `d` is equal to `a`, then the inequality is trivial. rcases eq_or_ne b a with rfl|hb, { rw [dist_self, zero_mul, zero_add] }, rcases eq_or_ne c a with rfl|hc, { rw [dist_self, zero_mul], apply_rules [add_nonneg, mul_nonneg, dist_nonneg] }, rcases eq_or_ne d a with rfl|hd, { rw [dist_self, mul_zero, add_zero, dist_comm d, dist_comm d, mul_comm] }, /- Otherwise, we apply the triangle inequality to `euclidean_geometry.inversion a 1 b`, `euclidean_geometry.inversion a 1 c`, and `euclidean_geometry.inversion a 1 d`. -/ have H := dist_triangle (inversion a 1 b) (inversion a 1 c) (inversion a 1 d), rw [dist_inversion_inversion hb hd, dist_inversion_inversion hb hc, dist_inversion_inversion hc hd, one_pow] at H, rw [← dist_pos] at hb hc hd, rw [← div_le_div_right (mul_pos hb (mul_pos hc hd))], convert H; { field_simp [hb.ne', hc.ne', hd.ne', dist_comm a], ring } end end euclidean_geometry
c259e5b81def8390e8efbce32ef0574d6e2ac486
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/lie/engel.lean
78ba41c33c521738a658ca087a646f9126bfdc6b
[ "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
13,623
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.nilpotent import algebra.lie.centralizer /-! # Engel's theorem This file contains a proof of Engel's theorem providing necessary and sufficient conditions for Lie algebras and Lie modules to be nilpotent. The key result `lie_module.is_nilpotent_iff_forall` says that if `M` is a Lie module of a Noetherian Lie algebra `L`, then `M` is nilpotent iff the image of `L → End(M)` consists of nilpotent elements. In the special case that we have the adjoint representation `M = L`, this says that a Lie algebra is nilpotent iff `ad x : End(L)` is nilpotent for all `x : L`. Engel's theorem is true for any coefficients (i.e., it is really a theorem about Lie rings) and so we work with coefficients in any commutative ring `R` throughout. On the other hand, Engel's theorem is not true for infinite-dimensional Lie algebras and so a finite-dimensionality assumption is required. We prove the theorem subject to the the assumption that the Lie algebra is Noetherian as an `R`-module, though actually we only need the slightly weaker property that the relation `>` is well-founded on the complete lattice of Lie subalgebras. ## Remarks about the proof Engel's theorem is usually proved in the special case that the coefficients are a field, and uses an inductive argument on the dimension of the Lie algebra. One begins by choosing either a maximal proper Lie subalgebra (in some proofs) or a maximal nilpotent Lie subalgebra (in other proofs, at the cost of obtaining a weaker end result). Since we work with general coefficients, we cannot induct on dimension and an alternate approach must be taken. The key ingredient is the concept of nilpotency, not just for Lie algebras, but for Lie modules. Using this concept, we define an _Engelian Lie algebra_ `lie_algebra.is_engelian` to be one for which a Lie module is nilpotent whenever the action consists of nilpotent endomorphisms. The argument then proceeds by selecting a maximal Engelian Lie subalgebra and showing that it cannot be proper. The first part of the traditional statement of Engel's theorem consists of the statement that if `M` is a non-trivial `R`-module and `L ⊆ End(M)` is a finite-dimensional Lie subalgebra of nilpotent elements, then there exists a non-zero element `m : M` that is annihilated by every element of `L`. This follows trivially from the result established here `lie_module.is_nilpotent_iff_forall`, that `M` is a nilpotent Lie module over `L`, since the last non-zero term in the lower central series will consist of such elements `m` (see: `lie_module.nontrivial_max_triv_of_is_nilpotent`). It seems that this result has not previously been established at this level of generality. The second part of the traditional statement of Engel's theorem concerns nilpotency of the Lie algebra and a proof of this for general coefficients appeared in the literature as long ago [as 1937](zorn1937). This also follows trivially from `lie_module.is_nilpotent_iff_forall` simply by taking `M = L`. It is pleasing that the two parts of the traditional statements of Engel's theorem are thus unified into a single statement about nilpotency of Lie modules. This is not usually emphasised. ## Main definitions * `lie_algebra.is_engelian` * `lie_algebra.is_engelian_of_is_noetherian` * `lie_module.is_nilpotent_iff_forall` * `lie_algebra.is_nilpotent_iff_forall` -/ universes u₁ u₂ u₃ u₄ variables {R : Type u₁} {L : Type u₂} {L₂ : Type u₃} {M : Type u₄} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L₂] [lie_algebra R L₂] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] include R L namespace lie_submodule open lie_module variables {I : lie_ideal R L} {x : L} (hxI : (R ∙ x) ⊔ I = ⊤) include hxI lemma exists_smul_add_of_span_sup_eq_top (y : L) : ∃ (t : R) (z ∈ I), y = t • x + z := begin have hy : y ∈ (⊤ : submodule R L) := submodule.mem_top, simp only [← hxI, submodule.mem_sup, submodule.mem_span_singleton] at hy, obtain ⟨-, ⟨t, rfl⟩, z, hz, rfl⟩ := hy, exact ⟨t, z, hz, rfl⟩, end lemma lie_top_eq_of_span_sup_eq_top (N : lie_submodule R L M) : (↑⁅(⊤ : lie_ideal R L), N⁆ : submodule R M) = (N : submodule R M).map (to_endomorphism R L M x) ⊔ (↑⁅I, N⁆ : submodule R M) := begin simp only [lie_ideal_oper_eq_linear_span', submodule.sup_span, mem_top, exists_prop, exists_true_left, submodule.map_coe, to_endomorphism_apply_apply], refine le_antisymm (submodule.span_le.mpr _) (submodule.span_mono (λ z hz, _)), { rintros z ⟨y, n, hn : n ∈ N, rfl⟩, obtain ⟨t, z, hz, rfl⟩ := exists_smul_add_of_span_sup_eq_top hxI y, simp only [set_like.mem_coe, submodule.span_union, submodule.mem_sup], exact ⟨t • ⁅x, n⁆, submodule.subset_span ⟨t • n, N.smul_mem' t hn, lie_smul t x n⟩, ⁅z, n⁆, submodule.subset_span ⟨z, hz, n, hn, rfl⟩, by simp⟩, }, { rcases hz with ⟨m, hm, rfl⟩ | ⟨y, hy, m, hm, rfl⟩, exacts [⟨x, m, hm, rfl⟩, ⟨y, m, hm, rfl⟩], }, end lemma lcs_le_lcs_of_is_nilpotent_span_sup_eq_top {n i j : ℕ} (hxn : (to_endomorphism R L M x)^n = 0) (hIM : lower_central_series R L M i ≤ I.lcs M j) : lower_central_series R L M (i + n) ≤ I.lcs M (j + 1) := begin suffices : ∀ l, ((⊤ : lie_ideal R L).lcs M (i + l) : submodule R M) ≤ (I.lcs M j : submodule R M).map ((to_endomorphism R L M x)^l) ⊔ (I.lcs M (j + 1) : submodule R M), { simpa only [bot_sup_eq, lie_ideal.incl_coe, submodule.map_zero, hxn] using this n, }, intros l, induction l with l ih, { simp only [add_zero, lie_ideal.lcs_succ, pow_zero, linear_map.one_eq_id, submodule.map_id], exact le_sup_of_le_left hIM, }, { simp only [lie_ideal.lcs_succ, i.add_succ l, lie_top_eq_of_span_sup_eq_top hxI, sup_le_iff], refine ⟨(submodule.map_mono ih).trans _, le_sup_of_le_right _⟩, { rw [submodule.map_sup, ← submodule.map_comp, ← linear_map.mul_eq_comp, ← pow_succ, ← I.lcs_succ], exact sup_le_sup_left coe_map_to_endomorphism_le _, }, { refine le_trans (mono_lie_right _ _ I _) (mono_lie_right _ _ I hIM), exact antitone_lower_central_series R L M le_self_add, }, }, end lemma is_nilpotent_of_is_nilpotent_span_sup_eq_top (hnp : is_nilpotent $ to_endomorphism R L M x) (hIM : is_nilpotent R I M) : is_nilpotent R L M := begin obtain ⟨n, hn⟩ := hnp, unfreezingI { obtain ⟨k, hk⟩ := hIM, }, have hk' : I.lcs M k = ⊥, { simp only [← coe_to_submodule_eq_iff, I.coe_lcs_eq, hk, bot_coe_submodule], }, suffices : ∀ l, lower_central_series R L M (l * n) ≤ I.lcs M l, { use k * n, simpa [hk'] using this k, }, intros l, induction l with l ih, { simp, }, { exact (l.succ_mul n).symm ▸ lcs_le_lcs_of_is_nilpotent_span_sup_eq_top hxI hn ih, }, end end lie_submodule section lie_algebra open lie_module (hiding is_nilpotent) variables (R L) /-- A Lie algebra `L` is said to be Engelian if a sufficient condition for any `L`-Lie module `M` to be nilpotent is that the image of the map `L → End(M)` consists of nilpotent elements. Engel's theorem `lie_algebra.is_engelian_of_is_noetherian` states that any Noetherian Lie algebra is Engelian. -/ def lie_algebra.is_engelian : Prop := ∀ (M : Type u₄) [add_comm_group M], by exactI ∀ [module R M] [lie_ring_module L M], by exactI ∀ [lie_module R L M], by exactI ∀ (h : ∀ (x : L), is_nilpotent (to_endomorphism R L M x)), lie_module.is_nilpotent R L M variables {R L} lemma lie_algebra.is_engelian_of_subsingleton [subsingleton L] : lie_algebra.is_engelian R L := begin intros M _i1 _i2 _i3 _i4 h, use 1, suffices : (⊤ : lie_ideal R L) = ⊥, { simp [this], }, haveI := (lie_submodule.subsingleton_iff R L L).mpr infer_instance, apply subsingleton.elim, end lemma function.surjective.is_engelian {f : L →ₗ⁅R⁆ L₂} (hf : function.surjective f) (h : lie_algebra.is_engelian.{u₁ u₂ u₄} R L) : lie_algebra.is_engelian.{u₁ u₃ u₄} R L₂ := begin introsI M _i1 _i2 _i3 _i4 h', letI : lie_ring_module L M := lie_ring_module.comp_lie_hom M f, letI : lie_module R L M := comp_lie_hom M f, have hnp : ∀ x, is_nilpotent (to_endomorphism R L M x) := λ x, h' (f x), have surj_id : function.surjective (linear_map.id : M →ₗ[R] M) := function.surjective_id, haveI : lie_module.is_nilpotent R L M := h M hnp, apply hf.lie_module_is_nilpotent surj_id, simp, end lemma lie_equiv.is_engelian_iff (e : L ≃ₗ⁅R⁆ L₂) : lie_algebra.is_engelian.{u₁ u₂ u₄} R L ↔ lie_algebra.is_engelian.{u₁ u₃ u₄} R L₂ := ⟨e.surjective.is_engelian, e.symm.surjective.is_engelian⟩ lemma lie_algebra.exists_engelian_lie_subalgebra_of_lt_normalizer {K : lie_subalgebra R L} (hK₁ : lie_algebra.is_engelian.{u₁ u₂ u₄} R K) (hK₂ : K < K.normalizer) : ∃ (K' : lie_subalgebra R L) (hK' : lie_algebra.is_engelian.{u₁ u₂ u₄} R K'), K < K' := begin obtain ⟨x, hx₁, hx₂⟩ := set_like.exists_of_lt hK₂, let K' : lie_subalgebra R L := { lie_mem' := λ y z, lie_subalgebra.lie_mem_sup_of_mem_normalizer hx₁, .. (R ∙ x) ⊔ (K : submodule R L) }, have hxK' : x ∈ K' := submodule.mem_sup_left (submodule.subset_span (set.mem_singleton _)), have hKK' : K ≤ K' := (lie_subalgebra.coe_submodule_le_coe_submodule K K').mp le_sup_right, have hK' : K' ≤ K.normalizer, { rw ← lie_subalgebra.coe_submodule_le_coe_submodule, exact sup_le ((submodule.span_singleton_le_iff_mem _ _).mpr hx₁) hK₂.le, }, refine ⟨K', _, lt_iff_le_and_ne.mpr ⟨hKK', λ contra, hx₂ (contra.symm ▸ hxK')⟩⟩, introsI M _i1 _i2 _i3 _i4 h, obtain ⟨I, hI₁ : (I : lie_subalgebra R K') = lie_subalgebra.of_le hKK'⟩ := lie_subalgebra.exists_nested_lie_ideal_of_le_normalizer hKK' hK', have hI₂ : (R ∙ (⟨x, hxK'⟩ : K')) ⊔ I = ⊤, { rw [← lie_ideal.coe_to_lie_subalgebra_to_submodule R K' I, hI₁], apply submodule.map_injective_of_injective (K' : submodule R L).injective_subtype, simpa, }, have e : K ≃ₗ⁅R⁆ I := (lie_subalgebra.equiv_of_le hKK').trans (lie_equiv.of_eq _ _ ((lie_subalgebra.coe_set_eq _ _).mpr hI₁.symm)), have hI₃ : lie_algebra.is_engelian R I := e.is_engelian_iff.mp hK₁, exact lie_submodule.is_nilpotent_of_is_nilpotent_span_sup_eq_top hI₂ (h _) (hI₃ _ (λ x, h x)), end local attribute [instance] lie_subalgebra.subsingleton_bot variables [is_noetherian R L] /-- *Engel's theorem*. Note that this implies all traditional forms of Engel's theorem via `lie_module.nontrivial_max_triv_of_is_nilpotent`, `lie_module.is_nilpotent_iff_forall`, `lie_algebra.is_nilpotent_iff_forall`. -/ lemma lie_algebra.is_engelian_of_is_noetherian : lie_algebra.is_engelian R L := begin introsI M _i1 _i2 _i3 _i4 h, rw ← is_nilpotent_range_to_endomorphism_iff, let L' := (to_endomorphism R L M).range, replace h : ∀ (y : L'), is_nilpotent (y : module.End R M), { rintros ⟨-, ⟨y, rfl⟩⟩, simp [h], }, change lie_module.is_nilpotent R L' M, let s := { K : lie_subalgebra R L' | lie_algebra.is_engelian R K }, have hs : s.nonempty := ⟨⊥, lie_algebra.is_engelian_of_subsingleton⟩, suffices : ⊤ ∈ s, { rw ← is_nilpotent_of_top_iff, apply this M, simp [lie_subalgebra.to_endomorphism_eq, h], }, have : ∀ (K ∈ s), K ≠ ⊤ → ∃ (K' ∈ s), K < K', { rintros K (hK₁ : lie_algebra.is_engelian R K) hK₂, apply lie_algebra.exists_engelian_lie_subalgebra_of_lt_normalizer hK₁, apply lt_of_le_of_ne K.le_normalizer, rw [ne.def, eq_comm, K.normalizer_eq_self_iff, ← ne.def, ← lie_submodule.nontrivial_iff_ne_bot R K], haveI : nontrivial (L' ⧸ K.to_lie_submodule), { replace hK₂ : K.to_lie_submodule ≠ ⊤ := by rwa [ne.def, ← lie_submodule.coe_to_submodule_eq_iff, K.coe_to_lie_submodule, lie_submodule.top_coe_submodule, ← lie_subalgebra.top_coe_submodule, K.coe_to_submodule_eq_iff], exact submodule.quotient.nontrivial_of_lt_top _ hK₂.lt_top, }, haveI : lie_module.is_nilpotent R K (L' ⧸ K.to_lie_submodule), { refine hK₁ _ (λ x, _), have hx := lie_algebra.is_nilpotent_ad_of_is_nilpotent (h x), exact module.End.is_nilpotent.mapq _ hx, }, exact nontrivial_max_triv_of_is_nilpotent R K (L' ⧸ K.to_lie_submodule), }, haveI _i5 : is_noetherian R L' := is_noetherian_of_surjective L _ (linear_map.range_range_restrict (to_endomorphism R L M)), obtain ⟨K, hK₁, hK₂⟩ := well_founded.well_founded_iff_has_max'.mp (lie_subalgebra.well_founded_of_noetherian R L') s hs, have hK₃ : K = ⊤, { by_contra contra, obtain ⟨K', hK'₁, hK'₂⟩ := this K hK₁ contra, specialize hK₂ K' hK'₁ (le_of_lt hK'₂), replace hK'₂ := (ne_of_lt hK'₂).symm, contradiction, }, exact hK₃ ▸ hK₁, end /-- Engel's theorem. -/ lemma lie_module.is_nilpotent_iff_forall : lie_module.is_nilpotent R L M ↔ ∀ x, is_nilpotent $ to_endomorphism R L M x := ⟨begin introsI h, obtain ⟨k, hk⟩ := nilpotent_endo_of_nilpotent_module R L M, exact λ x, ⟨k, hk x⟩, end, λ h, lie_algebra.is_engelian_of_is_noetherian M h⟩ /-- Engel's theorem. -/ lemma lie_algebra.is_nilpotent_iff_forall : lie_algebra.is_nilpotent R L ↔ ∀ x, is_nilpotent $ lie_algebra.ad R L x := lie_module.is_nilpotent_iff_forall end lie_algebra
c937324434db5e6155b33ef60ba49834a1ac5cde
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/algebra/group_power/lemmas.lean
e5f001a7bdfac68d7a5f6277d85e4a90200ac5af
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
34,910
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.group_power.basic import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import deprecated.group /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul` which require additional imports besides those available in `.basic`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem pow_one (a : M) : a^1 = a := mul_one _ @[simp] theorem one_nsmul (a : A) : 1 •ℕ a = a := add_zero _ @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp @[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem nsmul_zero (n : ℕ) : n •ℕ (0 : A) = 0 := by induction n with n ih; [refl, rw [succ_nsmul, ih, zero_add]] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem mul_nsmul' : ∀ (a : A) (m n : ℕ), m * n •ℕ a = n •ℕ (m •ℕ a) := @pow_mul (multiplicative A) _ theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [mul_comm, pow_mul] theorem mul_nsmul (a : A) (m n : ℕ) : m * n •ℕ a = m •ℕ (n •ℕ a) := @pow_mul' (multiplicative A) _ a m n theorem pow_mul_pow_sub (a : M) {m n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n := by rw [←pow_add, nat.add_sub_cancel' h] theorem nsmul_add_sub_nsmul (a : A) {m n : ℕ} (h : m ≤ n) : (m •ℕ a) + ((n - m) •ℕ a) = n •ℕ a := @pow_mul_pow_sub (multiplicative A) _ _ _ _ h theorem pow_sub_mul_pow (a : M) {m n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n := by rw [←pow_add, nat.sub_add_cancel h] theorem sub_nsmul_nsmul_add (a : A) {m n : ℕ} (h : m ≤ n) : ((n - m) •ℕ a) + (m •ℕ a) = n •ℕ a := @pow_sub_mul_pow (multiplicative A) _ _ _ _ h @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_nsmul (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ a + n •ℕ a := add_nsmul _ _ _ theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_nsmul : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ a + n •ℕ a + a := @pow_bit1 (multiplicative A) _ theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n theorem nsmul_add_comm : ∀ (a : A) (m n : ℕ), m •ℕ a + n •ℕ a = n •ℕ a + m •ℕ a := @pow_mul_comm (multiplicative A) _ @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { refl }, { rw [list.repeat_succ, list.prod_cons, ih], refl, } end @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a := @list.prod_repeat (multiplicative A) _ theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := f.map_one | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] theorem add_monoid_hom.map_nsmul (f : A →+ B) (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := f.to_multiplicative.map_pow a n theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n := (monoid_hom.of f).map_pow a theorem is_add_monoid_hom.map_nsmul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := (add_monoid_hom.of f).map_nsmul a n @[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := nat.rec_on n (by simp) $ λ n ihn, by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm] theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n := (neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n end monoid theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n := by induction m with m ih; [rw [zero_nsmul, zero_mul], rw [succ_nsmul', ih, nat.succ_mul]] /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n theorem nsmul_add : ∀ (a b : A) (n : ℕ), n •ℕ (a + b) = n •ℕ a + n •ℕ b := @mul_pow (multiplicative A) _ instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance nsmul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (nsmul n : A → A) := { map_add := λ _ _, nsmul_add _ _ _, map_zero := nsmul_zero _ } lemma dvd_pow {x y : M} : ∀ {n : ℕ} (hxy : x ∣ y) (hn : n ≠ 0), x ∣ y^n | 0 hxy hn := (hn rfl).elim | (n+1) hxy hn := by { rw [pow_succ], exact dvd_mul_of_dvd_left hxy _ } end comm_monoid section group variables [group G] [group H] [add_group A] [add_group B] section nat @[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem neg_nsmul : ∀ (a : A) (n : ℕ), n •ℕ (-a) = -(n •ℕ a) := @inv_pow (multiplicative A) _ theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem nsmul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n) •ℕ a = m •ℕ a - n •ℕ a := @pow_sub (multiplicative A) _ theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := (commute.refl a).inv_left.pow_pow m n theorem nsmul_neg_comm : ∀ (a : A) (m n : ℕ), m •ℕ (-a) + n •ℕ a = n •ℕ a + m •ℕ (-a) := @pow_inv_comm (multiplicative A) _ end nat open int @[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : n •ℤ a = n •ℕ a := rfl theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n •ℤ a = n •ℕ a := rfl @[simp] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ_of_nat (a : A) (n : ℕ) : -[1+n] •ℤ a = - (n.succ •ℕ a) := rfl local attribute [ematch] le_of_lt open nat @[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : A) : (0:ℤ) •ℤ a = 0 := rfl @[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := pow_one a @[simp] theorem one_gsmul (a : A) : (1:ℤ) •ℤ a = a := add_zero _ @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:G), by rw [_root_.one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n •ℤ (0 : A) = 0 := @one_gpow (multiplicative A) _ @[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm lemma mul_gpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) := by simp only [mul_inv_rev, gpow_one, gpow_neg] @[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n •ℤ a = -(n •ℤ a) := @gpow_neg (multiplicative A) _ theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : A) : (-1:ℤ) •ℤ x = -x := congr_arg has_neg.neg $ one_nsmul x theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n := by cases n; simp theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a := @inv_gpow (multiplicative A) _ a n lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, _root_.pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a := @gpow_add_one (multiplicative A) _ lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel] lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] }, { rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] } end lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] } lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] } theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a := @gpow_add (multiplicative A) _ lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, gpow_add, gpow_neg] lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a := @gpow_sub (multiplicative A) _ _ _ _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn]) (λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one]) theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add]; simp [gpow_bit0] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a := @gpow_bit1 (multiplicative A) _ theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a := f.to_multiplicative.map_gpow a n @[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_gpow u n theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n | (n : ℕ) := h.mul_pow n | -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq] end group section comm_group variables [comm_group G] [add_comm_group A] theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative A) _ theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b := by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) := { map_mul := λ _ _, mul_gpow _ _ n } instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) := { map_add := λ _ _, gsmul_add _ _ n } end comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((nsmul n a : A) : with_bot A) = nsmul n a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] lemma zero_pow [monoid_with_zero R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := zero_mul _ @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]] @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]] namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a end ring_hom theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul h (pow_dvd_pow_of_dvd n) lemma pow_two_sub_pow_two {R : Type*} [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by simp only [pow_two, mul_sub, add_mul, sub_sub, add_sub, mul_comm, sub_add_cancel] lemma eq_or_eq_neg_of_pow_two_eq_pow_two [integral_domain R] (a b : R) (h : a ^ 2 = b ^ 2) : a = b ∨ a = -b := by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero, ← pow_two_sub_pow_two a b, sub_eq_zero] -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) := by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) := by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a | (n : ℕ) := nsmul_eq_mul _ _ | -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, (n.cast_commute a).eq] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul] lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [pow_two, pow_two, mul_self_sub_mul_self] theorem pow_eq_zero [monoid_with_zero R] [no_zero_divisors R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end @[field_simps] theorem pow_ne_zero [monoid_with_zero R] [no_zero_divisors R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h theorem nsmul_nonneg [ordered_add_comm_monoid R] {a : R} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n •ℕ a | 0 := le_refl _ | (n+1) := add_nonneg H (nsmul_nonneg n) lemma pow_abs [decidable_linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma abs_neg_one_pow [decidable_linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] section add_monoid variable [ordered_add_comm_monoid A] theorem nsmul_le_nsmul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℕ a ≤ m •ℕ a := let ⟨k, hk⟩ := nat.le.dest h in calc n •ℕ a = n •ℕ a + 0 : (add_zero _).symm ... ≤ n •ℕ a + k •ℕ a : add_le_add_left (nsmul_nonneg ha _) _ ... = m •ℕ a : by rw [← hk, add_nsmul] lemma nsmul_le_nsmul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i •ℕ a ≤ i •ℕ b | 0 := by simp | (k+1) := add_le_add hab (nsmul_le_nsmul_of_le_right _) end add_monoid namespace canonically_ordered_semiring variable [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n | 0 := canonically_ordered_semiring.zero_lt_one | (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa only [one_pow] using pow_le_pow_of_le_left H n theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:= by simpa only [one_pow] using pow_le_pow_of_le_left H n end canonically_ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := zero_lt_one | (n+1) := mul_pos H (pow_pos _) theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := begin rcases lt_trichotomy x y with hxy | rfl | hyx, { exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) }, { refl }, { exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) }, end theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) /-- Bernoulli's inequality. This version works for semirings but requires an additional hypothesis `0 ≤ a * a`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) : ∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := calc 1 + (n + 1) •ℕ a ≤ (1 + a) * (1 + n •ℕ a) : by simpa [succ_nsmul, mul_add, add_mul, mul_nsmul_left, add_comm, add_left_comm] using nsmul_nonneg Hsqr n ... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := begin have h' : 1 ≤ a := le_of_lt h, have h'' : 0 < a := lt_trans zero_lt_one h, cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)], exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'') end lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : R) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring R] (a : R) : 0 ≤ a ^ 2 := by { rw pow_two, exact mul_self_nonneg _ } theorem pow_two_pos_of_ne_zero [linear_ordered_ring R] (a : R) (h : a ≠ 0) : 0 < a ^ 2 := lt_of_le_of_ne (pow_two_nonneg a) (pow_ne_zero 2 h).symm /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow [linear_ordered_ring R] {a : R} (H : -2 ≤ a) : ∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | 1 := by simp | (n+2) := have H' : 0 ≤ 2 + a, from neg_le_iff_add_nonneg.1 H, have 0 ≤ n •ℕ (a * a * (2 + a)) + a * a, from add_nonneg (nsmul_nonneg (mul_nonneg (mul_self_nonneg a) H') n) (mul_self_nonneg a), calc 1 + (n + 2) •ℕ a ≤ 1 + (n + 2) •ℕ a + (n •ℕ (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n •ℕ a) : by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_nsmul, nsmul_add, mul_nsmul_assoc, (mul_nsmul_left _ _ _).symm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a)) ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_sub_mul_le_pow [linear_ordered_ring R] {a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n •ℕ (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 }, by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] @[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [pow_two, int.nat_abs_mul_self', pow_two] end int @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n •ℕ x) = (multiplicative.of_add x)^n := rfl lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) } variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl lemma mnat_monoid_hom_eq [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] lemma mnat_monoid_hom_ext [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [mnat_monoid_hom_eq f, mnat_monoid_hom_eq g, h] /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] @[simp] lemma gpow_right {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := h.pow_right n | -[1+n] := (h.pow_right n.succ).inv_right variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_gpow_right m @[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_gpow_right m).symm section variables {a b : G} @[simp] lemma gpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.gpow_right m @[simp] lemma gpow_left (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.gpow_right m).symm lemma gpow_gpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.gpow_left m).gpow_right n variables (a) (m n : ℕ) @[simp] theorem self_gpow : commute a (a ^ n) := (commute.refl a).gpow_right n @[simp] theorem gpow_self : commute (a ^ n) a := (commute.refl a).gpow_left n @[simp] theorem gpow_gpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).gpow_gpow m n end variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [gpow_add, mul_add] {contextual := tt}) (by simp [gpow_add, mul_add, sub_eq_add_neg] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_gpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n open opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', op_mul, h, pow_succ] } end @[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', unop_mul, h, pow_succ] } end end units
2be731b34fe28e0fa78092dbfc785ad68457b552
3b1abba731363bfec018d9d2cfee7fd90e1dc93c
/RT_n_m.lean
bfe8c4055f59646a065f9ebb1bee1f85a1e7e0e8
[]
no_license
minchaowu/Ramsey.lean
dcf4e0845cca6dc02ef898f3fd9123c079c5a1a9
8ebbead4869bdf3f4788137411c5f36f2e72943a
refs/heads/master
1,610,462,544,433
1,488,596,497,000
1,488,596,497,000
72,063,527
0
0
null
null
null
null
UTF-8
Lean
false
false
4,959
lean
import definitions lemmas_for_RT_n_m RT_1_2 RT_n_2 open classical set nat decidable noncomputable theory theorem RT_n_m (n m : ℕ) : ∀ X : set ℕ, ∀ c : set ℕ → ℕ, infinite X → is_coloring X (n+1) (m+2) c → ∃ S, S ⊆ X ∧ infinite S ∧ is_homogeneous X c (n+1) (m+2) S := nat.induction_on m (take X, take c, assume H1, assume H2, show ∃ S, S ⊆ X ∧ infinite S ∧ is_homogeneous X c (n+1) (0+2) S, from RT_n_2 n X c H1 H2) (take m, assume IH, take X, take c, assume Hinf, assume Hic, let c' (s : set ℕ) : ℕ := if c s = (m+(2:ℕ)) then (1:ℕ) else 0 in have is_coloring X (n+1) 2 c', from take a, assume Ha, by_cases (suppose Hca : c a = m+2, have Hcca : c' a = (1:ℕ),from if_pos Hca, by_contradiction (assume Hn : ¬ c' a < 2, have H12 : 1 < (2:ℕ), from dec_trivial, have ¬ 1 < (2:ℕ), by+ rewrite Hcca at Hn;exact Hn, this H12)) (suppose Hnca : c a ≠ m+2, have Hcca : c' a = (0:ℕ),from if_neg Hnca, by_contradiction (assume Hn : ¬ c' a < 2, have H02 : 0 < (2:ℕ), from dec_trivial, have ¬ 0 < (2:ℕ), by+ rewrite Hcca at Hn;exact Hn, this H02)), have ∃ S, S ⊆ X ∧ infinite S ∧ is_homogeneous X c' (n+1) 2 S, from RT_n_2 _ _ _ Hinf this, obtain (H : set ℕ) (Hp : H ⊆ X ∧ infinite H ∧ is_homogeneous X c' (n+1) 2 H), from this, have Hsub : H ⊆ X, from and.left Hp, have HinfH : infinite H, from and.left (and.right Hp), --show ∃ H, H ⊆ X ∧ infinite H ∧ is_homogeneous X c (n+1) (m+3) H, from by_cases (suppose Ha : ∀₀ a ∈ tuples H (n+1), c' a = 1, have Hp1 : H ⊆ X, from and.left Hp, have ∀₀ a ∈ tuples H (n+1), ∀₀ b ∈ tuples H (n+1), c a = c b, from take a, assume Hta, take b, assume Htb, have Hc'a : c' a = 1, from Ha Hta, have (1:ℕ) ≠ 0, from dec_trivial, have Hcaneq0 : c' a ≠ 0, by+ rewrite -Hc'a at this;exact this, have Hca : c a = m+2, from by_contradiction (assume Hc : c a ≠ m+2, have c' a = 0, from if_neg Hc, Hcaneq0 this), have Hc'b : c' b = 1, from Ha Htb, have (1:ℕ) ≠ 0, from dec_trivial, have Hcbneq0 : c' b ≠ 0, by+ rewrite -Hc'b at this;exact this, have Hcb : c b = m+2, from by_contradiction (assume Hc : c b ≠ m+2, have c' b = 0, from if_neg Hc, Hcbneq0 this), begin+ rewrite -Hcb at Hca, exact Hca end, have is_homogeneous X c (n+1) (m+3) H, from and.intro Hic (and.intro Hp1 this), have H ⊆ X ∧ infinite H ∧ is_homogeneous X c (n+1) (m+3) H, from and.intro Hsub (and.intro HinfH this), exists.intro H this) (suppose ¬∀₀ a ∈ tuples H (n+1), c' a = 1, have ∃₀ a ∈ tuples H (n+1), ¬ c' a = 1, by+ rewrite not_bounded_forall at this;exact this, obtain (a : set ℕ) (Hc'a1 : a ∈ tuples H (n+1) ∧ c' a ≠ 1), from this, have Hc'aneq1 : c' a ≠ 1, from and.right Hc'a1, have c a ≠ m+2, from by_contradiction (suppose ¬ c a ≠ m+2, have c a = m+2, from dne this, have c' a = 1, from if_pos this, Hc'aneq1 this), have Hc'aeq0 : c' a = 0, from if_neg this, have Hall0 : ∀₀ a ∈ tuples H (n+1), c' a = 0, from take b, assume Hbt, have is_homogeneous X c' (n+1) 2 H, from and.right (and.right Hp), have ∀₀ a ∈ tuples H (n+1), ∀₀ b ∈ tuples H (n+1), c' a = c' b, from and.right (and.right this), have c' a = c' b, from this (and.left Hc'a1) Hbt, by+ rewrite this at Hc'aeq0;exact Hc'aeq0, have is_coloring H (n+1) (m+2) c, from take d, assume Hdt, have Hcdneq : c d ≠ m+2, from by_contradiction (suppose ¬ c d ≠ m+2, have c d = m+2, from dne this, have Hc'deq1 : c' d = 1, from if_pos this, have Hc'd0 : c' d = 0, from Hall0 Hdt, have (0:ℕ) ≠ 1, from dec_trivial, have c' d ≠ 1, by+ rewrite -Hc'd0 at this;exact this, this Hc'deq1), have d ∈ tuples X (n+1), from sub_tuples H X (and.left Hp) (n+1) Hdt, have c d < m+3, from Hic this, have c d ≤ m+2, from le_of_lt_succ this, have c d < m+2 ∨ c d = m+2, from lt_or_eq_of_le this, or_resolve_left this Hcdneq, have ∃ S, S ⊆ H ∧ infinite S ∧ is_homogeneous H c (n+1) (m+2) S, from IH H c HinfH this, obtain (S : set ℕ) (HS : S ⊆ H ∧ infinite S ∧ is_homogeneous H c (n+1) (m+2) S), from this, have HsubS : S ⊆ X, from subset.trans (and.left HS) Hsub, have HinfS : infinite S, from and.left (and.right HS), have is_homogeneous H c (n+1) (m+2) S, from and.right (and.right HS), have ∀₀ a ∈ tuples S (n+1), ∀₀ b ∈ tuples S (n+1), c a = c b, from and.right (and.right this), have is_homogeneous X c (n+1) (m+3) S, from and.intro Hic (and.intro HsubS this), have S ⊆ X ∧ infinite S ∧ is_homogeneous X c (n+1) (m+3) S, from and.intro HsubS (and.intro HinfS this), exists.intro S this)) check RT_n_m
e3233bba1cc6ce22d324dba016f141ea8e89043c
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/topology/homeomorph.lean
64328f6ebcc5a2bebc04b04cb1c08487ca2c11a7
[ "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
12,608
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton -/ import topology.dense_embedding open set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Homeomorphism between `α` and `β`, also called topological isomorphism -/ @[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends α ≃ β := (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') (continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity') infix ` ≃ₜ `:25 := homeomorph namespace homeomorph variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : has_coe_to_fun (α ≃ₜ β) := ⟨λ_, α → β, λe, e.to_equiv⟩ @[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) : ((homeomorph.mk a b c) : α → β) = a := rfl lemma coe_eq_to_equiv (h : α ≃ₜ β) (a : α) : h a = h.to_equiv a := rfl lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β) | ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl @[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' := to_equiv_injective $ equiv.ext H /-- Identity map as a homeomorphism. -/ protected def refl (α : Type*) [topological_space α] : α ≃ₜ α := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, to_equiv := equiv.refl α } @[simp] lemma coe_refl : ⇑(homeomorph.refl α) = id := rfl /-- Composition of two homeomorphisms. -/ protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ := { continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun, continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun, to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv } /-- Inverse of a homeomorphism. -/ protected def symm (h : α ≃ₜ β) : β ≃ₜ α := { continuous_to_fun := h.continuous_inv_fun, continuous_inv_fun := h.continuous_to_fun, to_equiv := h.to_equiv.symm } @[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) : ((homeomorph.mk a b c).symm : β → α) = a.symm := rfl @[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl @[continuity] protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun @[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x := h.to_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x := h.to_equiv.symm_apply_apply x protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective /-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/ def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β := have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm ... = f.symm x : by rw hg x), { to_fun := f, inv_fun := g, left_inv := by convert f.left_inv, right_inv := by convert f.right_inv, continuous_to_fun := f.continuous, continuous_inv_fun := by convert f.symm.continuous } @[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id := funext h.symm_apply_apply @[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id := funext h.apply_symm_apply @[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ := h.surjective.range_eq lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h := funext h.symm.to_equiv.image_eq_preimage lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h := (funext h.to_equiv.image_eq_preimage).symm @[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s := h.to_equiv.image_preimage s @[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s := h.to_equiv.preimage_image s protected lemma inducing (h : α ≃ₜ β) : inducing h := inducing_of_inducing_compose h.continuous h.symm.continuous $ by simp only [symm_comp_self, inducing_id] lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h := quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $ by simp only [self_comp_symm, quotient_map.id] lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› := h.quotient_map.2.symm protected lemma embedding (h : α ≃ₜ β) : embedding h := ⟨h.inducing, h.to_equiv.injective⟩ lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s := h.embedding.compact_iff_compact_image.symm lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s := by rw ← image_symm; exact h.symm.compact_image protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h := { dense := h.surjective.dense_range, inj := h.injective, induced := h.induced_eq.symm } @[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s := h.quotient_map.is_open_preimage @[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s := by rw [← preimage_symm, is_open_preimage] @[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s := by simp only [is_closed, ← preimage_compl, is_open_preimage] @[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s := by rw [← preimage_symm, is_closed_preimage] lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) := by rw [h.embedding.closure_eq_preimage_closure_image, h.image_preimage] lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) := by rw [← preimage_symm, preimage_closure] protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2 protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2 protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h := closed_embedding_of_embedding_closed h.embedding h.is_closed_map @[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) := h.embedding.map_nhds_of_mem _ (by simp) lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) := h.embedding.to_inducing.nhds_eq_comap x @[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) := by rw [h.nhds_eq_comap, h.apply_symm_apply] /-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/ def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) : α ≃ₜ β := { continuous_to_fun := h₁, continuous_inv_fun := begin rw continuous_def, intros s hs, convert ← h₂ s hs using 1, apply e.image_eq_preimage end, to_equiv := e } @[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) : continuous_on (h ∘ f) s ↔ continuous_on f s := h.inducing.continuous_on_iff.symm @[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} : continuous (h ∘ f) ↔ continuous f := h.inducing.continuous_iff.symm @[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} : continuous (f ∘ h) ↔ continuous f := h.quotient_map.continuous_iff.symm /-- If two sets are equal, then they are homeomorphic. -/ def set_congr {s t : set α} (h : s = t) : s ≃ₜ t := { continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val, continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val, to_equiv := equiv.set_congr h } /-- Sum of two homeomorphisms. -/ def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ := { continuous_to_fun := begin convert continuous_sum_rec (continuous_inl.comp h₁.continuous) (continuous_inr.comp h₂.continuous), ext x, cases x; refl, end, continuous_inv_fun := begin convert continuous_sum_rec (continuous_inl.comp h₁.symm.continuous) (continuous_inr.comp h₂.symm.continuous), ext x, cases x; refl end, to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv } /-- Product of two homeomorphisms. -/ def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ := { continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk (h₂.continuous.comp continuous_snd), continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk (h₂.symm.continuous.comp continuous_snd), to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv } @[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : (h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl @[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : ⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl section variables (α β γ) /-- `α × β` is homeomorphic to `β × α`. -/ def prod_comm : α × β ≃ₜ β × α := { continuous_to_fun := continuous_snd.prod_mk continuous_fst, continuous_inv_fun := continuous_snd.prod_mk continuous_fst, to_equiv := equiv.prod_comm α β } @[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl @[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl /-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/ def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) := { continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk ((continuous_snd.comp continuous_fst).prod_mk continuous_snd), continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk (continuous_snd.comp continuous_snd), to_equiv := equiv.prod_assoc α β γ } /-- `α × {*}` is homeomorphic to `α`. -/ def prod_punit : α × punit ≃ₜ α := { to_equiv := equiv.prod_punit α, continuous_to_fun := continuous_fst, continuous_inv_fun := continuous_id.prod_mk continuous_const } @[simp] lemma coe_prod_punit : ⇑(prod_punit α) = prod.fst := rfl /-- `{*} × α` is homeomorphic to `α`. -/ def punit_prod : punit × α ≃ₜ α := (prod_comm _ _).trans (prod_punit _) @[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl end /-- `ulift α` is homeomorphic to `α`. -/ def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α := { continuous_to_fun := continuous_ulift_down, continuous_inv_fun := continuous_ulift_up, to_equiv := equiv.ulift } section distrib /-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/ def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ := begin refine (homeomorph.homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm _ _).symm, { convert continuous_sum_rec ((continuous_inl.comp continuous_fst).prod_mk continuous_snd) ((continuous_inr.comp continuous_fst).prod_mk continuous_snd), ext1 x, cases x; refl, }, { exact (is_open_map_sum (open_embedding_inl.prod open_embedding_id).is_open_map (open_embedding_inr.prod open_embedding_id).is_open_map) } end /-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/ def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ := (prod_comm _ _).trans $ sum_prod_distrib.trans $ sum_congr (prod_comm _ _) (prod_comm _ _) variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] /-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/ def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) := homeomorph.symm $ homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm (continuous_sigma $ λ i, (continuous_sigma_mk.comp continuous_fst).prod_mk continuous_snd) (is_open_map_sigma $ λ i, (open_embedding_sigma_mk.prod open_embedding_id).is_open_map) end distrib end homeomorph
e81818efaae534aa9a0ede07055efb49a35edc8a
fe84e287c662151bb313504482b218a503b972f3
/src/data/int_lemmas.lean
d1ed1c411bd6ccd3e7a5c28281b105d297051ba6
[]
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
2,305
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Some basic lemmas about integers. I should check whether the new coercion tactic makes them trivial. -/ import data.fintype.basic data.nat.sqrt lemma int.lt_succ_iff {n m : ℤ} : n < m + 1 ↔ n ≤ m := ⟨int.le_of_lt_add_one,int.lt_add_one_of_le⟩ lemma nat.square_le {n m : ℕ} : m ^ 2 ≤ n ↔ m ≤ n.sqrt := ⟨λ h0, le_of_not_gt (λ h1, not_le_of_gt ((pow_two m).symm.subst (nat.sqrt_lt.mp h1)) h0), λ h0, le_of_not_gt (λ h1,not_le_of_gt (nat.sqrt_lt.mpr ((pow_two m).subst h1)) h0)⟩ lemma nat.square_lt {n m : ℕ} : m ^ 2 < n.succ ↔ m ≤ n.sqrt := (@nat.lt_succ_iff (m ^ 2) n).trans (@nat.square_le n m) lemma int.abs_le {n m : ℤ} : abs m ≤ n ↔ (- n ≤ m ∧ m ≤ n) := begin by_cases hm : 0 ≤ m, { rw[abs_of_nonneg hm], exact ⟨ λ hmn, ⟨le_trans (neg_nonpos_of_nonneg (le_trans hm hmn)) hm,hmn⟩, λ hmn, hmn.right ⟩ },{ let hma := le_of_lt (lt_of_not_ge hm), let hmb := neg_nonneg_of_nonpos hma, rw[abs_of_nonpos hma], exact ⟨ λ hmn, ⟨(neg_neg m) ▸ (neg_le_neg hmn),le_trans (le_trans hma hmb) hmn⟩, λ hmn, (neg_neg n) ▸ (neg_le_neg hmn.left), ⟩ } end lemma int.abs_le' {n : ℕ} {m : ℤ} : m.nat_abs ≤ n ↔ (- (n : ℤ) ≤ m ∧ m ≤ n) := begin let h := @int.abs_le n m, rw[int.abs_eq_nat_abs,int.coe_nat_le] at h, exact h, end lemma int.abs_square (n : ℤ) : n ^ 2 = (abs n) ^ 2 := begin by_cases h0 : n ≥ 0, {rw[abs_of_nonneg h0]}, {rw[abs_of_neg (lt_of_not_ge h0),pow_two,pow_two,neg_mul_neg],} end lemma int.abs_square' (n : ℤ) : n ^ 2 = ((int.nat_abs n) ^ 2 : ℕ) := calc n ^ 2 = n * n : pow_two n ... = ↑ (n.nat_abs * n.nat_abs) : int.nat_abs_mul_self.symm ... = ↑ (n.nat_abs ^ 2 : ℕ) : by rw[(pow_two n.nat_abs).symm] lemma int.square_le {n : ℕ} {m : ℤ} : m ^ 2 ≤ n ↔ - (n.sqrt : ℤ) ≤ m ∧ m ≤ n.sqrt := begin rw[int.abs_square',int.coe_nat_le,nat.square_le,int.abs_le'], end lemma int.square_lt {n : ℕ} {m : ℤ} : m ^ 2 < n.succ ↔ - (n.sqrt : ℤ) ≤ m ∧ m ≤ n.sqrt := begin rw[int.abs_square',int.coe_nat_lt,nat.square_lt,int.abs_le'], end
6ef92f625f3739569c5f2640cf61717526ec0dc0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/typeclass_metas_internal_goals2.lean
98a2df71077d79c5b84ff7be847b1767ba5d9b52
[ "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
413
lean
class Foo (α β : Type) : Type := (u : Unit := ()) class Bar (α β : Type) : Type := (u : Unit := ()) class Top : Type := (u : Unit := ()) instance FooNatA (β : Type) : Foo Nat β := {u:=()} instance BarANat (α : Type) : Bar α Nat := {u:=()} set_option synthInstance.checkSynthOrder false in instance FooBarToTop (α β : Type) [Foo α β] [Bar α β] : Top := {u:=()} set_option pp.all true #synth Top
90263087f6f33a692d903e26e6b27c90759ab35e
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/algebra/module/linear_map.lean
6d8920ced26b250ffc5b7206c4b38b16cc6016b3
[ "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
18,859
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen -/ import algebra.group.hom import algebra.module.basic import algebra.group_action_hom /-! # Linear maps and linear equivalences In this file we define * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. * `linear_equiv R M ₂`, `M ≃ₗ[R] M₂`: an invertible linear map ## Tags linear map, linear equiv, linear equivalences, linear isomorphism, linear isomorphic -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends add_hom M M₂, M →[R] M₂ end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom /-- The `mul_action_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_mul_action_hom infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [semimodule R M] [semimodule R M₂] /-- The `distrib_mul_action_hom` underlying a `linear_map`. -/ def to_distrib_mul_action_hom (f : M →ₗ[R] M₂) : distrib_mul_action_hom R M M₂ := { map_zero' := zero_smul R (0 : M) ▸ zero_smul R (f.to_fun 0) ▸ f.map_smul' 0 0, ..f } instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [semimodule R M] [semimodule R M₂] variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} theorem coe_injective : injective (λ f : M →ₗ[R] M₂, show M → M₂, from f) := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] lemma mk_coe (f : M →ₗ[R] M₂) (h₁ h₂) : (linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) = f := ext $ λ _, rfl variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := f.to_distrib_mul_action_hom.map_zero variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] := (map_smul : ∀ (f : M →ₗ[S] M₂) (c : R) (x : M), f (c • x) = c • f x) variables {M M₂} @[priority 100] instance compatible_smul.is_scalar_tower {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [semimodule S M] [is_scalar_tower R S M] [has_scalar R M₂] [semimodule S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ f c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (f x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [semimodule S M] [has_scalar R M₂] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) (c : R) (x : M) : f (c • x) = c • f x := compatible_smul.map_smul f c x instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ⇑f.to_add_monoid_hom = f := rfl variable (R) /-- If `M` and `M₂` are both `R`-semimodules and `S`-semimodules and `R`-semimodule structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ def restrict_scalars {S : Type*} [semiring S] [semimodule S M] [semimodule S M₂] [compatible_smul M M₂ R S] (f : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul_of_tower } variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `R`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₗ[R] M} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smul, g.map_smul, h] theorem ext_ring_iff {f g : R →ₗ[R] M} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} {semimodule_M₃ : semimodule R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[norm_cast] lemma comp_coe : (f : M₂ → M₃) ∘ (g : M → M₂) = f.comp g := rfl end /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [semimodule R M] [semimodule R M₂] (f : M →ₗ[R] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, λ a b, by { rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂] }⟩ end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f } instance compatible_smul.int_module {S : Type*} [semiring S] [semimodule ℤ M] [semimodule S M] [semimodule ℤ M₂] [semimodule S M₂] : compatible_smul M M₂ ℤ S := ⟨λ f c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simpa [add_smul] using ih }, case hn : n ih { simpa [sub_smul] using ih } end⟩ end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [semimodule R M] [semimodule R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `linear_map.endomorphism_semiring` and algebra structure `module.endomorphism_algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } /-! ### Linear equivalences -/ section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends M →ₗ[R] M₂, M ≃+ M₂ end attribute [nolint doc_blame] linear_equiv.to_linear_map attribute [nolint doc_blame] linear_equiv.to_add_equiv infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section add_comm_monoid variables {M₄ : Type*} variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] section variables [semimodule R M] [semimodule R M₂] [semimodule R M₃] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_mk {to_fun inv_fun map_add map_smul left_inv right_inv } : ⇑(⟨to_fun, map_add, map_smul, inv_fun, left_inv, right_inv⟩ : M ≃ₗ[R] M₂) = to_fun := rfl -- This exists for compatibility, previously `≃ₗ[R]` extended `≃` instead of `≃+`. @[nolint doc_blame] def to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂ := λ f, f.to_add_equiv.to_equiv lemma injective_to_equiv : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) @[simp] lemma to_equiv_inj {e₁ e₂ : M ≃ₗ[R] M₂} : e₁.to_equiv = e₂.to_equiv ↔ e₁ = e₂ := injective_to_equiv.eq_iff lemma injective_to_linear_map : function.injective (coe : (M ≃ₗ[R] M₂) → (M →ₗ[R] M₂)) := λ e₁ e₂ H, injective_to_equiv $ equiv.ext $ linear_map.congr_fun H @[simp, norm_cast] lemma to_linear_map_inj {e₁ e₂ : M ≃ₗ[R] M₂} : (e₁ : M →ₗ[R] M₂) = e₂ ↔ e₁ = e₂ := injective_to_linear_map.eq_iff end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (e e' : M ≃ₗ[R] M₂) lemma to_linear_map_eq_coe : e.to_linear_map = ↑e := rfl @[simp, norm_cast] theorem coe_coe : ⇑(e : M →ₗ[R] M₂) = e := rfl @[simp] lemma coe_to_equiv : ⇑e.to_equiv = e := rfl @[simp] lemma coe_to_linear_map : ⇑e.to_linear_map = e := rfl @[simp] lemma to_fun_eq_coe : e.to_fun = e := rfl section variables {e e'} @[ext] lemma ext (h : ∀ x, e x = e' x) : e = e' := injective_to_equiv (equiv.ext h) protected lemma congr_arg : Π {x x' : M}, x = x' → e x = e x' | _ _ rfl := rfl protected lemma congr_fun (h : e = e') (x : M) : e x = e' x := h ▸ rfl lemma ext_iff : e = e' ↔ ∀ x, e x = e' x := ⟨λ h x, h ▸ rfl, ext⟩ end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [semimodule R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [semimodule R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } /-- See Note [custom simps projection] -/ def simps.inv_fun [semimodule R M] [semimodule R M₂] (e : M ≃ₗ[R] M₂) : M₂ → M := e.symm initialize_simps_projections linear_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma inv_fun_eq_symm : e.inv_fun = e.symm := rfl variables {semimodule_M₃ : semimodule R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } @[simp] lemma coe_to_add_equiv : ⇑(e.to_add_equiv) = e := rfl /-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/ lemma to_add_monoid_hom_commutes : e.to_linear_map.to_add_monoid_hom = e.to_add_equiv.to_add_monoid_hom := rfl @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] lemma symm_trans_apply (c : M₃) : (e₁.trans e₂).symm c = e₁.symm (e₂.symm c) := rfl @[simp] lemma trans_refl : e.trans (refl R M₂) = e := injective_to_equiv e.to_equiv.trans_refl @[simp] lemma refl_trans : (refl R M).trans e = e := injective_to_equiv e.to_equiv.refl_trans lemma symm_apply_eq {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq lemma eq_symm_apply {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[simp] lemma trans_symm [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.trans f.symm = linear_equiv.refl R M := by { ext x, simp } @[simp] lemma symm_trans [semimodule R M] [semimodule R M₂] (f : M ≃ₗ[R] M₂) : f.symm.trans f = linear_equiv.refl R M₂ := by { ext x, simp } @[simp, norm_cast] lemma refl_to_linear_map [semimodule R M] : (linear_equiv.refl R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma comp_coe [semimodule R M] [semimodule R M₂] [semimodule R M₃] (f : M ≃ₗ[R] M₂) (f' : M₂ ≃ₗ[R] M₃) : (f' : M₂ →ₗ[R] M₃).comp (f : M →ₗ[R] M₂) = (f.trans f' : M →ₗ[R] M₃) := rfl @[simp] lemma mk_coe (h₁ h₂ f h₃ h₄) : (linear_equiv.mk e h₁ h₂ f h₃ h₄ : M ≃ₗ[R] M₂) = e := ext $ λ _, rfl @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.map_add' a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.map_smul' c x @[simp] lemma map_sum {s : finset ι} (u : ι → M) : e (∑ i in s, u i) = ∑ i in s, e (u i) := e.to_linear_map.map_sum @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } lemma symm_bijective [semimodule R M] [semimodule R M₂] : function.bijective (symm : (M ≃ₗ[R] M₂) → (M₂ ≃ₗ[R] M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (f h₁ h₂ h₃ h₄) : (linear_equiv.mk f h₁ h₂ ⇑e h₃ h₄ : M₂ ≃ₗ[R] M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] theorem symm_mk (f h₁ h₂ h₃ h₄) : (⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₗ[R] M₂).symm = { to_fun := f, inv_fun := e, ..(⟨e, h₁, h₂, f, h₃, h₄⟩ : M ≃ₗ[R] M₂).symm } := rfl protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective protected lemma image_eq_preimage (s : set M) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end /-- An involutive linear map is a linear equivalence. -/ def of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : M ≃ₗ[R] M := { .. f, .. hf.to_equiv f } @[simp] lemma coe_of_involutive [semimodule R M] (f : M →ₗ[R] M) (hf : involutive f) : ⇑(of_involutive f hf) = f := rfl end add_comm_monoid end linear_equiv
5848ff383c9a4443803ee4b31cf1178daa7eb866
976d2334b51721ddc405deb2e1754016d454286e
/src/game_files/sqrt2/sq_eq_zero2.lean
fa9a134e62ae1fbb95563188a3a634f6c85c300b
[]
no_license
kbuzzard/lean-at-MC2020
11bb6ac9ec38a6caace9d5d9a1705d6794d9f477
1f7ca65a7ba5cc17eb49f525c02dc6b0e65d6543
refs/heads/master
1,668,496,422,317
1,594,131,838,000
1,594,131,838,000
277,877,735
0
0
null
1,594,142,006,000
1,594,142,005,000
null
UTF-8
Lean
false
false
143
lean
lemma sq_eq_zero_iff_eq_zero (m : ℕ) : m^2 = 0 ↔ m = 0 := begin split, { apply eq_zero_of_sq_eq_zero }, intro h, rw h, ring, end
9e896c20b2278f544ede191627119a920ee9aeac
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/monoidal/End.lean
872bc5a39375725eb13bc5619804747f8ecbec91
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
2,527
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.functor /-! # Endofunctors as a monoidal category. We give the monoidal category structure on `C ⥤ C`, and show that when `C` itself is monoidal, it embeds via a monoidal functor into `C ⥤ C`. ## TODO Can we use this to show coherence results, e.g. a cheap proof that `λ_ (𝟙_ C) = ρ_ (𝟙_ C)`? I suspect this is harder than is usually made out. -/ universes v u namespace category_theory variables (C : Type u) [category.{v} C] /-- The category of endofunctors of any category is a monoidal category, with tensor product given by composition of functors (and horizontal composition of natural transformations). -/ def endofunctor_monoidal_category : monoidal_category (C ⥤ C) := { tensor_obj := λ F G, F ⋙ G, tensor_hom := λ F G F' G' α β, nat_trans.hcomp α β, tensor_unit := 𝟭 C, associator := λ F G H, functor.associator F G H, left_unitor := λ F, functor.left_unitor F, right_unitor := λ F, functor.right_unitor F, }. open category_theory.monoidal_category variables [monoidal_category.{v} C] local attribute [instance] endofunctor_monoidal_category local attribute [reducible] endofunctor_monoidal_category /-- Tensoring on the right gives a monoidal functor from `C` into endofunctors of `C`. -/ @[simps] def tensoring_right_monoidal : monoidal_functor C (C ⥤ C) := { ε := (right_unitor_nat_iso C).inv, μ := λ X Y, { app := λ Z, (α_ Z X Y).hom, naturality' := λ Z Z' f, by { dsimp, rw associator_naturality, simp, } }, μ_natural' := λ X Y X' Y' f g, by { ext Z, dsimp, simp [associator_naturality], }, associativity' := λ X Y Z, by { ext W, dsimp, simp [pentagon], }, left_unitality' := λ X, by { ext Y, dsimp, rw [category.id_comp, triangle, ←tensor_comp], simp, }, right_unitality' := λ X, begin ext Y, dsimp, rw [tensor_id, category.comp_id, right_unitor_tensor_inv, category.assoc, iso.inv_hom_id_assoc, ←id_tensor_comp, iso.inv_hom_id, tensor_id], end, ε_is_iso := by apply_instance, μ_is_iso := λ X Y, { inv := -- We could avoid needing to do this explicitly by -- constructing a partially applied analogue of `associator_nat_iso`. { app := λ Z, (α_ Z X Y).inv, naturality' := λ Z Z' f, by { dsimp, rw ←associator_inv_naturality, simp, } }, }, ..tensoring_right C }. end category_theory
6320ba3b6b628f0736fd277871732ec647fd6e48
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/representation_theory/maschke.lean
0eee7243865a4b133e9f15788b627d4776c46d8f
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,491
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.monoid_algebra.basic import algebra.char_p.invertible import linear_algebra.basis /-! # Maschke's theorem We prove **Maschke's theorem** for finite groups, in the formulation that every submodule of a `k[G]` module has a complement, when `k` is a field with `invertible (fintype.card G : k)`. We do the core computation in greater generality. For any `[comm_ring k]` in which `[invertible (fintype.card G : k)]`, and a `k[G]`-linear map `i : V → W` which admits a `k`-linear retraction `π`, we produce a `k[G]`-linear retraction by taking the average over `G` of the conjugates of `π`. ## Implementation Notes * These results assume `invertible (fintype.card G : k)` which is equivalent to the more familiar `¬(ring_char k ∣ fintype.card G)`. It is possible to convert between them using `invertible_of_ring_char_not_dvd` and `not_ring_char_dvd_of_invertible`. ## Future work It's not so far to give the usual statement, that every finite dimensional representation of a finite group is semisimple (i.e. a direct sum of irreducibles). -/ universes u noncomputable theory open module open monoid_algebra open_locale big_operators section -- At first we work with any `[comm_ring k]`, and add the assumption that -- `[invertible (fintype.card G : k)]` when it is required. variables {k : Type u} [comm_ring k] {G : Type u} [group G] variables {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] variables [is_scalar_tower k (monoid_algebra k G) V] variables {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] variables [is_scalar_tower k (monoid_algebra k G) W] /-! We now do the key calculation in Maschke's theorem. Given `V → W`, an inclusion of `k[G]` modules,, assume we have some retraction `π` (i.e. `∀ v, π (i v) = v`), just as a `k`-linear map. (When `k` is a field, this will be available cheaply, by choosing a basis.) We now construct a retraction of the inclusion as a `k[G]`-linear map, by the formula $$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$ -/ namespace linear_map variables (π : W →ₗ[k] V) include π /-- We define the conjugate of `π` by `g`, as a `k`-linear map. -/ def conjugate (g : G) : W →ₗ[k] V := ((group_smul.linear_map k V g⁻¹).comp π).comp (group_smul.linear_map k W g) variables (i : V →ₗ[monoid_algebra k G] W) (h : ∀ v : V, π (i v) = v) section include h lemma conjugate_i (g : G) (v : V) : (conjugate π g) (i v) = v := begin dsimp [conjugate], simp only [←i.map_smul, h, ←mul_smul, single_mul_single, mul_one, mul_left_inv], change (1 : monoid_algebra k G) • v = v, simp, end end variables (G) [fintype G] /-- The sum of the conjugates of `π` by each element `g : G`, as a `k`-linear map. (We postpone dividing by the size of the group as long as possible.) -/ def sum_of_conjugates : W →ₗ[k] V := ∑ g : G, π.conjugate g /-- In fact, the sum over `g : G` of the conjugate of `π` by `g` is a `k[G]`-linear map. -/ def sum_of_conjugates_equivariant : W →ₗ[monoid_algebra k G] V := monoid_algebra.equivariant_of_linear_of_comm (π.sum_of_conjugates G) (λ g v, begin simp only [sum_of_conjugates, linear_map.sum_apply, -- We have a `module (monoid_algebra k G)` instance but are working with `finsupp`s, -- so help the elaborator unfold everything correctly. @finset.smul_sum (monoid_algebra k G)], dsimp [conjugate], conv_lhs { rw [←finset.univ_map_embedding (mul_right_embedding g⁻¹)], simp only [mul_right_embedding], }, simp only [←mul_smul, single_mul_single, mul_inv_rev, mul_one, function.embedding.coe_fn_mk, finset.sum_map, inv_inv, inv_mul_cancel_right] end) section variables [inv : invertible (fintype.card G : k)] include inv /-- We construct our `k[G]`-linear retraction of `i` as $$ \frac{1}{|G|} \sum_{g \in G} g⁻¹ • π(g • -). $$ -/ def equivariant_projection : W →ₗ[monoid_algebra k G] V := ⅟(fintype.card G : k) • (π.sum_of_conjugates_equivariant G) include h lemma equivariant_projection_condition (v : V) : (π.equivariant_projection G) (i v) = v := begin rw [equivariant_projection, smul_apply, sum_of_conjugates_equivariant, equivariant_of_linear_of_comm_apply, sum_of_conjugates], rw [linear_map.sum_apply], simp only [conjugate_i π i h], rw [finset.sum_const, finset.card_univ, nsmul_eq_smul_cast k, ←mul_smul, invertible.inv_of_mul_self, one_smul], end end end linear_map end namespace char_zero variables {k : Type u} [field k] {G : Type u} [fintype G] [group G] [char_zero k] instance : invertible (fintype.card G : k) := invertible_of_ring_char_not_dvd (by simp [fintype.card_eq_zero_iff]) end char_zero namespace monoid_algebra -- Now we work over a `[field k]`. variables {k : Type u} [field k] {G : Type u} [fintype G] [invertible (fintype.card G : k)] variables [group G] variables {V : Type u} [add_comm_group V] [module k V] [module (monoid_algebra k G) V] variables [is_scalar_tower k (monoid_algebra k G) V] variables {W : Type u} [add_comm_group W] [module k W] [module (monoid_algebra k G) W] variables [is_scalar_tower k (monoid_algebra k G) W] lemma exists_left_inverse_of_injective (f : V →ₗ[monoid_algebra k G] W) (hf : f.ker = ⊥) : ∃ (g : W →ₗ[monoid_algebra k G] V), g.comp f = linear_map.id := begin obtain ⟨φ, hφ⟩ := (f.restrict_scalars k).exists_left_inverse_of_injective (by simp only [hf, submodule.restrict_scalars_bot, linear_map.ker_restrict_scalars]), refine ⟨φ.equivariant_projection G, _⟩, apply linear_map.ext, intro v, simp only [linear_map.id_coe, id.def, linear_map.comp_apply], apply linear_map.equivariant_projection_condition, intro v, have := congr_arg linear_map.to_fun hφ, exact congr_fun this v end namespace submodule lemma exists_is_compl (p : submodule (monoid_algebra k G) V) : ∃ q : submodule (monoid_algebra k G) V, is_compl p q := let ⟨f, hf⟩ := monoid_algebra.exists_left_inverse_of_injective p.subtype p.ker_subtype in ⟨f.ker, linear_map.is_compl_of_proj $ linear_map.ext_iff.1 hf⟩ /-- This also implies an instance `is_semisimple_module (monoid_algebra k G) V`. -/ instance complemented_lattice : complemented_lattice (submodule (monoid_algebra k G) V) := ⟨exists_is_compl⟩ end submodule end monoid_algebra
405a8979395d22156eda41af17c39d758dcb7300
92b50235facfbc08dfe7f334827d47281471333b
/library/data/quotient/util.lean
174bd121b2b8dfe9f0eb16caf0eba2554a1be303
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
7,023
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn -/ import logic ..prod algebra.relation open prod eq.ops namespace quotient /- auxiliary facts about products -/ variables {A B : Type} /- flip -/ definition flip (a : A × B) : B × A := pair (pr2 a) (pr1 a) theorem flip_def (a : A × B) : flip a = pair (pr2 a) (pr1 a) := rfl theorem flip_pair (a : A) (b : B) : flip (pair a b) = pair b a := rfl theorem flip_pr1 (a : A × B) : pr1 (flip a) = pr2 a := rfl theorem flip_pr2 (a : A × B) : pr2 (flip a) = pr1 a := rfl theorem flip_flip (a : A × B) : flip (flip a) = a := destruct a (take x y, rfl) theorem P_flip {P : A → B → Prop} (a : A × B) (H : P (pr1 a) (pr2 a)) : P (pr2 (flip a)) (pr1 (flip a)) := (flip_pr1 a)⁻¹ ▸ (flip_pr2 a)⁻¹ ▸ H theorem flip_inj {a b : A × B} (H : flip a = flip b) : a = b := have H2 : flip (flip a) = flip (flip b), from congr_arg flip H, show a = b, from (flip_flip a) ▸ (flip_flip b) ▸ H2 /- coordinatewise unary maps -/ definition map_pair (f : A → B) (a : A × A) : B × B := pair (f (pr1 a)) (f (pr2 a)) theorem map_pair_def (f : A → B) (a : A × A) : map_pair f a = pair (f (pr1 a)) (f (pr2 a)) := rfl theorem map_pair_pair (f : A → B) (a a' : A) : map_pair f (pair a a') = pair (f a) (f a') := (pr1.mk a a') ▸ (pr2.mk a a') ▸ rfl theorem map_pair_pr1 (f : A → B) (a : A × A) : pr1 (map_pair f a) = f (pr1 a) := by esimp theorem map_pair_pr2 (f : A → B) (a : A × A) : pr2 (map_pair f a) = f (pr2 a) := by esimp /- coordinatewise binary maps -/ definition map_pair2 {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) : C × C := pair (f (pr1 a) (pr1 b)) (f (pr2 a) (pr2 b)) theorem map_pair2_def {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) : map_pair2 f a b = pair (f (pr1 a) (pr1 b)) (f (pr2 a) (pr2 b)) := rfl theorem map_pair2_pair {A B C : Type} (f : A → B → C) (a a' : A) (b b' : B) : map_pair2 f (pair a a') (pair b b') = pair (f a b) (f a' b') := calc map_pair2 f (pair a a') (pair b b') = pair (f (pr1 (pair a a')) b) (f (pr2 (pair a a')) (pr2 (pair b b'))) : {pr1.mk b b'} ... = pair (f (pr1 (pair a a')) b) (f (pr2 (pair a a')) b') : {pr2.mk b b'} ... = pair (f (pr1 (pair a a')) b) (f a' b') : {pr2.mk a a'} ... = pair (f a b) (f a' b') : {pr1.mk a a'} theorem map_pair2_pr1 {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) : pr1 (map_pair2 f a b) = f (pr1 a) (pr1 b) := by esimp theorem map_pair2_pr2 {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) : pr2 (map_pair2 f a b) = f (pr2 a) (pr2 b) := by esimp theorem map_pair2_flip {A B C : Type} (f : A → B → C) (a : A × A) (b : B × B) : flip (map_pair2 f a b) = map_pair2 f (flip a) (flip b) := have Hx : pr1 (flip (map_pair2 f a b)) = pr1 (map_pair2 f (flip a) (flip b)), from calc pr1 (flip (map_pair2 f a b)) = pr2 (map_pair2 f a b) : flip_pr1 _ ... = f (pr2 a) (pr2 b) : map_pair2_pr2 f a b ... = f (pr1 (flip a)) (pr2 b) : {(flip_pr1 a)⁻¹} ... = f (pr1 (flip a)) (pr1 (flip b)) : {(flip_pr1 b)⁻¹} ... = pr1 (map_pair2 f (flip a) (flip b)) : (map_pair2_pr1 f _ _)⁻¹, have Hy : pr2 (flip (map_pair2 f a b)) = pr2 (map_pair2 f (flip a) (flip b)), from calc pr2 (flip (map_pair2 f a b)) = pr1 (map_pair2 f a b) : flip_pr2 _ ... = f (pr1 a) (pr1 b) : map_pair2_pr1 f a b ... = f (pr2 (flip a)) (pr1 b) : {flip_pr2 a} ... = f (pr2 (flip a)) (pr2 (flip b)) : {flip_pr2 b} ... = pr2 (map_pair2 f (flip a) (flip b)) : (map_pair2_pr2 f _ _)⁻¹, pair_eq Hx Hy -- add_rewrite flip_pr1 flip_pr2 flip_pair -- add_rewrite map_pair_pr1 map_pair_pr2 map_pair_pair -- add_rewrite map_pair2_pr1 map_pair2_pr2 map_pair2_pair theorem map_pair2_comm {A B : Type} {f : A → A → B} (Hcomm : ∀a b : A, f a b = f b a) (v w : A × A) : map_pair2 f v w = map_pair2 f w v := have Hx : pr1 (map_pair2 f v w) = pr1 (map_pair2 f w v), from calc pr1 (map_pair2 f v w) = f (pr1 v) (pr1 w) : map_pair2_pr1 f v w ... = f (pr1 w) (pr1 v) : Hcomm _ _ ... = pr1 (map_pair2 f w v) : (map_pair2_pr1 f w v)⁻¹, have Hy : pr2 (map_pair2 f v w) = pr2 (map_pair2 f w v), from calc pr2 (map_pair2 f v w) = f (pr2 v) (pr2 w) : map_pair2_pr2 f v w ... = f (pr2 w) (pr2 v) : Hcomm _ _ ... = pr2 (map_pair2 f w v) : (map_pair2_pr2 f w v)⁻¹, pair_eq Hx Hy theorem map_pair2_assoc {A : Type} {f : A → A → A} (Hassoc : ∀a b c : A, f (f a b) c = f a (f b c)) (u v w : A × A) : map_pair2 f (map_pair2 f u v) w = map_pair2 f u (map_pair2 f v w) := have Hx : pr1 (map_pair2 f (map_pair2 f u v) w) = pr1 (map_pair2 f u (map_pair2 f v w)), from calc pr1 (map_pair2 f (map_pair2 f u v) w) = f (pr1 (map_pair2 f u v)) (pr1 w) : map_pair2_pr1 f _ _ ... = f (f (pr1 u) (pr1 v)) (pr1 w) : {map_pair2_pr1 f _ _} ... = f (pr1 u) (f (pr1 v) (pr1 w)) : Hassoc (pr1 u) (pr1 v) (pr1 w) ... = f (pr1 u) (pr1 (map_pair2 f v w)) : by rewrite [map_pair2_pr1 f] ... = pr1 (map_pair2 f u (map_pair2 f v w)) : (map_pair2_pr1 f _ _)⁻¹, have Hy : pr2 (map_pair2 f (map_pair2 f u v) w) = pr2 (map_pair2 f u (map_pair2 f v w)), from calc pr2 (map_pair2 f (map_pair2 f u v) w) = f (pr2 (map_pair2 f u v)) (pr2 w) : map_pair2_pr2 f _ _ ... = f (f (pr2 u) (pr2 v)) (pr2 w) : {map_pair2_pr2 f _ _} ... = f (pr2 u) (f (pr2 v) (pr2 w)) : Hassoc (pr2 u) (pr2 v) (pr2 w) ... = f (pr2 u) (pr2 (map_pair2 f v w)) : {map_pair2_pr2 f _ _} ... = pr2 (map_pair2 f u (map_pair2 f v w)) : (map_pair2_pr2 f _ _)⁻¹, pair_eq Hx Hy theorem map_pair2_id_right {A B : Type} {f : A → B → A} {e : B} (Hid : ∀a : A, f a e = a) (v : A × A) : map_pair2 f v (pair e e) = v := have Hx : pr1 (map_pair2 f v (pair e e)) = pr1 v, from (calc pr1 (map_pair2 f v (pair e e)) = f (pr1 v) (pr1 (pair e e)) : by simp ... = f (pr1 v) e : by simp ... = pr1 v : Hid (pr1 v)), have Hy : pr2 (map_pair2 f v (pair e e)) = pr2 v, from (calc pr2 (map_pair2 f v (pair e e)) = f (pr2 v) (pr2 (pair e e)) : by simp ... = f (pr2 v) e : by simp ... = pr2 v : Hid (pr2 v)), prod.eq Hx Hy theorem map_pair2_id_left {A B : Type} {f : B → A → A} {e : B} (Hid : ∀a : A, f e a = a) (v : A × A) : map_pair2 f (pair e e) v = v := have Hx : pr1 (map_pair2 f (pair e e) v) = pr1 v, from calc pr1 (map_pair2 f (pair e e) v) = f (pr1 (pair e e)) (pr1 v) : by simp ... = f e (pr1 v) : by simp ... = pr1 v : Hid (pr1 v), have Hy : pr2 (map_pair2 f (pair e e) v) = pr2 v, from calc pr2 (map_pair2 f (pair e e) v) = f (pr2 (pair e e)) (pr2 v) : by simp ... = f e (pr2 v) : by simp ... = pr2 v : Hid (pr2 v), prod.eq Hx Hy end quotient
fc20c772a589ea515d30cb3558ba7ac5adcf3c80
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/topology/bases.lean
0dc17441b19f6d715f2993dc664872c07aeea852
[ "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
22,042
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 /-! # Bases of topologies. Countability axioms. A topological basis on a topological space `t` is a collection of sets, such that all open sets can be generated as unions of these sets, without the need to take finite intersections of them. This file introduces a framework for dealing with these collections, and also what more we can say under certain countability conditions on bases, which are referred to as first- and second-countable. We also briefly cover the theory of separable spaces, which are those with a countable, dense subset. If a space is second-countable, and also has a countably generated uniformity filter (for example, if `t` is a metric space), it will automatically be separable (and indeed, these conditions are equivalent in this case). ## Main definitions * `is_topological_basis s`: The topological space `t` has basis `s`. * `separable_space α`: The topological space `t` has a countable, dense subset. * `first_countable_topology α`: A topology in which `𝓝 x` is countably generated for every `x`. * `second_countable_topology α`: A topology which has a topological basis which is countable. ## Main results * `first_countable_topology.tendsto_subseq`: In a first-countable space, cluster points are limits of subsequences. * `second_countable_topology.is_open_Union_countable`: In a second-countable space, the union of arbitrarily-many open sets is equal to a sub-union of only countably many of these sets. * `second_countable_topology.countable_cover_nhds`: Consider `f : α → set α` with the property that `f x ∈ 𝓝 x` for all `x`. Then there is some countable set `s` whose image covers the space. ## Implementation Notes For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. ### TODO: More fine grained instances for `first_countable_topology`, `separable_space`, `t2_space`, and more (see the comment below `subtype.second_countable_topology`.) -/ open set filter classical open_locale topological_space filter noncomputable theory namespace topological_space universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ structure is_topological_basis (s : set (set α)) : Prop := (exists_subset_inter : ∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) (sUnion_eq : (⋃₀ s) = univ) (eq_generate_from : t = generate_from s) /-- If a family of sets `s` generates the topology, then nonempty intersections of finite subcollections of `s` form a topological basis. -/ lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λ f, ⋂₀ f) '' {f : set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty}) := begin refine ⟨_, _, _⟩, { rintro _ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, rfl⟩ _ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, rfl⟩ x h, have : ⋂₀ (t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂ := sInter_union t₁ t₂, exact ⟨_, ⟨t₁ ∪ t₂, ⟨hft₁.union hft₂, union_subset ht₁b ht₂b, this.symm ▸ ⟨x, h⟩⟩, this⟩, h, subset.rfl⟩ }, { rw [sUnion_image, bUnion_eq_univ_iff], intro x, have : x ∈ ⋂₀ ∅, { rw sInter_empty, exact mem_univ x }, exact ⟨∅, ⟨finite_empty, empty_subset _, x, this⟩, this⟩ }, { rw hs, apply le_antisymm; apply le_generate_from, { rintro _ ⟨t, ⟨hft, htb, ht⟩, rfl⟩, exact @is_open_sInter _ (generate_from s) _ hft (λ s hs, generate_open.basic _ $ htb hs) }, { intros t ht, rcases t.eq_empty_or_nonempty with rfl|hne, { apply @is_open_empty _ _ }, rw ← sInter_singleton t at hne ⊢, exact generate_open.basic _ ⟨{t}, ⟨finite_singleton t, singleton_subset_iff.2 ht, hne⟩, rfl⟩ } } end /-- If a family of open sets `s` is such that every open neighbourhood contains some member of `s`, then `s` is a topological basis. -/ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := begin refine ⟨λ t₁ ht₁ t₂ ht₂ x hx, h_nhds _ _ hx (is_open.inter (h_open _ ht₁) (h_open _ ht₂)), _, _⟩, { refine sUnion_eq_univ_iff.2 (λ a, _), rcases h_nhds a univ trivial is_open_univ with ⟨u, h₁, h₂, -⟩, exact ⟨u, h₁, h₂⟩ }, { refine (le_generate_from h_open).antisymm (λ u hu, _), refine (@is_open_iff_nhds α (generate_from s) u).mpr (λ a ha, _), rcases h_nhds a u ha hu with ⟨v, hvs, hav, hvu⟩, rw nhds_generate_from, exact binfi_le_of_le v ⟨hav, hvs⟩ (le_principal_iff.2 hvu) } end /-- A set `s` is in the neighbourhood of `a` iff there is some basis set `t`, which contains `a` and is itself contained in `s`. -/ lemma is_topological_basis.mem_nhds_iff {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin change s ∈ (𝓝 a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s, rw [hb.eq_generate_from, nhds_generate_from, binfi_sets_eq], { simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.sUnion_eq a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_topological_basis.nhds_has_basis {b : set (set α)} (hb : is_topological_basis b) {a : α} : (𝓝 a).has_basis (λ t : set α, t ∈ b ∧ a ∈ t) (λ t, t) := ⟨λ s, hb.mem_nhds_iff.trans $ by simp only [exists_prop, and_assoc]⟩ protected lemma is_topological_basis.is_open {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : is_open s := by { rw hb.eq_generate_from, exact generate_open.basic s hs } lemma is_topological_basis.exists_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := hb.mem_nhds_iff.1 $ is_open.mem_nhds ou au /-- Any open set is the union of the basis sets contained in it. -/ lemma is_topological_basis.open_eq_sUnion' {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : u = ⋃₀ {s ∈ B | s ⊆ u} := ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := hB.exists_subset_of_mem_open ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩ lemma is_topological_basis.open_eq_sUnion {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, hB.open_eq_sUnion' ou⟩ lemma is_topological_basis.open_eq_Union {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := ⟨↥{s ∈ B | s ⊆ u}, coe, by { rw ← sUnion_eq_Union, apply hB.open_eq_sUnion' ou }, λ s, and.left s.2⟩ /-- A point `a` is in the closure of `s` iff all basis sets containing `a` intersect `s`. -/ lemma is_topological_basis.mem_closure_iff {b : set (set α)} (hb : is_topological_basis b) {s : set α} {a : α} : a ∈ closure s ↔ ∀ o ∈ b, a ∈ o → (o ∩ s).nonempty := (mem_closure_iff_nhds_basis' hb.nhds_has_basis).trans $ by simp only [and_imp] /-- A set is dense iff it has non-trivial intersection with all basis sets. -/ lemma is_topological_basis.dense_iff {b : set (set α)} (hb : is_topological_basis b) {s : set α} : dense s ↔ ∀ o ∈ b, set.nonempty o → (o ∩ s).nonempty := begin simp only [dense, hb.mem_closure_iff], exact ⟨λ h o hb ⟨a, ha⟩, h a o hb ha, λ h a o hb ha, h o hb ⟨a, ha⟩⟩ end protected lemma is_topological_basis.prod {β} [topological_space β] {B₁ : set (set α)} {B₂ : set (set β)} (h₁ : is_topological_basis B₁) (h₂ : is_topological_basis B₂) : is_topological_basis (image2 set.prod B₁ B₂) := begin refine is_topological_basis_of_open_of_nhds _ _, { rintro _ ⟨u₁, u₂, hu₁, hu₂, rfl⟩, exact (h₁.is_open hu₁).prod (h₂.is_open hu₂) }, { rintro ⟨a, b⟩ u hu uo, rcases (h₁.nhds_has_basis.prod_nhds h₂.nhds_has_basis).mem_iff.1 (is_open.mem_nhds uo hu) with ⟨⟨s, t⟩, ⟨⟨hs, ha⟩, ht, hb⟩, hu⟩, exact ⟨s.prod t, mem_image2_of_mem hs ht, ⟨ha, hb⟩, hu⟩ } end lemma is_topological_basis_of_cover {ι} {U : ι → set α} (Uo : ∀ i, is_open (U i)) (Uc : (⋃ i, U i) = univ) {b : Π i, set (set (U i))} (hb : ∀ i, is_topological_basis (b i)) : is_topological_basis (⋃ i : ι, image (coe : U i → α) '' (b i)) := begin refine is_topological_basis_of_open_of_nhds (λ u hu, _) _, { simp only [mem_Union, mem_image] at hu, rcases hu with ⟨i, s, sb, rfl⟩, exact (Uo i).is_open_map_subtype_coe _ ((hb i).is_open sb) }, { intros a u ha uo, rcases Union_eq_univ_iff.1 Uc a with ⟨i, hi⟩, lift a to ↥(U i) using hi, rcases (hb i).exists_subset_of_mem_open (by exact ha) (uo.preimage continuous_subtype_coe) with ⟨v, hvb, hav, hvu⟩, exact ⟨coe '' v, mem_Union.2 ⟨i, mem_image_of_mem _ hvb⟩, mem_image_of_mem _ hav, image_subset_iff.2 hvu⟩ } end variables (α) /-- A separable space is one with a countable dense subset, available through `topological_space.exists_countable_dense`. If `α` is also known to be nonempty, then `topological_space.dense_seq` provides a sequence `ℕ → α` with dense range, see `topological_space.dense_range_dense_seq`. If `α` is a uniform space with countably generated uniformity filter (e.g., an `emetric_space`), then this condition is equivalent to `topological_space.second_countable_topology α`. In this case the latter should be used as a typeclass argument in theorems because Lean can automatically deduce `separable_space` from `second_countable_topology` but it can't deduce `second_countable_topology` and `emetric_space`. -/ class separable_space : Prop := (exists_countable_dense : ∃s:set α, countable s ∧ dense s) lemma exists_countable_dense [separable_space α] : ∃ s : set α, countable s ∧ dense s := separable_space.exists_countable_dense /-- A nonempty separable space admits a sequence with dense range. Instead of running `cases` on the conclusion of this lemma, you might want to use `topological_space.dense_seq` and `topological_space.dense_range_dense_seq`. If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/ lemma exists_dense_seq [separable_space α] [nonempty α] : ∃ u : ℕ → α, dense_range u := begin obtain ⟨s : set α, hs, s_dense⟩ := exists_countable_dense α, cases countable_iff_exists_surjective.mp hs with u hu, exact ⟨u, s_dense.mono hu⟩, end /-- A dense sequence in a non-empty separable topological space. If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/ def dense_seq [separable_space α] [nonempty α] : ℕ → α := classical.some (exists_dense_seq α) /-- The sequence `dense_seq α` has dense range. -/ @[simp] lemma dense_range_dense_seq [separable_space α] [nonempty α] : dense_range (dense_seq α) := classical.some_spec (exists_dense_seq α) end topological_space open topological_space /-- If `α` is a separable space and `f : α → β` is a continuous map with dense range, then `β` is a separable space as well. E.g., the completion of a separable uniform space is separable. -/ protected lemma dense_range.separable_space {α β : Type*} [topological_space α] [separable_space α] [topological_space β] {f : α → β} (h : dense_range f) (h' : continuous f) : separable_space β := let ⟨s, s_cnt, s_dense⟩ := exists_countable_dense α in ⟨⟨f '' s, countable.image s_cnt f, h.dense_image h' s_dense⟩⟩ namespace topological_space universe u variables (α : Type u) [t : topological_space α] include t /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, (𝓝 a).is_countably_generated) namespace first_countable_topology variable {α} /-- In a first-countable space, a cluster point `x` of a sequence is the limit of some subsequence. -/ lemma tendsto_subseq [first_countable_topology α] {u : ℕ → α} {x : α} (hx : map_cluster_pt x at_top u) : ∃ (ψ : ℕ → ℕ), (strict_mono ψ) ∧ (tendsto (u ∘ ψ) at_top (𝓝 x)) := (nhds_generated_countable x).subseq_tendsto hx end first_countable_topology variables {α} lemma is_countably_generated_nhds [first_countable_topology α] (x : α) : is_countably_generated (𝓝 x) := first_countable_topology.nhds_generated_countable x lemma is_countably_generated_nhds_within [first_countable_topology α] (x : α) (s : set α) : is_countably_generated (𝓝[s] x) := (is_countably_generated_nhds x).inf_principal s variable (α) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable [] : ∃ b : set (set α), countable b ∧ t = topological_space.generate_from b) variable {α} protected lemma is_topological_basis.second_countable_topology {b : set (set α)} (hb : is_topological_basis b) (hc : countable b) : second_countable_topology α := ⟨⟨b, hc, hb.eq_generate_from⟩⟩ variable (α) lemma exists_countable_basis [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ (⋂₀ s).nonempty} in ⟨b', ((countable_set_of_finite_subset hb₁).mono (by { simp only [← and_assoc], apply inter_subset_left })).image _, assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 hp), is_topological_basis_of_subbasis hb₂⟩ /-- A countable topological basis of `α`. -/ def countable_basis [second_countable_topology α] : set (set α) := (exists_countable_basis α).some lemma countable_countable_basis [second_countable_topology α] : countable (countable_basis α) := (exists_countable_basis α).some_spec.1 instance encodable_countable_basis [second_countable_topology α] : encodable (countable_basis α) := (countable_countable_basis α).to_encodable lemma empty_nmem_countable_basis [second_countable_topology α] : ∅ ∉ countable_basis α := (exists_countable_basis α).some_spec.2.1 lemma is_basis_countable_basis [second_countable_topology α] : is_topological_basis (countable_basis α) := (exists_countable_basis α).some_spec.2.2 lemma eq_generate_from_countable_basis [second_countable_topology α] : ‹topological_space α› = generate_from (countable_basis α) := (is_basis_countable_basis α).eq_generate_from variable {α} lemma is_open_of_mem_countable_basis [second_countable_topology α] {s : set α} (hs : s ∈ countable_basis α) : is_open s := (is_basis_countable_basis α).is_open hs lemma nonempty_of_mem_countable_basis [second_countable_topology α] {s : set α} (hs : s ∈ countable_basis α) : s.nonempty := ne_empty_iff_nonempty.1 $ ne_of_mem_of_not_mem hs $ empty_nmem_countable_basis α variable (α) @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := ⟨λ x, has_countable_basis.is_countably_generated $ ⟨(is_basis_countable_basis α).nhds_has_basis, (countable_countable_basis α).mono $ inter_subset_left _ _⟩⟩ /-- If `β` is a second-countable space, then its induced topology via `f` on `α` is also second-countable. -/ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, hb.image _, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance {β : Type*} [topological_space β] [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ((is_basis_countable_basis α).prod (is_basis_countable_basis β)).second_countable_topology $ (countable_countable_basis α).image2 (countable_countable_basis β) _ instance second_countable_topology_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := begin have : t = (λa, generate_from (countable_basis (π a))), from funext (assume a, (is_basis_countable_basis (π a)).eq_generate_from), rw this, constructor, refine ⟨pi univ '' pi univ (λ a, countable_basis (π a)), countable.image _ _, _⟩, { suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ countable_basis (π a)}, { simpa [pi] }, exact countable_pi (assume i, (countable_countable_basis _)), }, rw [pi_generate_from_eq_fintype], { congr' 1 with f, simp [pi, eq_comm] }, exact assume a, (is_basis_countable_basis (π a)).sUnion_eq end @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := begin choose p hp using λ s : countable_basis α, nonempty_of_mem_countable_basis s.2, exact ⟨⟨range p, countable_range _, (is_basis_countable_basis α).dense_iff.2 $ λ o ho _, ⟨p ⟨o, ho⟩, hp _, mem_range_self _⟩⟩⟩ end variables {α} /-- A countable open cover induces a second-countable topology if all open covers are themselves second countable. -/ lemma second_countable_topology_of_countable_cover {ι} [encodable ι] {U : ι → set α} [∀ i, second_countable_topology (U i)] (Uo : ∀ i, is_open (U i)) (hc : (⋃ i, U i) = univ) : second_countable_topology α := begin have : is_topological_basis (⋃ i, image (coe : U i → α) '' (countable_basis (U i))), from is_topological_basis_of_cover Uo hc (λ i, is_basis_countable_basis (U i)), exact this.second_countable_topology (countable_Union $ λ i, (countable_countable_basis _).image _) end /-- In a second-countable space, an open set, given as a union of open sets, is equal to the union of countably many of those sets. -/ lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := begin let B := {b ∈ countable_basis α | ∃ i, b ⊆ s i}, choose f hf using λ b : B, b.2.2, haveI : encodable B := ((countable_countable_basis α).mono (sep_subset _ _)).to_encodable, refine ⟨_, countable_range f, subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases (is_basis_countable_basis α).exists_subset_of_mem_open xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, cT.image _, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ /-- In a topological space with second countable topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ lemma countable_cover_nhds [second_countable_topology α] {f : α → set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, countable s ∧ (⋃ x ∈ s, f x) = univ := begin rcases is_open_Union_countable (λ x, interior (f x)) (λ x, is_open_interior) with ⟨s, hsc, hsU⟩, suffices : (⋃ x ∈ s, interior (f x)) = univ, from ⟨s, hsc, flip eq_univ_of_subset this (bUnion_mono $ λ _ _, interior_subset)⟩, simp only [hsU, eq_univ_iff_forall, mem_Union], exact λ x, ⟨x, mem_interior_iff_mem_nhds.2 (hf x)⟩ end end topological_space open topological_space variables {α β : Type*} [topological_space α] [topological_space β] {f : α → β} protected lemma inducing.second_countable_topology [second_countable_topology β] (hf : inducing f) : second_countable_topology α := by { rw hf.1, exact second_countable_topology_induced α β f } protected lemma embedding.second_countable_topology [second_countable_topology β] (hf : embedding f) : second_countable_topology α := hf.1.second_countable_topology
c5ee50956ab57df85d10824dcc989d355f699175
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/tests/lean/run/1685.lean
7de58d60c5a6dde4bdbfc271673b9018d90620b9
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
2,622
lean
/- This test assumes the total order on terms used by simp compares local constants using the order they appear in the local context. -/ example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, m + n = k → n + m = k := by intros; simp; assumption example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end example (m : ℕ) : ∀ n k, n + m = k → n + m = k := begin intros, simp, fail_if_success {assumption}, sorry end
d8d20000f34ae5359992d528a703036293ba12c3
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/linear_algebra/matrix/nonsingular_inverse.lean
e247fa8e54051c6875368c818677803ae5553a3d
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,211
lean
/- Copyright (c) 2019 Tim Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baanen, Lu-Ming Zhang -/ import algebra.associated import algebra.regular.smul import data.matrix.notation import linear_algebra.matrix.polynomial import tactic.linarith import tactic.ring_exp /-! # Nonsingular inverses In this file, we define an inverse for square matrices of invertible determinant. For matrices that are not square or not of full rank, there is a more general notion of pseudoinverses which we do not consider here. The definition of inverse used in this file is the adjugate divided by the determinant. The adjugate is calculated with Cramer's rule, which we introduce first. The vectors returned by Cramer's rule are given by the linear map `cramer`, which sends a matrix `A` and vector `b` to the vector consisting of the determinant of replacing the `i`th column of `A` with `b` at index `i` (written as `(A.update_column i b).det`). Using Cramer's rule, we can compute for each matrix `A` the matrix `adjugate A`. The entries of the adjugate are the determinants of each minor of `A`. Instead of defining a minor to be `A` with row `i` and column `j` deleted, we replace the `i`th row of `A` with the `j`th basis vector; this has the same determinant as the minor but more importantly equals Cramer's rule applied to `A` and the `j`th basis vector, simplifying the subsequent proofs. We prove the adjugate behaves like `det A • A⁻¹`. Finally, we show that dividing the adjugate by `det A` (if possible), giving a matrix `A⁻¹` (`nonsing_inv`), will result in a multiplicative inverse to `A`. ## References * https://en.wikipedia.org/wiki/Cramer's_rule#Finding_inverse_matrix ## Tags matrix inverse, cramer, cramer's rule, adjugate -/ namespace matrix universes u v variables {n : Type u} [decidable_eq n] [fintype n] {α : Type v} [comm_ring α] open_locale matrix big_operators open equiv equiv.perm finset section cramer /-! ### `cramer` section Introduce the linear map `cramer` with values defined by `cramer_map`. After defining `cramer_map` and showing it is linear, we will restrict our proofs to using `cramer`. -/ variables (A : matrix n n α) (b : n → α) /-- `cramer_map A b i` is the determinant of the matrix `A` with column `i` replaced with `b`, and thus `cramer_map A b` is the vector output by Cramer's rule on `A` and `b`. If `A ⬝ x = b` has a unique solution in `x`, `cramer_map A` sends the vector `b` to `A.det • x`. Otherwise, the outcome of `cramer_map` is well-defined but not necessarily useful. -/ def cramer_map (i : n) : α := (A.update_column i b).det lemma cramer_map_is_linear (i : n) : is_linear_map α (λ b, cramer_map A b i) := { map_add := det_update_column_add _ _, map_smul := det_update_column_smul _ _ } lemma cramer_is_linear : is_linear_map α (cramer_map A) := begin split; intros; ext i, { apply (cramer_map_is_linear A i).1 }, { apply (cramer_map_is_linear A i).2 } end /-- `cramer A b i` is the determinant of the matrix `A` with column `i` replaced with `b`, and thus `cramer A b` is the vector output by Cramer's rule on `A` and `b`. If `A ⬝ x = b` has a unique solution in `x`, `cramer A` sends the vector `b` to `A.det • x`. Otherwise, the outcome of `cramer` is well-defined but not necessarily useful. -/ def cramer (A : matrix n n α) : (n → α) →ₗ[α] (n → α) := is_linear_map.mk' (cramer_map A) (cramer_is_linear A) lemma cramer_apply (i : n) : cramer A b i = (A.update_column i b).det := rfl lemma cramer_transpose_row_self (i : n) : Aᵀ.cramer (A i) = pi.single i A.det := begin ext j, rw [cramer_apply, pi.single_apply], split_ifs with h, { -- i = j: this entry should be `A.det` subst h, simp only [update_column_transpose, det_transpose, update_row, function.update_eq_self] }, { -- i ≠ j: this entry should be 0 rw [update_column_transpose, det_transpose], apply det_zero_of_row_eq h, rw [update_row_self, update_row_ne (ne.symm h)] } end lemma cramer_row_self (i : n) (h : ∀ j, b j = A j i) : A.cramer b = pi.single i A.det := begin rw [← transpose_transpose A, det_transpose], convert cramer_transpose_row_self Aᵀ i, exact funext h end @[simp] lemma cramer_one : cramer (1 : matrix n n α) = 1 := begin ext i j, convert congr_fun (cramer_row_self (1 : matrix n n α) (pi.single i 1) i _) j, { simp }, { intros j, rw [matrix.one_eq_pi_single, pi.single_comm] } end lemma cramer_smul (r : α) (A : matrix n n α) : cramer (r • A) = r ^ (fintype.card n - 1) • cramer A := linear_map.ext $ λ b, funext $ λ _, det_update_column_smul' _ _ _ _ @[simp] lemma cramer_subsingleton_apply [subsingleton n] (A : matrix n n α) (b : n → α) (i : n) : cramer A b i = b i := by rw [cramer_apply, det_eq_elem_of_subsingleton _ i, update_column_self] lemma cramer_zero [nontrivial n] : cramer (0 : matrix n n α) = 0 := begin ext i j, obtain ⟨j', hj'⟩ : ∃ j', j' ≠ j := exists_ne j, apply det_eq_zero_of_column_eq_zero j', intro j'', simp [update_column_ne hj'], end /-- Use linearity of `cramer` to take it out of a summation. -/ lemma sum_cramer {β} (s : finset β) (f : β → n → α) : ∑ x in s, cramer A (f x) = cramer A (∑ x in s, f x) := (linear_map.map_sum (cramer A)).symm /-- Use linearity of `cramer` and vector evaluation to take `cramer A _ i` out of a summation. -/ lemma sum_cramer_apply {β} (s : finset β) (f : n → β → α) (i : n) : ∑ x in s, cramer A (λ j, f j x) i = cramer A (λ (j : n), ∑ x in s, f j x) i := calc ∑ x in s, cramer A (λ j, f j x) i = (∑ x in s, cramer A (λ j, f j x)) i : (finset.sum_apply i s _).symm ... = cramer A (λ (j : n), ∑ x in s, f j x) i : by { rw [sum_cramer, cramer_apply], congr' with j, apply finset.sum_apply } end cramer section adjugate /-! ### `adjugate` section Define the `adjugate` matrix and a few equations. These will hold for any matrix over a commutative ring, while the `inv` section is specifically for invertible matrices. -/ /-- The adjugate matrix is the transpose of the cofactor matrix. Typically, the cofactor matrix is defined by taking the determinant of minors, i.e. the matrix with a row and column removed. However, the proof of `mul_adjugate` becomes a lot easier if we define the minor as replacing a column with a basis vector, since it allows us to use facts about the `cramer` map. -/ def adjugate (A : matrix n n α) : matrix n n α := λ i, cramer Aᵀ (pi.single i 1) lemma adjugate_def (A : matrix n n α) : adjugate A = λ i, cramer Aᵀ (pi.single i 1) := rfl lemma adjugate_apply (A : matrix n n α) (i j : n) : adjugate A i j = (A.update_row j (pi.single i 1)).det := by { rw adjugate_def, simp only, rw [cramer_apply, update_column_transpose, det_transpose], } lemma adjugate_transpose (A : matrix n n α) : (adjugate A)ᵀ = adjugate (Aᵀ) := begin ext i j, rw [transpose_apply, adjugate_apply, adjugate_apply, update_row_transpose, det_transpose], rw [det_apply', det_apply'], apply finset.sum_congr rfl, intros σ _, congr' 1, by_cases i = σ j, { -- Everything except `(i , j)` (= `(σ j , j)`) is given by A, and the rest is a single `1`. congr; ext j', subst h, have : σ j' = σ j ↔ j' = j := σ.injective.eq_iff, rw [update_row_apply, update_column_apply], simp_rw this, rw [←dite_eq_ite, ←dite_eq_ite], congr' 1 with rfl, rw [pi.single_eq_same, pi.single_eq_same], }, { -- Otherwise, we need to show that there is a `0` somewhere in the product. have : (∏ j' : n, update_column A j (pi.single i 1) (σ j') j') = 0, { apply prod_eq_zero (mem_univ j), rw [update_column_self, pi.single_eq_of_ne' h], }, rw this, apply prod_eq_zero (mem_univ (σ⁻¹ i)), erw [apply_symm_apply σ i, update_row_self], apply pi.single_eq_of_ne, intro h', exact h ((symm_apply_eq σ).mp h') } end /-- Since the map `b ↦ cramer A b` is linear in `b`, it must be multiplication by some matrix. This matrix is `A.adjugate`. -/ lemma cramer_eq_adjugate_mul_vec (A : matrix n n α) (b : n → α) : cramer A b = A.adjugate.mul_vec b := begin nth_rewrite 1 ← A.transpose_transpose, rw [← adjugate_transpose, adjugate_def], have : b = ∑ i, (b i) • (pi.single i 1), { refine (pi_eq_sum_univ b).trans _, congr' with j, simp [pi.single_apply, eq_comm], congr, }, nth_rewrite 0 this, ext k, simp [mul_vec, dot_product, mul_comm], end lemma mul_adjugate_apply (A : matrix n n α) (i j k) : A i k * adjugate A k j = cramer Aᵀ (pi.single k (A i k)) j := begin erw [←smul_eq_mul, ←pi.smul_apply, ←linear_map.map_smul, ←pi.single_smul', smul_eq_mul, mul_one], end lemma mul_adjugate (A : matrix n n α) : A ⬝ adjugate A = A.det • 1 := begin ext i j, rw [mul_apply, pi.smul_apply, pi.smul_apply, one_apply, smul_eq_mul, mul_boole], simp [mul_adjugate_apply, sum_cramer_apply, cramer_transpose_row_self, pi.single_apply, eq_comm] end lemma adjugate_mul (A : matrix n n α) : adjugate A ⬝ A = A.det • 1 := calc adjugate A ⬝ A = (Aᵀ ⬝ (adjugate Aᵀ))ᵀ : by rw [←adjugate_transpose, ←transpose_mul, transpose_transpose] ... = A.det • 1 : by rw [mul_adjugate (Aᵀ), det_transpose, transpose_smul, transpose_one] lemma adjugate_smul (r : α) (A : matrix n n α) : adjugate (r • A) = r ^ (fintype.card n - 1) • adjugate A := begin rw [adjugate, adjugate, transpose_smul, cramer_smul], refl, end /-- `det_adjugate_of_cancel` is an auxiliary lemma for computing `(adjugate A).det`, used in `det_adjugate_eq_one` and `det_adjugate_of_is_unit`. The formula for the determinant of the adjugate of an `n` by `n` matrix `A` is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases. This lemma `det_adjugate_of_cancel` covers the case that `det A` cancels on the left of the equation `A.det * b = A.det ^ n`. -/ lemma det_adjugate_of_cancel {A : matrix n n α} (h : ∀ b, A.det * b = A.det ^ fintype.card n → b = A.det ^ (fintype.card n - 1)) : (adjugate A).det = A.det ^ (fintype.card n - 1) := h (adjugate A).det (calc A.det * (adjugate A).det = (A ⬝ adjugate A).det : (det_mul _ _).symm ... = A.det ^ fintype.card n : by simp [mul_adjugate]) lemma adjugate_subsingleton [subsingleton n] (A : matrix n n α) : adjugate A = 1 := begin ext i j, simp [subsingleton.elim i j, adjugate_apply, det_eq_elem_of_subsingleton _ i] end lemma adjugate_eq_one_of_card_eq_one {A : matrix n n α} (h : fintype.card n = 1) : adjugate A = 1 := begin haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le, exact adjugate_subsingleton _ end @[simp] lemma adjugate_zero [nontrivial n] : adjugate (0 : matrix n n α) = 0 := begin ext i j, obtain ⟨j', hj'⟩ : ∃ j', j' ≠ j := exists_ne j, apply det_eq_zero_of_column_eq_zero j', intro j'', simp [update_column_ne hj'], end @[simp] lemma adjugate_one : adjugate (1 : matrix n n α) = 1 := by { ext, simp [adjugate_def, matrix.one_apply, pi.single_apply, eq_comm] } lemma det_adjugate_eq_one {A : matrix n n α} (h : A.det = 1) : (adjugate A).det = 1 := calc (adjugate A).det = A.det ^ (fintype.card n - 1) : det_adjugate_of_cancel (λ b hb, by simpa [h] using hb) ... = 1 : by rw [h, one_pow] /-- `det_adjugate_of_is_unit` gives the formula for `(adjugate A).det` if `A.det` has an inverse. The formula for the determinant of the adjugate of an `n` by `n` matrix `A` is in general `(adjugate A).det = A.det ^ (n - 1)`, but the proof differs in several cases. This lemma `det_adjugate_of_is_unit` covers the case that `det A` has an inverse. -/ lemma det_adjugate_of_is_unit {A : matrix n n α} (h : is_unit A.det) : (adjugate A).det = A.det ^ (fintype.card n - 1) := begin rcases is_unit_iff_exists_inv'.mp h with ⟨a, ha⟩, by_cases card_lt_zero : fintype.card n ≤ 0, { have h : fintype.card n = 0 := by linarith, simp [det_eq_one_of_card_eq_zero h] }, have zero_lt_card : 0 < fintype.card n := by linarith, have n_nonempty : nonempty n := fintype.card_pos_iff.mp zero_lt_card, by_cases card_lt_one : fintype.card n ≤ 1, { have h : fintype.card n = 1 := by linarith, simp [h, adjugate_eq_one_of_card_eq_one h] }, have one_lt_card : 1 < fintype.card n := by linarith, have zero_lt_card_sub_one : 0 < fintype.card n - 1 := (tsub_lt_tsub_iff_right (refl 1)).mpr one_lt_card, apply det_adjugate_of_cancel, intros b hb, calc b = a * (det A ^ (fintype.card n - 1 + 1)) : by rw [←one_mul b, ←ha, mul_assoc, hb, tsub_add_cancel_of_le zero_lt_card.nat_succ_le] ... = a * det A * det A ^ (fintype.card n - 1) : by ring_exp ... = det A ^ (fintype.card n - 1) : by rw [ha, one_mul] end @[simp] lemma adjugate_fin_zero (A : matrix (fin 0) (fin 0) α) : adjugate A = 0 := @subsingleton.elim _ matrix.subsingleton_of_empty_left _ _ @[simp] lemma adjugate_fin_one (A : matrix (fin 1) (fin 1) α) : adjugate A = 1 := adjugate_subsingleton A lemma adjugate_fin_two (A : matrix (fin 2) (fin 2) α) : adjugate A = ![![A 1 1, -A 0 1], ![-A 1 0, A 0 0]] := begin ext i j, rw [adjugate_apply, det_fin_two], fin_cases i with [0, 1]; fin_cases j with [0, 1]; simp only [nat.one_ne_zero, one_mul, fin.one_eq_zero_iff, pi.single_eq_same, zero_mul, fin.zero_eq_one_iff, sub_zero, pi.single_eq_of_ne, ne.def, not_false_iff, update_row_self, update_row_ne, cons_val_zero, mul_zero, mul_one, zero_sub, cons_val_one, head_cons], end @[simp] lemma adjugate_fin_two' (a b c d : α) : adjugate ![![a, b], ![c, d]] = ![![d, -b], ![-c, a]] := adjugate_fin_two _ end adjugate section inv /-! ### `inv` section Defines the matrix `A⁻¹` and proves it is the inverse matrix of a square matrix `A` as long as `det A` has a multiplicative inverse. -/ variables (A : matrix n n α) (B : matrix n n α) open_locale classical lemma is_unit_det_transpose (h : is_unit A.det) : is_unit Aᵀ.det := by { rw det_transpose, exact h, } /-- The inverse of a square matrix, when it is invertible (and zero otherwise).-/ noncomputable instance : has_inv (matrix n n α) := ⟨λ A, ring.inverse A.det • A.adjugate⟩ lemma inv_def (A : matrix n n α) : A⁻¹ = ring.inverse A.det • A.adjugate := rfl lemma nonsing_inv_apply_not_is_unit (h : ¬ is_unit A.det) : A⁻¹ = 0 := by rw [inv_def, ring.inverse_non_unit _ h, zero_smul] lemma nonsing_inv_apply (h : is_unit A.det) : A⁻¹ = (↑h.unit⁻¹ : α) • A.adjugate := begin rw [inv_def, ←ring.inverse_unit h.unit], refl, end lemma transpose_nonsing_inv : (A⁻¹)ᵀ = (Aᵀ)⁻¹ := by rw [inv_def, inv_def, transpose_smul, det_transpose, adjugate_transpose] /-- The `nonsing_inv` of `A` is a right inverse. -/ @[simp] lemma mul_nonsing_inv (h : is_unit A.det) : A ⬝ A⁻¹ = 1 := by rw [A.nonsing_inv_apply h, mul_smul, mul_adjugate, smul_smul, units.inv_mul_of_eq h.unit_spec, one_smul] /-- The `nonsing_inv` of `A` is a left inverse. -/ @[simp] lemma nonsing_inv_mul (h : is_unit A.det) : A⁻¹ ⬝ A = 1 := calc A⁻¹ ⬝ A = (Aᵀ ⬝ (Aᵀ)⁻¹)ᵀ : by { rw [transpose_mul, Aᵀ.transpose_nonsing_inv, transpose_transpose], } ... = 1ᵀ : by { rw Aᵀ.mul_nonsing_inv, exact A.is_unit_det_transpose h, } ... = 1 : transpose_one lemma nonsing_inv_cancel_or_zero : (A⁻¹ ⬝ A = 1 ∧ A ⬝ A⁻¹ = 1) ∨ A⁻¹ = 0 := begin by_cases h : is_unit A.det, { exact or.inl ⟨nonsing_inv_mul _ h, mul_nonsing_inv _ h⟩ }, { exact or.inr (nonsing_inv_apply_not_is_unit _ h) } end @[simp] lemma nonsing_inv_det (h : is_unit A.det) : A⁻¹.det * A.det = 1 := by rw [←det_mul, A.nonsing_inv_mul h, det_one] lemma is_unit_nonsing_inv_det (h : is_unit A.det) : is_unit A⁻¹.det := is_unit_of_mul_eq_one _ _ (A.nonsing_inv_det h) @[simp] lemma nonsing_inv_nonsing_inv (h : is_unit A.det) : (A⁻¹)⁻¹ = A := calc (A⁻¹)⁻¹ = 1 ⬝ (A⁻¹)⁻¹ : by rw matrix.one_mul ... = A ⬝ A⁻¹ ⬝ (A⁻¹)⁻¹ : by rw A.mul_nonsing_inv h ... = A : by { rw [matrix.mul_assoc, (A⁻¹).mul_nonsing_inv (A.is_unit_nonsing_inv_det h), matrix.mul_one], } @[simp] lemma is_unit_nonsing_inv_det_iff {A : matrix n n α} : is_unit A⁻¹.det ↔ is_unit A.det := begin refine ⟨λ h, _, is_unit_nonsing_inv_det _⟩, nontriviality α, casesI is_empty_or_nonempty n, { simp }, contrapose! h, rw [nonsing_inv_apply_not_is_unit _ h, det_zero], { simp }, { apply_instance } end /-- If `A.det` has a constructive inverse, produce one for `A`. -/ def invertible_of_det_invertible [invertible A.det] : invertible A := { inv_of := ⅟A.det • A.adjugate, mul_inv_of_self := by rw [mul_smul_comm, matrix.mul_eq_mul, mul_adjugate, smul_smul, inv_of_mul_self, one_smul], inv_of_mul_self := by rw [smul_mul_assoc, matrix.mul_eq_mul, adjugate_mul, smul_smul, inv_of_mul_self, one_smul] } /-- `A.det` is invertible if `A` has a left inverse. -/ def det_invertible_of_left_inverse (h : B ⬝ A = 1) : invertible A.det := { inv_of := B.det, mul_inv_of_self := by rw [mul_comm, ← det_mul, h, det_one], inv_of_mul_self := by rw [← det_mul, h, det_one] } /-- `A.det` is invertible if `A` has a right inverse. -/ def det_invertible_of_right_inverse (h : A ⬝ B = 1) : invertible A.det := { inv_of := B.det, mul_inv_of_self := by rw [← det_mul, h, det_one], inv_of_mul_self := by rw [mul_comm, ← det_mul, h, det_one] } /-- If `A` has a constructive inverse, produce one for `A.det`. -/ def det_invertible_of_invertible [invertible A] : invertible A.det := det_invertible_of_left_inverse A (⅟A) (inv_of_mul_self _) /-- Given a proof that `A.det` has a constructive inverse, lift `A` to `units (matrix n n α)`-/ def unit_of_det_invertible [invertible A.det] : units (matrix n n α) := @unit_of_invertible _ _ A (invertible_of_det_invertible A) /-- A matrix whose determinant is a unit is itself a unit. This is a noncomputable version of `matrix.units_of_det_invertible`, with the inverse defeq to `matrix.nonsing_inv`. -/ noncomputable def nonsing_inv_unit (h : is_unit A.det) : units (matrix n n α) := { val := A, inv := A⁻¹, val_inv := by { rw matrix.mul_eq_mul, apply A.mul_nonsing_inv h, }, inv_val := by { rw matrix.mul_eq_mul, apply A.nonsing_inv_mul h, } } lemma unit_of_det_invertible_eq_nonsing_inv_unit [invertible A.det] : unit_of_det_invertible A = nonsing_inv_unit A (is_unit_of_invertible _) := by { ext, refl } /-- When lowered to a prop, `matrix.det_invertible_of_invertible` and `matrix.invertible_of_det_invertible` form an `iff`. -/ lemma is_unit_iff_is_unit_det : is_unit A ↔ is_unit A.det := begin split; rintros ⟨x, hx⟩; refine @is_unit_of_invertible _ _ _ (id _), { haveI : invertible A := hx.rec x.invertible, apply det_invertible_of_invertible, }, { haveI : invertible A.det := hx.rec x.invertible, apply invertible_of_det_invertible, }, end /- `is_unit_of_invertible A` converts the "stronger" condition `invertible A` to proposition `is_unit A`. -/ /-- `matrix.is_unit_det_of_invertible` converts `invertible A` to `is_unit A.det`. -/ lemma is_unit_det_of_invertible [invertible A] : is_unit A.det := @is_unit_of_invertible _ _ _(det_invertible_of_invertible A) @[simp] lemma inv_eq_nonsing_inv_of_invertible [invertible A] : ⅟ A = A⁻¹ := begin suffices : is_unit A, { rw [←this.mul_left_inj, inv_of_mul_self, matrix.mul_eq_mul, nonsing_inv_mul], rwa ←is_unit_iff_is_unit_det }, exact is_unit_of_invertible _ end variables {A} {B} /- `is_unit.invertible` lifts the proposition `is_unit A` to a constructive inverse of `A`. -/ /-- "Lift" the proposition `is_unit A.det` to a constructive inverse of `A`. -/ noncomputable def invertible_of_is_unit_det (h : is_unit A.det) : invertible A := ⟨A⁻¹, nonsing_inv_mul A h, mul_nonsing_inv A h⟩ lemma is_unit_det_of_left_inverse (h : B ⬝ A = 1) : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_left_inverse _ _ h) lemma is_unit_det_of_right_inverse (h : A ⬝ B = 1) : is_unit A.det := @is_unit_of_invertible _ _ _ (det_invertible_of_right_inverse _ _ h) lemma det_ne_zero_of_left_inverse [nontrivial α] (h : B ⬝ A = 1) : A.det ≠ 0 := is_unit.ne_zero (matrix.is_unit_det_of_left_inverse h) lemma det_ne_zero_of_right_inverse [nontrivial α] (h : A ⬝ B = 1) : A.det ≠ 0 := is_unit.ne_zero (matrix.is_unit_det_of_right_inverse h) lemma nonsing_inv_left_right (h : A ⬝ B = 1) : B ⬝ A = 1 := begin have h' : is_unit B.det := is_unit_det_of_left_inverse h, calc B ⬝ A = (B ⬝ A) ⬝ (B ⬝ B⁻¹) : by simp only [h', matrix.mul_one, mul_nonsing_inv] ... = B ⬝ ((A ⬝ B) ⬝ B⁻¹) : by simp only [matrix.mul_assoc] ... = B ⬝ B⁻¹ : by simp only [h, matrix.one_mul] ... = 1 : mul_nonsing_inv B h', end lemma nonsing_inv_right_left (h : B ⬝ A = 1) : A ⬝ B = 1 := nonsing_inv_left_right h /-- If matrix A is left invertible, then its inverse equals its left inverse. -/ lemma inv_eq_left_inv (h : B ⬝ A = 1) : A⁻¹ = B := begin have h1 := (is_unit_det_of_left_inverse h), have h2 := matrix.invertible_of_is_unit_det h1, have := @inv_of_eq_left_inv (matrix n n α) (infer_instance) A B h2 h, simp* at *, end /-- If matrix A is right invertible, then its inverse equals its right inverse. -/ lemma inv_eq_right_inv (h : A ⬝ B = 1) : A⁻¹ = B := begin have h1 := (is_unit_det_of_right_inverse h), have h2 := matrix.invertible_of_is_unit_det h1, have := @inv_of_eq_right_inv (matrix n n α) (infer_instance) A B h2 h, simp* at *, end /-- We can construct an instance of invertible A if A has a left inverse. -/ def invertible_of_left_inverse (h: B ⬝ A = 1) : invertible A := ⟨B, h, nonsing_inv_right_left h⟩ /-- We can construct an instance of invertible A if A has a right inverse. -/ def invertible_of_right_inverse (h: A ⬝ B = 1) : invertible A := ⟨B, nonsing_inv_left_right h, h⟩ section inv_eq_inv variables {C : matrix n n α} /-- The left inverse of matrix A is unique when existing. -/ lemma left_inv_eq_left_inv (h: B ⬝ A = 1) (g: C ⬝ A = 1) : B = C := by rw [←(inv_eq_left_inv h), ←(inv_eq_left_inv g)] /-- The right inverse of matrix A is unique when existing. -/ lemma right_inv_eq_right_inv (h: A ⬝ B = 1) (g: A ⬝ C = 1) : B = C := by rw [←(inv_eq_right_inv h), ←(inv_eq_right_inv g)] /-- The right inverse of matrix A equals the left inverse of A when they exist. -/ lemma right_inv_eq_left_inv (h: A ⬝ B = 1) (g: C ⬝ A = 1) : B = C := by rw [←(inv_eq_right_inv h), ←(inv_eq_left_inv g)] lemma inv_inj (h : A⁻¹ = B⁻¹) (h' : is_unit A.det) : A = B := begin refine left_inv_eq_left_inv (mul_nonsing_inv _ h') _, rw h, refine mul_nonsing_inv _ _, rwa [←is_unit_nonsing_inv_det_iff, ←h, is_unit_nonsing_inv_det_iff] end end inv_eq_inv variable (A) @[simp] lemma mul_inv_of_invertible [invertible A] : A ⬝ A⁻¹ = 1 := mul_nonsing_inv A (is_unit_det_of_invertible A) @[simp] lemma inv_mul_of_invertible [invertible A] : A⁻¹ ⬝ A = 1 := nonsing_inv_mul A (is_unit_det_of_invertible A) @[simp] lemma inv_zero : (0 : matrix n n α)⁻¹ = 0 := begin casesI (subsingleton_or_nontrivial α) with ht ht, { simp }, cases (fintype.card n).zero_le.eq_or_lt with hc hc, { rw [eq_comm, fintype.card_eq_zero_iff] at hc, haveI := hc, ext i, exact (is_empty.false i).elim }, { have hn : nonempty n := fintype.card_pos_iff.mp hc, refine nonsing_inv_apply_not_is_unit _ _, simp [hn] }, end @[simp] lemma inv_one : (1 : matrix n n α)⁻¹ = 1 := inv_eq_left_inv (by simp) lemma inv_smul (k : α) [invertible k] (h : is_unit A.det) : (k • A)⁻¹ = ⅟k • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) lemma inv_smul' (k : units α) (h : is_unit A.det) : (k • A)⁻¹ = k⁻¹ • A⁻¹ := inv_eq_left_inv (by simp [h, smul_smul]) lemma inv_adjugate (A : matrix n n α) (h : is_unit A.det) : (adjugate A)⁻¹ = h.unit⁻¹ • A := begin refine inv_eq_left_inv _, rw [smul_mul, mul_adjugate, units.smul_def, smul_smul, h.coe_inv_mul, one_smul] end @[simp] lemma inv_inv_inv (A : matrix n n α) : A⁻¹⁻¹⁻¹ = A⁻¹ := begin by_cases h : is_unit A.det, { rw [nonsing_inv_nonsing_inv _ h] }, { simp [nonsing_inv_apply_not_is_unit _ h] } end lemma _root_.ring_hom.map_adjugate {R S : Type*} [comm_ring R] [comm_ring S] (f : R →+* S) (M : matrix n n R) : f.map_matrix M.adjugate = matrix.adjugate (f.map_matrix M) := begin ext i k, have : pi.single i (1 : S) = f ∘ pi.single i 1, { rw ←f.map_one, exact pi.single_op (λ i, f) (λ i, f.map_zero) i (1 : R) }, rw [adjugate_apply, ring_hom.map_matrix_apply, map_apply, ring_hom.map_matrix_apply, this, ←map_update_row, ←ring_hom.map_matrix_apply, ←ring_hom.map_det, ←adjugate_apply] end lemma adjugate_conj_transpose [star_ring α] (A : matrix n n α) : A.adjugateᴴ = adjugate (Aᴴ) := begin dsimp only [conj_transpose], have : Aᵀ.adjugate.map star = adjugate (Aᵀ.map star) := ((star_ring_aut : α ≃+* α).to_ring_hom.map_adjugate Aᵀ), rw [A.adjugate_transpose, this], end lemma is_regular_of_is_left_regular_det {A : matrix n n α} (hA : is_left_regular A.det) : is_regular A := begin split, { intros B C h, refine hA.matrix _, rw [←matrix.one_mul B, ←matrix.one_mul C, ←matrix.smul_mul, ←matrix.smul_mul, ←adjugate_mul, matrix.mul_assoc, matrix.mul_assoc, ←mul_eq_mul A, h, mul_eq_mul] }, { intros B C h, simp only [mul_eq_mul] at h, refine hA.matrix _, rw [←matrix.mul_one B, ←matrix.mul_one C, ←matrix.mul_smul, ←matrix.mul_smul, ←mul_adjugate, ←matrix.mul_assoc, ←matrix.mul_assoc, h] } end lemma adjugate_mul_distrib_aux (A B : matrix n n α) (hA : is_left_regular A.det) (hB : is_left_regular B.det) : adjugate (A ⬝ B) = adjugate B ⬝ adjugate A := begin have hAB : is_left_regular (A ⬝ B).det, { rw [det_mul], exact hA.mul hB }, refine (is_regular_of_is_left_regular_det hAB).left _, rw [mul_eq_mul, mul_adjugate, mul_eq_mul, matrix.mul_assoc, ←matrix.mul_assoc B, mul_adjugate, smul_mul, matrix.one_mul, mul_smul, mul_adjugate, smul_smul, mul_comm, ←det_mul] end /-- Proof follows from "The trace Cayley-Hamilton theorem" by Darij Grinberg, Section 5.3 -/ lemma adjugate_mul_distrib (A B : matrix n n α) : adjugate (A ⬝ B) = adjugate B ⬝ adjugate A := begin casesI subsingleton_or_nontrivial α, { simp }, let g : matrix n n α → matrix n n (polynomial α) := λ M, M.map polynomial.C + (polynomial.X : polynomial α) • 1, let f' : matrix n n (polynomial α) →+* matrix n n α := (polynomial.eval_ring_hom 0).map_matrix, have f'_inv : ∀ M, f' (g M) = M, { intro, ext, simp [f', g], }, have f'_adj : ∀ (M : matrix n n α), f' (adjugate (g M)) = adjugate M, { intro, rw [ring_hom.map_adjugate, f'_inv] }, have f'_g_mul : ∀ (M N : matrix n n α), f' (g M ⬝ g N) = M ⬝ N, { intros, rw [←mul_eq_mul, ring_hom.map_mul, f'_inv, f'_inv, mul_eq_mul] }, have hu : ∀ (M : matrix n n α), is_regular (g M).det, { intros M, refine polynomial.monic.is_regular _, simp only [g, polynomial.monic.def, ←polynomial.leading_coeff_det_X_one_add_C M, add_comm] }, rw [←f'_adj, ←f'_adj, ←f'_adj, ←mul_eq_mul (f' (adjugate (g B))), ←f'.map_mul, mul_eq_mul, ←adjugate_mul_distrib_aux _ _ (hu A).left (hu B).left, ring_hom.map_adjugate, ring_hom.map_adjugate, f'_inv, f'_g_mul] end lemma mul_inv_rev (A B : matrix n n α) : (A ⬝ B)⁻¹ = B⁻¹ ⬝ A⁻¹ := begin simp only [inv_def], rw [matrix.smul_mul, matrix.mul_smul, smul_smul, det_mul, adjugate_mul_distrib, ring.mul_inverse_rev], end @[simp] lemma adjugate_pow (A : matrix n n α) (k : ℕ) : adjugate (A ^ k) = (adjugate A) ^ k := begin induction k with k IH, { simp }, { rw [pow_succ', mul_eq_mul, adjugate_mul_distrib, IH, ←mul_eq_mul, pow_succ] } end end inv /-- One form of Cramer's rule -/ @[simp] lemma det_smul_inv_mul_vec_eq_cramer (A : matrix n n α) (b : n → α) (h : is_unit A.det) : A.det • A⁻¹.mul_vec b = cramer A b := begin rw [cramer_eq_adjugate_mul_vec, A.nonsing_inv_apply h, ← smul_mul_vec_assoc, smul_smul, h.mul_coe_inv, one_smul] end /-- A stronger form of **Cramer's rule** that allows us to solve some instances of `A ⬝ x = b` even if the determinant is not a unit. A sufficient (but still not necessary) condition is that `A.det` divides `b`. -/ @[simp] lemma mul_vec_cramer (A : matrix n n α) (b : n → α) : A.mul_vec (cramer A b) = A.det • b := by rw [cramer_eq_adjugate_mul_vec, mul_vec_mul_vec, mul_adjugate, smul_mul_vec_assoc, one_mul_vec] section nondegenerate variables {m R A : Type*} [fintype m] [comm_ring R] /-- A matrix `M` is nondegenerate if for all `v ≠ 0`, there is a `w ≠ 0` with `w ⬝ M ⬝ v ≠ 0`. -/ def nondegenerate (M : matrix m m R) := ∀ v, (∀ w, matrix.dot_product v (mul_vec M w) = 0) → v = 0 /-- If `M` is nondegenerate and `w ⬝ M ⬝ v = 0` for all `w`, then `v = 0`. -/ lemma nondegenerate.eq_zero_of_ortho {M : matrix m m R} (hM : nondegenerate M) {v : m → R} (hv : ∀ w, matrix.dot_product v (mul_vec M w) = 0) : v = 0 := hM v hv /-- If `M` is nondegenerate and `v ≠ 0`, then there is some `w` such that `w ⬝ M ⬝ v ≠ 0`. -/ lemma nondegenerate.exists_not_ortho_of_ne_zero {M : matrix m m R} (hM : nondegenerate M) {v : m → R} (hv : v ≠ 0) : ∃ w, matrix.dot_product v (mul_vec M w) ≠ 0 := not_forall.mp (mt hM.eq_zero_of_ortho hv) variables [comm_ring A] [is_domain A] /-- If `M` has a nonzero determinant, then `M` as a bilinear form on `n → A` is nondegenerate. See also `bilin_form.nondegenerate_of_det_ne_zero'` and `bilin_form.nondegenerate_of_det_ne_zero`. -/ theorem nondegenerate_of_det_ne_zero {M : matrix n n A} (hM : M.det ≠ 0) : nondegenerate M := begin intros v hv, ext i, specialize hv (M.cramer (pi.single i 1)), refine (mul_eq_zero.mp _).resolve_right hM, convert hv, simp only [mul_vec_cramer M (pi.single i 1), dot_product, pi.smul_apply, smul_eq_mul], rw [finset.sum_eq_single i, pi.single_eq_same, mul_one], { intros j _ hj, simp [hj] }, { intros, have := finset.mem_univ i, contradiction } end theorem eq_zero_of_vec_mul_eq_zero {M : matrix n n A} (hM : M.det ≠ 0) {v : n → A} (hv : M.vec_mul v = 0) : v = 0 := (nondegenerate_of_det_ne_zero hM).eq_zero_of_ortho (λ w, by rw [dot_product_mul_vec, hv, zero_dot_product]) theorem eq_zero_of_mul_vec_eq_zero {M : matrix n n A} (hM : M.det ≠ 0) {v : n → A} (hv : M.mul_vec v = 0) : v = 0 := eq_zero_of_vec_mul_eq_zero (by rwa det_transpose) ((vec_mul_transpose M v).trans hv) end nondegenerate end matrix
ce43c75ed9aaca688b0f173644a8fefd1d543aa9
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Util/FindMVar.lean
4d18130a1f78ab74a27aa0a1601bc525140ff928
[ "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,046
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean namespace FindMVar abbrev Visitor := Option MVarId → Option MVarId mutual partial def visit (p : MVarId → Bool) (e : Expr) : Visitor := fun s => if s.isSome || !e.hasMVar then s else main p e s @[specialize] partial def main (p : MVarId → Bool) : Expr → Visitor | Expr.proj _ _ e _ => visit p e | Expr.forallE _ d b _ => visit p b ∘ visit p d | Expr.lam _ d b _ => visit p b ∘ visit p d | Expr.letE _ t v b _ => visit p b ∘ visit p v ∘ visit p t | Expr.app f a _ => visit p a ∘ visit p f | Expr.mdata _ b _ => visit p b | Expr.mvar mvarId _ => fun s => if s.isNone && p mvarId then some mvarId else s | _ => id end end FindMVar @[inline] def Expr.findMVar? (e : Expr) (p : MVarId → Bool) : Option MVarId := FindMVar.main p e none end Lean
35457238d83b048d9fe67f34a270e6596756a1d8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/continued_fractions/computation/terminates_iff_rat.lean
dddf5af9ecba89477720c3e7adaa1b5b2df3f07f
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,232
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.approximations import algebra.continued_fractions.computation.correctness_terminating import data.rat /-! # Termination of Continued Fraction Computations (`gcf.of`) ## Summary We show that the continued fraction for a value `v`, as defined in `algebra.continued_fractions.computation.basic`, terminates if and only if `v` corresponds to a rational number, that is `↑v = q` for some `q : ℚ`. ## Main Theorems - `generalized_continued_fraction.coe_of_rat` shows that `generalized_continued_fraction.of v = generalized_continued_fraction.of q` for `v : α` given that `↑v = q` and `q : ℚ`. - `generalized_continued_fraction.terminates_iff_rat` shows that `generalized_continued_fraction.of v` terminates if and only if `↑v = q` for some `q : ℚ`. ## Tags rational, continued fraction, termination -/ namespace generalized_continued_fraction open generalized_continued_fraction (of) variables {K : Type*} [linear_ordered_field K] [floor_ring K] /- We will have to constantly coerce along our structures in the following proofs using their provided map functions. -/ local attribute [simp] pair.map int_fract_pair.mapFr section rat_of_terminates /-! ### Terminating Continued Fractions Are Rational We want to show that the computation of a continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`. In this section, we show the implication from left to right. We first show that every finite convergent corresponds to a rational number `q` and then use the finite correctness proof (`of_correctness_of_terminates`) of `generalized_continued_fraction.of` to show that `v = ↑q`. -/ variables (v : K) (n : ℕ) lemma exists_gcf_pair_rat_eq_of_nth_conts_aux : ∃ (conts : pair ℚ), (of v).continuants_aux n = (conts.map coe : pair K) := nat.strong_induction_on n begin clear n, let g := of v, assume n IH, rcases n with _|_|n, -- n = 0 { suffices : ∃ (gp : pair ℚ), pair.mk (1 : K) 0 = gp.map coe, by simpa [continuants_aux], use (pair.mk 1 0), simp }, -- n = 1 { suffices : ∃ (conts : pair ℚ), pair.mk g.h 1 = conts.map coe, by simpa [continuants_aux], use (pair.mk ⌊v⌋ 1), simp }, -- 2 ≤ n { cases (IH (n + 1) $ lt_add_one (n + 1)) with pred_conts pred_conts_eq, -- invoke the IH cases s_ppred_nth_eq : (g.s.nth n) with gp_n, -- option.none { use pred_conts, have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from continuants_aux_stable_of_terminated (n + 1).le_succ s_ppred_nth_eq, simp only [this, pred_conts_eq] }, -- option.some { -- invoke the IH a second time cases (IH n $ lt_of_le_of_lt (n.le_succ) $ lt_add_one $ n + 1) with ppred_conts ppred_conts_eq, obtain ⟨a_eq_one, z, b_eq_z⟩ : gp_n.a = 1 ∧ ∃ (z : ℤ), gp_n.b = (z : K), from of_part_num_eq_one_and_exists_int_part_denom_eq s_ppred_nth_eq, -- finally, unfold the recurrence to obtain the required rational value. simp only [a_eq_one, b_eq_z, (continuants_aux_recurrence s_ppred_nth_eq ppred_conts_eq pred_conts_eq)], use (next_continuants 1 (z : ℚ) ppred_conts pred_conts), cases ppred_conts, cases pred_conts, simp [next_continuants, next_numerator, next_denominator] } } end lemma exists_gcf_pair_rat_eq_nth_conts : ∃ (conts : pair ℚ), (of v).continuants n = (conts.map coe : pair K) := by { rw [nth_cont_eq_succ_nth_cont_aux], exact (exists_gcf_pair_rat_eq_of_nth_conts_aux v $ n + 1) } lemma exists_rat_eq_nth_numerator : ∃ (q : ℚ), (of v).numerators n = (q : K) := begin rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨a, _⟩, nth_cont_eq⟩, use a, simp [num_eq_conts_a, nth_cont_eq], end lemma exists_rat_eq_nth_denominator : ∃ (q : ℚ), (of v).denominators n = (q : K) := begin rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨_, b⟩, nth_cont_eq⟩, use b, simp [denom_eq_conts_b, nth_cont_eq] end /-- Every finite convergent corresponds to a rational number. -/ lemma exists_rat_eq_nth_convergent : ∃ (q : ℚ), (of v).convergents n = (q : K) := begin rcases (exists_rat_eq_nth_numerator v n) with ⟨Aₙ, nth_num_eq⟩, rcases (exists_rat_eq_nth_denominator v n) with ⟨Bₙ, nth_denom_eq⟩, use (Aₙ / Bₙ), simp [nth_num_eq, nth_denom_eq, convergent_eq_num_div_denom] end variable {v} /-- Every terminating continued fraction corresponds to a rational number. -/ theorem exists_rat_eq_of_terminates (terminates : (of v).terminates) : ∃ (q : ℚ), v = ↑q := begin obtain ⟨n, v_eq_conv⟩ : ∃ n, v = (of v).convergents n, from of_correctness_of_terminates terminates, obtain ⟨q, conv_eq_q⟩ : ∃ (q : ℚ), (of v).convergents n = (↑q : K), from exists_rat_eq_nth_convergent v n, have : v = (↑q : K), from eq.trans v_eq_conv conv_eq_q, use [q, this] end end rat_of_terminates section rat_translation /-! ### Technical Translation Lemmas Before we can show that the continued fraction of a rational number terminates, we have to prove some technical translation lemmas. More precisely, in this section, we show that, given a rational number `q : ℚ` and value `v : K` with `v = ↑q`, the continued fraction of `q` and `v` coincide. In particular, we show that ```lean (↑(generalized_continued_fraction.of q : generalized_continued_fraction ℚ) : generalized_continued_fraction K) = generalized_continued_fraction.of v` ``` in `generalized_continued_fraction.coe_of_rat`. To do this, we proceed bottom-up, showing the correspondence between the basic functions involved in the computation first and then lift the results step-by-step. -/ /- The lifting works for arbitrary linear ordered fields with a floor function. -/ variables {v : K} {q : ℚ} (v_eq_q : v = (↑q : K)) (n : ℕ) include v_eq_q /-! First, we show the correspondence for the very basic functions in `generalized_continued_fraction.int_fract_pair`. -/ namespace int_fract_pair lemma coe_of_rat_eq : ((int_fract_pair.of q).mapFr coe : int_fract_pair K) = int_fract_pair.of v := by simp [int_fract_pair.of, v_eq_q] lemma coe_stream_nth_rat_eq : ((int_fract_pair.stream q n).map (mapFr coe) : option $ int_fract_pair K) = int_fract_pair.stream v n := begin induction n with n IH, case nat.zero : { simp [int_fract_pair.stream, (coe_of_rat_eq v_eq_q)] }, case nat.succ : { rw v_eq_q at IH, cases stream_q_nth_eq : (int_fract_pair.stream q n) with ifp_n, case option.none : { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq] }, case option.some : { cases ifp_n with b fr, cases decidable.em (fr = 0) with fr_zero fr_ne_zero, { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_zero] }, { replace IH : some (int_fract_pair.mk b ↑fr) = int_fract_pair.stream ↑q n, by rwa [stream_q_nth_eq] at IH, have : (fr : K)⁻¹ = ((fr⁻¹ : ℚ) : K), by norm_cast, have coe_of_fr := (coe_of_rat_eq this), simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_ne_zero], unfold_coes, simpa [coe_of_fr] } } } end lemma coe_stream_rat_eq : ((int_fract_pair.stream q).map (option.map (mapFr coe)) : stream $ option $ int_fract_pair K) = int_fract_pair.stream v := by { funext n, exact (int_fract_pair.coe_stream_nth_rat_eq v_eq_q n) } end int_fract_pair /-! Now we lift the coercion results to the continued fraction computation. -/ lemma coe_of_h_rat_eq : (↑((of q).h : ℚ) : K) = (of v).h := begin unfold of int_fract_pair.seq1, rw ←(int_fract_pair.coe_of_rat_eq v_eq_q), simp end lemma coe_of_s_nth_rat_eq : (((of q).s.nth n).map (pair.map coe) : option $ pair K) = (of v).s.nth n := begin simp only [of, int_fract_pair.seq1, seq.map_nth, seq.nth_tail], simp only [seq.nth], rw [←(int_fract_pair.coe_stream_rat_eq v_eq_q)], rcases succ_nth_stream_eq : (int_fract_pair.stream q (n + 1)) with _ | ⟨_, _⟩; simp [stream.map, stream.nth, succ_nth_stream_eq] end lemma coe_of_s_rat_eq : (((of q).s).map (pair.map coe) : seq $ pair K) = (of v).s := by { ext n, rw ←(coe_of_s_nth_rat_eq v_eq_q), refl } /-- Given `(v : K), (q : ℚ), and v = q`, we have that `gcf.of q = gcf.of v` -/ lemma coe_of_rat_eq : (⟨(of q).h, (of q).s.map (pair.map coe)⟩ : generalized_continued_fraction K) = of v := begin cases gcf_v_eq : (of v) with h s, subst v, obtain rfl : ↑⌊↑q⌋ = h, by { injection gcf_v_eq }, simp [coe_of_h_rat_eq rfl, coe_of_s_rat_eq rfl, gcf_v_eq] end lemma of_terminates_iff_of_rat_terminates {v : K} {q : ℚ} (v_eq_q : v = (q : K)) : (of v).terminates ↔ (of q).terminates := begin split; intro h; cases h with n h; use n; simp only [seq.terminated_at, (coe_of_s_nth_rat_eq v_eq_q n).symm] at h ⊢; cases ((of q).s.nth n); trivial end end rat_translation section terminates_of_rat /-! ### Continued Fractions of Rationals Terminate Finally, we show that the continued fraction of a rational number terminates. The crucial insight is that, given any `q : ℚ` with `0 < q < 1`, the numerator of `int.fract q` is smaller than the numerator of `q`. As the continued fraction computation recursively operates on the fractional part of a value `v` and `0 ≤ int.fract v < 1`, we infer that the numerator of the fractional part in the computation decreases by at least one in each step. As `0 ≤ int.fract v`, this process must stop after finite number of steps, and the computation hence terminates. -/ namespace int_fract_pair variables {q : ℚ} {n : ℕ} /-- Shows that for any `q : ℚ` with `0 < q < 1`, the numerator of the fractional part of `int_fract_pair.of q⁻¹` is smaller than the numerator of `q`. -/ lemma of_inv_fr_num_lt_num_of_pos (q_pos : 0 < q) : (int_fract_pair.of q⁻¹).fr.num < q.num := rat.fract_inv_num_lt_num_of_pos q_pos /-- Shows that the sequence of numerators of the fractional parts of the stream is strictly antitone. -/ lemma stream_succ_nth_fr_num_lt_nth_fr_num_rat {ifp_n ifp_succ_n : int_fract_pair ℚ} (stream_nth_eq : int_fract_pair.stream q n = some ifp_n) (stream_succ_nth_eq : int_fract_pair.stream q (n + 1) = some ifp_succ_n) : ifp_succ_n.fr.num < ifp_n.fr.num := begin obtain ⟨ifp_n', stream_nth_eq', ifp_n_fract_ne_zero, int_fract_pair.of_eq_ifp_succ_n⟩ : ∃ ifp_n', int_fract_pair.stream q n = some ifp_n' ∧ ifp_n'.fr ≠ 0 ∧ int_fract_pair.of ifp_n'.fr⁻¹ = ifp_succ_n, from succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq, have : ifp_n = ifp_n', by injection (eq.trans stream_nth_eq.symm stream_nth_eq'), cases this, rw [←int_fract_pair.of_eq_ifp_succ_n], cases (nth_stream_fr_nonneg_lt_one stream_nth_eq) with zero_le_ifp_n_fract ifp_n_fract_lt_one, have : 0 < ifp_n.fr, from (lt_of_le_of_ne zero_le_ifp_n_fract $ ifp_n_fract_ne_zero.symm), exact (of_inv_fr_num_lt_num_of_pos this) end lemma stream_nth_fr_num_le_fr_num_sub_n_rat : ∀ {ifp_n : int_fract_pair ℚ}, int_fract_pair.stream q n = some ifp_n → ifp_n.fr.num ≤ (int_fract_pair.of q).fr.num - n := begin induction n with n IH, case nat.zero { assume ifp_zero stream_zero_eq, have : int_fract_pair.of q = ifp_zero, by injection stream_zero_eq, simp [le_refl, this.symm] }, case nat.succ { assume ifp_succ_n stream_succ_nth_eq, suffices : ifp_succ_n.fr.num + 1 ≤ (int_fract_pair.of q).fr.num - n, by { rw [int.coe_nat_succ, sub_add_eq_sub_sub], solve_by_elim [le_sub_right_of_add_le] }, rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with ⟨ifp_n, stream_nth_eq, -⟩, have : ifp_succ_n.fr.num < ifp_n.fr.num, from stream_succ_nth_fr_num_lt_nth_fr_num_rat stream_nth_eq stream_succ_nth_eq, have : ifp_succ_n.fr.num + 1 ≤ ifp_n.fr.num, from int.add_one_le_of_lt this, exact (le_trans this (IH stream_nth_eq)) } end lemma exists_nth_stream_eq_none_of_rat (q : ℚ) : ∃ (n : ℕ), int_fract_pair.stream q n = none := begin let fract_q_num := (int.fract q).num, let n := fract_q_num.nat_abs + 1, cases stream_nth_eq : (int_fract_pair.stream q n) with ifp, { use n, exact stream_nth_eq }, { -- arrive at a contradiction since the numerator decreased num + 1 times but every fractional -- value is nonnegative. have ifp_fr_num_le_q_fr_num_sub_n : ifp.fr.num ≤ fract_q_num - n, from stream_nth_fr_num_le_fr_num_sub_n_rat stream_nth_eq, have : fract_q_num - n = -1, by { have : 0 ≤ fract_q_num, from rat.num_nonneg_iff_zero_le.elim_right (int.fract_nonneg q), simp [(int.nat_abs_of_nonneg this), sub_add_eq_sub_sub_swap, sub_right_comm] }, have : ifp.fr.num ≤ -1, by rwa this at ifp_fr_num_le_q_fr_num_sub_n, have : 0 ≤ ifp.fr, from (nth_stream_fr_nonneg_lt_one stream_nth_eq).left, have : 0 ≤ ifp.fr.num, from rat.num_nonneg_iff_zero_le.elim_right this, linarith } end end int_fract_pair /-- The continued fraction of a rational number terminates. -/ theorem terminates_of_rat (q : ℚ) : (of q).terminates := exists.elim (int_fract_pair.exists_nth_stream_eq_none_of_rat q) ( assume n stream_nth_eq_none, exists.intro n ( have int_fract_pair.stream q (n + 1) = none, from int_fract_pair.stream_is_seq q stream_nth_eq_none, (of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_right this) ) ) end terminates_of_rat /-- The continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`. -/ theorem terminates_iff_rat (v : K) : (of v).terminates ↔ ∃ (q : ℚ), v = (q : K) := iff.intro ( assume terminates_v : (of v).terminates, show ∃ (q : ℚ), v = (q : K), from exists_rat_eq_of_terminates terminates_v ) ( assume exists_q_eq_v : ∃ (q : ℚ), v = (↑q : K), exists.elim exists_q_eq_v ( assume q, assume v_eq_q : v = ↑q, have (of q).terminates, from terminates_of_rat q, (of_terminates_iff_of_rat_terminates v_eq_q).elim_right this ) ) end generalized_continued_fraction
edc8064a9ba67bcee232627849385762037b3d68
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/group_with_zero/defs.lean
2465879a2a70252a4004b1e4ad6e2d68a1ddfab8
[ "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
5,434
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 algebra.group.defs import logic.nontrivial /-! # Typeclasses for groups with an adjoined zero element This file provides just the typeclass definitions, and the projection lemmas that expose their members. ## Main definitions * `group_with_zero` * `comm_group_with_zero` -/ set_option old_structure_cmd true universe u -- We have to fix the universe of `G₀` here, since the default argument to -- `group_with_zero.div'` cannot contain a universe metavariable. variables {G₀ : Type u} {M₀ M₀' G₀' : Type*} section /-- Typeclass for expressing that a type `M₀` with multiplication and a zero satisfies `0 * a = 0` and `a * 0 = 0` for all `a : M₀`. -/ @[protect_proj, ancestor has_mul has_zero] class mul_zero_class (M₀ : Type*) extends has_mul M₀, has_zero M₀ := (zero_mul : ∀ a : M₀, 0 * a = 0) (mul_zero : ∀ a : M₀, a * 0 = 0) section mul_zero_class variables [mul_zero_class M₀] {a b : M₀} @[ematch, simp] lemma zero_mul (a : M₀) : 0 * a = 0 := mul_zero_class.zero_mul a @[ematch, simp] lemma mul_zero (a : M₀) : a * 0 = 0 := mul_zero_class.mul_zero a end mul_zero_class /-- Predicate typeclass for expressing that `a * b = 0` implies `a = 0` or `b = 0` for all `a` and `b` of type `G₀`. -/ class no_zero_divisors (M₀ : Type*) [has_mul M₀] [has_zero M₀] : Prop := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ {a b : M₀}, a * b = 0 → a = 0 ∨ b = 0) export no_zero_divisors (eq_zero_or_eq_zero_of_mul_eq_zero) /-- A type `S₀` is a "semigroup with zero” if it is a semigroup with zero element, and `0` is left and right absorbing. -/ @[protect_proj] class semigroup_with_zero (S₀ : Type*) extends semigroup S₀, mul_zero_class S₀. /- By defining this _after_ `semigroup_with_zero`, we ensure that searches for `mul_zero_class` find this class first. -/ /-- A typeclass for non-associative monoids with zero elements. -/ @[protect_proj] class mul_zero_one_class (M₀ : Type*) extends mul_one_class M₀, mul_zero_class M₀. /-- A type `M₀` is a “monoid with zero” if it is a monoid with zero element, and `0` is left and right absorbing. -/ @[protect_proj] class monoid_with_zero (M₀ : Type*) extends monoid M₀, mul_zero_one_class M₀. @[priority 100] -- see Note [lower instance priority] instance monoid_with_zero.to_semigroup_with_zero (M₀ : Type*) [monoid_with_zero M₀] : semigroup_with_zero M₀ := { ..‹monoid_with_zero M₀› } /-- A type `M` is a `cancel_monoid_with_zero` if it is a monoid with zero element, `0` is left and right absorbing, and left/right multiplication by a non-zero element is injective. -/ @[protect_proj] class cancel_monoid_with_zero (M₀ : Type*) extends monoid_with_zero M₀ := (mul_left_cancel_of_ne_zero : ∀ {a b c : M₀}, a ≠ 0 → a * b = a * c → b = c) (mul_right_cancel_of_ne_zero : ∀ {a b c : M₀}, b ≠ 0 → a * b = c * b → a = c) section cancel_monoid_with_zero variables [cancel_monoid_with_zero M₀] {a b c : M₀} lemma mul_left_cancel' (ha : a ≠ 0) (h : a * b = a * c) : b = c := cancel_monoid_with_zero.mul_left_cancel_of_ne_zero ha h lemma mul_right_cancel' (hb : b ≠ 0) (h : a * b = c * b) : a = c := cancel_monoid_with_zero.mul_right_cancel_of_ne_zero hb h lemma mul_right_injective' (ha : a ≠ 0) : function.injective ((*) a) := λ b c, mul_left_cancel' ha lemma mul_left_injective' (hb : b ≠ 0) : function.injective (λ a, a * b) := λ a c, mul_right_cancel' hb end cancel_monoid_with_zero /-- A type `M` is a commutative “monoid with zero” if it is a commutative monoid with zero element, and `0` is left and right absorbing. -/ @[protect_proj] class comm_monoid_with_zero (M₀ : Type*) extends comm_monoid M₀, monoid_with_zero M₀. /-- A type `M` is a `comm_cancel_monoid_with_zero` if it is a commutative monoid with zero element, `0` is left and right absorbing, and left/right multiplication by a non-zero element is injective. -/ @[protect_proj] class comm_cancel_monoid_with_zero (M₀ : Type*) extends comm_monoid_with_zero M₀, cancel_monoid_with_zero M₀. /-- A type `G₀` is a “group with zero” if it is a monoid with zero element (distinct from `1`) such that every nonzero element is invertible. The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. Examples include division rings and the ordered monoids that are the target of valuations in general valuation theory.-/ class group_with_zero (G₀ : Type u) extends monoid_with_zero G₀, div_inv_monoid G₀, nontrivial G₀ := (inv_zero : (0 : G₀)⁻¹ = 0) (mul_inv_cancel : ∀ a:G₀, a ≠ 0 → a * a⁻¹ = 1) section group_with_zero variables [group_with_zero G₀] @[simp] lemma inv_zero : (0 : G₀)⁻¹ = 0 := group_with_zero.inv_zero @[simp] lemma mul_inv_cancel {a : G₀} (h : a ≠ 0) : a * a⁻¹ = 1 := group_with_zero.mul_inv_cancel a h end group_with_zero /-- A type `G₀` is a commutative “group with zero” if it is a commutative monoid with zero element (distinct from `1`) such that every nonzero element is invertible. The type is required to come with an “inverse” function, and the inverse of `0` must be `0`. -/ class comm_group_with_zero (G₀ : Type*) extends comm_monoid_with_zero G₀, group_with_zero G₀. end
a479406d02696cb40e7383d4e4ca277cb56aa91d
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/geo/src/pfin/default.lean
bbdf59fc03d21ad227a3a36125637f39ae044b93
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
52
lean
import pfin.basic pfin.ops pfin.lemmas pfin.fintype
9e891b19cc2131b9c77afdc6ec05e0bc5c5b8672
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Data/OpenDecl.lean
6fef6f08a68e63612654c10ac053a4398b4efdd4
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
758
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.Data.Name namespace Lean inductive OpenDecl | simple (ns : Name) (except : List Name) | explicit (id : Name) (declName : Name) namespace OpenDecl instance : Inhabited OpenDecl := ⟨simple Name.anonymous []⟩ instance : ToString OpenDecl := ⟨fun decl => match decl with | explicit id decl => toString id ++ " → " ++ toString decl | simple ns ex => toString ns ++ (if ex == [] then "" else " hiding " ++ toString ex)⟩ end OpenDecl def rootNamespace := `_root_ def removeRoot (n : Name) : Name := n.replacePrefix rootNamespace Name.anonymous end Lean
8d4148192c7c80ff3987061e6d42c3d1864556b0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/hashableBug.lean
0e21932fc4556888967345217201eac18e110290
[ "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
87
lean
inductive Step (α : Type u) where | impossible : α → Step α deriving Hashable
1d6a73be99b195335c5905f1d194d1a36d2e529a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/coe2.lean
84c2e92ab2436b5a344e011ca11b21618a48f97f
[ "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
895
lean
namespace hidden set_option pp.coercions false #check if tt then "a" else "b" /- Remark: in the standard library nat_to_int and int_to_real are has_lift instances instead of has_coe. -/ constant int : Type constant real : Type constant nat_to_int : has_coe nat int constant int_to_real : has_coe int real attribute [instance] nat_to_int int_to_real constant sine : real → real constants n m : nat constants i j : int constants x y : real #check sine x #check sine n #check sine i constant int_has_add : has_add int constant real_has_add : has_add real attribute [instance] int_has_add real_has_add #check x + i /- The following one does not work because the implicit argument ?A of add is bound to int when x is processed. -/ #check i + x -- FAIL /- The workaround is to use the explicit lift -/ #check ↑i + x #check x + n #check n + x -- FAIL #check ↑n + x end hidden
60cea66fa0cab941a0b818843230a345a95baa99
037dba89703a79cd4a4aec5e959818147f97635d
/src/2020/problem_sheets/Part_II_sheet1.lean
72cffe0a58e5fe06448bef58c6063b721a7998c4
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
660
lean
import tactic variables (x y : ℕ) open nat theorem Q1a : x + y = y + x := begin sorry end theorem Q1b : x + y = x → y = 0 := begin sorry end theorem Q1c : x + y = 0 → x = 0 ∧ y = 0 := begin sorry end theorem Q1d : x * y = y * x := begin sorry end theorem Q2a : 1 * x = x ∧ x = x * 1 := begin sorry end variable z : ℕ theorem Q2b : (x + y) * z = x * z + y * z := begin sorry end theorem Q2c : (x * y) * z = x * (y * z) := begin sorry end -- Q3 def def is_pred (x y : ℕ) := x.succ = y theorem Q3a : ¬ ∃ x : ℕ, is_pred x 0 := begin sorry end theorem Q3b : y ≠ 0 → ∃! x, is_pred x y := begin sorry end
17d9bd468a61f92bb3381b0acbb6d90dc70e2119
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean/Meta/Message.lean
7cc26d0fa3d1ab805b81ac9b0fbf6f316cba21d6
[ "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
4,608
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Meta.Basic namespace Lean namespace Meta namespace Exception private def run? {α} (ctx : ExceptionContext) (x : MetaM α) : Option α := match x { lctx := ctx.lctx, currRecDepth := 0, maxRecDepth := getMaxRecDepth ctx.opts } { env := ctx.env, mctx := ctx.mctx, ngen := { namePrefix := `_meta_exception } } with | EStateM.Result.ok a _ => some a | EStateM.Result.error _ _ => none private def inferType? (ctx : ExceptionContext) (e : Expr) : Option Expr := run? ctx (inferType e) private def inferDomain? (ctx : ExceptionContext) (f : Expr) : Option Expr := run? ctx $ do fType ← inferType f; fType ← whnf fType; match fType with | Expr.forallE _ d _ _ => pure d | _ => throw $ Exception.other "unexpected" private def whnf? (ctx : ExceptionContext) (e : Expr) : Option Expr := run? ctx (whnf e) def mkAppTypeMismatchMessage (f a : Expr) (ctx : ExceptionContext) : MessageData := mkCtx ctx $ let e := mkApp f a; match inferType? ctx a, inferDomain? ctx f with | some aType, some expectedType => "application type mismatch" ++ indentExpr e ++ Format.line ++ "argument" ++ indentExpr a ++ Format.line ++ "has type" ++ indentExpr aType ++ Format.line ++ "but is expected to have type" ++ indentExpr expectedType | _, _ => "application type mismatch" ++ indentExpr e def mkLetTypeMismatchMessage (fvarId : FVarId) (ctx : ExceptionContext) : MessageData := mkCtx ctx $ match ctx.lctx.find? fvarId with | some (LocalDecl.ldecl _ n t v b) => match inferType? ctx v with | some vType => "invalid let declaration, term" ++ indentExpr v ++ Format.line ++ "has type " ++ indentExpr vType ++ Format.line ++ "but is expected to have type" ++ indentExpr t | none => "type mismatch at let declaration for " ++ n | _ => unreachable! /-- Convert to `MessageData` that is supposed to be displayed in user-friendly error messages. -/ def toMessageData : Exception → MessageData | unknownConst c ctx => mkCtx ctx $ "unknown constant " ++ c | unknownFVar fvarId ctx => mkCtx ctx $ "unknown free variable " ++ fvarId | unknownExprMVar mvarId ctx => mkCtx ctx $ "unknown metavariable " ++ mvarId | unknownLevelMVar mvarId ctx => mkCtx ctx $ "unknown universe level metavariable " ++ mvarId | unexpectedBVar bvarIdx => "unexpected bound variable " ++ mkBVar bvarIdx | functionExpected f a ctx => mkCtx ctx $ "function expected " ++ mkApp f a | typeExpected t ctx => mkCtx ctx $ "type expected " ++ t | incorrectNumOfLevels c lvls ctx => mkCtx ctx $ "incorrect number of universe levels " ++ mkConst c lvls | invalidProjection s i e ctx => mkCtx ctx $ "invalid projection" ++ indentExpr (mkProj s i e) | revertFailure xs decl ctx => mkCtx ctx $ "revert failure" | readOnlyMVar mvarId ctx => mkCtx ctx $ "tried to update read only metavariable " ++ mkMVar mvarId | isLevelDefEqStuck u v ctx => mkCtx ctx $ "stuck at universe level constraint " ++ u ++ " =?= " ++ v | isExprDefEqStuck t s ctx => mkCtx ctx $ "stuck at constraint " ++ t ++ " =?= " ++ s | letTypeMismatch fvarId ctx => mkLetTypeMismatchMessage fvarId ctx | appTypeMismatch f a ctx => mkAppTypeMismatchMessage f a ctx | notInstance i ctx => mkCtx ctx $ "not a type class instance " ++ i | appBuilder op msg args ctx => mkCtx ctx $ "application builder failure " ++ op ++ " " ++ args ++ " " ++ msg | synthInstance inst ctx => mkCtx ctx $ "failed to synthesize" ++ indentExpr inst | tactic tacName mvarId msg ctx => mkCtx ctx $ "tactic '" ++ tacName ++ "' failed, " ++ msg ++ Format.line ++ MessageData.ofGoal mvarId | kernel ex opts => ex.toMessageData opts | bug _ _ => "internal bug" -- TODO improve | other s => s end Exception instance MetaHasEval {α} [MetaHasEval α] : MetaHasEval (MetaM α) := ⟨fun env opts x _ => do match x { config := { opts := opts }, currRecDepth := 0, maxRecDepth := getMaxRecDepth opts } { env := env } with | EStateM.Result.ok a s => do s.traceState.traces.forM $ fun m => IO.println $ format m; MetaHasEval.eval s.env opts a | EStateM.Result.error err s => do s.traceState.traces.forM $ fun m => IO.println $ format m; throw (IO.userError (toString (format err.toMessageData)))⟩ end Meta end Lean
8aed5134f84c770bb29afb3c4ca3a770ad4c63b5
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/ideal/over.lean
016bad775a0082602137f5bb4cdd23dbfac523a8
[ "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
14,558
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen -/ import ring_theory.algebraic import ring_theory.localization /-! # Ideals over/under ideals This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ variables {R : Type*} [comm_ring R] namespace ideal open polynomial open submodule section comm_ring variables {S : Type*} [comm_ring S] {f : R →+* S} {I J : ideal S} lemma coeff_zero_mem_comap_of_root_mem_of_eval_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r ∈ I) : p.coeff 0 ∈ I.comap f := begin rw [←p.div_X_mul_X_add, eval₂_add, eval₂_C, eval₂_mul, eval₂_X] at hp, refine mem_comap.mpr ((I.add_mem_iff_right _).mp hp), exact I.mul_mem_left _ hr end lemma coeff_zero_mem_comap_of_root_mem {r : S} (hr : r ∈ I) {p : polynomial R} (hp : p.eval₂ f r = 0) : p.coeff 0 ∈ I.comap f := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (hp.symm ▸ I.zero_mem) lemma exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {r : S} (r_non_zero_divisor : ∀ {x}, x * r = 0 → x = 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := begin refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a coeff_eq_zero a_ne_zero ih p_ne_zero hp, refine ⟨0, _, coeff_zero_mem_comap_of_root_mem hr hp⟩, simp [coeff_eq_zero, a_ne_zero] }, { intros p p_nonzero ih mul_nonzero hp, rw [eval₂_mul, eval₂_X] at hp, obtain ⟨i, hi, mem⟩ := ih p_nonzero (r_non_zero_divisor hp), refine ⟨i + 1, _, _⟩; simp [hi, mem] } end /-- Let `P` be an ideal in `R[x]`. The map `R[x]/P → (R / (P ∩ R))[x] / (P / (P ∩ R))` is injective. -/ lemma injective_quotient_le_comap_map (P : ideal (polynomial R)) : function.injective ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map) := begin refine quotient_map_injective' (le_of_eq _), rw comap_map_of_surjective (map_ring_hom (quotient.mk (P.comap C))) (map_surjective _ quotient.mk_surjective), refine le_antisymm (sup_le le_rfl _) (le_sup_left_of_le le_rfl), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using ext_iff.mp (ideal.mem_bot.mp (mem_comap.mp hp)) n, end /-- The identity in this lemma asserts that the "obvious" square ``` R → (R / (P ∩ R)) ↓ ↓ R[x] / P → (R / (P ∩ R))[x] / (P / (P ∩ R)) ``` commutes. It is used, for instance, in the proof of `quotient_mk_comp_C_is_integral_of_jacobson`, in the file `ring_theory/jacobson`. -/ lemma quotient_mk_maps_eq (P : ideal (polynomial R)) : ((quotient.mk (map (map_ring_hom (quotient.mk (P.comap C))) P)).comp C).comp (quotient.mk (P.comap C)) = ((map (map_ring_hom (quotient.mk (P.comap C))) P).quotient_map (map_ring_hom (quotient.mk (P.comap C))) le_comap_map).comp ((quotient.mk P).comp C) := begin refine ring_hom.ext (λ x, _), repeat { rw [ring_hom.coe_comp, function.comp_app] }, rw [quotient_map_mk, coe_map_ring_hom, map_C], end /-- This technical lemma asserts the existence of a polynomial `p` in an ideal `P ⊂ R[x]` that is non-zero in the quotient `R / (P ∩ R) [x]`. The assumptions are equivalent to `P ≠ 0` and `P ∩ R = (0)`. -/ lemma exists_nonzero_mem_of_ne_bot {P : ideal (polynomial R)} (Pb : P ≠ ⊥) (hP : ∀ (x : R), C x ∈ P → x = 0) : ∃ p : polynomial R, p ∈ P ∧ (polynomial.map (quotient.mk (P.comap C)) p) ≠ 0 := begin obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr Pb), refine ⟨m, submodule.coe_mem m, λ pp0, hm (submodule.coe_eq_zero.mp _)⟩, refine (is_add_group_hom.injective_iff (polynomial.map (quotient.mk (P.comap C)))).mp _ _ pp0, refine map_injective _ ((quotient.mk (P.comap C)).injective_iff_ker_eq_bot.mpr _), rw [mk_ker], exact (submodule.eq_bot_iff _).mpr (λ x hx, hP x (mem_comap.mp hx)), end end comm_ring section integral_domain variables {S : Type*} [integral_domain S] {f : R →+* S} {I J : ideal S} lemma exists_coeff_ne_zero_mem_comap_of_root_mem {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} : ∀ (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0), ∃ i, p.coeff i ≠ 0 ∧ p.coeff i ∈ I.comap f := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (λ _ h, or.resolve_right (mul_eq_zero.mp h) r_ne_zero) hr lemma exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hpI : p.eval₂ f r ∈ I) : ∃ i, p.coeff i ∈ (J.comap f : set R) \ (I.comap f) := begin obtain ⟨hrJ, hrI⟩ := hr, have rbar_ne_zero : quotient.mk I r ≠ 0 := mt (quotient.mk_eq_zero I).mp hrI, have rbar_mem_J : quotient.mk I r ∈ J.map (quotient.mk I) := mem_map_of_mem hrJ, have quotient_f : ∀ x ∈ I.comap f, (quotient.mk I).comp f x = 0, { simp [quotient.eq_zero_iff_mem] }, have rbar_root : (p.map (quotient.mk (I.comap f))).eval₂ (quotient.lift (I.comap f) _ quotient_f) (quotient.mk I r) = 0, { convert quotient.eq_zero_iff_mem.mpr hpI, exact trans (eval₂_map _ _ _) (hom_eval₂ p f (quotient.mk I) r).symm }, obtain ⟨i, ne_zero, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem rbar_ne_zero rbar_mem_J p_ne_zero rbar_root, rw coeff_map at ne_zero mem, refine ⟨i, (mem_quotient_iff_mem hIJ).mp _, mt _ ne_zero⟩, { simpa using mem }, simp [quotient.eq_zero_iff_mem], end lemma comap_ne_bot_of_root_mem {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : p.eval₂ f r = 0) : I.comap f ≠ ⊥ := λ h, let ⟨i, hi, mem⟩ := exists_coeff_ne_zero_mem_comap_of_root_mem r_ne_zero hr p_ne_zero hp in absurd (mem_bot.mp (eq_bot_iff.mp h mem)) hi lemma comap_lt_comap_of_root_mem_sdiff [I.is_prime] (hIJ : I ≤ J) {r : S} (hr : r ∈ (J : set S) \ I) {p : polynomial R} (p_ne_zero : p.map (quotient.mk (I.comap f)) ≠ 0) (hp : p.eval₂ f r ∈ I) : I.comap f < J.comap f := let ⟨i, hJ, hI⟩ := exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff hIJ hr p_ne_zero hp in lt_iff_le_and_exists.mpr ⟨comap_mono hIJ, p.coeff i, hJ, hI⟩ variables [algebra R S] lemma comap_ne_bot_of_algebraic_mem {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : I.comap (algebra_map R S) ≠ ⊥ := let ⟨p, p_ne_zero, hp⟩ := hx in comap_ne_bot_of_root_mem x_ne_zero x_mem p_ne_zero hp lemma comap_ne_bot_of_integral_mem [nontrivial R] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : I.comap (algebra_map R S) ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (hx.is_algebraic R) lemma eq_bot_of_comap_eq_bot [nontrivial R] (hRS : algebra.is_integral R S) (hI : I.comap (algebra_map R S) = ⊥) : I = ⊥ := begin refine eq_bot_iff.2 (λ x hx, _), by_cases hx0 : x = 0, { exact hx0.symm ▸ ideal.zero_mem ⊥ }, { exact absurd hI (comap_ne_bot_of_integral_mem hx0 hx (hRS x)) } end lemma mem_of_one_mem (h : (1 : S) ∈ I) (x) : x ∈ I := (I.eq_top_iff_one.mpr h).symm ▸ mem_top lemma comap_lt_comap_of_integral_mem_sdiff [hI : I.is_prime] (hIJ : I ≤ J) {x : S} (mem : x ∈ (J : set S) \ I) (integral : is_integral R x) : I.comap (algebra_map R S) < J.comap (algebra_map _ _) := begin obtain ⟨p, p_monic, hpx⟩ := integral, refine comap_lt_comap_of_root_mem_sdiff hIJ mem _ _, swap, { apply map_monic_ne_zero p_monic, apply quotient.nontrivial, apply mt comap_eq_top_iff.mp, apply hI.1 }, convert I.zero_mem end lemma is_maximal_of_is_integral_of_is_maximal_comap (hRS : algebra.is_integral R S) (I : ideal S) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R S))) : is_maximal I := ⟨⟨mt comap_eq_top_iff.mpr hI.1.1, λ J I_lt_J, let ⟨I_le_J, x, hxJ, hxI⟩ := lt_iff_le_and_exists.mp I_lt_J in comap_eq_top_iff.1 $ hI.1.2 _ (comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (hRS x))⟩⟩ lemma is_maximal_of_is_integral_of_is_maximal_comap' {R S : Type*} [comm_ring R] [integral_domain S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) [hI' : I.is_prime] (hI : is_maximal (I.comap f)) : is_maximal I := @is_maximal_of_is_integral_of_is_maximal_comap R _ S _ f.to_algebra hf I hI' hI lemma is_maximal_comap_of_is_integral_of_is_maximal (hRS : algebra.is_integral R S) (I : ideal S) [hI : I.is_maximal] : is_maximal (I.comap (algebra_map R S)) := begin refine quotient.maximal_of_is_field _ _, haveI : is_prime (I.comap (algebra_map R S)) := comap_is_prime _ _, exact is_field_of_is_integral_of_is_field (is_integral_quotient_of_is_integral hRS) algebra_map_quotient_injective (by rwa ← quotient.maximal_ideal_iff_is_field_quotient), end lemma is_maximal_comap_of_is_integral_of_is_maximal' {R S : Type*} [comm_ring R] [integral_domain S] (f : R →+* S) (hf : f.is_integral) (I : ideal S) (hI : I.is_maximal) : is_maximal (I.comap f) := @is_maximal_comap_of_is_integral_of_is_maximal R _ S _ f.to_algebra hf I hI lemma integral_closure.comap_ne_bot [nontrivial R] {I : ideal (integral_closure R S)} (I_ne_bot : I ≠ ⊥) : I.comap (algebra_map R (integral_closure R S)) ≠ ⊥ := let ⟨x, x_mem, x_ne_zero⟩ := I.ne_bot_iff.mp I_ne_bot in comap_ne_bot_of_integral_mem x_ne_zero x_mem (integral_closure.is_integral x) lemma integral_closure.eq_bot_of_comap_eq_bot [nontrivial R] {I : ideal (integral_closure R S)} : I.comap (algebra_map R (integral_closure R S)) = ⊥ → I = ⊥ := imp_of_not_imp_not _ _ integral_closure.comap_ne_bot lemma integral_closure.comap_lt_comap {I J : ideal (integral_closure R S)} [I.is_prime] (I_lt_J : I < J) : I.comap (algebra_map R (integral_closure R S)) < J.comap (algebra_map _ _) := let ⟨I_le_J, x, hxJ, hxI⟩ := lt_iff_le_and_exists.mp I_lt_J in comap_lt_comap_of_integral_mem_sdiff I_le_J ⟨hxJ, hxI⟩ (integral_closure.is_integral x) lemma integral_closure.is_maximal_of_is_maximal_comap (I : ideal (integral_closure R S)) [I.is_prime] (hI : is_maximal (I.comap (algebra_map R (integral_closure R S)))) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (λ x, integral_closure.is_integral x) I hI /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_prime_of_is_integral' (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ Q.comap (algebra_map R S) = P := begin have hP0 : (0 : S) ∉ algebra.algebra_map_submonoid S P.prime_compl, { rintro ⟨x, ⟨hx, x0⟩⟩, exact absurd (hP x0) hx }, let Rₚ := localization P.prime_compl, let f := localization.of P.prime_compl, let Sₚ := localization (algebra.algebra_map_submonoid S P.prime_compl), let g := localization.of (algebra.algebra_map_submonoid S P.prime_compl), letI : integral_domain (localization (algebra.algebra_map_submonoid S P.prime_compl)) := localization_map.integral_domain_localization (le_non_zero_divisors_of_domain hP0), obtain ⟨Qₚ : ideal Sₚ, Qₚ_maximal⟩ := exists_maximal Sₚ, haveI Qₚ_max : is_maximal (comap _ Qₚ) := @is_maximal_comap_of_is_integral_of_is_maximal Rₚ _ Sₚ _ (localization_algebra P.prime_compl f g) (is_integral_localization f g H) _ Qₚ_maximal, refine ⟨comap g.to_map Qₚ, ⟨comap_is_prime g.to_map Qₚ, _⟩⟩, convert localization.at_prime.comap_maximal_ideal, rw [comap_comap, ← local_ring.eq_maximal_ideal Qₚ_max, ← f.map_comp _], refl end /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : I.comap (algebra_map R S) ≤ P) : ∃ Q ≥ I, is_prime Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q' : ideal I.quotient, ⟨Q'_prime, hQ'⟩⟩ := @exists_ideal_over_prime_of_is_integral' (I.comap (algebra_map R S)).quotient _ I.quotient _ ideal.quotient_algebra (is_integral_quotient_of_is_integral H) (map (quotient.mk (I.comap (algebra_map R S))) P) (map_is_prime_of_surjective quotient.mk_surjective (by simp [hIP])) (le_trans (le_of_eq ((ring_hom.injective_iff_ker_eq_bot _).1 algebra_map_quotient_injective)) bot_le), haveI := Q'_prime, refine ⟨Q'.comap _, le_trans (le_of_eq mk_ker.symm) (ker_le_comap _), ⟨comap_is_prime _ Q', _⟩⟩, rw comap_comap, refine trans _ (trans (congr_arg (comap (quotient.mk (comap (algebra_map R S) I))) hQ') _), { simpa [comap_comap] }, { refine trans (comap_map_of_surjective _ quotient.mk_surjective _) (sup_eq_left.2 _), simpa [← ring_hom.ker_eq_comap_bot] using hIP}, end /-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ lemma exists_ideal_over_maximal_of_is_integral (H : algebra.is_integral R S) (P : ideal R) [P_max : is_maximal P] (hP : (algebra_map R S).ker ≤ P) : ∃ (Q : ideal S), is_maximal Q ∧ Q.comap (algebra_map R S) = P := begin obtain ⟨Q, ⟨Q_prime, hQ⟩⟩ := exists_ideal_over_prime_of_is_integral' H P hP, haveI : Q.is_prime := Q_prime, exact ⟨Q, is_maximal_of_is_integral_of_is_maximal_comap H _ (hQ.symm ▸ P_max), hQ⟩, end end integral_domain end ideal
797251f6e8b8cc4b8d4f12d542eec8561e240355
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/test/library_search/basic.lean
0e952cd412ea14b23b530ac2b2491115c06223f1
[ "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,654
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 data.nat.basic /- Turn off trace messages so they don't pollute the test build: -/ set_option trace.silence_library_search true /- For debugging purposes, we can display the list of lemmas: -/ -- set_option trace.suggest true namespace test.library_search -- Check that `library_search` fails if there are no goals. example : true := begin trivial, success_if_fail { library_search }, end -- Verify that `library_search` solves goals via `solve_by_elim` when the library isn't -- even needed. example (P : Prop) (p : P) : P := by library_search example (P : Prop) (p : P) (np : ¬P) : false := by library_search example (X : Type) (P : Prop) (x : X) (h : Π x : X, x = x → P) : P := by library_search def lt_one (n : ℕ) := n < 1 lemma zero_lt_one (n : ℕ) (h : n = 0) : lt_one n := by subst h; dsimp [lt_one]; simp -- Verify that calls to solve_by_elim to discharge subgoals use `rfl` example : lt_one 0 := by library_search example (α : Prop) : α → α := by library_search -- says: `exact id` example (p : Prop) [decidable p] : (¬¬p) → p := by library_search -- says: `exact not_not.mp` example (a b : Prop) (h : a ∧ b) : a := by library_search -- says: `exact h.left` example (P Q : Prop) [decidable P] [decidable Q]: (¬ Q → ¬ P) → (P → Q) := by library_search -- says: `exact not_imp_not.mp` example (a b : ℕ) : a + b = b + a := by library_search -- says: `exact add_comm a b` example {a b : ℕ} : a ≤ a + b := by library_search -- says: `exact nat.le.intro rfl` example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- says: `exact nat.mul_sub_left_distrib n m k` example (n m k : ℕ) : n * m - n * k = n * (m - k) := by library_search -- says: `exact eq.symm (nat.mul_sub_left_distrib n m k)` example {n m : ℕ} (h : m < n) : m ≤ n - 1 := by library_search -- says: `exact nat.le_pred_of_lt h` example {α : Type} (x y : α) : x = y ↔ y = x := by library_search -- says: `exact eq_comm` example (a b : ℕ) (ha : 0 < a) (hb : 0 < b) : 0 < a + b := by library_search -- says: `exact add_pos ha hb` example (a b : ℕ) : 0 < a → 0 < b → 0 < a + b := by library_search -- says: `exact add_pos` example (a b : ℕ) (h : a ∣ b) (w : b > 0) : a ≤ b := by library_search -- says: `exact nat.le_of_dvd w h` -- We even find `iff` results: example : ∀ P : Prop, ¬(P ↔ ¬P) := by library_search -- says: `λ (a : Prop), (iff_not_self a).mp` example {a b c : ℕ} (ha : a > 0) (w : b ∣ c) : a * b ∣ a * c := by library_search -- exact mul_dvd_mul_left a w example {a b c : ℕ} (h₁ : a ∣ c) (h₂ : a ∣ b + c) : a ∣ b := by library_search -- says `exact (nat.dvd_add_left h₁).mp h₂` -- We have control of how `library_search` uses `solve_by_elim`. -- In particular, we can add extra lemmas to the `solve_by_elim` step -- (i.e. for `library_search` to use to attempt to discharge subgoals -- after successfully applying a lemma from the library.) example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end -- We can also use attributes: meta def ex_attr : user_attribute := { name := `ex, descr := "A lemma that should be applied by `library_search` when discharging subgoals." } run_cmd attribute.register ``ex_attr attribute [ex] add_lt_add example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest with ex, library_search with ex, -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end example (a b : ℕ) (h : 0 < b) : (a * b) / b = a := by library_search -- Says: `exact nat.mul_div_left a h` example (a b : ℕ) (h : b ≠ 0) : (a * b) / b = a := begin success_if_fail { library_search }, library_search [nat.pos_iff_ne_zero.mpr], end -- Checking examples from issue #2220 example {α : Sort*} (h : empty) : α := by library_search example {α : Type*} (h : empty) : α := by library_search def map_from_sum {A B C : Type} (f : A → C) (g : B → C) : (A ⊕ B) → C := by library_search -- Test that we can provide custom `apply` tactics, -- e.g. to change how aggressively we unfold definitions in trying to apply lemmas. lemma bind_singleton {α β} (x : α) (f : α → list β) : list.bind [x] f = f x := begin success_if_fail { library_search { apply := λ e, tactic.apply e { md := tactic.transparency.reducible } }, }, library_search, end end test.library_search
dac548a81e839f770bfb6c80428a3251435abdf5
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Elab/Import.lean
4d5ac679e02b2bf02fecca5ae37691b7321b950e
[ "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
2,009
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Lean.Parser.Module namespace Lean namespace Elab def headerToImports (header : Syntax) : List Import := let header := header.asNode; let imports := if (header.getArg 0).isNone then [{Import . module := `Init.Default}] else []; imports ++ (header.getArg 1).getArgs.toList.map (fun stx => -- `stx` is of the form `(Module.import "import" "runtime"? id) let runtime := !(stx.getArg 1).isNone; let id := stx.getIdAt 2; { module := normalizeModuleName id, runtimeOnly := runtime }) def processHeader (header : Syntax) (messages : MessageLog) (inputCtx : Parser.InputContext) (trustLevel : UInt32 := 0) : IO (Environment × MessageLog) := catch (do env ← importModules (headerToImports header) trustLevel; pure (env, messages)) (fun e => do env ← mkEmptyEnvironment; let spos := header.getPos.getD 0; let pos := inputCtx.fileMap.toPosition spos; pure (env, messages.add { fileName := inputCtx.fileName, data := toString e, pos := pos })) def parseImports (input : String) (fileName : Option String := none) : IO (List Import × Position × MessageLog) := do env ← mkEmptyEnvironment; let fileName := fileName.getD "<input>"; let inputCtx := Parser.mkInputContext input fileName; match Parser.parseHeader env inputCtx with | (header, parserState, messages) => do pure (headerToImports header, inputCtx.fileMap.toPosition parserState.pos, messages) @[export lean_parse_imports] def parseImportsExport (input : String) (fileName : Option String) : IO (List Import × Position × List Message) := do (imports, pos, log) ← parseImports input fileName; pure (imports, pos, log.toList) @[export lean_print_deps] def printDeps (deps : List Import) : IO Unit := deps.forM $ fun dep => do fname ← findOLean dep.module; IO.println fname end Elab end Lean
e4f5f3b5a3863c261cb17abe32449b7103382781
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/combinatorics/derangements/exponential.lean
9d1a1dc3c58aeab7a300725fb7ec8e432fa7c4ef
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,887
lean
/- Copyright (c) 2021 Henry Swanson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henry Swanson, Patrick Massot -/ import analysis.normed_space.exponential import combinatorics.derangements.finite import order.filter.basic /-! # Derangement exponential series This file proves that the probability of a permutation on n elements being a derangement is 1/e. The specific lemma is `num_derangements_tendsto_inv_e`. -/ open filter open_locale big_operators open_locale topological_space theorem num_derangements_tendsto_inv_e : tendsto (λ n, (num_derangements n : ℝ) / n.factorial) at_top (𝓝 (real.exp (-1))) := begin -- we show that d(n)/n! is the partial sum of exp(-1), but offset by 1. -- this isn't entirely obvious, since we have to ensure that asc_factorial and -- factorial interact in the right way, e.g., that k ≤ n always let s : ℕ → ℝ := λ n, ∑ k in finset.range n, (-1 : ℝ)^k / k.factorial, suffices : ∀ n : ℕ, (num_derangements n : ℝ) / n.factorial = s(n+1), { simp_rw this, -- shift the function by 1, and then use the fact that the partial sums -- converge to the infinite sum rw tendsto_add_at_top_iff_nat 1, apply has_sum.tendsto_sum_nat, -- there's no specific lemma for ℝ that ∑ x^k/k! sums to exp(x), but it's -- true in more general fields, so use that lemma rw real.exp_eq_exp_ℝ_ℝ, exact exp_series_field_has_sum_exp (-1 : ℝ) }, intro n, rw [← int.cast_coe_nat, num_derangements_sum], push_cast, rw finset.sum_div, -- get down to individual terms refine finset.sum_congr (refl _) _, intros k hk, have h_le : k ≤ n := finset.mem_range_succ_iff.mp hk, rw [nat.asc_factorial_eq_div, nat.add_sub_cancel' h_le], push_cast [nat.factorial_dvd_factorial h_le], field_simp [nat.factorial_ne_zero], ring, end
0dc1934b134b4fef094d57063545a69f3dcfd78c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/bigUnivOffsets.lean
1cb12dc39230d70bbf4c8ca63ca78e9a121a6baf
[ "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
62
lean
#check Type 100000000 universe u #check Type (u + 10000000)
7f538e79c78e831485078d1166dd6df64ade7d0c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/invariant_basis_number_auto.lean
193bc6d19807111cea9fc302eb22558e842f6ff0
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,026
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.finite_dimensional import Mathlib.ring_theory.ideal.basic import Mathlib.PostPort universes u l v w namespace Mathlib /-! # Invariant basis number property We say that a ring `R` satisfies the invariant basis number property if there is a well-defined notion of the rank of a finitely generated free (left) `R`-module. Since a finitely generated free module with a basis consisting of `n` elements is linearly equivalent to `fin n → R`, it is sufficient that `(fin n → R) ≃ₗ[R] (fin m → R)` implies `n = m`. ## Main definitions `invariant_basis_number R` is a type class stating that `R` has the invariant basis number property. ## Main results We show that every nontrivial commutative ring has the invariant basis number property. ## Future work So far, there is no API at all for the `invariant_basis_number` class. There are several natural ways to formulate that a module `M` is finitely generated and free, for example `M ≃ₗ[R] (fin n → R)`, `M ≃ₗ[R] (ι → R)`, where `ι` is a fintype, or prividing a basis indexed by a finite type. There should be lemmas applying the invariant basis number property to each situation. The finite version of the invariant basis number property implies the infinite analogue, i.e., that `(ι →₀ R) ≃ₗ[R] (ι' →₀ R)` implies that `cardinal.mk ι = cardinal.mk ι'`. This fact (and its variants) should be formalized. ## References * https://en.wikipedia.org/wiki/Invariant_basis_number ## Tags free module, rank, invariant basis number, IBN -/ /-- We say that `R` has the invariant basis number property if `(fin n → R) ≃ₗ[R] (fin m → R)` implies `n = m`. This gives rise to a well-defined notion of rank of a finitely generated free module. -/ class invariant_basis_number (R : Type u) [ring R] where eq_of_fin_equiv : ∀ {n m : ℕ}, linear_equiv R (fin n → R) (fin m → R) → n = m theorem eq_of_fin_equiv (R : Type u) [ring R] [invariant_basis_number R] {n : ℕ} {m : ℕ} : linear_equiv R (fin n → R) (fin m → R) → n = m := invariant_basis_number.eq_of_fin_equiv theorem nontrivial_of_invariant_basis_number (R : Type u) [ring R] [invariant_basis_number R] : nontrivial R := sorry /-- A field has invariant basis number. This will be superseded below by the fact that any nonzero commutative ring has invariant basis number. -/ theorem invariant_basis_number_field {K : Type u} [field K] : invariant_basis_number K := sorry /-! We want to show that nontrivial commutative rings have invariant basis number. The idea is to take a maximal ideal `I` of `R` and use an isomorphism `R^n ≃ R^m` of `R` modules to produce an isomorphism `(R/I)^n ≃ (R/I)^m` of `R/I`-modules, which will imply `n = m` since `R/I` is a field and we know that fields have invariant basis number. We construct the isomorphism in two steps: 1. We construct the ring `R^n/I^n`, show that it is an `R/I`-module and show that there is an isomorphism of `R/I`-modules `R^n/I^n ≃ (R/I)^n`. This isomorphism is called `ideal.pi_quot_equiv` and is located in the file `ring_theory/ideals.lean`. 2. We construct an isomorphism of `R/I`-modules `R^n/I^n ≃ R^m/I^m` using the isomorphism `R^n ≃ R^m`. -/ /-- An `R`-linear map `R^n → R^m` induces a function `R^n/I^n → R^m/I^m`. -/ /-- An isomorphism of `R`-modules `R^n ≃ R^m` induces an isomorphism `R/I`-modules `R^n/I^n ≃ R^m/I^m`. -/ /-- Nontrivial commutative rings have the invariant basis number property. -/ protected instance invariant_basis_number_of_nontrivial_of_comm_ring {R : Type u} [comm_ring R] [nontrivial R] : invariant_basis_number R := invariant_basis_number.mk fun (n m : ℕ) (e : linear_equiv R (fin n → R) (fin m → R)) => sorry end Mathlib
87dec63672f4bc1fbc778995f732c13e39fa000a
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Data/Lsp/Capabilities.lean
3ad3e7386edad9e13a94aedb66eeeaf8019e5ec4
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
936
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.JsonRpc import Lean.Data.Lsp.TextSync /-! Minimal LSP servers/clients do not have to implement a lot of functionality. Most useful additional behaviour is instead opted into via capabilities. -/ namespace Lean namespace Lsp open Json -- TODO: right now we ignore the client's capabilities inductive ClientCapabilities := | mk instance : FromJson ClientCapabilities := ⟨fun j => ClientCapabilities.mk⟩ -- TODO largely unimplemented structure ServerCapabilities := (textDocumentSync? : Option TextDocumentSyncOptions := none) (hoverProvider : Bool := false) instance : ToJson ServerCapabilities := ⟨fun o => mkObj $ opt "textDocumentSync" o.textDocumentSync? ++ [⟨"hoverProvider", o.hoverProvider⟩]⟩ end Lsp end Lean
77b3c95c3a2a9f414cec57fc32707cfe4b871c39
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/alternating.lean
c828f011cb6947fb2237b9d2fc2ce36f3b77ea60
[ "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
31,924
lean
/- Copyright (c) 2020 Zhangir Azerbayev. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Zhangir Azerbayev -/ import linear_algebra.multilinear.basis import linear_algebra.multilinear.tensor_product import linear_algebra.linear_independent import group_theory.perm.sign import group_theory.perm.subgroup import data.equiv.fin import group_theory.quotient_group /-! # Alternating Maps We construct the bundled function `alternating_map`, which extends `multilinear_map` with all the arguments of the same type. ## Main definitions * `alternating_map R M N ι` is the space of `R`-linear alternating maps from `ι → M` to `N`. * `f.map_eq_zero_of_eq` expresses that `f` is zero when two inputs are equal. * `f.map_swap` expresses that `f` is negated when two inputs are swapped. * `f.map_perm` expresses how `f` varies by a sign change under a permutation of its inputs. * An `add_comm_monoid`, `add_comm_group`, and `module` structure over `alternating_map`s that matches the definitions over `multilinear_map`s. * `multilinear_map.alternatization`, which makes an alternating map out of a non-alternating one. * `alternating_map.dom_coprod`, which behaves as a product between two alternating maps. ## Implementation notes `alternating_map` is defined in terms of `map_eq_zero_of_eq`, as this is easier to work with than using `map_swap` as a definition, and does not require `has_neg N`. `alternating_map`s are provided with a coercion to `multilinear_map`, along with a set of `norm_cast` lemmas that act on the algebraic structure: * `alternating_map.coe_add` * `alternating_map.coe_zero` * `alternating_map.coe_sub` * `alternating_map.coe_neg` * `alternating_map.coe_smul` -/ -- semiring / add_comm_monoid variables {R : Type*} [semiring R] variables {M : Type*} [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] -- semiring / add_comm_group variables {M' : Type*} [add_comm_group M'] [module R M'] variables {N' : Type*} [add_comm_group N'] [module R N'] variables {ι : Type*} [decidable_eq ι] set_option old_structure_cmd true section variables (R M N ι) /-- An alternating map is a multilinear map that vanishes when two of its arguments are equal. -/ structure alternating_map extends multilinear_map R (λ i : ι, M) N := (map_eq_zero_of_eq' : ∀ (v : ι → M) (i j : ι) (h : v i = v j) (hij : i ≠ j), to_fun v = 0) end /-- The multilinear map associated to an alternating map -/ add_decl_doc alternating_map.to_multilinear_map namespace alternating_map variables (f f' : alternating_map R M N ι) variables (g g₂ : alternating_map R M N' ι) variables (g' : alternating_map R M' N' ι) variables (v : ι → M) (v' : ι → M') open function /-! Basic coercion simp lemmas, largely copied from `ring_hom` and `multilinear_map` -/ section coercions instance : has_coe_to_fun (alternating_map R M N ι) (λ _, (ι → M) → N) := ⟨λ x, x.to_fun⟩ initialize_simps_projections alternating_map (to_fun → apply) @[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl @[simp] lemma coe_mk (f : (ι → M) → N) (h₁ h₂ h₃) : ⇑(⟨f, h₁, h₂, h₃⟩ : alternating_map R M N ι) = f := rfl theorem congr_fun {f g : alternating_map R M N ι} (h : f = g) (x : ι → M) : f x = g x := congr_arg (λ h : alternating_map R M N ι, h x) h theorem congr_arg (f : alternating_map R M N ι) {x y : ι → M} (h : x = y) : f x = f y := congr_arg (λ x : ι → M, f x) h theorem coe_injective : injective (coe_fn : alternating_map R M N ι → ((ι → M) → N)) := λ f g h, by { cases f, cases g, cases h, refl } @[simp, norm_cast] theorem coe_inj {f g : alternating_map R M N ι} : (f : (ι → M) → N) = g ↔ f = g := coe_injective.eq_iff @[ext] theorem ext {f f' : alternating_map R M N ι} (H : ∀ x, f x = f' x) : f = f' := coe_injective (funext H) theorem ext_iff {f g : alternating_map R M N ι} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : has_coe (alternating_map R M N ι) (multilinear_map R (λ i : ι, M) N) := ⟨λ x, x.to_multilinear_map⟩ @[simp, norm_cast] lemma coe_multilinear_map : ⇑(f : multilinear_map R (λ i : ι, M) N) = f := rfl lemma coe_multilinear_map_injective : function.injective (coe : alternating_map R M N ι → multilinear_map R (λ i : ι, M) N) := λ x y h, ext $ multilinear_map.congr_fun h @[simp] lemma to_multilinear_map_eq_coe : f.to_multilinear_map = f := rfl @[simp] lemma coe_multilinear_map_mk (f : (ι → M) → N) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = ⟨f, h₁, h₂⟩ := rfl end coercions /-! ### Simp-normal forms of the structure fields These are expressed in terms of `⇑f` instead of `f.to_fun`. -/ @[simp] lemma map_add (i : ι) (x y : M) : f (update v i (x + y)) = f (update v i x) + f (update v i y) := f.to_multilinear_map.map_add' v i x y @[simp] lemma map_sub (i : ι) (x y : M') : g' (update v' i (x - y)) = g' (update v' i x) - g' (update v' i y) := g'.to_multilinear_map.map_sub v' i x y @[simp] lemma map_neg (i : ι) (x : M') : g' (update v' i (-x)) = -g' (update v' i x) := g'.to_multilinear_map.map_neg v' i x @[simp] lemma map_smul (i : ι) (r : R) (x : M) : f (update v i (r • x)) = r • f (update v i x) := f.to_multilinear_map.map_smul' v i r x @[simp] lemma map_eq_zero_of_eq (v : ι → M) {i j : ι} (h : v i = v j) (hij : i ≠ j) : f v = 0 := f.map_eq_zero_of_eq' v i j h hij lemma map_coord_zero {m : ι → M} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_update_zero (m : ι → M) (i : ι) : f (update m i 0) = 0 := f.to_multilinear_map.map_update_zero m i @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero lemma map_eq_zero_of_not_injective (v : ι → M) (hv : ¬function.injective v) : f v = 0 := begin rw function.injective at hv, push_neg at hv, rcases hv with ⟨i₁, i₂, heq, hne⟩, exact f.map_eq_zero_of_eq v heq hne end /-! ### Algebraic structure inherited from `multilinear_map` `alternating_map` carries the same `add_comm_monoid`, `add_comm_group`, and `module` structure as `multilinear_map` -/ instance : has_add (alternating_map R M N ι) := ⟨λ a b, { map_eq_zero_of_eq' := λ v i j h hij, by simp [a.map_eq_zero_of_eq v h hij, b.map_eq_zero_of_eq v h hij], ..(a + b : multilinear_map R (λ i : ι, M) N)}⟩ @[simp] lemma add_apply : (f + f') v = f v + f' v := rfl @[norm_cast] lemma coe_add : (↑(f + f') : multilinear_map R (λ i : ι, M) N) = f + f' := rfl instance : has_zero (alternating_map R M N ι) := ⟨{map_eq_zero_of_eq' := λ v i j h hij, by simp, ..(0 : multilinear_map R (λ i : ι, M) N)}⟩ @[simp] lemma zero_apply : (0 : alternating_map R M N ι) v = 0 := rfl @[norm_cast] lemma coe_zero : ((0 : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = 0 := rfl instance : inhabited (alternating_map R M N ι) := ⟨0⟩ instance : add_comm_monoid (alternating_map R M N ι) := { zero := 0, add := (+), zero_add := by intros; ext; simp [add_comm, add_left_comm], add_zero := by intros; ext; simp [add_comm, add_left_comm], add_comm := by intros; ext; simp [add_comm, add_left_comm], add_assoc := by intros; ext; simp [add_comm, add_left_comm], nsmul := λ n f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], .. ((n • f : multilinear_map R (λ i : ι, M) N)) }, nsmul_zero' := by { intros, ext, simp [add_smul], }, nsmul_succ' := by { intros, ext, simp [add_smul, nat.succ_eq_one_add], } } instance : has_neg (alternating_map R M N' ι) := ⟨λ f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..(-(f : multilinear_map R (λ i : ι, M) N')) }⟩ @[simp] lemma neg_apply (m : ι → M) : (-g) m = -(g m) := rfl @[norm_cast] lemma coe_neg : ((-g : alternating_map R M N' ι) : multilinear_map R (λ i : ι, M) N') = -g := rfl instance : has_sub (alternating_map R M N' ι) := ⟨λ f g, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij, g.map_eq_zero_of_eq v h hij], ..(f - g : multilinear_map R (λ i : ι, M) N') }⟩ @[simp] lemma sub_apply (m : ι → M) : (g - g₂) m = g m - g₂ m := rfl @[norm_cast] lemma coe_sub : (↑(g - g₂) : multilinear_map R (λ i : ι, M) N') = g - g₂ := rfl instance : add_comm_group (alternating_map R M N' ι) := by refine { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, nsmul := λ n f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], .. ((n • f : multilinear_map R (λ i : ι, M) N')) }, zsmul := λ n f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], .. ((n • f : multilinear_map R (λ i : ι, M) N')) }, zsmul_zero' := _, zsmul_succ' := _, zsmul_neg' := _, .. alternating_map.add_comm_monoid, .. }; intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one, coe_nat_zsmul] section distrib_mul_action variables {S : Type*} [monoid S] [distrib_mul_action S N] [smul_comm_class R S N] instance : has_scalar S (alternating_map R M N ι) := ⟨λ c f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..((c • f : multilinear_map R (λ i : ι, M) N)) }⟩ @[simp] lemma smul_apply (c : S) (m : ι → M) : (c • f) m = c • f m := rfl @[norm_cast] lemma coe_smul (c : S): ((c • f : alternating_map R M N ι) : multilinear_map R (λ i : ι, M) N) = c • f := rfl lemma coe_fn_smul (c : S) (f : alternating_map R M N ι) : ⇑(c • f) = c • f := rfl instance : distrib_mul_action S (alternating_map R M N ι) := { one_smul := λ f, ext $ λ x, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _, smul_zero := λ r, ext $ λ x, smul_zero _, smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ } end distrib_mul_action section module variables {S : Type*} [semiring S] [module S N] [smul_comm_class R S N] /-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance : module S (alternating_map R M N ι) := { add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } instance [no_zero_smul_divisors S N] : no_zero_smul_divisors S (alternating_map R M N ι) := coe_injective.no_zero_smul_divisors _ rfl coe_fn_smul end module section variables (R N) /-- The evaluation map from `ι → N` to `N` at a given `i` is alternating when `ι` is subsingleton. -/ @[simps] def of_subsingleton [subsingleton ι] (i : ι) : alternating_map R N N ι := { to_fun := function.eval i, map_eq_zero_of_eq' := λ v i j hv hij, (hij $ subsingleton.elim _ _).elim, ..multilinear_map.of_subsingleton R N i } end end alternating_map /-! ### Composition with linear maps -/ namespace linear_map variables {N₂ : Type*} [add_comm_monoid N₂] [module R N₂] /-- Composing a alternating map with a linear map gives again a alternating map. -/ def comp_alternating_map (g : N →ₗ[R] N₂) : alternating_map R M N ι →+ alternating_map R M N₂ ι := { to_fun := λ f, { map_eq_zero_of_eq' := λ v i j h hij, by simp [f.map_eq_zero_of_eq v h hij], ..(g.comp_multilinear_map (f : multilinear_map R (λ _ : ι, M) N)) }, map_zero' := by { ext, simp }, map_add' := λ a b, by { ext, simp } } @[simp] lemma coe_comp_alternating_map (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) : ⇑(g.comp_alternating_map f) = g ∘ f := rfl lemma comp_alternating_map_apply (g : N →ₗ[R] N₂) (f : alternating_map R M N ι) (m : ι → M) : g.comp_alternating_map f m = g (f m) := rfl end linear_map namespace alternating_map variables (f f' : alternating_map R M N ι) variables (g g₂ : alternating_map R M N' ι) variables (g' : alternating_map R M' N' ι) variables (v : ι → M) (v' : ι → M') open function /-! ### Other lemmas from `multilinear_map` -/ section open_locale big_operators lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M) (m : ι → M): f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) := f.to_multilinear_map.map_update_sum t i g m end /-! ### Theorems specific to alternating maps Various properties of reordered and repeated inputs which follow from `alternating_map.map_eq_zero_of_eq`. -/ lemma map_update_self {i j : ι} (hij : i ≠ j) : f (function.update v i (v j)) = 0 := f.map_eq_zero_of_eq _ (by rw [function.update_same, function.update_noteq hij.symm]) hij lemma map_update_update {i j : ι} (hij : i ≠ j) (m : M) : f (function.update (function.update v i m) j m) = 0 := f.map_eq_zero_of_eq _ (by rw [function.update_same, function.update_noteq hij, function.update_same]) hij lemma map_swap_add {i j : ι} (hij : i ≠ j) : f (v ∘ equiv.swap i j) + f v = 0 := begin rw equiv.comp_swap_eq_update, convert f.map_update_update v hij (v i + v j), simp [f.map_update_self _ hij, f.map_update_self _ hij.symm, function.update_comm hij (v i + v j) (v _) v, function.update_comm hij.symm (v i) (v i) v], end lemma map_add_swap {i j : ι} (hij : i ≠ j) : f v + f (v ∘ equiv.swap i j) = 0 := by { rw add_comm, exact f.map_swap_add v hij } lemma map_swap {i j : ι} (hij : i ≠ j) : g (v ∘ equiv.swap i j) = - g v := eq_neg_of_add_eq_zero (g.map_swap_add v hij) lemma map_perm [fintype ι] (v : ι → M) (σ : equiv.perm ι) : g (v ∘ σ) = σ.sign • g v := begin apply equiv.perm.swap_induction_on' σ, { simp }, { intros s x y hxy hI, simpa [g.map_swap (v ∘ s) hxy, equiv.perm.sign_swap hxy] using hI, } end lemma map_congr_perm [fintype ι] (σ : equiv.perm ι) : g v = σ.sign • g (v ∘ σ) := by { rw [g.map_perm, smul_smul], simp } lemma coe_dom_dom_congr [fintype ι] (σ : equiv.perm ι) : (g : multilinear_map R (λ _ : ι, M) N').dom_dom_congr σ = σ.sign • (g : multilinear_map R (λ _ : ι, M) N') := multilinear_map.ext $ λ v, g.map_perm v σ /-- If the arguments are linearly dependent then the result is `0`. -/ lemma map_linear_dependent {K : Type*} [ring K] {M : Type*} [add_comm_group M] [module K M] {N : Type*} [add_comm_group N] [module K N] [no_zero_smul_divisors K N] (f : alternating_map K M N ι) (v : ι → M) (h : ¬linear_independent K v) : f v = 0 := begin obtain ⟨s, g, h, i, hi, hz⟩ := linear_dependent_iff.mp h, suffices : f (update v i (g i • v i)) = 0, { rw [f.map_smul, function.update_eq_self, smul_eq_zero] at this, exact or.resolve_left this hz, }, conv at h in (g _ • v _) { rw ←if_t_t (i = x) (g _ • v _), }, rw [finset.sum_ite, finset.filter_eq, finset.filter_ne, if_pos hi, finset.sum_singleton, add_eq_zero_iff_eq_neg] at h, rw [h, f.map_neg, f.map_update_sum, neg_eq_zero, finset.sum_eq_zero], intros j hj, obtain ⟨hij, _⟩ := finset.mem_erase.mp hj, rw [f.map_smul, f.map_update_self _ hij.symm, smul_zero], end end alternating_map open_locale big_operators namespace multilinear_map open equiv variables [fintype ι] private lemma alternization_map_eq_zero_of_eq_aux (m : multilinear_map R (λ i : ι, M) N') (v : ι → M) (i j : ι) (i_ne_j : i ≠ j) (hv : v i = v j) : (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ) v = 0 := begin rw sum_apply, exact finset.sum_involution (λ σ _, swap i j * σ) (λ σ _, by simp [perm.sign_swap i_ne_j, apply_swap_eq_self hv]) (λ σ _ _, (not_congr swap_mul_eq_iff).mpr i_ne_j) (λ σ _, finset.mem_univ _) (λ σ _, swap_mul_involutive i j σ) end /-- Produce an `alternating_map` out of a `multilinear_map`, by summing over all argument permutations. -/ def alternatization : multilinear_map R (λ i : ι, M) N' →+ alternating_map R M N' ι := { to_fun := λ m, { to_fun := ⇑(∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ), map_eq_zero_of_eq' := λ v i j hvij hij, alternization_map_eq_zero_of_eq_aux m v i j hij hvij, .. (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ)}, map_add' := λ a b, begin ext, simp only [ finset.sum_add_distrib, smul_add, add_apply, dom_dom_congr_apply, alternating_map.add_apply, alternating_map.coe_mk, smul_apply, sum_apply], end, map_zero' := begin ext, simp only [ finset.sum_const_zero, smul_zero, zero_apply, dom_dom_congr_apply, alternating_map.zero_apply, alternating_map.coe_mk, smul_apply, sum_apply], end } lemma alternatization_def (m : multilinear_map R (λ i : ι, M) N') : ⇑(alternatization m) = (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ : _) := rfl lemma alternatization_coe (m : multilinear_map R (λ i : ι, M) N') : ↑m.alternatization = (∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ : _) := coe_injective rfl lemma alternatization_apply (m : multilinear_map R (λ i : ι, M) N') (v : ι → M) : alternatization m v = ∑ (σ : perm ι), σ.sign • m.dom_dom_congr σ v := by simp only [alternatization_def, smul_apply, sum_apply] end multilinear_map namespace alternating_map /-- Alternatizing a multilinear map that is already alternating results in a scale factor of `n!`, where `n` is the number of inputs. -/ lemma coe_alternatization [fintype ι] (a : alternating_map R M N' ι) : (↑a : multilinear_map R (λ ι, M) N').alternatization = nat.factorial (fintype.card ι) • a := begin apply alternating_map.coe_injective, simp_rw [multilinear_map.alternatization_def, coe_dom_dom_congr, smul_smul, int.units_mul_self, one_smul, finset.sum_const, finset.card_univ, fintype.card_perm, ←coe_multilinear_map, coe_smul], end end alternating_map namespace linear_map variables {N'₂ : Type*} [add_comm_group N'₂] [module R N'₂] [fintype ι] /-- Composition with a linear map before and after alternatization are equivalent. -/ lemma comp_multilinear_map_alternatization (g : N' →ₗ[R] N'₂) (f : multilinear_map R (λ _ : ι, M) N') : (g.comp_multilinear_map f).alternatization = g.comp_alternating_map (f.alternatization) := by { ext, simp [multilinear_map.alternatization_def] } end linear_map section coprod open_locale big_operators open_locale tensor_product variables {ιa ιb : Type*} [decidable_eq ιa] [decidable_eq ιb] [fintype ιa] [fintype ιb] variables {R' : Type*} {Mᵢ N₁ N₂ : Type*} [comm_semiring R'] [add_comm_group N₁] [module R' N₁] [add_comm_group N₂] [module R' N₂] [add_comm_monoid Mᵢ] [module R' Mᵢ] namespace equiv.perm /-- Elements which are considered equivalent if they differ only by swaps within α or β -/ abbreviation mod_sum_congr (α β : Type*) := quotient_group.quotient (equiv.perm.sum_congr_hom α β).range lemma mod_sum_congr.swap_smul_involutive {α β : Type*} [decidable_eq (α ⊕ β)] (i j : α ⊕ β) : function.involutive (has_scalar.smul (equiv.swap i j) : mod_sum_congr α β → mod_sum_congr α β) := λ σ, begin apply σ.induction_on' (λ σ, _), exact _root_.congr_arg quotient.mk' (equiv.swap_mul_involutive i j σ) end end equiv.perm namespace alternating_map open equiv /-- summand used in `alternating_map.dom_coprod` -/ def dom_coprod.summand (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) : multilinear_map R' (λ _ : ιa ⊕ ιb, Mᵢ) (N₁ ⊗[R'] N₂) := quotient.lift_on' σ (λ σ, σ.sign • (multilinear_map.dom_coprod ↑a ↑b : multilinear_map R' (λ _, Mᵢ) (N₁ ⊗ N₂)).dom_dom_congr σ) (λ σ₁ σ₂ ⟨⟨sl, sr⟩, h⟩, begin ext v, simp only [multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply, coe_multilinear_map, multilinear_map.smul_apply], replace h := inv_mul_eq_iff_eq_mul.mp h.symm, have : (σ₁ * perm.sum_congr_hom _ _ (sl, sr)).sign = σ₁.sign * (sl.sign * sr.sign) := by simp, rw [h, this, mul_smul, mul_smul, smul_left_cancel_iff, ←tensor_product.tmul_smul, tensor_product.smul_tmul'], simp only [sum.map_inr, perm.sum_congr_hom_apply, perm.sum_congr_apply, sum.map_inl, function.comp_app, perm.coe_mul], rw [←a.map_congr_perm (λ i, v (σ₁ _)), ←b.map_congr_perm (λ i, v (σ₁ _))], end) lemma dom_coprod.summand_mk' (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : equiv.perm (ιa ⊕ ιb)) : dom_coprod.summand a b (quotient.mk' σ) = σ.sign • (multilinear_map.dom_coprod ↑a ↑b : multilinear_map R' (λ _, Mᵢ) (N₁ ⊗ N₂)).dom_dom_congr σ := rfl /-- Swapping elements in `σ` with equal values in `v` results in an addition that cancels -/ lemma dom_coprod.summand_add_swap_smul_eq_zero (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) {v : ιa ⊕ ιb → Mᵢ} {i j : ιa ⊕ ιb} (hv : v i = v j) (hij : i ≠ j) : dom_coprod.summand a b σ v + dom_coprod.summand a b (swap i j • σ) v = 0 := begin apply σ.induction_on' (λ σ, _), dsimp only [quotient.lift_on'_mk', quotient.map'_mk', mul_action.quotient.smul_mk, dom_coprod.summand], rw [perm.sign_mul, perm.sign_swap hij], simp only [one_mul, units.neg_mul, function.comp_app, units.neg_smul, perm.coe_mul, units.coe_neg, multilinear_map.smul_apply, multilinear_map.neg_apply, multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply], convert add_right_neg _; { ext k, rw equiv.apply_swap_eq_self hv }, end /-- Swapping elements in `σ` with equal values in `v` result in zero if the swap has no effect on the quotient. -/ lemma dom_coprod.summand_eq_zero_of_smul_invariant (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) (σ : perm.mod_sum_congr ιa ιb) {v : ιa ⊕ ιb → Mᵢ} {i j : ιa ⊕ ιb} (hv : v i = v j) (hij : i ≠ j) : swap i j • σ = σ → dom_coprod.summand a b σ v = 0 := begin apply σ.induction_on' (λ σ, _), dsimp only [quotient.lift_on'_mk', quotient.map'_mk', multilinear_map.smul_apply, multilinear_map.dom_dom_congr_apply, multilinear_map.dom_coprod_apply, dom_coprod.summand], intro hσ, with_cases { cases hi : σ⁻¹ i; cases hj : σ⁻¹ j; rw perm.inv_eq_iff_eq at hi hj; substs hi hj, }, case [sum.inl sum.inr : i' j', sum.inr sum.inl : i' j'] { -- the term pairs with and cancels another term all_goals { obtain ⟨⟨sl, sr⟩, hσ⟩ := quotient.exact' hσ, }, work_on_goal 0 { replace hσ := equiv.congr_fun hσ (sum.inl i'), }, work_on_goal 1 { replace hσ := equiv.congr_fun hσ (sum.inr i'), }, all_goals { rw [←equiv.mul_swap_eq_swap_mul, mul_inv_rev, equiv.swap_inv, inv_mul_cancel_right] at hσ, simpa using hσ, }, }, case [sum.inr sum.inr : i' j', sum.inl sum.inl : i' j'] { -- the term does not pair but is zero all_goals { convert smul_zero _, }, work_on_goal 0 { convert tensor_product.tmul_zero _ _, }, work_on_goal 1 { convert tensor_product.zero_tmul _ _, }, all_goals { exact alternating_map.map_eq_zero_of_eq _ _ hv (λ hij', hij (hij' ▸ rfl)), } }, end /-- Like `multilinear_map.dom_coprod`, but ensures the result is also alternating. Note that this is usually defined (for instance, as used in Proposition 22.24 in [Gallier2011Notes]) over integer indices `ιa = fin n` and `ιb = fin m`, as $$ (f \wedge g)(u_1, \ldots, u_{m+n}) = \sum_{\operatorname{shuffle}(m, n)} \operatorname{sign}(\sigma) f(u_{\sigma(1)}, \ldots, u_{\sigma(m)}) g(u_{\sigma(m+1)}, \ldots, u_{\sigma(m+n)}), $$ where $\operatorname{shuffle}(m, n)$ consists of all permutations of $[1, m+n]$ such that $\sigma(1) < \cdots < \sigma(m)$ and $\sigma(m+1) < \cdots < \sigma(m+n)$. Here, we generalize this by replacing: * the product in the sum with a tensor product * the filtering of $[1, m+n]$ to shuffles with an isomorphic quotient * the additions in the subscripts of $\sigma$ with an index of type `sum` The specialized version can be obtained by combining this definition with `fin_sum_fin_equiv` and `algebra.lmul'`. -/ @[simps] def dom_coprod (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : alternating_map R' Mᵢ (N₁ ⊗[R'] N₂) (ιa ⊕ ιb) := { to_fun := λ v, ⇑(∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ) v, map_eq_zero_of_eq' := λ v i j hv hij, begin dsimp only, rw multilinear_map.sum_apply, exact finset.sum_involution (λ σ _, equiv.swap i j • σ) (λ σ _, dom_coprod.summand_add_swap_smul_eq_zero a b σ hv hij) (λ σ _, mt $ dom_coprod.summand_eq_zero_of_smul_invariant a b σ hv hij) (λ σ _, finset.mem_univ _) (λ σ _, equiv.perm.mod_sum_congr.swap_smul_involutive i j σ), end, ..(∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ) } lemma dom_coprod_coe (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : (↑(a.dom_coprod b) : multilinear_map R' (λ _, Mᵢ) _) = ∑ σ : perm.mod_sum_congr ιa ιb, dom_coprod.summand a b σ := multilinear_map.ext $ λ _, rfl /-- A more bundled version of `alternating_map.dom_coprod` that maps `((ι₁ → N) → N₁) ⊗ ((ι₂ → N) → N₂)` to `(ι₁ ⊕ ι₂ → N) → N₁ ⊗ N₂`. -/ def dom_coprod' : (alternating_map R' Mᵢ N₁ ιa ⊗[R'] alternating_map R' Mᵢ N₂ ιb) →ₗ[R'] alternating_map R' Mᵢ (N₁ ⊗[R'] N₂) (ιa ⊕ ιb) := tensor_product.lift $ by refine linear_map.mk₂ R' (dom_coprod) (λ m₁ m₂ n, _) (λ c m n, _) (λ m n₁ n₂, _) (λ c m n, _); { ext, simp only [dom_coprod_apply, add_apply, smul_apply, ←finset.sum_add_distrib, finset.smul_sum, multilinear_map.sum_apply, dom_coprod.summand], congr, ext σ, apply σ.induction_on' (λ σ, _), simp only [quotient.lift_on'_mk', coe_add, coe_smul, multilinear_map.smul_apply, ←multilinear_map.dom_coprod'_apply], simp only [tensor_product.add_tmul, ←tensor_product.smul_tmul', tensor_product.tmul_add, tensor_product.tmul_smul, linear_map.map_add, linear_map.map_smul], rw ←smul_add <|> rw smul_comm, congr } @[simp] lemma dom_coprod'_apply (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : dom_coprod' (a ⊗ₜ[R'] b) = dom_coprod a b := by simp only [dom_coprod', tensor_product.lift.tmul, linear_map.mk₂_apply] end alternating_map open equiv /-- A helper lemma for `multilinear_map.dom_coprod_alternization`. -/ lemma multilinear_map.dom_coprod_alternization_coe (a : multilinear_map R' (λ _ : ιa, Mᵢ) N₁) (b : multilinear_map R' (λ _ : ιb, Mᵢ) N₂) : multilinear_map.dom_coprod ↑a.alternatization ↑b.alternatization = ∑ (σa : perm ιa) (σb : perm ιb), σa.sign • σb.sign • multilinear_map.dom_coprod (a.dom_dom_congr σa) (b.dom_dom_congr σb) := begin simp_rw [←multilinear_map.dom_coprod'_apply, multilinear_map.alternatization_coe], simp_rw [tensor_product.sum_tmul, tensor_product.tmul_sum, linear_map.map_sum, ←tensor_product.smul_tmul', tensor_product.tmul_smul, linear_map.map_smul_of_tower], end open alternating_map /-- Computing the `multilinear_map.alternatization` of the `multilinear_map.dom_coprod` is the same as computing the `alternating_map.dom_coprod` of the `multilinear_map.alternatization`s. -/ lemma multilinear_map.dom_coprod_alternization (a : multilinear_map R' (λ _ : ιa, Mᵢ) N₁) (b : multilinear_map R' (λ _ : ιb, Mᵢ) N₂) : (multilinear_map.dom_coprod a b).alternatization = a.alternatization.dom_coprod b.alternatization := begin apply coe_multilinear_map_injective, rw [dom_coprod_coe, multilinear_map.alternatization_coe, finset.sum_partition (quotient_group.left_rel (perm.sum_congr_hom ιa ιb).range)], congr' 1, ext1 σ, apply σ.induction_on' (λ σ, _), -- unfold the quotient mess left by `finset.sum_partition` conv in (_ = quotient.mk' _) { change quotient.mk' _ = quotient.mk' _, rw quotient.eq', rw [quotient_group.left_rel], dsimp only [setoid.r] }, -- eliminate a multiplication have : @finset.univ (perm (ιa ⊕ ιb)) _ = finset.univ.image ((*) σ) := (finset.eq_univ_iff_forall.mpr $ λ a, let ⟨a', ha'⟩ := mul_left_surjective σ a in finset.mem_image.mpr ⟨a', finset.mem_univ _, ha'⟩).symm, rw [this, finset.image_filter], simp only [function.comp, mul_inv_rev, inv_mul_cancel_right, subgroup.inv_mem_iff], simp only [monoid_hom.mem_range], -- needs to be separate from the above `simp only` rw [finset.filter_congr_decidable, finset.univ_filter_exists (perm.sum_congr_hom ιa ιb), finset.sum_image (λ x _ y _ (h : _ = _), mul_right_injective _ h), finset.sum_image (λ x _ y _ (h : _ = _), perm.sum_congr_hom_injective h)], dsimp only, -- now we're ready to clean up the RHS, pulling out the summation rw [dom_coprod.summand_mk', multilinear_map.dom_coprod_alternization_coe, ←finset.sum_product', finset.univ_product_univ, ←multilinear_map.dom_dom_congr_equiv_apply, add_equiv.map_sum, finset.smul_sum], congr' 1, ext1 ⟨al, ar⟩, dsimp only, -- pull out the pair of smuls on the RHS, by rewriting to `_ →ₗ[ℤ] _` and back rw [←add_equiv.coe_to_add_monoid_hom, ←add_monoid_hom.coe_to_int_linear_map, linear_map.map_smul_of_tower, linear_map.map_smul_of_tower, add_monoid_hom.coe_to_int_linear_map, add_equiv.coe_to_add_monoid_hom, multilinear_map.dom_dom_congr_equiv_apply], -- pick up the pieces rw [multilinear_map.dom_dom_congr_mul, perm.sign_mul, perm.sum_congr_hom_apply, multilinear_map.dom_coprod_dom_dom_congr_sum_congr, perm.sign_sum_congr, mul_smul, mul_smul], end /-- Taking the `multilinear_map.alternatization` of the `multilinear_map.dom_coprod` of two `alternating_map`s gives a scaled version of the `alternating_map.coprod` of those maps. -/ lemma multilinear_map.dom_coprod_alternization_eq (a : alternating_map R' Mᵢ N₁ ιa) (b : alternating_map R' Mᵢ N₂ ιb) : (multilinear_map.dom_coprod a b : multilinear_map R' (λ _ : ιa ⊕ ιb, Mᵢ) (N₁ ⊗ N₂)) .alternatization = ((fintype.card ιa).factorial * (fintype.card ιb).factorial) • a.dom_coprod b := begin rw [multilinear_map.dom_coprod_alternization, coe_alternatization, coe_alternatization, mul_smul, ←dom_coprod'_apply, ←dom_coprod'_apply, ←tensor_product.smul_tmul', tensor_product.tmul_smul, linear_map.map_smul_of_tower dom_coprod', linear_map.map_smul_of_tower dom_coprod'], -- typeclass resolution is a little confused here apply_instance, apply_instance, end end coprod section basis open alternating_map variables {ι₁ : Type*} [fintype ι] variables {R' : Type*} {N₁ N₂ : Type*} [comm_semiring R'] [add_comm_monoid N₁] [add_comm_monoid N₂] variables [module R' N₁] [module R' N₂] /-- Two alternating maps indexed by a `fintype` are equal if they are equal when all arguments are distinct basis vectors. -/ lemma basis.ext_alternating {f g : alternating_map R' N₁ N₂ ι} (e : basis ι₁ R' N₁) (h : ∀ v : ι → ι₁, function.injective v → f (λ i, e (v i)) = g (λ i, e (v i))) : f = g := begin refine alternating_map.coe_multilinear_map_injective (basis.ext_multilinear e $ λ v, _), by_cases hi : function.injective v, { exact h v hi }, { have : ¬function.injective (λ i, e (v i)) := hi.imp function.injective.of_comp, rw [coe_multilinear_map, coe_multilinear_map, f.map_eq_zero_of_not_injective _ this, g.map_eq_zero_of_not_injective _ this], } end end basis
0ea519315562e0034d3d912983bb389f65ac2f78
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/unreachable_cases.lean
09606047a39ed95991df2e55dc1014f5efd21b1b
[ "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
600
lean
open nat prod inductive ifin : ℕ → Type -- inductively defined fin-type | fz : Π n, ifin (succ n) | fs : Π {n}, ifin n → ifin (succ n) open ifin noncomputable definition foo {N : Type} : Π{n : ℕ}, N → ifin n → (N × ifin n) | (succ k) n (fz .k) := sorry | (succ k) n (fs x) := sorry noncomputable definition bar {N : Type} : Π{n : ℕ}, (N × ifin n) → (N × ifin n) | (succ k) (n, fz .k) := sorry | (succ k) (n, fs x) := sorry noncomputable definition bar2 {N : Type} : Π{n : ℕ}, (N × ifin n) → (N × ifin n) | (succ k) (n, fz .k) := sorry | (succ k) (n, fs x) := sorry
961c79ae5a5ef198f07d9c1be7bc600c334459a1
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/mv_polynomial/monad.lean
aa55345fa1bc2ac5b8295a16568c409984f141ee
[ "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
13,430
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.mv_polynomial.rename /-! # Monad operations on `mv_polynomial` This file defines two monadic operations on `mv_polynomial`. Given `p : mv_polynomial σ R`, * `mv_polynomial.bind₁` and `mv_polynomial.join₁` operate on the variable type `σ`. * `mv_polynomial.bind₂` and `mv_polynomial.join₂` operate on the coefficient type `R`. - `mv_polynomial.bind₁ f φ` with `f : σ → mv_polynomial τ R` and `φ : mv_polynomial σ R`, is the polynomial `φ(f 1, ..., f i, ...) : mv_polynomial τ R`. - `mv_polynomial.join₁ φ` with `φ : mv_polynomial (mv_polynomial σ R) R` collapses `φ` to a `mv_polynomial σ R`, by evaluating `φ` under the map `X f ↦ f` for `f : mv_polynomial σ R`. In other words, if you have a polynomial `φ` in a set of variables indexed by a polynomial ring, you evaluate the polynomial in these indexing polynomials. - `mv_polynomial.bind₂ f φ` with `f : R →+* mv_polynomial σ S` and `φ : mv_polynomial σ R` is the `mv_polynomial σ S` obtained from `φ` by mapping the coefficients of `φ` through `f` and considering the resulting polynomial as polynomial expression in `mv_polynomial σ R`. - `mv_polynomial.join₂ φ` with `φ : mv_polynomial σ (mv_polynomial σ R)` collapses `φ` to a `mv_polynomial σ R`, by considering `φ` as polynomial expression in `mv_polynomial σ R`. These operations themselves have algebraic structure: `mv_polynomial.bind₁` and `mv_polynomial.join₁` are algebra homs and `mv_polynomial.bind₂` and `mv_polynomial.join₂` are ring homs. They interact in convenient ways with `mv_polynomial.rename`, `mv_polynomial.map`, `mv_polynomial.vars`, and other polynomial operations. Indeed, `mv_polynomial.rename` is the "map" operation for the (`bind₁`, `join₁`) pair, whereas `mv_polynomial.map` is the "map" operation for the other pair. ## Implementation notes We add an `is_lawful_monad` instance for the (`bind₁`, `join₁`) pair. The second pair cannot be instantiated as a `monad`, since it is not a monad in `Type` but in `CommRing` (or rather `CommSemiRing`). -/ open_locale big_operators noncomputable theory namespace mv_polynomial open finsupp variables {σ : Type*} {τ : Type*} variables {R S T : Type*} [comm_semiring R] [comm_semiring S] [comm_semiring T] /-- `bind₁` is the "left hand side" bind operation on `mv_polynomial`, operating on the variable type. Given a polynomial `p : mv_polynomial σ R` and a map `f : σ → mv_polynomial τ R` taking variables in `p` to polynomials in the variable type `τ`, `bind₁ f p` replaces each variable in `p` with its value under `f`, producing a new polynomial in `τ`. The coefficient type remains the same. This operation is an algebra hom. -/ def bind₁ (f : σ → mv_polynomial τ R) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R := aeval f /-- `bind₂` is the "right hand side" bind operation on `mv_polynomial`, operating on the coefficient type. Given a polynomial `p : mv_polynomial σ R` and a map `f : R → mv_polynomial σ S` taking coefficients in `p` to polynomials over a new ring `S`, `bind₂ f p` replaces each coefficient in `p` with its value under `f`, producing a new polynomial over `S`. The variable type remains the same. This operation is a ring hom. -/ def bind₂ (f : R →+* mv_polynomial σ S) : mv_polynomial σ R →+* mv_polynomial σ S := eval₂_hom f X /-- `join₁` is the monadic join operation corresponding to `mv_polynomial.bind₁`. Given a polynomial `p` with coefficients in `R` whose variables are polynomials in `σ` with coefficients in `R`, `join₁ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is an algebra hom. -/ def join₁ : mv_polynomial (mv_polynomial σ R) R →ₐ[R] mv_polynomial σ R := aeval id /-- `join₂` is the monadic join operation corresponding to `mv_polynomial.bind₂`. Given a polynomial `p` with variables in `σ` whose coefficients are polynomials in `σ` with coefficients in `R`, `join₂ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is a ring hom. -/ def join₂ : mv_polynomial σ (mv_polynomial σ R) →+* mv_polynomial σ R := eval₂_hom (ring_hom.id _) X @[simp] lemma aeval_eq_bind₁ (f : σ → mv_polynomial τ R) : aeval f = bind₁ f := rfl @[simp] lemma eval₂_hom_C_eq_bind₁ (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl @[simp] lemma eval₂_hom_eq_bind₂ (f : R →+* mv_polynomial σ S) : eval₂_hom f X = bind₂ f := rfl section variables (σ R) @[simp] lemma aeval_id_eq_join₁ : aeval id = @join₁ σ R _ := rfl lemma eval₂_hom_C_id_eq_join₁ (φ : mv_polynomial (mv_polynomial σ R) R) : eval₂_hom C id φ = join₁ φ := rfl @[simp] lemma eval₂_hom_id_X_eq_join₂ : eval₂_hom (ring_hom.id _) X = @join₂ σ R _ := rfl end -- In this file, we don't want to use these simp lemmas, -- because we first need to show how these new definitions interact -- and the proofs fall back on unfolding the definitions and call simp afterwards local attribute [-simp] aeval_eq_bind₁ eval₂_hom_C_eq_bind₁ eval₂_hom_eq_bind₂ aeval_id_eq_join₁ eval₂_hom_id_X_eq_join₂ @[simp] lemma bind₁_X_right (f : σ → mv_polynomial τ R) (i : σ) : bind₁ f (X i) = f i := aeval_X f i @[simp] lemma bind₂_X_right (f : R →+* mv_polynomial σ S) (i : σ) : bind₂ f (X i) = X i := eval₂_hom_X' f X i @[simp] lemma bind₁_X_left : bind₁ (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by { ext1 i, simp } lemma aeval_X_left : aeval (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by rw [aeval_eq_bind₁, bind₁_X_left] lemma aeval_X_left_apply (φ : mv_polynomial σ R) : aeval X φ = φ := by rw [aeval_eq_bind₁, bind₁_X_left, alg_hom.id_apply] variable (f : σ → mv_polynomial τ R) @[simp] lemma bind₁_C_right (f : σ → mv_polynomial τ R) (x) : bind₁ f (C x) = C x := by simp [bind₁, C, aeval_monomial, finsupp.prod_zero_index]; refl @[simp] lemma bind₂_C_right (f : R →+* mv_polynomial σ S) (r : R) : bind₂ f (C r) = f r := eval₂_hom_C f X r @[simp] lemma bind₂_C_left : bind₂ (C : R →+* mv_polynomial σ R) = ring_hom.id _ := by { ext1; simp } @[simp] lemma bind₂_comp_C (f : R →+* mv_polynomial σ S) : (bind₂ f).comp C = f := ring_hom.ext $ bind₂_C_right _ @[simp] lemma join₂_map (f : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : join₂ (map f φ) = bind₂ f φ := by simp only [join₂, bind₂, eval₂_hom_map_hom, ring_hom.id_comp] @[simp] lemma join₂_comp_map (f : R →+* mv_polynomial σ S) : join₂.comp (map f) = bind₂ f := ring_hom.ext $ join₂_map _ lemma aeval_id_rename (f : σ → mv_polynomial τ R) (p : mv_polynomial σ R) : aeval id (rename f p) = aeval f p := by rw [aeval_rename, function.comp.left_id] @[simp] lemma join₁_rename (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : join₁ (rename f φ) = bind₁ f φ := aeval_id_rename _ _ @[simp] lemma bind₁_id : bind₁ (@id (mv_polynomial σ R)) = join₁ := rfl @[simp] lemma bind₂_id : bind₂ (ring_hom.id (mv_polynomial σ R)) = join₂ := rfl lemma bind₁_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) (φ : mv_polynomial σ R) : (bind₁ g) (bind₁ f φ) = bind₁ (λ i, bind₁ g (f i)) φ := by simp [bind₁, ← comp_aeval] lemma bind₁_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) : (bind₁ g).comp (bind₁ f) = bind₁ (λ i, bind₁ g (f i)) := by { ext1, apply bind₁_bind₁ } lemma bind₂_comp_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) : (bind₂ g).comp (bind₂ f) = bind₂ ((bind₂ g).comp f) := by { ext1; simp } lemma bind₂_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) (φ : mv_polynomial σ R) : (bind₂ g) (bind₂ f φ) = bind₂ ((bind₂ g).comp f) φ := ring_hom.congr_fun (bind₂_comp_bind₂ f g) φ lemma rename_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) : (rename g).comp (bind₁ f) = bind₁ (λ i, rename g $ f i) := by { ext1 i, simp } lemma rename_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) (φ : mv_polynomial σ R) : rename g (bind₁ f φ) = bind₁ (λ i, rename g $ f i) φ := alg_hom.congr_fun (rename_comp_bind₁ f g) φ lemma map_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* T) (φ : mv_polynomial σ R) : map g (bind₂ f φ) = bind₂ ((map g).comp f) φ := begin simp only [bind₂, eval₂_comp_right, coe_eval₂_hom, eval₂_map], congr' 1 with : 1, simp only [function.comp_app, map_X] end lemma bind₁_comp_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) : (bind₁ f).comp (rename g) = bind₁ (f ∘ g) := by { ext1 i, simp } lemma bind₁_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) (φ : mv_polynomial σ R) : bind₁ f (rename g φ) = bind₁ (f ∘ g) φ := alg_hom.congr_fun (bind₁_comp_rename f g) φ lemma bind₂_map (f : S →+* mv_polynomial σ T) (g : R →+* S) (φ : mv_polynomial σ R) : bind₂ f (map g φ) = bind₂ (f.comp g) φ := by simp [bind₂] @[simp] lemma map_comp_C (f : R →+* S) : (map f).comp (C : R →+* mv_polynomial σ R) = C.comp f := by { ext1, apply map_C } -- mixing the two monad structures lemma hom_bind₁ (f : mv_polynomial τ R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : f (bind₁ g φ) = eval₂_hom (f.comp C) (λ i, f (g i)) φ := by rw [bind₁, map_aeval, algebra_map_eq] lemma map_bind₁ (f : R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : map f (bind₁ g φ) = bind₁ (λ (i : σ), (map f) (g i)) (map f φ) := by { rw [hom_bind₁, map_comp_C, ← eval₂_hom_map_hom], refl } @[simp] lemma eval₂_hom_comp_C (f : R →+* S) (g : σ → S) : (eval₂_hom f g).comp C = f := by { ext1 r, exact eval₂_C f g r } lemma eval₂_hom_bind₁ (f : R →+* S) (g : τ → S) (h : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₁ h φ) = eval₂_hom f (λ i, eval₂_hom f g (h i)) φ := by rw [hom_bind₁, eval₂_hom_comp_C] lemma aeval_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : aeval f (bind₁ g φ) = aeval (λ i, aeval f (g i)) φ := eval₂_hom_bind₁ _ _ _ _ lemma aeval_comp_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) : (aeval f).comp (bind₁ g) = aeval (λ i, aeval f (g i)) := by { ext1, apply aeval_bind₁ } lemma eval₂_hom_comp_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) : (eval₂_hom f g).comp (bind₂ h) = eval₂_hom ((eval₂_hom f g).comp h) g := by { ext1; simp } lemma eval₂_hom_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₂ h φ) = eval₂_hom ((eval₂_hom f g).comp h) g φ := ring_hom.congr_fun (eval₂_hom_comp_bind₂ f g h) φ lemma aeval_bind₂ [algebra S T] (f : σ → T) (g : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : aeval f (bind₂ g φ) = eval₂_hom ((@aeval S T σ _ f _ _ : mv_polynomial σ S →+* T).comp g) f φ := eval₂_hom_bind₂ _ _ _ _ lemma eval₂_hom_C_left (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl lemma bind₁_monomial (f : σ → mv_polynomial τ R) (d : σ →₀ ℕ) (r : R) : bind₁ f (monomial d r) = C r * ∏ i in d.support, f i ^ d i := by simp only [monomial_eq, alg_hom.map_mul, bind₁_C_right, finsupp.prod, alg_hom.map_prod, alg_hom.map_pow, bind₁_X_right] lemma bind₂_monomial (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) (r : R) : bind₂ f (monomial d r) = f r * monomial d 1 := by simp only [monomial_eq, ring_hom.map_mul, bind₂_C_right, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, bind₂_X_right, C_1, one_mul] @[simp] lemma bind₂_monomial_one (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) : bind₂ f (monomial d 1) = monomial d 1 := by rw [bind₂_monomial, f.map_one, one_mul] instance monad : monad (λ σ, mv_polynomial σ R) := { map := λ α β f p, rename f p, pure := λ _, X, bind := λ _ _ p f, bind₁ f p } instance is_lawful_functor : is_lawful_functor (λ σ, mv_polynomial σ R) := { id_map := by intros; simp [(<$>)], comp_map := by intros; simp [(<$>)] } instance is_lawful_monad : is_lawful_monad (λ σ, mv_polynomial σ R) := { pure_bind := by intros; simp [pure, bind], bind_assoc := by intros; simp [bind, ← bind₁_comp_bind₁] } /- Possible TODO for the future: Enable the following definitions, and write a lot of supporting lemmas. def bind (f : R →+* mv_polynomial τ S) (g : σ → mv_polynomial τ S) : mv_polynomial σ R →+* mv_polynomial τ S := eval₂_hom f g def join (f : R →+* S) : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := aeval (map f) def ajoin [algebra R S] : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := join (algebra_map R S) -/ end mv_polynomial
e7a9cafccd419f355b67ad6dc950df123a45617b
0d107d7abd6ae235d586830f8e09b1b30e7eef0b
/src/math_limit_2/Solution.lean
653515db20fcd292b4cb4f11fffc148e5e4d4b55
[]
no_license
ukikagi/codewars-lean
6b9a83ebbb159e7eebf8551b745a1c4d450e747f
1912f2a4e25e917abfce70d65c0469cfac19dc93
refs/heads/master
1,672,948,190,244
1,603,361,004,000
1,603,795,841,000
303,746,208
0
0
null
null
null
null
UTF-8
Lean
false
false
423
lean
import .Preloaded theorem exercise_1p3 (x y : ℕ → ℝ) (l : ℝ) (h₁ : ∀ n, abs (x n - l) ≤ y n) (h₂ : lim_to_inf y 0) : lim_to_inf x l := begin unfold lim_to_inf at *, intros ε hep, specialize h₂ ε hep, simp at h₂, cases h₂ with N H, use N, intros n hn, specialize H n hn, apply lt_of_le_of_lt, exact h₁ n, apply lt_of_le_of_lt, exact le_abs_self (y n), exact H, end
bb2ed01e52c02a36014a4f95b351a5ac7fda9c79
4767244035cdd124e1ce3d0c81128f8929df6163
/data/list/basic.lean
e25ec6517a555354a80c06f07e5b07c2b74c3839
[ "Apache-2.0" ]
permissive
5HT/mathlib
b941fecacd31a9c5dd0abad58770084b8a1e56b1
40fa9ade2f5649569639608db5e621e5fad0cc02
refs/heads/master
1,586,978,681,358
1,546,681,764,000
1,546,681,764,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
183,592
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Basic properties of lists. -/ import tactic.interactive tactic.mk_iff_of_inductive_prop tactic.split_ifs logic.basic logic.function logic.relation algebra.group order.basic data.list.defs data.nat.basic data.option.basic data.bool data.prod data.sigma data.fin open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} instance : is_left_id (list α) has_append.append [] := ⟨ nil_append ⟩ instance : is_right_id (list α) has_append.append [] := ⟨ append_nil ⟩ instance : is_associative (list α) has_append.append := ⟨ append_assoc ⟩ @[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe @[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /- mem -/ theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil | [] := assume h, rfl | (b :: l') := assume h, absurd (mem_cons_self b l') (h b) theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, or.inl⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) := classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩ theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih, {cases h}, rcases h with rfl | h, { exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, rfl⟩, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {cases h}, {rcases h with rfl | h, {exact or.inl rfl}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {cases h}, {cases (eq_or_mem_of_mem_cons h) with h h, {exact ⟨c, mem_cons_self _ _, h.symm⟩}, {rcases ih h with ⟨a, ha₁, ha₂⟩, exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp only [cons_bind, map_append, bind_map l] /- bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x. @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [or_imp_distrib, forall_and_distrib, forall_eq] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp only [mem_cons_iff, forall_mem_cons'] theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp only [mem_singleton, forall_eq] theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_append, or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x. theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (mem_cons_self _ _) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, left, exact px end) (assume : x ∈ l, or.inr (bex.intro x this px))) @[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) /- list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩ /- append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t := by {induction s with b s H generalizing a, refl, simp only [foldl, cons_append], rw H _} theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s := by {induction s with b s H generalizing a, refl, simp only [foldr, cons_append], rw H _} @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and] @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true, true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left'] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { rw nil_append, split, { rintro rfl, left, exact ⟨_, rfl, rfl⟩ }, { rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } }, case cons : a as ih { cases c, { simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'], exact eq_comm }, { simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left, exists_and_distrib_left] } } end @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_left h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_right' h rfl theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply nat.le_add_right end /- join -/ attribute [simp] join theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = [] | [] := iff_of_true rfl (forall_mem_nil _) | (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons] @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]] /- repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂; unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; [refl, simp only [*, map]]; split; refl theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; [refl, simp only [*, repeat, map]]; split; refl @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl @[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α := by induction n; [refl, simp only [*, repeat, join, append_nil]] /- bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append {α β} (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := append_bind _ _ _ /- concat -/ @[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl @[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by induction l; intro h; contradiction @[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by induction l₁; simp only [*, cons_append, concat]; split; refl @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp only [*, concat]; split; refl @[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp only [concat_eq_append, length_append, length] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by induction l₂ with b l₂ ih; simp only [concat_eq_append, nil_append, cons_append, append_assoc] /- reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]], (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]]; refl theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp only [reverse_cons, concat_eq_append] @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; [rw [nil_append, reverse_nil, append_nil], simp only [*, cons_append, reverse_cons, append_assoc]] @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl theorem reverse_injective : injective (@reverse α) := injective_of_left_inverse reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp only [concat_eq_append, reverse_cons, reverse_reverse] @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; [refl, simp only [*, reverse_cons, length_append, length]] @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; [refl, simp only [*, map, reverse_cons, map_append]] theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp only [reverse_core_eq, map_append, map_reverse] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff, not_mem_nil, false_or, or_false, or_comm]] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp only [length_reverse, length_repeat], λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ @[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { rw reverse_cons, exact H1 _ _ ih } end /- last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp only [concat_eq_append, last_append] @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head(') and tail -/ theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, refl} theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, refl} /- map -/ lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in by rw [map, map, h₁, map_congr h₂] theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; [refl, simp only [*, map]]; split; refl @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldl]] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; [refl, simp only [*, map, foldr]] theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α) (h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l := by revert a; induction l; intros; [refl, simp only [*, foldl]] theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α) (h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l := by revert a; induction l; intros; [refl, simp only [*, foldr]] theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; [refl, simp only [*, join, map, map_append]] theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *]; split; refl @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl /- map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /- sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih, {refl}, { rw reverse_cons, exact sublist_app_of_sublist_left ih }, { rw [reverse_cons, reverse_cons], exact append_sublist_append_of_sublist_right ih [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp only [reverse_reverse] at this; assumption, reverse_sublist⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp only [reverse_append, append_sublist_append_left, reverse_sublist_iff] at this; assumption, λ h, append_sublist_append_of_sublist_right h l⟩ theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (subset_of_sublist s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ subset_of_sublist s theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h, λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /- index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih, { exact iff_of_true rfl (not_mem_nil _) }, simp only [length, mem_cons_iff, index_of_cons], split_ifs, { exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) }, { simp only [h, false_or], rw ← ih, exact succ_inj' } end @[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih, {refl}, simp only [length, index_of_cons], by_cases h : a = b, {rw if_pos h, exact nat.zero_le _}, rw if_neg h, exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /- nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_ge_len (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_ge_len hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ @[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) : nth_le [a] n hn = a := have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn), by subst hn0; refl lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂), (l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂ | [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim | (a::l) _ 0 hn₁ hn₂ := rfl | (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append]; exact nth_le_append _ _ @[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < n) : (list.repeat a n).nth_le m (by rwa list.length_repeat) = a := eq_of_mem_repeat (nth_le_mem _ _ _) lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) : (l₁ ++ l₂).nth n = l₁.nth n := have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn (by rw length_append; exact le_add_right _ _), by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append] @[simp] lemma nth_concat_length: ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = a | [] a := rfl | (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length] @[extensionality] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp only [aa, ext (λn, h (n+1))]; split; refl theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])] @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l] @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) : ∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) = l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l) lemma modify_nth_tail_modify_nth_tail_le {f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) : (l.modify_nth_tail f n).modify_nth_tail g m = l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n := begin rcases le_iff_exists_add.1 h with ⟨m, rfl⟩, rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail] end lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) : (l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n := by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl lemma modify_nth_tail_id : ∀n (l:list α), l.modify_nth_tail id n = l | 0 l := rfl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ_inj, not_false_iff] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp only [update_nth_eq_modify_nth, modify_nth_length] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp only [nth_modify_nth, if_pos] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp only [nth_modify_nth, if_neg h, id_map'] theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h] section insert_nth variable {a : α} @[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1 | 0 as h := rfl | (n+1) [] h := (nat.not_succ_le_zero _ h).elim | (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h) lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l := by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same]; from modify_nth_tail_id _ _ lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → m ≥ n → insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n | 0 0 [] has _ := (lt_irrefl _ has).elim | 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth] | 0 (m+1) (a::as) has hmn := rfl | (n+1) (m+1) (a::as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n → insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1) | n 0 (a :: as) has hmn := rfl | (n + 1) (m + 1) (a :: as) has hmn := congr_arg (cons a) $ insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn) lemma insert_nth_comm (a b : α) : ∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l), (l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a | 0 j l := by simp [insert_nth] | (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim | (i + 1) (j+1) [] := by simp | (i + 1) (j+1) (c::l) := assume h₀ h₁, by simp [insert_nth]; exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁) end insert_nth /- take, drop -/ @[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl @[simp] theorem take_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_ge (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by rw [zero_min, take_zero, take_zero] | (succ n) (succ m) nil := by simp only [take_nil] | (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ @[simp] lemma drop_all (l : list α) : l.drop l.length = [] := calc l.drop l.length = (l ++ []).drop l.length : by simp ... = [] : drop_left _ _ lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).drop n = l₁.drop n ++ l₂ | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)] lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n | l₁ l₂ 0 hn := by simp | [] l₂ (n+1) hn := absurd hn dec_trivial | (a::l₁) l₂ (n+1) hn := by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)] @[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l | m [] := by simp | 0 l := by simp | (m+1) (a::l) := calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl ... = drop (n + m) l : drop_drop m l ... = drop (n + (m + 1)) (a :: l) : rfl theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α), drop m (take (m + n) l) = take n (drop m l) | 0 n _ := by simp | (m+1) n nil := by simp | (m+1) n (_::l) := have h: m + 1 + n = (m+n) + 1, by simp, by simpa [take_cons, h] using drop_take m n l theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp only [update_nth] section take' variable [inhabited α] @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /- foldl, foldr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := begin induction l with hd tl ih generalizing a, {refl}, unfold foldl, rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)] end lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := begin induction l with hd tl ih, {refl}, simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H, simp only [foldr, ih H.2, H.1] end @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl @[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l := by rw ←foldr_reverse; simp /- scanr -/ @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp only [scanr, scanr_aux, t, foldr_cons] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp only [foldl_cons]; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons] lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := rfl | (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /- mfoldl, mfoldr -/ section mfoldl_mfoldr variables {m : Type v → Type w} [monad m] @[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl @[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl @[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} : mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl @[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} : mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl variables [is_lawful_monad m] @[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂}, mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂ | _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind] | _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc] @[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂}, mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁ | _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure] | _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc] end mfoldl_mfoldr /- sum -/ attribute [to_additive list.sum] list.prod attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1 section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive list.sum_nil] theorem prod_nil : ([] : list α).prod = 1 := rfl @[simp, to_additive list.sum_cons] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive list.sum_append] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive list.sum_join] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] end monoid @[simp, to_additive list.sum_erase] theorem prod_erase [decidable_eq α] [comm_monoid α] {a} : Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod | (b::l) h := begin rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end lemma dvd_prod [comm_semiring α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _ @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; [refl, simp only [*, join, map, sum_cons, length_append]] @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] /- lexicographic ordering -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {} {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /- all & any -/ @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /- map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]] theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; [refl, simp only [*, pmap, map]]; split; refl theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; [refl, simp only [*, pmap, length]] @[simp] lemma length_attach {α} (L : list α) : L.attach.length = L.length := length_pmap /- find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases h : p a, { simp only [find_cons_of_pos _ h, h, not_true, false_and] }, { rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] } end @[simp] theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, exact h }, { rw find_cons_of_neg _ h at H, exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases h : p b, { rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self }, { rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) } end end find /- lookmap -/ section lookmap variables (f : α → option α) @[simp] theorem lookmap_nil : [].lookmap f = [] := rfl @[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) : (a :: l).lookmap f = a :: l.lookmap f := by simp [lookmap, h] @[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) : (a :: l).lookmap f = b :: l := by simp [lookmap, h] theorem lookmap_some : ∀ l : list α, l.lookmap some = l | [] := rfl | (a::l) := rfl theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l | [] := rfl | (a::l) := congr_arg (cons a) (lookmap_none l) theorem lookmap_congr {f g : α → option α} : ∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g | [] H := rfl | (a::l) H := begin cases forall_mem_cons.1 H with H₁ H₂, cases h : g a with b, { simp [h, H₁.trans h, lookmap_congr H₂] }, { simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] } end theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l := (lookmap_congr H).trans (lookmap_none l) theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) : ∀ l : list α, map g (l.lookmap f) = map g l | [] := rfl | (a::l) := begin cases h' : f a with b, { simp [h', lookmap_map_eq] }, { simp [lookmap_cons_some _ _ h', h _ _ h'] } end theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l := by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h theorem length_lookmap (l : list α) : length (l.lookmap f) = length l := by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp end lookmap /- filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp only [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp only [filter_map, h]; split; refl theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {refl}, simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {refl}, by_cases pa : p a, { simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl }, { simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] } end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp only [h, option.none_bind'] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp only [h, h', option.some_bind'] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases h : p x, { simp only [option.guard, if_pos h, option.some_bind'] }, { simp only [option.guard, if_neg h, option.none_bind'] } end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, { split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } }, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff, or_and_distrib_right, exists_or_distrib, this, exists_eq_left] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp only [map_filter_map, H, filter_map_some] theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp only [filter_map]; cases f a with b; simp only [filter_map, IH, sublist.cons, sublist.cons2] theorem map_sublist_map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s /- filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a; [simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2], simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]]; split; refl @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := subset_of_sublist $ filter_sublist l theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self | (b::l) (or.inr ain) pa := if pb : p b then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, rw forall_mem_cons, by_cases p a, { rw [filter_cons_of_pos _ h, cons_inj', ih, and_iff_right h] }, { rw [filter_cons_of_neg _ h], refine iff_of_false _ (mt and.left h), intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) } end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l, filter p (filter q l) = filter (λ a, p a ∧ q a) l | [] := rfl | (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false, true_and, false_and, filter_filter l, eq_self_iff_true] @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while] else by simp only [span, take_while, drop_while, if_neg pa] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append, take_while_append_drop l] else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append] @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l ih; [refl, by_cases (p x)]; [simp only [filter_cons_of_pos _ h, countp, ih, if_pos h], simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp only [countp_eq_length_filter, filter_append, length_append] theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s) @[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) : countp p (filter q l) = countp (λ a, p a ∧ q a) l := by simp only [countp_eq_length_filter, filter_filter] end filter /- count -/ section count variable [decidable_eq α] @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append @[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by rw [concat_eq_append, count_append, count_singleton] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp only [count, countp_pos, exists_prop, exists_eq_right'] @[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩ @[simp] theorem count_filter {p} [decidable_pred p] {a} {l : list α} (h : p a) : count a (filter p l) = count a l := by simp only [count, countp_filter]; congr; exact set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h)) end count /- prefix, suffix, infix -/ @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ @[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] @[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp only [concat_eq_append, prefix_append] theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp only [reverse_reverse] theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_left_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_left_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton], ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp only [tails, mem_singleton]; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /- sublists -/ @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; [refl, simp only [*, sublists'_aux]] theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s, { simp only [sublists'_nil, mem_singleton], exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, simp only [sublists'_cons, mem_append, IH, mem_map], split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ h }, { exact cons_sublist_cons _ h }, { cases h with _ _ _ h s _ _ h, { exact or.inl h }, { exact or.inr ⟨s, h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map, length, pow_succ, mul_succ, mul_zero, zero_add] @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc] theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih, {refl}, simp only [ih, foldr_cons] end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil] | (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc]; refl theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := rfl | (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l] theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind, sublists_aux₁_bind], congr, funext x, apply congr_arg _, rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind, cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind, map_eq_map, map_eq_map, map_id' (append_nil), append_nil] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l with hd tl ih; [refl, simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton, map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro, {rwa foldr}, simp only [foldr, mem_cons_iff, false_or, not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp only [map, map_append, sublists_concat]; exact ((append_sublist_append_left _).2 $ singleton_sublist.2 $ mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans ((append_sublist_append_right _).2 IH) /- forall₂ -/ section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator relation run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff @[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} : forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := ⟨λ h, by cases h with h₁ h₂; split; assumption, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩ theorem forall₂.imp {R S : α → β → Prop} (H : ∀ a b, R a b → S a b) {l₁ l₂} (h : forall₂ R l₁ l₂) : forall₂ S l₁ l₂ := by induction h; constructor; solve_by_elim lemma forall₂.mp {r q s : α → β → Prop} (h : ∀a b, r a b → q a b → s a b) : ∀{l₁ l₂}, forall₂ r l₁ l₂ → forall₂ q l₁ l₂ → forall₂ s l₁ l₂ | [] [] forall₂.nil forall₂.nil := forall₂.nil | (a::l₁) (b::l₂) (forall₂.cons hr hrs) (forall₂.cons hq hqs) := forall₂.cons (h a b hr hq) (forall₂.mp hrs hqs) lemma forall₂.flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ h₂.flip lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l | [] _ := forall₂.nil | (a::as) h := forall₂.cons (h _ (mem_cons_self _ _)) (forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha) lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l := forall₂_same $ assume a h, is_refl.refl _ _ lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) := begin funext a b, apply propext, split, { assume h, induction h, {refl}, simp only [*]; split; refl }, { assume h, subst h, exact forall₂_refl _ } end @[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ @[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil := ⟨λ H, by cases H; refl, by rintro rfl; exact forall₂.nil⟩ lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_cons_right_iff {b l u} : forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_and_left {r : α → β → Prop} {p : α → Prop} : ∀l u, forall₂ (λa b, p a ∧ r a b) l u ↔ (∀a∈l, p a) ∧ forall₂ r l u | [] u := by simp only [forall₂_nil_left_iff, forall_prop_of_false (not_mem_nil _), imp_true_iff, true_and] | (a::l) u := by simp only [forall₂_and_left l, forall₂_cons_left_iff, forall_mem_cons, and_assoc, and_comm, and.left_comm, exists_and_distrib_left.symm] @[simp] lemma forall₂_map_left_iff {f : γ → α} : ∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u | [] _ := by simp only [map, forall₂_nil_left_iff] | (a::l) _ := by simp only [map, forall₂_cons_left_iff, forall₂_map_left_iff] @[simp] lemma forall₂_map_right_iff {f : γ → β} : ∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u | _ [] := by simp only [map, forall₂_nil_right_iff] | _ (b::u) := by simp only [map, forall₂_cons_right_iff, forall₂_map_right_iff] lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r) | a₀ nil a₁ forall₂.nil forall₂.nil := rfl | (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r) | nil a₀ a₁ forall₂.nil forall₂.nil := rfl | (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) := ⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩ theorem forall₂_length_eq {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂ | _ _ forall₂.nil := rfl | _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂) theorem forall₂_zip {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b | _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁ | _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃ theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b := ⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩, λ h, begin cases h with h₁ h₂, induction l₁ with a l₁ IH generalizing l₂, { cases length_eq_zero.1 h₁.symm, constructor }, { cases l₂ with b l₂; injection h₁ with h₁, exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) } end⟩ theorem forall₂_take {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (take n l₁) (take n l₂) | 0 _ _ _ := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, take] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_take n] theorem forall₂_drop {R : α → β → Prop} : ∀ n {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (drop n l₁) (drop n l₂) | 0 _ _ h := by simp only [drop, h] | (n+1) _ _ (forall₂.nil) := by simp only [forall₂.nil, drop] | (n+1) _ _ (forall₂.cons h₁ h₂) := by simp [and.intro h₁ h₂, forall₂_drop n] theorem forall₂_take_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.take (length l₁) l) l₁ := have h': forall₂ R (take (length l₁) l) (take (length l₁) (l₁ ++ l₂)), from forall₂_take (length l₁) h, by rwa [take_left] at h' theorem forall₂_drop_append {R : α → β → Prop} (l : list α) (l₁ : list β) (l₂ : list β) (h : forall₂ R l (l₁ ++ l₂)) : forall₂ R (list.drop (length l₁) l) l₂ := have h': forall₂ R (drop (length l₁) l) (drop (length l₁) (l₁ ++ l₂)), from forall₂_drop (length l₁) h, by rwa [drop_left] at h' lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp only [not_mem_nil] | a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂) lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map | f g h [] [] forall₂.nil := forall₂.nil | f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂) lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append | [] [] h l₁ l₂ hl := hl | (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl) lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join | [] [] forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂) lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind := assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁) lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs) lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : (r ⇒ (↔)) p q) : (forall₂ r ⇒ forall₂ r) (filter p) (filter q) | _ _ forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := begin by_cases p a, { have : q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_pos _ h, filter_cons_of_pos _ this, forall₂_cons, h₁, rel_filter h₂, and_true], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp only [filter_cons_of_neg _ h, filter_cons_of_neg _ this, rel_filter h₂], }, end theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { rw filter_map_cons_none _ _ eq }, { rw filter_map_cons_some _ _ _ eq }, end lemma rel_filter_map {f : α → option γ} {q : β → option δ} : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive list.rel_sum] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := assume a b, rel_foldl (assume a b, hf) h end forall₂ /- sections -/ theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L := begin refine ⟨λ h, _, λ h, _⟩, { induction L generalizing f, {cases mem_singleton.1 h, exact forall₂.nil}, simp only [sections, bind_eq_bind, mem_bind, mem_map] at h, rcases h with ⟨_, _, _, _, rfl⟩, simp only [*, forall₂_cons, true_and] }, { induction h with a l f L al fL fs, {exact or.inl rfl}, simp only [sections, bind_eq_bind, mem_bind, mem_map], exact ⟨_, fs, _, al, rfl, rfl⟩ } end theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L := forall₂_length_eq (mem_sections.1 h) lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections | _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil | _ _ (forall₂.cons h₀ h₁) := rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀) /- permutations -/ section permutations @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by rw [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by rw [permutations_aux, permutations_aux.rec]; refl end permutations /- insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp only [insert.def, if_pos h] @[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp only [insert.def, if_neg h]; split; refl @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l, { simp only [insert_of_mem h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' }, simp only [insert_of_not_mem h', mem_cons_iff] end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]] @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) @[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) : length (insert a l) = length l := by rw insert_of_mem h @[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by rw insert_of_not_mem h; refl end insert /- erasep -/ section erasep variables {p : α → Prop} [decidable_pred p] @[simp] theorem erasep_nil : [].erasep p = [] := rfl theorem erasep_cons (a : α) (l : list α) : (a :: l).erasep p = if p a then l else a :: l.erasep p := rfl @[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l := by simp [erasep_cons, h] @[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) : (a::l).erasep p = a :: l.erasep p := by simp [erasep_cons, h] theorem erasep_of_forall_not {l : list α} (h : ∀ a ∈ l, ¬ p a) : l.erasep p = l := by induction l with _ _ ih; [refl, simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]] theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) : ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin induction l with b l IH, {cases al}, by_cases pb : p b, { exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ }, { rcases al with rfl | al, {exact pb.elim pa}, rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩, h₂, by rw h₃; refl, by simp [pb, h₄]⟩ } end theorem exists_or_eq_self_of_erasep (l : list α) : l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ := begin by_cases h : ∃ a ∈ l, p a, { rcases h with ⟨a, ha, pa⟩, exact or.inr (exists_of_erasep ha pa) }, { simp at h, exact or.inl (erasep_of_forall_not h) } end @[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) : length (l.erasep p) = pred (length l) := by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩; rw e₂; simp [-add_comm, e₁]; refl theorem erasep_append_left {a : α} (pa : p a) : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂ | (x::xs) l₂ h := begin by_cases h' : p x; simp [h'], rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h), rintro rfl, exact pa end theorem erasep_append_right : ∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p | [] l₂ h := rfl | (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1, erasep_append_right _ (forall_mem_cons.1 h).2] theorem erasep_sublist (l : list α) : l.erasep p <+ l := by rcases exists_or_eq_self_of_erasep l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩; [rw h, {rw [h₄, h₃], simp}] theorem erasep_subset (l : list α) : l.erasep p ⊆ l := subset_of_sublist (erasep_sublist l) theorem erasep_sublist_erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p := begin induction s, case list.sublist.slnil { refl }, case list.sublist.cons : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] }, case list.sublist.cons2 : l₁ l₂ a s IH { by_cases h : p a; simp [h], exacts [s, IH.cons2 _ _ _] } end theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l := @erasep_subset _ _ _ _ _ @[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l := ⟨mem_of_mem_erasep, λ al, begin rcases exists_or_eq_self_of_erasep l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩, { rwa h }, { rw h₄, rw h₃ at al, have : a ≠ c, {rintro rfl, exact pa.elim h₂}, simpa [this] using al } end⟩ theorem erasep_map (f : β → α) : ∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f)) | [] := rfl | (b::l) := by by_cases p (f b); simp [h, erasep_map l] @[simp] theorem extractp_eq_find_erasep : ∀ l : list α, extractp p l = (find p l, erasep p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l] end erasep /- erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp only [erase_cons, if_pos rfl] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp only [erase_cons, if_neg h]; split; refl theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) := by { induction l with b l, {refl}, by_cases a = b; [simp [h], simp [h, ne.symm h, *]] } @[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h' theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩; rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩ @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := by rw erase_eq_erasep; exact length_erasep_of_mem h rfl theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) : (l₁++l₂).erase a = l₁.erase a ++ l₂ := by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) : (l₁++l₂).erase a = l₁ ++ l₂.erase a := by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right]; rintro b h' rfl; exact h h' theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := by rw erase_eq_erasep; apply erasep_sublist theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := subset_of_sublist (erase_sublist a l) theorem erase_sublist_erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a := by simp [erase_eq_erasep]; exact erasep_sublist_erasep h theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by rw ab else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)] else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} (l : list α) : map f (l.erase a) = (map f l).erase (f a) := by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr; ext b; simp [finj.eq_iff] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; [refl, simp only [foldl_cons, map_erase finj, *]] end erase /- diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := if h : a ∈ l₁ then by simp only [list.diff, if_pos h] else by simp only [list.diff, if_neg h, erase_of_not_mem h] @[simp] theorem nil_diff (l : list α) : [].diff l = [] := by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp only [diff_eq_foldl, foldl_append] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj] theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁ | l₁ [] := sublist.refl _ | l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _ ... <+ l₁.erase a : diff_sublist _ _ ... <+ l₁ : list.erase_sublist _ _ theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ := subset_of_sublist $ diff_sublist _ _ theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂ | l₁ [] h₁ h₂ := h₁ | l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂) theorem diff_sublist_of_sublist : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃ | l₁ l₂ [] h := h | l₁ l₂ (a::l₃) h := by simp only [diff_cons, diff_sublist_of_sublist (erase_sublist_erase _ h)] theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁ | [] l₂ h := erase_sublist _ _ | (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons] else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons, erase_comm a b l₂] using erase_diff_erase_sublist_of_sublist (erase_sublist_erase b h) end diff /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := (zip_nil_right _).symm | l₁ [] := by rw zip_nil_right; refl | (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := rfl | l₁ [] := by simp only [length, zip_nil_right, min_zero] | (a::l₁) (b::l₂) := by by simp only [length, zip_cons_cons, length_zip l₁ l₂, min_add_add_right] theorem zip_append : ∀ {l₁ l₂ r₁ r₂ : list α} (h : length l₁ = length l₂), zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ | [] l₂ r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl | l₁ [] r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl | (a::l₁) (b::l₂) r₁ r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ_inj h)]; split; refl theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g) | [] l₂ := rfl | l₁ [] := by simp only [map, zip_nil_right] | (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) : zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) := by rw [← zip_map, map_id] theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) : zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) := by rw [← zip_map, map_id] theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α), zip (l.map f) (l.map g) = l.map (λ a, (f a, g a)) | [] := rfl | (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ | (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩ | (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h] @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd) | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp only [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp only [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁ | [] l₂ h := rfl | l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl | (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) : (unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)] @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := unzip_zip (length_reverse l).symm @[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l := by rw [← unzip_left, unzip_revzip] @[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse := by rw [← unzip_right, unzip_revzip] theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip] theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse := by simp [revzip] /- enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp only [enum, enum_from_nth, zero_add]; intros; refl @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ /- product -/ @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; [exact (zero_mul _).symm, simp only [length, product_cons, length_append, IH, right_distrib, one_mul, length_map, add_comm]] /- sigma -/ section variable {σ : α → Type*} @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left, and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; [refl, simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]] end /- of_fn -/ theorem length_of_fn_aux {n} (f : fin n → α) : ∀ m h l, length (of_fn_aux f m h l) = length l + m | 0 h l := rfl | (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _) @[simp] theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) theorem nth_of_fn_aux {n} (f : fin n → α) (i) : ∀ m h l, (∀ i, nth l i = of_fn_nth_val f (i + m)) → nth (of_fn_aux f m h l) i = of_fn_nth_val f i | 0 h l H := H i | (succ m) h l H := nth_of_fn_aux m _ _ begin intro j, cases j with j, { simp only [nth, of_fn_nth_val, zero_add, dif_pos (show m < n, from h)] }, { simp only [nth, H, succ_add] } end @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = of_fn_nth_val f i := nth_of_fn_aux f _ _ _ _ $ λ i, by simp only [of_fn_nth_val, dif_neg (not_lt.2 (le_add_left n i))]; refl @[simp] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) : nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i := option.some.inj $ by rw [← nth_le_nth]; simp only [list.nth_of_fn, of_fn_nth_val, fin.eta, dif_pos i.2] theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read := suffices ∀ {m h l}, d_array.rev_iterate_aux a (λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, simp only [d_array.rev_iterate_aux, of_fn_aux, IH] end theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl theorem of_fn_succ {n} (f : fin (succ n) → α) : of_fn f = f 0 :: of_fn (λ i, f i.succ) := suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l = f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, rw [of_fn_aux, IH], refl end theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l | [] := rfl | (a::l) := by rw of_fn_succ; congr; simp only [fin.succ_val]; exact of_fn_nth_le l /- disjoint -/ section disjoint theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp only [disjoint, mem_singleton, forall_eq]; refl @[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp only [singleton_disjoint] @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint] @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /- union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff, mem_cons_iff, or_assoc, *] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in if h : a ∈ l₁ ∪ l₂ then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩ else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h]; split; refl⟩ theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp only [mem_union, or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /- inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter /- bag_inter -/ section bag_inter variable [decidable_eq α] @[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] := by cases l; refl @[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] := by cases l; refl @[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) : (a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) := by cases l₂; exact if_pos h @[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) : (a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ := begin cases l₂, {simp only [bag_inter_nil]}, simp only [erase_of_not_mem h, list.bag_inter, if_neg h] end theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ | [] l₂ := by simp only [nil_bag_inter, not_mem_nil, false_and] | (b::l₁) l₂ := begin by_cases b ∈ l₂, { rw [cons_bag_inter_of_pos _ h, mem_cons_iff, mem_cons_iff, mem_bag_inter], by_cases ba : a = b, { simp only [ba, h, eq_self_iff_true, true_or, true_and] }, { simp only [mem_erase_of_ne ba, ba, false_or] } }, { rw [cons_bag_inter_of_neg _ h, mem_bag_inter, mem_cons_iff, or_and_distrib_right], symmetry, apply or_iff_right_of_imp, rintro ⟨rfl, h'⟩, exact h.elim h' } end theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁ | [] l₂ := by simp [nil_sublist] | (b::l₁) l₂ := begin by_cases b ∈ l₂; simp [h], { apply cons_sublist_cons, apply bag_inter_sublist_left }, { apply sublist_cons_of_sublist, apply bag_inter_sublist_left } end end bag_inter /- pairwise relation (generalized no duplicate) -/ section pairwise run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pairwise_iff variable {R : α → α → Prop} theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp only [pairwise.nil, pairwise_cons] at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; [exact pairwise.nil, simp only [*, pairwise_cons, forall_2_true_iff, and_true]] theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i) theorem forall_of_forall_of_pairwise (H : symmetric R) {l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) : ∀ (x ∈ l) (y ∈ l), R x y := begin induction l with a l IH, { exact forall_mem_nil _ }, cases forall_mem_cons.1 H₁ with H₁₁ H₁₂, cases pairwise_cons.1 H₂ with H₂₁ H₂₂, rintro x (rfl | hx) y (rfl | hy), exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy] end theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append], simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]] theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp only [map, pairwise.nil] | (b::l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'], by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map] theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp only [option.mem_def], induction l with a l IH, { simp only [filter_map, pairwise.nil] }, cases e : f a with b, { rw [filter_map_cons_none _ _ e, IH, pairwise_cons], simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] }, rw [filter_map_cons_some _ _ _ e], simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'], end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons], simp only [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH, pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h] theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (not_lt_zero j).elim h | (a::l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (not_lt_zero _).elim h₂}, cases i with i, { exact H.1 _ (nth_le_mem l _ _) }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ pairwise.nil := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this /- pairwise reduct -/ variable [decidable_rel R] @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := subset_of_sublist (pw_filter_sublist _) theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {refl}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH, { exact λ _ _, false.elim }, simp only [forall_mem_cons], by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end pairwise /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ section chain run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff variable {R : α → α → Prop} theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := by induction p with _ a b l r p IH; constructor; [exact H _ _ r, exact IH] theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp only [chain_cons, chain.nil, and_true] theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp only [*, nil_append, cons_append, chain.nil, chain_cons, and_true, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp only [map, chain.nil, chain_cons, *] theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a, {exact chain.nil}, simp only [chain_cons, forall_mem_cons] at r, exact chain_cons.2 ⟨r.1, IH r'⟩ end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {exact pairwise_singleton _ _}, apply IH.cons _, simp only [mem_cons_iff, forall_mem_cons', r, true_and], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ theorem chain'.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} (p : chain' R l) : chain' S l := by cases l; [trivial, exact p.imp H] theorem chain'.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : chain' R l ↔ chain' S l := ⟨chain'.imp (λ a b, (H a b).1), chain'.imp (λ a b, (H a b).2)⟩ theorem chain'.iff_mem {S : α → α → Prop} : ∀ {l : list α}, chain' R l ↔ chain' (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l | [] := iff.rfl | (x::l) := ⟨λ h, (chain.iff_mem.1 h).imp $ λ a b ⟨h₁, h₂, h₃⟩, ⟨h₁, or.inr h₂, h₃⟩, chain'.imp $ λ a b h, h.2.2⟩ theorem chain'_singleton (a : α) : chain' R [a] := chain.nil theorem chain'_split {a : α} : ∀ {l₁ l₂ : list α}, chain' R (l₁++a::l₂) ↔ chain' R (l₁++[a]) ∧ chain' R (a::l₂) | [] l₂ := (and_iff_right (chain'_singleton a)).symm | (b::l₁) l₂ := chain_split theorem chain'_map (f : β → α) {l : list β} : chain' R (map f l) ↔ chain' (λ a b : β, R (f a) (f b)) l := by cases l; [refl, exact chain_map _] theorem chain'_of_chain'_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : chain' S (map f l)) : chain' R l := ((chain'_map f).1 p).imp H theorem chain'_map_of_chain' {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : chain' R l) : chain' S (map f l) := (chain'_map f).2 $ p.imp H theorem chain'_of_pairwise : ∀ {l : list α}, pairwise R l → chain' R l | [] _ := trivial | (a::l) h := chain_of_pairwise h theorem chain'_iff_pairwise (tr : transitive R) : ∀ {l : list α}, chain' R l ↔ pairwise R l | [] := (iff_true_intro pairwise.nil).symm | (a::l) := chain_iff_pairwise tr end chain /- no duplicates predicate -/ section nodup @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_nil : @nodup α [] := pairwise.nil @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp only [nodup, pairwise_cons, forall_mem_ne] lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp only [nodup_nil] | _ _ (forall₂.cons hab h) := by simpa only [nodup_cons] using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin induction l with a l IH; intro h, {exact nodup_nil}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt theorem nodup_repeat (a : α) : ∀ {n : ℕ}, nodup (repeat a n) ↔ n ≤ 1 | 0 := by simp [nat.zero_le] | 1 := by simp | (n+2) := iff_of_false (λ H, nodup_iff_sublist.1 H a ((repeat_sublist_repeat _).2 (le_add_left 2 n))) (not_le_of_lt $ le_add_left 2 n) @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp only [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp only [nodup_append, and.left_comm, disjoint_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp only [nodup_append, not_or_distrib, and.left_comm, and_assoc, nodup_cons, mem_append, disjoint_cons_right] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) := nodup_map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup_of_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp only [nodup, ne.def, eq_comm] theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH, {refl}, by_cases b = a, { subst h, rw [erase_cons_head, filter_cons_of_neg], symmetry, rw filter_eq_self, simpa only [ne.def, eq_comm] using m, exact not_not_intro rfl }, { rw [erase_cons_tail _ h, filter_cons_of_pos, IH], exact h } end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp only [mem_filter, and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := λ H, ((mem_erase_iff_of_nodup h).1 H).1 rfl theorem nodup_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp only [nodup, pairwise_join, disjoint_left.symm, forall_mem_ne] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp only [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm, mem_map, exists_imp_distrib, and_imp]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, forall_eq'] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂, d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), d₁.imp $ λ a₁ a₂ n x h₁ h₂, begin rcases mem_map.1 h₁ with ⟨b₁, mb₁, rfl⟩, rcases mem_map.1 h₂ with ⟨b₂, mb₂, ⟨⟩⟩, exact n rfl end⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by rw concat_eq_append; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := if h' : a ∈ l then by rw [insert_of_mem h']; exact h else by rw [insert_of_not_mem h', nodup_cons]; split; assumption theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] end nodup /- erase duplicates function -/ section erase_dup variable [decidable_eq α] @[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) : erase_dup (a::l) = erase_dup l := pw_filter_cons_of_neg $ by simpa only [forall_mem_ne] using h theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) : erase_dup (a::l) = a :: erase_dup l := pw_filter_cons_of_pos $ by simpa only [forall_mem_ne] using h @[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l := by simpa only [erase_dup, forall_mem_ne, not_not] using not_congr (@forall_mem_pw_filter α (≠) _ (λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l) @[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) : erase_dup (a::l) = erase_dup l := erase_dup_cons_of_mem' $ mem_erase_dup.2 h @[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) : erase_dup (a::l) = a :: erase_dup l := erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l := λ a, mem_erase_dup.2 theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self @[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l := pw_filter_idempotent theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ := begin induction l₁ with a l₁ IH, {refl}, rw [cons_union, ← IH], show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)), by_cases a ∈ erase_dup (l₁ ++ l₂); [ rw [erase_dup_cons_of_mem' h, insert_of_mem h], rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]] end end erase_dup /- iota and range(') -/ @[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n | s 0 := rfl | s (n+1) := congr_arg succ (length_range' _ _) @[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n | s 0 := (false_iff _).2 $ λ ⟨H1, H2⟩, not_le_of_lt H2 H1 | s (succ n) := have m = s → m < s + n + 1, from λ e, e ▸ lt_succ_of_le (le_add_right _ _), have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m, by simpa only [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm, (mem_cons_iff _ _ _).trans $ by simp only [mem_range', or_and_distrib_left, or_iff_right_of_imp this, l, add_right_comm]; refl theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n | s 0 := rfl | s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n) theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa only [length_range'] using length_le_of_sublist h, λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩ theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n := ⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $ (mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2, λ h, subset_of_sublist (range'_sublist_right.2 h)⟩ theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m) | s 0 (n+1) _ := rfl | s (m+1) (n+1) h := (nth_range' (s+1) (lt_of_add_lt_add_right h)).trans $ by rw add_right_comm; refl theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] := by rw add_comm n 1; exact (range'_append s n 1).symm theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s) | 0 n := rfl | (s+1) n := by rw [show n+(s+1) = n+1+s, from add_right_comm n s 1]; exact range_core_range' s (n+1) theorem range_eq_range' (n : ℕ) : range n = range' 0 n := (range_core_range' n 0).trans $ by rw zero_add theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) := by rw [range_eq_range', range_eq_range', range', add_comm, ← map_add_range']; congr; exact funext one_add theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) := by rw [range_eq_range', map_add_range']; refl @[simp] theorem length_range (n : ℕ) : length (range n) = n := by simp only [range_eq_range', length_range'] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp only [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp only [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp only [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp only [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp only [range_eq_range', mem_range', nat.zero_le, true_and, zero_add] @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := mt mem_range.1 $ lt_irrefl _ theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m := by simp only [range_eq_range', nth_range' _ h, zero_add] theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] := by simp only [range_eq_range', range'_concat, zero_add] theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp only [iota, range'_concat, iota_eq_reverse_range' n, reverse_append, add_comm]; refl @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp only [iota_eq_reverse_range', length_reverse, length_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp only [iota_eq_reverse_range', pairwise_reverse, pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp only [iota_eq_reverse_range', nodup_reverse, nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp only [iota_eq_reverse_range', mem_reverse, mem_range', add_comm, lt_succ_iff] theorem reverse_range' : ∀ s n : ℕ, reverse (range' s n) = map (λ i, s + n - 1 - i) (range n) | s 0 := rfl | s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map]; simpa only [show s + (n + 1) - 1 = s + n, from rfl, (∘), λ a i, show a - 1 - i = a - succ i, from pred_sub _ _, reverse_singleton, map_cons, nat.sub_zero, cons_append, nil_append, eq_self_iff_true, true_and, map_map] using reverse_range' s n @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp only [enum, enum_from_map_fst, range_eq_range'] theorem last'_mem {α} : ∀ a l, @last' α a l ∈ a :: l | a [] := or.inl rfl | a (b::l) := or.inr (last'_mem b l) @[simp] lemma nth_le_attach {α} (L : list α) (i) (H : i < L.attach.length) : (L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) := calc (L.attach.nth_le i H).1 = (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map' ... = L.nth_le i _ : by congr; apply attach_map_val @[simp] lemma nth_le_range {n} (i) (H : i < (range n).length) : nth_le (range n) i H = i := option.some.inj $ by rw [← nth_le_nth _, nth_range (by simpa using H)] theorem of_fn_eq_pmap {α n} {f : fin n → α} : of_fn f = pmap (λ i hi, f ⟨i, hi⟩) (range n) (λ _, mem_range.1) := by rw [pmap_eq_map_attach]; from ext_le (by simp) (λ i hi1 hi2, by simp at hi1; simp [nth_le_of_fn f ⟨i, hi1⟩]) theorem nodup_of_fn {α n} {f : fin n → α} (hf : function.injective f) : nodup (of_fn f) := by rw of_fn_eq_pmap; from nodup_pmap (λ _ _ _ _ H, fin.veq_of_eq $ hf H) (nodup_range n) section tfae /- tfae: The Following (propositions) Are Equivalent -/ theorem tfae_nil : tfae [] := forall_mem_nil _ theorem tfae_singleton (p) : tfae [p] := by simp [tfae] theorem tfae_cons_of_mem {a b} {l : list Prop} (h : b ∈ l) : tfae (a::l) ↔ (a ↔ b) ∧ tfae l := ⟨λ H, ⟨H a (by simp) b (or.inr h), λ p hp q hq, H _ (or.inr hp) _ (or.inr hq)⟩, begin rintro ⟨ab, H⟩ p (rfl | hp) q (rfl | hq), { refl }, { exact ab.trans (H _ h _ hq) }, { exact (ab.trans (H _ h _ hp)).symm }, { exact H _ hp _ hq } end⟩ theorem tfae_cons_cons {a b} {l : list Prop} : tfae (a::b::l) ↔ (a ↔ b) ∧ tfae (b::l) := tfae_cons_of_mem (or.inl rfl) theorem tfae_of_forall (b : Prop) (l : list Prop) (h : ∀ a ∈ l, a ↔ b) : tfae l := λ a₁ h₁ a₂ h₂, (h _ h₁).trans (h _ h₂).symm theorem tfae_of_cycle {a b} {l : list Prop} : list.chain (→) a (b::l) → (last' b l → a) → tfae (a::b::l) := begin induction l with c l IH generalizing a b; simp [tfae_cons_cons, tfae_singleton] at *, { intros a _ b, exact iff.intro a b }, intros ab bc ch la, have := IH bc ch (ab ∘ la), exact ⟨⟨ab, la ∘ (this.2 c (or.inl rfl) _ (last'_mem _ _)).1 ∘ bc⟩, this⟩ end theorem tfae.out {l} (h : tfae l) (n₁ n₂) (h₁ : n₁ < list.length l . tactic.exact_dec_trivial) (h₂ : n₂ < list.length l . tactic.exact_dec_trivial) : list.nth_le l n₁ h₁ ↔ list.nth_le l n₂ h₂ := h _ (list.nth_le_mem _ _ _) _ (list.nth_le_mem _ _ _) end tfae lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n := by simp [rotate] @[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; refl @[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate] @[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl @[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate'] @[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length | [] n := rfl | (a::l) 0 := rfl | (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp lemma rotate'_eq_take_append_drop : ∀ {l : list α} {n : ℕ}, n ≤ l.length → l.rotate' n = l.drop n ++ l.take n | [] n h := by simp [drop_append_of_le_length h] | l 0 h := by simp [take_append_of_le_length h] | (a::l) (n+1) h := have hnl : n ≤ l.length, from le_of_succ_le_succ h, have hnl' : n ≤ (l ++ [a]).length, by rw [length_append, length_cons, list.length, zero_add]; exact (le_of_succ_le h), by rw [rotate'_cons_succ, rotate'_eq_take_append_drop hnl', drop, take, drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m) | (a::l) 0 m := by simp | [] n m := by simp | (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ] @[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l := by rw rotate'_eq_take_append_drop (le_refl _); simp @[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l | 0 := by simp | (n+1) := calc l.rotate' (l.length * (n + 1)) = (l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length : by simp [-rotate'_length, nat.mul_succ, rotate'_rotate'] ... = l : by rw [rotate'_length, rotate'_length_mul] lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n := calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul ... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div] lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n := if h : l.length = 0 then by simp [length_eq_zero, *] at * else by rw [← rotate'_mod, rotate'_eq_take_append_drop (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))]; simp [rotate] lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate n.succ = (l ++ [a]).rotate n := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ] @[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length := by rw [rotate_eq_rotate', length_rotate'] lemma rotate_eq_take_append_drop {l : list α} {n : ℕ} : n ≤ l.length → l.rotate n = l.drop n ++ l.take n := by rw rotate_eq_rotate'; exact rotate'_eq_take_append_drop lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate'] @[simp] lemma rotate_length (l : list α) : rotate l l.length = l := by rw [rotate_eq_rotate', rotate'_length] @[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l := by rw [rotate_eq_rotate', rotate'_length_mul] lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ), (l.rotate n).prod = 1 | [] _ _ := by simp | (a::l) hl n := have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial), by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl; rw [← rotate_mod, rotate_eq_take_append_drop this, list.prod_append, mul_eq_one_iff_inv_eq, ← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one] section choose variables (p : α → Prop) [decidable_pred p] (l : list α) lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose end list theorem option.to_list_nodup {α} : ∀ o : option α, o.to_list.nodup | none := list.nodup_nil | (some x) := list.nodup_singleton x