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
4335b211572d1890415aa3184466cb78a1b307b5
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/Robust.lean
4ed51b49ca55c8690c571890aeeb55b252f3350c
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
639
lean
-- Robust /- [Robust] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Dependable]. An instance of type [SystemType] is deemed [Robust] if and only if all the requirements are satisfied. -/ import SystemModel.System inductive Robust (sys_type: SystemType): Prop | intro : (exists robust: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, robust c p s st) -> Robust
6ea71ea7630446168db0e202cd0e3402e5fccd88
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/category/Top/basic.lean
59a22e0dd3533ca8fa63aae328523068afb20149
[ "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
3,480
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison, Mario Carneiro -/ import category_theory.concrete_category.bundled_hom import topology.continuous_function.basic /-! # Category instance for topological spaces We introduce the bundled category `Top` of topological spaces together with the functors `discrete` and `trivial` from the category of types to `Top` which equip a type with the corresponding discrete, resp. trivial, topology. For a proof that these functors are left, resp. right adjoint to the forgetful functor, see `topology.category.Top.adjunctions`. -/ open category_theory open topological_space universe u /-- The category of topological spaces and continuous maps. -/ def Top : Type (u+1) := bundled topological_space namespace Top instance bundled_hom : bundled_hom @continuous_map := ⟨@continuous_map.to_fun, @continuous_map.id, @continuous_map.comp, @continuous_map.coe_injective⟩ attribute [derive [large_category, concrete_category]] Top instance : has_coe_to_sort Top Type* := bundled.has_coe_to_sort instance topological_space_unbundled (x : Top) : topological_space x := x.str @[simp] lemma id_app (X : Top.{u}) (x : X) : (𝟙 X : X → X) x = x := rfl @[simp] lemma comp_app {X Y Z : Top.{u}} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g : X → Z) x = g (f x) := rfl /-- Construct a bundled `Top` from the underlying type and the typeclass. -/ def of (X : Type u) [topological_space X] : Top := ⟨X⟩ instance (X : Top) : topological_space X := X.str @[simp] lemma coe_of (X : Type u) [topological_space X] : (of X : Type u) = X := rfl instance : inhabited Top := ⟨Top.of empty⟩ /-- The discrete topology on any type. -/ def discrete : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊥⟩, map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_bot } } /-- The trivial topology on any type. -/ def trivial : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊤⟩, map := λ X Y f, { to_fun := f, continuous_to_fun := continuous_top } } /-- Any homeomorphisms induces an isomorphism in `Top`. -/ @[simps] def iso_of_homeo {X Y : Top.{u}} (f : X ≃ₜ Y) : X ≅ Y := { hom := ⟨f⟩, inv := ⟨f.symm⟩ } /-- Any isomorphism in `Top` induces a homeomorphism. -/ @[simps] def homeo_of_iso {X Y : Top.{u}} (f : X ≅ Y) : X ≃ₜ Y := { to_fun := f.hom, inv_fun := f.inv, left_inv := λ x, by simp, right_inv := λ x, by simp, continuous_to_fun := f.hom.continuous, continuous_inv_fun := f.inv.continuous } @[simp] lemma of_iso_of_homeo {X Y : Top.{u}} (f : X ≃ₜ Y) : homeo_of_iso (iso_of_homeo f) = f := by { ext, refl } @[simp] lemma of_homeo_of_iso {X Y : Top.{u}} (f : X ≅ Y) : iso_of_homeo (homeo_of_iso f) = f := by { ext, refl } @[simp] lemma open_embedding_iff_comp_is_iso {X Y Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso g] : open_embedding (f ≫ g) ↔ open_embedding f := open_embedding_iff_open_embedding_compose f (Top.homeo_of_iso (as_iso g)).open_embedding @[simp] lemma open_embedding_iff_is_iso_comp {X Y Z : Top} (f : X ⟶ Y) (g : Y ⟶ Z) [is_iso f] : open_embedding (f ≫ g) ↔ open_embedding g := begin split, { intro h, convert h.comp (Top.homeo_of_iso (as_iso f).symm).open_embedding, exact congr_arg _ (is_iso.inv_hom_id_assoc f g).symm }, { exact λ h, h.comp (Top.homeo_of_iso (as_iso f)).open_embedding } end end Top
af2953855591f02ad4d6bd6059caee9dec36fb1c
08a8ee10652ba4f8592710ceb654b37e951d9082
/src/hott/types/fiber.lean
43bc726a11274bec837d3a33da0a818169a2947b
[ "Apache-2.0" ]
permissive
felixwellen/hott3
e9f299c84d30a782a741c40d38741ec024d391fb
8ac87a2699ab94c23ea7984b4a5fbd5a7052575c
refs/heads/master
1,619,972,899,098
1,509,047,351,000
1,518,040,986,000
120,676,559
0
0
null
1,518,040,503,000
1,518,040,503,000
null
UTF-8
Lean
false
false
18,816
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Mike Shulman Ported from Coq HoTT Theorems about fibers -/ import .sigma .eq .pi ..cubical.squareover .pointed .eq universes u v w hott_theory namespace hott open hott.equiv hott.sigma hott.eq hott.pi hott.pointed hott.is_equiv structure fiber {A B : Type _} (f : A → B) (b : B) := (point : A) (point_eq : f point = b) namespace fiber variables {A : Type _} {B : Type _} {f : A → B} {b : B} @[hott] protected def sigma_char (f : A → B) (b : B) : fiber f b ≃ (Σ(a : A), f a = b) := begin fapply equiv.MK, {intro x, exact ⟨point x, point_eq x⟩}, {intro x, exact (fiber.mk x.1 x.2)}, {intro x, cases x, apply idp }, {intro x, cases x, apply idp }, end @[hott, hsimp] def sigma_char_mk_snd {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b) : ((fiber.sigma_char f b) ⟨ a , p ⟩).snd = p := refl _ @[hott, hsimp] def sigma_char_mk_fst {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b) : ((fiber.sigma_char f b) ⟨ a , p ⟩).fst = a := refl _ @[hott] def fiber_eq_equiv (x y : fiber f b) : (x = y) ≃ (Σ(p : point x = point y), point_eq x = ap f p ⬝ point_eq y) := begin apply equiv.trans, apply eq_equiv_fn_eq_of_equiv, apply fiber.sigma_char, apply equiv.trans, apply sigma_eq_equiv, apply sigma_equiv_sigma_right, intro p, apply eq_pathover_equiv_Fl, end @[hott] def fiber_eq {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : x = y := to_inv (fiber_eq_equiv _ _) ⟨p, q⟩ @[hott] def fiber_pathover {X : Type _} {A B : X → Type _} {x₁ x₂ : X} {p : x₁ = x₂} {f : Πx, A x → B x} {b : Πx, B x} {v₁ : fiber (f x₁) (b x₁)} {v₂ : fiber (f x₂) (b x₂)} (q : point v₁ =[p] point v₂) (r : squareover B hrfl (pathover_idp_of_eq _ (point_eq v₁)) (pathover_idp_of_eq _ (point_eq v₂)) (apo f q) (apd b p)) : v₁ =[p; λ x, fiber (f x) (b x)] v₂ := begin apply (pathover_of_fn_pathover_fn (λ (x : X), @fiber.sigma_char (A x) (B x) (f x) (b x))), dsimp, fapply sigma_pathover; dsimp, { exact q}, { induction v₁ with a₁ p₁, induction v₂ with a₂ p₂, dsimp at *, induction q, apply pathover_idp_of_eq, apply eq_of_vdeg_square, dsimp[hrfl] at r, dsimp[apo, apd] at r, exact (square_of_squareover_ids B r)} end open is_trunc @[hott] def π₁ {B : A → Type _} : (Σa, B a) → A := sigma.fst @[hott] def fiber_pr1 (B : A → Type _) (a : A) : fiber (π₁ : (Σa, B a) → A) a ≃ B a := calc fiber π₁ a ≃ Σ(u : Σ a, B a), (π₁ u) = a : fiber.sigma_char _ _ ... ≃ Σ (a' : A) (b : B a'), a' = a : (sigma_assoc_equiv (λ (u : Σ a, B a), (π₁ u) = a) ) ⁻¹ᵉ ... ≃ Σa' (p : a' = a), B a' : sigma_equiv_sigma_right (λa', comm_equiv_nondep _ _) ... ≃ Σ(w : Σ a', a'=a), B (π₁ w) : sigma_assoc_equiv (λ (w : Σ a', a'=a), B (π₁ w)) ... ≃ B a : sigma_equiv_of_is_contr_left (λ (w : Σ a', a'=a), B (π₁ w)) @[hott] def sigma_fiber_equiv (f : A → B) : (Σb, fiber f b) ≃ A := calc (Σb, fiber f b) ≃ Σb a, f a = b : sigma_equiv_sigma_right (λb, fiber.sigma_char _ b) ... ≃ Σa b, f a = b : sigma_comm_equiv _ ... ≃ A : sigma_equiv_of_is_contr_right _ @[hott, instance] def is_pointed_fiber (f : A → B) (a : A) : pointed (fiber f (f a)) := pointed.mk (fiber.mk a idp) @[hott] def pointed_fiber (f : A → B) (a : A) : Type* := pointed.Mk (fiber.mk a (idpath (f a))) @[hott, reducible] def is_trunc_fun (n : ℕ₋₂) (f : A → B) := Π(b : B), is_trunc n (fiber f b) @[hott, reducible] def is_contr_fun (f : A → B) := is_trunc_fun -2 f -- pre and post composition with equivalences open function variable (f) @[hott] protected def equiv_postcompose {B' : Type _} (g : B ≃ B') --[H : is_equiv g] (b : B) : fiber (g ∘ f) (g b) ≃ fiber f b := calc fiber (g ∘ f) (g b) ≃ Σa : A, g (f a) = g b : fiber.sigma_char _ _ ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma_right, intro a, apply equiv.symm, apply eq_equiv_fn_eq end ... ≃ fiber f b : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott] protected def equiv_precompose {A' : Type _} (g : A' ≃ A) --[H : is_equiv g] (b : B) : fiber (f ∘ g) b ≃ fiber f b := calc fiber (f ∘ g) b ≃ Σa' : A', f (g a') = b : fiber.sigma_char _ _ ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma g, intro a', apply erfl end ... ≃ fiber f b : (fiber.sigma_char _ _) ⁻¹ᵉ end fiber open unit is_trunc pointed namespace fiber @[hott] def fiber_star_equiv (A : Type _) : fiber (λx : A, star) star ≃ A := begin fapply equiv.MK, { intro f, cases f with a H, exact a }, { intro a, apply fiber.mk a, reflexivity }, { intro a, reflexivity }, { intro f, cases f with a H, change fiber.mk a (refl star) = fiber.mk a H, rwr [is_set.elim H (refl star)] } end @[hott] def fiber_const_equiv (A : Type _) (a₀ : A) (a : A) : fiber (λz : unit, a₀) a ≃ a₀ = a := calc fiber (λz : unit, a₀) a ≃ Σz : unit, a₀ = a : fiber.sigma_char _ _ ... ≃ a₀ = a : sigma_unit_left _ -- the pointed fiber of a pointed map, which is the fiber over the basepoint open pointed @[hott] def pfiber {X Y : Type*} (f : X →* Y) : Type* := pointed.MK (fiber f pt) (fiber.mk pt (respect_pt _)) @[hott] def ppoint {X Y : Type*} (f : X →* Y) : pfiber f →* X := pmap.mk point idp @[hott] def pfiber.sigma_char {A B : Type*} (f : A →* B) : pfiber f ≃* pointed.MK (Σa, f a = pt) ⟨pt, respect_pt f⟩ := pequiv_of_equiv (fiber.sigma_char f pt) idp @[hott, hsimp] def pfiber.sigma_char_mk_snd {A B : Type*} (f : A →* B) (a : A) (p : f a = pt) : ((pfiber.sigma_char f).to_pmap ⟨ a , p ⟩).snd = p := refl _ @[hott] def pointed_fst {A : Type*} (B : A → Type) (pt_B : B pt) : pointed.MK (Σa, B a) ⟨pt, pt_B⟩ →* A := pmap.mk π₁ (refl _) @[hott] def ppoint_sigma_char {A B : Type*} (f : A →* B) : ppoint f ~* (pointed_fst _ _) ∘* (pfiber.sigma_char f).to_pmap := phomotopy.refl _ @[hott] def pfiber_pequiv_of_phomotopy {A B : Type*} {f g : A →* B} (h : f ~* g) : pfiber f ≃* pfiber g := begin fapply pequiv_of_equiv, { refine (fiber.sigma_char f pt ⬝e _ ⬝e (fiber.sigma_char g pt)⁻¹ᵉ), apply sigma_equiv_sigma_right, intros a, apply equiv_eq_closed_left, apply (to_homotopy h) }, { refine (fiber_eq rfl _), change (h pt)⁻¹ ⬝ respect_pt f = idp ⬝ respect_pt g, rwr idp_con, apply inv_con_eq_of_eq_con, symmetry, exact (to_homotopy_pt h) } end @[hott] def transport_fiber_equiv {A B : Type _} (f : A → B) {b1 b2 : B} (p : b1 = b2) : fiber f b1 ≃ fiber f b2 := calc fiber f b1 ≃ Σa, f a = b1 : fiber.sigma_char _ _ ... ≃ Σa, f a = b2 : sigma_equiv_sigma_right (λa, equiv_eq_closed_right (f a) p) ... ≃ fiber f b2 : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott,hsimp] def transport_fiber_equiv_mk {A B : Type _} (f : A → B) {b1 b2 : B} (p : b1 = b2) (a : A) (q : f a = b1) : (transport_fiber_equiv f p) ⟨ a , q ⟩ = ⟨ a , q ⬝ p ⟩ := begin induction p, induction q, refl end @[hott, hsimp] def snd_point_pfiber_eq_respect_pt {A B : Type*} (f : A →* B) : (pfiber f).Point = ⟨ pt , respect_pt f ⟩ := by refl @[hott] def pequiv_postcompose {A B B' : Type*} (f : A →* B) (g : B ≃* B') : pfiber (g.to_pmap ∘* f) ≃* pfiber f := begin fapply pequiv_of_equiv, refine transport_fiber_equiv (g.to_pmap ∘* f) (respect_pt g.to_pmap)⁻¹ ⬝e fiber.equiv_postcompose f (equiv_of_pequiv g) (Point B), dsimp, apply (ap (fiber.mk (Point A))), refine (con.assoc _ _ _) ⬝ _, apply inv_con_eq_of_eq_con, dsimp, rwr [con.assoc, eq.con.right_inv, con_idp, ← ap_compose], exact ap_con_eq_con (λ x, ap g⁻¹ᵉ*.to_pmap (ap g.to_pmap (pleft_inv' g x)⁻¹) ⬝ ap g⁻¹ᵉ*.to_pmap (pright_inv g (g.to_pmap x)) ⬝ pleft_inv' g x) (respect_pt f) end @[hott] def pequiv_precompose {A A' B : Type*} (f : A →* B) (g : A' ≃* A) : pfiber (f ∘* g.to_pmap) ≃* pfiber f := begin fapply pequiv_of_equiv, refine fiber.equiv_precompose f (equiv_of_pequiv g) (Point B), apply (eq_of_fn_eq_fn (fiber.sigma_char _ _)), fapply sigma_eq, { apply respect_pt g.to_pmap }, { apply eq_pathover_Fl' } end @[hott] def pfiber_pequiv_of_square {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C) (k : B ≃* D) (s : k.to_pmap ∘* f ~* g ∘* h.to_pmap) : pfiber f ≃* pfiber g := calc pfiber f ≃* pfiber (k.to_pmap ∘* f) : (pequiv_postcompose f k) ⁻¹ᵉ* ... ≃* pfiber (g ∘* h.to_pmap) : pfiber_pequiv_of_phomotopy s ... ≃* pfiber g : (pequiv_precompose _ _) @[hott] def pcompose_ppoint {A B : Type*} (f : A →* B) : f ∘* ppoint f ~* pconst (pfiber f) B := begin fapply phomotopy.mk, { exact point_eq }, { exact !idp_con⁻¹ } end @[hott] def point_fiber_eq {A B : Type _} {f : A → B} {b : B} {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : ap point (fiber_eq p q) = p := begin induction x with a γ, induction y with a' γ', dsimp at p q, induction p, induction γ', dsimp at q, hinduction q using eq.rec_symm, reflexivity end @[hott] def fiber_eq_equiv_fiber {A B : Type _} {f : A → B} {b : B} (x y : fiber f b) : x = y ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) := calc x = y ≃ fiber.sigma_char f b x = fiber.sigma_char f b y : eq_equiv_fn_eq_of_equiv (fiber.sigma_char f b) x y ... ≃ Σ(p : point x = point y), point_eq x =[p; λ z, f z = b] point_eq y : sigma_eq_equiv _ _ ... ≃ Σ(p : point x = point y), (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : sigma_equiv_sigma_right (λp, calc point_eq x =[p; λ z, f z = b] point_eq y ≃ point_eq x = ap f p ⬝ point_eq y : eq_pathover_equiv_Fl _ _ _ ... ≃ ap f p ⬝ point_eq y = point_eq x : eq_equiv_eq_symm _ _ ... ≃ (point_eq x)⁻¹ ⬝ (ap f p ⬝ point_eq y) = idp : eq_equiv_inv_con_eq_idp _ _ ... ≃ (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : equiv_eq_closed_left _ (con.assoc _ _ _) ⁻¹) ... ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott] def loop_pfiber {A B : Type*} (f : A →* B) : Ω (pfiber f) ≃* pfiber (Ω→ f) := pequiv_of_equiv (fiber_eq_equiv_fiber (Point (pfiber f)) (Point (pfiber f))) begin induction f with f f₀, induction B with B b₀, dsimp at f f₀, induction f₀, reflexivity end @[hott] def pfiber_loop_space {A B : Type*} (f : A →* B) : pfiber (Ω→ f) ≃* Ω (pfiber f) := (loop_pfiber f)⁻¹ᵉ* @[hott] def point_fiber_eq_equiv_fiber {A B : Type _} {f : A → B} {b : B} {x y : fiber f b} (p : x = y) : point (fiber_eq_equiv_fiber x y p) = ap1_gen point idp idp p := by induction p; reflexivity @[hott] lemma ppoint_loop_pfiber {A B : Type*} (f : A →* B) : ppoint (Ω→ f) ∘* (loop_pfiber f).to_pmap ~* Ω→ (ppoint f) := phomotopy.mk (point_fiber_eq_equiv_fiber) begin induction f with f f₀, induction B with B b₀, dsimp at f f₀, induction f₀, reflexivity end @[hott] lemma ppoint_loop_pfiber_inv {A B : Type*} (f : A →* B) : Ω→ (ppoint f) ∘* ((loop_pfiber f)⁻¹ᵉ*).to_pmap ~* ppoint (Ω→ f) := (phomotopy_pinv_right_of_phomotopy (ppoint_loop_pfiber f))⁻¹* @[hott] lemma pfiber_pequiv_of_phomotopy_ppoint {A B : Type*} {f g : A →* B} (h : f ~* g) : ppoint g ∘* (pfiber_pequiv_of_phomotopy h).to_pmap ~* ppoint f := begin induction f with f f₀, induction g with g g₀, induction h with h h₀, induction B with B b₀, induction A with A a₀, dsimp at *, induction g₀, dsimp [respect_pt] at h₀, induction h₀, dsimp [ppoint], fapply phomotopy.mk, { reflexivity }, { dsimp at *, refine idp_con _ ⬝ _, symmetry, apply point_fiber_eq } end @[hott] lemma pequiv_postcompose_ppoint {A B B' : Type*} (f : A →* B) (g : B ≃* B') : ppoint f ∘* (fiber.pequiv_postcompose f g).to_pmap ~* ppoint (g.to_pmap ∘* f) := begin induction f with f f₀, induction g with g hg g₀, induction B with B b₀, induction B' with B' b₀', dsimp at *, induction g₀, induction f₀, fapply phomotopy.mk, { reflexivity }, { sorry } -- { refine idp_con _ ⬝ _, symmetry, dsimp [pequiv_postcompose], -- refine (ap_compose _ _ _) ⁻¹ ⬝ _, apply ap_constant } end @[hott] lemma pequiv_precompose_ppoint {A A' B : Type*} (f : A →* B) (g : A' ≃* A) : ppoint f ∘* (fiber.pequiv_precompose f g).to_pmap ~* g.to_pmap ∘* ppoint (f ∘* g.to_pmap) := begin induction f with f f₀, induction g with g h₁ h₂ p₁ p₂, induction B with B b₀, induction g with g g₀, induction A with A a₀', dsimp at *, induction g₀, induction f₀, reflexivity end @[hott] def pfiber_pequiv_of_square_ppoint {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C) (k : B ≃* D) (s : k.to_pmap ∘* f ~* g ∘* h.to_pmap) : ppoint g ∘* (pfiber_pequiv_of_square h k s).to_pmap ~* h.to_pmap ∘* ppoint f := begin refine (passoc _ _ _) ⁻¹* ⬝* _, refine pwhisker_right _ (pequiv_precompose_ppoint _ _) ⬝* _, refine (passoc _ _ _) ⬝* _, apply pwhisker_left, refine (passoc _ _ _) ⁻¹* ⬝* _, refine pwhisker_right _ (pfiber_pequiv_of_phomotopy_ppoint _) ⬝* _, apply pinv_right_phomotopy_of_phomotopy, refine (pequiv_postcompose_ppoint _ _)⁻¹*, end -- this breaks certain proofs if it is an instance @[hott] def is_trunc_fiber (n : ℕ₋₂) {A B : Type _} (f : A → B) (b : B) [is_trunc n A] [is_trunc (n.+1) B] : is_trunc n (fiber f b) := is_trunc_equiv_closed_rev n (fiber.sigma_char _ _) (is_trunc_sigma _ n) @[hott] def is_trunc_pfiber (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc n A] [is_trunc (n.+1) B] : is_trunc n (pfiber f) := is_trunc_fiber n f pt @[hott] def fiber_equiv_of_is_contr {A B : Type _} (f : A → B) (b : B) [is_contr B] : fiber f b ≃ A := (fiber.sigma_char _ _) ⬝e sigma_equiv_of_is_contr_right _ @[hott] def pfiber_pequiv_of_is_contr {A B : Type*} (f : A →* B) [is_contr B] : pfiber f ≃* A := pequiv_of_equiv (fiber_equiv_of_is_contr f pt) idp @[hott] def pfiber_ppoint_equiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃ Ω B := calc pfiber (ppoint f) ≃ Σ(x : pfiber f), ppoint f x = pt : fiber.sigma_char _ _ ... ≃ Σ(x : Σa, f a = pt), x.1 = pt : by exact sigma_equiv_sigma (fiber.sigma_char _ _) (λ a, erfl) ... ≃ Σ(x : Σa, a = pt), f x.1 = pt : by exact sorry --(sigma_assoc_comm_equiv _ _) ... ≃ f pt = pt : by exact sorry -- (sigma_equiv_of_is_contr_left _) ... ≃ Ω B : by exact (equiv_eq_closed_left _ (respect_pt _)) @[hott] def pfiber_ppoint_pequiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃* Ω B := pequiv_of_equiv (pfiber_ppoint_equiv f) sorry -- (con.left_inv _) @[hott] def fiber_ppoint_equiv_eq {A B : Type*} {f : A →* B} {a : A} (p : f a = pt) (q : ppoint f (fiber.mk a p) = pt) : pfiber_ppoint_equiv f (fiber.mk (fiber.mk a p) q) = (respect_pt f)⁻¹ ⬝ ap f q⁻¹ ⬝ p := begin refine _ ⬝ (con.assoc _ _ _) ⁻¹, apply whisker_left, sorry -- refine eq_transport_Fl _ _ ⬝ _, -- apply whisker_right -- refine inverse2 (ap_inv _ _) ⬝ (inv_inv _) ⬝ _, -- refine ap_compose f pr₁ _ ⬝ ap02 f !ap_pr1_center_eq_sigma_eq', end @[hott] def fiber_ppoint_equiv_inv_eq {A B : Type*} (f : A →* B) (p : Ω B) : (pfiber_ppoint_equiv f)⁻¹ᵉ p = fiber.mk (fiber.mk pt (respect_pt f ⬝ p)) idp := begin apply inv_eq_of_eq, refine _ ⬝ (fiber_ppoint_equiv_eq _ _)⁻¹, exact (inv_con_cancel_left _ _)⁻¹ end end fiber open function is_equiv namespace fiber /- @[hott] theorem 4.7.6 -/ variables {A : Type _} {P : A → Type _ } {Q : A → Type _} variable (f : Πa, P a → Q a) @[hott] def fiber_total_equiv {a : A} (q : Q a) : fiber (total f) ⟨a , q⟩ ≃ fiber (f a) q := sorry -- calc -- fiber (total f) ⟨a , q⟩ -- ≃ Σ(w : Σx, P x), (⟨w.1 , f w.1 w.2 ⟩ : Σ x, _) = ⟨a , q⟩ -- : fiber.sigma_char _ _ -- ... ≃ Σ(x : A), Σ(p : P x), (⟨x , f x p⟩ : Σx, _) = ⟨a , q⟩ -- : (sigma_assoc_equiv _) -- ... ≃ Σ(x : A), Σ(p : P x), Σ(H : x = a), f x p =[H] q -- : -- begin -- apply sigma_equiv_sigma_right, intro x, -- apply sigma_equiv_sigma_right, intro p, -- apply sigma_eq_equiv -- end -- ... ≃ Σ(x : A), Σ(H : x = a), Σ(p : P x), f x p =[H] q -- : -- begin -- apply sigma_equiv_sigma_right, intro x, -- apply sigma_comm_equiv -- end -- ... ≃ Σ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q -- : sigma_assoc_equiv -- ... ≃ Σ(p : P (center (Σx, x=a)).1), f (center (Σx, x=a)).1 p =[(center (Σx, x=a)).2] q -- : sigma_equiv_of_is_contr_left -- ... ≃ Σ(p : P a), f a p =[idpath a] q -- : equiv_of_eq idp -- ... ≃ Σ(p : P a), f a p = q -- : -- begin -- apply sigma_equiv_sigma_right, intro p, -- apply pathover_idp -- end -- ... ≃ fiber (f a) q -- : fiber.sigma_char end fiber end hott
084cf10a1ecc12e2d9f34b65f5f837a2336f7d45
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/ref1.lean
b3f233f92977a8e1d7b41fab044415772bcc61fd
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
599
lean
new_frontend def inc (r : IO.Ref Nat) : IO Unit := do let v ← r.get; r.set (v+1); IO.println (">> " ++ toString v) def initArray (r : IO.Ref (Array Nat)) (n : Nat) : IO Unit := n.forM $ fun i => do r.modify $ fun a => a.push (2*i) def showArrayRef (r : IO.Ref (Array Nat)) : IO Unit := do let a ← r.swap ∅; a.size.forM (fun i => IO.println ("[" ++ toString i ++ "]: " ++ toString (a.get! i))); r.swap a; pure () def tst (n : Nat) : IO Unit := do let r₁ ← IO.mkRef 0; n.forM fun _ => inc r₁; let r₂ ← IO.mkRef (∅ : Array Nat); initArray r₂ n; showArrayRef r₂ #eval tst 10
097d99d814c2ee72695bab630001669ea5118fce
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Parser/Tactic.lean
876e5a8c37bca7743f459aa7d0a2d79f7c0201ae
[ "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
6,385
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Parser.Term namespace Lean namespace Parser namespace Tactic -- Auxiliary parsing category just to expose the nonterminal `tacticSeq` to the `syntax` command builtin_initialize registerBuiltinParserAttribute `builtinTacticSeqParser `tacticSeq @[builtinTacticSeqParser] def tacticSeqElem := tacticSeq def underscoreFn : ParserFn := fun c s => let s := symbolFn "_" c s; let stx := s.stxStack.back; let s := s.popSyntax; s.pushSyntax $ mkIdentFrom stx `_ @[inline] def underscore : Parser := { fn := underscoreFn, info := mkAtomicInfo "ident" } @[combinatorParenthesizer Lean.Parser.Tactic.underscore] def underscore.parenthesizer := PrettyPrinter.Parenthesizer.rawIdent.parenthesizer @[combinatorFormatter Lean.Parser.Tactic.underscore] def underscore.formatter := PrettyPrinter.Formatter.rawIdent.formatter def ident' : Parser := ident <|> underscore @[builtinTacticParser] def «intro» := parser! nonReservedSymbol "intro " >> notSymbol "|" >> many (checkColGt >> termParser maxPrec) @[builtinTacticParser] def «intros» := parser! nonReservedSymbol "intros " >> many (checkColGt >> ident') @[builtinTacticParser] def «revert» := parser! nonReservedSymbol "revert " >> many1 (checkColGt >> ident) @[builtinTacticParser] def «clear» := parser! nonReservedSymbol "clear " >> many1 (checkColGt >> ident) @[builtinTacticParser] def «subst» := parser! nonReservedSymbol "subst " >> many1 (checkColGt >> ident) @[builtinTacticParser] def «assumption» := parser! nonReservedSymbol "assumption" @[builtinTacticParser] def «apply» := parser! nonReservedSymbol "apply " >> termParser @[builtinTacticParser] def «exact» := parser! nonReservedSymbol "exact " >> termParser @[builtinTacticParser] def «refine» := parser! nonReservedSymbol "refine " >> termParser @[builtinTacticParser] def «refine!» := parser! nonReservedSymbol "refine! " >> termParser @[builtinTacticParser] def «case» := parser! nonReservedSymbol "case " >> ident >> darrow >> tacticSeq @[builtinTacticParser] def «allGoals» := parser! nonReservedSymbol "allGoals " >> tacticSeq @[builtinTacticParser] def «focus» := parser! nonReservedSymbol "focus " >> tacticSeq @[builtinTacticParser] def «skip» := parser! nonReservedSymbol "skip" @[builtinTacticParser] def «done» := parser! nonReservedSymbol "done" @[builtinTacticParser] def «traceState» := parser! nonReservedSymbol "traceState" @[builtinTacticParser] def «failIfSuccess» := parser! nonReservedSymbol "failIfSuccess " >> tacticSeq @[builtinTacticParser] def «generalize» := parser! nonReservedSymbol "generalize " >> optional («try» (ident >> " : ")) >> termParser 51 >> " = " >> ident @[builtinTacticParser] def «unknown» := parser! withPosition (ident >> errorAtSavedPos "unknown tactic" true) def locationWildcard := parser! "*" def locationTarget := parser! unicodeSymbol "⊢" "|-" def locationHyp := parser! many1 (checkColGt >> ident) def location := parser! withPosition ("at " >> (locationWildcard <|> locationTarget <|> locationHyp)) @[builtinTacticParser] def change := parser! nonReservedSymbol "change " >> termParser >> optional location @[builtinTacticParser] def changeWith := parser! nonReservedSymbol "change " >> termParser >> " with " >> termParser >> optional location def rwRule := parser! optional (unicodeSymbol "←" "<-") >> termParser def rwRuleSeq := parser! "[" >> sepBy1 rwRule ", " true >> "]" @[builtinTacticParser] def «rewrite» := parser! (nonReservedSymbol "rewrite" <|> nonReservedSymbol "rw") >> notSymbol "[" >> rwRule >> optional location @[builtinTacticParser] def «rewriteSeq» := parser! (nonReservedSymbol "rewrite" <|> nonReservedSymbol "rw") >> rwRuleSeq >> optional location def altRHS := Term.hole <|> Term.syntheticHole <|> tacticSeq def inductionAlt : Parser := nodeWithAntiquot "inductionAlt" `Lean.Parser.Tactic.inductionAlt $ ident' >> many ident' >> darrow >> altRHS def inductionAlts : Parser := withPosition $ "| " >> sepBy1 inductionAlt (checkColGe "alternatives must be indented" >> "|") def withAlts : Parser := optional inductionAlts def usingRec : Parser := optional (" using " >> ident) def generalizingVars := optional (" generalizing " >> many1 ident) @[builtinTacticParser] def «induction» := parser! nonReservedSymbol "induction " >> sepBy1 termParser ", " >> usingRec >> generalizingVars >> withAlts def majorPremise := parser! optional («try» (ident >> " : ")) >> termParser @[builtinTacticParser] def «cases» := parser! nonReservedSymbol "cases " >> sepBy1 majorPremise ", " >> usingRec >> withAlts def matchAlt : Parser := parser! sepBy1 termParser ", " >> darrow >> altRHS def matchAlts : Parser := group $ withPosition $ (optional "| ") >> sepBy1 matchAlt (checkColGe "alternatives must be indented" >> "| ") @[builtinTacticParser] def «match» := parser! nonReservedSymbol "match " >> sepBy1 Term.matchDiscr ", " >> Term.optType >> " with " >> matchAlts @[builtinTacticParser] def «introMatch» := parser! nonReservedSymbol "intro " >> matchAlts def withIds : Parser := optional (" with " >> many1 (checkColGt >> ident')) @[builtinTacticParser] def «injection» := parser! nonReservedSymbol "injection " >> termParser >> withIds @[builtinTacticParser] def paren := parser! "(" >> tacticSeq >> ")" @[builtinTacticParser] def nestedTactic := tacticSeqBracketed @[builtinTacticParser] def orelse := tparser!:2 " <|> " >> tacticParser 1 /- Term binders as tactics. They are all implemented as macros using the triad: named holes, hygiene, and `refine` tactic. -/ @[builtinTacticParser] def «have» := parser! "have " >> Term.haveDecl @[builtinTacticParser] def «suffices» := parser! "suffices " >> Term.sufficesDecl @[builtinTacticParser] def «show» := parser! "show " >> termParser @[builtinTacticParser] def «let» := parser! "let " >> Term.letDecl @[builtinTacticParser] def «let!» := parser! "let! " >> Term.letDecl @[builtinTacticParser] def «letrec» := parser! withPosition (group ("let " >> nonReservedSymbol "rec ") >> Term.letRecDecls) end Tactic end Parser end Lean
0d5bf584c0cb536f23070ec31bcf01ce8ed7c96d
274748215b6d042f0d9c9a505f9551fa8e0c5f38
/src/affine_algebraic_set/V.lean
6ec9d14c23b30d0f433066439721ecf24bdcc901
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M4P33
878ecb515c77d20cc799ff1ebd78f1bf4fd65c12
1a179372db71ad6802d11eacbc1f02f327d55f8f
refs/heads/master
1,607,519,867,193
1,583,344,297,000
1,583,344,297,000
233,316,107
59
4
Apache-2.0
1,579,285,778,000
1,578,788,367,000
Lean
UTF-8
Lean
false
false
18,337
lean
/- Algebraic geometry M4P33, Jan-Mar 2020, formalised in Lean. Copyright (c) 2020 Kevin Buzzard Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, and whoever else in the class wants to join in. Note: if you are viewing this file in a browser via the following link: https://leanprover-community.github.io/lean-web-editor/#url=https%3A%2F%2Fraw.githubusercontent.com%2FImperialCollegeLondon%2FM4P33%2Fmaster%2Fsrc%2Faffine_algebraic_set%2FV.lean then you can click around on the code and see the state of Lean's "brain" at any point within any begin/end proof block. -/ -- imports the theory of multivariable polynomials over rings import data.mv_polynomial import for_mathlib.mv_polynomial -- imports the concept of the radical of an ideal import ring_theory.ideal_operations import ring_theory.noetherian import ring_theory.polynomial import topology.basic /-! # Lecture 2 : The 𝕍 construction Let k be a commutative ring and let n be a natural number. This file defines the map 𝕍 from subsets of k[X₁,X₂,…,Xₙ] to subsets of kⁿ, and proves basic properties about this map. To get 𝕍 in VS Code, type `\bbV`. Note: we never assume that the number of variables is finite, so actually instead of using a natural number n, we use an arbitrary set n for our variables. All the definitions work for k a commutative ring, but not all of the the theorems do. However, computer scientists want us to set up the theory in as much generality as possible, and I believe that mathematicians should learn to think more like computer scientists. So k starts off being a commutative ring, and occasionally changes later. ## Lean 3 notation: important comments. Because we're not using Lean 4, we will have to deal with some awkward notational issues. * the multivariable polynomial ring k[X₁,X₂,…,Xₙ] is denoted `mv_polynomial n k`. * The set kⁿ is denoted `n → k`. (note: this means maps from n to k, and if you're thinking about n as {1,2,3,...,n} then you can see that this makes sense). * subsets of a set X are denoted `set X` * The subset of X which is all of X is not called X :-) It's called `univ` * To evaluate a polynomial f on a vector x, we write `eval x f` Note the order! "Maps on the right". ## Important definitions * `𝕍 : set (mv_polynomial n k) → set (n → k)` sending a subset S of k[X₁,X₂,…Xₙ] to the subset of kⁿ cut out by the zeros of all the elements of S. ## References Martin Orr's lecture notes at https://homepages.warwick.ac.uk/staff/Martin.Orr/2017-8/alg-geom/ ## Tags algebraic geometry, algebraic variety, 𝕍 -/ -- code starts here -- We're dealing with multivariable polynomials so let's open the -- namespace to get easy access to all the functions open mv_polynomial -- let k be a commutative ring variables {k : Type*} [comm_semiring k] -- and let σ be any set, but pretend it's {1,2,...,n} with n a natural number. -- We'll work with polynomials in variables X_i for i ∈ σ. variable {σ : Type*} local notation `𝔸ⁿ` := σ → k /- recall: Maths Lean 3 --------------------------------------- k[X₁, X₂, ..., Xₙ] mv_polynomial σ k kⁿ or 𝔸ⁿ σ → k subsets of X set X the subset X of X univ f(x) eval x f -/ /-- 𝕍 : the function sending a subset S of k[X₁,X₂,…Xₙ] to the subset of kⁿ defined as the intersection of the zeros of all the elements of S. For more details, see Martin Orr's notes -/ def 𝕍 (S : set (mv_polynomial σ k)) : set 𝔸ⁿ := {x : 𝔸ⁿ | ∀ f ∈ S, eval x f = 0} -- Now let's prove a bunch of theorems about 𝕍, in a namespace namespace affine_algebraic_set -- the theorems will be about sets, so let's open the set namespace -- giving us easier access to theorems about sets open set -- The following lemma has a trivial proof so don't worry about it. /-- x ∈ 𝕍 S ↔ for all f ∈ S, f(x) = 0. This is true by definition. -/ lemma mem_𝕍_iff {S : set (mv_polynomial σ k)} {x : σ → k} : x ∈ 𝕍 S ↔ ∀ f ∈ S, eval x f = 0 := iff.rfl -- The rest of the proofs in this file are supposed to be comprehensible -- to mathematicians /-- 𝕍(∅) = kⁿ -/ lemma 𝕍_empty : 𝕍 (∅ : set (mv_polynomial σ k)) = univ := begin -- We need to show that for all x in kⁿ, x ∈ 𝕍 ∅ rw eq_univ_iff_forall, -- so say x ∈ kⁿ. intro x, -- By definition of 𝕍, we need to check that f(x) = 0 for all f in ∅ rw mem_𝕍_iff, -- so say f is a polynomial intro f, -- and f is in the empty set intro hf, -- well, our assumptions give a contradiction, -- and we can deduce anything from a contradiction cases hf, end /-- Over a non-zero commutative ring, 𝕍 (k[X₁,X₂,…,Xₙ]) = ∅ -/ lemma 𝕍_univ {k : Type*} [nonzero_comm_ring k] {n : Type*} : 𝕍 (univ : set (mv_polynomial n k)) = ∅ := begin -- It suffices to show that for all x ∈ kⁿ, x isn't in 𝕍 (all polynomials) rw eq_empty_iff_forall_not_mem, -- so say x ∈ kⁿ intro x, -- we need to check that it's not true that for every polynomial f, f(x) = 0 rw mem_𝕍_iff, -- so let's assume that f(x) = 0 for every polynomial f, intro h, -- and get a contradiction (note that the goal is now `false`). -- Let's consider the constant polynomial 1; we deduce 1(x) = 0. replace h := h (C 1) (mem_univ _), -- evaluating 1 at x gives the value 1 rw eval_C at h, -- so 1 = 0 in k, which contradicts k being non-zero exact zero_ne_one h.symm end /-- 𝕍({0}) = kⁿ -/ lemma 𝕍_zero : 𝕍 ({0} : set (mv_polynomial σ k)) = univ := begin -- It suffices to prove every element of kⁿ is in 𝕍(0) rw eq_univ_iff_forall, -- so say x ∈ kⁿ intro x, -- To prove it's in V(0), we need to show f(x)=0 for all f in {0} rw mem_𝕍_iff, -- so take f in {0} intros f hf, -- Then it's zero! rw mem_singleton_iff at hf, -- so we have to prove 0(x) = 0 rw hf, -- which is obvious refl, end /-- If k ≠ 0 then 𝕍({1}) = ∅ -/ lemma 𝕍_one {k : Type*} [nonzero_comm_ring k] {n : Type*} : 𝕍 ({1} : set (mv_polynomial n k)) = ∅ := begin -- this is basically the same proof as 𝕍_univ -- It suffices to show that for all x ∈ kⁿ, x isn't in 𝕍 ({1}) rw eq_empty_iff_forall_not_mem, -- so say x ∈ kⁿ intro x, -- we need to check that it's not true that for all f ∈ {1}, f(x) = 0 rw mem_𝕍_iff, -- so let's assume that f(x) = 0 for every polynomial f in {1}, intro h, -- and get a contradiction (note that the goal is now `false`). -- Setting f = 1, we deduce 1(x) = 0. replace h := h (C 1) (mem_singleton _), -- evaluating the polynomial 1 at x gives the value 1 rw eval_C at h, -- so 1 = 0 in k, which contradicts k being non-zero exact zero_ne_one h.symm end /-- If S ⊆ T then 𝕍(T) ⊆ 𝕍(S) -/ theorem 𝕍_antimono (S T : set (mv_polynomial σ k)) : S ⊆ T → 𝕍 T ⊆ 𝕍 S := begin -- We are assuming S ⊆ T intro hST, -- Let x ∈ 𝕍 T be arbitrary intros x hx, -- We want to prove x ∈ 𝕍 S. -- We know that ∀ t ∈ T, t(x) = 0, and we want to -- prove that ∀ s ∈ S, s(x) = 0. rw mem_𝕍_iff at hx ⊢, -- So say s ∈ S. intros s hs, -- we want to prove s(x) = 0. -- But t(x) = 0 for all t in T, so it suffices to prove s ∈ T apply hx, -- and this is clear because S ⊆ T exact hST hs end theorem 𝕍_union (S T : set (mv_polynomial σ k)) : 𝕍 (S ∪ T) = 𝕍 S ∩ 𝕍 T := begin -- let's prove this equality of sets by proving ⊆ and ⊇ apply set.subset.antisymm, { -- Step 1: we prove the inclusion 𝕍 (S ∪ T) ⊆ 𝕍 S ∩ 𝕍 T. -- So let x be an element of the LHS intros x hx, -- then x ∈ 𝕍 (S ∪ T) so ∀ f ∈ S ∪ T, f(x) = 0. Call this hypothesis `hx`. rw mem_𝕍_iff at hx, -- To prove x ∈ 𝕍 S ∩ 𝕍 T, it suffices to prove x ∈ 𝕍 S and x ∈ 𝕍 T split, { -- We deal with the two cases separately. -- To prove x ∈ 𝕍 S, we need to show that for all f ∈ S, f(x) = 0 rw mem_𝕍_iff, -- so say f ∈ S intros f hf, -- By hypothesis `hx`, it suffices to prove that f ∈ S ∪ T apply hx, -- but this is obvious left, assumption }, { -- To prove x ∈ 𝕍 T, the argument is the same, -- so we write it the way a computer scientist would. -- (they prefer one incomprehensible line to four simple ones) exact mem_𝕍_iff.2 (λ f hf, hx _ (set.subset_union_right _ _ hf)), }, }, { -- Step 2: we prove the other inclusion. -- ⊢ 𝕍 S ∩ 𝕍 T ⊆ 𝕍 (S ∪ T) (NB `⊢` means "the goal is") -- say x is in 𝕍 S and 𝕍 T rintro x ⟨hxS, hxT⟩, -- We need to show that for all f ∈ S ∪ T, f(x) = 0 rw mem_𝕍_iff, -- so choose f in S ∪ T intros f hf, -- Well, f is either in S or in T, so there are two cases. cases hf, { -- Say f ∈ S -- Recall that x ∈ 𝕍 S, so ∀ f ∈ S, f(x) = 0 rw mem_𝕍_iff at hxS, -- so we're done. exact hxS f hf }, { -- Say f ∈ T -- The argument is the same so we do it in one step exact hxT f hf, } } end -- Infinite (or rather, arbitrary) unions work just the same -- We consider a collection Sᵢ of subsets indexed by i ∈ I. theorem 𝕍_Union {I : Type*} (S : I → set (mv_polynomial σ k)) : 𝕍 (⋃ i, S i) = ⋂ i, 𝕍 (S i) := begin -- To prove equality of two subsets of kⁿ it suffices to prove ⊆ and ⊇. apply set.subset.antisymm, { -- Goal: 𝕍 (⋃ i, S i) ⊆ ⋂ i, 𝕍 (S i) -- Let x be in the left hand side intros x hx, -- it suffices to prove that for all j, x ∈ 𝕍 (S j) rw set.mem_Inter, -- so choose some j ∈ I intro j, -- and say f ∈ S j. intros f hf, -- We now want to prove f(x) = 0. -- Now we know x ∈ 𝕍 (⋃ i, S i), so g(x) = 0 for all g in ⋃ i, S i -- Hence it suffices to prove that f ∈ ⋃ i, S i apply hx, -- By definition of the infinite union, it suffices to find -- some i ∈ I such that f ∈ S i rw set.mem_Union, -- and we can use j for this i use j, -- and what we need to show is true now by assumption, because f ∈ S j assumption }, { -- Now the other way. -- ⊢ (⋂ (i : I), 𝕍 (S i)) ⊆ 𝕍 (⋃ (i : I), S i) -- Say x is in the left hand side intros x hx, -- It suffices to show that for all f ∈ ⋃ i, S i, f(x) = 0 rw mem_𝕍_iff, -- so say f is a polynomial in this union intros f hf, -- If f is in the union, then it's in one of the S i, so say f ∈ S j rw set.mem_Union at hf, cases hf with j hj, -- Now we know x is in the intersection of the 𝕍 (S i) for all i, -- so x ∈ 𝕍 (S j) rw set.mem_Inter at hx, have hxj := hx j, -- and because h(x) = 0 for every element h ∈ S j, -- and we know f ∈ S j, we deduce f(x) = 0 as required. exact hxj _ hj } end -- For convenience, let's define multiplication on subsets of k[X₁,X₂,…,Xₙ] -- in the obvious way: S * T := {s * t | s ∈ S, t ∈ T}. instance : has_mul (set (mv_polynomial σ k)) := ⟨λ S T, {u | ∃ (s ∈ S) (t ∈ T), u = s * t}⟩ -- For this theorem, we need that k satisfies a * b = 0 => a = 0 or b = 0 theorem 𝕍_mul {k : Type*} [integral_domain k] {n : Type*} (S T : set (mv_polynomial n k)) : 𝕍 (S * T) = 𝕍 S ∪ 𝕍 T := begin -- to prove that the two sets are equal we will prove ⊆ and ⊇ apply set.subset.antisymm, { -- This is the "harder" of the two inclusions; -- we need to check that if x vanishes on every element of S*T, -- then x ∈ 𝕍 S or x ∈ 𝕍 T. So let x be in 𝕍 (S * T) intros x hx, -- We then know that for every f ∈ S * T, f(x) = 0 rw mem_𝕍_iff at hx, -- Note for logicians: in this proof, we will assume -- the law of the excluded middle. classical, -- If x ∈ 𝕍 S then the result is easy... by_cases hx2 : x ∈ 𝕍 S, -- because 𝕍 S ⊆ 𝕍 S ∪ 𝕍 T exact subset_union_left _ _ hx2, -- ...so we can assume assume x ∉ 𝕍 S, -- and hence that there's s ∈ S such that s(x) ≠ 0 rw mem_𝕍_iff at hx2, push_neg at hx2, rcases hx2 with ⟨s, hs, hsx⟩, -- we now show x ∈ 𝕍 T, right, -- i.e., that for all t ∈ T we have t(x) = 0 rw mem_𝕍_iff, -- So say t ∈ T intros t ht, -- We want to prove that t(x) = 0. -- Now by assumption, x vanishes on s * t. replace hx := hx (s * t) ⟨s, hs, t, ht, rfl⟩, -- so s(x) * t(x) = 0 rw eval_mul at hx, -- so either s(x) or t(x) = 0, cases mul_eq_zero.1 hx with hxs hxt, -- So the case s(x) = 0 is a contradiction contradiction, -- and t(x) = 0 is what we wanted to prove assumption }, { -- Here's the easier of the two inclusions. -- say x ∈ 𝕍 S ∪ 𝕍 T, intros x hx, -- it's either in 𝕍 S or 𝕍 T. cases hx with hxS hxT, { -- Say x ∈ 𝕍 S. -- We know that x vanishes at every element of S. rw mem_𝕍_iff at hxS, -- We want to prove x vanishes at every polynomial of the form s * t -- with s ∈ S and t ∈ T. rw mem_𝕍_iff, -- so let's take a polynomial of the form s * t rintro _ ⟨s, hs, t, ht, rfl⟩, -- we need to show st(x)=0. So it suffices to show s(x)*t(x)=0 rw eval_mul, -- Because x ∈ 𝕍 S, we have s(x)=0. replace hxS := hxS s hs, -- so it suffices to show 0 * t(x) = 0 rw hxS, -- but this is obvious apply zero_mul, }, { -- This is the case x ∈ 𝕍 T and it's of course completely analogous. -- If I knew more about Lean's `WLOG` tactic I might not have to do -- this case. I'll just do it the computer science way (i.e., a proof -- which is quick to write but harder for a human to understand) rintro _ ⟨s, hs, t, ht, rfl⟩, rw [eval_mul, hxT t ht, mul_zero], } } end -- Pedantic exercise: we assumed a * b = 0 => a = 0 or b = 0. Give an -- example of a commutative ring with that property which is not an -- integral domain. Is the theorem still true for this ring? -- there seems to be no `semiideal.span`. /-- 𝕍(S) equals 𝕍(<S>), where <S> denotes the ideal of k[X₁,…,Xₙ] spanned by S. -/ theorem 𝕍_span {k : Type*} [comm_ring k] {n : Type*} (S : set (mv_polynomial n k)) : 𝕍 S = 𝕍 (ideal.span S) := begin -- Let's prove ⊆ and ⊇ apply set.subset.antisymm, { -- This way is the tricky way -- We need to prove 𝕍(S) ⊆ 𝕍(<S>), and we prove -- this by induction on the ideal <S>. -- Say x ∈ 𝕍(S) intros x hx, -- We need to prove that f(x) = 0 for all f in <S> rw mem_𝕍_iff, -- so say f ∈ <S> intros f hf, -- Apply the principle of induction for ideals. apply submodule.span_induction hf, -- We now have four goals! { -- first goal -- check that if g ∈ S then g(x) = 0 intros g hg, -- this follows because x ∈ 𝕍(S) exact hx _ hg, }, { -- second goal -- check that if g = 0 then g(x) = 0 -- this is true by definition refl }, { -- third goal -- check that if g(x) = 0 and h(x) = 0 -- then (g+h)(x) = 0 intros g h hg hh, -- This is easy because (g+h)(x)=g(x)+h(x) rw eval_add, -- and 0 + 0 = 0 rw [hg, hh, zero_add], }, { -- finally, say g(x) = 0 and r ∈ k[X₁,…,Xₙ] intros r g hg, -- Need to check (r*g)(x) = 0 rw smul_eq_mul, -- i.e. that r(x)*g(x)=0 rw eval_mul, -- but g(x)=0 rw hg, -- so this is obvious exact mul_zero _, } }, { -- The fact that 𝕍(<S>) ⊆ 𝕍(S) follows from 𝕍_antimono and -- the fact that S ⊆ <S> apply 𝕍_antimono, exact ideal.subset_span, } end /-- If I is an ideal of k[X₁,…,Xₙ] then 𝕍(I)=𝕍(√I), where √I is the radical of I -/ theorem 𝕍_radical' {k : Type*} [integral_domain k] {n : Type*} (I : ideal (mv_polynomial n k)) : 𝕍 (↑I : set (mv_polynomial n k)) = 𝕍 (↑(ideal.radical I) : set _) := begin apply set.subset.antisymm, { -- this is the slightly trickier direction; -- we want to prove 𝕍(I) ⊆ 𝕍(√I). So say x ∈ 𝕍(I). intros x hx, rw mem_𝕍_iff, intro f, intro hf, cases hf with n hfn, rw mem_𝕍_iff at hx, replace hx := hx _ hfn, rw eval_pow at hx, exact pow_eq_zero hx, }, { -- this is the easy way apply 𝕍_antimono, apply ideal.le_radical, } end open_locale classical -- theorem 𝕍_fin {k : Type*} [comm_ring k] {n : Type*} (S : set (mv_polynomial n k)) [fintype n] [is_noetherian_ring k] : ∃ (T : finset (mv_polynomial n k)), 𝕍 (S) = 𝕍 (↑T) := begin -- We want to utilize the fact that all ideals in a notherian ring are -- finitely generated. In lean this is true by definition. First we use a -- theorem in lean that mv_poynomial n k is notherian haveI : is_noetherian_ring (mv_polynomial n k) := is_noetherian_ring_mv_polynomial_of_fintype, -- We can now use the fact that the ring is notherian to show that S is -- finitely generated have fg_s : (submodule.fg : ideal (mv_polynomial n k) -> Prop) (ideal.span S), { apply (is_noetherian.noetherian (ideal.span S)), }, -- unpack the definition of finitely generated S cases fg_s with T span_eq, -- T will satisfy the required property so we "use T" and now our goal will -- be to show that T indeed satisfies the property use T, -- We now use the fact that V(S) = V(Span S) and the fact that the span of -- S and T are the same rw [𝕍_span S, 𝕍_span ↑T, ←span_eq], -- The goal is now true by definition, so we use refl refl, end end affine_algebraic_set -- Questions or comments? You can often find Kevin on the Lean chat -- at https://leanprover.zulipchat.com (login required, -- real names preferred, be nice) -- Prove a theorem. Write a function. xenaproject.wordpress.com
91c323075fe752bac08a9e7117754bccb52fe74c
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/topology/algebra/group.lean
43aa2bcb7676c9d6eaf1df392e955379bbf698d9
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,634
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.pointwise import group_theory.quotient_group import topology.algebra.monoid import topology.homeomorph /-! # Theory of topological groups This file defines the following typeclasses: * `topological_group`, `topological_add_group`: multiplicative and additive topological groups, i.e., groups with continuous `(*)` and `(⁻¹)` / `(+)` and `(-)`; * `has_continuous_sub G` means that `G` has a continuous subtraction operation. There is an instance deducing `has_continuous_sub` from `topological_group` but we use a separate typeclass because, e.g., `ℕ` and `ℝ≥0` have continuous subtraction but are not additive groups. We also define `homeomorph` versions of several `equiv`s: `homeomorph.mul_left`, `homeomorph.mul_right`, `homeomorph.inv`, and prove a few facts about neighbourhood filters in groups. ## Tags topological space, group, topological group -/ open classical set filter topological_space function open_locale classical topological_space filter pointwise universes u v w x variables {α : Type u} {β : Type v} {G : Type w} {H : Type x} section continuous_mul_group /-! ### Groups with continuous multiplication In this section we prove a few statements about groups with continuous `(*)`. -/ variables [topological_space G] [group G] [has_continuous_mul G] /-- Multiplication from the left in a topological group as a homeomorphism. -/ @[to_additive "Addition from the left in a topological additive group as a homeomorphism."] protected def homeomorph.mul_left (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_const.mul continuous_id, continuous_inv_fun := continuous_const.mul continuous_id, .. equiv.mul_left a } @[simp, to_additive] lemma homeomorph.coe_mul_left (a : G) : ⇑(homeomorph.mul_left a) = (*) a := rfl @[to_additive] lemma homeomorph.mul_left_symm (a : G) : (homeomorph.mul_left a).symm = homeomorph.mul_left a⁻¹ := by { ext, refl } @[to_additive] lemma is_open_map_mul_left (a : G) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map @[to_additive] lemma is_closed_map_mul_left (a : G) : is_closed_map (λ x, a * x) := (homeomorph.mul_left a).is_closed_map /-- Multiplication from the right in a topological group as a homeomorphism. -/ @[to_additive "Addition from the right in a topological additive group as a homeomorphism."] protected def homeomorph.mul_right (a : G) : G ≃ₜ G := { continuous_to_fun := continuous_id.mul continuous_const, continuous_inv_fun := continuous_id.mul continuous_const, .. equiv.mul_right a } @[to_additive] lemma is_open_map_mul_right (a : G) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map @[to_additive] lemma is_closed_map_mul_right (a : G) : is_closed_map (λ x, x * a) := (homeomorph.mul_right a).is_closed_map @[to_additive] lemma is_open_map_div_right (a : G) : is_open_map (λ x, x / a) := by simpa only [div_eq_mul_inv] using is_open_map_mul_right (a⁻¹) @[to_additive] lemma is_closed_map_div_right (a : G) : is_closed_map (λ x, x / a) := by simpa only [div_eq_mul_inv] using is_closed_map_mul_right (a⁻¹) @[to_additive] lemma discrete_topology_of_open_singleton_one (h : is_open ({1} : set G)) : discrete_topology G := begin rw ← singletons_open_iff_discrete, intro g, suffices : {g} = (λ (x : G), g⁻¹ * x) ⁻¹' {1}, { rw this, exact (continuous_mul_left (g⁻¹)).is_open_preimage _ h, }, simp only [mul_one, set.preimage_mul_left_singleton, eq_self_iff_true, inv_inv, set.singleton_eq_singleton_iff], end end continuous_mul_group section topological_group /-! ### Topological groups A topological group is a group in which the multiplication and inversion operations are continuous. Topological additive groups are defined in the same way. Equivalently, we can require that the division operation `λ x y, x * y⁻¹` (resp., subtraction) is continuous. -/ /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (G : Type u) [topological_space G] [add_group G] extends has_continuous_add G : Prop := (continuous_neg : continuous (λa:G, -a)) /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ @[to_additive] class topological_group (G : Type*) [topological_space G] [group G] extends has_continuous_mul G : Prop := (continuous_inv : continuous (has_inv.inv : G → G)) variables [topological_space G] [group G] [topological_group G] export topological_group (continuous_inv) export topological_add_group (continuous_neg) @[to_additive] lemma continuous_on_inv {s : set G} : continuous_on has_inv.inv s := continuous_inv.continuous_on @[to_additive] lemma continuous_within_at_inv {s : set G} {x : G} : continuous_within_at has_inv.inv s x := continuous_inv.continuous_within_at @[to_additive] lemma continuous_at_inv {x : G} : continuous_at has_inv.inv x := continuous_inv.continuous_at @[to_additive] lemma tendsto_inv (a : G) : tendsto has_inv.inv (𝓝 a) (𝓝 (a⁻¹)) := continuous_at_inv /-- If a function converges to a value in a multiplicative topological group, then its inverse converges to the inverse of this value. For the version in normed fields assuming additionally that the limit is nonzero, use `tendsto.inv'`. -/ @[to_additive] lemma filter.tendsto.inv {f : α → G} {l : filter α} {y : G} (h : tendsto f l (𝓝 y)) : tendsto (λ x, (f x)⁻¹) l (𝓝 y⁻¹) := (continuous_inv.tendsto y).comp h variables [topological_space α] {f : α → G} {s : set α} {x : α} @[continuity, to_additive] lemma continuous.inv (hf : continuous f) : continuous (λx, (f x)⁻¹) := continuous_inv.comp hf attribute [continuity] continuous.neg -- TODO @[to_additive] lemma continuous_on.inv (hf : continuous_on f s) : continuous_on (λx, (f x)⁻¹) s := continuous_inv.comp_continuous_on hf @[to_additive] lemma continuous_within_at.inv (hf : continuous_within_at f s x) : continuous_within_at (λ x, (f x)⁻¹) s x := hf.inv @[instance, to_additive] instance [topological_space H] [group H] [topological_group H] : topological_group (G × H) := { continuous_inv := continuous_inv.prod_map continuous_inv } @[to_additive] instance pi.topological_group {C : β → Type*} [∀ b, topological_space (C b)] [∀ b, group (C b)] [∀ b, topological_group (C b)] : topological_group (Π b, C b) := { continuous_inv := continuous_pi (λ i, (continuous_apply i).inv) } variable (G) /-- Inversion in a topological group as a homeomorphism. -/ @[to_additive "Negation in a topological group as a homeomorphism."] protected def homeomorph.inv : G ≃ₜ G := { continuous_to_fun := continuous_inv, continuous_inv_fun := continuous_inv, .. equiv.inv G } @[to_additive] lemma nhds_one_symm : comap has_inv.inv (𝓝 (1 : G)) = 𝓝 (1 : G) := ((homeomorph.inv G).comap_nhds_eq _).trans (congr_arg nhds one_inv) /-- The map `(x, y) ↦ (x, xy)` as a homeomorphism. This is a shear mapping. -/ @[to_additive "The map `(x, y) ↦ (x, x + y)` as a homeomorphism. This is a shear mapping."] protected def homeomorph.shear_mul_right : G × G ≃ₜ G × G := { continuous_to_fun := continuous_fst.prod_mk continuous_mul, continuous_inv_fun := continuous_fst.prod_mk $ continuous_fst.inv.mul continuous_snd, .. equiv.prod_shear (equiv.refl _) equiv.mul_left } @[simp, to_additive] lemma homeomorph.shear_mul_right_coe : ⇑(homeomorph.shear_mul_right G) = λ z : G × G, (z.1, z.1 * z.2) := rfl @[simp, to_additive] lemma homeomorph.shear_mul_right_symm_coe : ⇑(homeomorph.shear_mul_right G).symm = λ z : G × G, (z.1, z.1⁻¹ * z.2) := rfl variable {G} @[to_additive] lemma inv_closure (s : set G) : (closure s)⁻¹ = closure s⁻¹ := (homeomorph.inv G).preimage_closure s /-- The (topological-space) closure of a subgroup of a space `M` with `has_continuous_mul` is itself a subgroup. -/ @[to_additive "The (topological-space) closure of an additive subgroup of a space `M` with `has_continuous_add` is itself an additive subgroup."] def subgroup.topological_closure (s : subgroup G) : subgroup G := { carrier := closure (s : set G), inv_mem' := λ g m, by simpa [←mem_inv, inv_closure] using m, ..s.to_submonoid.topological_closure } @[simp, to_additive] lemma subgroup.topological_closure_coe {s : subgroup G} : (s.topological_closure : set G) = closure s := rfl @[to_additive] instance subgroup.topological_closure_topological_group (s : subgroup G) : topological_group (s.topological_closure) := { continuous_inv := begin apply continuous_induced_rng, change continuous (λ p : s.topological_closure, (p : G)⁻¹), continuity, end ..s.to_submonoid.topological_closure_has_continuous_mul} @[to_additive] lemma subgroup.subgroup_topological_closure (s : subgroup G) : s ≤ s.topological_closure := subset_closure @[to_additive] lemma subgroup.is_closed_topological_closure (s : subgroup G) : is_closed (s.topological_closure : set G) := by convert is_closed_closure @[to_additive] lemma subgroup.topological_closure_minimal (s : subgroup G) {t : subgroup G} (h : s ≤ t) (ht : is_closed (t : set G)) : s.topological_closure ≤ t := closure_minimal h ht @[to_additive] lemma dense_range.topological_closure_map_subgroup [group H] [topological_space H] [topological_group H] {f : G →* H} (hf : continuous f) (hf' : dense_range f) {s : subgroup G} (hs : s.topological_closure = ⊤) : (s.map f).topological_closure = ⊤ := begin rw set_like.ext'_iff at hs ⊢, simp only [subgroup.topological_closure_coe, subgroup.coe_top, ← dense_iff_closure_eq] at hs ⊢, exact hf'.dense_image hf hs end @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv {s : set G} (hs : s ∈ 𝓝 (1 : G)) : ∃ V ∈ 𝓝 (1 : G), ∀ (v ∈ V) (w ∈ V), v / w ∈ s := have ((λp : G × G, p.1 * p.2⁻¹) ⁻¹' s) ∈ 𝓝 ((1, 1) : G × G), from continuous_at_fst.mul continuous_at_snd.inv (by simpa), by simpa only [div_eq_mul_inv, nhds_prod_eq, mem_prod_self_iff, prod_subset_iff, mem_preimage] using this @[to_additive] lemma nhds_translation_mul_inv (x : G) : comap (λ y : G, y * x⁻¹) (𝓝 1) = 𝓝 x := ((homeomorph.mul_right x⁻¹).comap_nhds_eq 1).trans $ show 𝓝 (1 * x⁻¹⁻¹) = 𝓝 x, by simp @[simp, to_additive] lemma map_mul_left_nhds (x y : G) : map ((*) x) (𝓝 y) = 𝓝 (x * y) := (homeomorph.mul_left x).map_nhds_eq y @[to_additive] lemma map_mul_left_nhds_one (x : G) : map ((*) x) (𝓝 1) = 𝓝 x := by simp @[to_additive] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} (tg : @topological_group G t _) (tg' : @topological_group G t' _) (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] @[to_additive] lemma topological_group.of_nhds_aux {G : Type*} [group G] [topological_space G] (hinv : tendsto (λ (x : G), x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ (x₀ : G), 𝓝 x₀ = map (λ (x : G), x₀ * x) (𝓝 1)) (hconj : ∀ (x₀ : G), map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) ≤ 𝓝 1) : continuous (λ x : G, x⁻¹) := begin rw continuous_iff_continuous_at, rintros x₀, have key : (λ x, (x₀*x)⁻¹) = (λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹) ∘ (λ x, x⁻¹), by {ext ; simp[mul_assoc] }, calc map (λ x, x⁻¹) (𝓝 x₀) = map (λ x, x⁻¹) (map (λ x, x₀*x) $ 𝓝 1) : by rw hleft ... = map (λ x, (x₀*x)⁻¹) (𝓝 1) : by rw filter.map_map ... = map (((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) ∘ (λ x, x⁻¹)) (𝓝 1) : by rw key ... = map ((λ x, x₀⁻¹*x) ∘ (λ x, x₀*x*x₀⁻¹)) _ : by rw ← filter.map_map ... ≤ map ((λ x, x₀⁻¹ * x) ∘ λ x, x₀ * x * x₀⁻¹) (𝓝 1) : map_mono hinv ... = map (λ x, x₀⁻¹ * x) (map (λ x, x₀ * x * x₀⁻¹) (𝓝 1)) : filter.map_map ... ≤ map (λ x, x₀⁻¹ * x) (𝓝 1) : map_mono (hconj x₀) ... = 𝓝 x₀⁻¹ : (hleft _).symm end @[to_additive] lemma topological_group.of_nhds_one' {G : Type u} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : topological_group G := begin refine { continuous_mul := (has_continuous_mul.of_nhds_one hmul hleft hright).continuous_mul, continuous_inv := topological_group.of_nhds_aux hinv hleft _ }, intros x₀, suffices : map (λ (x : G), x₀ * x * x₀⁻¹) (𝓝 1) = 𝓝 1, by simp [this, le_refl], rw [show (λ x, x₀ * x * x₀⁻¹) = (λ x, x₀ * x) ∘ λ x, x*x₀⁻¹, by {ext, simp [mul_assoc] }, ← filter.map_map, ← hright, hleft x₀⁻¹, filter.map_map], convert map_id, ext, simp end @[to_additive] lemma topological_group.of_nhds_one {G : Type u} [group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hconj : ∀ x₀ : G, tendsto (λ x, x₀*x*x₀⁻¹) (𝓝 1) (𝓝 1)) : topological_group G := { continuous_mul := begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) = ((λ x, x₀*y₀*x) ∘ (uncurry (*)) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id)), by { ext, simp [uncurry, prod.map, mul_assoc] }, specialize hconj y₀⁻¹, rw inv_inv at hconj, calc map (λ (p : G × G), p.1 * p.2) (𝓝 (x₀, y₀)) = map (λ (p : G × G), p.1 * p.2) ((𝓝 x₀) ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : G × G), x₀ * p.1 * (y₀ * p.2)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [hleft x₀, hleft y₀, prod_map_map_eq, filter.map_map] ... = map (((λ x, x₀*y₀*x) ∘ (uncurry (*))) ∘ (prod.map (λ x, y₀⁻¹*x*y₀) id))((𝓝 1) ×ᶠ (𝓝 1)) : by rw key ... = map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((map (λ x, y₀⁻¹*x*y₀) $ 𝓝 1) ×ᶠ (𝓝 1)) : by rw [← filter.map_map, ← prod_map_map_eq', map_id] ... ≤ map ((λ x, x₀*y₀*x) ∘ (uncurry (*))) ((𝓝 1) ×ᶠ (𝓝 1)) : map_mono (filter.prod_mono hconj $ le_refl _) ... = map (λ x, x₀*y₀*x) (map (uncurry (*)) ((𝓝 1) ×ᶠ (𝓝 1))) : by rw filter.map_map ... ≤ map (λ x, x₀*y₀*x) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : (hleft _).symm end, continuous_inv := topological_group.of_nhds_aux hinv hleft hconj} @[to_additive] lemma topological_group.of_comm_of_nhds_one {G : Type u} [comm_group G] [topological_space G] (hmul : tendsto (uncurry ((*) : G → G → G)) ((𝓝 1) ×ᶠ 𝓝 1) (𝓝 1)) (hinv : tendsto (λ x : G, x⁻¹) (𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : G, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : topological_group G := topological_group.of_nhds_one hmul hinv hleft (by simpa using tendsto_id) end topological_group section quotient_topological_group variables [topological_space G] [group G] [topological_group G] (N : subgroup G) (n : N.normal) @[to_additive] instance {G : Type*} [group G] [topological_space G] (N : subgroup G) : topological_space (quotient_group.quotient N) := quotient.topological_space open quotient_group @[to_additive] lemma quotient_group.is_open_map_coe : is_open_map (coe : G → quotient N) := begin intros s s_op, change is_open ((coe : G → quotient N) ⁻¹' (coe '' s)), rw quotient_group.preimage_image_coe N s, exact is_open_Union (λ n, (continuous_mul_right _).is_open_preimage s s_op) end @[to_additive] instance topological_group_quotient [N.normal] : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : G → quotient N) ∘ (λ (p : G × G), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, have quot : quotient_map (λ p : G × G, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact (quotient_group.is_open_map_coe N).prod (quotient_group.is_open_map_coe N) }, { exact continuous_quot_mk.prod_map continuous_quot_mk }, { exact (surjective_quot_mk _).prod_map (surjective_quot_mk _) } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin have : continuous ((coe : G → quotient N) ∘ (λ (a : G), a⁻¹)) := continuous_quot_mk.comp continuous_inv, convert continuous_quotient_lift _ this, end } attribute [instance] topological_add_group_quotient end quotient_topological_group /-- A typeclass saying that `λ p : G × G, p.1 - p.2` is a continuous function. This property automatically holds for topological additive groups but it also holds, e.g., for `ℝ≥0`. -/ class has_continuous_sub (G : Type*) [topological_space G] [has_sub G] : Prop := (continuous_sub : continuous (λ p : G × G, p.1 - p.2)) @[priority 100] -- see Note [lower instance priority] instance topological_add_group.to_has_continuous_sub [topological_space G] [add_group G] [topological_add_group G] : has_continuous_sub G := ⟨by { simp only [sub_eq_add_neg], exact continuous_fst.add continuous_snd.neg }⟩ export has_continuous_sub (continuous_sub) section has_continuous_sub variables [topological_space G] [has_sub G] [has_continuous_sub G] lemma filter.tendsto.sub {f g : α → G} {l : filter α} {a b : G} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) : tendsto (λx, f x - g x) l (𝓝 (a - b)) := (continuous_sub.tendsto (a, b)).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → G} {s : set α} {x : α} @[continuity] lemma continuous.sub (hf : continuous f) (hg : continuous g) : continuous (λ x, f x - g x) := continuous_sub.comp (hf.prod_mk hg : _) lemma continuous_within_at.sub (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.sub hg lemma continuous_on.sub (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x - g x) s := λ x hx, (hf x hx).sub (hg x hx) end has_continuous_sub lemma nhds_translation [topological_space G] [add_group G] [topological_add_group G] (x : G) : comap (λy:G, y - x) (𝓝 0) = 𝓝 x := by simpa only [sub_eq_add_neg] using nhds_translation_add_neg x /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (G : Type u) extends add_comm_group G := (Z [] : filter G) (zero_Z : pure 0 ≤ Z) (sub_Z : tendsto (λp:G×G, p.1 - p.2) (Z ×ᶠ Z) Z) namespace add_group_with_zero_nhd variables (G) [add_group_with_zero_nhd G] local notation `Z` := add_group_with_zero_nhd.Z @[priority 100] -- see Note [lower instance priority] instance : topological_space G := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z G) variables {G} lemma neg_Z : tendsto (λa:G, - a) (Z G) (Z G) := have tendsto (λa, (0:G)) (Z G) (Z G), by refine le_trans (assume h, _) zero_Z; simp [univ_mem'] {contextual := tt}, have tendsto (λa:G, 0 - a) (Z G) (Z G), from sub_Z.comp (tendsto.prod_mk this tendsto_id), by simpa lemma add_Z : tendsto (λp:G×G, p.1 + p.2) (Z G ×ᶠ Z G) (Z G) := suffices tendsto (λp:G×G, p.1 - -p.2) (Z G ×ᶠ Z G) (Z G), by simpa [sub_eq_add_neg], sub_Z.comp (tendsto.prod_mk tendsto_fst (neg_Z.comp tendsto_snd)) lemma exists_Z_half {s : set G} (hs : s ∈ Z G) : ∃ V ∈ Z G, ∀ (v ∈ V) (w ∈ V), v + w ∈ s := begin have : ((λa:G×G, a.1 + a.2) ⁻¹' s) ∈ Z G ×ᶠ Z G := add_Z (by simpa using hs), rcases mem_prod_self_iff.1 this with ⟨V, H, H'⟩, exact ⟨V, H, prod_subset_iff.1 H'⟩ end lemma nhds_eq (a : G) : 𝓝 a = map (λx, x + a) (Z G) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:G) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:G, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 t0 b hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z G).sets_of_superset ht (assume x hxt, _), simpa [add_assoc] using eqt _ hxt _ hb } end) lemma nhds_zero_eq_Z : 𝓝 0 = Z G := by simp [nhds_eq]; exact filter.map_id @[priority 100] -- see Note [lower instance priority] instance : has_continuous_add G := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, (a + b) + x) ∘ (λp:G×G,p.1 + p.2)) (Z G ×ᶠ Z G) (map (λx:G, (a + b) + x) (Z G)), { simpa [(∘), add_comm, add_left_comm] }, exact tendsto_map.comp add_Z end ⟩ @[priority 100] -- see Note [lower instance priority] instance : topological_add_group G := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:G, x - a) ∘ (λx:G, -x)) (Z G) (map (λx:G, x - a) (Z G)), { simpa [(∘), add_comm, sub_eq_add_neg] using this }, exact tendsto_map.comp neg_Z end⟩ end add_group_with_zero_nhd section filter_mul section variables [topological_space G] [group G] [topological_group G] @[to_additive] lemma is_open.mul_left {s t : set G} : is_open t → is_open (s * t) := λ ht, begin have : ∀a, is_open ((λ (x : G), a * x) '' t) := assume a, is_open_map_mul_left a t ht, rw ← Union_mul_left_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end @[to_additive] lemma is_open.mul_right {s t : set G} : is_open s → is_open (s * t) := λ hs, begin have : ∀a, is_open ((λ (x : G), x * a) '' s), assume a, apply is_open_map_mul_right, exact hs, rw ← Union_mul_right_image, exact is_open_Union (λa, is_open_Union $ λha, this _), end variables (G) lemma topological_group.t1_space (h : @is_closed G _ {1}) : t1_space G := ⟨assume x, by { convert is_closed_map_mul_right x _ h, simp }⟩ lemma topological_group.regular_space [t1_space G] : regular_space G := ⟨assume s a hs ha, let f := λ p : G × G, p.1 * (p.2)⁻¹ in have hf : continuous f := continuous_fst.mul continuous_snd.inv, -- a ∈ -s implies f (a, 1) ∈ -s, and so (a, 1) ∈ f⁻¹' (-s); -- and so can find t₁ t₂ open such that a ∈ t₁ × t₂ ⊆ f⁻¹' (-s) let ⟨t₁, t₂, ht₁, ht₂, a_mem_t₁, one_mem_t₂, t_subset⟩ := is_open_prod_iff.1 ((is_open_compl_iff.2 hs).preimage hf) a (1:G) (by simpa [f]) in begin use [s * t₂, ht₂.mul_left, λ x hx, ⟨x, 1, hx, one_mem_t₂, mul_one _⟩], rw [nhds_within, inf_principal_eq_bot, mem_nhds_iff], refine ⟨t₁, _, ht₁, a_mem_t₁⟩, rintros x hx ⟨y, z, hy, hz, yz⟩, have : x * z⁻¹ ∈ sᶜ := (prod_subset_iff.1 t_subset) x hx z hz, have : x * z⁻¹ ∈ s, rw ← yz, simpa, contradiction end⟩ local attribute [instance] topological_group.regular_space lemma topological_group.t2_space [t1_space G] : t2_space G := regular_space.t2_space G end section /-! Some results about an open set containing the product of two sets in a topological group. -/ variables [topological_space G] [group G] [topological_group G] /-- Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `1` such that `KV ⊆ U`. -/ @[to_additive "Given a compact set `K` inside an open set `U`, there is a open neighborhood `V` of `0` such that `K + V ⊆ U`."] lemma compact_open_separated_mul {K U : set G} (hK : is_compact K) (hU : is_open U) (hKU : K ⊆ U) : ∃ V : set G, is_open V ∧ (1 : G) ∈ V ∧ K * V ⊆ U := begin let W : G → set G := λ x, (λ y, x * y) ⁻¹' U, have h1W : ∀ x, is_open (W x) := λ x, hU.preimage (continuous_mul_left x), have h2W : ∀ x ∈ K, (1 : G) ∈ W x := λ x hx, by simp only [mem_preimage, mul_one, hKU hx], choose V hV using λ x : K, exists_open_nhds_one_mul_subset ((h1W x).mem_nhds (h2W x.1 x.2)), let X : K → set G := λ x, (λ y, (x : G)⁻¹ * y) ⁻¹' (V x), obtain ⟨t, ht⟩ : ∃ t : finset ↥K, K ⊆ ⋃ i ∈ t, X i, { refine hK.elim_finite_subcover X (λ x, (hV x).1.preimage (continuous_mul_left x⁻¹)) _, intros x hx, rw [mem_Union], use ⟨x, hx⟩, rw [mem_preimage], convert (hV _).2.1, simp only [mul_left_inv, subtype.coe_mk] }, refine ⟨⋂ x ∈ t, V x, is_open_bInter (finite_mem_finset _) (λ x hx, (hV x).1), _, _⟩, { simp only [mem_Inter], intros x hx, exact (hV x).2.1 }, rintro _ ⟨x, y, hx, hy, rfl⟩, simp only [mem_Inter] at hy, have := ht hx, simp only [mem_Union, mem_preimage] at this, rcases this with ⟨z, h1z, h2z⟩, have : (z : G)⁻¹ * x * y ∈ W z := (hV z).2.2 (mul_mem_mul h2z (hy z h1z)), rw [mem_preimage] at this, convert this using 1, simp only [mul_assoc, mul_inv_cancel_left] end /-- A compact set is covered by finitely many left multiplicative translates of a set with non-empty interior. -/ @[to_additive "A compact set is covered by finitely many left additive translates of a set with non-empty interior."] lemma compact_covered_by_mul_left_translates {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ t : finset G, K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V := begin obtain ⟨t, ht⟩ : ∃ t : finset G, K ⊆ ⋃ x ∈ t, interior (((*) x) ⁻¹' V), { refine hK.elim_finite_subcover (λ x, interior $ ((*) x) ⁻¹' V) (λ x, is_open_interior) _, cases hV with g₀ hg₀, refine λ g hg, mem_Union.2 ⟨g₀ * g⁻¹, _⟩, refine preimage_interior_subset_interior_preimage (continuous_const.mul continuous_id) _, rwa [mem_preimage, inv_mul_cancel_right] }, exact ⟨t, subset.trans ht $ bUnion_subset_bUnion_right $ λ g hg, interior_subset⟩ end /-- Every locally compact separable topological group is σ-compact. Note: this is not true if we drop the topological group hypothesis. -/ @[priority 100, to_additive separable_locally_compact_add_group.sigma_compact_space] instance separable_locally_compact_group.sigma_compact_space [separable_space G] [locally_compact_space G] : sigma_compact_space G := begin obtain ⟨L, hLc, hL1⟩ := exists_compact_mem_nhds (1 : G), refine ⟨⟨λ n, (λ x, x * dense_seq G n) ⁻¹' L, _, _⟩⟩, { intro n, exact (homeomorph.mul_right _).compact_preimage.mpr hLc }, { refine Union_eq_univ_iff.2 (λ x, _), obtain ⟨_, ⟨n, rfl⟩, hn⟩ : (range (dense_seq G) ∩ (λ y, x * y) ⁻¹' L).nonempty, { rw [← (homeomorph.mul_left x).apply_symm_apply 1] at hL1, exact (dense_range_dense_seq G).inter_nhds_nonempty ((homeomorph.mul_left x).continuous.continuous_at $ hL1) }, exact ⟨n, hn⟩ } end end section variables [topological_space G] [comm_group G] [topological_group G] @[to_additive] lemma nhds_mul (x y : G) : 𝓝 (x * y) = 𝓝 x * 𝓝 y := filter_eq $ set.ext $ assume s, begin rw [← nhds_translation_mul_inv x, ← nhds_translation_mul_inv y, ← nhds_translation_mul_inv (x*y)], split, { rintros ⟨t, ht, ts⟩, rcases exists_nhds_one_split ht with ⟨V, V1, h⟩, refine ⟨(λa, a * x⁻¹) ⁻¹' V, (λa, a * y⁻¹) ⁻¹' V, ⟨V, V1, subset.refl _⟩, ⟨V, V1, subset.refl _⟩, _⟩, rintros a ⟨v, w, v_mem, w_mem, rfl⟩, apply ts, simpa [mul_comm, mul_assoc, mul_left_comm] using h (v * x⁻¹) v_mem (w * y⁻¹) w_mem }, { rintros ⟨a, c, ⟨b, hb, ba⟩, ⟨d, hd, dc⟩, ac⟩, refine ⟨b ∩ d, inter_mem hb hd, assume v, _⟩, simp only [preimage_subset_iff, mul_inv_rev, mem_preimage] at *, rintros ⟨vb, vd⟩, refine ac ⟨v * y⁻¹, y, _, _, _⟩, { rw ← mul_assoc _ _ _ at vb, exact ba _ vb }, { apply dc y, rw mul_right_inv, exact mem_of_mem_nhds hd }, { simp only [inv_mul_cancel_right] } } end /-- On a topological group, `𝓝 : G → filter G` can be promoted to a `mul_hom`. -/ @[to_additive "On an additive topological group, `𝓝 : G → filter G` can be promoted to an `add_hom`.", simps] def nhds_mul_hom : mul_hom G (filter G) := { to_fun := 𝓝, map_mul' := λ_ _, nhds_mul _ _ } end end filter_mul instance additive.topological_add_group {G} [h : topological_space G] [group G] [topological_group G] : @topological_add_group (additive G) h _ := { continuous_neg := @continuous_inv G _ _ _ } instance multiplicative.topological_group {G} [h : topological_space G] [add_group G] [topological_add_group G] : @topological_group (multiplicative G) h _ := { continuous_inv := @continuous_neg G _ _ _ } namespace units variables [monoid α] [topological_space α] [has_continuous_mul α] instance : topological_group (units α) := { continuous_inv := continuous_induced_rng ((continuous_unop.comp (continuous_snd.comp (@continuous_embed_product α _ _))).prod_mk (continuous_op.comp continuous_coe)) } end units
3488f5ef837de55350e8c1dbc8c9f607f4b7a758
9cba98daa30c0804090f963f9024147a50292fa0
/old/geom3d_timestamped.lean
72b32da59dfe143b93deb97950eb83968d32a70e
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
28,963
lean
import ..geom.geom3d open_locale affine section foo universes u #check add_maps abbreviation geom3d_frame := (mk_prod_spc (mk_prod_spc geom1d_std_space geom1d_std_space) geom1d_std_space).frame_type abbreviation geom3d_space (f : geom3d_frame) := spc real_scalar f noncomputable def geom3d_std_frame := (mk_prod_spc (mk_prod_spc geom1d_std_space geom1d_std_space) geom1d_std_space).frame noncomputable def geom3d_std_space : geom3d_space geom3d_std_frame := (mk_prod_spc (mk_prod_spc geom1d_std_space geom1d_std_space) geom1d_std_space) --@[reducible, elab_with_expected_type] /- def geom3d_std_frame : geom3d_frame := (let eqpf : (add_maps (add_maps (λi : fin 1, LENGTH) (λi : fin 1, LENGTH)) (λi : fin 1, LENGTH)) = LENGTH := by simp * in (eq.rec_on eqpf (mk_prod_spc (mk_prod_spc geom1d_std_space geom1d_std_space) geom1d_std_space).fm) : fm real_scalar 3 LENGTH) -/ /- def ppp := mk_prod_spc (mk_prod_spc geom1d_std_space geom1d_std_space) geom1d_std_space #check (merge_prod_fm (merge_prod_fm geom1d_std_frame geom1d_std_frame) geom1d_std_frame) example : ppp.fm = geom3d_std_frame := #check spc.rec_on #check @spc.rec_on real_scalar _ _ (λ dim, λ id_vec, λf, λ sp,) #check eq.rec #check homogeneous def geom3d_std_space : geom3d_space (_ : geom3d_frame) := begin let v : spc real_scalar (_ : fm real_scalar (1 + 1 + 1) (add_maps (add_maps ↑LENGTH ↑LENGTH) ↑LENGTH)) := mk_prod_spc (mk_prod_spc geom1d_std_space geom1d_std_space) geom1d_std_space, let f := v.fm, let : v.frame_type = fm real_scalar (1 + 1 + 1) (add_maps (add_maps ↑LENGTH ↑LENGTH) ↑LENGTH) := rfl, let : v.frame_type = geom3d_frame := begin let eqf : (add_maps (add_maps (λi : fin 1, LENGTH) (λi : fin 1, LENGTH)) (λi : fin 1, LENGTH)) = (λ i:fin 3, LENGTH) := by simp *, simp *, refl end, let h : fm real_scalar (1 + 1 + 1) (add_maps (add_maps ↑LENGTH ↑LENGTH) ↑LENGTH) = geom3d_frame := begin simp *, refl end, let fm_ := v.fm, simp * at v, let fm_g : geom3d_frame := eq.rec fm_ (begin end), let vg : geom3d_space geom3d_frame := eq.rec v (by cc) let : v.fm = geom3d_std_frame := rfl, exact v, end -/ structure position3d {f : geom3d_frame} (s : geom3d_space f ) extends point s @[ext] lemma position3d.ext : ∀ {f : geom3d_frame} {s : geom3d_space f } (x y : position3d s), x.to_point = y.to_point → x = y := begin intros f s x y e, cases x, cases y, simp *, have h₁ : ({to_point := x} : position3d s).to_point = x := rfl, simp [h₁] at e, exact e end noncomputable def position3d.coords {f : geom3d_frame} {s : geom3d_space f } (t :position3d s) := t.to_point.coords noncomputable def position3d.x {f : geom3d_frame} {s : geom3d_space f } (t :position3d s) : real_scalar := (t.to_point.coords 0).coord noncomputable def position3d.y {f : geom3d_frame} {s : geom3d_space f } (t :position3d s) : real_scalar := (t.to_point.coords 1).coord noncomputable def position3d.z {f : geom3d_frame} {s : geom3d_space f } (t :position3d s) : real_scalar := (t.to_point.coords 2).coord @[simp] def mk_position3d' {f : geom3d_frame} (s : geom3d_space f ) (p : point s) : position3d s := position3d.mk p @[simp] noncomputable def mk_position3d {f : geom3d_frame} (s : geom3d_space f ) (k₁ k₂ k₃ : real_scalar) : position3d s := position3d.mk (mk_point s ⟨[k₁,k₂,k₃],rfl⟩) @[simp] noncomputable def mk_position3d'' {f1 f2 f3 : geom1d_frame } { s1 : geom1d_space f1} {s2 : geom1d_space f2} { s3 : geom1d_space f3} (p1 : position1d s1) (p2 : position1d s2) (p3 : position1d s3 ) : position3d (mk_prod_spc (mk_prod_spc s1 s2) s3) := ⟨mk_point_prod (mk_point_prod p1.to_point p2.to_point) p3.to_point⟩ structure displacement3d {f : geom3d_frame} (s : geom3d_space f ) extends vectr s @[ext] lemma displacement3d.ext : ∀ {f : geom3d_frame} {s : geom3d_space f } (x y : displacement3d s), x.to_vectr = y.to_vectr → x = y := begin intros f s x y e, cases x, cases y, simp *, have h₁ : ({to_vectr := x} : displacement3d s).to_vectr = x := rfl, simp [h₁] at e, exact e end def displacement3d.frame {f : geom3d_frame} {s : geom3d_space f } (d :displacement3d s) := f noncomputable def displacement3d.coords {f : geom3d_frame} {s : geom3d_space f } (d :displacement3d s) := d.to_vectr.coords @[simp] def mk_displacement3d' {f : geom3d_frame} (s : geom3d_space f ) (v : vectr s) : displacement3d s := displacement3d.mk v @[simp] noncomputable def mk_displacement3d {f : geom3d_frame} (s : geom3d_space f ) (k₁ k₂ k₃ : real_scalar) : displacement3d s := displacement3d.mk (mk_vectr s ⟨[k₁,k₂,k₃],rfl⟩) @[simp] noncomputable def mk_displacement3d'' {f1 f2 f3 : geom1d_frame } { s1 : geom1d_space f1} {s2 : geom1d_space f2} { s3 : geom1d_space f3} (p1 : displacement1d s1) (p2 : displacement1d s2) (p3 : displacement1d s3 ) : displacement3d (mk_prod_spc (mk_prod_spc s1 s2) s3) := ⟨mk_vectr_prod (mk_vectr_prod p1.to_vectr p2.to_vectr) p3.to_vectr⟩ @[simp] noncomputable def mk_geom3d_frame {parent : geom3d_frame} {s : spc real_scalar parent} (p : position3d s) (v0 : displacement3d s) (v1 : displacement3d s) (v2 : displacement3d s) : geom3d_frame := (mk_frame p.to_point ⟨(λi, if i = 0 then v0.to_vectr else if i = 1 then v1.to_vectr else v2.to_vectr),sorry,sorry⟩) @[simp] noncomputable def mk_geom3d_space (fr : geom3d_frame) := mk_space fr end foo section bar /- ************************************* Instantiate module real_scalar (vector real_scalar) ************************************* -/ namespace geom3d variables {f : geom3d_frame} {s : geom3d_space f } @[simp] noncomputable def add_displacement3d_displacement3d (v3 v2 : displacement3d s) : displacement3d s := mk_displacement3d' s (v3.to_vectr + v2.to_vectr) @[simp] noncomputable def smul_displacement3d (k : real_scalar) (v : displacement3d s) : displacement3d s := mk_displacement3d' s (k • v.to_vectr) @[simp] noncomputable def neg_displacement3d (v : displacement3d s) : displacement3d s := mk_displacement3d' s ((-1 : real_scalar) • v.to_vectr) @[simp] noncomputable def sub_displacement3d_displacement3d (v3 v2 : displacement3d s) : displacement3d s := -- v3-v2 add_displacement3d_displacement3d v3 (neg_displacement3d v2) noncomputable instance has_add_displacement3d : has_add (displacement3d s) := ⟨ add_displacement3d_displacement3d ⟩ lemma add_assoc_displacement3d : ∀ a b c : displacement3d s, a + b + c = a + (b + c) := begin intros, ext, dsimp only [has_add.add], dsimp only [add_displacement3d_displacement3d, has_add.add], dsimp only [add_vectr_vectr, has_add.add], dsimp only [add_vec_vec, mk_displacement3d', mk_vectr'], simp only [add_assoc], end noncomputable instance add_semigroup_displacement3d : add_semigroup (displacement3d s) := ⟨ add_displacement3d_displacement3d, add_assoc_displacement3d⟩ @[simp] noncomputable def displacement3d_zero := mk_displacement3d s 0 0 0 noncomputable instance : inhabited (displacement3d s) := ⟨displacement3d_zero⟩ noncomputable instance has_zero_displacement3d : has_zero (displacement3d s) := ⟨displacement3d_zero⟩ lemma zero_add_displacement3d : ∀ a : displacement3d s, 0 + a = a := begin intros, ext, dsimp only [has_zero.zero, has_add.add], dsimp only [add_displacement3d_displacement3d, displacement3d_zero, mk_displacement3d', mk_displacement3d, has_add.add], dsimp only [add_vectr_vectr, mk_vectr', mk_vectr, mk_vec_n, has_add.add], dsimp only [add_vec_vec, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le, zero_add], simp only [add_left_eq_self, list.nth_le], cases x' with x'', simp only [list.nth_le, zero_add], simp only [add_left_eq_self, list.nth_le], cases x'' with x''', simp only [list.nth_le, zero_add], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end lemma add_zero_displacement3d : ∀ a : displacement3d s, a + 0 = a := begin intros, ext, dsimp only [has_zero.zero, has_add.add], dsimp only [add_displacement3d_displacement3d, displacement3d_zero, mk_displacement3d', mk_displacement3d, has_add.add], dsimp only [add_vectr_vectr, mk_vectr', mk_vectr, mk_vec_n, has_add.add], dsimp only [add_vec_vec, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le, add_zero], simp only [add_left_eq_self, list.nth_le], cases x' with x'', simp only [list.nth_le, add_zero], simp only [add_left_eq_self, list.nth_le], cases x'' with x''', simp only [list.nth_le, add_zero], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end @[simp] noncomputable def nsmul_displacement3d : ℕ → (displacement3d s) → (displacement3d s) | nat.zero v := displacement3d_zero --| 3 v := v | (nat.succ n) v := (add_displacement3d_displacement3d) v (nsmul_displacement3d n v) noncomputable instance add_monoid_displacement3d : add_monoid (displacement3d s) := ⟨ -- add_semigroup add_displacement3d_displacement3d, add_assoc_displacement3d, -- has_zero displacement3d_zero, -- new structure @zero_add_displacement3d f s, add_zero_displacement3d, nsmul_displacement3d, begin admit end, begin admit end ⟩ noncomputable instance has_neg_displacement3d : has_neg (displacement3d s) := ⟨neg_displacement3d⟩ noncomputable instance has_sub_displacement3d : has_sub (displacement3d s) := ⟨ sub_displacement3d_displacement3d⟩ lemma sub_eq_add_neg_displacement3d : ∀ a b : displacement3d s, a - b = a + -b := begin intros,ext, refl, end noncomputable instance sub_neg_monoid_displacement3d : sub_neg_monoid (displacement3d s) := { neg := neg_displacement3d , ..(show add_monoid (displacement3d s), by apply_instance) } lemma add_left_neg_displacement3d : ∀ a : displacement3d s, -a + a = 0 := begin intros, ext, dsimp only [has_zero.zero, has_add.add, has_neg.neg], dsimp only [neg_displacement3d, has_scalar.smul], dsimp only [add_displacement3d_displacement3d, smul_vectr, has_add.add, has_scalar.smul], dsimp only [add_vectr_vectr, smul_vec, mk_displacement3d', mk_vectr', has_add.add], dsimp only [add_vec_vec], simp only [neg_mul_eq_neg_mul_symm, one_mul, mk_vectr, displacement3d_zero, mk_displacement3d, add_left_neg], dsimp only [mk_vec_n, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le], simp only [add_left_eq_self, list.nth_le], cases x' with x'', simp only [list.nth_le], simp only [add_left_eq_self, list.nth_le], cases x'' with x''', simp only [list.nth_le], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end noncomputable instance : add_group (displacement3d s) := { add_left_neg := begin exact add_left_neg_displacement3d, end, ..(show sub_neg_monoid (displacement3d s), by apply_instance), } lemma add_comm_displacement3d : ∀ a b : displacement3d s, a + b = b + a := begin intros, ext, dsimp only [has_add.add], dsimp only [add_displacement3d_displacement3d, has_add.add], dsimp only [add_vectr_vectr, has_add.add], dsimp only [add_vec_vec, mk_displacement3d', mk_vectr'], simp only [add_comm], end noncomputable instance add_comm_semigroup_displacement3d : add_comm_semigroup (displacement3d s) := ⟨ -- add_semigroup add_displacement3d_displacement3d, add_assoc_displacement3d, add_comm_displacement3d, ⟩ noncomputable instance add_comm_monoid_displacement3d : add_comm_monoid (displacement3d s) := { add_comm := begin exact add_comm_displacement3d end, ..(show add_monoid (displacement3d s), by apply_instance) } noncomputable instance has_scalar_displacement3d : has_scalar real_scalar (displacement3d s) := ⟨ smul_displacement3d, ⟩ lemma one_smul_displacement3d : ∀ b : displacement3d s, (1 : real_scalar) • b = b := begin intros, ext, dsimp only [has_scalar.smul], dsimp only [smul_displacement3d, has_scalar.smul], dsimp only [smul_vectr, has_scalar.smul], dsimp only [smul_vec, mk_displacement3d', mk_vectr'], simp only [one_mul], end lemma mul_smul_displacement3d : ∀ (x y : real_scalar) (b : displacement3d s), (x * y) • b = x • y • b := begin intros, cases b, ext, exact mul_assoc x y _, end noncomputable instance mul_action_displacement3d : mul_action real_scalar (displacement3d s) := ⟨ one_smul_displacement3d, mul_smul_displacement3d, ⟩ lemma smul_add_displacement3d : ∀(r : real_scalar) (x y : displacement3d s), r • (x + y) = r • x + r • y := begin intros, ext, dsimp only [has_scalar.smul, has_add.add], dsimp only [smul_displacement3d, add_displacement3d_displacement3d, has_scalar.smul, has_add.add], dsimp only [smul_vectr, add_vectr_vectr, has_scalar.smul, has_add.add], dsimp only [smul_vec, add_vec_vec, mk_displacement3d', mk_vectr'], simp only [distrib.left_distrib], refl, end lemma smul_zero_displacement3d : ∀(r : real_scalar), r • (0 : displacement3d s) = 0 := begin intros, ext, dsimp only [has_scalar.smul, has_zero.zero], dsimp only [smul_displacement3d, displacement3d_zero, has_scalar.smul], dsimp only [smul_vectr, has_scalar.smul], dsimp only [smul_vec, mk_displacement3d', mk_vectr', mk_displacement3d, mk_vectr, mk_vec_n, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le, mul_zero], simp only [list.nth_le], cases x' with x'', simp only [list.nth_le, mul_zero], simp only [list.nth_le], cases x'' with x''', simp only [list.nth_le, mul_zero], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end noncomputable instance distrib_mul_action_K_displacement3d : distrib_mul_action real_scalar (displacement3d s) := ⟨ smul_add_displacement3d, smul_zero_displacement3d, ⟩ -- renaming vs template due to clash with name "s" for prevailing variable lemma add_smul_displacement3d : ∀ (a b : real_scalar) (x : displacement3d s), (a + b) • x = a • x + b • x := begin intros, ext, exact right_distrib _ _ _, end lemma zero_smul_displacement3d : ∀ (x : displacement3d s), (0 : real_scalar) • x = 0 := begin intros, ext, dsimp only [has_scalar.smul, has_zero.zero], dsimp only [smul_displacement3d, displacement3d_zero, has_scalar.smul], dsimp only [smul_vectr, has_scalar.smul], dsimp only [smul_vec, mk_displacement3d', mk_vectr', mk_displacement3d, mk_vectr, mk_vec_n, mk_vec, vector.nth], cases x_1, dsimp only [fin.mk], cases x_1_val with x', simp only [list.nth_le, mul_eq_zero], apply or.inl, refl, simp only [list.nth_le], cases x' with x'', simp only [list.nth_le, mul_eq_zero], apply or.inl, refl, simp only [list.nth_le], cases x'' with x''', simp only [list.nth_le, mul_eq_zero], apply or.inl, refl, have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_1_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_1_property, dsimp only [has_le.le], exact x_1_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end noncomputable instance module_K_displacement3d : module real_scalar (displacement3d s) := ⟨ add_smul_displacement3d, zero_smul_displacement3d ⟩ noncomputable instance add_comm_group_displacement3d : add_comm_group (displacement3d s) := { add_comm := begin exact add_comm_displacement3d end, ..(show add_group (displacement3d s), by apply_instance) } noncomputable instance : module real_scalar (displacement3d s) := @geom3d.module_K_displacement3d f s /- ******************** *** Affine space *** ******************** -/ /- Affine operations -/ noncomputable instance : has_add (displacement3d s) := ⟨add_displacement3d_displacement3d⟩ noncomputable instance : has_zero (displacement3d s) := ⟨displacement3d_zero⟩ noncomputable instance : has_neg (displacement3d s) := ⟨neg_displacement3d⟩ /- Lemmas needed to implement affine space API -/ @[simp] noncomputable def sub_position3d_position3d {f : geom3d_frame} {s : geom3d_space f } (p3 p2 : position3d s) : displacement3d s := mk_displacement3d' s (p3.to_point -ᵥ p2.to_point) @[simp] noncomputable def add_position3d_displacement3d {f : geom3d_frame} {s : geom3d_space f } (p : position3d s) (v : displacement3d s) : position3d s := mk_position3d' s (v.to_vectr +ᵥ p.to_point) -- reorder assumes order is irrelevant @[simp] noncomputable def add_displacement3d_position3d {f : geom3d_frame} {s : geom3d_space f } (v : displacement3d s) (p : position3d s) : position3d s := mk_position3d' s (v.to_vectr +ᵥ p.to_point) --@[simp] --def aff_displacement3d_group_action : displacement3d s → position3d s → position3d s := add_displacement3d_position3d real_scalar noncomputable instance : has_vadd (displacement3d s) (position3d s) := ⟨add_displacement3d_position3d⟩ lemma zero_displacement3d_vadd'_a3 : ∀ p : position3d s, (0 : displacement3d s) +ᵥ p = p := begin intros, ext, dsimp only [has_vadd.vadd, has_zero.zero], dsimp only [add_displacement3d_position3d, displacement3d_zero, has_vadd.vadd], dsimp only [add_vectr_point, has_vadd.vadd], dsimp only [aff_vec_group_action, add_vec_pt, mk_position3d', mk_point', mk_displacement3d, mk_vectr, mk_vec_n, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le, add_zero], simp only [list.nth_le], cases x' with x'', simp only [list.nth_le, add_zero], simp only [list.nth_le], cases x'' with x''', simp only [list.nth_le, add_zero], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end lemma displacement3d_add_assoc'_a3 : ∀ (g3 g2 : displacement3d s) (p : position3d s), g3 +ᵥ (g2 +ᵥ p) = (g3 + g2) +ᵥ p := begin intros, ext, dsimp only [has_add.add, has_vadd.vadd], dsimp only [add_displacement3d_position3d, add_displacement3d_displacement3d, has_add.add, has_vadd.vadd], dsimp only [add_vectr_point, add_vectr_vectr, has_add.add, has_vadd.vadd], dsimp only [aff_vec_group_action, add_vec_vec, add_vec_pt, mk_position3d', mk_point', mk_displacement3d', mk_vectr'], simp only [add_assoc, add_right_inj], simp only [add_comm], end noncomputable instance displacement3d_add_action: add_action (displacement3d s) (position3d s) := ⟨ zero_displacement3d_vadd'_a3, begin let h0 := displacement3d_add_assoc'_a3, intros, exact (h0 g₁ g₂ p).symm end⟩ --@[simp] --def aff_geom3d_group_sub : position3d s → position3d s → displacement3d s := sub_geom3d_position3d real_scalar noncomputable instance position3d_has_vsub : has_vsub (displacement3d s) (position3d s) := ⟨ sub_position3d_position3d⟩ instance : nonempty (position3d s) := ⟨mk_position3d s 0 0 0⟩ noncomputable instance : inhabited (position3d s) := ⟨mk_position3d s 0 0 0⟩ lemma position3d_vsub_vadd_a3 : ∀ (p3 p2 : (position3d s)), (p3 -ᵥ p2) +ᵥ p2 = p3 := begin intros, ext, dsimp only [has_vsub.vsub, has_vadd.vadd], dsimp only [add_displacement3d_position3d, sub_position3d_position3d, has_vsub.vsub, has_vadd.vadd], dsimp only [add_vectr_point, aff_point_group_sub, sub_point_point, has_vsub.vsub, has_vadd.vadd], dsimp only [aff_vec_group_action, aff_point_group_sub, add_vec_pt, aff_pt_group_sub, sub_pt_pt, mk_position3d', mk_point', mk_displacement3d', mk_vectr'], simp only [add_sub_cancel'_right], end lemma position3d_vadd_vsub_a3 : ∀ (g : displacement3d s) (p : position3d s), g +ᵥ p -ᵥ p = g := begin intros, ext, repeat { have h0 : ((g +ᵥ p -ᵥ p) : displacement3d s).to_vectr = (g.to_vectr +ᵥ p.to_point -ᵥ p.to_point) := rfl, rw h0, simp *, } end noncomputable instance aff_geom3d_torsor : add_torsor (displacement3d s) (position3d s) := ⟨ begin exact position3d_vsub_vadd_a3, end, begin exact position3d_vadd_vsub_a3, end, ⟩ open_locale affine noncomputable instance : affine_space (displacement3d s) (position3d s) := @geom3d.aff_geom3d_torsor f s end geom3d -- ha ha end bar /- Newer version Tradeoff - Does not directly extend from affine equiv. Base class is an equiv on points and vectrs Extension methods are provided to directly transform Times and Duration between frames -/ @[ext] structure geom3d_transform {f3 : geom3d_frame} {f2 : geom3d_frame} (sp3 : geom3d_space f3) (sp2 : geom3d_space f2) extends fm_tr sp3 sp2 noncomputable def geom3d_space.mk_geom3d_transform_to {f3 : geom3d_frame} (s3 : geom3d_space f3) : Π {f2 : geom3d_frame} (s2 : geom3d_space f2), geom3d_transform s3 s2 := --(position3d s2) ≃ᵃ[scalar] (position3d s3) := λ f2 s2, ⟨s3.fm_tr s2⟩ noncomputable instance g3tr_inh {f3 : geom3d_frame} {f2 : geom3d_frame} (sp3 : geom3d_space f3) (sp2 : geom3d_space f2) : inhabited (geom3d_transform sp3 sp2) := ⟨sp3.mk_geom3d_transform_to sp2⟩ noncomputable def geom3d_transform.symm {f3 : geom3d_frame} {f2 : geom3d_frame} {sp3 : geom3d_space f3} {sp2 : geom3d_space f2} (ttr : geom3d_transform sp3 sp2) : geom3d_transform sp2 sp3 := ⟨(ttr.1).symm⟩ noncomputable def geom3d_transform.trans {f3 : geom3d_frame} {f2 : geom3d_frame} {f3 : geom3d_frame} {sp3 : geom3d_space f3} {sp2 : geom3d_space f2} {sp3 : geom3d_space f3} (ttr : geom3d_transform sp3 sp2) : geom3d_transform sp2 sp3 → geom3d_transform sp3 sp3 := λttr_, ⟨(ttr.1).trans ttr_.1⟩ noncomputable def geom3d_transform.transform_position3d {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : position3d s3 → position3d s2 := λt : position3d s3, ⟨tr.to_fm_tr.to_equiv t.to_point⟩ noncomputable def geom3d_transform.transform_displacement3d {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : displacement3d s3 → displacement3d s2 := λd, let as_pt : point s3 := ⟨λi, mk_pt real_scalar (d.coords i).coord⟩ in let tr_pt := (tr.to_equiv as_pt) in ⟨⟨λi, mk_vec real_scalar (tr_pt.coords i).coord⟩⟩ variables {f : geom3d_frame} (s : geom3d_space f ) structure orientation3d extends orientation s := mk :: noncomputable instance o3i : inhabited (orientation3d s) := ⟨ ⟨mk_orientation s (λi, mk_vectr s ⟨[0,0,0],rfl⟩)⟩ ⟩ noncomputable def mk_orientation3d (s1 s2 s3 s4 s5 s6 s7 s8 s9 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then (mk_displacement3d s s1 s2 s3).to_vectr else if i.1 = 1 then (mk_displacement3d s s4 s5 s6).to_vectr else (mk_displacement3d s s7 s8 s9).to_vectr )⟩ --: orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then ax1.to_vectr else if i.1 = 1 then ax2.to_vectr else ax3.to_vectr )⟩ --okay, i can fill in this function now... noncomputable def mk_orientation3d_from_euler_angles (s1 s2 s3 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then (mk_displacement3d s s1 s2 s3).to_vectr else if i.1 = 1 then (mk_displacement3d s s4 s5 s6).to_vectr else (mk_displacement3d s s7 s8 s9).to_vectr )⟩ noncomputable def mk_orientation3d_from_quaternion (s1 s2 s3 s4 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : orientation3d s := mk_orientation3d s (2*(s1*s1 + s2*s2) - 1) (2*(s2*s3 - s1*s4)) (2*(s2*s4 + s1*s3)) (2*(s2*s3 + s1*s4)) (2*(s1*s1 + s3*s3)) (2*(s3*s4 - s1*s2)) (2*(s2*s4 - s1*s3)) (2*(s3*s4 + s1*s2)) (2*(s1*s1 + s1*s1 + s4*s4) - 1) --: orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then ax1.to_vectr else if i.1 = 1 then ax2.to_vectr else ax3.to_vectr )⟩ noncomputable def geom3d_transform.transform_orientation {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : orientation3d s3 → orientation3d s2 := λo : orientation3d s3, ⟨tr.to_fm_tr.transform_orientation o.to_orientation⟩ structure rotation3d extends rotation s := mk :: /- noncomputable def mk_rotation3d (ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : rotation3d s := ⟨mk_rotation s (λi, if i.1 = 0 then ax1.to_vectr else if i.1 = 1 then ax2.to_vectr else ax3.to_vectr )⟩ -/ noncomputable def mk_rotation3d (s1 s2 s3 s4 s5 s6 s7 s8 s9 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : rotation3d s := ⟨mk_rotation s (λi, if i.1 = 0 then (mk_displacement3d s s1 s2 s3).to_vectr else if i.1 = 1 then (mk_displacement3d s s4 s5 s6).to_vectr else (mk_displacement3d s s7 s8 s9).to_vectr )⟩ noncomputable instance r3i : inhabited (rotation3d s) := ⟨ mk_rotation3d s 1 1 1 1 1 1 1 1 1 ⟩ noncomputable def mk_rotation3d_from_quaternion (s1 s2 s3 s4 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : rotation3d s := mk_rotation3d s (2*(s1*s1 + s2*s2) - 1) (2*(s2*s3 - s1*s4)) (2*(s2*s4 + s1*s3)) (2*(s2*s3 + s1*s4)) (2*(s1*s1 + s3*s3)) (2*(s3*s4 - s1*s2)) (2*(s2*s4 - s1*s3)) (2*(s3*s4 + s1*s2)) (2*(s1*s1 + s1*s1 + s4*s4) - 1) --: orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then ax1.to_vectr else if i.1 = 1 then ax2.to_vectr else ax3.to_vectr )⟩ structure pose3d := mk :: (orientation : orientation3d s) (position : position3d s) def mk_pose3d (orientation : orientation3d s) (position : position3d s) : pose3d s := ⟨orientation,position⟩ noncomputable instance p3i : inhabited (pose3d s) := ⟨ ( mk_pose3d _ (mk_orientation3d _ 0 0 0 0 0 0 0 0 0) (mk_position3d _ 0 0 0) ) ⟩ noncomputable def geom3d_transform.transform_pose3d {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : pose3d s3 → pose3d s2 := λp :_, (⟨tr.transform_orientation p.orientation, tr.transform_position3d p.position⟩:pose3d s2)
ec05aa3e803f35648b77127023e8a831ef6344a2
4727251e0cd73359b15b664c3170e5d754078599
/src/geometry/manifold/instances/units_of_normed_algebra.lean
f80a4a3fe5c6bb1271694a1fe29434413dbb205f
[ "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
2,473
lean
/- Copyright © 2021 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Heather Macbeth -/ import geometry.manifold.smooth_manifold_with_corners import analysis.normed_space.units /-! # Units of a normed algebra This file is a stub, containing a construction of the charted space structure on the group of units of a complete normed ring `R`, and of the smooth manifold structure on the group of units of a complete normed `𝕜`-algebra `R`. This manifold is actually a Lie group, which eventually should be the main result of this file. An important special case of this construction is the general linear group. For a normed space `V` over a field `𝕜`, the `𝕜`-linear endomorphisms of `V` are a normed `𝕜`-algebra (see `continuous_linear_map.to_normed_algebra`), so this construction provides a Lie group structure on its group of units, the general linear group GL(`𝕜`, `V`). ## TODO The Lie group instance requires the following fields: ``` instance : lie_group 𝓘(𝕜, R) Rˣ := { smooth_mul := sorry, smooth_inv := sorry, ..units.smooth_manifold_with_corners } ``` The ingredients needed for the construction are * smoothness of multiplication and inversion in the charts, i.e. as functions on the normed `𝕜`-space `R`: see `cont_diff_at_ring_inverse` for the inversion result, and `cont_diff_mul` (needs to be generalized from field to algebra) for the multiplication result * for an open embedding `f`, whose domain is equipped with the induced manifold structure `f.singleton_smooth_manifold_with_corners`, characterization of smoothness of functions to/from this manifold in terms of smoothness in the target space. See the pair of lemmas `cont_mdiff_coe_sphere` and `cont_mdiff.cod_restrict_sphere` for a model. None of this should be particularly difficult. -/ noncomputable theory open_locale manifold namespace units variables {R : Type*} [normed_ring R] [complete_space R] instance : charted_space R Rˣ := open_embedding_coe.singleton_charted_space lemma chart_at_apply {a : Rˣ} {b : Rˣ} : chart_at R a b = b := rfl lemma chart_at_source {a : Rˣ} : (chart_at R a).source = set.univ := rfl variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_algebra 𝕜 R] instance : smooth_manifold_with_corners 𝓘(𝕜, R) Rˣ := open_embedding_coe.singleton_smooth_manifold_with_corners 𝓘(𝕜, R) end units
2565c73f1904327b8ce50cee6217418ea64f76b8
94e33a31faa76775069b071adea97e86e218a8ee
/src/number_theory/function_field.lean
5c7febc62fa100056ea61d7f15e2205072899fc1
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
10,459
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Ashvni Narayanan -/ import field_theory.ratfunc import ring_theory.algebraic import ring_theory.dedekind_domain.integral_closure import ring_theory.integrally_closed import topology.algebra.valued_field /-! # Function fields This file defines a function field and the ring of integers corresponding to it. ## Main definitions - `function_field Fq F` states that `F` is a function field over the (finite) field `Fq`, i.e. it is a finite extension of the field of rational functions in one variable over `Fq`. - `function_field.ring_of_integers` defines the ring of integers corresponding to a function field as the integral closure of `polynomial Fq` in the function field. - `function_field.infty_valuation` : The place at infinity on `Fq(t)` is the nonarchimedean valuation on `Fq(t)` with uniformizer `1/t`. - `function_field.Fqt_infty` : The completion `Fq((t⁻¹))` of `Fq(t)` with respect to the valuation at infinity. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. We also omit assumptions like `finite Fq` or `is_scalar_tower Fq[X] (fraction_ring Fq[X]) F` in definitions, adding them back in lemmas when they are needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [P. Samuel, *Algebraic Theory of Numbers*][samuel1970algebraic] ## Tags function field, ring of integers -/ noncomputable theory open_locale non_zero_divisors polynomial discrete_valuation variables (Fq F : Type) [field Fq] [field F] /-- `F` is a function field over the finite field `Fq` if it is a finite extension of the field of rational functions in one variable over `Fq`. Note that `F` can be a function field over multiple, non-isomorphic, `Fq`. -/ abbreviation function_field [algebra (ratfunc Fq) F] : Prop := finite_dimensional (ratfunc Fq) F /-- `F` is a function field over `Fq` iff it is a finite extension of `Fq(t)`. -/ protected lemma function_field_iff (Fqt : Type*) [field Fqt] [algebra Fq[X] Fqt] [is_fraction_ring Fq[X] Fqt] [algebra (ratfunc Fq) F] [algebra Fqt F] [algebra Fq[X] F] [is_scalar_tower Fq[X] Fqt F] [is_scalar_tower Fq[X] (ratfunc Fq) F] : function_field Fq F ↔ finite_dimensional Fqt F := begin let e := is_localization.alg_equiv Fq[X]⁰ (ratfunc Fq) Fqt, have : ∀ c (x : F), e c • x = c • x, { intros c x, rw [algebra.smul_def, algebra.smul_def], congr, refine congr_fun _ c, refine is_localization.ext (non_zero_divisors (Fq[X])) _ _ _ _ _ _ _; intros; simp only [alg_equiv.map_one, ring_hom.map_one, alg_equiv.map_mul, ring_hom.map_mul, alg_equiv.commutes, ← is_scalar_tower.algebra_map_apply], }, split; intro h; resetI, { let b := finite_dimensional.fin_basis (ratfunc Fq) F, exact finite_dimensional.of_fintype_basis (b.map_coeffs e this) }, { let b := finite_dimensional.fin_basis Fqt F, refine finite_dimensional.of_fintype_basis (b.map_coeffs e.symm _), intros c x, convert (this (e.symm c) x).symm, simp only [e.apply_symm_apply] }, end lemma algebra_map_injective [algebra Fq[X] F] [algebra (ratfunc Fq) F] [is_scalar_tower Fq[X] (ratfunc Fq) F] : function.injective ⇑(algebra_map Fq[X] F) := begin rw is_scalar_tower.algebra_map_eq Fq[X] (ratfunc Fq) F, exact function.injective.comp ((algebra_map (ratfunc Fq) F).injective) (is_fraction_ring.injective Fq[X] (ratfunc Fq)), end namespace function_field /-- The function field analogue of `number_field.ring_of_integers`: `function_field.ring_of_integers Fq Fqt F` is the integral closure of `Fq[t]` in `F`. We don't actually assume `F` is a function field over `Fq` in the definition, only when proving its properties. -/ def ring_of_integers [algebra Fq[X] F] := integral_closure Fq[X] F namespace ring_of_integers variables [algebra Fq[X] F] instance : is_domain (ring_of_integers Fq F) := (ring_of_integers Fq F).is_domain instance : is_integral_closure (ring_of_integers Fq F) Fq[X] F := integral_closure.is_integral_closure _ _ variables [algebra (ratfunc Fq) F] [is_scalar_tower Fq[X] (ratfunc Fq) F] lemma algebra_map_injective : function.injective ⇑(algebra_map Fq[X] (ring_of_integers Fq F)) := begin have hinj : function.injective ⇑(algebra_map Fq[X] F), { rw is_scalar_tower.algebra_map_eq Fq[X] (ratfunc Fq) F, exact function.injective.comp ((algebra_map (ratfunc Fq) F).injective) (is_fraction_ring.injective Fq[X] (ratfunc Fq)), }, rw injective_iff_map_eq_zero (algebra_map Fq[X] ↥(ring_of_integers Fq F)), intros p hp, rw [← subtype.coe_inj, subalgebra.coe_zero] at hp, rw injective_iff_map_eq_zero (algebra_map Fq[X] F) at hinj, exact hinj p hp, end lemma not_is_field : ¬ is_field (ring_of_integers Fq F) := by simpa [← ((is_integral_closure.is_integral_algebra Fq[X] F).is_field_iff_is_field (algebra_map_injective Fq F))] using (polynomial.not_is_field Fq) variables [function_field Fq F] instance : is_fraction_ring (ring_of_integers Fq F) F := integral_closure.is_fraction_ring_of_finite_extension (ratfunc Fq) F instance : is_integrally_closed (ring_of_integers Fq F) := integral_closure.is_integrally_closed_of_finite_extension (ratfunc Fq) instance [is_separable (ratfunc Fq) F] : is_dedekind_domain (ring_of_integers Fq F) := is_integral_closure.is_dedekind_domain Fq[X] (ratfunc Fq) F _ end ring_of_integers /-! ### The place at infinity on Fq(t) -/ section infty_valuation variable [decidable_eq (ratfunc Fq)] /-- The valuation at infinity is the nonarchimedean valuation on `Fq(t)` with uniformizer `1/t`. Explicitly, if `f/g ∈ Fq(t)` is a nonzero quotient of polynomials, its valuation at infinity is `multiplicative.of_add(degree(f) - degree(g))`. -/ def infty_valuation_def (r : ratfunc Fq) : ℤₘ₀ := if r = 0 then 0 else (multiplicative.of_add r.int_degree) lemma infty_valuation.map_zero' : infty_valuation_def Fq 0 = 0 := if_pos rfl lemma infty_valuation.map_one' : infty_valuation_def Fq 1 = 1 := (if_neg one_ne_zero).trans $ by rw [ratfunc.int_degree_one, of_add_zero, with_zero.coe_one] lemma infty_valuation.map_mul' (x y : ratfunc Fq) : infty_valuation_def Fq (x * y) = infty_valuation_def Fq x * infty_valuation_def Fq y := begin rw [infty_valuation_def, infty_valuation_def, infty_valuation_def], by_cases hx : x = 0, { rw [hx, zero_mul, if_pos (eq.refl _), zero_mul] }, { by_cases hy : y = 0, { rw [hy, mul_zero, if_pos (eq.refl _), mul_zero] }, { rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_zero.coe_mul, with_zero.coe_inj, ← of_add_add, ratfunc.int_degree_mul hx hy], }} end lemma infty_valuation.map_add_le_max' (x y : ratfunc Fq) : infty_valuation_def Fq (x + y) ≤ max (infty_valuation_def Fq x) (infty_valuation_def Fq y) := begin by_cases hx : x = 0, { rw [hx, zero_add], conv_rhs { rw [infty_valuation_def, if_pos (eq.refl _)] }, rw max_eq_right (with_zero.zero_le (infty_valuation_def Fq y)), exact le_refl _ }, { by_cases hy : y = 0, { rw [hy, add_zero], conv_rhs { rw [max_comm, infty_valuation_def, if_pos (eq.refl _)] }, rw max_eq_right (with_zero.zero_le (infty_valuation_def Fq x)), exact le_refl _ }, { by_cases hxy : x + y = 0, { rw [infty_valuation_def, if_pos hxy], exact zero_le',}, { rw [infty_valuation_def, infty_valuation_def, infty_valuation_def, if_neg hx, if_neg hy, if_neg hxy], rw [le_max_iff, with_zero.coe_le_coe, multiplicative.of_add_le, with_zero.coe_le_coe, multiplicative.of_add_le, ← le_max_iff], exact ratfunc.int_degree_add_le hy hxy }}} end @[simp] lemma infty_valuation_of_nonzero {x : ratfunc Fq} (hx : x ≠ 0) : infty_valuation_def Fq x = (multiplicative.of_add x.int_degree) := by rw [infty_valuation_def, if_neg hx] /-- The valuation at infinity on `Fq(t)`. -/ def infty_valuation : valuation (ratfunc Fq) ℤₘ₀ := { to_fun := infty_valuation_def Fq, map_zero' := infty_valuation.map_zero' Fq, map_one' := infty_valuation.map_one' Fq, map_mul' := infty_valuation.map_mul' Fq, map_add_le_max' := infty_valuation.map_add_le_max' Fq } @[simp] lemma infty_valuation_apply {x : ratfunc Fq} : infty_valuation Fq x = infty_valuation_def Fq x := rfl @[simp] lemma infty_valuation.C {k : Fq} (hk : k ≠ 0) : infty_valuation_def Fq (ratfunc.C k) = (multiplicative.of_add (0 : ℤ)) := begin have hCk : ratfunc.C k ≠ 0 := (ring_hom.map_ne_zero _).mpr hk, rw [infty_valuation_def, if_neg hCk, ratfunc.int_degree_C], end @[simp] lemma infty_valuation.X : infty_valuation_def Fq (ratfunc.X) = (multiplicative.of_add (1 : ℤ)) := by rw [infty_valuation_def, if_neg ratfunc.X_ne_zero, ratfunc.int_degree_X] @[simp] lemma infty_valuation.polynomial {p : polynomial Fq} (hp : p ≠ 0) : infty_valuation_def Fq (algebra_map (polynomial Fq) (ratfunc Fq) p) = (multiplicative.of_add (p.nat_degree : ℤ)) := begin have hp' : algebra_map (polynomial Fq) (ratfunc Fq) p ≠ 0, { rw [ne.def, ratfunc.algebra_map_eq_zero_iff], exact hp }, rw [infty_valuation_def, if_neg hp', ratfunc.int_degree_polynomial] end /-- The valued field `Fq(t)` with the valuation at infinity. -/ def infty_valued_Fqt : valued (ratfunc Fq) ℤₘ₀ := valued.mk' $ infty_valuation Fq lemma infty_valued_Fqt.def {x : ratfunc Fq} : @valued.v (ratfunc Fq) _ _ _ (infty_valued_Fqt Fq) x = infty_valuation_def Fq x := rfl /-- The completion `Fq((t⁻¹))` of `Fq(t)` with respect to the valuation at infinity. -/ def Fqt_infty := @uniform_space.completion (ratfunc Fq) $ (infty_valued_Fqt Fq).to_uniform_space instance : field (Fqt_infty Fq) := by { letI := infty_valued_Fqt Fq, exact uniform_space.completion.field } instance : inhabited (Fqt_infty Fq) := ⟨(0 : Fqt_infty Fq)⟩ /-- The valuation at infinity on `k(t)` extends to a valuation on `Fqt_infty`. -/ instance valued_Fqt_infty : valued (Fqt_infty Fq) ℤₘ₀ := @valued.valued_completion _ _ _ _ (infty_valued_Fqt Fq) lemma valued_Fqt_infty.def {x : Fqt_infty Fq} : valued.v x = @valued.extension (ratfunc Fq) _ _ _ (infty_valued_Fqt Fq) x := rfl end infty_valuation end function_field
159b7115579b28af5e8ac75b7244a81b9b84493d
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/data/array/slice.lean
402bce67d1bead77e9f6690d674076f20f978332
[ "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,307
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ prelude import init.data.nat init.data.array.basic init.data.nat.lemmas universes u variables {α : Type u} {n : nat} namespace array def slice (a : array α n) (k l : nat) (h₁ : k ≤ l) (h₂ : l ≤ n) : array α (l - k) := ⟨ λ ⟨ i, hi ⟩, a.read ⟨ i + k, calc i + k < (l - k) + k : add_lt_add_right hi _ ... = l : nat.sub_add_cancel h₁ ... ≤ n : h₂⟩ ⟩ def taken (a : array α n) (m : nat) (h : m ≤ n) : array α m := cast (by simp) $ a.slice 0 m (nat.zero_le _) h def dropn (a : array α n) (m : nat) (h : m ≤ n) : array α (n-m) := a.slice m n h (le_refl _) private lemma sub_sub_cancel (m n : ℕ) (h : m ≤ n) : n - (n - m) = m := calc n - (n - m) = (n - m) + m - (n - m) : by rw nat.sub_add_cancel; assumption ... = m : nat.add_sub_cancel_left _ _ def taken_right (a : array α n) (m : nat) (h : m ≤ n) : array α m := cast (by simph [sub_sub_cancel]) $ a.dropn (n - m) (nat.sub_le _ _) def reverse (a : array α n) : array α n := ⟨ λ ⟨ i, hi ⟩, a.read ⟨ n - (i + 1), begin apply nat.sub_lt_of_pos_le, apply nat.zero_lt_succ, assumption end ⟩ ⟩ end array
31a05953cb39ce47b9fa1259a70656cc28a40e85
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/10_Structures_and_Records.org.19.lean
3f58111020ef64086c02d82acf06cacac68b82c7
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
309
lean
import standard structure has_mul [class] (A : Type) := mk :: (mul : A → A → A) infixl `*` := has_mul.mul structure semigroup [class] (A : Type) extends has_mul A := mk :: (assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)) section variables (A : Type) (s : semigroup A) (a b : A) check a * b end
1fbf7a949145223d00c304d63bc3c31ec5e16dda
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/rewrite5.lean
a88f6dcae0f2eb255965be670fd8bf7c1cf98add
[ "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
175
lean
import algebra.group variable {A : Type} variable [s : group A] include s theorem mul.right_inv₁ (a : A) : a * a⁻¹ = 1 := by rewrite [-{a}inv_inv at {1}, mul.left_inv]
43b44e2b31b266cfe5283cab93ca16524697b636
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/rcases.lean
4ea77d3e8a28413d0bd2b8360fa714bbac385d02
[]
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
20,916
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.Lean3Lib.data.dlist import Mathlib.tactic.core import Mathlib.tactic.clear import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Recursive cases (`rcases`) tactic and related tactics `rcases` is a tactic that will perform `cases` recursively, according to a pattern. It is used to destructure hypotheses or expressions composed of inductive types like `h1 : a ∧ b ∧ c ∨ d` or `h2 : ∃ x y, trans_rel R x y`. Usual usage might be `rcases h1 with ⟨ha, hb, hc⟩ | hd` or `rcases h2 with ⟨x, y, _ | ⟨z, hxz, hzy⟩⟩` for these examples. Each element of an `rcases` pattern is matched against a particular local hypothesis (most of which are generated during the execution of `rcases` and represent individual elements destructured from the input expression). An `rcases` pattern has the following grammar: * A name like `x`, which names the active hypothesis as `x`. * A blank `_`, which does nothing (letting the automatic naming system used by `cases` name the hypothesis). * A hyphen `-`, which clears the active hypothesis and any dependents. * The keyword `rfl`, which expects the hypothesis to be `h : a = b`, and calls `subst` on the hypothesis (which has the effect of replacing `b` with `a` everywhere or vice versa). * A type ascription `p : ty`, which sets the type of the hypothesis to `ty` and then matches it against `p`. (Of course, `ty` must unify with the actual type of `h` for this to work.) * A tuple pattern `⟨p1, p2, p3⟩`, which matches a constructor with many arguments, or a series of nested conjunctions or existentials. For example if the active hypothesis is `a ∧ b ∧ c`, then the conjunction will be destructured, and `p1` will be matched against `a`, `p2` against `b` and so on. * An alteration pattern `p1 | p2 | p3`, which matches an inductive type with multiple constructors, or a nested disjunction like `a ∨ b ∨ c`. The patterns are fairly liberal about the exact shape of the constructors, and will insert additional alternation branches and tuple arguments if there are not enough arguments provided, and reuse the tail for further matches if there are too many arguments provided to alternation and tuple patterns. This file also contains the `obtain` and `rintro` tactics, which use the same syntax of `rcases` patterns but with a slightly different use case: * `rintro` (or `rintros`) is used like `rintro x ⟨y, z⟩` and is the same as `intros` followed by `rcases` on the newly introduced arguments. * `obtain` is the same as `rcases` but with a syntax styled after `have` rather than `cases`. `obtain ⟨hx, hy⟩ | hz := foo` is equivalent to `rcases foo with ⟨hx, hy⟩ | hz`. Unlike `rcases`, `obtain` also allows one to omit `:= foo`, although a type must be provided in this case, as in `obtain ⟨hx, hy⟩ | hz : a ∧ b ∨ c`, in which case it produces a subgoal for proving `a ∧ b ∨ c` in addition to the subgoals `hx : a, hy : b |- goal` and `hz : c |- goal`. ## Tags rcases, rintro, obtain, destructuring, cases, pattern matching, match -/ namespace tactic /-! These synonyms for `list` are used to clarify the meanings of the many usages of lists in this module. - `listΣ` is used where a list represents a disjunction, such as the list of possible constructors of an inductive type. - `listΠ` is used where a list represents a conjunction, such as the list of arguments of an individual constructor. These are merely type synonyms, and so are not checked for consistency by the compiler. The `def`/`local notation` combination makes Lean retain these annotations in reported types. -/ /-- A list, with a disjunctive meaning (like a list of inductive constructors, or subgoals) -/ def list_Sigma (T : Type u_1) := List /-- A list, with a conjunctive meaning (like a list of constructor arguments, or hypotheses) -/ def list_Pi (T : Type u_1) := List /-- A metavariable representing a subgoal, together with a list of local constants to clear. -/ /-- An `rcases` pattern can be one of the following, in a nested combination: * A name like `foo` * The special keyword `rfl` (for pattern matching on equality using `subst`) * A hyphen `-`, which clears the active hypothesis and any dependents. * A type ascription like `pat : ty` (parentheses are optional) * A tuple constructor like `⟨p1, p2, p3⟩` * An alternation / variant pattern `p1 | p2 | p3` Parentheses can be used for grouping; alternation is higher precedence than type ascription, so `p1 | p2 | p3 : ty` means `(p1 | p2 | p3) : ty`. N-ary alternations are treated as a group, so `p1 | p2 | p3` is not the same as `p1 | (p2 | p3)`, and similarly for tuples. However, note that an n-ary alternation or tuple can match an n-ary conjunction or disjunction, because if the number of patterns exceeds the number of constructors in the type being destructed, the extra patterns will match on the last element, meaning that `p1 | p2 | p3` will act like `p1 | (p2 | p3)` when matching `a1 ∨ a2 ∨ a3`. If matching against a type with 3 constructors, `p1 | (p2 | p3)` will act like `p1 | (p2 | p3) | _` instead. -/ namespace rcases_patt /-- Get the name from a pattern, if provided -/ /-- Interpret an rcases pattern as a tuple, where `p` becomes `⟨p⟩` if `p` is not already a tuple. -/ /-- Interpret an rcases pattern as an alternation, where non-alternations are treated as one alternative. -/ /-- Convert a list of patterns to a tuple pattern, but mapping `[p]` to `p` instead of `⟨p⟩`. -/ /-- Convert a list of patterns to an alternation pattern, but mapping `[p]` to `p` instead of a unary alternation `|p`. -/ /-- This function is used for producing rcases patterns based on a case tree. Suppose that we have a list of patterns `ps` that will match correctly against the branches of the case tree for one constructor. This function will merge tuples at the end of the list, so that `[a, b, ⟨c, d⟩]` becomes `⟨a, b, c, d⟩` instead of `⟨a, b, ⟨c, d⟩⟩`. We must be careful to turn `[a, ⟨⟩]` into `⟨a, ⟨⟩⟩` instead of `⟨a⟩` (which will not perform the nested match). -/ /-- This function is used for producing rcases patterns based on a case tree. This is like `tuple₁_core` but it produces a pattern instead of a tuple pattern list, converting `[n]` to `n` instead of `⟨n⟩` and `[]` to `_`, and otherwise just converting `[a, b, c]` to `⟨a, b, c⟩`. -/ /-- This function is used for producing rcases patterns based on a case tree. Here we are given the list of patterns to apply to each argument of each constructor after the main case, and must produce a list of alternatives with the same effect. This function calls `tuple₁` to make the individual alternatives, and handles merging `[a, b, c | d]` to `a | b | c | d` instead of `a | b | (c | d)`. -/ /-- This function is used for producing rcases patterns based on a case tree. This is like `alts₁_core`, but it produces a cases pattern directly instead of a list of alternatives. We specially translate the empty alternation to `⟨⟩`, and translate `|(a | b)` to `⟨a | b⟩` (because we don't have any syntax for unary alternation). Otherwise we can use the regular merging of alternations at the last argument so that `a | b | (c | d)` becomes `a | b | c | d`. -/ /-- Formats an `rcases` pattern. If the `bracket` argument is true, then it will be printed at high precedence, i.e. it will have parentheses around it if it is not already a tuple or atomic name. -/ end rcases_patt /-- Takes the number of fields of a single constructor and patterns to match its fields against (not necessarily the same number). The returned lists each contain one element per field of the constructor. The `name` is the name which will be used in the top-level `cases` tactic, and the `rcases_patt` is the pattern which the field will be matched against by subsequent `cases` tactics. -/ -- The interesting case: we matched the last field against multiple -- patterns, so split off the remaining patterns into a subsequent -- match. This handles matching `α × β × γ` against `⟨a, b, c⟩`. /-- Takes a list of constructor names, and an (alternation) list of patterns, and matches each pattern against its constructor. It returns the list of names that will be passed to `cases`, and the list of `(constructor name, patterns)` for each constructor, where `patterns` is the (conjunctive) list of patterns to apply to each constructor argument. -/ /-- Like `zip`, but only elements satisfying a matching predicate `p` will go in the list, and elements of the first list that fail to match the second list will be skipped. -/ /-- Given a local constant `e`, get its type. *But* if `e` does not exist, go find a hypothesis with the same pretty name as `e` and get it instead. This is needed because we can sometimes lose track of the unique names of hypotheses when they are revert/intro'd by `change` and `cases`. (A better solution would be for these tactics to return a map of renamed hypotheses so that we don't lose track of them.) -/ /-- * `rcases_core p e` will match a pattern `p` against a local hypothesis `e`. It returns the list of subgoals that were produced. * `rcases.continue pes` will match a (conjunctive) list of `(p, e)` pairs which refer to patterns and local hypotheses to match against, and applies all of them. Note that this can involve matching later arguments multiple times given earlier arguments, for example `⟨a | b, ⟨c, d⟩⟩` performs the `⟨c, d⟩` match twice, once on the `a` branch and once on `b`. -/ -- If the pattern is any other name, we already bound the name in the -- top-level `cases` tactic, so there is no more work to do for it. /-- Given a list of `uncleared_goal`s, each of which is a goal metavariable and a list of variables to clear, actually perform the clear and set the goals with the result. -/ /-- `rcases h e pat` performs case distinction on `e` using `pat` to name the arising new variables and assumptions. If `h` is `some` name, a new assumption `h : e = pat` will relate the expression `e` with the current pattern. See the module comment for the syntax of `pat`. -/ /-- `rcases_many es pats` performs case distinction on the `es` using `pat` to name the arising new variables and assumptions. See the module comment for the syntax of `pat`. -/ /-- `rintro pat₁ pat₂ ... patₙ` introduces `n` arguments, then pattern matches on the `patᵢ` using the same syntax as `rcases`. -/ /-- Like `zip_with`, but if the lists don't match in length, the excess elements will be put at the end of the result. -/ def merge_list {α : Type u_1} (m : α → α → α) : List α → List α → List α := sorry /-- Merge two `rcases` patterns. This is used to underapproximate a case tree by an `rcases` pattern. The two patterns come from cases in two branches, that due to the syntax of `rcases` patterns are forced to overlap. The rule here is that we take only the case splits that are in common between both branches. For example if one branch does `⟨a, b⟩` and the other does `c`, then we return `c` because we don't know that a case on `c` would be safe to do. -/ /-- * `rcases_hint_core depth e` does the same as `rcases p e`, except the pattern `p` is an output instead of an input, controlled only by the case depth argument `depth`. We use `cases` to depth `depth` and then reconstruct an `rcases` pattern `p` that would, if passed to `rcases`, perform the same thing as the case tree we just constructed (or at least, the nearest expressible approximation to this.) * `rcases_hint.process_constructors depth cs l` takes a list of constructor names `cs` and a matching list `l` of elements `(g, c', hs, _)` where `c'` is a constructor name (used for alignment with `cs`), `g` is the subgoal, and `hs` is the list of local hypotheses created by `cases` in that subgoal. It matches on all of them, and then produces a `ΣΠ`-list of `rcases` patterns describing the result, and the list of generated subgoals. * `rcases_hint.continue depth es` does the same as `rcases.continue (ps.zip es)`, except the patterns `ps` are an output instead of an input, created by matching on everything to depth `depth` and recording the successful cases. It returns `ps`, and the list of generated subgoals. -/ /-- * `rcases? e` is like `rcases e with ...`, except it generates `...` by matching on everything it can, and it outputs an `rcases` invocation that should have the same effect. * `rcases? e : n` can be used to control the depth of case splits (especially important for recursive types like `nat`, which can be cased as many times as you like). -/ /-- * `rcases? ⟨e1, e2, e3⟩` is like `rcases ⟨e1, e2, e3⟩ with ...`, except it generates `...` by matching on everything it can, and it outputs an `rcases` invocation that should have the same effect. * `rcases? ⟨e1, e2, e3⟩ : n` can be used to control the depth of case splits (especially important for recursive types like `nat`, which can be cased as many times as you like). -/ /-- * `rintro?` is like `rintro ...`, except it generates `...` by introducing and matching on everything it can, and it outputs an `rintro` invocation that should have the same effect. * `rintro? : n` can be used to control the depth of case splits (especially important for recursive types like `nat`, which can be cased as many times as you like). -/ /-- * `rcases_patt_parse tt` will parse a high precedence `rcases` pattern, `patt_hi`. This means only tuples and identifiers are allowed; alternations and type ascriptions require `(...)` instead, which switches to `patt`. * `rcases_patt_parse ff` will parse a low precedence `rcases` pattern, `patt`. This consists of a `patt_med` (which deals with alternations), optionally followed by a `: ty` type ascription. The expression `ty` is at `texpr` precedence because it can appear at the end of a tactic, for example in `rcases e with x : ty <|> skip`. * `rcases_patt_parse_list` will parse an alternation list, `patt_med`, one or more `patt` patterns separated by `|`. It does not parse a `:` at the end, so that `a | b : ty` parses as `(a | b) : ty` where `a | b` is the `patt_med` part. * `rcases_patt_parse_list_rest a` parses an alternation list after the initial pattern, `| b | c`. ```lean patt ::= patt_med (":" expr)? patt_med ::= (patt_hi "|")* patt_hi patt_hi ::= id | "rfl" | "_" | "⟨" (patt ",")* patt "⟩" | "(" patt ")" ``` -/ /-- Parse the optional depth argument `(: n)?` of `rcases?` and `rintro?`, with default depth 5. -/ /-- The arguments to `rcases`, which in fact dispatch to several other tactics. * `rcases? expr (: n)?` or `rcases? ⟨expr, ...⟩ (: n)?` calls `rcases_hint` * `rcases? ⟨expr, ...⟩ (: n)?` calls `rcases_hint_many` * `rcases (h :)? expr (with patt)?` calls `rcases` * `rcases ⟨expr, ...⟩ (with patt)?` calls `rcases_many` -/ /-- Syntax for a `rcases` pattern: * `rcases? expr (: n)?` * `rcases (h :)? expr (with patt_list (: expr)?)?`. -/ /-- `rintro_patt_parse_hi` and `rintro_patt_parse` are like `rcases_patt_parse`, but is used for parsing top level `rintro` patterns, which allow sequences like `(x y : t)` in addition to simple `rcases` patterns. * `rintro_patt_parse_hi` will parse a high precedence `rcases` pattern, `rintro_patt_hi` below. This means only tuples and identifiers are allowed; alternations and type ascriptions require `(...)` instead, which switches to `patt`. * `rintro_patt_parse tt` will parse a low precedence `rcases` pattern, `rintro_patt` below. This consists of either a sequence of patterns `p1 p2 p3` or an alternation list `p1 | p2 | p3` treated as a single pattern, optionally followed by a `: ty` type ascription, which applies to every pattern in the list. * `rintro_patt_parse ff` parses `rintro_patt_low`, which is the same as `rintro_patt_parse tt` but it does not permit an unparenthesized alternation list, it must have the form `p1 p2 p3 (: ty)?`. ```lean rintro_patt ::= (rintro_patt_hi+ | patt_med) (":" expr)? rintro_patt_low ::= rintro_patt_hi* (":" expr)? rintro_patt_hi ::= patt_hi | "(" rintro_patt ")" ``` -/ /-- Syntax for a `rintro` pattern: `('?' (: n)?) | rintro_patt`. -/ namespace interactive /-- `rcases` is a tactic that will perform `cases` recursively, according to a pattern. It is used to destructure hypotheses or expressions composed of inductive types like `h1 : a ∧ b ∧ c ∨ d` or `h2 : ∃ x y, trans_rel R x y`. Usual usage might be `rcases h1 with ⟨ha, hb, hc⟩ | hd` or `rcases h2 with ⟨x, y, _ | ⟨z, hxz, hzy⟩⟩` for these examples. Each element of an `rcases` pattern is matched against a particular local hypothesis (most of which are generated during the execution of `rcases` and represent individual elements destructured from the input expression). An `rcases` pattern has the following grammar: * A name like `x`, which names the active hypothesis as `x`. * A blank `_`, which does nothing (letting the automatic naming system used by `cases` name the hypothesis). * A hyphen `-`, which clears the active hypothesis and any dependents. * The keyword `rfl`, which expects the hypothesis to be `h : a = b`, and calls `subst` on the hypothesis (which has the effect of replacing `b` with `a` everywhere or vice versa). * A type ascription `p : ty`, which sets the type of the hypothesis to `ty` and then matches it against `p`. (Of course, `ty` must unify with the actual type of `h` for this to work.) * A tuple pattern `⟨p1, p2, p3⟩`, which matches a constructor with many arguments, or a series of nested conjunctions or existentials. For example if the active hypothesis is `a ∧ b ∧ c`, then the conjunction will be destructured, and `p1` will be matched against `a`, `p2` against `b` and so on. * An alteration pattern `p1 | p2 | p3`, which matches an inductive type with multiple constructors, or a nested disjunction like `a ∨ b ∨ c`. A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype, naming the first three parameters of the first constructor as `a,b,c` and the first two of the second constructor `d,e`. If the list is not as long as the number of arguments to the constructor or the number of constructors, the remaining variables will be automatically named. If there are nested brackets such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary. If there are too many arguments, such as `⟨a, b, c⟩` for splitting on `∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last parameter as necessary. `rcases` also has special support for quotient types: quotient induction into Prop works like matching on the constructor `quot.mk`. `rcases h : e with PAT` will do the same as `rcases e with PAT` with the exception that an assumption `h : e = PAT` will be added to the context. `rcases? e` will perform case splits on `e` in the same way as `rcases e`, but rather than accepting a pattern, it does a maximal cases and prints the pattern that would produce this case splitting. The default maximum depth is 5, but this can be modified with `rcases? e : n`. -/ /-- The `rintro` tactic is a combination of the `intros` tactic with `rcases` to allow for destructuring patterns while introducing variables. See `rcases` for a description of supported patterns. For example, `rintro (a | ⟨b, c⟩) ⟨d, e⟩` will introduce two variables, and then do case splits on both of them producing two subgoals, one with variables `a d e` and the other with `b c d e`. `rintro`, unlike `rcases`, also supports the form `(x y : ty)` for introducing and type-ascripting multiple variables at once, similar to binders. `rintro?` will introduce and case split on variables in the same way as `rintro`, but will also print the `rintro` invocation that would have the same result. Like `rcases?`, `rintro? : n` allows for modifying the depth of splitting; the default is 5. `rintros` is an alias for `rintro`. -/ /-- Alias for `rintro`. -/ /-- Parses `patt? (: expr)? (:= expr)?`, the arguments for `obtain`. (This is almost the same as `rcases_patt_parse ff`, but it allows the pattern part to be empty.) -/ /-- The `obtain` tactic is a combination of `have` and `rcases`. See `rcases` for a description of supported patterns. ```lean obtain ⟨patt⟩ : type, { ... } ``` is equivalent to ```lean have h : type, { ... }, rcases h with ⟨patt⟩ ``` The syntax `obtain ⟨patt⟩ : type := proof` is also supported. If `⟨patt⟩` is omitted, `rcases` will try to infer the pattern. If `type` is omitted, `:= proof` is required. -/
929e1fcc2f9b0af6de1f37d5a527fcfb0d5ce86b
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/t4.lean
a053e49d1619a5bf084bc54e3216603977227d3d
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
1,179
lean
definition Prop [inline] : Type.{1} := Type.{0} variable N : Type.{1} check N variable a : N check a check Prop → Prop variable F.{l} : Type.{l} → Type.{l} check F.{2} universe u check F.{u} variable vec.{l} (A : Type.{l}) (n : N) : Type.{l} variable f (a b : N) : N variable len.{l} (A : Type.{l}) (n : N) (v : vec.{l} A n) : N check f check len.{1} section variable A : Type variable B : Prop hypothesis H : B parameter {C : Type} check B -> B check A → A check C end check A -- Error: A is part of the section variable R : Type → Type check R.{1 0} check fun x y : N, x namespace tst variable N : Type.{2} variable M : Type.{2} print raw N -- Two possible interpretations N and tst.N print raw tst.N -- Only one interpretation end print raw N -- Only one interpretation namespace foo variable M : Type.{3} print raw M -- Only one interpretation end check tst.M check foo.M namespace foo check M end check M -- Error print "ok" (* local env = get_env() print("Declarations:") env:for_each_decl(function(d) print(d:name()) end) print("-------------") *) universe l_1 variable T1 : Type -- T1 parameter is going to be called l_2
7377bd075fa6cfa16913465a2bd9509508f03348
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/AppBuilder.lean
b9fd3c5f7db8fe3443aa12dae9a67330dd7f27b7
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,592
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Structure import Lean.Util.Recognizers import Lean.Meta.SynthInstance import Lean.Meta.Check namespace Lean.Meta /-- Return `id e` -/ def mkId (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type return mkApp2 (mkConst ``id [u]) type e /-- Return `idRhs e` -/ def mkIdRhs (e : Expr) : MetaM Expr := do let type ← inferType e let u ← getLevel type return mkApp2 (mkConst ``idRhs [u]) type e /-- Given `e` s.t. `inferType e` is definitionally equal to `expectedType`, return term `@id expectedType e`. -/ def mkExpectedTypeHint (e : Expr) (expectedType : Expr) : MetaM Expr := do let u ← getLevel expectedType return mkApp2 (mkConst ``id [u]) expectedType e def mkEq (a b : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType return mkApp3 (mkConst ``Eq [u]) aType a b def mkHEq (a b : Expr) : MetaM Expr := do let aType ← inferType a let bType ← inferType b let u ← getLevel aType return mkApp4 (mkConst ``HEq [u]) aType a bType b def mkEqRefl (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType return mkApp2 (mkConst ``Eq.refl [u]) aType a def mkHEqRefl (a : Expr) : MetaM Expr := do let aType ← inferType a let u ← getLevel aType return mkApp2 (mkConst ``HEq.refl [u]) aType a private def infer (h : Expr) : MetaM Expr := do let hType ← inferType h whnfD hType private def hasTypeMsg (e type : Expr) : MessageData := m!"{indentExpr e}\nhas type{indentExpr type}" private def throwAppBuilderException {α} (op : Name) (msg : MessageData) : MetaM α := throwError! "AppBuilder for '{op}', {msg}" def mkEqSymm (h : Expr) : MetaM Expr := do if h.isAppOf ``Eq.refl then return h else let hType ← infer h match hType.eq? with | some (α, a, b) => let u ← getLevel α return mkApp4 (mkConst ``Eq.symm [u]) α a b h | none => throwAppBuilderException ``Eq.symm ("equality proof expected" ++ hasTypeMsg h hType) def mkEqTrans (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf ``Eq.refl then return h₂ else if h₂.isAppOf ``Eq.refl then return h₁ else let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (α, a, b), some (_, _, c) => let u ← getLevel α return mkApp6 (mkConst ``Eq.trans [u]) α a b c h₁ h₂ | none, _ => throwAppBuilderException ``Eq.trans ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``Eq.trans ("equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkHEqSymm (h : Expr) : MetaM Expr := do if h.isAppOf ``HEq.refl then return h else let hType ← infer h match hType.heq? with | some (α, a, β, b) => let u ← getLevel α return mkApp5 (mkConst ``HEq.symm [u]) α β a b h | none => throwAppBuilderException ``HEq.symm ("heterogeneous equality proof expected" ++ hasTypeMsg h hType) def mkHEqTrans (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf ``HEq.refl then return h₂ else if h₂.isAppOf ``HEq.refl then return h₁ else let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.heq?, hType₂.heq? with | some (α, a, β, b), some (_, _, γ, c) => let u ← getLevel α return mkApp8 (mkConst ``HEq.trans [u]) α β γ a b c h₁ h₂ | none, _ => throwAppBuilderException ``HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``HEq.trans ("heterogeneous equality proof expected" ++ hasTypeMsg h₂ hType₂) def mkEqOfHEq (h : Expr) : MetaM Expr := do let hType ← infer h match hType.heq? with | some (α, a, β, b) => unless (← isDefEq α β) do throwAppBuilderException ``eqOfHEq m!"heterogeneous equality types are not definitionally equal{indentExpr α}\nis not definitionally equal to{indentExpr β}" let u ← getLevel α return mkApp4 (mkConst ``eqOfHEq [u]) α a b h | _ => throwAppBuilderException ``HEq.trans m!"heterogeneous equality proof expected{indentExpr h}" def mkCongrArg (f h : Expr) : MetaM Expr := do if h.isAppOf ``Eq.refl then mkEqRefl (mkApp f h.appArg!) else let hType ← infer h let fType ← infer f match fType.arrow?, hType.eq? with | some (α, β), some (_, a, b) => let u ← getLevel α let v ← getLevel β return mkApp6 (mkConst ``congrArg [u, v]) α β a b f h | none, _ => throwAppBuilderException ``congrArg ("non-dependent function expected" ++ hasTypeMsg f fType) | _, none => throwAppBuilderException ``congrArg ("equality proof expected" ++ hasTypeMsg h hType) def mkCongrFun (h a : Expr) : MetaM Expr := do if h.isAppOf ``Eq.refl then mkEqRefl (mkApp h.appArg! a) else let hType ← infer h match hType.eq? with | some (ρ, f, g) => do let ρ ← whnfD ρ match ρ with | Expr.forallE n α β _ => let β' := Lean.mkLambda n BinderInfo.default α β let u ← getLevel α let v ← getLevel (mkApp β' a) return mkApp6 (mkConst ``congrFun [u, v]) α β' f g h a | _ => throwAppBuilderException ``congrFun ("equality proof between functions expected" ++ hasTypeMsg h hType) | _ => throwAppBuilderException ``congrFun ("equality proof expected" ++ hasTypeMsg h hType) def mkCongr (h₁ h₂ : Expr) : MetaM Expr := do if h₁.isAppOf ``Eq.refl then mkCongrArg h₁.appArg! h₂ else if h₂.isAppOf ``Eq.refl then mkCongrFun h₁ h₂.appArg! else let hType₁ ← infer h₁ let hType₂ ← infer h₂ match hType₁.eq?, hType₂.eq? with | some (ρ, f, g), some (α, a, b) => let ρ ← whnfD ρ match ρ.arrow? with | some (_, β) => do let u ← getLevel α let v ← getLevel β return mkApp8 (mkConst ``congr [u, v]) α β f g a b h₁ h₂ | _ => throwAppBuilderException ``congr ("non-dependent function expected" ++ hasTypeMsg h₁ hType₁) | none, _ => throwAppBuilderException ``congr ("equality proof expected" ++ hasTypeMsg h₁ hType₁) | _, none => throwAppBuilderException ``congr ("equality proof expected" ++ hasTypeMsg h₂ hType₂) private def mkAppMFinal (methodName : Name) (f : Expr) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do instMVars.forM fun mvarId => do let mvarDecl ← getMVarDecl mvarId let mvarVal ← synthInstance mvarDecl.type assignExprMVar mvarId mvarVal let result ← instantiateMVars (mkAppN f args) if (← hasAssignableMVar result) then throwAppBuilderException methodName ("result contains metavariables" ++ indentExpr result) return result private partial def mkAppMArgs (f : Expr) (fType : Expr) (xs : Array Expr) : MetaM Expr := let rec loop (type : Expr) (i : Nat) (j : Nat) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do if i >= xs.size then mkAppMFinal `mkAppM f args instMVars else match type with | Expr.forallE n d b c => let d := d.instantiateRevRange j args.size args match c.binderInfo with | BinderInfo.implicit => let mvar ← mkFreshExprMVar d MetavarKind.natural n loop b i j (args.push mvar) instMVars | BinderInfo.instImplicit => let mvar ← mkFreshExprMVar d MetavarKind.synthetic n loop b i j (args.push mvar) (instMVars.push mvar.mvarId!) | _ => let x := xs[i] let xType ← inferType x if (← isDefEq d xType) then loop b (i+1) j (args.push x) instMVars else throwAppTypeMismatch (mkAppN f args) x | type => let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then loop type i args.size args instMVars else throwAppBuilderException `mkAppM m!"too many explicit arguments provided to{indentExpr f}\narguments{indentD xs}" loop fType 0 0 #[] #[] private def mkFun (constName : Name) : MetaM (Expr × Expr) := do let cinfo ← getConstInfo constName let us ← cinfo.levelParams.mapM fun _ => mkFreshLevelMVar let f := mkConst constName us let fType := cinfo.instantiateTypeLevelParams us return (f, fType) /-- Return the application `constName xs`. It tries to fill the implicit arguments before the last element in `xs`. Remark: ``mkAppM `arbitrary #[α]`` returns `@arbitrary.{u} α` without synthesizing the implicit argument occurring after `α`. Given a `x : (([Decidable p] → Bool) × Nat`, ``mkAppM `Prod.fst #[x]`` returns `@Prod.fst ([Decidable p] → Bool) Nat x` -/ def mkAppM (constName : Name) (xs : Array Expr) : MetaM Expr := do traceCtx `Meta.appBuilder <| withNewMCtxDepth do let (f, fType) ← mkFun constName let r ← mkAppMArgs f fType xs trace[Meta.appBuilder]! "constName: {constName}, xs: {xs}, result: {r}" return r private partial def mkAppOptMAux (f : Expr) (xs : Array (Option Expr)) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr | i, args, j, instMVars, Expr.forallE n d b c => do let d := d.instantiateRevRange j args.size args if h : i < xs.size then match xs.get ⟨i, h⟩ with | none => match c.binderInfo with | BinderInfo.instImplicit => do let mvar ← mkFreshExprMVar d MetavarKind.synthetic n mkAppOptMAux f xs (i+1) (args.push mvar) j (instMVars.push mvar.mvarId!) b | _ => do let mvar ← mkFreshExprMVar d MetavarKind.natural n mkAppOptMAux f xs (i+1) (args.push mvar) j instMVars b | some x => let xType ← inferType x if (← isDefEq d xType) then mkAppOptMAux f xs (i+1) (args.push x) j instMVars b else throwAppTypeMismatch (mkAppN f args) x else mkAppMFinal `mkAppOptM f args instMVars | i, args, j, instMVars, type => do let type := type.instantiateRevRange j args.size args let type ← whnfD type if type.isForall then mkAppOptMAux f xs i args args.size instMVars type else if i == xs.size then mkAppMFinal `mkAppOptM f args instMVars else do let xs : Array Expr := xs.foldl (fun r x? => match x? with | none => r | some x => r.push x) #[] throwAppBuilderException `mkAppOptM ("too many arguments provided to" ++ indentExpr f ++ Format.line ++ "arguments" ++ xs) /-- Similar to `mkAppM`, but it allows us to specify which arguments are provided explicitly using `Option` type. Example: Given `Pure.pure {m : Type u → Type v} [Pure m] {α : Type u} (a : α) : m α`, ``` mkAppOptM `Pure.pure #[m, none, none, a] ``` returns a `Pure.pure` application if the instance `Pure m` can be synthesized, and the universes match. Note that, ``` mkAppM `Pure.pure #[a] ``` fails because the only explicit argument `(a : α)` is not sufficient for inferring the remaining arguments, we would need the expected type. -/ def mkAppOptM (constName : Name) (xs : Array (Option Expr)) : MetaM Expr := do traceCtx `Meta.appBuilder <| withNewMCtxDepth do let (f, fType) ← mkFun constName mkAppOptMAux f xs 0 #[] 0 #[] fType def mkEqNDRec (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf ``Eq.refl then return h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException ``Eq.ndrec ("equality proof expected" ++ hasTypeMsg h2 h2Type) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.sort u1 _) _ => return mkAppN (mkConst ``Eq.ndrec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException ``Eq.ndrec ("invalid motive" ++ indentExpr motive) def mkEqRec (motive h1 h2 : Expr) : MetaM Expr := do if h2.isAppOf ``Eq.refl then return h1 else let h2Type ← infer h2 match h2Type.eq? with | none => throwAppBuilderException ``Eq.rec ("equality proof expected" ++ indentExpr h2) | some (α, a, b) => let u2 ← getLevel α let motiveType ← infer motive match motiveType with | Expr.forallE _ _ (Expr.forallE _ _ (Expr.sort u1 _) _) _ => return mkAppN (mkConst ``Eq.rec [u1, u2]) #[α, a, motive, h1, b, h2] | _ => throwAppBuilderException ``Eq.rec ("invalid motive" ++ indentExpr motive) def mkEqMP (eqProof pr : Expr) : MetaM Expr := mkAppM ``Eq.mp #[eqProof, pr] def mkEqMPR (eqProof pr : Expr) : MetaM Expr := mkAppM ``Eq.mpr #[eqProof, pr] def mkNoConfusion (target : Expr) (h : Expr) : MetaM Expr := do let type ← inferType h let type ← whnf type match type.eq? with | none => throwAppBuilderException `noConfusion ("equality expected" ++ hasTypeMsg h type) | some (α, a, b) => let α ← whnf α matchConstInduct α.getAppFn (fun _ => throwAppBuilderException `noConfusion ("inductive type expected" ++ indentExpr α)) fun v us => do let u ← getLevel target return mkAppN (mkConst (Name.mkStr v.name "noConfusion") (u :: us)) (α.getAppArgs ++ #[target, a, b, h]) def mkPure (monad : Expr) (e : Expr) : MetaM Expr := mkAppOptM ``Pure.pure #[monad, none, none, e] /-- `mkProjection s fieldName` return an expression for accessing field `fieldName` of the structure `s`. Remark: `fieldName` may be a subfield of `s`. -/ partial def mkProjection : Expr → Name → MetaM Expr | s, fieldName => do let type ← inferType s let type ← whnf type match type.getAppFn with | Expr.const structName us _ => let env ← getEnv unless isStructureLike env structName do throwAppBuilderException `mkProjection ("structure expected" ++ hasTypeMsg s type) match getProjFnForField? env structName fieldName with | some projFn => let params := type.getAppArgs return mkApp (mkAppN (mkConst projFn us) params) s | none => let fields := getStructureFields env structName let r? ← fields.findSomeM? fun fieldName' => do match isSubobjectField? env structName fieldName' with | none => pure none | some _ => let parent ← mkProjection s fieldName' (do let r ← mkProjection parent fieldName; return some r) <|> pure none match r? with | some r => pure r | none => throwAppBuilderException `mkProjectionn ("invalid field name '" ++ toString fieldName ++ "' for" ++ hasTypeMsg s type) | _ => throwAppBuilderException `mkProjectionn ("structure expected" ++ hasTypeMsg s type) private def mkListLitAux (nil : Expr) (cons : Expr) : List Expr → Expr | [] => nil | x::xs => mkApp (mkApp cons x) (mkListLitAux nil cons xs) def mkListLit (type : Expr) (xs : List Expr) : MetaM Expr := do let u ← getDecLevel type let nil := mkApp (mkConst ``List.nil [u]) type match xs with | [] => return nil | _ => let cons := mkApp (mkConst ``List.cons [u]) type return mkListLitAux nil cons xs def mkArrayLit (type : Expr) (xs : List Expr) : MetaM Expr := do let u ← getDecLevel type let listLit ← mkListLit type xs return mkApp (mkApp (mkConst ``List.toArray [u]) type) listLit def mkSorry (type : Expr) (synthetic : Bool) : MetaM Expr := do let u ← getLevel type return mkApp2 (mkConst ``sorryAx [u]) type (toExpr synthetic) /-- Return `Decidable.decide p` -/ def mkDecide (p : Expr) : MetaM Expr := mkAppOptM ``Decidable.decide #[p, none] /-- Return a proof for `p : Prop` using `decide p` -/ def mkDecideProof (p : Expr) : MetaM Expr := do let decP ← mkDecide p let decEqTrue ← mkEq decP (mkConst ``Bool.true) let h ← mkEqRefl (mkConst ``Bool.true) let h ← mkExpectedTypeHint h decEqTrue mkAppM ``ofDecideEqTrue #[h] /-- Return `a < b` -/ def mkLt (a b : Expr) : MetaM Expr := mkAppM ``HasLess.Less #[a, b] /-- Return `a <= b` -/ def mkLe (a b : Expr) : MetaM Expr := mkAppM ``HasLessEq.LessEq #[a, b] /-- Return `arbitrary α` -/ def mkArbitrary (α : Expr) : MetaM Expr := mkAppOptM ``arbitrary #[α, none] /-- Return `sorryAx type` -/ def mkSyntheticSorry (type : Expr) : MetaM Expr := return mkApp2 (mkConst ``sorryAx [← getLevel type]) type (mkConst ``Bool.true) /-- Return `funext h` -/ def mkFunExt (h : Expr) : MetaM Expr := mkAppM ``funext #[h] /-- Return `propext h` -/ def mkPropExt (h : Expr) : MetaM Expr := mkAppM ``propext #[h] /-- Return `ofEqTrue h` -/ def mkOfEqTrue (h : Expr) : MetaM Expr := mkAppM ``ofEqTrue #[h] /-- Return `eqTrue h` -/ def mkEqTrue (h : Expr) : MetaM Expr := mkAppM ``eqTrue #[h] /-- Return `eqFalse h` `h` must have type definitionally equal to `¬ p` in the current reducibility setting. -/ def mkEqFalse (h : Expr) : MetaM Expr := mkAppM ``eqFalse #[h] /-- Return `eqFalse' h` `h` must have type definitionally equal to `p → False` in the current reducibility setting. -/ def mkEqFalse' (h : Expr) : MetaM Expr := mkAppM ``eqFalse' #[h] def mkImpCongr (h₁ h₂ : Expr) : MetaM Expr := mkAppM ``impCongr #[h₁, h₂] def mkImpCongrCtx (h₁ h₂ : Expr) : MetaM Expr := mkAppM ``impCongrCtx #[h₁, h₂] def mkForallCongr (h : Expr) : MetaM Expr := mkAppM ``forallCongr #[h] /-- Return instance for `[Monad m]` if there is one -/ def isMonad? (m : Expr) : MetaM (Option Expr) := try let monadType ← mkAppM `Monad #[m] let result ← trySynthInstance monadType match result with | LOption.some inst => pure inst | _ => pure none catch _ => pure none /-- Return `(n : type)`, a numeric literal of type `type`. The method fails if we don't have an instance `OfNat type n` -/ def mkNumeral (type : Expr) (n : Nat) : MetaM Expr := do let u ← getDecLevel type let inst ← synthInstance (mkApp2 (mkConst ``OfNat [u]) type (mkNatLit n)) return mkApp3 (mkConst ``OfNat.ofNat [u]) type (mkNatLit n) inst /-- Return `a op b`, where `op` has name `opName` and is implemented using the typeclass `className`. This method assumes `a` and `b` have the same type, and typeclass `className` is heterogeneous. Examples of supported clases: `HAdd`, `HSub`, `HMul`. We use heterogeneous operators to ensure we have a uniform representation. -/ private def mkBinaryOp (className : Name) (opName : Name) (a b : Expr) : MetaM Expr := do let aType ← inferType a let u ← getDecLevel aType let inst ← synthInstance (mkApp3 (mkConst className [u, u, u]) aType aType aType) return mkApp6 (mkConst opName [u, u, u]) aType aType aType inst a b /-- Return `a + b` using a heterogeneous `+`. This method assumes `a` and `b` have the same type. -/ def mkAdd (a b : Expr) : MetaM Expr := mkBinaryOp ``HAdd ``HAdd.hAdd a b /-- Return `a - b` using a heterogeneous `-`. This method assumes `a` and `b` have the same type. -/ def mkSub (a b : Expr) : MetaM Expr := mkBinaryOp ``HSub ``HSub.hSub a b /-- Return `a * b` using a heterogeneous `*`. This method assumes `a` and `b` have the same type. -/ def mkMul (a b : Expr) : MetaM Expr := mkBinaryOp ``HMul ``HMul.hMul a b builtin_initialize registerTraceClass `Meta.appBuilder end Lean.Meta
824cb3f03dbac673980937a21b13c36e9875f08a
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/set_theory/cofinality.lean
a49386ae13fc3221db0ce6d2a7df3acb81268f00
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
17,376
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Cofinality on ordinals, regular cardinals. -/ import set_theory.ordinal noncomputable theory open function cardinal local attribute [instance] classical.prop_decidable universes u v w variables {α : Type*} {r : α → α → Prop} /-- Cofinality of a reflexive order `≼`. This is the smallest cardinality of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/ def order.cof (r : α → α → Prop) [is_refl α r] : cardinal := @cardinal.min {S : set α // ∀ a, ∃ b ∈ S, r a b} ⟨⟨set.univ, λ a, ⟨a, ⟨⟩, refl _⟩⟩⟩ (λ S, mk S) theorem order_iso.cof.aux {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃o s) : cardinal.lift.{u (max u v)} (order.cof r) ≤ cardinal.lift.{v (max u v)} (order.cof s) := begin rw [order.cof, order.cof, lift_min, lift_min, cardinal.le_min], intro S, cases S with S H, simp [(∘)], refine le_trans (min_le _ _) _, { exact ⟨f ⁻¹' S, λ a, let ⟨b, bS, h⟩ := H (f a) in ⟨f.symm b, by simp [bS, f.ord', h, -coe_fn_coe_base, -coe_fn_coe_trans, principal_seg.coe_coe_fn', initial_seg.coe_coe_fn]⟩⟩ }, { exact lift_mk_le.{u v (max u v)}.2 ⟨⟨λ ⟨x, h⟩, ⟨f x, h⟩, λ ⟨x, h₁⟩ ⟨y, h₂⟩ h₃, by congr; injection h₃ with h'; exact f.to_equiv.bijective.1 h'⟩⟩ } end theorem order_iso.cof {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃o s) : cardinal.lift.{u (max u v)} (order.cof r) = cardinal.lift.{v (max u v)} (order.cof s) := le_antisymm (order_iso.cof.aux f) (order_iso.cof.aux f.symm) namespace ordinal /-- Cofinality of an ordinal. This is the smallest cardinal of a subset `S` of the ordinal which is unbounded, in the sense `∀ a, ∃ b ∈ S, a ≤ b`. It is defined for all ordinals, but `cof 0 = 0` and `cof (succ o) = 1`, so it is only really interesting on limit ordinals (when it is an infinite cardinal). -/ def cof (o : ordinal.{u}) : cardinal.{u} := quot.lift_on o (λ ⟨α, r, _⟩, @order.cof α (λ x y, ¬ r y x) ⟨λ a, by resetI; apply irrefl⟩) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨⟨f, hf⟩⟩, begin show @order.cof α (λ x y, ¬ r y x) ⟨_⟩ = @order.cof β (λ x y, ¬ s y x) ⟨_⟩, refine cardinal.lift_inj.1 (@order_iso.cof _ _ _ _ ⟨_⟩ ⟨_⟩ _), exact ⟨f, λ a b, not_congr hf⟩, end theorem le_cof_type [is_well_order α r] {c} : c ≤ cof (type r) ↔ ∀ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) → c ≤ mk S := by dsimp [cof, order.cof, type, quotient.mk, quot.lift_on]; rw [cardinal.le_min, subtype.forall]; refl theorem cof_type_le [is_well_order α r] (S : set α) (h : ∀ a, ∃ b ∈ S, ¬ r b a) : cof (type r) ≤ mk S := le_cof_type.1 (le_refl _) S h theorem lt_cof_type [is_well_order α r] (S : set α) (hl : mk S < cof (type r)) : ∃ a, ∀ b ∈ S, r b a := not_forall_not.1 $ λ h, not_le_of_lt hl $ cof_type_le S (λ a, not_ball.1 (h a)) theorem cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ mk S = cof (type r) := begin have : ∃ i, cof (type r) = _, { dsimp [cof, order.cof, type, quotient.mk, quot.lift_on], apply cardinal.min_eq }, exact let ⟨⟨S, hl⟩, e⟩ := this in ⟨S, hl, e.symm⟩, end theorem ord_cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ type (subrel r S) = (cof (type r)).ord := let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S, T : set α := {a | ∃ aS : a ∈ S, ∀ b : S, s b ⟨_, aS⟩ → r b a} in begin resetI, suffices, { refine ⟨T, this, le_antisymm _ (cardinal.ord_le.2 $ cof_type_le T this)⟩, rw [← e, e'], refine type_le'.2 ⟨order_embedding.of_monotone (λ a, ⟨a, let ⟨aS, _⟩ := a.2 in aS⟩) (λ a b h, _)⟩, rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩, change s ⟨a, _⟩ ⟨b, _⟩, refine ((trichotomous_of s _ _).resolve_left (λ hn, _)).resolve_left _, { exact asymm h (ha _ hn) }, { intro e, injection e with e, subst b, exact irrefl _ h } }, { intro a, have : {b : S | ¬ r b a} ≠ ∅ := let ⟨b, bS, ba⟩ := hS a in @set.ne_empty_of_mem S {b | ¬ r b a} ⟨b, bS⟩ ba, let b := (is_well_order.wf s).min _ this, have ba : ¬r b a := (is_well_order.wf s).min_mem _ this, refine ⟨b, ⟨b.2, λ c, not_imp_not.1 $ λ h, _⟩, ba⟩, rw [show ∀b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl], exact (is_well_order.wf s).not_lt_min _ this (is_order_connected.neg_trans h ba) } end theorem lift_cof (o) : (cof o).lift = cof o.lift := induction_on o $ begin introsI α r _, cases lift_type r with _ e, rw e, apply le_antisymm, { refine le_cof_type.2 (λ S H, _), have : (mk (ulift.up ⁻¹' S)).lift ≤ mk S := ⟨⟨λ ⟨⟨x, h⟩⟩, ⟨⟨x⟩, h⟩, λ ⟨⟨x, h₁⟩⟩ ⟨⟨y, h₂⟩⟩ e, by simp at e; congr; injection e⟩⟩, refine le_trans (cardinal.lift_le.2 $ cof_type_le _ _) this, exact λ a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ }, { rcases cof_eq r with ⟨S, H, e'⟩, have : mk (ulift.down ⁻¹' S) ≤ (mk S).lift := ⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩, λ ⟨⟨x⟩, h₁⟩ ⟨⟨y⟩, h₂⟩ e, by simp at e; congr; injections⟩⟩, rw e' at this, refine le_trans (cof_type_le _ _) this, exact λ ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ } end theorem cof_le_card (o) : cof o ≤ card o := induction_on o $ λ α r _, begin resetI, have : mk (@set.univ α) = card (type r) := quotient.sound ⟨equiv.set.univ _⟩, rw ← this, exact cof_type_le set.univ (λ a, ⟨a, ⟨⟩, irrefl a⟩) end theorem cof_ord_le (c : cardinal) : cof c.ord ≤ c := by simpa using cof_le_card c.ord @[simp] theorem cof_zero : cof 0 = 0 := le_antisymm (by simpa using cof_le_card 0) (cardinal.zero_le _) @[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ z, by exactI let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_empty.2 $ λ ⟨a⟩, let ⟨b, h, _⟩ := hl a in ne_zero_iff_nonempty.2 (by exact ⟨⟨_, h⟩⟩) (e.trans z), λ e, by simp [e]⟩ @[simp] theorem cof_succ (o) : cof (succ o) = 1 := begin apply le_antisymm, { refine induction_on o (λ α r _, _), change cof (type _) ≤ _, rw [← (_ : mk _ = 1)], apply cof_type_le, { refine λ a, ⟨sum.inr punit.star, set.mem_singleton _, _⟩, rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] }, { rw [cardinal.fintype_card, set.card_singleton], simp } }, { rw [← cardinal.succ_zero, cardinal.succ_le], simpa [lt_iff_le_and_ne, cardinal.zero_le] using λ h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) } end @[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ ∃ a, o = succ a := ⟨induction_on o $ λ α r _ z, begin resetI, rcases cof_eq r with ⟨S, hl, e⟩, rw z at e, cases ne_zero_iff_nonempty.1 (by rw e; exact one_ne_zero) with a, refine ⟨typein r a, eq.symm $ quotient.sound ⟨order_iso.of_surjective (order_embedding.of_monotone _ (λ x y, _)) (λ x, _)⟩⟩, { apply sum.rec; [exact subtype.val, exact λ _, a] }, { rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩; simp [subrel, order.preimage, empty_relation], exact x.2 }, { suffices : r x a ∨ ∃ (b : punit), ↑a = x, {simpa}, rcases trichotomous_of r x a with h|h|h, { exact or.inl h }, { exact or.inr ⟨punit.star, h.symm⟩ }, { rcases hl x with ⟨a', aS, hn⟩, rw (_ : ↑a = a') at h, {exact absurd h hn}, refine congr_arg subtype.val (_ : a = ⟨a', aS⟩), haveI := le_one_iff_subsingleton.1 (le_of_eq e), apply subsingleton.elim } } end, λ ⟨a, e⟩, by simp [e]⟩ @[simp] theorem cof_add (a b : ordinal) : b ≠ 0 → cof (a + b) = cof b := induction_on a $ λ α r _, induction_on b $ λ β s _ b0, begin resetI, change cof (type _) = _, refine eq_of_forall_le_iff (λ c, _), rw [le_cof_type, le_cof_type], split; intros H S hS, { refine le_trans (H {a | sum.rec_on a (∅:set α) S} (λ a, _)) ⟨⟨_, _⟩⟩, { cases a with a b, { cases type_ne_zero_iff_nonempty.1 b0 with b, rcases hS b with ⟨b', bs, _⟩, exact ⟨sum.inr b', bs, by simp⟩ }, { rcases hS b with ⟨b', bs, h⟩, exact ⟨sum.inr b', bs, by simp [h]⟩ } }, { exact λ a, match a with ⟨sum.inr b, h⟩ := ⟨b, h⟩ end }, { exact λ a b, match a, b with ⟨sum.inr a, h₁⟩, ⟨sum.inr b, h₂⟩, h := by congr; injection h end } }, { refine le_trans (H (sum.inr ⁻¹' S) (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS (sum.inr a) with ⟨a'|b', bs, h⟩; simp at h, { cases h }, { exact ⟨b', bs, h⟩ } }, { exact λ ⟨a, h⟩, ⟨_, h⟩ }, { exact λ ⟨a, h₁⟩ ⟨b, h₂⟩ h, by injection h with h; congr; injection h } } end @[simp] theorem cof_cof (o : ordinal) : cof (cof o).ord = cof o := le_antisymm (le_trans (cof_le_card _) (by simp)) $ induction_on o $ λ α r _, by exactI let ⟨S, hS, e₁⟩ := ord_cof_eq r, ⟨T, hT, e₂⟩ := cof_eq (subrel r S) in begin rw e₁ at e₂, rw ← e₂, refine le_trans (cof_type_le {a | ∃ h, (subtype.mk a h : S) ∈ T} (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS a with ⟨b, bS, br⟩, rcases hT ⟨b, bS⟩ with ⟨⟨c, cS⟩, cT, cs⟩, exact ⟨c, ⟨cS, cT⟩, is_order_connected.neg_trans cs br⟩ }, { exact λ ⟨a, h⟩, ⟨⟨a, h.fst⟩, h.snd⟩ }, { exact λ ⟨a, ha⟩ ⟨b, hb⟩ h, by injection h with h; congr; injection h }, end theorem omega_le_cof {o} : cardinal.omega ≤ cof o ↔ is_limit o := begin rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l, { simp [not_zero_is_limit, cardinal.omega_ne_zero] }, { simp [not_succ_is_limit, cardinal.one_lt_omega] }, { simp [l], refine le_of_not_lt (λ h, _), cases cardinal.lt_omega.1 h with n e, have := cof_cof o, rw [e, ord_nat] at this, cases n, { simp at e, simpa [e, not_zero_is_limit] using l }, { rw [← nat_cast_succ, cof_succ] at this, rw [← this, cof_eq_one_iff_is_succ] at e, rcases e with ⟨a, rfl⟩, exact not_succ_is_limit _ l } } end @[simp] theorem cof_omega : cof omega = cardinal.omega := le_antisymm (by rw ← card_omega; apply cof_le_card) (omega_le_cof.2 omega_is_limit) theorem cof_eq' (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) : ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ mk S = cof (type r) := let ⟨S, H, e⟩ := cof_eq r in ⟨S, λ a, let a' := enum r _ (h.2 _ (typein_lt_type r a)) in let ⟨b, h, ab⟩ := H a' in ⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1 (by rw typein_enum; apply ordinal.lt_succ_self)).resolve_right ab⟩, e⟩ theorem cof_sup_le_lift {ι} (f : ι → ordinal) (H : ∀ i, f i < sup f) : cof (sup f) ≤ (mk ι).lift := begin generalize e : sup f = o, refine ordinal.induction_on o _ e, introsI α r _ e', rw e' at H, refine le_trans (cof_type_le (set.range (λ i, enum r _ (H i))) _) ⟨embedding.of_surjective _⟩, { intro a, by_contra h, apply not_le_of_lt (typein_lt_type r a), rw [← e', sup_le], intro i, simp [set.range] at h, simpa using le_of_lt ((typein_lt_typein r).2 (h _ i rfl)) }, { exact λ i, ⟨_, set.mem_range_self i.1⟩ }, { intro a, rcases a with ⟨_, i, rfl⟩, exact ⟨⟨i⟩, by simp⟩ } end theorem cof_sup_le {ι} (f : ι → ordinal) (H : ∀ i, f i < sup.{u u} f) : cof (sup.{u u} f) ≤ mk ι := by simpa using cof_sup_le_lift.{u u} f H theorem cof_bsup_le_lift {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup o f) → cof (bsup o f) ≤ o.card.lift := induction_on o $ λ α r _ f H, by rw bsup_type; refine cof_sup_le_lift _ _; rw ← bsup_type; intro a; apply H theorem cof_bsup_le {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup.{u u} o f) → cof (bsup.{u u} o f) ≤ o.card := induction_on o $ λ α r _ f H, by simpa using cof_bsup_le_lift.{u u} f H @[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ := le_antisymm (cof_le_card _) begin refine le_of_forall_lt (λ c h, _), rcases lt_univ'.1 h with ⟨c, rfl⟩, rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩, rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se], refine lt_of_not_ge (λ h, _), cases cardinal.lift_down h with a e, refine quotient.induction_on a (λ α e, _) e, cases quotient.exact e with f, have f := equiv.ulift.symm.trans f, let g := λ a, (f a).1, let o := succ (sup.{u u} g), rcases H o with ⟨b, h, l⟩, refine l (lt_succ.2 _), rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp, apply le_sup end end ordinal namespace cardinal open ordinal local infixr ^ := @pow cardinal.{u} cardinal cardinal.has_pow /-- A cardinal is a limit if it is not zero or a successor cardinal. Note that `ω` is a limit cardinal by this definition. -/ def is_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, succ x < c /-- A cardinal is a strong limit if it is not zero and it is closed under powersets. Note that `ω` is a strong limit by this definition. -/ def is_strong_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, 2 ^ x < c theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c := ⟨H.1, λ x h, lt_of_le_of_lt (succ_le.2 $ cantor _) (H.2 _ h)⟩ /-- A cardinal is regular if it is infinite and it equals its own cofinality. -/ def is_regular (c : cardinal) : Prop := omega ≤ c ∧ c.ord.cof = c theorem cof_is_regular {o : ordinal} (h : o.is_limit) : is_regular o.cof := ⟨omega_le_cof.2 h, cof_cof _⟩ theorem omega_is_regular : is_regular omega := ⟨le_refl _, by simp⟩ theorem succ_is_regular {c : cardinal.{u}} (h : omega ≤ c) : is_regular (succ c) := ⟨le_trans h (le_of_lt $ lt_succ_self _), begin refine le_antisymm (cof_ord_le _) (succ_le.2 _), cases quotient.exists_rep (succ c) with α αe, simp at αe, rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit (le_trans h $ le_of_lt $ lt_succ_self _), rw [← αe, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, rw [← Se], apply lt_imp_lt_of_le_imp_le (mul_le_mul_right c), rw [mul_eq_self h, ← succ_le, ← αe, ← sum_const], refine le_trans _ (sum_le_sum (λ x:S, card (typein r x)) _ _), { simp [typein, sum_mk (λ x:S, {a//r a x})], refine ⟨embedding.of_surjective _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { intro i, rw [← lt_succ, ← lt_ord, ← αe, re], apply typein_lt_type } end⟩ theorem sup_lt_of_is_regular {ι} (f : ι → cardinal) {c} (hc : is_regular c) (H1 : cardinal.mk ι < c) (H2 : ∀ i, f i < c) : sup.{u u} f < c := begin refine lt_of_le_of_ne (sup_le.2 (λ i, le_of_lt $ H2 i)) _, rintro rfl, apply not_le_of_lt H1, simpa [sup_ord, H2, hc.2] using cof_sup_le.{u} (λ i, (f i).ord) end theorem sum_lt_of_is_regular {ι} (f : ι → cardinal) {c} (hc : is_regular c) (H1 : cardinal.mk ι < c) (H2 : ∀ i, f i < c) : sum.{u u} f < c := lt_of_le_of_lt (sum_le_sup _) $ mul_lt_of_lt hc.1 H1 $ sup_lt_of_is_regular f hc H1 H2 /-- A cardinal is inaccessible if it is an uncountable regular strong limit cardinal. -/ def is_inaccessible (c : cardinal) := omega < c ∧ is_regular c ∧ is_strong_limit c theorem is_inaccessible.mk {c} (h₁ : omega < c) (h₂ : c ≤ c.ord.cof) (h₃ : ∀ x < c, 2 ^ x < c) : is_inaccessible c := ⟨h₁, ⟨le_of_lt h₁, le_antisymm (cof_ord_le _) h₂⟩, ne_of_gt (lt_trans omega_pos h₁), h₃⟩ /- Lean's foundations prove the existence of ω many inaccessible cardinals -/ theorem univ_inaccessible : is_inaccessible (univ.{u v}) := is_inaccessible.mk (by simpa using lift_lt_univ' omega) (by simp) (λ c h, begin rcases lt_univ'.1 h with ⟨c, rfl⟩, rw ← lift_two_power.{u (max (u+1) v)}, apply lift_lt_univ' end) theorem lt_power_cof {c : cardinal.{u}} : omega ≤ c → c < c ^ cof c.ord := quotient.induction_on c $ λ α h, begin rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit h, rw [mk_def, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, have := sum_lt_prod (λ a:S, mk {x // r x a}) (λ _, mk α) (λ i, _), { simp [Se.symm] at this ⊢, refine lt_of_le_of_lt _ this, refine ⟨embedding.of_surjective _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { have := typein_lt_type r i, rwa [← re, lt_ord] at this } end theorem lt_cof_power {a b : cardinal} (ha : omega ≤ a) (b1 : 1 < b) : a < cof (b ^ a).ord := begin have b0 : b ≠ 0 := ne_of_gt (lt_trans zero_lt_one b1), apply lt_imp_lt_of_le_imp_le (power_le_power_left $ power_ne_zero a b0), rw [power_mul, mul_eq_self ha], exact lt_power_cof (le_trans ha $ le_of_lt $ cantor' _ b1), end end cardinal
f03d923f8ba2ffb031985f0cef65c489356b47e6
359199d7253811b032ab92108191da7336eba86e
/src/homework/practice_1b.lean
d7c56a6473b93432f1ab5eaf18f72ce3ff33eb67
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
6,803
lean
/- secret code name: groundhog Yashavi Prakash, yp3ez, github url: https://github.com/yashaviprakash/cs2120f21.git Jacqueline Chao, jc7rw, github url: https://github.com/arte-et-marte/my_cs2120f21.git -/ /- EQUALITY -/ /- #1 Suppose that x, y, z, and w are arbitrary objects of some type, T; and suppose further that we know (have proofs of the facts) that x = y, y = z, and w = z. Give a very, very short English proof of the conjecture that z = w. You can use not only the axioms of equality, but either of the theorems about properties of equality that we have proven. Hint: There's something about this question that makes it much easier to answer than it might at first appear. Answer: By the theorem that states that equality is symmetric, we can prove that z=w by the axiom of substutability and the axiom of reflexivity. QED. -/ /- #2 Give a formal statement of the conjecture (proposition) from #1 by filling in the "hole" in the following definition. The def is a keyword. The name you're binding to your proposition is prop_1. The type of the value is Prop (which is the type of all propositions in Lean). -/ def prop_1 : Prop := ∀ (T: Type) (x y z w: T) (e1: x = y) (e2: y = z) (e3: w = z), z = w /- #3 (extra credit) Give a formal proof of the proposition from #2 by filling in the hole in this next definition. Hint: Use Lean's versions of the axioms and basic theorems concerning equality. They are, again, called eq.refl, eq.subst, eq.symm, eq.trans. -/ theorem prop_1_proof : prop_1 := begin assume T x y z w e1 e2 e3, apply eq.symm, exact e3, end /- FOR ALL: ∀. -/ /- #4 Give a very brief explanation in English of the introduction rule for ∀. For example, suppose you need to prove (∀ x, P x); what do you do? (I'm being a little informal in leaving out the type of X.) Answer: Assume arbritary x of type T, then show that x shares property P of all types T. -/ /- #5 Suppose you have a proof, let's call it pf, of the proposition, (∀ x, P x), and you need a proof of P t, for some particular t. Write an expression then uses the elimination rule for ∀ to get such a proof. Complete the answer by replacing the underscores in the following expression: ( _ _ ). Answer: apply pf t -/ /- IMPLIES: → In the "code" that follows, we define two predicates, each taking one natural number as an argument. We call them ev and odd. When applied to any value, n, ev yields the proposition that n is even (n % 2 = 0), while odd yields the proposition that n is odd (n % 2 = 1). -/ def ev (n : ℕ) := n % 2 = 0 def odd (n : ℕ) := n % 2 = 1 /- #6 Write a formal version of the proposition that, for *any* natural number n, *if* n is even, *then* n + 1 is odd. Give your answer by filling the hole in the following definition. Hint: put parenthesis around "n + 1" in your answer. -/ def successor_of_even_is_odd : Prop := ∀ (n: ℕ), n % 2 = 0 → (n+1) % 2 = 1 /- #7 Suppose that "its_raining" and "the_streets_are_wet" are propositions. (We formalize these assumptions as axioms in what follows. Then give a formal definition of the (larger) proposition, "if it's raining out then the streets are wet") by filling in the hole -/ axioms (raining streets_wet : Prop) axiom if_raining_then_streets_wet : raining → streets_wet /- #9 Now suppose that in addition, its_raining is true, and we have a proof of it, pf_its_raining. Again, we again give you this assumption formally as an axiom below. Finish the formal proof that the streets must be wet. Hint: here you are asked to use the elimination rule for →. -/ axiom pf_raining : raining example : streets_wet := begin apply if_raining_then_streets_wet pf_raining, end /- AND: ∧ -/ /- #10 In our last class, we proved that "∧ is *commutative*." That is, for any given *propositions*, P and Q, (P ∧ Q) → (Q ∧ P). The way we proved it was to *assume* that we're given such a P, Q, and proof, pq, of (P ∧ Q) -- applying the introduction rules for ∀ and →). In this context, we *use* the proof, pq, to derive separate proofs, let's call them p, a proof of P, and q, a proof of Q. With these in hand, we then apply the introduction rule for ∧ to put them back together into a proof of (Q ∧ P). We give you a formal version of this proof as a reminder, next. -/ theorem and_commutative : ∀ (P Q : Prop), P ∧ Q → Q ∧ P := begin assume P Q pq, apply and.intro _ _, exact (and.elim_right pq), exact (and.elim_left pq), end /- Your task now is to prove the theorem, "∧ is *associative*." What this means is that for arbitrary propositions, P, Q, and R, if (P ∧ (Q ∧ R)) is true, then ((P ∧ Q) ∧ R) is true, *and vice versa*. You just need to prove it in the first direction. Hint, if you have a proof, p_qr, of (P ∧ (Q ∧ R)), then the application of and.elim_left will give you a proof of P, and and.elim_right will give you a proof of (Q ∧ R). To help you along, we give you the first part of the proof, including an example of a new Lean tactic called have, which allows you to give a name to a new value in the middle of a proof script. -/ theorem and_associative : ∀ (P Q R : Prop), (P ∧ (Q ∧ R)) → ((P ∧ Q) ∧ R) := begin intros P Q R h, have p : P := and.elim_left h, have qr : Q ∧ R := and.elim_right h, have q : Q := and.elim_left qr, have r : R := and.elim_right qr, apply and.intro (and.intro p q) r, end /- #11 Give an English language proof of the preceding theorem. Do it by finishing off the following partial "proof explanation." Proof. We assume that P, Q, and R are arbitrary but specific propositions, and that we have a proof, let's call it p_qr, of (P ∧ (Q ∧ R)) [by application of ∧ and → introduction.] What now remains to be proved is ((P ∧ Q) ∧ R). We can construct a proof of this proposition by applying _____ to a proof of (P ∧ Q) and a proof of R. What remains, then, is to obtain these proofs. But this is easily done by the application of ____ to ____. QED. Answer: We assume that P, Q, and R are arbitrary but specific propositions, and that we have a proof, let's call it p_qr, of (P ∧ (Q ∧ R)) [by application of ∧ and → introduction.] What now remains to be proved is ((P ∧ Q) ∧ R). We can construct a proof of this proposition by applying "the and introduction rule" to a proof of (P ∧ Q) and a proof of R. What remains, then, is to obtain these proofs. But this is easily done by the application of "the and elimination rule" to "pq_r". QED. -/ /- Note that Lean includes versions of these theorems (and many, many, many others) in its extensive library of formalized maths, as the following check commands reveal. Note the difference in naming relative to the definitions we give in this file. -/ #check @and.comm #check @and.assoc
0825d06368374ce1e4a39dc47ff768505e7aac38
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/polynomial/homogeneous.lean
aab46047cd89a4458d71b4254499f99527c0e871
[ "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
10,890
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Eric Wieser -/ import algebra.direct_sum.internal import algebra.graded_monoid import data.fintype.card import data.mv_polynomial.variables /-! # Homogeneous polynomials A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. ## Main definitions/lemmas * `is_homogeneous φ n`: a predicate that asserts that `φ` is homogeneous of degree `n`. * `homogeneous_submodule σ R n`: the submodule of homogeneous polynomials of degree `n`. * `homogeneous_component n`: the additive morphism that projects polynomials onto their summand that is homogeneous of degree `n`. * `sum_homogeneous_component`: every polynomial is the sum of its homogeneous components -/ open_locale big_operators namespace mv_polynomial variables {σ : Type*} {τ : Type*} {R : Type*} {S : Type*} /- TODO * create definition for `∑ i in d.support, d i` * show that `mv_polynomial σ R ≃ₐ[R] ⨁ i, homogeneous_submodule σ R i` -/ /-- A multivariate polynomial `φ` is homogeneous of degree `n` if all monomials occuring in `φ` have degree `n`. -/ def is_homogeneous [comm_semiring R] (φ : mv_polynomial σ R) (n : ℕ) := ∀ ⦃d⦄, coeff d φ ≠ 0 → ∑ i in d.support, d i = n variables (σ R) /-- The submodule of homogeneous `mv_polynomial`s of degree `n`. -/ def homogeneous_submodule [comm_semiring R] (n : ℕ) : submodule R (mv_polynomial σ R) := { carrier := { x | x.is_homogeneous n }, smul_mem' := λ r a ha c hc, begin rw coeff_smul at hc, apply ha, intro h, apply hc, rw h, exact smul_zero r, end, zero_mem' := λ d hd, false.elim (hd $ coeff_zero _), add_mem' := λ a b ha hb c hc, begin rw coeff_add at hc, obtain h|h : coeff c a ≠ 0 ∨ coeff c b ≠ 0, { contrapose! hc, simp only [hc, add_zero] }, { exact ha h }, { exact hb h } end } variables {σ R} @[simp] lemma mem_homogeneous_submodule [comm_semiring R] (n : ℕ) (p : mv_polynomial σ R) : p ∈ homogeneous_submodule σ R n ↔ p.is_homogeneous n := iff.rfl variables (σ R) /-- While equal, the former has a convenient definitional reduction. -/ lemma homogeneous_submodule_eq_finsupp_supported [comm_semiring R] (n : ℕ) : homogeneous_submodule σ R n = finsupp.supported _ R {d | ∑ i in d.support, d i = n} := begin ext, rw [finsupp.mem_supported, set.subset_def], simp only [finsupp.mem_support_iff, finset.mem_coe], refl, end variables {σ R} lemma homogeneous_submodule_mul [comm_semiring R] (m n : ℕ) : homogeneous_submodule σ R m * homogeneous_submodule σ R n ≤ homogeneous_submodule σ R (m + n) := begin rw submodule.mul_le, intros φ hφ ψ hψ c hc, rw [coeff_mul] at hc, obtain ⟨⟨d, e⟩, hde, H⟩ := finset.exists_ne_zero_of_sum_ne_zero hc, have aux : coeff d φ ≠ 0 ∧ coeff e ψ ≠ 0, { contrapose! H, by_cases h : coeff d φ = 0; simp only [*, ne.def, not_false_iff, zero_mul, mul_zero] at * }, specialize hφ aux.1, specialize hψ aux.2, rw finsupp.mem_antidiagonal at hde, classical, have hd' : d.support ⊆ d.support ∪ e.support := finset.subset_union_left _ _, have he' : e.support ⊆ d.support ∪ e.support := finset.subset_union_right _ _, rw [← hde, ← hφ, ← hψ, finset.sum_subset (finsupp.support_add), finset.sum_subset hd', finset.sum_subset he', ← finset.sum_add_distrib], { congr }, all_goals { intros i hi, apply finsupp.not_mem_support_iff.mp }, end section variables [comm_semiring R] variables {σ R} lemma is_homogeneous_monomial (d : σ →₀ ℕ) (r : R) (n : ℕ) (hn : ∑ i in d.support, d i = n) : is_homogeneous (monomial d r) n := begin intros c hc, classical, rw coeff_monomial at hc, split_ifs at hc with h, { subst c, exact hn }, { contradiction } end variables (σ) {R} lemma is_homogeneous_of_total_degree_zero {p : mv_polynomial σ R} (hp : p.total_degree = 0) : is_homogeneous p 0 := begin erw [total_degree, finset.sup_eq_bot_iff] at hp, -- we have to do this in two steps to stop simp changing bot to zero simp_rw [mem_support_iff] at hp, exact hp, end lemma is_homogeneous_C (r : R) : is_homogeneous (C r : mv_polynomial σ R) 0 := begin apply is_homogeneous_monomial, simp only [finsupp.zero_apply, finset.sum_const_zero], end variables (σ R) lemma is_homogeneous_zero (n : ℕ) : is_homogeneous (0 : mv_polynomial σ R) n := (homogeneous_submodule σ R n).zero_mem lemma is_homogeneous_one : is_homogeneous (1 : mv_polynomial σ R) 0 := is_homogeneous_C _ _ variables {σ} (R) lemma is_homogeneous_X (i : σ) : is_homogeneous (X i : mv_polynomial σ R) 1 := begin apply is_homogeneous_monomial, simp only [finsupp.support_single_ne_zero one_ne_zero, finset.sum_singleton], exact finsupp.single_eq_same end end namespace is_homogeneous variables [comm_semiring R] {φ ψ : mv_polynomial σ R} {m n : ℕ} lemma coeff_eq_zero (hφ : is_homogeneous φ n) (d : σ →₀ ℕ) (hd : ∑ i in d.support, d i ≠ n) : coeff d φ = 0 := by { have aux := mt (@hφ d) hd, classical, rwa not_not at aux } lemma inj_right (hm : is_homogeneous φ m) (hn : is_homogeneous φ n) (hφ : φ ≠ 0) : m = n := begin obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero hφ, rw [← hm hd, ← hn hd] end lemma add (hφ : is_homogeneous φ n) (hψ : is_homogeneous ψ n) : is_homogeneous (φ + ψ) n := (homogeneous_submodule σ R n).add_mem hφ hψ lemma sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) n) : is_homogeneous (∑ i in s, φ i) n := (homogeneous_submodule σ R n).sum_mem h lemma mul (hφ : is_homogeneous φ m) (hψ : is_homogeneous ψ n) : is_homogeneous (φ * ψ) (m + n) := homogeneous_submodule_mul m n $ submodule.mul_mem_mul hφ hψ lemma prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) (n : ι → ℕ) (h : ∀ i ∈ s, is_homogeneous (φ i) (n i)) : is_homogeneous (∏ i in s, φ i) (∑ i in s, n i) := begin classical, revert h, apply finset.induction_on s, { intro, simp only [is_homogeneous_one, finset.sum_empty, finset.prod_empty] }, { intros i s his IH h, simp only [his, finset.prod_insert, finset.sum_insert, not_false_iff], apply (h i (finset.mem_insert_self _ _)).mul (IH _), intros j hjs, exact h j (finset.mem_insert_of_mem hjs) } end lemma total_degree (hφ : is_homogeneous φ n) (h : φ ≠ 0) : total_degree φ = n := begin rw total_degree, apply le_antisymm, { apply finset.sup_le, intros d hd, rw mem_support_iff at hd, rw [finsupp.sum, hφ hd], }, { obtain ⟨d, hd⟩ : ∃ d, coeff d φ ≠ 0 := exists_coeff_ne_zero h, simp only [← hφ hd, finsupp.sum], replace hd := finsupp.mem_support_iff.mpr hd, exact finset.le_sup hd, } end /-- The homogeneous submodules form a graded ring. This instance is used by `direct_sum.comm_semiring` and `direct_sum.algebra`. -/ instance homogeneous_submodule.gcomm_semiring : set_like.graded_monoid (homogeneous_submodule σ R) := { one_mem := is_homogeneous_one σ R, mul_mem := λ i j xi xj, is_homogeneous.mul} open_locale direct_sum noncomputable example : comm_semiring (⨁ i, homogeneous_submodule σ R i) := infer_instance noncomputable example : algebra R (⨁ i, homogeneous_submodule σ R i) := infer_instance end is_homogeneous section noncomputable theory open_locale classical open finset /-- `homogeneous_component n φ` is the part of `φ` that is homogeneous of degree `n`. See `sum_homogeneous_component` for the statement that `φ` is equal to the sum of all its homogeneous components. -/ def homogeneous_component [comm_semiring R] (n : ℕ) : mv_polynomial σ R →ₗ[R] mv_polynomial σ R := (submodule.subtype _).comp $ finsupp.restrict_dom _ _ {d | ∑ i in d.support, d i = n} section homogeneous_component open finset variables [comm_semiring R] (n : ℕ) (φ ψ : mv_polynomial σ R) lemma coeff_homogeneous_component (d : σ →₀ ℕ) : coeff d (homogeneous_component n φ) = if ∑ i in d.support, d i = n then coeff d φ else 0 := by convert finsupp.filter_apply (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ d lemma homogeneous_component_apply : homogeneous_component n φ = ∑ d in φ.support.filter (λ d, ∑ i in d.support, d i = n), monomial d (coeff d φ) := by convert finsupp.filter_eq_sum (λ d : σ →₀ ℕ, ∑ i in d.support, d i = n) φ lemma homogeneous_component_is_homogeneous : (homogeneous_component n φ).is_homogeneous n := begin intros d hd, contrapose! hd, rw [coeff_homogeneous_component, if_neg hd] end @[simp] lemma homogeneous_component_zero : homogeneous_component 0 φ = C (coeff 0 φ) := begin ext1 d, rcases em (d = 0) with (rfl|hd), { simp only [coeff_homogeneous_component, sum_eq_zero_iff, finsupp.zero_apply, if_true, coeff_C, eq_self_iff_true, forall_true_iff] }, { rw [coeff_homogeneous_component, if_neg, coeff_C, if_neg (ne.symm hd)], simp only [finsupp.ext_iff, finsupp.zero_apply] at hd, simp [hd] } end @[simp] lemma homogeneous_component_C_mul (n : ℕ) (r : R) : homogeneous_component n (C r * φ) = C r * homogeneous_component n φ := by simp only [C_mul', linear_map.map_smul] lemma homogeneous_component_eq_zero' (h : ∀ d : σ →₀ ℕ, d ∈ φ.support → ∑ i in d.support, d i ≠ n) : homogeneous_component n φ = 0 := begin rw [homogeneous_component_apply, sum_eq_zero], intros d hd, rw mem_filter at hd, exfalso, exact h _ hd.1 hd.2 end lemma homogeneous_component_eq_zero (h : φ.total_degree < n) : homogeneous_component n φ = 0 := begin apply homogeneous_component_eq_zero', rw [total_degree, finset.sup_lt_iff] at h, { intros d hd, exact ne_of_lt (h d hd), }, { exact lt_of_le_of_lt (nat.zero_le _) h, } end lemma sum_homogeneous_component : ∑ i in range (φ.total_degree + 1), homogeneous_component i φ = φ := begin ext1 d, suffices : φ.total_degree < d.support.sum d → 0 = coeff d φ, by simpa [coeff_sum, coeff_homogeneous_component], exact λ h, (coeff_eq_zero_of_total_degree_lt h).symm end lemma homogeneous_component_homogeneous_polynomial (m n : ℕ) (p : mv_polynomial σ R) (h : p ∈ homogeneous_submodule σ R n) : homogeneous_component m p = if m = n then p else 0 := begin simp only [mem_homogeneous_submodule] at h, ext x, rw coeff_homogeneous_component, by_cases zero_coeff : coeff x p = 0, { split_ifs, all_goals { simp only [zero_coeff, coeff_zero], }, }, { rw h zero_coeff, simp only [show n = m ↔ m = n, from eq_comm], split_ifs with h1, { refl }, { simp only [coeff_zero] } } end end homogeneous_component end end mv_polynomial
7b6a4b2745ff6f57894ef0175fe0b9ee75d158cb
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/antichain.lean
4141504e474992948c4b2597aba9cf3db3401350
[ "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
4,518
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.pairwise /-! # Antichains This file defines antichains. An antichain is a set where any two distinct elements are not related. If the relation is `(≤)`, this corresponds to incomparability and usual order antichains. If the relation is `G.adj` for `G : simple_graph α`, this corresponds to independent sets of `G`. ## Definitions * `is_antichain r s`: Any two elements of `s : set α` are unrelated by `r : α → α → Prop`. * `is_antichain.mk r s`: Turns `s` into an antichain by keeping only the "maximal" elements. -/ open function set variables {α β : Type*} {r r₁ r₂ : α → α → Prop} {r' : β → β → Prop} {s t : set α} {a : α} protected lemma symmetric.compl (h : symmetric r) : symmetric rᶜ := λ x y hr hr', hr $ h hr' /-- An antichain is a set such that no two distinct elements are related. -/ def is_antichain (r : α → α → Prop) (s : set α) : Prop := s.pairwise rᶜ namespace is_antichain protected lemma subset (hs : is_antichain r s) (h : t ⊆ s) : is_antichain r t := hs.mono h lemma mono (hs : is_antichain r₁ s) (h : r₂ ≤ r₁) : is_antichain r₂ s := hs.mono' $ compl_le_compl h lemma mono_on (hs : is_antichain r₁ s) (h : s.pairwise (λ ⦃a b⦄, r₂ a b → r₁ a b)) : is_antichain r₂ s := hs.imp_on $ h.imp $ λ a b h h₁ h₂, h₁ $ h h₂ lemma eq_of_related (hs : is_antichain r s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) (h : r a b) : a = b := of_not_not $ λ hab, hs _ ha _ hb hab h protected lemma is_antisymm (h : is_antichain r univ) : is_antisymm α r := ⟨λ a b ha _, h.eq_of_related trivial trivial ha⟩ protected lemma subsingleton [is_trichotomous α r] (h : is_antichain r s) : s.subsingleton := begin rintro a ha b hb, obtain hab | hab | hab := trichotomous_of r a b, { exact h.eq_of_related ha hb hab }, { exact hab }, { exact (h.eq_of_related hb ha hab).symm } end protected lemma flip (hs : is_antichain r s) : is_antichain (flip r) s := λ a ha b hb h, hs _ hb _ ha h.symm lemma swap (hs : is_antichain r s) : is_antichain (swap r) s := hs.flip lemma image (hs : is_antichain r s) (f : α → β) (h : ∀ ⦃a b⦄, r' (f a) (f b) → r a b) : is_antichain r' (f '' s) := begin rintro _ ⟨b, hb, rfl⟩ _ ⟨c, hc, rfl⟩ hbc hr, exact hs _ hb _ hc (ne_of_apply_ne _ hbc) (h hr), end lemma preimage (hs : is_antichain r s) {f : β → α} (hf : injective f) (h : ∀ ⦃a b⦄, r' a b → r (f a) (f b)) : is_antichain r' (f ⁻¹' s) := λ b hb c hc hbc hr, hs _ hb _ hc (hf.ne hbc) $ h hr lemma _root_.is_antichain_insert : is_antichain r (insert a s) ↔ is_antichain r s ∧ ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r a b ∧ ¬ r b a := set.pairwise_insert protected lemma insert (hs : is_antichain r s) (hl : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r b a) (hr : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r a b) : is_antichain r (insert a s) := is_antichain_insert.2 ⟨hs, λ b hb hab, ⟨hr hb hab, hl hb hab⟩⟩ lemma _root_.is_antichain_insert_of_symmetric (hr : symmetric r) : is_antichain r (insert a s) ↔ is_antichain r s ∧ ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r a b := pairwise_insert_of_symmetric hr.compl lemma insert_of_symmetric (hs : is_antichain r s) (hr : symmetric r) (h : ∀ ⦃b⦄, b ∈ s → a ≠ b → ¬ r a b) : is_antichain r (insert a s) := (is_antichain_insert_of_symmetric hr).2 ⟨hs, h⟩ /-- Turns a set into an antichain by keeping only the "maximal" elements. -/ protected def mk (r : α → α → Prop) (s : set α) : set α := {a ∈ s | ∀ ⦃b⦄, b ∈ s → r a b → a = b} lemma mk_is_antichain (r : α → α → Prop) (s : set α) : is_antichain r (is_antichain.mk r s) := λ a ha b hb hab h, hab $ ha.2 hb.1 h lemma mk_subset : is_antichain.mk r s ⊆ s := sep_subset _ _ /-- If `is_antichain.mk r s` is included in but *shadows* the antichain `t`, then it is actually equal to `t`. -/ lemma mk_max (ht : is_antichain r t) (h : is_antichain.mk r s ⊆ t) (hs : ∀ ⦃a⦄, a ∈ t → ∃ b ∈ is_antichain.mk r s, r a b) : t = is_antichain.mk r s := begin refine subset.antisymm (λ a ha, _) h, obtain ⟨b, hb, hr⟩ := hs ha, rwa of_not_not (λ hab, ht _ ha _ (h hb) hab hr), end end is_antichain lemma set.subsingleton.is_antichain (hs : s.subsingleton) (r : α → α → Prop): is_antichain r s := hs.pairwise _
8ce85d7134434212911638a2c6b95d7609bd4086
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monoidal/functor.lean
2c3693a4677a5803a779f582f8bf1aff8aa3fc34
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
12,119
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monoidal.category import Mathlib.PostPort universes v₁ v₂ u₁ u₂ l u₃ v₃ namespace Mathlib /-! # (Lax) monoidal functors A lax monoidal functor `F` between monoidal categories `C` and `D` is a functor between the underlying categories equipped with morphisms * `ε : 𝟙_ D ⟶ F.obj (𝟙_ C)` (called the unit morphism) * `μ X Y : (F.obj X) ⊗ (F.obj Y) ⟶ F.obj (X ⊗ Y)` (called the tensorator, or strength). satisfying various axioms. A monoidal functor is a lax monoidal functor for which `ε` and `μ` are isomorphisms. We show that the composition of (lax) monoidal functors gives a (lax) monoidal functor. See also `category_theory.monoidal.functorial` for a typeclass decorating an object-level function with the additional data of a monoidal functor. This is useful when stating that a pre-existing functor is monoidal. See `category_theory.monoidal.natural_transformation` for monoidal natural transformations. We show in `category_theory.monoidal.Mon_` that lax monoidal functors take monoid objects to monoid objects. ## Future work * Oplax monoidal functors. ## References See https://stacks.math.columbia.edu/tag/0FFL. -/ namespace category_theory /-- A lax monoidal functor is a functor `F : C ⥤ D` between monoidal categories, equipped with morphisms `ε : 𝟙 _D ⟶ F.obj (𝟙_ C)` and `μ X Y : F.obj X ⊗ F.obj Y ⟶ F.obj (X ⊗ Y)`, satisfying the the appropriate coherences. -/ -- unit morphism structure lax_monoidal_functor (C : Type u₁) [category C] [monoidal_category C] (D : Type u₂) [category D] [monoidal_category D] extends C ⥤ D where ε : 𝟙_ ⟶ functor.obj _to_functor 𝟙_ μ : (X Y : C) → functor.obj _to_functor X ⊗ functor.obj _to_functor Y ⟶ functor.obj _to_functor (X ⊗ Y) μ_natural' : autoParam (∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), (functor.map _to_functor f ⊗ functor.map _to_functor g) ≫ μ Y Y' = μ X X' ≫ functor.map _to_functor (f ⊗ g)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) associativity' : autoParam (∀ (X Y Z : C), (μ X Y ⊗ 𝟙) ≫ μ (X ⊗ Y) Z ≫ functor.map _to_functor (iso.hom α_) = iso.hom α_ ≫ (𝟙 ⊗ μ Y Z) ≫ μ X (Y ⊗ Z)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) left_unitality' : autoParam (∀ (X : C), iso.hom λ_ = (ε ⊗ 𝟙) ≫ μ 𝟙_ X ≫ functor.map _to_functor (iso.hom λ_)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) right_unitality' : autoParam (∀ (X : C), iso.hom ρ_ = (𝟙 ⊗ ε) ≫ μ X 𝟙_ ≫ functor.map _to_functor (iso.hom ρ_)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) -- tensorator -- associativity of the tensorator -- unitality @[simp] theorem lax_monoidal_functor.μ_natural {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) {X : C} {Y : C} {X' : C} {Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : (functor.map (lax_monoidal_functor.to_functor c) f ⊗ functor.map (lax_monoidal_functor.to_functor c) g) ≫ lax_monoidal_functor.μ c Y Y' = lax_monoidal_functor.μ c X X' ≫ functor.map (lax_monoidal_functor.to_functor c) (f ⊗ g) := sorry @[simp] theorem lax_monoidal_functor.μ_natural_assoc {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) {X : C} {Y : C} {X' : C} {Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : ∀ {X'_1 : D} (f' : functor.obj (lax_monoidal_functor.to_functor c) (Y ⊗ Y') ⟶ X'_1), (functor.map (lax_monoidal_functor.to_functor c) f ⊗ functor.map (lax_monoidal_functor.to_functor c) g) ≫ lax_monoidal_functor.μ c Y Y' ≫ f' = lax_monoidal_functor.μ c X X' ≫ functor.map (lax_monoidal_functor.to_functor c) (f ⊗ g) ≫ f' := sorry @[simp] theorem lax_monoidal_functor.left_unitality {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) (X : C) : iso.hom λ_ = (lax_monoidal_functor.ε c ⊗ 𝟙) ≫ lax_monoidal_functor.μ c 𝟙_ X ≫ functor.map (lax_monoidal_functor.to_functor c) (iso.hom λ_) := sorry @[simp] theorem lax_monoidal_functor.right_unitality {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) (X : C) : iso.hom ρ_ = (𝟙 ⊗ lax_monoidal_functor.ε c) ≫ lax_monoidal_functor.μ c X 𝟙_ ≫ functor.map (lax_monoidal_functor.to_functor c) (iso.hom ρ_) := sorry @[simp] theorem lax_monoidal_functor.associativity {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (c : lax_monoidal_functor C D) (X : C) (Y : C) (Z : C) : (lax_monoidal_functor.μ c X Y ⊗ 𝟙) ≫ lax_monoidal_functor.μ c (X ⊗ Y) Z ≫ functor.map (lax_monoidal_functor.to_functor c) (iso.hom α_) = iso.hom α_ ≫ (𝟙 ⊗ lax_monoidal_functor.μ c Y Z) ≫ lax_monoidal_functor.μ c X (Y ⊗ Z) := sorry -- When `rewrite_search` lands, add @[search] attributes to -- lax_monoidal_functor.μ_natural lax_monoidal_functor.left_unitality -- lax_monoidal_functor.right_unitality lax_monoidal_functor.associativity /-- A monoidal functor is a lax monoidal functor for which the tensorator and unitor as isomorphisms. See https://stacks.math.columbia.edu/tag/0FFL. -/ structure monoidal_functor (C : Type u₁) [category C] [monoidal_category C] (D : Type u₂) [category D] [monoidal_category D] extends lax_monoidal_functor C D where ε_is_iso : autoParam (is_iso (lax_monoidal_functor.ε _to_lax_monoidal_functor)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) μ_is_iso : autoParam ((X Y : C) → is_iso (lax_monoidal_functor.μ _to_lax_monoidal_functor X Y)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.apply_instance") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "apply_instance") []) /-- The unit morphism of a (strong) monoidal functor as an isomorphism. -/ def monoidal_functor.ε_iso {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) : 𝟙_ ≅ functor.obj (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor F)) 𝟙_ := as_iso (lax_monoidal_functor.ε (monoidal_functor.to_lax_monoidal_functor F)) /-- The tensorator of a (strong) monoidal functor as an isomorphism. -/ def monoidal_functor.μ_iso {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) (X : C) (Y : C) : functor.obj (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor F)) X ⊗ functor.obj (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor F)) Y ≅ functor.obj (lax_monoidal_functor.to_functor (monoidal_functor.to_lax_monoidal_functor F)) (X ⊗ Y) := as_iso (lax_monoidal_functor.μ (monoidal_functor.to_lax_monoidal_functor F) X Y) namespace lax_monoidal_functor /-- The identity lax monoidal functor. -/ @[simp] theorem id_ε (C : Type u₁) [category C] [monoidal_category C] : ε (id C) = 𝟙 := Eq.refl (ε (id C)) protected instance inhabited (C : Type u₁) [category C] [monoidal_category C] : Inhabited (lax_monoidal_functor C C) := { default := id C } end lax_monoidal_functor namespace monoidal_functor theorem map_tensor {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) {X : C} {Y : C} {X' : C} {Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) (f ⊗ g) = inv (lax_monoidal_functor.μ (to_lax_monoidal_functor F) X X') ≫ (functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) f ⊗ functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) g) ≫ lax_monoidal_functor.μ (to_lax_monoidal_functor F) Y Y' := sorry theorem map_left_unitor {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) (X : C) : functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) (iso.hom λ_) = inv (lax_monoidal_functor.μ (to_lax_monoidal_functor F) 𝟙_ X) ≫ (inv (lax_monoidal_functor.ε (to_lax_monoidal_functor F)) ⊗ 𝟙) ≫ iso.hom λ_ := sorry theorem map_right_unitor {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) (X : C) : functor.map (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) (iso.hom ρ_) = inv (lax_monoidal_functor.μ (to_lax_monoidal_functor F) X 𝟙_) ≫ (𝟙 ⊗ inv (lax_monoidal_functor.ε (to_lax_monoidal_functor F))) ≫ iso.hom ρ_ := sorry /-- The tensorator as a natural isomorphism. -/ def μ_nat_iso {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] (F : monoidal_functor C D) : functor.prod (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F)) ⋙ monoidal_category.tensor D ≅ monoidal_category.tensor C ⋙ lax_monoidal_functor.to_functor (to_lax_monoidal_functor F) := nat_iso.of_components (fun (X : C × C) => μ_iso F (prod.fst X) (prod.snd X)) sorry /-- The identity monoidal functor. -/ def id (C : Type u₁) [category C] [monoidal_category C] : monoidal_functor C C := mk (lax_monoidal_functor.mk (functor.mk (functor.obj 𝟭) (functor.map 𝟭)) 𝟙 fun (X Y : C) => 𝟙) protected instance inhabited (C : Type u₁) [category C] [monoidal_category C] : Inhabited (monoidal_functor C C) := { default := id C } end monoidal_functor namespace lax_monoidal_functor -- The proofs here are horrendous; rewrite_search helps a lot. /-- The composition of two lax monoidal functors is again lax monoidal. -/ @[simp] theorem comp_ε {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] {E : Type u₃} [category E] [monoidal_category E] (F : lax_monoidal_functor C D) (G : lax_monoidal_functor D E) : ε (comp F G) = ε G ≫ functor.map (to_functor G) (ε F) := Eq.refl (ε (comp F G)) infixr:80 " ⊗⋙ " => Mathlib.category_theory.lax_monoidal_functor.comp end lax_monoidal_functor namespace monoidal_functor /-- The composition of two monoidal functors is again monoidal. -/ def comp {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] [monoidal_category D] {E : Type u₃} [category E] [monoidal_category E] (F : monoidal_functor C D) (G : monoidal_functor D E) : monoidal_functor C E := mk (lax_monoidal_functor.mk (lax_monoidal_functor.to_functor (to_lax_monoidal_functor F ⊗⋙ to_lax_monoidal_functor G)) (lax_monoidal_functor.ε (to_lax_monoidal_functor F ⊗⋙ to_lax_monoidal_functor G)) (lax_monoidal_functor.μ (to_lax_monoidal_functor F ⊗⋙ to_lax_monoidal_functor G))) infixr:80 " ⊗⋙ " => Mathlib.category_theory.monoidal_functor.comp
49be1623fe3368c42d5ec4a05aabe1fcbb61074f
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/hahn_series.lean
d1ccfe53f7386ebdb469b552d24a2d559ed0aabb
[ "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
54,051
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.well_founded_set import algebra.big_operators.finprod import ring_theory.valuation.basic import algebra.module.pi import ring_theory.power_series.basic /-! # Hahn Series ## Main Definitions * If `Γ` is ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are partially well-ordered. * If `R` is a (commutative) additive monoid or group, then so is `hahn_series Γ R`. * If `R` is a (comm_)(semi)ring, then so is `hahn_series Γ R`. * `hahn_series.add_val Γ R` defines an `add_valuation` on `hahn_series Γ R` when `Γ` is linearly ordered. * A `hahn_series.summable_family` is a family of Hahn series such that the union of their supports is well-founded and only finitely many are nonzero at any given coefficient. They have a formal sum, `hahn_series.summable_family.hsum`, which can be bundled as a `linear_map` as `hahn_series.summable_family.lsum`. Note that this is different from `summable` in the valuation topology, because there are topologically summable families that do not satisfy the axioms of `hahn_series.summable_family`, and formally summable families whose sums do not converge topologically. ## TODO * Given `[linear_ordered_add_comm_group Γ]` and `[field R]`, define `field (hahn_series Γ R)`. * Build an API for the variable `X` * Define Laurent series -/ open finset open_locale big_operators classical noncomputable theory /-- If `Γ` is linearly ordered and `R` has zero, then `hahn_series Γ R` consists of formal series over `Γ` with coefficients in `R`, whose supports are well-founded. -/ @[ext] structure hahn_series (Γ : Type*) (R : Type*) [partial_order Γ] [has_zero R] := (coeff : Γ → R) (is_pwo_support' : (function.support coeff).is_pwo) variables {Γ : Type*} {R : Type*} namespace hahn_series section zero variables [partial_order Γ] [has_zero R] /-- The support of a Hahn series is just the set of indices whose coefficients are nonzero. Notably, it is well-founded. -/ def support (x : hahn_series Γ R) : set Γ := function.support x.coeff @[simp] lemma is_pwo_support (x : hahn_series Γ R) : x.support.is_pwo := x.is_pwo_support' @[simp] lemma is_wf_support (x : hahn_series Γ R) : x.support.is_wf := x.is_pwo_support.is_wf @[simp] lemma mem_support (x : hahn_series Γ R) (a : Γ) : a ∈ x.support ↔ x.coeff a ≠ 0 := iff.refl _ instance : has_zero (hahn_series Γ R) := ⟨{ coeff := 0, is_pwo_support' := by simp }⟩ instance : inhabited (hahn_series Γ R) := ⟨0⟩ instance [subsingleton R] : subsingleton (hahn_series Γ R) := ⟨λ a b, a.ext b (subsingleton.elim _ _)⟩ @[simp] lemma zero_coeff {a : Γ} : (0 : hahn_series Γ R).coeff a = 0 := rfl lemma ne_zero_of_coeff_ne_zero {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : x ≠ 0 := mt (λ x0, (x0.symm ▸ zero_coeff : x.coeff g = 0)) h @[simp] lemma support_zero : support (0 : hahn_series Γ R) = ∅ := function.support_zero @[simp] lemma support_nonempty_iff {x : hahn_series Γ R} : x.support.nonempty ↔ x ≠ 0 := begin split, { rintro ⟨a, ha⟩ rfl, apply ha zero_coeff }, { contrapose!, rw set.not_nonempty_iff_eq_empty, intro h, ext a, have ha := set.not_mem_empty a, rw [← h, mem_support, not_not] at ha, rw [ha, zero_coeff] } end /-- `single a r` is the Hahn series which has coefficient `r` at `a` and zero otherwise. -/ def single (a : Γ) : zero_hom R (hahn_series Γ R) := { to_fun := λ r, { coeff := pi.single a r, is_pwo_support' := (set.is_pwo_singleton a).mono pi.support_single_subset }, map_zero' := ext _ _ (pi.single_zero _) } variables {a b : Γ} {r : R} @[simp] theorem single_coeff_same (a : Γ) (r : R) : (single a r).coeff a = r := pi.single_eq_same a r @[simp] theorem single_coeff_of_ne (h : b ≠ a) : (single a r).coeff b = 0 := pi.single_eq_of_ne h r theorem single_coeff : (single a r).coeff b = if (b = a) then r else 0 := by { split_ifs with h; simp [h] } @[simp] lemma support_single_of_ne (h : r ≠ 0) : support (single a r) = {a} := pi.support_single_of_ne h lemma support_single_subset : support (single a r) ⊆ {a} := pi.support_single_subset lemma eq_of_mem_support_single {b : Γ} (h : b ∈ support (single a r)) : b = a := support_single_subset h @[simp] lemma single_eq_zero : (single a (0 : R)) = 0 := (single a).map_zero lemma single_injective (a : Γ) : function.injective (single a : R → hahn_series Γ R) := λ r s rs, by rw [← single_coeff_same a r, ← single_coeff_same a s, rs] lemma single_ne_zero (h : r ≠ 0) : single a r ≠ 0 := λ con, h (single_injective a (con.trans single_eq_zero.symm)) instance [nonempty Γ] [nontrivial R] : nontrivial (hahn_series Γ R) := ⟨begin obtain ⟨r, s, rs⟩ := exists_pair_ne R, inhabit Γ, refine ⟨single (arbitrary Γ) r, single (arbitrary Γ) s, λ con, rs _⟩, rw [← single_coeff_same (arbitrary Γ) r, con, single_coeff_same], end⟩ section order variable [has_zero Γ] /-- The order of a nonzero Hahn series `x` is a minimal element of `Γ` where `x` has a nonzero coefficient, the order of 0 is 0. -/ def order (x : hahn_series Γ R) : Γ := if h : x = 0 then 0 else x.is_wf_support.min (support_nonempty_iff.2 h) @[simp] lemma order_zero : order (0 : hahn_series Γ R) = 0 := dif_pos rfl lemma order_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) : order x = x.is_wf_support.min (support_nonempty_iff.2 hx) := dif_neg hx lemma coeff_order_ne_zero {x : hahn_series Γ R} (hx : x ≠ 0) : x.coeff x.order ≠ 0 := begin rw order_of_ne hx, exact x.is_wf_support.min_mem (support_nonempty_iff.2 hx) end lemma order_le_of_coeff_ne_zero {Γ} [linear_ordered_cancel_add_comm_monoid Γ] {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : x.order ≤ g := le_trans (le_of_eq (order_of_ne (ne_zero_of_coeff_ne_zero h))) (set.is_wf.min_le _ _ ((mem_support _ _).2 h)) @[simp] lemma order_single (h : r ≠ 0) : (single a r).order = a := (order_of_ne (single_ne_zero h)).trans (support_single_subset ((single a r).is_wf_support.min_mem (support_nonempty_iff.2 (single_ne_zero h)))) end order section domain variables {Γ' : Type*} [partial_order Γ'] /-- Extends the domain of a `hahn_series` by an `order_embedding`. -/ def emb_domain (f : Γ ↪o Γ') : hahn_series Γ R → hahn_series Γ' R := λ x, { coeff := λ (b : Γ'), if h : b ∈ f '' x.support then x.coeff (classical.some h) else 0, is_pwo_support' := (x.is_pwo_support.image_of_monotone f.monotone).mono (λ b hb, begin contrapose! hb, rw [function.mem_support, dif_neg hb, not_not], end) } @[simp] lemma emb_domain_coeff {f : Γ ↪o Γ'} {x : hahn_series Γ R} {a : Γ} : (emb_domain f x).coeff (f a) = x.coeff a := begin rw emb_domain, dsimp only, by_cases ha : a ∈ x.support, { rw dif_pos (set.mem_image_of_mem f ha), exact congr rfl (f.injective (classical.some_spec (set.mem_image_of_mem f ha)).2) }, { rw [dif_neg, not_not.1 (λ c, ha ((mem_support _ _).2 c))], contrapose! ha, obtain ⟨b, hb1, hb2⟩ := (set.mem_image _ _ _).1 ha, rwa f.injective hb2 at hb1 } end @[simp] lemma emb_domain_mk_coeff {f : Γ → Γ'} (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') {x : hahn_series Γ R} {a : Γ} : (emb_domain ⟨⟨f, hfi⟩, hf⟩ x).coeff (f a) = x.coeff a := begin apply eq.trans (congr rfl _) emb_domain_coeff, simp, end lemma emb_domain_notin_image_support {f : Γ ↪o Γ'} {x : hahn_series Γ R} {b : Γ'} (hb : b ∉ f '' x.support) : (emb_domain f x).coeff b = 0 := dif_neg hb lemma support_emb_domain_subset {f : Γ ↪o Γ'} {x : hahn_series Γ R} : support (emb_domain f x) ⊆ f '' x.support := begin intros g hg, contrapose! hg, rw [mem_support, emb_domain_notin_image_support hg, not_not], end lemma emb_domain_notin_range {f : Γ ↪o Γ'} {x : hahn_series Γ R} {b : Γ'} (hb : b ∉ set.range f) : (emb_domain f x).coeff b = 0 := emb_domain_notin_image_support (λ con, hb (set.image_subset_range _ _ con)) @[simp] lemma emb_domain_zero {f : Γ ↪o Γ'} : emb_domain f (0 : hahn_series Γ R) = 0 := by { ext, simp [emb_domain_notin_image_support] } @[simp] lemma emb_domain_single {f : Γ ↪o Γ'} {g : Γ} {r : R} : emb_domain f (single g r) = single (f g) r := begin ext g', by_cases h : g' = f g, { simp [h] }, rw [emb_domain_notin_image_support, single_coeff_of_ne h], by_cases hr : r = 0, { simp [hr] }, rwa [support_single_of_ne hr, set.image_singleton, set.mem_singleton_iff], end lemma emb_domain_injective {f : Γ ↪o Γ'} : function.injective (emb_domain f : hahn_series Γ R → hahn_series Γ' R) := λ x y xy, begin ext g, rw [ext_iff, function.funext_iff] at xy, have xyg := xy (f g), rwa [emb_domain_coeff, emb_domain_coeff] at xyg, end end domain end zero section addition variable [partial_order Γ] section add_monoid variable [add_monoid R] instance : has_add (hahn_series Γ R) := { add := λ x y, { coeff := x.coeff + y.coeff, is_pwo_support' := (x.is_pwo_support.union y.is_pwo_support).mono (function.support_add _ _) } } instance : add_monoid (hahn_series Γ R) := { zero := 0, add := (+), add_assoc := λ x y z, by { ext, apply add_assoc }, zero_add := λ x, by { ext, apply zero_add }, add_zero := λ x, by { ext, apply add_zero } } @[simp] lemma add_coeff' {x y : hahn_series Γ R} : (x + y).coeff = x.coeff + y.coeff := rfl lemma add_coeff {x y : hahn_series Γ R} {a : Γ} : (x + y).coeff a = x.coeff a + y.coeff a := rfl lemma support_add_subset {x y : hahn_series Γ R} : support (x + y) ⊆ support x ∪ support y := λ a ha, begin rw [mem_support, add_coeff] at ha, rw [set.mem_union, mem_support, mem_support], contrapose! ha, rw [ha.1, ha.2, add_zero], end lemma min_order_le_order_add {Γ} [linear_ordered_cancel_add_comm_monoid Γ] {x y : hahn_series Γ R} (hx : x ≠ 0) (hy : y ≠ 0) (hxy : x + y ≠ 0) : min x.order y.order ≤ (x + y).order := begin rw [order_of_ne hx, order_of_ne hy, order_of_ne hxy], refine le_trans _ (set.is_wf.min_le_min_of_subset support_add_subset), { exact x.is_wf_support.union y.is_wf_support }, { exact set.nonempty.mono (set.subset_union_left _ _) (support_nonempty_iff.2 hx) }, rw set.is_wf.min_union, end /-- `single` as an additive monoid/group homomorphism -/ @[simps] def single.add_monoid_hom (a : Γ) : R →+ (hahn_series Γ R) := { map_add' := λ x y, by { ext b, by_cases h : b = a; simp [h] }, ..single a } /-- `coeff g` as an additive monoid/group homomorphism -/ @[simps] def coeff.add_monoid_hom (g : Γ) : (hahn_series Γ R) →+ R := { to_fun := λ f, f.coeff g, map_zero' := zero_coeff, map_add' := λ x y, add_coeff } end add_monoid instance [add_comm_monoid R] : add_comm_monoid (hahn_series Γ R) := { add_comm := λ x y, by { ext, apply add_comm } .. hahn_series.add_monoid } section add_group variable [add_group R] instance : add_group (hahn_series Γ R) := { neg := λ x, { coeff := λ a, - x.coeff a, is_pwo_support' := by { rw function.support_neg, exact x.is_pwo_support }, }, add_left_neg := λ x, by { ext, apply add_left_neg }, .. hahn_series.add_monoid } @[simp] lemma neg_coeff' {x : hahn_series Γ R} : (- x).coeff = - x.coeff := rfl lemma neg_coeff {x : hahn_series Γ R} {a : Γ} : (- x).coeff a = - x.coeff a := rfl @[simp] lemma support_neg {x : hahn_series Γ R} : (- x).support = x.support := by { ext, simp } @[simp] lemma sub_coeff' {x y : hahn_series Γ R} : (x - y).coeff = x.coeff - y.coeff := by { ext, simp [sub_eq_add_neg] } lemma sub_coeff {x y : hahn_series Γ R} {a : Γ} : (x - y).coeff a = x.coeff a - y.coeff a := by simp end add_group instance [add_comm_group R] : add_comm_group (hahn_series Γ R) := { .. hahn_series.add_comm_monoid, .. hahn_series.add_group } end addition section distrib_mul_action variables [partial_order Γ] {V : Type*} [monoid R] [add_monoid V] [distrib_mul_action R V] instance : has_scalar R (hahn_series Γ V) := ⟨λ r x, { coeff := r • x.coeff, is_pwo_support' := x.is_pwo_support.mono (function.support_smul_subset_right r x.coeff) }⟩ @[simp] lemma smul_coeff {r : R} {x : hahn_series Γ V} {a : Γ} : (r • x).coeff a = r • (x.coeff a) := rfl instance : distrib_mul_action R (hahn_series Γ V) := { smul := (•), one_smul := λ _, by { ext, simp }, smul_zero := λ _, by { ext, simp }, smul_add := λ _ _ _, by { ext, simp [smul_add] }, mul_smul := λ _ _ _, by { ext, simp [mul_smul] } } variables {S : Type*} [monoid S] [distrib_mul_action S V] instance [has_scalar R S] [is_scalar_tower R S V] : is_scalar_tower R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp }⟩ instance [smul_comm_class R S V] : smul_comm_class R S (hahn_series Γ V) := ⟨λ r s a, by { ext, simp [smul_comm] }⟩ end distrib_mul_action section module variables [partial_order Γ] [semiring R] {V : Type*} [add_comm_monoid V] [module R V] instance : module R (hahn_series Γ V) := { zero_smul := λ _, by { ext, simp }, add_smul := λ _ _ _, by { ext, simp [add_smul] }, .. hahn_series.distrib_mul_action } /-- `single` as a linear map -/ @[simps] def single.linear_map (a : Γ) : R →ₗ[R] (hahn_series Γ R) := { map_smul' := λ r s, by { ext b, by_cases h : b = a; simp [h] }, ..single.add_monoid_hom a } /-- `coeff g` as a linear map -/ @[simps] def coeff.linear_map (g : Γ) : (hahn_series Γ R) →ₗ[R] R := { map_smul' := λ r s, rfl, ..coeff.add_monoid_hom g } section domain variables {Γ' : Type*} [partial_order Γ'] /-- Extending the domain of Hahn series is a linear map. -/ @[simps] def emb_domain_linear_map (f : Γ ↪o Γ') : hahn_series Γ R →ₗ[R] hahn_series Γ' R := ⟨emb_domain f, λ x y, begin ext g, by_cases hg : g ∈ set.range f, { obtain ⟨a, rfl⟩ := hg, simp }, { simp [emb_domain_notin_range, hg] } end, λ x y, begin ext g, by_cases hg : g ∈ set.range f, { obtain ⟨a, rfl⟩ := hg, simp }, { simp [emb_domain_notin_range, hg] } end⟩ end domain end module section multiplication variable [ordered_cancel_add_comm_monoid Γ] instance [has_zero R] [has_one R] : has_one (hahn_series Γ R) := ⟨single 0 1⟩ @[simp] lemma one_coeff [has_zero R] [has_one R] {a : Γ} : (1 : hahn_series Γ R).coeff a = if a = 0 then 1 else 0 := single_coeff @[simp] lemma single_zero_one [has_zero R] [has_one R] : (single 0 (1 : R)) = 1 := rfl @[simp] lemma support_one [semiring R] [nontrivial R] : support (1 : hahn_series Γ R) = {0} := support_single_of_ne one_ne_zero @[simp] lemma order_one [semiring R] : order (1 : hahn_series Γ R) = 0 := begin cases subsingleton_or_nontrivial R with h h; haveI := h, { rw [subsingleton.elim (1 : hahn_series Γ R) 0, order_zero] }, { exact order_single one_ne_zero } end instance [semiring R] : has_mul (hahn_series Γ R) := { mul := λ x y, { coeff := λ a, ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd, is_pwo_support' := begin have h : {a : Γ | ∑ (ij : Γ × Γ) in add_antidiagonal x.is_pwo_support y.is_pwo_support a, x.coeff ij.fst * y.coeff ij.snd ≠ 0} ⊆ {a : Γ | (add_antidiagonal x.is_pwo_support y.is_pwo_support a).nonempty}, { intros a ha, contrapose! ha, simp [not_nonempty_iff_eq_empty.1 ha] }, exact is_pwo_support_add_antidiagonal.mono h, end, }, } @[simp] lemma mul_coeff [semiring R] {x y : hahn_series Γ R} {a : Γ} : (x * y).coeff a = ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd := rfl lemma mul_coeff_right' [semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_pwo) (hys : y.support ⊆ s) : (x * y).coeff a = ∑ ij in (add_antidiagonal x.is_pwo_support hs a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_right hys) _ (λ _ _, rfl), intros b hb, simp only [not_and, not_not, mem_sdiff, mem_add_antidiagonal, ne.def, set.mem_set_of_eq, mem_support] at hb, rw [(hb.2 hb.1.1 hb.1.2.1), mul_zero] end lemma mul_coeff_left' [semiring R] {x y : hahn_series Γ R} {a : Γ} {s : set Γ} (hs : s.is_pwo) (hxs : x.support ⊆ s) : (x * y).coeff a = ∑ ij in (add_antidiagonal hs y.is_pwo_support a), x.coeff ij.fst * y.coeff ij.snd := begin rw mul_coeff, apply sum_subset_zero_on_sdiff (add_antidiagonal_mono_left hxs) _ (λ _ _, rfl), intros b hb, simp only [not_and, not_not, mem_sdiff, mem_add_antidiagonal, ne.def, set.mem_set_of_eq, mem_support] at hb, rw [not_not.1 (λ con, hb.1.2.2 (hb.2 hb.1.1 con)), zero_mul], end instance [semiring R] : distrib (hahn_series Γ R) := { left_distrib := λ x y z, begin ext a, have hwf := (y.is_pwo_support.union z.is_pwo_support), rw [mul_coeff_right' hwf, add_coeff, mul_coeff_right' hwf (set.subset_union_right _ _), mul_coeff_right' hwf (set.subset_union_left _ _)], { simp only [add_coeff, mul_add, sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], } end, right_distrib := λ x y z, begin ext a, have hwf := (x.is_pwo_support.union y.is_pwo_support), rw [mul_coeff_left' hwf, add_coeff, mul_coeff_left' hwf (set.subset_union_right _ _), mul_coeff_left' hwf (set.subset_union_left _ _)], { simp only [add_coeff, add_mul, sum_add_distrib] }, { intro b, simp only [add_coeff, ne.def, set.mem_union_eq, set.mem_set_of_eq, mem_support], contrapose!, intro h, rw [h.1, h.2, add_zero], }, end, .. hahn_series.has_mul, .. hahn_series.has_add } lemma single_mul_coeff_add [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : ((single b r) * x).coeff (a + b) = r * x.coeff a := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, mul_zero], rw [sum_congr _ (λ _ _, rfl), sum_empty], ext ⟨a1, a2⟩, simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not, mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro h1 rfl h2, rw add_comm at h1, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(b, a)}, (single b r).coeff ij.fst * x.coeff ij.snd, { apply sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal, mem_singleton, set.mem_set_of_eq], split, { rintro ⟨h1, rfl, h2⟩, rw add_comm at h1, refine ⟨rfl, add_right_cancel h1⟩ }, { rintro ⟨rfl, rfl⟩, refine ⟨add_comm _ _, _⟩, simp [hx] } }, { simp } end lemma mul_single_coeff_add [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} {b : Γ} : (x * (single b r)).coeff (a + b) = x.coeff a * r := begin by_cases hr : r = 0, { simp [hr] }, simp only [hr, smul_coeff, mul_coeff, support_single_of_ne, ne.def, not_false_iff, smul_eq_mul], by_cases hx : x.coeff a = 0, { simp only [hx, zero_mul], rw [sum_congr _ (λ _ _, rfl), sum_empty], ext ⟨a1, a2⟩, simp only [not_mem_empty, not_and, set.mem_singleton_iff, not_not, mem_add_antidiagonal, set.mem_set_of_eq, iff_false], rintro h1 h2 rfl, rw ← add_right_cancel h1 at hx, exact h2 hx, }, transitivity ∑ (ij : Γ × Γ) in {(a,b)}, x.coeff ij.fst * (single b r).coeff ij.snd, { apply sum_congr _ (λ _ _, rfl), ext ⟨a1, a2⟩, simp only [set.mem_singleton_iff, prod.mk.inj_iff, mem_add_antidiagonal, mem_singleton, set.mem_set_of_eq], split, { rintro ⟨h1, h2, rfl⟩, refine ⟨add_right_cancel h1, rfl⟩ }, { rintro ⟨rfl, rfl⟩, simp [hx] } }, { simp } end @[simp] lemma mul_single_zero_coeff [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : (x * (single 0 r)).coeff a = x.coeff a * r := by rw [← add_zero a, mul_single_coeff_add, add_zero] lemma single_zero_mul_coeff [semiring R] {r : R} {x : hahn_series Γ R} {a : Γ} : ((single 0 r) * x).coeff a = r * x.coeff a := by rw [← add_zero a, single_mul_coeff_add, add_zero] @[simp] lemma single_zero_mul_eq_smul [semiring R] {r : R} {x : hahn_series Γ R} : (single 0 r) * x = r • x := by { ext, exact single_zero_mul_coeff } theorem support_mul_subset_add_support [semiring R] {x y : hahn_series Γ R} : support (x * y) ⊆ support x + support y := begin apply set.subset.trans (λ x hx, _) support_add_antidiagonal_subset_add, { exact x.is_pwo_support }, { exact y.is_pwo_support }, contrapose! hx, simp only [not_nonempty_iff_eq_empty, ne.def, set.mem_set_of_eq] at hx, simp [hx], end lemma mul_coeff_order_add_order {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [semiring R] {x y : hahn_series Γ R} (hx : x ≠ 0) (hy : y ≠ 0) : (x * y).coeff (x.order + y.order) = x.coeff x.order * y.coeff y.order := by rw [order_of_ne hx, order_of_ne hy, mul_coeff, finset.add_antidiagonal_min_add_min, finset.sum_singleton] private lemma mul_assoc' [semiring R] (x y z : hahn_series Γ R) : x * y * z = x * (y * z) := begin ext b, rw [mul_coeff_left' (x.is_pwo_support.add y.is_pwo_support) support_mul_subset_add_support, mul_coeff_right' (y.is_pwo_support.add z.is_pwo_support) support_mul_subset_add_support], simp only [mul_coeff, add_coeff, sum_mul, mul_sum, sum_sigma'], refine sum_bij_ne_zero (λ a has ha0, ⟨⟨a.2.1, a.2.2 + a.1.2⟩, ⟨a.2.2, a.1.2⟩⟩) _ _ _ _, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [true_and, set.image2_add, eq_self_iff_true, mem_add_antidiagonal, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq] at H1 H2 ⊢, obtain ⟨⟨rfl, ⟨H3, nz⟩⟩, ⟨rfl, nx, ny⟩⟩ := H1, refine ⟨⟨(add_assoc _ _ _).symm, nx, set.add_mem_add ny nz⟩, ny, nz⟩ }, { rintros ⟨⟨i1,j1⟩, ⟨k1,l1⟩⟩ ⟨⟨i2,j2⟩, ⟨k2,l2⟩⟩ H1 H2 H3 H4 H5, simp only [set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq] at H1 H3 H5, obtain ⟨⟨rfl, H⟩, rfl, rfl⟩ := H5, simp only [and_true, prod.mk.inj_iff, eq_self_iff_true, heq_iff_eq], exact add_right_cancel (H1.1.1.trans H3.1.1.symm) }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp only [exists_prop, set.image2_add, prod.mk.inj_iff, mem_add_antidiagonal, sigma.exists, ne.def, set.image_prod, mem_sigma, set.mem_set_of_eq, heq_iff_eq, prod.exists] at H1 H2 ⊢, obtain ⟨⟨rfl, nx, H⟩, rfl, ny, nz⟩ := H1, exact ⟨i + k, l, i, k, ⟨⟨add_assoc _ _ _, set.add_mem_add nx ny, nz⟩, rfl, nx, ny⟩, λ con, H2 ((mul_assoc _ _ _).symm.trans con), ⟨rfl, rfl⟩, rfl, rfl⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H1 H2, simp [mul_assoc], } end instance [semiring R] : semiring (hahn_series Γ R) := { zero := 0, one := 1, add := (+), mul := (*), zero_mul := λ _, by { ext, simp }, mul_zero := λ _, by { ext, simp }, one_mul := λ x, single_zero_mul_eq_smul.trans (one_smul _ _), mul_one := λ x, by { ext, exact mul_single_zero_coeff.trans (mul_one _) }, mul_assoc := mul_assoc', .. hahn_series.add_comm_monoid, .. hahn_series.distrib } instance [comm_semiring R] : comm_semiring (hahn_series Γ R) := { mul_comm := λ x y, begin ext, simp_rw [mul_coeff, mul_comm], refine sum_bij (λ a ha, ⟨a.2, a.1⟩) _ (λ a ha, by simp) _ _, { intros a ha, simp only [mem_add_antidiagonal, ne.def, set.mem_set_of_eq] at ha ⊢, obtain ⟨h1, h2, h3⟩ := ha, refine ⟨_, h3, h2⟩, rw [add_comm, h1], }, { rintros ⟨a1, a2⟩ ⟨b1, b2⟩ ha hb hab, rw prod.ext_iff at *, refine ⟨hab.2, hab.1⟩, }, { intros a ha, refine ⟨a.swap, _, by simp⟩, simp only [prod.fst_swap, mem_add_antidiagonal, prod.snd_swap, ne.def, set.mem_set_of_eq] at ha ⊢, exact ⟨(add_comm _ _).trans ha.1, ha.2.2, ha.2.1⟩ } end, .. hahn_series.semiring } instance [ring R] : ring (hahn_series Γ R) := { .. hahn_series.semiring, .. hahn_series.add_comm_group } instance [comm_ring R] : comm_ring (hahn_series Γ R) := { .. hahn_series.comm_semiring, .. hahn_series.ring } instance {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [integral_domain R] : integral_domain (hahn_series Γ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y xy, begin by_cases hx : x = 0, { left, exact hx }, right, contrapose! xy, rw [hahn_series.ext_iff, function.funext_iff, not_forall], refine ⟨x.order + y.order, _⟩, rw [mul_coeff_order_add_order hx xy, zero_coeff, mul_eq_zero], simp [coeff_order_ne_zero, hx, xy], end, .. hahn_series.nontrivial, .. hahn_series.comm_ring } @[simp] lemma order_mul {Γ} [linear_ordered_cancel_add_comm_monoid Γ] [integral_domain R] {x y : hahn_series Γ R} (hx : x ≠ 0) (hy : y ≠ 0) : (x * y).order = x.order + y.order := begin apply le_antisymm, { apply order_le_of_coeff_ne_zero, rw [mul_coeff_order_add_order hx hy], exact mul_ne_zero (coeff_order_ne_zero hx) (coeff_order_ne_zero hy) }, { rw [order_of_ne hx, order_of_ne hy, order_of_ne (mul_ne_zero hx hy), ← set.is_wf.min_add], exact set.is_wf.min_le_min_of_subset (support_mul_subset_add_support) }, end section semiring variables [semiring R] @[simp] lemma single_mul_single {a b : Γ} {r s : R} : single a r * single b s = single (a + b) (r * s) := begin ext x, by_cases h : x = a + b, { rw [h, mul_single_coeff_add], simp }, { rw [single_coeff_of_ne h, mul_coeff, sum_eq_zero], rintros ⟨y1, y2⟩ hy, obtain ⟨rfl, hy1, hy2⟩ := mem_add_antidiagonal.1 hy, rw [eq_of_mem_support_single hy1, eq_of_mem_support_single hy2] at h, exact (h rfl).elim } end /-- `C a` is the constant Hahn Series `a`. `C` is provided as a ring homomorphism. -/ @[simps] def C : R →+* (hahn_series Γ R) := { to_fun := single 0, map_zero' := single_eq_zero, map_one' := rfl, map_add' := λ x y, by { ext a, by_cases h : a = 0; simp [h] }, map_mul' := λ x y, by rw [single_mul_single, zero_add] } @[simp] lemma C_zero : C (0 : R) = (0 : hahn_series Γ R) := C.map_zero @[simp] lemma C_one : C (1 : R) = (1 : hahn_series Γ R) := C.map_one lemma C_mul_eq_smul {r : R} {x : hahn_series Γ R} : C r * x = r • x := single_zero_mul_eq_smul lemma C_injective : function.injective (C : R → hahn_series Γ R) := begin intros r s rs, rw [ext_iff, function.funext_iff] at rs, have h := rs 0, rwa [C_apply, single_coeff_same, C_apply, single_coeff_same] at h, end lemma C_ne_zero {r : R} (h : r ≠ 0) : (C r : hahn_series Γ R) ≠ 0 := begin contrapose! h, rw ← C_zero at h, exact C_injective h, end lemma order_C {r : R} : order (C r : hahn_series Γ R) = 0 := begin by_cases h : r = 0, { rw [h, C_zero, order_zero] }, { exact order_single h } end section domain variables {Γ' : Type*} [ordered_cancel_add_comm_monoid Γ'] /-- Extending the domain of Hahn series is a ring homomorphism. -/ @[simps] def emb_domain_ring_hom (f : Γ →+ Γ') (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') : hahn_series Γ R →+* hahn_series Γ' R := ⟨emb_domain_linear_map ⟨⟨f, hfi⟩, hf⟩, emb_domain_single.trans begin simp only [rel_embedding.coe_fn_mk, function.embedding.coe_fn_mk, add_monoid_hom.map_zero], rw [← C_apply, C_one], end, λ x y, begin simp only [emb_domain_linear_map_apply], ext g, by_cases hg : g ∈ set.range (⟨⟨f, hfi⟩, hf⟩ : Γ ↪o Γ'), { obtain ⟨g, rfl⟩ := hg, simp only [mul_coeff, emb_domain_mk_coeff, emb_domain_linear_map_apply], transitivity ∑ ij in (add_antidiagonal x.is_pwo_support y.is_pwo_support g).map (function.embedding.prod_map ⟨f, hfi⟩ ⟨f, hfi⟩), (emb_domain ⟨⟨f, hfi⟩, hf⟩ x).coeff (ij.1) * (emb_domain ⟨⟨f, hfi⟩, hf⟩ y).coeff (ij.2), { simp }, apply sum_subset, { rintro ⟨i, j⟩ hij, simp only [exists_prop, mem_map, prod.mk.inj_iff, function.embedding.coe_fn_mk, mem_add_antidiagonal, ne.def, function.embedding.coe_prod_map, mem_support, prod.exists] at hij, obtain ⟨i, j, ⟨rfl, hx, hy⟩, rfl, rfl⟩ := hij, simp [hx, hy], }, { rintro ⟨_, _⟩ h1 h2, contrapose! h2, obtain ⟨i, hi, rfl⟩ := support_emb_domain_subset (ne_zero_and_ne_zero_of_mul h2).1, obtain ⟨j, hj, rfl⟩ := support_emb_domain_subset (ne_zero_and_ne_zero_of_mul h2).2, simp only [exists_prop, mem_map, prod.mk.inj_iff, function.embedding.coe_fn_mk, mem_add_antidiagonal, ne.def, function.embedding.coe_prod_map, mem_support, prod.exists], simp only [mem_add_antidiagonal, rel_embedding.coe_fn_mk, emb_domain_mk_coeff, function.embedding.coe_fn_mk, ne.def, mem_support, ← f.map_add] at h1, exact ⟨i, j, ⟨hfi h1.1, h1.2.1, h1.2.2⟩, rfl⟩, } }, { rw [emb_domain_notin_range hg, eq_comm], contrapose! hg, obtain ⟨_, _, hi, hj, rfl⟩ := support_mul_subset_add_support ((mem_support _ _).2 hg), obtain ⟨i, hi, rfl⟩ := support_emb_domain_subset hi, obtain ⟨j, hj, rfl⟩ := support_emb_domain_subset hj, refine ⟨i + j, _⟩, simp, } end, linear_map.map_zero _, linear_map.map_add _⟩ lemma emb_domain_ring_hom_C {f : Γ →+ Γ'} {hfi : function.injective f} {hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g'} {r : R} : emb_domain_ring_hom f hfi hf (C r) = C r := emb_domain_single.trans (by simp) end domain end semiring section algebra variables [comm_semiring R] {A : Type*} [semiring A] [algebra R A] instance : algebra R (hahn_series Γ A) := { to_ring_hom := C.comp (algebra_map R A), smul_def' := λ r x, by { ext, simp }, commutes' := λ r x, by { ext, simp only [smul_coeff, single_zero_mul_eq_smul, ring_hom.coe_comp, ring_hom.to_fun_eq_coe, C_apply, function.comp_app, algebra_map_smul, mul_single_zero_coeff], rw [← algebra.commutes, algebra.smul_def], }, } theorem C_eq_algebra_map : C = (algebra_map R (hahn_series Γ R)) := rfl theorem algebra_map_apply {r : R} : algebra_map R (hahn_series Γ A) r = C (algebra_map R A r) := rfl instance [nontrivial Γ] [nontrivial R] : nontrivial (subalgebra R (hahn_series Γ R)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], obtain ⟨a, ha⟩ := exists_ne (0 : Γ), refine ⟨single a 1, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top], intros x, rw [ext_iff, function.funext_iff, not_forall], refine ⟨a, _⟩, rw [single_coeff_same, algebra_map_apply, C_apply, single_coeff_of_ne ha], exact zero_ne_one end⟩⟩ section domain variables {Γ' : Type*} [ordered_cancel_add_comm_monoid Γ'] /-- Extending the domain of Hahn series is an algebra homomorphism. -/ @[simps] def emb_domain_alg_hom (f : Γ →+ Γ') (hfi : function.injective f) (hf : ∀ g g' : Γ, f g ≤ f g' ↔ g ≤ g') : hahn_series Γ A →ₐ[R] hahn_series Γ' A := { commutes' := λ r, emb_domain_ring_hom_C, .. emb_domain_ring_hom f hfi hf } end domain end algebra end multiplication section semiring variables [semiring R] /-- The ring `hahn_series ℕ R` is isomorphic to `power_series R`. -/ @[simps] def to_power_series : (hahn_series ℕ R) ≃+* power_series R := { to_fun := λ f, power_series.mk f.coeff, inv_fun := λ f, ⟨λ n, power_series.coeff R n f, (nat.lt_wf.is_wf _).is_pwo⟩, left_inv := λ f, by { ext, simp }, right_inv := λ f, by { ext, simp }, map_add' := λ f g, by { ext, simp }, map_mul' := λ f g, begin ext n, simp only [power_series.coeff_mul, power_series.coeff_mk, mul_coeff, is_pwo_support], classical, refine sum_filter_ne_zero.symm.trans ((sum_congr _ (λ _ _, rfl)).trans sum_filter_ne_zero), ext m, simp only [nat.mem_antidiagonal, and.congr_left_iff, mem_add_antidiagonal, ne.def, and_iff_left_iff_imp, mem_filter, mem_support], intros h1 h2, contrapose h1, rw ← decidable.or_iff_not_and_not at h1, cases h1; simp [h1] end } lemma coeff_to_power_series {f : hahn_series ℕ R} {n : ℕ} : power_series.coeff R n f.to_power_series = f.coeff n := power_series.coeff_mk _ _ lemma coeff_to_power_series_symm {f : power_series R} {n : ℕ} : (hahn_series.to_power_series.symm f).coeff n = power_series.coeff R n f := rfl variables [ordered_semiring Γ] [nontrivial Γ] /-- Casts a power series as a Hahn series with coefficients from an `ordered_semiring`. -/ @[simps] def of_power_series : (power_series R) →+* hahn_series Γ R := (hahn_series.emb_domain_ring_hom (nat.cast_add_monoid_hom Γ) nat.strict_mono_cast.injective (λ _ _, nat.cast_le)).comp (ring_equiv.to_ring_hom to_power_series.symm) end semiring section algebra variables (R) [comm_semiring R] {A : Type*} [semiring A] [algebra R A] /-- The `R`-algebra `hahn_series ℕ A` is isomorphic to `power_series A`. -/ @[simps] def to_power_series_alg : (hahn_series ℕ A) ≃ₐ[R] power_series A := { commutes' := λ r, begin ext n, simp only [algebra_map_apply, power_series.algebra_map_apply, ring_equiv.to_fun_eq_coe, C_apply, coeff_to_power_series], cases n, { simp only [power_series.coeff_zero_eq_constant_coeff, single_coeff_same], refl }, { simp only [n.succ_ne_zero, ne.def, not_false_iff, single_coeff_of_ne], rw [power_series.coeff_C, if_neg n.succ_ne_zero] } end, .. to_power_series } variables [ordered_semiring Γ] [nontrivial Γ] /-- Casting a power series as a Hahn series with coefficients from an `ordered_semiring` is an algebra homomorphism. -/ @[simps] def of_power_series_alg : (power_series A) →ₐ[R] hahn_series Γ A := (hahn_series.emb_domain_alg_hom (nat.cast_add_monoid_hom Γ) nat.strict_mono_cast.injective (λ _ _, nat.cast_le)).comp (alg_equiv.to_alg_hom (to_power_series_alg R).symm) end algebra section valuation variables [linear_ordered_add_comm_group Γ] [integral_domain R] instance : linear_ordered_comm_group (multiplicative Γ) := { .. (infer_instance : linear_order (multiplicative Γ)), .. (infer_instance : ordered_comm_group (multiplicative Γ)) } instance : linear_ordered_comm_group_with_zero (with_zero (multiplicative Γ)) := { zero_le_one := with_zero.zero_le 1, .. (with_zero.ordered_comm_monoid), .. (infer_instance : linear_order (with_zero (multiplicative Γ))), .. (infer_instance : comm_group_with_zero (with_zero (multiplicative Γ))) } variables (Γ) (R) /-- The additive valuation on `hahn_series Γ R`, returning the smallest index at which a Hahn Series has a nonzero coefficient, or `⊤` for the 0 series. -/ def add_val : add_valuation (hahn_series Γ R) (with_top Γ) := add_valuation.of (λ x, if x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.order) (if_pos rfl) ((if_neg one_ne_zero).trans (by simp [order_of_ne])) (λ x y, begin by_cases hx : x = 0, { by_cases hy : y = 0; { simp [hx, hy] } }, { by_cases hy : y = 0, { simp [hx, hy] }, { simp only [hx, hy, support_nonempty_iff, if_neg, not_false_iff, is_wf_support], by_cases hxy : x + y = 0, { simp [hxy] }, rw [if_neg hxy, ← with_top.coe_min, with_top.coe_le_coe], exact min_order_le_order_add hx hy hxy } }, end) (λ x y, begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [if_neg hx, if_neg hy, if_neg (mul_ne_zero hx hy), ← with_top.coe_add, with_top.coe_eq_coe, order_mul hx hy], end) variables {Γ} {R} lemma add_val_apply {x : hahn_series Γ R} : add_val Γ R x = if x = (0 : hahn_series Γ R) then (⊤ : with_top Γ) else x.order := add_valuation.of_apply _ @[simp] lemma add_val_apply_of_ne {x : hahn_series Γ R} (hx : x ≠ 0) : add_val Γ R x = x.order := if_neg hx lemma add_val_le_of_coeff_ne_zero {x : hahn_series Γ R} {g : Γ} (h : x.coeff g ≠ 0) : add_val Γ R x ≤ g := begin rw [add_val_apply_of_ne (ne_zero_of_coeff_ne_zero h), with_top.coe_le_coe], exact order_le_of_coeff_ne_zero h end end valuation lemma is_pwo_Union_support_powers [linear_ordered_add_comm_group Γ] [integral_domain R] {x : hahn_series Γ R} (hx : 0 < add_val Γ R x) : (⋃ n : ℕ, (x ^ n).support).is_pwo := begin apply (x.is_wf_support.is_pwo.add_submonoid_closure (λ g hg, _)).mono _, { exact with_top.coe_le_coe.1 (le_trans (le_of_lt hx) (add_val_le_of_coeff_ne_zero hg)) }, refine set.Union_subset (λ n, _), induction n with n ih; intros g hn, { simp only [exists_prop, and_true, set.mem_singleton_iff, set.set_of_eq_eq_singleton, mem_support, ite_eq_right_iff, ne.def, not_false_iff, one_ne_zero, pow_zero, not_forall, one_coeff] at hn, rw [hn, set_like.mem_coe], exact add_submonoid.zero_mem _ }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support hn, exact set_like.mem_coe.2 (add_submonoid.add_mem _ (add_submonoid.subset_closure hi) (ih hj)) } end section variables (Γ) (R) [partial_order Γ] [add_comm_monoid R] /-- An infinite family of Hahn series which has a formal coefficient-wise sum. The requirements for this are that the union of the supports of the series is well-founded, and that only finitely many series are nonzero at any given coefficient. -/ structure summable_family (α : Type*) := (to_fun : α → hahn_series Γ R) (is_pwo_Union_support' : set.is_pwo (⋃ (a : α), (to_fun a).support)) (finite_co_support' : ∀ (g : Γ), ({a | (to_fun a).coeff g ≠ 0}).finite) end namespace summable_family section add_comm_monoid variables [partial_order Γ] [add_comm_monoid R] {α : Type*} instance : has_coe_to_fun (summable_family Γ R α) := ⟨λ _, (α → hahn_series Γ R), to_fun⟩ lemma is_pwo_Union_support (s : summable_family Γ R α) : set.is_pwo (⋃ (a : α), (s a).support) := s.is_pwo_Union_support' lemma finite_co_support (s : summable_family Γ R α) (g : Γ) : (function.support (λ a, (s a).coeff g)).finite := s.finite_co_support' g lemma coe_injective : @function.injective (summable_family Γ R α) (α → hahn_series Γ R) coe_fn | ⟨f1, hU1, hf1⟩ ⟨f2, hU2, hf2⟩ h := begin change f1 = f2 at h, subst h, end @[ext] lemma ext {s t : summable_family Γ R α} (h : ∀ (a : α), s a = t a) : s = t := coe_injective $ funext h instance : has_add (summable_family Γ R α) := ⟨λ x y, { to_fun := x + y, is_pwo_Union_support' := (x.is_pwo_Union_support.union y.is_pwo_Union_support).mono (begin rw ← set.Union_union_distrib, exact set.Union_subset_Union (λ a, support_add_subset) end), finite_co_support' := λ g, ((x.finite_co_support g).union (y.finite_co_support g)).subset begin intros a ha, change (x a).coeff g + (y a).coeff g ≠ 0 at ha, rw [set.mem_union, function.mem_support, function.mem_support], contrapose! ha, rw [ha.1, ha.2, add_zero] end }⟩ instance : has_zero (summable_family Γ R α) := ⟨⟨0, by simp, by simp⟩⟩ instance : inhabited (summable_family Γ R α) := ⟨0⟩ @[simp] lemma coe_add {s t : summable_family Γ R α} : ⇑(s + t) = s + t := rfl lemma add_apply {s t : summable_family Γ R α} {a : α} : (s + t) a = s a + t a := rfl @[simp] lemma coe_zero : ((0 : summable_family Γ R α) : α → hahn_series Γ R) = 0 := rfl lemma zero_apply {a : α} : (0 : summable_family Γ R α) a = 0 := rfl instance : add_comm_monoid (summable_family Γ R α) := { add := (+), zero := 0, zero_add := λ s, by { ext, apply zero_add }, add_zero := λ s, by { ext, apply add_zero }, add_comm := λ s t, by { ext, apply add_comm }, add_assoc := λ r s t, by { ext, apply add_assoc } } /-- The infinite sum of a `summable_family` of Hahn series. -/ def hsum (s : summable_family Γ R α) : hahn_series Γ R := { coeff := λ g, ∑ᶠ i, (s i).coeff g, is_pwo_support' := s.is_pwo_Union_support.mono (λ g, begin contrapose, rw [set.mem_Union, not_exists, function.mem_support, not_not], simp_rw [mem_support, not_not], intro h, rw [finsum_congr h, finsum_zero], end) } @[simp] lemma hsum_coeff {s : summable_family Γ R α} {g : Γ} : s.hsum.coeff g = ∑ᶠ i, (s i).coeff g := rfl lemma support_hsum_subset {s : summable_family Γ R α} : s.hsum.support ⊆ ⋃ (a : α), (s a).support := λ g hg, begin rw [mem_support, hsum_coeff, finsum_eq_sum _ (s.finite_co_support _)] at hg, obtain ⟨a, h1, h2⟩ := exists_ne_zero_of_sum_ne_zero hg, rw [set.mem_Union], exact ⟨a, h2⟩, end @[simp] lemma hsum_add {s t : summable_family Γ R α} : (s + t).hsum = s.hsum + t.hsum := begin ext g, simp only [hsum_coeff, add_coeff, add_apply], exact finsum_add_distrib (s.finite_co_support _) (t.finite_co_support _) end end add_comm_monoid section add_comm_group variables [partial_order Γ] [add_comm_group R] {α : Type*} {s t : summable_family Γ R α} {a : α} instance : add_comm_group (summable_family Γ R α) := { neg := λ s, { to_fun := λ a, - s a, is_pwo_Union_support' := by { simp_rw [support_neg], exact s.is_pwo_Union_support' }, finite_co_support' := λ g, by { simp only [neg_coeff', pi.neg_apply, ne.def, neg_eq_zero], exact s.finite_co_support g } }, add_left_neg := λ a, by { ext, apply add_left_neg }, .. summable_family.add_comm_monoid } @[simp] lemma coe_neg : ⇑(-s) = - s := rfl lemma neg_apply : (-s) a = - (s a) := rfl @[simp] lemma coe_sub : ⇑(s - t) = s - t := rfl lemma sub_apply : (s - t) a = s a - t a := rfl end add_comm_group section semiring variables [ordered_cancel_add_comm_monoid Γ] [semiring R] {α : Type*} instance : has_scalar (hahn_series Γ R) (summable_family Γ R α) := { smul := λ x s, { to_fun := λ a, x * (s a), is_pwo_Union_support' := begin apply (x.is_pwo_support.add s.is_pwo_Union_support).mono, refine set.subset.trans (set.Union_subset_Union (λ a, support_mul_subset_add_support)) _, intro g, simp only [set.mem_Union, exists_imp_distrib], exact λ a ha, (set.add_subset_add (set.subset.refl _) (set.subset_Union _ a)) ha, end, finite_co_support' := λ g, begin refine ((add_antidiagonal x.is_pwo_support s.is_pwo_Union_support g).finite_to_set.bUnion (λ ij hij, _)).subset (λ a ha, _), { exact λ ij hij, function.support (λ a, (s a).coeff ij.2) }, { apply s.finite_co_support }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support ha, simp only [exists_prop, set.mem_Union, mem_add_antidiagonal, mul_coeff, ne.def, mem_support, is_pwo_support, prod.exists], refine ⟨i, j, mem_coe.2 (mem_add_antidiagonal.2 ⟨rfl, hi, set.mem_Union.2 ⟨a, hj⟩⟩), hj⟩, } end } } @[simp] lemma smul_apply {x : hahn_series Γ R} {s : summable_family Γ R α} {a : α} : (x • s) a = x * (s a) := rfl instance : module (hahn_series Γ R) (summable_family Γ R α) := { smul := (•), smul_zero := λ x, ext (λ a, mul_zero _), zero_smul := λ x, ext (λ a, zero_mul _), one_smul := λ x, ext (λ a, one_mul _), add_smul := λ x y s, ext (λ a, add_mul _ _ _), smul_add := λ x s t, ext (λ a, mul_add _ _ _), mul_smul := λ x y s, ext (λ a, mul_assoc _ _ _) } @[simp] lemma hsum_smul {x : hahn_series Γ R} {s : summable_family Γ R α} : (x • s).hsum = x * s.hsum := begin ext g, simp only [mul_coeff, hsum_coeff, smul_apply], have h : ∀ i, (s i).support ⊆ ⋃ j, (s j).support := set.subset_Union _, refine (eq.trans (finsum_congr (λ a, _)) (finsum_sum_comm (add_antidiagonal x.is_pwo_support s.is_pwo_Union_support g) (λ i ij, x.coeff (prod.fst ij) * (s i).coeff ij.snd) _)).trans _, { refine sum_subset (add_antidiagonal_mono_right (set.subset_Union _ a)) _, rintro ⟨i, j⟩ hU ha, rw mem_add_antidiagonal at *, rw [not_not.1 (λ con, ha ⟨hU.1, hU.2.1, con⟩), mul_zero] }, { rintro ⟨i, j⟩ hij, refine (s.finite_co_support j).subset _, simp_rw [function.support_subset_iff', function.mem_support, not_not], intros a ha, rw [ha, mul_zero] }, { refine (sum_congr rfl _).trans (sum_subset (add_antidiagonal_mono_right _) _).symm, { rintro ⟨i, j⟩ hij, rw mul_finsum, apply s.finite_co_support, }, { intros x hx, simp only [set.mem_Union, ne.def, mem_support], contrapose! hx, simp [hx] }, { rintro ⟨i, j⟩ hU ha, rw mem_add_antidiagonal at *, rw [← hsum_coeff, not_not.1 (λ con, ha ⟨hU.1, hU.2.1, con⟩), mul_zero] } } end /-- The summation of a `summable_family` as a `linear_map`. -/ @[simps] def lsum : (summable_family Γ R α) →ₗ[hahn_series Γ R] (hahn_series Γ R) := ⟨hsum, λ _ _, hsum_add, λ _ _, hsum_smul⟩ @[simp] lemma hsum_sub {R : Type*} [ring R] {s t : summable_family Γ R α} : (s - t).hsum = s.hsum - t.hsum := by rw [← lsum_apply, linear_map.map_sub, lsum_apply, lsum_apply] end semiring section of_finsupp variables [partial_order Γ] [add_comm_monoid R] {α : Type*} /-- A family with only finitely many nonzero elements is summable. -/ def of_finsupp (f : α →₀ (hahn_series Γ R)) : summable_family Γ R α := { to_fun := f, is_pwo_Union_support' := begin apply (f.support.is_pwo_sup (λ a, (f a).support) (λ a ha, (f a).is_pwo_support)).mono, intros g hg, obtain ⟨a, ha⟩ := set.mem_Union.1 hg, have haf : a ∈ f.support, { rw finsupp.mem_support_iff, contrapose! ha, rw [ha, support_zero], exact set.not_mem_empty _ }, have h : (λ i, (f i).support) a ≤ _ := le_sup haf, exact h ha, end, finite_co_support' := λ g, begin refine f.support.finite_to_set.subset (λ a ha, _), simp only [coeff.add_monoid_hom_apply, mem_coe, finsupp.mem_support_iff, ne.def, function.mem_support], contrapose! ha, simp [ha] end } @[simp] lemma coe_of_finsupp {f : α →₀ (hahn_series Γ R)} : ⇑(summable_family.of_finsupp f) = f := rfl @[simp] lemma hsum_of_finsupp {f : α →₀ (hahn_series Γ R)} : (of_finsupp f).hsum = f.sum (λ a, id) := begin ext g, simp only [hsum_coeff, coe_of_finsupp, finsupp.sum, ne.def], simp_rw [← coeff.add_monoid_hom_apply, id.def], rw [add_monoid_hom.map_sum, finsum_eq_sum_of_support_subset], intros x h, simp only [coeff.add_monoid_hom_apply, mem_coe, finsupp.mem_support_iff, ne.def], contrapose! h, simp [h] end end of_finsupp section emb_domain variables [partial_order Γ] [add_comm_monoid R] {α β : Type*} /-- A summable family can be reindexed by an embedding without changing its sum. -/ def emb_domain (s : summable_family Γ R α) (f : α ↪ β) : summable_family Γ R β := { to_fun := λ b, if h : b ∈ set.range f then s (classical.some h) else 0, is_pwo_Union_support' := begin refine s.is_pwo_Union_support.mono (set.Union_subset (λ b g h, _)), by_cases hb : b ∈ set.range f, { rw dif_pos hb at h, exact set.mem_Union.2 ⟨classical.some hb, h⟩ }, { contrapose! h, simp [hb] } end, finite_co_support' := λ g, ((s.finite_co_support g).image f).subset begin intros b h, by_cases hb : b ∈ set.range f, { simp only [ne.def, set.mem_set_of_eq, dif_pos hb] at h, exact ⟨classical.some hb, h, classical.some_spec hb⟩ }, { contrapose! h, simp only [ne.def, set.mem_set_of_eq, dif_neg hb, not_not, zero_coeff] } end } variables (s : summable_family Γ R α) (f : α ↪ β) {a : α} {b : β} lemma emb_domain_apply : s.emb_domain f b = if h : b ∈ set.range f then s (classical.some h) else 0 := rfl @[simp] lemma emb_domain_image : s.emb_domain f (f a) = s a := begin rw [emb_domain_apply, dif_pos (set.mem_range_self a)], exact congr rfl (f.injective (classical.some_spec (set.mem_range_self a))) end @[simp] lemma emb_domain_notin_range (h : b ∉ set.range f) : s.emb_domain f b = 0 := by rw [emb_domain_apply, dif_neg h] @[simp] lemma hsum_emb_domain : (s.emb_domain f).hsum = s.hsum := begin ext g, simp only [hsum_coeff, emb_domain_apply, apply_dite hahn_series.coeff, dite_apply, zero_coeff], exact finsum_emb_domain f (λ a, (s a).coeff g) end end emb_domain section powers variables [linear_ordered_add_comm_group Γ] [integral_domain R] /-- The powers of an element of positive valuation form a summable family. -/ def powers (x : hahn_series Γ R) (hx : 0 < add_val Γ R x) : summable_family Γ R ℕ := { to_fun := λ n, x ^ n, is_pwo_Union_support' := is_pwo_Union_support_powers hx, finite_co_support' := λ g, begin have hpwo := (is_pwo_Union_support_powers hx), by_cases hg : g ∈ ⋃ n : ℕ, {g | (x ^ n).coeff g ≠ 0 }, swap, { exact set.finite_empty.subset (λ n hn, hg (set.mem_Union.2 ⟨n, hn⟩)) }, apply hpwo.is_wf.induction hg, intros y ys hy, refine ((((add_antidiagonal x.is_pwo_support hpwo y).finite_to_set.bUnion (λ ij hij, hy ij.snd _ _)).image nat.succ).union (set.finite_singleton 0)).subset _, { exact (mem_add_antidiagonal.1 (mem_coe.1 hij)).2.2 }, { obtain ⟨rfl, hi, hj⟩ := mem_add_antidiagonal.1 (mem_coe.1 hij), rw [← zero_add ij.snd, ← add_assoc, add_zero], exact add_lt_add_right (with_top.coe_lt_coe.1 (lt_of_lt_of_le hx (add_val_le_of_coeff_ne_zero hi))) _, }, { intros n hn, cases n, { exact set.mem_union_right _ (set.mem_singleton 0) }, { obtain ⟨i, j, hi, hj, rfl⟩ := support_mul_subset_add_support hn, refine set.mem_union_left _ ⟨n, set.mem_Union.2 ⟨⟨i, j⟩, set.mem_Union.2 ⟨_, hj⟩⟩, rfl⟩, simp only [true_and, set.mem_Union, mem_add_antidiagonal, mem_coe, eq_self_iff_true, ne.def, mem_support, set.mem_set_of_eq], exact ⟨hi, ⟨n, hj⟩⟩ } } end } variables {x : hahn_series Γ R} (hx : 0 < add_val Γ R x) @[simp] lemma coe_powers : ⇑(powers x hx) = pow x := rfl lemma emb_domain_succ_smul_powers : (x • powers x hx).emb_domain ⟨nat.succ, nat.succ_injective⟩ = powers x hx - of_finsupp (finsupp.single 0 1) := begin apply summable_family.ext (λ n, _), cases n, { rw [emb_domain_notin_range, sub_apply, coe_powers, pow_zero, coe_of_finsupp, finsupp.single_eq_same, sub_self], rw [set.mem_range, not_exists], exact nat.succ_ne_zero }, { refine eq.trans (emb_domain_image _ ⟨nat.succ, nat.succ_injective⟩) _, simp only [pow_succ, coe_powers, coe_sub, smul_apply, coe_of_finsupp, pi.sub_apply], rw [finsupp.single_eq_of_ne (n.succ_ne_zero).symm, sub_zero] } end lemma one_sub_self_mul_hsum_powers : (1 - x) * (powers x hx).hsum = 1 := begin rw [← hsum_smul, sub_smul, one_smul, hsum_sub, ← hsum_emb_domain (x • powers x hx) ⟨nat.succ, nat.succ_injective⟩, emb_domain_succ_smul_powers], simp, end end powers end summable_family section inversion variables [linear_ordered_add_comm_group Γ] section integral_domain variable [integral_domain R] lemma unit_aux (x : hahn_series Γ R) {r : R} (hr : r * x.coeff x.order = 1) : 0 < add_val Γ R (1 - C r * (single (- x.order) 1) * x) := begin have h10 : (1 : R) ≠ 0 := one_ne_zero, have x0 : x ≠ 0 := ne_zero_of_coeff_ne_zero (right_ne_zero_of_mul_eq_one hr), refine lt_of_le_of_ne ((add_val Γ R).map_le_sub (ge_of_eq (add_val Γ R).map_one) _) _, { simp only [add_valuation.map_mul], rw [add_val_apply_of_ne x0, add_val_apply_of_ne (single_ne_zero h10), add_val_apply_of_ne _, order_C, order_single h10, with_top.coe_zero, zero_add, ← with_top.coe_add, neg_add_self, with_top.coe_zero], { exact le_refl 0 }, { exact C_ne_zero (left_ne_zero_of_mul_eq_one hr) } }, { rw [add_val_apply, ← with_top.coe_zero], split_ifs, { apply with_top.coe_ne_top }, rw [ne.def, with_top.coe_eq_coe], intro con, apply coeff_order_ne_zero h, rw [← con, mul_assoc, sub_coeff, one_coeff, if_pos rfl, C_mul_eq_smul, smul_coeff, smul_eq_mul, ← add_neg_self x.order, single_mul_coeff_add, one_mul, hr, sub_self] } end lemma is_unit_iff {x : hahn_series Γ R} : is_unit x ↔ is_unit (x.coeff x.order) := begin split, { rintro ⟨⟨u, i, ui, iu⟩, rfl⟩, refine is_unit_of_mul_eq_one (u.coeff u.order) (i.coeff i.order) ((mul_coeff_order_add_order (left_ne_zero_of_mul_eq_one ui) (right_ne_zero_of_mul_eq_one ui)).symm.trans _), rw [ui, one_coeff, if_pos], rw [← order_mul (left_ne_zero_of_mul_eq_one ui) (right_ne_zero_of_mul_eq_one ui), ui, order_one] }, { rintro ⟨⟨u, i, ui, iu⟩, h⟩, rw [units.coe_mk] at h, rw h at iu, have h := summable_family.one_sub_self_mul_hsum_powers (unit_aux x iu), rw [sub_sub_cancel] at h, exact is_unit_of_mul_is_unit_right (is_unit_of_mul_eq_one _ _ h) }, end end integral_domain instance [field R] : field (hahn_series Γ R) := { inv := λ x, if x0 : x = 0 then 0 else (C (x.coeff x.order)⁻¹ * (single (-x.order)) 1 * (summable_family.powers _ (unit_aux x (inv_mul_cancel (coeff_order_ne_zero x0)))).hsum), inv_zero := dif_pos rfl, mul_inv_cancel := λ x x0, begin refine (congr rfl (dif_neg x0)).trans _, have h := summable_family.one_sub_self_mul_hsum_powers (unit_aux x (inv_mul_cancel (coeff_order_ne_zero x0))), rw [sub_sub_cancel] at h, rw [← mul_assoc, mul_comm x, h], end, .. hahn_series.integral_domain } end inversion end hahn_series
b0bdcbda301c7584ef5a85408aedae23d524f7c0
94e33a31faa76775069b071adea97e86e218a8ee
/src/number_theory/cyclotomic/gal.lean
d4f9dbd21fcfc5e9d13764419702bb64fd9dffde
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
7,017
lean
/- Copyright (c) 2022 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import number_theory.cyclotomic.primitive_roots import field_theory.polynomial_galois_group /-! # Galois group of cyclotomic extensions In this file, we show the relationship between the Galois group of `K(ζₙ)` and `(zmod n)ˣ`; it is always a subgroup, and if the `n`th cyclotomic polynomial is irreducible, they are isomorphic. ## Main results * `is_primitive_root.aut_to_pow_injective`: `is_primitive_root.aut_to_pow` is injective in the case that it's considered over a cyclotomic field extension. * `is_cyclotomic_extension.aut_equiv_pow`: If the `n`th cyclotomic polynomial is irreducible in `K`, then `aut_to_pow` is a `mul_equiv` (for example, in `ℚ` and certain `𝔽ₚ`). * `gal_X_pow_equiv_units_zmod`, `gal_cyclotomic_equiv_units_zmod`: Repackage `aut_equiv_pow` in terms of `polynomial.gal`. * `is_cyclotomic_extension.aut.comm_group`: Cyclotomic extensions are abelian. ## References * https://kconrad.math.uconn.edu/blurbs/galoistheory/cyclotomic.pdf ## TODO * We currently can get away with the fact that the power of a primitive root is a primitive root, but the correct long-term solution for computing other explicit Galois groups is creating `power_basis.map_conjugate`; but figuring out the exact correct assumptions + proof for this is mathematically nontrivial. (Current thoughts: the correct condition is that the annihilating ideal of both elements is equal. This may not hold in an ID, and definitely holds in an ICD.) -/ local attribute [instance] pnat.fact_pos variables {n : ℕ+} (K : Type*) [field K] {L : Type*} [field L] {μ : L} (hμ : is_primitive_root μ n) [algebra K L] [is_cyclotomic_extension {n} K L] open polynomial is_cyclotomic_extension open_locale cyclotomic namespace is_primitive_root /-- `is_primitive_root.aut_to_pow` is injective in the case that it's considered over a cyclotomic field extension. -/ lemma aut_to_pow_injective : function.injective $ hμ.aut_to_pow K := begin intros f g hfg, apply_fun units.val at hfg, simp only [is_primitive_root.coe_aut_to_pow_apply, units.val_eq_coe] at hfg, generalize_proofs hf' hg' at hfg, have hf := hf'.some_spec, have hg := hg'.some_spec, generalize_proofs hζ at hf hg, suffices : f hμ.to_roots_of_unity = g hμ.to_roots_of_unity, { apply alg_equiv.coe_alg_hom_injective, apply (hμ.power_basis K).alg_hom_ext, exact this }, rw zmod.eq_iff_modeq_nat at hfg, refine (hf.trans _).trans hg.symm, rw [←roots_of_unity.coe_pow _ hf'.some, ←roots_of_unity.coe_pow _ hg'.some], congr' 1, rw [pow_eq_pow_iff_modeq], convert hfg, rw [hμ.eq_order_of], rw [←hμ.coe_to_roots_of_unity_coe] {occs := occurrences.pos [2]}, rw [order_of_units, order_of_subgroup] end end is_primitive_root namespace is_cyclotomic_extension /-- Cyclotomic extensions are abelian. -/ noncomputable def aut.comm_group : comm_group (L ≃ₐ[K] L) := ((zeta_spec n K L).aut_to_pow_injective K).comm_group _ (map_one _) (map_mul _) (map_inv _) (map_div _) (map_pow _) (map_zpow _) variables (h : irreducible (cyclotomic n K)) {K} (L) include h /-- The `mul_equiv` that takes an automorphism `f` to the element `k : (zmod n)ˣ` such that `f μ = μ ^ k`. A stronger version of `is_primitive_root.aut_to_pow`. -/ @[simps] noncomputable def aut_equiv_pow : (L ≃ₐ[K] L) ≃* (zmod n)ˣ := let hζ := zeta_spec n K L, hμ := λ t, hζ.pow_of_coprime _ (zmod.val_coe_unit_coprime t) in { inv_fun := λ t, (hζ.power_basis K).equiv_of_minpoly ((hμ t).power_basis K) begin haveI := is_cyclotomic_extension.ne_zero' n K L, simp only [is_primitive_root.power_basis_gen], have hr := is_primitive_root.minpoly_eq_cyclotomic_of_irreducible ((zeta_spec n K L).pow_of_coprime _ (zmod.val_coe_unit_coprime t)) h, exact ((zeta_spec n K L).minpoly_eq_cyclotomic_of_irreducible h).symm.trans hr end, left_inv := λ f, begin simp only [monoid_hom.to_fun_eq_coe], apply alg_equiv.coe_alg_hom_injective, apply (hζ.power_basis K).alg_hom_ext, simp only [alg_equiv.coe_alg_hom, alg_equiv.map_pow], rw power_basis.equiv_of_minpoly_gen, simp only [is_primitive_root.power_basis_gen, is_primitive_root.aut_to_pow_spec], end, right_inv := λ x, begin simp only [monoid_hom.to_fun_eq_coe], generalize_proofs _ _ _ h, have key := hζ.aut_to_pow_spec K ((hζ.power_basis K).equiv_of_minpoly ((hμ x).power_basis K) h), have := (hζ.power_basis K).equiv_of_minpoly_gen ((hμ x).power_basis K) h, rw hζ.power_basis_gen K at this, rw [this, is_primitive_root.power_basis_gen] at key, rw ← hζ.coe_to_roots_of_unity_coe at key {occs := occurrences.pos [1, 5]}, simp only [←coe_coe, ←roots_of_unity.coe_pow] at key, replace key := roots_of_unity.coe_injective key, rw [pow_eq_pow_iff_modeq, ←order_of_subgroup, ←order_of_units, hζ.coe_to_roots_of_unity_coe, ←(zeta_spec n K L).eq_order_of, ←zmod.eq_iff_modeq_nat] at key, simp only [zmod.nat_cast_val, zmod.cast_id', id.def] at key, exact units.ext key end, .. (zeta_spec n K L).aut_to_pow K } include hμ variables {L} /-- Maps `μ` to the `alg_equiv` that sends `is_cyclotomic_extension.zeta` to `μ`. -/ noncomputable def from_zeta_aut : L ≃ₐ[K] L := let hζ := (zeta_spec n K L).eq_pow_of_pow_eq_one hμ.pow_eq_one n.pos in (aut_equiv_pow L h).symm $ zmod.unit_of_coprime hζ.some $ ((zeta_spec n K L).pow_iff_coprime n.pos hζ.some).mp $ hζ.some_spec.some_spec.symm ▸ hμ lemma from_zeta_aut_spec : from_zeta_aut hμ h (zeta n K L) = μ := begin simp_rw [from_zeta_aut, aut_equiv_pow_symm_apply], generalize_proofs _ _ hζ h _ hμ _, rw [←hζ.power_basis_gen K] {occs := occurrences.pos [4]}, rw [power_basis.equiv_of_minpoly_gen, hμ.power_basis_gen K], convert h.some_spec.some_spec, exact zmod.val_cast_of_lt h.some_spec.some end end is_cyclotomic_extension section gal variables (h : irreducible (cyclotomic n K)) {K} /-- `is_cyclotomic_extension.aut_equiv_pow` repackaged in terms of `gal`. Asserts that the Galois group of `cyclotomic n K` is equivalent to `(zmod n)ˣ` if `cyclotomic n K` is irreducible in the base field. -/ noncomputable def gal_cyclotomic_equiv_units_zmod : (cyclotomic n K).gal ≃* (zmod n)ˣ := (alg_equiv.aut_congr (is_splitting_field.alg_equiv _ _)).symm.trans (is_cyclotomic_extension.aut_equiv_pow L h) /-- `is_cyclotomic_extension.aut_equiv_pow` repackaged in terms of `gal`. Asserts that the Galois group of `X ^ n - 1` is equivalent to `(zmod n)ˣ` if `cyclotomic n K` is irreducible in the base field. -/ noncomputable def gal_X_pow_equiv_units_zmod : (X ^ (n : ℕ) - 1).gal ≃* (zmod n)ˣ := (alg_equiv.aut_congr (is_splitting_field.alg_equiv _ _)).symm.trans (is_cyclotomic_extension.aut_equiv_pow L h) end gal
151468144fad0aabaf0c7a8554d59b725a530f58
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/stirling.lean
9852179666596674cf9aeabdf4c4382e510c206f
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
11,150
lean
/- Copyright (c) 2022. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Firsching, Fabian Kruse, Nikolas Kuhn -/ import analysis.p_series import data.real.pi.wallis /-! # Stirling's formula This file proves Stirling's formula for the factorial. It states that $n!$ grows asymptotically like $\sqrt{2\pi n}(\frac{n}{e})^n$. ## Proof outline The proof follows: <https://proofwiki.org/wiki/Stirling%27s_Formula>. We proceed in two parts. **Part 1**: We consider the sequence $a_n$ of fractions $\frac{n!}{\sqrt{2n}(\frac{n}{e})^n}$ and prove that this sequence converges to a real, positive number $a$. For this the two main ingredients are - taking the logarithm of the sequence and - using the series expansion of $\log(1 + x)$. **Part 2**: We use the fact that the series defined in part 1 converges againt a real number $a$ and prove that $a = \sqrt{\pi}$. Here the main ingredient is the convergence of Wallis' product formula for `π`. -/ open_locale topology real big_operators nat open finset filter nat real namespace stirling /-! ### Part 1 https://proofwiki.org/wiki/Stirling%27s_Formula#Part_1 -/ /-- Define `stirling_seq n` as $\frac{n!}{\sqrt{2n}(\frac{n}{e})^n}$. Stirling's formula states that this sequence has limit $\sqrt(π)$. -/ noncomputable def stirling_seq (n : ℕ) : ℝ := n! / (sqrt (2 * n) * (n / exp 1) ^ n) @[simp] lemma stirling_seq_zero : stirling_seq 0 = 0 := by rw [stirling_seq, cast_zero, mul_zero, real.sqrt_zero, zero_mul, div_zero] @[simp] lemma stirling_seq_one : stirling_seq 1 = exp 1 / sqrt 2 := by rw [stirling_seq, pow_one, factorial_one, cast_one, mul_one, mul_one_div, one_div_div] /-- We have the expression `log (stirling_seq (n + 1)) = log(n + 1)! - 1 / 2 * log(2 * n) - n * log ((n + 1) / e)`. -/ lemma log_stirling_seq_formula (n : ℕ) : log (stirling_seq n.succ) = log n.succ!- 1 / 2 * log (2 * n.succ) - n.succ * log (n.succ / exp 1) := by rw [stirling_seq, log_div, log_mul, sqrt_eq_rpow, log_rpow, real.log_pow, tsub_tsub]; try { apply ne_of_gt }; positivity -- TODO: Make `positivity` handle `≠ 0` goals /-- The sequence `log (stirling_seq (m + 1)) - log (stirling_seq (m + 2))` has the series expansion `∑ 1 / (2 * (k + 1) + 1) * (1 / 2 * (m + 1) + 1)^(2 * (k + 1))` -/ lemma log_stirling_seq_diff_has_sum (m : ℕ) : has_sum (λ k : ℕ, (1 : ℝ) / (2 * k.succ + 1) * ((1 / (2 * m.succ + 1)) ^ 2) ^ k.succ) (log (stirling_seq m.succ) - log (stirling_seq m.succ.succ)) := begin change has_sum ((λ b : ℕ, 1 / (2 * (b : ℝ) + 1) * ((1 / (2 * m.succ + 1)) ^ 2) ^ b) ∘ succ) _, refine (has_sum_nat_add_iff 1).mpr _, convert (has_sum_log_one_add_inv $ cast_pos.mpr (succ_pos m)).mul_left ((m.succ : ℝ) + 1 / 2), { ext k, rw [← pow_mul, pow_add], push_cast, have : 2 * (k : ℝ) + 1 ≠ 0, {norm_cast, exact succ_ne_zero (2*k)}, have : 2 * ((m : ℝ) + 1) + 1 ≠ 0, {norm_cast, exact succ_ne_zero (2*m.succ)}, field_simp, ring }, { have h : ∀ (x : ℝ) (hx : x ≠ 0), 1 + x⁻¹ = (x + 1) / x, { intros, rw [_root_.add_div, div_self hx, inv_eq_one_div], }, simp only [log_stirling_seq_formula, log_div, log_mul, log_exp, factorial_succ, cast_mul, cast_succ, cast_zero, range_one, sum_singleton, h] { discharger := `[norm_cast, apply_rules [mul_ne_zero, succ_ne_zero, factorial_ne_zero, exp_ne_zero]] }, ring }, end /-- The sequence `log ∘ stirling_seq ∘ succ` is monotone decreasing -/ lemma log_stirling_seq'_antitone : antitone (real.log ∘ stirling_seq ∘ succ) := antitone_nat_of_succ_le $ λ n, sub_nonneg.mp $ (log_stirling_seq_diff_has_sum n).nonneg $ λ m, by positivity /-- We have a bound for successive elements in the sequence `log (stirling_seq k)`. -/ lemma log_stirling_seq_diff_le_geo_sum (n : ℕ) : log (stirling_seq n.succ) - log (stirling_seq n.succ.succ) ≤ (1 / (2 * n.succ + 1)) ^ 2 / (1 - (1 / (2 * n.succ + 1)) ^ 2) := begin have h_nonneg : 0 ≤ ((1 / (2 * (n.succ : ℝ) + 1)) ^ 2) := sq_nonneg _, have g : has_sum (λ k : ℕ, ((1 / (2 * (n.succ : ℝ) + 1)) ^ 2) ^ k.succ) ((1 / (2 * n.succ + 1)) ^ 2 / (1 - (1 / (2 * n.succ + 1)) ^ 2)), { have := (has_sum_geometric_of_lt_1 h_nonneg _).mul_left ((1 / (2 * (n.succ : ℝ) + 1)) ^ 2), { simp_rw ←pow_succ at this, exact this, }, rw [one_div, inv_pow], exact inv_lt_one (one_lt_pow ((lt_add_iff_pos_left 1).mpr $ by positivity) two_ne_zero) }, have hab : ∀ (k : ℕ), (1 / (2 * (k.succ : ℝ) + 1)) * ((1 / (2 * n.succ + 1)) ^ 2) ^ k.succ ≤ ((1 / (2 * n.succ + 1)) ^ 2) ^ k.succ, { refine λ k, mul_le_of_le_one_left (pow_nonneg h_nonneg k.succ) _, rw one_div, exact inv_le_one (le_add_of_nonneg_left $ by positivity) }, exact has_sum_le hab (log_stirling_seq_diff_has_sum n) g, end /-- We have the bound `log (stirling_seq n) - log (stirling_seq (n+1))` ≤ 1/(4 n^2) -/ lemma log_stirling_seq_sub_log_stirling_seq_succ (n : ℕ) : log (stirling_seq n.succ) - log (stirling_seq n.succ.succ) ≤ 1 / (4 * n.succ ^ 2) := begin have h₁ : 0 < 4 * ((n : ℝ) + 1) ^ 2 := by positivity, have h₃ : 0 < (2 * ((n : ℝ) + 1) + 1) ^ 2 := by positivity, have h₂ : 0 < 1 - (1 / (2 * ((n : ℝ) + 1) + 1)) ^ 2, { rw ← mul_lt_mul_right h₃, have H : 0 < (2 * ((n : ℝ) + 1) + 1) ^ 2 - 1 := by nlinarith [@cast_nonneg ℝ _ n], convert H using 1; field_simp [h₃.ne'] }, refine (log_stirling_seq_diff_le_geo_sum n).trans _, push_cast, rw div_le_div_iff h₂ h₁, field_simp [h₃.ne'], rw div_le_div_right h₃, ring_nf, norm_cast, linarith, end /-- For any `n`, we have `log_stirling_seq 1 - log_stirling_seq n ≤ 1/4 * ∑' 1/k^2` -/ lemma log_stirling_seq_bounded_aux : ∃ (c : ℝ), ∀ (n : ℕ), log (stirling_seq 1) - log (stirling_seq n.succ) ≤ c := begin let d := ∑' k : ℕ, (1 : ℝ) / k.succ ^ 2, use (1 / 4 * d : ℝ), let log_stirling_seq' : ℕ → ℝ := λ k, log (stirling_seq k.succ), intro n, have h₁ : ∀ k, log_stirling_seq' k - log_stirling_seq' (k + 1) ≤ 1 / 4 * (1 / k.succ ^ 2) := by { intro k, convert log_stirling_seq_sub_log_stirling_seq_succ k using 1, field_simp, }, have h₂ : ∑ (k : ℕ) in range n, (1 : ℝ) / (k.succ) ^ 2 ≤ d := by { exact sum_le_tsum (range n) (λ k _, by positivity) ((summable_nat_add_iff 1).mpr $ real.summable_one_div_nat_pow.mpr one_lt_two) }, calc log (stirling_seq 1) - log (stirling_seq n.succ) = log_stirling_seq' 0 - log_stirling_seq' n : rfl ... = ∑ k in range n, (log_stirling_seq' k - log_stirling_seq' (k + 1)) : by rw ← sum_range_sub' log_stirling_seq' n ... ≤ ∑ k in range n, (1/4) * (1 / k.succ^2) : sum_le_sum (λ k _, h₁ k) ... = 1 / 4 * ∑ k in range n, 1 / k.succ ^ 2 : by rw mul_sum ... ≤ 1 / 4 * d : mul_le_mul_of_nonneg_left h₂ $ by positivity, end /-- The sequence `log_stirling_seq` is bounded below for `n ≥ 1`. -/ lemma log_stirling_seq_bounded_by_constant : ∃ c, ∀ (n : ℕ), c ≤ log (stirling_seq n.succ) := begin obtain ⟨d, h⟩ := log_stirling_seq_bounded_aux, exact ⟨log (stirling_seq 1) - d, λ n, sub_le_comm.mp (h n)⟩, end /-- The sequence `stirling_seq` is positive for `n > 0` -/ lemma stirling_seq'_pos (n : ℕ) : 0 < stirling_seq n.succ := by { unfold stirling_seq, positivity } /-- The sequence `stirling_seq` has a positive lower bound. -/ lemma stirling_seq'_bounded_by_pos_constant : ∃ a, 0 < a ∧ ∀ n : ℕ, a ≤ stirling_seq n.succ := begin cases log_stirling_seq_bounded_by_constant with c h, refine ⟨exp c, exp_pos _, λ n, _⟩, rw ← le_log_iff_exp_le (stirling_seq'_pos n), exact h n, end /-- The sequence `stirling_seq ∘ succ` is monotone decreasing -/ lemma stirling_seq'_antitone : antitone (stirling_seq ∘ succ) := λ n m h, (log_le_log (stirling_seq'_pos m) (stirling_seq'_pos n)).mp (log_stirling_seq'_antitone h) /-- The limit `a` of the sequence `stirling_seq` satisfies `0 < a` -/ lemma stirling_seq_has_pos_limit_a : ∃ (a : ℝ), 0 < a ∧ tendsto stirling_seq at_top (𝓝 a) := begin obtain ⟨x, x_pos, hx⟩ := stirling_seq'_bounded_by_pos_constant, have hx' : x ∈ lower_bounds (set.range (stirling_seq ∘ succ)) := by simpa [lower_bounds] using hx, refine ⟨_, lt_of_lt_of_le x_pos (le_cInf (set.range_nonempty _) hx'), _⟩, rw ←filter.tendsto_add_at_top_iff_nat 1, exact tendsto_at_top_cinfi stirling_seq'_antitone ⟨x, hx'⟩, end /-! ### Part 2 https://proofwiki.org/wiki/Stirling%27s_Formula#Part_2 -/ /-- The sequence `n / (2 * n + 1)` tends to `1/2` -/ lemma tendsto_self_div_two_mul_self_add_one : tendsto (λ (n : ℕ), (n : ℝ) / (2 * n + 1)) at_top (𝓝 (1 / 2)) := begin conv { congr, skip, skip, rw [one_div, ←add_zero (2 : ℝ)] }, refine (((tendsto_const_div_at_top_nhds_0_nat 1).const_add (2 : ℝ)).inv₀ ((add_zero (2 : ℝ)).symm ▸ two_ne_zero)).congr' (eventually_at_top.mpr ⟨1, λ n hn, _⟩), rw [add_div' (1 : ℝ) 2 n (cast_ne_zero.mpr (one_le_iff_ne_zero.mp hn)), inv_div], end /-- For any `n ≠ 0`, we have the identity `(stirling_seq n)^4 / (stirling_seq (2*n))^2 * (n / (2 * n + 1)) = W n`, where `W n` is the `n`-th partial product of Wallis' formula for `π / 2`. -/ lemma stirling_seq_pow_four_div_stirling_seq_pow_two_eq (n : ℕ) (hn : n ≠ 0) : ((stirling_seq n) ^ 4 / (stirling_seq (2 * n)) ^ 2) * (n / (2 * n + 1)) = wallis.W n := begin rw [bit0_eq_two_mul, stirling_seq, pow_mul, stirling_seq, wallis.W_eq_factorial_ratio], simp_rw [div_pow, mul_pow], rw [sq_sqrt, sq_sqrt], any_goals { positivity }, have : (n : ℝ) ≠ 0, from cast_ne_zero.mpr hn, have : (exp 1) ≠ 0, from exp_ne_zero 1, have : ((2 * n)!: ℝ) ≠ 0, from cast_ne_zero.mpr (factorial_ne_zero (2 * n)), have : 2 * (n : ℝ) + 1 ≠ 0, by {norm_cast, exact succ_ne_zero (2*n)}, field_simp, simp only [mul_pow, mul_comm 2 n, mul_comm 4 n, pow_mul], ring, end /-- Suppose the sequence `stirling_seq` (defined above) has the limit `a ≠ 0`. Then the Wallis sequence `W n` has limit `a^2 / 2`. -/ lemma second_wallis_limit (a : ℝ) (hane : a ≠ 0) (ha : tendsto stirling_seq at_top (𝓝 a)) : tendsto wallis.W at_top (𝓝 (a ^ 2 / 2)):= begin refine tendsto.congr' (eventually_at_top.mpr ⟨1, λ n hn, stirling_seq_pow_four_div_stirling_seq_pow_two_eq n (one_le_iff_ne_zero.mp hn)⟩) _, have h : a ^ 2 / 2 = (a ^ 4 / a ^ 2) * (1 / 2), { rw [mul_one_div, ←mul_one_div (a ^ 4) (a ^ 2), one_div, ←pow_sub_of_lt a], norm_num }, rw h, exact ((ha.pow 4).div ((ha.comp (tendsto_id.const_mul_at_top' two_pos)).pow 2) (pow_ne_zero 2 hane)).mul tendsto_self_div_two_mul_self_add_one, end /-- **Stirling's Formula** -/ theorem tendsto_stirling_seq_sqrt_pi : tendsto (λ (n : ℕ), stirling_seq n) at_top (𝓝 (sqrt π)) := begin obtain ⟨a, hapos, halimit⟩ := stirling_seq_has_pos_limit_a, have hπ : π / 2 = a ^ 2 / 2 := tendsto_nhds_unique wallis.tendsto_W_nhds_pi_div_two (second_wallis_limit a hapos.ne' halimit), rwa [(div_left_inj' (two_ne_zero' ℝ)).mp hπ, sqrt_sq hapos.le], end end stirling
c4f6390e7461ea25cdb58de4beb282c1924febc4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/noetherian.lean
41b91c12f57de1bf96bdc71c4931c8c689f32f87
[ "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
23,431
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal.operations import linear_algebra.linear_independent import order.order_iso_nat /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [semimodule R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h, linear_map.map_injective hf $ by { rw [map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [semimodule R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply rel_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian {R M} [ring R] [add_comm_group M] [module R M] : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end section local attribute [instance] subset.comm_ring instance is_noetherian_ring_set_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range (f.cod_restrict' f.range f.mem_range_self) f.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
c4ed6e3bf037b2d631f0356be76a3ba07b6cf44d
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/category_theory/limits/lattice.lean
0a3db300a2810faeb20ada615cfab5366e696282
[ "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
7,232
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import category_theory.category.preorder import category_theory.limits.shapes.finite_limits import order.complete_lattice universes u open category_theory open category_theory.limits namespace category_theory.limits.complete_lattice section semilattice variables {α : Type u} variables {J : Type u} [small_category J] [fin_category J] /-- The limit cone over any functor from a finite diagram into a `semilattice_inf_top`. -/ def finite_limit_cone [semilattice_inf_top α] (F : J ⥤ α) : limit_cone F := { cone := { X := finset.univ.inf F.obj, π := { app := λ j, hom_of_le (finset.inf_le (fintype.complete _)) } }, is_limit := { lift := λ s, hom_of_le (finset.le_inf (λ j _, (s.π.app j).down.down)) } } /-- The colimit cocone over any functor from a finite diagram into a `semilattice_sup_bot`. -/ def finite_colimit_cocone [semilattice_sup_bot α] (F : J ⥤ α) : colimit_cocone F := { cocone := { X := finset.univ.sup F.obj, ι := { app := λ i, hom_of_le (finset.le_sup (fintype.complete _)) } }, is_colimit := { desc := λ s, hom_of_le (finset.sup_le (λ j _, (s.ι.app j).down.down)) } } @[priority 100] -- see Note [lower instance priority] instance has_finite_limits_of_semilattice_inf_top [semilattice_inf_top α] : has_finite_limits α := ⟨λ J 𝒥₁ 𝒥₂, by exactI { has_limit := λ F, has_limit.mk (finite_limit_cone F) }⟩ @[priority 100] -- see Note [lower instance priority] instance has_finite_colimits_of_semilattice_sup_bot [semilattice_sup_bot α] : has_finite_colimits α := ⟨λ J 𝒥₁ 𝒥₂, by exactI { has_colimit := λ F, has_colimit.mk (finite_colimit_cocone F) }⟩ /-- The limit of a functor from a finite diagram into a `semilattice_inf_top` is the infimum of the objects in the image. -/ lemma finite_limit_eq_finset_univ_inf [semilattice_inf_top α] (F : J ⥤ α) : limit F = finset.univ.inf F.obj := (is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (finite_limit_cone F).is_limit).to_eq /-- The colimit of a functor from a finite diagram into a `semilattice_sup_bot` is the supremum of the objects in the image. -/ lemma finite_colimit_eq_finset_univ_sup [semilattice_sup_bot α] (F : J ⥤ α) : colimit F = finset.univ.sup F.obj := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (finite_colimit_cocone F).is_colimit).to_eq /-- A finite product in the category of a `semilattice_inf_top` is the same as the infimum. -/ lemma finite_product_eq_finset_inf [semilattice_inf_top α] {ι : Type u} [decidable_eq ι] [fintype ι] (f : ι → α) : (∏ f) = (fintype.elems ι).inf f := (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (finite_limit_cone (discrete.functor f)).is_limit).to_eq /-- A finite coproduct in the category of a `semilattice_sup_bot` is the same as the supremum. -/ lemma finite_coproduct_eq_finset_sup [semilattice_sup_bot α] {ι : Type u} [decidable_eq ι] [fintype ι] (f : ι → α) : (∐ f) = (fintype.elems ι).sup f := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (finite_colimit_cocone (discrete.functor f)).is_colimit).to_eq /-- The binary product in the category of a `semilattice_inf_top` is the same as the infimum. -/ @[simp] lemma prod_eq_inf [semilattice_inf_top α] (x y : α) : limits.prod x y = x ⊓ y := calc limits.prod x y = limit (pair x y) : rfl ... = finset.univ.inf (pair x y).obj : by rw finite_limit_eq_finset_univ_inf (pair x y) ... = x ⊓ (y ⊓ ⊤) : rfl -- Note: finset.inf is realized as a fold, hence the definitional equality ... = x ⊓ y : by rw inf_top_eq /-- The binary coproduct in the category of a `semilattice_sup_bot` is the same as the supremum. -/ @[simp] lemma coprod_eq_sup [semilattice_sup_bot α] (x y : α) : limits.coprod x y = x ⊔ y := calc limits.coprod x y = colimit (pair x y) : rfl ... = finset.univ.sup (pair x y).obj : by rw finite_colimit_eq_finset_univ_sup (pair x y) ... = x ⊔ (y ⊔ ⊥) : rfl -- Note: finset.sup is realized as a fold, hence the definitional equality ... = x ⊔ y : by rw sup_bot_eq /-- The pullback in the category of a `semilattice_inf_top` is the same as the infimum over the objects. -/ @[simp] lemma pullback_eq_inf [semilattice_inf_top α] {x y z : α} (f : x ⟶ z) (g : y ⟶ z) : pullback f g = x ⊓ y := calc pullback f g = limit (cospan f g) : rfl ... = finset.univ.inf (cospan f g).obj : by rw finite_limit_eq_finset_univ_inf ... = z ⊓ (x ⊓ (y ⊓ ⊤)) : rfl ... = z ⊓ (x ⊓ y) : by rw inf_top_eq ... = x ⊓ y : inf_eq_right.mpr (inf_le_of_left_le f.le) /-- The pushout in the category of a `semilattice_sup_bot` is the same as the supremum over the objects. -/ @[simp] lemma pushout_eq_sup [semilattice_sup_bot α] (x y z : α) (f : z ⟶ x) (g : z ⟶ y) : pushout f g = x ⊔ y := calc pushout f g = colimit (span f g) : rfl ... = finset.univ.sup (span f g).obj : by rw finite_colimit_eq_finset_univ_sup ... = z ⊔ (x ⊔ (y ⊔ ⊥)) : rfl ... = z ⊔ (x ⊔ y) : by rw sup_bot_eq ... = x ⊔ y : sup_eq_right.mpr (le_sup_of_le_left f.le) end semilattice variables {α : Type u} [complete_lattice α] variables {J : Type u} [small_category J] /-- The limit cone over any functor into a complete lattice. -/ def limit_cone (F : J ⥤ α) : limit_cone F := { cone := { X := infi F.obj, π := { app := λ j, hom_of_le (complete_lattice.Inf_le _ _ (set.mem_range_self _)) } }, is_limit := { lift := λ s, hom_of_le (complete_lattice.le_Inf _ _ begin rintros _ ⟨j, rfl⟩, exact (s.π.app j).le, end) } } /-- The colimit cocone over any functor into a complete lattice. -/ def colimit_cocone (F : J ⥤ α) : colimit_cocone F := { cocone := { X := supr F.obj, ι := { app := λ j, hom_of_le (complete_lattice.le_Sup _ _ (set.mem_range_self _)) } }, is_colimit := { desc := λ s, hom_of_le (complete_lattice.Sup_le _ _ begin rintros _ ⟨j, rfl⟩, exact (s.ι.app j).le, end) } } -- It would be nice to only use the `Inf` half of the complete lattice, but -- this seems not to have been described separately. @[priority 100] -- see Note [lower instance priority] instance has_limits_of_complete_lattice : has_limits α := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk (limit_cone F) } } @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_complete_lattice : has_colimits α := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk (colimit_cocone F) } } /-- The limit of a functor into a complete lattice is the infimum of the objects in the image. -/ lemma limit_eq_infi (F : J ⥤ α) : limit F = infi F.obj := (is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (limit_cone F).is_limit).to_eq /-- The colimit of a functor into a complete lattice is the supremum of the objects in the image. -/ lemma colimit_eq_supr (F : J ⥤ α) : colimit F = supr F.obj := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone F).is_colimit).to_eq end category_theory.limits.complete_lattice
2159398defdda6ca7a6db355a64cf856129642fe
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/topology/algebra/monoid.lean
a78708b8bcaa4537283e3b10be0bfcd062533353
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,292
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 @[to_additive, continuity] 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 : _) 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))⟩ @[to_additive, priority 100] 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 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 @[to_additive, continuity] 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 _ attribute [continuity] continuous_finset_sum end
4b1bf1dfc1a5a162934ff61e711159e760940241
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/rewrite.lean
45f1a86ab9334c32767c781d54b34ffb34863bba
[ "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
7,963
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.dlist import tactic.core namespace tactic open expr list meta def match_fn (fn : expr) : expr → tactic (expr × expr) | (app (app fn' e₀) e₁) := unify fn fn' $> (e₀, e₁) | _ := failed meta def fill_args : expr → tactic (expr × list expr) | (pi n bi d b) := do v ← mk_meta_var d, (r, vs) ← fill_args (b.instantiate_var v), return (r, v::vs) | e := return (e, []) meta def mk_assoc_pattern' (fn : expr) : expr → tactic (dlist expr) | e := (do (e₀, e₁) ← match_fn fn e, (++) <$> mk_assoc_pattern' e₀ <*> mk_assoc_pattern' e₁) <|> pure (dlist.singleton e) meta def mk_assoc_pattern (fn e : expr) : tactic (list expr) := dlist.to_list <$> mk_assoc_pattern' fn e meta def mk_assoc (fn : expr) : list expr → tactic expr | [] := failed | [x] := pure x | (x₀ :: x₁ :: xs) := mk_assoc (fn x₀ x₁ :: xs) meta def chain_eq_trans : list expr → tactic expr | [] := to_expr ``(rfl) | [e] := pure e | (e :: es) := chain_eq_trans es >>= mk_eq_trans e meta def unify_prefix : list expr → list expr → tactic unit | [] _ := pure () | _ [] := failed | (x :: xs) (y :: ys) := unify x y >> unify_prefix xs ys meta def match_assoc_pattern' (p : list expr) : list expr → tactic (list expr × list expr) | es := unify_prefix p es $> ([], es.drop p.length) <|> match es with | [] := failed | (x :: xs) := prod.map (cons x) id <$> match_assoc_pattern' xs end meta def match_assoc_pattern (fn p e : expr) : tactic (list expr × list expr) := do p' ← mk_assoc_pattern fn p, e' ← mk_assoc_pattern fn e, match_assoc_pattern' p' e' meta def mk_eq_proof (fn : expr) (e₀ e₁ : list expr) (p : expr) : tactic (expr × expr × expr) := do (l, r) ← infer_type p >>= match_eq, if e₀.empty ∧ e₁.empty then pure (l, r, p) else do l' ← mk_assoc fn (e₀ ++ [l] ++ e₁), r' ← mk_assoc fn (e₀ ++ [r] ++ e₁), t ← infer_type l', v ← mk_local_def `x t, e ← mk_assoc fn (e₀ ++ [v] ++ e₁), p ← mk_congr_arg (e.lambdas [v]) p, p' ← mk_id_eq l' r' p, return (l', r', p') meta def assoc_root (fn assoc : expr) : expr → tactic (expr × expr) | e := (do (e₀, e₁) ← match_fn fn e, (ea, eb) ← match_fn fn e₁, let e' := fn (fn e₀ ea) eb, p' ← mk_eq_symm (assoc e₀ ea eb), (e'', p'') ← assoc_root e', prod.mk e'' <$> mk_eq_trans p' p'') <|> prod.mk e <$> mk_eq_refl e meta def assoc_refl' (fn assoc : expr) : expr → expr → tactic expr | l r := (is_def_eq l r >> mk_eq_refl l) <|> do (l', l_p) ← assoc_root fn assoc l <|> fail "A", (el₀, el₁) ← match_fn fn l' <|> fail "B", (r', r_p) ← assoc_root fn assoc r <|> fail "C", (er₀, er₁) ← match_fn fn r' <|> fail "D", p₀ ← assoc_refl' el₀ er₀, p₁ ← is_def_eq el₁ er₁ >> mk_eq_refl el₁, f_eq ← mk_congr_arg fn p₀ <|> fail "G", p' ← mk_congr f_eq p₁ <|> fail "H", r_p' ← mk_eq_symm r_p, chain_eq_trans [l_p, p', r_p'] meta def assoc_refl (fn : expr) : tactic unit := do (l, r) ← target >>= match_eq, assoc ← mk_mapp ``is_associative.assoc [none, fn, none] <|> fail format!"{fn} is not associative", assoc_refl' fn assoc l r >>= tactic.exact meta def flatten (fn assoc e : expr) : tactic (expr × expr) := do ls ← mk_assoc_pattern fn e, e' ← mk_assoc fn ls, p ← assoc_refl' fn assoc e e', return (e', p) meta def assoc_rewrite_intl (assoc h e : expr) : tactic (expr × expr) := do t ← infer_type h, (lhs, rhs) ← match_eq t, let fn := lhs.app_fn.app_fn, (l, r) ← match_assoc_pattern fn lhs e, (lhs', rhs', h') ← mk_eq_proof fn l r h, e_p ← assoc_refl' fn assoc e lhs', (rhs'', rhs_p) ← flatten fn assoc rhs', final_p ← chain_eq_trans [e_p, h', rhs_p], return (rhs'', final_p) -- TODO(Simon): visit expressions built of `fn` nested inside other such expressions: -- e.g.: x + f (a + b + c) + y should generate two rewrite candidates meta def enum_assoc_subexpr' (fn : expr) : expr → tactic (dlist expr) | e := dlist.singleton e <$ (match_fn fn e >> guard (¬ e.has_var)) <|> expr.mfoldl (λ es e', (++ es) <$> enum_assoc_subexpr' e') dlist.empty e meta def enum_assoc_subexpr (fn e : expr) : tactic (list expr) := dlist.to_list <$> enum_assoc_subexpr' fn e meta def mk_assoc_instance (fn : expr) : tactic expr := do t ← mk_mapp ``is_associative [none, fn], inst ← prod.snd <$> solve_aux t assumption <|> (mk_instance t >>= assertv `_inst t) <|> fail format!"{fn} is not associative", mk_mapp ``is_associative.assoc [none, fn, inst] meta def assoc_rewrite (h e : expr) (opt_assoc : option expr := none) : tactic (expr × expr × list expr) := do (t, vs) ← infer_type h >>= fill_args, (lhs, rhs) ← match_eq t, let fn := lhs.app_fn.app_fn, es ← enum_assoc_subexpr fn e, assoc ← match opt_assoc with | none := mk_assoc_instance fn | (some assoc) := pure assoc end, (_, p) ← mfirst (assoc_rewrite_intl assoc $ h.mk_app vs) es, (e', p', _) ← tactic.rewrite p e, pure (e', p', vs) meta def assoc_rewrite_target (h : expr) (opt_assoc : option expr := none) : tactic unit := do tgt ← target, (tgt', p, _) ← assoc_rewrite h tgt opt_assoc, replace_target tgt' p meta def assoc_rewrite_hyp (h hyp : expr) (opt_assoc : option expr := none) : tactic expr := do tgt ← infer_type hyp, (tgt', p, _) ← assoc_rewrite h tgt opt_assoc, replace_hyp hyp tgt' p namespace interactive open lean.parser interactive interactive.types tactic private meta def assoc_rw_goal (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, assoc_rewrite_target e) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, assoc_rewrite_target e) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || (t = h) private meta def assoc_rw_hyp : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (¬ uses_hyp e hyp) $ assoc_rewrite_hyp e hyp >>= assoc_rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, assoc_rewrite_hyp e hyp >>= assoc_rw_hyp rs) (eq_lemmas.empty) private meta def assoc_rw_core (rs : parse rw_rules) (loca : parse location) : tactic unit := match loca with | loc.wildcard := loca.try_apply (assoc_rw_hyp rs.rules) (assoc_rw_goal rs.rules) | _ := loca.apply (assoc_rw_hyp rs.rules) (assoc_rw_goal rs.rules) end >> try reflexivity >> try (returnopt rs.end_pos >>= save_info) /-- `assoc_rewrite [h₀,← h₁] at ⊢ h₂` behaves like `rewrite [h₀,← h₁] at ⊢ h₂` with the exception that associativity is used implicitly to make rewriting possible. It works for any function `f` for which an `is_associative f` instance can be found. ``` example {α : Type*} (f : α → α → α) [is_associative α f] (a b c d x : α) : let infix `~` := f in b ~ c = x → (a ~ b ~ c ~ d) = (a ~ x ~ d) := begin intro h, assoc_rw h, end ``` -/ meta def assoc_rewrite (q : parse rw_rules) (l : parse location) : tactic unit := propagate_tags (assoc_rw_core q l) /-- synonym for `assoc_rewrite` -/ meta def assoc_rw (q : parse rw_rules) (l : parse location) : tactic unit := assoc_rewrite q l add_tactic_doc { name := "assoc_rewrite", category := doc_category.tactic, decl_names := [`tactic.interactive.assoc_rewrite, `tactic.interactive.assoc_rw], tags := ["rewriting"], inherit_description_from := `tactic.interactive.assoc_rewrite } end interactive end tactic
fc76776268f4395e670853dc28cdffe150dfc27c
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/linear_algebra/quadratic_form.lean
e973fbbec384494f54f71720314ad88f343aa112
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
11,675
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen Quadratic forms over modules. -/ import algebra.invertible import linear_algebra.bilinear_form import linear_algebra.determinant import linear_algebra.special_linear_group /-! # Quadratic forms This file defines quadratic forms over a `R`-module `M`. A quadratic form is a map `Q : M → R` such that (`to_fun_smul`) `Q (a • x) = a * a * Q x` (`polar_...`) The map `polar Q := λ x y, Q (x + y) - Q x - Q y` is bilinear. They come with a scalar multiplication, `(a • Q) x = Q (a • x) = a * a * Q x`, and composition with linear maps `f`, `Q.comp f x = Q (f x)`. ## Main definitions * `quadratic_form.associated`: associated bilinear form * `quadratic_form.pos_def`: positive definite quadratic forms * `quadratic_form.discr`: discriminant of a quadratic form ## Main statements * `quadratic_form.associated_left_inverse`, * `quadratic_form.associated_right_inverse`: in a commutative ring where 2 has an inverse, there is a correspondence between quadratic forms and symmetric bilinear forms ## Notation In this file, the variable `R` is used when a `ring` structure is sufficient and `R₁` is used when specifically a `comm_ring` is required. This allows us to keep `[module R M]` and `[module R₁ M]` assumptions in the variables without confusion between `*` from `ring` and `*` from `comm_ring`. ## References * https://en.wikipedia.org/wiki/Quadratic_form * https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms ## Tags quadratic form, homogeneous polynomial, quadratic polynomial -/ universes u v w variables {R : Type u} {M : Type v} [add_comm_group M] [ring R] variables {R₁ : Type u} [comm_ring R₁] [module R₁ M] /-- Up to a factor 2, `Q.polar` is the associated bilinear form for a quadratic form `Q`.d Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization -/ def quadratic_form.polar (f : M → R) (x y : M) := f (x + y) - f x - f y variables [module R M] open quadratic_form /-- A quadratic form over a module. -/ structure quadratic_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] := (to_fun : M → R) (to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x) (polar_add_left : ∀ (x x' y : M), polar to_fun (x + x') y = polar to_fun x y + polar to_fun x' y) (polar_smul_left : ∀ (a : R) (x y : M), polar to_fun (a • x) y = a • polar to_fun x y) (polar_add_right : ∀ (x y y' : M), polar to_fun x (y + y') = polar to_fun x y + polar to_fun x y') (polar_smul_right : ∀ (a : R) (x y : M), polar to_fun x (a • y) = a • polar to_fun x y) namespace quadratic_form variables {Q : quadratic_form R M} instance : has_coe_to_fun (quadratic_form R M) := ⟨_, λ B, B.to_fun⟩ /-- The `simp` normal form for a quadratic form is `coe_fn`, not `to_fun`. -/ @[simp] lemma to_fun_eq_apply : Q.to_fun = ⇑ Q := rfl lemma map_smul (a : R) (x : M) : Q (a • x) = a * a * Q x := Q.to_fun_smul a x lemma map_add_self (x : M) : Q (x + x) = 4 * Q x := by { rw [←one_smul R x, ←add_smul, map_smul], norm_num } lemma map_zero : Q 0 = 0 := by rw [←@zero_smul R _ _ _ _ (0 : M), map_smul, zero_mul, zero_mul] lemma map_neg (x : M) : Q (-x) = Q x := by rw [←@neg_one_smul R _ _ _ _ x, map_smul, neg_one_mul, neg_neg, one_mul] lemma map_sub (x y : M) : Q (x - y) = Q (y - x) := by rw [←neg_sub, map_neg] variable {Q' : quadratic_form R M} @[ext] lemma ext (H : ∀ (x : M), Q x = Q' x) : Q = Q' := by { cases Q, cases Q', congr, funext, apply H } instance : has_zero (quadratic_form R M) := ⟨ { to_fun := λ x, 0, to_fun_smul := λ a x, by simp, polar_add_left := λ x x' y, by simp [polar], polar_smul_left := λ a x y, by simp [polar], polar_add_right := λ x y y', by simp [polar], polar_smul_right := λ a x y, by simp [polar] } ⟩ instance : inhabited (quadratic_form R M) := ⟨0⟩ instance : has_scalar R₁ (quadratic_form R₁ M) := ⟨ λ a Q, { to_fun := λ x, Q (a • x), to_fun_smul := λ b x, by rw [smul_comm, map_smul], polar_add_left := λ x x' y, by convert Q.polar_add_left (a • x) (a • x') (a • y) using 1; simp [polar, smul_add], polar_smul_left := λ b x y, by convert Q.polar_smul_left b (a • x) (a • y) using 1; simp [polar, smul_add, smul_comm], polar_add_right := λ x y y', by convert Q.polar_add_right (a • x) (a • y) (a • y') using 1; simp [polar, smul_add], polar_smul_right := λ b x y, by convert Q.polar_smul_right b (a • x) (a • y) using 1; simp [polar, smul_add, smul_comm] } ⟩ @[simp] lemma smul_apply (a : R₁) (Q : quadratic_form R₁ M) (x : M) : (a • Q) x = Q (a • x) := rfl instance : mul_action R₁ (quadratic_form R₁ M) := { mul_smul := λ a b Q, ext (λ x, by simp [mul_smul, smul_comm]), one_smul := λ Q, ext (λ x, by simp), ..quadratic_form.has_scalar } section comp variables {N : Type v} [add_comm_group N] [module R N] /-- Compose the quadratic form with a linear function. -/ def comp (Q : quadratic_form R N) (f : M →ₗ[R] N) : quadratic_form R M := { to_fun := λ x, Q (f x), to_fun_smul := λ a x, by simp [map_smul], polar_add_left := λ x x' y, by convert Q.polar_add_left (f x) (f x') (f y) using 1; simp [polar], polar_smul_left := λ a x y, by convert Q.polar_smul_left a (f x) (f y) using 1; simp [polar], polar_add_right := λ x y y', by convert Q.polar_add_right (f x) (f y) (f y') using 1; simp [polar], polar_smul_right := λ a x y, by convert Q.polar_smul_right a (f x) (f y) using 1; simp [polar] } @[simp] lemma comp_apply (Q : quadratic_form R N) (f : M →ₗ[R] N) (x : M) : (Q.comp f) x = Q (f x) := rfl end comp end quadratic_form /-! ### Associated bilinear forms Over a commutative ring with an inverse of 2, the theory of quadratic forms is basically identical to that of symmetric bilinear forms. The map from quadratic forms to bilinear forms giving this identification is called the `associated` quadratic form. -/ variables {B : bilin_form R M} namespace bilin_form open quadratic_form lemma polar_to_quadratic_form (x y : M) : polar (λ x, B x x) x y = B x y + B y x := by simp [polar, add_left, add_right, sub_eq_add_neg _ (B y y), add_comm (B y x) _] /-- A bilinear form gives a quadratic form by applying the argument twice. -/ def to_quadratic_form (B : bilin_form R M) : quadratic_form R M := ⟨ λ x, B x x, λ a x, by simp [smul_left, smul_right, mul_assoc], λ x x' y, by simp [polar_to_quadratic_form, add_left, add_right, add_left_comm], λ a x y, by simp [polar_to_quadratic_form, smul_left, smul_right, mul_add], λ x y y', by simp [polar_to_quadratic_form, add_left, add_right, add_left_comm], λ a x y, by simp [polar_to_quadratic_form, smul_left, smul_right, mul_add] ⟩ @[simp] lemma to_quadratic_form_apply (B : bilin_form R M) (x : M) : B.to_quadratic_form x = B x x := rfl end bilin_form namespace quadratic_form open bilin_form sym_bilin_form section associated variables [invertible (2 : R₁)] {B₁ : bilin_form R₁ M} (Q : quadratic_form R₁ M) /-- `Q.associated` is the symmetric bilinear form associated to a quadratic form `Q`. -/ def associated : bilin_form R₁ M := { bilin := λ x y, ⅟2 * polar Q x y, bilin_add_left := λ x y z, by { erw [← mul_add, Q.polar_add_left], refl }, bilin_smul_left := λ x y z, by { erw [← mul_left_comm, Q.polar_smul_left], refl }, bilin_add_right := λ x y z, by { erw [← mul_add, Q.polar_add_right], refl }, bilin_smul_right := λ x y z, by { erw [← mul_left_comm, Q.polar_smul_right], refl } } @[simp] lemma associated_apply (x y : M) : Q.associated x y = ⅟2 * (Q (x + y) - Q x - Q y) := rfl lemma associated_is_sym : is_sym Q.associated := λ x y, by simp [add_comm, add_left_comm, sub_eq_add_neg] @[simp] lemma associated_smul (a : R₁) : (a • Q).associated = (a * a) • Q.associated := by { ext, simp [bilin_form.smul_apply, map_smul, mul_sub, mul_left_comm] } @[simp] lemma associated_comp {N : Type v} [add_comm_group N] [module R₁ N] (f : N →ₗ[R₁] M) : (Q.comp f).associated = Q.associated.comp f f := by { ext, simp } lemma associated_to_quadratic_form (B : bilin_form R₁ M) (x y : M) : B.to_quadratic_form.associated x y = ⅟2 * (B x y + B y x) := by simp [associated_apply, ←polar_to_quadratic_form, polar] lemma associated_left_inverse (h : is_sym B₁) : B₁.to_quadratic_form.associated = B₁ := bilin_form.ext $ λ x y, by rw [associated_to_quadratic_form, sym h x y, ←two_mul, ←mul_assoc, inv_of_mul_self, one_mul] lemma associated_right_inverse : Q.associated.to_quadratic_form = Q := quadratic_form.ext $ λ x, calc Q.associated.to_quadratic_form x = ⅟2 * (Q x + Q x) : by simp [map_add_self, bit0, add_mul] ... = Q x : by rw [← two_mul (Q x), ←mul_assoc, inv_of_mul_self, one_mul] end associated section pos_def variables {R₂ : Type u} [ordered_ring R₂] [module R₂ M] {Q₂ : quadratic_form R₂ M} /-- A positive definite quadratic form is positive on nonzero vectors. -/ def pos_def (Q₂ : quadratic_form R₂ M) : Prop := ∀ x ≠ 0, 0 < Q₂ x lemma smul_pos_def_of_smul_nonzero {R} [linear_ordered_comm_ring R] [module R M] {Q : quadratic_form R M} (h : pos_def Q) {a : R} : (∀ x ≠ (0 : M), a • x ≠ 0) → pos_def (a • Q) := λ ha x hx, h (a • x) (ha x hx) lemma smul_pos_def_of_nonzero {K : Type u} [linear_ordered_field K] [module K M] {Q : quadratic_form K M} (h : pos_def Q) {a : K} : a ≠ 0 → pos_def (a • Q) := λ ha x hx, h (a • x) (λ hax, (smul_eq_zero.mp hax).elim ha hx) end pos_def end quadratic_form /-! ### Quadratic forms and matrices Connect quadratic forms and matrices, in order to explicitly compute with them. The convention is twos out, so there might be a factor 2⁻¹ in the entries of the matrix. The determinant of the matrix is the discriminant of the quadratic form. -/ variables {n : Type w} [fintype n] /-- `M.to_quadratic_form` is the map `λ x, col x ⬝ M ⬝ row x` as a quadratic form. -/ def matrix.to_quadratic_form (M : matrix n n R₁) : quadratic_form R₁ (n → R₁) := M.to_bilin_form.to_quadratic_form variables [decidable_eq n] [invertible (2 : R₁)] /-- A matrix representation of the quadratic form. -/ def quadratic_form.to_matrix (Q : quadratic_form R₁ (n → R₁)) : matrix n n R₁ := Q.associated.to_matrix open quadratic_form lemma quadratic_form.to_matrix_smul (a : R₁) (Q : quadratic_form R₁ (n → R₁)) : (a • Q).to_matrix = (a * a) • Q.to_matrix := by simp_rw [to_matrix, associated_smul, mul_smul, bilin_form.to_matrix_smul] namespace quadratic_form variables {m : Type w} [fintype m] [decidable_eq m] open_locale matrix @[simp] lemma to_matrix_comp (Q : quadratic_form R₁ (m → R₁)) (f : (n → R₁) →ₗ[R₁] (m → R₁)) : (Q.comp f).to_matrix = f.to_matrixᵀ ⬝ Q.to_matrix ⬝ f.to_matrix := by { ext, simp [to_matrix, bilin_form.to_matrix_comp] } section discriminant variables {Q : quadratic_form R₁ (n → R₁)} /-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/ def discr (Q : quadratic_form R₁ (n → R₁)) : R₁ := Q.to_matrix.det lemma discr_smul (a : R₁) : (a • Q).discr = (a * a) ^ fintype.card n * Q.discr := by simp [discr, to_matrix_smul] lemma discr_comp (f : (n → R₁) →ₗ[R₁] (n → R₁)) : (Q.comp f).discr = f.to_matrix.det * f.to_matrix.det * Q.discr := by simp [discr, mul_left_comm, mul_comm] end discriminant end quadratic_form
ee3b4b8d150d4c016021be1934ed752821f11101
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Server/FileSource.lean
f393560e149e605d7df138cd7da7cedb5eee13b3
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
2,690
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga -/ import Lean.Data.Lsp namespace Lean.Lsp class FileSource (α : Type) where fileSource : α → DocumentUri export FileSource (fileSource) instance : FileSource Location := ⟨fun l => l.uri⟩ instance : FileSource TextDocumentIdentifier := ⟨fun i => i.uri⟩ instance : FileSource VersionedTextDocumentIdentifier := ⟨fun i => i.uri⟩ instance : FileSource TextDocumentEdit := ⟨fun e => fileSource e.textDocument⟩ instance : FileSource TextDocumentItem := ⟨fun i => i.uri⟩ instance : FileSource TextDocumentPositionParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidOpenTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidChangeTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource DidCloseTextDocumentParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource CompletionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource HoverParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DeclarationParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DefinitionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource TypeDefinitionParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource ReferenceParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource WaitForDiagnosticsParams := ⟨fun p => p.uri⟩ instance : FileSource DocumentHighlightParams := ⟨fun h => fileSource h.toTextDocumentPositionParams⟩ instance : FileSource DocumentSymbolParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource SemanticTokensParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource SemanticTokensRangeParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource FoldingRangeParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource PlainGoalParams := ⟨fun p => fileSource p.textDocument⟩ instance : FileSource PlainTermGoalParams where fileSource p := fileSource p.textDocument instance : FileSource RpcConnectParams where fileSource p := p.uri instance : FileSource RpcCallParams where fileSource p := fileSource p.textDocument instance : FileSource RpcReleaseParams where fileSource p := p.uri instance : FileSource RpcKeepAliveParams where fileSource p := p.uri end Lean.Lsp
0d9501ae1348b174bd826a048f4a5d3abfa7f68e
fe84e287c662151bb313504482b218a503b972f3
/src/algebra/affine_space.lean
bf6f596ccc931f98a5d0e904743da4b45a5a9d25
[]
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
6,548
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This file sets up the theory of affine spaces. One approach would be to say that an affine space consists of a commutative additive group A together with a type V and a free transitive action of A on V. From this point of view, we could define a parallelogram to be a list of the form [v, v + a, v + b, v + a + b] for some v in V and a,b in A. Here, however, we proceed in a slightly different way: we assume that we are given an inhabited type V and a set of parallelograms subject to some axioms. From these we construct A as a quotient of V × V, and then construct a free transitive action of A on V. -/ import algebra.group class affine_space (V : Type*) := (is_parallelogram : V → V → V → V → Prop) (flip : ∀ {a b c d}, is_parallelogram a b c d → is_parallelogram c d a b) (flip' : ∀ {a b c d}, is_parallelogram a b c d → is_parallelogram a c b d) (glue : ∀ {a b c d e f}, is_parallelogram a b c d → is_parallelogram c d e f → is_parallelogram a b e f) (thin : ∀ a b, is_parallelogram a b a b) (fill : V → V → V → V) (fill_iff : ∀ {a b c d}, is_parallelogram a b c d ↔ d = fill a b c) namespace affine_space variables (V : Type*) [affine_space V] [inhabited V] variables a b c d e f a' b' c' d' : V instance translation_setoid : setoid (V × V) := { r := λ st uv , is_parallelogram st.1 st.2 uv.1 uv.2, iseqv := by { split, {intro st, exact thin st.1 st.2}, split, {intros st uv h, exact flip h}, {intros st uv xy h k, exact glue h k} } } variable {V} lemma flip_iff : is_parallelogram a b c d ↔ is_parallelogram c d a b := ⟨flip, flip⟩ lemma flip'_iff : is_parallelogram a b c d ↔ is_parallelogram a c b d := ⟨flip', flip'⟩ lemma fill_prop : is_parallelogram a b c (fill a b c) := (@fill_iff V _ _ _ _ _).mpr (rfl : fill a b c = fill a b c) lemma fill_symm : fill a b c = fill a c b := (@fill_iff V _ _ _ _ _).mp (flip' (fill_prop a b c)) variables {a b c d a' b' c' d'} lemma inj_d : is_parallelogram a b c d → is_parallelogram a b c d' → d = d' := by { rw [fill_iff, fill_iff], intros h h', exact h.trans h'.symm } lemma inj_c : is_parallelogram a b c d → is_parallelogram a b c' d → c = c' := by { intros h h', rw [flip'_iff, flip_iff] at h h', exact inj_d h h' } lemma inj_b : is_parallelogram a b c d → is_parallelogram a b' c d → b = b' := by { intros h h', rw [flip'_iff] at h h', exact inj_c h h' } lemma inj_a : is_parallelogram a b c d → is_parallelogram a' b c d → a = a' := by { intros h h', rw [flip_iff] at h h', exact inj_c h h' } lemma fill_zero (a b : V) : fill a a b = b := by { symmetry, rw [← fill_iff], apply flip', apply thin} variable (V) def translations : Type* := quotient (by apply_instance : setoid (V × V)) namespace translations variable {V} variables (t u : translations V) def gap (a b : V) : translations V := quotient.mk ⟨a,b⟩ lemma gap_eq_iff : gap a b = gap c d ↔ is_parallelogram a b c d := ⟨ @quotient.exact (V × V) _ ⟨a,b⟩ ⟨c,d⟩, @quotient.sound (V × V) _ ⟨a,b⟩ ⟨c,d⟩⟩ def add' : translations V → V → V := quotient.lift (λ (ab : V × V) (x : V), fill ab.1 ab.2 x) (λ ⟨a₁,b₁⟩ ⟨a₂,b₂⟩ h, by {funext x, simp only [],rw[← fill_iff], change is_parallelogram a₁ b₁ a₂ b₂ at h, exact glue (flip h) (fill_prop a₁ b₁ x) }) theorem is_parallelogram_add' (a b : V) (t : translations V) : is_parallelogram a b (add' t a) (add' t b) := begin rcases t with ⟨⟨x,y⟩⟩, change is_parallelogram a b (fill x y a) (fill x y b), have ha : is_parallelogram x y a (fill x y a) := fill_prop x y a, have hb : is_parallelogram x y b (fill x y b) := fill_prop x y b, exact flip' (glue (flip ha) hb), end theorem gap_add' : add' (gap a b) c = fill a b c := rfl theorem gap_add'' : add' (gap a b) a = b := by { change fill a b a = b, symmetry, rw[← fill_iff], exact thin a b } theorem add'_gap (a : V) (t : translations V) : gap a (add' t a) = t := by { rcases t with ⟨⟨x,y⟩⟩, change gap a (fill x y a) = gap x y, rw [gap_eq_iff, flip_iff], apply fill_prop } def zero : translations V := gap default default lemma gap_eq_zero_iff (a b : V) : gap a b = zero ↔ a = b := begin dsimp [zero], rw [gap_eq_iff, flip_iff, fill_iff, fill_zero], split; intro h; exact h.symm end def neg : translations V → translations V := quotient.lift (λ (ab : V × V), gap ab.2 ab.1) (λ ⟨a,b⟩ ⟨c,d⟩ h, gap_eq_iff.mpr (flip' (flip (flip' h)))) theorem neg_gap : neg (gap a b) = gap b a := rfl def add : translations V → translations V → translations V := λ t, quotient.lift (λ cd : V × V, gap cd.1 (add' t cd.2)) (λ ⟨c₁,d₁⟩ ⟨c₂,d₂⟩ h, by { change is_parallelogram c₁ d₁ c₂ d₂ at h, change gap c₁ (add' t d₁) = gap c₂ (add' t d₂), rw [gap_eq_iff, flip'_iff], exact glue (flip' h) (is_parallelogram_add' d₁ d₂ t) }) theorem add_gap : add (gap a b) (gap c d) = gap c (fill a b d) := rfl theorem add_gap' : add (gap a b) (gap b c) = gap a c := by { rw [add_gap, gap_eq_iff, flip_iff, flip'_iff], exact fill_prop a b c } theorem zero_add (t : translations V) : add zero t = t := begin rcases t with ⟨a,b⟩, change _ = gap a b, change gap a (fill default default b) = gap a b, rw [gap_eq_iff, fill_zero], apply thin end theorem zero_neg (t : translations V) : add t (neg t) = zero := begin rcases t with ⟨a,b⟩, change add (gap a b) (gap b a) = zero, rw [add_gap, gap_eq_zero_iff, ← fill_iff], apply thin, end theorem add_comm (t u : translations V) : add t u = add u t := begin rcases t with ⟨a,b⟩, change add (gap a b) u = add u (gap a b), let c := add' u b, have : u = gap b c := (add'_gap b u).symm, rw [this, add_gap', add_gap, gap_eq_iff, flip'_iff, fill_symm, fill_zero, flip'_iff], apply thin end theorem add_assoc (t u v : translations V) : add (add t u) v = add t (add u v) := begin rcases t with ⟨a,b⟩, let c := add' u b, have : u = gap b c := (add'_gap b u).symm, rw [this], let d := add' v c, have : v = gap c d := (add'_gap c v).symm, rw [this], change add (add (gap a b) (gap b c)) (gap c d) = add (gap a b) (add (gap b c) (gap c d)), simp only [add_gap'], end end translations end affine_space
082a0082f016ee050f39bf9dbc5c63a119840e1d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Server/InfoUtils.lean
a9f52e24729bd313f7f01a750683cf37b2a97cfa
[ "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
16,675
lean
/- Copyright (c) 2021 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.PrettyPrinter namespace Lean.Elab /-- Elaborator information with elaborator context. It can be thought of as a "thunked" elaboration computation that allows us to retroactively extract type information, symbol locations, etc. through arbitrary invocations of `runMetaM` (where the necessary context and state can be reconstructed from `ctx` and `info.lctx`). W.r.t. widgets, this is used to tag different parts of expressions in `ppExprTagged`. This is the input to the RPC call `Lean.Widget.InteractiveDiagnostics.infoToInteractive`. It carries over information about delaborated `Info` nodes in a `CodeWithInfos`, and the associated pretty-printing functionality is purpose-specific to showing the contents of infoview popups. For use in standard LSP go-to-definition (see `Lean.Server.FileWorker.locationLinksOfInfo`), all the elaborator information we need for similar tasks is already fully recoverable via the `InfoTree` structure (see `Lean.Elab.InfoTree.visitM`). There we use this as a convienience wrapper for queried nodes (e.g. the return value of `Lean.Elab.InfoTree.hoverableInfoAt?`). It also includes the children info nodes as additional context (this is unused in the RPC case, as delaboration has no notion of child nodes). NOTE: This type is for internal use in the infoview/LSP. It should not be used in user widgets. -/ structure InfoWithCtx where ctx : Elab.ContextInfo info : Elab.Info children : PersistentArray InfoTree /-- Visit nodes, passing in a surrounding context (the innermost one) and accumulating results on the way back up. -/ partial def InfoTree.visitM [Monad m] (preNode : ContextInfo → Info → (children : PersistentArray InfoTree) → m Unit := fun _ _ _ => pure ()) (postNode : ContextInfo → Info → (children : PersistentArray InfoTree) → List (Option α) → m α) : InfoTree → m (Option α) := go none where go | _, context ctx t => go ctx t | some ctx, node i cs => do preNode ctx i cs let as ← cs.toList.mapM (go <| i.updateContext? ctx) postNode ctx i cs as | none, node .. => panic! "unexpected context-free info tree node" | _, hole .. => pure none /-- `InfoTree.visitM` specialized to `Unit` return type -/ def InfoTree.visitM' [Monad m] (preNode : ContextInfo → Info → (children : PersistentArray InfoTree) → m Unit := fun _ _ _ => pure ()) (postNode : ContextInfo → Info → (children : PersistentArray InfoTree) → m Unit := fun _ _ _ => pure ()) (t : InfoTree) : m Unit := t.visitM preNode (fun ci i cs _ => postNode ci i cs) |> discard /-- Visit nodes bottom-up, passing in a surrounding context (the innermost one) and the union of nested results (empty at leaves). -/ def InfoTree.collectNodesBottomUp (p : ContextInfo → Info → PersistentArray InfoTree → List α → List α) (i : InfoTree) : List α := i.visitM (m := Id) (postNode := fun ci i cs as => p ci i cs (as.filterMap id).join) |>.getD [] /-- For every branch of the `InfoTree`, find the deepest node in that branch for which `p` returns `some _` and return the union of all such nodes. The visitor `p` is given a node together with its innermost surrounding `ContextInfo`. -/ partial def InfoTree.deepestNodes (p : ContextInfo → Info → PersistentArray InfoTree → Option α) (infoTree : InfoTree) : List α := infoTree.collectNodesBottomUp fun ctx i cs rs => if rs.isEmpty then match p ctx i cs with | some r => [r] | none => [] else rs partial def InfoTree.foldInfo (f : ContextInfo → Info → α → α) (init : α) : InfoTree → α := go none init where go ctx? a | context ctx t => go ctx a t | node i ts => let a := match ctx? with | none => a | some ctx => f ctx i a ts.foldl (init := a) (go <| i.updateContext? ctx?) | _ => a def Info.isTerm : Info → Bool | ofTermInfo _ => true | _ => false def Info.isCompletion : Info → Bool | ofCompletionInfo .. => true | _ => false def InfoTree.getCompletionInfos (infoTree : InfoTree) : Array (ContextInfo × CompletionInfo) := infoTree.foldInfo (init := #[]) fun ctx info result => match info with | Info.ofCompletionInfo info => result.push (ctx, info) | _ => result def Info.stx : Info → Syntax | ofTacticInfo i => i.stx | ofTermInfo i => i.stx | ofCommandInfo i => i.stx | ofMacroExpansionInfo i => i.stx | ofOptionInfo i => i.stx | ofFieldInfo i => i.stx | ofCompletionInfo i => i.stx | ofCustomInfo i => i.stx | ofUserWidgetInfo i => i.stx | ofFVarAliasInfo _ => .missing | ofFieldRedeclInfo i => i.stx def Info.lctx : Info → LocalContext | Info.ofTermInfo i => i.lctx | Info.ofFieldInfo i => i.lctx | _ => LocalContext.empty def Info.pos? (i : Info) : Option String.Pos := i.stx.getPos? (canonicalOnly := true) def Info.tailPos? (i : Info) : Option String.Pos := i.stx.getTailPos? (canonicalOnly := true) def Info.range? (i : Info) : Option String.Range := i.stx.getRange? (canonicalOnly := true) def Info.contains (i : Info) (pos : String.Pos) (includeStop := false) : Bool := i.range?.any (·.contains pos includeStop) def Info.size? (i : Info) : Option String.Pos := do let pos ← i.pos? let tailPos ← i.tailPos? return tailPos - pos -- `Info` without position information are considered to have "infinite" size def Info.isSmaller (i₁ i₂ : Info) : Bool := match i₁.size?, i₂.pos? with | some sz₁, some sz₂ => sz₁ < sz₂ | some _, none => true | _, _ => false def Info.occursBefore? (i : Info) (hoverPos : String.Pos) : Option String.Pos := do let tailPos ← i.tailPos? guard (tailPos ≤ hoverPos) return hoverPos - tailPos def Info.occursInside? (i : Info) (hoverPos : String.Pos) : Option String.Pos := do let headPos ← i.pos? let tailPos ← i.tailPos? guard (headPos ≤ hoverPos && hoverPos < tailPos) return hoverPos - headPos def InfoTree.smallestInfo? (p : Info → Bool) (t : InfoTree) : Option (ContextInfo × Info) := let ts := t.deepestNodes fun ctx i _ => if p i then some (ctx, i) else none let infos := ts.map fun (ci, i) => let diff := i.tailPos?.get! - i.pos?.get! (diff, ci, i) infos.toArray.getMax? (fun a b => a.1 > b.1) |>.map fun (_, ci, i) => (ci, i) /-- Find an info node, if any, which should be shown on hover/cursor at position `hoverPos`. -/ partial def InfoTree.hoverableInfoAt? (t : InfoTree) (hoverPos : String.Pos) (includeStop := false) (omitAppFns := false) (omitIdentApps := false) : Option InfoWithCtx := Id.run do let results := t.visitM (m := Id) (postNode := fun ctx info children results => do let mut results := results.bind (·.getD []) if omitAppFns && info.stx.isOfKind ``Parser.Term.app && info.stx[0].isIdent then results := results.filter (·.2.info.stx != info.stx[0]) if omitIdentApps && info.stx.isIdent then -- if an identifier stands for an application (e.g. in the case of a typeclass projection), prefer the application if let .ofTermInfo ti := info then if ti.expr.isApp then results := results.filter (·.2.info.stx != info.stx) unless results.isEmpty do return results -- prefer innermost results /- Remark: we skip `info` nodes associated with the `nullKind` and `withAnnotateState` because they are used by tactics (e.g., `rewrite`) to control which goal is displayed in the info views. See issue #1403 -/ if info.stx.isOfKind nullKind || info.toElabInfo?.any (·.elaborator == `Lean.Elab.Tactic.evalWithAnnotateState) then return results unless (info matches .ofFieldInfo _ | .ofOptionInfo _ || info.toElabInfo?.isSome) && info.contains hoverPos includeStop do return results let r := info.range?.get! let priority := ( -- prefer results directly *after* the hover position (only matters for `includeStop = true`; see #767) if r.stop == hoverPos then 0 else 1, -- relying on the info tree structure is _not_ sufficient for choosing the smallest surrounding node: -- `⟨x⟩` expands to an application of a canonical syntax with the span of the anonymous constructor to `x`, -- i.e. there are two info tree siblings whose spans are not disjoint and we should choose the smaller node -- surrounding the cursor Int.negOfNat (r.stop - r.start).byteIdx, -- prefer results for constants over variables (which overlap at declaration names) if info matches .ofTermInfo { expr := .fvar .., .. } then 0 else 1) [(priority, {ctx, info, children})]) |>.getD [] -- sort results by lexicographical priority let maxPrio? := let _ := @lexOrd let _ := @leOfOrd.{0} let _ := @maxOfLe results.map (·.1) |>.maximum? let res? := results.find? (·.1 == maxPrio?) |>.map (·.2) if let some i := res? then if let .ofTermInfo ti := i.info then if ti.expr.isSyntheticSorry then return none return res? def Info.type? (i : Info) : MetaM (Option Expr) := match i with | Info.ofTermInfo ti => Meta.inferType ti.expr | Info.ofFieldInfo fi => Meta.inferType fi.val | _ => return none def Info.docString? (i : Info) : MetaM (Option String) := do let env ← getEnv match i with | Info.ofTermInfo ti => if let some n := ti.expr.constName? then return ← findDocString? env n | .ofFieldInfo fi => return ← findDocString? env fi.projName | .ofOptionInfo oi => if let some doc ← findDocString? env oi.declName then return doc if let some decl := (← getOptionDecls).find? oi.optionName then return decl.descr return none | _ => pure () if let some ei := i.toElabInfo? then return ← findDocString? env ei.stx.getKind <||> findDocString? env ei.elaborator return none /-- Construct a hover popup, if any, from an info node in a context.-/ def Info.fmtHover? (ci : ContextInfo) (i : Info) : IO (Option FormatWithInfos) := do ci.runMetaM i.lctx do let mut fmts := #[] let mut infos := ∅ let modFmt ← try let (termFmt, modFmt) ← fmtTermAndModule? if let some f := termFmt then fmts := fmts.push f.fmt infos := f.infos pure modFmt catch _ => pure none if let some m ← i.docString? then fmts := fmts.push m if let some f := modFmt then fmts := fmts.push f if fmts.isEmpty then return none else return some ⟨f!"\n***\n".joinSep fmts.toList, infos⟩ where fmtModule? (decl : Name) : MetaM (Option Format) := do let some mod ← findModuleOf? decl | return none return some f!"*import {mod}*" fmtTermAndModule? : MetaM (Option FormatWithInfos × Option Format) := do match i with | Info.ofTermInfo ti => let e ← instantiateMVars ti.expr if e.isSort then -- Types of sorts are funny to look at in widgets, but ultimately not very helpful return (none, none) let tp ← instantiateMVars (← Meta.inferType e) let tpFmt ← Meta.ppExpr tp if let .const c _ := e then let eFmt ← PrettyPrinter.ppSignature c return (some { eFmt with fmt := f!"```lean\n{eFmt.fmt}\n```" }, ← fmtModule? c) let eFmt ← Meta.ppExpr e -- Try not to show too scary internals let showTerm := if let .fvar _ := e then if let some ldecl := (← getLCtx).findFVar? e then !ldecl.userName.hasMacroScopes else false else isAtomicFormat eFmt let fmt := if showTerm then f!"{eFmt} : {tpFmt}" else tpFmt return (some f!"```lean\n{fmt}\n```", none) | Info.ofFieldInfo fi => let tp ← Meta.inferType fi.val let tpFmt ← Meta.ppExpr tp return (some f!"```lean\n{fi.fieldName} : {tpFmt}\n```", none) | _ => return (none, none) isAtomicFormat : Format → Bool | Std.Format.text _ => true | Std.Format.group f _ => isAtomicFormat f | Std.Format.nest _ f => isAtomicFormat f | Std.Format.tag _ f => isAtomicFormat f | _ => false structure GoalsAtResult where ctxInfo : ContextInfo tacticInfo : TacticInfo useAfter : Bool /-- Whether the tactic info is further indented than the hover position. -/ indented : Bool -- for overlapping goals, only keep those of the highest reported priority priority : Nat /-- Try to retrieve `TacticInfo` for `hoverPos`. We retrieve all `TacticInfo` nodes s.t. `hoverPos` is inside the node's range plus trailing whitespace. We usually prefer the innermost such nodes so that for composite tactics such as `induction`, we show the nested proofs' states. However, if `hoverPos` is after the tactic, we prefer nodes that are not indented relative to it, meaning that e.g. at `|` in ```lean have := by exact foo | ``` we show the (final, see below) state of `have`, not `exact`. Moreover, we instruct the LSP server to use the state after tactic execution if - the hover position is after the info's start position *and* - there is no nested tactic info after the hover position (tactic combinators should decide for themselves where to show intermediate states by calling `withTacticInfoContext`) -/ partial def InfoTree.goalsAt? (text : FileMap) (t : InfoTree) (hoverPos : String.Pos) : List GoalsAtResult := let gs := t.collectNodesBottomUp fun ctx i cs gs => Id.run do if let Info.ofTacticInfo ti := i then if let (some pos, some tailPos) := (i.pos?, i.tailPos?) then let trailSize := i.stx.getTrailingSize -- show info at EOF even if strictly outside token + trail let atEOF := tailPos.byteIdx + trailSize == text.source.endPos.byteIdx -- include at least one trailing character (see also `priority` below) if pos ≤ hoverPos ∧ (hoverPos.byteIdx < tailPos.byteIdx + max 1 trailSize || atEOF) then -- overwrite bottom-up results according to "innermost" heuristics documented above if gs.isEmpty || hoverPos ≥ tailPos && gs.all (·.indented) then return [{ ctxInfo := ctx tacticInfo := ti useAfter := hoverPos > pos && !cs.any (hasNestedTactic pos tailPos) -- consider every position unindented after an empty `by` to support "hanging" `by` uses indented := (text.toPosition pos).column > (text.toPosition hoverPos).column && !isEmptyBy ti.stx -- use goals just before cursor as fall-back only -- thus for `(by foo)`, placing the cursor after `foo` shows its state as long -- as there is no state on `)` priority := if hoverPos.byteIdx == tailPos.byteIdx + trailSize then 0 else 1 }] return gs let maxPrio? := gs.map (·.priority) |>.maximum? gs.filter (some ·.priority == maxPrio?) where hasNestedTactic (pos tailPos) : InfoTree → Bool | InfoTree.node i@(Info.ofTacticInfo _) cs => Id.run do if let `(by $_) := i.stx then return false -- ignore term-nested proofs such as in `simp [show p by ...]` if let (some pos', some tailPos') := (i.pos?, i.tailPos?) then -- ignore preceding nested infos -- ignore nested infos of the same tactic, e.g. from expansion if tailPos' > hoverPos && (pos', tailPos') != (pos, tailPos) then return true cs.any (hasNestedTactic pos tailPos) | InfoTree.node (Info.ofMacroExpansionInfo _) cs => cs.any (hasNestedTactic pos tailPos) | _ => false isEmptyBy (stx : Syntax) : Bool := -- there are multiple `by` kinds with the same structure stx.getNumArgs == 2 && stx[0].isToken "by" && stx[1].getNumArgs == 1 && stx[1][0].isMissing partial def InfoTree.termGoalAt? (t : InfoTree) (hoverPos : String.Pos) : Option InfoWithCtx := -- In the case `f a b`, where `f` is an identifier, the term goal at `f` should be the goal for the full application `f a b`. hoverableInfoAt? t hoverPos (includeStop := true) (omitAppFns := true) partial def InfoTree.hasSorry : InfoTree → IO Bool := go none where go ci? | .context ci t => go ci t | .node i cs => if let (some ci, .ofTermInfo ti) := (ci?, i) then do let expr ← ti.runMetaM ci (instantiateMVars ti.expr) return expr.hasSorry -- we assume that `cs` are subterms of `ti.expr` and -- thus do not have to be checked as well else cs.anyM (go ci?) | _ => return false end Lean.Elab
245081f4438f684745d7440ac6fe7af09483e6aa
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/e6.lean
88346a7c0dcc356f8e8468b95e82f02bb2f79876
[ "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
624
lean
prelude precedence `+`:65 namespace nat constant nat : Type.{1} constant add : nat → nat → nat infixl + := add end nat namespace int open nat (nat) constant int : Type.{1} constant add : int → int → int infixl + := add constant of_nat : nat → int attribute of_nat [coercion] end int open int open nat constants n m : nat constants i j : int check n + m check i + j check i + n check i + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n + n
49d19eecb1c0c37e1c3ebdcd46d28b1cc1c8be73
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Tactic/Intro.lean
2ce21e13ff7eb855ec4a1c62f51a674e52ea0721
[ "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
8,285
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Util namespace Lean.Meta @[inline] private partial def introNImp {σ} (mvarId : MVarId) (n : Nat) (mkName : LocalContext → Name → Bool → σ → MetaM (Name × σ)) (s : σ) : MetaM (Array FVarId × MVarId) := mvarId.withContext do mvarId.checkNotAssigned `introN let mvarType ← mvarId.getType let lctx ← getLCtx let rec @[specialize] loop (i : Nat) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (s : σ) (type : Expr) : MetaM (Array Expr × MVarId) := do match i, type with | 0, type => let type := type.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstances fvars j do let tag ← mvarId.getTag let type := type.headBeta let newMVar ← mkFreshExprSyntheticOpaqueMVar type tag let newVal ← mkLambdaFVars fvars newMVar mvarId.assign newVal return (fvars, newMVar.mvarId!) | i+1, .letE n type val body _ => let type := type.instantiateRevRange j fvars.size fvars let type := type.headBeta let val := val.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let (n, s) ← mkName lctx n true s let lctx := lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId let fvars := fvars.push fvar loop i lctx fvars j s body | i+1, .forallE n type body c => let type := type.instantiateRevRange j fvars.size fvars let type := type.headBeta let fvarId ← mkFreshFVarId let (n, s) ← mkName lctx n c.isExplicit s let lctx := lctx.mkLocalDecl fvarId n type c let fvar := mkFVar fvarId let fvars := fvars.push fvar loop i lctx fvars j s body | i+1, type => let type := type.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstances fvars j do /- We used to use just `whnf`, but it produces counterintuitive behavior if - `type` is a metavariable `?m` such that `?m := let x := v; b`, or - `type` has `MData` or annotations such as `optParam` around a `let`-expression. `whnf` instantiates metavariables, and consumes `MData`, but it also expands the `let`. -/ let newType := (← instantiateMVars type).cleanupAnnotations if newType.isForall || newType.isLet then loop (i+1) lctx fvars fvars.size s newType else let newType ← whnf newType if newType.isForall then loop (i+1) lctx fvars fvars.size s newType else throwTacticEx `introN mvarId "insufficient number of binders" let (fvars, mvarId) ← loop n lctx #[] 0 s mvarType return (fvars.map Expr.fvarId!, mvarId) register_builtin_option tactic.hygienic : Bool := { defValue := true group := "tactic" descr := "make sure tactics are hygienic" } private def mkFreshBinderNameForTacticCore (lctx : LocalContext) (binderName : Name) (hygienic := true) : MetaM Name := do if hygienic then mkFreshUserName binderName else return lctx.getUnusedName binderName /-- Similar to `mkFreshUserName`, but takes into account `tactic.hygienic` option value. If `tactic.hygienic = true`, then the current macro scopes are applied to `binderName`. If not, then an unused (accessible) name (based on `binderName`) in the local context is used. -/ def mkFreshBinderNameForTactic (binderName : Name) : MetaM Name := do mkFreshBinderNameForTacticCore (← getLCtx) binderName (tactic.hygienic.get (← getOptions)) private def mkAuxNameImp (preserveBinderNames : Bool) (hygienic : Bool) (useNamesForExplicitOnly : Bool) (lctx : LocalContext) (binderName : Name) (isExplicit : Bool) : List Name → MetaM (Name × List Name) | [] => mkAuxNameWithoutGivenName [] | n :: rest => do if useNamesForExplicitOnly && !isExplicit then mkAuxNameWithoutGivenName (n :: rest) else if n != Name.mkSimple "_" then return (n, rest) else mkAuxNameWithoutGivenName rest where mkAuxNameWithoutGivenName (rest : List Name) : MetaM (Name × List Name) := do if preserveBinderNames then return (binderName, rest) else let binderName ← mkFreshBinderNameForTacticCore lctx binderName hygienic return (binderName, rest) def introNCore (mvarId : MVarId) (n : Nat) (givenNames : List Name) (useNamesForExplicitOnly : Bool) (preserveBinderNames : Bool) : MetaM (Array FVarId × MVarId) := do let hygienic := tactic.hygienic.get (← getOptions) if n == 0 then return (#[], mvarId) else introNImp mvarId n (mkAuxNameImp preserveBinderNames hygienic useNamesForExplicitOnly) givenNames /-- Introduce `n` binders in the goal `mvarId`. -/ abbrev _root_.Lean.MVarId.introN (mvarId : MVarId) (n : Nat) (givenNames : List Name := []) (useNamesForExplicitOnly := false) : MetaM (Array FVarId × MVarId) := introNCore mvarId n givenNames (useNamesForExplicitOnly := useNamesForExplicitOnly) (preserveBinderNames := false) @[deprecated MVarId.introN] abbrev introN (mvarId : MVarId) (n : Nat) (givenNames : List Name := []) (useNamesForExplicitOnly := false) : MetaM (Array FVarId × MVarId) := mvarId.introN n givenNames useNamesForExplicitOnly /-- Introduce `n` binders in the goal `mvarId`. The new hypotheses are named using the binder names. The suffix `P` stands for "preserving`. -/ abbrev _root_.Lean.MVarId.introNP (mvarId : MVarId) (n : Nat) : MetaM (Array FVarId × MVarId) := introNCore mvarId n [] (useNamesForExplicitOnly := false) (preserveBinderNames := true) @[deprecated MVarId.introNP] abbrev introNP (mvarId : MVarId) (n : Nat) : MetaM (Array FVarId × MVarId) := mvarId.introNP n /-- Introduce one binder using `name` as the the new hypothesis name. -/ def _root_.Lean.MVarId.intro (mvarId : MVarId) (name : Name) : MetaM (FVarId × MVarId) := do let (fvarIds, mvarId) ← mvarId.introN 1 [name] return (fvarIds[0]!, mvarId) @[deprecated MVarId.intro] def intro (mvarId : MVarId) (name : Name) : MetaM (FVarId × MVarId) := do mvarId.intro name def intro1Core (mvarId : MVarId) (preserveBinderNames : Bool) : MetaM (FVarId × MVarId) := do let (fvarIds, mvarId) ← introNCore mvarId 1 [] (useNamesForExplicitOnly := false) preserveBinderNames return (fvarIds[0]!, mvarId) /-- Introduce one object from the goal `mvarid`, without preserving the name used in the binder. Returns a pair made of the newly introduced variable (which will have an inaccessible name) and the new goal. This will fail if there is nothing to introduce, ie when the goal does not start with a forall, lambda or let. -/ abbrev _root_.Lean.MVarId.intro1 (mvarId : MVarId) : MetaM (FVarId × MVarId) := intro1Core mvarId false @[deprecated MVarId.intro1] abbrev intro1 (mvarId : MVarId) : MetaM (FVarId × MVarId) := mvarId.intro1 /-- Introduce one object from the goal `mvarid`, preserving the name used in the binder. Returns a pair made of the newly introduced variable and the new goal. This will fail if there is nothing to introduce, ie when the goal does not start with a forall, lambda or let. -/ abbrev _root_.Lean.MVarId.intro1P (mvarId : MVarId) : MetaM (FVarId × MVarId) := intro1Core mvarId true @[deprecated MVarId.intro1P] abbrev intro1P (mvarId : MVarId) : MetaM (FVarId × MVarId) := mvarId.intro1P private def getIntrosSize : Expr → Nat | .forallE _ _ b _ => getIntrosSize b + 1 | .letE _ _ _ b _ => getIntrosSize b + 1 | .mdata _ b => getIntrosSize b | _ => 0 /-- Introduce as many binders as possible without unfolding definitions. -/ def _root_.Lean.MVarId.intros (mvarId : MVarId) : MetaM (Array FVarId × MVarId) := do let type ← mvarId.getType let type ← instantiateMVars type let n := getIntrosSize type if n == 0 then return (#[], mvarId) else mvarId.introN n @[deprecated MVarId.intros] def intros (mvarId : MVarId) : MetaM (Array FVarId × MVarId) := do mvarId.intros end Lean.Meta
c99a94f87fbeb0bc4a7a2319f0f660b13c6407ba
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/char_p.lean
2d71836a54783dd2a10de499abd32333a4123e46
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
10,848
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau, Joey van Langen, Casper Putz -/ import data.fintype.basic import data.nat.choose import data.int.modeq import algebra.module import algebra.iterate_hom /-! # Characteristic of semirings -/ universes u v /-- The generator of the kernel of the unique homomorphism ℕ → α for a semiring α -/ class char_p (α : Type u) [semiring α] (p : ℕ) : Prop := (cast_eq_zero_iff [] : ∀ x:ℕ, (x:α) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero (α : Type u) [semiring α] (p : ℕ) [char_p α p] : (p:α) = 0 := (char_p.cast_eq_zero_iff α p p).2 (dvd_refl p) lemma char_p.int_cast_eq_zero_iff (R : Type u) [ring R] (p : ℕ) [char_p R p] (a : ℤ) : (a : R) = 0 ↔ (p:ℤ) ∣ a := begin rcases lt_trichotomy a 0 with h|rfl|h, { rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg], lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }, { simp only [int.cast_zero, eq_self_iff_true, dvd_zero] }, { lift a to ℕ using (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] } end lemma char_p.int_coe_eq_int_coe_iff (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = (b : R) ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] theorem char_p.eq (α : Type u) [semiring α] {p q : ℕ} (c1 : char_p α p) (c2 : char_p α q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff α p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff α q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero (α : Type u) [semiring α] [char_zero α] : char_p α 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists (α : Type u) [semiring α] : ∃ p, char_p α p := by letI := classical.dec_eq α; exact classical.by_cases (assume H : ∀ p:ℕ, (p:α) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (classical.not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (classical.not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (classical.not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (classical.not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique (α : Type u) [semiring α] : ∃! p, char_p α p := let ⟨c, H⟩ := char_p.exists α in ⟨c, H, λ y H2, char_p.eq α H2 H⟩ /-- Noncomuptable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char (α : Type u) [semiring α] : ℕ := classical.some (char_p.exists_unique α) theorem ring_char.spec (α : Type u) [semiring α] : ∀ x:ℕ, (x:α) = 0 ↔ ring_char α ∣ x := by letI := (classical.some_spec (char_p.exists_unique α)).1; unfold ring_char; exact char_p.cast_eq_zero_iff α (ring_char α) theorem ring_char.eq (α : Type u) [semiring α] {p : ℕ} (C : char_p α p) : p = ring_char α := (classical.some_spec (char_p.exists_unique α)).2 p C theorem add_pow_char_of_commute (R : Type u) [ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y): (x + y)^p = x^p + y^p := begin rw [commute.add_pow h, finset.sum_range_succ, nat.sub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one, add_right_inj], convert finset.sum_eq_single 0 _ _, { simp }, swap, { intro h1, contrapose! h1, rw finset.mem_range, apply nat.prime.pos, assumption }, intros b h1 h2, suffices : (p.choose b : R) = 0, { rw this, simp }, rw char_p.cast_eq_zero_iff R p, apply nat.prime.dvd_choose_self, assumption', { omega }, rwa ← finset.mem_range end theorem add_pow_char (α : Type u) [comm_ring α] {p : ℕ} (hp : nat.prime p) [char_p α p] (x y : α) : (x + y)^p = x^p + y^p := begin haveI : fact p.prime := hp, apply add_pow_char_of_commute, apply commute.all, end lemma eq_iff_modeq_int (R : Type*) [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = b ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq.modeq_iff_dvd] lemma char_p.neg_one_ne_one (R : Type*) [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] : (-1 : R) ≠ (1 : R) := begin suffices : (2 : R) ≠ 0, { symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this }, assume h, rw [show (2 : R) = (2 : ℕ), by norm_cast] at h, have := (char_p.cast_eq_zero_iff R p 2).mp h, have := nat.le_of_dvd dec_trivial this, rw fact at *, linarith, end section frobenius variables (R : Type u) [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) /-- The frobenius map that sends x to x^p -/ def frobenius : R →+* R := { to_fun := λ x, x^p, map_one' := one_pow p, map_mul' := λ x y, mul_pow x y p, map_zero' := zero_pow (lt_trans zero_lt_one ‹nat.prime p›.one_lt), map_add' := add_pow_char R ‹nat.prime p› } variable {R} theorem frobenius_def : frobenius R p x = x ^ p := rfl theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y := (frobenius R p).map_mul x y theorem frobenius_one : frobenius R p 1 = 1 := one_pow _ variable {R} theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) := f.map_pow x p theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) := g.map_pow x p theorem monoid_hom.map_iterate_frobenius (n : ℕ) : f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) := function.semiconj.iterate_right (f.map_frobenius p) n x theorem ring_hom.map_iterate_frobenius (n : ℕ) : g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) := g.to_monoid_hom.map_iterate_frobenius p x n theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ variable (R) theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y := (frobenius R p).map_add x y theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y := (frobenius R p).map_sub x y theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n end frobenius theorem frobenius_inj (α : Type u) [integral_domain α] (p : ℕ) [fact p.prime] [char_p α p] : function.injective (frobenius α p) := λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H } namespace char_p section variables (α : Type u) [ring α] lemma char_p_to_char_zero [char_p α 0] : char_zero α := add_group.char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff α 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p α p] (k : ℕ) : (k : α) = (k % p : ℕ) := calc (k : α) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p α p] [fintype α] : p ≠ 0 := assume h : p = 0, have char_zero α := @char_p_to_char_zero α _ (h ▸ hc), absurd (@nat.cast_injective α _ _ this) (not_injective_infinite_fintype coe) end section integral_domain open nat variables (α : Type u) [integral_domain α] theorem char_ne_one (p : ℕ) [hc : char_p α p] : p ≠ 1 := assume hp : p = 1, have ( 1 : α) = 0, by simpa using (cast_eq_zero_iff α p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero theorem char_is_prime_of_ge_two (p : ℕ) [hc : char_p α p] (hp : p ≥ 2) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : α) = 0, from (cast_eq_zero_iff α p p).mpr (dvd_refl p), have (d : α) * e = 0, from (@cast_mul α _ d e) ▸ (hmul ▸ this), or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume hd : (d : α) = 0, have p ∣ d, from (cast_eq_zero_iff α p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : α) = 0, have p ∣ e, from (cast_eq_zero_iff α p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) theorem char_is_prime_or_zero (p : ℕ) [hc : char_p α p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one α _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_ge_two α _ (m+2) hc (nat.le_add_left 2 m)) end lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p α p] : fact p.prime := (char_p.char_is_prime_or_zero α _).resolve_right (nat.pos_iff_ne_zero.1 h) theorem char_is_prime [fintype α] (p : ℕ) [char_p α p] : p.prime := or.resolve_right (char_is_prime_or_zero α p) (char_ne_zero_of_fintype α p) end integral_domain section char_one variables {R : Type*} section prio set_option default_priority 100 -- see Note [default priority] instance [semiring R] [char_p R 1] : subsingleton R := subsingleton.intro $ suffices ∀ (r : R), r = 0, from assume a b, show a = b, by rw [this a, this b], assume r, calc r = 1 * r : by rw one_mul ... = (1 : ℕ) * r : by rw nat.cast_one ... = 0 * r : by rw char_p.cast_eq_zero ... = 0 : by rw zero_mul end prio lemma false_of_nonzero_of_char_one [semiring R] [nontrivial R] [char_p R 1] : false := zero_ne_one $ show (0:R) = 1, from subsingleton.elim 0 1 lemma ring_char_ne_one [semiring R] [nontrivial R] : ring_char R ≠ 1 := by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], } end char_one end char_p
1b15865aca4cc70d668722770bbb43202aeef184
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1907.lean
f5518c54fc47a63c77a21771d882249abc5ffabf
[ "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
2,232
lean
class One (α : Type u) where one : α instance One.toOfNat1 {α} [One α] : OfNat α (nat_lit 1) where ofNat := ‹One α›.1 class MulOneClass (M : Type u) extends One M, Mul M class FunLike (F : Sort _) (α : outParam (Sort _)) (β : outParam <| α → Sort _) where coe : F → ∀ a : α, β a instance (priority := 100) [FunLike F α β] : CoeFun F fun _ => ∀ a : α, β a where coe := FunLike.coe section One variable [One M] [One N] structure OneHom (M : Type _) (N : Type _) [One M] [One N] where toFun : M → N map_one' : toFun 1 = 1 class OneHomClass (F : Type _) (M N : outParam (Type _)) [One M] [One N] extends FunLike F M fun _ => N where map_one : ∀ f : F, f 1 = 1 @[simp] theorem map_one [OneHomClass F M N] (f : F) : f 1 = 1 := OneHomClass.map_one f end One section Mul variable [Mul M] [Mul N] structure MulHom (M : Type _) (N : Type _) [Mul M] [Mul N] where toFun : M → N map_mul' : ∀ x y, toFun (x * y) = toFun x * toFun y infixr:25 " →ₙ* " => MulHom class MulHomClass (F : Type _) (M N : outParam (Type _)) [Mul M] [Mul N] extends FunLike F M fun _ => N where map_mul : ∀ (f : F) (x y : M), f (x * y) = f x * f y @[simp] theorem map_mul [MulHomClass F M N] (f : F) (x y : M) : f (x * y) = f x * f y := MulHomClass.map_mul f x y end Mul section mul_one variable [MulOneClass M] [MulOneClass N] structure MonoidHom (M : Type _) (N : Type _) [MulOneClass M] [MulOneClass N] extends OneHom M N, M →ₙ* N infixr:25 " →* " => MonoidHom class MonoidHomClass (F : Type _) (M N : outParam (Type _)) [MulOneClass M] [MulOneClass N] extends MulHomClass F M N, OneHomClass F M N instance (F : Type _) (M N : outParam (Type _)) [MulOneClass M] [MulOneClass N] [MonoidHomClass F M N] : CoeTC F (M →* N) := ⟨fun f => { toFun := f, map_one' := map_one f, map_mul' := map_mul f }⟩ -- Now we reverse the order of the parents in the extends clause: class MonoidHomClass' (F : Type _) (M N : outParam (Type _)) [MulOneClass M] [MulOneClass N] extends OneHomClass F M N, MulHomClass F M N instance [MonoidHomClass' F M N] : CoeTC F (M →* N) := ⟨fun f => { toFun := f, map_one' := map_one f, map_mul' := map_mul f }⟩
2f971d6778bb356e3905e468530ee26b56624dad
9d11251b9f3420c543cb6bda174321e389baadaf
/system_f_sub.lean
bd51db55b0ef1ac43bd2984ab2ab5df7dc87770e
[]
no_license
Kha/system_f_sub
2d2dce8aa1a1f497458c7287873f9e8e7acef44c
66b726d47b279de535e6ec9bdc57dd2445ebf750
refs/heads/master
1,625,203,792,419
1,506,084,775,000
1,506,084,775,000
103,531,071
0
0
null
null
null
null
UTF-8
Lean
false
false
28,051
lean
import data.list.basic /- Prelude -/ attribute [simp] nat.succ_le_succ nat.zero_le attribute [reducible] id lemma {u v} if_distrib {c : Prop} {h : decidable c} {α : Sort u} {t e : α} {β : Sort v} (f : α → β) : f (ite c t e) = ite c (f t) (f e) := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma nat.succ_lt_succ_iff (n m : ℕ) : n.succ < m.succ ↔ n < m := ⟨nat.lt_of_succ_lt_succ, nat.succ_lt_succ⟩ theorem nat.sub_lt_sub_right : Π {n m k : ℕ} (h₁ : n < m) (h₂ : k ≤ n), n - k < m - k | n m 0 h₁ h₂ := h₁ | (n+1) (m+1) (k+1) h₁ h₂ := by simp; apply nat.sub_lt_sub_right (nat.lt_of_succ_lt_succ h₁) (nat.le_of_succ_le_succ h₂) theorem nat.le_sub_one_of_lt {a b : ℕ} (h : a < b) : a ≤ b - 1 := begin cases b, { simp [nat.not_lt_zero] at h; contradiction }, { simp [nat.le_of_succ_le_succ h] } end namespace list universe u variables {α β : Type u} @[simp] lemma nth_map (xs : list α) (f : α → β) (i : ℕ) : (xs.map f).nth i = f <$> xs.nth i := begin induction xs generalizing i, { refl }, { cases i, { refl }, apply ih_1 } end @[simp] lemma nth_drop (xs : list α) (i k : ℕ) : (xs.drop k).nth i = xs.nth (i + k) := begin induction xs generalizing k i, { cases k; refl }, { cases k, { refl }, simp [nat.add_succ], apply ih_1 } end lemma nth_take (xs : list α) (i k : ℕ) : (xs.take k).nth i = if i < k then xs.nth i else none := begin induction xs generalizing k i, { simp [list.nth] }, { cases k, { refl }, cases i, { refl }, simp [list.take, ih_1, nat.succ_lt_succ_iff], apply if_congr; refl } end lemma nth_append (xs ys : list α) (i : ℕ) : (xs ++ ys).nth i = if i < length xs then xs.nth i else ys.nth (i - length xs) := begin induction xs generalizing i, case list.nil { refl }, case list.cons x xs { cases i with i, { refl }, { simp [ih_1, nat.one_add, nat.succ_lt_succ_iff], apply if_congr; refl } } end end list namespace system_f_sub /- Recursive types in F<: -/ inductive type | var (idx : ℕ) | top | «fun» (domain body : type) | abs (bound body : type) | mu (rec : type) open type infixr ` →ₛ `:55 := type.fun notation `∀0<: ` t `, ` s := abs t s /- Parallel substitution -/ def rename := ℕ → ℕ def rename.up (ξ : rename) : rename | 0 := 0 | (k+1) := ξ k + 1 @[simp] def type.rename : rename → type → type | ξ (var x) := var (ξ x) | ξ top := top | ξ (a →ₛ b) := a.rename ξ →ₛ b.rename ξ | ξ (∀0<:a, b) := ∀0<:a.rename ξ, b.rename ξ.up | ξ (mu a) := mu (a.rename ξ.up) def subst := ℕ → type def subst.up (σ : subst) : subst | 0 := var 0 | (k+1) := (σ k).rename (+1) @[simp] def type.subst : subst → type → type | σ (var x) := σ x | σ top := top | σ (a →ₛ b) := a.subst σ →ₛ b.subst σ | σ (∀0<:a, b) := ∀0<:a.subst σ, b.subst σ.up | σ (mu a) := mu (a.subst σ.up) def subst.comp (σ' σ : subst) : subst := type.subst σ' ∘ σ infix ` ∘ₛ `:90 := subst.comp def lift_idx (k : ℕ) (d := 0) : rename := λ i, if i ≥ d then i + k else i def type.lift (a : type) (k : ℕ) (d := 0) : type := a.rename (lift_idx k d) def instantiate_idx (r : type) (d := 0) : subst := λ i, if d < i then var (i-1) else if i = d then r.lift d else var i def type.instantiate (a b : type) (d := 0) : type := a.subst (instantiate_idx b d) def type.expand (a : type) : type := a.instantiate (mu a) def type.free_range : type → ℕ | (var d) := d + 1 | top := 0 | (a →ₛ b) := max a.free_range b.free_range | (∀0<: a, b) := max a.free_range (b.free_range - 1) | (mu a) := a.free_range - 1 def type.closed (t : type) := t.free_range = 0 /- The subtyping relation -/ @[reducible] def env := list type def env.lift : env → ℕ → opt_param ℕ 0 → env | [] k d := [] | (a::e) k d := a.lift k (d + e.length) :: env.lift e k d inductive sub : env → type → type → Prop notation e ` ⊢ `:40 a ` <: `:40 b:40 := sub e a b | var_refl (e x) : e ⊢ var x <: var x | env {e x a b} : list.nth e x = some a → e ⊢ a.lift (x+1) <: b → e ⊢ var x <: b | top (e a) : e ⊢ a <: top | «fun» {e a a' b b'} : e ⊢ a' <: a → e ⊢ b <: b' → e ⊢ a →ₛ b <: a' →ₛ b' | abs {e a a' b b'} : e ⊢ a' <: a → a'::e ⊢ b <: b' → e ⊢ ∀0<:a, b <: ∀0<:a', b' -- violates the positivity restriction --| mu {e a a'} : (∀ b b', e ⊢ b <: b' → e ⊢ type.instantiate a b <: type.instantiate a' b') → e ⊢ mu a <: mu a' | mu_refl (e a) : e ⊢ mu a <: mu a | expₗ {e a a'} : e ⊢ type.expand a <: a' → e ⊢ mu a <: a' | expᵣ {e a a'} : e ⊢ a <: type.expand a' → e ⊢ a <: mu a' notation e ` ⊢ `:40 a:41 ` <: `:40 b:40 := sub e a b notation a ` <: `:40 b:40 := sub [] a b lemma sub.refl : Π e a, e ⊢ a <: a | e (var x) := sub.var_refl e x | e top := sub.top e top | e (a →ₛ b) := sub.fun (sub.refl e a) (sub.refl e b) | e (∀0<:a, b) := sub.abs (sub.refl e a) (sub.refl _ b) | e (mu a) := sub.mu_refl e a /- A macro for translating Lean types into F<: types -/ section open lean open lean.parser open interactive open interactive.types open expr (app pi const lam) reserve notation `⟦ₛ`:1000 def mu_helper := 0 notation `μ ` binder `, ` a:scoped := mu_helper a def ctx_helper := 0 notation `bctx ` binder <: a:50 `⊢` b:scoped := ctx_helper a b private meta def parse_type : ℕ → ℕ → pexpr → parser pexpr | d d' (expr.var n) := let n := n - d' in pure ``(var %%(reflect n)) | d d' (const n ls) := pure $ const n ls | d d' (app (const ``mu_helper _) (lam _ _ _ a)) := do a ← parse_type (d+1) d' a, pure ``(mu %%a) | d d' (expr.local_const n m bi t) := pure $ ``(type.lift %%(expr.local_const n m bi t) %%(reflect d)) -- ``(∀ x <: %%a, %%b) | d d' (pi _ _ _ (pi _ _ (app (app (app (const `system_f_sub.sub []) _) (expr.var 0)) a) b)) := do a ← parse_type (d+1) (d'+1) a, b ← parse_type (d+1) (d'+1) b, pure ``(∀0<:%%a, %%b) | d d' (expr.pi _ _ dom b) := if (@unchecked_cast _ expr b).has_var_idx 0 then do b ← parse_type (d+1) d' b, pure ``(∀0<:top, %%b) else do dom ← parse_type d d' dom, b ← parse_type d (d'+1) b, pure ``(%%dom →ₛ %%b) | d d' e := match e.get_structure_instance_info with | some info := do fields ← (info.field_names.zip info.field_values).mmap (λ ⟨n, v⟩, do v ← parse_type d d' v, pure ``(⟨%%(const (`system_f_sub.labels ++ n) [] : pexpr), %%v⟩)), pure (app (const `system_f_sub.record []) (fields.foldr (λ e f, ``(%%e::%%f)) ``([]))) | _ := tactic.fail format!"unsupported sub-expression {e.to_raw_fmt}" end private meta def parse_ctx : list pexpr → pexpr → parser pexpr | ctx (app (app (const ``ctx_helper _) a) (lam _ _ _ b)) := do a ← parse_type ctx.length 0 a, let ctx := a::ctx, parse_ctx ctx b | ctx (app (app (app (const ``sub _) _) a) b) := do a ← parse_type ctx.length 0 a, b ← parse_type ctx.length 0 b, pure ``(sub %%(ctx.foldl (λ ctx a, ``(%%a :: %%ctx)) ``([])) %%a %%b) | _ e := parse_type 0 0 e private meta def erase_all_annotations : expr → expr := λ e, expr.replace e (λ e _, match e.is_annotation with | some (_, e') := some (erase_all_annotations e') | _ := none end) @[user_notation] meta def interpret_notation (_ : parse $ tk "⟦ₛ") (e : parse $ parser.pexpr <* tk "⟧") : parser pexpr := let e := erase_all_annotations (unchecked_cast e) in parse_ctx [] (unchecked_cast e) end /- Basic types -/ -- def Bool := ∀0<:top, var 0 →ₛ var 0 →ₛ var 0 def Bool := ⟦ₛ ∀ a, a → a → a ⟧ def True := ⟦ₛ ∀ a, a → top → a ⟧ def False := ⟦ₛ ∀ a, top → a → a ⟧ def None := ⟦ₛ ∀ a, top → top → a ⟧ example : None <: True := by repeat {constructor} example : None <: False := by repeat {constructor} example : True <: Bool := by repeat {constructor} example : False <: Bool := by repeat {constructor} def prod (a b : type) := ⟦ₛ ∀ r, (a → b → r) → r ⟧ infix ` ×ₛ `:45 := prod def tuple : list type → type | [] := top | (a::as) := a ×ₛ tuple as structure field := (idx : ℕ) (type : type) def record_list (fields : list field) : list type := let max_idx := (fields.map field.idx).foldr max 0 in (list.range (max_idx+1)).map (λ i, (field.type <$> fields.find (λ f, f.idx = i)).get_or_else top) def record (fields : list field) : type := tuple (record_list fields ++ [top]) /- Finally, some proofs -/ lemma rename_up_id : rename.up id = id := begin apply funext, intro i, cases i; simp [rename.up] end lemma rename_up_comp_rename_up (ξ ξ' : rename) : ξ'.up ∘ ξ.up = rename.up (ξ' ∘ ξ) := begin apply funext, intro i, cases i; simp [function.comp, rename.up] end @[simp] lemma rename_rename (a : type) (ξ ξ') : (a.rename ξ).rename ξ' = a.rename (ξ' ∘ ξ) := by induction a generalizing ξ ξ'; simp [*,rename_up_comp_rename_up] lemma subst_up_comp_rename_up (ξ : rename) (σ : subst) : σ.up ∘ ξ.up = subst.up (σ ∘ ξ) := begin apply funext, intro i, cases i; simp [function.comp, rename.up, subst.up] end @[simp] lemma rename_subst (a : type) (ξ σ) : (a.rename ξ).subst σ = a.subst (σ ∘ ξ) := by induction a generalizing ξ σ; simp [*,subst_up_comp_rename_up] lemma rename_up_comp_subst_up (ξ : rename) (σ : subst) : type.rename ξ.up ∘ σ.up = subst.up (type.rename ξ ∘ σ) := begin apply funext, intro i, cases i with i; simp [function.comp, rename.up, subst.up] end @[simp] lemma subst_rename (a : type) (ξ σ) : (a.subst σ).rename ξ = a.subst (type.rename ξ ∘ σ) := by induction a generalizing ξ σ; simp [*,rename_up_comp_subst_up] lemma subst_up_comp_subst_up (σ σ' : subst) : σ'.up ∘ₛ σ.up = (σ' ∘ₛ σ).up := begin apply funext, intro i, cases i with i; simp [subst.comp, function.comp, subst.up] end @[simp] lemma subst_subst (a : type) (σ σ') : (a.subst σ).subst σ' = a.subst (σ' ∘ₛ σ) := begin induction a generalizing σ σ'; simp [*,subst_up_comp_subst_up], case var { simp [subst.comp, function.comp] } end lemma lift_lift {k k' d d'} (a : type) : d ≤ d' → d' ≤ k + d → (a.lift k d).lift k' d' = a.lift (k + k') d := begin intros, simp [type.lift,rename_rename,function.comp], congr, apply funext, intro i, by_cases i ≥ d, { simp [ge, h, type.lift, lift_idx, le_trans ‹d' ≤ k + d› (add_le_add_left h _)] }, { have : ¬d' ≤ i, from λ hcontr, h (le_trans ‹d ≤ d'› hcontr), simp [ge, h, type.lift, lift_idx, this] } end @[simp] lemma lift_lift' (k k') (a : type) : (a.lift k).lift k' = a.lift (k + k') := lift_lift _ dec_trivial dec_trivial lemma lift_lift2 (k k' d d') (a : type) : k + d ≤ d' → (a.lift k d).lift k' d' = (a.lift k' (d' - k)).lift k d := begin intros, simp [type.lift,rename_rename,function.comp], congr, apply funext, intro i, have : k ≤ d', from le_trans (nat.le_add_right _ _) ‹k + d ≤ d'›, by_cases i ≥ d, { by_cases d' ≤ k + i with h', { have : d' - k ≤ k + i - k, from nat.sub_le_sub_right h' k, simp [nat.add_sub_cancel_left] at this, simp [ge, h, type.lift, lift_idx, h', this, le_add_of_nonneg_of_le (nat.zero_le _) h] }, { have : ¬ d' - k ≤ i, begin assume hcontr, apply h', have : d' - k + k ≤ i + k, from nat.add_le_add_right hcontr k, simp [nat.sub_add_cancel ‹k ≤ d'›] at this, simp [this], end, simp [ge, h, type.lift, lift_idx, h', this] } }, { simp [ge, lift_idx, h], have : ¬d' - k ≤ i, begin have : k + i < k + d, from add_lt_add_left (lt_of_not_ge h) _, have : i + k < k + d, by simp [this], have : d' > i + k, from lt_of_lt_of_le this ‹k + d ≤ d'›, have : d' - k > i + k - k, from nat.sub_lt_sub_right this (nat.le_add_left _ _), simp only [nat.add_sub_cancel] at this, exact not_le_of_gt this, end, have : d ≤ d', from le_trans (nat.le_add_left _ _) ‹k + d ≤ d'›, have : ¬d' ≤ i, from not_le_of_gt (lt_of_lt_of_le (lt_of_not_ge h) this), simp [*, h, type.lift, this] } end lemma nat.succ_le_iff_lt (n m : ℕ) : n.succ ≤ m ↔ n < m := ⟨nat.succ_le_of_lt, nat.lt_of_succ_le⟩ @[simp] lemma expand_lift (k d) (a : type) : (a.lift k (d+1)).expand = a.expand.lift k d := begin intros, simp [type.expand,type.instantiate,type.lift,instantiate_idx,rename_rename,function.comp], congr, apply funext, intro i, simp [nat.not_lt_zero,ge,lift_idx,nat.succ_le_iff_lt], by_cases d < i, { have : 0 < i, from lt_of_le_of_lt (nat.zero_le _) ‹d < i›, have : 0 < k + i, from lt_of_lt_of_le this (nat.le_add_left _ _), simp [*, le_of_lt h, nat.add_sub_assoc, nat.succ_le_iff_lt, nat.le_sub_one_of_lt] }, { simp [*], cases i with i, { simp [rename_up_comp_rename_up, nat.not_lt_zero], congr, apply funext, intro j, cases j, --by_cases d ≤ j, { simp [rename.up,*] }, { simp [rename.up,*, function.comp, if_distrib nat.succ, nat.add_one, nat.add_succ, nat.lt_succ_iff_le, rename_up_id], apply if_congr; simp } }, { have : ¬ d ≤ i, from h ∘ nat.lt_succ_of_le, simp [nat.zero_lt_succ,*] } } end @[simp] lemma env.length_lift (e : env) (k d) : (e.lift k d).length = e.length := by induction e; simp [env.lift, *] @[simp] lemma option_has_map_map_none {α β : Type} (f : α → β) : f <$> none = none := rfl @[simp] lemma option_has_map_map_some {α β : Type} (f : α → β) (x : α) : f <$> some x = f x := rfl @[simp] lemma env.nth_lift {e : env} (k d i) : (e.lift k d).nth i = (λ a : type, a.lift k (d + (e.length - 1 - i))) <$> e.nth i := begin induction e generalizing i, { simp [env.lift] }, { simp [list.nth], cases i with i, { simp [env.lift, list.nth, nat.add_sub_cancel_left], refl }, { simp [env.lift, ih_1, nat.add_sub_cancel_left, nat.sub_sub] } } end @[simp] lemma lift_zero (a : type) : a.lift 0 = a := by induction a; simp [*, type.lift, lift_idx, rename_up_id] at * @[simp] lemma up_lift_idx (k d) : (lift_idx k d).up = lift_idx k (d+1) := begin apply funext, intro i, simp [lift_idx], cases i, { have : d + 1 > 0, from nat.zero_lt_succ _, simp [rename.up, ge, not_le_of_gt this] }, { simp [rename.up, ge, nat.succ_le_succ_iff], rw if_distrib (has_add.add 1), simp [nat.add_one], apply if_congr; refl } end @[simp] lemma up_instantiate_idx (a d) : (instantiate_idx a d).up = instantiate_idx a (d+1) := begin apply funext, intro i, simp [instantiate_idx], cases i with i, { have : d + 1 > 0, from nat.zero_lt_succ _, simp [subst.up, not_lt_of_ge (nat.zero_le _), ne_of_lt this] }, { simp [subst.up, ge, nat.succ_lt_succ_iff, nat.add_one], by_cases d < i, { have : 0 < i, from lt_of_le_of_lt (nat.zero_le _) h, simp [*, (nat.succ_sub this).symm] }, { simp *, by_cases i = d, { simp [*,type.lift,lift_idx,function.comp,nat.zero_le,ge,nat.add_succ] }, { have : i.succ ≠ d.succ, from h ∘ nat.succ.inj, simp [*] } } } end section variables (k d : ℕ) @[simp] def type.lift_idx (x : ℕ) : (var x).lift k d = var (lift_idx k d x) := rfl @[simp] def type.lift_top : top.lift k d = top := rfl @[simp] def type.lift_app (a b) : (a →ₛ b).lift k d = a.lift k d →ₛ b.lift k d := rfl @[simp] def type.lift_abs (a b) : (∀0<:a, b).lift k d = ∀0<:a.lift k d, b.lift k (d+1) := by simp [type.lift] @[simp] def type.lift_mu (a) : (mu a).lift k d = mu (a.lift k (d+1)) := by simp [type.lift] variables (r : type) @[simp] def type.instantiate_var (x : ℕ) : (var x).instantiate r d = if d < x then var (x-1) else if x = d then r.lift d else var x := rfl @[simp] def type.instantiate_top : top.instantiate r d = top := rfl @[simp] def type.instantiate_app (a b) : (a →ₛ b).instantiate r d = a.instantiate r d →ₛ b.instantiate r d := rfl @[simp] def type.instantiate_abs (a b) : (∀0<: a, b).instantiate r d = ∀0<:a.instantiate r d, b.instantiate r (d+1) := by simp [type.instantiate] @[simp] def type.instantiate_mu (a) : (mu a).instantiate r d = mu (a.instantiate r (d+1)) := by simp [type.instantiate] end lemma sub_insert {e₁ e₂ : env} {a b c} : e₁ ++ e₂ ⊢ a <: b → e₁.lift 1 ++ c::e₂ ⊢ a.lift 1 e₁.length <: b.lift 1 e₁.length := begin generalize he' : e₁ ++ e₂ = e', intro h, induction h generalizing c e₁, all_goals { simp [lift_idx, -add_comm], try {constructor; done} }, case sub.env e' x a b h₁ h₂ ih { subst e', by_cases x ≥ e₁.length, { simp [if_pos h], apply sub.env, { have : ¬ (x + 1 < e₁.length), from λ hcontr, not_lt_of_ge h (nat.lt_of_succ_lt hcontr), simp [list.nth_append, this, nat.sub_add_comm h, -add_comm, list.nth], simp [list.nth_append, if_neg (not_lt_of_ge h)] at h₁, apply h₁ }, { have ih := ih rfl, rw lift_lift _ (nat.zero_le _) (nat.le_succ_of_le h) at ih, apply ih } }, { simp [if_neg h], apply sub.env, { simp [list.nth_append, lt_of_not_ge h] at ⊢ h₁, -- HACK show _ = some (a.lift 1 (e₁.length - 1 - x)), simp [h₁], refl }, { have ih := ih rfl, rw lift_lift2 at ih, { rw [nat.sub_sub, nat.one_add], apply ih }, { apply nat.succ_le_of_lt (lt_of_not_ge h) } } } }, case sub.abs { have ih_2 := @ih_2 c (a'::e₁), apply sub.abs; simp [*, env.lift] at * }, case sub.fun { apply sub.fun (ih_1 he') (ih_2 he') }, case sub.expₗ { apply sub.expₗ, simp only [expand_lift], apply ih_1 he' }, case sub.expᵣ { apply sub.expᵣ, simp only [expand_lift], apply ih_1 he' } end lemma prod.sub {e : env} {a a' b b'} : e ⊢ a <: a' → e ⊢ b <: b' → e ⊢ a ×ₛ b <: a' ×ₛ b' := begin intros, repeat {any_goals {constructor}}, apply @sub_insert []; assumption, apply @sub_insert []; assumption end lemma {u} list.elem_zip_cons_of_elem_zip {α β : Type u} {a : α} {b : β} {p as bs} : p ∈ list.zip as bs → p ∈ list.zip (a::as) (b::bs) := or.inr lemma list.sub {e : env} {as as'} : list.length as = list.length as' → (∀ p ∈ as.zip as', e ⊢ prod.fst p <: p.2) → e ⊢ tuple as <: tuple as' := begin intros hlen helem, induction as generalizing as', { cases as', {constructor}, {contradiction} }, { cases as', {contradiction}, simp [tuple], apply prod.sub, { apply helem (a, a_2), simp [list.zip, list.zip_with] }, { simp [list.length] at hlen, apply ih_1 (eq_of_add_eq_add_left hlen), intros p hp, apply helem p (list.elem_zip_cons_of_elem_zip hp), } } end @[simp] lemma lift_tuple (as k d) : (tuple as).lift k d = tuple (as.map (λ a, a.lift k d)) := begin induction as generalizing d, { refl }, { simp [tuple, prod, lift_idx, lift_lift2, *, ge, not_le_of_gt (nat.zero_lt_succ _)] } end @[simp] lemma instantiate_idx_lift_idx (i b d) : instantiate_idx b (d + 1) (lift_idx 1 0 i) = type.rename (lift_idx 1) (instantiate_idx b d i) := begin simp [instantiate_idx, lift_idx, ge, nat.zero_le, nat.add_one, nat.succ_lt_succ_iff], by_cases d < i, { have : 0 < i, from lt_of_le_of_lt (nat.zero_le _) ‹d < i›, simp [*, has_sub.sub, nat.sub, nat.succ_pred_eq_of_pos this] }, { simp [*], by_cases i = d, { simp [*, type.lift, lift_idx, function.comp, ge, nat.zero_le, nat.add_succ] }, { simp [*, show i.succ ≠ d.succ, from h ∘ nat.succ.inj] } } end @[simp] lemma instantiate_tuple (as b d) : (tuple as).instantiate b d = tuple (as.map (λ a, a.instantiate b d)) := begin generalize h : as.length = l, induction l generalizing as b d, { simp [list.eq_nil_of_length_eq_zero h], refl }, { cases as, { contradiction }, { rw list.length at h, injection h with h, simp [tuple, prod, nat.not_lt_zero], rw ih_1 _ b (d+1), { have : 0 ≠ d + 1, by intro hcontr; injection hcontr, simp [*, type.instantiate, type.lift, function.comp, list.length_map] }, { simp [*, list.length_map] } } } end lemma instantiate_record (b fs) : (record fs).instantiate b = record (fs.map (λ ⟨i, a⟩, ⟨i, a.instantiate b⟩)) := begin simp [record, record_list], congr, { apply funext, intro i, induction fs, { refl }, { simp [list.find], cases a, simp, by_cases idx = i, { simp [function.comp, h, option.get_or_else, has_map.map, option.map, option.bind] }, { simp [function.comp, h], apply ih_1 }, } }, { apply funext, intro a, cases a with idx ty, simp } end lemma record.sub {e} {fs fs' : list field} : (record_list fs).length ≥ (record_list fs').length → (∀ p : _ × _, p ∈ (record_list fs).zip (record_list fs') → e ⊢ p.1 <: p.2) → e ⊢ record fs <: record fs' := begin simp [record], generalize : record_list fs = rfs, induction record_list fs' generalizing rfs, all_goals { intros hlen helem }, case list.nil { cases rfs, { apply sub.refl }, { simp [tuple], apply prod.sub; apply sub.top } }, case list.cons { cases rfs, { cases hlen }, { simp [tuple], apply prod.sub, { apply helem, simp [list.zip, list.zip_with] }, { apply ih_1, { simp at hlen, apply le_of_add_le_add_left hlen }, { intros a b hab, apply helem a b (list.elem_zip_cons_of_elem_zip hab) } } } } end lemma lift_free_range {t : type} (k m) : t.free_range ≤ m → t.lift k m = t := begin induction t generalizing m, all_goals { simp [type.free_range] }, { intro h, simp [lift_idx, ge, not_le_of_gt (nat.lt_of_succ_le h)] }, { intro h, have := ih_1 m (le_trans (le_max_left _ _) h), rw [this], have := ih_2 m (le_trans (le_max_right _ _) h), rw [this] }, { intro h, have := ih_1 m (le_trans (le_max_left _ _) h), rw [this], have : body.lift k (m+1) = body, { apply ih_2 (m+1), have : body.free_range - 1 ≤ m, from le_trans (le_max_right _ _) h, show body.free_range ≤ m + 1, from nat.le_succ_of_pred_le this, }, rw [this] }, { intro h, have := ih_1 (m+1) (nat.le_succ_of_pred_le h), rw [this] } end lemma lift_closed {t : type} (k) : t.closed → (t.lift k) = t := begin intro h, apply lift_free_range, simp [type.closed] at h, simp [h] end lemma left_le_of_max_le {a b c : ℕ} : max a b ≤ c → a ≤ c := begin intro h, by_cases a ≤ b with ab, { simp [max, ab] at h, apply le_trans ab h }, { simp [max, ab] at h, apply h } end lemma right_le_of_max_le {a b c : ℕ} : max a b ≤ c → b ≤ c := begin intro h, by_cases a ≤ b with ab, { simp [max, ab] at h, apply h }, { simp [max, ab] at h, apply le_trans (le_of_not_le ab) h } end lemma instantiate_free_range {t t' : type} {d} : t.free_range ≤ d → t.instantiate t' d = t := begin induction t generalizing d, all_goals { simp [type.free_range] }, { intro h, have : idx < d, from nat.lt_of_succ_le h, simp [lift_idx, instantiate_idx, ne_of_lt this, not_lt_of_gt this] }, { intro h, rw[ih_1 (le_trans (left_le_of_max_le h) (le_refl _)), ih_2 (le_trans (right_le_of_max_le h) (le_refl _))] }, { intro h, rw[ih_1 (le_trans (left_le_of_max_le h) (le_refl _)), ih_2 (le_trans (nat.le_succ_of_pred_le (right_le_of_max_le h)) (le_refl _))] }, { intro h, rw[ih_1 (le_trans (nat.le_succ_of_pred_le h) (le_refl _))] }, end @[simp] lemma instantiate_closed {t t' : type} : t.closed → t.instantiate t' = t := begin intro h, apply instantiate_free_range, simp [type.closed] at h, simp [h] end /- A tactic for reducing record relations to field-wise relations -/ section private meta def go := `[simp [record_list, list.range, list.range_core, list.find, option.get_or_else, list.zip, list.zip_with, max_eq_left, max_eq_right] at h {fail_if_unchanged:=ff}, do { h ← tactic.get_local `h >>= tactic.infer_type, match h with | `(_ ∨ _) := `[ cases h with h h, tactic.swap, go] | _ := tactic.skip end }] meta def record.fieldwise_eq : tactic unit := `[apply record.sub, { exact dec_trivial }, intros p h, cases p with a b, go, all_goals { simp [h] }] run_cmd add_interactive [``record.fieldwise_eq] end section attribute [reducible] lift_t coe_to_lift coe_t coe_option @[simp] def labels.a := 0 @[simp] def labels.b := 1 @[simp] def labels.c := 2 def foo := ⟦ₛ { a := Bool, b := top } ⟧ def bar := ⟦ₛ { a := Bool, b := Bool, c := Bool } ⟧ example : bar <: foo := record.sub dec_trivial (λ ⟨a, b⟩ h, begin conv at h { change (a, b) = (Bool, Bool) ∨ _, simp, }, cases h with h h; simp [h], { apply sub.refl }, { apply sub.top }, end) def A := ⟦ₛ { a := Bool } ⟧ def B := ⟦ₛ ∀ α <: A, μ β, { a := Bool, b := Bool → α → β } ⟧ def C := ⟦ₛ ∀ α <: A, { a := Bool, b := Bool → α → A } ⟧ @[simp] lemma A.is_closed : A.closed := show A.free_range = 0, from rfl example : B <: C := begin suffices : ⟦ₛ bctx α <: A ⊢ (μ β, { a := Bool, b := Bool → α → β }) <: { a := Bool, b := Bool → α → A } ⟧, from sub.abs (sub.refl _ _) this, suffices : ⟦ₛ bctx α <: A ⊢ { a := Bool, b := Bool → α → μ β, { a := Bool, b := Bool → α → β } } <: { a := Bool, b := Bool → α → A } ⟧, from sub.expₗ this, record.fieldwise_eq, show ⟦ₛ bctx α <: A ⊢ (Bool → α → μ β, { a := Bool, b := Bool → α → β }) <: (Bool → α → A) ⟧, { suffices : ⟦ₛ bctx α <: A ⊢ (μ β, { a := Bool, b := Bool → α → β }) <: A ⟧, by simp at this; simp [sub.fun, sub.refl, this], suffices : ⟦ₛ bctx α <: A ⊢ { a := Bool, b := Bool → α → (μ β, { a := Bool, b := Bool → α → β }) } <: A ⟧, from sub.expₗ this, simp [lift_closed], record.fieldwise_eq, show [A] ⊢ Bool <: Bool, from sub.refl _ _ }, show [A] ⊢ Bool <: Bool, from sub.refl _ _ end end end system_f_sub /- Unused experiments -/ section open lean open lean.parser open interactive open interactive.types open tactic @[user_command] meta def extend_inductive_cmd (dmi : decl_meta_info) (_ : parse $ tk "extend_inductive") : parser unit := do base ← ident, base ← resolve_constant base, env ← get_env, guard (env.is_inductive base) <|> fail "expected inductive type", tk "with", decl ← inductive_decl.parse dmi, [idecl] ← pure decl.decls | fail "mutual inductives not supported", let new := idecl.sig.app_fn.local_uniq_name, let ls : list name := [], -- TODO let p := env.inductive_num_params base, ty ← declaration.type <$> env.get base, is ← (env.constructors_of base).mmap (λ ctor, do ty ← declaration.type <$> env.get ctor, let ty := ty.replace (λ e _, match e with | expr.const n ls := if n = base then some (expr.const new ls) else none | _ := none end) in pure (new ++ ctor.components.ilast, ty)), let is := is ++ idecl.intros.map (λ e, (e.local_uniq_name, e.local_type)), set_env $ env.add_namespace new, add_inductive new ls p ty is meta def dunfold_productive (cfg : delta_config := {}) : conv unit := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do (expr.const f_name _) ← return e.get_app_fn, es ← get_eqn_lemmas_for ff f_name, guard $ es.length > 1, sl ← es.mfoldl simp_lemmas.add_simp simp_lemmas.mk, new_e ← sl.drewrite e, return (u, new_e, tt) in do e ← target, (c, new_e) ← dsimplify_core () (λ c e, failed) unfold e {max_steps := cfg.max_steps, canonize_instances := cfg.visit_instances}, change new_e meta def delta_target (cs : list name) (cfg : delta_config := {}) : tactic unit := do t ← target, delta cs t cfg >>= unsafe_change run_cmd add_interactive [`dunfold_productive] `conv.interactive end
35d2218e3a4cbe6243d1820dadac4dd6cb4c46f2
4f065978c49388d188224610d9984673079f7d91
/zfc_structures.lean
73ddc8c7d7c2965a6e025f8745f999cb578b7a6c
[]
no_license
kckennylau/Lean
b323103f52706304907adcfaee6f5cb8095d4a33
907d0a4d2bd8f23785abd6142ad53d308c54fdcb
refs/heads/master
1,624,623,720,653
1,563,901,820,000
1,563,901,820,000
109,506,702
3
1
null
null
null
null
UTF-8
Lean
false
false
59,597
lean
import order.lattice set_option old_structure_cmd true universe u variable (α : Type u) namespace zfc class has_zmem extends has_mem α α instance [has_zmem α] : has_subset α := ⟨λ x y, ∀ z, z ∈ x → z ∈ y⟩ variable {α} theorem subset.refl [has_zmem α] (x : α) : x ⊆ x := λ z, id theorem subset.trans [has_zmem α] {x y z : α} (hxy : x ⊆ y) (hyz : y ⊆ z) : x ⊆ z := λ p hp, hyz p $ hxy p hp instance [has_zmem α] : preorder α := ⟨(⊆), _, subset.refl, λ x y z, subset.trans⟩ variable α class is_extensional extends has_zmem α := (ext : ∀ x y : α, (∀ z, z ∈ x ↔ z ∈ y) → x = y ) variable {α} theorem subset.antisymm [is_extensional α] {x y : α} (hxy : x ⊆ y) (hyx : y ⊆ x) : x = y := is_extensional.ext x y $ λ z, ⟨λ hx, hxy z hx, λ hy, hyx z hy⟩ instance partial_order [is_extensional α] : partial_order α := { le_antisymm := λ x y, subset.antisymm, .. zfc.preorder } variable α class has_zempty extends has_zmem α, has_emptyc α := (not_zmem_empty : ∀ x, x ∉ (∅:α)) class has_upair extends has_zmem α := (upair : α → α → α) (zmem_upair_iff_eq_or_eq : ∀ x y z, z ∈ upair x y ↔ z = x ∨ z = y) variable {α} theorem not_zmem_empty [has_zempty α] : ∀ {x}, x ∉ (∅:α) := has_zempty.not_zmem_empty def upair [has_upair α] : α → α → α := has_upair.upair def zmem_upair_iff_eq_or_eq [has_upair α] {x y z : α} : z ∈ upair x y ↔ z = x ∨ z = y := has_upair.zmem_upair_iff_eq_or_eq x y z theorem zmem_upair_left [has_upair α] {x y : α} : x ∈ upair x y := zmem_upair_iff_eq_or_eq.2 $ or.inl rfl theorem zmem_upair_right [has_upair α] {x y : α} : y ∈ upair x y := zmem_upair_iff_eq_or_eq.2 $ or.inr rfl def opair [has_upair α] (x y : α) : α := upair (upair x x) (upair x y) theorem opair.ext [has_upair α] {p q r s : α} (h : opair p q = opair r s) : p = r ∧ q = s := begin have h1 : upair p p ∈ opair p q, from zmem_upair_left, have h2 : upair p q ∈ opair p q, from zmem_upair_right, have h3 : p ∈ upair p p, from zmem_upair_left, have h4 : p ∈ upair p q, from zmem_upair_left, have h5 : q ∈ upair p q, from zmem_upair_right, have h6 : upair r r ∈ opair r s, from zmem_upair_left, have h7 : upair r s ∈ opair r s, from zmem_upair_right, have h8 : r ∈ upair r r, from zmem_upair_left, have h9 : r ∈ upair r s, from zmem_upair_left, have h0 : s ∈ upair r s, from zmem_upair_right, rw h at h1 h2, rw ← h at h6 h7, unfold opair at h1 h2 h6 h7, rw zmem_upair_iff_eq_or_eq at h1 h2 h6 h7, cases h1, { rw [h1, zmem_upair_iff_eq_or_eq, or_self] at h3, subst h3, cases h2, { rw [h2, zmem_upair_iff_eq_or_eq, or_self] at h5, subst h5, rw or_self at h7, rw [h7, zmem_upair_iff_eq_or_eq, or_self] at h0, subst h0, split, refl, refl }, { rw [h2, zmem_upair_iff_eq_or_eq] at h5, cases h5; subst h5, { rw [← h2, zmem_upair_iff_eq_or_eq, or_self] at h0, subst h0, split, refl, refl }, { split, refl, refl } } }, { rw [← h1, zmem_upair_iff_eq_or_eq, or_self] at h9, subst h9, rw [← h1, zmem_upair_iff_eq_or_eq, or_self] at h0, subst h0, rw or_self at h2, rw [h2, zmem_upair_iff_eq_or_eq, or_self] at h5, subst h5, split, refl, refl } end theorem opair.iff [has_upair α] {p q r s : α} : opair p q = opair r s ↔ p = r ∧ q = s := ⟨opair.ext, λ ⟨hpq, hrs⟩, hpq ▸ hrs ▸ rfl⟩ variable α class has_sUnion extends has_zmem α := (sUnion : α → α) (zmem_sUnion_iff_zmem_zmem : ∀ x z, z ∈ sUnion x ↔ ∃ t, z ∈ t ∧ t ∈ x) variable {α} def sUnion [has_sUnion α] : α → α := has_sUnion.sUnion def zmem_sUnion_iff_zmem_zmem [has_sUnion α] {x z : α} : z ∈ sUnion x ↔ ∃ t, z ∈ t ∧ t ∈ x := has_sUnion.zmem_sUnion_iff_zmem_zmem x z variable α class has_sUnion_upair extends has_sUnion α, has_upair α instance [has_sUnion_upair α] : has_union α := ⟨λ x y, sUnion $ upair x y⟩ instance [has_sUnion_upair α] : has_insert α α := ⟨λ x A, upair x x ∪ A⟩ lemma union_def [has_sUnion_upair α] (x y : α) : x ∪ y = (sUnion $ upair x y) := rfl lemma insert_def [has_sUnion_upair α] (x A : α) : has_insert.insert x A = upair x x ∪ A := rfl variable {α} lemma zmem_union_iff_zmem_or_zmem [has_sUnion_upair α] {x y z : α} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := begin rw [union_def, zmem_sUnion_iff_zmem_zmem], split, { intro H, rcases H with ⟨t, H1, H2⟩, rw [zmem_upair_iff_eq_or_eq] at H2, cases H2; subst H2, { left, assumption }, { right, assumption } }, { intro H, cases H, { existsi x, split, exact H, exact zmem_upair_left }, { existsi y, split, exact H, exact zmem_upair_right } } end lemma zmem_insert_iff_eq_or_zmem [has_sUnion_upair α] {x A z : α} : z ∈ has_insert.insert x A ↔ z = x ∨ z ∈ A := by rw [insert_def, zmem_union_iff_zmem_or_zmem, zmem_upair_iff_eq_or_eq, or_self] theorem zmem_insert [has_sUnion_upair α] {x y : α} : x ∈ has_insert.insert x y := zmem_insert_iff_eq_or_zmem.2 $ or.inl rfl theorem zmem_insert_of_zmem [has_sUnion_upair α] {x y z : α} (H : x ∈ z) : x ∈ has_insert.insert y z := zmem_insert_iff_eq_or_zmem.2 $ or.inr H def succ [has_sUnion_upair α] : α → α := λ x, has_insert.insert x x theorem zmem_succ_iff_eq_or_zmem [has_sUnion_upair α] {x y : α} : x ∈ succ y ↔ x = y ∨ x ∈ y := zmem_insert_iff_eq_or_zmem theorem zmem_succ [has_sUnion_upair α] {x : α} : x ∈ succ x := zmem_succ_iff_eq_or_zmem.2 $ or.inl rfl theorem zmem_succ_of_zmem [has_sUnion_upair α] {x y : α} (H : x ∈ y) : x ∈ succ y := zmem_succ_iff_eq_or_zmem.2 $ or.inr H variable α class has_powerset extends has_zmem α := (powerset : α → α) (zmem_powerset : ∀ x z, z ∈ powerset x ↔ z ⊆ x) class has_comprehension extends has_zmem α := (comprehension : α → (α → Prop) → α) (zmem_comprehension_iff : ∀ A p x, x ∈ comprehension A p ↔ x ∈ A ∧ p x) class has_infty := (infinity : α) notation `∞` := has_infty.infinity _ class has_replacement extends has_zmem α := (replacement : α → (α → α → Prop) → α) (zmem_replacement_iff : ∀ A (f : α → α → Prop) y (H : ∀ A B C, f A B → f A C → B = C), (y ∈ replacement A f ↔ ∃ x, x ∈ A ∧ f x y)) class has_infty_replacement_powerset extends has_infty α, has_replacement α, has_powerset α class has_infty_replacement_powerset_sUnion extends has_infty_replacement_powerset α, has_sUnion α variable {α} instance has_infty.to_inhabited [has_infty α] : inhabited α := ⟨∞⟩ def powerset [has_powerset α] : α → α := has_powerset.powerset theorem zmem_powerset [has_powerset α] : ∀ {x z : α}, z ∈ powerset x ↔ z ⊆ x := has_powerset.zmem_powerset def comprehension [has_comprehension α] : α → (α → Prop) → α := has_comprehension.comprehension theorem zmem_comprehension_iff [has_comprehension α] : ∀ {A : α} {p x}, x ∈ comprehension A p ↔ x ∈ A ∧ p x := has_comprehension.zmem_comprehension_iff def replacement [has_replacement α] : α → (α → α → Prop) → α := has_replacement.replacement theorem zmem_replacement_iff [has_replacement α] {A} {f : α → α → Prop} {y} (H : ∀ A B C, f A B → f A C → B = C) : (y ∈ replacement A f ↔ ∃ x, x ∈ A ∧ f x y) := has_replacement.zmem_replacement_iff A f y H instance has_comprehension.to_has_zempty [s : has_comprehension α] [inhabited α] : has_zempty α := { emptyc := comprehension (inhabited.default α) (λ x, false), not_zmem_empty := λ x hx, begin simp [∅] at hx, rw [zmem_comprehension_iff] at hx, exact hx.2 end, .. s } instance has_replacement.to_has_comprehension [s : has_replacement α] : has_comprehension α := { comprehension := λ A p, replacement A (λ x y, x = y ∧ p x), zmem_comprehension_iff := λ A p x, begin have h1 : ∀ A B C, A = B ∧ p A → A = C ∧ p A → B = C, { intros A B C h1 h2, rw [← h1.1, ← h2.1] }, rw [zmem_replacement_iff h1], split, { intro H, rcases H with ⟨w, H1, H2, H3⟩, subst H2, exact ⟨H1, H3⟩ }, { intro H, existsi x, simpa } end, .. s } instance has_infty_replacement_powerset.to_has_zempty [s : has_infty_replacement_powerset α] : has_zempty α := { .. s, .. has_comprehension.to_has_zempty } instance has_infty_replacement_powerset.to_has_upair [s : has_infty_replacement_powerset α] : has_upair α := { upair := λ x y, replacement (powerset (powerset ∅)) (λ m n, m = ∅ ∧ n = x ∨ m = powerset ∅ ∧ n = y), zmem_upair_iff_eq_or_eq := λ x y z, begin have h1 : ∀ (A B C : α), A = ∅ ∧ B = x ∨ A = powerset ∅ ∧ B = y → A = ∅ ∧ C = x ∨ A = powerset ∅ ∧ C = y → B = C, { intros A B C h1 h2, cases h1; cases h2; cases h1 with h3 h4; cases h2 with h5 h6, { subst h4, subst h6 }, { exfalso, rw h3 at h5, have h7 : (∅:α) ∈ powerset ∅, { rw zmem_powerset, exact subset.refl ∅ }, rw ← h5 at h7, exact not_zmem_empty h7 }, { exfalso, rw h3 at h5, have h7 : (∅:α) ∈ powerset ∅, { rw zmem_powerset, exact subset.refl ∅ }, rw h5 at h7, exact not_zmem_empty h7 }, { subst h4, subst h6 } }, rw zmem_replacement_iff h1, split, { intro H, rcases H with ⟨w, H1, ⟨H2, H3⟩ | ⟨H2, H3⟩⟩, { left, assumption }, { right, assumption } }, { intro H, cases H, { existsi ∅, split, { rw zmem_powerset, intros z hz, exfalso, exact not_zmem_empty hz }, { left, split, refl, assumption } }, { existsi powerset ∅, split, { rw zmem_powerset, exact subset.refl _ }, { right, split, refl, assumption } } } end, .. s } instance has_infty_replacement_powerset_sUnion.to_has_sUnion_upair [s : has_infty_replacement_powerset_sUnion α] : has_sUnion_upair α := { .. s, .. has_infty_replacement_powerset.to_has_upair } variable α class has_zinfty extends has_infty α, has_infty_replacement_powerset_sUnion α := (empty_zmem_infinity : (∅:α) ∈ (∞:α)) (succ_zmem_infinity_of_zmem_infinity : ∀ x:α, x ∈ (∞:α) → succ x ∈ (∞:α)) class is_regular extends has_zmem α := (regular : ∀ x : α, (∃ y, y ∈ x) → (∃ y : α, y ∈ x ∧ ∀ z, z ∈ y → z ∈ x → false)) variable {α} theorem empty_zmem_infinity [has_zinfty α] : (∅:α) ∈ (∞:α) := has_zinfty.empty_zmem_infinity α theorem succ_zmem_infinity_of_zmem_infinity [has_zinfty α] : ∀ x:α, x ∈ (∞:α) → succ x ∈ (∞:α) := has_zinfty.succ_zmem_infinity_of_zmem_infinity theorem regular [is_regular α] : ∀ x : α, (∃ y, y ∈ x) → (∃ y : α, y ∈ x ∧ ∀ z, z ∈ y → z ∈ x → false) := is_regular.regular variable α class zf extends has_zmem α, is_extensional α, has_sUnion α, has_powerset α, has_replacement α, has_zinfty α, is_regular α section zf variables {α} [zf α] {x y z : α} theorem singleton_def : {x} = has_insert.insert x (∅:α) := rfl theorem zmem_singleton_iff : x ∈ ({y}:α) ↔ x = y := begin rw [singleton_def, zmem_insert_iff_eq_or_zmem], apply or_iff_left_of_imp, intro H, exfalso, exact not_zmem_empty H end theorem zmem_singleton : x ∈ ({x}:α) := begin rw [singleton_def, zmem_insert_iff_eq_or_zmem], left, refl end theorem not_zmem_self : x ∉ x := λ h, begin rcases regular {x} ⟨x, zmem_singleton⟩ with ⟨y, h1, h2⟩, rw zmem_singleton_iff at h1, subst h1, exact h2 y h zmem_singleton end theorem not_zmem_and_zmem : x ∈ y → y ∈ x → false := λ hxy hyx, begin rcases regular {x, y} ⟨x, by simp [zmem_insert_iff_eq_or_zmem]; right; exact zmem_singleton⟩ with ⟨z, h1, h2⟩, rw [zmem_insert_iff_eq_or_zmem, zmem_singleton_iff] at h1, cases h1; subst h1, { apply h2 _ hxy, simp [zmem_insert_iff_eq_or_zmem], right, exact zmem_singleton }, { apply h2 _ hyx, simp [zmem_insert_iff_eq_or_zmem] } end theorem succ.ext {x y : α} (H : succ x = succ y) : x = y := begin simp [succ] at H, have H1 : x ∈ has_insert.insert x x, { rw zmem_insert_iff_eq_or_zmem, left, refl }, have H2 : y ∈ has_insert.insert y y, { rw zmem_insert_iff_eq_or_zmem, left, refl }, rw [H, zmem_insert_iff_eq_or_zmem] at H1, rw [← H, zmem_insert_iff_eq_or_zmem] at H2, cases H1, { assumption }, { cases H2, { subst H2 }, { exfalso, exact not_zmem_and_zmem H1 H2 } } end def prod : α → α → α := λ X Y, comprehension (powerset $ powerset $ X ∪ Y) (λ z, ∃ x y, x ∈ X ∧ y ∈ Y ∧ z = opair x y) theorem zmem_prod {A B : α} (hx : x ∈ A) (hy : y ∈ B) : opair x y ∈ prod A B := zmem_comprehension_iff.2 ⟨zmem_powerset.2 $ λ z (hz : z ∈ opair x y), or.cases_on (zmem_upair_iff_eq_or_eq.1 hz) (λ hzx, zmem_powerset.2 $ λ w hw, or.cases_on (zmem_upair_iff_eq_or_eq.1 $ (hzx ▸ hw : w ∈ upair x x)) (λ hwx, zmem_union_iff_zmem_or_zmem.2 $ or.inl $ hwx.symm ▸ hx) (λ hwx, zmem_union_iff_zmem_or_zmem.2 $ or.inl $ hwx.symm ▸ hx)) (λ hzxy, zmem_powerset.2 $ λ w hw, or.cases_on (zmem_upair_iff_eq_or_eq.1 $ (hzxy ▸ hw : w ∈ upair x y)) (λ hwx, zmem_union_iff_zmem_or_zmem.2 $ or.inl $ hwx.symm ▸ hx) (λ hwy, zmem_union_iff_zmem_or_zmem.2 $ or.inr $ hwy.symm ▸ hy)), x, y, hx, hy, rfl⟩ theorem zmem_left_of_zmem_prod {A B : α} (h : opair x y ∈ prod A B) : x ∈ A := let ⟨x1, y1, hx1, hy1, h⟩ := (zmem_comprehension_iff.1 h).2 in (opair.ext h).1.symm ▸ hx1 theorem zmem_right_of_zmem_prod {A B : α} (h : opair x y ∈ prod A B) : y ∈ B := let ⟨x1, y1, hx1, hy1, h⟩ := (zmem_comprehension_iff.1 h).2 in (opair.ext h).2.symm ▸ hy1 class is_relation (f : α) : Prop := (eq_opair_of_zmem : ∀ z, z ∈ f → ∃ x y, z = opair x y) def dom (f : α) : α := replacement f (λ z x, ∃ y, z = opair x y) def range (f : α) : α := replacement f (λ z y, ∃ x, z = opair x y) class is_function (f : α) extends is_relation f : Prop := (exists_unique : ∀ x, x ∈ dom f → ∃! y, opair x y ∈ f) class is_injective (f : α) extends is_function f : Prop := (injective : ∀ x y z, opair x z ∈ f → opair y z ∈ f → x = y) theorem zmem_dom_iff {f x : α} : x ∈ dom f ↔ ∃ y, opair x y ∈ f := begin have h1 : ∀ (A B C : α), (∃ (y : α), A = opair B y) → (∃ (y : α), A = opair C y) → B = C, { intros A B C h1 h2, cases h1 with m h1, cases h2 with n h2, subst h1, exact (opair.ext h2).1 }, rw [dom, zmem_replacement_iff h1], split; intro H, { rcases H with ⟨z, h1, w, h2⟩, subst h2, existsi w, assumption }, { cases H with z h, existsi opair x z, split, assumption, existsi z, refl } end theorem zmem_range_iff {f y : α} : y ∈ range f ↔ ∃ x, opair x y ∈ f := begin have h1 : ∀ (A B C : α), (∃ (x : α), A = opair x B) → (∃ (x : α), A = opair x C) → B = C, { intros A B C h1 h2, cases h1 with m h1, cases h2 with n h2, subst h1, exact (opair.ext h2).2 }, rw [range, zmem_replacement_iff h1], split; intro H, { rcases H with ⟨z, h1, w, h2⟩, subst h2, existsi w, assumption }, { cases H with z h, existsi opair z y, split, assumption, existsi z, refl } end theorem zmem_dom_of_opair_zmem {f : α} [is_function f] {x y : α} (H : opair x y ∈ f) : x ∈ dom f := zmem_dom_iff.2 ⟨_, H⟩ theorem zmem_range_of_opair_zmem {f : α} [is_function f] {x y : α} (H : opair x y ∈ f) : y ∈ range f := zmem_range_iff.2 ⟨_, H⟩ def eval (f : α) [is_function f] (x : α) : α := sUnion $ comprehension (range f) (λ y, opair x y ∈ f) theorem eval_unique {f : α} [is_function f] {x y : α} (H : x ∈ dom f) (Hxy : opair x y ∈ f) : y = eval f x := begin rcases is_function.exists_unique _ H with ⟨y', H1, H2⟩, have H3 := H2 _ Hxy, subst H3, apply is_extensional.ext, intro z, split; intro hz, { rw [eval, zmem_sUnion_iff_zmem_zmem], existsi y, rw [zmem_comprehension_iff, zmem_range_iff], exact ⟨hz, ⟨x, Hxy⟩, Hxy⟩ }, { rw [eval, zmem_sUnion_iff_zmem_zmem] at hz, rcases hz with ⟨t, ht1, ht2⟩, rw [zmem_comprehension_iff, zmem_range_iff] at ht2, specialize H2 _ ht2.2, subst H2, exact ht1 } end theorem opair_eval_zmem {f : α} [is_function f] {x : α} (H : x ∈ dom f) : opair x (eval f x) ∈ f := begin rcases is_function.exists_unique _ H with ⟨y, H1, H2⟩, have H3 := eval_unique H H1, subst H3, exact H1 end theorem eval_zmem_range {f : α} [is_function f] {x : α} (H : x ∈ dom f) : eval f x ∈ range f := zmem_range_iff.2 ⟨_, opair_eval_zmem H⟩ def inv (f : α) : α := replacement f (λ x y, ∃ m n, opair m n = x ∧ opair n m = y) theorem inv.aux (A B C : α) (H1 : ∃ (m n : α), opair m n = A ∧ opair n m = B) (H2 : ∃ (m n : α), opair m n = A ∧ opair n m = C) : B = C := begin rcases H1 with ⟨m1, n1, H3, H4⟩, rcases H2 with ⟨m2, n2, H5, H6⟩, subst H3, subst H4, subst H6, rw opair.iff at H5 ⊢, cases H5 with H1 H2, split; symmetry; assumption end theorem zmem_inv_iff {f x y : α} : opair x y ∈ inv f ↔ opair y x ∈ f := begin rw [inv, zmem_replacement_iff inv.aux], split; intro h, { rcases h with ⟨z, hz, m, n, h1, h2⟩, rcases opair.ext h2 with ⟨h3, h4⟩, subst h1, subst h3, subst h4, exact hz }, { exact ⟨_, h, _, _, rfl, rfl⟩ } end instance inv.is_relation (f : α) : is_relation (inv f) := { eq_opair_of_zmem := begin intros z hz, rw [inv, zmem_replacement_iff inv.aux] at hz, rcases hz with ⟨x, hxf, m, n, h1, h2⟩, subst h2, exact ⟨_, _, rfl⟩ end } instance inv.is_injective (f : α) [is_injective f] : is_injective (inv f) := { exists_unique := begin intros x hx, rw zmem_dom_iff at hx, cases hx with y hy, existsi y, split, { exact hy }, { intros z hz, rw zmem_inv_iff at hy hz, exact is_injective.injective _ _ _ hz hy } end, injective := begin intros x y z hx hy, rw zmem_inv_iff at hx hy, have h1 : z ∈ dom f, { rw zmem_dom_iff, exact ⟨_, hy⟩ }, have h2 := is_function.exists_unique z h1, exact unique_of_exists_unique h2 hx hy end, .. inv.is_relation f } theorem inv.dom {f : α} : dom (inv f) = range f := begin apply is_extensional.ext, intro z, rw [zmem_dom_iff, zmem_range_iff], split; intro hz, { cases hz with y h, rw zmem_inv_iff at h, exact ⟨_, h⟩ }, { cases hz with y h, existsi y, rw zmem_inv_iff, exact h } end theorem inv.range {f : α} : range (inv f) = dom f := begin apply is_extensional.ext, intro z, rw [zmem_dom_iff, zmem_range_iff], split; intro hz, { cases hz with y h, rw zmem_inv_iff at h, exact ⟨_, h⟩ }, { cases hz with y h, existsi y, rw zmem_inv_iff, exact h } end variable α def omega : α := comprehension ∞ (λ n, ∀ A:α, ∅ ∈ A → (∀ k, k ∈ A → succ k ∈ A) → n ∈ A) notation `ω` := omega _ variable {α} theorem empty_zmem_omega : (∅:α) ∈ (ω:α) := zmem_comprehension_iff.2 ⟨empty_zmem_infinity, λ A h1 h2, h1⟩ theorem succ_zmem_omega_of_zmem (H : x ∈ (ω:α)) : succ x ∈ (ω:α) := zmem_comprehension_iff.2 ⟨succ_zmem_infinity_of_zmem_infinity x $ (zmem_comprehension_iff.1 H).1, λ A h1 h2, h2 x $ (zmem_comprehension_iff.1 H).2 A h1 h2⟩ theorem induction (p : α → Prop) (H1 : p ∅) (H2 : ∀ k, k ∈ omega α → p k → p (succ k)) (n : α) (Hn : n ∈ omega α) : p n := (zmem_comprehension_iff.1 $ (zmem_comprehension_iff.1 Hn).2 (comprehension (omega α) p) (zmem_comprehension_iff.2 ⟨empty_zmem_omega, H1⟩) (λ k hk, zmem_comprehension_iff.2 ⟨succ_zmem_omega_of_zmem $ (zmem_comprehension_iff.1 hk).1, H2 k (zmem_comprehension_iff.1 hk).1 (zmem_comprehension_iff.1 hk).2⟩)).2 theorem omega.structure (H : x ∈ (ω:α)) : x = ∅ ∨ ∃ y ∈ (ω:α), x = succ y := @induction α _ (λ z:α, z = ∅ ∨ ∃ y ∈ (ω:α), z = succ y) (or.inl rfl) (λ k hk1 hk2, or.inr ⟨k, hk1, rfl⟩) x H class is_transitive (x : α) : Prop := (zmem_trans : ∀ m n, m ∈ n → n ∈ x → m ∈ x) instance omega.transitive : is_transitive (ω:α) := { zmem_trans := λ m n hmn hno, @induction α _ (λ z, ∀ x, x ∈ z → x ∈ (ω:α)) (λ x hx, false.elim $ not_zmem_empty hx) (λ k hk1 hk2 x hx, or.cases_on (zmem_succ_iff_eq_or_zmem.1 hx) (λ hxk, hxk.symm ▸ hk1) (hk2 x)) n hno m hmn } variable α def nat.to_omega : nat → α | nat.zero := ∅ | (nat.succ n) := succ (n.to_omega) theorem nat.to_omega.zmem_omega : ∀ n, nat.to_omega α n ∈ omega α | nat.zero := empty_zmem_omega | (nat.succ n) := succ_zmem_omega_of_zmem $ nat.to_omega.zmem_omega n def nat.to_omega' : nat → {x // x ∈ omega α} := λ n, ⟨nat.to_omega α n, nat.to_omega.zmem_omega α n⟩ theorem nat.to_omega.injective : function.injective (nat.to_omega α) := begin intros m n H, induction m with m ihm generalizing n H; induction n with n ihn, { refl }, { exfalso, have h1 : nat.to_omega α n ∈ nat.to_omega α (nat.succ n), { unfold nat.to_omega, unfold succ, rw zmem_insert_iff_eq_or_zmem, left, refl }, rw ← H at h1, exact not_zmem_empty h1 }, { exfalso, have h1 : nat.to_omega α m ∈ nat.to_omega α (nat.succ m), { unfold nat.to_omega, unfold succ, rw zmem_insert_iff_eq_or_zmem, left, refl }, rw H at h1, exact not_zmem_empty h1 }, { unfold nat.to_omega at H, congr, exact ihm (succ.ext H) } end -- it isn't supposed to be surjective unless the model is transitive theorem nat.to_omega.surjective_cheating : function.surjective (nat.to_omega' α) := begin intros x, cases x with x hx, dsimp [omega] at hx, rw zmem_comprehension_iff at hx, cases hx with h1 h2, let cheating := comprehension (omega α) (nat.to_omega α '' set.univ), specialize h2 cheating, simp [cheating, zmem_comprehension_iff] at h2, specialize h2 empty_zmem_omega, specialize h2 ⟨0, rfl⟩, specialize h2 (λ k hk1 ⟨n, hk2⟩, ⟨succ_zmem_omega_of_zmem hk1, nat.succ n, by rw ← hk2; refl⟩), rcases h2 with ⟨h2, n, h3⟩, existsi n, apply subtype.eq, exact h3 end variable {α} section erase def erase (x y : α) : α := comprehension x (λ z, z ≠ y) theorem zmem_erase_iff : z ∈ erase x y ↔ z ∈ x ∧ z ≠ y := zmem_comprehension_iff theorem zmem_of_zmem_erase (H : z ∈ erase x y) : z ∈ x := (zmem_erase_iff.1 H).1 theorem ne_of_zmem_erase (H : z ∈ erase x y) : z ≠ y := (zmem_erase_iff.1 H).2 theorem zmem_erase_of_zmem_of_ne (H1 : z ∈ x) (H2 : z ≠ y) : z ∈ erase x y := zmem_erase_iff.2 ⟨H1, H2⟩ end erase section recursion variables (f A c : α) [is_function f] (H1 : dom f = prod ω A) (H2 : range f ⊆ A) (H3 : c ∈ A) -- {(x,y) ∈ ω × A | ∃ h : ω → A, h(∅) = c ∧ (∀ m ∈ x, h(m⁺) = f(m, h(m))) ∧ h(x) = y} def recursion : α := comprehension (prod ω A) (λ z, ∃ (h x y : α) [is_function h] (H4 : z = opair x y) (H5 : dom h = ω) (H6 : range h ⊆ A) (H7 : opair ∅ c ∈ h) (H8: ∀ m hm hsm, m ∈ x → opair m hm ∈ h → opair (opair m hm) hsm ∈ f → opair (succ m) hsm ∈ h), z ∈ h) include H3 theorem recursion.empty : opair ∅ c ∈ recursion f A c := begin let h : α := prod ω {c}, have hf : is_function h, { split, { intros z hz, dsimp [h] at hz, rw [prod, zmem_comprehension_iff] at hz, replace hz := hz.2, rcases hz with ⟨x', y', _, _, h'⟩, exact ⟨x', y', h'⟩ }, { intros x' hx', existsi c, rw [zmem_dom_iff] at hx', rcases hx' with ⟨y, hy⟩, dsimp [h] at hy ⊢, split, { exact zmem_prod (zmem_left_of_zmem_prod hy) zmem_singleton }, { intros y' hy', replace hy' := zmem_right_of_zmem_prod hy', rwa zmem_singleton_iff at hy' } } }, have H5 : dom h = ω, { apply is_extensional.ext, intro z, rw [zmem_dom_iff], split; intro h5, { cases h5 with y hy, exact zmem_left_of_zmem_prod hy }, { existsi c, exact zmem_prod h5 zmem_singleton } }, have H6 : range h ⊆ A, { intros z hz, rw [zmem_range_iff] at hz, cases hz with y hy, replace hy := zmem_right_of_zmem_prod hy, rw zmem_singleton_iff at hy, subst hy, exact H3 }, have H7 : opair ∅ c ∈ h, { exact zmem_prod empty_zmem_omega zmem_singleton }, rw [recursion, zmem_comprehension_iff], split, { exact zmem_prod empty_zmem_omega H3 }, { exact ⟨h, _, _, hf, rfl, H5, H6, H7, (λ m _ _ hm, false.elim $ not_zmem_empty hm), H7⟩ } end omit H3 include H1 H2 H3 theorem recursion.succ (h1 : opair x y ∈ recursion f A c) (h2 : opair (opair x y) z ∈ f) : opair (succ x) z ∈ recursion f A c := begin have h3 : opair x y ∈ prod ω A, { rw [← H1, zmem_dom_iff], exact ⟨z, h2⟩ }, have h5 : z ∈ A, { apply H2, rw [zmem_range_iff], exact ⟨_, h2⟩ }, rw [recursion, zmem_comprehension_iff] at h1, cases h1 with h1 h3, rcases h3 with ⟨h, x', y', hf, H4, H5, H6, H7, H8, H9⟩, have h4 : opair x y ∈ dom f, { rw H1, exact h1 }, let h' : α := comprehension (prod ω A) (λ w, ∀ m n, w = opair m n → ((m = succ x ∧ n = z) ∨ (m ≠ succ x ∧ w ∈ h))), have hf' : is_function h' := { eq_opair_of_zmem := λ z hz, begin dsimp [h'] at hz, rw [zmem_comprehension_iff] at hz, cases hz with hz1 hz2, rw [prod, zmem_comprehension_iff] at hz1, rcases hz1.2 with ⟨x'', y'', _, _, h''⟩, exact ⟨x'', y'', h''⟩ end, exists_unique := begin intros x hx, rw [zmem_dom_iff] at hx, cases hx with y hy, dsimp [h'] at hy, rw [zmem_comprehension_iff] at hy, cases hy with hy1 hy2, specialize hy2 x y rfl, cases hy2 with hy2 hy2; cases hy2 with hy2 hy3, { existsi y, split, { dsimp [h'], rw [zmem_comprehension_iff], split, exact hy1, intros m n hxy, cases opair.ext hxy with hxy1 hxy2, subst hxy1, subst hxy2, left, split, subst hy2, subst hy3 }, { intros z hz, dsimp [h'] at hz, rw [zmem_comprehension_iff] at hz, cases hz with hz1 hz2, specialize hz2 _ _ rfl, cases hz2 with hz2 hz2; cases hz2 with hz2 hz3, { subst hy3, subst hz3 }, { exfalso, exact hz2 hy2 } } }, { existsi y, split, { dsimp [h'], rw [zmem_comprehension_iff], split, exact hy1, intros m n hxy, cases opair.ext hxy with hxy1 hxy2, subst hxy1, subst hxy2, right, split, exact hy2, exact hy3 }, { intros z hz, dsimp [h'] at hz, rw [zmem_comprehension_iff] at hz, cases hz with hz1 hz2, specialize hz2 _ _ rfl, cases hz2 with hz2 hz2; cases hz2 with hz2 hz3, { exfalso, exact hy2 hz2 }, { have hf1 := hf.exists_unique, have hf2 : x ∈ dom h, { rw [zmem_dom_iff], existsi y, exact hy3 }, specialize hf1 _ hf2, exact unique_of_exists_unique hf1 hz3 hy3 } } } end }, have H5' : dom h' = ω, { apply is_extensional.ext, intro w, rw [zmem_dom_iff], split; intro hw, { cases hw with w hw, dsimp [h'] at hw, rw [zmem_comprehension_iff] at hw, cases hw with hw1 hw2, exact zmem_left_of_zmem_prod hw1 }, { cases classical.em (w = succ x) with hzk hzk, { existsi z, dsimp [h'], rw [zmem_comprehension_iff], split, { exact zmem_prod hw h5 }, { intros m n hmn, cases opair.ext hmn with hmn1 hmn2, subst hmn1, subst hmn2, left, split, exact hzk, refl } }, { have hf1 := hf.exists_unique, specialize hf1 w (H5.symm ▸ hw), rcases hf1 with ⟨w', hf1, hf2⟩, existsi w', dsimp [h'], rw [zmem_comprehension_iff], split, have hf3 : w' ∈ range h, { rw [zmem_range_iff], existsi w, exact hf1 }, { exact zmem_prod hw (H6 _ hf3) }, { intros m n hmn, cases opair.ext hmn with hmn1 hmn2, subst hmn1, subst hmn2, right, split, exact hzk, exact hf1 } } } }, have H6' : range h' ⊆ A, { intros z hz, rw [zmem_range_iff] at hz, cases hz with w hw, dsimp [h'] at hw, rw [zmem_comprehension_iff] at hw, cases hw with hw1 hw2, specialize hw2 _ _ rfl, cases hw2 with hw2 hw2; cases hw2 with hw2 hw3, { subst hw3, apply H2, rw [zmem_range_iff], exact ⟨_, h2⟩ }, { have hf1 : z ∈ range h, { rw [zmem_range_iff], existsi w, exact hw3 }, exact H6 _ hf1 } }, have H7' : opair ∅ c ∈ h', { dsimp [h'], rw [zmem_comprehension_iff], split, { exact zmem_prod empty_zmem_omega H3 }, { intros m n hmn, cases opair.ext hmn with hmn1 hmn2, subst hmn1, subst hmn2, right, split, { intro hmn1, have hmn2 : x ∈ succ x := zmem_succ, rw ← hmn1 at hmn2, exact not_zmem_empty hmn2 }, { exact H7 } } }, have H8' : ∀ (m hm hsm : α), m ∈ succ x → opair m hm ∈ h' → opair (opair m hm) hsm ∈ f → opair (succ m) hsm ∈ h', { intros m hm hsm hm1 hm2 hm3, rw zmem_succ_iff_eq_or_zmem at hm1, cases hm1 with hm1 hm1, { subst hm1, dsimp [h'], rw [zmem_comprehension_iff], have hm4 : hsm ∈ range f, { rw [zmem_range_iff], existsi _, exact hm3 }, have hm5 : m ∈ ω, { rw ← H5', rw [zmem_dom_iff], existsi _, exact hm2 }, split, { exact zmem_prod (succ_zmem_omega_of_zmem hm5) (H2 _ hm4) }, { intros m n hmn, cases opair.ext hmn with hmn1 hmn2, subst hmn1, subst hmn2, left, split, refl, dsimp [h'] at hm2, rw [zmem_comprehension_iff] at hm2, cases hm2 with hm8 hm6, specialize hm6 _ _ rfl, cases hm6 with hm6 hm6; cases hm6 with hm6 hm7, { exfalso, have hm9 : m ∈ succ m := zmem_succ, rw ← hm6 at hm9, exact not_zmem_self hm9 }, { have hf1 := hf.exists_unique, have hf2 : m ∈ dom h, { rw H5, exact hm5 }, specialize hf1 _ hf2, have hf3 := unique_of_exists_unique hf1 hm7 H9, subst hf3, have hf4 := is_function.exists_unique _ h4, exact unique_of_exists_unique hf4 hm3 h2 } } }, { cases opair.ext H4 with H41 H42, subst H41, subst H42, dsimp [h'], rw [zmem_comprehension_iff], have hm4 : hsm ∈ range f, { rw [zmem_range_iff], existsi _, exact hm3 }, have hm5 : m ∈ ω, { rw ← H5', rw [zmem_dom_iff], existsi _, exact hm2 }, split, { exact zmem_prod (succ_zmem_omega_of_zmem hm5) (H2 _ hm4) }, { intros m n hmn, cases opair.ext hmn with hmn1 hmn2, subst hmn1, subst hmn2, right, split, { intro hmk, replace hmk := succ.ext hmk, subst hmk, exact not_zmem_self hm1 }, { have hm6 : opair m hm ∈ h, { dsimp [h'] at hm2, rw [zmem_comprehension_iff] at hm2, cases hm2 with hm8 hm6, specialize hm6 _ _ rfl, cases hm6 with hm6 hm6; cases hm6 with hm6 hm7, { exfalso, subst hm6, apply not_zmem_and_zmem hm1 zmem_succ }, { exact hm7 } }, exact H8 _ _ _ hm1 hm6 hm3 } } } }, have H9' : opair (succ x) z ∈ h', { dsimp [h'], rw [zmem_comprehension_iff], split, { exact zmem_prod (succ_zmem_omega_of_zmem $ zmem_left_of_zmem_prod h3) h5 }, { intros m n hmn, cases opair.ext hmn with hmn1 hmn2, subst hmn1, subst hmn2, left, split, refl, refl } }, rw [recursion, zmem_comprehension_iff], split, { exact zmem_prod (succ_zmem_omega_of_zmem $ zmem_left_of_zmem_prod h3) h5 }, { exact ⟨h', _, _, hf', rfl, H5', H6', H7', H8', H9'⟩ } end theorem recursion.dom_omega (n : α) (Hn : n ∈ (ω:α)) : ∃! y, opair n y ∈ recursion f A c := begin apply @induction _ _ _ _ _ n Hn, { existsi c, split, { exact recursion.empty f A c H3 }, { intros y h1, rw [recursion, zmem_comprehension_iff] at h1, rcases h1 with ⟨h1, h, x', y', hf, H4, H5, H6, H7, H8, H9⟩, have hf1 := hf.exists_unique, specialize hf1 ∅ (H5.symm ▸ empty_zmem_omega), exact unique_of_exists_unique hf1 H9 H7 } }, { intros k hk h1, rcases h1 with ⟨y, h1, h2⟩, have h4 : opair k y ∈ dom f, { rw [recursion, zmem_comprehension_iff] at h1, rw H1, exact h1.1 }, existsi (eval f (opair k y)), split, { exact recursion.succ f A c H1 H2 H3 h1 (opair_eval_zmem h4) }, { intros z hz, apply eval_unique h4, rw [recursion, zmem_comprehension_iff] at hz, rcases hz with ⟨hz1, h'', x'', y'', hf'', H4'', H5'', H6'', H7'', H8'', H9''⟩, cases opair.ext H4'' with H41'' H42'', subst H41'', subst H42'', rw [recursion, zmem_comprehension_iff] at h1, cases h1 with h1 h3, rcases h3 with ⟨h, x', y', hf, H4, H5, H6, H7, H8, H9⟩, cases opair.ext H4 with H41 H42, subst H41, subst H42, cases omega.structure hk with h3 h3, { subst h3, have hf1 := hf.exists_unique, specialize hf1 ∅ (H5.symm ▸ empty_zmem_omega), have hf2 := unique_of_exists_unique hf1 H9 H7, subst hf2, specialize H8'' ∅ _ _ zmem_succ H7'' (opair_eval_zmem h4), have hf3 := hf''.exists_unique, specialize hf3 (succ ∅) (H5''.symm ▸ succ_zmem_omega_of_zmem empty_zmem_omega), have hf2 := unique_of_exists_unique hf3 H8'' H9'', subst hf2, apply opair_eval_zmem h4 }, { rcases h3 with ⟨k, H, hk⟩, subst hk, have h5 : succ k ∈ dom h'', { rw H5'', exact hk }, have h6 : opair (succ k) (@@eval _ h'' hf'' (succ k)) ∈ recursion f A c, { rw [recursion, zmem_comprehension_iff], split, { exact zmem_prod hk (H6'' _ $ @eval_zmem_range _ _ _ hf'' _ h5) }, { exact ⟨h'', _, _, hf'', rfl, H5'', H6'', H7'', (λ m hm hsm hm1 hm2 hm3, H8'' m hm hsm (zmem_succ_of_zmem hm1) hm2 hm3), @opair_eval_zmem _ _ _ hf'' _ h5⟩ } }, specialize H8'' _ _ _ zmem_succ (@opair_eval_zmem _ _ _ hf'' _ h5) (opair_eval_zmem (H1.symm ▸ zmem_prod hk (H6'' _ $ @eval_zmem_range _ _ _ hf'' _ h5))), specialize h2 _ h6, subst h2, have hf3 := hf''.exists_unique, specialize hf3 (succ (succ k)) (H5''.symm ▸ succ_zmem_omega_of_zmem hk), have hf2 := unique_of_exists_unique hf3 H8'' H9'', subst hf2, apply opair_eval_zmem h4 } } } end instance recursion.is_function : is_function (recursion f A c) := { eq_opair_of_zmem := λ z hz, let ⟨x, y, _, _, h⟩ := (zmem_comprehension_iff.1 (zmem_comprehension_iff.1 hz).1).2 in ⟨x, y, h⟩, exists_unique := λ x hx, begin rw [zmem_dom_iff] at hx, cases hx with w hw, rw [recursion, zmem_comprehension_iff] at hw, have hx : x ∈ ω := zmem_left_of_zmem_prod hw.1, exact recursion.dom_omega f A c H1 H2 H3 x hx end } theorem recursion.dom : dom (recursion f A c) = ω := begin apply is_extensional.ext, intro n, rw [zmem_dom_iff], split; intro hn, { cases hn with y hy, rw [recursion, zmem_comprehension_iff] at hy, exact zmem_left_of_zmem_prod hy.1 }, { rcases recursion.dom_omega f A c H1 H2 H3 n hn with ⟨y, h1, h2⟩, exact ⟨y, h1⟩ } end theorem recursion.range : range (recursion f A c) ⊆ A := begin intros z hz, rw [zmem_range_iff] at hz, cases hz with n hn, rw [recursion, zmem_comprehension_iff] at hn, exact zmem_right_of_zmem_prod hn.1 end -- recursion theorem: -- for any function f : ω×A → A and c ∈ A, there is a unique function h : ω → A such that: -- 1. h(0) = c -- 2. h(m⁺) = f(m,h(m)) -- (I left uniqueness unproved) end recursion section transitive_closure def transitive_closure (z : α) : α := sUnion $ replacement ω (λ x y, ∃ (A : α) (H1 : x ∈ (ω:α)) (H2 : ∀ p q r, opair p q ∈ A → opair p r ∈ A → q = r) (H3 : ∀ p q, opair p q ∈ A → p ∈ succ x) (H4 : ∀ p, p ∈ x → ∃ q, opair p q ∈ A) (H5 : opair ∅ z ∈ A) (H6 : ∀ p q, p ∈ x → opair p q ∈ A → opair (succ p) (sUnion q) ∈ A), opair x y ∈ A) theorem transitive_closure.aux.empty : ∃ (A : α) (H1 : (∅:α) ∈ (ω:α)) (H2 : ∀ (p q r : α), opair p q ∈ A → opair p r ∈ A → q = r) (H3 : ∀ (p q : α), opair p q ∈ A → p ∈ succ (∅:α)) (H4 : ∀ (p : α), p ∈ (∅:α) → (∃ (q : α), opair p q ∈ A)) (H5 : opair ∅ z ∈ A) (H6 : ∀ (p q : α), p ∈ (∅:α) → opair p q ∈ A → opair (succ p) (sUnion q) ∈ A), opair ∅ z ∈ A := begin have H2 : ∀ (p q r : α), opair p q ∈ {opair ∅ z} → opair p r ∈ {opair ∅ z} → q = r, { intros p q r hpq hpr, rw zmem_singleton_iff at hpq hpr, have h1 := (opair.ext hpq).2, have h2 := (opair.ext hpr).2, subst h1, subst h2 }, have H3 : ∀ (p q : α), opair p q ∈ {opair ∅ z} → p ∈ succ (∅:α), { intros p q h, rw zmem_singleton_iff at h, rw (opair.ext h).1, exact zmem_succ }, exact ⟨{opair ∅ z}, empty_zmem_omega, H2, H3, (λ p hp, false.elim $ not_zmem_empty hp), zmem_singleton, (λ p q hp, false.elim $ not_zmem_empty hp), zmem_singleton⟩ end theorem transitive_closure.aux.succ {k : α} (hk : k ∈ (ω:α)) : (∃ (A : α) (H1 : k ∈ (ω:α)) (H2 : ∀ (p q r : α), opair p q ∈ A → opair p r ∈ A → q = r) (H3 : ∀ (p q : α), opair p q ∈ A → p ∈ succ k) (H4 : ∀ (p : α), p ∈ k → (∃ (q : α), opair p q ∈ A)) (H5 : opair ∅ z ∈ A) (H6 : ∀ (p q : α), p ∈ k → opair p q ∈ A → opair (succ p) (sUnion q) ∈ A), opair k y ∈ A) → (∃ (A : α) (H1 : succ k ∈ (ω:α)) (H2 : ∀ (p q r : α), opair p q ∈ A → opair p r ∈ A → q = r) (H3 : ∀ (p q : α), opair p q ∈ A → p ∈ succ (succ k)) (H4 : ∀ (p : α), p ∈ succ k → (∃ (q : α), opair p q ∈ A)) (H5 : opair ∅ z ∈ A) (H6 : ∀ (p q : α), p ∈ succ k → opair p q ∈ A → opair (succ p) (sUnion q) ∈ A), opair (succ k) (sUnion y) ∈ A) := begin intro h1, rcases h1 with ⟨A, H1, H2, H3, H4, H5, H6, H7⟩, have H2' : ∀ (p q r : α), opair p q ∈ has_insert.insert (opair (succ k) (sUnion y)) A → opair p r ∈ has_insert.insert (opair (succ k) (sUnion y)) A → q = r, { intros p q r hpq hpr, rw zmem_insert_iff_eq_or_zmem at hpq hpr, cases hpq; cases hpr, { have h1 := (opair.ext hpq).2, have h2 := (opair.ext hpr).2, subst h1, subst h2 }, { exfalso, have h1 := (opair.ext hpq).1, subst h1, exact not_zmem_self (H3 _ _ hpr) }, { exfalso, have h1 := (opair.ext hpr).1, subst h1, exact not_zmem_self (H3 _ _ hpq) }, { exact H2 _ _ _ hpq hpr } }, have H3' : ∀ (p q : α), opair p q ∈ has_insert.insert (opair (succ k) (sUnion y)) A → p ∈ succ (succ k), { intros p q h, rw zmem_insert_iff_eq_or_zmem at h, cases h with h h, { rw (opair.ext h).1, exact zmem_succ }, { exact zmem_succ_of_zmem (H3 _ _ h) } }, have H4' : ∀ (p : α), p ∈ succ k → (∃ (q : α), opair p q ∈ has_insert.insert (opair (succ k) (sUnion y)) A), { intros p hp, rw zmem_succ_iff_eq_or_zmem at hp, cases hp with hp hp, { subst hp, existsi y, exact zmem_insert_of_zmem H7 }, { cases H4 p hp with q hq, exact ⟨q, zmem_insert_of_zmem hq⟩ } }, have H6' : ∀ (p q : α), p ∈ succ k → opair p q ∈ has_insert.insert (opair (succ k) (sUnion y)) A → opair (succ p) (sUnion q) ∈ has_insert.insert (opair (succ k) (sUnion y)) A, { intros p q hp hpq, rw zmem_succ_iff_eq_or_zmem at hp, rw zmem_insert_iff_eq_or_zmem at hpq, cases hp with hp hp; cases hpq with hpq hpq, { subst hp, exfalso, have h1 : p ∈ succ p := zmem_succ, rw ← (opair.ext hpq).1 at h1, exact not_zmem_self h1 }, { subst hp, rw H2 _ _ _ hpq H7, exact zmem_insert }, { exfalso, apply not_zmem_and_zmem hp, rw (opair.ext hpq).1, exact zmem_succ }, { exact zmem_insert_of_zmem (H6 _ _ hp hpq) } }, exact ⟨has_insert.insert (opair (succ k) (sUnion y)) A, succ_zmem_omega_of_zmem hk, H2', H3', H4', zmem_insert_of_zmem H5, H6', zmem_insert⟩ end theorem transitive_closure.aux : ∀ x, x ∈ (ω:α) → ∃! y, ∃ (A : α) (H1 : x ∈ (ω:α)) (H2 : ∀ p q r, opair p q ∈ A → opair p r ∈ A → q = r) (H3 : ∀ p q, opair p q ∈ A → p ∈ succ x) (H4 : ∀ p, p ∈ x → ∃ q, opair p q ∈ A) (H5 : opair ∅ z ∈ A) (H6 : ∀ p q, p ∈ x → opair p q ∈ A → opair (succ p) (sUnion q) ∈ A), opair x y ∈ A := begin apply induction, { existsi z, split, { exact transitive_closure.aux.empty }, { intros y hy, rcases hy with ⟨A, H1, H2, H3, H4, H5, H6, H7⟩, exact H2 _ _ _ H7 H5 } }, { intros k hk ih, rcases ih with ⟨y, h1, h2⟩, existsi sUnion y, split, { exact transitive_closure.aux.succ hk h1 }, { intros w hw, rcases hw with ⟨A', H1', H2', H3', H4', H5', H6', H7'⟩, cases H4' _ zmem_succ with q hq, have h := H2' _ _ _ H7' (H6' _ _ zmem_succ hq), subst h, congr, have H3'' : ∀ (p q_1 : α), opair p q_1 ∈ erase A' (opair (succ k) (sUnion q)) → p ∈ succ k, { intros p q h, have h1 := H3' _ _ (zmem_of_zmem_erase h), cases zmem_succ_iff_eq_or_zmem.1 h1 with h3 h3, { exfalso, subst h3, have h3 := H2' _ _ _ (H6' _ _ zmem_succ hq) (zmem_of_zmem_erase h), subst h3, exact ne_of_zmem_erase h rfl }, { exact h3 } }, have H4'' : ∀ (p : α), p ∈ k → (∃ (q_1 : α), opair p q_1 ∈ erase A' (opair (succ k) (sUnion q))), { intros p hp, cases H4' p (zmem_succ_of_zmem hp) with q hq, existsi q, apply zmem_erase_of_zmem_of_ne hq, intro h, rw (opair.ext h).1 at hp, exact not_zmem_and_zmem hp zmem_succ }, have H5'' : opair ∅ z ∈ erase A' (opair (succ k) (sUnion q)), { apply zmem_erase_of_zmem_of_ne H5', intro h, have h1 : k ∈ succ k := zmem_succ, rw ← (opair.ext h).1 at h1, exact not_zmem_empty h1 }, have H6'' : ∀ (p q_1 : α), p ∈ k → opair p q_1 ∈ erase A' (opair (succ k) (sUnion q)) → opair (succ p) (sUnion q_1) ∈ erase A' (opair (succ k) (sUnion q)), { intros p q hp hpq, apply zmem_erase_of_zmem_of_ne, { exact H6' _ _ (zmem_succ_of_zmem hp) (zmem_of_zmem_erase hpq) }, { intro h, rw succ.ext (opair.ext h).1 at hp, exact not_zmem_self hp } }, have H7'' : opair k q ∈ erase A' (opair (succ k) (sUnion q)), { apply zmem_erase_of_zmem_of_ne hq, intro h, have h1 : k ∈ succ k := zmem_succ, rw ← (opair.ext h).1 at h1, exact not_zmem_self h1 }, exact h2 q ⟨erase A' (opair (succ k) (sUnion q)), hk, λ p q r hpq hpr, H2' p q r (zmem_of_zmem_erase hpq) (zmem_of_zmem_erase hpr), H3'', H4'', H5'', H6'', H7''⟩ } } end theorem transitive_closure.aux.iff {w : α} : w ∈ transitive_closure z ↔ ∃ y, w ∈ y ∧ ∃ x, x ∈ (ω:α) ∧ ∃ (A : α) (H1 : x ∈ (ω:α)) (H2 : ∀ p q r, opair p q ∈ A → opair p r ∈ A → q = r) (H3 : ∀ p q, opair p q ∈ A → p ∈ succ x) (H4 : ∀ p, p ∈ x → ∃ q, opair p q ∈ A) (H5 : opair ∅ z ∈ A) (H6 : ∀ p q, p ∈ x → opair p q ∈ A → opair (succ p) (sUnion q) ∈ A), opair x y ∈ A := begin rw [transitive_closure], rw [zmem_sUnion_iff_zmem_zmem], split; intro h; rcases h with ⟨h1, h2, h3⟩; refine ⟨h1, h2, _⟩; rwa [zmem_replacement_iff] <|> rwa [zmem_replacement_iff] at h3; { intros A B C hab hac, have hab1 := hab, rcases hab1 with ⟨_, h, _⟩, exact unique_of_exists_unique (transitive_closure.aux _ h) hab hac } end variable z theorem transitive_closure.subset : z ⊆ transitive_closure z := λ w hw, transitive_closure.aux.iff.2 ⟨z, hw, ∅, empty_zmem_omega, transitive_closure.aux.empty⟩ instance transitive_closure.is_transitive : is_transitive (transitive_closure z) := { zmem_trans := begin intros m n hmn hn, rw transitive_closure.aux.iff at hn ⊢, rcases hn with ⟨y, hny, k, hk, hn⟩, refine ⟨_, zmem_sUnion_iff_zmem_zmem.2 ⟨n, hmn, hny⟩, _, succ_zmem_omega_of_zmem hk, transitive_closure.aux.succ hk hn⟩ end } theorem transitive_closure.UMP (w : α) (H : z ⊆ w) [is_transitive w] : transitive_closure z ⊆ w := begin intros x hx, rw [transitive_closure.aux.iff] at hx, rcases hx with ⟨y, hxy, k, hk, A, H1, H2, H3, H4, H5, H6, H7⟩, revert x y A, apply induction _ _ _ k hk, { intros x y A hxy H2 H3 H4 H5 H6 H7, specialize H2 _ _ _ H7 H5, subst H2, exact H _ hxy }, { clear hk H1 k, intros k hk ih x y A hxy H2 H3 H4 H5 H6 H7, cases H4 _ zmem_succ with q hq, have H2subst := H2 _ _ _ H7 (H6 _ _ zmem_succ hq), subst H2subst, rw zmem_sUnion_iff_zmem_zmem at hxy, rcases hxy with ⟨t, hxt, hty⟩, have H3' : ∀ (p q_1 : α), opair p q_1 ∈ erase A (opair (succ k) (sUnion q)) → p ∈ succ k, { intros p q h, have h1 := H3 _ _ (zmem_of_zmem_erase h), cases zmem_succ_iff_eq_or_zmem.1 h1 with h3 h3, { exfalso, subst h3, have h3 := H2 _ _ _ (H6 _ _ zmem_succ hq) (zmem_of_zmem_erase h), subst h3, exact ne_of_zmem_erase h rfl }, { exact h3 } }, have H4' : ∀ (p : α), p ∈ k → (∃ (q_1 : α), opair p q_1 ∈ erase A (opair (succ k) (sUnion q))), { intros p hp, cases H4 p (zmem_succ_of_zmem hp) with q hq, existsi q, apply zmem_erase_of_zmem_of_ne hq, intro h, rw (opair.ext h).1 at hp, exact not_zmem_and_zmem hp zmem_succ }, have H5' : opair ∅ z ∈ erase A (opair (succ k) (sUnion q)), { apply zmem_erase_of_zmem_of_ne H5, intro h, have h1 : k ∈ succ k := zmem_succ, rw ← (opair.ext h).1 at h1, exact not_zmem_empty h1 }, have H6' : ∀ (p q_1 : α), p ∈ k → opair p q_1 ∈ erase A (opair (succ k) (sUnion q)) → opair (succ p) (sUnion q_1) ∈ erase A (opair (succ k) (sUnion q)), { intros p q hp hpq, apply zmem_erase_of_zmem_of_ne, { exact H6 _ _ (zmem_succ_of_zmem hp) (zmem_of_zmem_erase hpq) }, { intro h, rw succ.ext (opair.ext h).1 at hp, exact not_zmem_self hp } }, have H7' : opair k q ∈ erase A (opair (succ k) (sUnion q)), { apply zmem_erase_of_zmem_of_ne hq, intro h, have h1 : k ∈ succ k := zmem_succ, rw ← (opair.ext h).1 at h1, exact not_zmem_self h1 }, specialize ih t q (erase A (opair (succ k) (sUnion q))) hty (λ p q r hpq hpr, H2 p q r (zmem_of_zmem_erase hpq) (zmem_of_zmem_erase hpr)) H3' H4' H5' H6' H7', exact is_transitive.zmem_trans _ _ hxt ih } end end transitive_closure def prod_assoc (x y z : α) : α := comprehension (prod (prod (prod x y) z) (prod x (prod y z))) (λ m, ∃ p q r, m = opair (opair (opair p q) r) (opair p (opair q r))) theorem prod_assoc.dom {x y z : α} : dom (prod_assoc x y z) = prod (prod x y) z := begin apply is_extensional.ext, intro m, rw zmem_dom_iff, split; intro h, { cases h with n h, rw [prod_assoc, zmem_comprehension_iff] at h, rcases h with ⟨h1, p, q, r, h2⟩, exact zmem_left_of_zmem_prod h1 }, { rw [prod, zmem_comprehension_iff] at h, rcases h with ⟨_, pq, r, hpq, hr, h⟩, subst h, rw zmem_comprehension_iff at hpq, rcases hpq with ⟨_, p, q, hp, hq, hpq⟩, subst hpq, existsi opair p (opair q r), rw [prod_assoc, zmem_comprehension_iff], refine ⟨zmem_prod (zmem_prod (zmem_prod hp hq) hr) (zmem_prod hp (zmem_prod hq hr)), _, _, _, rfl⟩ } end theorem prod_assoc.range {x y z : α} : range (prod_assoc x y z) = prod x (prod y z) := begin apply is_extensional.ext, intro m, rw zmem_range_iff, split; intro h, { cases h with n h, rw [prod_assoc, zmem_comprehension_iff] at h, rcases h with ⟨h1, p, q, r, h2⟩, exact zmem_right_of_zmem_prod h1 }, { rw [prod, zmem_comprehension_iff] at h, rcases h with ⟨_, p, qr, hp, hqr, h⟩, subst h, rw zmem_comprehension_iff at hqr, rcases hqr with ⟨_, q, r, hq, hr, hqr⟩, subst hqr, existsi opair (opair p q) r, rw [prod_assoc, zmem_comprehension_iff], refine ⟨zmem_prod (zmem_prod (zmem_prod hp hq) hr) (zmem_prod hp (zmem_prod hq hr)), _, _, _, rfl⟩ } end instance prod_assoc.is_injective {x y z : α} : is_injective (prod_assoc x y z) := { eq_opair_of_zmem := begin intros m h, rw [prod_assoc, zmem_comprehension_iff] at h, rcases h with ⟨h1, p, q, r, h2⟩, exact ⟨_, _, h2⟩ end, exists_unique := begin intros m h, rw zmem_dom_iff at h, cases h with n hn, existsi n, split, exact hn, intros n' hn', rw [prod_assoc, zmem_comprehension_iff] at hn, rcases hn with ⟨h1, p, q, r, h2⟩, rw [prod_assoc, zmem_comprehension_iff] at hn', rcases hn' with ⟨h1', p', q', r', h2'⟩, rw opair.iff at h2 h2', cases h2 with h2 h3, cases h2' with h2' h3', subst h2, subst h3, subst h3', rw [opair.iff, opair.iff] at h2', cases h2' with hpq hr, cases hpq with hp hq, subst hp, subst hq, subst hr end, injective := begin intros m m' n hm hm', rw [prod_assoc, zmem_comprehension_iff] at hm, rcases hm with ⟨h1, p, q, r, h2⟩, rw [prod_assoc, zmem_comprehension_iff] at hm', rcases hm' with ⟨h1', p', q', r', h2'⟩, rw opair.iff at h2 h2', cases h2 with h2 h3, cases h2' with h2' h3', subst h2, subst h2', subst h3, rw [opair.iff, opair.iff] at h3', rcases h3' with ⟨hp, hq, hr⟩, subst hp, subst hq, subst hr end } def hom (x y : α) : α := comprehension (powerset $ prod x y) (λ f, is_function f ∧ dom f = x) theorem zmem_hom_iff {f : α} : f ∈ hom x y ↔ is_function f ∧ dom f = x ∧ range f ⊆ y := begin rw [hom, zmem_comprehension_iff, zmem_powerset], split; intro hf; rcases hf with ⟨hf1, hf2, hf3⟩, { refine ⟨hf2, hf3, _⟩, intros z hz, rw zmem_range_iff at hz, cases hz with w hwz, exact zmem_right_of_zmem_prod (hf1 _ hwz) }, { refine ⟨_, hf1, hf2⟩, intros z hz, have hf4 := hf1.eq_opair_of_zmem, specialize hf4 _ hz, rcases hf4 with ⟨m, n, hf4⟩, subst hf4, have hf4 : m ∈ dom f, { rw zmem_dom_iff, exact ⟨_, hz⟩ }, have hf5 : n ∈ range f, { rw zmem_range_iff, exact ⟨_, hz⟩ }, rw hf2 at hf4, replace hf5 := hf3 _ hf5, exact zmem_prod hf4 hf5 } end def prod_adjoint_hom (x y z : α) : α := comprehension (prod (hom (prod x y) z) (hom x (hom y z))) (λ m, ∃ (f g : α) (H : m = opair f g), ∀ p h, opair p h ∈ g → ∀ q r, opair (opair p q) r ∈ f → opair q r ∈ h) theorem prod_adjoint_hom.dom {x y z : α} : dom (prod_adjoint_hom x y z) = hom (prod x y) z := begin apply is_extensional.ext, intro m, rw zmem_dom_iff, split; intro h, { cases h with n h, rw [prod_adjoint_hom, zmem_comprehension_iff] at h, rcases h with ⟨h1, p, q, r, h2⟩, exact zmem_left_of_zmem_prod h1 }, { have h := h, rw zmem_hom_iff at h, rcases h with ⟨h1, h2, h3⟩, let m' : α := comprehension (prod x (hom y z)) (λ n, ∀ p g, n = opair p g → ∀ q r, opair q r ∈ g → opair (opair p q) r ∈ m), have h1' : is_function m', { split, { intros z hz, rw [zmem_comprehension_iff, prod, zmem_comprehension_iff] at hz, rcases hz.1.2 with ⟨_, _, _, _, hz1⟩, exact ⟨_, _, hz1⟩ }, { intros x' hx', rw [zmem_dom_iff] at hx', cases hx' with y' hy', existsi y', split, { exact hy' }, { intros y'' hy'', rw [zmem_comprehension_iff, prod, zmem_comprehension_iff] at hy', rcases hy' with ⟨hy1', hy2'⟩, rcases hy1' with ⟨_, p', q', hp', hq', h'⟩, rcases opair.ext h' with ⟨h1', h2'⟩, subst h1', subst h2', clear h', rw zmem_hom_iff at hq', rcases hq' with ⟨hy1', hy3', hy4'⟩, cases hy1' with hy5' hy6', specialize hy2' _ _ rfl, rw [zmem_comprehension_iff, prod, zmem_comprehension_iff] at hy'', rcases hy'' with ⟨hy1'', hy2''⟩, rcases hy1'' with ⟨_, p'', q'', hp'', hq'', h''⟩, rcases opair.ext h'' with ⟨h1'', h2''⟩, subst h1'', subst h2'', clear h'', rw zmem_hom_iff at hq'', rcases hq'' with ⟨hy1'', hy3'', hy4''⟩, cases hy1'' with hy5'' hy6'', specialize hy2'' _ _ rfl, apply is_extensional.ext, intro z', cases h1 with h4 h5, split; intro hz', { specialize hy5'' _ hz', rcases hy5'' with ⟨q'', r'', h⟩, subst h, specialize hy2'' _ _ hz', have hz1' : q'' ∈ dom y'', { rw zmem_dom_iff, exact ⟨_, hz'⟩ }, rw [hy3'', ← hy3'] at hz1', specialize hy6' _ hz1', rcases hy6' with ⟨r', hy6', _⟩, specialize hy2' _ _ hy6', have hz2' : opair x' q'' ∈ dom m, { rw zmem_dom_iff, exact ⟨_, hy2'⟩ }, specialize h5 _ hz2', replace h5 := unique_of_exists_unique h5 hy2'' hy2', subst h5, exact hy6' }, { specialize hy5' _ hz', rcases hy5' with ⟨q', r', h⟩, subst h, specialize hy2' _ _ hz', have hz1' : q' ∈ dom y', { rw zmem_dom_iff, exact ⟨_, hz'⟩ }, rw [hy3', ← hy3''] at hz1', specialize hy6'' _ hz1', rcases hy6'' with ⟨r'', hy6'', _⟩, specialize hy2'' _ _ hy6'', have hz2' : opair x' q' ∈ dom m, { rw zmem_dom_iff, exact ⟨_, hy2'⟩ }, specialize h5 _ hz2', replace h5 := unique_of_exists_unique h5 hy2'' hy2', subst h5, exact hy6'' } } } }, have h2' : dom m' = x, { apply is_extensional.ext, intro p, rw [zmem_dom_iff], split; intro hp, { cases hp with g hg, rw [zmem_comprehension_iff] at hg, exact zmem_left_of_zmem_prod hg.1 }, { let g : α := comprehension (prod y z) (λ n, ∀ q r, n = opair q r → opair (opair p q) r ∈ m), cases h1 with h4 h5, have hg1 : is_function g, { split, { intros z hz, rw [zmem_comprehension_iff, prod, zmem_comprehension_iff] at hz, rcases hz.1.2 with ⟨_, _, _, _, hz1⟩, exact ⟨_, _, hz1⟩ }, { intros q hq, rw zmem_dom_iff at hq, cases hq with r hr, existsi r, split, { exact hr }, { intros r' hr', rw [zmem_comprehension_iff] at hr hr', rw h2 at h5, specialize h5 _ (zmem_prod hp $ zmem_left_of_zmem_prod hr.1), exact unique_of_exists_unique h5 (hr'.2 _ _ rfl) (hr.2 _ _ rfl) } } }, have hg2 : dom g = y, { apply is_extensional.ext, intro q, rw zmem_dom_iff, split; intro hq, { cases hq with r hr, rw [zmem_comprehension_iff] at hr, exact zmem_left_of_zmem_prod hr.1 }, { have h6 : opair p q ∈ dom m, { rw h2, exact zmem_prod hp hq }, specialize h5 _ h6, rcases h5 with ⟨r, hr1, hr2⟩, have hr : r ∈ z, { apply h3, rw zmem_range_iff, exact ⟨_, hr1⟩ }, existsi r, rw zmem_comprehension_iff, split, { exact zmem_prod hq hr }, { intros _ _ hqr, cases opair.ext hqr with hqr1 hqr2, subst hqr1, subst hqr2, clear hqr, exact hr1 } } }, have hg3 : range g ⊆ z, { intros r hr, rw zmem_range_iff at hr, cases hr with q hq, rw zmem_comprehension_iff at hq, exact zmem_right_of_zmem_prod hq.1 }, existsi g, rw zmem_comprehension_iff, split, { apply zmem_prod hp, rw zmem_hom_iff, exact ⟨hg1, hg2, hg3⟩ }, { intros _ _ hpg, cases opair.ext hpg with hpg1 hpg2, subst hpg1, subst hpg2, clear hpg, intros q r hqr, rw zmem_comprehension_iff at hqr, exact hqr.2 _ _ rfl } } }, have h3' : range m' ⊆ hom y z, { intros g hg, rw zmem_range_iff at hg, cases hg with p hg, rw zmem_comprehension_iff at hg, exact zmem_right_of_zmem_prod hg.1 }, existsi m', rw [prod_adjoint_hom, zmem_comprehension_iff], split, { apply zmem_prod h, rw zmem_hom_iff, exact ⟨h1', h2', h3'⟩ }, { refine ⟨_, _, rfl, _⟩, intros p g hp q r hpqr, rw zmem_comprehension_iff at hp, have hg := zmem_right_of_zmem_prod hp.1, rw zmem_hom_iff at hg, rcases hg with ⟨hg1, hg2, hg3⟩, cases hg1 with hg4 hg5, rw hg2 at hg5, have hpq : opair p q ∈ prod x y, { rw [← h2, zmem_dom_iff], exact ⟨_, hpqr⟩ }, specialize hg5 _ (zmem_right_of_zmem_prod hpq), rcases hg5 with ⟨r', hr1', hr2'⟩, have hpqr' := hp.2 _ _ rfl _ _ hr1', cases h1 with h4 h5, rw h2 at h5, replace h5 := unique_of_exists_unique (h5 _ hpq) hpqr' hpqr, subst h5, exact hr1' } } end theorem prod_adjoint_hom.range {x y z : α} : range (prod_adjoint_hom x y z) = hom x (hom y z) := sorry instance prod_adjoint_hom.is_injective {x y z : α} : is_injective (prod_adjoint_hom x y z) := sorry -- maximum usability theorem prod_adjoint_hom.prop {x y z f g p q : α} [is_function f] [is_function g] (H1 : f ∈ dom (prod_adjoint_hom x y z)) (H2 : eval (prod_adjoint_hom x y z) f = g) (H3 : opair p q ∈ dom f) (H4 : p ∈ dom g) (H5 : q ∈ dom (eval g p)) [is_function (eval g p)] : eval f (opair p q) = eval (eval g p) q := sorry end zf end zfc
dac5a7e025e1f9b2d1a8971e6ea28aad03395dac
98000ddc36f1ec26addea0df1853c69fa0e71d67
/real.lean
f66819d778b231f74433826ade067f8e80637b5b
[]
no_license
SCRK16/Intuitionism
50b7b5ed780a75c4ff1339c3d36f1133b8acdfe3
a3d9920ae056b39a66e37d1d0e03d246bca1e961
refs/heads/master
1,670,199,869,808
1,598,045,061,000
1,598,045,061,000
254,657,585
1
0
null
1,590,754,909,000
1,586,529,604,000
Lean
UTF-8
Lean
false
false
15,199
lean
/- This file defines the constructive real numbers ℛ, defined by sequences of shrinking and dwindling rational segments -/ import ..Intuitionism.segment /-- We say that a sequence of segments is 'shrinking' if each segment is contained within its predecessor -/ def shrinking (r : ℕ → 𝕊) := ∀ n, r (n + 1) ⊑ r n /-- We say that a sequence of segments is 'dwindling' if we can make the segments arbitrarily small -/ def dwindling (r : ℕ → 𝕊) := ∀ q : ℚ, q > 0 → ∃ n : ℕ, (r n).snd - (r n).fst < q /-- The definition of real sequences ℛ, representing the real numbers (Called 'real_seq' here to not interfere with the classical real numbers, which are already defined in Lean using Cauchy sequences) A real sequence is a sequence of rational segments that shrinks and dwindles -/ def real_seq := {r : ℕ → 𝕊 // shrinking r ∧ dwindling r} notation `ℛ` := real_seq namespace real_seq /-- Used to extract the underlying sequence of rational segments -/ def seq (r : ℛ) : ℕ → 𝕊 := subtype.val r -- We can turn a real segment into a sequence of rationals by only taking the first position def fst (r : ℛ) : ℕ → ℚ := λ n, (r.seq n).fst -- We can turn a real segment into a sequence of rationals by only taking the second position def snd (r : ℛ) : ℕ → ℚ := λ n, (r.seq n).snd lemma shrinking (r : ℛ) : shrinking r.val := (subtype.property r).elim_left lemma dwindling (r : ℛ) : dwindling r.val := (subtype.property r).elim_right theorem contained_of_le (r : ℛ) {n m : ℕ} (h₁ : n ≤ m) : r.seq m ⊑ r.seq n := begin induction h₁ with d hd, {-- need to prove: seq r n ⊑ seq r n refl, }, {-- need to prove: seq r (nat.succ d) ⊑ seq r n transitivity (seq r d), {-- need to prove: seq r (nat.succ d) ⊑ seq r d exact r.shrinking d, }, {-- need to prove: seq r d ⊑ seq r n exact h₁_ih, } } end def lt (x y : ℛ) : Prop := ∃ n : ℕ, x.seq n < y.seq n infix `<` := lt def le (x y : ℛ) : Prop := ∀ n : ℕ, x.seq n ≤ y.seq n infix `≤` := le def apart (x y : ℛ) : Prop := x < y ∨ y < x infix `#` := apart def eq (x y : ℛ) : Prop := ∀ n : ℕ, x.seq n ≈ y.seq n infix `='`:50 := eq def ne (x y : ℛ) : Prop := ¬ x =' y infix `≠'`:50 := ne @[trans] theorem lt_trans (x y z : ℛ) (h₁ : x < y) (h₂ : y < z) : x < z := begin cases h₁ with n hn, cases h₂ with m hm, use max m n, transitivity seq y (max m n), {-- need to prove: seq x (max m n) < seq y (max m n) have h₁ := contained_of_le x (le_max_right m n), have h₂ := contained_of_le y (le_max_right m n), apply lt_of_le_of_lt h₁.elim_right, apply lt_of_lt_of_le hn, exact h₂.elim_left, }, {-- need to prove: seq y (max m n) < seq z (max m n) have h₁ := contained_of_le y (le_max_left m n), have h₂ := contained_of_le z (le_max_left m n), apply lt_of_le_of_lt h₁.elim_right, apply lt_of_lt_of_le hm, exact h₂.elim_left, } end lemma lt_or_lt_from_sub_lt_sub {a b c d : ℚ} (h : a - b < c - d) : a < c ∨ d < b := begin have hac := lt_trichotomy a c, cases hac with hl hr, {-- case: a < c left, exact hl, }, {-- case: a = c ∨ c < a right, cases hr with heq hlt, {-- case: a = c rwa [heq, sub_eq_add_neg, sub_eq_add_neg, add_lt_add_iff_left, neg_lt_neg_iff] at h, }, {-- case: c < a rw ← sub_lt_zero, transitivity (c-a), {-- need to prove: d - b < c - a rwa [lt_sub_iff_add_lt', ← add_sub_assoc, sub_lt_iff_lt_add', ← lt_sub_iff_add_lt, add_sub_assoc, add_comm, ← sub_lt_iff_lt_add] at h, }, {-- need to prove: c - a < 0 rw ← sub_lt_zero at hlt, exact hlt, } } } end theorem lt_cotrans (x y z : ℛ) (h₁ : x < y) : x < z ∨ z < y := begin cases h₁ with n hn, rwa [segment.lt, ← sub_pos, ← gt_from_lt] at hn, cases z.dwindling (segment.fst (seq y n) - segment.snd (seq x n)) hn with m hm, cases lt_or_lt_from_sub_lt_sub hm with zlty xltz, {-- case: z.snd m < y.fst n right, use max m n, have h₁ := contained_of_le z (le_max_left m n), have h₂ := contained_of_le y (le_max_right m n), apply lt_of_le_of_lt h₁.elim_right, exact lt_of_lt_of_le zlty h₂.elim_left, }, {-- case: x.snd n < z.fst m left, use max m n, have h₁ := contained_of_le z (le_max_left m n), have h₂ := contained_of_le x (le_max_right m n), apply lt_of_le_of_lt h₂.elim_right, exact lt_of_lt_of_le xltz h₁.elim_left, } end theorem apart_cotrans (x y z : ℛ) (h : x # y) : x # z ∨ z # y := begin cases h with h₁ h₂, {-- case: x < y cases lt_cotrans x y z h₁ with hz hz, {-- case: x < z left, left, exact hz, }, {-- case: z < y right, left, exact hz, } }, {-- case: case y < x cases lt_cotrans y x z h₂ with hz hz, {-- case: y < z right, right, exact hz, }, {-- case: z < x left, right, exact hz, } } end theorem le_iff_not_lt (x y : ℛ) : x ≤ y ↔ ¬ y < x := begin split, {-- need to prove: x ≤ y → ¬ y < x intros h₁ h₂, cases h₂ with n hn, have hn₁ := h₁ n, rw segment.le_iff_not_lt at hn₁, exact hn₁ hn, }, {-- need to prove: ¬ y < x → x ≤ y intros h n, rw segment.le_iff_not_lt, revert n, exact forall_not_of_not_exists h, } end theorem eq_of_le_of_le (x y : ℛ) : x ≤ y → y ≤ x → x =' y := begin intros hxy hyx n, split, {-- need to prove: seq x n ≤ seq y n exact hxy n, }, {-- need to prove: seq y n ≤ seq x n exact hyx n, } end @[trans] theorem le_trans (x y z : ℛ) (h₁ : x ≤ y) (h₂ : y ≤ z) : x ≤ z := begin rw le_iff_not_lt at *, intro zltx, cases lt_cotrans z x y zltx with hz hz, {-- case: z < y exact h₂ hz, }, {-- case: y < x exact h₁ hz, } end @[refl] theorem le_refl (x : ℛ) : x ≤ x := begin intro n, refl, end theorem eq_iff_not_apart (x y : ℛ) : x =' y ↔ ¬x # y := begin split, {-- need to prove: x = y → ¬ x # y intros h₁ h₂, cases h₂ with xlty yltx, {-- case: x < y cases xlty with n hn, have hn₁ := h₁ n, rw segment.lt_iff_not_le at hn, exact hn hn₁.elim_right, }, {-- case: y < x cases yltx with n hn, have hn₁ := h₁ n, rw segment.lt_iff_not_le at hn, exact hn hn₁.elim_left, } }, {-- need to prove: ¬ x # y → x = y intros h n, rw apart at h, rw segment.touches, rw not_or_distrib at h, split, {-- need to prove: seq x n ≤ seq y n rw segment.le_iff_not_lt, have h₁ := forall_not_of_not_exists h.elim_right n, exact h₁, }, {-- need to prove: seq y n ≤ seq x n rw segment.le_iff_not_lt, have h₂ := forall_not_of_not_exists h.elim_left n, exact h₂, } } end @[trans] theorem eq_trans (x y z: ℛ) (h₁ : x =' y) (h₂ : y =' z) : x =' z := begin rw eq_iff_not_apart, intro h₃, cases apart_cotrans x z y h₃ with xay yaz, {-- case: x # y rw eq_iff_not_apart at h₁, exact h₁ xay, }, {-- case: y # z rw eq_iff_not_apart at h₂, exact h₂ yaz, } end @[symm] theorem eq_symm (x y : ℛ) : x =' y ↔ y =' x := begin repeat {rw eq}, simp [segment.touches_symm], end @[refl] theorem eq_refl (x : ℛ) : x =' x := begin intro n, refl, end theorem le_stable (x y : ℛ) : ¬¬x ≤ y → x ≤ y := begin rw le_iff_not_lt, exact not_of_not_not_not, end theorem eq_stable (x y : ℛ) : ¬¬x =' y → x =' y := begin rw eq_iff_not_apart, exact not_of_not_not_not, end /-- The inclusion from ℚ into ℛ -/ def inclusion_const (q : ℚ) : ℛ := subtype.mk (λ _ , segment.inclusion q) begin split, {-- need to prove: the defined real_seq is shrinking intro n, refl, }, {-- need to prove: the defined real_seq is dwindling intros e he, use 0, rw gt_iff_lt at he, apply lt_of_le_of_lt _ he, apply le_of_eq, rw sub_eq_zero, refl, } end @[instance] def has_zero : has_zero ℛ := { zero := inclusion_const 0 } lemma zero : 0 = inclusion_const 0 := rfl /-- The definition of + on real sequences -/ def add (x y : ℛ) : ℛ := subtype.mk (λ n, segment.add (x.seq n) (y.seq n)) begin have hx := subtype.property x, have hy := subtype.property y, split, {-- need to prove: shrinking intro n, split, { apply add_le_add, exact (hx.elim_left n).elim_left, exact (hy.elim_left n).elim_left, }, { apply add_le_add, exact (hx.elim_left n).elim_right, exact (hy.elim_left n).elim_right, } }, {-- need to prove: dwindling intros q hq, have hq2 : q / 2 > 0, by { rw gt_iff_lt, apply div_pos, exact gt_iff_lt.elim_left hq, exact zero_lt_two, }, cases hx.elim_right (q / 2) hq2 with xn hxn, cases hy.elim_right (q / 2) hq2 with yn hyn, use max xn yn, simp [add_sub_comm, segment.add, segment.fst, segment.snd], have hqa : (q / 2) + (q / 2) = q, by { rw ← mul_two, rw div_mul_cancel, exact two_ne_zero, }, rw ← hqa, apply add_lt_add, {-- need to prove: snd (x.seq (max xn yn)) - fst (x.seq (max xn yn)) < q / 2 have hm : segment.snd (seq x (max xn yn)) - segment.fst (seq x (max xn yn)) ≤ (segment.snd (x.val xn) - segment.fst (x.val xn)), by {-- need to prove: snd - fst of x.seq (max xn yn) < snd - fst of x.seq xn apply segment.contained_bounds_le, apply contained_of_le _ (le_max_left _ _), }, exact lt_of_le_of_lt hm hxn, }, { have hm : segment.snd (seq y (max xn yn)) - segment.fst (seq y (max xn yn)) ≤ (segment.snd (y.val yn) - segment.fst (y.val yn)), by {-- need to prove: snd - fst of x.seq (max xn yn) < snd - fst of x.seq xn apply segment.contained_bounds_le, exact contained_of_le _ (le_max_right _ _), }, exact lt_of_le_of_lt hm hyn, } } end theorem add_assoc {x y z : ℛ} : add (add x y) z =' add x (add y z) := begin intro n, split, repeat {simp [seq, add, segment.add_assoc]}, end theorem add_comm {x y : ℛ} : add x y =' add y x := begin intro n, split, repeat {simp [seq, add, segment.add_comm]}, end theorem add_zero {x : ℛ} : add x 0 =' x := begin intro n, simp [zero, add, inclusion_const, seq, segment.add, segment.fst, segment.snd, segment.inclusion, segment.touches], end theorem zero_add {x : ℛ} : add 0 x =' x := begin transitivity (add x 0), exact add_comm, exact add_zero, end theorem eq_implies_add_eq_add {x y z : ℛ} : y =' z → add x y =' add x z := begin intros h n, have hn := h n, split, {-- need to prove: seq (add x y) n≤seq (add x z) n simp [seq, add, segment.le, segment.fst, segment.snd, segment.add], apply add_le_add, exact subtype.property (x.val n), exact hn.elim_left, }, { simp [seq, add, segment.le, segment.fst, segment.snd, segment.add], apply add_le_add, exact subtype.property (x.val n), exact hn.elim_right, } end def neg (x : ℛ) : ℛ := subtype.mk (λ n, (x.val n).neg) begin split, {-- shrinking intro n, split, { -- use: segment.snd (x.val (n + 1)) ≤ segment.snd (x.val n) simp [segment.fst, segment.fst, segment.neg, segment.neg, neg_le_neg_iff], exact ((subtype.property x).elim_left n).elim_right, }, {-- use: segment.fst (x.val n) ≤ segment.fst (x.val (n + 1)) simp [segment.snd, segment.snd, segment.neg, segment.neg, neg_le_neg_iff], exact ((subtype.property x).elim_left n).elim_left, } }, {-- dwindling intros q hq, have hx := (subtype.property x).elim_right q hq, cases hx with xn hxn, use xn, have h : segment.snd ((λ (n : ℕ), segment.neg (x.val n)) xn) - segment.fst ((λ (n : ℕ), segment.neg (x.val n)) xn) = segment.snd (x.val xn) - segment.fst (x.val xn), by simp [segment.snd, segment.fst, segment.neg], rw h, exact hxn, } end def sub (x y : ℛ) : ℛ := add x (neg y) theorem sub_self_eq_zero (x : ℛ) : sub x x =' 0 := begin rwa [zero, inclusion_const], intro n, simp [sub, add, neg, seq, segment.add, segment.neg, segment.fst, segment.snd, segment.touches, segment.inclusion], split, {-- sub x x ≤ 0 simp [segment.le, segment.snd, segment.fst], exact (subtype.property (x.seq n)), --use: (x.seq n) is a segment }, {-- 0 ≤ sub x x simp [segment.le, segment.snd, segment.fst], rwa [← sub_eq_add_neg, le_sub, sub_zero], exact (subtype.property (x.seq n)), --use: (x.seq n) is a segment } end theorem forall_exists_additive_inverse : ∀ x : ℛ, ∃ y : ℛ, add x y =' 0 := begin intro x, use neg x, rw ← sub, exact sub_self_eq_zero x, end -- In traditional notation: (x + y) - y = x theorem sub_add (x y : ℛ) : sub (add x y) y =' x := begin transitivity add x (add y (neg y)), exact add_assoc, transitivity add x 0, {-- need to prove: add x (sub y y) =' add x 0 exact eq_implies_add_eq_add (sub_self_eq_zero y), }, exact add_zero, end theorem sub_add_comm {x y z : ℛ} : sub (add x y) z =' add x (sub y z) := add_assoc end real_seq
08115ce3b6c18bba7f738b8a75b822037381a2bc
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/limits/cones.lean
781de54f6bfae502d6f9b49d8805513bf649e35a
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
17,023
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, Floris van Doorn -/ import category_theory.const import category_theory.yoneda universes v u u' -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] open category_theory open category_theory.category open category_theory.functor open opposite namespace category_theory namespace functor variables {J C} (F : J ⥤ C) /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ def cones : Cᵒᵖ ⥤ Type v := (const J).op ⋙ (yoneda.obj F) lemma cones_obj (X : Cᵒᵖ) : F.cones.obj X = ((const J).obj (unop X) ⟶ F) := rfl @[simp] lemma cones_map_app {X₁ X₂ : Cᵒᵖ} (f : X₁ ⟶ X₂) (t : F.cones.obj X₁) (j : J) : (F.cones.map f t).app j = f.unop ≫ t.app j := rfl /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ def cocones : C ⥤ Type v := const J ⋙ coyoneda.obj (op F) lemma cocones_obj (X : C) : F.cocones.obj X = (F ⟶ (const J).obj X) := rfl @[simp] lemma cocones_map_app {X₁ X₂ : C} (f : X₁ ⟶ X₂) (t : F.cocones.obj X₁) (j : J) : (F.cocones.map f t).app j = t.app j ≫ f := rfl end functor section variables (J C) /-- Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of cones with a given cone point. -/ @[simps] def cones : (J ⥤ C) ⥤ (Cᵒᵖ ⥤ Type v) := { obj := functor.cones, map := λ F G f, whisker_left (const J).op (yoneda.map f) } /-- Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of cocones with a given cocone point. -/ @[simps] def cocones : (J ⥤ C)ᵒᵖ ⥤ (C ⥤ Type v) := { obj := λ F, functor.cocones (unop F), map := λ F G f, whisker_left (const J) (coyoneda.map f) } end namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cones.obj X`. -/ structure cone (F : J ⥤ C) := (X : C) (π : (const J).obj X ⟶ F) @[simp] lemma cone.w {F : J ⥤ C} (c : cone F) {j j' : J} (f : j ⟶ j') : c.π.app j ≫ F.map f = c.π.app j' := by convert ←(c.π.naturality f).symm; apply id_comp /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cocones.obj X`. -/ structure cocone (F : J ⥤ C) := (X : C) (ι : F ⟶ (const J).obj X) @[simp] lemma cocone.w {F : J ⥤ C} (c : cocone F) {j j' : J} (f : j ⟶ j') : F.map f ≫ c.ι.app j' = c.ι.app j := by convert ←(c.ι.naturality f); apply comp_id variables {F : J ⥤ C} namespace cone def equiv (F : J ⥤ C) : cone F ≅ Σ X, F.cones.obj X := { hom := λ c, ⟨op c.X, c.π⟩, inv := λ c, { X := unop c.1, π := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } @[simp] def extensions (c : cone F) : yoneda.obj c.X ⟶ F.cones := { app := λ X f, ((const J).map f) ≫ c.π } /-- A map to the vertex of a cone induces a cone by composition. -/ @[simp] def extend (c : cone F) {X : C} (f : X ⟶ c.X) : cone F := { X := X, π := c.extensions.app (op X) f } @[simp] lemma extend_π (c : cone F) {X : Cᵒᵖ} (f : unop X ⟶ c.X) : (extend c f).π = c.extensions.app X f := rfl @[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) := { X := c.X, π := whisker_left E c.π } end cone namespace cocone def equiv (F : J ⥤ C) : cocone F ≅ Σ X, F.cocones.obj X := { hom := λ c, ⟨c.X, c.ι⟩, inv := λ c, { X := c.1, ι := c.2 }, hom_inv_id' := begin ext, cases x, refl, end, inv_hom_id' := begin ext, cases x, refl, end } @[simp] def extensions (c : cocone F) : coyoneda.obj (op c.X) ⟶ F.cocones := { app := λ X f, c.ι ≫ (const J).map f } /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simp] def extend (c : cocone F) {X : C} (f : c.X ⟶ X) : cocone F := { X := X, ι := c.extensions.app X f } @[simp] lemma extend_ι (c : cocone F) {X : C} (f : c.X ⟶ X) : (extend c f).ι = c.extensions.app X f := rfl @[simps] def whisker {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : cocone (E ⋙ F) := { X := c.X, ι := whisker_left E c.ι } end cocone @[ext] structure cone_morphism (A B : cone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, hom ≫ B.π.app j = A.π.app j . obviously) restate_axiom cone_morphism.w' attribute [simp] cone_morphism.w @[simps] instance cone.category : category.{v} (cone F) := { hom := λ A B, cone_morphism A B, comp := λ X Y Z f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [assoc, g.w, f.w] }, id := λ B, { hom := 𝟙 B.X } } namespace cones /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ @[ext, simps] def ext {c c' : cone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.π.app j = φ.hom ≫ c'.π.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.inv_comp_eq.mpr (w j) } } @[simps] def postcompose {G : J ⥤ C} (α : F ⟶ G) : cone F ⥤ cone G := { obj := λ c, { X := c.X, π := c.π ≫ α }, map := λ c₁ c₂ f, { hom := f.hom, w' := by intro; erw ← category.assoc; simp [-category.assoc] } } def postcompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) def postcompose_id : postcompose (𝟙 F) ≅ 𝟭 (cone F) := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) @[simps] def postcompose_equivalence {G : J ⥤ C} (α : F ≅ G) : cone F ≌ cone G := { functor := postcompose α.hom, inverse := postcompose α.inv, unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy) } /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cone F` to `cone (E ⋙ F)`. -/ @[simps] def whiskering {K : Type v} [small_category K] (E : K ⥤ J) : cone F ⥤ cone (E ⋙ F) := { obj := λ c, c.whisker E, map := λ c c' f, { hom := f.hom, } } /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simps] def whiskering_equivalence {K : Type v} [small_category K] (e : K ≌ J) : cone F ≌ cone (e.functor ⋙ F) := { functor := whiskering e.functor, inverse := whiskering e.inverse ⋙ postcompose ((functor.associator _ _ _).inv ≫ (whisker_right (e.counit_iso).hom F) ≫ (functor.left_unitor F).hom), unit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cones.ext (iso.refl _) (begin intro k, have t := s.π.naturality (e.unit_inv.app k), dsimp at t, simp only [←e.counit_functor k, id_comp] at t, dsimp, simp [t], end)) (by tidy), } /-- The categories of cones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ def equivalence_of_reindexing {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cone F ≌ cone G := (whiskering_equivalence e).trans (postcompose_equivalence α) @[simp] lemma equivalence_of_reindexing_functor_obj {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) (c : cone F) : (equivalence_of_reindexing e α).functor.obj c = (postcompose α.hom).obj (cone.whisker e.functor c) := rfl section variable (F) @[simps] def forget : cone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } variables {D : Type u'} [category.{v} D] (G : C ⥤ D) @[simps] def functoriality : cone F ⥤ cone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, π := { app := λ j, G.map (A.π.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ X Y f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, f.w] } } instance functoriality_full [full G] [faithful G] : full (functoriality F G) := { preimage := λ X Y t, { hom := G.preimage t.hom, w' := λ j, G.map_injective (by simpa using t.w j) } } instance functoriality_faithful [faithful G] : faithful (cones.functoriality F G) := { map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } } end end cones @[ext] structure cocone_morphism (A B : cocone F) := (hom : A.X ⟶ B.X) (w' : ∀ j : J, A.ι.app j ≫ hom = B.ι.app j . obviously) restate_axiom cocone_morphism.w' attribute [simp] cocone_morphism.w @[simps] instance cocone.category : category.{v} (cocone F) := { hom := λ A B, cocone_morphism A B, comp := λ _ _ _ f g, { hom := f.hom ≫ g.hom, w' := by intro j; rw [←assoc, f.w, g.w] }, id := λ B, { hom := 𝟙 B.X } } namespace cocones /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[ext, simps] def ext {c c' : cocone F} (φ : c.X ≅ c'.X) (w : ∀ j, c.ι.app j ≫ φ.hom = c'.ι.app j) : c ≅ c' := { hom := { hom := φ.hom }, inv := { hom := φ.inv, w' := λ j, φ.comp_inv_eq.mpr (w j).symm } } @[simps] def precompose {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G := { obj := λ c, { X := c.X, ι := α ≫ c.ι }, map := λ c₁ c₂ f, { hom := f.hom } } def precompose_comp {G H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : precompose (α ≫ β) ≅ precompose β ⋙ precompose α := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } def precompose_id : precompose (𝟙 F) ≅ 𝟭 (cocone F) := by { fapply nat_iso.of_components, { intro s, fapply ext, refl, obviously }, obviously } @[simps] def precompose_equivalence {G : J ⥤ C} (α : G ≅ F) : cocone F ≌ cocone G := { functor := precompose α.hom, inverse := precompose α.inv, unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy) } /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cocone F` to `cocone (E ⋙ F)`. -/ @[simps] def whiskering {K : Type v} [small_category K] (E : K ⥤ J) : cocone F ⥤ cocone (E ⋙ F) := { obj := λ c, c.whisker E, map := λ c c' f, { hom := f.hom, } } /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simps] def whiskering_equivalence {K : Type v} [small_category K] (e : K ≌ J) : cocone F ≌ cocone (e.functor ⋙ F) := { functor := whiskering e.functor, inverse := whiskering e.inverse ⋙ precompose ((functor.left_unitor F).inv ≫ (whisker_right (e.counit_iso).inv F) ≫ (functor.associator _ _ _).inv), unit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (by tidy)) (by tidy), counit_iso := nat_iso.of_components (λ s, cocones.ext (iso.refl _) (begin intro k, have t := s.ι.naturality (e.unit.app k), dsimp at t, simp only [e.functor_unit k, comp_id] at t, dsimp, simp [t], end)) (by tidy), } /-- The categories of cocones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ def equivalence_of_reindexing {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) : cocone F ≌ cocone G := (whiskering_equivalence e).trans (precompose_equivalence α.symm) @[simp] lemma equivalence_of_reindexing_functor_obj {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : e.functor ⋙ F ≅ G) (c : cocone F) : (equivalence_of_reindexing e α).functor.obj c = (precompose α.inv).obj (cocone.whisker e.functor c) := rfl section variable (F) @[simps] def forget : cocone F ⥤ C := { obj := λ t, t.X, map := λ s t f, f.hom } variables {D : Type u'} [category.{v} D] (G : C ⥤ D) @[simps] def functoriality : cocone F ⥤ cocone (F ⋙ G) := { obj := λ A, { X := G.obj A.X, ι := { app := λ j, G.map (A.ι.app j), naturality' := by intros; erw ←G.map_comp; tidy } }, map := λ _ _ f, { hom := G.map f.hom, w' := by intros; rw [←functor.map_comp, cocone_morphism.w] } } instance functoriality_full [full G] [faithful G] : full (functoriality F G) := { preimage := λ X Y t, { hom := G.preimage t.hom, w' := λ j, G.map_injective (by simpa using t.w j) } } instance functoriality_faithful [faithful G] : faithful (functoriality F G) := { map_injective' := λ X Y f g e, by { ext1, injection e, apply G.map_injective h_1 } } end end cocones end limits namespace functor variables {D : Type u'} [category.{v} D] variables {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) open category_theory.limits /-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/ def map_cone (c : cone F) : cone (F ⋙ H) := (cones.functoriality F H).obj c /-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/ def map_cocone (c : cocone F) : cocone (F ⋙ H) := (cocones.functoriality F H).obj c @[simp] lemma map_cone_X (c : cone F) : (H.map_cone c).X = H.obj c.X := rfl @[simp] lemma map_cocone_X (c : cocone F) : (H.map_cocone c).X = H.obj c.X := rfl @[simps] def map_cone_inv [is_equivalence H] (c : cone (F ⋙ H)) : cone F := let t := (inv H).map_cone c in let α : (F ⋙ H) ⋙ inv H ⟶ F := ((whisker_left F is_equivalence.unit_iso.inv) : F ⋙ (H ⋙ inv H) ⟶ _) ≫ (functor.right_unitor _).hom in { X := t.X, π := ((category_theory.cones J C).map α).app (op t.X) t.π } def map_cone_morphism {c c' : cone F} (f : c ⟶ c') : (H.map_cone c) ⟶ (H.map_cone c') := (cones.functoriality F H).map f def map_cocone_morphism {c c' : cocone F} (f : c ⟶ c') : (H.map_cocone c) ⟶ (H.map_cocone c') := (cocones.functoriality F H).map f @[simp] lemma map_cone_π (c : cone F) (j : J) : (map_cone H c).π.app j = H.map (c.π.app j) := rfl @[simp] lemma map_cocone_ι (c : cocone F) (j : J) : (map_cocone H c).ι.app j = H.map (c.ι.app j) := rfl /-- `map_cone` is the left inverse to `map_cone_inv`. -/ def map_cone_map_cone_inv {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : cone (F ⋙ H)) : map_cone H (map_cone_inv H c) ≅ c := begin apply cones.ext _ (λ j, _), { exact H.inv_fun_id.app c.X }, { dsimp, erw [comp_id, ← H.inv_fun_id.hom.naturality (c.π.app j), comp_map, H.map_comp], congr' 1, erw [← cancel_epi (H.inv_fun_id.inv.app (H.obj (F.obj j))), iso.inv_hom_id_app, ← (functor.as_equivalence H).functor_unit _, ← H.map_comp, iso.hom_inv_id_app, H.map_id], refl } end end functor end category_theory namespace category_theory.limits variables {F : J ⥤ Cᵒᵖ} -- Here and below we only automatically generate the `@[simp]` lemma for the `X` field, -- as we can be a simpler `rfl` lemma for the components of the natural transformation by hand. @[simps X] def cone_of_cocone_left_op (c : cocone F.left_op) : cone F := { X := op c.X, π := nat_trans.right_op (c.ι ≫ (const.op_obj_unop (op c.X)).hom) } @[simp] lemma cone_of_cocone_left_op_π_app (c : cocone F.left_op) (j) : (cone_of_cocone_left_op c).π.app j = (c.ι.app (op j)).op := by { dsimp [cone_of_cocone_left_op], simp } @[simps X] def cocone_left_op_of_cone (c : cone F) : cocone (F.left_op) := { X := unop c.X, ι := nat_trans.left_op c.π } @[simp] lemma cocone_left_op_of_cone_ι_app (c : cone F) (j) : (cocone_left_op_of_cone c).ι.app j = (c.π.app (unop j)).unop := by { dsimp [cocone_left_op_of_cone], simp } @[simps X] def cocone_of_cone_left_op (c : cone F.left_op) : cocone F := { X := op c.X, ι := nat_trans.right_op ((const.op_obj_unop (op c.X)).hom ≫ c.π) } @[simp] lemma cocone_of_cone_left_op_ι_app (c : cone F.left_op) (j) : (cocone_of_cone_left_op c).ι.app j = (c.π.app (op j)).op := by { dsimp [cocone_of_cone_left_op], simp } @[simps X] def cone_left_op_of_cocone (c : cocone F) : cone (F.left_op) := { X := unop c.X, π := nat_trans.left_op c.ι } @[simp] lemma cone_left_op_of_cocone_π_app (c : cocone F) (j) : (cone_left_op_of_cocone c).π.app j = (c.ι.app (unop j)).unop := by { dsimp [cone_left_op_of_cocone], simp } end category_theory.limits
5d24dd7e7dd91d89af1ac6c0f3c910f025efd4dd
7fffa00a5bb999b720b69874e6c324f7d8d5e838
/src/category_theory/limits/shapes/kernels.lean
96a3597115fb64606a2d75b9749d21b062f8d11b
[ "Apache-2.0" ]
permissive
ocornoc/mathlib
d720550e3c28c1d4d569de196826a4bd1b292ade
43431be5ab141dcf9a6c7f446cdaf35e4b7f071a
refs/heads/master
1,615,610,363,242
1,583,921,741,000
1,583,921,741,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,802
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.zero import category_theory.limits.shapes.equalizers /-! # Kernels and cokernels In a category with zero morphisms, the kernel of a morphism `f : X ⟶ Y` is just the equalizer of `f` and `0 : X ⟶ Y`. (Similarly the cokernel is the coequalizer.) We don't yet prove much here, just provide * `kernel : (X ⟶ Y) → C` * `kernel.ι : kernel f ⟶ X` * `kernel.condition : kernel.ι f ≫ f = 0` and * `kernel.lift (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f` (as well as the dual versions) ## Main statements Besides the definition and lifts, * `kernel.ι_zero_is_iso`: a kernel map of a zero morphism is an isomorphism * `kernel.is_limit_cone_zero_cone`: if our category has a zero object, then the map from the zero obect is a kernel map of any monomorphism ## Future work * TODO: images and coimages, and then abelian categories. * TODO: connect this with existing working in the group theory and ring theory libraries. ## Implementation notes As with the other special shapes in the limits library, all the definitions here are given as `abbreviation`s of the general statements for limits, so all the `simp` lemmas and theorems about general limits can be used. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] -/ universes v u open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables {X Y : C} (f : X ⟶ Y) section variables [has_zero_morphisms.{v} C] [has_limit (parallel_pair f 0)] /-- The kernel of a morphism, expressed as the equalizer with the 0 morphism. -/ abbreviation kernel : C := equalizer f 0 /-- The map from `kernel f` into the source of `f`. -/ abbreviation kernel.ι : kernel f ⟶ X := equalizer.ι f 0 @[simp, reassoc] lemma kernel.condition : kernel.ι f ≫ f = 0 := by simp [equalizer.condition] /-- Given any morphism `k` so `k ≫ f = 0`, `k` factors through `kernel f`. -/ abbreviation kernel.lift {W : C} (k : W ⟶ X) (h : k ≫ f = 0) : W ⟶ kernel f := limit.lift (parallel_pair f 0) (fork.of_ι k (by simpa)) /-- Every kernel of the zero morphism is an isomorphism -/ def kernel.ι_zero_is_iso [has_limit (parallel_pair (0 : X ⟶ Y) 0)] : is_iso (kernel.ι (0 : X ⟶ Y)) := by { apply limit_cone_parallel_pair_self_is_iso, apply limit.is_limit } end section has_zero_object variables [has_zero_object.{v} C] local attribute [instance] zero_of_zero_object local attribute [instance] has_zero_object.zero_morphisms_of_zero_object /-- The morphism from the zero object determines a cone on a kernel diagram -/ def kernel.zero_cone : cone (parallel_pair f 0) := { X := 0, π := { app := λ j, 0 }} /-- The map from the zero object is a kernel of a monomorphism -/ def kernel.is_limit_cone_zero_cone [mono f] : is_limit (kernel.zero_cone f) := { lift := λ s, 0, fac' := λ s j, begin cases j, { erw has_zero_morphisms.zero_comp, convert (@zero_of_comp_mono _ _ _ _ _ _ _ f _ _).symm, erw fork.condition, convert has_zero_morphisms.comp_zero.{v} _ (s.π.app zero) _ }, { rw ←cone_parallel_pair_right s, simp only [has_zero_morphisms.zero_comp], convert (has_zero_morphisms.comp_zero.{v} _ (s.π.app zero) _).symm }, end, uniq' := λ _ m _, has_zero_object.zero_of_to_zero m } /-- The kernel of a monomorphism is isomorphic to the zero object -/ def kernel.of_mono [has_limit (parallel_pair f 0)] [mono f] : kernel f ≅ 0 := functor.map_iso cones.forget $ is_limit.unique_up_to_iso (limit.is_limit (parallel_pair f 0)) (kernel.is_limit_cone_zero_cone f) /-- The kernel morphism of a monomorphism is a zero morphism -/ lemma kernel.ι_of_mono [has_limit (parallel_pair f 0)] [mono f] : kernel.ι f = 0 := by rw [←category.id_comp _ (kernel.ι f), ←iso.hom_inv_id (kernel.of_mono f), category.assoc, has_zero_object.zero_of_to_zero (kernel.of_mono f).hom, has_zero_morphisms.zero_comp] section variables (X) (Y) /-- The kernel morphism of a zero morphism is an isomorphism -/ def kernel.ι_of_zero [has_limit (parallel_pair (0 : X ⟶ Y) 0)] : is_iso (kernel.ι (0 : X ⟶ Y)) := equalizer.ι_of_self _ end end has_zero_object section variables [has_zero_morphisms.{v} C] [has_colimit (parallel_pair f 0)] /-- The cokernel of a morphism, expressed as the coequalizer with the 0 morphism. -/ abbreviation cokernel : C := coequalizer f 0 /-- The map from the target of `f` to `cokernel f`. -/ abbreviation cokernel.π : Y ⟶ cokernel f := coequalizer.π f 0 @[simp, reassoc] lemma cokernel.condition : f ≫ cokernel.π f = 0 := by simp [coequalizer.condition] /-- Given any morphism `k` so `f ≫ k = 0`, `k` factors through `cokernel f`. -/ abbreviation cokernel.desc {W : C} (k : Y ⟶ W) (h : f ≫ k = 0) : cokernel f ⟶ W := colimit.desc (parallel_pair f 0) (cofork.of_π k (by simpa)) end section has_zero_object variables [has_zero_object.{v} C] local attribute [instance] zero_of_zero_object local attribute [instance] has_zero_object.zero_morphisms_of_zero_object /-- The morphism to the zero object determines a cocone on a cokernel diagram -/ def cokernel.zero_cocone : cocone (parallel_pair f 0) := { X := 0, ι := { app := λ j, 0 } } /-- The morphism to the zero object is a cokernel of an epimorphism -/ def cokernel.is_colimit_cocone_zero_cocone [epi f] : is_colimit (cokernel.zero_cocone f) := { desc := λ s, 0, fac' := λ s j, begin cases j, { erw [←cocone_parallel_pair_left s, has_zero_morphisms.comp_zero _ ((cokernel.zero_cocone f).ι.app zero) _, cofork.condition, has_zero_morphisms.zero_comp], refl }, { erw has_zero_morphisms.zero_comp, convert (@zero_of_comp_epi _ _ _ _ _ _ f _ _ _).symm, erw [cofork.condition, has_zero_morphisms.zero_comp], refl }, end, uniq' := λ _ m _, has_zero_object.zero_of_from_zero m } /-- The cokernel of an epimorphism is isomorphic to the zero object -/ def cokernel.of_epi [has_colimit (parallel_pair f 0)] [epi f] : cokernel f ≅ 0 := functor.map_iso cocones.forget $ is_colimit.unique_up_to_iso (colimit.is_colimit (parallel_pair f 0)) (cokernel.is_colimit_cocone_zero_cocone f) /-- The cokernel morphism if an epimorphism is a zero morphism -/ lemma cokernel.π_of_epi [has_colimit (parallel_pair f 0)] [epi f] : cokernel.π f = 0 := by rw [←category.comp_id _ (cokernel.π f), ←iso.hom_inv_id (cokernel.of_epi f), ←category.assoc, has_zero_object.zero_of_from_zero (cokernel.of_epi f).inv, has_zero_morphisms.comp_zero] section variables (X) (Y) /-- The cokernel of a zero morphism is an isomorphism -/ def cokernel.π_of_zero [has_colimit (parallel_pair (0 : X ⟶ Y) 0)] : is_iso (cokernel.π (0 : X ⟶ Y)) := coequalizer.π_of_self _ end end has_zero_object section has_zero_object variables [has_zero_object.{v} C] local attribute [instance] zero_of_zero_object local attribute [instance] has_zero_object.zero_morphisms_of_zero_object /-- The kernel of the cokernel of an epimorphism is an isomorphism -/ def kernel.of_cokernel_of_epi [has_colimit (parallel_pair f 0)] [has_limit (parallel_pair (cokernel.π f) 0)] [epi f] : is_iso (kernel.ι (cokernel.π f)) := equalizer.ι_of_self' _ _ $ cokernel.π_of_epi f /-- The cokernel of the kernel of a monomorphism is an isomorphism -/ def cokernel.of_kernel_of_mono [has_limit (parallel_pair f 0)] [has_colimit (parallel_pair (kernel.ι f) 0)] [mono f] : is_iso (cokernel.π (kernel.ι f)) := coequalizer.π_of_self' _ _ $ kernel.ι_of_mono f end has_zero_object end category_theory.limits namespace category_theory.limits variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 variables [has_zero_morphisms.{v} C] /-- `has_kernels` represents a choice of kernel for every morphism -/ class has_kernels := (has_limit : Π {X Y : C} (f : X ⟶ Y), has_limit (parallel_pair f 0)) /-- `has_cokernels` represents a choice of cokernel for every morphism -/ class has_cokernels := (has_colimit : Π {X Y : C} (f : X ⟶ Y), has_colimit (parallel_pair f 0)) attribute [instance] has_kernels.has_limit has_cokernels.has_colimit /-- Kernels are finite limits, so if `C` has all finite limits, it also has all kernels -/ def has_kernels_of_has_finite_limits [has_finite_limits.{v} C] : has_kernels.{v} C := { has_limit := infer_instance } /-- Cokernels are finite limits, so if `C` has all finite colimits, it also has all cokernels -/ def has_cokernels_of_has_finite_colimits [has_finite_colimits.{v} C] : has_cokernels.{v} C := { has_colimit := infer_instance } end category_theory.limits
22b94e7cde16073bf542a7aad7f378e1b0b9119b
63abd62053d479eae5abf4951554e1064a4c45b4
/src/combinatorics/simple_graph.lean
0e8d413c55253266f431c853caed5c22ea494ead
[ "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
6,323
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson, Jalex Stark, Kyle Miller. -/ import data.fintype.basic import data.sym2 /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `neighbor_set` is the `set` of vertices adjacent to a given vertex * `neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite ## Implementation notes * A locally finite graph is one with instances `∀ v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. TODO: This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. TODO: Part of this would include defining, for example, subgraphs of a simple graph. -/ open finset universe u /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent edges; see `simple_graph.edge_set` for the corresponding edge set. -/ structure simple_graph (V : Type u) := (adj : V → V → Prop) (sym : symmetric adj . obviously) (loopless : irreflexive adj . obviously) /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. -/ def complete_graph (V : Type u) : simple_graph V := { adj := ne } instance (V : Type u) : inhabited (simple_graph V) := ⟨complete_graph V⟩ instance complete_graph_adj_decidable (V : Type u) [decidable_eq V] : decidable_rel (complete_graph V).adj := by { dsimp [complete_graph], apply_instance } namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set (v : V) : set V := set_of (G.adj v) lemma ne_of_adj {a b : V} (hab : G.adj a b) : a ≠ b := by { rintro rfl, exact G.loopless a hab } /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. -/ def edge_set : set (sym2 V) := sym2.from_rel G.sym @[simp] lemma mem_edge_set {v w : V} : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w := by refl /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ lemma adj_iff_exists_edge {v w : V} : G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e := begin split, { intro, split, { exact G.ne_of_adj ‹_›, }, {use ⟦(v,w)⟧, simpa} }, { rintro ⟨hne, e, he, hv⟩, rw sym2.elems_iff_eq hne at hv, subst e, rwa mem_edge_set at he, } end lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v := begin erw [← sym2.mem_other_spec h, sym2.eq_swap] at he, exact G.ne_of_adj he, end instance edges_fintype [decidable_eq V] [fintype V] [decidable_rel G.adj] : fintype G.edge_set := by { dunfold edge_set, exact subtype.fintype _ } /-- The `edge_set` of the graph as a `finset`. -/ def edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] : finset (sym2 V) := set.to_finset G.edge_set @[simp] lemma mem_edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] (e : sym2 V) : e ∈ G.edge_finset ↔ e ∈ G.edge_set := by { dunfold edge_finset, simp } @[simp] lemma irrefl {v : V} : ¬G.adj v v := G.loopless v @[symm] lemma edge_symm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.sym x, λ x, G.sym x⟩ @[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := by tauto section finite_at /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ variables (v : V) [fintype (G.neighbor_set v)] /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset : finset V := (G.neighbor_set v).to_finset @[simp] lemma mem_neighbor_finset (w : V) : w ∈ G.neighbor_finset v ↔ G.adj v w := by simp [neighbor_finset] /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighbor_finset v).card @[simp] lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v := by simp [degree, neighbor_finset] end finite_at section locally_finite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ @[reducible] def locally_finite := Π (v : V), fintype (G.neighbor_set v) variable [locally_finite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d end locally_finite section finite variables [fintype V] instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) := @subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _ lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] : G.neighbor_finset v = finset.univ.filter (G.adj v) := by { ext, simp } @[simp] lemma complete_graph_degree [decidable_eq V] (v : V) : (complete_graph V).degree v = fintype.card V - 1 := begin convert univ.card.pred_eq_sub_one, erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v)], end lemma complete_graph_is_regular [decidable_eq V] : (complete_graph V).is_regular_of_degree (fintype.card V - 1) := by { intro v, simp } end finite end simple_graph
da80ed5e2fdda2b256191622f4ab541afc86e893
1e7164e9c5aacccd114777e0ea8f8201177f1289
/src/traversals/basic.lean
4604f62f7d2c281006288d4e90bf33f608304d36
[]
no_license
floriscnossen/simplicial_sets_in_lean
e7cb1780474407668208ec5b8f19de7eb5936701
c260d8196964bb288331bff7a3bfe24266792f0c
refs/heads/master
1,685,636,159,913
1,624,118,064,000
1,624,118,064,000
352,801,219
0
0
null
null
null
null
UTF-8
Lean
false
false
19,992
lean
import algebraic_topology.simplicial_set import category_theory.limits.has_limits import category_theory.functor_category import category_theory.limits.yoneda import category_theory.limits.presheaf import simplicial_sets.simplex_as_hom open category_theory open category_theory.limits open simplex_category open sSet open_locale simplicial /-! # Traversals Defines n-traversals, pointed n-traversals and their corresponding simplicial sets. ## Notations * `∔` for a plus, * `∸` for a minus, * `e :: θ` for adding an edge e at the start of a traversal θ, * `e ⬝ α` for the action of a map α on an edge e, * `θ ⬝ α` for the action of a map α on a traversal θ. -/ namespace traversal @[derive decidable_eq] inductive pm | plus : pm | minus : pm notation `±` := pm notation `∔` := pm.plus notation `∸` := pm.minus @[reducible] def edge (n : ℕ) := fin (n+1) × ± def edge.lt {n} : edge n → edge n → Prop | (i, ∸) (j, ∸) := i < j | (i, ∸) (j, ∔) := true | (i, ∔) (j, ∸) := false | (i, ∔) (j, ∔) := j < i instance {n} : has_lt (edge n) := ⟨edge.lt⟩ instance edge.has_decidable_lt {n} : Π e₁ e₂ : edge n, decidable (e₁ < e₂) | (i, ∸) (j, ∸) := fin.decidable_lt i j | (i, ∸) (j, ∔) := is_true trivial | (i, ∔) (j, ∸) := is_false not_false | (i, ∔) (j, ∔) := fin.decidable_lt j i lemma edge.lt_asymm {n} : Π e₁ e₂ : edge n, e₁ < e₂ → e₂ < e₁ → false | (i, ∸) (j, ∸) := nat.lt_asymm | (i, ∸) (j, ∔) := λ h₁ h₂, h₂ | (i, ∔) (j, ∸) := λ h₁ h₂, h₁ | (i, ∔) (j, ∔) := nat.lt_asymm instance {n} : is_asymm (edge n) edge.lt := ⟨edge.lt_asymm⟩ end traversal @[reducible] def traversal (n : ℕ) := list (traversal.edge n) @[reducible] def pointed_traversal (n : ℕ) := traversal n × traversal n namespace traversal notation h :: t := list.cons h t notation `⟦` l:(foldr `, ` (h t, list.cons h t) list.nil `⟧`) := (l : traversal _) instance decidable_mem {n} : Π (e : edge n) (θ : traversal n), decidable (e ∈ θ) := list.decidable_mem @[reducible] def sorted {n} (θ : traversal n) := list.sorted edge.lt θ theorem eq_of_sorted_of_same_elem {n : ℕ} : Π (θ₁ θ₂ : traversal n) (s₁ : sorted θ₁) (s₂ : sorted θ₂), (Π e, e ∈ θ₁ ↔ e ∈ θ₂) → θ₁ = θ₂ | ⟦⟧ ⟦⟧ := λ _ _ _, rfl | ⟦⟧ (e₂ :: t₂) := λ _ _ H, begin exfalso, simpa using H e₂, end | (e₁ :: t₁) ⟦⟧ := λ _ _ H, begin exfalso, simpa using H e₁, end | (e₁ :: t₁) (e₂ :: t₂) := λ s₁ s₂ H, begin simp only [sorted, list.sorted_cons] at s₁ s₂, cases s₁ with he₁ ht₁, cases s₂ with he₂ ht₂, have he₁e₂ : e₁ = e₂, { have He₁ := H e₁, simp at He₁, cases He₁ with heq He₁, from heq, have He₂ := H e₂, simp at He₂, cases He₂ with heq He₂, from heq.symm, exfalso, exact edge.lt_asymm e₁ e₂ (he₁ e₂ He₂) (he₂ e₁ He₁), }, cases he₁e₂, simp, { apply eq_of_sorted_of_same_elem t₁ t₂ ht₁ ht₂, intro e, specialize H e, simp at H, split, { intro he, cases H.1 (or.intro_right _ he) with h, cases h, exfalso, exact edge.lt_asymm e₁ e₁ (he₁ e₁ he) (he₁ e₁ he), exact h, }, { intro he, cases H.2 (or.intro_right _ he) with h, cases h, exfalso, exact edge.lt_asymm e₁ e₁ (he₂ e₁ he) (he₂ e₁ he), exact h, }} end theorem append_sorted {n : ℕ} : Π (θ₁ θ₂ : traversal n) (s₁ : sorted θ₁) (s₂ : sorted θ₂), (∀ (e₁ ∈ θ₁) (e₂ ∈ θ₂), e₁ < e₂) → sorted (θ₁ ++ θ₂) | ⟦⟧ θ₂ := λ _ s₂ _, s₂ | (e₁ :: t₁) θ₂ := λ s₁ s₂ H, begin simp only [sorted, list.sorted_cons] at s₁ s₂ ⊢, cases s₁ with he₁ ht₁, dsimp, rw list.sorted_cons, split, { intros e he, simp at he, cases he, exact he₁ e he, refine H e₁ (list.mem_cons_self e₁ t₁) e he }, { apply append_sorted t₁ θ₂ ht₁ s₂, intros e₁' he₁' e₂' he₂', refine H e₁' (list.mem_cons_of_mem e₁ he₁') e₂' he₂' } end theorem append_sorted_iff {n : ℕ} : Π (θ₁ θ₂ : traversal n), sorted θ₁ ∧ sorted θ₂ ∧ (∀ (e₁ ∈ θ₁) (e₂ ∈ θ₂), e₁ < e₂) ↔ sorted (θ₁ ++ θ₂) | ⟦⟧ θ₂ := by simp[sorted, list.sorted_nil] | (e₁ :: t₁) θ₂ := begin split, rintro ⟨s₁, s₂, H⟩, apply append_sorted _ _ s₁ s₂ H, intro H, dsimp[sorted] at H, rw list.sorted_cons at H, change _ ∧ sorted _ at H, rw ←append_sorted_iff at H, split, { dsimp[sorted], rw list.sorted_cons, split, intros b hb, exact H.1 b (list.mem_append_left θ₂ hb), exact H.2.1 }, split, exact H.2.2.1, intros e' he', simp at he', cases he', cases he', intros e₂ he₂, exact H.1 e₂ (list.mem_append_right t₁ he₂), exact H.2.2.2 e' he', end /-! # Applying a map to an edge -/ def apply_map_to_plus {n m : simplex_category} (i : fin (n.len+1)) (α : m ⟶ n) : Π (j : ℕ), j < m.len+1 → traversal m.len | 0 h0 := if α.to_preorder_hom 0 = i then ⟦⟨0, ∔⟩⟧ else ⟦⟧ | (j + 1) hj := if α.to_preorder_hom ⟨j+1,hj⟩ = i then (⟨j+1, hj⟩, ∔) :: (apply_map_to_plus j (nat.lt_of_succ_lt hj)) else apply_map_to_plus j (nat.lt_of_succ_lt hj) lemma min_notin_apply_map_to_plus {n m : simplex_category} (α : m ⟶ n) (i : fin (n.len+1)) (j : ℕ) (hj : j < m.len + 1) : ∀ (k : fin (m.len + 1)), (k, ∸) ∉ apply_map_to_plus i α j hj := begin intros k hk, induction j with j, { simp [apply_map_to_plus] at hk, split_ifs at hk; simp at hk; exact hk }, { simp [apply_map_to_plus] at hk, split_ifs at hk, simp at hk, repeat {exact j_ih _ hk }} end lemma plus_in_apply_map_to_plus_iff {n m : simplex_category} (α : m ⟶ n) (i : fin (n.len+1)) (j : ℕ) (hj : j < m.len + 1) : ∀ (k : fin (m.len + 1)), (k, ∔) ∈ apply_map_to_plus i α j hj ↔ k.val < j + 1 ∧ α.to_preorder_hom k = i := begin intros k, induction j with j, { simp only [apply_map_to_plus], split_ifs; simp, split, intro hk, cases hk, simp, exact h, intro hk, ext, simp, linarith, intro hk, replace hk : k = 0, ext, simp, linarith, cases hk, exact h, }, { simp only [apply_map_to_plus], split_ifs; simp; rw j_ih; simp, split, intro hk, cases hk, cases hk, split, simp, exact h, split, exact nat.le_succ_of_le hk.1, exact hk.2, intro hk, rw hk.2, simp, cases nat.of_le_succ hk.1, right, exact h_1, left, ext, simp, exact nat.succ.inj h_1, intro hk, split, intro hkj, exact nat.le_succ_of_le hkj, intro hkj, cases nat.of_le_succ hkj, exact h_1, exfalso, have H : k = ⟨j + 1, hj⟩, ext, exact nat.succ.inj h_1, cases H, exact h hk, } end lemma apply_map_to_plus_sorted {n m : simplex_category} (α : m ⟶ n) (i : fin (n.len+1)) (j : ℕ) (hj : j < m.len + 1) : sorted (apply_map_to_plus i α j hj) := begin dsimp [sorted], induction j with j, { simp [apply_map_to_plus], split_ifs; simp, }, { simp [apply_map_to_plus], split_ifs, swap, exact j_ih (nat.lt_of_succ_lt hj), simp only [list.sorted_cons], split, swap, exact j_ih (nat.lt_of_succ_lt hj), intros e he, cases e with k, cases e_snd, rw plus_in_apply_map_to_plus_iff at he, exact he.1, exact absurd he (min_notin_apply_map_to_plus α i j _ k), }, end def apply_map_to_min {n m : simplex_category} (i : fin (n.len+1)) (α : m ⟶ n) : Π (j : ℕ), j < m.len+1 → traversal m.len | 0 h0 := if α.to_preorder_hom m.last = i then ⟦⟨m.last, ∸⟩⟧ else ⟦⟧ | (j + 1) hj := if α.to_preorder_hom ⟨m.len-(j+1), nat.sub_lt_succ _ _⟩ = i then (⟨m.len-(j+1), nat.sub_lt_succ _ _⟩, ∸) :: (apply_map_to_min j (nat.lt_of_succ_lt hj)) else apply_map_to_min j (nat.lt_of_succ_lt hj) lemma plus_notin_apply_map_to_min {n m : simplex_category} (α : m ⟶ n) (i : fin (n.len+1)) (j : ℕ) (hj : j < m.len + 1) : ∀ (k : fin (m.len + 1)), (k, ∔) ∉ apply_map_to_min i α j hj := begin intros k hk, induction j with j, { simp [apply_map_to_min] at hk, split_ifs at hk; simp at hk; exact hk }, { simp [apply_map_to_min] at hk, split_ifs at hk, simp at hk, repeat {exact j_ih _ hk }} end lemma min_in_apply_map_to_min_iff {n m : simplex_category} (α : m ⟶ n) (i : fin (n.len+1)) (j : ℕ) (hj : j < m.len + 1) : ∀ (k : fin (m.len + 1)), (k, ∸) ∈ apply_map_to_min i α j hj ↔ k.val ≥ m.len - j ∧ α.to_preorder_hom k = i := begin intros k, induction j with j, { simp only [apply_map_to_min], split_ifs; simp, split, intro hk, cases hk, simp, split, refl, exact h, intro hk, ext, exact le_antisymm (fin.le_last k) hk.1, intro hk, replace hk : k = m.last, ext, exact le_antisymm (fin.le_last k) hk, cases hk, exact h, }, { have Hk : ∀ k, m.len - j.succ ≤ k ↔ m.len - j ≤ k ∨ m.len - j.succ = k, { have hmj_pos : 0 < m.len - j, from nat.sub_pos_of_lt (nat.succ_lt_succ_iff.mp hj), rw nat.lt_succ_iff at hj, intro k, rw [nat.sub_succ, ←nat.succ_le_succ_iff, ←nat.succ_inj', nat.succ_pred_eq_of_pos hmj_pos], exact nat.le_add_one_iff, }, simp only [apply_map_to_min], split_ifs; simp; rw j_ih; simp, split, intro hk, cases hk, cases hk, split, simp, exact h, split, rw nat.sub_succ, exact nat.le_trans (nat.pred_le _) hk.1, exact hk.2, intro hk, rw hk.2, simp, cases (Hk k).mp hk.1, right, exact h_1, left, ext, exact h_1.symm, intro hk, rw Hk k, split, intro hkj, left, exact hkj, intro hkj, cases hkj, exact hkj, have Hk' : k = ⟨m.len - (j + 1), apply_map_to_min._main._proof_1 _⟩, ext, exact hkj.symm, cases Hk', exact absurd hk h,} end lemma apply_map_to_min_sorted {n m : simplex_category} (α : m ⟶ n) (i : fin (n.len+1)) (j : ℕ) (hj : j < m.len + 1) : list.sorted edge.lt (apply_map_to_min i α j hj) := begin induction j with j, { simp [apply_map_to_min], split_ifs; simp, }, { simp [apply_map_to_min], split_ifs, swap, exact j_ih (nat.lt_of_succ_lt hj), simp only [list.sorted_cons], split, swap, exact j_ih (nat.lt_of_succ_lt hj), intros e he, cases e with k, cases e_snd, exact absurd he (plus_notin_apply_map_to_min α i j _ k), rw min_in_apply_map_to_min_iff at he, replace he : k.val ≥ m.len - j := he.1, change m.len - (j + 1) < k.val, refine lt_of_lt_of_le _ he, rw nat.sub_succ, refine nat.pred_lt _, simp, rwa [nat.sub_eq_zero_iff_le, not_le, ←nat.succ_lt_succ_iff], }, end def apply_map_to_edge {n m : simplex_category} (α : m ⟶ n) : edge n.len → traversal m.len | (i, ∔) := apply_map_to_plus i α m.last.1 m.last.2 | (i, ∸) := apply_map_to_min i α m.last.1 m.last.2 notation e ⬝ α := apply_map_to_edge α e example (p : Prop) (h : p) : p ↔ true := iff_of_true h trivial @[simp] lemma edge_in_apply_map_to_edge_iff {n m : simplex_category} (α : m ⟶ n) : ∀ (e₁ : edge m.len) (e₂), e₁ ∈ e₂ ⬝ α ↔ (α.to_preorder_hom e₁.1, e₁.2) = e₂ := begin intros e₁ e₂, cases e₁ with i₁ b₁, cases e₂ with i₂ b₂, cases b₁; cases b₂; simp [apply_map_to_edge], { simp [plus_in_apply_map_to_plus_iff], exact λ _, i₁.2, }, { apply plus_notin_apply_map_to_min, }, { apply min_notin_apply_map_to_plus, }, { simp [min_in_apply_map_to_min_iff, simplex_category.last], }, end lemma apply_map_to_edge_sorted {n m : simplex_category} (α : m ⟶ n) : ∀ (e : edge n.len), sorted (e ⬝ α) | (i, ∔) := apply_map_to_plus_sorted α i _ _ | (i, ∸) := apply_map_to_min_sorted α i _ _ /-! # Applying a map to a traversal -/ def apply_map {n m : simplex_category} (α : m ⟶ n) : traversal n.len → traversal m.len | ⟦⟧ := ⟦⟧ | (e :: t) := (e ⬝ α) ++ apply_map t notation θ ⬝ α := apply_map α θ @[simp] lemma edge_in_apply_map_iff {n m : simplex_category} (α : m ⟶ n) (θ : traversal n.len) : ∀ (e : edge m.len), e ∈ θ ⬝ α ↔ (α.to_preorder_hom e.1, e.2) ∈ θ := begin intros e, induction θ; simp [apply_map, list.mem_append], simp [edge_in_apply_map_to_edge_iff, θ_ih], end def apply_map_preserves_sorted {n m : simplex_category} (α : m ⟶ n) (θ : traversal n.len) : sorted θ → sorted (θ ⬝ α) := begin intro sθ, induction θ; dsimp [sorted, apply_map], { exact list.sorted_nil }, simp only [sorted, list.sorted_cons] at sθ, apply append_sorted, apply apply_map_to_edge_sorted, apply θ_ih sθ.2, intros e₁ he₁ e₂ he₂, rw edge_in_apply_map_to_edge_iff at he₁, rw edge_in_apply_map_iff at he₂, replace sθ := sθ.1 (α.to_preorder_hom e₂.fst, e₂.snd) he₂, cases he₁, clear he₁ he₂, cases e₁ with i₁ b₁, cases e₂ with i₂ b₂, cases b₁; cases b₂; simp [edge.lt] at sθ ⊢; try {change i₂ < i₁}; try {trivial}; try {change i₁ < i₂}; rw ←not_le at sθ ⊢; exact λ H, sθ (α.to_preorder_hom.monotone H), end @[simp] lemma apply_map_append {n m : simplex_category} (α : m ⟶ n) : Π (θ₁ θ₂ : traversal n.len), apply_map α (θ₁ ++ θ₂) = (apply_map α θ₁) ++ (apply_map α θ₂) | ⟦⟧ θ₂ := rfl | (h :: θ₁) θ₂ := begin dsimp[apply_map], rw apply_map_append, rw list.append_assoc, end @[simp] lemma apply_id {n : simplex_category} : ∀ (θ : traversal n.len), apply_map (𝟙 n) θ = θ | ⟦⟧ := rfl | (e :: θ) := begin unfold apply_map, rw [apply_id θ], change _ = ⟦e⟧ ++ θ, rw list.append_left_inj, apply eq_of_sorted_of_same_elem, { apply apply_map_to_edge_sorted }, { exact list.sorted_singleton e }, { intro e, simp } end @[simp] lemma apply_comp {n m l : simplex_category} (α : m ⟶ n) (β : n ⟶ l) : ∀ (θ : traversal l.len), apply_map (α ≫ β) θ = apply_map α (apply_map β θ) | ⟦⟧ := rfl | (e :: θ) := begin unfold apply_map, rw [apply_map_append, ←apply_comp, list.append_left_inj], apply eq_of_sorted_of_same_elem, { apply apply_map_to_edge_sorted }, { apply apply_map_preserves_sorted, apply apply_map_to_edge_sorted }, { intro e, simp, } end /-! # The application of the standard face maps and standard degeneracies. -/ @[simp] lemma apply_δ_self {n} (i : fin (n + 2)) (b : ±) : apply_map_to_edge (δ i) (i, b) = ⟦⟧ := begin apply eq_of_sorted_of_same_elem, apply apply_map_to_edge_sorted, exact list.sorted_nil, intro e, cases e, simp, intro h, exfalso, simp [δ, fin.succ_above] at h, split_ifs at h, finish, rw [not_lt, fin.le_cast_succ_iff] at h_1, finish, end @[simp] lemma apply_δ_succ_cast_succ {n} (i : fin (n + 1)) (b : ±) : apply_map_to_edge (δ i.succ) (i.cast_succ, b) = ⟦(i, b)⟧ := begin apply eq_of_sorted_of_same_elem, apply apply_map_to_edge_sorted, exact list.sorted_singleton (i, b), intro e, cases e, simp, intro hb, cases hb, split, { intro he, have H : (δ i.succ ≫ σ i).to_preorder_hom e_fst = (σ i).to_preorder_hom i.cast_succ, { rw ←he, simp, }, rw δ_comp_σ_succ at H, simpa [σ, fin.pred_above] using H, }, { intro he, cases he, simp [δ, fin.succ_above, fin.cast_succ_lt_succ], } end @[simp] lemma apply_δ_cast_succ_succ {n} (i : fin (n + 1)) (b : ±) : apply_map_to_edge (δ i.cast_succ) (i.succ, b) = ⟦(i, b)⟧ := begin apply eq_of_sorted_of_same_elem, apply apply_map_to_edge_sorted, exact list.sorted_singleton (i, b), intro e, cases e, simp, intro hb, cases hb, split, { intro he, have H : (δ i.cast_succ ≫ σ i).to_preorder_hom e_fst = (σ i).to_preorder_hom i.succ, { rw ←he, simp, }, rw δ_comp_σ_self at H, simp [σ, fin.pred_above] at H, split_ifs at H, from H, exact absurd (fin.cast_succ_lt_succ i) h, }, { intro he, cases he, simp [δ, fin.succ_above, fin.cast_succ_lt_succ], } end @[simp] lemma apply_σ_to_plus {n} (i : fin (n + 1)) : apply_map_to_edge (σ i) (i, ∔) = ⟦(i.succ, ∔), (i.cast_succ, ∔)⟧ := begin apply eq_of_sorted_of_same_elem, { apply apply_map_to_edge_sorted,}, { simp [sorted], intros a b ha hb, rw ha, rw hb, exact fin.cast_succ_lt_succ i, }, { intro e, cases e with l b, rw edge_in_apply_map_to_edge_iff, simp, rw ←or_and_distrib_right, simp, intro hb, clear hb b, simp [σ, fin.pred_above], split, { intro H, split_ifs at H, rw ←fin.succ_inj at H, simp at H, left, exact H, rw ←fin.cast_succ_inj at H, simp at H, right, exact H, }, { intro H, cases H; rw H; simp[fin.cast_succ_lt_succ], }} end @[simp] lemma apply_σ_to_min {n} (i : fin (n + 1)) : apply_map_to_edge (σ i) (i, ∸) = ⟦(i.cast_succ, ∸), (i.succ, ∸)⟧ := begin apply eq_of_sorted_of_same_elem, { apply apply_map_to_edge_sorted, }, { simp[sorted], intros a b ha hb, rw [ha, hb], exact fin.cast_succ_lt_succ i, }, { intro e, cases e with l b, rw edge_in_apply_map_to_edge_iff, simp, rw ←or_and_distrib_right, simp, intro hb, clear hb b, simp [σ, fin.pred_above], split, { intro H, split_ifs at H, rw ←fin.succ_inj at H, simp at H, right, exact H, rw ←fin.cast_succ_inj at H, simp at H, left, exact H, }, { intro H, cases H; rw H; simp[fin.cast_succ_lt_succ], }} end def edge.s {n} : edge n → fin (n+2) | ⟨k, ∔⟩ := k.succ | ⟨k, ∸⟩ := k.cast_succ def edge.t {n} : edge n → fin (n+2) | ⟨k, ∔⟩ := k.cast_succ | ⟨k, ∸⟩ := k.succ notation e`ˢ` := e.s notation e`ᵗ` := e.t lemma apply_σ_to_self {n} (e : edge n) : apply_map_to_edge (σ e.1) e = ⟦(eˢ, e.2), (eᵗ, e.2)⟧ := begin apply eq_of_sorted_of_same_elem, { apply apply_map_to_edge_sorted, }, { dsimp [sorted], rw [list.sorted_cons], split, swap, apply list.sorted_singleton, intro e', simp, intro he', cases he', cases e with i b, cases b; exact fin.cast_succ_lt_succ i }, { intro e', simp, cases e with i b, cases i with i hi, cases e' with i' b', cases i' with i' hi', cases b; cases b'; simp [σ, fin.pred_above, edge.s, edge.t]; split_ifs; try { rw ←fin.succ_inj, simp [h] }; split; intro hi; cases hi; try { linarith }; simp } end /- Simplicial set of traversals. -/ def 𝕋₀ : sSet := { obj := λ n, traversal n.unop.len, map := λ x y α, apply_map α.unop, map_id' := λ n, funext (λ θ, apply_id θ), map_comp' := λ l n m β α, funext (λ θ, apply_comp α.unop β.unop θ) } lemma 𝕋₀_map_apply {n m : simplex_categoryᵒᵖ} {f : n ⟶ m} {θ : traversal n.unop.len} : 𝕋₀.map f θ = θ.apply_map f.unop := rfl /- Simplicial set of pointed traversals. -/ def 𝕋₁ : sSet := { obj := λ x, pointed_traversal x.unop.len, map := λ _ _ α θ, (𝕋₀.map α θ.1, 𝕋₀.map α θ.2), map_id' := λ _, by ext1 θ; simp, map_comp' := λ _ _ _ _ _, by ext1 θ; simp } @[simp] lemma 𝕋₁_map_apply {n m : simplex_categoryᵒᵖ} {f : n ⟶ m} {θ₁ θ₂ : traversal n.unop.len} : 𝕋₁.map f (θ₁, θ₂) = (𝕋₀.map f θ₁, 𝕋₀.map f θ₂) := rfl @[simp] lemma 𝕋₁_map_apply_fst {n m : simplex_categoryᵒᵖ} {f : n ⟶ m} {θ : pointed_traversal n.unop.len} : (𝕋₁.map f θ).1 = 𝕋₀.map f θ.1 := rfl @[simp] lemma 𝕋₁_map_apply_snd {n m : simplex_categoryᵒᵖ} {f : n ⟶ m} {θ : pointed_traversal n.unop.len} : (𝕋₁.map f θ).2 = 𝕋₀.map f θ.2 := rfl def dom : 𝕋₁ ⟶ 𝕋₀ := { app := λ n θ, θ.2, naturality' := λ n m α, rfl } def cod : 𝕋₁ ⟶ 𝕋₀ := { app := λ n θ, list.append θ.1 θ.2, naturality' := λ m m α, funext (λ θ, (traversal.apply_map_append α.unop θ.1 θ.2).symm) } def as_hom {n} (θ : traversal n) : Δ[n] ⟶ 𝕋₀ := simplex_as_hom θ end traversal def pointed_traversal.as_hom {n} (θ : pointed_traversal n) : Δ[n] ⟶ traversal.𝕋₁ := simplex_as_hom θ
5adc529c09c7b635924cde7e98ce51d917bc8b23
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/module/submodule/basic.lean
edee030082de4371f02c1ccd0461e03b82f9288e
[ "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
17,530
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import algebra.module.linear_map import algebra.module.equiv import group_theory.group_action.sub_mul_action /-! # Submodules of a module In this file we define * `submodule R M` : a subset of a `module` `M` that contains zero and is closed with respect to addition and scalar multiplication. * `subspace k M` : an abbreviation for `submodule` assuming that `k` is a `field`. ## Tags submodule, subspace, linear map -/ open function open_locale big_operators universes u'' u' u v w variables {G : Type u''} {S : Type u'} {R : Type u} {M : Type v} {ι : Type w} set_option old_structure_cmd true /-- `submodule_class S R M` says `S` is a type of submodules `s ≤ M`. -/ class submodule_class (S : Type*) (R M : out_param $ Type*) [add_zero_class M] [has_smul R M] [set_like S M] [add_submonoid_class S M] extends smul_mem_class S R M /-- A submodule of a module is one which is closed under vector operations. This is a sufficient condition for the subset of vectors in the submodule to themselves form a module. -/ structure submodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] extends add_submonoid M, sub_mul_action R M : Type v. /-- Reinterpret a `submodule` as an `add_submonoid`. -/ add_decl_doc submodule.to_add_submonoid /-- Reinterpret a `submodule` as an `sub_mul_action`. -/ add_decl_doc submodule.to_sub_mul_action namespace submodule variables [semiring R] [add_comm_monoid M] [module R M] instance : set_like (submodule R M) M := { coe := submodule.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } instance : add_submonoid_class (submodule R M) M := { zero_mem := zero_mem', add_mem := add_mem' } instance : submodule_class (submodule R M) R M := { smul_mem := smul_mem' } @[simp] theorem mem_to_add_submonoid (p : submodule R M) (x : M) : x ∈ p.to_add_submonoid ↔ x ∈ p := iff.rfl variables {p q : submodule R M} @[simp] lemma mem_mk {S : set M} {x : M} (h₁ h₂ h₃) : x ∈ (⟨S, h₁, h₂, h₃⟩ : submodule R M) ↔ x ∈ S := iff.rfl @[simp] lemma coe_set_mk (S : set M) (h₁ h₂ h₃) : ((⟨S, h₁, h₂, h₃⟩ : submodule R M) : set M) = S := rfl @[simp] lemma mk_le_mk {S S' : set M} (h₁ h₂ h₃ h₁' h₂' h₃') : (⟨S, h₁, h₂, h₃⟩ : submodule R M) ≤ (⟨S', h₁', h₂', h₃'⟩ : submodule R M) ↔ S ⊆ S' := iff.rfl @[ext] theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a submodule with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (p : submodule R M) (s : set M) (hs : s = ↑p) : submodule R M := { carrier := s, zero_mem' := hs.symm ▸ p.zero_mem', add_mem' := λ _ _, hs.symm ▸ p.add_mem', smul_mem' := hs.symm ▸ p.smul_mem' } @[simp] lemma coe_copy (S : submodule R M) (s : set M) (hs : s = ↑S) : (S.copy s hs : set M) = s := rfl lemma copy_eq (S : submodule R M) (s : set M) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs theorem to_add_submonoid_injective : injective (to_add_submonoid : submodule R M → add_submonoid M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_add_submonoid_eq : p.to_add_submonoid = q.to_add_submonoid ↔ p = q := to_add_submonoid_injective.eq_iff @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : submodule R M → add_submonoid M) := λ _ _, id lemma to_add_submonoid_le : p.to_add_submonoid ≤ q.to_add_submonoid ↔ p ≤ q := iff.rfl @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : submodule R M → add_submonoid M) := to_add_submonoid_strict_mono.monotone @[simp] theorem coe_to_add_submonoid (p : submodule R M) : (p.to_add_submonoid : set M) = p := rfl theorem to_sub_mul_action_injective : injective (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp] theorem to_sub_mul_action_eq : p.to_sub_mul_action = q.to_sub_mul_action ↔ p = q := to_sub_mul_action_injective.eq_iff @[mono] lemma to_sub_mul_action_strict_mono : strict_mono (to_sub_mul_action : submodule R M → sub_mul_action R M) := λ _ _, id @[mono] lemma to_sub_mul_action_mono : monotone (to_sub_mul_action : submodule R M → sub_mul_action R M) := to_sub_mul_action_strict_mono.monotone @[simp] theorem coe_to_sub_mul_action (p : submodule R M) : (p.to_sub_mul_action : set M) = p := rfl end submodule namespace submodule_class variables [semiring R] [add_comm_monoid M] [module R M] {A : Type*} [set_like A M] [add_submonoid_class A M] [hA : submodule_class A R M] (S' : A) include hA /-- A submodule of a `module` is a `module`. -/ @[priority 75] -- Prefer subclasses of `module` over `submodule_class`. instance to_module : module R S' := subtype.coe_injective.module R (add_submonoid_class.subtype S') (set_like.coe_smul S') /-- The natural `R`-linear map from a submodule of an `R`-module `M` to `M`. -/ protected def subtype : S' →ₗ[R] M := ⟨coe, λ _ _, rfl, λ _ _, rfl⟩ @[simp] protected theorem coe_subtype : (submodule_class.subtype S' : S' → M) = coe := rfl end submodule_class namespace submodule section add_comm_monoid variables [semiring R] [add_comm_monoid M] -- We can infer the module structure implicitly from the bundled submodule, -- rather than via typeclass resolution. variables {module_M : module R M} variables {p q : submodule R M} variables {r : R} {x y : M} variables (p) @[simp] lemma mem_carrier : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[simp] protected lemma zero_mem : (0 : M) ∈ p := zero_mem _ protected lemma add_mem (h₁ : x ∈ p) (h₂ : y ∈ p) : x + y ∈ p := add_mem h₁ h₂ lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h lemma smul_of_tower_mem [has_smul S R] [has_smul S M] [is_scalar_tower S R M] (r : S) (h : x ∈ p) : r • x ∈ p := p.to_sub_mul_action.smul_of_tower_mem r h protected lemma sum_mem {t : finset ι} {f : ι → M} : (∀c∈t, f c ∈ p) → (∑ i in t, f i) ∈ p := sum_mem lemma sum_smul_mem {t : finset ι} {f : ι → M} (r : ι → R) (hyp : ∀ c ∈ t, f c ∈ p) : (∑ i in t, r i • f i) ∈ p := sum_mem (λ i hi, smul_mem _ _ (hyp i hi)) @[simp] lemma smul_mem_iff' [group G] [mul_action G M] [has_smul G R] [is_scalar_tower G R M] (g : G) : g • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff' g instance : has_add p := ⟨λx y, ⟨x.1 + y.1, add_mem x.2 y.2⟩⟩ instance : has_zero p := ⟨⟨0, zero_mem _⟩⟩ instance : inhabited p := ⟨0⟩ instance [has_smul S R] [has_smul S M] [is_scalar_tower S R M] : has_smul S p := ⟨λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩⟩ instance [has_smul S R] [has_smul S M] [is_scalar_tower S R M] : is_scalar_tower S R p := p.to_sub_mul_action.is_scalar_tower instance is_scalar_tower' {S' : Type*} [has_smul S R] [has_smul S M] [has_smul S' R] [has_smul S' M] [has_smul S S'] [is_scalar_tower S' R M] [is_scalar_tower S S' M] [is_scalar_tower S R M] : is_scalar_tower S S' p := p.to_sub_mul_action.is_scalar_tower' instance [has_smul S R] [has_smul S M] [is_scalar_tower S R M] [has_smul Sᵐᵒᵖ R] [has_smul Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] : is_central_scalar S p := p.to_sub_mul_action.is_central_scalar protected lemma nonempty : (p : set M).nonempty := ⟨0, p.zero_mem⟩ @[simp] lemma mk_eq_zero {x} (h : x ∈ p) : (⟨x, h⟩ : p) = 0 ↔ x = 0 := subtype.ext_iff_val variables {p} @[simp, norm_cast] lemma coe_eq_zero {x : p} : (x : M) = 0 ↔ x = 0 := (set_like.coe_eq_coe : (x : M) = (0 : p) ↔ x = 0) @[simp, norm_cast] lemma coe_add (x y : p) : (↑(x + y) : M) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : p) : M) = 0 := rfl @[norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_smul_of_tower [has_smul S R] [has_smul S M] [is_scalar_tower S R M] (r : S) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl @[simp] lemma coe_mem (x : p) : (x : M) ∈ p := x.2 variables (p) instance : add_comm_monoid p := { add := (+), zero := 0, .. p.to_add_submonoid.to_add_comm_monoid } instance module' [semiring S] [has_smul S R] [module S M] [is_scalar_tower S R M] : module S p := by refine {smul := (•), ..p.to_sub_mul_action.mul_action', ..}; { intros, apply set_coe.ext, simp [smul_add, add_smul, mul_smul] } instance : module R p := p.module' instance no_zero_smul_divisors [no_zero_smul_divisors R M] : no_zero_smul_divisors R p := ⟨λ c x h, have c = 0 ∨ (x : M) = 0, from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h), this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩ /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →ₗ[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] theorem subtype_apply (x : p) : p.subtype x = x := rfl @[simp] lemma coe_subtype : ((submodule.subtype p) : p → M) = coe := rfl lemma injective_subtype : injective p.subtype := subtype.coe_injective /-- Note the `add_submonoid` version of this lemma is called `add_submonoid.coe_finset_sum`. -/ @[simp] lemma coe_sum (x : ι → p) (s : finset ι) : ↑(∑ i in s, x i) = ∑ i in s, (x i : M) := p.subtype.map_sum section restrict_scalars variables (S) [semiring S] [module S M] [module R M] [has_smul S R] [is_scalar_tower S R M] /-- `V.restrict_scalars S` is the `S`-submodule of the `S`-module given by restriction of scalars, corresponding to `V`, an `R`-submodule of the original `R`-module. -/ def restrict_scalars (V : submodule R M) : submodule S M := { carrier := V, zero_mem' := V.zero_mem, smul_mem' := λ c m h, V.smul_of_tower_mem c h, add_mem' := λ x y hx hy, V.add_mem hx hy } @[simp] lemma coe_restrict_scalars (V : submodule R M) : (V.restrict_scalars S : set M) = V := rfl @[simp] lemma restrict_scalars_mem (V : submodule R M) (m : M) : m ∈ V.restrict_scalars S ↔ m ∈ V := iff.refl _ @[simp] lemma restrict_scalars_self (V : submodule R M) : V.restrict_scalars R = V := set_like.coe_injective rfl variables (R S M) lemma restrict_scalars_injective : function.injective (restrict_scalars S : submodule R M → submodule S M) := λ V₁ V₂ h, ext $ set.ext_iff.1 (set_like.ext'_iff.1 h : _) @[simp] lemma restrict_scalars_inj {V₁ V₂ : submodule R M} : restrict_scalars S V₁ = restrict_scalars S V₂ ↔ V₁ = V₂ := (restrict_scalars_injective S _ _).eq_iff /-- Even though `p.restrict_scalars S` has type `submodule S M`, it is still an `R`-module. -/ instance restrict_scalars.orig_module (p : submodule R M) : module R (p.restrict_scalars S) := (by apply_instance : module R p) instance (p : submodule R M) : is_scalar_tower S R (p.restrict_scalars S) := { smul_assoc := λ r s x, subtype.ext $ smul_assoc r s (x : M) } /-- `restrict_scalars S` is an embedding of the lattice of `R`-submodules into the lattice of `S`-submodules. -/ @[simps] def restrict_scalars_embedding : submodule R M ↪o submodule S M := { to_fun := restrict_scalars S, inj' := restrict_scalars_injective S R M, map_rel_iff' := λ p q, by simp [set_like.le_def] } /-- Turning `p : submodule R M` into an `S`-submodule gives the same module structure as turning it into a type and adding a module structure. -/ @[simps {simp_rhs := tt}] def restrict_scalars_equiv (p : submodule R M) : p.restrict_scalars S ≃ₗ[R] p := { to_fun := id, inv_fun := id, map_smul' := λ c x, rfl, .. add_equiv.refl p } end restrict_scalars end add_comm_monoid section add_comm_group variables [ring R] [add_comm_group M] variables {module_M : module R M} variables (p p' : submodule R M) variables {r : R} {x y : M} instance [module R M] : add_subgroup_class (submodule R M) M := { neg_mem := λ p x, p.to_sub_mul_action.neg_mem, .. submodule.add_submonoid_class } protected lemma neg_mem (hx : x ∈ p) : -x ∈ p := neg_mem hx /-- Reinterpret a submodule as an additive subgroup. -/ def to_add_subgroup : add_subgroup M := { neg_mem' := λ _, p.neg_mem , .. p.to_add_submonoid } @[simp] lemma coe_to_add_subgroup : (p.to_add_subgroup : set M) = p := rfl @[simp] lemma mem_to_add_subgroup : x ∈ p.to_add_subgroup ↔ x ∈ p := iff.rfl include module_M theorem to_add_subgroup_injective : injective (to_add_subgroup : submodule R M → add_subgroup M) | p q h := set_like.ext (set_like.ext_iff.1 h : _) @[simp] theorem to_add_subgroup_eq : p.to_add_subgroup = p'.to_add_subgroup ↔ p = p' := to_add_subgroup_injective.eq_iff @[mono] lemma to_add_subgroup_strict_mono : strict_mono (to_add_subgroup : submodule R M → add_subgroup M) := λ _ _, id lemma to_add_subgroup_le : p.to_add_subgroup ≤ p'.to_add_subgroup ↔ p ≤ p' := iff.rfl @[mono] lemma to_add_subgroup_mono : monotone (to_add_subgroup : submodule R M → add_subgroup M) := to_add_subgroup_strict_mono.monotone omit module_M protected lemma sub_mem : x ∈ p → y ∈ p → x - y ∈ p := sub_mem protected lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := neg_mem_iff protected lemma add_mem_iff_left : y ∈ p → (x + y ∈ p ↔ x ∈ p) := add_mem_cancel_right protected lemma add_mem_iff_right : x ∈ p → (x + y ∈ p ↔ y ∈ p) := add_mem_cancel_left protected lemma coe_neg (x : p) : ((-x : p) : M) = -x := add_subgroup_class.coe_neg _ protected lemma coe_sub (x y : p) : (↑(x - y) : M) = ↑x - ↑y := add_subgroup_class.coe_sub _ _ lemma sub_mem_iff_left (hy : y ∈ p) : (x - y) ∈ p ↔ x ∈ p := by rw [sub_eq_add_neg, p.add_mem_iff_left (p.neg_mem hy)] lemma sub_mem_iff_right (hx : x ∈ p) : (x - y) ∈ p ↔ y ∈ p := by rw [sub_eq_add_neg, p.add_mem_iff_right hx, p.neg_mem_iff] instance : add_comm_group p := { add := (+), zero := 0, neg := has_neg.neg, ..p.to_add_subgroup.to_add_comm_group } end add_comm_group section is_domain variables [ring R] [is_domain R] variables [add_comm_group M] [module R M] {b : ι → M} lemma not_mem_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ∉ N := by { intro hx, simpa using ortho (-1) x hx } lemma ne_zero_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ≠ 0 := mt (λ h, show x ∈ N, from h.symm ▸ N.zero_mem) (not_mem_of_ortho ortho) end is_domain section ordered_monoid variables [semiring R] /-- A submodule of an `ordered_add_comm_monoid` is an `ordered_add_comm_monoid`. -/ instance to_ordered_add_comm_monoid {M} [ordered_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_add_comm_monoid S := subtype.coe_injective.ordered_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_monoid` is a `linear_ordered_add_comm_monoid`. -/ instance to_linear_ordered_add_comm_monoid {M} [linear_ordered_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_add_comm_monoid S := subtype.coe_injective.linear_ordered_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A submodule of an `ordered_cancel_add_comm_monoid` is an `ordered_cancel_add_comm_monoid`. -/ instance to_ordered_cancel_add_comm_monoid {M} [ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : ordered_cancel_add_comm_monoid S := subtype.coe_injective.ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_cancel_add_comm_monoid` is a `linear_ordered_cancel_add_comm_monoid`. -/ instance to_linear_ordered_cancel_add_comm_monoid {M} [linear_ordered_cancel_add_comm_monoid M] [module R M] (S : submodule R M) : linear_ordered_cancel_add_comm_monoid S := subtype.coe_injective.linear_ordered_cancel_add_comm_monoid coe rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end ordered_monoid section ordered_group variables [ring R] /-- A submodule of an `ordered_add_comm_group` is an `ordered_add_comm_group`. -/ instance to_ordered_add_comm_group {M} [ordered_add_comm_group M] [module R M] (S : submodule R M) : ordered_add_comm_group S := subtype.coe_injective.ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A submodule of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`. -/ instance to_linear_ordered_add_comm_group {M} [linear_ordered_add_comm_group M] [module R M] (S : submodule R M) : linear_ordered_add_comm_group S := subtype.coe_injective.linear_ordered_add_comm_group coe rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) end ordered_group end submodule namespace submodule variables [division_ring S] [semiring R] [add_comm_monoid M] [module R M] variables [has_smul S R] [module S M] [is_scalar_tower S R M] variables (p : submodule R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.to_sub_mul_action.smul_mem_iff s0 end submodule /-- Subspace of a vector space. Defined to equal `submodule`. -/ abbreviation subspace (R : Type u) (M : Type v) [division_ring R] [add_comm_group M] [module R M] := submodule R M
a2ea3f8b4991f9c94291ff4725fcde9ff8ece004
d3aa99b88d7159fbbb8ab10d699374ab7be89e03
/src/meta/expr.lean
b2e09c78c3516566923969390ba4708f991606e9
[ "Apache-2.0" ]
permissive
mzinkevi/mathlib
62e0920edaf743f7fc53aaf42a08e372954af298
c718a22925872db4cb5f64c36ed6e6a07bdf647c
refs/heads/master
1,599,359,590,404
1,573,098,221,000
1,573,098,221,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,258
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis -/ import data.string.defs /-! # Additional operations on expr and related types This file defines basic operations on the types expr, name, declaration, level, environment. This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`. ## Tags expr, name, declaration, level, environment, meta, metaprogramming, tactic -/ namespace binder_info instance : inhabited binder_info := ⟨ binder_info.default ⟩ /-- The brackets corresponding to a given binder_info. -/ def brackets : binder_info → string × string | binder_info.implicit := ("{", "}") | binder_info.strict_implicit := ("{{", "}}") | binder_info.inst_implicit := ("[", "]") | _ := ("(", ")") end binder_info namespace name /-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix with the value of `f n`. -/ def map_prefix (f : name → option name) : name → name | anonymous := anonymous | (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n') | (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n') /-- If `nm` is a simple name (having only one string component) starting with `_`, then `deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/ meta def deinternalize_field : name → name | (mk_string s name.anonymous) := let i := s.mk_iterator in if i.curr = '_' then i.next.next_to_string else s | n := n /-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/ meta def get_nth_prefix : name → ℕ → name | nm 0 := nm | nm (n + 1) := get_nth_prefix nm.get_prefix n /-- Auxilliary definition for `pop_nth_prefix` -/ private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ | anonymous n := (anonymous, 1) | nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in if height ≤ n then (anonymous, height + 1) else (nm.update_prefix pfx, height + 1) /-- Pops the top `n` prefixes from the given name. -/ meta def pop_nth_prefix (nm : name) (n : ℕ) : name := prod.fst $ pop_nth_prefix_aux nm n /-- Pop the prefix of a name -/ meta def pop_prefix (n : name) : name := pop_nth_prefix n 1 /-- Auxilliary definition for `from_components` -/ private def from_components_aux : name → list string → name | n [] := n | n (s :: rest) := from_components_aux (name.mk_string s n) rest /-- Build a name from components. For example `from_components ["foo","bar"]` becomes ``` `foo.bar``` -/ def from_components : list string → name := from_components_aux name.anonymous /-- `name`s can contain numeral pieces, which are not legal names when typed/passed directly to the parser. We turn an arbitrary name into a legal identifier name by turning the numbers to strings. -/ meta def sanitize_name : name → name | name.anonymous := name.anonymous | (name.mk_string s p) := name.mk_string s $ sanitize_name p | (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p /-- Append a string to the last component of a name -/ def append_suffix : name → string → name | (mk_string s n) s' := mk_string (s ++ s') n | n _ := n /-- The first component of a name, turning a number to a string -/ meta def head : name → string | (mk_string s anonymous) := s | (mk_string s p) := head p | (mk_numeral n p) := head p | anonymous := "[anonymous]" /-- Tests whether the first component of a name is `"_private"` -/ meta def is_private (n : name) : bool := n.head = "_private" /-- Get the last component of a name, and convert it to a string. -/ meta def last : name → string | (mk_string s _) := s | (mk_numeral n _) := repr n | anonymous := "[anonymous]" /-- Returns the number of characters used to print all the string components of a name, including periods between name segments. Ignores numerical parts of a name. -/ meta def length : name → ℕ | (mk_string s anonymous) := s.length | (mk_string s p) := s.length + 1 + p.length | (mk_numeral n p) := p.length | anonymous := "[anonymous]".length /-- Checks whether `nm` has a prefix (including itself) such that P is true -/ def has_prefix (P : name → bool) : name → bool | anonymous := ff | (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm | (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm /-- Appends `'` to the end of a name. -/ meta def add_prime : name → name | (name.mk_string s p) := name.mk_string (s ++ "'") p | n := (name.mk_string "x'" n) end name namespace level /-- Tests whether a universe level is non-zero for all assignments of its variables -/ meta def nonzero : level → bool | (succ _) := tt | (max l₁ l₂) := l₁.nonzero || l₂.nonzero | (imax _ l₂) := l₂.nonzero | _ := ff end level /-- The type of binders containing a name, the binding info and the binding type -/ @[derive decidable_eq] meta structure binder := (name : name) (info : binder_info) (type : expr) namespace binder /-- Turn a binder into a string. Uses expr.to_string for the type. -/ protected meta def to_string (b : binder) : string := let (l, r) := b.info.brackets in l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r open tactic meta instance : inhabited binder := ⟨⟨default _, default _, default _⟩⟩ meta instance : has_to_string binder := ⟨ binder.to_string ⟩ meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩ meta instance : has_to_tactic_format binder := ⟨ λ b, let (l, r) := b.info.brackets in (λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩ end binder /- converting between expressions and numerals -/ /-- `nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc. -/ meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr := let z : expr := `(@has_zero.zero.{0} %%type %%has_zero), o : expr := `(@has_one.one.{0} %%type %%has_one) in nat.binary_rec z (λ b n e, if n = 0 then o else if b then `(@bit1.{0} %%type %%has_one %%has_add %%e) else `(@bit0.{0} %%type %%has_add %%e)) /-- `int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -. `type`: an expression representing the target type. This must live in Type 0. `has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc. -/ meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr | (int.of_nat n) := n.mk_numeral type has_zero has_one has_add | -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in `(@has_neg.neg.{0} %%type %%has_neg %%ne) namespace expr /-- Turns an expression into a positive natural number, assuming it is only built up from `has_one.one`, `bit0` and `bit1`. -/ protected meta def to_pos_nat : expr → option ℕ | `(has_one.one _) := some 1 | `(bit0 %%e) := bit0 <$> e.to_pos_nat | `(bit1 %%e) := bit1 <$> e.to_pos_nat | _ := none /-- Turns an expression into a natural number, assuming it is only built up from `has_one.one`, `bit0`, `bit1` and `has_zero.zero`. -/ protected meta def to_nat : expr → option ℕ | `(has_zero.zero _) := some 0 | e := e.to_pos_nat /-- Turns an expression into a integer, assuming it is only built up from `has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head. -/ protected meta def to_int : expr → option ℤ | `(has_neg.neg %%e) := do n ← e.to_nat, some (-n) | e := coe <$> e.to_nat end expr namespace expr open tactic /-- Apply a function to each constant (inductive type, defined function etc) in an expression. -/ protected meta def apply_replacement_fun (f : name → name) (e : expr) : expr := e.replace $ λ e d, match e with | expr.const n ls := some $ expr.const (f n) ls | _ := none end /-- Tests whether an expression is a meta-variable. -/ meta def is_mvar : expr → bool | (mvar _ _ _) := tt | _ := ff /-- Tests whether an expression is a sort. -/ meta def is_sort : expr → bool | (sort _) := tt | e := ff /-- If `e` is a local constant, `to_implicit e` changes the binder info of `e` to `implicit`. -/ meta def to_implicit : expr → expr | (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t | e := e /-- Returns a list of all local constants in an expression (without duplicates). -/ meta def list_local_consts (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es) /-- Returns a name_set of all constants in an expression. -/ meta def list_constant (e : expr) : name_set := e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es) /-- Returns a list of all meta-variables in an expression (without duplicates). -/ meta def list_meta_vars (e : expr) : list expr := e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es) /-- Returns a name_set of all constants in an expression starting with a certain prefix. -/ meta def list_names_with_prefix (pre : name) (e : expr) : name_set := e.fold mk_name_set $ λ e' _ l, match e' with | expr.const n _ := if n.get_prefix = pre then l.insert n else l | _ := l end /-- Returns true if `e` contains a name `n` where `p n` is true. Returns `true` if `p name.anonymous` is true -/ meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool := e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b) /-- is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure, ignoring differences in type and type class arguments. -/ meta def is_num_eq : expr → expr → bool | `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt | `(@has_one.one _ _) `(@has_one.one _ _) := tt | `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b | `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b | `(-%%a) `(-%%b) := a.is_num_eq b | `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b | _ _ := ff /-- Simplifies the expression `t` with the specified options. The result is `(new_e, pr)` with the new expression `new_e` and a proof `pr : e = new_e`. -/ meta def simp (t : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger /-- Definitionally simplifies the expression `t` with the specified options. The result is the simplified expression. -/ meta def dsimp (t : expr) (cfg : dsimp_config := {}) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg /-- Auxilliary definition for `expr.pi_arity` -/ meta def pi_arity_aux : ℕ → expr → ℕ | n (pi _ _ _ b) := pi_arity_aux (n + 1) b | n e := n /-- The arity of a pi-type. Does not perform any reduction of the expression. In one application this was ~30 times quicker than `tactic.get_pi_arity`. -/ meta def pi_arity : expr → ℕ := pi_arity_aux 0 /-- Get the names of the bound variables by a sequence of pis or lambdas. -/ meta def binding_names : expr → list name | (pi n _ _ e) := n :: e.binding_names | (lam n _ _ e) := n :: e.binding_names | e := [] /-- head-reduce a single let expression -/ meta def reduce_let : expr → expr | (elet _ _ v b) := b.instantiate_var v | e := e /-- head-reduce all let expressions -/ meta def reduce_lets : expr → expr | (elet _ _ v b) := reduce_lets $ b.instantiate_var v | e := e /-- Instantiate lambdas in the second argument by expressions from the first. -/ meta def instantiate_lambdas : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e') | _ e := e /-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms. Also reduces head let-expressions in `e`, including those after instantiating all lambdas. -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v | es e := mk_app e es /- Note [open expressions]: Some declarations work with open expressions, i.e. an expr that has free variables. Terms will free variables are not well-typed, and one should not use them in tactics like `infer_type` or `unify`. You can still do syntactic analysis/manipulation on them. The reason for working with open types is for performance: instantiating variables requires iterating through the expression. In one performance test `pi_binders` was more than 6x quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x). -/ /-- Get the codomain/target of a pi-type. This definition doesn't Instantiate bound variables, and therefore produces a term that is open.-/ meta def pi_codomain : expr → expr -- see note [open expressions] | (pi n bi d b) := pi_codomain b | e := e /-- Auxilliary defintion for `pi_binders`. -/ -- see note [open expressions] meta def pi_binders_aux : list binder → expr → list binder × expr | es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b | es e := (es, e) /-- Get the binders and codomain of a pi-type. This definition doesn't Instantiate bound variables, and therefore produces a term that is open. The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the free variables -/ meta def pi_binders (e : expr) : list binder × expr := -- see note [open expressions] let (es, e) := pi_binders_aux [] e in (es.reverse, e) /-- Auxilliary defintion for `get_app_fn_args`. -/ meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) /-- A combination of `get_app_fn` and `get_app_args`: lists both the function and its arguments of an application -/ meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] /-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/ meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed /-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`. Returns `empty` if the list is empty. -/ meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es /-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/ meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) /-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/ meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) /-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant. Otherwise returns `binder_info.default`. -/ meta def local_binding_info : expr → binder_info | (expr.local_const _ _ bi _) := bi | _ := binder_info.default /-- `is_default_local e` tests whether `e` is a local constant with binder info `binder_info.default` -/ meta def is_default_local : expr → bool | (expr.local_const _ _ binder_info.default _) := tt | _ := ff end expr namespace environment /-- Tests whether a name is declared in the current file. Fixes an error in `in_current_file` which returns `tt` for the four names `quot, quot.mk, quot.lift, quot.ind` -/ meta def in_current_file' (env : environment) (n : name) : bool := env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind]) /-- Tests whether `n` is an inductive type with one constructor without indices. If so, returns the number of paramaters and the name of the constructor. Otherwise, returns `none`. -/ meta def is_structure_like (env : environment) (n : name) : option (nat × name) := do guardb (env.is_inductive n), d ← (env.get n).to_option, [intro] ← pure (env.constructors_of n) | none, guard (env.inductive_num_indices n = 0), some (env.inductive_num_params n, intro) /-- Tests whether `n` is a structure. It will first test whether `n` is structure-like and then test that the first projection is defined in the environment and is a projection. -/ meta def is_structure (env : environment) (n : name) : bool := option.is_some $ do (nparams, intro) ← env.is_structure_like n, di ← (env.get intro).to_option, expr.pi x _ _ _ ← nparams.iterate (λ e : option expr, do expr.pi _ _ _ body ← e | none, some body) (some di.type) | none, env.is_projection (n ++ x.deinternalize_field) /-- Get all projections of the structure `n`. Returns `none` if `n` is not structure-like. If `n` is not a structure, but is structure-like, this does not check whether the names are existing declarations. -/ meta def get_projections (env : environment) (n : name) : option (list name) := do (nparams, intro) ← env.is_structure_like n, di ← (env.get intro).to_option, tgt ← nparams.iterate (λ e : option expr, do expr.pi _ _ _ body ← e | none, some body) (some di.type) | none, return $ tgt.binding_names.map (λ x, n ++ x.deinternalize_field) /-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type. Note that `is_ginductive` returns `tt` even on regular inductive types. This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive type. -/ meta def is_ginductive' (e : environment) (nm : name) : bool := e.is_ginductive nm ∧ ¬ e.is_inductive nm /-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/ meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α := e.fold [] $ λ d l, match f d with | some r := r :: l | none := l end /-- Maps `f` to all declarations in the environment. -/ meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α := e.decl_filter_map $ λ d, some (f d) /-- Lists all declarations in the environment -/ meta def get_decls (e : environment) : list declaration := e.decl_map id /-- Lists all trusted (non-meta) declarations in the environment -/ meta def get_trusted_decls (e : environment) : list declaration := e.decl_filter_map (λ d, if d.is_trusted then some d else none) /-- Lists the name of all declarations in the environment -/ meta def get_decl_names (e : environment) : list name := e.decl_map declaration.to_name /-- Fold a monad over all declarations in the environment. -/ meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α) (fn : declaration → α → m α) : m α := e.fold (return x) (λ d t, t >>= fn d) /-- Filters all declarations in the environment. -/ meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) := e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds /-- Checks whether `s` is a prefix of the file where `n` is declared. This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/ meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool := s.is_prefix_of $ (e.decl_olean n).get_or_else "" end environment namespace expr /- In this section we define the tactic `is_eta_expansion` which checks whether an expression is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`). -/ open tactic /-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have `pr = nm.{univs} args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) : bool := l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args /-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`. Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we want to eta-reduce. -/ meta def is_eta_expansion_test : list (name × expr) → option expr | [] := none | (⟨proj, val⟩::l) := match val.get_app_fn with | (const nm univs : expr) := if nm = proj then let args := val.get_app_args in let e := args.ilast in if is_eta_expansion_of args univs l then some e else none else none | _ := none end /-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`. Here `l` is intended to consists of the projections and the fields of `val`. This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and afterward checks whether the retulting expression `e` unifies with `val`. This last check is necessary, because `val` and `e` might have different types. -/ meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) := do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val), match is_eta_expansion_test l' with | some e := option.map (λ _, e) <$> try_core (unify e val) | none := return none end /-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. With eta-expansion we here mean the eta-expansion of a structure, not of a function. For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`. This assumes that `val` is a fully-applied application of the constructor of a structure. This is useful to reduce expressions generated by the notation `{ field_1 := _, ..other_structure }` If `other_structure` is itself a field of the structure, then the elaborator will insert an eta-expanded version of `other_structure`. -/ meta def is_eta_expansion (val : expr) : tactic (option expr) := do e ← get_env, type ← infer_type val, projs ← e.get_projections type.get_app_fn.const_name, let args := (val.get_app_args).drop type.get_app_args.length, is_eta_expansion_aux val (projs.zip args) end expr namespace declaration open tactic protected meta def update_with_fun (f : name → name) (tgt : name) (decl : declaration) : declaration := let decl := decl.update_name $ tgt in let decl := decl.update_type $ decl.type.apply_replacement_fun f in decl.update_value $ decl.value.apply_replacement_fun f /-- Checks whether the declaration is declared in the current file. This is a simple wrapper around `environment.in_current_file'` Use `environment.in_current_file'` instead if performance matters. -/ meta def in_current_file (d : declaration) : tactic bool := do e ← get_env, return $ e.in_current_file' d.to_name /-- Checks whether a declaration is a theorem -/ meta def is_theorem : declaration → bool | (thm _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a constant -/ meta def is_constant : declaration → bool | (cnst _ _ _ _) := tt | _ := ff /-- Checks whether a declaration is a axiom -/ meta def is_axiom : declaration → bool | (ax _ _ _) := tt | _ := ff /-- Checks whether a declaration is automatically generated in the environment. There is no cheap way to check whether a declaration in the namespace of a generalized inductive type is automatically generated, so for now we say that all of them are automatically generated. -/ meta def is_auto_generated (e : environment) (d : declaration) : bool := e.is_constructor d.to_name ∨ (e.is_projection d.to_name).is_some ∨ (e.is_constructor d.to_name.get_prefix ∧ d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨ (e.is_inductive d.to_name.get_prefix ∧ d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec", "rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨ d.to_name.has_prefix (λ nm, e.is_ginductive' nm) /-- Returns the list of universe levels of a declaration. -/ meta def univ_levels (d : declaration) : list level := d.univ_params.map level.param end declaration
930ba0a9de4e97fdad223650996f5bda9b6b89cc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed_space/banach_steinhaus.lean
c8d8c11946514a524fcf8784a3756054ed6168e6
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
6,491
lean
/- Copyright (c) 2021 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.operator_norm import topology.metric_space.baire import topology.algebra.module.basic /-! # The Banach-Steinhaus theorem: Uniform Boundedness Principle > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Herein we prove the Banach-Steinhaus theorem: any collection of bounded linear maps from a Banach space into a normed space which is pointwise bounded is uniformly bounded. ## TODO For now, we only prove the standard version by appeal to the Baire category theorem. Much more general versions exist (in particular, for maps from barrelled spaces to locally convex spaces), but these are not yet in `mathlib`. -/ open set variables {E F 𝕜 𝕜₂ : Type*} [seminormed_add_comm_group E] [seminormed_add_comm_group F] [nontrivially_normed_field 𝕜] [nontrivially_normed_field 𝕜₂] [normed_space 𝕜 E] [normed_space 𝕜₂ F] {σ₁₂ : 𝕜 →+* 𝕜₂} [ring_hom_isometric σ₁₂] /-- This is the standard Banach-Steinhaus theorem, or Uniform Boundedness Principle. If a family of continuous linear maps from a Banach space into a normed space is pointwise bounded, then the norms of these linear maps are uniformly bounded. -/ theorem banach_steinhaus {ι : Type*} [complete_space E] {g : ι → E →SL[σ₁₂] F} (h : ∀ x, ∃ C, ∀ i, ‖g i x‖ ≤ C) : ∃ C', ∀ i, ‖g i‖ ≤ C' := begin /- sequence of subsets consisting of those `x : E` with norms `‖g i x‖` bounded by `n` -/ let e : ℕ → set E := λ n, (⋂ i : ι, { x : E | ‖g i x‖ ≤ n }), /- each of these sets is closed -/ have hc : ∀ n : ℕ, is_closed (e n), from λ i, is_closed_Inter (λ i, is_closed_le (continuous.norm (g i).cont) continuous_const), /- the union is the entire space; this is where we use `h` -/ have hU : (⋃ n : ℕ, e n) = univ, { refine eq_univ_of_forall (λ x, _), cases h x with C hC, obtain ⟨m, hm⟩ := exists_nat_ge C, exact ⟨e m, mem_range_self m, mem_Inter.mpr (λ i, le_trans (hC i) hm)⟩ }, /- apply the Baire category theorem to conclude that for some `m : ℕ`, `e m` contains some `x` -/ rcases nonempty_interior_of_Union_of_closed hc hU with ⟨m, x, hx⟩, rcases metric.is_open_iff.mp is_open_interior x hx with ⟨ε, ε_pos, hε⟩, obtain ⟨k, hk⟩ := normed_field.exists_one_lt_norm 𝕜, /- show all elements in the ball have norm bounded by `m` after applying any `g i` -/ have real_norm_le : ∀ z : E, z ∈ metric.ball x ε → ∀ i : ι, ‖g i z‖ ≤ m, { intros z hz i, replace hz := mem_Inter.mp (interior_Inter_subset _ (hε hz)) i, apply interior_subset hz }, have εk_pos : 0 < ε / ‖k‖ := div_pos ε_pos (zero_lt_one.trans hk), refine ⟨(m + m : ℕ) / (ε / ‖k‖), λ i, continuous_linear_map.op_norm_le_of_shell ε_pos _ hk _⟩, { exact div_nonneg (nat.cast_nonneg _) εk_pos.le }, intros y le_y y_lt, calc ‖g i y‖ = ‖g i (y + x) - g i x‖ : by rw [continuous_linear_map.map_add, add_sub_cancel] ... ≤ ‖g i (y + x)‖ + ‖g i x‖ : norm_sub_le _ _ ... ≤ m + m : add_le_add (real_norm_le (y + x) (by rwa [add_comm, add_mem_ball_iff_norm]) i) (real_norm_le x (metric.mem_ball_self ε_pos) i) ... = (m + m : ℕ) : (m.cast_add m).symm ... ≤ (m + m : ℕ) * (‖y‖ / (ε / ‖k‖)) : le_mul_of_one_le_right (nat.cast_nonneg _) ((one_le_div $ div_pos ε_pos (zero_lt_one.trans hk)).2 le_y) ... = (m + m : ℕ) / (ε / ‖k‖) * ‖y‖ : (mul_comm_div _ _ _).symm, end open_locale ennreal open ennreal /-- This version of Banach-Steinhaus is stated in terms of suprema of `↑‖⬝‖₊ : ℝ≥0∞` for convenience. -/ theorem banach_steinhaus_supr_nnnorm {ι : Type*} [complete_space E] {g : ι → E →SL[σ₁₂] F} (h : ∀ x, (⨆ i, ↑‖g i x‖₊) < ∞) : (⨆ i, ↑‖g i‖₊) < ∞ := begin have h' : ∀ x : E, ∃ C : ℝ, ∀ i : ι, ‖g i x‖ ≤ C, { intro x, rcases lt_iff_exists_coe.mp (h x) with ⟨p, hp₁, _⟩, refine ⟨p, (λ i, _)⟩, exact_mod_cast calc (‖g i x‖₊ : ℝ≥0∞) ≤ ⨆ j, ‖g j x‖₊ : le_supr _ i ... = p : hp₁ }, cases banach_steinhaus h' with C' hC', refine (supr_le $ λ i, _).trans_lt (@coe_lt_top C'.to_nnreal), rw ←norm_to_nnreal, exact coe_mono (real.to_nnreal_le_to_nnreal $ hC' i), end open_locale topology open filter /-- Given a *sequence* of continuous linear maps which converges pointwise and for which the domain is complete, the Banach-Steinhaus theorem is used to guarantee that the limit map is a *continuous* linear map as well. -/ def continuous_linear_map_of_tendsto [complete_space E] [t2_space F] (g : ℕ → E →SL[σ₁₂] F) {f : E → F} (h : tendsto (λ n x, g n x) at_top (𝓝 f)) : E →SL[σ₁₂] F := { to_fun := f, map_add' := (linear_map_of_tendsto _ _ h).map_add', map_smul' := (linear_map_of_tendsto _ _ h).map_smul', cont := begin /- show that the maps are pointwise bounded and apply `banach_steinhaus`-/ have h_point_bdd : ∀ x : E, ∃ C : ℝ, ∀ n : ℕ, ‖g n x‖ ≤ C, { intro x, rcases cauchy_seq_bdd (tendsto_pi_nhds.mp h x).cauchy_seq with ⟨C, C_pos, hC⟩, refine ⟨C + ‖g 0 x‖, (λ n, _)⟩, simp_rw dist_eq_norm at hC, calc ‖g n x‖ ≤ ‖g 0 x‖ + ‖g n x - g 0 x‖ : norm_le_insert' _ _ ... ≤ C + ‖g 0 x‖ : by linarith [hC n 0] }, cases banach_steinhaus h_point_bdd with C' hC', /- show the uniform bound from `banach_steinhaus` is a norm bound of the limit map by allowing "an `ε` of room." -/ refine add_monoid_hom_class.continuous_of_bound (linear_map_of_tendsto _ _ h) C' (λ x, le_of_forall_pos_lt_add (λ ε ε_pos, _)), cases metric.tendsto_at_top.mp (tendsto_pi_nhds.mp h x) ε ε_pos with n hn, have lt_ε : ‖g n x - f x‖ < ε, by {rw ←dist_eq_norm, exact hn n (le_refl n)}, calc ‖f x‖ ≤ ‖g n x‖ + ‖g n x - f x‖ : norm_le_insert _ _ ... < ‖g n‖ * ‖x‖ + ε : by linarith [lt_ε, (g n).le_op_norm x] ... ≤ C' * ‖x‖ + ε : by nlinarith [hC' n, norm_nonneg x], end }
4b2ce97c359497025d052f2054487ee534a7d6d9
bb31430994044506fa42fd667e2d556327e18dfe
/src/group_theory/order_of_element.lean
c8fd227ddc3ed212ca077314129a903dcff99986
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
39,878
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, Julian Kuelshammer -/ import algebra.hom.iterate import data.nat.modeq import data.set.pointwise.basic import data.set.intervals.infinite import dynamics.periodic_pts import group_theory.index /-! # Order of an element This file defines the order of an element of a finite group. For a finite group `G` the order of `x ∈ G` is the minimal `n ≥ 1` such that `x ^ n = 1`. ## Main definitions * `is_of_fin_order` is a predicate on an element `x` of a monoid `G` saying that `x` is of finite order. * `is_of_fin_add_order` is the additive analogue of `is_of_fin_order`. * `order_of x` defines the order of an element `x` of a monoid `G`, by convention its value is `0` if `x` has infinite order. * `add_order_of` is the additive analogue of `order_of`. ## Tags order of an element -/ open function nat open_locale pointwise universes u v variables {G : Type u} {A : Type v} variables {x y : G} {a b : A} {n m : ℕ} section monoid_add_monoid variables [monoid G] [add_monoid A] section is_of_fin_order @[to_additive] lemma is_periodic_pt_mul_iff_pow_eq_one (x : G) : is_periodic_pt ((*) x) n 1 ↔ x ^ n = 1 := by rw [is_periodic_pt, is_fixed_pt, mul_left_iterate, mul_one] /-- `is_of_fin_add_order` is a predicate on an element `a` of an additive monoid to be of finite order, i.e. there exists `n ≥ 1` such that `n • a = 0`.-/ def is_of_fin_add_order (a : A) : Prop := (0 : A) ∈ periodic_pts ((+) a) /-- `is_of_fin_order` is a predicate on an element `x` of a monoid to be of finite order, i.e. there exists `n ≥ 1` such that `x ^ n = 1`.-/ @[to_additive is_of_fin_add_order] def is_of_fin_order (x : G) : Prop := (1 : G) ∈ periodic_pts ((*) x) lemma is_of_fin_add_order_of_mul_iff : is_of_fin_add_order (additive.of_mul x) ↔ is_of_fin_order x := iff.rfl lemma is_of_fin_order_of_add_iff : is_of_fin_order (multiplicative.of_add a) ↔ is_of_fin_add_order a := iff.rfl @[to_additive is_of_fin_add_order_iff_nsmul_eq_zero] lemma is_of_fin_order_iff_pow_eq_one (x : G) : is_of_fin_order x ↔ ∃ n, 0 < n ∧ x ^ n = 1 := by { convert iff.rfl, simp [is_periodic_pt_mul_iff_pow_eq_one] } /-- See also `injective_pow_iff_not_is_of_fin_order`. -/ @[to_additive not_is_of_fin_add_order_of_injective_nsmul "See also `injective_nsmul_iff_not_is_of_fin_add_order`."] lemma not_is_of_fin_order_of_injective_pow {x : G} (h : injective (λ (n : ℕ), x^n)) : ¬ is_of_fin_order x := begin simp_rw [is_of_fin_order_iff_pow_eq_one, not_exists, not_and], intros n hn_pos hnx, rw ← pow_zero x at hnx, rw h hnx at hn_pos, exact irrefl 0 hn_pos, end /-- Elements of finite order are of finite order in submonoids.-/ @[to_additive is_of_fin_add_order_iff_coe "Elements of finite order are of finite order in submonoids."] lemma is_of_fin_order_iff_coe (H : submonoid G) (x : H) : is_of_fin_order x ↔ is_of_fin_order (x : G) := by { rw [is_of_fin_order_iff_pow_eq_one, is_of_fin_order_iff_pow_eq_one], norm_cast } /-- The image of an element of finite order has finite order. -/ @[to_additive add_monoid_hom.is_of_fin_order "The image of an element of finite additive order has finite additive order."] lemma monoid_hom.is_of_fin_order {H : Type v} [monoid H] (f : G →* H) {x : G} (h : is_of_fin_order x) : is_of_fin_order $ f x := (is_of_fin_order_iff_pow_eq_one _).mpr $ begin rcases (is_of_fin_order_iff_pow_eq_one _).mp h with ⟨n, npos, hn⟩, exact ⟨n, npos, by rw [←f.map_pow, hn, f.map_one]⟩, end /-- If a direct product has finite order then so does each component. -/ @[to_additive "If a direct product has finite additive order then so does each component."] lemma is_of_fin_order.apply {η : Type*} {Gs : η → Type*} [∀ i, monoid (Gs i)] {x : Π i, Gs i} (h : is_of_fin_order x) : ∀ i, is_of_fin_order (x i) := begin rcases (is_of_fin_order_iff_pow_eq_one _).mp h with ⟨n, npos, hn⟩, exact λ _, (is_of_fin_order_iff_pow_eq_one _).mpr ⟨n, npos, (congr_fun hn.symm _).symm⟩, end /-- 1 is of finite order in any monoid. -/ @[to_additive "0 is of finite order in any additive monoid."] lemma is_of_fin_order_one : is_of_fin_order (1 : G) := (is_of_fin_order_iff_pow_eq_one 1).mpr ⟨1, _root_.one_pos, one_pow 1⟩ end is_of_fin_order /-- `order_of x` is the order of the element `x`, i.e. the `n ≥ 1`, s.t. `x ^ n = 1` if it exists. Otherwise, i.e. if `x` is of infinite order, then `order_of x` is `0` by convention.-/ @[to_additive add_order_of "`add_order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `n • a = 0` if it exists. Otherwise, i.e. if `a` is of infinite order, then `add_order_of a` is `0` by convention."] noncomputable def order_of (x : G) : ℕ := minimal_period ((*) x) 1 @[simp] lemma add_order_of_of_mul_eq_order_of (x : G) : add_order_of (additive.of_mul x) = order_of x := rfl @[simp] lemma order_of_of_add_eq_add_order_of (a : A) : order_of (multiplicative.of_add a) = add_order_of a := rfl @[to_additive add_order_of_pos'] lemma order_of_pos' (h : is_of_fin_order x) : 0 < order_of x := minimal_period_pos_of_mem_periodic_pts h @[to_additive add_order_of_nsmul_eq_zero] lemma pow_order_of_eq_one (x : G) : x ^ order_of x = 1 := begin convert is_periodic_pt_minimal_period ((*) x) _, rw [order_of, mul_left_iterate, mul_one], end @[to_additive add_order_of_eq_zero] lemma order_of_eq_zero (h : ¬ is_of_fin_order x) : order_of x = 0 := by rwa [order_of, minimal_period, dif_neg] @[to_additive add_order_of_eq_zero_iff] lemma order_of_eq_zero_iff : order_of x = 0 ↔ ¬ is_of_fin_order x := ⟨λ h H, (order_of_pos' H).ne' h, order_of_eq_zero⟩ @[to_additive add_order_of_eq_zero_iff'] lemma order_of_eq_zero_iff' : order_of x = 0 ↔ ∀ n : ℕ, 0 < n → x ^ n ≠ 1 := by simp_rw [order_of_eq_zero_iff, is_of_fin_order_iff_pow_eq_one, not_exists, not_and] @[to_additive add_order_of_eq_iff] lemma order_of_eq_iff {n} (h : 0 < n) : order_of x = n ↔ x ^ n = 1 ∧ ∀ m, m < n → 0 < m → x ^ m ≠ 1 := begin simp_rw [ne, ← is_periodic_pt_mul_iff_pow_eq_one, order_of, minimal_period], split_ifs with h1, { rw [find_eq_iff, exists_prop_of_true h], push_neg, refl }, { rw iff_false_left h.ne, rintro ⟨h', -⟩, exact h1 ⟨n, h, h'⟩ }, end /-- A group element has finite order iff its order is positive. -/ @[to_additive add_order_of_pos_iff "A group element has finite additive order iff its order is positive."] lemma order_of_pos_iff : 0 < order_of x ↔ is_of_fin_order x := by rwa [iff_not_comm.mp order_of_eq_zero_iff, pos_iff_ne_zero] @[to_additive nsmul_ne_zero_of_lt_add_order_of'] lemma pow_ne_one_of_lt_order_of' (n0 : n ≠ 0) (h : n < order_of x) : x ^ n ≠ 1 := λ j, not_is_periodic_pt_of_pos_of_lt_minimal_period n0 h ((is_periodic_pt_mul_iff_pow_eq_one x).mpr j) @[to_additive add_order_of_le_of_nsmul_eq_zero] lemma order_of_le_of_pow_eq_one (hn : 0 < n) (h : x ^ n = 1) : order_of x ≤ n := is_periodic_pt.minimal_period_le hn (by rwa is_periodic_pt_mul_iff_pow_eq_one) @[simp, to_additive] lemma order_of_one : order_of (1 : G) = 1 := by rw [order_of, one_mul_eq_id, minimal_period_id] @[simp, to_additive add_monoid.order_of_eq_one_iff] lemma order_of_eq_one_iff : order_of x = 1 ↔ x = 1 := by rw [order_of, is_fixed_point_iff_minimal_period_eq_one, is_fixed_pt, mul_one] @[to_additive nsmul_eq_mod_add_order_of] lemma pow_eq_mod_order_of {n : ℕ} : x ^ n = x ^ (n % order_of x) := calc x ^ n = x ^ (n % order_of x + order_of x * (n / order_of x)) : by rw [nat.mod_add_div] ... = x ^ (n % order_of x) : by simp [pow_add, pow_mul, pow_order_of_eq_one] @[to_additive add_order_of_dvd_of_nsmul_eq_zero] lemma order_of_dvd_of_pow_eq_one (h : x ^ n = 1) : order_of x ∣ n := is_periodic_pt.minimal_period_dvd ((is_periodic_pt_mul_iff_pow_eq_one _).mpr h) @[to_additive add_order_of_dvd_iff_nsmul_eq_zero] lemma order_of_dvd_iff_pow_eq_one {n : ℕ} : order_of x ∣ n ↔ x ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ @[to_additive add_order_of_smul_dvd] lemma order_of_pow_dvd (n : ℕ) : order_of (x ^ n) ∣ order_of x := by rw [order_of_dvd_iff_pow_eq_one, pow_right_comm, pow_order_of_eq_one, one_pow] @[to_additive add_order_of_map_dvd] lemma order_of_map_dvd {H : Type*} [monoid H] (ψ : G →* H) (x : G) : order_of (ψ x) ∣ order_of x := by { apply order_of_dvd_of_pow_eq_one, rw [←map_pow, pow_order_of_eq_one], apply map_one } @[to_additive] lemma exists_pow_eq_self_of_coprime (h : n.coprime (order_of x)) : ∃ m : ℕ, (x ^ n) ^ m = x := begin by_cases h0 : order_of x = 0, { rw [h0, coprime_zero_right] at h, exact ⟨1, by rw [h, pow_one, pow_one]⟩ }, by_cases h1 : order_of x = 1, { exact ⟨0, by rw [order_of_eq_one_iff.mp h1, one_pow, one_pow]⟩ }, obtain ⟨m, hm⟩ := exists_mul_mod_eq_one_of_coprime h (one_lt_iff_ne_zero_and_ne_one.mpr ⟨h0, h1⟩), exact ⟨m, by rw [←pow_mul, pow_eq_mod_order_of, hm, pow_one]⟩, end /-- If `x^n = 1`, but `x^(n/p) ≠ 1` for all prime factors `p` of `n`, then `x` has order `n` in `G`. -/ @[to_additive add_order_of_eq_of_nsmul_and_div_prime_nsmul "If `n * x = 0`, but `n/p * x ≠ 0` for all prime factors `p` of `n`, then `x` has order `n` in `G`."] theorem order_of_eq_of_pow_and_pow_div_prime (hn : 0 < n) (hx : x^n = 1) (hd : ∀ p : ℕ, p.prime → p ∣ n → x^(n/p) ≠ 1) : order_of x = n := begin -- Let `a` be `n/(order_of x)`, and show `a = 1` cases exists_eq_mul_right_of_dvd (order_of_dvd_of_pow_eq_one hx) with a ha, suffices : a = 1, by simp [this, ha], -- Assume `a` is not one... by_contra, have a_min_fac_dvd_p_sub_one : a.min_fac ∣ n, { obtain ⟨b, hb⟩ : ∃ (b : ℕ), a = b * a.min_fac := exists_eq_mul_left_of_dvd a.min_fac_dvd, rw [hb, ←mul_assoc] at ha, exact dvd.intro_left (order_of x * b) ha.symm, }, -- Use the minimum prime factor of `a` as `p`. refine hd a.min_fac (nat.min_fac_prime h) a_min_fac_dvd_p_sub_one _, rw [←order_of_dvd_iff_pow_eq_one, nat.dvd_div_iff (a_min_fac_dvd_p_sub_one), ha, mul_comm, nat.mul_dvd_mul_iff_left (order_of_pos' _)], { exact nat.min_fac_dvd a, }, { rw is_of_fin_order_iff_pow_eq_one, exact Exists.intro n (id ⟨hn, hx⟩) }, end @[to_additive add_order_of_eq_add_order_of_iff] lemma order_of_eq_order_of_iff {H : Type*} [monoid H] {y : H} : order_of x = order_of y ↔ ∀ n : ℕ, x ^ n = 1 ↔ y ^ n = 1 := by simp_rw [← is_periodic_pt_mul_iff_pow_eq_one, ← minimal_period_eq_minimal_period_iff, order_of] @[to_additive add_order_of_injective] lemma order_of_injective {H : Type*} [monoid H] (f : G →* H) (hf : function.injective f) (x : G) : order_of (f x) = order_of x := by simp_rw [order_of_eq_order_of_iff, ←f.map_pow, ←f.map_one, hf.eq_iff, iff_self, forall_const] @[simp, norm_cast, to_additive] lemma order_of_submonoid {H : submonoid G} (y : H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y @[to_additive] lemma order_of_units {y : Gˣ} : order_of (y : G) = order_of y := order_of_injective (units.coe_hom G) units.ext y variables (x) @[to_additive add_order_of_nsmul'] lemma order_of_pow' (h : n ≠ 0) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd h, simp only [order_of, mul_left_iterate], end variables (a) (n) @[to_additive add_order_of_nsmul''] lemma order_of_pow'' (h : is_of_fin_order x) : order_of (x ^ n) = order_of x / gcd (order_of x) n := begin convert minimal_period_iterate_eq_div_gcd' h, simp only [order_of, mul_left_iterate], end @[to_additive add_order_of_nsmul_coprime] lemma order_of_pow_coprime (h : (order_of y).coprime m) : order_of (y ^ m) = order_of y := begin by_cases hg : order_of y = 0, { rw [m.coprime_zero_left.mp (hg ▸ h), pow_one] }, { rw [order_of_pow'' y m (hg.imp_symm order_of_eq_zero), h.gcd_eq_one, nat.div_one] }, end namespace commute variables {x y} (h : commute x y) include h @[to_additive] lemma order_of_mul_dvd_lcm : order_of (x * y) ∣ nat.lcm (order_of x) (order_of y) := begin convert function.commute.minimal_period_of_comp_dvd_lcm h.function_commute_mul_left, rw [order_of, comp_mul_left], end @[to_additive] lemma order_of_dvd_lcm_mul : order_of y ∣ nat.lcm (order_of x) (order_of (x * y)) := begin by_cases h0 : order_of x = 0, { rw [h0, lcm_zero_left], apply dvd_zero }, conv_lhs { rw [← one_mul y, ← pow_order_of_eq_one x, ← succ_pred_eq_of_pos (nat.pos_of_ne_zero h0), pow_succ', mul_assoc] }, exact (((commute.refl x).mul_right h).pow_left _).order_of_mul_dvd_lcm.trans (lcm_dvd_iff.2 ⟨trans (order_of_pow_dvd _) (dvd_lcm_left _ _), dvd_lcm_right _ _⟩), end @[to_additive add_order_of_add_dvd_mul_add_order_of] lemma order_of_mul_dvd_mul_order_of : order_of (x * y) ∣ (order_of x) * (order_of y) := dvd_trans h.order_of_mul_dvd_lcm (lcm_dvd_mul _ _) @[to_additive add_order_of_add_eq_mul_add_order_of_of_coprime] lemma order_of_mul_eq_mul_order_of_of_coprime (hco : (order_of x).coprime (order_of y)) : order_of (x * y) = (order_of x) * (order_of y) := begin convert h.function_commute_mul_left.minimal_period_of_comp_eq_mul_of_coprime hco, simp only [order_of, comp_mul_left], end /-- Commuting elements of finite order are closed under multiplication. -/ @[to_additive "Commuting elements of finite additive order are closed under addition."] lemma is_of_fin_order_mul (hx : is_of_fin_order x) (hy : is_of_fin_order y) : is_of_fin_order (x * y) := order_of_pos_iff.mp $ pos_of_dvd_of_pos h.order_of_mul_dvd_mul_order_of $ mul_pos (order_of_pos' hx) (order_of_pos' hy) /-- If each prime factor of `order_of x` has higher multiplicity in `order_of y`, and `x` commutes with `y`, then `x * y` has the same order as `y`. -/ @[to_additive add_order_of_add_eq_right_of_forall_prime_mul_dvd "If each prime factor of `add_order_of x` has higher multiplicity in `add_order_of y`, and `x` commutes with `y`, then `x + y` has the same order as `y`."] lemma order_of_mul_eq_right_of_forall_prime_mul_dvd (hy : is_of_fin_order y) (hdvd : ∀ p : ℕ, p.prime → p ∣ order_of x → (p * order_of x) ∣ order_of y) : order_of (x * y) = order_of y := begin have hoy := order_of_pos' hy, have hxy := dvd_of_forall_prime_mul_dvd hdvd, apply order_of_eq_of_pow_and_pow_div_prime hoy; simp only [ne, ← order_of_dvd_iff_pow_eq_one], { exact trans h.order_of_mul_dvd_lcm (lcm_dvd hxy dvd_rfl) }, refine λ p hp hpy hd, hp.ne_one _, rw [← nat.dvd_one, ← mul_dvd_mul_iff_right hoy.ne', one_mul, ← dvd_div_iff hpy], refine trans (order_of_dvd_lcm_mul h) (lcm_dvd ((dvd_div_iff hpy).2 _) hd), by_cases p ∣ order_of x, exacts [hdvd p hp h, (hp.coprime_iff_not_dvd.2 h).mul_dvd_of_dvd_of_dvd hpy hxy], end end commute section p_prime variables {a x n} {p : ℕ} [hp : fact p.prime] include hp @[to_additive add_order_of_eq_prime] lemma order_of_eq_prime (hg : x ^ p = 1) (hg1 : x ≠ 1) : order_of x = p := minimal_period_eq_prime ((is_periodic_pt_mul_iff_pow_eq_one _).mpr hg) (by rwa [is_fixed_pt, mul_one]) @[to_additive add_order_of_eq_prime_pow] lemma order_of_eq_prime_pow (hnot : ¬ x ^ p ^ n = 1) (hfin : x ^ p ^ (n + 1) = 1) : order_of x = p ^ (n + 1) := begin apply minimal_period_eq_prime_pow; rwa is_periodic_pt_mul_iff_pow_eq_one, end @[to_additive exists_add_order_of_eq_prime_pow_iff] lemma exists_order_of_eq_prime_pow_iff : (∃ k : ℕ, order_of x = p ^ k) ↔ (∃ m : ℕ, x ^ (p : ℕ) ^ m = 1) := ⟨λ ⟨k, hk⟩, ⟨k, by rw [←hk, pow_order_of_eq_one]⟩, λ ⟨_, hm⟩, begin obtain ⟨k, _, hk⟩ := (nat.dvd_prime_pow hp.elim).mp (order_of_dvd_of_pow_eq_one hm), exact ⟨k, hk⟩, end⟩ end p_prime end monoid_add_monoid section cancel_monoid variables [left_cancel_monoid G] (x y) @[to_additive nsmul_injective_of_lt_add_order_of] lemma pow_injective_of_lt_order_of (hn : n < order_of x) (hm : m < order_of x) (eq : x ^ n = x ^ m) : n = m := eq_of_lt_minimal_period_of_iterate_eq hn hm (by simpa only [mul_left_iterate, mul_one]) @[to_additive mem_multiples_iff_mem_range_add_order_of'] lemma mem_powers_iff_mem_range_order_of' [decidable_eq G] (hx : 0 < order_of x) : y ∈ submonoid.powers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := finset.mem_range_iff_mem_finset_range_of_mod_eq' hx (λ i, pow_eq_mod_order_of.symm) @[to_additive] lemma pow_eq_one_iff_modeq : x ^ n = 1 ↔ n ≡ 0 [MOD (order_of x)] := by rw [modeq_zero_iff_dvd, order_of_dvd_iff_pow_eq_one] @[to_additive] lemma pow_eq_pow_iff_modeq : x ^ n = x ^ m ↔ n ≡ m [MOD (order_of x)] := begin wlog hmn : m ≤ n, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le hmn, rw [← mul_one (x ^ m), pow_add, mul_left_cancel_iff, pow_eq_one_iff_modeq], exact ⟨λ h, nat.modeq.add_left _ h, λ h, nat.modeq.add_left_cancel' _ h⟩, end @[simp, to_additive injective_nsmul_iff_not_is_of_fin_add_order] lemma injective_pow_iff_not_is_of_fin_order {x : G} : injective (λ (n : ℕ), x^n) ↔ ¬ is_of_fin_order x := begin refine ⟨λ h, not_is_of_fin_order_of_injective_pow h, λ h n m hnm, _⟩, rwa [pow_eq_pow_iff_modeq, order_of_eq_zero_iff.mpr h, modeq_zero_iff] at hnm, end @[to_additive infinite_not_is_of_fin_add_order] lemma infinite_not_is_of_fin_order {x : G} (h : ¬ is_of_fin_order x) : {y : G | ¬ is_of_fin_order y}.infinite := begin let s := {n | 0 < n}.image (λ (n : ℕ), x^n), have hs : s ⊆ {y : G | ¬ is_of_fin_order y}, { rintros - ⟨n, hn : 0 < n, rfl⟩ (contra : is_of_fin_order (x^n)), apply h, rw is_of_fin_order_iff_pow_eq_one at contra ⊢, obtain ⟨m, hm, hm'⟩ := contra, exact ⟨n * m, mul_pos hn hm, by rwa pow_mul⟩, }, suffices : s.infinite, { exact this.mono hs, }, contrapose! h, have : ¬ injective (λ (n : ℕ), x^n), { have := set.not_inj_on_infinite_finite_image (set.Ioi_infinite 0) (set.not_infinite.mp h), contrapose! this, exact set.inj_on_of_injective this _, }, rwa [injective_pow_iff_not_is_of_fin_order, not_not] at this, end end cancel_monoid section group variables [group G] [add_group A] {x a} {i : ℤ} /-- Inverses of elements of finite order have finite order. -/ @[to_additive "Inverses of elements of finite additive order have finite additive order."] lemma is_of_fin_order.inv {x : G} (hx : is_of_fin_order x) : is_of_fin_order x⁻¹ := (is_of_fin_order_iff_pow_eq_one _).mpr $ begin rcases (is_of_fin_order_iff_pow_eq_one x).mp hx with ⟨n, npos, hn⟩, refine ⟨n, npos, by simp_rw [inv_pow, hn, inv_one]⟩, end /-- Inverses of elements of finite order have finite order. -/ @[simp, to_additive "Inverses of elements of finite additive order have finite additive order."] lemma is_of_fin_order_inv_iff {x : G} : is_of_fin_order x⁻¹ ↔ is_of_fin_order x := ⟨λ h, inv_inv x ▸ h.inv, is_of_fin_order.inv⟩ @[to_additive add_order_of_dvd_iff_zsmul_eq_zero] lemma order_of_dvd_iff_zpow_eq_one : (order_of x : ℤ) ∣ i ↔ x ^ i = 1 := begin rcases int.eq_coe_or_neg i with ⟨i, rfl|rfl⟩, { rw [int.coe_nat_dvd, order_of_dvd_iff_pow_eq_one, zpow_coe_nat] }, { rw [dvd_neg, int.coe_nat_dvd, zpow_neg, inv_eq_one, zpow_coe_nat, order_of_dvd_iff_pow_eq_one] } end @[simp, to_additive] lemma order_of_inv (x : G) : order_of x⁻¹ = order_of x := by simp [order_of_eq_order_of_iff] @[simp, norm_cast, to_additive] lemma order_of_subgroup {H : subgroup G} (y: H) : order_of (y : G) = order_of y := order_of_injective H.subtype subtype.coe_injective y @[to_additive zsmul_eq_mod_add_order_of] lemma zpow_eq_mod_order_of : x ^ i = x ^ (i % order_of x) := calc x ^ i = x ^ (i % order_of x + order_of x * (i / order_of x)) : by rw [int.mod_add_div] ... = x ^ (i % order_of x) : by simp [zpow_add, zpow_mul, pow_order_of_eq_one] @[to_additive nsmul_inj_iff_of_add_order_of_eq_zero] lemma pow_inj_iff_of_order_of_eq_zero (h : order_of x = 0) {n m : ℕ} : x ^ n = x ^ m ↔ n = m := begin rw [order_of_eq_zero_iff, is_of_fin_order_iff_pow_eq_one] at h, push_neg at h, induction n with n IH generalizing m, { cases m, { simp }, { simpa [eq_comm] using h m.succ m.zero_lt_succ } }, { cases m, { simpa using h n.succ n.zero_lt_succ }, { simp [pow_succ, IH] } } end @[to_additive] lemma pow_inj_mod {n m : ℕ} : x ^ n = x ^ m ↔ n % order_of x = m % order_of x := begin cases (order_of x).zero_le.eq_or_lt with hx hx, { simp [pow_inj_iff_of_order_of_eq_zero, hx.symm] }, rw [pow_eq_mod_order_of, @pow_eq_mod_order_of _ _ _ m], exact ⟨pow_injective_of_lt_order_of _ (nat.mod_lt _ hx) (nat.mod_lt _ hx), λ h, congr_arg _ h⟩ end @[simp, to_additive zsmul_smul_order_of] lemma zpow_pow_order_of : (x^i)^order_of x = 1 := begin by_cases h : is_of_fin_order x, { rw [← zpow_coe_nat, ← zpow_mul, mul_comm, zpow_mul, zpow_coe_nat, pow_order_of_eq_one, one_zpow], }, { rw [order_of_eq_zero h, pow_zero], }, end @[to_additive is_of_fin_add_order.zsmul] lemma is_of_fin_order.zpow (h : is_of_fin_order x) {i : ℤ} : is_of_fin_order (x^i) := (is_of_fin_order_iff_pow_eq_one _).mpr ⟨order_of x, order_of_pos' h, zpow_pow_order_of⟩ @[to_additive is_of_fin_add_order.of_mem_zmultiples] lemma is_of_fin_order.of_mem_zpowers (h : is_of_fin_order x) (h' : y ∈ subgroup.zpowers x) : is_of_fin_order y := by { obtain ⟨k, rfl⟩ := subgroup.mem_zpowers_iff.mp h', exact h.zpow, } @[to_additive add_order_of_dvd_of_mem_zmultiples] lemma order_of_dvd_of_mem_zpowers (h : y ∈ subgroup.zpowers x) : order_of y ∣ order_of x := begin obtain ⟨k, rfl⟩ := subgroup.mem_zpowers_iff.mp h, rw order_of_dvd_iff_pow_eq_one, exact zpow_pow_order_of, end lemma smul_eq_self_of_mem_zpowers {α : Type*} [mul_action G α] (hx : x ∈ subgroup.zpowers y) {a : α} (hs : y • a = a) : x • a = a := begin obtain ⟨k, rfl⟩ := subgroup.mem_zpowers_iff.mp hx, rw [← mul_action.to_perm_apply, ← mul_action.to_perm_hom_apply, monoid_hom.map_zpow _ y k, mul_action.to_perm_hom_apply], exact function.is_fixed_pt.perm_zpow hs k, end lemma vadd_eq_self_of_mem_zmultiples {α G : Type*} [add_group G] [add_action G α] {x y : G} (hx : x ∈ add_subgroup.zmultiples y) {a : α} (hs : y +ᵥ a = a) : x +ᵥ a = a := @smul_eq_self_of_mem_zpowers (multiplicative G) _ _ _ α _ hx a hs attribute [to_additive vadd_eq_self_of_mem_zmultiples] smul_eq_self_of_mem_zpowers end group section comm_monoid variables [comm_monoid G] /-- Elements of finite order are closed under multiplication. -/ @[to_additive "Elements of finite additive order are closed under addition."] lemma is_of_fin_order.mul (hx : is_of_fin_order x) (hy : is_of_fin_order y) : is_of_fin_order (x * y) := (commute.all x y).is_of_fin_order_mul hx hy end comm_monoid section finite_monoid variables [monoid G] open_locale big_operators @[to_additive sum_card_add_order_of_eq_card_nsmul_eq_zero] lemma sum_card_order_of_eq_card_pow_eq_one [fintype G] [decidable_eq G] (hn : 0 < n) : ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ x : G, order_of x = m)).card = (finset.univ.filter (λ x : G, x ^ n = 1)).card := calc ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ x : G, order_of x = m)).card = _ : (finset.card_bUnion (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume x, suffices : order_of x ≤ n ∧ order_of x ∣ n ↔ x ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) end finite_monoid section finite_cancel_monoid -- TODO: Of course everything also works for right_cancel_monoids. variables [left_cancel_monoid G] [add_left_cancel_monoid A] -- TODO: Use this to show that a finite left cancellative monoid is a group. @[to_additive] lemma exists_pow_eq_one [finite G] (x : G) : is_of_fin_order x := begin have : (set.univ : set G).finite := set.univ.to_finite, contrapose! this, exact set.infinite.mono (set.subset_univ _) (infinite_not_is_of_fin_order this), end @[to_additive add_order_of_le_card_univ] lemma order_of_le_card_univ [fintype G] : order_of x ≤ fintype.card G := finset.le_card_of_inj_on_range ((^) x) (assume n _, finset.mem_univ _) (assume i hi j hj, pow_injective_of_lt_order_of x hi hj) /-- This is the same as `order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative monoid.-/ @[to_additive add_order_of_pos "This is the same as `add_order_of_pos' but with one fewer explicit assumption since this is automatic in case of a finite cancellative additive monoid."] lemma order_of_pos [finite G] (x : G) : 0 < order_of x := order_of_pos' (exists_pow_eq_one x) open nat /-- This is the same as `order_of_pow'` and `order_of_pow''` but with one assumption less which is automatic in the case of a finite cancellative monoid.-/ @[to_additive add_order_of_nsmul "This is the same as `add_order_of_nsmul'` and `add_order_of_nsmul` but with one assumption less which is automatic in the case of a finite cancellative additive monoid."] lemma order_of_pow [finite G] (x : G) : order_of (x ^ n) = order_of x / gcd (order_of x) n := order_of_pow'' _ _ (exists_pow_eq_one _) @[to_additive mem_multiples_iff_mem_range_add_order_of] lemma mem_powers_iff_mem_range_order_of [finite G] [decidable_eq G] : y ∈ submonoid.powers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := finset.mem_range_iff_mem_finset_range_of_mod_eq' (order_of_pos x) (assume i, pow_eq_mod_order_of.symm) @[to_additive decidable_multiples] noncomputable instance decidable_powers : decidable_pred (∈ submonoid.powers x) := classical.dec_pred _ /--The equivalence between `fin (order_of x)` and `submonoid.powers x`, sending `i` to `x ^ i`."-/ @[to_additive fin_equiv_multiples "The equivalence between `fin (add_order_of a)` and `add_submonoid.multiples a`, sending `i` to `i • a`."] noncomputable def fin_equiv_powers [finite G] (x : G) : fin (order_of x) ≃ (submonoid.powers x : set G) := equiv.of_bijective (λ n, ⟨x ^ ↑n, ⟨n, rfl⟩⟩) ⟨λ ⟨i, hi⟩ ⟨j, hj⟩ ij, fin.ext (pow_injective_of_lt_order_of x hi hj (subtype.mk_eq_mk.1 ij)), λ ⟨_, i, rfl⟩, ⟨⟨i % order_of x, mod_lt i (order_of_pos x)⟩, subtype.eq pow_eq_mod_order_of.symm⟩⟩ @[simp, to_additive fin_equiv_multiples_apply] lemma fin_equiv_powers_apply [finite G] {x : G} {n : fin (order_of x)} : fin_equiv_powers x n = ⟨x ^ ↑n, n, rfl⟩ := rfl @[simp, to_additive fin_equiv_multiples_symm_apply] lemma fin_equiv_powers_symm_apply [finite G] (x : G) (n : ℕ) {hn : ∃ (m : ℕ), x ^ m = x ^ n} : ((fin_equiv_powers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by rw [equiv.symm_apply_eq, fin_equiv_powers_apply, subtype.mk_eq_mk, pow_eq_mod_order_of, fin.coe_mk] /-- The equivalence between `submonoid.powers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ @[to_additive multiples_equiv_multiples "The equivalence between `submonoid.multiples` of two elements `a, b` of the same additive order, mapping `i • a` to `i • b`."] noncomputable def powers_equiv_powers [finite G] (h : order_of x = order_of y) : (submonoid.powers x : set G) ≃ (submonoid.powers y : set G) := (fin_equiv_powers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_powers y)) @[simp, to_additive multiples_equiv_multiples_apply] lemma powers_equiv_powers_apply [finite G] (h : order_of x = order_of y) (n : ℕ) : powers_equiv_powers h ⟨x ^ n, n, rfl⟩ = ⟨y ^ n, n, rfl⟩ := begin rw [powers_equiv_powers, equiv.trans_apply, equiv.trans_apply, fin_equiv_powers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_powers_symm_apply], simp [h] end @[to_additive add_order_of_eq_card_multiples] lemma order_eq_card_powers [fintype G] : order_of x = fintype.card (submonoid.powers x : set G) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_powers x⟩) end finite_cancel_monoid section finite_group variables [group G] [add_group A] @[to_additive] lemma exists_zpow_eq_one [finite G] (x : G) : ∃ (i : ℤ) (H : i ≠ 0), x ^ (i : ℤ) = 1 := begin rcases exists_pow_eq_one x with ⟨w, hw1, hw2⟩, refine ⟨w, int.coe_nat_ne_zero.mpr (ne_of_gt hw1), _⟩, rw zpow_coe_nat, exact (is_periodic_pt_mul_iff_pow_eq_one _).mp hw2, end open subgroup @[to_additive mem_multiples_iff_mem_zmultiples] lemma mem_powers_iff_mem_zpowers [finite G] : y ∈ submonoid.powers x ↔ y ∈ zpowers x := ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of x).nat_abs, by rwa [← zpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos x))), ← zpow_eq_mod_order_of]⟩⟩ @[to_additive multiples_eq_zmultiples] lemma powers_eq_zpowers [finite G] (x : G) : (submonoid.powers x : set G) = zpowers x := set.ext $ λ x, mem_powers_iff_mem_zpowers @[to_additive mem_zmultiples_iff_mem_range_add_order_of] lemma mem_zpowers_iff_mem_range_order_of [finite G] [decidable_eq G] : y ∈ subgroup.zpowers x ↔ y ∈ (finset.range (order_of x)).image ((^) x : ℕ → G) := by rw [← mem_powers_iff_mem_zpowers, mem_powers_iff_mem_range_order_of] @[to_additive decidable_zmultiples] noncomputable instance decidable_zpowers : decidable_pred (∈ subgroup.zpowers x) := classical.dec_pred _ /-- The equivalence between `fin (order_of x)` and `subgroup.zpowers x`, sending `i` to `x ^ i`. -/ @[to_additive fin_equiv_zmultiples "The equivalence between `fin (add_order_of a)` and `subgroup.zmultiples a`, sending `i` to `i • a`."] noncomputable def fin_equiv_zpowers [finite G] (x : G) : fin (order_of x) ≃ (subgroup.zpowers x : set G) := (fin_equiv_powers x).trans (equiv.set.of_eq (powers_eq_zpowers x)) @[simp, to_additive fin_equiv_zmultiples_apply] lemma fin_equiv_zpowers_apply [finite G] {n : fin (order_of x)} : fin_equiv_zpowers x n = ⟨x ^ (n : ℕ), n, zpow_coe_nat x n⟩ := rfl @[simp, to_additive fin_equiv_zmultiples_symm_apply] lemma fin_equiv_zpowers_symm_apply [finite G] (x : G) (n : ℕ) {hn : ∃ (m : ℤ), x ^ m = x ^ n} : ((fin_equiv_zpowers x).symm ⟨x ^ n, hn⟩) = ⟨n % order_of x, nat.mod_lt _ (order_of_pos x)⟩ := by { rw [fin_equiv_zpowers, equiv.symm_trans_apply, equiv.set.of_eq_symm_apply], exact fin_equiv_powers_symm_apply x n } /-- The equivalence between `subgroup.zpowers` of two elements `x, y` of the same order, mapping `x ^ i` to `y ^ i`. -/ @[to_additive zmultiples_equiv_zmultiples "The equivalence between `subgroup.zmultiples` of two elements `a, b` of the same additive order, mapping `i • a` to `i • b`."] noncomputable def zpowers_equiv_zpowers [finite G] (h : order_of x = order_of y) : (subgroup.zpowers x : set G) ≃ (subgroup.zpowers y : set G) := (fin_equiv_zpowers x).symm.trans ((fin.cast h).to_equiv.trans (fin_equiv_zpowers y)) @[simp, to_additive zmultiples_equiv_zmultiples_apply] lemma zpowers_equiv_zpowers_apply [finite G] (h : order_of x = order_of y) (n : ℕ) : zpowers_equiv_zpowers h ⟨x ^ n, n, zpow_coe_nat x n⟩ = ⟨y ^ n, n, zpow_coe_nat y n⟩ := begin rw [zpowers_equiv_zpowers, equiv.trans_apply, equiv.trans_apply, fin_equiv_zpowers_symm_apply, ← equiv.eq_symm_apply, fin_equiv_zpowers_symm_apply], simp [h] end variables [fintype G] /-- See also `order_eq_card_zpowers'`. -/ @[to_additive add_order_eq_card_zmultiples "See also `add_order_eq_card_zmultiples'`."] lemma order_eq_card_zpowers : order_of x = fintype.card (zpowers x) := (fintype.card_fin (order_of x)).symm.trans (fintype.card_eq.2 ⟨fin_equiv_zpowers x⟩) open quotient_group @[to_additive add_order_of_dvd_card_univ] lemma order_of_dvd_card_univ : order_of x ∣ fintype.card G := begin classical, have ft_prod : fintype ((G ⧸ zpowers x) × zpowers x), from fintype.of_equiv G group_equiv_quotient_times_subgroup, have ft_s : fintype (zpowers x), from @fintype.prod_right _ _ _ ft_prod _, have ft_cosets : fintype (G ⧸ zpowers x), from @fintype.prod_left _ _ _ ft_prod ⟨⟨1, (zpowers x).one_mem⟩⟩, have eq₁ : fintype.card G = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card G = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of x = @fintype.card _ ft_s, from calc order_of x = _ : order_eq_card_zpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, exact dvd.intro (@fintype.card (G ⧸ subgroup.zpowers x) ft_cosets) (by rw [eq₁, eq₂, mul_comm]) end @[to_additive add_order_of_dvd_nat_card] lemma order_of_dvd_nat_card {G : Type*} [group G] {x : G} : order_of x ∣ nat.card G := begin casesI fintype_or_infinite G with h h, { simp only [nat.card_eq_fintype_card, order_of_dvd_card_univ] }, { simp only [card_eq_zero_of_infinite, dvd_zero] }, end @[simp, to_additive card_nsmul_eq_zero'] lemma pow_card_eq_one' {G : Type*} [group G] {x : G} : x ^ nat.card G = 1 := order_of_dvd_iff_pow_eq_one.mp order_of_dvd_nat_card @[simp, to_additive card_nsmul_eq_zero] lemma pow_card_eq_one : x ^ fintype.card G = 1 := by rw [←nat.card_eq_fintype_card, pow_card_eq_one'] @[to_additive] lemma subgroup.pow_index_mem {G : Type*} [group G] (H : subgroup G) [normal H] (g : G) : g ^ index H ∈ H := by rw [←eq_one_iff, quotient_group.coe_pow H, index, pow_card_eq_one'] @[to_additive] lemma pow_eq_mod_card (n : ℕ) : x ^ n = x ^ (n % fintype.card G) := by rw [pow_eq_mod_order_of, ←nat.mod_mod_of_dvd n order_of_dvd_card_univ, ← pow_eq_mod_order_of] @[to_additive] lemma zpow_eq_mod_card (n : ℤ) : x ^ n = x ^ (n % fintype.card G) := by rw [zpow_eq_mod_order_of, ← int.mod_mod_of_dvd n (int.coe_nat_dvd.2 order_of_dvd_card_univ), ← zpow_eq_mod_order_of] /-- If `gcd(|G|,n)=1` then the `n`th power map is a bijection -/ @[to_additive "If `gcd(|G|,n)=1` then the smul by `n` is a bijection", simps] noncomputable def pow_coprime {G : Type*} [group G] (h : (nat.card G).coprime n) : G ≃ G := { to_fun := λ g, g ^ n, inv_fun := λ g, g ^ ((nat.card G).gcd_b n), left_inv := λ g, by { have key := congr_arg ((^) g) ((nat.card G).gcd_eq_gcd_ab n), rwa [zpow_add, zpow_mul, zpow_mul, zpow_coe_nat, zpow_coe_nat, zpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one', one_zpow, one_mul, eq_comm] at key }, right_inv := λ g, by { have key := congr_arg ((^) g) ((nat.card G).gcd_eq_gcd_ab n), rwa [zpow_add, zpow_mul, zpow_mul', zpow_coe_nat, zpow_coe_nat, zpow_coe_nat, h.gcd_eq_one, pow_one, pow_card_eq_one', one_zpow, one_mul, eq_comm] at key } } @[simp, to_additive] lemma pow_coprime_one {G : Type*} [group G] (h : (nat.card G).coprime n) : pow_coprime h 1 = 1 := one_pow n @[simp, to_additive] lemma pow_coprime_inv {G : Type*} [group G] (h : (nat.card G).coprime n) {g : G} : pow_coprime h g⁻¹ = (pow_coprime h g)⁻¹ := inv_pow g n @[to_additive add_inf_eq_bot_of_coprime] lemma inf_eq_bot_of_coprime {G : Type*} [group G] {H K : subgroup G} [fintype H] [fintype K] (h : nat.coprime (fintype.card H) (fintype.card K)) : H ⊓ K = ⊥ := begin refine (H ⊓ K).eq_bot_iff_forall.mpr (λ x hx, _), rw [←order_of_eq_one_iff, ←nat.dvd_one, ←h.gcd_eq_one, nat.dvd_gcd_iff], exact ⟨(congr_arg (∣ fintype.card H) (order_of_subgroup ⟨x, hx.1⟩)).mpr order_of_dvd_card_univ, (congr_arg (∣ fintype.card K) (order_of_subgroup ⟨x, hx.2⟩)).mpr order_of_dvd_card_univ⟩, end variable (a) /-- TODO: Generalise to `submonoid.powers`.-/ @[to_additive image_range_add_order_of, nolint to_additive_doc] lemma image_range_order_of [decidable_eq G] : finset.image (λ i, x ^ i) (finset.range (order_of x)) = (zpowers x : set G).to_finset := by { ext x, rw [set.mem_to_finset, set_like.mem_coe, mem_zpowers_iff_mem_range_order_of] } /-- TODO: Generalise to `finite` + `cancel_monoid`. -/ @[to_additive gcd_nsmul_card_eq_zero_iff "TODO: Generalise to `finite` + `cancel_add_monoid`"] lemma pow_gcd_card_eq_one_iff : x ^ n = 1 ↔ x ^ (gcd n (fintype.card G)) = 1 := ⟨λ h, pow_gcd_eq_one _ h $ pow_card_eq_one, λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card G) in by rw [hm, pow_mul, h, one_pow]⟩ end finite_group section pow_is_subgroup /-- A nonempty idempotent subset of a finite cancellative monoid is a submonoid -/ @[to_additive "A nonempty idempotent subset of a finite cancellative add monoid is a submonoid"] def submonoid_of_idempotent {M : Type*} [left_cancel_monoid M] [fintype M] (S : set M) (hS1 : S.nonempty) (hS2 : S * S = S) : submonoid M := have pow_mem : ∀ a : M, a ∈ S → ∀ n : ℕ, a ^ (n + 1) ∈ S := λ a ha, nat.rec (by rwa [zero_add, pow_one]) (λ n ih, (congr_arg2 (∈) (pow_succ a (n + 1)).symm hS2).mp (set.mul_mem_mul ha ih)), { carrier := S, one_mem' := by { obtain ⟨a, ha⟩ := hS1, rw [←pow_order_of_eq_one a, ← tsub_add_cancel_of_le (succ_le_of_lt (order_of_pos a))], exact pow_mem a ha (order_of a - 1) }, mul_mem' := λ a b ha hb, (congr_arg2 (∈) rfl hS2).mp (set.mul_mem_mul ha hb) } /-- A nonempty idempotent subset of a finite group is a subgroup -/ @[to_additive "A nonempty idempotent subset of a finite add group is a subgroup"] def subgroup_of_idempotent {G : Type*} [group G] [fintype G] (S : set G) (hS1 : S.nonempty) (hS2 : S * S = S) : subgroup G := { carrier := S, inv_mem' := λ a ha, show a⁻¹ ∈ submonoid_of_idempotent S hS1 hS2, by { rw [←one_mul a⁻¹, ←pow_one a, ←pow_order_of_eq_one a, ←pow_sub a (order_of_pos a)], exact pow_mem ha (order_of a - 1) }, .. submonoid_of_idempotent S hS1 hS2 } /-- If `S` is a nonempty subset of a finite group `G`, then `S ^ |G|` is a subgroup -/ @[to_additive smul_card_add_subgroup "If `S` is a nonempty subset of a finite add group `G`, then `|G| • S` is a subgroup", simps] def pow_card_subgroup {G : Type*} [group G] [fintype G] (S : set G) (hS : S.nonempty) : subgroup G := have one_mem : (1 : G) ∈ (S ^ fintype.card G) := by { obtain ⟨a, ha⟩ := hS, rw ← pow_card_eq_one, exact set.pow_mem_pow ha (fintype.card G) }, subgroup_of_idempotent (S ^ (fintype.card G)) ⟨1, one_mem⟩ begin classical!, refine (set.eq_of_subset_of_card_le (set.subset_mul_left _ one_mem) (ge_of_eq _)).symm, simp_rw [← pow_add, group.card_pow_eq_card_pow_card_univ S (fintype.card G) le_rfl, group.card_pow_eq_card_pow_card_univ S (fintype.card G + fintype.card G) le_add_self], end end pow_is_subgroup section linear_ordered_ring variable [linear_ordered_ring G] lemma order_of_abs_ne_one (h : |x| ≠ 1) : order_of x = 0 := begin rw order_of_eq_zero_iff', intros n hn hx, replace hx : |x| ^ n = 1 := by simpa only [abs_one, abs_pow] using congr_arg abs hx, cases h.lt_or_lt with h h, { exact ((pow_lt_one (abs_nonneg x) h hn.ne').ne hx).elim }, { exact ((one_lt_pow h hn.ne').ne' hx).elim } end lemma linear_ordered_ring.order_of_le_two : order_of x ≤ 2 := begin cases ne_or_eq (|x|) 1 with h h, { simp [order_of_abs_ne_one h] }, rcases eq_or_eq_neg_of_abs_eq h with rfl | rfl, { simp }, apply order_of_le_of_pow_eq_one; norm_num end end linear_ordered_ring
f171f4230ea34016493ab8394395be83487517cc
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/holor.lean
18a484aba65606af5f902e1b35d8747b9543e7fd
[ "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
14,871
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import algebra.module.pi import algebra.big_operators.basic /-! # Basic properties of holors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ universes u open list open_locale big_operators /-- `holor_index ds` is the type of valid index tuples used to identify an entry of a holor of dimensions `ds`. -/ def holor_index (ds : list ℕ) : Type := {is : list ℕ // forall₂ (<) is ds} namespace holor_index variables {ds₁ ds₂ ds₃ : list ℕ} def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩ def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂ | ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩ lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm) lemma take_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq $ by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left] lemma drop_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds : list ℕ) := holor_index ds → α namespace holor variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ} instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default⟩ instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩ instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩ instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩ instance [add_semigroup α] : add_semigroup (holor α ds) := by refine_struct { add := (+), .. }; tactic.pi_instance_derive_field instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by refine_struct { add := (+), .. }; tactic.pi_instance_derive_field instance [add_monoid α] : add_monoid (holor α ds) := by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := λ n x i, n • (x i) }; tactic.pi_instance_derive_field instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := add_monoid.nsmul }; tactic.pi_instance_derive_field instance [add_group α] : add_group (holor α ds) := by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := add_monoid.nsmul, zsmul := λ n x i, n • (x i) }; tactic.pi_instance_derive_field instance [add_comm_group α] : add_comm_group (holor α ds) := by refine_struct { zero := (0 : holor α ds), add := (+), nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field /- scalar product -/ instance [has_mul α] : has_smul α (holor α ds) := ⟨λ a x, λ t, a * x t⟩ instance [semiring α] : module α (holor α ds) := pi.module _ _ _ /-- The tensor product of two holors. -/ def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := λ t, x (t.take) * y (t.drop) local infix ` ⊗ ` : 70 := mul lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm) lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left := funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext $ λt, add_mul (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t)) @[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) : (0 : holor α ds₁) ⊗ x = 0 := funext (λ t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) : x ⊗ (0 :holor α ds₂) = 0 := funext (λ t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) : x ⊗ y = x ⟨[], forall₂.nil⟩ • y := by simp [mul, has_smul.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := (λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩) /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := λ ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) : Π (t : holor_index (d :: ds)), (∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t | ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨(i :: is), hforall₂⟩ hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis, have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forall₂_cons.1 hiisdds).1, have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 := funext $ λ t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)]) lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) : slice (0 : holor α (d :: ds)) i hid = 0 := rfl lemma slice_sum [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : ∑ x in s, slice (f x) i hid = slice (∑ x in s, f x) i hid := begin letI := classical.dec_eq β, refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) : ∑ i in (finset.range d).attach, unit_vec d i ⊗ slice x i (nat.succ_le_of_lt (finset.mem_range.1 i.prop)) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i $ finset.mem_range.2 hid), { simp }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩), have hbi' : i ≠ b, { simpa only [ne.def, subtype.ext_iff, subtype.coe_mk] using hbi.symm }, simp [hbi'] }, { assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop | nil (x : holor α []) : cprank_max1 x | cons {d} {ds} (x : holor α [d]) (y : holor α ds) : cprank_max1 y → cprank_max1 (x ⊗ y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop | zero {ds} : cprank_max 0 (0 : holor α ds) | succ n {ds} (x : holor α ds) (y : holor α ds) : cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid α] [add_monoid α]: ∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds}, cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hx₂ hy } end lemma cprank_max_mul [ring α] : ∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x y₂ hy₂ } end lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (∑ x in s, f x) := by letI := classical.dec_eq β; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x ∉ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s, finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (∑ x in s, f x), { apply ih, assume (x : β) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Π (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)), from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)), from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [ring α] (x : holor α ds) : nat := @nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod := λ ds (x : holor α ds), by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
dafe12236c5cd4c551c305ac83d9b0cb6ce76396
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/set_theory/cardinal_ordinal.lean
23007411e94cacb1563d9faaee8804554405dda9
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,209
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn -/ import set_theory.ordinal_arithmetic import tactic.linarith /-! # Cardinals and ordinals Relationships between cardinals and ordinals, properties of cardinals that are proved using ordinals. ## Main definitions * The function `cardinal.aleph'` gives the cardinals listed by their ordinal index, and is the inverse of `cardinal.aleph_idx`. `aleph' n = n`, `aleph' ω = cardinal.omega = ℵ₀`, `aleph' (ω + 1) = ℵ₁`, etc. It is an order isomorphism between ordinals and cardinals. * The function `cardinal.aleph` gives the infinite cardinals listed by their ordinal index. `aleph 0 = cardinal.omega = ℵ₀`, `aleph 1 = ℵ₁` is the first uncountable cardinal, and so on. ## Main Statements * `cardinal.mul_eq_max` and `cardinal.add_eq_max` state that the product (resp. sum) of two infinite cardinals is just their maximum. Several variations around this fact are also given. * `cardinal.mk_list_eq_mk` : when `α` is infinite, `α` and `list α` have the same cardinality. * simp lemmas for inequalities between `bit0 a` and `bit1 b` are registered, making `simp` able to prove inequalities about numeral cardinals. ## Tags cardinal arithmetic (for infinite cardinals) -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w namespace cardinal section using_ordinals open ordinal theorem ord_is_limit {c} (co : omega ≤ c) : (ord c).is_limit := begin refine ⟨λ h, omega_ne_zero _, λ a, lt_imp_lt_of_le_imp_le _⟩, { rw [← ordinal.le_zero, ord_le] at h, simpa only [card_zero, nonpos_iff_eq_zero] using le_trans co h }, { intro h, rw [ord_le] at h ⊢, rwa [← @add_one_of_omega_le (card a), ← card_succ], rw [← ord_le, ← le_succ_of_is_limit, ord_le], { exact le_trans co h }, { rw ord_omega, exact omega_is_limit } } end /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this definition, we register additionally that this function is an initial segment, i.e., it is order preserving and its range is an initial segment of the ordinals. For the basic function version, see `aleph_idx`. For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) := @rel_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding.lt_embedding /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) For an upgraded version stating that the range is everything, see `aleph_idx.rel_iso`. -/ def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg @[simp] theorem aleph_idx.initial_seg_coe : (aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b := aleph_idx.initial_seg.to_rel_embedding.map_rel_iff @[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b := by rw [← not_lt, ← not_lt, aleph_idx_lt] theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b := aleph_idx.initial_seg.init _ _ /-- The `aleph'` index function, which gives the ordinal index of a cardinal. (The `aleph'` part is because unlike `aleph` this counts also the finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`, `aleph_idx ℵ₁ = ω + 1` and so on.) In this version, we register additionally that this function is an order isomorphism between cardinals and ordinals. For the basic function version, see `aleph_idx`. -/ def aleph_idx.rel_iso : @rel_iso cardinal.{u} ordinal.{u} (<) (<) := @rel_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $ (initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $ λ ⟨o, e⟩, begin have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩, refine ordinal.induction_on o _ this, introsI α r _ h, let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)), apply not_le_of_gt (lt_succ_self s), have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.injective, simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a)) (ordinal.enum r _ (h (succ s))), end @[simp] theorem aleph_idx.rel_iso_coe : (aleph_idx.rel_iso : cardinal → ordinal) = aleph_idx := rfl @[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} := by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.rel_iso⟩ @[simp] theorem mk_cardinal : mk cardinal = univ.{u (u+1)} := by simpa only [card_type, card_univ] using congr_arg card type_cardinal /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. In this version, we register additionally that this function is an order isomorphism between ordinals and cardinals. For the basic function version, see `aleph'`. -/ def aleph'.rel_iso := cardinal.aleph_idx.rel_iso.symm /-- The `aleph'` function gives the cardinals listed by their ordinal index, and is the inverse of `aleph_idx`. `aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁`, etc. -/ def aleph' : ordinal → cardinal := aleph'.rel_iso @[simp] theorem aleph'.rel_iso_coe : (aleph'.rel_iso : ordinal → cardinal) = aleph' := rfl @[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ := aleph'.rel_iso.map_rel_iff @[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph'_lt @[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c := cardinal.aleph_idx.rel_iso.to_equiv.symm_apply_apply c @[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o := cardinal.aleph_idx.rel_iso.to_equiv.apply_symm_apply o @[simp] theorem aleph'_zero : aleph' 0 = 0 := by rw [← nonpos_iff_eq_zero, ← aleph'_aleph_idx 0, aleph'_le]; apply ordinal.zero_le @[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ := le_antisymm (cardinal.aleph_idx_le.1 $ by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx]; apply cardinal.lt_succ_self) (cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _) @[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n | 0 := aleph'_zero | (n+1) := show aleph' (ordinal.succ n) = n.succ, by rw [aleph'_succ, aleph'_nat, nat_succ] theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} : aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c := ⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h, λ h, begin rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l], intros x h', rw [← aleph'_le, aleph'_aleph_idx], exact h _ h' end⟩ @[simp] theorem aleph'_omega : aleph' ordinal.omega = omega := eq_of_forall_ge_iff $ λ c, begin simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le], exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]), end /-- `aleph'` and `aleph_idx` form an equivalence between `ordinal` and `cardinal` -/ @[simp] def aleph'_equiv : ordinal ≃ cardinal := ⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩ /-- The `aleph` function gives the infinite cardinals listed by their ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first uncountable cardinal, and so on. -/ def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o) @[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ := aleph'_lt.trans (ordinal.add_lt_add_iff_left _) @[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ := le_iff_le_iff_lt_iff_lt.2 aleph_lt @[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ := by rw [aleph, ordinal.add_succ, aleph'_succ]; refl @[simp] theorem aleph_zero : aleph 0 = omega := by simp only [aleph, add_zero, aleph'_omega] theorem omega_le_aleph' {o : ordinal} : omega ≤ aleph' o ↔ ordinal.omega ≤ o := by rw [← aleph'_omega, aleph'_le] theorem omega_le_aleph (o : ordinal) : omega ≤ aleph o := by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord := ord_is_limit $ omega_le_aleph _ theorem exists_aleph {c : cardinal} : omega ≤ c ↔ ∃ o, c = aleph o := ⟨λ h, ⟨aleph_idx c - ordinal.omega, by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx]; rwa [← omega_le_aleph', aleph'_aleph_idx]⟩, λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩ theorem aleph'_is_normal : is_normal (ord ∘ aleph') := ⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _, λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩ theorem aleph_is_normal : is_normal (ord ∘ aleph) := aleph'_is_normal.trans $ add_is_normal ordinal.omega /-! ### Properties of `mul` -/ /-- If `α` is an infinite type, then `α × α` and `α` have the same cardinality. -/ theorem mul_eq_self {c : cardinal} (h : omega ≤ c) : c * c = c := begin refine le_antisymm _ (by simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul_left' (one_lt_omega.le.trans h) c), -- the only nontrivial part is `c * c ≤ c`. We prove it inductively. refine acc.rec_on (cardinal.wf.apply c) (λ c _, quotient.induction_on c $ λ α IH ol, _) h, -- consider the minimal well-order `r` on `α` (a type with cardinality `c`). rcases ord_eq α with ⟨r, wo, e⟩, resetI, letI := linear_order_of_STO' r, haveI : is_well_order α (<) := wo, -- Define an order `s` on `α × α` by writing `(a, b) < (c, d)` if `max a b < max c d`, or -- the max are equal and `a < c`, or the max are equal and `a = c` and `b < d`. let g : α × α → α := λ p, max p.1 p.2, let f : α × α ↪ ordinal × (α × α) := ⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩, let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))), -- this is a well order on `α × α`. haveI : is_well_order _ s := (rel_embedding.preimage _ _).is_well_order, /- it suffices to show that this well order is smaller than `r` if it were larger, then `r` would be a strict prefix of `s`. It would be contained in `β × β` for some `β` of cardinality `< c`. By the inductive assumption, this set has the same cardinality as `β` (or it is finite if `β` is finite), so it is `< c`, which is a contradiction. -/ suffices : type s ≤ type r, {exact card_le_card this}, refine le_of_forall_lt (λ o h, _), rcases typein_surj s h with ⟨p, rfl⟩, rw [← e, lt_ord], refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _, { have : {q|s q p} ⊆ (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}), { intros q h, simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h, exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) }, suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit), { exact ⟨(set.embedding_of_subset _ _ this).trans ((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ }, refine (equiv.set.insert _).trans ((equiv.refl _).sum_congr punit_equiv_punit), apply @irrefl _ r }, cases lt_or_ge (card (typein (<) (g p)).succ) omega with qo qo, { exact lt_of_lt_of_le (mul_lt_omega qo qo) ol }, { suffices, {exact lt_of_le_of_lt (IH _ this qo) this}, rw ← lt_ord, apply (ord_is_limit ol).2, rw [mk_def, e], apply typein_lt_type } end end using_ordinals /-- If `α` and `β` are infinite types, then the cardinality of `α × β` is the maximum of the cardinalities of `α` and `β`. -/ theorem mul_eq_max {a b : cardinal} (ha : omega ≤ a) (hb : omega ≤ b) : a * b = max a b := le_antisymm (mul_eq_self (le_trans ha (le_max_left a b)) ▸ canonically_ordered_semiring.mul_le_mul (le_max_left _ _) (le_max_right _ _)) $ max_le (by simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul_left' (one_lt_omega.le.trans hb) a) (by simpa only [one_mul] using canonically_ordered_semiring.mul_le_mul_right' (one_lt_omega.le.trans ha) b) theorem mul_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a * b < c := lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (mul_lt_omega h h) hc) (λ h, by rw mul_eq_self h; exact max_lt h1 h2) lemma mul_le_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) : a * b ≤ max a b := begin convert canonically_ordered_semiring.mul_le_mul (le_max_left a b) (le_max_right a b), rw [mul_eq_self], refine le_trans h (le_max_left a b) end lemma mul_eq_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) (h' : b ≠ 0) : a * b = max a b := begin apply le_antisymm, apply mul_le_max_of_omega_le_left h, cases le_or_gt omega b with hb hb, rw [mul_eq_max h hb], have : b ≤ a, exact le_trans (le_of_lt hb) h, rw [max_eq_left this], convert canonically_ordered_semiring.mul_le_mul_left' (one_le_iff_ne_zero.mpr h') _, rw [mul_one], end lemma mul_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a := by { rw [mul_eq_max_of_omega_le_left ha hb', max_eq_left hb] } lemma mul_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b := by { rw [mul_comm, mul_eq_left hb ha ha'] } lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a := by { convert canonically_ordered_semiring.mul_le_mul_right' (one_le_iff_ne_zero.mpr h) _, rw [one_mul] } lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b := by { rw [mul_comm], exact le_mul_left h } lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max omega b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { have : a ≠ 0, { rintro rfl, exact not_lt_of_le ha omega_pos }, left, use ha, { rw [← not_lt], intro hb, apply ne_of_gt _ h, refine lt_of_lt_of_le hb (le_mul_left this) }, { rintro rfl, apply this, rw [_root_.mul_zero] at h, subst h }}, right, by_cases h2a : a = 0, { right, exact h2a }, have hb : b ≠ 0, { rintro rfl, apply h2a, rw [mul_zero] at h, subst h }, left, rw [← h, mul_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction, rw [← ne] at h2a, rw [← one_le_iff_ne_zero] at h2a hb, norm_cast at h2a hb h ⊢, apply le_antisymm _ hb, rw [← not_lt], intro h2b, apply ne_of_gt _ h, conv_lhs { rw [← mul_one n] }, rwa [mul_lt_mul_left], apply nat.lt_of_succ_le h2a }, { rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl), { rw [mul_eq_max_of_omega_le_left ha hb, max_eq_left hab] }, all_goals {simp}} end /-! ### Properties of `add` -/ /-- If `α` is an infinite type, then `α ⊕ α` and `α` have the same cardinality. -/ theorem add_eq_self {c : cardinal} (h : omega ≤ c) : c + c = c := le_antisymm (by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using canonically_ordered_semiring.mul_le_mul_right' ((nat_lt_omega 2).le.trans h) c) (self_le_add_left c c) /-- If `α` is an infinite type, then the cardinality of `α ⊕ β` is the maximum of the cardinalities of `α` and `β`. -/ theorem add_eq_max {a b : cardinal} (ha : omega ≤ a) : a + b = max a b := le_antisymm (add_eq_self (le_trans ha (le_max_left a b)) ▸ add_le_add (le_max_left _ _) (le_max_right _ _)) $ max_le (self_le_add_right _ _) (self_le_add_left _ _) theorem add_lt_of_lt {a b c : cardinal} (hc : omega ≤ c) (h1 : a < c) (h2 : b < c) : a + b < c := lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $ (lt_or_le (max a b) omega).elim (λ h, lt_of_lt_of_le (add_lt_omega h h) hc) (λ h, by rw add_eq_self h; exact max_lt h1 h2) lemma eq_of_add_eq_of_omega_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : omega ≤ c) : b = c := begin apply le_antisymm, { rw [← h], apply self_le_add_left }, rw[← not_lt], intro hb, have : a + b < c := add_lt_of_lt hc ha hb, simpa [h, lt_irrefl] using this end lemma add_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) : a + b = a := by { rw [add_eq_max ha, max_eq_left hb] } lemma add_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) : a + b = b := by { rw [add_comm, add_eq_left hb ha] } lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max omega b ≤ a ∨ b = 0) := begin rw [max_le_iff], split, { intro h, cases (le_or_lt omega a) with ha ha, { left, use ha, rw [← not_lt], intro hb, apply ne_of_gt _ h, exact lt_of_lt_of_le hb (self_le_add_left b a) }, right, rw [← h, add_lt_omega_iff, lt_omega, lt_omega] at ha, rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢, rw [← add_right_inj, h, add_zero] }, { rintro (⟨h1, h2⟩|h3), rw [add_eq_max h1, max_eq_left h2], rw [h3, add_zero] } end lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max omega a ≤ b ∨ a = 0) := by { rw [add_comm, add_eq_left_iff] } lemma add_one_eq {a : cardinal} (ha : omega ≤ a) : a + 1 = a := have 1 ≤ a, from le_trans (le_of_lt one_lt_omega) ha, add_eq_left ha this protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < omega) : b = c := begin cases le_or_lt omega b with hb hb, { have : a < b := lt_of_lt_of_le ha hb, rw [add_eq_right hb (le_of_lt this), eq_comm] at h, rw [eq_of_add_eq_of_omega_le h this hb] }, { have hc : c < omega, { rw [← not_le], intro hc, apply lt_irrefl omega, apply lt_of_le_of_lt (le_trans hc (self_le_add_left _ a)), rw [← h], apply add_lt_omega ha hb }, rw [lt_omega] at *, rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩, norm_cast at h ⊢, apply add_left_cancel h } end protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < omega) : a = c := by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb } /-! ### Properties about power -/ theorem pow_le {κ μ : cardinal.{u}} (H1 : omega ≤ κ) (H2 : μ < omega) : κ ^ μ ≤ κ := let ⟨n, H3⟩ := lt_omega.1 H2 in H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n (le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero]; from one_lt_omega) H1) (λ n ih, trans_rel_left _ (by { rw [nat.cast_succ, power_add, power_one]; exact canonically_ordered_semiring.mul_le_mul_right' ih _ }) (mul_eq_self H1))) H1) lemma power_self_eq {c : cardinal} (h : omega ≤ c) : c ^ c = 2 ^ c := begin apply le_antisymm, { apply le_trans (power_le_power_right $ le_of_lt $ cantor c), rw [power_mul, mul_eq_self h] }, { convert power_le_power_right (le_trans (le_of_lt $ nat_lt_omega 2) h), apply nat.cast_two.symm } end lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : omega ≤ c) : c ^ (n : cardinal.{u}) ≤ c := pow_le h (nat_lt_omega n) lemma powerlt_omega {c : cardinal} (h : omega ≤ c) : c ^< omega = c := begin apply le_antisymm, { rw [powerlt_le], intro c', rw [lt_omega], rintro ⟨n, rfl⟩, apply power_nat_le h }, convert le_powerlt one_lt_omega, rw [power_one] end lemma powerlt_omega_le (c : cardinal) : c ^< omega ≤ max c omega := begin cases le_or_gt omega c, { rw [powerlt_omega h], apply le_max_left }, rw [powerlt_le], intros c' hc', refine le_trans (le_of_lt $ power_lt_omega h hc') (le_max_right _ _) end /-! ### Computing cardinality of various types -/ theorem mk_list_eq_mk {α : Type u} (H1 : omega ≤ mk α) : mk (list α) = mk α := eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $ calc mk (list α) = sum (λ n : ℕ, mk α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α ... ≤ sum (λ n : ℕ, mk α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_omega n ... = sum (λ n : ulift.{u} ℕ, mk α) : quotient.sound ⟨@sigma_congr_left _ _ (λ _, quotient.out (mk α)) equiv.ulift.symm⟩ ... = omega * mk α : sum_const _ _ ... = max (omega) (mk α) : mul_eq_max (le_refl _) H1 ... = mk α : max_eq_right H1 theorem mk_finset_eq_mk {α : Type u} (h : omega ≤ mk α) : mk (finset α) = mk α := eq.symm $ le_antisymm (mk_le_of_injective (λ x y, finset.singleton_inj.1)) $ calc mk (finset α) ≤ mk (list α) : mk_le_of_surjective list.to_finset_surjective ... = mk α : mk_list_eq_mk h lemma mk_bounded_set_le_of_omega_le (α : Type u) (c : cardinal) (hα : omega ≤ mk α) : mk {t : set α // mk t ≤ c} ≤ mk α ^ c := begin refine le_trans _ (by rw [←add_one_eq hα]), refine quotient.induction_on c _, clear c, intro β, fapply mk_le_of_surjective, { intro f, use sum.inl ⁻¹' range f, refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _, apply mk_range_le }, rintro ⟨s, ⟨g⟩⟩, use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩, apply subtype.eq, ext, split, { rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y, { rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 }, { rw [dif_neg h'] at h, cases h }}, { intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩, use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr', suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this, apply g.2, exact classical.some_spec this } end lemma mk_bounded_set_le (α : Type u) (c : cardinal) : mk {t : set α // mk t ≤ c} ≤ max (mk α) omega ^ c := begin transitivity mk {t : set (ulift.{u} nat ⊕ α) // mk t ≤ c}, { refine ⟨embedding.subtype_map _ _⟩, apply embedding.image, use sum.inr, apply sum.inr.inj, intros s hs, exact le_trans mk_image_le hs }, refine le_trans (mk_bounded_set_le_of_omega_le (ulift.{u} nat ⊕ α) c (self_le_add_right omega (mk α))) _, rw [max_comm, ←add_eq_max]; refl end lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) : mk {t : set α // t ⊆ s ∧ mk t ≤ c} ≤ max (mk s) omega ^ c := begin refine le_trans _ (mk_bounded_set_le s c), refine ⟨embedding.cod_restrict _ _ _⟩, use λ t, coe ⁻¹' t.1, { rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢, refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_coe]; assumption }, rintro ⟨t, h1t, h2t⟩, exact le_trans (mk_preimage_of_injective _ _ subtype.val_injective) h2t end /-! ### Properties of `compl` -/ lemma mk_compl_of_omega_le {α : Type*} (s : set α) (h : omega ≤ #α) (h2 : #s < #α) : #(sᶜ : set α) = #α := by { refine eq_of_add_eq_of_omega_le _ h2 h, exact mk_sum_compl s } lemma mk_compl_finset_of_omega_le {α : Type*} (s : finset α) (h : omega ≤ #α) : #((↑s)ᶜ : set α) = #α := by { apply mk_compl_of_omega_le _ h, exact lt_of_lt_of_le (finset_card_lt_omega s) h } lemma mk_compl_eq_mk_compl_infinite {α : Type*} {s t : set α} (h : omega ≤ #α) (hs : #s < #α) (ht : #t < #α) : #(sᶜ : set α) = #(tᶜ : set α) := by { rw [mk_compl_of_omega_le s h hs, mk_compl_of_omega_le t h ht] } lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} {s : set α} {t : set β} (hα : #α < omega) (h1 : lift.{u (max v w)} (#α) = lift.{v (max u w)} (#β)) (h2 : lift.{u (max v w)} (#s) = lift.{v (max u w)} (#t)) : lift.{u (max v w)} (#(sᶜ : set α)) = lift.{v (max u w)} (#(tᶜ : set β)) := begin have hα' := hα, have h1' := h1, rw [← mk_sum_compl s, ← mk_sum_compl t] at h1, rw [← mk_sum_compl s, add_lt_omega_iff] at hα, lift #s to ℕ using hα.1 with n hn, lift #(sᶜ : set α) to ℕ using hα.2 with m hm, have : #(tᶜ : set β) < omega, { refine lt_of_le_of_lt (mk_subtype_le _) _, rw [← lift_lt, lift_omega, ← h1', ← lift_omega.{u (max v w)}, lift_lt], exact hα' }, lift #(tᶜ : set β) to ℕ using this with k hk, simp [nat_eq_lift_eq_iff] at h2, rw [nat_eq_lift_eq_iff.{v (max u w)}] at h2, simp [h2.symm] at h1 ⊢, norm_cast at h1, simp at h1, exact h1 end lemma mk_compl_eq_mk_compl_finite {α β : Type u} {s : set α} {t : set β} (hα : #α < omega) (h1 : #α = #β) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set β) := by { rw [← lift_inj], apply mk_compl_eq_mk_compl_finite_lift hα; rw [lift_inj]; assumption } lemma mk_compl_eq_mk_compl_finite_same {α : Type*} {s t : set α} (hα : #α < omega) (h : #s = #t) : #(sᶜ : set α) = #(tᶜ : set α) := mk_compl_eq_mk_compl_finite hα rfl h /-! ### Extending an injection to an equiv -/ theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β) (h : nonempty ((sᶜ : set α) ≃ ((range f)ᶜ : set β))) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin intros, have := h, cases this with g, let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans ((sum_congr (equiv.of_injective f f.2) g).trans (set.sum_compl (range f))), refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx] end theorem extend_function_finite {α β : Type*} {s : set α} (f : s ↪ β) (hs : #α < omega) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift hs h], rw [mk_range_eq_lift], exact f.2 end theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x := begin cases (le_or_lt omega (#α)) with hα hα, { apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h, cases cardinal.eq.mp (mk_compl_of_omega_le s hα hs) with g2, cases cardinal.eq.mp (mk_compl_of_omega_le (range f) _ _) with g3, { constructor, exact g2.trans (g.trans g3.symm) }, { rw [← lift_le, ← h], refine le_trans _ (lift_le.mpr hα), simp }, rwa [← lift_lt, ← h, mk_range_eq_lift, lift_lt], exact f.2 }, { exact extend_function_finite f hα h } end section bit /-! This section proves inequalities for `bit0` and `bit1`, enabling `simp` to solve inequalities for numeral cardinals. The complexity of the resulting algorithm is not good, as in some cases `simp` reduces an inequality to a disjunction of two situations, depending on whether a cardinal is finite or infinite. Since the evaluation of the branches is not lazy, this is bad. It is good enough for practical situations, though. For specific numbers, these inequalities could also be deduced from the corresponding inequalities of natural numbers using `norm_cast`: ``` example : (37 : cardinal) < 42 := by { norm_cast, norm_num } ``` -/ @[simp] lemma bit0_ne_zero (a : cardinal) : ¬bit0 a = 0 ↔ ¬a = 0 := by simp [bit0] @[simp] lemma bit1_ne_zero (a : cardinal) : ¬bit1 a = 0 := by simp [bit1] @[simp] lemma zero_lt_bit0 (a : cardinal) : 0 < bit0 a ↔ 0 < a := by { rw ←not_iff_not, simp [bit0], } @[simp] lemma zero_lt_bit1 (a : cardinal) : 0 < bit1 a := lt_of_lt_of_le zero_lt_one (self_le_add_left _ _) @[simp] lemma one_le_bit0 (a : cardinal) : 1 ≤ bit0 a ↔ 0 < a := ⟨λ h, (zero_lt_bit0 a).mp (lt_of_lt_of_le zero_lt_one h), λ h, le_trans (one_le_iff_pos.mpr h) (self_le_add_left a a)⟩ @[simp] lemma one_le_bit1 (a : cardinal) : 1 ≤ bit1 a := self_le_add_left _ _ theorem bit0_eq_self {c : cardinal} (h : omega ≤ c) : bit0 c = c := add_eq_self h @[simp] theorem bit0_lt_omega {c : cardinal} : bit0 c < omega ↔ c < omega := by simp [bit0, add_lt_omega_iff] @[simp] theorem omega_le_bit0 {c : cardinal} : omega ≤ bit0 c ↔ omega ≤ c := by { rw ← not_iff_not, simp } @[simp] theorem bit1_eq_self_iff {c : cardinal} : bit1 c = c ↔ omega ≤ c := begin by_cases h : omega ≤ c, { simp only [bit1, bit0_eq_self h, h, eq_self_iff_true, add_one_of_omega_le] }, { simp only [h, iff_false], apply ne_of_gt, rcases lt_omega.1 (not_le.1 h) with ⟨n, rfl⟩, norm_cast, dsimp [bit1, bit0], linarith } end @[simp] theorem bit1_lt_omega {c : cardinal} : bit1 c < omega ↔ c < omega := by simp [bit1, bit0, add_lt_omega_iff, one_lt_omega] @[simp] theorem omega_le_bit1 {c : cardinal} : omega ≤ bit1 c ↔ omega ≤ c := by { rw ← not_iff_not, simp } @[simp] lemma bit0_le_bit0 {a b : cardinal} : bit0 a ≤ bit0 b ↔ a ≤ b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb), have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit0_le_bit1 {a b : cardinal} : bit0 a ≤ bit1 b ↔ a ≤ b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit1_eq_self_iff.2 hb], }, { rw bit0_eq_self ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a ≤ b := le_of_lt (lt_of_lt_of_le ha hb), have I2 : bit0 a ≤ b := le_trans (le_of_lt (bit0_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_le_bit1 {a b : cardinal} : bit1 a ≤ bit1 b ↔ a ≤ b := begin split, { assume h, apply bit0_le_bit1.1 (le_trans (self_le_add_right (bit0 a) 1) h) }, { assume h, calc a + a + 1 ≤ a + b + 1 : add_le_add_right (add_le_add_left h a) 1 ... ≤ b + b + 1 : add_le_add_right (add_le_add_right h b) 1 } end @[simp] lemma bit1_le_bit0 {a b : cardinal} : bit1 a ≤ bit0 b ↔ (a < b ∨ (a ≤ b ∧ omega ≤ a)) := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { simp only [bit1_eq_self_iff.mpr ha, bit0_eq_self hb, ha, and_true], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a ≤ b), { assume h, apply hb, exact le_trans ha h }, have I2 : ¬ (a ≤ bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_of_lt_of_le (lt_of_lt_of_le A ha) h) }, simp [I1, I2, le_of_not_ge I1] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := lt_of_lt_of_le ha hb, have I2 : bit1 a ≤ b := le_trans (le_of_lt (bit1_lt_omega.2 ha)) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp [not_le.mpr ha], } end @[simp] lemma bit0_lt_bit0 {a b : cardinal} : bit0 a < bit0 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit0_eq_self ha, bit0_eq_self hb] }, { rw bit0_eq_self ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_trans ha (le_of_lt h) }, have I2 : ¬ (a < bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := lt_of_lt_of_le ha hb, have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_lt_bit0 {a b : cardinal} : bit1 a < bit0 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit1_eq_self_iff.2 ha, bit0_eq_self hb], }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit0 b), { assume h, have A : bit0 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit0_eq_self hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit1_lt_bit1 {a b : cardinal} : bit1 a < bit1 b ↔ a < b := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { rw [bit1_eq_self_iff.2 ha, bit1_eq_self_iff.2 hb], }, { rw bit1_eq_self_iff.2 ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit1 a < b := lt_of_lt_of_le (bit1_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp } end @[simp] lemma bit0_lt_bit1 {a b : cardinal} : bit0 a < bit1 b ↔ (a < b ∨ (a ≤ b ∧ a < omega)) := begin by_cases ha : omega ≤ a; by_cases hb : omega ≤ b, { simp [bit0_eq_self ha, bit1_eq_self_iff.2 hb, not_lt.mpr ha] }, { rw bit0_eq_self ha, have I1 : ¬ (a < b), { assume h, apply hb, exact le_of_lt (lt_of_le_of_lt ha h) }, have I2 : ¬ (a < bit1 b), { assume h, have A : bit1 b < omega, by simpa using hb, exact lt_irrefl _ (lt_trans (lt_of_lt_of_le A ha) h) }, simp [I1, I2, not_lt.mpr ha] }, { rw [bit1_eq_self_iff.2 hb], simp only [not_le] at ha, have I1 : a < b := (lt_of_lt_of_le ha hb), have I2 : bit0 a < b := lt_of_lt_of_le (bit0_lt_omega.2 ha) hb, simp [I1, I2] }, { simp at ha hb, rcases lt_omega.1 ha with ⟨m, rfl⟩, rcases lt_omega.1 hb with ⟨n, rfl⟩, norm_cast, simp only [ha, and_true, nat.bit0_lt_bit1_iff], refine ⟨λ h, or.inr h, λ h, _⟩, cases h, { exact le_of_lt h }, { exact h } } end lemma one_lt_two : (1 : cardinal) < 2 := -- This strategy works generally to prove inequalities between numerals in `cardinality`. by { norm_cast, norm_num } @[simp] lemma one_lt_bit0 {a : cardinal} : 1 < bit0 a ↔ 0 < a := by simp [← bit1_zero] @[simp] lemma one_lt_bit1 (a : cardinal) : 1 < bit1 a ↔ 0 < a := by simp [← bit1_zero] @[simp] lemma one_le_one : (1 : cardinal) ≤ 1 := le_refl _ end bit end cardinal
988bd42ee9f80b462e628065bdabc817143db7cf
2f8bf12144551bc7d8087a6320990c4621741f3d
/tests/compiler/rbmap.lean
72179c811bf324659c1aeec36e44f74acd841171
[ "Apache-2.0" ]
permissive
jesse-michael-han/lean4
eb63a12960e69823749edceb4f23fd33fa2253ce
fa16920a6a7700cabc567aa629ce4ae2478a2f40
refs/heads/master
1,589,935,810,594
1,557,177,860,000
1,557,177,860,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,233
lean
def check (b : Bool) : IO Unit := unless b $ IO.println "ERROR" def sz {α β : Type} {lt : α → α → Bool} (m : RBMap α β lt) : Nat := m.fold (λ sz _ _, sz+1) 0 def depth {α β : Type} {lt : α → α → Bool} (m : RBMap α β lt) : Nat := m.depth Nat.max def tst1 : IO Unit := do let Map := RBMap String Nat (λ a b, a < b), let m : Map := {}, let m := m.insert "hello" 0, let m := m.insert "world" 1, check (m.find "hello" == some 0), check (m.find "world" == some 1), let m := m.erase "hello", check (m.find "hello" == none), check (m.find "world" == some 1), pure () def tst2 : IO Unit := do let Map := RBMap Nat Nat (λ a b, a < b), let m : Map := {}, let n : Nat := 10000, let m := n.for (λ i (m : Map), m.insert i (i*10)) m, check (m.all (λ k v, v == k*10)), check (sz m == n), IO.println (">> " ++ toString (depth m) ++ ", " ++ toString (sz m)), let m := (n/2).for (λ i (m : Map), m.erase (2*i)) m, check (m.all (λ k v, v == k*10)), check (sz m == n / 2), IO.println (">> " ++ toString (depth m) ++ ", " ++ toString (sz m)), pure () abbrev Map := RBMap Nat Nat (λ a b, a < b) def mkRandMap (max : Nat) : Nat → Map → Array (Nat × Nat) → IO (Map × Array (Nat × Nat)) | 0 m a := pure (m, a) | (n+1) m a := do k ← IO.rand 0 max, v ← IO.rand 0 max, if m.find k == none then do let m := m.insert k v, let a := a.push (k, v), mkRandMap n m a else mkRandMap n m a def tst3 (seed : Nat) (n : Nat) (max : Nat) : IO Unit := do IO.setRandSeed seed, (m, a) ← mkRandMap max n {} Array.empty, check (sz m == a.size), check (a.all (λ ⟨k, v⟩, m.find k == some v)), IO.println ("tst3 size: " ++ toString a.size), let m := a.iterate m (λ i ⟨k, v⟩ m, if i.val % 2 == 0 then m.erase k else m), check (sz m == a.size / 2), a.miterate () (λ i ⟨k, v⟩ _, when (i.val % 2 == 1) (check (m.find k == some v))), IO.println ("tst3 after, depth: " ++ toString (depth m) ++ ", size: " ++ toString (sz m)), pure () def main (xs : List String) : IO Unit := tst1 *> tst2 *> tst3 1 10000 20000 *> tst3 2 10000 40000 *> tst3 3 1000 4000 *> tst3 4 50000 100000 *> tst3 5 10000 40000 *> pure ()
84c271051709130eb2ff581b44fa539798c53dd3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/control/traversable/basic_auto.lean
60ecc07d19474d800fb9a83fe0a3b927c15941c6
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
12,949
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.control.functor import Mathlib.PostPort universes u v w l s t u_1 namespace Mathlib /-! # Traversable type class Type classes for traversing collections. The concepts and laws are taken from <http://hackage.haskell.org/package/base-4.11.1.0/docs/Data-Traversable.html> Traversable collections are a generalization of functors. Whereas functors (such as `list`) allow us to apply a function to every element, it does not allow functions which external effects encoded in a monad. Consider for instance a functor `invite : email → io response` that takes an email address, sends an email and waits for a response. If we have a list `guests : list email`, using calling `invite` using `map` gives us the following: `map invite guests : list (io response)`. It is not what we need. We need something of type `io (list response)`. Instead of using `map`, we can use `traverse` to send all the invites: `traverse invite guests : io (list response)`. `traverse` applies `invite` to every element of `guests` and combines all the resulting effects. In the example, the effect is encoded in the monad `io` but any applicative functor is accepted by `traverse`. For more on how to use traversable, consider the Haskell tutorial: <https://en.wikibooks.org/wiki/Haskell/Traversable> ## Main definitions * `traversable` type class - exposes the `traverse` function * `sequence` - based on `traverse`, turns a collection of effects into an effect returning a collection * `is_lawful_traversable` - laws for a traversable functor * `applicative_transformation` - the notion of a natural transformation for applicative functors ## Tags traversable iterator functor applicative ## References * "Applicative Programming with Effects", by Conor McBride and Ross Paterson, Journal of Functional Programming 18:1 (2008) 1-13, online at <http://www.soi.city.ac.uk/~ross/papers/Applicative.html> * "The Essence of the Iterator Pattern", by Jeremy Gibbons and Bruno Oliveira, in Mathematically-Structured Functional Programming, 2006, online at <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator> * "An Investigation of the Laws of Traversals", by Mauro Jaskelioff and Ondrej Rypacek, in Mathematically-Structured Functional Programming, 2012, online at <http://arxiv.org/pdf/1202.2919> -/ /-- A transformation between applicative functors. It a natural transformation such that `app` preserves the `has_pure.pure` and `functor.map` (`<*>`) operations. See `applicative_transformation.preserves_map` for naturality. -/ structure applicative_transformation (F : Type u → Type v) [Applicative F] [is_lawful_applicative F] (G : Type u → Type w) [Applicative G] [is_lawful_applicative G] where app : (α : Type u) → F α → G α preserves_pure' : ∀ {α : Type u} (x : α), app α (pure x) = pure x preserves_seq' : ∀ {α β : Type u} (x : F (α → β)) (y : F α), app β (x <*> y) = app (α → β) x <*> app α y namespace applicative_transformation protected instance has_coe_to_fun (F : Type u → Type v) [Applicative F] [is_lawful_applicative F] (G : Type u → Type w) [Applicative G] [is_lawful_applicative G] : has_coe_to_fun (applicative_transformation F G) := has_coe_to_fun.mk (fun (_x : applicative_transformation F G) => {α : Type u} → F α → G α) fun (a : applicative_transformation F G) => app a @[simp] theorem app_eq_coe {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) : app η = ⇑η := rfl @[simp] theorem coe_mk {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (f : (α : Type u) → F α → G α) (pp : ∀ {α : Type u} (x : α), f α (pure x) = pure x) (ps : ∀ {α β : Type u} (x : F (α → β)) (y : F α), f β (x <*> y) = f (α → β) x <*> f α y) : ⇑(mk f pp ps) = f := rfl protected theorem congr_fun {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) (η' : applicative_transformation F G) (h : η = η') {α : Type u} (x : F α) : coe_fn η α x = coe_fn η' α x := congr_arg (fun (η'' : applicative_transformation F G) => coe_fn η'' α x) h protected theorem congr_arg {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) {α : Type u} {x : F α} {y : F α} (h : x = y) : coe_fn η α x = coe_fn η α y := congr_arg (fun (z : F α) => coe_fn η α z) h theorem coe_inj {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] {η : applicative_transformation F G} {η' : applicative_transformation F G} (h : ⇑η = ⇑η') : η = η' := sorry theorem ext {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] {η : applicative_transformation F G} {η' : applicative_transformation F G} (h : ∀ (α : Type u) (x : F α), coe_fn η α x = coe_fn η' α x) : η = η' := coe_inj (funext fun (α : Type u) => funext (h α)) theorem ext_iff {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] {η : applicative_transformation F G} {η' : applicative_transformation F G} : η = η' ↔ ∀ (α : Type u) (x : F α), coe_fn η α x = coe_fn η' α x := { mp := fun (h : η = η') (α : Type u) (x : F α) => h ▸ rfl, mpr := fun (h : ∀ (α : Type u) (x : F α), coe_fn η α x = coe_fn η' α x) => ext h } theorem preserves_pure {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) {α : Type u} (x : α) : coe_fn η α (pure x) = pure x := preserves_pure' η theorem preserves_seq {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) {α : Type u} {β : Type u} (x : F (α → β)) (y : F α) : coe_fn η β (x <*> y) = coe_fn η (α → β) x <*> coe_fn η α y := preserves_seq' η theorem preserves_map {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) {α : Type u} {β : Type u} (x : α → β) (y : F α) : coe_fn η β (x <$> y) = x <$> coe_fn η α y := sorry theorem preserves_map' {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) {α : Type u} {β : Type u} (x : α → β) : coe_fn η β ∘ Functor.map x = Functor.map x ∘ coe_fn η α := funext fun (y : F α) => preserves_map η x y /-- The identity applicative transformation from an applicative functor to itself. -/ def id_transformation {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] : applicative_transformation F F := mk (fun (α : Type u) => id) sorry sorry protected instance inhabited {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] : Inhabited (applicative_transformation F F) := { default := id_transformation } /-- The composition of applicative transformations. -/ def comp {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] {H : Type u → Type s} [Applicative H] [is_lawful_applicative H] (η' : applicative_transformation G H) (η : applicative_transformation F G) : applicative_transformation F H := mk (fun (α : Type u) (x : F α) => coe_fn η' α (coe_fn η α x)) sorry sorry @[simp] theorem comp_apply {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] {H : Type u → Type s} [Applicative H] [is_lawful_applicative H] (η' : applicative_transformation G H) (η : applicative_transformation F G) {α : Type u} (x : F α) : coe_fn (comp η' η) α x = coe_fn η' α (coe_fn η α x) := rfl theorem comp_assoc {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] {H : Type u → Type s} [Applicative H] [is_lawful_applicative H] {I : Type u → Type t} [Applicative I] [is_lawful_applicative I] (η'' : applicative_transformation H I) (η' : applicative_transformation G H) (η : applicative_transformation F G) : comp (comp η'' η') η = comp η'' (comp η' η) := rfl @[simp] theorem comp_id {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) : comp η id_transformation = η := ext fun (α : Type u) (x : F α) => rfl @[simp] theorem id_comp {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] {G : Type u → Type w} [Applicative G] [is_lawful_applicative G] (η : applicative_transformation F G) : comp id_transformation η = η := ext fun (α : Type u) (x : F α) => rfl end applicative_transformation /-- A traversable functor is a functor along with a way to commute with all applicative functors (see `sequence`). For example, if `t` is the traversable functor `list` and `m` is the applicative functor `io`, then given a function `f : α → io β`, the function `functor.map f` is `list α → list (io β)`, but `traverse f` is `list α → io (list β)`. -/ class traversable (t : Type u → Type u) extends Functor t where traverse : {m : Type u → Type u} → [_inst_1 : Applicative m] → {α β : Type u} → (α → m β) → t α → m (t β) /-- A traversable functor commutes with all applicative functors. -/ def sequence {t : Type u → Type u} {α : Type u} {f : Type u → Type u} [Applicative f] [traversable t] : t (f α) → f (t α) := traverse id /-- A traversable functor is lawful if its `traverse` satisfies a number of additional properties. It must send `id.mk` to `id.mk`, send the composition of applicative functors to the composition of the `traverse` of each, send each function `f` to `λ x, f <$> x`, and satisfy a naturality condition with respect to applicative transformations. -/ class is_lawful_traversable (t : Type u → Type u) [traversable t] extends is_lawful_functor t where id_traverse : ∀ {α : Type u} (x : t α), traverse id.mk x = x comp_traverse : ∀ {F G : Type u → Type u} [_inst_1_1 : Applicative F] [_inst_2 : Applicative G] [_inst_3 : is_lawful_applicative F] [_inst_4 : is_lawful_applicative G] {α β γ : Type u} (f : β → F γ) (g : α → G β) (x : t α), traverse (functor.comp.mk ∘ Functor.map f ∘ g) x = functor.comp.mk (traverse f <$> traverse g x) traverse_eq_map_id : ∀ {α β : Type u} (f : α → β) (x : t α), traverse (id.mk ∘ f) x = id.mk (f <$> x) naturality : ∀ {F G : Type u → Type u} [_inst_1_1 : Applicative F] [_inst_2 : Applicative G] [_inst_3 : is_lawful_applicative F] [_inst_4 : is_lawful_applicative G] (η : applicative_transformation F G) {α β : Type u} (f : α → F β) (x : t α), coe_fn η (t β) (traverse f x) = traverse (coe_fn η β ∘ f) x protected instance id.traversable : traversable id := traversable.mk fun (_x : Type u_1 → Type u_1) (_x_1 : Applicative _x) (_x_2 _x_3 : Type u_1) => id protected instance id.is_lawful_traversable : is_lawful_traversable id := is_lawful_traversable.mk sorry sorry sorry sorry protected instance option.traversable : traversable Option := traversable.mk option.traverse protected instance list.traversable : traversable List := traversable.mk list.traverse namespace sum /-- Defines a `traverse` function on the second component of a sum type. This is used to give a `traversable` instance for the functor `σ ⊕ -`. -/ protected def traverse {σ : Type u} {F : Type u → Type u} [Applicative F] {α : Type u_1} {β : Type u} (f : α → F β) : σ ⊕ α → F (σ ⊕ β) := sorry end sum protected instance sum.traversable {σ : Type u} : traversable (sum σ) := traversable.mk sum.traverse end Mathlib
30d62250420546e63a5b037394c9376e2269ae2f
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/tools/debugger/util.lean
7b497303fe444eef8d9229815808b1be10fce2ea
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,988
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ namespace debugger def is_space (c : char) : bool := if c = ' ' ∨ c = char.of_nat 11 ∨ c = '\n' then tt else ff def split_core : string → string → list string | (c::cs) [] := if is_space c then split_core cs [] else split_core cs [c] | (c::cs) r := if is_space c then r.reverse :: split_core cs [] else split_core cs (c::r) | [] [] := [] | [] r := [r.reverse] def split (s : string) : list string := (split_core s []).reverse def to_qualified_name_core : string → string → name | [] r := if r = "" then name.anonymous else mk_simple_name r.reverse | (c::cs) r := if is_space c then to_qualified_name_core cs r else if c = '.' then if r = "" then to_qualified_name_core cs [] else name.mk_string r.reverse (to_qualified_name_core cs []) else to_qualified_name_core cs (c::r) def to_qualified_name (s : string) : name := to_qualified_name_core s [] def olean_to_lean (s : string) := list.dropn 5 s ++ "lean" meta def get_file (fn : name) : vm string := do { d ← vm.get_decl fn, some n ← return (vm_decl.olean d) | failure, return (olean_to_lean n) } <|> return "[current file]" meta def pos_info (fn : name) : vm string := do { d ← vm.get_decl fn, some p ← return (vm_decl.pos d) | failure, file ← get_file fn, return (file ++ ":" ++ p.line.to_string ++ ":" ++ p.column.to_string) } <|> return "<position not available>" meta def show_fn (header : string) (fn : name) (frame : nat) : vm unit := do pos ← pos_info fn, vm.put_str ("[" ++ frame.to_string ++ "] " ++ header), if header = "" then return () else vm.put_str " ", vm.put_str (fn.to_string ++ " at " ++ pos ++ "\n") meta def show_curr_fn (header : string) : vm unit := do fn ← vm.curr_fn, sz ← vm.call_stack_size, show_fn header fn (sz-1) meta def is_valid_fn_prefix (p : name) : vm bool := do env ← vm.get_env, return $ env.fold ff (λ d r, r || let n := d.to_name in p.is_prefix_of n) meta def show_frame (frame_idx : nat) : vm unit := do sz ← vm.call_stack_size, fn ← if frame_idx >= sz then vm.curr_fn else vm.call_stack_fn frame_idx, show_fn "" fn frame_idx meta def type_to_string : option expr → nat → vm string | none i := do o ← vm.stack_obj i, match o.kind with | vm_obj_kind.simple := return "[tagged value]" | vm_obj_kind.constructor := return "[constructor]" | vm_obj_kind.closure := return "[closure]" | vm_obj_kind.native_closure := return "[native closure]" | vm_obj_kind.mpz := return "[big num]" | vm_obj_kind.name := return "name" | vm_obj_kind.level := return "level" | vm_obj_kind.expr := return "expr" | vm_obj_kind.declaration := return "declaration" | vm_obj_kind.environment := return "environment" | vm_obj_kind.tactic_state := return "tactic_state" | vm_obj_kind.format := return "format" | vm_obj_kind.options := return "options" | vm_obj_kind.other := return "[other]" end | (some type) i := do fmt ← vm.pp_expr type, opts ← vm.get_options, return (fmt.to_string opts) meta def show_vars_core : nat → nat → nat → vm unit | c i e := if i = e then return () else do (n, type) ← vm.stack_obj_info i, type_str ← type_to_string type i, vm.put_str $ "#" ++ c.to_string ++ " " ++ n.to_string ++ " : " ++ type_str ++ "\n", show_vars_core (c+1) (i+1) e meta def show_vars (frame : nat) : vm unit := do (s, e) ← vm.call_stack_var_range frame, show_vars_core 0 s e meta def show_stack_core : nat → vm unit | 0 := return () | (i+1) := do fn ← vm.call_stack_fn i, show_fn "" fn i, show_stack_core i meta def show_stack : vm unit := do sz ← vm.call_stack_size, show_stack_core sz end debugger
381dd5d922bc774c9f0f089576adaecc6a424fa1
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/sheaves/stalk_of_rings.lean
ca7c3258b460cba94c21450a03e1b7a74820504d
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
14,394
lean
/- Stalk of rings. https://stacks.math.columbia.edu/tag/007L (just says that the category of rings is a type of algebraic structure) Author -- Ramon Fernandez Mir -/ import topology.basic import for_mathlib.sheaves.stalk import for_mathlib.sheaves.presheaf_of_rings universes u v w open topological_space section stalk_of_rings variables {α : Type u} [topological_space α] variables (F : presheaf_of_rings α) (x : α) definition stalk_of_rings := stalk F.to_presheaf x end stalk_of_rings -- Stalks are rings. section stalk_of_rings_is_ring parameters {α : Type u} [topological_space α] parameters (F : presheaf_of_rings α) (x : α) -- Add. private def stalk_of_rings_add_aux : stalk.elem F.to_presheaf x → stalk.elem F.to_presheaf x → stalk F.to_presheaf x := λ s t, ⟦{U := s.U ∩ t.U, HxU := ⟨s.HxU, t.HxU⟩, s := F.res s.U _ (set.inter_subset_left _ _) s.s + F.res t.U _ (set.inter_subset_right _ _) t.s}⟧ instance stalk_of_rings_has_add : has_add (stalk_of_rings F x) := { add := quotient.lift₂ (stalk_of_rings_add_aux) $ begin intros a1 a2 b1 b2 H1 H2, let F' := F.to_presheaf, rcases H1 with ⟨U1, ⟨HxU1, ⟨HU1a1U, HU1b1U, HresU1⟩⟩⟩, rcases H2 with ⟨U2, ⟨HxU2, ⟨HU2a2U, HU2b2U, HresU2⟩⟩⟩, apply quotient.sound, use [U1 ∩ U2, ⟨HxU1, HxU2⟩], use [set.inter_subset_inter HU1a1U HU2a2U, set.inter_subset_inter HU1b1U HU2b2U], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, have HresU1' : (F'.res U1 (U1 ∩ U2) (set.inter_subset_left _ _) ((F'.res a1.U U1 HU1a1U) (a1.s))) = (F'.res U1 (U1 ∩ U2) (set.inter_subset_left _ _) ((F'.res b1.U U1 HU1b1U) (b1.s))) := by rw HresU1, have HresU2' : (F'.res U2 (U1 ∩ U2) (set.inter_subset_right _ _) ((F'.res a2.U U2 HU2a2U) (a2.s))) = (F'.res U2 (U1 ∩ U2) (set.inter_subset_right _ _) ((F'.res b2.U U2 HU2b2U) (b2.s))) := by rw HresU2, repeat { rw ←(presheaf.Hcomp' F') at HresU1' }, repeat { rw ←(presheaf.Hcomp' F') at HresU2' }, repeat { rw ←(presheaf.Hcomp' F') }, rw [HresU1', HresU2'], end } instance stalk_of_rings_add_semigroup : add_semigroup (stalk_of_rings F x) := { add := stalk_of_rings_has_add.add, add_assoc := begin intros a b c, refine quotient.induction_on₃ a b c _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, have HUVWsub : U ∩ V ∩ W ⊆ U ∩ (V ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨HxU, ⟨HxV, HxW⟩⟩, apply quotient.sound, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩], use [set.subset.refl _, HUVWsub], dsimp, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { erw ←presheaf.Hcomp' }, rw add_assoc, end } instance stalk_of_rings_add_comm_semigroup : add_comm_semigroup (stalk_of_rings F x) := { add_comm := begin intros a b, refine quotient.induction_on₂ a b _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩, apply quotient.sound, have HUVUV : U ∩ V ⊆ U ∩ V := λ x HxUV, HxUV, have HUVVU : U ∩ V ⊆ V ∩ U := λ x ⟨HxU, HxV⟩, ⟨HxV, HxU⟩, use [U ∩ V, ⟨HxU, HxV⟩, HUVUV, HUVVU], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, rw add_comm, end, ..stalk_of_rings_add_semigroup } -- Zero. private def stalk_of_rings_zero : stalk_of_rings F x := ⟦{U := opens.univ, HxU := trivial, s:= 0}⟧ instance stalk_of_rings_has_zero : has_zero (stalk_of_rings F x) := { zero := stalk_of_rings_zero } instance stalk_of_rings_add_comm_monoid : add_comm_monoid (stalk_of_rings F x) := { zero := stalk_of_rings_zero, zero_add := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUsub : U ⊆ opens.univ ∩ U := λ x HxU, ⟨trivial, HxU⟩, use [U, HxU, HUsub, set.subset.refl U], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, erw (is_ring_hom.map_zero ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw zero_add, refl, end, add_zero := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUsub : U ⊆ U ∩ opens.univ := λ x HxU, ⟨HxU, trivial⟩, use [U, HxU, HUsub, set.subset.refl U], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { erw ←presheaf.Hcomp' }, dsimp, erw (is_ring_hom.map_zero ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw add_zero, refl, end, ..stalk_of_rings_add_comm_semigroup } -- Neg. private def stalk_sub_aux : stalk.elem F.to_presheaf x → stalk F.to_presheaf x := λ s, ⟦{U := s.U, HxU := s.HxU, s := -s.s}⟧ instance stalk_of_rings_has_neg : has_neg (stalk_of_rings F x) := { neg := quotient.lift stalk_sub_aux $ begin intros a b H, rcases H with ⟨U, ⟨HxU, ⟨HUaU, HUbU, HresU⟩⟩⟩, apply quotient.sound, use [U, HxU, HUaU, HUbU], repeat { rw @is_ring_hom.map_neg _ _ _ _ _ (F.res_is_ring_hom _ _ _) }, rw HresU, end } instance stalk_of_rings_add_comm_group : add_comm_group (stalk_of_rings F x) := { neg := stalk_of_rings_has_neg.neg, add_left_neg := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUUU : U ⊆ U ∩ U := λ x HxU, ⟨HxU, HxU⟩, have HUuniv : U ⊆ opens.univ := λ x HxU, trivial, use [U, HxU, HUUU, HUuniv], repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, erw (is_ring_hom.map_neg ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw add_left_neg, erw (is_ring_hom.map_zero ((F.to_presheaf).res _ _ _)); try { apply_instance }, end, ..stalk_of_rings_add_comm_monoid } -- Mul. private def stalk_of_rings_mul_aux : stalk.elem F.to_presheaf x → stalk.elem F.to_presheaf x → stalk F.to_presheaf x := λ s t, ⟦{U := s.U ∩ t.U, HxU := ⟨s.HxU, t.HxU⟩, s := F.res s.U _ (set.inter_subset_left _ _) s.s * F.res t.U _ (set.inter_subset_right _ _) t.s}⟧ instance stalk_of_rings_has_mul : has_mul (stalk_of_rings F x) := { mul := quotient.lift₂ (stalk_of_rings_mul_aux) $ begin intros a1 a2 b1 b2 H1 H2, let F' := F.to_presheaf, rcases H1 with ⟨U1, ⟨HxU1, ⟨HU1a1U, HU1b1U, HresU1⟩⟩⟩, rcases H2 with ⟨U2, ⟨HxU2, ⟨HU2a2U, HU2b2U, HresU2⟩⟩⟩, apply quotient.sound, use [U1 ∩ U2, ⟨HxU1, HxU2⟩], use [set.inter_subset_inter HU1a1U HU2a2U, set.inter_subset_inter HU1b1U HU2b2U], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, have HresU1' : (F'.res U1 (U1 ∩ U2) (set.inter_subset_left _ _) ((F'.res a1.U U1 HU1a1U) (a1.s))) = (F'.res U1 (U1 ∩ U2) (set.inter_subset_left _ _) ((F'.res b1.U U1 HU1b1U) (b1.s))) := by rw HresU1, have HresU2' : (F'.res U2 (U1 ∩ U2) (set.inter_subset_right _ _) ((F'.res a2.U U2 HU2a2U) (a2.s))) = (F'.res U2 (U1 ∩ U2) (set.inter_subset_right _ _) ((F'.res b2.U U2 HU2b2U) (b2.s))) := by rw HresU2, repeat { rw ←(presheaf.Hcomp' F') at HresU1' }, repeat { rw ←(presheaf.Hcomp' F') at HresU2' }, repeat { rw ←(presheaf.Hcomp' F') }, rw [HresU1', HresU2'], end } instance stalk_of_rings_mul_semigroup : semigroup (stalk_of_rings F x) := { mul := stalk_of_rings_has_mul.mul, mul_assoc := begin intros a b c, refine quotient.induction_on₃ a b c _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, have HUVWsub : U ∩ V ∩ W ⊆ U ∩ (V ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨HxU, ⟨HxV, HxW⟩⟩, apply quotient.sound, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩], use [set.subset.refl _, HUVWsub], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw ←presheaf.Hcomp' }, rw mul_assoc, end } instance stalk_of_rings_mul_comm_semigroup : comm_semigroup (stalk_of_rings F x) := { mul_comm := begin intros a b, refine quotient.induction_on₂ a b _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩, apply quotient.sound, have HUVUV : U ∩ V ⊆ U ∩ V := λ x HxUV, HxUV, have HUVVU : U ∩ V ⊆ V ∩ U := λ x ⟨HxU, HxV⟩, ⟨HxV, HxU⟩, use [U ∩ V, ⟨HxU, HxV⟩, HUVUV, HUVVU], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw ←presheaf.Hcomp' }, rw mul_comm, end, ..stalk_of_rings_mul_semigroup } -- One. private def stalk_of_rings_one : stalk_of_rings F x := ⟦{U := opens.univ, HxU := trivial, s:= 1}⟧ instance stalk_of_rings_has_one : has_one (stalk_of_rings F x) := { one := stalk_of_rings_one } instance stalk_of_rings_mul_comm_monoid : comm_monoid (stalk_of_rings F x) := { one := stalk_of_rings_one, one_mul := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUsub : U ⊆ opens.univ ∩ U := λ x HxU, ⟨trivial, HxU⟩, use [U, HxU, HUsub, set.subset.refl U], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw ←presheaf.Hcomp' }, erw (is_ring_hom.map_one ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw one_mul, refl, end, mul_one := begin intros a, refine quotient.induction_on a _, rintros ⟨U, HxU, sU⟩, apply quotient.sound, have HUsub : U ⊆ U ∩ opens.univ := λ x HxU, ⟨HxU, trivial⟩, use [U, HxU, HUsub, set.subset.refl U], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw ←presheaf.Hcomp' }, dsimp, erw (is_ring_hom.map_one ((F.to_presheaf).res _ _ _)); try { apply_instance }, rw mul_one, refl, end, ..stalk_of_rings_mul_comm_semigroup } -- Ring. instance stalk_of_rings_is_comm_ring : comm_ring (stalk_of_rings F x) := { left_distrib := begin intros a b c, refine quotient.induction_on₃ a b c _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, have HUVWsub : U ∩ V ∩ W ⊆ U ∩ (V ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨HxU, ⟨HxV, HxW⟩⟩, have HUVWsub2 : U ∩ V ∩ W ⊆ U ∩ V ∩ (U ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨⟨HxU, HxV⟩, ⟨HxU, HxW⟩⟩, apply quotient.sound, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩, HUVWsub, HUVWsub2], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, rw mul_add, end, right_distrib := begin intros a b c, refine quotient.induction_on₃ a b c _, rintros ⟨U, HxU, sU⟩ ⟨V, HxV, sV⟩ ⟨W, HxW, sW⟩, have HUVWrfl : U ∩ V ∩ W ⊆ U ∩ V ∩ W := λ x Hx, Hx, have HUVWsub : U ∩ V ∩ W ⊆ U ∩ W ∩ (V ∩ W) := λ x ⟨⟨HxU, HxV⟩, HxW⟩, ⟨⟨HxU, HxW⟩, ⟨HxV, HxW⟩⟩, apply quotient.sound, use [U ∩ V ∩ W, ⟨⟨HxU, HxV⟩, HxW⟩, HUVWrfl, HUVWsub], repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, repeat { rw (F.res_is_ring_hom _ _ _).map_mul }, repeat { rw (F.res_is_ring_hom _ _ _).map_add }, repeat { rw ←presheaf.Hcomp' }, rw add_mul, end, ..stalk_of_rings_add_comm_group, ..stalk_of_rings_mul_comm_monoid } end stalk_of_rings_is_ring -- Stalks are colimits. section stalk_colimit variables {α : Type u} [topological_space α] variables (F : presheaf_of_rings α) (x : α) variables (S : Type w) [comm_ring S] [decidable_eq S] variables (G : Π U, x ∈ U → F.F U → S) [HG : ∀ U, ∀ (h : x ∈ U), is_ring_hom (G U h)] variables (hg : ∀ U V (H : U ⊆ V) r, ∀ (h : x ∈ U), G U h (F.res V U H r) = G V (H h) r) def to_stalk (U : opens α) (HxU : x ∈ U) (s : F.F U) : stalk_of_rings F x := ⟦{U := U, HxU := HxU, s := s}⟧ instance to_stalk.is_ring_hom (U) (HxU) : is_ring_hom (to_stalk F x U HxU) := { map_one := quotient.sound $ ⟨U, HxU, set.subset.refl _, λ x Hx, trivial, begin erw (F.res_is_ring_hom _ _ _).map_one, erw (F.res_is_ring_hom _ _ _).map_one, end⟩, map_add := λ y z, quotient.sound $ ⟨U, HxU, set.subset.refl _, λ x Hx, ⟨Hx, Hx⟩, begin erw ←(F.res_is_ring_hom _ _ _).map_add, erw presheaf.Hcomp', end⟩, map_mul := λ y z, quotient.sound $ ⟨U, HxU, set.subset.refl _, λ x Hx, ⟨Hx, Hx⟩, begin erw ←(F.res_is_ring_hom _ _ _).map_mul, erw presheaf.Hcomp', end⟩ } include hg protected def to_stalk.rec (y : stalk_of_rings F x) : S := quotient.lift_on' y (λ Us, G Us.1 Us.2 Us.3) $ λ ⟨U, HxU, s⟩ ⟨V, HxV, t⟩ ⟨W, HxW, HWU, HWV, Hres⟩, begin dsimp, erw [←hg W U HWU s HxW, ←hg W V HWV t HxW, Hres], end /- to_stalk.rec : Π {α : Type u} [_inst_1 : topological_space α] (F : presheaf_of_rings α) (x : α) (S : Type w) [_inst_2 : comm_ring S] [_inst_3 : decidable_eq S] (G : Π (U : opens α), (F.to_presheaf).F U → S), (∀ (U V : opens α) (H : U ⊆ V) (r : (F.to_presheaf).F V), G U ((F.to_presheaf).res V U H r) = G V r) → stalk_of_rings F x → S -/ theorem to_stalk.rec_to_stalk (U HxU s) : to_stalk.rec F x S G hg (to_stalk F x U HxU s) = G U HxU s := rfl include HG instance to_stalk.rec_is_ring_hom : is_ring_hom (to_stalk.rec F x S G hg) := { map_one := (HG opens.univ (set.mem_univ x)).map_one ▸ rfl, map_add := λ y z, quotient.induction_on₂' y z $ λ ⟨U, HxU, s⟩ ⟨V, HxV, t⟩, begin have HxUV : x ∈ U ∩ V := ⟨HxU, HxV⟩, show G (U ∩ V) HxUV (_ + _) = G _ _ _ + G _ _ _, rw (HG (U ∩ V) HxUV).map_add, erw ←hg (U ∩ V) U (set.inter_subset_left _ _), erw ←hg (U ∩ V) V (set.inter_subset_right _ _), end, map_mul := λ y z, quotient.induction_on₂' y z $ λ ⟨U, HxU, s⟩ ⟨V, HxV, t⟩, begin have HxUV : x ∈ U ∩ V := ⟨HxU, HxV⟩, show G (U ∩ V) HxUV (_ * _) = G _ _ _ * G _ _ _, rw (HG (U ∩ V) HxUV).map_mul, erw ←hg (U ∩ V) U (set.inter_subset_left _ _), erw ←hg (U ∩ V) V (set.inter_subset_right _ _), end } end stalk_colimit
32c99310f82471bec97579bcdf5407d6eae97001
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monoidal/of_chosen_finite_products_auto.lean
ae21085241fc5de3b9bafdaf4a41f1e085c243ad
[]
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
18,453
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monoidal.braided import Mathlib.category_theory.limits.shapes.binary_products import Mathlib.category_theory.limits.shapes.terminal import Mathlib.category_theory.pempty import Mathlib.PostPort universes v u namespace Mathlib /-! # The monoidal structure on a category with chosen finite products. This is a variant of the development in `category_theory.monoidal.of_has_finite_products`, which uses specified choices of the terminal object and binary product, enabling the construction of a cartesian category with specific definitions of the tensor unit and tensor product. (Because the construction in `category_theory.monoidal.of_has_finite_products` uses `has_limit` classes, the actual definitions there are opaque behind `classical.choice`.) We use this in `category_theory.monoidal.types` to construct the monoidal category of types so that the tensor product is the usual cartesian product of types. For now we only do the construction from products, and not from coproducts, which seems less often useful. -/ namespace category_theory namespace limits /-- Swap the two sides of a `binary_fan`. -/ def binary_fan.swap {C : Type u} [category C] {P : C} {Q : C} (t : binary_fan P Q) : binary_fan Q P := binary_fan.mk (binary_fan.snd t) (binary_fan.fst t) @[simp] theorem binary_fan.swap_fst {C : Type u} [category C] {P : C} {Q : C} (t : binary_fan P Q) : binary_fan.fst (binary_fan.swap t) = binary_fan.snd t := rfl @[simp] theorem binary_fan.swap_snd {C : Type u} [category C] {P : C} {Q : C} (t : binary_fan P Q) : binary_fan.snd (binary_fan.swap t) = binary_fan.fst t := rfl /-- If a cone `t` over `P Q` is a limit cone, then `t.swap` is a limit cone over `Q P`. -/ @[simp] theorem is_limit.swap_binary_fan_lift {C : Type u} [category C] {P : C} {Q : C} {t : binary_fan P Q} (I : is_limit t) (s : cone (pair Q P)) : is_limit.lift (is_limit.swap_binary_fan I) s = is_limit.lift I (binary_fan.swap s) := Eq.refl (is_limit.lift (is_limit.swap_binary_fan I) s) /-- Construct `has_binary_product Q P` from `has_binary_product P Q`. This can't be an instance, as it would cause a loop in typeclass search. -/ theorem has_binary_product.swap {C : Type u} [category C] (P : C) (Q : C) [has_binary_product P Q] : has_binary_product Q P := has_limit.mk (limit_cone.mk (binary_fan.swap (limit.cone (pair P Q))) (is_limit.swap_binary_fan (limit.is_limit (pair P Q)))) /-- Given a limit cone over `X` and `Y`, and another limit cone over `Y` and `X`, we can construct an isomorphism between the cone points. Relative to some fixed choice of limits cones for every pair, these isomorphisms constitute a braiding. -/ def binary_fan.braiding {C : Type u} [category C] {X : C} {Y : C} {s : binary_fan X Y} (P : is_limit s) {t : binary_fan Y X} (Q : is_limit t) : cone.X s ≅ cone.X t := is_limit.cone_point_unique_up_to_iso P (is_limit.swap_binary_fan Q) /-- Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `sXY.X Z`, if `sYZ` is a limit cone we can construct a binary fan over `X sYZ.X`. This is an ingredient of building the associator for a cartesian category. -/ def binary_fan.assoc {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan (cone.X sXY) Z) : binary_fan X (cone.X sYZ) := binary_fan.mk (binary_fan.fst s ≫ binary_fan.fst sXY) (is_limit.lift Q (binary_fan.mk (binary_fan.fst s ≫ binary_fan.snd sXY) (binary_fan.snd s))) @[simp] theorem binary_fan.assoc_fst {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan (cone.X sXY) Z) : binary_fan.fst (binary_fan.assoc Q s) = binary_fan.fst s ≫ binary_fan.fst sXY := rfl @[simp] theorem binary_fan.assoc_snd {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan (cone.X sXY) Z) : binary_fan.snd (binary_fan.assoc Q s) = is_limit.lift Q (binary_fan.mk (binary_fan.fst s ≫ binary_fan.snd sXY) (binary_fan.snd s)) := rfl /-- Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `X sYZ.X`, if `sYZ` is a limit cone we can construct a binary fan over `sXY.X Z`. This is an ingredient of building the associator for a cartesian category. -/ def binary_fan.assoc_inv {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X (cone.X sYZ)) : binary_fan (cone.X sXY) Z := binary_fan.mk (is_limit.lift P (binary_fan.mk (binary_fan.fst s) (binary_fan.snd s ≫ binary_fan.fst sYZ))) (binary_fan.snd s ≫ binary_fan.snd sYZ) @[simp] theorem binary_fan.assoc_inv_fst {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X (cone.X sYZ)) : binary_fan.fst (binary_fan.assoc_inv P s) = is_limit.lift P (binary_fan.mk (binary_fan.fst s) (binary_fan.snd s ≫ binary_fan.fst sYZ)) := rfl @[simp] theorem binary_fan.assoc_inv_snd {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X (cone.X sYZ)) : binary_fan.snd (binary_fan.assoc_inv P s) = binary_fan.snd s ≫ binary_fan.snd sYZ := rfl /-- If all the binary fans involved a limit cones, `binary_fan.assoc` produces another limit cone. -/ def is_limit.assoc {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ) {s : binary_fan (cone.X sXY) Z} (R : is_limit s) : is_limit (binary_fan.assoc Q s) := is_limit.mk fun (t : cone (pair X (cone.X sYZ))) => is_limit.lift R (binary_fan.assoc_inv P t) /-- Given two pairs of limit cones corresponding to the parenthesisations of `X × Y × Z`, we obtain an isomorphism between the cone points. -/ def binary_fan.associator {C : Type u} [category C] {X : C} {Y : C} {Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ) {s : binary_fan (cone.X sXY) Z} (R : is_limit s) {t : binary_fan X (cone.X sYZ)} (S : is_limit t) : cone.X s ≅ cone.X t := is_limit.cone_point_unique_up_to_iso (is_limit.assoc P Q R) S /-- Given a fixed family of limit data for every pair `X Y`, we obtain an associator. -/ def binary_fan.associator_of_limit_cone {C : Type u} [category C] (L : (X Y : C) → limit_cone (pair X Y)) (X : C) (Y : C) (Z : C) : cone.X (limit_cone.cone (L (cone.X (limit_cone.cone (L X Y))) Z)) ≅ cone.X (limit_cone.cone (L X (cone.X (limit_cone.cone (L Y Z))))) := binary_fan.associator (limit_cone.is_limit (L X Y)) (limit_cone.is_limit (L Y Z)) (limit_cone.is_limit (L (cone.X (limit_cone.cone (L X Y))) Z)) (limit_cone.is_limit (L X (cone.X (limit_cone.cone (L Y Z))))) /-- Construct a left unitor from specified limit cones. -/ def binary_fan.left_unitor {C : Type u} [category C] {X : C} {s : cone (functor.empty C)} (P : is_limit s) {t : binary_fan (cone.X s) X} (Q : is_limit t) : cone.X t ≅ X := iso.mk (binary_fan.snd t) (is_limit.lift Q (binary_fan.mk (is_limit.lift P (cone.mk X (nat_trans.mk (pempty.rec fun (n : pempty) => functor.obj (functor.obj (functor.const (discrete pempty)) X) n ⟶ functor.obj (functor.empty C) n)))) 𝟙)) /-- Construct a right unitor from specified limit cones. -/ def binary_fan.right_unitor {C : Type u} [category C] {X : C} {s : cone (functor.empty C)} (P : is_limit s) {t : binary_fan X (cone.X s)} (Q : is_limit t) : cone.X t ≅ X := iso.mk (binary_fan.fst t) (is_limit.lift Q (binary_fan.mk 𝟙 (is_limit.lift P (cone.mk X (nat_trans.mk (pempty.rec fun (n : pempty) => functor.obj (functor.obj (functor.const (discrete pempty)) X) n ⟶ functor.obj (functor.empty C) n)))))) end limits namespace monoidal_of_chosen_finite_products /-- Implementation of the tensor product for `monoidal_of_chosen_finite_products`. -/ def tensor_obj {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) : C := limits.cone.X (limits.limit_cone.cone (ℬ X Y)) /-- Implementation of the tensor product of morphisms for `monoidal_of_chosen_finite_products`. -/ def tensor_hom {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {W : C} {X : C} {Y : C} {Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : tensor_obj ℬ W Y ⟶ tensor_obj ℬ X Z := subtype.val (limits.binary_fan.is_limit.lift' (limits.limit_cone.is_limit (ℬ X Z)) (nat_trans.app (limits.cone.π (limits.limit_cone.cone (ℬ W Y))) limits.walking_pair.left ≫ f) (nat_trans.app (limits.cone.π (limits.limit_cone.cone (ℬ W Y))) limits.walking_pair.right ≫ g)) theorem tensor_id {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X₁ : C) (X₂ : C) : tensor_hom ℬ 𝟙 𝟙 = 𝟙 := sorry theorem tensor_comp {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X₁ : C} {Y₁ : C} {Z₁ : C} {X₂ : C} {Y₂ : C} {Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom ℬ (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom ℬ f₁ f₂ ≫ tensor_hom ℬ g₁ g₂ := sorry theorem pentagon {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (W : C) (X : C) (Y : C) (Z : C) : tensor_hom ℬ (iso.hom (limits.binary_fan.associator_of_limit_cone ℬ W X Y)) 𝟙 ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ W (tensor_obj ℬ X Y) Z) ≫ tensor_hom ℬ 𝟙 (iso.hom (limits.binary_fan.associator_of_limit_cone ℬ X Y Z)) = iso.hom (limits.binary_fan.associator_of_limit_cone ℬ (tensor_obj ℬ W X) Y Z) ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ W X (tensor_obj ℬ Y Z)) := sorry theorem triangle {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) : iso.hom (limits.binary_fan.associator_of_limit_cone ℬ X (limits.cone.X (limits.limit_cone.cone 𝒯)) Y) ≫ tensor_hom ℬ 𝟙 (iso.hom (limits.binary_fan.left_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ (limits.cone.X (limits.limit_cone.cone 𝒯)) Y)))) = tensor_hom ℬ (iso.hom (limits.binary_fan.right_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ X (limits.cone.X (limits.limit_cone.cone 𝒯)))))) 𝟙 := sorry theorem left_unitor_naturality {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X₁ : C} {X₂ : C} (f : X₁ ⟶ X₂) : tensor_hom ℬ 𝟙 f ≫ iso.hom (limits.binary_fan.left_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ (limits.cone.X (limits.limit_cone.cone 𝒯)) X₂))) = iso.hom (limits.binary_fan.left_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ (limits.cone.X (limits.limit_cone.cone 𝒯)) X₁))) ≫ f := sorry theorem right_unitor_naturality {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X₁ : C} {X₂ : C} (f : X₁ ⟶ X₂) : tensor_hom ℬ f 𝟙 ≫ iso.hom (limits.binary_fan.right_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ X₂ (limits.cone.X (limits.limit_cone.cone 𝒯))))) = iso.hom (limits.binary_fan.right_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ X₁ (limits.cone.X (limits.limit_cone.cone 𝒯))))) ≫ f := sorry theorem associator_naturality {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X₁ : C} {X₂ : C} {X₃ : C} {Y₁ : C} {Y₂ : C} {Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom ℬ (tensor_hom ℬ f₁ f₂) f₃ ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ Y₁ Y₂ Y₃) = iso.hom (limits.binary_fan.associator_of_limit_cone ℬ X₁ X₂ X₃) ≫ tensor_hom ℬ f₁ (tensor_hom ℬ f₂ f₃) := sorry end monoidal_of_chosen_finite_products /-- A category with a terminal object and binary products has a natural monoidal structure. -/ def monoidal_of_chosen_finite_products {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) : monoidal_category C := monoidal_category.mk (fun (X Y : C) => sorry) (fun (_x _x_1 _x_2 _x_3 : C) (f : _x ⟶ _x_1) (g : _x_2 ⟶ _x_3) => sorry) (limits.cone.X (limits.limit_cone.cone 𝒯)) (fun (X Y Z : C) => limits.binary_fan.associator_of_limit_cone ℬ X Y Z) (fun (X : C) => limits.binary_fan.left_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ (limits.cone.X (limits.limit_cone.cone 𝒯)) X))) fun (X : C) => limits.binary_fan.right_unitor (limits.limit_cone.is_limit 𝒯) (limits.limit_cone.is_limit (ℬ X (limits.cone.X (limits.limit_cone.cone 𝒯)))) namespace monoidal_of_chosen_finite_products /-- A type synonym for `C` carrying a monoidal category structure corresponding to a fixed choice of limit data for the empty functor, and for `pair X Y` for every `X Y : C`. This is an implementation detail for `symmetric_of_chosen_finite_products`. -/ def monoidal_of_chosen_finite_products_synonym {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) := C protected instance monoidal_of_chosen_finite_products_synonym.category_theory.monoidal_category {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) : monoidal_category (monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) := monoidal_of_chosen_finite_products 𝒯 ℬ theorem braiding_naturality {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) {X : C} {X' : C} {Y : C} {Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : tensor_hom ℬ f g ≫ iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ Y Y')) (limits.limit_cone.is_limit (ℬ Y' Y))) = iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X X')) (limits.limit_cone.is_limit (ℬ X' X))) ≫ tensor_hom ℬ g f := sorry theorem hexagon_forward {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) (Z : C) : iso.hom (limits.binary_fan.associator_of_limit_cone ℬ X Y Z) ≫ iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X (tensor_obj ℬ Y Z))) (limits.limit_cone.is_limit (ℬ (tensor_obj ℬ Y Z) X))) ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ Y Z X) = tensor_hom ℬ (iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X Y)) (limits.limit_cone.is_limit (ℬ Y X)))) 𝟙 ≫ iso.hom (limits.binary_fan.associator_of_limit_cone ℬ Y X Z) ≫ tensor_hom ℬ 𝟙 (iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X Z)) (limits.limit_cone.is_limit (ℬ Z X)))) := sorry theorem hexagon_reverse {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) (Z : C) : iso.inv (limits.binary_fan.associator_of_limit_cone ℬ X Y Z) ≫ iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ (tensor_obj ℬ X Y) Z)) (limits.limit_cone.is_limit (ℬ Z (tensor_obj ℬ X Y)))) ≫ iso.inv (limits.binary_fan.associator_of_limit_cone ℬ Z X Y) = tensor_hom ℬ 𝟙 (iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ Y Z)) (limits.limit_cone.is_limit (ℬ Z Y)))) ≫ iso.inv (limits.binary_fan.associator_of_limit_cone ℬ X Z Y) ≫ tensor_hom ℬ (iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X Z)) (limits.limit_cone.is_limit (ℬ Z X)))) 𝟙 := sorry theorem symmetry {C : Type u} [category C] (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) (X : C) (Y : C) : iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ X Y)) (limits.limit_cone.is_limit (ℬ Y X))) ≫ iso.hom (limits.binary_fan.braiding (limits.limit_cone.is_limit (ℬ Y X)) (limits.limit_cone.is_limit (ℬ X Y))) = 𝟙 := sorry end monoidal_of_chosen_finite_products /-- The monoidal structure coming from finite products is symmetric. -/ def symmetric_of_chosen_finite_products {C : Type u} [category C] (𝒯 : limits.limit_cone (functor.empty C)) (ℬ : (X Y : C) → limits.limit_cone (limits.pair X Y)) : symmetric_category (monoidal_of_chosen_finite_products.monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) := symmetric_category.mk end Mathlib
86eb6eeda55b99b15c0d2204a2f2e6230cfc2dcd
f3849be5d845a1cb97680f0bbbe03b85518312f0
/old_library/init/wf_k.lean
482e41fba2afa836de029487a11eca273ff95627
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
772
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura prelude import init.wf universe variables u namespace well_founded -- This is an auxiliary definition that useful for generating a new "proof" for (well_founded R) -- that allows us to use well_founded.fix and execute the definitions up to k nested recursive -- calls without "computing" with the proofs in Hwf. definition intro_k {A : Type u} {R : A → A → Prop} (Hwf : well_founded R) (k : nat) : well_founded R := well_founded.intro (nat.rec_on k (λ n : A, well_founded.apply Hwf n) (λ (k' : nat) (f : Π a, acc R a), (λ n : A, acc.intro n (λ y H, f y)))) end well_founded
ad31fc9c147df84661f205b60e97031b886d78e8
aa2345b30d710f7e75f13157a35845ee6d48c017
/data/multiset.lean
ed5c4adad69be5b9ab0faf257ce9e5fcd31704dd
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
120,263
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function order.boolean_algebra data.list.basic data.list.perm data.list.sort data.quot data.string algebra.order_functions algebra.group_power algebra.ordered_group category.traversable.lemmas tactic.interactive category.traversable.instances category.basic open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} local infix ` • ` := add_monoid.smul instance list.perm.setoid (α : Type*) : setoid (list α) := setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩ /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.perm.setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_of_forall_not_mem H; refl theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a :: as = b :: a :: cs, by simp [eq, hcs], have : a :: as = a :: b :: cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero (n : ℕ) : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl @[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ @[simp] theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive multiset.sum_singleton] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive multiset.sum_add] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp @[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n := by simp [repeat, list.prod_repeat] @[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a := @prod_repeat (multiplicative α) _ attribute [to_additive multiset.sum_repeat] prod_repeat @[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} : prod (m.map (λa, (1 : γ))) = (1 : γ) := multiset.induction_on m (by simp) (by simp) @[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} : sum (m.map (λa, (0 : γ))) = (0 : γ) := multiset.induction_on m (by simp) (by simp) attribute [to_additive multiset.sum_map_zero] prod_map_one @[simp, to_additive multiset.sum_map_add] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ}, sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) := @prod_map_prod_map _ _ (multiplicative γ) _ attribute [to_additive multiset.sum_map_sum_map] prod_map_prod_map lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, b * f a)) = b * sum (s.map f) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add]) lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} : sum (s.map (λa, f a * b)) = sum (s.map f) * b := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul]) /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 := by simp [bind, -map_const, join] @[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) : bind s (λa, f a + g a) = bind s f + bind s g := by simp [bind, join] @[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) : bind s (λa, f a :: g a) = map f s + bind s g := multiset.induction_on s (by simp) (by simp {contextual := tt}) @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) : bind (map f m) n = bind m (λa, n (f a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} : (s.bind f).bind g = s.bind (λa, (f a).bind g) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} : (bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) := multiset.induction_on m (by simp) (by simp {contextual := tt}) @[simp, to_additive multiset.sum_bind] lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) : prod (bind s t) = prod (s.map $ λa, prod (t a)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind]) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, repeat, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a::m, p b), pmap f (a :: m) h = f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m list.decidable_exists_mem instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∃a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _ @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter l theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- diagonal -/ theorem revzip_powerset_aux {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux l)) : s + t = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux' l)) : s + t = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃s t⦄, (s, t) ∈ revzip l' → s + t = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact perm_map _ powerset_aux_perm_powerset_aux', end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact perm_map _ (powerset_aux_perm p) end def diagonal (s : multiset α) : multiset (multiset α × multiset α) := quot.lift_on s (λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α))) (λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h)) theorem diagonal_coe (l : list α) : @diagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem diagonal_coe' (l : list α) : @diagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' @[simp] theorem mem_diagonal {s₁ s₂ t : multiset α} : (s₁, s₂) ∈ diagonal t ↔ s₁ + s₂ = t := quotient.induction_on t $ λ l, begin simp [diagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], exact ⟨_, le_add_right _ _, rfl, add_sub_cancel_left _ _⟩ end @[simp] theorem diagonal_map_fst (s : multiset α) : (diagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_map_snd (s : multiset α) : (diagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_zero : @diagonal α 0 = (0, 0)::0 := rfl @[simp] theorem diagonal_cons (a : α) (s) : diagonal (a::s) = map (prod.map id (cons a)) (diagonal s) + map (prod.map (cons a) id) (diagonal s) := quotient.induction_on s $ λ l, begin simp [revzip, reverse_append], rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)], {congr; simp}, {simp} end @[simp] theorem card_diagonal (s : multiset α) : card (diagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← diagonal_map_fst, card_map] at this lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} : prod (s.map (λa, f a + g a)) = sum ((diagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) := begin refine s.induction_on _ _, { simp }, { assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] }, end /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) @[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add @[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_smul', succ_mul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[extensionality] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp [max_min_distrib_left], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- relator -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero {} : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs) run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_eq_refl {s : multiset α} : rel (=) s s := multiset.induction_on s rel.zero (assume a s, rel.cons rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') := begin split, { generalize hm : a :: as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') := begin rw [← rel_flip, rel_cons_left], apply exists_congr, assume a, apply exists_congr, assume as', rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join := begin induction h, case rel.zero { simp }, case rel.cons : a b s t hab hst ih { simpa using hab.add ih } end lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) : rel p (s.map f) (t.map g) := by rw [rel_map_left, rel_map_right]; exact hst.mono (assume a b, h) lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ} (h : (r ⇒ rel p) f g) (hst : rel r s t) : rel p (s.bind f) (t.bind g) := by apply rel_join; apply rel_map; assumption lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff] theorem injective_map {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := begin simp [disjoint], split, from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm, from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁) end /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h) (assume h, ⟨l, rfl, h⟩) /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[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_zero : @nodup α 0 := pairwise.nil _ @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} : (∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s := quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩ theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) 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 [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ assume l₁, begin choose f hf using assume a, quotient.exists_rep (t a), rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a), simpa using nodup_sigma end theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ @[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} : nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) := have h₁ : ∀a, ∃l:list β, t a = l, from assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩, let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in have t = λa, t' a, from funext h', have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm, quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd] theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ @[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 := erase_dup_eq_self.2 $ nodup_singleton _ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ lemma attach_ndinsert (a : α) (s : multiset α) : (s.ndinsert a).attach = ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) := have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s, (λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from assume h, funext $ assume p, subtype.eq rfl, have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩), begin intros t ht, by_cases a ∈ s, { rw [ndinsert_of_mem h] at ht, subst ht, rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] }, { rw [ndinsert_of_not_mem h] at ht, subst ht, simp [attach_cons, h] } end, this _ rfl @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ n • erase_dup s := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sup variables [semilattice_sup_bot α] /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup (s : multiset α) : α := s.fold (⊔) ⊥ @[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ := fold_zero _ _ @[simp] lemma sup_cons (a : α) (s : multiset α) : (a :: s).sup = a ⊔ s.sup := fold_cons_left _ _ _ _ @[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp @[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup := eq.trans (by simp [sup]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup := fold_erase_dup_idem _ _ _ @[simp] lemma sup_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp @[simp] lemma sup_ndinsert (a : α) (s : multiset α) : (ndinsert a s).sup = a ⊔ s.sup := by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup := sup_le.1 (le_refl _) _ h lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup := sup_le.2 $ assume b hb, le_sup (h hb) end sup section inf variables [semilattice_inf_top α] /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf (s : multiset α) : α := s.fold (⊓) ⊤ @[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ := fold_zero _ _ @[simp] lemma inf_cons (a : α) (s : multiset α) : (a :: s).inf = a ⊓ s.inf := fold_cons_left _ _ _ _ @[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp @[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf := eq.trans (by simp [inf]) (fold_add _ _ _ _ _) variables [decidable_eq α] @[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf := fold_erase_dup_idem _ _ _ @[simp] lemma inf_ndunion (s₁ s₂ : multiset α) : (ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_union (s₁ s₂ : multiset α) : (s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp @[simp] lemma inf_ndinsert (a : α) (s : multiset α) : (ndinsert a s).inf = a ⊓ s.inf := by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) := multiset.induction_on s (by simp) (by simp [or_imp_distrib, forall_and_distrib] {contextual := tt}) lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a := le_inf.1 (le_refl _) _ h lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf := le_inf.2 $ assume b hb, inf_le (h hb) end inf section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r _) (sorted_merge_sort r _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ @[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s := by rw [← mem_coe, sort_eq] end sort instance [has_repr α] : has_repr (multiset α) := ⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩ section sections def sections (s : multiset (multiset α)) : multiset (multiset α) := multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a)) (assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap]) @[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 := rfl @[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) : sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) := rec_on_cons m s lemma coe_sections : ∀(l : list (list α)), sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) = ((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α)) | [] := rfl | (a :: l) := begin simp, rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l], simp [list.sections, (∘), list.bind] end @[simp] lemma sections_add (s t : multiset (multiset α)) : sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm]) lemma mem_sections {s : multiset (multiset α)} : ∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a := multiset.induction_on s (by simp) (assume a s ih a', by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm]) lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) := multiset.induction_on s (by simp) (by simp {contextual := tt}) lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} : prod (s.map sum) = sum ((sections s).map prod) := multiset.induction_on s (by simp) (assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right]) end sections section pi variables [decidable_eq α] {δ : α → Type*} open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a :: s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp, split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset namespace multiset instance : functor multiset := { map := @map } instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F] variables {α' β' : Type u_1} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.skip { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end open functor open traversable is_lawful_traversable @[simp] lemma lift_beta {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_beta _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x (by { intro, rw [traverse,quotient.lift_beta,function.comp], simp, congr }) lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [comp_map,map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) end multiset
c592b079d47345e1cd7a52069a569150d2a9f037
626e312b5c1cb2d88fca108f5933076012633192
/src/group_theory/perm/concrete_cycle.lean
922944be7346129d0a7b6f7ac07452a262884a15
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,183
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import group_theory.perm.list import data.list.cycle import group_theory.perm.cycle_type /-! # Properties of cyclic permutations constructed from lists ## Main results In the following, `{α : Type*} [fintype α] [decidable_eq α]`. * `list.is_cycle_form_perm`: a nontrivial list without duplicates, when interpreted as a permutation, is cyclic -/ open equiv equiv.perm list namespace list variables {α : Type*} [decidable_eq α] {l l' : list α} lemma form_perm_disjoint_iff (hl : nodup l) (hl' : nodup l') (hn : 2 ≤ l.length) (hn' : 2 ≤ l'.length) : perm.disjoint (form_perm l) (form_perm l') ↔ l.disjoint l' := begin rw [disjoint_iff_eq_or_eq, list.disjoint], split, { rintro h x hx hx', specialize h x, rw [form_perm_apply_mem_eq_self_iff _ hl _ hx, form_perm_apply_mem_eq_self_iff _ hl' _ hx'] at h, rcases h with hl | hl'; linarith }, { intros h x, by_cases hx : x ∈ l; by_cases hx' : x ∈ l', { exact (h hx hx').elim }, all_goals { have := form_perm_eq_self_of_not_mem _ _ ‹_›, tauto } } end lemma is_cycle_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : is_cycle (form_perm l) := begin cases l with x l, { norm_num at hn }, induction l with y l IH generalizing x, { norm_num at hn }, { use x, split, { rwa form_perm_apply_mem_ne_self_iff _ hl _ (mem_cons_self _ _) }, { intros w hw, have : w ∈ (x :: y :: l) := mem_of_form_perm_ne_self _ _ hw, obtain ⟨k, hk, rfl⟩ := nth_le_of_mem this, use k, simp only [gpow_coe_nat, form_perm_pow_apply_head _ _ hl k, nat.mod_eq_of_lt hk] } } end lemma pairwise_same_cycle_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : pairwise (l.form_perm.same_cycle) l := pairwise.imp_mem.mpr (pairwise_of_forall (λ x y hx hy, (is_cycle_form_perm hl hn).same_cycle ((form_perm_apply_mem_ne_self_iff _ hl _ hx).mpr hn) ((form_perm_apply_mem_ne_self_iff _ hl _ hy).mpr hn))) lemma cycle_of_form_perm (hl : nodup l) (hn : 2 ≤ l.length) (x) : cycle_of l.attach.form_perm x = l.attach.form_perm := have hn : 2 ≤ l.attach.length := by rwa ← length_attach at hn, have hl : l.attach.nodup := by rwa ← nodup_attach at hl, (is_cycle_form_perm hl hn).cycle_of_eq ((form_perm_apply_mem_ne_self_iff _ hl _ (mem_attach _ _)).mpr hn) lemma cycle_type_form_perm (hl : nodup l) (hn : 2 ≤ l.length) : cycle_type l.attach.form_perm = {l.length} := begin rw ←length_attach at hn, rw ←nodup_attach at hl, rw cycle_type_eq [l.attach.form_perm], { simp only [map, function.comp_app], rw [support_form_perm_of_nodup _ hl, card_to_finset, erase_dup_eq_self.mpr hl], { simpa }, { intros x h, simpa [h, nat.succ_le_succ_iff] using hn } }, { simp }, { simpa using is_cycle_form_perm hl hn }, { simp } end lemma form_perm_apply_mem_eq_next (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = next l x hx := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [next_nth_le _ hl, form_perm_apply_nth_le _ hl] end end list
cea0fdc7e5f383bc06ab663866e555f21848eac2
4fa161becb8ce7378a709f5992a594764699e268
/src/measure_theory/l1_space.lean
8cd6cbe13a3255636190a1d6a3ab4e874021bb8b
[ "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
28,596
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import measure_theory.ae_eq_fun /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. In the second part, the space `L¹` of equivalence classes of integrable functions under the relation of being almost everywhere equal is defined as a subspace of the space `L⁰`. See the file `src/measure_theory/ae_eq_fun.lean` for information on `L⁰` space. ## Notation * `α →₁ β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `f` is called `integrable` if `(∫⁻ a, nnnorm (f a)) < ⊤` holds. * The space `L¹` is defined as a subspace of `L⁰` : An `ae_eq_fun` `[f] : α →ₘ β` is in the space `L¹` if `edist [f] 0 < ⊤`, which means `(∫⁻ a, edist (f a) 0) < ⊤` if we expand the definition of `edist` in `L⁰`. ## Main statements `L¹`, as a subspace, inherits most of the structures of `L⁰`. ## Implementation notes Maybe `integrable f` should be mean `(∫⁻ a, edist (f a) 0) < ⊤`, so that `integrable` and `ae_eq_fun.integrable` are more aligned. But in the end one can use the lemma `lintegral_nnnorm_eq_lintegral_edist : (∫⁻ a, nnnorm (f a)) = (∫⁻ a, edist (f a) 0)` to switch the two forms. ## Tags integrable, function space, l1 -/ noncomputable theory open_locale classical topological_space namespace measure_theory open set filter topological_space ennreal emetric open_locale big_operators universes u v w variables {α : Type u} [measure_space α] variables {β : Type v} [normed_group β] {γ : Type w} [normed_group γ] /-- A function is `integrable` if the integral of its pointwise norm is less than infinity. -/ def integrable (f : α → β) : Prop := (∫⁻ a, nnnorm (f a)) < ⊤ lemma integrable_iff_norm (f : α → β) : integrable f ↔ (∫⁻ a, ennreal.of_real ∥f a∥) < ⊤ := by simp only [integrable, of_real_norm_eq_coe_nnnorm] lemma integrable_iff_edist (f : α → β) : integrable f ↔ (∫⁻ a, edist (f a) 0) < ⊤ := have eq : (λa, edist (f a) 0) = (λa, (nnnorm(f a) : ennreal)), by { funext, rw edist_eq_coe_nnnorm }, iff.intro (by { rw eq, exact λh, h }) $ by { rw eq, exact λh, h } lemma integrable_iff_of_real {f : α → ℝ} (h : ∀ₘ a, 0 ≤ f a) : integrable f ↔ (∫⁻ a, ennreal.of_real (f a)) < ⊤ := have lintegral_eq : (∫⁻ a, ennreal.of_real ∥f a∥) = (∫⁻ a, ennreal.of_real (f a)) := begin apply lintegral_congr_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a h, rw [real.norm_eq_abs, abs_of_nonneg], exact h end, by rw [integrable_iff_norm, lintegral_eq] lemma integrable_of_ae_eq {f g : α → β} (hf : integrable f) (h : ∀ₘ a, f a = g a) : integrable g := begin simp only [integrable] at *, have : (∫⁻ (a : α), ↑(nnnorm (f a))) = (∫⁻ (a : α), ↑(nnnorm (g a))), { apply lintegral_congr_ae, filter_upwards [h], assume a, simp only [mem_set_of_eq], assume h, rw h }, rwa ← this end lemma integrable_congr_ae {f g : α → β} (h : ∀ₘ a, f a = g a) : integrable f ↔ integrable g := iff.intro (λhf, integrable_of_ae_eq hf h) (λhg, integrable_of_ae_eq hg (ae_eq_symm h)) lemma integrable_of_le_ae {f : α → β} {g : α → γ} (h : ∀ₘ a, ∥f a∥ ≤ ∥g a∥) (hg : integrable g) : integrable f := begin simp only [integrable_iff_norm] at *, calc (∫⁻ a, ennreal.of_real ∥f a∥) ≤ (∫⁻ (a : α), ennreal.of_real ∥g a∥) : lintegral_le_lintegral_ae (by { filter_upwards [h], assume a h, exact of_real_le_of_real h }) ... < ⊤ : hg end lemma integrable_of_le {f : α → β} {g : α → γ} (h : ∀a, ∥f a∥ ≤ ∥g a∥) (hg : integrable g) : integrable f := integrable_of_le_ae (ae_of_all _ h) hg lemma lintegral_nnnorm_eq_lintegral_edist (f : α → β) : (∫⁻ a, nnnorm (f a)) = ∫⁻ a, edist (f a) 0 := by simp only [edist_eq_coe_nnnorm] lemma lintegral_norm_eq_lintegral_edist (f : α → β) : (∫⁻ a, ennreal.of_real ∥f a∥) = ∫⁻ a, edist (f a) 0 := by simp only [of_real_norm_eq_coe_nnnorm, edist_eq_coe_nnnorm] lemma lintegral_edist_triangle [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g h : α → β} (hf : measurable f) (hg : measurable g) (hh : measurable h) : (∫⁻ a, edist (f a) (g a)) ≤ (∫⁻ a, edist (f a) (h a)) + ∫⁻ a, edist (g a) (h a) := begin rw ← lintegral_add (hf.edist hh) (hg.edist hh), apply lintegral_mono, assume a, have := edist_triangle (f a) (h a) (g a), convert this, rw edist_comm (h a) (g a), end lemma lintegral_edist_lt_top [second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : (∫⁻ a, edist (f a) (g a)) < ⊤ := lt_of_le_of_lt (lintegral_edist_triangle hfm hgm (measurable_const : measurable (λa, (0 : β)))) (ennreal.add_lt_top.2 $ by { split; rw ← integrable_iff_edist; assumption }) lemma lintegral_nnnorm_zero : (∫⁻ a : α, nnnorm (0 : β)) = 0 := by simp variables (α β) @[simp] lemma integrable_zero : integrable (λa:α, (0:β)) := by simp [integrable] variables {α β} lemma lintegral_nnnorm_add [measurable_space β] [opens_measurable_space β] [measurable_space γ] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : (∫⁻ a, nnnorm (f a) + nnnorm (g a)) = (∫⁻ a, nnnorm (f a)) + ∫⁻ a, nnnorm (g a) := lintegral_add hf.ennnorm hg.ennnorm lemma integrable.add [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : integrable (λa, f a + g a) := calc (∫⁻ (a : α), ↑(nnnorm ((f + g) a))) ≤ ∫⁻ (a : α), ↑(nnnorm (f a)) + ↑(nnnorm (g a)) : lintegral_mono (assume a, by { simp only [← coe_add, coe_le_coe], exact nnnorm_add_le _ _ }) ... = _ : lintegral_nnnorm_add hfm hgm ... < ⊤ : add_lt_top.2 ⟨hfi, hgi⟩ lemma integrable_finset_sum {ι} [measurable_space β] [borel_space β] [second_countable_topology β] (s : finset ι) {f : ι → α → β} (hfm : ∀ i, measurable (f i)) (hfi : ∀ i, integrable (f i)) : integrable (λ a, ∑ i in s, f i a) := begin refine finset.induction_on s _ _, { simp only [finset.sum_empty, integrable_zero] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], refine (hfi _).add (hfm _) (s.measurable_sum hfm) ih } end lemma lintegral_nnnorm_neg {f : α → β} : (∫⁻ (a : α), ↑(nnnorm ((-f) a))) = ∫⁻ (a : α), ↑(nnnorm ((f) a)) := by simp only [pi.neg_apply, nnnorm_neg] lemma integrable.neg {f : α → β} : integrable f → integrable (λa, -f a) := assume hfi, calc _ = _ : lintegral_nnnorm_neg ... < ⊤ : hfi @[simp] lemma integrable_neg_iff (f : α → β) : integrable (λa, -f a) ↔ integrable f := begin split, { assume h, simpa only [_root_.neg_neg] using h.neg }, exact integrable.neg end lemma integrable.sub [measurable_space β] [opens_measurable_space β] {f g : α → β} (hfm : measurable f) (hfi : integrable f) (hgm : measurable g) (hgi : integrable g) : integrable (λa, f a - g a) := calc (∫⁻ (a : α), ↑(nnnorm ((f - g) a))) ≤ ∫⁻ (a : α), ↑(nnnorm (f a)) + ↑(nnnorm (-g a)) : lintegral_mono (assume a, by { simp only [← coe_add, coe_le_coe], exact nnnorm_add_le _ _ }) ... = _ : by { simp only [nnnorm_neg], exact lintegral_nnnorm_add hfm hgm } ... < ⊤ : add_lt_top.2 ⟨hfi, hgi⟩ lemma integrable.norm {f : α → β} (hfi : integrable f) : integrable (λa, ∥f a∥) := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rwa [integrable, eq] } lemma integrable_norm_iff (f : α → β) : integrable (λa, ∥f a∥) ↔ integrable f := have eq : (λa, (nnnorm ∥f a∥ : ennreal)) = λa, (nnnorm (f a) : ennreal), by { funext, rw nnnorm_norm }, by { rw [integrable, integrable, eq] } lemma integrable_of_integrable_bound {f : α → β} {bound : α → ℝ} (h : integrable bound) (h_bound : ∀ₘ a, ∥f a∥ ≤ bound a) : integrable f := have h₁ : ∀ₘ a, (nnnorm (f a) : ennreal) ≤ ennreal.of_real (bound a), begin filter_upwards [h_bound], simp only [mem_set_of_eq], assume a h, calc (nnnorm (f a) : ennreal) = ennreal.of_real (∥f a∥) : by rw of_real_norm_eq_coe_nnnorm ... ≤ ennreal.of_real (bound a) : ennreal.of_real_le_of_real h end, calc (∫⁻ a, nnnorm (f a)) ≤ (∫⁻ a, ennreal.of_real (bound a)) : by { apply lintegral_le_lintegral_ae, exact h₁ } ... ≤ (∫⁻ a, ennreal.of_real ∥bound a∥) : lintegral_mono $ by { assume a, apply ennreal.of_real_le_of_real, exact le_max_left (bound a) (-bound a) } ... < ⊤ : by { rwa [integrable_iff_norm] at h } section dominated_convergence variables {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} lemma all_ae_of_real_F_le_bound (h : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) : ∀ n, ∀ₘ a, ennreal.of_real ∥F n a∥ ≤ ennreal.of_real (bound a) := λn, by filter_upwards [h n] λ a h, ennreal.of_real_le_of_real h lemma all_ae_tendsto_of_real_norm (h : ∀ₘ a, tendsto (λ n, F n a) at_top $ 𝓝 $ f a) : ∀ₘ a, tendsto (λn, ennreal.of_real ∥F n a∥) at_top $ 𝓝 $ ennreal.of_real ∥f a∥ := by filter_upwards [h] λ a h, tendsto_of_real $ tendsto.comp (continuous.tendsto continuous_norm _) h lemma all_ae_of_real_f_le_bound (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : ∀ₘ a, ennreal.of_real ∥f a∥ ≤ ennreal.of_real (bound a) := begin have F_le_bound := all_ae_of_real_F_le_bound h_bound, rw ← ae_all_iff at F_le_bound, apply F_le_bound.mp ((all_ae_tendsto_of_real_norm h_lim).mono _), assume a tendsto_norm F_le_bound, exact le_of_tendsto' at_top_ne_bot tendsto_norm (F_le_bound) end lemma integrable_of_dominated_convergence {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : integrable f := /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ⊤` since `bound` is integrable -/ begin rw integrable_iff_norm, calc (∫⁻ a, (ennreal.of_real ∥f a∥)) ≤ ∫⁻ a, ennreal.of_real (bound a) : lintegral_le_lintegral_ae $ all_ae_of_real_f_le_bound h_bound h_lim ... < ⊤ : begin rw ← integrable_iff_of_real, { exact bound_integrable }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h, end end lemma tendsto_lintegral_norm_of_dominated_convergence [measurable_space β] [borel_space β] [second_countable_topology β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable bound) (h_bound : ∀ n, ∀ₘ a, ∥F n a∥ ≤ bound a) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0) := let b := λa, 2 * ennreal.of_real (bound a) in /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ have hb : ∀ n, ∀ₘ a, ennreal.of_real ∥F n a - f a∥ ≤ b a, begin assume n, filter_upwards [all_ae_of_real_F_le_bound h_bound n, all_ae_of_real_f_le_bound h_bound h_lim], assume a h₁ h₂, calc ennreal.of_real ∥F n a - f a∥ ≤ (ennreal.of_real ∥F n a∥) + (ennreal.of_real ∥f a∥) : begin rw [← ennreal.of_real_add], apply of_real_le_of_real, { apply norm_sub_le }, { exact norm_nonneg _ }, { exact norm_nonneg _ } end ... ≤ (ennreal.of_real (bound a)) + (ennreal.of_real (bound a)) : add_le_add' h₁ h₂ ... = b a : by rw ← two_mul end, /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ have h : ∀ₘ a, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 0), begin suffices h : ∀ₘ a, tendsto (λ n, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 $ ennreal.of_real 0), { rwa ennreal.of_real_zero at h }, filter_upwards [h_lim], assume a h, refine tendsto.comp (continuous.tendsto continuous_of_real _) _, rw ← tendsto_iff_norm_tendsto_zero, exact h end, /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ begin suffices h : tendsto (λn, ∫⁻ a, ennreal.of_real ∥F n a - f a∥) at_top (𝓝 (∫⁻ (a:α), 0)), { rwa lintegral_zero at h }, -- Using the dominated convergence theorem. refine tendsto_lintegral_of_dominated_convergence _ _ hb _ _, -- Show `λa, ∥f a - F n a∥` is measurable for all `n` { exact λn, measurable_of_real.comp ((F_measurable n).sub f_measurable).norm }, -- Show `2 * bound` is integrable { rw integrable_iff_of_real at bound_integrable, { calc (∫⁻ a, b a) = 2 * (∫⁻ a, ennreal.of_real (bound a)) : by { rw lintegral_const_mul', exact coe_ne_top } ... < ⊤ : mul_lt_top (coe_lt_top) bound_integrable }, filter_upwards [h_bound 0] λ a h, le_trans (norm_nonneg _) h }, -- Show `∥f a - F n a∥ --> 0` { exact h } end end dominated_convergence section pos_part /-! Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.max_zero {f : α → ℝ} (hf : integrable f) : integrable (λa, max (f a) 0) := begin simp only [integrable_iff_norm] at *, calc (∫⁻ a, ennreal.of_real ∥max (f a) 0∥) ≤ (∫⁻ (a : α), ennreal.of_real ∥f a∥) : lintegral_mono begin assume a, apply of_real_le_of_real, simp only [real.norm_eq_abs], calc abs (max (f a) 0) = max (f a) 0 : by { rw abs_of_nonneg, apply le_max_right } ... ≤ abs (f a) : max_le (le_abs_self _) (abs_nonneg _) end ... < ⊤ : hf end lemma integrable.min_zero {f : α → ℝ} (hf : integrable f) : integrable (λa, min (f a) 0) := begin have : (λa, min (f a) 0) = (λa, - max (-f a) 0), { funext, rw [min_eq_neg_max_neg_neg, neg_zero] }, rw this, exact (integrable.max_zero hf.neg).neg, end end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul (c : 𝕜) {f : α → β} : integrable f → integrable (λa, c • f a) := begin simp only [integrable], assume hfi, calc (∫⁻ (a : α), nnnorm ((c • f) a)) = (∫⁻ (a : α), (nnnorm c) * nnnorm (f a)) : begin apply lintegral_congr_ae, filter_upwards [], assume a, simp only [nnnorm_smul, set.mem_set_of_eq, pi.smul_apply, ennreal.coe_mul] end ... < ⊤ : begin rw lintegral_const_mul', apply mul_lt_top, { exact coe_lt_top }, { exact hfi }, { simp only [ennreal.coe_ne_top, ne.def, not_false_iff] } end end lemma integrable_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (λa, c • f a) ↔ integrable f := begin split, { assume h, simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.smul c⁻¹ }, exact integrable.smul _ end end normed_space variables [second_countable_topology β] namespace ae_eq_fun variable [measurable_space β] section variable [opens_measurable_space β] /-- An almost everywhere equal function is `integrable` if it has a finite distance to the origin. Should mean the same thing as the predicate `integrable` over functions. -/ def integrable (f : α →ₘ β) : Prop := f ∈ ball (0 : α →ₘ β) ⊤ lemma integrable_mk {f : α → β} (hf : measurable f) : (integrable (mk f hf)) ↔ measure_theory.integrable f := by simp [integrable, zero_def, edist_mk_mk', measure_theory.integrable, nndist_eq_nnnorm] lemma integrable_to_fun (f : α →ₘ β) : integrable f ↔ (measure_theory.integrable f.to_fun) := by conv_lhs { rw [self_eq_mk f, integrable_mk] } local attribute [simp] integrable_mk lemma integrable_zero : integrable (0 : α →ₘ β) := mem_ball_self coe_lt_top end section variable [borel_space β] lemma integrable.add : ∀ {f g : α →ₘ β}, integrable f → integrable g → integrable (f + g) := begin rintros ⟨f, hf⟩ ⟨g, hg⟩, simp only [mem_ball, zero_def, mk_add_mk, integrable_mk, quot_mk_eq_mk], assume hfi hgi, exact hfi.add hf hg hgi end lemma integrable.neg : ∀ {f : α →ₘ β}, integrable f → integrable (-f) := begin rintros ⟨f, hfm⟩ hfi, exact (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg end lemma integrable.sub : ∀ {f g : α →ₘ β}, integrable f → integrable g → integrable (f - g) := begin rintros ⟨f, hfm⟩ ⟨g, hgm⟩, simp only [quot_mk_eq_mk, integrable_mk, mk_sub_mk], exact λ hfi hgi, hfi.sub hfm hgm hgi end protected lemma is_add_subgroup : is_add_subgroup (ball (0 : α →ₘ β) ⊤) := { zero_mem := integrable_zero, add_mem := λ _ _, integrable.add, neg_mem := λ _, integrable.neg } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul : ∀ {c : 𝕜} {f : α →ₘ β}, integrable f → integrable (c • f) := begin rintros c ⟨f, hfm⟩, simp only [quot_mk_eq_mk, integrable_mk, smul_mk], exact λ hfi, hfi.smul c end end normed_space end end ae_eq_fun section variables (α β) [measurable_space β] [opens_measurable_space β] /-- The space of equivalence classes of integrable (and measurable) functions, where two integrable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def l1 : Type (max u v) := subtype (@ae_eq_fun.integrable α _ β _ _ _ _) infixr ` →₁ `:25 := l1 end namespace l1 open ae_eq_fun local attribute [instance] ae_eq_fun.is_add_subgroup variables [measurable_space β] section variable [opens_measurable_space β] instance : has_coe (α →₁ β) (α →ₘ β) := ⟨subtype.val⟩ protected lemma eq {f g : α →₁ β} : (f : α →ₘ β) = (g : α →ₘ β) → f = g := subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ β} : (f : α →ₘ β) = (g : α →ₘ β) ↔ f = g := iff.intro (l1.eq) (congr_arg coe) /- TODO : order structure of l1-/ /-- `L¹` space forms a `emetric_space`, with the emetric being inherited from almost everywhere functions, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ instance : emetric_space (α →₁ β) := subtype.emetric_space /-- `L¹` space forms a `metric_space`, with the metric being inherited from almost everywhere functions, i.e., `edist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a))`. -/ instance : metric_space (α →₁ β) := metric_space_emetric_ball 0 ⊤ end variable [borel_space β] instance : add_comm_group (α →₁ β) := subtype.add_comm_group instance : inhabited (α →₁ β) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ β) : α →ₘ β) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ β) : ((f + g : α →₁ β) : α →ₘ β) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ β) : ((-f : α →₁ β) : α →ₘ β) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ β) : ((f - g : α →₁ β) : α →ₘ β) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ β) : edist f g = edist (f : α →ₘ β) (g : α →ₘ β) := rfl lemma dist_eq (f g : α →₁ β) : dist f g = ennreal.to_real (edist (f : α →ₘ β) (g : α →ₘ β)) := rfl /-- The norm on `L¹` space is defined to be `∥f∥ = ∫⁻ a, edist (f a) 0`. -/ instance : has_norm (α →₁ β) := ⟨λ f, dist f 0⟩ lemma norm_eq (f : α →₁ β) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ β) 0) := rfl instance : normed_group (α →₁ β) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add], rw edist_eq_add_add } section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] instance : has_scalar 𝕜 (α →₁ β) := ⟨λ x f, ⟨x • (f : α →ₘ β), ae_eq_fun.integrable.smul f.2⟩⟩ @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ β) : ((c • f : α →₁ β) : α →ₘ β) = c • (f : α →ₘ β) := rfl instance : semimodule 𝕜 (α →₁ β) := { one_smul := λf, l1.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, l1.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, l1.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, l1.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, l1.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, l1.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } instance : normed_space 𝕜 (α →₁ β) := ⟨ begin rintros x ⟨f, hf⟩, show ennreal.to_real (edist (x • f) 0) ≤ ∥x∥ * ennreal.to_real (edist f 0), rw [edist_smul, to_real_of_real_mul], exact norm_nonneg _ end ⟩ end normed_space section of_fun /-- Construct the equivalence class `[f]` of a measurable and integrable function `f`. -/ def of_fun (f : α → β) (hfm : measurable f) (hfi : integrable f) : (α →₁ β) := ⟨mk f hfm, by { rw integrable_mk, exact hfi }⟩ lemma of_fun_eq_mk (f : α → β) (hfm hfi) : (of_fun f hfm hfi : α →ₘ β) = mk f hfm := rfl lemma of_fun_eq_of_fun (f g : α → β) (hfm hfi hgm hgi) : of_fun f hfm hfi = of_fun g hgm hgi ↔ ∀ₘ a, f a = g a := by { rw ← l1.eq_iff, simp only [of_fun_eq_mk, mk_eq_mk] } lemma of_fun_zero : of_fun (λa:α, (0:β)) (@measurable_const _ _ _ _ (0:β)) (integrable_zero α β) = 0 := rfl lemma of_fun_add (f g : α → β) (hfm hfi hgm hgi) : of_fun (λa, f a + g a) (measurable.add hfm hgm) (integrable.add hfm hfi hgm hgi) = of_fun f hfm hfi + of_fun g hgm hgi := rfl lemma of_fun_neg (f : α → β) (hfm hfi) : of_fun (λa, - f a) (measurable.neg hfm) (integrable.neg hfi) = - of_fun f hfm hfi := rfl lemma of_fun_sub (f g : α → β) (hfm hfi hgm hgi) : of_fun (λa, f a - g a) (measurable.sub hfm hgm) (integrable.sub hfm hfi hgm hgi) = of_fun f hfm hfi - of_fun g hgm hgi := rfl lemma norm_of_fun (f : α → β) (hfm hfi) : ∥of_fun f hfm hfi∥ = ennreal.to_real (∫⁻ a, edist (f a) 0) := rfl lemma norm_of_fun_eq_lintegral_norm (f : α → β) (hfm hfi) : ∥of_fun f hfm hfi∥ = ennreal.to_real (∫⁻ a, ennreal.of_real ∥f a∥) := by { rw [norm_of_fun, lintegral_norm_eq_lintegral_edist] } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma of_fun_smul (f : α → β) (hfm : measurable f) (hfi : integrable f) (k : 𝕜) : of_fun (λa, k • f a) (hfm.const_smul _) (hfi.smul _) = k • of_fun f hfm hfi := rfl end of_fun section to_fun /-- Find a representative of an `L¹` function [f] -/ @[reducible] protected def to_fun (f : α →₁ β) : α → β := (f : α →ₘ β).to_fun protected lemma measurable (f : α →₁ β) : measurable f.to_fun := f.1.measurable protected lemma integrable (f : α →₁ β) : integrable f.to_fun := by { rw [l1.to_fun, ← integrable_to_fun], exact f.2 } lemma of_fun_to_fun (f : α →₁ β) : of_fun (f.to_fun) f.measurable f.integrable = f := begin rcases f with ⟨f, hfi⟩, rw [of_fun, subtype.mk_eq_mk], exact (self_eq_mk f).symm end lemma mk_to_fun (f : α →₁ β) : mk (f.to_fun) f.measurable = f := by { rw ← of_fun_eq_mk, rw l1.eq_iff, exact of_fun_to_fun f } lemma to_fun_of_fun (f : α → β) (hfm hfi) : ∀ₘ a, (of_fun f hfm hfi).to_fun a = f a := (all_ae_mk_to_fun f hfm).mono $ assume a, id variables (α β) lemma zero_to_fun : ∀ₘ a, (0 : α →₁ β).to_fun a = 0 := ae_eq_fun.zero_to_fun variables {α β} lemma add_to_fun (f g : α →₁ β) : ∀ₘ a, (f + g).to_fun a = f.to_fun a + g.to_fun a := ae_eq_fun.add_to_fun _ _ lemma neg_to_fun (f : α →₁ β) : ∀ₘ a, (-f).to_fun a = -f.to_fun a := ae_eq_fun.neg_to_fun _ lemma sub_to_fun (f g : α →₁ β) : ∀ₘ a, (f - g).to_fun a = f.to_fun a - g.to_fun a := ae_eq_fun.sub_to_fun _ _ lemma dist_to_fun (f g : α →₁ β) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_fun x) (g.to_fun x)) := by { simp only [dist_eq, edist_to_fun] } lemma norm_eq_nnnorm_to_fun (f : α →₁ β) : ∥f∥ = ennreal.to_real (∫⁻ a, nnnorm (f.to_fun a)) := by { rw [lintegral_nnnorm_eq_lintegral_edist, ← edist_zero_to_fun], refl } lemma norm_eq_norm_to_fun (f : α →₁ β) : ∥f∥ = ennreal.to_real (∫⁻ a, ennreal.of_real ∥f.to_fun a∥) := by { rw norm_eq_nnnorm_to_fun, congr, funext, rw of_real_norm_eq_coe_nnnorm } lemma lintegral_edist_to_fun_lt_top (f g : α →₁ β) : (∫⁻ a, edist (f.to_fun a) (g.to_fun a)) < ⊤ := begin apply lintegral_edist_lt_top, exact f.measurable, exact f.integrable, exact g.measurable, exact g.integrable end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma smul_to_fun (c : 𝕜) (f : α →₁ β) : ∀ₘ a, (c • f).to_fun a = c • f.to_fun a := ae_eq_fun.smul_to_fun _ _ end to_fun section pos_part /-- Positive part of a function in `L¹` space. -/ def pos_part (f : α →₁ ℝ) : α →₁ ℝ := ⟨ ae_eq_fun.pos_part f, begin rw [ae_eq_fun.integrable_to_fun, integrable_congr_ae (pos_part_to_fun _)], exact integrable.max_zero f.integrable end ⟩ /-- Negative part of a function in `L¹` space. -/ def neg_part (f : α →₁ ℝ) : α →₁ ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ ℝ) : (f.pos_part : α →ₘ ℝ) = (f : α →ₘ ℝ).pos_part := rfl lemma pos_part_to_fun (f : α →₁ ℝ) : ∀ₘ a, (pos_part f).to_fun a = max (f.to_fun a) 0 := ae_eq_fun.pos_part_to_fun _ lemma neg_part_to_fun_eq_max (f : α →₁ ℝ) : ∀ₘ a, (neg_part f).to_fun a = max (- f.to_fun a) 0 := begin rw neg_part, filter_upwards [pos_part_to_fun (-f), neg_to_fun f], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂] end lemma neg_part_to_fun_eq_min (f : α →₁ ℝ) : ∀ₘ a, (neg_part f).to_fun a = - min (f.to_fun a) 0 := begin filter_upwards [neg_part_to_fun_eq_max f], simp only [mem_set_of_eq], assume a h, rw [h, min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero], end lemma norm_le_norm_of_ae_le {f g : α →₁ β} (h : ∀ₘ a, ∥f.to_fun a∥ ≤ ∥g.to_fun a∥) : ∥f∥ ≤ ∥g∥ := begin simp only [l1.norm_eq_norm_to_fun], rw to_real_le_to_real, { apply lintegral_le_lintegral_ae, filter_upwards [h], simp only [mem_set_of_eq], assume a h, exact of_real_le_of_real h }, { rw [← lt_top_iff_ne_top, ← integrable_iff_norm], exact f.integrable }, { rw [← lt_top_iff_ne_top, ← integrable_iff_norm], exact g.integrable } end lemma continuous_pos_part : continuous $ λf : α →₁ ℝ, pos_part f := begin simp only [metric.continuous_iff], assume g ε hε, use ε, use hε, simp only [dist_eq_norm], assume f hfg, refine lt_of_le_of_lt (norm_le_norm_of_ae_le _) hfg, filter_upwards [l1.sub_to_fun f g, l1.sub_to_fun (pos_part f) (pos_part g), pos_part_to_fun f, pos_part_to_fun g], simp only [mem_set_of_eq], assume a h₁ h₂ h₃ h₄, simp only [real.norm_eq_abs, h₁, h₂, h₃, h₄], exact abs_max_sub_max_le_abs _ _ _ end lemma continuous_neg_part : continuous $ λf : α →₁ ℝ, neg_part f := have eq : (λf : α →₁ ℝ, neg_part f) = (λf : α →₁ ℝ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part /- TODO: l1 is a complete space -/ end l1 end measure_theory
53e3edf03ede5c9d0c972d03a753e4350acb181c
f20db13587f4dd28a4b1fbd31953afd491691fa0
/library/init/data/list/lemmas.lean
efd4130f910c18cf41db978b6536f2cc2b7508cf
[ "Apache-2.0" ]
permissive
AHartNtkn/lean
9a971edfc6857c63edcbf96bea6841b9a84cf916
0d83a74b26541421fc1aa33044c35b03759710ed
refs/heads/master
1,620,592,591,236
1,516,749,881,000
1,516,749,881,000
118,697,288
1
0
null
1,516,759,470,000
1,516,759,470,000
null
UTF-8
Lean
false
false
10,451
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn -/ prelude import init.data.list.basic init.function init.meta init.data.nat.lemmas import init.meta.interactive init.meta.smt.rsimp universes u v w w₁ w₂ variables {α : Type u} {β : Type v} {γ : Type w} namespace list open nat /- append -/ @[simp] lemma nil_append (s : list α) : [] ++ s = s := rfl @[simp] lemma cons_append (x : α) (s t : list α) : (x::s) ++ t = x::(s ++ t) := rfl @[simp] lemma append_nil (t : list α) : t ++ [] = t := by induction t; simp [*] @[simp] lemma append_assoc (s t u : list α) : s ++ t ++ u = s ++ (t ++ u) := by induction s; simp [*] /- length -/ lemma length_cons (a : α) (l : list α) : length (a :: l) = length l + 1 := rfl @[simp] lemma length_append (s t : list α) : length (s ++ t) = length s + length t := by induction s; simp [*] @[simp] lemma length_repeat (a : α) (n : ℕ) : length (repeat a n) = n := by induction n; simp [*]; refl @[simp] lemma length_tail (l : list α) : length (tail l) = length l - 1 := by cases l; refl -- TODO(Leo): cleanup proof after arith dec proc @[simp] lemma length_drop : ∀ (i : ℕ) (l : list α), length (drop i l) = length l - i | 0 l := rfl | (succ i) [] := eq.symm (nat.zero_sub (succ i)) | (succ i) (x::l) := calc length (drop (succ i) (x::l)) = length l - i : length_drop i l ... = succ (length l) - succ i : (nat.succ_sub_succ_eq_sub (length l) i).symm /- map -/ lemma map_cons (f : α → β) (a l) : map f (a::l) = f a :: map f l := rfl @[simp] lemma map_append (f : α → β) : ∀ l₁ l₂, map f (l₁ ++ l₂) = (map f l₁) ++ (map f l₂) := by intro l₁; induction l₁; intros; simp [*] lemma map_singleton (f : α → β) (a : α) : map f [a] = [f a] := rfl @[simp] lemma map_id (l : list α) : map id l = l := by induction l; simp [*] @[simp] lemma map_map (g : β → γ) (f : α → β) (l : list α) : map g (map f l) = map (g ∘ f) l := by induction l; simp [*] @[simp] lemma length_map (f : α → β) (l : list α) : length (map f l) = length l := by induction l; simp [*] /- bind -/ @[simp] lemma nil_bind (f : α → list β) : bind [] f = [] := by simp [join, bind] @[simp] lemma cons_bind (x xs) (f : α → list β) : bind (x :: xs) f = f x ++ bind xs f := by simp [join, bind] @[simp] lemma append_bind (xs ys) (f : α → list β) : bind (xs ++ ys) f = bind xs f ++ bind ys f := by induction xs; [refl, simp [*, cons_bind]] /- mem -/ @[simp] lemma mem_nil_iff (a : α) : a ∈ ([] : list α) ↔ false := iff.rfl @[simp] lemma not_mem_nil (a : α) : a ∉ ([] : list α) := iff.mp $ mem_nil_iff a @[simp] lemma mem_cons_self (a : α) (l : list α) : a ∈ a :: l := or.inl rfl @[simp] lemma mem_cons_iff (a y : α) (l : list α) : a ∈ y :: l ↔ (a = y ∨ a ∈ l) := iff.rfl @[rsimp] lemma mem_cons_eq (a y : α) (l : list α) : (a ∈ y :: l) = (a = y ∨ a ∈ l) := rfl lemma mem_cons_of_mem (y : α) {a : α} {l : list α} : a ∈ l → a ∈ y :: l := assume H, or.inr H lemma eq_or_mem_of_mem_cons {a y : α} {l : list α} : a ∈ y::l → a = y ∨ a ∈ l := assume h, h @[simp] lemma mem_append {a : α} {s t : list α} : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t := by induction s; simp [*, or_assoc] @[rsimp] lemma mem_append_eq (a : α) (s t : list α) : (a ∈ s ++ t) = (a ∈ s ∨ a ∈ t) := propext mem_append lemma mem_append_left {a : α} {l₁ : list α} (l₂ : list α) (h : a ∈ l₁) : a ∈ l₁ ++ l₂ := mem_append.2 (or.inl h) lemma mem_append_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ++ l₂ := mem_append.2 (or.inr h) @[simp] lemma not_bex_nil (p : α → Prop) : ¬ (∃ x ∈ @nil α, p x) := λ⟨x, hx, px⟩, hx @[simp] lemma ball_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := λx, false.elim @[simp] lemma bex_cons (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ (a :: l), p x) ↔ (p a ∨ ∃ x ∈ l, p x) := ⟨λ⟨x, h, px⟩, by { simp at h, cases h with h h, {cases h, exact or.inl px}, {exact or.inr ⟨x, h, px⟩}}, λo, o.elim (λpa, ⟨a, mem_cons_self _ _, pa⟩) (λ⟨x, h, px⟩, ⟨x, mem_cons_of_mem _ h, px⟩)⟩ @[simp] lemma ball_cons (p : α → Prop) (a : α) (l : list α) : (∀ x ∈ (a :: l), p x) ↔ (p a ∧ ∀ x ∈ l, p x) := ⟨λal, ⟨al a (mem_cons_self _ _), λx h, al x (mem_cons_of_mem _ h)⟩, λ⟨pa, al⟩ x o, o.elim (λe, e.symm ▸ pa) (al x)⟩ /- list subset -/ protected def subset (l₁ l₂ : list α) := ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ instance : has_subset (list α) := ⟨list.subset⟩ @[simp] lemma nil_subset (l : list α) : [] ⊆ l := λ b i, false.elim (iff.mp (mem_nil_iff b) i) @[refl, simp] lemma subset.refl (l : list α) : l ⊆ l := λ b i, i @[trans] lemma subset.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := λ b i, h₂ (h₁ i) @[simp] lemma subset_cons (a : α) (l : list α) : l ⊆ a::l := λ b i, or.inr i lemma subset_of_cons_subset {a : α} {l₁ l₂ : list α} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ := λ s b i, s (mem_cons_of_mem _ i) lemma cons_subset_cons {l₁ l₂ : list α} (a : α) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) := λ b hin, or.elim (eq_or_mem_of_mem_cons hin) (λ e : b = a, or.inl e) (λ i : b ∈ l₁, or.inr (s i)) @[simp] lemma subset_append_left (l₁ l₂ : list α) : l₁ ⊆ l₁++l₂ := λ b, mem_append_left _ @[simp] lemma subset_append_right (l₁ l₂ : list α) : l₂ ⊆ l₁++l₂ := λ b, mem_append_right _ lemma subset_cons_of_subset (a : α) {l₁ l₂ : list α} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) := λ (s : l₁ ⊆ l₂) (a : α) (i : a ∈ l₁), or.inr (s i) theorem eq_nil_of_length_eq_zero {l : list α} : length l = 0 → l = [] := by {induction l; intros, refl, contradiction} theorem ne_nil_of_length_eq_succ {l : list α} : ∀ {n : nat}, length l = succ n → l ≠ [] := by induction l; intros; contradiction @[simp] theorem length_map₂ (f : α → β → γ) (l₁) : ∀ l₂, length (map₂ f l₁ l₂) = min (length l₁) (length l₂) := by {induction l₁; intro l₂; cases l₂; simp [*, add_one, min_succ_succ]} @[simp] theorem length_take : ∀ (i : ℕ) (l : list α), length (take i l) = min i (length l) | 0 l := by simp | (succ n) [] := by simp | (succ n) (a::l) := by simp [*, nat.min_succ_succ, add_one] theorem length_take_le (n) (l : list α) : length (take n l) ≤ n := by simp [min_le_left] theorem length_remove_nth : ∀ (l : list α) (i : ℕ), i < length l → length (remove_nth l i) = length l - 1 | [] _ h := rfl | (x::xs) 0 h := by simp [remove_nth, -add_comm] | (x::xs) (i+1) h := have i < length xs, from lt_of_succ_lt_succ h, by dsimp [remove_nth]; rw [length_remove_nth xs i this, nat.sub_add_cancel (lt_of_le_of_lt (nat.zero_le _) this)]; refl @[simp] lemma partition_eq_filter_filter (p : α → Prop) [decidable_pred p] : ∀ (l : list α), partition p l = (filter p l, filter (not ∘ p) l) | [] := rfl | (a::l) := by { by_cases pa : p a; simp [partition, filter, pa, partition_eq_filter_filter l], rw [if_neg (not_not_intro pa)], rw [if_pos pa] } /- sublists -/ inductive sublist : list α → list α → Prop | slnil : sublist [] [] | cons (l₁ l₂ a) : sublist l₁ l₂ → sublist l₁ (a::l₂) | cons2 (l₁ l₂ a) : sublist l₁ l₂ → sublist (a::l₁) (a::l₂) infix ` <+ `:50 := sublist lemma length_le_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ ≤ length l₂ | _ _ sublist.slnil := le_refl 0 | _ _ (sublist.cons l₁ l₂ a s) := le_succ_of_le (length_le_of_sublist s) | _ _ (sublist.cons2 l₁ l₂ a s) := succ_le_succ (length_le_of_sublist s) /- filter -/ @[simp] theorem filter_nil (p : α → Prop) [h : decidable_pred p] : filter p [] = [] := rfl @[simp] theorem filter_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, p a → filter p (a::l) = a :: filter p l := λ l pa, if_pos pa @[simp] theorem filter_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α} : ∀ l, ¬ p a → filter p (a::l) = filter p l := λ l pa, if_neg pa @[simp] theorem filter_append {p : α → Prop} [h : decidable_pred p] : ∀ (l₁ l₂ : list α), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂ | [] l₂ := rfl | (a::l₁) l₂ := by by_cases pa : p a; simp [pa, filter_append] @[simp] theorem filter_sublist {p : α → Prop} [h : decidable_pred p] : Π (l : list α), filter p l <+ l | [] := sublist.slnil | (a::l) := if pa : p a then by simp [pa]; apply sublist.cons2; apply filter_sublist l else by simp [pa]; apply sublist.cons; apply filter_sublist l /- map_accumr -/ section map_accumr variables {φ : Type w₁} {σ : Type w₂} -- This runs a function over a list returning the intermediate results and a -- a final result. def map_accumr (f : α → σ → σ × β) : list α → σ → (σ × list β) | [] c := (c, []) | (y::yr) c := let r := map_accumr yr c in let z := f y r.1 in (z.1, z.2 :: r.2) @[simp] theorem length_map_accumr : ∀ (f : α → σ → σ × β) (x : list α) (s : σ), length (map_accumr f x s).2 = length x | f (a::x) s := congr_arg succ (length_map_accumr f x s) | f [] s := rfl end map_accumr section map_accumr₂ variables {φ : Type w₁} {σ : Type w₂} -- This runs a function over two lists returning the intermediate results and a -- a final result. def map_accumr₂ (f : α → β → σ → σ × φ) : list α → list β → σ → σ × list φ | [] _ c := (c,[]) | _ [] c := (c,[]) | (x::xr) (y::yr) c := let r := map_accumr₂ xr yr c in let q := f x y r.1 in (q.1, q.2 :: r.2) @[simp] theorem length_map_accumr₂ : ∀ (f : α → β → σ → σ × φ) x y c, length (map_accumr₂ f x y c).2 = min (length x) (length y) | f (a::x) (b::y) c := calc succ (length (map_accumr₂ f x y c).2) = succ (min (length x) (length y)) : congr_arg succ (length_map_accumr₂ f x y c) ... = min (succ (length x)) (succ (length y)) : eq.symm (min_succ_succ (length x) (length y)) | f (a::x) [] c := rfl | f [] (b::y) c := rfl | f [] [] c := rfl end map_accumr₂ end list
685fe07694f4db298be3b98b4703f69c461d51d0
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/lie/abelian.lean
12aa6a6f3afb68180a6e6b2cc3e5cf9638bce95d
[ "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
11,613
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.of_associative import algebra.lie.ideal_operations /-! # Trivial Lie modules and Abelian Lie algebras The action of a Lie algebra `L` on a module `M` is trivial if `⁅x, m⁆ = 0` for all `x ∈ L` and `m ∈ M`. In the special case that `M = L` with the adjoint action, triviality corresponds to the concept of an Abelian Lie algebra. In this file we define these concepts and provide some related definitions and results. ## Main definitions * `lie_module.is_trivial` * `is_lie_abelian` * `commutative_ring_iff_abelian_lie_ring` * `lie_module.ker` * `lie_module.max_triv_submodule` * `lie_algebra.center` ## Tags lie algebra, abelian, commutative, center -/ universes u v w w₁ w₂ /-- A Lie (ring) module is trivial iff all brackets vanish. -/ class lie_module.is_trivial (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] : Prop := (trivial : ∀ (x : L) (m : M), ⁅x, m⁆ = 0) @[simp] lemma trivial_lie_zero (L : Type v) (M : Type w) [has_bracket L M] [has_zero M] [lie_module.is_trivial L M] (x : L) (m : M) : ⁅x, m⁆ = 0 := lie_module.is_trivial.trivial x m /-- A Lie algebra is Abelian iff it is trivial as a Lie module over itself. -/ abbreviation is_lie_abelian (L : Type v) [has_bracket L L] [has_zero L] : Prop := lie_module.is_trivial L L instance lie_ideal.is_lie_abelian_of_trivial (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] (I : lie_ideal R L) [h : lie_module.is_trivial L I] : is_lie_abelian I := { trivial := λ x y, by apply h.trivial } lemma function.injective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.injective f) (h₂ : is_lie_abelian L₂) : is_lie_abelian L₁ := { trivial := λ x y, h₁ $ calc f ⁅x,y⁆ = ⁅f x, f y⁆ : lie_hom.map_lie f x y ... = 0 : trivial_lie_zero _ _ _ _ ... = f 0 : f.map_zero.symm } lemma function.surjective.is_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] {f : L₁ →ₗ⁅R⁆ L₂} (h₁ : function.surjective f) (h₂ : is_lie_abelian L₁) : is_lie_abelian L₂ := { trivial := λ x y, begin obtain ⟨u, rfl⟩ := h₁ x, obtain ⟨v, rfl⟩ := h₁ y, rw [← lie_hom.map_lie, trivial_lie_zero, lie_hom.map_zero], end } lemma lie_abelian_iff_equiv_lie_abelian {R : Type u} {L₁ : Type v} {L₂ : Type w} [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] (e : L₁ ≃ₗ⁅R⁆ L₂) : is_lie_abelian L₁ ↔ is_lie_abelian L₂ := ⟨e.symm.injective.is_lie_abelian, e.injective.is_lie_abelian⟩ lemma commutative_ring_iff_abelian_lie_ring {A : Type v} [ring A] : is_commutative A (*) ↔ is_lie_abelian A := have h₁ : is_commutative A (*) ↔ ∀ (a b : A), a * b = b * a := ⟨λ h, h.1, λ h, ⟨h⟩⟩, have h₂ : is_lie_abelian A ↔ ∀ (a b : A), ⁅a, b⁆ = 0 := ⟨λ h, h.1, λ h, ⟨h⟩⟩, by simp only [h₁, h₂, lie_ring.of_associative_ring_bracket, sub_eq_zero] lemma lie_algebra.is_lie_abelian_bot (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] : is_lie_abelian (⊥ : lie_ideal R L) := ⟨λ ⟨x, hx⟩ _, by convert zero_lie _⟩ section center variables (R : Type u) (L : Type v) (M : Type w) (N : Type w₁) variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N] namespace lie_module /-- The kernel of the action of a Lie algebra `L` on a Lie module `M` as a Lie ideal in `L`. -/ protected def ker : lie_ideal R L := (to_endomorphism R L M).ker @[simp] protected lemma mem_ker (x : L) : x ∈ lie_module.ker R L M ↔ ∀ (m : M), ⁅x, m⁆ = 0 := by simp only [lie_module.ker, lie_hom.mem_ker, linear_map.ext_iff, linear_map.zero_apply, to_endomorphism_apply_apply] /-- The largest submodule of a Lie module `M` on which the Lie algebra `L` acts trivially. -/ def max_triv_submodule : lie_submodule R L M := { carrier := { m | ∀ (x : L), ⁅x, m⁆ = 0 }, zero_mem' := λ x, lie_zero x, add_mem' := λ x y hx hy z, by rw [lie_add, hx, hy, add_zero], smul_mem' := λ c x hx y, by rw [lie_smul, hx, smul_zero], lie_mem := λ x m hm y, by rw [hm, lie_zero], } @[simp] lemma mem_max_triv_submodule (m : M) : m ∈ max_triv_submodule R L M ↔ ∀ (x : L), ⁅x, m⁆ = 0 := iff.rfl instance : is_trivial L (max_triv_submodule R L M) := { trivial := λ x m, subtype.ext (m.property x), } @[simp] lemma ideal_oper_max_triv_submodule_eq_bot (I : lie_ideal R L) : ⁅I, max_triv_submodule R L M⁆ = ⊥ := begin rw [← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.lie_ideal_oper_eq_linear_span, lie_submodule.bot_coe_submodule, submodule.span_eq_bot], rintros m ⟨⟨x, hx⟩, ⟨⟨m, hm⟩, rfl⟩⟩, exact hm x, end lemma le_max_triv_iff_bracket_eq_bot {N : lie_submodule R L M} : N ≤ max_triv_submodule R L M ↔ ⁅(⊤ : lie_ideal R L), N⁆ = ⊥ := begin refine ⟨λ h, _, λ h m hm, _⟩, { rw [← le_bot_iff, ← ideal_oper_max_triv_submodule_eq_bot R L M ⊤], exact lie_submodule.mono_lie_right _ _ ⊤ h, }, { rw mem_max_triv_submodule, rw lie_submodule.lie_eq_bot_iff at h, exact λ x, h x (lie_submodule.mem_top x) m hm, }, end lemma trivial_iff_le_maximal_trivial (N : lie_submodule R L M) : is_trivial L N ↔ N ≤ max_triv_submodule R L M := ⟨ λ h m hm x, is_trivial.dcases_on h (λ h, subtype.ext_iff.mp (h x ⟨m, hm⟩)), λ h, { trivial := λ x m, subtype.ext (h m.2 x) }⟩ lemma is_trivial_iff_max_triv_eq_top : is_trivial L M ↔ max_triv_submodule R L M = ⊤ := begin split, { rintros ⟨h⟩, ext, simp only [mem_max_triv_submodule, h, forall_const, true_iff, eq_self_iff_true], }, { intros h, constructor, intros x m, revert x, rw [← mem_max_triv_submodule R L M, h], exact lie_submodule.mem_top m, }, end variables {R L M N} /-- `max_triv_submodule` is functorial. -/ def max_triv_hom (f : M →ₗ⁅R,L⁆ N) : max_triv_submodule R L M →ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := λ m, ⟨f m, λ x, (lie_module_hom.map_lie _ _ _).symm.trans $ (congr_arg f (m.property x)).trans (lie_module_hom.map_zero _)⟩, map_add' := λ m n, by simpa, map_smul' := λ t m, by simpa, map_lie' := λ x m, by simp, } @[norm_cast, simp] lemma coe_max_triv_hom_apply (f : M →ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_hom f m : N) = f m := rfl /-- The maximal trivial submodules of Lie-equivalent Lie modules are Lie-equivalent. -/ def max_triv_equiv (e : M ≃ₗ⁅R,L⁆ N) : max_triv_submodule R L M ≃ₗ⁅R,L⁆ max_triv_submodule R L N := { to_fun := max_triv_hom (e : M →ₗ⁅R,L⁆ N), inv_fun := max_triv_hom (e.symm : N →ₗ⁅R,L⁆ M), left_inv := λ m, by { ext, simp, }, right_inv := λ n, by { ext, simp, }, .. max_triv_hom (e : M →ₗ⁅R,L⁆ N), } @[norm_cast, simp] lemma coe_max_triv_equiv_apply (e : M ≃ₗ⁅R,L⁆ N) (m : max_triv_submodule R L M) : (max_triv_equiv e m : N) = e ↑m := rfl @[simp] lemma max_triv_equiv_of_refl_eq_refl : max_triv_equiv (lie_module_equiv.refl : M ≃ₗ⁅R,L⁆ M) = lie_module_equiv.refl := by { ext, simp only [coe_max_triv_equiv_apply, lie_module_equiv.refl_apply], } @[simp] lemma max_triv_equiv_of_equiv_symm_eq_symm (e : M ≃ₗ⁅R,L⁆ N) : (max_triv_equiv e).symm = max_triv_equiv e.symm := rfl /-- A linear map between two Lie modules is a morphism of Lie modules iff the Lie algebra action on it is trivial. -/ def max_triv_linear_map_equiv_lie_module_hom : (max_triv_submodule R L (M →ₗ[R] N)) ≃ₗ[R] (M →ₗ⁅R,L⁆ N) := { to_fun := λ f, { to_linear_map := f.val, map_lie' := λ x m, by { have hf : ⁅x, f.val⁆ m = 0, { rw [f.property x, linear_map.zero_apply], }, rw [lie_hom.lie_apply, sub_eq_zero, ← linear_map.to_fun_eq_coe] at hf, exact hf.symm, }, }, map_add' := λ f g, by { ext, simp, }, map_smul' := λ F G, by { ext, simp, }, inv_fun := λ F, ⟨F, λ x, by { ext, simp, }⟩, left_inv := λ f, by simp, right_inv := λ F, by simp, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M → N) = f := by { ext, refl, } @[simp] lemma coe_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M → N) = f := rfl @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom (f : max_triv_submodule R L (M →ₗ[R] N)) : ((max_triv_linear_map_equiv_lie_module_hom f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := by { ext, refl, } @[simp] lemma coe_linear_map_max_triv_linear_map_equiv_lie_module_hom_symm (f : M →ₗ⁅R,L⁆ N) : ((max_triv_linear_map_equiv_lie_module_hom.symm f) : M →ₗ[R] N) = (f : M →ₗ[R] N) := rfl end lie_module namespace lie_algebra /-- The center of a Lie algebra is the set of elements that commute with everything. It can be viewed as the maximal trivial submodule of the Lie algebra as a Lie module over itself via the adjoint representation. -/ abbreviation center : lie_ideal R L := lie_module.max_triv_submodule R L L instance : is_lie_abelian (center R L) := infer_instance @[simp] lemma ad_ker_eq_self_module_ker : (ad R L).ker = lie_module.ker R L L := rfl @[simp] lemma self_module_ker_eq_center : lie_module.ker R L L = center R L := begin ext y, simp only [lie_module.mem_max_triv_submodule, lie_module.mem_ker, ← lie_skew _ y, neg_eq_zero], end lemma abelian_of_le_center (I : lie_ideal R L) (h : I ≤ center R L) : is_lie_abelian I := begin haveI : lie_module.is_trivial L I := (lie_module.trivial_iff_le_maximal_trivial R L L I).mpr h, exact lie_ideal.is_lie_abelian_of_trivial R L I, end lemma is_lie_abelian_iff_center_eq_top : is_lie_abelian L ↔ center R L = ⊤ := lie_module.is_trivial_iff_max_triv_eq_top R L L end lie_algebra end center section ideal_operations open lie_submodule lie_subalgebra variables {R : Type u} {L : Type v} {M : Type w} variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] variables [lie_ring_module L M] [lie_module R L M] variables (N N' : lie_submodule R L M) (I J : lie_ideal R L) @[simp] lemma lie_submodule.trivial_lie_oper_zero [lie_module.is_trivial L M] : ⁅I, N⁆ = ⊥ := begin suffices : ⁅I, N⁆ ≤ ⊥, from le_bot_iff.mp this, rw [lie_ideal_oper_eq_span, lie_submodule.lie_span_le], rintros m ⟨x, n, h⟩, rw trivial_lie_zero at h, simp [← h], end lemma lie_submodule.lie_abelian_iff_lie_self_eq_bot : is_lie_abelian I ↔ ⁅I, I⁆ = ⊥ := begin simp only [_root_.eq_bot_iff, lie_ideal_oper_eq_span, lie_submodule.lie_span_le, lie_submodule.bot_coe, set.subset_singleton_iff, set.mem_set_of_eq, exists_imp_distrib], refine ⟨λ h z x y hz, hz.symm.trans ((lie_subalgebra.coe_bracket _ _ _).symm.trans ((coe_zero_iff_zero _ _).mpr (by apply h.trivial))), λ h, ⟨λ x y, (coe_zero_iff_zero _ _).mp (h _ x y rfl)⟩⟩, end end ideal_operations
0d7a807e297ea28711d69eaba54851fc4dc2b6f4
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/fold.lean
027a70c72106a5626b23e854630d0f2b30bd502c
[ "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
994
lean
prelude definition Prop := Type.{0} inductive true : Prop | intro : true inductive false : Prop constant num : Type inductive prod (A B : Type*) | mk : A → B → prod infixl ` × `:30 := prod variables a b c : num section local notation `(` t:(foldr `, ` (e r, prod.mk e r)) `)` := t #check (a, false, b, true, c) set_option pp.notation false #check (a, false, b, true, c) end section local notation `(` t:(foldr `, ` (e r, prod.mk r e)) `)` := t set_option pp.notation true #check (a, false, b, true, c) set_option pp.notation false #check (a, false, b, true, c) end section local notation `(` t:(foldl `, ` (e r, prod.mk r e)) `)` := t set_option pp.notation true #check (a, false, b, true, c) set_option pp.notation false #check (a, false, b, true, c) end section local notation `(` t:(foldl `, ` (e r, prod.mk e r)) `)` := t set_option pp.notation true #check (a, false, b, true, c) set_option pp.notation false #check (a, false, b, true, c) end
7720144bece53b0b833789f45bfa3457ccfc9bb1
26ac254ecb57ffcb886ff709cf018390161a9225
/src/tactic/linarith/datatypes.lean
fd07fb155f529c01c382ec5432efdec21237aea9
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
10,453
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import meta.rb_map import tactic.ring import tactic.linarith.lemmas /-! # Datatypes for `linarith` Some of the data structures here are used in multiple parts of the tactic. We split them into their own file. This file also contains a few convenient auxiliary functions. -/ declare_trace linarith open native namespace linarith /-- A shorthand for tracing when the `trace.linarith` option is set to true. -/ meta def linarith_trace {α} [has_to_tactic_format α] (s : α) : tactic unit := tactic.when_tracing `linarith (tactic.trace s) /-- A shorthand for tracing the types of a list of proof terms when the `trace.linarith` option is set to true. -/ meta def linarith_trace_proofs (s : string := "") (l : list expr) : tactic unit := tactic.when_tracing `linarith $ do tactic.trace s, l.mmap tactic.infer_type >>= tactic.trace /-! ### Linear expressions -/ /-- A linear expression is a list of pairs of variable indices and coefficients, representing the sum of the products of each coefficient with its corresponding variable. Some functions on `linexp` assume that `n : ℕ` occurs at most once as the first element of a pair, and that the list is sorted in decreasing order of the first argument. This is not enforced by the type but the operations here preserve it. -/ @[reducible] def linexp : Type := list (ℕ × ℤ) namespace linexp /-- Add two `linexp`s together componentwise. Preserves sorting and uniqueness of the first argument. -/ meta def add : linexp → linexp → linexp | [] a := a | a [] := a | (a@(n1,z1)::t1) (b@(n2,z2)::t2) := if n1 < n2 then b::add (a::t1) t2 else if n2 < n1 then a::add t1 (b::t2) else let sum := z1 + z2 in if sum = 0 then add t1 t2 else (n1, sum)::add t1 t2 /-- `l.scale c` scales the values in `l` by `c` without modifying the order or keys. -/ def scale (c : ℤ) (l : linexp) : linexp := if c = 0 then [] else if c = 1 then l else l.map $ λ ⟨n, z⟩, (n, z*c) /-- `l.get n` returns the value in `l` associated with key `n`, if it exists, and `none` otherwise. This function assumes that `l` is sorted in decreasing order of the first argument, that is, it will return `none` as soon as it finds a key smaller than `n`. -/ def get (n : ℕ) : linexp → option ℤ | [] := none | ((a, b)::t) := if a < n then none else if a = n then some b else get t /-- `l.contains n` is true iff `n` is the first element of a pair in `l`. -/ def contains (n : ℕ) : linexp → bool := option.is_some ∘ get n /-- `l.zfind n` returns the value associated with key `n` if there is one, and 0 otherwise. -/ def zfind (n : ℕ) (l : linexp) : ℤ := match l.get n with | none := 0 | some v := v end /-- `l.vars` returns the list of variables that occur in `l`. -/ def vars (l : linexp) : list ℕ := l.map prod.fst /-- Defines a lex ordering on `linexp`. This function is performance critical. -/ def cmp : linexp → linexp → ordering | [] [] := ordering.eq | [] _ := ordering.lt | _ [] := ordering.gt | ((n1,z1)::t1) ((n2,z2)::t2) := if n1 < n2 then ordering.lt else if n2 < n1 then ordering.gt else if z1 < z2 then ordering.lt else if z2 < z1 then ordering.gt else cmp t1 t2 end linexp /-! ### Inequalities -/ /-- The three-element type `ineq` is used to represent the strength of a comparison between terms. -/ @[derive decidable_eq, derive inhabited] inductive ineq : Type | eq | le | lt namespace ineq /-- `max R1 R2` computes the strength of the sum of two inequalities. If `t1 R1 0` and `t2 R2 0`, then `t1 + t2 (max R1 R2) 0`. -/ def max : ineq → ineq → ineq | lt a := lt | a lt := lt | le a := le | a le := le | eq eq := eq /-- `ineq` is ordered `eq < le < lt`. -/ def cmp : ineq → ineq → ordering | eq eq := ordering.eq | eq _ := ordering.lt | le le := ordering.eq | le lt := ordering.lt | lt lt := ordering.eq | _ _ := ordering.gt /-- Prints an `ineq` as the corresponding infix symbol. -/ def to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" /-- Finds the name of a multiplicative lemma corresponding to an inequality strength. -/ meta def to_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq instance : has_to_string ineq := ⟨ineq.to_string⟩ meta instance : has_to_format ineq := ⟨λ i, ineq.to_string i⟩ end ineq /-! ### Comparisons with 0 -/ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is `coeffs.sum (λ ⟨k, v⟩, v * Var[k])`. str determines the strength of the comparison -- is it < 0, ≤ 0, or = 0? -/ @[derive inhabited] structure comp : Type := (str : ineq) (coeffs : linexp) /-- `c.vars` returns the list of variables that appear in the linear expression contained in `c`. -/ def comp.vars : comp → list ℕ := linexp.vars ∘ comp.coeffs /-- `comp.coeff_of c a` projects the coefficient of variable `a` out of `c`. -/ def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a /-- `comp.scale c n` scales the coefficients of `c` by `n`. -/ def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.scale n } /-- `comp.add c1 c2` adds the expressions represented by `c1` and `c2`. The coefficient of variable `a` in `c1.add c2` is the sum of the coefficients of `a` in `c1` and `c2`. -/ meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ /-- `comp` has a lex order. First the `ineq`s are compared, then the `coeff`s. -/ meta def comp.cmp : comp → comp → ordering | ⟨str1, coeffs1⟩ ⟨str2, coeffs2⟩ := match str1.cmp str2 with | ordering.lt := ordering.lt | ordering.gt := ordering.gt | ordering.eq := coeffs1.cmp coeffs2 end /-- A `comp` represents a contradiction if its expression has no coefficients and its strength is <, that is, it represents the fact `0 < 0`. -/ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs ++ to_string p.str ++ "0"⟩ /-! ### Parsing into linear form -/ /-! ### Control -/ /-- A preprocessor transforms a proof of a proposition into a proof of a different propositon. The return type is `list expr`, since some preprocessing steps may create multiple new hypotheses, and some may remove a hypothesis from the list. A "no-op" preprocessor should return its input as a singleton list. -/ meta structure preprocessor : Type := (name : string) (transform : expr → tactic (list expr)) /-- Some preprocessors need to examine the full list of hypotheses instead of working item by item. As with `preprocessor`, the input to a `global_preprocessor` is replaced by, not added to, its output. -/ meta structure global_preprocessor : Type := (name : string) (transform : list expr → tactic (list expr)) /-- A `preprocessor` lifts to a `global_preprocessor` by folding it over the input list. -/ meta def preprocessor.globalize (pp : preprocessor) : global_preprocessor := { name := pp.name, transform := list.mfoldl (λ ret e, do l' ← pp.transform e, return (l' ++ ret)) [] } /-- `process pp l` runs `pp.transform` on `l` and returns the result, tracing the result if `trace.linarith` is on. -/ meta def global_preprocessor.process (pp : global_preprocessor) (l : list expr) : tactic (list expr) := do l ← pp.transform l, linarith_trace_proofs (to_string format!"Preprocessing: {pp.name}") l, return l meta instance : has_coe preprocessor global_preprocessor := ⟨preprocessor.globalize⟩ /-- A configuration object for `linarith`. -/ meta structure linarith_config : Type := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . tactic.apply_instance) (exfalso : bool := tt) (transparency : tactic.transparency := reducible) (split_hypotheses : bool := tt) (preprocessors : option (list global_preprocessor) := none) /-- `cfg.update_reducibility reduce_semi` will change the transparency setting of `cfg` to `semireducible` if `reduce_semi` is true. In this case, it also sets the discharger to `ring!`, since this is typically needed when using stronger unification. -/ meta def linarith_config.update_reducibility (cfg : linarith_config) (reduce_semi : bool) : linarith_config := if reduce_semi then { cfg with transparency := semireducible, discharger := `[ring!] } else cfg /-! ### Auxiliary functions These functions are used by multiple modules, so we put them here for accessibility. -/ open tactic /-- `get_rel_sides e` returns the left and right hand sides of `e` if `e` is a comparison, and fails otherwise. This function is more naturally in the `option` monad, but it is convenient to put in `tactic` for compositionality. -/ meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := tactic.failed /-- `parse_into_comp_and_expr e` checks if `e` is of the form `t < 0`, `t ≤ 0`, or `t = 0`. If it is, it returns the comparison along with `t`. -/ meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none /-- `mk_single_comp_zero_pf c h` assumes that `h` is a proof of `t R 0`. It produces a pair `(R', h')`, where `h'` is a proof of `c*t R' 0`. Typically `R` and `R'` will be the same, except when `c = 0`, in which case `R'` is `=`. If `c = 1`, `h'` is the same as `h` -- specifically, it does *not* change the type to `1*t R 0`. -/ meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (ineq.eq, e') else if c = 1 then return (iq, h) else do tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, c ← tp.of_nat c, cpos ← to_expr ``(%%c > 0), (_, ex) ← solve_aux cpos `[norm_num, done], e' ← mk_app iq.to_const_mul_nm [h, ex], return (iq, e') end linarith
4d004275c66220d582dbc25353006bf49966bb52
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/linear_algebra/prod.lean
c61f2a1064911d185bca97820a2e5c4d9189aa7d
[ "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
24,500
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, Kevin Buzzard, Yury Kudryashov, Eric Wieser -/ import linear_algebra.basic import order.partial_sups /-! ### Products of modules This file defines constructors for linear maps whose domains or codomains are products. It contains theorems relating these to each other, as well as to `submodule.prod`, `submodule.map`, `submodule.comap`, `linear_map.range`, and `linear_map.ker`. ## Main definitions - products in the domain: - `linear_map.fst` - `linear_map.snd` - `linear_map.coprod` - `linear_map.prod_ext` - products in the codomain: - `linear_map.inl` - `linear_map.inr` - `linear_map.prod` - products in both domain and codomain: - `linear_map.prod_map` - `linear_equiv.prod_map` - `linear_equiv.skew_prod` -/ universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} section prod namespace linear_map variables (S : Type*) [semiring R] [semiring S] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f : M →ₗ[R] M₂) section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := { to_fun := prod.fst, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := { to_fun := prod.snd, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl /-- The prod of two linear maps is a linear map. -/ @[simps] def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (M →ₗ[R] M₂ × M₃) := { to_fun := λ x, (f x, g x), map_add' := λ x y, by simp only [prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := by ext; refl /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def prod_equiv [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] : ((M →ₗ[R] M₂) × (M →ₗ[R] M₃)) ≃ₗ[S] (M →ₗ[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, map_add' := λ a b, rfl, map_smul' := λ r a, rfl } section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := prod linear_map.id 0 /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := prod 0 linear_map.id end @[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f.1 x.1 + f.2 x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := f.comp (fst _ _ _) + g.comp (snd _ _ _) @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M × M₂) : coprod f g x = f x.1 + g x.2 := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem comp_coprod (f : M₃ →ₗ[R] M₄) (g₁ : M →ₗ[R] M₃) (g₂ : M₂ →ₗ[R] M₃) : f.comp (g₁.coprod g₂) = (f.comp g₁).coprod (f.comp g₂) := ext $ λ x, f.map_add (g₁ x.1) (g₂ x.2) theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext; simp @[simp] theorem coprod_comp_prod (f : M₂ →ₗ[R] M₄) (g : M₃ →ₗ[R] M₄) (f' : M →ₗ[R] M₂) (g' : M →ₗ[R] M₃) : (f.coprod g).comp (f'.prod g') = f.comp f' + g.comp g' := rfl @[simp] lemma coprod_map_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (S : submodule R M) (S' : submodule R M₂) : (submodule.prod S S').map (linear_map.coprod f g) = S.map f ⊔ S'.map g := set_like.coe_injective $ begin simp only [linear_map.coprod_apply, submodule.coe_sup, submodule.map_coe], rw [←set.image2_add, set.image2_image_left, set.image2_image_right], exact set.image_prod (λ m m₂, f m + g m₂), end /-- Taking the product of two maps with the same codomain is equivalent to taking the product of their domains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def coprod_equiv [module S M₃] [smul_comm_class R S M₃] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₃)) ≃ₗ[S] (M × M₂ →ₗ[R] M₃) := { to_fun := λ f, f.1.coprod f.2, inv_fun := λ f, (f.comp (inl _ _ _), f.comp (inr _ _ _)), left_inv := λ f, by simp only [prod.mk.eta, coprod_inl, coprod_inr], right_inv := λ f, by simp only [←comp_coprod, comp_id, coprod_inl_inr], map_add' := λ a b, by { ext, simp only [prod.snd_add, add_apply, coprod_apply, prod.fst_add], ac_refl }, map_smul' := λ r a, by { ext, simp only [smul_add, smul_apply, prod.smul_snd, prod.smul_fst, coprod_apply] } } theorem prod_ext_iff {f g : M × M₂ →ₗ[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := (coprod_equiv ℕ).symm.injective.eq_iff.symm.trans prod.ext_iff /-- Split equality of linear maps from a product into linear maps over each component, to allow `ext` to apply lemmas specific to `M →ₗ M₃` and `M₂ →ₗ M₃`. See note [partially-applied ext lemmas]. -/ @[ext] theorem prod_ext {f g : M × M₂ →ₗ[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl lemma prod_map_comap_prod (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) (S : submodule R M₂) (S' : submodule R M₄) : (submodule.prod S S').comap (linear_map.prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ lemma ker_prod_map (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) : (linear_map.prod_map f g).ker = submodule.prod f.ker g.ker := begin dsimp only [ker], rw [←prod_map_comap_prod, submodule.prod_bot], end section map_mul variables {A : Type*} [non_unital_non_assoc_semiring A] [module R A] variables {B : Type*} [non_unital_non_assoc_semiring B] [module R B] lemma inl_map_mul (a₁ a₂ : A) : linear_map.inl R A B (a₁ * a₂) = linear_map.inl R A B a₁ * linear_map.inl R A B a₂ := prod.ext rfl (by simp) lemma inr_map_mul (b₁ b₂ : B) : linear_map.inr R A B (b₁ * b₂) = linear_map.inr R A B b₁ * linear_map.inr R A B b₂ := prod.ext (by simp) rfl end map_mul end linear_map end prod namespace linear_map open submodule variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma is_compl_range_inl_inr : is_compl (inl R M M₂).range (inr R M M₂).range := begin split, { rintros ⟨_, _⟩ ⟨⟨x, hx⟩, ⟨y, hy⟩⟩, simp only [prod.ext_iff, inl_apply, inr_apply, mem_bot] at hx hy ⊢, exact ⟨hy.1.symm, hx.2.symm⟩ }, { rintros ⟨x, y⟩ -, simp only [mem_sup, mem_range, exists_prop], refine ⟨(x, 0), ⟨x, rfl⟩, (0, y), ⟨y, rfl⟩, _⟩, simp } end lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := is_compl_range_inl_inr.sup_eq_top lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw set_like.le_def, rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image] @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end lemma ker_prod_ker_le_ker_coprod {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := by { rintros ⟨y, z⟩, simp {contextual := tt} } lemma ker_coprod_of_disjoint_range {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := begin apply le_antisymm _ (ker_prod_ker_le_ker_coprod f g), rintros ⟨y, z⟩ h, simp only [mem_ker, mem_prod, coprod_apply] at h ⊢, have : f y ∈ f.range ⊓ g.range, { simp only [true_and, mem_range, mem_inf, exists_apply_eq_apply], use -z, rwa [eq_comm, map_neg, ← sub_eq_zero, sub_neg_eq_add] }, rw [hd.eq_bot, mem_bot] at this, rw [this] at h, simpa [this] using h, end end linear_map namespace submodule open linear_map variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] lemma sup_eq_range (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, set_like.exists] variables (p : submodule R M) (q : submodule R M₂) @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_snd] variables (R M M₂) /-- `M` as a submodule of `M × N`. -/ def fst : submodule R (M × M₂) := (⊥ : submodule R M₂).comap (linear_map.snd R M M₂) /-- `M` as a submodule of `M × N` is isomorphic to `M`. -/ @[simps] def fst_equiv : submodule.fst R M M₂ ≃ₗ[R] M := { to_fun := λ x, x.1.1, inv_fun := λ m, ⟨⟨m, 0⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma fst_map_fst : (submodule.fst R M M₂).map (linear_map.fst R M M₂) = ⊤ := by tidy lemma fst_map_snd : (submodule.fst R M M₂).map (linear_map.snd R M M₂) = ⊥ := by { tidy, exact 0, } /-- `N` as a submodule of `M × N`. -/ def snd : submodule R (M × M₂) := (⊥ : submodule R M).comap (linear_map.fst R M M₂) /-- `N` as a submodule of `M × N` is isomorphic to `N`. -/ @[simps] def snd_equiv : submodule.snd R M M₂ ≃ₗ[R] M₂ := { to_fun := λ x, x.1.2, inv_fun := λ n, ⟨⟨0, n⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma snd_map_fst : (submodule.snd R M M₂).map (linear_map.fst R M M₂) = ⊥ := by { tidy, exact 0, } lemma snd_map_snd : (submodule.snd R M M₂).map (linear_map.snd R M M₂) = ⊤ := by tidy lemma fst_sup_snd : submodule.fst R M M₂ ⊔ submodule.snd R M M₂ = ⊤ := begin rw eq_top_iff, rintro ⟨m, n⟩ -, rw [show (m, n) = (m, 0) + (0, n), by simp], apply submodule.add_mem (submodule.fst R M M₂ ⊔ submodule.snd R M M₂), { exact submodule.mem_sup_left (submodule.mem_comap.mpr (by simp)), }, { exact submodule.mem_sup_right (submodule.mem_comap.mpr (by simp)), }, end lemma fst_inf_snd : submodule.fst R M M₂ ⊓ submodule.snd R M M₂ = ⊥ := by tidy end submodule namespace linear_equiv section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_add' := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), map_smul' := λ c x, prod.ext (e₁.map_smul c _) (e₂.map_smul c _), .. equiv.prod_congr e₁.to_equiv e₂.to_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end end linear_equiv namespace linear_map open submodule variables [ring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { rwa add_sub_cancel }, { rwa [← eq_sub_iff_add_eq.1 H, add_sub_add_right_eq_sub, ← neg_mem_iff, neg_sub, add_sub_cancel'] } end end linear_map namespace linear_map /-! ## Tunnels and tailings Some preliminary work for establishing the strong rank condition for noetherian rings. Given a morphism `f : M × N →ₗ[R] M` which is `i : injective f`, we can find an infinite decreasing `tunnel f i n` of copies of `M` inside `M`, and sitting beside these, an infinite sequence of copies of `N`. We picturesquely name these as `tailing f i n` for each individual copy of `N`, and `tailings f i n` for the supremum of the first `n+1` copies: they are the pieces left behind, sitting inside the tunnel. By construction, each `tailing f i (n+1)` is disjoint from `tailings f i n`; later, when we assume `M` is noetherian, this implies that `N` must be trivial, and establishes the strong rank condition for any left-noetherian ring. -/ section tunnel -- (This doesn't work over a semiring: we need to use that `submodule R M` is a modular lattice, -- which requires cancellation.) variables [ring R] variables {N : Type*} [add_comm_group M] [module R M] [add_comm_group N] [module R N] open function /-- An auxiliary construction for `tunnel`. The composition of `f`, followed by the isomorphism back to `K`, followed by the inclusion of this submodule back into `M`. -/ def tunnel_aux (f : M × N →ₗ[R] M) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : M × N →ₗ[R] M := (Kφ.1.subtype.comp Kφ.2.symm.to_linear_map).comp f lemma tunnel_aux_injective (f : M × N →ₗ[R] M) (i : injective f) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : injective (tunnel_aux f Kφ) := (subtype.val_injective.comp Kφ.2.symm.injective).comp i noncomputable theory /-- Auxiliary definition for `tunnel`. -/ -- Even though we have `noncomputable theory`, -- we get an error without another `noncomputable` here. noncomputable def tunnel' (f : M × N →ₗ[R] M) (i : injective f) : ℕ → Σ (K : submodule R M), K ≃ₗ[R] M | 0 := ⟨⊤, linear_equiv.of_top ⊤ rfl⟩ | (n+1) := ⟨(submodule.fst R M N).map (tunnel_aux f (tunnel' n)), ((submodule.fst R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' n))).symm.trans (submodule.fst_equiv R M N)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a nested sequence of submodules all isomorphic to `M`. -/ def tunnel (f : M × N →ₗ[R] M) (i : injective f) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (tunnel' f i n).1, monotone_nat_of_le_succ (λ n, begin dsimp [tunnel', tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a sequence of submodules all isomorphic to `N`. -/ def tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : submodule R M := (submodule.snd R M N).map (tunnel_aux f (tunnel' f i n)) /-- Each `tailing f i n` is a copy of `N`. -/ def tailing_linear_equiv (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≃ₗ[R] N := ((submodule.snd R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' f i n))).symm.trans (submodule.snd_equiv R M N) lemma tailing_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≤ tunnel f i n := begin dsimp [tailing, tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end lemma tailing_disjoint_tunnel_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailing f i n) (tunnel f i (n+1)) := begin rw disjoint_iff, dsimp [tailing, tunnel, tunnel'], rw [submodule.map_inf_eq_map_inf_comap, submodule.comap_map_eq_of_injective (tunnel_aux_injective _ i _), inf_comm, submodule.fst_inf_snd, submodule.map_bot], end lemma tailing_sup_tunnel_succ_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ⊔ tunnel f i (n+1) ≤ tunnel f i n := begin dsimp [tailing, tunnel, tunnel', tunnel_aux], rw [←submodule.map_sup, sup_comm, submodule.fst_sup_snd, submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end /-- The supremum of all the copies of `N` found inside the tunnel. -/ def tailings (f : M × N →ₗ[R] M) (i : injective f) : ℕ → submodule R M := partial_sups (tailing f i) @[simp] lemma tailings_zero (f : M × N →ₗ[R] M) (i : injective f) : tailings f i 0 = tailing f i 0 := by simp [tailings] @[simp] lemma tailings_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailings f i (n+1) = tailings f i n ⊔ tailing f i (n+1) := by simp [tailings] lemma tailings_disjoint_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tunnel f i (n+1)) := begin induction n with n ih, { simp only [tailings_zero], apply tailing_disjoint_tunnel_succ, }, { simp only [tailings_succ], refine disjoint.disjoint_sup_left_of_disjoint_sup_right _ _, apply tailing_disjoint_tunnel_succ, apply disjoint.mono_right _ ih, apply tailing_sup_tunnel_succ_le_tunnel, }, end lemma tailings_disjoint_tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tailing f i (n+1)) := disjoint.mono_right (tailing_le_tunnel f i _) (tailings_disjoint_tunnel f i _) end tunnel end linear_map
ddd448e758a207fe64a0c31a50e46acd494f6b2e
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/print_ax3.lean
d2032e09d12b71e5fd2ad367d6a01d45d50416e2
[ "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
231
lean
theorem foo1 : 0 = (0:num) := rfl theorem foo2 : 0 = (0:num) := rfl theorem foo3 : 0 = (0:num) := foo2 definition foo4 : 0 = (0:num) := eq.trans foo2 foo1 print axioms foo4 print "------" print axioms print "------" print foo3
484a96a53b1af7bc0a02de0642b72139a8eac304
fe84e287c662151bb313504482b218a503b972f3
/src/commutative_algebra/pow_add_split.lean
a712e8f165f86148df0f59431e30135c0e3543ef
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
1,818
lean
import algebra.ring algebra.group_power import tactic.ring variables {A : Type*} [comm_ring A] (a b : A) (n m : ℕ) namespace pow_add_split def α : ℕ → ℕ → A → A → A | 0 m a b := 0 | (n + 1) 0 a b := (a + b) ^ n | (n + 1) (m + 1) a b := (α (n + 1) m a b) + (α n (m + 1) a b) * b end pow_add_split open pow_add_split /- It looks like the induction needs to be generalised for this to work lemma pow_add_split : ∀ (p n m : ℕ) (hp : p + 1 = n + m) (a b : A), (a + b) ^ p = (α m n a b) * a ^ n + (α n m b a) * b ^ m | 0 0 0 hp a b := by {exfalso, exact nat.zero_ne_one hp.symm,} | 0 0 1 _ a b := by {rw[α,α,zero_mul,add_zero,pow_zero,pow_zero,mul_one],} | 0 1 0 _ a b := by {rw[α,α,zero_mul,zero_add,pow_zero,pow_zero,pow_zero,mul_one],} | 0 (n + 1) (m + 1) hp a b := by { rw[zero_add,add_assoc,add_comm 1,add_assoc m,← add_assoc] at hp, cases hp, } | (p + 1) 0 0 hp a b := by {cases hp} | (p + 1) 0 (m + 1) hp a b := by { rw[zero_add] at hp,let hp' := nat.succ_inj hp, rw[α,α,hp',pow_zero,mul_one,zero_mul,add_zero], } | (p + 1) (n + 1) 0 hp a b := by { rw[add_zero] at hp,let hp' := nat.succ_inj hp, rw[α,α,hp',pow_zero,mul_one,zero_mul,zero_add,add_comm], } | (p + 1) (n + 1) (m + 1) hp a b := by { rw[add_assoc,add_assoc,add_comm 1 (m + 1),add_assoc,← add_assoc n m] at hp, let hp' : p = n + m := nat.succ_inj (nat.succ_inj hp), have hn : p + 1 = n + (m + 1) := by {rw[hp',add_assoc],}, have hm : p + 1 = (n + 1) + m := by {rw[hp',add_assoc,add_assoc,add_comm 1],}, let en := congr_arg (λ x, x * b) (pow_add_split p n (m + 1) hn a b), let em := congr_arg (λ x, x * a) (pow_add_split p (n + 1) m hm a b), simp only [] at en em, rw[α,α], repeat {rw[pow_add,pow_one]}, rw[mul_add,en,em], ring, sorry } -/
b13082077176417c69e4079fa605a4406e93b6ee
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Std/Data/BinomialHeap.lean
fbe28c2fcc7bbec8bd838e79accb89cf80e3c892
[ "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
5,342
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 namespace BinomialHeapImp structure HeapNodeAux (α : Type u) (h : Type u) := (val : α) (rank : Nat) (children : List h) inductive Heap (α : Type u) : Type u := | empty : Heap α | heap (ns : List (HeapNodeAux α (Heap α))) : Heap α abbrev HeapNode (α) := HeapNodeAux α (Heap α) variables {α : Type u} instance : Inhabited (Heap α) := ⟨Heap.empty⟩ def hRank : List (HeapNode α) → Nat | [] => 0 | h::_ => h.rank def isEmpty : Heap α → Bool | Heap.empty => true | _ => false def singleton (a : α) : Heap α := Heap.heap [{ val := a, rank := 1, children := [] }] @[specialize] def combine (lt : α → α → Bool) (n₁ n₂ : HeapNode α) : HeapNode α := if lt n₂.val n₁.val then { n₂ with rank := n₂.rank + 1, children := n₂.children ++ [Heap.heap [n₁]] } else { n₁ with rank := n₁.rank + 1, children := n₁.children ++ [Heap.heap [n₂]] } @[specialize] partial def mergeNodes (lt : α → α → Bool) : List (HeapNode α) → List (HeapNode α) → List (HeapNode α) | [], h => h | h, [] => h | f@(h₁ :: t₁), s@(h₂ :: t₂) => if h₁.rank < h₂.rank then h₁ :: mergeNodes lt t₁ s else if h₂.rank < h₁.rank then h₂ :: mergeNodes lt t₂ f else let merged := combine lt h₁ h₂; let r := merged.rank; if r != hRank t₁ then if r != hRank t₂ then merged :: mergeNodes lt t₁ t₂ else mergeNodes lt (merged :: t₁) t₂ else if r != hRank t₂ then mergeNodes lt t₁ (merged :: t₂) else merged :: mergeNodes lt t₁ t₂ @[specialize] def merge (lt : α → α → Bool) : Heap α → Heap α → Heap α | Heap.empty, h => h | h, Heap.empty => h | Heap.heap h₁, Heap.heap h₂ => Heap.heap (mergeNodes lt h₁ h₂) @[specialize] def head? (lt : α → α → Bool) : Heap α → Option α | Heap.empty => none | Heap.heap h => h.foldl (init := none) fun r n => match r with | none => some n.val | some v => if lt v n.val then v else some n.val /- O(log n) -/ @[specialize] def head [Inhabited α] (lt : α → α → Bool) : Heap α → α | Heap.empty => arbitrary | Heap.heap [] => arbitrary | Heap.heap (h::hs) => hs.foldl (init := h.val) fun r n => if lt r n.val then r else n.val @[specialize] def findMin (lt : α → α → Bool) : List (HeapNode α) → Nat → HeapNode α × Nat → HeapNode α × Nat | [], _, r => r | h::hs, idx, (h', idx') => if lt h.val h'.val then findMin lt hs (idx+1) (h, idx) else findMin lt hs (idx+1) (h', idx') def tail (lt : α → α → Bool) : Heap α → Heap α | Heap.empty => Heap.empty | Heap.heap [] => Heap.empty | Heap.heap [h] => match h.children with | [] => Heap.empty | (h::hs) => hs.foldl (merge lt) h | Heap.heap hhs@(h::hs) => let (min, minIdx) := findMin lt hs 1 (h, 0); let rest := hhs.eraseIdx minIdx; min.children.foldl (merge lt) (Heap.heap rest) partial def toList (lt : α → α → Bool) : Heap α → List α | Heap.empty => [] | h => match head? lt h with | none => [] | some a => a :: toList lt (tail lt h) inductive WellFormed (lt : α → α → Bool) : Heap α → Prop := | emptyWff : WellFormed lt Heap.empty | singletonWff (a : α) : WellFormed lt (singleton a) | mergeWff (h₁ h₂ : Heap α) : WellFormed lt h₁ → WellFormed lt h₂ → WellFormed lt (merge lt h₁ h₂) | tailWff (h : Heap α) : WellFormed lt h → WellFormed lt (tail lt h) end BinomialHeapImp open BinomialHeapImp def BinomialHeap (α : Type u) (lt : α → α → Bool) := { h : Heap α // WellFormed lt h } @[inline] def mkBinomialHeap (α : Type u) (lt : α → α → Bool) : BinomialHeap α lt := ⟨Heap.empty, WellFormed.emptyWff⟩ namespace BinomialHeap variables {α : Type u} {lt : α → α → Bool} @[inline] def empty : BinomialHeap α lt := mkBinomialHeap α lt @[inline] def isEmpty : BinomialHeap α lt → Bool | ⟨b, _⟩ => BinomialHeapImp.isEmpty b /- O(1) -/ @[inline] def singleton (a : α) : BinomialHeap α lt := ⟨BinomialHeapImp.singleton a, WellFormed.singletonWff a⟩ /- O(log n) -/ @[inline] def merge : BinomialHeap α lt → BinomialHeap α lt → BinomialHeap α lt | ⟨b₁, h₁⟩, ⟨b₂, h₂⟩ => ⟨BinomialHeapImp.merge lt b₁ b₂, WellFormed.mergeWff b₁ b₂ h₁ h₂⟩ /- O(log n) -/ @[inline] def head [Inhabited α] : BinomialHeap α lt → α | ⟨b, _⟩ => BinomialHeapImp.head lt b /- O(log n) -/ @[inline] def head? : BinomialHeap α lt → Option α | ⟨b, _⟩ => BinomialHeapImp.head? lt b /- O(log n) -/ @[inline] def tail : BinomialHeap α lt → BinomialHeap α lt | ⟨b, h⟩ => ⟨BinomialHeapImp.tail lt b, WellFormed.tailWff b h⟩ /- O(log n) -/ @[inline] def insert (a : α) (h : BinomialHeap α lt) : BinomialHeap α lt := merge (singleton a) h /- O(n log n) -/ @[inline] def toList : BinomialHeap α lt → List α | ⟨b, _⟩ => BinomialHeapImp.toList lt b end BinomialHeap end Std
d728265a34b03083b3eee904d99d72ce4200a56f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/field_theory/separable.lean
974d52878f13a8fab035199e8dbd62456a64a54e
[ "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
26,620
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.polynomial.big_operators import field_theory.minpoly import field_theory.splitting_field import field_theory.tower import algebra.squarefree /-! # Separable polynomials We define a polynomial to be separable if it is coprime with its derivative. We prove basic properties about separable polynomials here. ## Main definitions * `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative. * `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`. * `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ universes u v w open_locale classical big_operators open finset namespace polynomial section comm_semiring variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S] /-- A polynomial is separable iff it is coprime with its derivative. -/ def separable (f : polynomial R) : Prop := is_coprime f f.derivative lemma separable_def (f : polynomial R) : f.separable ↔ is_coprime f f.derivative := iff.rfl lemma separable_def' (f : polynomial R) : f.separable ↔ ∃ a b : polynomial R, a * f + b * f.derivative = 1 := iff.rfl lemma separable_one : (1 : polynomial R).separable := is_coprime_one_left lemma separable_X_add_C (a : R) : (X + C a).separable := by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero], exact is_coprime_one_right } lemma separable_X : (X : polynomial R).separable := by { rw [separable_def, derivative_X], exact is_coprime_one_right } lemma separable_C (r : R) : (C r).separable ↔ is_unit r := by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C] lemma separable.of_mul_left {f g : polynomial R} (h : (f * g).separable) : f.separable := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this) end lemma separable.of_mul_right {f g : polynomial R} (h : (f * g).separable) : g.separable := by { rw mul_comm at h, exact h.of_mul_left } lemma separable.of_dvd {f g : polynomial R} (hf : f.separable) (hfg : g ∣ f) : g.separable := by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf } lemma separable_gcd_left {F : Type*} [field F] {f : polynomial F} (hf : f.separable) (g : polynomial F) : (euclidean_domain.gcd f g).separable := separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g) lemma separable_gcd_right {F : Type*} [field F] {g : polynomial F} (f : polynomial F) (hg : g.separable) : (euclidean_domain.gcd f g).separable := separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g) lemma separable.is_coprime {f g : polynomial R} (h : (f * g).separable) : is_coprime f g := begin have := h.of_mul_left_left, rw derivative_mul at this, exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this) end theorem separable.of_pow' {f : polynomial R} : ∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0 | 0 := λ h, or.inr $ or.inr rfl | 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩ | (n+2) := λ h, by { rw [pow_succ, pow_succ] at h, exact or.inl (is_coprime_self.1 h.is_coprime.of_mul_right_left) } theorem separable.of_pow {f : polynomial R} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0) (hfs : (f ^ n).separable) : f.separable ∧ n = 1 := (hfs.of_pow'.resolve_left hf).resolve_right hn theorem separable.map {p : polynomial R} (h : p.separable) {f : R →+* S} : (p.map f).separable := let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f, by rw [derivative_map, ← map_mul, ← map_mul, ← map_add, H, map_one]⟩ variables (R) (p q : ℕ) /-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/ noncomputable def expand : polynomial R →ₐ[R] polynomial R := { commutes' := λ r, eval₂_C _ _, .. (eval₂_ring_hom C (X ^ p) : polynomial R →+* polynomial R) } lemma coe_expand : (expand R p : polynomial R → polynomial R) = eval₂ C (X ^ p) := rfl variables {R} lemma expand_eq_sum {f : polynomial R} : expand R p f = f.sum (λ e a, C a * (X ^ p) ^ e) := by { dsimp [expand, eval₂], refl, } @[simp] lemma expand_C (r : R) : expand R p (C r) = C r := eval₂_C _ _ @[simp] lemma expand_X : expand R p X = X ^ p := eval₂_X _ _ @[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r := by simp_rw [monomial_eq_smul_X, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul] theorem expand_expand (f : polynomial R) : expand R p (expand R q f) = expand R (p * q) f := polynomial.induction_on f (λ r, by simp_rw expand_C) (λ f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, alg_hom.map_pow, expand_X, pow_mul]) theorem expand_mul (f : polynomial R) : expand R (p * q) f = expand R p (expand R q f) := (expand_expand p q f).symm @[simp] theorem expand_one (f : polynomial R) : expand R 1 f = f := polynomial.induction_on f (λ r, by rw expand_C) (λ f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg]) (λ n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one]) theorem expand_pow (f : polynomial R) : expand R (p ^ q) f = (expand R p ^[q] f) := nat.rec_on q (by rw [pow_zero, expand_one, function.iterate_zero, id]) $ λ n ih, by rw [function.iterate_succ_apply', pow_succ, expand_mul, ih] theorem derivative_expand (f : polynomial R) : (expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) := by rw [coe_expand, derivative_eval₂_C, derivative_pow, derivative_X, mul_one] theorem coeff_expand {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 := begin simp only [expand_eq_sum], simp_rw [coeff_sum, ← pow_mul, C_mul_X_pow_eq_monomial, coeff_monomial, sum], split_ifs with h, { rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl], { intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] }, { intro hn, rw not_mem_support_iff.1 hn, split_ifs; refl } }, { rw finset.sum_eq_zero, intros k hk, rw if_neg, exact λ hkn, h ⟨k, hkn.symm⟩, }, end @[simp] theorem coeff_expand_mul {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (n * p) = f.coeff n := by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp] @[simp] theorem coeff_expand_mul' {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) : (expand R p f).coeff (p * n) = f.coeff n := by rw [mul_comm, coeff_expand_mul hp] theorem expand_inj {p : ℕ} (hp : 0 < p) {f g : polynomial R} : expand R p f = expand R p g ↔ f = g := ⟨λ H, ext $ λ n, by rw [← coeff_expand_mul hp, H, coeff_expand_mul hp], congr_arg _⟩ theorem expand_eq_zero {p : ℕ} (hp : 0 < p) {f : polynomial R} : expand R p f = 0 ↔ f = 0 := by rw [← (expand R p).map_zero, expand_inj hp, alg_hom.map_zero] theorem expand_eq_C {p : ℕ} (hp : 0 < p) {f : polynomial R} {r : R} : expand R p f = C r ↔ f = C r := by rw [← expand_C, expand_inj hp, expand_C] theorem nat_degree_expand (p : ℕ) (f : polynomial R) : (expand R p f).nat_degree = f.nat_degree * p := begin cases p.eq_zero_or_pos with hp hp, { rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, eval₂_hom, nat_degree_C] }, by_cases hf : f = 0, { rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] }, have hf1 : expand R p f ≠ 0 := mt (expand_eq_zero hp).1 hf, rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1], refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ λ n hn, _) _, { rw coeff_expand hp, split_ifs with hpn, { rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn, rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn }, { refl } }, { refine le_degree_of_ne_zero _, rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf } end theorem map_expand {p : ℕ} (hp : 0 < p) {f : R →+* S} {q : polynomial R} : map f (expand R p q) = expand S p (map f q) := by { ext, rw [coeff_map, coeff_expand hp, coeff_expand hp], split_ifs; simp, } /-- Expansion is injective. -/ lemma expand_injective {n : ℕ} (hn : 0 < n) : function.injective (expand R n) := λ g g' h, begin ext, have h' : (expand R n g).coeff (n * n_1) = (expand R n g').coeff (n * n_1) := begin apply polynomial.ext_iff.1, exact h, end, rw [polynomial.coeff_expand hn g (n * n_1), polynomial.coeff_expand hn g' (n * n_1)] at h', simp only [if_true, dvd_mul_right] at h', rw (nat.mul_div_right n_1 hn) at h', exact h', end end comm_semiring section comm_ring variables {R : Type u} [comm_ring R] lemma separable_X_sub_C {x : R} : separable (X - C x) := by simpa only [sub_eq_add_neg, C_neg] using separable_X_add_C (-x) lemma separable.mul {f g : polynomial R} (hf : f.separable) (hg : g.separable) (h : is_coprime f g) : (f * g).separable := by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left ((h.symm.mul_right hg).mul_add_right_right _) } lemma separable_prod' {ι : Sort*} {f : ι → polynomial R} {s : finset ι} : (∀x∈s, ∀y∈s, x ≠ y → is_coprime (f x) (f y)) → (∀x∈s, (f x).separable) → (∏ x in s, f x).separable := finset.induction_on s (λ _ _, separable_one) $ λ a s has ih h1 h2, begin simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has, exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ λ i his, h1.1.2 i his $ ne.symm $ ne_of_mem_of_not_mem his has) end lemma separable_prod {ι : Sort*} [fintype ι] {f : ι → polynomial R} (h1 : pairwise (is_coprime on f)) (h2 : ∀ x, (f x).separable) : (∏ x, f x).separable := separable_prod' (λ x hx y hy hxy, h1 x y hxy) (λ x hx, h2 x) lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ι : Sort*} {f : ι → R} {s : finset ι} (hfs : (∏ i in s, (X - C (f i))).separable) {x y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y := begin by_contra hxy, rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy), prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← sq] at hfs, cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C) two_ne_zero).2 end lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ι : Sort*} [fintype ι] {f : ι → R} (hfs : (∏ i, (X - C (f i))).separable) : function.injective f := λ x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy lemma is_unit_of_self_mul_dvd_separable {p q : polynomial R} (hp : p.separable) (hq : q * q ∣ p) : is_unit q := begin obtain ⟨p, rfl⟩ := hq, apply is_coprime_self.mp, have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)), { simp only [← mul_assoc, mul_add], convert hp, rw [derivative_mul, derivative_mul], ring }, exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this) end end comm_ring section integral_domain variables (R : Type u) [integral_domain R] theorem is_local_ring_hom_expand {p : ℕ} (hp : 0 < p) : is_local_ring_hom (↑(expand R p) : polynomial R →+* polynomial R) := begin refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1, have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1), rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2, rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C] end end integral_domain section field variables {F : Type u} [field F] {K : Type v} [field K] theorem separable_iff_derivative_ne_zero {f : polynomial F} (hf : irreducible f) : f.separable ↔ f.derivative ≠ 0 := ⟨λ h1 h2, hf.not_unit $ is_coprime_zero_right.1 $ h2 ▸ h1, λ h, is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4, let ⟨u, hu⟩ := (hf.is_unit_or_is_unit hg3).resolve_left hg1 in have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd }, not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt h⟩ theorem separable_map (f : F →+* K) {p : polynomial F} : (p.map f).separable ↔ p.separable := by simp_rw [separable_def, derivative_map, is_coprime_map] section char_p /-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/ noncomputable def contract (p : ℕ) (f : polynomial F) : polynomial F := ∑ n in range (f.nat_degree + 1), monomial n (f.coeff (n * p)) variables (p : ℕ) [hp : fact p.prime] include hp theorem coeff_contract (f : polynomial F) (n : ℕ) : (contract p f).coeff n = f.coeff (n * p) := begin simp only [contract, coeff_monomial, sum_ite_eq', finset_sum_coeff, mem_range, not_lt, ite_eq_left_iff], assume hn, apply (coeff_eq_zero_of_nat_degree_lt _).symm, calc f.nat_degree < f.nat_degree + 1 : nat.lt_succ_self _ ... ≤ n * 1 : by simpa only [mul_one] using hn ... ≤ n * p : mul_le_mul_of_nonneg_left (@nat.prime.one_lt p (fact.out _)).le (zero_le n) end theorem of_irreducible_expand {f : polynomial F} (hf : irreducible (expand F p f)) : irreducible f := @@of_irreducible_map _ _ _ (is_local_ring_hom_expand F hp.1.pos) hf theorem of_irreducible_expand_pow {f : polynomial F} {n : ℕ} : irreducible (expand F (p ^ n) f) → irreducible f := nat.rec_on n (λ hf, by rwa [pow_zero, expand_one] at hf) $ λ n ih hf, ih $ of_irreducible_expand p $ by { rw pow_succ at hf, rwa [expand_expand] } variables [HF : char_p F p] include HF theorem expand_char (f : polynomial F) : map (frobenius F p) (expand F p f) = f ^ p := begin refine f.induction_on' (λ a b ha hb, _) (λ n a, _), { rw [alg_hom.map_add, map_add, ha, hb, add_pow_char], }, { rw [expand_monomial, map_monomial, monomial_eq_C_mul_X, monomial_eq_C_mul_X, mul_pow, ← C.map_pow, frobenius_def], ring_exp } end theorem map_expand_pow_char (f : polynomial F) (n : ℕ) : map ((frobenius F p) ^ n) (expand F (p ^ n) f) = f ^ (p ^ n) := begin induction n, { simp [ring_hom.one_def] }, symmetry, rw [pow_succ', pow_mul, ← n_ih, ← expand_char, pow_succ, ring_hom.mul_def, ← map_map, mul_comm, expand_mul, ← map_expand (nat.prime.pos hp.1)], end theorem expand_contract {f : polynomial F} (hf : f.derivative = 0) : expand F p (contract p f) = f := begin ext n, rw [coeff_expand hp.1.pos, coeff_contract], split_ifs with h, { rw nat.div_mul_cancel h }, { cases n, { exact absurd (dvd_zero p) h }, have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this }, rw [← nat.cast_succ, char_p.cast_eq_zero_iff F p] at this, exact absurd this h } end theorem separable_or {f : polynomial F} (hf : irreducible f) : f.separable ∨ ¬f.separable ∧ ∃ g : polynomial F, irreducible g ∧ expand F p g = f := if H : f.derivative = 0 then or.inr ⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H], contract p f, by haveI := is_local_ring_hom_expand F hp.1.pos; exact of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H at hf), expand_contract p H⟩ else or.inl $ (separable_iff_derivative_ne_zero hf).2 H theorem exists_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) : ∃ (n : ℕ) (g : polynomial F), g.separable ∧ expand F (p ^ n) g = f := begin generalize hn : f.nat_degree = N, unfreezingI { revert f }, apply nat.strong_induction_on N, intros N ih f hf hf0 hn, rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩, { refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] }, { cases N with N, { rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn, rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1, rw [h1, C_0] at hn, exact absurd hn hf0 }, have hg1 : g.nat_degree * p = N.succ, { rwa [← nat_degree_expand, hgf] }, have hg2 : g.nat_degree ≠ 0, { intro this, rw [this, zero_mul] at hg1, cases hg1 }, have hg3 : g.nat_degree < N.succ, { rw [← mul_one g.nat_degree, ← hg1], exact nat.mul_lt_mul_of_pos_left hp.1.one_lt (nat.pos_of_ne_zero hg2) }, have hg4 : g ≠ 0, { rintro rfl, exact hg2 nat_degree_zero }, rcases ih _ hg3 hg hg4 rfl with ⟨n, g, hg5, rfl⟩, refine ⟨n+1, g, hg5, _⟩, rw [← hgf, expand_expand, pow_succ] } end theorem is_unit_or_eq_zero_of_separable_expand {f : polynomial F} (n : ℕ) (hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 := begin rw or_iff_not_imp_right, intro hn, have hf2 : (expand F (p ^ n) f).derivative = 0, { by rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero, zero_pow (nat.pos_of_ne_zero hn), zero_mul, mul_zero] }, rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩, rw [eq_comm, expand_eq_C (pow_pos hp.1.pos _)] at hrf, rwa [hrf, is_unit_C] end theorem unique_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) (n₁ : ℕ) (g₁ : polynomial F) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f) (n₂ : ℕ) (g₂ : polynomial F) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) : n₁ = n₂ ∧ g₁ = g₂ := begin revert g₁ g₂, wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁] tactic.skip, unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩, rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp.1.pos n₁)] at hgf₂, subst hgf₂, subst hgf₁, rcases is_unit_or_eq_zero_of_separable_expand p k hg₁ with h | rfl, { rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩, simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 }, { rw [add_zero, pow_zero, expand_one], split; refl } }, exact λ g₁ g₂ hg₁ hgf₁ hg₂ hgf₂, let ⟨hn, hg⟩ := this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁ in ⟨hn.symm, hg.symm⟩ end end char_p lemma separable_prod_X_sub_C_iff' {ι : Sort*} {f : ι → F} {s : finset ι} : (∏ i in s, (X - C (f i))).separable ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) := ⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy, λ H, by { rw ← prod_attach, exact separable_prod' (λ x hx y hy hxy, @pairwise_coprime_X_sub _ _ { x // x ∈ s } (λ x, f x) (λ x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy) (λ _ _, separable_X_sub_C) }⟩ lemma separable_prod_X_sub_C_iff {ι : Sort*} [fintype ι] {f : ι → F} : (∏ i, (X - C (f i))).separable ↔ function.injective f := separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff] section splits open_locale big_operators variables {i : F →+* K} lemma not_unit_X_sub_C (a : F) : ¬ is_unit (X - C a) := λ h, have one_eq_zero : (1 : with_bot ℕ) = 0, by simpa using degree_eq_zero_of_is_unit h, one_ne_zero (option.some_injective _ one_eq_zero) lemma nodup_of_separable_prod {s : multiset F} (hs : separable (multiset.map (λ a, X - C a) s).prod) : s.nodup := begin rw multiset.nodup_iff_ne_cons_cons, rintros a t rfl, refine not_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _), simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _) end lemma multiplicity_le_one_of_separable {p q : polynomial F} (hq : ¬ is_unit q) (hsep : separable p) : multiplicity q p ≤ 1 := begin contrapose! hq, apply is_unit_of_self_mul_dvd_separable hsep, rw ← sq, apply multiplicity.pow_dvd_of_le_multiplicity, exact_mod_cast (enat.add_one_le_of_lt hq) end lemma separable.squarefree {p : polynomial F} (hsep : separable p) : squarefree p := begin rw multiplicity.squarefree_iff_multiplicity_le_one p, intro f, by_cases hunit : is_unit f, { exact or.inr hunit }, exact or.inl (multiplicity_le_one_of_separable hunit hsep) end /--If `n ≠ 0` in `F`, then ` X ^ n - a` is separable for any `a ≠ 0`. -/ lemma separable_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : separable (X ^ n - C a) := begin cases nat.eq_zero_or_pos n with hzero hpos, { exfalso, rw hzero at hn, exact hn (refl 0) }, apply (separable_def' (X ^ n - C a)).2, use [-C (a⁻¹), (C ((a⁻¹) * (↑n)⁻¹) * X)], have mul_pow_sub : X * X ^ (n - 1) = X ^ n, { nth_rewrite 0 [←pow_one X], rw pow_mul_pow_sub X (nat.succ_le_iff.mpr hpos) }, rw [derivative_sub, derivative_C, sub_zero, derivative_pow X n, derivative_X, mul_one], have hcalc : C (a⁻¹ * (↑n)⁻¹) * (↑n * (X ^ n)) = C a⁻¹ * (X ^ n), { calc C (a⁻¹ * (↑n)⁻¹) * (↑n * (X ^ n)) = C a⁻¹ * C ((↑n)⁻¹) * (C ↑n * (X ^ n)) : by rw [C_mul, C_eq_nat_cast] ... = C a⁻¹ * (C ((↑n)⁻¹) * C ↑n) * (X ^ n) : by ring ... = C a⁻¹ * C ((↑n)⁻¹ * ↑n) * (X ^ n) : by rw [← C_mul] ... = C a⁻¹ * C 1 * (X ^ n) : by field_simp [hn] ... = C a⁻¹ * (X ^ n) : by rw [C_1, mul_one] }, calc -C a⁻¹ * (X ^ n - C a) + C (a⁻¹ * (↑n)⁻¹) * X * (↑n * X ^ (n - 1)) = -C a⁻¹ * (X ^ n - C a) + C (a⁻¹ * (↑n)⁻¹) * (↑n * (X * X ^ (n - 1))) : by ring ... = -C a⁻¹ * (X ^ n - C a) + C a⁻¹ * (X ^ n) : by rw [mul_pow_sub, hcalc] ... = C a⁻¹ * C a : by ring ... = (1 : polynomial F) : by rw [← C_mul, inv_mul_cancel ha, C_1] end /--If `n ≠ 0` in `F`, then ` X ^ n - a` is squarefree for any `a ≠ 0`. -/ lemma squarefree_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) : squarefree (X ^ n - C a) := (separable_X_pow_sub_C a hn ha).squarefree lemma root_multiplicity_le_one_of_separable {p : polynomial F} (hp : p ≠ 0) (hsep : separable p) (x : F) : root_multiplicity x p ≤ 1 := begin rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_le_coe, enat.coe_get], exact multiplicity_le_one_of_separable (not_unit_X_sub_C _) hsep end lemma count_roots_le_one {p : polynomial F} (hsep : separable p) (x : F) : p.roots.count x ≤ 1 := begin by_cases hp : p = 0, { simp [hp] }, rw count_roots hp, exact root_multiplicity_le_one_of_separable hp hsep x end lemma nodup_roots {p : polynomial F} (hsep : separable p) : p.roots.nodup := multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep) lemma card_root_set_eq_nat_degree [algebra F K] {p : polynomial F} (hsep : p.separable) (hsplit : splits (algebra_map F K) p) : fintype.card (p.root_set K) = p.nat_degree := begin simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe], rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots hsplit], exact nodup_roots hsep.map, end lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : polynomial F} (h_ne_zero : h ≠ 0) (h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h) (h_roots : ∀ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits, apply finset.mk.inj, { change _ = {i x}, rw finset.eq_singleton_iff_unique_mem, split, { apply finset.mem_mk.mpr, rw mem_roots (show h.map i ≠ 0, by exact map_ne_zero h_ne_zero), rw [is_root.def,←eval₂_eq_eval_map,eval₂_hom,h_root], exact ring_hom.map_zero i }, { exact h_roots } }, { exact nodup_roots (separable.map h_sep) }, end end splits end field end polynomial open polynomial theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F} (hf : irreducible f) : f.separable := begin rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], rintro ⟨⟩, rw [pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff], refine λ hf1, hf.not_unit _, rw [hf1, is_unit_C, is_unit_iff_ne_zero], intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf.ne_zero end -- TODO: refactor to allow transcendental extensions? -- See: https://en.wikipedia.org/wiki/Separable_extension#Separability_of_transcendental_extensions /-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff the minimal polynomial of every `x : K` is separable. -/ class is_separable (F K : Sort*) [field F] [field K] [algebra F K] : Prop := (is_integral' (x : K) : is_integral F x) (separable' (x : K) : (minpoly F x).separable) theorem is_separable.is_integral {F K} [field F] [field K] [algebra F K] (h : is_separable F K) : ∀ x : K, is_integral F x := is_separable.is_integral' theorem is_separable.separable {F K} [field F] [field K] [algebra F K] (h : is_separable F K) : ∀ x : K, (minpoly F x).separable := is_separable.separable' theorem is_separable_iff {F K} [field F] [field K] [algebra F K] : is_separable F K ↔ ∀ x : K, is_integral F x ∧ (minpoly F x).separable := ⟨λ h x, ⟨h.is_integral x, h.separable x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩ instance is_separable_self (F : Type*) [field F] : is_separable F F := ⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact separable_X_sub_C }⟩ section is_separable_tower variables (F K E : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma is_separable_tower_top_of_is_separable [h : is_separable F E] : is_separable K E := ⟨λ x, is_integral_of_is_scalar_tower x (h.is_integral x), λ x, (h.separable x).map.of_dvd (minpoly.dvd_map_of_is_scalar_tower _ _ _)⟩ lemma is_separable_tower_bot_of_is_separable [h : is_separable F E] : is_separable F K := is_separable_iff.2 $ λ x, begin refine (is_separable_iff.1 h (algebra_map K E x)).imp is_integral_tower_bot_of_is_integral_field (λ hs, _), obtain ⟨q, hq⟩ := minpoly.dvd F x (is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero_field (minpoly.aeval F ((algebra_map K E) x))), rw hq at hs, exact hs.of_mul_left end variables {E} lemma is_separable.of_alg_hom (E' : Type*) [field E'] [algebra F E'] (f : E →ₐ[F] E') [is_separable F E'] : is_separable F E := begin letI : algebra E E' := ring_hom.to_algebra f.to_ring_hom, haveI : is_scalar_tower F E E' := is_scalar_tower.of_algebra_map_eq (λ x, (f.commutes x).symm), exact is_separable_tower_bot_of_is_separable F E E', end end is_separable_tower
cc1c96a0c9b3faf6c60847972a0cbf441d7d6ded
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/algebra/group/to_additive.lean
5b0fe7bab3c9e3b6137947677f24b60ec775a2c8
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
9,873
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov. -/ import tactic.basic import tactic.transform_decl import tactic.algebra /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from multiplicative theory to additive theory. To use this attribute, just write ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration, and provide a documentation string. The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. ## Implementation notes ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. After transporting the “main” declaration, `to_additive` transports its equational lemmas. ### Structure fields and constructors If `src` is a structure, then `to_additive` automatically adds structure fields to its mapping, and similarly for constructors of inductive types. For new structures this means that `to_additive` automatically handles coercions, and for old structures it does the same, if ancestry information is present in `@[ancestor]` attributes. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `new_namespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first two cases `to_additive` double checks that the new name differs from the original one. ### Missing features * Automatically transport structures and other inductive types. * Handle `protected` attribute. Currently all new definitions are public. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. * Mapping of prefixes that do not correspond to any definition, see `quotient_group`. * Rewrite rules for the last part of the name that work in more cases. E.g., we can replace `monoid` with `add_monoid` etc. -/ namespace to_additive open tactic exceptional @[user_attribute] meta def aux_attr : user_attribute (name_map name) name := { name := `to_additive_aux, descr := "Auxiliary attribute for `to_additive`. DON'T USE IT", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n', let n := match n' with | name.mk_string s pre := if s = "_to_additive" then pre else n' | _ := n' end in dict.insert n <$> aux_attr.get_param n') mk_name_map, []⟩, parser := lean.parser.ident } meta def map_namespace (src tgt : name) : command := do let n := src.mk_string "_to_additive", let decl := declaration.thm n [] `(unit) (pure (reflect ())), add_decl decl, aux_attr.set n tgt tt @[derive has_reflect, derive inhabited] structure value_type := (tgt : name) (doc : option string) /-- Dictionary of words used by `to_additive.guess_name` to autogenerate names. -/ meta def tokens_dict : native.rb_map string string := native.rb_map.of_list $ [("mul", "add"), ("one", "zero"), ("inv", "neg"), ("prod", "sum")] /-- Autogenerate target name for `to_additive`. -/ meta def guess_name : string → string := string.map_tokens '_' $ string.map_tokens ''' $ λ s, (tokens_dict.find s).get_or_else s meta def target_name (src tgt : name) (dict : name_map name) : tactic name := (if tgt.get_prefix ≠ name.anonymous -- `tgt` is a full name then pure tgt else match src with | (name.mk_string s pre) := do let tgt_auto := guess_name s, guard (tgt.to_string ≠ tgt_auto) <|> trace ("`to_additive " ++ src.to_string ++ "`: remove `name` argument"), pure $ name.mk_string (if tgt = name.anonymous then tgt_auto else tgt.to_string) (pre.map_prefix dict.find) | _ := fail ("to_additive: can't transport " ++ src.to_string) end) >>= (λ res, if res = src then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself") else pure res) meta def parser : lean.parser value_type := do tgt ← optional lean.parser.ident, e ← optional interactive.types.texpr, doc ← match e with | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string) | none := pure none end, return ⟨tgt.get_or_else name.anonymous, doc⟩ private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) : command := do src_fields ← f src, tgt_fields ← f tgt, guard (src_fields.length = tgt_fields.length) <|> fail ("Failed to map fields of " ++ src.to_string), (src_fields.zip tgt_fields).mmap' $ λ names, guard (names.fst = names.snd) <|> aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command := let aux := proceed_fields_aux src tgt prio in do aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >> aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> (ancestor_attr.get_param n <|> pure []))) >> aux (λ n, (env.constructors_of n).mmap $ λ cs, match cs with | (name.mk_string s pre) := (guard (pre = n) <|> fail "Bad constructor name") >> pure s | _ := fail "Bad constructor name" end) @[user_attribute] protected meta def attr : user_attribute unit value_type := { name := `to_additive, descr := "Transport multiplicative to additive", parser := parser, after_set := some $ λ src prio persistent, do guard persistent <|> fail "`to_additive` can't be used as a local attribute", env ← get_env, val ← attr.get_param src, dict ← aux_attr.get_cache, tgt ← target_name src val.tgt dict, aux_attr.set src tgt tt, let dict := dict.insert src tgt, if env.contains tgt then proceed_fields env src tgt prio else do transform_decl_with_prefix_dict dict src tgt [`reducible, `simp, `instance, `refl, `symm, `trans, `elab_as_eliminator], match val.doc with | some doc := add_doc_string tgt doc | none := skip end } end to_additive /- map operations -/ attribute [to_additive] has_mul has_one has_inv /- map structures -/ attribute [to_additive add_semigroup] semigroup attribute [to_additive add_comm_semigroup] comm_semigroup attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup attribute [to_additive add_monoid] monoid attribute [to_additive add_comm_monoid] comm_monoid attribute [to_additive add_group] group attribute [to_additive add_comm_group] comm_group /- map theorems -/ attribute [to_additive] mul_assoc attribute [to_additive add_semigroup_to_is_eq_associative] semigroup_to_is_associative attribute [to_additive] mul_comm attribute [to_additive add_comm_semigroup_to_is_eq_commutative] comm_semigroup_to_is_commutative attribute [to_additive] mul_left_comm attribute [to_additive] mul_right_comm attribute [to_additive] mul_left_cancel attribute [to_additive] mul_right_cancel attribute [to_additive] mul_left_cancel_iff attribute [to_additive] mul_right_cancel_iff attribute [to_additive] one_mul attribute [to_additive] mul_one attribute [to_additive] mul_left_inv attribute [to_additive] inv_mul_self attribute [to_additive] inv_mul_cancel_left attribute [to_additive] inv_mul_cancel_right attribute [to_additive] inv_eq_of_mul_eq_one attribute [to_additive neg_zero] one_inv attribute [to_additive] inv_inv attribute [to_additive] mul_right_inv attribute [to_additive] mul_inv_self attribute [to_additive] inv_inj attribute [to_additive] group.mul_left_cancel attribute [to_additive] group.mul_right_cancel attribute [to_additive to_left_cancel_add_semigroup] group.to_left_cancel_semigroup attribute [to_additive to_right_cancel_add_semigroup] group.to_right_cancel_semigroup attribute [to_additive] mul_inv_cancel_left attribute [to_additive] mul_inv_cancel_right attribute [to_additive neg_add_rev] mul_inv_rev attribute [to_additive] eq_inv_of_eq_inv attribute [to_additive] eq_inv_of_mul_eq_one attribute [to_additive] eq_mul_inv_of_mul_eq attribute [to_additive] eq_inv_mul_of_mul_eq attribute [to_additive] inv_mul_eq_of_eq_mul attribute [to_additive] mul_inv_eq_of_eq_mul attribute [to_additive] eq_mul_of_mul_inv_eq attribute [to_additive] eq_mul_of_inv_mul_eq attribute [to_additive] mul_eq_of_eq_inv_mul attribute [to_additive] mul_eq_of_eq_mul_inv attribute [to_additive neg_add] mul_inv
fd9198a8c001efc7927ecca0a3890cc6d9c1d6fe
c062f1c97fdef9ac746f08754e7d766fd6789aa9
/data/bool.lean
a93ff7ce9cfb6a36c6443f408157adcfd00b6322
[]
no_license
emberian/library_dev
00c7a985b21bdebe912f4127a363f2874e1e7555
f3abd7db0238edc18a397540e361a1da2f51503c
refs/heads/master
1,624,153,474,804
1,490,147,180,000
1,490,147,180,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,447
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad -/ -- TODO(Jeremy): these used to be proved by rec_simp. Write a special tactic for these, or -- get auto or super to do them. namespace bool -- TODO(Jeremy): is this right? @[simp] theorem coe_tt : (↑tt : Prop) := dec_trivial theorem band_tt (a : bool) : a && tt = a := begin cases a, repeat { reflexivity } end theorem tt_band (a : bool) : tt && a = a := begin cases a, repeat { reflexivity } end theorem band_ff (a : bool) : a && ff = ff := begin cases a, repeat { reflexivity } end theorem ff_band (a : bool) : ff && a = ff := begin cases a, repeat { reflexivity } end theorem bor_tt (a : bool) : a || tt = tt := begin cases a, repeat { reflexivity } end theorem tt_bor (a : bool) : tt || a = tt := begin cases a, repeat { reflexivity } end theorem bor_ff (a : bool) : a || ff = a := begin cases a, repeat { reflexivity } end theorem ff_bor (a : bool) : ff || a = a := begin cases a, repeat { reflexivity } end attribute [simp] band_tt tt_band band_ff ff_band bor_tt tt_bor bor_ff ff_bor theorem band_eq_tt (a b : bool) : (a && b = tt) = (a = tt ∧ b = tt) := begin cases a, repeat { cases b, repeat { simp } } end theorem band_eq_ff (a b : bool) : (a && b = ff) = (a = ff ∨ b = ff) := begin cases a, repeat { cases b, repeat { simp } } end theorem bor_eq_tt (a b : bool) : (a || b = tt) = (a = tt ∨ b = tt) := begin cases a, repeat { cases b, repeat { simp } } end theorem bor_eq_ff (a b : bool) : (a || b = ff) = (a = ff ∧ b = ff) := begin cases a, repeat { cases b, repeat { simp } } end theorem dichotomy (b : bool) : b = ff ∨ b = tt := begin cases b, simp, simp end @[simp] theorem cond_ff {A : Type} (t e : A) : cond ff t e = e := rfl @[simp] 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 := begin intro a, cases a, simp, simp end theorem eq_ff_of_ne_tt : ∀ {a : bool}, a ≠ tt → a = ff := begin intro a, cases a, simp, simp end theorem absurd_of_eq_ff_of_eq_tt {B : Prop} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B := begin cases a, repeat { contradiction } end @[simp] theorem bor_comm (a b : bool) : a || b = b || a := begin cases a, repeat { cases b, repeat { simp } } end @[simp] theorem bor_assoc (a b c : bool) : (a || b) || c = a || (b || c) := begin cases a, repeat { cases b, repeat { simp } } end @[simp] theorem bor_left_comm (a b c : bool) : a || (b || c) = b || (a || c) := begin cases a, repeat { cases b, repeat { simp } } end theorem or_of_bor_eq {a b : bool} : a || b = tt → a = tt ∨ b = tt := begin cases a, simp, intro h, simp [h], simp end theorem bor_inl {a b : bool} (H : a = tt) : a || b = tt := by simp [H] theorem bor_inr {a b : bool} (H : b = tt) : a || b = tt := by simp [H] @[simp] theorem band_self (a : bool) : a && a = a := begin cases a, repeat { simp } end @[simp] theorem band_comm (a b : bool) : a && b = b && a := begin cases a, repeat { simp } end @[simp] theorem band_assoc (a b c : bool) : (a && b) && c = a && (b && c) := begin cases a, repeat { simp } end @[simp] theorem band_left_comm (a b c : bool) : a && (b && c) = b && (a && c) := begin cases a, repeat { simp } end theorem band_elim_left {a b : bool} (H : a && b = tt) : a = tt := begin cases a, simp at H, simp [H] end theorem band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt := begin cases a, repeat { simp [H₁, H₂] }, simp [H₂] end theorem band_elim_right {a b : bool} (H : a && b = tt) : b = tt := begin cases a, contradiction, simp at H, exact H end @[simp] theorem bnot_false : bnot ff = tt := rfl @[simp] theorem bnot_true : bnot tt = ff := rfl @[simp] theorem bnot_bnot (a : bool) : bnot (bnot a) = a := by cases a; simp; simp theorem eq_tt_of_bnot_eq_ff {a : bool} : bnot a = ff → a = tt := by cases a; simp; simp theorem eq_ff_of_bnot_eq_tt {a : bool} : bnot a = tt → a = ff := by cases a; simp; simp definition bxor : bool → bool → bool | ff ff := ff | ff tt := tt | tt ff := tt | tt tt := ff @[simp] lemma ff_bxor_ff : bxor ff ff = ff := rfl @[simp] lemma ff_bxor_tt : bxor ff tt = tt := rfl @[simp] lemma tt_bxor_ff : bxor tt ff = tt := rfl @[simp] lemma tt_bxor_tt : bxor tt tt = ff := rfl @[simp] lemma bxor_self (a : bool) : bxor a a = ff := begin cases a, repeat { simp } end @[simp] lemma bxor_ff (a : bool) : bxor a ff = a := begin cases a, repeat { simp } end @[simp] lemma bxor_tt (a : bool) : bxor a tt = bnot a := begin cases a, repeat { simp } end @[simp] lemma ff_bxor (a : bool) : bxor ff a = a := begin cases a, repeat { simp } end @[simp] lemma tt_bxor (a : bool) : bxor tt a = bnot a := begin cases a, repeat { simp } end @[simp] lemma bxor_comm (a b : bool) : bxor a b = bxor b a := begin cases a, repeat { simp } end @[simp] lemma bxor_assoc (a b c : bool) : bxor (bxor a b) c = bxor a (bxor b c) := begin cases a, repeat { cases b, repeat { simp } } end @[simp] lemma bxor_left_comm (a b c : bool) : bxor a (bxor b c) = bxor b (bxor a c) := begin cases a, repeat { cases b, repeat { simp } } end end bool
83f0199b4f1a4dff0bfa53848dccc94b55286285
137c667471a40116a7afd7261f030b30180468c2
/src/set_theory/cofinality.lean
b863aba1d8a4bde1b56de69cacdc14616b258687
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,515
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import set_theory.cardinal_ordinal /-! # Cofinality This file contains the definition of cofinality of a ordinal number and regular cardinals ## Main Definitions * `ordinal.cof o` is the cofinality of the ordinal `o`. If `o` is the order type of the relation `<` on `α`, then `o.cof` is the smallest cardinality of a subset `s` of α that is *cofinal* in `α`, i.e. `∀ x : α, ∃ y ∈ s, ¬ y < x`. * `cardinal.is_limit c` means that `c` is a (weak) limit cardinal: `c ≠ 0 ∧ ∀ x < c, succ x < c`. * `cardinal.is_strong_limit c` means that `c` is a strong limit cardinal: `c ≠ 0 ∧ ∀ x < c, 2 ^ x < c`. * `cardinal.is_regular c` means that `c` is a regular cardinal: `omega ≤ c ∧ c.ord.cof = c`. * `cardinal.is_inaccessible c` means that `c` is strongly inaccessible: `omega < c ∧ is_regular c ∧ is_strong_limit c`. ## Main Statements * `ordinal.infinite_pigeonhole_card`: the infinite pigeonhole principle * `cardinal.lt_power_cof`: A consequence of König's theorem stating that `c < c ^ c.ord.cof` for `c ≥ cardinal.omega` * `cardinal.univ_inaccessible`: The type of ordinals in `Type u` form an inaccessible cardinal (in `Type v` with `v > u`). This shows (externally) that in `Type u` there are at least `u` inaccessible cardinals. ## Implementation Notes * The cofinality is defined for ordinals. If `c` is a cardinal number, its cofinality is `c.ord.cof`. ## Tags cofinality, regular cardinals, limits cardinals, inaccessible cardinals, infinite pigeonhole principle -/ noncomputable theory open function cardinal set open_locale classical universes u v w variables {α : Type*} {r : α → α → Prop} namespace order /-- Cofinality of a reflexive order `≼`. This is the smallest cardinality of a subset `S : set α` such that `∀ a, ∃ b ∈ S, a ≼ b`. -/ def cof (r : α → α → Prop) [is_refl α r] : cardinal := @cardinal.min {S : set α // ∀ a, ∃ b ∈ S, r a b} ⟨⟨set.univ, λ a, ⟨a, ⟨⟩, refl _⟩⟩⟩ (λ S, mk S) lemma cof_le (r : α → α → Prop) [is_refl α r] {S : set α} (h : ∀a, ∃(b ∈ S), r a b) : order.cof r ≤ mk S := le_trans (cardinal.min_le _ ⟨S, h⟩) (le_refl _) lemma le_cof {r : α → α → Prop} [is_refl α r] (c : cardinal) : c ≤ order.cof r ↔ ∀ {S : set α} (h : ∀a, ∃(b ∈ S), r a b) , c ≤ mk S := by { rw [order.cof, cardinal.le_min], exact ⟨λ H S h, H ⟨S, h⟩, λ H ⟨S, h⟩, H h ⟩ } end order theorem rel_iso.cof.aux {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃r s) : cardinal.lift.{u (max u v)} (order.cof r) ≤ cardinal.lift.{v (max u v)} (order.cof s) := begin rw [order.cof, order.cof, lift_min, lift_min, cardinal.le_min], intro S, cases S with S H, simp [(∘)], refine le_trans (min_le _ _) _, { exact ⟨f ⁻¹' S, λ a, let ⟨b, bS, h⟩ := H (f a) in ⟨f.symm b, by simp [bS, ← f.map_rel_iff, h, -coe_fn_coe_base, -coe_fn_coe_trans, principal_seg.coe_coe_fn', initial_seg.coe_coe_fn]⟩⟩ }, { exact lift_mk_le.{u v (max u v)}.2 ⟨⟨λ ⟨x, h⟩, ⟨f x, h⟩, λ ⟨x, h₁⟩ ⟨y, h₂⟩ h₃, by congr; injection h₃ with h'; exact f.to_equiv.injective h'⟩⟩ } end theorem rel_iso.cof {α : Type u} {β : Type v} {r s} [is_refl α r] [is_refl β s] (f : r ≃r s) : cardinal.lift.{u (max u v)} (order.cof r) = cardinal.lift.{v (max u v)} (order.cof s) := le_antisymm (rel_iso.cof.aux f) (rel_iso.cof.aux f.symm) def strict_order.cof (r : α → α → Prop) [h : is_irrefl α r] : cardinal := @order.cof α (λ x y, ¬ r y x) ⟨h.1⟩ namespace ordinal /-- Cofinality of an ordinal. This is the smallest cardinal of a subset `S` of the ordinal which is unbounded, in the sense `∀ a, ∃ b ∈ S, ¬(b > a)`. It is defined for all ordinals, but `cof 0 = 0` and `cof (succ o) = 1`, so it is only really interesting on limit ordinals (when it is an infinite cardinal). -/ def cof (o : ordinal.{u}) : cardinal.{u} := quot.lift_on o (λ ⟨α, r, _⟩, by exactI strict_order.cof r) begin rintros ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨⟨f, hf⟩⟩, rw ← cardinal.lift_inj, apply rel_iso.cof ⟨f, _⟩, simp [hf] end lemma cof_type (r : α → α → Prop) [is_well_order α r] : (type r).cof = strict_order.cof r := rfl theorem le_cof_type [is_well_order α r] {c} : c ≤ cof (type r) ↔ ∀ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) → c ≤ mk S := by dsimp [cof, strict_order.cof, order.cof, type, quotient.mk, quot.lift_on]; rw [cardinal.le_min, subtype.forall]; refl theorem cof_type_le [is_well_order α r] (S : set α) (h : ∀ a, ∃ b ∈ S, ¬ r b a) : cof (type r) ≤ mk S := le_cof_type.1 (le_refl _) S h theorem lt_cof_type [is_well_order α r] (S : set α) (hl : mk S < cof (type r)) : ∃ a, ∀ b ∈ S, r b a := not_forall_not.1 $ λ h, not_le_of_lt hl $ cof_type_le S (λ a, not_ball.1 (h a)) theorem cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ mk S = cof (type r) := begin have : ∃ i, cof (type r) = _, { dsimp [cof, order.cof, type, quotient.mk, quot.lift_on], apply cardinal.min_eq }, exact let ⟨⟨S, hl⟩, e⟩ := this in ⟨S, hl, e.symm⟩, end theorem ord_cof_eq (r : α → α → Prop) [is_well_order α r] : ∃ S : set α, (∀ a, ∃ b ∈ S, ¬ r b a) ∧ type (subrel r S) = (cof (type r)).ord := let ⟨S, hS, e⟩ := cof_eq r, ⟨s, _, e'⟩ := cardinal.ord_eq S, T : set α := {a | ∃ aS : a ∈ S, ∀ b : S, s b ⟨_, aS⟩ → r b a} in begin resetI, suffices, { refine ⟨T, this, le_antisymm _ (cardinal.ord_le.2 $ cof_type_le T this)⟩, rw [← e, e'], refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, ⟨a, let ⟨aS, _⟩ := a.2 in aS⟩) (λ a b h, _)⟩, rcases a with ⟨a, aS, ha⟩, rcases b with ⟨b, bS, hb⟩, change s ⟨a, _⟩ ⟨b, _⟩, refine ((trichotomous_of s _ _).resolve_left (λ hn, _)).resolve_left _, { exact asymm h (ha _ hn) }, { intro e, injection e with e, subst b, exact irrefl _ h } }, { intro a, have : {b : S | ¬ r b a}.nonempty := let ⟨b, bS, ba⟩ := hS a in ⟨⟨b, bS⟩, ba⟩, let b := (is_well_order.wf).min _ this, have ba : ¬r b a := (is_well_order.wf).min_mem _ this, refine ⟨b, ⟨b.2, λ c, not_imp_not.1 $ λ h, _⟩, ba⟩, rw [show ∀b:S, (⟨b, b.2⟩:S) = b, by intro b; cases b; refl], exact (is_well_order.wf).not_lt_min _ this (is_order_connected.neg_trans h ba) } end theorem lift_cof (o) : (cof o).lift = cof o.lift := induction_on o $ begin introsI α r _, cases lift_type r with _ e, rw e, apply le_antisymm, { unfreezingI { refine le_cof_type.2 (λ S H, _) }, have : (mk (ulift.up ⁻¹' S)).lift ≤ mk S := ⟨⟨λ ⟨⟨x, h⟩⟩, ⟨⟨x⟩, h⟩, λ ⟨⟨x, h₁⟩⟩ ⟨⟨y, h₂⟩⟩ e, by simp at e; congr; injection e⟩⟩, refine le_trans (cardinal.lift_le.2 $ cof_type_le _ _) this, exact λ a, let ⟨⟨b⟩, bs, br⟩ := H ⟨a⟩ in ⟨b, bs, br⟩ }, { rcases cof_eq r with ⟨S, H, e'⟩, have : mk (ulift.down ⁻¹' S) ≤ (mk S).lift := ⟨⟨λ ⟨⟨x⟩, h⟩, ⟨⟨x, h⟩⟩, λ ⟨⟨x⟩, h₁⟩ ⟨⟨y⟩, h₂⟩ e, by simp at e; congr; injections⟩⟩, rw e' at this, unfreezingI { refine le_trans (cof_type_le _ _) this }, exact λ ⟨a⟩, let ⟨b, bs, br⟩ := H a in ⟨⟨b⟩, bs, br⟩ } end theorem cof_le_card (o) : cof o ≤ card o := induction_on o $ λ α r _, begin resetI, have : mk (@set.univ α) = card (type r) := quotient.sound ⟨equiv.set.univ _⟩, rw ← this, exact cof_type_le set.univ (λ a, ⟨a, ⟨⟩, irrefl a⟩) end theorem cof_ord_le (c : cardinal) : cof c.ord ≤ c := by simpa using cof_le_card c.ord @[simp] theorem cof_zero : cof 0 = 0 := le_antisymm (by simpa using cof_le_card 0) (cardinal.zero_le _) @[simp] theorem cof_eq_zero {o} : cof o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ z, by exactI let ⟨S, hl, e⟩ := cof_eq r in type_eq_zero_iff_empty.2 $ λ ⟨a⟩, let ⟨b, h, _⟩ := hl a in ne_zero_iff_nonempty.2 (by exact ⟨⟨_, h⟩⟩) (e.trans z), λ e, by simp [e]⟩ @[simp] theorem cof_succ (o) : cof (succ o) = 1 := begin apply le_antisymm, { refine induction_on o (λ α r _, _), change cof (type _) ≤ _, rw [← (_ : mk _ = 1)], apply cof_type_le, { refine λ a, ⟨sum.inr punit.star, set.mem_singleton _, _⟩, rcases a with a|⟨⟨⟨⟩⟩⟩; simp [empty_relation] }, { rw [cardinal.fintype_card, set.card_singleton], simp } }, { rw [← cardinal.succ_zero, cardinal.succ_le], simpa [lt_iff_le_and_ne, cardinal.zero_le] using λ h, succ_ne_zero o (cof_eq_zero.1 (eq.symm h)) } end @[simp] theorem cof_eq_one_iff_is_succ {o} : cof.{u} o = 1 ↔ ∃ a, o = succ a := ⟨induction_on o $ λ α r _ z, begin resetI, rcases cof_eq r with ⟨S, hl, e⟩, rw z at e, cases ne_zero_iff_nonempty.1 (by rw e; exact one_ne_zero) with a, refine ⟨typein r a, eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.of_monotone _ (λ x y, _)) (λ x, _)⟩⟩, { apply sum.rec; [exact subtype.val, exact λ _, a] }, { rcases x with x|⟨⟨⟨⟩⟩⟩; rcases y with y|⟨⟨⟨⟩⟩⟩; simp [subrel, order.preimage, empty_relation], exact x.2 }, { suffices : r x a ∨ ∃ (b : punit), ↑a = x, {simpa}, rcases trichotomous_of r x a with h|h|h, { exact or.inl h }, { exact or.inr ⟨punit.star, h.symm⟩ }, { rcases hl x with ⟨a', aS, hn⟩, rw (_ : ↑a = a') at h, {exact absurd h hn}, refine congr_arg subtype.val (_ : a = ⟨a', aS⟩), haveI := le_one_iff_subsingleton.1 (le_of_eq e), apply subsingleton.elim } } end, λ ⟨a, e⟩, by simp [e]⟩ @[simp] theorem cof_add (a b : ordinal) : b ≠ 0 → cof (a + b) = cof b := induction_on a $ λ α r _, induction_on b $ λ β s _ b0, begin resetI, change cof (type _) = _, refine eq_of_forall_le_iff (λ c, _), rw [le_cof_type, le_cof_type], split; intros H S hS, { refine le_trans (H {a | sum.rec_on a (∅:set α) S} (λ a, _)) ⟨⟨_, _⟩⟩, { cases a with a b, { cases type_ne_zero_iff_nonempty.1 b0 with b, rcases hS b with ⟨b', bs, _⟩, exact ⟨sum.inr b', bs, by simp⟩ }, { rcases hS b with ⟨b', bs, h⟩, exact ⟨sum.inr b', bs, by simp [h]⟩ } }, { exact λ a, match a with ⟨sum.inr b, h⟩ := ⟨b, h⟩ end }, { exact λ a b, match a, b with ⟨sum.inr a, h₁⟩, ⟨sum.inr b, h₂⟩, h := by congr; injection h end } }, { refine le_trans (H (sum.inr ⁻¹' S) (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS (sum.inr a) with ⟨a'|b', bs, h⟩; simp at h, { cases h }, { exact ⟨b', bs, h⟩ } }, { exact λ ⟨a, h⟩, ⟨_, h⟩ }, { exact λ ⟨a, h₁⟩ ⟨b, h₂⟩ h, by injection h with h; congr; injection h } } end @[simp] theorem cof_cof (o : ordinal) : cof (cof o).ord= cof o := le_antisymm (le_trans (cof_le_card _) (by simp)) $ induction_on o $ λ α r _, by exactI let ⟨S, hS, e₁⟩ := ord_cof_eq r, ⟨T, hT, e₂⟩ := cof_eq (subrel r S) in begin rw e₁ at e₂, rw ← e₂, refine le_trans (cof_type_le {a | ∃ h, (subtype.mk a h : S) ∈ T} (λ a, _)) ⟨⟨_, _⟩⟩, { rcases hS a with ⟨b, bS, br⟩, rcases hT ⟨b, bS⟩ with ⟨⟨c, cS⟩, cT, cs⟩, exact ⟨c, ⟨cS, cT⟩, is_order_connected.neg_trans cs br⟩ }, { exact λ ⟨a, h⟩, ⟨⟨a, h.fst⟩, h.snd⟩ }, { exact λ ⟨a, ha⟩ ⟨b, hb⟩ h, by injection h with h; congr; injection h }, end theorem omega_le_cof {o} : cardinal.omega ≤ cof o ↔ is_limit o := begin rcases zero_or_succ_or_limit o with rfl|⟨o,rfl⟩|l, { simp [not_zero_is_limit, cardinal.omega_ne_zero] }, { simp [not_succ_is_limit, cardinal.one_lt_omega] }, { simp [l], refine le_of_not_lt (λ h, _), cases cardinal.lt_omega.1 h with n e, have := cof_cof o, rw [e, ord_nat] at this, cases n, { simp at e, simpa [e, not_zero_is_limit] using l }, { rw [← nat_cast_succ, cof_succ] at this, rw [← this, cof_eq_one_iff_is_succ] at e, rcases e with ⟨a, rfl⟩, exact not_succ_is_limit _ l } } end @[simp] theorem cof_omega : cof omega = cardinal.omega := le_antisymm (by rw ← card_omega; apply cof_le_card) (omega_le_cof.2 omega_is_limit) theorem cof_eq' (r : α → α → Prop) [is_well_order α r] (h : is_limit (type r)) : ∃ S : set α, (∀ a, ∃ b ∈ S, r a b) ∧ mk S = cof (type r) := let ⟨S, H, e⟩ := cof_eq r in ⟨S, λ a, let a' := enum r _ (h.2 _ (typein_lt_type r a)) in let ⟨b, h, ab⟩ := H a' in ⟨b, h, (is_order_connected.conn a b a' $ (typein_lt_typein r).1 (by rw typein_enum; apply ordinal.lt_succ_self)).resolve_right ab⟩, e⟩ theorem cof_sup_le_lift {ι} (f : ι → ordinal) (H : ∀ i, f i < sup f) : cof (sup f) ≤ (mk ι).lift := begin generalize e : sup f = o, refine ordinal.induction_on o _ e, introsI α r _ e', rw e' at H, refine le_trans (cof_type_le (set.range (λ i, enum r _ (H i))) _) ⟨embedding.of_surjective _ _⟩, { intro a, by_contra h, apply not_le_of_lt (typein_lt_type r a), rw [← e', sup_le], intro i, have h : ∀ (x : ι), r (enum r (f x) _) a, { simpa using h }, simpa only [typein_enum] using le_of_lt ((typein_lt_typein r).2 (h i)) }, { exact λ i, ⟨_, set.mem_range_self i.1⟩ }, { intro a, rcases a with ⟨_, i, rfl⟩, exact ⟨⟨i⟩, by simp⟩ } end theorem cof_sup_le {ι} (f : ι → ordinal) (H : ∀ i, f i < sup.{u u} f) : cof (sup.{u u} f) ≤ mk ι := by simpa using cof_sup_le_lift.{u u} f H theorem cof_bsup_le_lift {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup o f) → cof (bsup o f) ≤ o.card.lift := induction_on o $ λ α r _ f H, by rw bsup_type; refine cof_sup_le_lift _ _; rw ← bsup_type; intro a; apply H theorem cof_bsup_le {o : ordinal} : ∀ (f : Π a < o, ordinal), (∀ i h, f i h < bsup.{u u} o f) → cof (bsup.{u u} o f) ≤ o.card := induction_on o $ λ α r _ f H, by simpa using cof_bsup_le_lift.{u u} f H @[simp] theorem cof_univ : cof univ.{u v} = cardinal.univ := le_antisymm (cof_le_card _) begin refine le_of_forall_lt (λ c h, _), rcases lt_univ'.1 h with ⟨c, rfl⟩, rcases @cof_eq ordinal.{u} (<) _ with ⟨S, H, Se⟩, rw [univ, ← lift_cof, ← cardinal.lift_lift, cardinal.lift_lt, ← Se], refine lt_of_not_ge (λ h, _), cases cardinal.lift_down h with a e, refine quotient.induction_on a (λ α e, _) e, cases quotient.exact e with f, have f := equiv.ulift.symm.trans f, let g := λ a, (f a).1, let o := succ (sup.{u u} g), rcases H o with ⟨b, h, l⟩, refine l (lt_succ.2 _), rw ← show g (f.symm ⟨b, h⟩) = b, by dsimp [g]; simp, apply le_sup end theorem sup_lt_ord {ι} (f : ι → ordinal) {c : ordinal} (H1 : cardinal.mk ι < c.cof) (H2 : ∀ i, f i < c) : sup.{u u} f < c := begin apply lt_of_le_of_ne, { rw [sup_le], exact λ i, le_of_lt (H2 i) }, rintro h, apply not_le_of_lt H1, simpa [sup_ord, H2, h] using cof_sup_le.{u} f end theorem sup_lt {ι} (f : ι → cardinal) {c : cardinal} (H1 : cardinal.mk ι < c.ord.cof) (H2 : ∀ i, f i < c) : cardinal.sup.{u u} f < c := by { rw [←ord_lt_ord, ←sup_ord], apply sup_lt_ord _ H1, intro i, rw ord_lt_ord, apply H2 } /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_sUnion (r : α → α → Prop) [wo : is_well_order α r] {s : set (set α)} (h₁ : unbounded r $ ⋃₀ s) (h₂ : mk s < strict_order.cof r) : ∃(x ∈ s), unbounded r x := begin by_contra h, simp only [not_exists, exists_prop, not_and, not_unbounded_iff] at h, apply not_le_of_lt h₂, let f : s → α := λ x : s, wo.wf.sup x (h x.1 x.2), let t : set α := range f, have : mk t ≤ mk s, exact mk_range_le, refine le_trans _ this, have : unbounded r t, { intro x, rcases h₁ x with ⟨y, ⟨c, hc, hy⟩, hxy⟩, refine ⟨f ⟨c, hc⟩, mem_range_self _, _⟩, intro hxz, apply hxy, refine trans (wo.wf.lt_sup _ hy) hxz }, exact cardinal.min_le _ (subtype.mk t this) end /-- If the union of s is unbounded and s is smaller than the cofinality, then s has an unbounded member -/ theorem unbounded_of_unbounded_Union {α β : Type u} (r : α → α → Prop) [wo : is_well_order α r] (s : β → set α) (h₁ : unbounded r $ ⋃x, s x) (h₂ : mk β < strict_order.cof r) : ∃x : β, unbounded r (s x) := begin rw [← sUnion_range] at h₁, have : mk ↥(range (λ (i : β), s i)) < strict_order.cof r := lt_of_le_of_lt mk_range_le h₂, rcases unbounded_of_unbounded_sUnion r h₁ this with ⟨_, ⟨x, rfl⟩, u⟩, exact ⟨x, u⟩ end /-- The infinite pigeonhole principle -/ theorem infinite_pigeonhole {β α : Type u} (f : β → α) (h₁ : cardinal.omega ≤ mk β) (h₂ : mk α < (mk β).ord.cof) : ∃a : α, mk (f ⁻¹' {a}) = mk β := begin have : ¬∀a, mk (f ⁻¹' {a}) < mk β, { intro h, apply not_lt_of_ge (ge_of_eq $ mk_univ), rw [←@preimage_univ _ _ f, ←Union_of_singleton, preimage_Union], apply lt_of_le_of_lt mk_Union_le_sum_mk, apply lt_of_le_of_lt (sum_le_sup _), apply mul_lt_of_lt h₁ (lt_of_lt_of_le h₂ $ cof_ord_le _), exact sup_lt _ h₂ h }, rw [not_forall] at this, cases this with x h, use x, apply le_antisymm _ (le_of_not_gt h), rw [le_mk_iff_exists_set], exact ⟨_, rfl⟩ end /-- pigeonhole principle for a cardinality below the cardinality of the domain -/ theorem infinite_pigeonhole_card {β α : Type u} (f : β → α) (θ : cardinal) (hθ : θ ≤ mk β) (h₁ : cardinal.omega ≤ θ) (h₂ : mk α < θ.ord.cof) : ∃a : α, θ ≤ mk (f ⁻¹' {a}) := begin rcases le_mk_iff_exists_set.1 hθ with ⟨s, rfl⟩, cases infinite_pigeonhole (f ∘ subtype.val : s → α) h₁ h₂ with a ha, use a, rw [←ha, @preimage_comp _ _ _ subtype.val f], apply mk_preimage_of_injective _ _ subtype.val_injective end theorem infinite_pigeonhole_set {β α : Type u} {s : set β} (f : s → α) (θ : cardinal) (hθ : θ ≤ mk s) (h₁ : cardinal.omega ≤ θ) (h₂ : mk α < θ.ord.cof) : ∃(a : α) (t : set β) (h : t ⊆ s), θ ≤ mk t ∧ ∀{{x}} (hx : x ∈ t), f ⟨x, h hx⟩ = a := begin cases infinite_pigeonhole_card f θ hθ h₁ h₂ with a ha, refine ⟨a, {x | ∃(h : x ∈ s), f ⟨x, h⟩ = a}, _, _, _⟩, { rintro x ⟨hx, hx'⟩, exact hx }, { refine le_trans ha _, apply ge_of_eq, apply quotient.sound, constructor, refine equiv.trans _ (equiv.subtype_subtype_equiv_subtype_exists _ _).symm, simp only [set_coe_eq_subtype, mem_singleton_iff, mem_preimage, mem_set_of_eq] }, rintro x ⟨hx, hx'⟩, exact hx' end end ordinal namespace cardinal open ordinal local infixr ^ := @pow cardinal.{u} cardinal cardinal.has_pow /-- A cardinal is a limit if it is not zero or a successor cardinal. Note that `ω` is a limit cardinal by this definition. -/ def is_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, succ x < c /-- A cardinal is a strong limit if it is not zero and it is closed under powersets. Note that `ω` is a strong limit by this definition. -/ def is_strong_limit (c : cardinal) : Prop := c ≠ 0 ∧ ∀ x < c, 2 ^ x < c theorem is_strong_limit.is_limit {c} (H : is_strong_limit c) : is_limit c := ⟨H.1, λ x h, lt_of_le_of_lt (succ_le.2 $ cantor _) (H.2 _ h)⟩ /-- A cardinal is regular if it is infinite and it equals its own cofinality. -/ def is_regular (c : cardinal) : Prop := omega ≤ c ∧ c.ord.cof = c theorem cof_is_regular {o : ordinal} (h : o.is_limit) : is_regular o.cof := ⟨omega_le_cof.2 h, cof_cof _⟩ theorem omega_is_regular : is_regular omega := ⟨le_refl _, by simp⟩ theorem succ_is_regular {c : cardinal.{u}} (h : omega ≤ c) : is_regular (succ c) := ⟨le_trans h (le_of_lt $ lt_succ_self _), begin refine le_antisymm (cof_ord_le _) (succ_le.2 _), cases quotient.exists_rep (succ c) with α αe, simp at αe, rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit (le_trans h $ le_of_lt $ lt_succ_self _), rw [← αe, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, rw [← Se], apply lt_imp_lt_of_le_imp_le (λ (h : mk S ≤ c), mul_le_mul_right' h c), rw [mul_eq_self h, ← succ_le, ← αe, ← sum_const], refine le_trans _ (sum_le_sum (λ x:S, card (typein r x)) _ _), { simp [typein, sum_mk (λ x:S, {a//r a x})], refine ⟨embedding.of_surjective _ _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { intro i, rw [← lt_succ, ← lt_ord, ← αe, re], apply typein_lt_type } end⟩ theorem sup_lt_ord_of_is_regular {ι} (f : ι → ordinal) {c} (hc : is_regular c) (H1 : cardinal.mk ι < c) (H2 : ∀ i, f i < c.ord) : ordinal.sup.{u u} f < c.ord := by { apply sup_lt_ord _ _ H2, rw [hc.2], exact H1 } theorem sup_lt_of_is_regular {ι} (f : ι → cardinal) {c} (hc : is_regular c) (H1 : cardinal.mk ι < c) (H2 : ∀ i, f i < c) : sup.{u u} f < c := by { apply sup_lt _ _ H2, rwa [hc.2] } theorem sum_lt_of_is_regular {ι} (f : ι → cardinal) {c} (hc : is_regular c) (H1 : cardinal.mk ι < c) (H2 : ∀ i, f i < c) : sum.{u u} f < c := lt_of_le_of_lt (sum_le_sup _) $ mul_lt_of_lt hc.1 H1 $ sup_lt_of_is_regular f hc H1 H2 /-- A cardinal is inaccessible if it is an uncountable regular strong limit cardinal. -/ def is_inaccessible (c : cardinal) := omega < c ∧ is_regular c ∧ is_strong_limit c theorem is_inaccessible.mk {c} (h₁ : omega < c) (h₂ : c ≤ c.ord.cof) (h₃ : ∀ x < c, 2 ^ x < c) : is_inaccessible c := ⟨h₁, ⟨le_of_lt h₁, le_antisymm (cof_ord_le _) h₂⟩, ne_of_gt (lt_trans omega_pos h₁), h₃⟩ /- Lean's foundations prove the existence of ω many inaccessible cardinals -/ theorem univ_inaccessible : is_inaccessible (univ.{u v}) := is_inaccessible.mk (by simpa using lift_lt_univ' omega) (by simp) (λ c h, begin rcases lt_univ'.1 h with ⟨c, rfl⟩, rw ← lift_two_power.{u (max (u+1) v)}, apply lift_lt_univ' end) theorem lt_power_cof {c : cardinal.{u}} : omega ≤ c → c < c ^ cof c.ord := quotient.induction_on c $ λ α h, begin rcases ord_eq α with ⟨r, wo, re⟩, resetI, have := ord_is_limit h, rw [mk_def, re] at this ⊢, rcases cof_eq' r this with ⟨S, H, Se⟩, have := sum_lt_prod (λ a:S, mk {x // r x a}) (λ _, mk α) (λ i, _), { simp [Se.symm] at this ⊢, refine lt_of_le_of_lt _ this, refine ⟨embedding.of_surjective _ _⟩, { exact λ x, x.2.1 }, { exact λ a, let ⟨b, h, ab⟩ := H a in ⟨⟨⟨_, h⟩, _, ab⟩, rfl⟩ } }, { have := typein_lt_type r i, rwa [← re, lt_ord] at this } end theorem lt_cof_power {a b : cardinal} (ha : omega ≤ a) (b1 : 1 < b) : a < cof (b ^ a).ord := begin have b0 : b ≠ 0 := ne_of_gt (lt_trans zero_lt_one b1), apply lt_imp_lt_of_le_imp_le (power_le_power_left $ power_ne_zero a b0), rw [← power_mul, mul_eq_self ha], exact lt_power_cof (le_trans ha $ le_of_lt $ cantor' _ b1), end end cardinal
8a267a1ced320e60616998c687093ffd1cdae0a9
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/topology/metric_space/baire.lean
8e04191ee5ad5fd7744b75c594018f80c7750561
[ "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
13,911
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.specific_limits import order.filter.countable_Inter import topology.G_delta /-! # Baire theorem In a complete metric space, a countable intersection of dense open subsets is dense. The good concept underlying the theorem is that of a Gδ set, i.e., a countable intersection of open sets. Then Baire theorem can also be formulated as the fact that a countable intersection of dense Gδ sets is a dense Gδ set. We prove Baire theorem, giving several different formulations that can be handy. We also prove the important consequence that, if the space is covered by a countable union of closed sets, then the union of their interiors is dense. The names of the theorems do not contain the string "Baire", but are instead built from the form of the statement. "Baire" is however in the docstring of all the theorems, to facilitate grep searches. We also define the filter `residual α` generated by dense `Gδ` sets and prove that this filter has the countable intersection property. -/ noncomputable theory open_locale classical topological_space filter ennreal open filter encodable set variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} section Baire_theorem open emetric ennreal variables [emetric_space α] [complete_space α] /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here when the source space is ℕ (and subsumed below by `dense_Inter_of_open` working with any encodable source space). -/ theorem dense_Inter_of_open_nat {f : ℕ → set α} (ho : ∀n, is_open (f n)) (hd : ∀n, dense (f n)) : dense (⋂n, f n) := begin let B : ℕ → ℝ≥0∞ := λn, 1/2^n, have Bpos : ∀n, 0 < B n, { intro n, simp only [B, one_div, one_mul, ennreal.inv_pos], exact pow_ne_top two_ne_top }, /- Translate the density assumption into two functions `center` and `radius` associating to any n, x, δ, δpos a center and a positive radius such that `closed_ball center radius` is included both in `f n` and in `closed_ball x δ`. We can also require `radius ≤ (1/2)^(n+1)`, to ensure we get a Cauchy sequence later. -/ have : ∀n x δ, δ ≠ 0 → ∃y r, 0 < r ∧ r ≤ B (n+1) ∧ closed_ball y r ⊆ (closed_ball x δ) ∩ f n, { assume n x δ δpos, have : x ∈ closure (f n) := hd n x, rcases emetric.mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, xy⟩, rw edist_comm at xy, obtain ⟨r, rpos, hr⟩ : ∃ r > 0, closed_ball y r ⊆ f n := nhds_basis_closed_eball.mem_iff.1 (is_open_iff_mem_nhds.1 (ho n) y ys), refine ⟨y, min (min (δ/2) r) (B (n+1)), _, _, λz hz, ⟨_, _⟩⟩, show 0 < min (min (δ / 2) r) (B (n+1)), from lt_min (lt_min (ennreal.half_pos δpos) rpos) (Bpos (n+1)), show min (min (δ / 2) r) (B (n+1)) ≤ B (n+1), from min_le_right _ _, show z ∈ closed_ball x δ, from calc edist z x ≤ edist z y + edist y x : edist_triangle _ _ _ ... ≤ (min (min (δ / 2) r) (B (n+1))) + (δ/2) : add_le_add hz (le_of_lt xy) ... ≤ δ/2 + δ/2 : add_le_add (le_trans (min_le_left _ _) (min_le_left _ _)) (le_refl _) ... = δ : ennreal.add_halves δ, show z ∈ f n, from hr (calc edist z y ≤ min (min (δ / 2) r) (B (n+1)) : hz ... ≤ r : le_trans (min_le_left _ _) (min_le_right _ _)) }, choose! center radius Hpos HB Hball using this, refine λ x, (mem_closure_iff_nhds_basis nhds_basis_closed_eball).2 (λ ε εpos, _), /- `ε` is positive. We have to find a point in the ball of radius `ε` around `x` belonging to all `f n`. For this, we construct inductively a sequence `F n = (c n, r n)` such that the closed ball `closed_ball (c n) (r n)` is included in the previous ball and in `f n`, and such that `r n` is small enough to ensure that `c n` is a Cauchy sequence. Then `c n` converges to a limit which belongs to all the `f n`. -/ let F : ℕ → (α × ℝ≥0∞) := λn, nat.rec_on n (prod.mk x (min ε (B 0))) (λn p, prod.mk (center n p.1 p.2) (radius n p.1 p.2)), let c : ℕ → α := λn, (F n).1, let r : ℕ → ℝ≥0∞ := λn, (F n).2, have rpos : ∀ n, 0 < r n, { assume n, induction n with n hn, exact lt_min εpos (Bpos 0), exact Hpos n (c n) (r n) hn.ne' }, have r0 : ∀ n, r n ≠ 0 := λ n, (rpos n).ne', have rB : ∀n, r n ≤ B n, { assume n, induction n with n hn, exact min_le_right _ _, exact HB n (c n) (r n) (r0 n) }, have incl : ∀n, closed_ball (c (n+1)) (r (n+1)) ⊆ (closed_ball (c n) (r n)) ∩ (f n) := λ n, Hball n (c n) (r n) (r0 n), have cdist : ∀n, edist (c n) (c (n+1)) ≤ B n, { assume n, rw edist_comm, have A : c (n+1) ∈ closed_ball (c (n+1)) (r (n+1)) := mem_closed_ball_self, have I := calc closed_ball (c (n+1)) (r (n+1)) ⊆ closed_ball (c n) (r n) : subset.trans (incl n) (inter_subset_left _ _) ... ⊆ closed_ball (c n) (B n) : closed_ball_subset_closed_ball (rB n), exact I A }, have : cauchy_seq c := cauchy_seq_of_edist_le_geometric_two _ one_ne_top cdist, -- as the sequence `c n` is Cauchy in a complete space, it converges to a limit `y`. rcases cauchy_seq_tendsto_of_complete this with ⟨y, ylim⟩, -- this point `y` will be the desired point. We will check that it belongs to all -- `f n` and to `ball x ε`. use y, simp only [exists_prop, set.mem_Inter], have I : ∀n, ∀m ≥ n, closed_ball (c m) (r m) ⊆ closed_ball (c n) (r n), { assume n, refine nat.le_induction _ (λm hnm h, _), { exact subset.refl _ }, { exact subset.trans (incl m) (subset.trans (inter_subset_left _ _) h) }}, have yball : ∀n, y ∈ closed_ball (c n) (r n), { assume n, refine is_closed_ball.mem_of_tendsto ylim _, refine (filter.eventually_ge_at_top n).mono (λ m hm, _), exact I n m hm mem_closed_ball_self }, split, show ∀n, y ∈ f n, { assume n, have : closed_ball (c (n+1)) (r (n+1)) ⊆ f n := subset.trans (incl n) (inter_subset_right _ _), exact this (yball (n+1)) }, show edist y x ≤ ε, from le_trans (yball 0) (min_le_left _ _), end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_open {S : set (set α)} (ho : ∀s∈S, is_open s) (hS : countable S) (hd : ∀s∈S, dense s) : dense (⋂₀S) := begin cases S.eq_empty_or_nonempty with h h, { simp [h] }, { rcases hS.exists_surjective h with ⟨f, hf⟩, have F : ∀n, f n ∈ S := λn, by rw hf; exact mem_range_self _, rw [hf, sInter_range], exact dense_Inter_of_open_nat (λn, ho _ (F n)) (λn, hd _ (F n)) } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_open {S : set β} {f : β → set α} (ho : ∀s∈S, is_open (f s)) (hS : countable S) (hd : ∀s∈S, dense (f s)) : dense (⋂s∈S, f s) := begin rw ← sInter_image, apply dense_sInter_of_open, { rwa ball_image_iff }, { exact hS.image _ }, { rwa ball_image_iff } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_open [encodable β] {f : β → set α} (ho : ∀s, is_open (f s)) (hd : ∀s, dense (f s)) : dense (⋂s, f s) := begin rw ← sInter_range, apply dense_sInter_of_open, { rwa forall_range_iff }, { exact countable_range _ }, { rwa forall_range_iff } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_Gδ {S : set (set α)} (ho : ∀s∈S, is_Gδ s) (hS : countable S) (hd : ∀s∈S, dense s) : dense (⋂₀S) := begin -- the result follows from the result for a countable intersection of dense open sets, -- by rewriting each set as a countable intersection of open sets, which are of course dense. choose T hT using ho, have : ⋂₀ S = ⋂₀ (⋃s∈S, T s ‹_›) := (sInter_bUnion (λs hs, (hT s hs).2.2)).symm, rw this, refine dense_sInter_of_open _ (hS.bUnion (λs hs, (hT s hs).2.1)) _; simp only [set.mem_Union, exists_prop]; rintro t ⟨s, hs, tTs⟩, show is_open t, { exact (hT s hs).1 t tTs }, show dense t, { intro x, have := hd s hs x, rw (hT s hs).2.2 at this, exact closure_mono (sInter_subset_of_mem tTs) this } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_Gδ [encodable β] {f : β → set α} (ho : ∀s, is_Gδ (f s)) (hd : ∀s, dense (f s)) : dense (⋂s, f s) := begin rw ← sInter_range, exact dense_sInter_of_Gδ (forall_range_iff.2 ‹_›) (countable_range _) (forall_range_iff.2 ‹_›) end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_Gδ {S : set β} {f : Π x ∈ S, set α} (ho : ∀s∈S, is_Gδ (f s ‹_›)) (hS : countable S) (hd : ∀s∈S, dense (f s ‹_›)) : dense (⋂s∈S, f s ‹_›) := begin rw bInter_eq_Inter, haveI := hS.to_encodable, exact dense_Inter_of_Gδ (λ s, ho s s.2) (λ s, hd s s.2) end /-- Baire theorem: the intersection of two dense Gδ sets is dense. -/ theorem dense.inter_of_Gδ {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) (hsc : dense s) (htc : dense t) : dense (s ∩ t) := begin rw [inter_eq_Inter], apply dense_Inter_of_Gδ; simp [bool.forall_bool, *] end /-- A property holds on a residual (comeagre) set if and only if it holds on some dense `Gδ` set. -/ lemma eventually_residual {p : α → Prop} : (∀ᶠ x in residual α, p x) ↔ ∃ (t : set α), is_Gδ t ∧ dense t ∧ ∀ x ∈ t, p x := calc (∀ᶠ x in residual α, p x) ↔ ∀ᶠ x in ⨅ (t : set α) (ht : is_Gδ t ∧ dense t), 𝓟 t, p x : by simp only [residual, infi_and] ... ↔ ∃ (t : set α) (ht : is_Gδ t ∧ dense t), ∀ᶠ x in 𝓟 t, p x : mem_binfi_of_directed (λ t₁ h₁ t₂ h₂, ⟨t₁ ∩ t₂, ⟨h₁.1.inter h₂.1, dense.inter_of_Gδ h₁.1 h₂.1 h₁.2 h₂.2⟩, by simp⟩) ⟨univ, is_Gδ_univ, dense_univ⟩ ... ↔ _ : by simp [and_assoc] /-- A set is residual (comeagre) if and only if it includes a dense `Gδ` set. -/ lemma mem_residual {s : set α} : s ∈ residual α ↔ ∃ t ⊆ s, is_Gδ t ∧ dense t := (@eventually_residual α _ _ (λ x, x ∈ s)).trans $ exists_congr $ λ t, by rw [exists_prop, and_comm (t ⊆ s), subset_def, and_assoc] instance : countable_Inter_filter (residual α) := ⟨begin intros S hSc hS, simp only [mem_residual] at *, choose T hTs hT using hS, refine ⟨⋂ s ∈ S, T s ‹_›, _, _, _⟩, { rw [sInter_eq_bInter], exact Inter_subset_Inter (λ s, Inter_subset_Inter $ hTs s) }, { exact is_Gδ_bInter hSc (λ s hs, (hT s hs).1) }, { exact dense_bInter_of_Gδ (λ s hs, (hT s hs).1) hSc (λ s hs, (hT s hs).2) } end⟩ /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bUnion_interior_of_closed {S : set β} {f : β → set α} (hc : ∀s∈S, is_closed (f s)) (hS : countable S) (hU : (⋃s∈S, f s) = univ) : dense (⋃s∈S, interior (f s)) := begin let g := λs, (frontier (f s))ᶜ, have : dense (⋂s∈S, g s), { refine dense_bInter_of_open (λs hs, _) hS (λs hs, _), show is_open (g s), from is_open_compl_iff.2 is_closed_frontier, show dense (g s), { intro x, simp [interior_frontier (hc s hs)] }}, refine this.mono _, show (⋂s∈S, g s) ⊆ (⋃s∈S, interior (f s)), assume x hx, have : x ∈ ⋃s∈S, f s, { have := mem_univ x, rwa ← hU at this }, rcases mem_bUnion_iff.1 this with ⟨s, hs, xs⟩, have : x ∈ g s := mem_bInter_iff.1 hx s hs, have : x ∈ interior (f s), { have : x ∈ f s \ (frontier (f s)) := mem_inter xs this, simpa [frontier, xs, (hc s hs).closure_eq] using this }, exact mem_bUnion_iff.2 ⟨s, ⟨hs, this⟩⟩ end /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with `⋃₀`. -/ theorem dense_sUnion_interior_of_closed {S : set (set α)} (hc : ∀s∈S, is_closed s) (hS : countable S) (hU : (⋃₀ S) = univ) : dense (⋃s∈S, interior s) := by rw sUnion_eq_bUnion at hU; exact dense_bUnion_interior_of_closed hc hS hU /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Union_interior_of_closed [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : dense (⋃s, interior (f s)) := begin rw ← bUnion_univ, apply dense_bUnion_interior_of_closed, { simp [hc] }, { apply countable_encodable }, { rwa ← bUnion_univ at hU } end /-- One of the most useful consequences of Baire theorem: if a countable union of closed sets covers the space, then one of the sets has nonempty interior. -/ theorem nonempty_interior_of_Union_of_closed [nonempty α] [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : ∃s, (interior $ f s).nonempty := begin by_contradiction h, simp only [not_exists, not_nonempty_iff_eq_empty] at h, have := calc ∅ = closure (⋃s, interior (f s)) : by simp [h] ... = univ : (dense_Union_interior_of_closed hc hU).closure_eq, exact univ_nonempty.ne_empty this.symm end end Baire_theorem
b90fed4eaebb6b0fd69bde192876fedc6c4bddca
9028d228ac200bbefe3a711342514dd4e4458bff
/src/linear_algebra/affine_space/finite_dimensional.lean
2281fe9c03a728b275d4ab992c3aa13e10cc49b2
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,077
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import linear_algebra.affine_space.independent import linear_algebra.finite_dimensional noncomputable theory open_locale big_operators open_locale classical /-! # Finite-dimensional subspaces of affine spaces. This file provides a few results relating to finite-dimensional subspaces of affine spaces. ## Main definitions * `collinear` defines collinear sets of points as those that span a subspace of dimension at most 1. -/ section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [field k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace finite_dimensional vector_space /-- The `vector_span` of a finite set is finite-dimensional. -/ lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (vector_span k s) := span_of_finite k $ vsub_set_finite_of_finite h /-- The `vector_span` of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (vector_span k (set.range p)) := finite_dimensional_vector_span_of_finite k (set.finite_range _) /-- The `vector_span` of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (vector_span k (p '' s)) := finite_dimensional_vector_span_of_finite k ((set.finite.of_fintype _).image _) /-- The direction of the affine span of a finite set is finite-dimensional. -/ lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h /-- The direction of the affine span of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (affine_span k (set.range p)).direction := finite_dimensional_direction_affine_span_of_finite k (set.finite_range _) /-- The direction of the affine span of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction := finite_dimensional_direction_affine_span_of_finite k ((set.finite.of_fintype _).image _) variables {k} /-- The `vector_span` of a finite subset of an affinely independent family has dimension one less than its cardinality. -/ lemma findim_vector_span_image_finset_of_affine_independent {p : ι → P} (hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) : findim k (vector_span k (p '' ↑s)) = n := begin have hi' := affine_independent_of_subset_affine_independent (affine_independent_set_of_affine_independent hi) (set.image_subset_range p ↑s), have hc' : fintype.card (p '' ↑s) = n + 1, { rwa [set.card_image_of_injective ↑s (injective_of_affine_independent hi), fintype.card_coe] }, have hn : (p '' ↑s).nonempty, { simp [hc, ←finset.card_pos] }, rcases hn with ⟨p₁, hp₁⟩, rw affine_independent_set_iff_linear_independent_vsub k hp₁ at hi', have hfr : (p '' ↑s \ {p₁}).finite := ((set.finite_mem_finset _).image _).subset (set.diff_subset _ _), haveI := hfr.fintype, have hf : set.finite ((λ (p : P), p -ᵥ p₁) '' (p '' ↑s \ {p₁})) := hfr.image _, haveI := hf.fintype, have hc : hf.to_finset.card = n, { rw [hf.card_to_finset, set.card_image_of_injective (p '' ↑s \ {p₁}) (vsub_left_injective _)], have hd : insert p₁ (p '' ↑s \ {p₁}) = p '' ↑s, { rw [set.insert_diff_singleton, set.insert_eq_of_mem hp₁] }, have hc'' : fintype.card ↥(insert p₁ (p '' ↑s \ {p₁})) = n + 1, { convert hc' }, rw set.card_insert (p '' ↑s \ {p₁}) (λ h, ((set.mem_diff p₁).2 h).2 rfl) at hc'', simpa using hc'' }, rw [vector_span_eq_span_vsub_set_right_ne k hp₁, findim_span_set_eq_card _ hi', ←hc], congr end /-- The `vector_span` of a finite affinely independent family has dimension one less than its cardinality. -/ lemma findim_vector_span_of_affine_independent [fintype ι] {p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) : findim k (vector_span k (set.range p)) = n := begin rw ←finset.card_univ at hc, rw [←set.image_univ, ←finset.coe_univ], exact findim_vector_span_image_finset_of_affine_independent hi hc end /-- If the `vector_span` of a finite subset of an affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma vector_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (p '' ↑s) ≤ sm) (hc : finset.card s = findim k sm + 1) : vector_span k (p '' ↑s) = sm := eq_of_le_of_findim_eq hle $ findim_vector_span_image_finset_of_affine_independent hi hc /-- If the `vector_span` of a finite affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma vector_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (set.range p) ≤ sm) (hc : fintype.card ι = findim k sm + 1) : vector_span k (set.range p) = sm := eq_of_le_of_findim_eq hle $ findim_vector_span_of_affine_independent hi hc /-- If the `affine_span` of a finite subset of an affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (p '' ↑s) ≤ sp) (hc : finset.card s = findim k sp.direction + 1) : affine_span k (p '' ↑s) = sp := begin have hn : (p '' ↑s).nonempty, { simp [hc, ←finset.card_pos] }, refine eq_of_direction_eq_of_nonempty_of_le _ ((affine_span_nonempty k _).2 hn) hle, have hd := direction_le hle, rw direction_affine_span at ⊢ hd, exact vector_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one hi hd hc end /-- If the `affine_span` of a finite affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (set.range p) ≤ sp) (hc : fintype.card ι = findim k sp.direction + 1) : affine_span k (set.range p) = sp := begin rw ←finset.card_univ at hc, rw [←set.image_univ, ←finset.coe_univ] at ⊢ hle, exact affine_span_image_finset_eq_of_le_of_affine_independent_of_card_eq_findim_add_one hi hle hc end /-- The `vector_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma vector_span_eq_top_of_affine_independent_of_card_eq_findim_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = findim k V + 1) : vector_span k (set.range p) = ⊤ := eq_top_of_findim_eq $ findim_vector_span_of_affine_independent hi hc /-- The `affine_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma affine_span_eq_top_of_affine_independent_of_card_eq_findim_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = findim k V + 1) : affine_span k (set.range p) = ⊤ := begin rw [←findim_top, ←direction_top k V P] at hc, exact affine_span_eq_of_le_of_affine_independent_of_card_eq_findim_add_one hi le_top hc end variables (k) /-- The `vector_span` of `n + 1` points in an indexed family has dimension at most `n`. -/ lemma findim_vector_span_image_finset_le (p : ι → P) (s : finset ι) {n : ℕ} (hc : finset.card s = n + 1) : findim k (vector_span k (p '' ↑s)) ≤ n := begin have hn : (p '' ↑s).nonempty, { simp [hc, ←finset.card_pos] }, rcases hn with ⟨p₁, hp₁⟩, rw [vector_span_eq_span_vsub_set_right_ne k hp₁], have hfp₁ : (p '' ↑s \ {p₁}).finite := ((finset.finite_to_set _).image _).subset (set.diff_subset _ _), haveI := hfp₁.fintype, have hf : ((λ p, p -ᵥ p₁) '' (p '' ↑s \ {p₁})).finite := hfp₁.image _, haveI := hf.fintype, convert le_trans (findim_span_le_card ((λ p, p -ᵥ p₁) '' (p '' ↑s \ {p₁}))) _, have hm : p₁ ∉ p '' ↑s \ {p₁}, by simp, haveI := set.fintype_insert' (p '' ↑s \ {p₁}) hm, rw [set.to_finset_card, set.card_image_of_injective (p '' ↑s \ {p₁}) (vsub_left_injective p₁), ←add_le_add_iff_right 1, ←set.card_fintype_insert' _ hm], have h : fintype.card (↑(s.image p) : set P) ≤ n + 1, { rw [fintype.card_coe, ←hc], exact finset.card_image_le }, convert h, simp [hp₁] end /-- The `vector_span` of an indexed family of `n + 1` points has dimension at most `n`. -/ lemma findim_vector_span_range_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : findim k (vector_span k (set.range p)) ≤ n := begin rw [←set.image_univ, ←finset.coe_univ], rw ←finset.card_univ at hc, exact findim_vector_span_image_finset_le _ _ _ hc end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension `n`. -/ lemma affine_independent_iff_findim_vector_span_eq [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ findim k (vector_span k (set.range p)) = n := begin have hn : nonempty ι, by simp [←fintype.card_pos_iff, hc], cases hn with i₁, rw [affine_independent_iff_linear_independent_vsub _ _ i₁, linear_independent_iff_card_eq_findim_span, eq_comm, vector_span_range_eq_span_range_vsub_right_ne k p i₁], congr', rw ←finset.card_univ at hc, rw fintype.subtype_card, simp [finset.filter_ne', finset.card_erase_of_mem, hc] end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension at least `n`. -/ lemma affine_independent_iff_le_findim_vector_span [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ n ≤ findim k (vector_span k (set.range p)) := begin rw affine_independent_iff_findim_vector_span_eq k p hc, split, { rintro rfl, refl }, { exact λ hle, le_antisymm (findim_vector_span_range_le k p hc) hle } end /-- `n + 2` points are affinely independent if and only if their `vector_span` does not have dimension at most `n`. -/ lemma affine_independent_iff_not_findim_vector_span_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : affine_independent k p ↔ ¬ findim k (vector_span k (set.range p)) ≤ n := by rw [affine_independent_iff_le_findim_vector_span k p hc, ←nat.lt_iff_add_one_le, lt_iff_not_ge] /-- `n + 2` points have a `vector_span` with dimension at most `n` if and only if they are not affinely independent. -/ lemma findim_vector_span_le_iff_not_affine_independent [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : findim k (vector_span k (set.range p)) ≤ n ↔ ¬ affine_independent k p := (not_iff_comm.1 (affine_independent_iff_not_findim_vector_span_le k p hc).symm).symm /-- A set of points is collinear if their `vector_span` has dimension at most `1`. -/ def collinear (s : set P) : Prop := dim k (vector_span k s) ≤ 1 /-- The definition of `collinear`. -/ lemma collinear_iff_dim_le_one (s : set P) : collinear k s ↔ dim k (vector_span k s) ≤ 1 := iff.rfl /-- A set of points, whose `vector_span` is finite-dimensional, is collinear if and only if their `vector_span` has dimension at most `1`. -/ lemma collinear_iff_findim_le_one (s : set P) [finite_dimensional k (vector_span k s)] : collinear k s ↔ findim k (vector_span k s) ≤ 1 := begin have h := collinear_iff_dim_le_one k s, rw ←findim_eq_dim at h, exact_mod_cast h end variables (P) /-- The empty set is collinear. -/ lemma collinear_empty : collinear k (∅ : set P) := begin rw [collinear_iff_dim_le_one, vector_span_empty], simp end variables {P} /-- A single point is collinear. -/ lemma collinear_singleton (p : P) : collinear k ({p} : set P) := begin rw [collinear_iff_dim_le_one, vector_span_singleton], simp end /-- Given a point `p₀` in a set of points, that set is collinear if and only if the points can all be expressed as multiples of the same vector, added to `p₀`. -/ lemma collinear_iff_of_mem {s : set P} {p₀ : P} (h : p₀ ∈ s) : collinear k s ↔ ∃ v : V, ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin simp_rw [collinear_iff_dim_le_one, dim_submodule_le_one_iff', submodule.le_span_singleton_iff], split, { rintro ⟨v₀, hv⟩, use v₀, intros p hp, obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vector_span k hp h), use r, rw eq_vadd_iff_vsub_eq, exact hr.symm }, { rintro ⟨v, hp₀v⟩, use v, intros w hw, have hs : vector_span k s ≤ submodule.span k ({v} : set V), { rw [vector_span_eq_span_vsub_set_right k h, submodule.span_le, set.subset_def], intros x hx, rw [submodule.mem_coe, submodule.mem_span_singleton], rw set.mem_image at hx, rcases hx with ⟨p, hp, rfl⟩, rcases hp₀v p hp with ⟨r, rfl⟩, use r, simp }, have hw' := submodule.le_def'.1 hs w hw, rwa submodule.mem_span_singleton at hw' } end /-- A set of points is collinear if and only if they can all be expressed as multiples of the same vector, added to the same base point. -/ lemma collinear_iff_exists_forall_eq_smul_vadd (s : set P) : collinear k s ↔ ∃ (p₀ : P) (v : V), ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin rcases set.eq_empty_or_nonempty s with rfl | ⟨⟨p₁, hp₁⟩⟩, { simp [collinear_empty] }, { rw collinear_iff_of_mem k hp₁, split, { exact λ h, ⟨p₁, h⟩ }, { rintros ⟨p, v, hv⟩, use v, intros p₂ hp₂, rcases hv p₂ hp₂ with ⟨r, rfl⟩, rcases hv p₁ hp₁ with ⟨r₁, rfl⟩, use r - r₁, simp [vadd_assoc, ←add_smul] } } end /-- Two points are collinear. -/ lemma collinear_insert_singleton (p₁ p₂ : P) : collinear k ({p₁, p₂} : set P) := begin rw collinear_iff_exists_forall_eq_smul_vadd, use [p₁, p₂ -ᵥ p₁], intros p hp, rw [set.mem_insert_iff, set.mem_singleton_iff] at hp, cases hp, { use 0, simp [hp] }, { use 1, simp [hp] } end /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear (p : fin 3 → P) : affine_independent k p ↔ ¬ collinear k (set.range p) := by rw [collinear_iff_findim_le_one, affine_independent_iff_not_findim_vector_span_le k p (fintype.card_fin 3)] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent (p : fin 3 → P) : collinear k (set.range p) ↔ ¬ affine_independent k p := by rw [collinear_iff_findim_le_one, findim_vector_span_le_iff_not_affine_independent k p (fintype.card_fin 3)] end affine_space'
4117a38a49f9221655823d52d5333fcb8d869a87
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/types/int/basic.hlean
e09199e26e3aadfdde54ec29cb748a8acec1d855
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,730
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad The integers, with addition, multiplication, and subtraction. The representation of the integers is chosen to compute efficiently. To faciliate proving things about these operations, we show that the integers are a quotient of ℕ × ℕ with the usual equivalence relation, ≡, and functions abstr : ℕ × ℕ → ℤ repr : ℤ → ℕ × ℕ satisfying: abstr_repr (a : ℤ) : abstr (repr a) = a repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p abstr_eq (p q : ℕ × ℕ) : p ≡ q → abstr p = abstr q For example, to "lift" statements about add to statements about padd, we need to prove the following: repr_add (a b : ℤ) : repr (a + b) = padd (repr a) (repr b) padd_congr (p p' q q' : ℕ × ℕ) (H1 : p ≡ p') (H2 : q ≡ q') : padd p q ≡ p' q' Ported from standard library -/ import types.nat.sub algebra.relation types.prod open core nat decidable prod relation prod /- the type of integers -/ inductive int : Type := | of_nat : nat → int | neg_succ_of_nat : nat → int notation `ℤ` := int attribute int.of_nat [coercion] definition int.of_num [coercion] [reducible] [constructor] (n : num) : ℤ := int.of_nat (nat.of_num n) namespace int /- definitions of basic functions -/ definition neg_of_nat (m : ℕ) : ℤ := nat.cases_on m 0 (take m', neg_succ_of_nat m') definition sub_nat_nat (m n : ℕ) : ℤ := nat.cases_on (n - m) (of_nat (m - n)) -- m ≥ n (take k, neg_succ_of_nat k) -- m < n, and n - m = succ k definition neg (a : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m nat.cases_on m 0 (take m', neg_succ_of_nat m')) (take m, of_nat (succ m)) -- a = neg_succ_of_nat m definition add (a b : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m int.cases_on b (take n, of_nat (m + n)) -- b = of_nat n (take n, sub_nat_nat m (succ n))) -- b = neg_succ_of_nat n (take m, -- a = neg_succ_of_nat m int.cases_on b (take n, sub_nat_nat n (succ m)) -- b = of_nat n (take n, neg_of_nat (succ m + succ n))) -- b = neg_succ_of_nat n definition mul (a b : ℤ) : ℤ := int.cases_on a (take m, -- a = of_nat m int.cases_on b (take n, of_nat (m * n)) -- b = of_nat n (take n, neg_of_nat (m * succ n))) -- b = neg_succ_of_nat n (take m, -- a = neg_succ_of_nat m int.cases_on b (take n, neg_of_nat (succ m * n)) -- b = of_nat n (take n, of_nat (succ m * succ n))) -- b = neg_succ_of_nat n /- notation -/ notation `-[` n `+1]` := int.neg_succ_of_nat n -- for pretty-printing output prefix - := int.neg infix + := int.add infix * := int.mul /- some basic functions and properties -/ definition of_nat.inj {m n : ℕ} (H : of_nat m = of_nat n) : m = n := by injection H; assumption definition neg_succ_of_nat.inj {m n : ℕ} (H : neg_succ_of_nat m = neg_succ_of_nat n) : m = n := by injection H; assumption definition neg_succ_of_nat_eq (n : ℕ) : -[n +1] = -(n + 1) := rfl definition has_decidable_eq [instance] : decidable_eq ℤ := take a b, int.cases_on a (take m, int.cases_on b (take n, if H : m = n then inl (ap of_nat H) else inr (take H1, H (of_nat.inj H1))) (take n', inr (by contradiction))) (take m', int.cases_on b (take n, inr (by contradiction)) (take n', (if H : m' = n' then inl (ap neg_succ_of_nat H) else inr (take H1, H (neg_succ_of_nat.inj H1))))) definition of_nat_add_of_nat (n m : nat) : of_nat n + of_nat m = #nat n + m := rfl definition of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl definition of_nat_mul_of_nat (n m : ℕ) : of_nat n * of_nat m = n * m := rfl definition sub_nat_nat_of_ge {m n : ℕ} (H : m ≥ n) : sub_nat_nat m n = of_nat (m - n) := have H1 : n - m = 0, from sub_eq_zero_of_le H, calc sub_nat_nat m n = nat.cases_on 0 (of_nat (m - n)) _ : H1 ▸ rfl ... = of_nat (m - n) : rfl section local attribute sub_nat_nat [reducible] definition sub_nat_nat_of_lt {m n : ℕ} (H : m < n) : sub_nat_nat m n = neg_succ_of_nat (pred (n - m)) := have H1 : n - m = succ (pred (n - m)), from (succ_pred_of_pos (sub_pos_of_lt H))⁻¹, calc sub_nat_nat m n = nat.cases_on (succ (pred (n - m))) (of_nat (m - n)) (take k, neg_succ_of_nat k) : H1 ▸ rfl ... = neg_succ_of_nat (pred (n - m)) : rfl end definition nat_abs (a : ℤ) : ℕ := int.cases_on a (take n, n) (take n', succ n') definition nat_abs_of_nat (n : ℕ) : nat_abs (of_nat n) = n := rfl definition nat_abs_eq_zero {a : ℤ} : nat_abs a = 0 → a = 0 := int.cases_on a (take m, assume H : nat_abs (of_nat m) = 0, ap of_nat H) (take m', assume H : nat_abs (neg_succ_of_nat m') = 0, absurd H (succ_ne_zero _)) /- int is a quotient of ordered pairs of natural numbers -/ definition int_equiv (p q : ℕ × ℕ) : Type₀ := pr1 p + pr2 q = pr2 p + pr1 q local infix `≡` := int_equiv protected theorem int_equiv.refl [refl] {p : ℕ × ℕ} : p ≡ p := !add.comm protected theorem int_equiv.symm [symm] {p q : ℕ × ℕ} (H : p ≡ q) : q ≡ p := calc pr1 q + pr2 p = pr2 p + pr1 q : !add.comm ... = pr1 p + pr2 q : H⁻¹ ... = pr2 q + pr1 p : !add.comm protected theorem int_equiv.trans [trans] {p q r : ℕ × ℕ} (H1 : p ≡ q) (H2 : q ≡ r) : p ≡ r := add.cancel_right (calc pr1 p + pr2 r + pr2 q = pr1 p + pr2 q + pr2 r : add.right_comm ... = pr2 p + pr1 q + pr2 r : {H1} ... = pr2 p + (pr1 q + pr2 r) : add.assoc ... = pr2 p + (pr2 q + pr1 r) : {H2} ... = pr2 p + pr2 q + pr1 r : add.assoc ... = pr2 p + pr1 r + pr2 q : add.right_comm) definition int_equiv_int_equiv : is_equivalence int_equiv := is_equivalence.mk @int_equiv.refl @int_equiv.symm @int_equiv.trans definition int_equiv_cases {p q : ℕ × ℕ} (H : int_equiv p q) : (pr1 p ≥ pr2 p × pr1 q ≥ pr2 q) ⊎ (pr1 p < pr2 p × pr1 q < pr2 q) := sum.rec_on (@le_or_gt (pr2 p) (pr1 p)) (assume H1: pr1 p ≥ pr2 p, have H2 : pr2 p + pr1 q ≥ pr2 p + pr2 q, from H ▸ add_le_add_right H1 (pr2 q), sum.inl (pair H1 (le_of_add_le_add_left H2))) (assume H1: pr1 p < pr2 p, have H2 : pr2 p + pr1 q < pr2 p + pr2 q, from H ▸ add_lt_add_right H1 (pr2 q), sum.inr (pair H1 (lt_of_add_lt_add_left H2))) definition int_equiv_of_eq {p q : ℕ × ℕ} (H : p = q) : p ≡ q := H ▸ int_equiv.refl /- the representation and abstraction functions -/ definition abstr (a : ℕ × ℕ) : ℤ := sub_nat_nat (pr1 a) (pr2 a) definition abstr_of_ge {p : ℕ × ℕ} (H : pr1 p ≥ pr2 p) : abstr p = of_nat (pr1 p - pr2 p) := sub_nat_nat_of_ge H definition abstr_of_lt {p : ℕ × ℕ} (H : pr1 p < pr2 p) : abstr p = neg_succ_of_nat (pred (pr2 p - pr1 p)) := sub_nat_nat_of_lt H definition repr (a : ℤ) : ℕ × ℕ := int.cases_on a (take m, (m, 0)) (take m, (0, succ m)) definition abstr_repr (a : ℤ) : abstr (repr a) = a := int.cases_on a (take m, (sub_nat_nat_of_ge (zero_le m))) (take m, rfl) definition repr_sub_nat_nat (m n : ℕ) : repr (sub_nat_nat m n) ≡ (m, n) := sum.rec_on (@le_or_gt n m) (take H : m ≥ n, have H1 : repr (sub_nat_nat m n) = (m - n, 0), from sub_nat_nat_of_ge H ▸ rfl, H1⁻¹ ▸ (calc m - n + n = m : sub_add_cancel H ... = 0 + m : zero_add)) (take H : m < n, have H1 : repr (sub_nat_nat m n) = (0, succ (pred (n - m))), from sub_nat_nat_of_lt H ▸ rfl, H1⁻¹ ▸ (calc 0 + n = n : zero_add ... = n - m + m : sub_add_cancel (le_of_lt H) ... = succ (pred (n - m)) + m : (succ_pred_of_pos (sub_pos_of_lt H))⁻¹ᵖ)) definition repr_abstr (p : ℕ × ℕ) : repr (abstr p) ≡ p := !prod.eta ▸ !repr_sub_nat_nat definition abstr_eq {p q : ℕ × ℕ} (Hint_equiv : p ≡ q) : abstr p = abstr q := sum.rec_on (int_equiv_cases Hint_equiv) (assume H2, have H3 : pr1 p ≥ pr2 p, from prod.pr1 H2, have H4 : pr1 q ≥ pr2 q, from prod.pr2 H2, have H5 : pr1 p = pr1 q - pr2 q + pr2 p, from calc pr1 p = pr1 p + pr2 q - pr2 q : add_sub_cancel ... = pr2 p + pr1 q - pr2 q : by rewrite [↑int_equiv at Hint_equiv,Hint_equiv] ... = pr2 p + (pr1 q - pr2 q) : add_sub_assoc H4 ... = pr1 q - pr2 q + pr2 p : add.comm, have H6 : pr1 p - pr2 p = pr1 q - pr2 q, from calc pr1 p - pr2 p = pr1 q - pr2 q + pr2 p - pr2 p : H5 ... = pr1 q - pr2 q : add_sub_cancel, abstr_of_ge H3 ⬝ ap of_nat H6 ⬝ (abstr_of_ge H4)⁻¹) (assume H2, have H3 : pr1 p < pr2 p, from prod.pr1 H2, have H4 : pr1 q < pr2 q, from prod.pr2 H2, have H5 : pr2 p = pr2 q - pr1 q + pr1 p, from calc pr2 p = pr2 p + pr1 q - pr1 q : add_sub_cancel ... = pr1 p + pr2 q - pr1 q : by rewrite [↑int_equiv at Hint_equiv,Hint_equiv] ... = pr1 p + (pr2 q - pr1 q) : add_sub_assoc (le_of_lt H4) ... = pr2 q - pr1 q + pr1 p : add.comm, have H6 : pr2 p - pr1 p = pr2 q - pr1 q, from calc pr2 p - pr1 p = pr2 q - pr1 q + pr1 p - pr1 p : H5 ... = pr2 q - pr1 q : add_sub_cancel, abstr_of_lt H3 ⬝ ap neg_succ_of_nat (ap pred H6)⬝ (abstr_of_lt H4)⁻¹) definition int_equiv_iff (p q : ℕ × ℕ) : (p ≡ q) ↔ ((p ≡ p) × (q ≡ q) × (abstr p = abstr q)) := iff.intro (assume H : int_equiv p q, pair !int_equiv.refl (pair !int_equiv.refl (abstr_eq H))) (assume H : int_equiv p p × int_equiv q q × abstr p = abstr q, have H1 : abstr p = abstr q, from prod.pr2 (prod.pr2 H), int_equiv.trans (H1 ▸ int_equiv.symm (repr_abstr p)) (repr_abstr q)) definition eq_abstr_of_int_equiv_repr {a : ℤ} {p : ℕ × ℕ} (Hint_equiv : repr a ≡ p) : a = abstr p := calc a = abstr (repr a) : abstr_repr ... = abstr p : abstr_eq Hint_equiv definition eq_of_repr_int_equiv_repr {a b : ℤ} (H : repr a ≡ repr b) : a = b := calc a = abstr (repr a) : abstr_repr ... = abstr (repr b) : abstr_eq H ... = b : abstr_repr section local attribute abstr [reducible] local attribute dist [reducible] definition nat_abs_abstr (p : ℕ × ℕ) : nat_abs (abstr p) = dist (pr1 p) (pr2 p) := let m := pr1 p, n := pr2 p in sum.rec_on (@le_or_gt n m) (assume H : m ≥ n, calc nat_abs (abstr (m, n)) = nat_abs (of_nat (m - n)) : int.abstr_of_ge H ... = dist m n : dist_eq_sub_of_ge H) (assume H : m < n, calc nat_abs (abstr (m, n)) = nat_abs (neg_succ_of_nat (pred (n - m))) : int.abstr_of_lt H ... = succ (pred (n - m)) : rfl ... = n - m : succ_pred_of_pos (sub_pos_of_lt H) ... = dist m n : dist_eq_sub_of_le (le_of_lt H)) end definition cases_of_nat (a : ℤ) : (Σn : ℕ, a = of_nat n) ⊎ (Σn : ℕ, a = - of_nat n) := int.cases_on a (take n, sum.inl (sigma.mk n rfl)) (take n', sum.inr (sigma.mk (succ n') rfl)) definition cases_of_nat_succ (a : ℤ) : (Σn : ℕ, a = of_nat n) ⊎ (Σn : ℕ, a = - (of_nat (succ n))) := int.cases_on a (take m, sum.inl (sigma.mk _ rfl)) (take m, sum.inr (sigma.mk _ rfl)) definition by_cases_of_nat {P : ℤ → Type} (a : ℤ) (H1 : Πn : ℕ, P (of_nat n)) (H2 : Πn : ℕ, P (- of_nat n)) : P a := sum.rec_on (cases_of_nat a) (assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n) (assume H, obtain (n : ℕ) (H3 : a = -n), from H, H3⁻¹ ▸ H2 n) definition by_cases_of_nat_succ {P : ℤ → Type} (a : ℤ) (H1 : Πn : ℕ, P (of_nat n)) (H2 : Πn : ℕ, P (- of_nat (succ n))) : P a := sum.rec_on (cases_of_nat_succ a) (assume H, obtain (n : ℕ) (H3 : a = n), from H, H3⁻¹ ▸ H1 n) (assume H, obtain (n : ℕ) (H3 : a = -(succ n)), from H, H3⁻¹ ▸ H2 n) /- int is a ring -/ /- addition -/ definition padd (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p + pr1 q, pr2 p + pr2 q) definition repr_add (a b : ℤ) : repr (add a b) ≡ padd (repr a) (repr b) := int.cases_on a (take m, int.cases_on b (take n, !int_equiv.refl) (take n', have H1 : int_equiv (repr (add (of_nat m) (neg_succ_of_nat n'))) (m, succ n'), from !repr_sub_nat_nat, have H2 : padd (repr (of_nat m)) (repr (neg_succ_of_nat n')) = (m, 0 + succ n'), from rfl, (!zero_add ▸ H2)⁻¹ ▸ H1)) (take m', int.cases_on b (take n, have H1 : int_equiv (repr (add (neg_succ_of_nat m') (of_nat n))) (n, succ m'), from !repr_sub_nat_nat, have H2 : padd (repr (neg_succ_of_nat m')) (repr (of_nat n)) = (0 + n, succ m'), from rfl, (!zero_add ▸ H2)⁻¹ ▸ H1) (take n',!repr_sub_nat_nat)) definition padd_congr {p p' q q' : ℕ × ℕ} (Ha : p ≡ p') (Hb : q ≡ q') : padd p q ≡ padd p' q' := calc pr1 p + pr1 q + (pr2 p' + pr2 q') = pr1 p + pr2 p' + (pr1 q + pr2 q') : add.comm4 ... = pr2 p + pr1 p' + (pr1 q + pr2 q') : {Ha} ... = pr2 p + pr1 p' + (pr2 q + pr1 q') : {Hb} ... = pr2 p + pr2 q + (pr1 p' + pr1 q') : add.comm4 definition padd_comm (p q : ℕ × ℕ) : padd p q = padd q p := calc padd p q = (pr1 p + pr1 q, pr2 p + pr2 q) : rfl ... = (pr1 q + pr1 p, pr2 p + pr2 q) : add.comm ... = (pr1 q + pr1 p, pr2 q + pr2 p) : add.comm ... = padd q p : rfl definition padd_assoc (p q r : ℕ × ℕ) : padd (padd p q) r = padd p (padd q r) := calc padd (padd p q) r = (pr1 p + pr1 q + pr1 r, pr2 p + pr2 q + pr2 r) : rfl ... = (pr1 p + (pr1 q + pr1 r), pr2 p + pr2 q + pr2 r) : add.assoc ... = (pr1 p + (pr1 q + pr1 r), pr2 p + (pr2 q + pr2 r)) : add.assoc ... = padd p (padd q r) : rfl definition add.comm (a b : ℤ) : a + b = b + a := begin apply eq_of_repr_int_equiv_repr, apply int_equiv.trans, apply repr_add, apply int_equiv.symm, apply eq.subst (padd_comm (repr b) (repr a)), apply repr_add end definition add.assoc (a b c : ℤ) : a + b + c = a + (b + c) := assert H1 : repr (a + b + c) ≡ padd (padd (repr a) (repr b)) (repr c), from int_equiv.trans (repr_add (a + b) c) (padd_congr !repr_add !int_equiv.refl), assert H2 : repr (a + (b + c)) ≡ padd (repr a) (padd (repr b) (repr c)), from int_equiv.trans (repr_add a (b + c)) (padd_congr !int_equiv.refl !repr_add), begin apply eq_of_repr_int_equiv_repr, apply int_equiv.trans, apply H1, apply eq.subst (padd_assoc _ _ _)⁻¹, apply int_equiv.symm, apply H2 end definition add_zero (a : ℤ) : a + 0 = a := int.cases_on a (take m, rfl) (take m', rfl) definition zero_add (a : ℤ) : 0 + a = a := add.comm a 0 ▸ add_zero a /- negation -/ definition pneg (p : ℕ × ℕ) : ℕ × ℕ := (pr2 p, pr1 p) -- note: this is =, not just ≡ definition repr_neg (a : ℤ) : repr (- a) = pneg (repr a) := int.cases_on a (take m, nat.cases_on m rfl (take m', rfl)) (take m', rfl) definition pneg_congr {p p' : ℕ × ℕ} (H : p ≡ p') : pneg p ≡ pneg p' := inverse H definition pneg_pneg (p : ℕ × ℕ) : pneg (pneg p) = p := !prod.eta definition nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a := calc nat_abs (-a) = nat_abs (abstr (repr (-a))) : abstr_repr ... = nat_abs (abstr (pneg (repr a))) : repr_neg ... = dist (pr1 (pneg (repr a))) (pr2 (pneg (repr a))) : nat_abs_abstr ... = dist (pr2 (pneg (repr a))) (pr1 (pneg (repr a))) : dist.comm ... = nat_abs (abstr (repr a)) : nat_abs_abstr ... = nat_abs a : abstr_repr definition padd_pneg (p : ℕ × ℕ) : padd p (pneg p) ≡ (0, 0) := show pr1 p + pr2 p + 0 = pr2 p + pr1 p + 0, from !nat.add.comm ▸ rfl definition padd_padd_pneg (p q : ℕ × ℕ) : padd (padd p q) (pneg q) ≡ p := calc pr1 p + pr1 q + pr2 q + pr2 p = pr1 p + (pr1 q + pr2 q) + pr2 p : nat.add.assoc ... = pr1 p + (pr1 q + pr2 q + pr2 p) : nat.add.assoc ... = pr1 p + (pr2 q + pr1 q + pr2 p) : nat.add.comm ... = pr1 p + (pr2 q + pr2 p + pr1 q) : add.right_comm ... = pr1 p + (pr2 p + pr2 q + pr1 q) : nat.add.comm ... = pr2 p + pr2 q + pr1 q + pr1 p : nat.add.comm definition add.left_inv (a : ℤ) : -a + a = 0 := have H : repr (-a + a) ≡ repr 0, from calc repr (-a + a) ≡ padd (repr (neg a)) (repr a) : repr_add ... = padd (pneg (repr a)) (repr a) : repr_neg ... ≡ repr 0 : padd_pneg, eq_of_repr_int_equiv_repr H /- nat abs -/ definition pabs (p : ℕ × ℕ) : ℕ := dist (pr1 p) (pr2 p) definition pabs_congr {p q : ℕ × ℕ} (H : p ≡ q) : pabs p = pabs q := calc pabs p = nat_abs (abstr p) : nat_abs_abstr ... = nat_abs (abstr q) : abstr_eq H ... = pabs q : nat_abs_abstr definition nat_abs_eq_pabs_repr (a : ℤ) : nat_abs a = pabs (repr a) := calc nat_abs a = nat_abs (abstr (repr a)) : abstr_repr ... = pabs (repr a) : nat_abs_abstr definition nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := have H : nat_abs (a + b) = pabs (padd (repr a) (repr b)), from calc nat_abs (a + b) = pabs (repr (a + b)) : nat_abs_eq_pabs_repr ... = pabs (padd (repr a) (repr b)) : pabs_congr !repr_add, have H1 : nat_abs a = pabs (repr a), from !nat_abs_eq_pabs_repr, have H2 : nat_abs b = pabs (repr b), from !nat_abs_eq_pabs_repr, have H3 : pabs (padd (repr a) (repr b)) ≤ pabs (repr a) + pabs (repr b), from !dist_add_add_le_add_dist_dist, H⁻¹ ▸ H1⁻¹ ▸ H2⁻¹ ▸ H3 section local attribute nat_abs [reducible] definition mul_nat_abs (a b : ℤ) : nat_abs (a * b) = #nat (nat_abs a) * (nat_abs b) := int.cases_on a (take m, int.cases_on b (take n, rfl) (take n', !nat_abs_neg ▸ rfl)) (take m', int.cases_on b (take n, !nat_abs_neg ▸ rfl) (take n', rfl)) end /- multiplication -/ definition pmul (p q : ℕ × ℕ) : ℕ × ℕ := (pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) definition repr_neg_of_nat (m : ℕ) : repr (neg_of_nat m) = (0, m) := nat.cases_on m rfl (take m', rfl) -- note: we have =, not just ≡ definition repr_mul (a b : ℤ) : repr (mul a b) = pmul (repr a) (repr b) := int.cases_on a (take m, int.cases_on b (take n, (calc pmul (repr m) (repr n) = (m * n + 0 * 0, m * 0 + 0 * n) : rfl ... = (m * n + 0 * 0, m * 0 + 0) : zero_mul)⁻¹) (take n', (calc pmul (repr m) (repr (neg_succ_of_nat n')) = (m * 0 + 0 * succ n', m * succ n' + 0 * 0) : rfl ... = (m * 0 + 0, m * succ n' + 0 * 0) : zero_mul ... = repr (mul m (neg_succ_of_nat n')) : repr_neg_of_nat)⁻¹)) (take m', int.cases_on b (take n, (calc pmul (repr (neg_succ_of_nat m')) (repr n) = (0 * n + succ m' * 0, 0 * 0 + succ m' * n) : rfl ... = (0 + succ m' * 0, 0 * 0 + succ m' * n) : zero_mul ... = (0 + succ m' * 0, succ m' * n) : {!nat.zero_add} ... = repr (mul (neg_succ_of_nat m') n) : repr_neg_of_nat)⁻¹) (take n', (calc pmul (repr (neg_succ_of_nat m')) (repr (neg_succ_of_nat n')) = (0 + succ m' * succ n', 0 * succ n') : rfl ... = (succ m' * succ n', 0 * succ n') : nat.zero_add ... = (succ m' * succ n', 0) : zero_mul ... = repr (mul (neg_succ_of_nat m') (neg_succ_of_nat n')) : rfl)⁻¹)) definition int_equiv_mul_prep {xa ya xb yb xn yn xm ym : ℕ} (H1 : xa + yb = ya + xb) (H2 : xn + ym = yn + xm) : xa * xn + ya * yn + (xb * ym + yb * xm) = xa * yn + ya * xn + (xb * xm + yb * ym) := nat.add.cancel_right (calc xa*xn+ya*yn + (xb*ym+yb*xm) + (yb*xn+xb*yn + (xb*xn+yb*yn)) = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*ym+yb*xm + (xb*xn+yb*yn)) : add.comm4 ... = xa*xn+ya*yn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*ym+yb*xm)) : nat.add.comm ... = xa*xn+yb*xn + (ya*yn+xb*yn) + (xb*xn+xb*ym + (yb*yn+yb*xm)) : !congr_arg2 add.comm4 add.comm4 ... = ya*xn+xb*xn + (xa*yn+yb*yn) + (xb*yn+xb*xm + (yb*xn+yb*ym)) : by rewrite[-+mul.left_distrib,-+mul.right_distrib]; exact H1 ▸ H2 ▸ rfl ... = ya*xn+xa*yn + (xb*xn+yb*yn) + (xb*yn+yb*xn + (xb*xm+yb*ym)) : !congr_arg2 add.comm4 add.comm4 ... = xa*yn+ya*xn + (xb*xn+yb*yn) + (yb*xn+xb*yn + (xb*xm+yb*ym)) : !nat.add.comm ▸ !nat.add.comm ▸ rfl ... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xn+yb*yn + (xb*xm+yb*ym)) : add.comm4 ... = xa*yn+ya*xn + (yb*xn+xb*yn) + (xb*xm+yb*ym + (xb*xn+yb*yn)) : nat.add.comm ... = xa*yn+ya*xn + (xb*xm+yb*ym) + (yb*xn+xb*yn + (xb*xn+yb*yn)) : add.comm4) definition pmul_congr {p p' q q' : ℕ × ℕ} (H1 : p ≡ p') (H2 : q ≡ q') : pmul p q ≡ pmul p' q' := int_equiv_mul_prep H1 H2 definition pmul_comm (p q : ℕ × ℕ) : pmul p q = pmul q p := calc (pr1 p * pr1 q + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) = (pr1 q * pr1 p + pr2 p * pr2 q, pr1 p * pr2 q + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr1 p * pr2 q + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr2 q * pr1 p + pr2 p * pr1 q) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr2 q * pr1 p + pr1 q * pr2 p) : mul.comm ... = (pr1 q * pr1 p + pr2 q * pr2 p, pr1 q * pr2 p + pr2 q * pr1 p) : nat.add.comm definition mul.comm (a b : ℤ) : a * b = b * a := eq_of_repr_int_equiv_repr ((calc repr (a * b) = pmul (repr a) (repr b) : repr_mul ... = pmul (repr b) (repr a) : pmul_comm ... = repr (b * a) : repr_mul) ▸ !int_equiv.refl) private theorem pmul_assoc_prep {p1 p2 q1 q2 r1 r2 : ℕ} : ((p1*q1+p2*q2)*r1+(p1*q2+p2*q1)*r2, (p1*q1+p2*q2)*r2+(p1*q2+p2*q1)*r1) = (p1*(q1*r1+q2*r2)+p2*(q1*r2+q2*r1), p1*(q1*r2+q2*r1)+p2*(q1*r1+q2*r2)) := begin rewrite[+mul.left_distrib,+mul.right_distrib,*mul.assoc], rewrite (@add.comm4 (p1 * (q1 * r1)) (p2 * (q2 * r1)) (p1 * (q2 * r2)) (p2 * (q1 * r2))), rewrite (nat.add.comm (p2 * (q2 * r1)) (p2 * (q1 * r2))), rewrite (@add.comm4 (p1 * (q1 * r2)) (p2 * (q2 * r2)) (p1 * (q2 * r1)) (p2 * (q1 * r1))), rewrite (nat.add.comm (p2 * (q2 * r2)) (p2 * (q1 * r1))) end definition pmul_assoc (p q r: ℕ × ℕ) : pmul (pmul p q) r = pmul p (pmul q r) := pmul_assoc_prep definition mul.assoc (a b c : ℤ) : (a * b) * c = a * (b * c) := eq_of_repr_int_equiv_repr ((calc repr (a * b * c) = pmul (repr (a * b)) (repr c) : repr_mul ... = pmul (pmul (repr a) (repr b)) (repr c) : repr_mul ... = pmul (repr a) (pmul (repr b) (repr c)) : pmul_assoc ... = pmul (repr a) (repr (b * c)) : repr_mul ... = repr (a * (b * c)) : repr_mul) ▸ !int_equiv.refl) set_option pp.coercions true definition mul_one (a : ℤ) : a * 1 = a := eq_of_repr_int_equiv_repr (int_equiv_of_eq ((calc repr (a * 1) = pmul (repr a) (repr 1) : repr_mul ... = (pr1 (repr a), pr2 (repr a)) : by unfold [pmul, repr]; krewrite [*mul_zero, *mul_one, *nat.add_zero, *nat.zero_add] ... = repr a : prod.eta))) definition one_mul (a : ℤ) : 1 * a = a := mul.comm a 1 ▸ mul_one a private theorem mul_distrib_prep {a1 a2 b1 b2 c1 c2 : ℕ} : ((a1+b1)*c1+(a2+b2)*c2, (a1+b1)*c2+(a2+b2)*c1) = (a1*c1+a2*c2+(b1*c1+b2*c2), a1*c2+a2*c1+(b1*c2+b2*c1)) := by rewrite[+mul.right_distrib] ⬝ (!congr_arg2 !add.comm4 !add.comm4) definition mul.right_distrib (a b c : ℤ) : (a + b) * c = a * c + b * c := eq_of_repr_int_equiv_repr (calc repr ((a + b) * c) = pmul (repr (a + b)) (repr c) : repr_mul ... ≡ pmul (padd (repr a) (repr b)) (repr c) : pmul_congr !repr_add int_equiv.refl ... = padd (pmul (repr a) (repr c)) (pmul (repr b) (repr c)) : mul_distrib_prep ... = padd (repr (a * c)) (pmul (repr b) (repr c)) : {(repr_mul a c)⁻¹} ... = padd (repr (a * c)) (repr (b * c)) : repr_mul ... ≡ repr (a * c + b * c) : int_equiv.symm !repr_add) definition mul.left_distrib (a b c : ℤ) : a * (b + c) = a * b + a * c := calc a * (b + c) = (b + c) * a : mul.comm a (b + c) ... = b * a + c * a : mul.right_distrib b c a ... = a * b + c * a : {mul.comm b a} ... = a * b + a * c : {mul.comm c a} definition zero_ne_one : (0 : int) ≠ 1 := assume H : 0 = 1, show empty, from succ_ne_zero 0 ((of_nat.inj H)⁻¹) definition eq_zero_or_eq_zero_of_mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ⊎ b = 0 := have H2 : (nat_abs a) * (nat_abs b) = nat.zero, from calc (nat_abs a) * (nat_abs b) = (nat_abs (a * b)) : (mul_nat_abs a b)⁻¹ ... = (nat_abs 0) : {H} ... = nat.zero : nat_abs_of_nat nat.zero, have H3 : (nat_abs a) = nat.zero ⊎ (nat_abs b) = nat.zero, from eq_zero_or_eq_zero_of_mul_eq_zero H2, sum_of_sum_of_imp_of_imp H3 (assume H : (nat_abs a) = nat.zero, nat_abs_eq_zero H) (assume H : (nat_abs b) = nat.zero, nat_abs_eq_zero H) section open [classes] algebra protected definition integral_domain [instance] [reducible] : algebra.integral_domain int := ⦃algebra.integral_domain, add := add, add_assoc := add.assoc, zero := zero, zero_add := zero_add, add_zero := add_zero, neg := neg, add_left_inv := add.left_inv, add_comm := add.comm, mul := mul, mul_assoc := mul.assoc, one := (of_num 1), one_mul := one_mul, mul_one := mul_one, left_distrib := mul.left_distrib, right_distrib := mul.right_distrib, mul_comm := mul.comm, eq_zero_or_eq_zero_of_mul_eq_zero := @eq_zero_or_eq_zero_of_mul_eq_zero, is_hset_carrier := is_hset_of_decidable_eq⦄ end /- instantiate ring theorems to int -/ section port_algebra open [classes] algebra definition mul.left_comm : Πa b c : ℤ, a * (b * c) = b * (a * c) := algebra.mul.left_comm definition mul.right_comm : Πa b c : ℤ, (a * b) * c = (a * c) * b := algebra.mul.right_comm definition add.left_comm : Πa b c : ℤ, a + (b + c) = b + (a + c) := algebra.add.left_comm definition add.right_comm : Πa b c : ℤ, (a + b) + c = (a + c) + b := algebra.add.right_comm definition add.left_cancel : Π{a b c : ℤ}, a + b = a + c → b = c := @algebra.add.left_cancel _ _ definition add.right_cancel : Π{a b c : ℤ}, a + b = c + b → a = c := @algebra.add.right_cancel _ _ definition neg_add_cancel_left : Πa b : ℤ, -a + (a + b) = b := algebra.neg_add_cancel_left definition neg_add_cancel_right : Πa b : ℤ, a + -b + b = a := algebra.neg_add_cancel_right definition neg_eq_of_add_eq_zero : Π{a b : ℤ}, a + b = 0 → -a = b := @algebra.neg_eq_of_add_eq_zero _ _ definition neg_zero : -0 = 0 := algebra.neg_zero definition neg_neg : Πa : ℤ, -(-a) = a := algebra.neg_neg definition neg.inj : Π{a b : ℤ}, -a = -b → a = b := @algebra.neg.inj _ _ definition neg_eq_neg_iff_eq : Πa b : ℤ, -a = -b ↔ a = b := algebra.neg_eq_neg_iff_eq definition neg_eq_zero_iff_eq_zero : Πa : ℤ, -a = 0 ↔ a = 0 := algebra.neg_eq_zero_iff_eq_zero definition eq_neg_of_eq_neg : Π{a b : ℤ}, a = -b → b = -a := @algebra.eq_neg_of_eq_neg _ _ definition eq_neg_iff_eq_neg : Π{a b : ℤ}, a = -b ↔ b = -a := @algebra.eq_neg_iff_eq_neg _ _ definition add.right_inv : Πa : ℤ, a + -a = 0 := algebra.add.right_inv definition add_neg_cancel_left : Πa b : ℤ, a + (-a + b) = b := algebra.add_neg_cancel_left definition add_neg_cancel_right : Πa b : ℤ, a + b + -b = a := algebra.add_neg_cancel_right definition neg_add_rev : Πa b : ℤ, -(a + b) = -b + -a := algebra.neg_add_rev definition eq_add_neg_of_add_eq : Π{a b c : ℤ}, a + c = b → a = b + -c := @algebra.eq_add_neg_of_add_eq _ _ definition eq_neg_add_of_add_eq : Π{a b c : ℤ}, b + a = c → a = -b + c := @algebra.eq_neg_add_of_add_eq _ _ definition neg_add_eq_of_eq_add : Π{a b c : ℤ}, b = a + c → -a + b = c := @algebra.neg_add_eq_of_eq_add _ _ definition add_neg_eq_of_eq_add : Π{a b c : ℤ}, a = c + b → a + -b = c := @algebra.add_neg_eq_of_eq_add _ _ definition eq_add_of_add_neg_eq : Π{a b c : ℤ}, a + -c = b → a = b + c := @algebra.eq_add_of_add_neg_eq _ _ definition eq_add_of_neg_add_eq : Π{a b c : ℤ}, -b + a = c → a = b + c := @algebra.eq_add_of_neg_add_eq _ _ definition add_eq_of_eq_neg_add : Π{a b c : ℤ}, b = -a + c → a + b = c := @algebra.add_eq_of_eq_neg_add _ _ definition add_eq_of_eq_add_neg : Π{a b c : ℤ}, a = c + -b → a + b = c := @algebra.add_eq_of_eq_add_neg _ _ definition add_eq_iff_eq_neg_add : Πa b c : ℤ, a + b = c ↔ b = -a + c := @algebra.add_eq_iff_eq_neg_add _ _ definition add_eq_iff_eq_add_neg : Πa b c : ℤ, a + b = c ↔ a = c + -b := @algebra.add_eq_iff_eq_add_neg _ _ definition sub (a b : ℤ) : ℤ := algebra.sub a b infix - := int.sub definition sub_eq_add_neg : Πa b : ℤ, a - b = a + -b := algebra.sub_eq_add_neg definition sub_self : Πa : ℤ, a - a = 0 := algebra.sub_self definition sub_add_cancel : Πa b : ℤ, a - b + b = a := algebra.sub_add_cancel definition add_sub_cancel : Πa b : ℤ, a + b - b = a := algebra.add_sub_cancel definition eq_of_sub_eq_zero : Π{a b : ℤ}, a - b = 0 → a = b := @algebra.eq_of_sub_eq_zero _ _ definition eq_iff_sub_eq_zero : Πa b : ℤ, a = b ↔ a - b = 0 := algebra.eq_iff_sub_eq_zero definition zero_sub : Πa : ℤ, 0 - a = -a := algebra.zero_sub definition sub_zero : Πa : ℤ, a - 0 = a := algebra.sub_zero definition sub_neg_eq_add : Πa b : ℤ, a - (-b) = a + b := algebra.sub_neg_eq_add definition neg_sub : Πa b : ℤ, -(a - b) = b - a := algebra.neg_sub definition add_sub : Πa b c : ℤ, a + (b - c) = a + b - c := algebra.add_sub definition sub_add_eq_sub_sub_swap : Πa b c : ℤ, a - (b + c) = a - c - b := algebra.sub_add_eq_sub_sub_swap definition sub_eq_iff_eq_add : Πa b c : ℤ, a - b = c ↔ a = c + b := algebra.sub_eq_iff_eq_add definition eq_sub_iff_add_eq : Πa b c : ℤ, a = b - c ↔ a + c = b := algebra.eq_sub_iff_add_eq definition eq_iff_eq_of_sub_eq_sub : Π{a b c d : ℤ}, a - b = c - d → (a = b ↔ c = d) := @algebra.eq_iff_eq_of_sub_eq_sub _ _ definition eq_sub_of_add_eq : Π{a b c : ℤ}, a + c = b → a = b - c := @algebra.eq_sub_of_add_eq _ _ definition sub_eq_of_eq_add : Π{a b c : ℤ}, a = c + b → a - b = c := @algebra.sub_eq_of_eq_add _ _ definition eq_add_of_sub_eq : Π{a b c : ℤ}, a - c = b → a = b + c := @algebra.eq_add_of_sub_eq _ _ definition add_eq_of_eq_sub : Π{a b c : ℤ}, a = c - b → a + b = c := @algebra.add_eq_of_eq_sub _ _ definition sub_add_eq_sub_sub : Πa b c : ℤ, a - (b + c) = a - b - c := algebra.sub_add_eq_sub_sub definition neg_add_eq_sub : Πa b : ℤ, -a + b = b - a := algebra.neg_add_eq_sub definition neg_add : Πa b : ℤ, -(a + b) = -a + -b := algebra.neg_add definition sub_add_eq_add_sub : Πa b c : ℤ, a - b + c = a + c - b := algebra.sub_add_eq_add_sub definition sub_sub_ : Πa b c : ℤ, a - b - c = a - (b + c) := algebra.sub_sub definition add_sub_add_left_eq_sub : Πa b c : ℤ, (c + a) - (c + b) = a - b := algebra.add_sub_add_left_eq_sub definition eq_sub_of_add_eq' : Π{a b c : ℤ}, c + a = b → a = b - c := @algebra.eq_sub_of_add_eq' _ _ definition sub_eq_of_eq_add' : Π{a b c : ℤ}, a = b + c → a - b = c := @algebra.sub_eq_of_eq_add' _ _ definition eq_add_of_sub_eq' : Π{a b c : ℤ}, a - b = c → a = b + c := @algebra.eq_add_of_sub_eq' _ _ definition add_eq_of_eq_sub' : Π{a b c : ℤ}, b = c - a → a + b = c := @algebra.add_eq_of_eq_sub' _ _ definition ne_zero_of_mul_ne_zero_right : Π{a b : ℤ}, a * b ≠ 0 → a ≠ 0 := @algebra.ne_zero_of_mul_ne_zero_right _ _ definition ne_zero_of_mul_ne_zero_left : Π{a b : ℤ}, a * b ≠ 0 → b ≠ 0 := @algebra.ne_zero_of_mul_ne_zero_left _ _ definition dvd (a b : ℤ) : Type₀ := algebra.dvd a b notation a ∣ b := dvd a b definition dvd.intro : Π{a b c : ℤ} (H : a * c = b), a ∣ b := @algebra.dvd.intro _ _ definition dvd.intro_left : Π{a b c : ℤ} (H : c * a = b), a ∣ b := @algebra.dvd.intro_left _ _ definition exists_eq_mul_right_of_dvd : Π{a b : ℤ} (H : a ∣ b), Σc, b = a * c := @algebra.exists_eq_mul_right_of_dvd _ _ definition dvd.elim : Π{P : Type} {a b : ℤ} (H₁ : a ∣ b) (H₂ : Πc, b = a * c → P), P := @algebra.dvd.elim _ _ definition exists_eq_mul_left_of_dvd : Π{a b : ℤ} (H : a ∣ b), Σc, b = c * a := @algebra.exists_eq_mul_left_of_dvd _ _ definition dvd.elim_left : Π{P : Type} {a b : ℤ} (H₁ : a ∣ b) (H₂ : Πc, b = c * a → P), P := @algebra.dvd.elim_left _ _ definition dvd.refl : Πa : ℤ, (a ∣ a) := algebra.dvd.refl definition dvd.trans : Π{a b c : ℤ} (H₁ : a ∣ b) (H₂ : b ∣ c), a ∣ c := @algebra.dvd.trans _ _ definition eq_zero_of_zero_dvd : Π{a : ℤ} (H : 0 ∣ a), a = 0 := @algebra.eq_zero_of_zero_dvd _ _ definition dvd_zero : Πa : ℤ, a ∣ 0 := algebra.dvd_zero definition one_dvd : Πa : ℤ, 1 ∣ a := algebra.one_dvd definition dvd_mul_right : Πa b : ℤ, a ∣ a * b := algebra.dvd_mul_right definition dvd_mul_left : Πa b : ℤ, a ∣ b * a := algebra.dvd_mul_left definition dvd_mul_of_dvd_left : Π{a b : ℤ} (H : a ∣ b) (c : ℤ), a ∣ b * c := @algebra.dvd_mul_of_dvd_left _ _ definition dvd_mul_of_dvd_right : Π{a b : ℤ} (H : a ∣ b) (c : ℤ), a ∣ c * b := @algebra.dvd_mul_of_dvd_right _ _ definition mul_dvd_mul : Π{a b c d : ℤ}, a ∣ b → c ∣ d → a * c ∣ b * d := @algebra.mul_dvd_mul _ _ definition dvd_of_mul_right_dvd : Π{a b c : ℤ}, a * b ∣ c → a ∣ c := @algebra.dvd_of_mul_right_dvd _ _ definition dvd_of_mul_left_dvd : Π{a b c : ℤ}, a * b ∣ c → b ∣ c := @algebra.dvd_of_mul_left_dvd _ _ definition dvd_add : Π{a b c : ℤ}, a ∣ b → a ∣ c → a ∣ b + c := @algebra.dvd_add _ _ definition zero_mul : Πa : ℤ, 0 * a = 0 := algebra.zero_mul definition mul_zero : Πa : ℤ, a * 0 = 0 := algebra.mul_zero definition neg_mul_eq_neg_mul : Πa b : ℤ, -(a * b) = -a * b := algebra.neg_mul_eq_neg_mul definition neg_mul_eq_mul_neg : Πa b : ℤ, -(a * b) = a * -b := algebra.neg_mul_eq_mul_neg definition neg_mul_neg : Πa b : ℤ, -a * -b = a * b := algebra.neg_mul_neg definition neg_mul_comm : Πa b : ℤ, -a * b = a * -b := algebra.neg_mul_comm definition neg_eq_neg_one_mul : Πa : ℤ, -a = -1 * a := algebra.neg_eq_neg_one_mul definition mul_sub_left_distrib : Πa b c : ℤ, a * (b - c) = a * b - a * c := algebra.mul_sub_left_distrib definition mul_sub_right_distrib : Πa b c : ℤ, (a - b) * c = a * c - b * c := algebra.mul_sub_right_distrib definition mul_add_eq_mul_add_iff_sub_mul_add_eq : Πa b c d e : ℤ, a * e + c = b * e + d ↔ (a - b) * e + c = d := algebra.mul_add_eq_mul_add_iff_sub_mul_add_eq definition mul_self_sub_mul_self_eq : Πa b : ℤ, a * a - b * b = (a + b) * (a - b) := algebra.mul_self_sub_mul_self_eq definition mul_self_sub_one_eq : Πa : ℤ, a * a - 1 = (a + 1) * (a - 1) := algebra.mul_self_sub_one_eq definition dvd_neg_iff_dvd : Πa b : ℤ, a ∣ -b ↔ a ∣ b := algebra.dvd_neg_iff_dvd definition neg_dvd_iff_dvd : Πa b : ℤ, -a ∣ b ↔ a ∣ b := algebra.neg_dvd_iff_dvd definition dvd_sub : Πa b c : ℤ, a ∣ b → a ∣ c → a ∣ b - c := algebra.dvd_sub definition mul_ne_zero : Π{a b : ℤ}, a ≠ 0 → b ≠ 0 → a * b ≠ 0 := @algebra.mul_ne_zero _ _ definition eq_of_mul_eq_mul_right : Π{a b c : ℤ}, a ≠ 0 → b * a = c * a → b = c := @algebra.eq_of_mul_eq_mul_right _ _ definition eq_of_mul_eq_mul_left : Π{a b c : ℤ}, a ≠ 0 → a * b = a * c → b = c := @algebra.eq_of_mul_eq_mul_left _ _ definition mul_self_eq_mul_self_iff : Πa b : ℤ, a * a = b * b ↔ a = b ⊎ a = -b := algebra.mul_self_eq_mul_self_iff definition mul_self_eq_one_iff : Πa : ℤ, a * a = 1 ↔ a = 1 ⊎ a = -1 := algebra.mul_self_eq_one_iff definition dvd_of_mul_dvd_mul_left : Π{a b c : ℤ}, a ≠ 0 → a*b ∣ a*c → b ∣ c := @algebra.dvd_of_mul_dvd_mul_left _ _ definition dvd_of_mul_dvd_mul_right : Π{a b c : ℤ}, a ≠ 0 → b*a ∣ c*a → b ∣ c := @algebra.dvd_of_mul_dvd_mul_right _ _ end port_algebra /- additional properties -/ definition of_nat_sub_of_nat {m n : ℕ} (H : #nat m ≥ n) : of_nat m - of_nat n = of_nat (#nat m - n) := have H1 : m = (#nat m - n + n), from (nat.sub_add_cancel H)⁻¹, have H2 : m = (#nat m - n) + n, from ap of_nat H1, sub_eq_of_eq_add H2 definition neg_succ_of_nat_eq' (m : ℕ) : -[m +1] = -m - 1 := by rewrite [neg_succ_of_nat_eq, -of_nat_add_of_nat, neg_add] definition succ (a : ℤ) := a + (nat.succ zero) definition pred (a : ℤ) := a - (nat.succ zero) definition pred_succ (a : ℤ) : pred (succ a) = a := !sub_add_cancel definition succ_pred (a : ℤ) : succ (pred a) = a := !add_sub_cancel definition neg_succ (a : ℤ) : -succ a = pred (-a) := by rewrite [↑succ,neg_add] definition succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rewrite [neg_succ,succ_pred] definition neg_pred (a : ℤ) : -pred a = succ (-a) := by rewrite [↑pred,neg_sub,sub_eq_add_neg,add.comm] definition pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rewrite [neg_pred,pred_succ] definition pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n definition neg_nat_succ (n : ℕ) : -nat.succ n = pred (-n) := !neg_succ definition succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := !succ_neg_succ definition rec_nat_on [unfold 2] {P : ℤ → Type} (z : ℤ) (H0 : P 0) (Hsucc : Π⦃n : ℕ⦄, P n → P (succ n)) (Hpred : Π⦃n : ℕ⦄, P (-n) → P (-nat.succ n)) : P z := begin induction z with n n, {exact nat.rec_on n H0 Hsucc}, {induction n with m ih, exact Hpred H0, exact Hpred ih} end --the only computation rule of rec_nat_on which is not definitional definition rec_nat_on_neg {P : ℤ → Type} (n : nat) (H0 : P zero) (Hsucc : Π⦃n : nat⦄, P n → P (succ n)) (Hpred : Π⦃n : nat⦄, P (-n) → P (-nat.succ n)) : rec_nat_on (-nat.succ n) H0 Hsucc Hpred = Hpred (rec_nat_on (-n) H0 Hsucc Hpred) := nat.rec_on n rfl (λn H, rfl) end int
6433d8866139bc300328a6884a3dc4b3ddafee5d
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/data/bag.lean
ac5a101add7069849f3e1aef7e815360ff4aef83
[ "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
34,407
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 Finite bags. -/ import data.nat data.list.perm algebra.binary open nat quot list subtype binary function eq.ops open [decl] perm variable {A : Type} definition bag.setoid [instance] (A : Type) : setoid (list A) := setoid.mk (@perm A) (mk_equivalence (@perm A) (@perm.refl A) (@perm.symm A) (@perm.trans A)) definition bag (A : Type) : Type := quot (bag.setoid A) namespace bag definition of_list (l : list A) : bag A := ⟦l⟧ definition empty : bag A := of_list nil definition singleton (a : A) : bag A := of_list [a] definition insert (a : A) (b : bag A) : bag A := quot.lift_on b (λ l, ⟦a::l⟧) (λ l₁ l₂ h, quot.sound (perm.skip a h)) lemma insert_empty_eq_singleton (a : A) : insert a empty = singleton a := rfl definition insert.comm (a₁ a₂ : A) (b : bag A) : insert a₁ (insert a₂ b) = insert a₂ (insert a₁ b) := quot.induction_on b (λ l, quot.sound !perm.swap) definition append (b₁ b₂ : bag A) : bag A := quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦l₁++l₂⟧) (λ l₁ l₂ l₃ l₄ h₁ h₂, quot.sound (perm_app h₁ h₂)) infix ++ := append lemma append.comm (b₁ b₂ : bag A) : b₁ ++ b₂ = b₂ ++ b₁ := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, quot.sound !perm_app_comm) lemma append.assoc (b₁ b₂ b₃ : bag A) : (b₁ ++ b₂) ++ b₃ = b₁ ++ (b₂ ++ b₃) := quot.induction_on₃ b₁ b₂ b₃ (λ l₁ l₂ l₃, quot.sound (by rewrite list.append.assoc; apply perm.refl)) lemma append_empty_left (b : bag A) : empty ++ b = b := quot.induction_on b (λ l, quot.sound (by rewrite append_nil_left; apply perm.refl)) lemma append_empty_right (b : bag A) : b ++ empty = b := quot.induction_on b (λ l, quot.sound (by rewrite append_nil_right; apply perm.refl)) lemma append_insert_left (a : A) (b₁ b₂ : bag A) : insert a b₁ ++ b₂ = insert a (b₁ ++ b₂) := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, quot.sound (by rewrite append_cons; apply perm.refl)) lemma append_insert_right (a : A) (b₁ b₂ : bag A) : b₁ ++ insert a b₂ = insert a (b₁ ++ b₂) := calc b₁ ++ insert a b₂ = insert a b₂ ++ b₁ : append.comm ... = insert a (b₂ ++ b₁) : append_insert_left ... = insert a (b₁ ++ b₂) : append.comm protected lemma induction_on [recursor 3] {C : bag A → Prop} (b : bag A) (h₁ : C empty) (h₂ : ∀ a b, C b → C (insert a b)) : C b := quot.induction_on b (λ l, list.induction_on l h₁ (λ h t ih, h₂ h ⟦t⟧ ih)) section decidable_eq variable [decA : decidable_eq A] include decA open decidable definition has_decidable_eq [instance] (b₁ b₂ : bag A) : decidable (b₁ = b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match decidable_perm l₁ l₂ with | inl h := inl (quot.sound h) | inr h := inr (λ n, absurd (quot.exact n) h) end) end decidable_eq section count variable [decA : decidable_eq A] include decA definition count (a : A) (b : bag A) : nat := quot.lift_on b (λ l, count a l) (λ l₁ l₂ h, count_eq_of_perm h a) lemma count_empty (a : A) : count a empty = 0 := rfl lemma count_insert (a : A) (b : bag A) : count a (insert a b) = succ (count a b) := quot.induction_on b (λ l, begin unfold [insert, count], rewrite count_cons_eq end) lemma count_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : count a₁ (insert a₂ b) = count a₁ b := quot.induction_on b (λ l, begin unfold [insert, count], rewrite (count_cons_of_ne h) end) lemma count_singleton (a : A) : count a (singleton a) = 1 := begin rewrite [-insert_empty_eq_singleton, count_insert] end lemma count_append (a : A) (b₁ b₂ : bag A) : count a (append b₁ b₂) = count a b₁ + count a b₂ := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, begin unfold [append, count], rewrite list.count_append end) open perm decidable protected lemma ext {b₁ b₂ : bag A} : (∀ a, count a b₁ = count a b₂) → b₁ = b₂ := quot.induction_on₂ b₁ b₂ (λ l₁ l₂ (h : ∀ a, count a ⟦l₁⟧ = count a ⟦l₂⟧), have gen : ∀ (l₁ l₂ : list A), (∀ a, list.count a l₁ = list.count a l₂) → l₁ ~ l₂ | [] [] h₁ := !perm.refl | [] (a₂::s₂) h₁ := have list.count a₂ [] = list.count a₂ (a₂::s₂), from h₁ a₂, by rewrite [count_nil at this, count_cons_eq at this]; contradiction | (a::s₁) s₂ h₁ := have g₁ : list.count a (a::s₁) > 0, from count_gt_zero_of_mem !mem_cons, have list.count a (a::s₁) = list.count a s₂, from h₁ a, have list.count a s₂ > 0, by rewrite [-this]; exact g₁, have a ∈ s₂, from mem_of_count_gt_zero this, have ∃ l r, s₂ = l++(a::r), from mem_split this, obtain l r (e₁ : s₂ = l++(a::r)), from this, have ∀ a, list.count a s₁ = list.count a (l++r), from take a₁, have e₂ : list.count a₁ (a::s₁) = list.count a₁ (l++(a::r)), by rewrite -e₁; exact h₁ a₁, by_cases (suppose a₁ = a, begin rewrite [-this at e₂, list.count_append at e₂, *count_cons_eq at e₂, add_succ at e₂], injection e₂ with e₃, rewrite e₃, rewrite list.count_append end) (suppose a₁ ≠ a, by rewrite [list.count_append at e₂, *count_cons_of_ne this at e₂, e₂, list.count_append]), have ih : s₁ ~ l++r, from gen s₁ (l++r) this, calc a::s₁ ~ a::(l++r) : perm.skip a ih ... ~ l++(a::r) : perm_middle ... = s₂ : e₁, quot.sound (gen l₁ l₂ h)) definition insert.inj {a : A} {b₁ b₂ : bag A} : insert a b₁ = insert a b₂ → b₁ = b₂ := assume h, bag.ext (take x, have e : count x (insert a b₁) = count x (insert a b₂), by rewrite h, by_cases (suppose x = a, begin subst x, rewrite [*count_insert at e], injection e, assumption end) (suppose x ≠ a, begin rewrite [*count_insert_of_ne this at e], assumption end)) end count section extract open decidable variable [decA : decidable_eq A] include decA definition extract (a : A) (b : bag A) : bag A := quot.lift_on b (λ l, ⟦filter (λ c, c ≠ a) l⟧) (λ l₁ l₂ h, quot.sound (perm_filter h)) lemma extract_singleton (a : A) : extract a (singleton a) = empty := begin unfold [extract, singleton, of_list, filter], rewrite [if_neg (λ h : a ≠ a, absurd rfl h)] end lemma extract_insert (a : A) (b : bag A) : extract a (insert a b) = extract a b := quot.induction_on b (λ l, begin unfold [insert, extract], rewrite [@filter_cons_of_neg _ (λ c, c ≠ a) _ _ l (not_not_intro (eq.refl a))] end) lemma extract_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : extract a₁ (insert a₂ b) = insert a₂ (extract a₁ b) := quot.induction_on b (λ l, begin unfold [insert, extract], rewrite [@filter_cons_of_pos _ (λ c, c ≠ a₁) _ _ l (ne.symm h)] end) lemma count_extract (a : A) (b : bag A) : count a (extract a b) = 0 := bag.induction_on b rfl (λ c b ih, by_cases (suppose a = c, begin subst c, rewrite [extract_insert, ih] end) (suppose a ≠ c, begin rewrite [extract_insert_of_ne this, count_insert_of_ne this, ih] end)) lemma count_extract_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : count a₁ (extract a₂ b) = count a₁ b := bag.induction_on b rfl (take x b ih, by_cases (suppose x = a₁, begin subst x, rewrite [extract_insert_of_ne (ne.symm h), *count_insert, ih] end) (suppose x ≠ a₁, by_cases (suppose x = a₂, begin subst x, rewrite [extract_insert, ih, count_insert_of_ne h] end) (suppose x ≠ a₂, begin rewrite [count_insert_of_ne (ne.symm `x ≠ a₁`), extract_insert_of_ne (ne.symm this)], rewrite [count_insert_of_ne (ne.symm `x ≠ a₁`), ih] end))) end extract section erase variable [decA : decidable_eq A] include decA definition erase (a : A) (b : bag A) : bag A := quot.lift_on b (λ l, ⟦erase a l⟧) (λ l₁ l₂ h, quot.sound (erase_perm_erase_of_perm _ h)) lemma erase_empty (a : A) : erase a empty = empty := rfl lemma erase_insert (a : A) (b : bag A) : erase a (insert a b) = b := quot.induction_on b (λ l, quot.sound (by rewrite erase_cons_head; apply perm.refl)) lemma erase_insert_of_ne {a₁ a₂ : A} (h : a₁ ≠ a₂) (b : bag A) : erase a₁ (insert a₂ b) = insert a₂ (erase a₁ b) := quot.induction_on b (λ l, quot.sound (by rewrite (erase_cons_tail _ h); apply perm.refl)) end erase section member variable [decA : decidable_eq A] include decA definition mem (a : A) (b : bag A) := count a b > 0 infix ∈ := mem lemma mem_def (a : A) (b : bag A) : (a ∈ b) = (count a b > 0) := rfl lemma mem_insert (a : A) (b : bag A) : a ∈ insert a b := begin unfold mem, rewrite count_insert, exact dec_trivial end lemma mem_of_list_iff_mem (a : A) (l : list A) : a ∈ of_list l ↔ a ∈ l := iff.intro !mem_of_count_gt_zero !count_gt_zero_of_mem lemma count_of_list_eq_count (a : A) (l : list A) : count a (of_list l) = list.count a l := rfl end member section union_inter variable [decA : decidable_eq A] include decA open perm decidable private definition union_list (l₁ l₂ : list A) := erase_dup (l₁ ++ l₂) private lemma perm_union_list {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : union_list l₁ l₂ ~ union_list l₃ l₄ := perm_erase_dup_of_perm (perm_app h₁ h₂) private lemma nodup_union_list (l₁ l₂ : list A) : nodup (union_list l₁ l₂) := !nodup_erase_dup private definition not_mem_of_not_mem_union_list_left {a : A} {l₁ l₂ : list A} (h : a ∉ union_list l₁ l₂) : a ∉ l₁ := suppose a ∈ l₁, have a ∈ l₁ ++ l₂, from mem_append_left _ this, have a ∈ erase_dup (l₁ ++ l₂), from mem_erase_dup this, absurd this h private definition not_mem_of_not_mem_union_list_right {a : A} {l₁ l₂ : list A} (h : a ∉ union_list l₁ l₂) : a ∉ l₂ := suppose a ∈ l₂, have a ∈ l₁ ++ l₂, from mem_append_right _ this, have a ∈ erase_dup (l₁ ++ l₂), from mem_erase_dup this, absurd this h private definition gen : nat → A → list A | 0 a := nil | (n+1) a := a :: gen n a private lemma not_mem_gen_of_ne {a b : A} (h : a ≠ b) : ∀ n, a ∉ gen n b | 0 := !not_mem_nil | (n+1) := not_mem_cons_of_ne_of_not_mem h (not_mem_gen_of_ne n) private lemma count_gen : ∀ (a : A) (n : nat), list.count a (gen n a) = n | a 0 := rfl | a (n+1) := begin unfold gen, rewrite [count_cons_eq, count_gen] end private lemma count_gen_eq_zero_of_ne {a b : A} (h : a ≠ b) : ∀ n, list.count a (gen n b) = 0 | 0 := rfl | (n+1) := begin unfold gen, rewrite [count_cons_of_ne h, count_gen_eq_zero_of_ne] end private definition max_count (l₁ l₂ : list A) : list A → list A | [] := [] | (a::l) := if list.count a l₁ ≥ list.count a l₂ then gen (list.count a l₁) a ++ max_count l else gen (list.count a l₂) a ++ max_count l private definition min_count (l₁ l₂ : list A) : list A → list A | [] := [] | (a::l) := if list.count a l₁ ≤ list.count a l₂ then gen (list.count a l₁) a ++ min_count l else gen (list.count a l₂) a ++ min_count l private lemma not_mem_max_count_of_not_mem (l₁ l₂ : list A) : ∀ {a l}, a ∉ l → a ∉ max_count l₁ l₂ l | a [] h := !not_mem_nil | a (b::l) h := have ih : a ∉ max_count l₁ l₂ l, from not_mem_max_count_of_not_mem (not_mem_of_not_mem_cons h), have a ≠ b, from ne_of_not_mem_cons h, by_cases (suppose list.count b l₁ ≥ list.count b l₂, begin unfold max_count, rewrite [if_pos this], exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih end) (suppose ¬ list.count b l₁ ≥ list.count b l₂, begin unfold max_count, rewrite [if_neg this], exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih end) private lemma max_count_eq (l₁ l₂ : list A) : ∀ {a : A} {l : list A}, a ∈ l → nodup l → list.count a (max_count l₁ l₂ l) = max (list.count a l₁) (list.count a l₂) | a [] h₁ h₂ := absurd h₁ !not_mem_nil | a (b::l) h₁ h₂ := have nodup l, from nodup_of_nodup_cons h₂, have b ∉ l, from not_mem_of_nodup_cons h₂, or.elim (eq_or_mem_of_mem_cons h₁) (suppose a = b, have a ∉ l, by rewrite this; assumption, have a ∉ max_count l₁ l₂ l, from not_mem_max_count_of_not_mem l₁ l₂ this, by_cases (suppose i : list.count a l₁ ≥ list.count a l₂, begin unfold max_count, subst b, rewrite [if_pos i, list.count_append, count_gen, max_eq_left i, count_eq_zero_of_not_mem `a ∉ max_count l₁ l₂ l`] end) (suppose i : ¬ list.count a l₁ ≥ list.count a l₂, begin unfold max_count, subst b, rewrite [if_neg i, list.count_append, count_gen, max_eq_right_of_lt (lt_of_not_ge i), count_eq_zero_of_not_mem `a ∉ max_count l₁ l₂ l`] end)) (suppose a ∈ l, have a ≠ b, from suppose a = b, begin subst b, contradiction end, have ih : list.count a (max_count l₁ l₂ l) = max (list.count a l₁) (list.count a l₂), from max_count_eq `a ∈ l` `nodup l`, by_cases (suppose i : list.count b l₁ ≥ list.count b l₂, begin unfold max_count, rewrite [if_pos i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add] end) (suppose i : ¬ list.count b l₁ ≥ list.count b l₂, begin unfold max_count, rewrite [if_neg i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add] end)) private lemma not_mem_min_count_of_not_mem (l₁ l₂ : list A) : ∀ {a l}, a ∉ l → a ∉ min_count l₁ l₂ l | a [] h := !not_mem_nil | a (b::l) h := have ih : a ∉ min_count l₁ l₂ l, from not_mem_min_count_of_not_mem (not_mem_of_not_mem_cons h), have a ≠ b, from ne_of_not_mem_cons h, by_cases (suppose list.count b l₁ ≤ list.count b l₂, begin unfold min_count, rewrite [if_pos this], exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih end) (suppose ¬ list.count b l₁ ≤ list.count b l₂, begin unfold min_count, rewrite [if_neg this], exact not_mem_append (not_mem_gen_of_ne `a ≠ b` _) ih end) private lemma min_count_eq (l₁ l₂ : list A) : ∀ {a : A} {l : list A}, a ∈ l → nodup l → list.count a (min_count l₁ l₂ l) = min (list.count a l₁) (list.count a l₂) | a [] h₁ h₂ := absurd h₁ !not_mem_nil | a (b::l) h₁ h₂ := have nodup l, from nodup_of_nodup_cons h₂, have b ∉ l, from not_mem_of_nodup_cons h₂, or.elim (eq_or_mem_of_mem_cons h₁) (suppose a = b, have a ∉ l, by rewrite this; assumption, have a ∉ min_count l₁ l₂ l, from not_mem_min_count_of_not_mem l₁ l₂ this, by_cases (suppose i : list.count a l₁ ≤ list.count a l₂, begin unfold min_count, subst b, rewrite [if_pos i, list.count_append, count_gen, min_eq_left i, count_eq_zero_of_not_mem `a ∉ min_count l₁ l₂ l`] end) (suppose i : ¬ list.count a l₁ ≤ list.count a l₂, begin unfold min_count, subst b, rewrite [if_neg i, list.count_append, count_gen, min_eq_right (le_of_lt (lt_of_not_ge i)), count_eq_zero_of_not_mem `a ∉ min_count l₁ l₂ l`] end)) (suppose a ∈ l, have a ≠ b, from suppose a = b, by subst b; contradiction, have ih : list.count a (min_count l₁ l₂ l) = min (list.count a l₁) (list.count a l₂), from min_count_eq `a ∈ l` `nodup l`, by_cases (suppose i : list.count b l₁ ≤ list.count b l₂, begin unfold min_count, rewrite [if_pos i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add] end) (suppose i : ¬ list.count b l₁ ≤ list.count b l₂, begin unfold min_count, rewrite [if_neg i, -ih, list.count_append, count_gen_eq_zero_of_ne `a ≠ b`, zero_add] end)) private lemma perm_max_count_left {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : ∀ l, max_count l₁ l₂ l ~ max_count l₃ l₄ l | [] := by esimp | (a::l) := have e₁ : list.count a l₁ = list.count a l₃, from count_eq_of_perm h₁ a, have e₂ : list.count a l₂ = list.count a l₄, from count_eq_of_perm h₂ a, by_cases (suppose list.count a l₁ ≥ list.count a l₂, begin unfold max_count, rewrite [-e₁, -e₂, *if_pos this], exact perm_app !perm.refl !perm_max_count_left end) (suppose ¬ list.count a l₁ ≥ list.count a l₂, begin unfold max_count, rewrite [-e₁, -e₂, *if_neg this], exact perm_app !perm.refl !perm_max_count_left end) private lemma perm_app_left_comm (l₁ l₂ l₃ : list A) : l₁ ++ (l₂ ++ l₃) ~ l₂ ++ (l₁ ++ l₃) := calc l₁ ++ (l₂ ++ l₃) = (l₁ ++ l₂) ++ l₃ : list.append.assoc ... ~ (l₂ ++ l₁) ++ l₃ : perm_app !perm_app_comm !perm.refl ... = l₂ ++ (l₁ ++ l₃) : list.append.assoc private lemma perm_max_count_right {l r : list A} (h : l ~ r) : ∀ l₁ l₂, max_count l₁ l₂ l ~ max_count l₁ l₂ r := perm.induction_on h (λ l₁ l₂, !perm.refl) (λ x s₁ s₂ p ih l₁ l₂, by_cases (suppose i : list.count x l₁ ≥ list.count x l₂, begin unfold max_count, rewrite [*if_pos i], exact perm_app !perm.refl !ih end) (suppose i : ¬ list.count x l₁ ≥ list.count x l₂, begin unfold max_count, rewrite [*if_neg i], exact perm_app !perm.refl !ih end)) (λ x y l l₁ l₂, by_cases (suppose i₁ : list.count x l₁ ≥ list.count x l₂, by_cases (suppose i₂ : list.count y l₁ ≥ list.count y l₂, begin unfold max_count, unfold max_count, rewrite [*if_pos i₁, *if_pos i₂], apply perm_app_left_comm end) (suppose i₂ : ¬ list.count y l₁ ≥ list.count y l₂, begin unfold max_count, unfold max_count, rewrite [*if_pos i₁, *if_neg i₂], apply perm_app_left_comm end)) (suppose i₁ : ¬ list.count x l₁ ≥ list.count x l₂, by_cases (suppose i₂ : list.count y l₁ ≥ list.count y l₂, begin unfold max_count, unfold max_count, rewrite [*if_neg i₁, *if_pos i₂], apply perm_app_left_comm end) (suppose i₂ : ¬ list.count y l₁ ≥ list.count y l₂, begin unfold max_count, unfold max_count, rewrite [*if_neg i₁, *if_neg i₂], apply perm_app_left_comm end))) (λ s₁ s₂ s₃ p₁ p₂ ih₁ ih₂ l₁ l₂, perm.trans (ih₁ l₁ l₂) (ih₂ l₁ l₂)) private lemma perm_max_count {l₁ l₂ l₃ r₁ r₂ r₃ : list A} (p₁ : l₁ ~ r₁) (p₂ : l₂ ~ r₂) (p₃ : l₃ ~ r₃) : max_count l₁ l₂ l₃ ~ max_count r₁ r₂ r₃ := calc max_count l₁ l₂ l₃ ~ max_count r₁ r₂ l₃ : perm_max_count_left p₁ p₂ ... ~ max_count r₁ r₂ r₃ : perm_max_count_right p₃ private lemma perm_min_count_left {l₁ l₂ l₃ l₄ : list A} (h₁ : l₁ ~ l₃) (h₂ : l₂ ~ l₄) : ∀ l, min_count l₁ l₂ l ~ min_count l₃ l₄ l | [] := by esimp | (a::l) := have e₁ : list.count a l₁ = list.count a l₃, from count_eq_of_perm h₁ a, have e₂ : list.count a l₂ = list.count a l₄, from count_eq_of_perm h₂ a, by_cases (suppose list.count a l₁ ≤ list.count a l₂, begin unfold min_count, rewrite [-e₁, -e₂, *if_pos this], exact perm_app !perm.refl !perm_min_count_left end) (suppose ¬ list.count a l₁ ≤ list.count a l₂, begin unfold min_count, rewrite [-e₁, -e₂, *if_neg this], exact perm_app !perm.refl !perm_min_count_left end) private lemma perm_min_count_right {l r : list A} (h : l ~ r) : ∀ l₁ l₂, min_count l₁ l₂ l ~ min_count l₁ l₂ r := perm.induction_on h (λ l₁ l₂, !perm.refl) (λ x s₁ s₂ p ih l₁ l₂, by_cases (suppose i : list.count x l₁ ≤ list.count x l₂, begin unfold min_count, rewrite [*if_pos i], exact perm_app !perm.refl !ih end) (suppose i : ¬ list.count x l₁ ≤ list.count x l₂, begin unfold min_count, rewrite [*if_neg i], exact perm_app !perm.refl !ih end)) (λ x y l l₁ l₂, by_cases (suppose i₁ : list.count x l₁ ≤ list.count x l₂, by_cases (suppose i₂ : list.count y l₁ ≤ list.count y l₂, begin unfold min_count, unfold min_count, rewrite [*if_pos i₁, *if_pos i₂], apply perm_app_left_comm end) (suppose i₂ : ¬ list.count y l₁ ≤ list.count y l₂, begin unfold min_count, unfold min_count, rewrite [*if_pos i₁, *if_neg i₂], apply perm_app_left_comm end)) (suppose i₁ : ¬ list.count x l₁ ≤ list.count x l₂, by_cases (suppose i₂ : list.count y l₁ ≤ list.count y l₂, begin unfold min_count, unfold min_count, rewrite [*if_neg i₁, *if_pos i₂], apply perm_app_left_comm end) (suppose i₂ : ¬ list.count y l₁ ≤ list.count y l₂, begin unfold min_count, unfold min_count, rewrite [*if_neg i₁, *if_neg i₂], apply perm_app_left_comm end))) (λ s₁ s₂ s₃ p₁ p₂ ih₁ ih₂ l₁ l₂, perm.trans (ih₁ l₁ l₂) (ih₂ l₁ l₂)) private lemma perm_min_count {l₁ l₂ l₃ r₁ r₂ r₃ : list A} (p₁ : l₁ ~ r₁) (p₂ : l₂ ~ r₂) (p₃ : l₃ ~ r₃) : min_count l₁ l₂ l₃ ~ min_count r₁ r₂ r₃ := calc min_count l₁ l₂ l₃ ~ min_count r₁ r₂ l₃ : perm_min_count_left p₁ p₂ ... ~ min_count r₁ r₂ r₃ : perm_min_count_right p₃ definition union (b₁ b₂ : bag A) : bag A := quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦max_count l₁ l₂ (union_list l₁ l₂)⟧) (λ l₁ l₂ l₃ l₄ p₁ p₂, quot.sound (perm_max_count p₁ p₂ (perm_union_list p₁ p₂))) infix ∪ := union definition inter (b₁ b₂ : bag A) : bag A := quot.lift_on₂ b₁ b₂ (λ l₁ l₂, ⟦min_count l₁ l₂ (union_list l₁ l₂)⟧) (λ l₁ l₂ l₃ l₄ p₁ p₂, quot.sound (perm_min_count p₁ p₂ (perm_union_list p₁ p₂))) infix ∩ := inter lemma count_union (a : A) (b₁ b₂ : bag A) : count a (b₁ ∪ b₂) = max (count a b₁) (count a b₂) := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, by_cases (suppose a ∈ union_list l₁ l₂, !max_count_eq this !nodup_union_list) (suppose ¬ a ∈ union_list l₁ l₂, have ¬ a ∈ l₁, from not_mem_of_not_mem_union_list_left `¬ a ∈ union_list l₁ l₂`, have ¬ a ∈ l₂, from not_mem_of_not_mem_union_list_right `¬ a ∈ union_list l₁ l₂`, have n : ¬ a ∈ max_count l₁ l₂ (union_list l₁ l₂), from not_mem_max_count_of_not_mem l₁ l₂ `¬ a ∈ union_list l₁ l₂`, begin unfold [union, count], rewrite [count_eq_zero_of_not_mem `¬ a ∈ l₁`, count_eq_zero_of_not_mem `¬ a ∈ l₂`, max_self], rewrite [count_eq_zero_of_not_mem n] end)) lemma count_inter (a : A) (b₁ b₂ : bag A) : count a (b₁ ∩ b₂) = min (count a b₁) (count a b₂) := quot.induction_on₂ b₁ b₂ (λ l₁ l₂, by_cases (suppose a ∈ union_list l₁ l₂, !min_count_eq this !nodup_union_list) (suppose ¬ a ∈ union_list l₁ l₂, have ¬ a ∈ l₁, from not_mem_of_not_mem_union_list_left `¬ a ∈ union_list l₁ l₂`, have ¬ a ∈ l₂, from not_mem_of_not_mem_union_list_right `¬ a ∈ union_list l₁ l₂`, have n : ¬ a ∈ min_count l₁ l₂ (union_list l₁ l₂), from not_mem_min_count_of_not_mem l₁ l₂ `¬ a ∈ union_list l₁ l₂`, begin unfold [inter, count], rewrite [count_eq_zero_of_not_mem `¬ a ∈ l₁`, count_eq_zero_of_not_mem `¬ a ∈ l₂`, min_self], rewrite [count_eq_zero_of_not_mem n] end)) lemma union_comm (b₁ b₂ : bag A) : b₁ ∪ b₂ = b₂ ∪ b₁ := bag.ext (λ a, by rewrite [*count_union, max.comm]) lemma union_assoc (b₁ b₂ b₃ : bag A) : (b₁ ∪ b₂) ∪ b₃ = b₁ ∪ (b₂ ∪ b₃) := bag.ext (λ a, by rewrite [*count_union, max.assoc]) theorem union_left_comm (s₁ s₂ s₃ : bag A) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ lemma union_self (b : bag A) : b ∪ b = b := bag.ext (λ a, by rewrite [*count_union, max_self]) lemma union_empty (b : bag A) : b ∪ empty = b := bag.ext (λ a, by rewrite [*count_union, count_empty, max_zero]) lemma empty_union (b : bag A) : empty ∪ b = b := calc empty ∪ b = b ∪ empty : union_comm ... = b : union_empty lemma inter_comm (b₁ b₂ : bag A) : b₁ ∩ b₂ = b₂ ∩ b₁ := bag.ext (λ a, by rewrite [*count_inter, min.comm]) lemma inter_assoc (b₁ b₂ b₃ : bag A) : (b₁ ∩ b₂) ∩ b₃ = b₁ ∩ (b₂ ∩ b₃) := bag.ext (λ a, by rewrite [*count_inter, min.assoc]) theorem inter_left_comm (s₁ s₂ s₃ : bag A) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ lemma inter_self (b : bag A) : b ∩ b = b := bag.ext (λ a, by rewrite [*count_inter, min_self]) lemma inter_empty (b : bag A) : b ∩ empty = empty := bag.ext (λ a, by rewrite [*count_inter, count_empty, min_zero]) lemma empty_inter (b : bag A) : empty ∩ b = empty := calc empty ∩ b = b ∩ empty : inter_comm ... = empty : inter_empty lemma append_union_inter (b₁ b₂ : bag A) : (b₁ ∪ b₂) ++ (b₁ ∩ b₂) = b₁ ++ b₂ := bag.ext (λ a, begin rewrite [*count_append, count_inter, count_union], apply (or.elim (lt_or_ge (count a b₁) (count a b₂))), { intro H, rewrite [min_eq_left_of_lt H, max_eq_right_of_lt H, add.comm] }, { intro H, rewrite [min_eq_right H, max_eq_left H, add.comm] } end) lemma inter_left_distrib (b₁ b₂ b₃ : bag A) : b₁ ∩ (b₂ ∪ b₃) = (b₁ ∩ b₂) ∪ (b₁ ∩ b₃) := bag.ext (λ a, begin rewrite [*count_inter, *count_union, *count_inter], apply (@by_cases (count a b₁ ≤ count a b₂)), { intro H₁₂, apply (@by_cases (count a b₂ ≤ count a b₃)), { intro H₂₃, have H₁₃ : count a b₁ ≤ count a b₃, from le.trans H₁₂ H₂₃, rewrite [max_eq_right H₂₃, min_eq_left H₁₂, min_eq_left H₁₃, max_self]}, { intro H₂₃, rewrite [min_eq_left H₁₂, max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃) ], apply (@by_cases (count a b₁ ≤ count a b₃)), { intro H₁₃, rewrite [min_eq_left H₁₃, max_self, min_eq_left H₁₂] }, { intro H₁₃, rewrite [min.comm (count a b₁) (count a b₃), min_eq_left_of_lt (lt_of_not_ge H₁₃), min_eq_left H₁₂, max.comm, max_eq_right_of_lt (lt_of_not_ge H₁₃)]}}}, { intro H₁₂, apply (@by_cases (count a b₂ ≤ count a b₃)), { intro H₂₃, rewrite [max_eq_right H₂₃], apply (@by_cases (count a b₁ ≤ count a b₃)), { intro H₁₃, rewrite [min_eq_left H₁₃, min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂), max_eq_right_of_lt (lt_of_not_ge H₁₂)] }, { intro H₁₃, rewrite [min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₃), min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂), max_eq_right H₂₃] } }, { intro H₂₃, have H₁₃ : count a b₁ > count a b₃, from lt.trans (lt_of_not_ge H₂₃) (lt_of_not_ge H₁₂), rewrite [max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃), min.comm, min_eq_left_of_lt (lt_of_not_ge H₁₂)], rewrite [min.comm, min_eq_left_of_lt H₁₃, max.comm, max_eq_right_of_lt (lt_of_not_ge H₂₃)] } } end) lemma inter_right_distrib (b₁ b₂ b₃ : bag A) : (b₁ ∪ b₂) ∩ b₃ = (b₁ ∩ b₃) ∪ (b₂ ∩ b₃) := calc (b₁ ∪ b₂) ∩ b₃ = b₃ ∩ (b₁ ∪ b₂) : inter_comm ... = (b₃ ∩ b₁) ∪ (b₃ ∩ b₂) : inter_left_distrib ... = (b₁ ∩ b₃) ∪ (b₃ ∩ b₂) : inter_comm ... = (b₁ ∩ b₃) ∪ (b₂ ∩ b₃) : inter_comm end union_inter section subbag variable [decA : decidable_eq A] include decA definition subbag (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix ⊆ := subbag lemma subbag.refl (b : bag A) : b ⊆ b := take a, !le.refl lemma subbag.trans {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₂ → b₂ ⊆ b₃ → b₁ ⊆ b₃ := assume h₁ h₂, take a, le.trans (h₁ a) (h₂ a) lemma subbag.antisymm {b₁ b₂ : bag A} : b₁ ⊆ b₂ → b₂ ⊆ b₁ → b₁ = b₂ := assume h₁ h₂, bag.ext (take a, le.antisymm (h₁ a) (h₂ a)) lemma count_le_of_subbag {b₁ b₂ : bag A} : b₁ ⊆ b₂ → ∀ a, count a b₁ ≤ count a b₂ := assume h, h lemma subbag.intro {b₁ b₂ : bag A} : (∀ a, count a b₁ ≤ count a b₂) → b₁ ⊆ b₂ := assume h, h lemma empty_subbag (b : bag A) : empty ⊆ b := subbag.intro (take a, !zero_le) lemma eq_empty_of_subbag_empty {b : bag A} : b ⊆ empty → b = empty := assume h, subbag.antisymm h (empty_subbag b) lemma union_subbag_of_subbag_of_subbag {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₃ → b₂ ⊆ b₃ → b₁ ∪ b₂ ⊆ b₃ := assume h₁ h₂, subbag.intro (λ a, calc count a (b₁ ∪ b₂) = max (count a b₁) (count a b₂) : by rewrite count_union ... ≤ count a b₃ : max_le (h₁ a) (h₂ a)) lemma subbag_inter_of_subbag_of_subbag {b₁ b₂ b₃ : bag A} : b₁ ⊆ b₂ → b₁ ⊆ b₃ → b₁ ⊆ b₂ ∩ b₃ := assume h₁ h₂, subbag.intro (λ a, calc count a b₁ ≤ min (count a b₂) (count a b₃) : le_min (h₁ a) (h₂ a) ... = count a (b₂ ∩ b₃) : by rewrite count_inter) lemma subbag_union_left (b₁ b₂ : bag A) : b₁ ⊆ b₁ ∪ b₂ := subbag.intro (take a, by rewrite [count_union]; apply le_max_left) lemma subbag_union_right (b₁ b₂ : bag A) : b₂ ⊆ b₁ ∪ b₂ := subbag.intro (take a, by rewrite [count_union]; apply le_max_right) lemma inter_subbag_left (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₁ := subbag.intro (take a, by rewrite [count_inter]; apply min_le_left) lemma inter_subbag_right (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₂ := subbag.intro (take a, by rewrite [count_inter]; apply min_le_right) lemma subbag_append_left (b₁ b₂ : bag A) : b₁ ⊆ b₁ ++ b₂ := subbag.intro (take a, by rewrite [count_append]; apply le_add_right) lemma subbag_append_right (b₁ b₂ : bag A) : b₂ ⊆ b₁ ++ b₂ := subbag.intro (take a, by rewrite [count_append]; apply le_add_left) lemma inter_subbag_union (b₁ b₂ : bag A) : b₁ ∩ b₂ ⊆ b₁ ∪ b₂ := subbag.trans (inter_subbag_left b₁ b₂) (subbag_union_left b₁ b₂) open decidable lemma union_subbag_append (b₁ b₂ : bag A) : b₁ ∪ b₂ ⊆ b₁ ++ b₂ := subbag.intro (take a, begin rewrite [count_append, count_union], exact (or.elim !lt_or_ge) (suppose count a b₁ < count a b₂, by rewrite [max_eq_right_of_lt this]; apply le_add_left) (suppose count a b₁ ≥ count a b₂, by rewrite [max_eq_left this]; apply le_add_right) end) lemma subbag_insert (a : A) (b : bag A) : b ⊆ insert a b := subbag.intro (take x, by_cases (suppose x = a, by rewrite [this, count_insert]; apply le_succ) (suppose x ≠ a, by rewrite [count_insert_of_ne this])) lemma mem_of_subbag_of_mem {a : A} {b₁ b₂ : bag A} : b₁ ⊆ b₂ → a ∈ b₁ → a ∈ b₂ := assume h₁ h₂, have count a b₁ ≤ count a b₂, from count_le_of_subbag h₁ a, have count a b₁ > 0, from h₂, show count a b₂ > 0, from lt_of_lt_of_le `0 < count a b₁` `count a b₁ ≤ count a b₂` lemma extract_subbag (a : A) (b : bag A) : extract a b ⊆ b := subbag.intro (take x, by_cases (suppose x = a, by rewrite [this, count_extract]; apply zero_le) (suppose x ≠ a, by rewrite [count_extract_of_ne this])) open bool private definition subcount : list A → list A → bool | [] l₂ := tt | (a::l₁) l₂ := if list.count a (a::l₁) ≤ list.count a l₂ then subcount l₁ l₂ else ff private lemma all_of_subcount_eq_tt : ∀ {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ | [] l₂ h := take x, !zero_le | (a::l₁) l₂ h := take x, have subcount l₁ l₂ = tt, from by_contradiction (suppose subcount l₁ l₂ ≠ tt, have subcount l₁ l₂ = ff, from eq_ff_of_ne_tt this, begin unfold subcount at h, rewrite [this at h, if_t_t at h], contradiction end), have ih : ∀ a, list.count a l₁ ≤ list.count a l₂, from all_of_subcount_eq_tt this, have i : list.count a (a::l₁) ≤ list.count a l₂, from by_contradiction (suppose ¬ list.count a (a::l₁) ≤ list.count a l₂, begin unfold subcount at h, rewrite [if_neg this at h], contradiction end), by_cases (suppose x = a, by rewrite this; apply i) (suppose x ≠ a, by rewrite [list.count_cons_of_ne this]; apply ih) private lemma ex_of_subcount_eq_ff : ∀ {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ | [] l₂ h := by contradiction | (a::l₁) l₂ h := by_cases (suppose i : list.count a (a::l₁) ≤ list.count a l₂, have subcount l₁ l₂ = ff, from by_contradiction (suppose subcount l₁ l₂ ≠ ff, have subcount l₁ l₂ = tt, from eq_tt_of_ne_ff this, begin unfold subcount at h, rewrite [if_pos i at h, this at h], contradiction end), have ih : ∃ a, ¬ list.count a l₁ ≤ list.count a l₂, from ex_of_subcount_eq_ff this, obtain w hw, from ih, by_cases (suppose w = a, begin subst w, existsi a, rewrite list.count_cons_eq, apply not_lt_of_ge, apply le_of_lt (lt_of_not_ge hw) end) (suppose w ≠ a, exists.intro w (by rewrite (list.count_cons_of_ne `w ≠ a`); exact hw))) (suppose ¬ list.count a (a::l₁) ≤ list.count a l₂, exists.intro a this) definition decidable_subbag [instance] (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quot.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂ with | tt := suppose subcount l₁ l₂ = tt, inl (all_of_subcount_eq_tt this) | ff := suppose subcount l₁ l₂ = ff, inr (suppose h : (∀ a, list.count a l₁ ≤ list.count a l₂), obtain w hw, from ex_of_subcount_eq_ff `subcount l₁ l₂ = ff`, absurd (h w) hw) end rfl) end subbag end bag
d869ca1b6d1e2ae9af456d389d488c6718a67ed4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/projective_space/subspace.lean
cfd0e70c8d05fbd6cce49583830677f9d6045a5e
[ "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
8,305
lean
/- Copyright (c) 2022 Michael Blyth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Blyth -/ import linear_algebra.projective_space.independence /-! # Subspaces of Projective Space In this file we define subspaces of a projective space, and show that the subspaces of a projective space form a complete lattice under inclusion. ## Implementation Details A subspace of a projective space ℙ K V is defined to be a structure consisting of a subset of ℙ K V such that if two nonzero vectors in V determine points in ℙ K V which are in the subset, and the sum of the two vectors is nonzero, then the point determined by the sum of the two vectors is also in the subset. ## Results - There is a Galois insertion between the subsets of points of a projective space and the subspaces of the projective space, which is given by taking the span of the set of points. - The subspaces of a projective space form a complete lattice under inclusion. # Future Work - Show that there is a one-to-one order-preserving correspondence between subspaces of a projective space and the submodules of the underlying vector space. -/ variables (K V : Type*) [field K] [add_comm_group V] [module K V] namespace projectivization /-- A subspace of a projective space is a structure consisting of a set of points such that: If two nonzero vectors determine points which are in the set, and the sum of the two vectors is nonzero, then the point determined by the sum is also in the set. -/ @[ext] structure subspace := (carrier : set (ℙ K V)) (mem_add' (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0) : mk K v hv ∈ carrier → mk K w hw ∈ carrier → mk K (v + w) (hvw) ∈ carrier) namespace subspace variables {K V} instance : set_like (subspace K V) (ℙ K V) := { coe := carrier, coe_injective' := λ A B, by { cases A, cases B, simp } } @[simp] lemma mem_carrier_iff (A : subspace K V) (x : ℙ K V) : x ∈ A.carrier ↔ x ∈ A := iff.refl _ lemma mem_add (T : subspace K V) (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0) : projectivization.mk K v hv ∈ T → projectivization.mk K w hw ∈ T → projectivization.mk K (v + w) (hvw) ∈ T := T.mem_add' v w hv hw hvw /-- The span of a set of points in a projective space is defined inductively to be the set of points which contains the original set, and contains all points determined by the (nonzero) sum of two nonzero vectors, each of which determine points in the span. -/ inductive span_carrier (S : set (ℙ K V)) : set (ℙ K V) | of (x : ℙ K V) (hx : x ∈ S) : span_carrier x | mem_add (v w : V) (hv : v ≠ 0) (hw : w ≠ 0) (hvw : v + w ≠ 0) : span_carrier (projectivization.mk K v hv) → span_carrier (projectivization.mk K w hw) → span_carrier (projectivization.mk K (v + w) (hvw)) /-- The span of a set of points in projective space is a subspace. -/ def span (S : set (ℙ K V)) : subspace K V := { carrier := span_carrier S, mem_add' := λ v w hv hw hvw, span_carrier.mem_add v w hv hw hvw } /-- The span of a set of points contains the set of points. -/ lemma subset_span (S : set (ℙ K V)) : S ⊆ span S := λ x hx, span_carrier.of _ hx /-- The span of a set of points is a Galois insertion between sets of points of a projective space and subspaces of the projective space. -/ def gi : galois_insertion (span : set (ℙ K V) → subspace K V) coe := { choice := λ S hS, span S, gc := λ A B, ⟨λ h, le_trans (subset_span _) h, begin intros h x hx, induction hx, { apply h, assumption }, { apply B.mem_add, assumption' } end⟩, le_l_u := λ S, subset_span _, choice_eq := λ _ _, rfl } /-- The span of a subspace is the subspace. -/ @[simp] lemma span_coe (W : subspace K V) : span ↑W = W := galois_insertion.l_u_eq gi W /-- The infimum of two subspaces exists. -/ instance has_inf : has_inf (subspace K V) := ⟨λ A B, ⟨A ⊓ B, λ v w hv hw hvw h1 h2, ⟨A.mem_add _ _ hv hw _ h1.1 h2.1, B.mem_add _ _ hv hw _ h1.2 h2.2⟩⟩⟩ /-- Infimums of arbitrary collections of subspaces exist. -/ instance has_Inf : has_Inf (subspace K V) := ⟨λ A, ⟨Inf (coe '' A), λ v w hv hw hvw h1 h2 t, begin rintro ⟨s, hs, rfl⟩, exact s.mem_add v w hv hw _ (h1 s ⟨s, hs, rfl⟩) (h2 s ⟨s, hs, rfl⟩), end⟩⟩ /-- The subspaces of a projective space form a complete lattice. -/ instance : complete_lattice (subspace K V) := { inf_le_left := λ A B x hx, by exact hx.1, inf_le_right := λ A B x hx, by exact hx.2, le_inf := λ A B C h1 h2 x hx, ⟨h1 hx, h2 hx⟩, ..(infer_instance : has_inf _), ..complete_lattice_of_Inf (subspace K V) begin refine λ s, ⟨λ a ha x hx, (hx _ ⟨a, ha, rfl⟩), λ a ha x hx E, _⟩, rintros ⟨E, hE, rfl⟩, exact (ha hE hx) end } instance subspace_inhabited : inhabited (subspace K V) := { default := ⊤ } /-- The span of the empty set is the bottom of the lattice of subspaces. -/ @[simp] lemma span_empty : span (∅ : set (ℙ K V)) = ⊥ := gi.gc.l_bot /-- The span of the entire projective space is the top of the lattice of subspaces. -/ @[simp] lemma span_univ : span (set.univ : set (ℙ K V)) = ⊤ := by { rw [eq_top_iff, set_like.le_def], intros x hx, exact subset_span _ (set.mem_univ x) } /-- The span of a set of points is contained in a subspace if and only if the set of points is contained in the subspace. -/ lemma span_le_subspace_iff {S : set (ℙ K V)} {W : subspace K V} : span S ≤ W ↔ S ⊆ W := gi.gc S W /-- If a set of points is a subset of another set of points, then its span will be contained in the span of that set. -/ @[mono] lemma monotone_span : monotone (span : set (ℙ K V) → subspace K V) := gi.gc.monotone_l lemma subset_span_trans {S T U : set (ℙ K V)} (hST : S ⊆ span T) (hTU : T ⊆ span U) : S ⊆ span U := gi.gc.le_u_l_trans hST hTU /-- The supremum of two subspaces is equal to the span of their union. -/ lemma span_union (S T : set (ℙ K V)) : span (S ∪ T) = span S ⊔ span T := (@gi K V _ _ _).gc.l_sup /-- The supremum of a collection of subspaces is equal to the span of the union of the collection. -/ lemma span_Union {ι} (s : ι → set (ℙ K V)) : span (⋃ i, s i) = ⨆ i, span (s i) := (@gi K V _ _ _).gc.l_supr /-- The supremum of a subspace and the span of a set of points is equal to the span of the union of the subspace and the set of points. -/ lemma sup_span {S : set (ℙ K V)} {W : subspace K V} : W ⊔ span S = span (W ∪ S) := by rw [span_union, span_coe] lemma span_sup {S : set (ℙ K V)} {W : subspace K V}: span S ⊔ W = span (S ∪ W) := by rw [span_union, span_coe] /-- A point in a projective space is contained in the span of a set of points if and only if the point is contained in all subspaces of the projective space which contain the set of points. -/ lemma mem_span {S : set (ℙ K V)} (u : ℙ K V) : u ∈ span S ↔ ∀ (W : subspace K V), S ⊆ W → u ∈ W := by { simp_rw ← span_le_subspace_iff, exact ⟨λ hu W hW, hW hu, λ W, W (span S) (le_refl _)⟩ } /-- The span of a set of points in a projective space is equal to the infimum of the collection of subspaces which contain the set. -/ lemma span_eq_Inf {S : set (ℙ K V)} : span S = Inf {W | S ⊆ W} := begin ext, simp_rw [mem_carrier_iff, mem_span x], refine ⟨λ hx, _, λ hx W hW, _⟩, { rintros W ⟨T, ⟨hT, rfl⟩⟩, exact (hx T hT) }, { exact (@Inf_le _ _ {W : subspace K V | S ⊆ ↑W} W hW) x hx }, end /-- If a set of points in projective space is contained in a subspace, and that subspace is contained in the span of the set of points, then the span of the set of points is equal to the subspace. -/ lemma span_eq_of_le {S : set (ℙ K V)} {W : subspace K V} (hS : S ⊆ W) (hW : W ≤ span S) : span S = W := le_antisymm (span_le_subspace_iff.mpr hS) hW /-- The spans of two sets of points in a projective space are equal if and only if each set of points is contained in the span of the other set. -/ lemma span_eq_span_iff {S T : set (ℙ K V)} : span S = span T ↔ S ⊆ span T ∧ T ⊆ span S := ⟨λ h, ⟨h ▸ subset_span S, h.symm ▸ subset_span T⟩, λ h, le_antisymm (span_le_subspace_iff.2 h.1) (span_le_subspace_iff.2 h.2)⟩ end subspace end projectivization
a7452f6dc5f6d52ecf9b1579cc5f71f1945942d9
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/converter/old_conv.lean
80ee915f024b64cd1c7874bf2d548ae82bbf0224
[ "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
9,284
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Converter monad for building simplifiers. -/ import category.basic open tactic meta structure old_conv_result (α : Type) := (val : α) (rhs : expr) (proof : option expr) meta def old_conv (α : Type) : Type := name → expr → tactic (old_conv_result α) namespace old_conv meta def lhs : old_conv expr := λ r e, return ⟨e, e, none⟩ meta def change (new_p : pexpr) : old_conv unit := λ r e, do e_type ← infer_type e, new_e ← to_expr ``(%%new_p : %%e_type), unify e new_e, return ⟨(), new_e, none⟩ protected meta def pure {α : Type} : α → old_conv α := λ a r e, return ⟨a, e, none⟩ private meta def join_proofs (r : name) (o₁ o₂ : option expr) : tactic (option expr) := match o₁, o₂ with | none, _ := return o₂ | _, none := return o₁ | some p₁, some p₂ := do env ← get_env, match env.trans_for r with | some trans := do pr ← mk_app trans [p₁, p₂], return $ some pr | none := fail format!"converter failed, relation '{r}' is not transitive" end end protected meta def seq {α β : Type} (c₁ : old_conv (α → β)) (c₂ : old_conv α) : old_conv β := λ r e, do ⟨fn, e₁, pr₁⟩ ← c₁ r e, ⟨a, e₂, pr₂⟩ ← c₂ r e₁, pr ← join_proofs r pr₁ pr₂, return ⟨fn a, e₂, pr⟩ protected meta def fail {α β : Type} [has_to_format β] (msg : β) : old_conv α := λ r e, tactic.fail msg protected meta def failed {α : Type} : old_conv α := λ r e, tactic.failed protected meta def orelse {α : Type} (c₁ : old_conv α) (c₂ : old_conv α) : old_conv α := λ r e, c₁ r e <|> c₂ r e protected meta def map {α β : Type} (f : α → β) (c : old_conv α) : old_conv β := λ r e, do ⟨a, e₁, pr⟩ ← c r e, return ⟨f a, e₁, pr⟩ protected meta def bind {α β : Type} (c₁ : old_conv α) (c₂ : α → old_conv β) : old_conv β := λ r e, has_bind.bind (c₁ r e) (λ⟨a, e₁, pr₁⟩, has_bind.bind (c₂ a r e₁) (λ⟨b, e₂, pr₂⟩, has_bind.bind (join_proofs r pr₁ pr₂) (λpr, return ⟨b, e₂, pr⟩))) /- do -- wrong bind instance something with `name`? ⟨a, e₁, pr₁⟩ ← c₁ r e, ⟨b, e₂, pr₂⟩ ← c₂ a r e₁, pr ← join_proofs r pr₁ pr₂, return ⟨b, e₂, pr⟩ -/ meta instance : monad old_conv := { map := @old_conv.map, pure := @old_conv.pure, bind := @old_conv.bind } meta instance : alternative old_conv := { failure := @old_conv.failed, orelse := @old_conv.orelse, ..old_conv.monad } meta def whnf (md : transparency := reducible) : old_conv unit := λ r e, do n ← tactic.whnf e md, return ⟨(), n, none⟩ meta def dsimp : old_conv unit := λ r e, do s ← simp_lemmas.mk_default, n ← s.dsimplify [] e, return ⟨(), n, none⟩ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : old_conv unit := λ r e, tactic.trace a >> return ⟨(), e, none⟩ meta def trace_lhs : old_conv unit := lhs >>= trace meta def apply_lemmas_core (s : simp_lemmas) (prove : tactic unit) : old_conv unit := λ r e, do (new_e, pr) ← s.rewrite e prove r, return ⟨(), new_e, some pr⟩ meta def apply_lemmas (s : simp_lemmas) : old_conv unit := apply_lemmas_core s failed /- adapter for using iff-lemmas as eq-lemmas -/ meta def apply_propext_lemmas_core (s : simp_lemmas) (prove : tactic unit) : old_conv unit := λ r e, do guard (r = `eq), (new_e, pr) ← s.rewrite e prove `iff, new_pr ← mk_app `propext [pr], return ⟨(), new_e, some new_pr⟩ meta def apply_propext_lemmas (s : simp_lemmas) : old_conv unit := apply_propext_lemmas_core s failed private meta def mk_refl_proof (r : name) (e : expr) : tactic expr := do env ← get_env, match (environment.refl_for env r) with | (some refl) := do pr ← mk_app refl [e], return pr | none := fail format!"converter failed, relation '{r}' is not reflexive" end meta def to_tactic (c : old_conv unit) : name → expr → tactic (expr × expr) := λ r e, do ⟨u, e₁, o⟩ ← c r e, match o with | none := do p ← mk_refl_proof r e, return (e₁, p) | some p := return (e₁, p) end meta def lift_tactic {α : Type} (t : tactic α) : old_conv α := λ r e, do a ← t, return ⟨a, e, none⟩ meta def apply_simp_set (attr_name : name) : old_conv unit := lift_tactic (get_user_simp_lemmas attr_name) >>= apply_lemmas meta def apply_propext_simp_set (attr_name : name) : old_conv unit := lift_tactic (get_user_simp_lemmas attr_name) >>= apply_propext_lemmas meta def skip : old_conv unit := return () meta def repeat : old_conv unit → old_conv unit | c r lhs := (do ⟨_, rhs₁, pr₁⟩ ← c r lhs, guard (¬ lhs =ₐ rhs₁), ⟨_, rhs₂, pr₂⟩ ← repeat c r rhs₁, pr ← join_proofs r pr₁ pr₂, return ⟨(), rhs₂, pr⟩) <|> return ⟨(), lhs, none⟩ meta def first {α : Type} : list (old_conv α) → old_conv α | [] := old_conv.failed | (c::cs) := c <|> first cs meta def match_pattern (p : pattern) : old_conv unit := λ r e, tactic.match_pattern p e >> return ⟨(), e, none⟩ meta def mk_match_expr (p : pexpr) : tactic (old_conv unit) := do new_p ← pexpr_to_pattern p, return (λ r e, tactic.match_pattern new_p e >> return ⟨(), e, none⟩) meta def match_expr (p : pexpr) : old_conv unit := λ r e, do new_p ← pexpr_to_pattern p, tactic.match_pattern new_p e >> return ⟨(), e, none⟩ meta def funext (c : old_conv unit) : old_conv unit := λ r lhs, do guard (r = `eq), (expr.lam n bi d b) ← return lhs, let aux_type := expr.pi n bi d (expr.const `true []), (result, _) ← solve_aux aux_type $ do { x ← intro1, c_result ← c r (b.instantiate_var x), let rhs := expr.lam n bi d (c_result.rhs.abstract x), match c_result.proof : _ → tactic (old_conv_result unit) with | some pr := do let aux_pr := expr.lam n bi d (pr.abstract x), new_pr ← mk_app `funext [lhs, rhs, aux_pr], return ⟨(), rhs, some new_pr⟩ | none := return ⟨(), rhs, none⟩ end }, return result meta def congr_core (c_f c_a : old_conv unit) : old_conv unit := λ r lhs, do guard (r = `eq), (expr.app f a) ← return lhs, f_type ← infer_type f >>= tactic.whnf, guard (f_type.is_arrow), ⟨(), new_f, of⟩ ← mtry c_f r f, ⟨(), new_a, oa⟩ ← mtry c_a r a, rhs ← return $ new_f new_a, match of, oa with | none, none := return ⟨(), rhs, none⟩ | none, some pr_a := do pr ← mk_app `congr_arg [a, new_a, f, pr_a], return ⟨(), new_f new_a, some pr⟩ | some pr_f, none := do pr ← mk_app `congr_fun [f, new_f, pr_f, a], return ⟨(), rhs, some pr⟩ | some pr_f, some pr_a := do pr ← mk_app `congr [f, new_f, a, new_a, pr_f, pr_a], return ⟨(), rhs, some pr⟩ end meta def congr (c : old_conv unit) : old_conv unit := congr_core c c meta def bottom_up (c : old_conv unit) : old_conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, failed) (λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt)) r e, return ⟨(), new_e, some pr⟩ meta def top_down (c : old_conv unit) : old_conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def find (c : old_conv unit) : old_conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, (do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff)) <|> return ((), e, none, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def find_pattern (pat : pattern) (c : old_conv unit) : old_conv unit := λ r e, do s ← simp_lemmas.mk_default, (a, new_e, pr) ← ext_simplify_core () {} s (λ u, return u) (λ a s r p e, do matched ← (tactic.match_pattern pat e >> return tt) <|> return ff, if matched then do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff) else return ((), e, none, tt)) (λ a s r p e, failed) r e, return ⟨(), new_e, some pr⟩ meta def findp : pexpr → old_conv unit → old_conv unit := λ p c r e, do pat ← pexpr_to_pattern p, find_pattern pat c r e meta def conversion (c : old_conv unit) : tactic unit := do (r, lhs, rhs) ← (target_lhs_rhs <|> fail "conversion failed, target is not of the form 'lhs R rhs'"), (new_lhs, pr) ← to_tactic c r lhs, (unify new_lhs rhs <|> do new_lhs_fmt ← pp new_lhs, rhs_fmt ← pp rhs, fail (to_fmt "conversion failed, expected" ++ rhs_fmt.indent 4 ++ format.line ++ "provided" ++ new_lhs_fmt.indent 4)), exact pr end old_conv
22f5db36434f3464bbb963c1b303fb45f78737c8
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/run/local_eqns2.lean
89bbaa71004dbc6194eae108da3d1dee8aa9ed1b
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
426
lean
import data.fin open fin nat definition nz_cases_on {C : Π n, fin (succ n) → Type} (H₁ : Π n, C n (fz n)) (H₂ : Π n (f : fin n), C n (fs f)) {n : nat} (f : fin (succ n)) : C n f := begin reverts (n, f), show ∀ (n : nat) (f : fin (succ n)), C n f | m (fz m) := by apply H₁ | m (fs f') := by apply H₂ end
96f33b788c2100f5694209e06f6a7373cb99321e
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/ring_theory/algebraic.lean
33eeb334f715eb9624fcd93ef3265b67efe804d7
[ "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
3,544
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.integral_closure /-! # Algebraic elements and algebraic extensions An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. An R-algebra is algebraic over R if and only if all its elements are algebraic over R. The main result in this file proves transitivity of algebraicity: a tower of algebraic field extensions is algebraic. -/ universe variables u v open_locale classical open polynomial section variables (R : Type u) {A : Type v} [comm_ring R] [comm_ring A] [algebra R A] /-- An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. -/ def is_algebraic (x : A) : Prop := ∃ p : polynomial R, p ≠ 0 ∧ aeval R A x p = 0 variables {R} /-- A subalgebra is algebraic if all its elements are algebraic. -/ def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x variables (R A) /-- An algebra is algebraic if all its elements are algebraic. -/ def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x variables {R A} /-- A subalgebra is algebraic if and only if it is algebraic an algebra. -/ lemma subalgebra.is_algebraic_iff (S : subalgebra R A) : S.is_algebraic ↔ @algebra.is_algebraic R S _ _ (by convert S.algebra) := begin delta algebra.is_algebraic subalgebra.is_algebraic, rw [subtype.forall'], apply forall_congr, rintro ⟨x, hx⟩, apply exists_congr, intro p, apply and_congr iff.rfl, have h : function.injective (S.val) := subtype.val_injective, conv_rhs { rw [← h.eq_iff, alg_hom.map_zero], }, apply eq_iff_eq_cancel_right.mpr, symmetry, -- TODO: add an `aeval`-specific version of `hom_eval₂` simp only [aeval_def], convert hom_eval₂ p (algebra_map R S) ↑S.val ⟨x, hx⟩, refl end /-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/ lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic := begin delta algebra.is_algebraic subalgebra.is_algebraic, simp only [algebra.mem_top, forall_prop_of_true, iff_self], end end section zero_ne_one variables (R : Type u) {A : Type v} [nonzero_comm_ring R] [comm_ring A] [algebra R A] /-- An integral element of an algebra is algebraic.-/ lemma is_integral.is_algebraic {x : A} (h : is_integral R x) : is_algebraic R x := by { rcases h with ⟨p, hp, hpx⟩, exact ⟨p, hp.ne_zero, hpx⟩ } end zero_ne_one section field variables (K : Type u) {A : Type v} [field K] [comm_ring A] [algebra K A] /-- An element of an algebra over a field is algebraic if and only if it is integral.-/ lemma is_algebraic_iff_is_integral {x : A} : is_algebraic K x ↔ is_integral K x := begin refine ⟨_, is_integral.is_algebraic K⟩, rintro ⟨p, hp, hpx⟩, refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩, rw [alg_hom.map_mul, hpx, zero_mul], end end field namespace algebra variables {K : Type*} {L : Type*} {A : Type*} variables [field K] [field L] [comm_ring A] variables [algebra K L] [algebra L A] /-- If L is an algebraic field extension of K and A is an algebraic algebra over L, then A is algebraic over K. -/ lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) : is_algebraic K (comap K L A) := begin simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢, exact is_integral_trans L_alg A_alg, end end algebra
994072b575a2e76817b93af0169bcc9165ae11b9
842b7df4a999c5c50bbd215b8617dd705e43c2e1
/nat_num_game/src/Advanced_Addition_World/adv_add_wrld8.lean
909eb00224d599f59040212061d682a0e72d9dd6
[]
no_license
Samyak-Surti/LeanCode
1c245631f74b00057d20483c8ac75916e8643b14
944eac3e5f43e2614ed246083b97fbdf24181d83
refs/heads/master
1,669,023,730,828
1,595,534,784,000
1,595,534,784,000
282,037,186
0
0
null
null
null
null
UTF-8
Lean
false
false
222
lean
lemma eq_zero_of_add_right_eq_self {a b : ℕ} : a + b = a → b = 0 := begin intro h, induction a with d hd, rw nat.zero_add at h, exact h, rw nat.succ_add at h, rw hd, rw nat.succ.inj h, end
6707838561da685c2610b95878d9a4c92ab44329
caa1512363b76923d0e9cdb716122a5c26c3c6bc
/src/vec_cone.lean
40c9e71de1f922b32dd87c2dcc7cff4d1fe8cd54
[]
no_license
apurvanakade/cvx
deb20e425ce478159a98e1ffc0d37f9c88a89280
b47784831339df5a3e45f5cddd84edc545f95808
refs/heads/master
1,687,403,288,536
1,555,930,740,000
1,555,930,740,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,638
lean
import .cone .colvec section dual_cone variables {k m n : nat} (a : ℝ) (x y z : colvec (fin n) ℝ) (A : set (colvec (fin n) ℝ)) def second_order_cone (n : nat): set (colvec (fin (n + 1)) ℝ ) := { x | ∥ x.tail ∥ ≤ x.head } lemma cone_second_order_cone : cone (second_order_cone n) := begin intros x ha c hc, unfold second_order_cone at *, rw [set.mem_set_of_eq, colvec.tail_smul, colvec.head_smul, norm_smul, real.norm_eq_abs, abs_of_nonneg hc], exact mul_le_mul (le_refl c) ha (norm_nonneg _) hc end postfix `ᵀ` : 1500 := set.image matrix.transpose lemma second_order_cone_self_dual : dual_cone (second_order_cone n) = second_order_cone n := begin have h_ltr: dual_cone (second_order_cone n) ⊆ second_order_cone n, { assume (y : colvec (fin (n + 1)) ℝ) (hy : y ∈ dual_cone (second_order_cone n)), by_cases h_cases : y.tail = 0, { have h : (0:ℝ) ≤ ⟪ colvec.cons 1 0, y ⟫, { apply hy (colvec.cons 1 0), simp [second_order_cone,zero_le_one] }, have h : 0 ≤ y.head, { rw [←@colvec.mul_head_add_mul_tail n ℝ _ (colvec.cons 1 0) y] at h, simpa [matrix.mul_zero'] using h }, show y ∈ second_order_cone n, { unfold second_order_cone, rwa [set.mem_set_of_eq, h_cases, norm_zero] } }, { let y1 := y.head, let y2 := y.tail, have h : (0 : ℝ) ≤ real.sqrt ⟪ y2, y2 ⟫ * y1 + ⟪ - y2, y2 ⟫, { convert hy (colvec.cons (real.sqrt ⟪ y2, y2 ⟫) (- y2)) _, unfold has_inner.inner, convert @colvec.mul_head_add_mul_tail n ℝ _ _ _, { simp }, { simp }, simp [second_order_cone], refl }, have h : ⟪ y2, y2 ⟫ ≤ real.sqrt ⟪ y2, y2 ⟫ * y1, { apply le_of_sub_nonneg, rw real_inner_product_space.inner_neg_left at h, rwa sub_eq_add_neg, }, have h : real.sqrt ⟪ y2, y2 ⟫ * ⟪ y2, y2 ⟫ ≤ real.sqrt ⟪ y2, y2 ⟫ * (real.sqrt ⟪ y2, y2 ⟫ * y1), from mul_le_mul (le_refl _) h (real_inner_product_space.inner_self_nonneg _) (real.sqrt_nonneg _), have h : ⟪ y2, y2 ⟫ * real.sqrt ⟪ y2, y2 ⟫ ≤ ⟪ y2, y2 ⟫ * y1, { rw [←mul_assoc, mul_comm] at h, convert h, convert (@real.sqrt_mul ⟪ y2, y2 ⟫ (real_inner_product_space.inner_self_nonneg _) ⟪ y2, y2 ⟫), apply (real.sqrt_mul_self (real_inner_product_space.inner_self_nonneg _)).symm }, show y ∈ second_order_cone n, from le_of_mul_le_mul_left h (real_inner_product_space.inner_self_pos h_cases), } }, have h_rtl: second_order_cone n ⊆ dual_cone (second_order_cone n), begin assume (y : colvec (fin (n + 1)) ℝ), assume (hy : y ∈ second_order_cone n), assume (x : colvec (fin (n + 1)) ℝ) (hx : real.sqrt ⟪ x.tail, x.tail ⟫ ≤ x.head), have hx' : real.sqrt ⟪ - x.tail, - x.tail ⟫ ≤ x.head, by simpa, have h : ⟪ -x.tail, y.tail ⟫ ≤ x.head * y.head, calc ⟪ -x.tail, y.tail ⟫ ≤ real.sqrt ⟪ -x.tail, -x.tail ⟫ * real.sqrt ⟪ y.tail, y.tail ⟫ : real_inner_product_space.cauchy_schwartz' _ _ ... ≤ x.head * y.head : mul_le_mul hx' hy (real.sqrt_nonneg _) (le_trans (real.sqrt_nonneg _) hx'), show 0 ≤ ⟪ x, y ⟫, { rw [←@colvec.mul_head_add_mul_tail n ℝ _ x y], rw [real_inner_product_space.inner_neg_left] at h, convert sub_nonneg_of_le h, simp } end, show dual_cone (second_order_cone n) = second_order_cone n, from set.subset.antisymm h_ltr h_rtl end end dual_cone
355c28e63f08eeb4a83179843e4905cdd1102264
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/newfrontend2.lean
4a5d3c70f867fc16361c90c616b2afbebb8362fd
[ "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
467
lean
def foo {α} (a : Option α) (b : α) : α := match a with | some a => a | none => b structure S := (x : Nat) new_frontend #check if 0 == 1 then true else false def f (x : Nat) : Nat := if x < 5 then x+1 else x-1 def x := 1 #check foo x x #check match 1 with x => x + 1 #check match 1 : Int with x => x + 1 #check match 1 with | x => x + 1 #check match 1 : Int with | x => x + 1 def g (x : Nat × Nat) (y : Nat) := x.1 + x.2 + y #check (g ⟨·, 1⟩ ·)
27f25c6ebffb53af06568d32caeafb40a58cbb86
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/maze.lean
309aaca71aa7538a77269e1d80f705070100cc99
[ "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
11,168
lean
import Lean -- Coordinates in a two dimensional grid. ⟨0,0⟩ is the upper left. structure Coords where x : Nat -- column number y : Nat -- row number deriving BEq instance : ToString Coords where toString := (λ ⟨x,y⟩ => String.join ["Coords.mk ", toString x, ", ", toString y]) structure GameState where size : Coords -- coordinates of bottom-right cell position : Coords -- row and column of the player walls : List Coords -- maze cells that are not traversible -- We define custom syntax for GameState. declare_syntax_cat game_cell declare_syntax_cat game_cell_sequence declare_syntax_cat game_row declare_syntax_cat horizontal_border declare_syntax_cat game_top_row declare_syntax_cat game_bottom_row syntax "─" : horizontal_border syntax "\n┌" horizontal_border* "┐\n" : game_top_row syntax "└" horizontal_border* "┘\n" : game_bottom_row syntax "░" : game_cell -- empty syntax "▓" : game_cell -- wall syntax "@" : game_cell -- player syntax "│" game_cell* "│\n" : game_row syntax:max game_top_row game_row* game_bottom_row : term inductive CellContents where | empty : CellContents | wall : CellContents | player : CellContents def update_state_with_row_aux : Nat → Nat → List CellContents → GameState → GameState | currentRowNum, currentColNum, [], oldState => oldState | currentRowNum, currentColNum, cell::contents, oldState => let oldState' := update_state_with_row_aux currentRowNum (currentColNum+1) contents oldState match cell with | CellContents.empty => oldState' | CellContents.wall => {oldState' .. with walls := ⟨currentColNum,currentRowNum⟩::oldState'.walls} | CellContents.player => {oldState' .. with position := ⟨currentColNum,currentRowNum⟩} def update_state_with_row : Nat → List CellContents → GameState → GameState | currentRowNum, rowContents, oldState => update_state_with_row_aux currentRowNum 0 rowContents oldState -- size, current row, remaining cells -> gamestate def game_state_from_cells_aux : Coords → Nat → List (List CellContents) → GameState | size, _, [] => ⟨size, ⟨0,0⟩, []⟩ | size, currentRow, row::rows => let prevState := game_state_from_cells_aux size (currentRow + 1) rows update_state_with_row currentRow row prevState -- size, remaining cells -> gamestate def game_state_from_cells : Coords → List (List CellContents) → GameState | size, cells => game_state_from_cells_aux size 0 cells def termOfCell : Lean.TSyntax `game_cell → Lean.MacroM (Lean.TSyntax `term) | `(game_cell| ░) => `(CellContents.empty) | `(game_cell| ▓) => `(CellContents.wall) | `(game_cell| @) => `(CellContents.player) | _ => Lean.Macro.throwError "unknown game cell" def termOfGameRow : Nat → Lean.TSyntax `game_row → Lean.MacroM (Lean.TSyntax `term) | expectedRowSize, `(game_row| │$cells:game_cell*│) => do if cells.size != expectedRowSize then Lean.Macro.throwError "row has wrong size" let cells' ← Array.mapM termOfCell cells `([$cells',*]) | _, _ => Lean.Macro.throwError "unknown game row" macro_rules | `(┌ $tb:horizontal_border* ┐ $rows:game_row* └ $bb:horizontal_border* ┘) => do let rsize := Lean.Syntax.mkNumLit (toString rows.size) let csize := Lean.Syntax.mkNumLit (toString tb.size) if tb.size != bb.size then Lean.Macro.throwError "top/bottom border mismatch" let rows' ← Array.mapM (termOfGameRow tb.size) rows `(game_state_from_cells ⟨$csize,$rsize⟩ [$rows',*]) --------------------------- -- Now we define a delaborator that will cause GameState to be rendered as a maze. def extractXY : Lean.Expr → Lean.MetaM Coords | e => do let e':Lean.Expr ← (Lean.Meta.whnf e) let sizeArgs := Lean.Expr.getAppArgs e' let x ← Lean.Meta.whnf sizeArgs[0]! let y ← Lean.Meta.whnf sizeArgs[1]! let numCols := (Lean.Expr.natLit? x).get! let numRows := (Lean.Expr.natLit? y).get! return Coords.mk numCols numRows partial def extractWallList : Lean.Expr → Lean.MetaM (List Coords) | exp => do let exp':Lean.Expr ← (Lean.Meta.whnf exp) let f := Lean.Expr.getAppFn exp' if f.constName!.toString == "List.cons" then let consArgs := Lean.Expr.getAppArgs exp' let rest ← extractWallList consArgs[2]! let ⟨wallCol, wallRow⟩ ← extractXY consArgs[1]! return (Coords.mk wallCol wallRow) :: rest else return [] -- "List.nil" partial def extractGameState : Lean.Expr → Lean.MetaM GameState | exp => do let exp': Lean.Expr ← (Lean.Meta.whnf exp) let gameStateArgs := Lean.Expr.getAppArgs exp' let size ← extractXY gameStateArgs[0]! let playerCoords ← extractXY gameStateArgs[1]! let walls ← extractWallList gameStateArgs[2]! pure ⟨size, playerCoords, walls⟩ def update2dArray {α : Type} : Array (Array α) → Coords → α → Array (Array α) | a, ⟨x,y⟩, v => Array.set! a y $ Array.set! (Array.get! a y) x v def update2dArrayMulti {α : Type} : Array (Array α) → List Coords → α → Array (Array α) | a, [], _ => a | a, c::cs, v => let a' := update2dArrayMulti a cs v update2dArray a' c v def delabGameRow : Array (Lean.TSyntax `game_cell) → Lean.PrettyPrinter.Delaborator.DelabM (Lean.TSyntax `game_row) | a => `(game_row| │ $a:game_cell* │) def delabGameState : Lean.Expr → Lean.PrettyPrinter.Delaborator.Delab | e => do guard $ e.getAppNumArgs == 3 let ⟨⟨numCols, numRows⟩, playerCoords, walls⟩ ← try extractGameState e catch err => failure -- can happen if game state has variables in it let topBar := Array.mkArray numCols $ ← `(horizontal_border| ─) let emptyCell ← `(game_cell| ░) let emptyRow := Array.mkArray numCols emptyCell let emptyRowStx ← `(game_row| │$emptyRow:game_cell*│) let allRows := Array.mkArray numRows emptyRowStx let a0 := Array.mkArray numRows $ Array.mkArray numCols emptyCell let a1 := update2dArray a0 playerCoords $ ← `(game_cell| @) let a2 := update2dArrayMulti a1 walls $ ← `(game_cell| ▓) let aa ← Array.mapM delabGameRow a2 `(┌$topBar:horizontal_border*┐ $aa:game_row* └$topBar:horizontal_border*┘) -- The attribute [delab] registers this function as a delaborator for the GameState.mk constructor. @[delab app.GameState.mk] def delabGameStateMk : Lean.PrettyPrinter.Delaborator.Delab := do let e ← Lean.PrettyPrinter.Delaborator.SubExpr.getExpr delabGameState e -- We register the same elaborator for applications of the game_state_from_cells function. @[delab app.game_state_from_cells] def delabGameState' : Lean.PrettyPrinter.Delaborator.Delab := do let e ← Lean.PrettyPrinter.Delaborator.SubExpr.getExpr let e' ← (Lean.Meta.whnf e) delabGameState e' -------------------------- inductive Move where | east : Move | west : Move | north : Move | south : Move @[simp] def make_move : GameState → Move → GameState | ⟨s, ⟨x,y⟩, w⟩, Move.east => if w.notElem ⟨x+1, y⟩ ∧ x + 1 ≤ s.x then ⟨s, ⟨x+1, y⟩, w⟩ else ⟨s, ⟨x,y⟩, w⟩ | ⟨s, ⟨x,y⟩, w⟩, Move.west => if w.notElem ⟨x-1, y⟩ then ⟨s, ⟨x-1, y⟩, w⟩ else ⟨s, ⟨x,y⟩, w⟩ | ⟨s, ⟨x,y⟩, w⟩, Move.north => if w.notElem ⟨x, y-1⟩ then ⟨s, ⟨x, y-1⟩, w⟩ else ⟨s, ⟨x,y⟩, w⟩ | ⟨s, ⟨x,y⟩, w⟩, Move.south => if w.notElem ⟨x, y + 1⟩ ∧ y + 1 ≤ s.y then ⟨s, ⟨x, y+1⟩, w⟩ else ⟨s, ⟨x,y⟩, w⟩ def is_win : GameState → Prop | ⟨⟨sx, sy⟩, ⟨x,y⟩, w⟩ => x = 0 ∨ y = 0 ∨ x + 1 = sx ∨ y + 1 = sy def can_escape (state : GameState) : Prop := ∃ (gs : List Move), is_win (List.foldl make_move state gs) theorem can_still_escape (g : GameState) (m : Move) (hg : can_escape (make_move g m)) : can_escape g := have ⟨pms, hpms⟩ := hg Exists.intro (m::pms) hpms theorem step_west {s: Coords} {x y : Nat} {w: List Coords} (hclear' : w.notElem ⟨x,y⟩) (W : can_escape ⟨s,⟨x,y⟩,w⟩) : can_escape ⟨s,⟨x+1,y⟩,w⟩ := by have hmm : GameState.mk s ⟨x,y⟩ w = make_move ⟨s,⟨x+1, y⟩,w⟩ Move.west := by have h' : x + 1 - 1 = x := rfl simp [h', hclear'] rw [hmm] at W exact can_still_escape ⟨s,⟨x+1,y⟩,w⟩ Move.west W theorem step_east {s: Coords} {x y : Nat} {w: List Coords} (hclear' : w.notElem ⟨x+1,y⟩) (hinbounds : x + 1 ≤ s.x) (E : can_escape ⟨s,⟨x+1,y⟩,w⟩) : can_escape ⟨s,⟨x, y⟩,w⟩ := by have hmm : GameState.mk s ⟨x+1,y⟩ w = make_move ⟨s, ⟨x,y⟩,w⟩ Move.east := by simp [hclear', hinbounds] rw [hmm] at E exact can_still_escape ⟨s, ⟨x,y⟩, w⟩ Move.east E theorem step_north {s: Coords} {x y : Nat} {w: List Coords} (hclear' : w.notElem ⟨x,y⟩) (N : can_escape ⟨s,⟨x,y⟩,w⟩) : can_escape ⟨s,⟨x, y+1⟩,w⟩ := by have hmm : GameState.mk s ⟨x,y⟩ w = make_move ⟨s,⟨x, y+1⟩,w⟩ Move.north := by have h' : y + 1 - 1 = y := rfl simp [h', hclear'] rw [hmm] at N exact can_still_escape ⟨s,⟨x,y+1⟩,w⟩ Move.north N theorem step_south {s: Coords} {x y : Nat} {w: List Coords} (hclear' : w.notElem ⟨x,y+1⟩) (hinbounds : y + 1 ≤ s.y) (S : can_escape ⟨s,⟨x,y+1⟩,w⟩) : can_escape ⟨s,⟨x, y⟩,w⟩ := by have hmm : GameState.mk s ⟨x,y+1⟩ w = make_move ⟨s,⟨x, y⟩,w⟩ Move.south := by simp [hclear', hinbounds] rw [hmm] at S exact can_still_escape ⟨s,⟨x,y⟩,w⟩ Move.south S def escape_west {sx sy : Nat} {y : Nat} {w : List Coords} : can_escape ⟨⟨sx, sy⟩,⟨0, y⟩,w⟩ := ⟨[], Or.inl rfl⟩ def escape_east {sy x y : Nat} {w : List Coords} : can_escape ⟨⟨x+1, sy⟩,⟨x, y⟩,w⟩ := ⟨[], Or.inr $ Or.inr $ Or.inl rfl⟩ def escape_north {sx sy : Nat} {x : Nat} {w : List Coords} : can_escape ⟨⟨sx, sy⟩,⟨x, 0⟩,w⟩ := ⟨[], Or.inr $ Or.inl rfl⟩ def escape_south {sx x y : Nat} {w: List Coords} : can_escape ⟨⟨sx, y+1⟩,⟨x, y⟩,w⟩ := ⟨[], Or.inr $ Or.inr $ Or.inr rfl⟩ -- Define an "or" tactic combinator, like <|> in Lean 3. elab t1:tactic " ⟨|⟩ " t2:tactic : tactic => try Lean.Elab.Tactic.evalTactic t1 catch err => Lean.Elab.Tactic.evalTactic t2 elab "fail" m:term : tactic => throwError m macro "out" : tactic => `(apply escape_north ⟨|⟩ apply escape_south ⟨|⟩ apply escape_east ⟨|⟩ apply escape_west ⟨|⟩ fail "not currently at maze boundary") def maze1 := ┌───┐ │▓▓▓│ │░@▓│ │▓▓▓│ └───┘ def foo : can_escape maze1 := by apply step_west set_option trace.Meta.debug true in simp out
54aae87ef96aba576438e361d780496ca1005062
76df16d6c3760cb415f1294caee997cc4736e09b
/lean/src/cs/thm.lean
fcca5156dff59b60093102b2447fbdcf316b45ca
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
1,681,592,449,670
1,637,037,431,000
1,637,037,431,000
414,331,908
6
1
null
null
null
null
UTF-8
Lean
false
false
10,291
lean
import tactic.basic import tactic.split_ifs import tactic.linarith import tactic.apply_fun import .sym import .svm import .lib import .fin import .rsc import .detc import .dets import .red import .query namespace sym open lang class has_contains (φ α β : Type) := (contains : φ → α → β → Prop) notation a ` ∈[` f `] ` b := has_contains.contains f a b section variables {Model SymB SymV D O : Type} [inhabited Model] [inhabited SymV] instance env.has_contains : has_contains (factory Model SymB SymV D O) (lang.env D O) (env SymV) := ⟨λ f e ε, ∃ (m : Model), ε.eval f.to_has_eval m = e⟩ instance result.has_contains : has_contains (factory Model SymB SymV D O) (lang.result D O) (result SymB SymV) := ⟨λ f r ρ, ∃ (m : Model), ρ.eval f.to_has_eval m = r⟩ end -- The following top-level theorems are proven with respect to the top-level state -- that is normal under every model. section thm parameters {Model SymB SymV D O : Type} [inhabited Model] [inhabited SymV] (f : factory Model SymB SymV D O) @[simp] def σₜₜ : state SymB := ⟨f.mk_tt, f.mk_tt⟩ lemma σₜₜ_normal (m : Model) : σₜₜ.normal f.to_has_eval m := by { simp only [σₜₜ, top_normal], } lemma σₜₜ_legal (m : Model) : σₜₜ.legal f.to_has_eval m := by { simp only [σₜₜ, top_legal], } -- The symbolic semantics evalS preserves the legality of states across steps: -- legal input state leads to a legal result. theorem legality {x : exp D O} {ε : env SymV} {σ : state SymB} {ρ : result SymB SymV} {m : Model} : σ.legal f.to_has_eval m → evalS f x ε σ ρ → ρ.legal f.to_has_eval m := begin apply svm_lgl end -- The symbolic semantics evalS is deterministic: given the same environment and -- state, it produces the same result. theorem determinism {x : exp D O} {ε : env SymV} {σ : state SymB} {ρ1 ρ2 : result SymB SymV} : evalS f x ε σ ρ1 → evalS f x ε σ ρ2 → ρ1 = ρ2 := begin apply svm_det end -- The symbolic semantics evalS is composable: -- if evalS terminates on a program x, equivalent environments ε1 and ε2, and states σₜₜ and σ to produce -- the results ρ1 and ρ2, respectively, then ρ2 can be obtained by strengthening ρ1 -- with σ under all models. theorem composability {x : exp D O} {ε1 ε2 : env SymV} {σ : state SymB} {ρ1 ρ2 : result SymB SymV} : evalS f x ε1 σₜₜ ρ1 → evalS f x ε2 σ ρ2 → (∀ (m : Model), ε1.eval f.to_has_eval m = ε2.eval f.to_has_eval m) → ∀ (m : Model), ρ2.eval f.to_has_eval m = (f.strengthen σ ρ1).eval f.to_has_eval m := begin intros h1 h2 heq m, cases hn : (σ.normal f.to_has_eval m), { rewrite ←bool_iff_false at hn, have hq1 : state.eqv f.to_has_eval m (f.strengthen σ ρ1).state σ := by { apply f.strengthen_hp hn, }, have hh1 : (f.strengthen σ ρ1).eval f.to_has_eval m = lang.result.halt ((f.strengthen σ ρ1).state.aborted f.to_has_eval m) := by { apply result.eval_halt, apply state.eqv_abnormal f.to_has_eval hn, symmetry, exact hq1, }, rcases (svm_hp f hn h2) with hq2, have hh2 : ρ2.eval f.to_has_eval m = lang.result.halt (ρ2.state.aborted f.to_has_eval m) := by { apply result.eval_halt, apply state.eqv_abnormal f.to_has_eval hn, symmetry, exact hq2, }, rewrite [hh1, hh2], simp only, apply state.eqv_aborted, transitivity σ, { exact hq2, }, { symmetry, exact hq1, }}, { rewrite bool.tt_eq_true at hn, have h1c : evalC f.opC x (ε1.eval f.to_has_eval m) (ρ1.eval f.to_has_eval m) := by { rewrite svm_rsc f (σₜₜ_normal f m) rfl h1, }, have h2c : evalC f.opC x (ε1.eval f.to_has_eval m) (ρ2.eval f.to_has_eval m) := by { rewrite heq, rewrite svm_rsc f hn rfl h2, }, rcases (evalC_det h2c h1c) with hq, rewrite hq, symmetry, apply f.eval_strengthen_normal hn, } end -- The symbolic semantics evalS behaves equivalently to the concrete semantics evalC -- when evaluating an expression x in a concrete environment and normal concrete state. theorem reducibility {x : exp D O} {e : lang.env D O} {r : lang.result D O} {pe : reducer Model SymB SymV D O} (hr : f = pe.to_factory) : evalS f x (e.lift pe.lift) σₜₜ (r.lift f pe.lift) ↔ evalC f.opC x e r := begin simp only [hr, σₜₜ], rewrite ←σₙ, apply svm_reduce pe, end -- The symbolic semantics evalS faithfully lifts the concrete semantics evalC: -- if evalS produces a result ρ on a program x, top symbolic state σₜₜ, and -- a symbolic environment ε, then for any model m and concrete environment -- e = ε.eval f m, evalC produces a result r on x and e if and only if r = ρ.eval f m. theorem faithful_lifting {x : exp D O} {ε : env SymV} {ρ : result SymB SymV} : evalS f x ε σₜₜ ρ → ∀ (m : Model) {e : lang.env D O} {r : lang.result D O}, ε.eval f.to_has_eval m = e → (evalC f.opC x e r ↔ ρ.eval f.to_has_eval m = r) := begin intros hs m e r he, apply svm_rsc f (σₜₜ_normal f m) he hs, end -- The symbolic semantics evalS is sound with respect to the concrete semantics evalC: -- if evalS produces a result ρ on a program x, symbolic environment ε, and the top -- state σₜₜ, then for all environments e ∈ ε, if evalC produces a result r on x and e, -- then r is covered by ρ, i.e., r ∈ ρ. theorem soundness {x : exp D O} {ε : env SymV} {ρ : result SymB SymV} : evalS f x ε σₜₜ ρ → ∀ (e : lang.env D O), (e ∈[f] ε) → ∀ (r : lang.result D O), (evalC f.opC x e r) → (r ∈[f] ρ) := begin intros hs e he r hc, rcases he with ⟨m, he⟩, apply exists.intro m, rewrite ←faithful_lifting f hs m he, exact hc, end -- The symbolic semantics evalS is sound with respect to the concrete semantics evalC: -- if evalC produces a result r on a program x and environment e, then for all -- environments ε such that e ∈ ε, if evalS produces a result ρ on x, ε, and σₜₜ, -- then r is covered by ρ, i.e., r ∈ ρ. theorem soundness' {x : exp D O} {e : lang.env D O} {r : lang.result D O} : (evalC f.opC x e r) → ∀ (ε : env SymV), (e ∈[f] ε) → ∀ (ρ : result SymB SymV), evalS f x ε σₜₜ ρ → (r ∈[f] ρ) := begin intros hc ε he ρ hs, rcases he with ⟨m, he⟩, apply exists.intro m, rewrite ←faithful_lifting f hs m he, exact hc, end -- The symbolic semantics evalS is complete with respect to the concrete semantics evalC: -- if evalS produces a result ρ on a program x, top symbolic state σₜₜ, and -- a symbolic environment ε, then for every concrete result r ∈ ρ, there -- exists a concrete environment e ∈ ε such that evalC produces r on x and e. theorem completeness {x : exp D O} {ε : env SymV} {ρ : result SymB SymV} : evalS f x ε σₜₜ ρ → ∀ (r : lang.result D O), (r ∈[f] ρ) → ∃ (e : lang.env D O), (evalC f.opC x e r) ∧ (e ∈[f] ε) := begin intros hs r hr, rcases hr with ⟨m, hr⟩, apply exists.intro (ε.eval f.to_has_eval m), constructor, { rewrite faithful_lifting f hs m rfl, exact hr, }, { simp only [has_contains.contains, exists_apply_eq_apply], }, end -- The symbolic semantics evalS terminates on every expression x -- that is finite with respect to the environment ε, i.e., free of calls and -- with all variable references bound to valid indices in ε. theorem termination {x : exp D O} {ε : env SymV} (σ : state SymB) : x.finite ε.length → ∃ (ρ : result SymB SymV), evalS f x ε σ ρ := by { apply svm_ft f, } open decision def normal (x : lang.exp D O) (e : lang.env D O) : Prop := ∃ (r : lang.result D O), evalC f.opC x e r ∧ r.normal def errors (x : lang.exp D O) (e : lang.env D O) : Prop := ∃ (r : lang.result D O), evalC f.opC x e r ∧ r.errors -- The guess(x, ε) query is correct: -- if it returns an environment e, then e ∈ ε and there is a normal concrete execution of x in e; -- if it returns unsat, then there is no normal concrete execution of x in any e ∈ ε. theorem guess_correct {se : evaluator f} {slv : solver f} {x : lang.exp D O} {ε : env SymV} : (∀ (e : lang.env D O), guess f se slv x ε = sat e → ((e ∈[f] ε) ∧ normal x e)) ∧ (guess f se slv x ε = unsat → ∀ (e : lang.env D O), (e ∈[f] ε) → ¬ normal x e) := begin constructor, { intros e h, constructor, { simp only [has_contains.contains], apply guess_sat_domain f h, }, { apply guess_sat_correct f h, } }, { simp only [normal, not_exists, eq_ff_eq_not_eq_tt, not_and], intros h e he r hc, rewrite ←bool_iff_false, simp only [has_contains.contains] at he, cases he with m he, rewrite ←he at hc, apply guess_unsat_correct f h m, exact hc, } end -- The verify(x, ε) query is correct: -- if it returns an environment e, then e ∈ ε and there is an erroneous concrete execution of x in e; -- if it returns unsat, then there is no erroneous concrete execution of x in any e ∈ ε. theorem verify_correct {se : evaluator f} {slv : solver f} {x : lang.exp D O} {ε : env SymV} : (∀ (e : lang.env D O), verify f se slv x ε = sat e → ((e ∈[f] ε) ∧ errors x e)) ∧ (verify f se slv x ε = unsat → ∀ (e : lang.env D O), (e ∈[f] ε) → ¬ errors x e) := begin constructor, { intros e h, constructor, { simp only [has_contains.contains], apply verify_sat_domain f h, }, { apply verify_sat_correct f h, } }, { simp only [errors, not_exists, eq_ff_eq_not_eq_tt, not_and], intros h e he r hc, rewrite ←bool_iff_false, simp only [has_contains.contains] at he, cases he with m he, rewrite ←he at hc, apply verify_unsat_correct f h m, exact hc, } end end thm end sym
73f754f0df5b109806ef5fc822356553c7ebe4df
b147e1312077cdcfea8e6756207b3fa538982e12
/data/seq/seq.lean
e7bd77d61cf5db64446c41210d15c5b6c33972e8
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,114
lean
import data.stream data.lazy_list data.seq.computation logic.basic tactic.interactive universes u v w /- coinductive seq (α : Type u) : Type u | nil : seq α | cons : α → seq α → seq α -/ /-- `seq α` is the type of possibly infinite lists (referred here as sequences). It is encoded as an infinite stream of options such that if `f n = none`, then `f m = none` for all `m ≥ n`. -/ def seq (α : Type u) : Type u := { f : stream (option α) // ∀ {n}, f n = none → f (n+1) = none } /-- `seq1 α` is the type of nonempty sequences. -/ def seq1 (α) := α × seq α namespace seq variables {α : Type u} {β : Type v} {γ : Type w} /-- The empty sequence -/ def nil : seq α := ⟨stream.const none, λn h, rfl⟩ /-- Prepend an element to a sequence -/ def cons (a : α) : seq α → seq α | ⟨f, al⟩ := ⟨some a :: f, λn h, by {cases n with n, contradiction, exact al h}⟩ /-- Get the nth element of a sequence (if it exists) -/ def nth : seq α → ℕ → option α := subtype.val /-- Functorial action of the functor `option (α × _)` -/ @[simp] def omap (f : β → γ) : option (α × β) → option (α × γ) | none := none | (some (a, b)) := some (a, f b) /-- Get the first element of a sequence -/ def head (s : seq α) : option α := nth s 0 /-- Get the tail of a sequence (or `nil` if the sequence is `nil`) -/ def tail : seq α → seq α | ⟨f, al⟩ := ⟨f.tail, λ n, al⟩ protected def mem (a : α) (s : seq α) := some a ∈ s.1 instance : has_mem α (seq α) := ⟨seq.mem⟩ theorem le_stable (s : seq α) {m n} (h : m ≤ n) : s.1 m = none → s.1 n = none := by {cases s with f al, induction h with n h IH, exacts [id, λ h2, al (IH h2)]} theorem not_mem_nil (a : α) : a ∉ @nil α := λ ⟨n, (h : some a = none)⟩, by injection h theorem mem_cons (a : α) : ∀ (s : seq α), a ∈ cons a s | ⟨f, al⟩ := stream.mem_cons (some a) _ theorem mem_cons_of_mem (y : α) {a : α} : ∀ {s : seq α}, a ∈ s → a ∈ cons y s | ⟨f, al⟩ := stream.mem_cons_of_mem (some y) theorem eq_or_mem_of_mem_cons {a b : α} : ∀ {s : seq α}, a ∈ cons b s → a = b ∨ a ∈ s | ⟨f, al⟩ h := (stream.eq_or_mem_of_mem_cons h).imp_left (λh, by injection h) @[simp] theorem mem_cons_iff {a b : α} {s : seq α} : a ∈ cons b s ↔ a = b ∨ a ∈ s := ⟨eq_or_mem_of_mem_cons, λo, by cases o with e m; [{rw e, apply mem_cons}, exact mem_cons_of_mem _ m]⟩ /-- Destructor for a sequence, resulting in either `none` (for `nil`) or `some (a, s)` (for `cons a s`). -/ def destruct (s : seq α) : option (seq1 α) := (λa', (a', s.tail)) <$> nth s 0 theorem destruct_eq_nil {s : seq α} : destruct s = none → s = nil := begin dsimp [destruct], induction f0 : nth s 0; intro h, { apply subtype.eq, funext n, induction n with n IH, exacts [f0, s.2 IH] }, { contradiction } end theorem destruct_eq_cons {s : seq α} {a s'} : destruct s = some (a, s') → s = cons a s' := begin dsimp [destruct], induction f0 : nth s 0 with a'; intro h, { contradiction }, { unfold functor.map at h, dsimp at h, cases s with f al, injections with _ h1 h2, rw ←h2, apply subtype.eq, dsimp [tail, cons], rw h1 at f0, rw ←f0, exact (stream.eta f).symm } end @[simp] theorem destruct_nil : destruct (nil : seq α) = none := rfl @[simp] theorem destruct_cons (a : α) : ∀ s, destruct (cons a s) = some (a, s) | ⟨f, al⟩ := begin unfold cons destruct functor.map, apply congr_arg (λ s, some (a, s)), apply subtype.eq, dsimp [tail], rw [stream.tail_cons] end theorem head_eq_destruct (s : seq α) : head s = prod.fst <$> destruct s := by unfold destruct head; cases nth s 0; refl @[simp] theorem head_nil : head (nil : seq α) = none := rfl @[simp] theorem head_cons (a : α) (s) : head (cons a s) = some a := by rw [head_eq_destruct, destruct_cons]; refl @[simp] theorem tail_nil : tail (nil : seq α) = nil := rfl @[simp] theorem tail_cons (a : α) (s) : tail (cons a s) = s := by cases s with f al; apply subtype.eq; dsimp [tail, cons]; rw [stream.tail_cons] def cases_on {C : seq α → Sort v} (s : seq α) (h1 : C nil) (h2 : ∀ x s, C (cons x s)) : C s := begin induction H : destruct s with v v, { rw destruct_eq_nil H, apply h1 }, { cases v with a s', rw destruct_eq_cons H, apply h2 } end theorem mem_rec_on {C : seq α → Prop} {a s} (M : a ∈ s) (h1 : ∀ b s', (a = b ∨ C s') → C (cons b s')) : C s := begin cases M with k e, unfold stream.nth at e, induction k with k IH generalizing s, { have TH : s = cons a (tail s), { apply destruct_eq_cons, unfold destruct nth functor.map, rw ←e, refl }, rw TH, apply h1 _ _ (or.inl rfl) }, revert e, apply s.cases_on _ (λ b s', _); intro e, { injection e }, { have h_eq : (cons b s').val (nat.succ k) = s'.val k, { cases s'; refl }, rw [h_eq] at e, apply h1 _ _ (or.inr (IH e)) } end def corec.F (f : β → option (α × β)) : option β → option α × option β | none := (none, none) | (some b) := match f b with none := (none, none) | some (a, b') := (some a, some b') end /-- Corecursor for `seq α` as a coinductive type. Iterates `f` to produce new elements of the sequence until `none` is obtained. -/ def corec (f : β → option (α × β)) (b : β) : seq α := begin refine ⟨stream.corec' (corec.F f) (some b), λn h, _⟩, rw stream.corec'_eq, change stream.corec' (corec.F f) (corec.F f (some b)).2 n = none, revert h, generalize : some b = o, revert o, induction n with n IH; intro o, { change (corec.F f o).1 = none → (corec.F f (corec.F f o).2).1 = none, cases o with b; intro h, { refl }, dsimp [corec.F] at h, dsimp [corec.F], cases f b with s, { refl }, { cases s with a b', contradiction } }, { rw [stream.corec'_eq (corec.F f) (corec.F f o).2, stream.corec'_eq (corec.F f) o], exact IH (corec.F f o).2 } end @[simp] theorem corec_eq (f : β → option (α × β)) (b : β) : destruct (corec f b) = omap (corec f) (f b) := begin dsimp [corec, destruct, nth], change stream.corec' (corec.F f) (some b) 0 with (corec.F f (some b)).1, unfold functor.map, dsimp [corec.F], induction h : f b with s, { refl }, cases s with a b', dsimp [corec.F, option.bind], apply congr_arg (λ b', some (a, b')), apply subtype.eq, dsimp [corec, tail], rw [stream.corec'_eq, stream.tail_cons], dsimp [corec.F], rw h, refl end /-- Embed a list as a sequence -/ def of_list (l : list α) : seq α := ⟨list.nth l, λn h, begin induction l with a l IH generalizing n, refl, dsimp [list.nth], cases n with n; dsimp [list.nth] at h, { contradiction }, { apply IH _ h } end⟩ instance coe_list : has_coe (list α) (seq α) := ⟨of_list⟩ section bisim variable (R : seq α → seq α → Prop) local infix ~ := R def bisim_o : option (seq1 α) → option (seq1 α) → Prop | none none := true | (some (a, s)) (some (a', s')) := a = a' ∧ R s s' | _ _ := false attribute [simp] bisim_o def is_bisimulation := ∀ ⦃s₁ s₂⦄, s₁ ~ s₂ → bisim_o R (destruct s₁) (destruct s₂) -- If two streams are bisimilar, then they are equal theorem eq_of_bisim (bisim : is_bisimulation R) {s₁ s₂} (r : s₁ ~ s₂) : s₁ = s₂ := begin apply subtype.eq, apply stream.eq_of_bisim (λx y, ∃ s s' : seq α, s.1 = x ∧ s'.1 = y ∧ R s s'), dsimp [stream.is_bisimulation], intros t₁ t₂ e, exact match t₁, t₂, e with ._, ._, ⟨s, s', rfl, rfl, r⟩ := suffices head s = head s' ∧ R (tail s) (tail s'), from and.imp id (λr, ⟨tail s, tail s', by cases s; refl, by cases s'; refl, r⟩) this, begin have := bisim r, revert r this, apply cases_on s _ _; intros; apply cases_on s' _ _; intros; intros r this, { constructor, refl, assumption }, { rw [destruct_nil, destruct_cons] at this, exact false.elim this }, { rw [destruct_nil, destruct_cons] at this, exact false.elim this }, { rw [destruct_cons, destruct_cons] at this, rw [head_cons, head_cons, tail_cons, tail_cons], cases this with h1 h2, constructor, rw h1, exact h2 } end end, exact ⟨s₁, s₂, rfl, rfl, r⟩ end end bisim theorem coinduction : ∀ {s₁ s₂ : seq α}, head s₁ = head s₂ → (∀ (β : Type u) (fr : seq α → β), fr s₁ = fr s₂ → fr (tail s₁) = fr (tail s₂)) → s₁ = s₂ | ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ hh ht := subtype.eq (stream.coinduction hh (λ β fr, ht β (λs, fr s.1))) theorem coinduction2 (s) (f g : seq α → seq β) (H : ∀ s, bisim_o (λ (s1 s2 : seq β), ∃ (s : seq α), s1 = f s ∧ s2 = g s) (destruct (f s)) (destruct (g s))) : f s = g s := begin refine eq_of_bisim (λ s1 s2, ∃ s, s1 = f s ∧ s2 = g s) _ ⟨s, rfl, rfl⟩, intros s1 s2 h, rcases h with ⟨s, h1, h2⟩, rw [h1, h2], apply H end /-- Embed an infinite stream as a sequence -/ def of_stream (s : stream α) : seq α := ⟨s.map some, λn h, by contradiction⟩ instance coe_stream : has_coe (stream α) (seq α) := ⟨of_stream⟩ /-- Embed a `lazy_list α` as a sequence. Note that even though this is non-meta, it will produce infinite sequences if used with cyclic `lazy_list`s created by meta constructions. -/ def of_lazy_list : lazy_list α → seq α := corec (λl, match l with | lazy_list.nil := none | lazy_list.cons a l' := some (a, l' ()) end) instance coe_lazy_list : has_coe (lazy_list α) (seq α) := ⟨of_lazy_list⟩ /-- Translate a sequence into a `lazy_list`. Since `lazy_list` and `list` are isomorphic as non-meta types, this function is necessarily meta. -/ meta def to_lazy_list : seq α → lazy_list α | s := match destruct s with | none := lazy_list.nil | some (a, s') := lazy_list.cons a (to_lazy_list s') end /-- Translate a sequence to a list. This function will run forever if run on an infinite sequence. -/ meta def force_to_list (s : seq α) : list α := (to_lazy_list s).to_list /-- Append two sequences. If `s₁` is infinite, then `s₁ ++ s₂ = s₁`, otherwise it puts `s₂` at the location of the `nil` in `s₁`. -/ def append (s₁ s₂ : seq α) : seq α := @corec α (seq α × seq α) (λ⟨s₁, s₂⟩, match destruct s₁ with | none := omap (λs₂, (nil, s₂)) (destruct s₂) | some (a, s₁') := some (a, s₁', s₂) end) (s₁, s₂) /-- Map a function over a sequence. -/ def map (f : α → β) : seq α → seq β | ⟨s, al⟩ := ⟨s.map (option.map f), λn, begin dsimp [stream.map, stream.nth], induction e : s n; intro, { rw al e, assumption }, { contradiction } end⟩ /-- Flatten a sequence of sequences. (It is required that the sequences be nonempty to ensure productivity; in the case of an infinite sequence of `nil`, the first element is never generated.) -/ def join : seq (seq1 α) → seq α := corec (λS, match destruct S with | none := none | some ((a, s), S') := some (a, match destruct s with | none := S' | some s' := cons s' S' end) end) /-- Remove the first `n` elements from the sequence. -/ def drop (s : seq α) : ℕ → seq α | 0 := s | (n+1) := tail (drop n) attribute [simp] drop /-- Take the first `n` elements of the sequence (producing a list) -/ def take : ℕ → seq α → list α | 0 s := [] | (n+1) s := match destruct s with | none := [] | some (x, r) := list.cons x (take n r) end /-- Split a sequence at `n`, producing a finite initial segment and an infinite tail. -/ def split_at : ℕ → seq α → list α × seq α | 0 s := ([], s) | (n+1) s := match destruct s with | none := ([], nil) | some (x, s') := let (l, r) := split_at n s' in (list.cons x l, r) end /-- Combine two sequences with a function -/ def zip_with (f : α → β → γ) : seq α → seq β → seq γ | ⟨f₁, a₁⟩ ⟨f₂, a₂⟩ := ⟨λn, match f₁ n, f₂ n with | some a, some b := some (f a b) | _, _ := none end, λn, begin induction h1 : f₁ n, { intro H, rw a₁ h1, refl }, induction h2 : f₂ n; dsimp [seq.zip_with._match_1]; intro H, { rw a₂ h2, cases f₁ (n + 1); refl }, { contradiction } end⟩ /-- Pair two sequences into a sequence of pairs -/ def zip : seq α → seq β → seq (α × β) := zip_with prod.mk /-- Separate a sequence of pairs into two sequences -/ def unzip (s : seq (α × β)) : seq α × seq β := (map prod.fst s, map prod.snd s) /-- Convert a sequence which is known to terminate into a list -/ def to_list (s : seq α) (h : ∃ n, ¬ (nth s n).is_some) : list α := take (nat.find h) s /-- Convert a sequence which is known not to terminate into a stream -/ def to_stream (s : seq α) (h : ∀ n, (nth s n).is_some) : stream α := λn, option.get (h n) /-- Convert a sequence into either a list or a stream depending on whether it is finite or infinite. (Without decidability of the infiniteness predicate, this is not constructively possible.) -/ def to_list_or_stream (s : seq α) [decidable (∃ n, ¬ (nth s n).is_some)] : list α ⊕ stream α := if h : ∃ n, ¬ (nth s n).is_some then sum.inl (to_list s h) else sum.inr (to_stream s (λn, decidable.by_contradiction (λ hn, h ⟨n, hn⟩))) @[simp] theorem nil_append (s : seq α) : append nil s = s := begin apply coinduction2, intro s, dsimp [append], rw [corec_eq], dsimp [append], apply cases_on s _ _, { trivial }, { intros x s, rw [destruct_cons], dsimp, exact ⟨rfl, s, rfl, rfl⟩ } end @[simp] theorem cons_append (a : α) (s t) : append (cons a s) t = cons a (append s t) := destruct_eq_cons $ begin dsimp [append], rw [corec_eq], dsimp [append], rw [destruct_cons], dsimp [append], refl end @[simp] theorem append_nil (s : seq α) : append s nil = s := begin apply coinduction2 s, intro s, apply cases_on s _ _, { trivial }, { intros x s, rw [cons_append, destruct_cons, destruct_cons], dsimp, exact ⟨rfl, s, rfl, rfl⟩ } end @[simp] theorem append_assoc (s t u : seq α) : append (append s t) u = append s (append t u) := begin apply eq_of_bisim (λs1 s2, ∃ s t u, s1 = append (append s t) u ∧ s2 = append s (append t u)), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, u, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on t; simp, { apply cases_on u; simp, { intros x u, refine ⟨nil, nil, u, _, _⟩; simp } }, { intros x t, refine ⟨nil, t, u, _, _⟩; simp } }, { intros x s, exact ⟨s, t, u, rfl, rfl⟩ } end end }, { exact ⟨s, t, u, rfl, rfl⟩ } end @[simp] theorem map_nil (f : α → β) : map f nil = nil := rfl @[simp] theorem map_cons (f : α → β) (a) : ∀ s, map f (cons a s) = cons (f a) (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [cons, map]; rw stream.map_cons; refl @[simp] theorem map_id : ∀ (s : seq α), map id s = s | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw [option.map_id, stream.map_id]; refl end @[simp] theorem map_tail (f : α → β) : ∀ s, map f (tail s) = tail (map f s) | ⟨s, al⟩ := by apply subtype.eq; dsimp [tail, map]; rw stream.map_tail; refl theorem map_comp (f : α → β) (g : β → γ) : ∀ (s : seq α), map (g ∘ f) s = map g (map f s) | ⟨s, al⟩ := begin apply subtype.eq; dsimp [map], rw stream.map_map, apply congr_arg (λ f : _ → option γ, stream.map f s), funext x, cases x with x; refl end @[simp] theorem map_append (f : α → β) (s t) : map f (append s t) = append (map f s) (map f t) := begin apply eq_of_bisim (λs1 s2, ∃ s t, s1 = map f (append s t) ∧ s2 = append (map f s) (map f t)) _ ⟨s, t, rfl, rfl⟩, intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, t, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on t; simp, { intros x t, refine ⟨nil, t, _, _⟩; simp } }, { intros x s, refine ⟨s, t, rfl, rfl⟩ } end end end @[simp] theorem map_nth (f : α → β) : ∀ s n, nth (map f s) n = (nth s n).map f | ⟨s, al⟩ n := rfl instance : functor seq := {map := @map} instance : is_lawful_functor seq := { id_map := @map_id, comp_map := @map_comp } @[simp] theorem join_nil : join nil = (nil : seq α) := destruct_eq_nil rfl @[simp] theorem join_cons_nil (a : α) (S) : join (cons (a, nil) S) = cons a (join S) := destruct_eq_cons $ by simp [join] @[simp] theorem join_cons_cons (a b : α) (s S) : join (cons (a, cons b s) S) = cons a (join (cons (b, s) S)) := destruct_eq_cons $ by simp [join] @[simp] theorem join_cons (a : α) (s S) : join (cons (a, s) S) = cons a (append s (join S)) := begin apply eq_of_bisim (λs1 s2, s1 = s2 ∨ ∃ a s S, s1 = join (cons (a, s) S) ∧ s2 = cons a (append s (join S))) _ (or.inr ⟨a, s, S, rfl, rfl⟩), intros s1 s2 h, exact match s1, s2, h with | _, _, (or.inl $ eq.refl s) := begin apply cases_on s, { trivial }, { intros x s, rw [destruct_cons], exact ⟨rfl, or.inl rfl⟩ } end | ._, ._, (or.inr ⟨a, s, S, rfl, rfl⟩) := begin apply cases_on s, { simp }, { intros x s, simp, refine or.inr ⟨x, s, S, rfl, rfl⟩ } end end end @[simp] theorem join_append (S T : seq (seq1 α)) : join (append S T) = append (join S) (join T) := begin apply eq_of_bisim (λs1 s2, ∃ s S T, s1 = append s (join (append S T)) ∧ s2 = append s (append (join S) (join T))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, T, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on S; simp, { apply cases_on T, { simp }, { intros s T, cases s with a s; simp, refine ⟨s, nil, T, _, _⟩; simp } }, { intros s S, cases s with a s; simp, exact ⟨s, S, T, rfl, rfl⟩ } }, { intros x s, exact ⟨s, S, T, rfl, rfl⟩ } end end }, { refine ⟨nil, S, T, _, _⟩; simp } end @[simp] theorem of_list_nil : of_list [] = (nil : seq α) := rfl @[simp] theorem of_list_cons (a : α) (l) : of_list (a :: l) = cons a (of_list l) := begin apply subtype.eq, simp [of_list, cons], funext n, cases n; simp [list.nth, stream.cons] end @[simp] theorem of_stream_cons (a : α) (s) : of_stream (a :: s) = cons a (of_stream s) := by apply subtype.eq; simp [of_stream, cons]; rw stream.map_cons @[simp] theorem of_list_append (l l' : list α) : of_list (l ++ l') = append (of_list l) (of_list l') := by induction l; simp [*] @[simp] theorem of_stream_append (l : list α) (s : stream α) : of_stream (l ++ₛ s) = append (of_list l) (of_stream s) := by induction l; simp [*, stream.nil_append_stream, stream.cons_append_stream] /-- Convert a sequence into a list, embedded in a computation to allow for the possibility of infinite sequences (in which case the computation never returns anything). -/ def to_list' {α} (s : seq α) : computation (list α) := @computation.corec (list α) (list α × seq α) (λ⟨l, s⟩, match destruct s with | none := sum.inl l.reverse | some (a, s') := sum.inr (a::l, s') end) ([], s) theorem dropn_add (s : seq α) (m) : ∀ n, drop s (m + n) = drop (drop s m) n | 0 := rfl | (n+1) := congr_arg tail (dropn_add n) theorem dropn_tail (s : seq α) (n) : drop (tail s) n = drop s (n + 1) := by rw add_comm; symmetry; apply dropn_add theorem nth_tail : ∀ (s : seq α) n, nth (tail s) n = nth s (n + 1) | ⟨f, al⟩ n := rfl @[simp] theorem head_dropn (s : seq α) (n) : head (drop s n) = nth s n := begin induction n with n IH generalizing s, { refl }, rw [nat.succ_eq_add_one, ←nth_tail, ←dropn_tail], apply IH end theorem mem_map (f : α → β) {a : α} : ∀ {s : seq α}, a ∈ s → f a ∈ map f s | ⟨g, al⟩ := stream.mem_map (option.map f) theorem exists_of_mem_map {f} {b : β} : ∀ {s : seq α}, b ∈ map f s → ∃ a, a ∈ s ∧ f a = b | ⟨g, al⟩ h := let ⟨o, om, oe⟩ := stream.exists_of_mem_map h in by cases o with a; injection oe with h'; exact ⟨a, om, h'⟩ theorem of_mem_append {s₁ s₂ : seq α} {a : α} (h : a ∈ append s₁ s₂) : a ∈ s₁ ∨ a ∈ s₂ := begin have := h, revert this, generalize e : append s₁ s₂ = ss, intro h, revert s₁, apply mem_rec_on h _, intros b s' o s₁, apply s₁.cases_on _ (λ c t₁, _); intros m e; have := congr_arg destruct e, { apply or.inr, simpa using m }, { cases (show a = c ∨ a ∈ append t₁ s₂, by simpa using m) with e' m, { rw e', exact or.inl (mem_cons _ _) }, { cases (show c = b ∧ append t₁ s₂ = s', by simpa) with i1 i2, cases o with e' IH, { simp [i1, e'] }, { exact or.imp_left (mem_cons_of_mem _) (IH m i2) } } } end theorem mem_append_left {s₁ s₂ : seq α} {a : α} (h : a ∈ s₁) : a ∈ append s₁ s₂ := by apply mem_rec_on h; intros; simp [*] end seq namespace seq1 variables {α : Type u} {β : Type v} {γ : Type w} open seq /-- Convert a `seq1` to a sequence. -/ def to_seq : seq1 α → seq α | (a, s) := cons a s instance coe_seq : has_coe (seq1 α) (seq α) := ⟨to_seq⟩ /-- Map a function on a `seq1` -/ def map (f : α → β) : seq1 α → seq1 β | (a, s) := (f a, seq.map f s) theorem map_id : ∀ (s : seq1 α), map id s = s | ⟨a, s⟩ := by simp [map] /-- Flatten a nonempty sequence of nonempty sequences -/ def join : seq1 (seq1 α) → seq1 α | ((a, s), S) := match destruct s with | none := (a, seq.join S) | some s' := (a, seq.join (cons s' S)) end @[simp] theorem join_nil (a : α) (S) : join ((a, nil), S) = (a, seq.join S) := rfl @[simp] theorem join_cons (a b : α) (s S) : join ((a, cons b s), S) = (a, seq.join (cons (b, s) S)) := by dsimp [join]; rw [destruct_cons]; refl /-- The `return` operator for the `seq1` monad, which produces a singleton sequence. -/ def ret (a : α) : seq1 α := (a, nil) /-- The `bind` operator for the `seq1` monad, which maps `f` on each element of `s` and appends the results together. (Not all of `s` may be evaluated, because the first few elements of `s` may already produce an infinite result.) -/ def bind (s : seq1 α) (f : α → seq1 β) : seq1 β := join (map f s) @[simp] theorem join_map_ret (s : seq α) : seq.join (seq.map ret s) = s := by apply coinduction2 s; intro s; apply cases_on s; simp [ret] @[simp] theorem bind_ret (f : α → β) : ∀ s, bind s (ret ∘ f) = map f s | ⟨a, s⟩ := begin dsimp [bind, map], change (λx, ret (f x)) with (ret ∘ f), rw [map_comp], simp [function.comp, ret] end @[simp] theorem ret_bind (a : α) (f : α → seq1 β) : bind (ret a) f = f a := begin simp [ret, bind, map], cases f a with a s, apply cases_on s; intros; simp end @[simp] theorem map_join' (f : α → β) (S) : seq.map f (seq.join S) = seq.join (seq.map (map f) S) := begin apply eq_of_bisim (λs1 s2, ∃ s S, s1 = append s (seq.map f (seq.join S)) ∧ s2 = append s (seq.join (seq.map (map f) S))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, S, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on S; simp, { intros x S, cases x with a s; simp [map], exact ⟨_, _, rfl, rfl⟩ } }, { intros x s, refine ⟨s, S, rfl, rfl⟩ } end end }, { refine ⟨nil, S, _, _⟩; simp } end @[simp] theorem map_join (f : α → β) : ∀ S, map f (join S) = join (map (map f) S) | ((a, s), S) := by apply cases_on s; intros; simp [map] @[simp] theorem join_join (SS : seq (seq1 (seq1 α))) : seq.join (seq.join SS) = seq.join (seq.map join SS) := begin apply eq_of_bisim (λs1 s2, ∃ s SS, s1 = seq.append s (seq.join (seq.join SS)) ∧ s2 = seq.append s (seq.join (seq.map join SS))), { intros s1 s2 h, exact match s1, s2, h with ._, ._, ⟨s, SS, rfl, rfl⟩ := begin apply cases_on s; simp, { apply cases_on SS; simp, { intros S SS, cases S with s S; cases s with x s; simp [map], apply cases_on s; simp, { exact ⟨_, _, rfl, rfl⟩ }, { intros x s, refine ⟨cons x (append s (seq.join S)), SS, _, _⟩; simp } } }, { intros x s, exact ⟨s, SS, rfl, rfl⟩ } end end }, { refine ⟨nil, SS, _, _⟩; simp } end @[simp] theorem bind_assoc (s : seq1 α) (f : α → seq1 β) (g : β → seq1 γ) : bind (bind s f) g = bind s (λ (x : α), bind (f x) g) := begin cases s with a s, simp [bind, map], rw [←map_comp], change (λ x, join (map g (f x))) with (join ∘ ((map g) ∘ f)), rw [map_comp _ join], generalize : seq.map (map g ∘ f) s = SS, rcases map g (f a) with ⟨⟨a, s⟩, S⟩, apply cases_on s; intros; apply cases_on S; intros; simp, { cases x with x t, apply cases_on t; intros; simp }, { cases x_1 with y t; simp } end instance : monad seq1 := { map := @map, pure := @ret, bind := @bind } instance : is_lawful_monad seq1 := { id_map := @map_id, bind_pure_comp_eq_map := @bind_ret, pure_bind := @ret_bind, bind_assoc := @bind_assoc } end seq1
a2dfa1573cd3eae73c10f1e78c1f10179cfc8632
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/legendre_symbol/jacobi_symbol.lean
7cead399fc0db63f192f3f80a041b89b14c4feec
[ "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
19,718
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import number_theory.legendre_symbol.quadratic_reciprocity /-! # The Jacobi Symbol > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the Jacobi symbol and prove its main properties. ## Main definitions We define the Jacobi symbol, `jacobi_sym a b`, for integers `a` and natural numbers `b` as the product over the prime factors `p` of `b` of the Legendre symbols `legendre_sym p a`. This agrees with the mathematical definition when `b` is odd. The prime factors are obtained via `nat.factors`. Since `nat.factors 0 = []`, this implies in particular that `jacobi_sym a 0 = 1` for all `a`. ## Main statements We prove the main properties of the Jacobi symbol, including the following. * Multiplicativity in both arguments (`jacobi_sym.mul_left`, `jacobi_sym.mul_right`) * The value of the symbol is `1` or `-1` when the arguments are coprime (`jacobi_sym.eq_one_or_neg_one`) * The symbol vanishes if and only if `b ≠ 0` and the arguments are not coprime (`jacobi_sym.eq_zero_iff`) * If the symbol has the value `-1`, then `a : zmod b` is not a square (`zmod.nonsquare_of_jacobi_sym_eq_neg_one`); the converse holds when `b = p` is a prime (`zmod.nonsquare_iff_jacobi_sym_eq_neg_one`); in particular, in this case `a` is a square mod `p` when the symbol has the value `1` (`zmod.is_square_of_jacobi_sym_eq_one`). * Quadratic reciprocity (`jacobi_sym.quadratic_reciprocity`, `jacobi_sym.quadratic_reciprocity_one_mod_four`, `jacobi_sym.quadratic_reciprocity_three_mod_four`) * The supplementary laws for `a = -1`, `a = 2`, `a = -2` (`jacobi_sym.at_neg_one`, `jacobi_sym.at_two`, `jacobi_sym.at_neg_two`) * The symbol depends on `a` only via its residue class mod `b` (`jacobi_sym.mod_left`) and on `b` only via its residue class mod `4*a` (`jacobi_sym.mod_right`) ## Notations We define the notation `J(a | b)` for `jacobi_sym a b`, localized to `number_theory_symbols`. ## Tags Jacobi symbol, quadratic reciprocity -/ section jacobi /-! ### Definition of the Jacobi symbol We define the Jacobi symbol $\Bigl(\frac{a}{b}\Bigr)$ for integers `a` and natural numbers `b` as the product of the Legendre symbols $\Bigl(\frac{a}{p}\Bigr)$, where `p` runs through the prime divisors (with multiplicity) of `b`, as provided by `b.factors`. This agrees with the Jacobi symbol when `b` is odd and gives less meaningful values when it is not (e.g., the symbol is `1` when `b = 0`). This is called `jacobi_sym a b`. We define localized notation (locale `number_theory_symbols`) `J(a | b)` for the Jacobi symbol `jacobi_sym a b`. -/ open nat zmod /-- The Jacobi symbol of `a` and `b` -/ -- Since we need the fact that the factors are prime, we use `list.pmap`. def jacobi_sym (a : ℤ) (b : ℕ) : ℤ := (b.factors.pmap (λ p pp, @legendre_sym p ⟨pp⟩ a) (λ p pf, prime_of_mem_factors pf)).prod -- Notation for the Jacobi symbol. localized "notation `J(` a ` | ` b `)` := jacobi_sym a b" in number_theory_symbols /-! ### Properties of the Jacobi symbol -/ namespace jacobi_sym /-- The symbol `J(a | 0)` has the value `1`. -/ @[simp] lemma zero_right (a : ℤ) : J(a | 0) = 1 := by simp only [jacobi_sym, factors_zero, list.prod_nil, list.pmap] /-- The symbol `J(a | 1)` has the value `1`. -/ @[simp] lemma one_right (a : ℤ) : J(a | 1) = 1 := by simp only [jacobi_sym, factors_one, list.prod_nil, list.pmap] /-- The Legendre symbol `legendre_sym p a` with an integer `a` and a prime number `p` is the same as the Jacobi symbol `J(a | p)`. -/ lemma _root_.legendre_sym.to_jacobi_sym (p : ℕ) [fp : fact p.prime] (a : ℤ) : legendre_sym p a = J(a | p) := by simp only [jacobi_sym, factors_prime fp.1, list.prod_cons, list.prod_nil, mul_one, list.pmap] /-- The Jacobi symbol is multiplicative in its second argument. -/ lemma mul_right' (a : ℤ) {b₁ b₂ : ℕ} (hb₁ : b₁ ≠ 0) (hb₂ : b₂ ≠ 0) : J(a | b₁ * b₂) = J(a | b₁) * J(a | b₂) := begin rw [jacobi_sym, ((perm_factors_mul hb₁ hb₂).pmap _).prod_eq, list.pmap_append, list.prod_append], exacts [rfl, λ p hp, (list.mem_append.mp hp).elim prime_of_mem_factors prime_of_mem_factors], end /-- The Jacobi symbol is multiplicative in its second argument. -/ lemma mul_right (a : ℤ) (b₁ b₂ : ℕ) [ne_zero b₁] [ne_zero b₂] : J(a | b₁ * b₂) = J(a | b₁) * J(a | b₂) := mul_right' a (ne_zero.ne b₁) (ne_zero.ne b₂) /-- The Jacobi symbol takes only the values `0`, `1` and `-1`. -/ lemma trichotomy (a : ℤ) (b : ℕ) : J(a | b) = 0 ∨ J(a | b) = 1 ∨ J(a | b) = -1 := ((@sign_type.cast_hom ℤ _ _).to_monoid_hom.mrange.copy {0, 1, -1} $ by {rw set.pair_comm, exact (sign_type.range_eq sign_type.cast_hom).symm}).list_prod_mem begin intros _ ha', rcases list.mem_pmap.mp ha' with ⟨p, hp, rfl⟩, haveI : fact p.prime := ⟨prime_of_mem_factors hp⟩, exact quadratic_char_is_quadratic (zmod p) a, end /-- The symbol `J(1 | b)` has the value `1`. -/ @[simp] lemma one_left (b : ℕ) : J(1 | b) = 1 := list.prod_eq_one (λ z hz, let ⟨p, hp, he⟩ := list.mem_pmap.1 hz in by rw [← he, legendre_sym.at_one]) /-- The Jacobi symbol is multiplicative in its first argument. -/ lemma mul_left (a₁ a₂ : ℤ) (b : ℕ) : J(a₁ * a₂ | b) = J(a₁ | b) * J(a₂ | b) := by { simp_rw [jacobi_sym, list.pmap_eq_map_attach, legendre_sym.mul], exact list.prod_map_mul } /-- The symbol `J(a | b)` vanishes iff `a` and `b` are not coprime (assuming `b ≠ 0`). -/ lemma eq_zero_iff_not_coprime {a : ℤ} {b : ℕ} [ne_zero b] : J(a | b) = 0 ↔ a.gcd b ≠ 1 := list.prod_eq_zero_iff.trans begin rw [list.mem_pmap, int.gcd_eq_nat_abs, ne, prime.not_coprime_iff_dvd], simp_rw [legendre_sym.eq_zero_iff, int_coe_zmod_eq_zero_iff_dvd, mem_factors (ne_zero.ne b), ← int.coe_nat_dvd_left, int.coe_nat_dvd, exists_prop, and_assoc, and_comm], end /-- The symbol `J(a | b)` is nonzero when `a` and `b` are coprime. -/ protected lemma ne_zero {a : ℤ} {b : ℕ} (h : a.gcd b = 1) : J(a | b) ≠ 0 := begin casesI eq_zero_or_ne_zero b with hb, { rw [hb, zero_right], exact one_ne_zero }, { contrapose! h, exact eq_zero_iff_not_coprime.1 h }, end /-- The symbol `J(a | b)` vanishes if and only if `b ≠ 0` and `a` and `b` are not coprime. -/ lemma eq_zero_iff {a : ℤ} {b : ℕ} : J(a | b) = 0 ↔ b ≠ 0 ∧ a.gcd b ≠ 1 := ⟨λ h, begin casesI eq_or_ne b 0 with hb hb, { rw [hb, zero_right] at h, cases h }, exact ⟨hb, mt jacobi_sym.ne_zero $ not_not.2 h⟩, end, λ ⟨hb, h⟩, by { rw ← ne_zero_iff at hb, exactI eq_zero_iff_not_coprime.2 h }⟩ /-- The symbol `J(0 | b)` vanishes when `b > 1`. -/ lemma zero_left {b : ℕ} (hb : 1 < b) : J(0 | b) = 0 := (@eq_zero_iff_not_coprime 0 b ⟨ne_zero_of_lt hb⟩).mpr $ by { rw [int.gcd_zero_left, int.nat_abs_of_nat], exact hb.ne' } /-- The symbol `J(a | b)` takes the value `1` or `-1` if `a` and `b` are coprime. -/ lemma eq_one_or_neg_one {a : ℤ} {b : ℕ} (h : a.gcd b = 1) : J(a | b) = 1 ∨ J(a | b) = -1 := (trichotomy a b).resolve_left $ jacobi_sym.ne_zero h /-- We have that `J(a^e | b) = J(a | b)^e`. -/ lemma pow_left (a : ℤ) (e b : ℕ) : J(a ^ e | b) = J(a | b) ^ e := nat.rec_on e (by rw [pow_zero, pow_zero, one_left]) $ λ _ ih, by rw [pow_succ, pow_succ, mul_left, ih] /-- We have that `J(a | b^e) = J(a | b)^e`. -/ lemma pow_right (a : ℤ) (b e : ℕ) : J(a | b ^ e) = J(a | b) ^ e := begin induction e with e ih, { rw [pow_zero, pow_zero, one_right], }, { casesI eq_zero_or_ne_zero b with hb, { rw [hb, zero_pow (succ_pos e), zero_right, one_pow], }, { rw [pow_succ, pow_succ, mul_right, ih], } } end /-- The square of `J(a | b)` is `1` when `a` and `b` are coprime. -/ lemma sq_one {a : ℤ} {b : ℕ} (h : a.gcd b = 1) : J(a | b) ^ 2 = 1 := by cases eq_one_or_neg_one h with h₁ h₁; rw h₁; refl /-- The symbol `J(a^2 | b)` is `1` when `a` and `b` are coprime. -/ lemma sq_one' {a : ℤ} {b : ℕ} (h : a.gcd b = 1) : J(a ^ 2 | b) = 1 := by rw [pow_left, sq_one h] /-- The symbol `J(a | b)` depends only on `a` mod `b`. -/ lemma mod_left (a : ℤ) (b : ℕ) : J(a | b) = J(a % b | b) := congr_arg list.prod $ list.pmap_congr _ begin rintro p hp _ _, conv_rhs { rw [legendre_sym.mod, int.mod_mod_of_dvd _ (int.coe_nat_dvd.2 $ dvd_of_mem_factors hp), ← legendre_sym.mod] }, end /-- The symbol `J(a | b)` depends only on `a` mod `b`. -/ lemma mod_left' {a₁ a₂ : ℤ} {b : ℕ} (h : a₁ % b = a₂ % b) : J(a₁ | b) = J(a₂ | b) := by rw [mod_left, h, ← mod_left] /-- If `p` is prime, `J(a | p) = -1` and `p` divides `x^2 - a*y^2`, then `p` must divide `x` and `y`. -/ lemma prime_dvd_of_eq_neg_one {p : ℕ} [fact p.prime] {a : ℤ} (h : J(a | p) = -1) {x y : ℤ} (hxy : ↑p ∣ x ^ 2 - a * y ^ 2) : ↑p ∣ x ∧ ↑p ∣ y := begin rw [← legendre_sym.to_jacobi_sym] at h, exact legendre_sym.prime_dvd_of_eq_neg_one h hxy, end /-- We can pull out a product over a list in the first argument of the Jacobi symbol. -/ lemma list_prod_left {l : list ℤ} {n : ℕ} : J(l.prod | n) = (l.map (λ a, J(a | n))).prod := begin induction l with n l' ih, { simp only [list.prod_nil, list.map_nil, one_left], }, { rw [list.map, list.prod_cons, list.prod_cons, mul_left, ih], } end /-- We can pull out a product over a list in the second argument of the Jacobi symbol. -/ lemma list_prod_right {a : ℤ} {l : list ℕ} (hl : ∀ n ∈ l, n ≠ 0) : J(a | l.prod) = (l.map (λ n, J(a | n))).prod := begin induction l with n l' ih, { simp only [list.prod_nil, one_right, list.map_nil], }, { have hn := hl n (list.mem_cons_self n l'), -- `n ≠ 0` have hl' := list.prod_ne_zero (λ hf, hl 0 (list.mem_cons_of_mem _ hf) rfl), -- `l'.prod ≠ 0` have h := λ m hm, hl m (list.mem_cons_of_mem _ hm), -- `∀ (m : ℕ), m ∈ l' → m ≠ 0` rw [list.map, list.prod_cons, list.prod_cons, mul_right' a hn hl', ih h], } end /-- If `J(a | n) = -1`, then `n` has a prime divisor `p` such that `J(a | p) = -1`. -/ lemma eq_neg_one_at_prime_divisor_of_eq_neg_one {a : ℤ} {n : ℕ} (h : J(a | n) = -1) : ∃ (p : ℕ) (hp : p.prime), p ∣ n ∧ J(a | p) = -1 := begin have hn₀ : n ≠ 0, { rintro rfl, rw [zero_right, eq_neg_self_iff] at h, exact one_ne_zero h, }, have hf₀ : ∀ p ∈ n.factors, p ≠ 0 := λ p hp, (nat.pos_of_mem_factors hp).ne.symm, rw [← nat.prod_factors hn₀, list_prod_right hf₀] at h, obtain ⟨p, hmem, hj⟩ := list.mem_map.mp (list.neg_one_mem_of_prod_eq_neg_one h), exact ⟨p, nat.prime_of_mem_factors hmem, nat.dvd_of_mem_factors hmem, hj⟩, end end jacobi_sym namespace zmod open jacobi_sym /-- If `J(a | b)` is `-1`, then `a` is not a square modulo `b`. -/ lemma nonsquare_of_jacobi_sym_eq_neg_one {a : ℤ} {b : ℕ} (h : J(a | b) = -1) : ¬ is_square (a : zmod b) := λ ⟨r, ha⟩, begin rw [← r.coe_val_min_abs, ← int.cast_mul, int_coe_eq_int_coe_iff', ← sq] at ha, apply (by norm_num : ¬ (0 : ℤ) ≤ -1), rw [← h, mod_left, ha, ← mod_left, pow_left], apply sq_nonneg, end /-- If `p` is prime, then `J(a | p)` is `-1` iff `a` is not a square modulo `p`. -/ lemma nonsquare_iff_jacobi_sym_eq_neg_one {a : ℤ} {p : ℕ} [fact p.prime] : J(a | p) = -1 ↔ ¬ is_square (a : zmod p) := by { rw [← legendre_sym.to_jacobi_sym], exact legendre_sym.eq_neg_one_iff p } /-- If `p` is prime and `J(a | p) = 1`, then `a` is q square mod `p`. -/ lemma is_square_of_jacobi_sym_eq_one {a : ℤ} {p : ℕ} [fact p.prime] (h : J(a | p) = 1) : is_square (a : zmod p) := not_not.mp $ by { rw [← nonsquare_iff_jacobi_sym_eq_neg_one, h], dec_trivial } end zmod /-! ### Values at `-1`, `2` and `-2` -/ namespace jacobi_sym /-- If `χ` is a multiplicative function such that `J(a | p) = χ p` for all odd primes `p`, then `J(a | b)` equals `χ b` for all odd natural numbers `b`. -/ lemma value_at (a : ℤ) {R : Type*} [comm_semiring R] (χ : R →* ℤ) (hp : ∀ (p : ℕ) (pp : p.prime) (h2 : p ≠ 2), @legendre_sym p ⟨pp⟩ a = χ p) {b : ℕ} (hb : odd b) : J(a | b) = χ b := begin conv_rhs { rw [← prod_factors hb.pos.ne', cast_list_prod, χ.map_list_prod] }, rw [jacobi_sym, list.map_map, ← list.pmap_eq_map nat.prime _ _ (λ _, prime_of_mem_factors)], congr' 1, apply list.pmap_congr, exact λ p h pp _, hp p pp (hb.ne_two_of_dvd_nat $ dvd_of_mem_factors h) end /-- If `b` is odd, then `J(-1 | b)` is given by `χ₄ b`. -/ lemma at_neg_one {b : ℕ} (hb : odd b) : J(-1 | b) = χ₄ b := value_at (-1) χ₄ (λ p pp, @legendre_sym.at_neg_one p ⟨pp⟩) hb /-- If `b` is odd, then `J(-a | b) = χ₄ b * J(a | b)`. -/ protected lemma neg (a : ℤ) {b : ℕ} (hb : odd b) : J(-a | b) = χ₄ b * J(a | b) := by rw [neg_eq_neg_one_mul, mul_left, at_neg_one hb] /-- If `b` is odd, then `J(2 | b)` is given by `χ₈ b`. -/ lemma at_two {b : ℕ} (hb : odd b) : J(2 | b) = χ₈ b := value_at 2 χ₈ (λ p pp, @legendre_sym.at_two p ⟨pp⟩) hb /-- If `b` is odd, then `J(-2 | b)` is given by `χ₈' b`. -/ lemma at_neg_two {b : ℕ} (hb : odd b) : J(-2 | b) = χ₈' b := value_at (-2) χ₈' (λ p pp, @legendre_sym.at_neg_two p ⟨pp⟩) hb end jacobi_sym /-! ### Quadratic Reciprocity -/ /-- The bi-multiplicative map giving the sign in the Law of Quadratic Reciprocity -/ def qr_sign (m n : ℕ) : ℤ := J(χ₄ m | n) namespace qr_sign /-- We can express `qr_sign m n` as a power of `-1` when `m` and `n` are odd. -/ lemma neg_one_pow {m n : ℕ} (hm : odd m) (hn : odd n) : qr_sign m n = (-1) ^ ((m / 2) * (n / 2)) := begin rw [qr_sign, pow_mul, ← χ₄_eq_neg_one_pow (odd_iff.mp hm)], cases odd_mod_four_iff.mp (odd_iff.mp hm) with h h, { rw [χ₄_nat_one_mod_four h, jacobi_sym.one_left, one_pow], }, { rw [χ₄_nat_three_mod_four h, ← χ₄_eq_neg_one_pow (odd_iff.mp hn), jacobi_sym.at_neg_one hn], } end /-- When `m` and `n` are odd, then the square of `qr_sign m n` is `1`. -/ lemma sq_eq_one {m n : ℕ} (hm : odd m) (hn : odd n) : (qr_sign m n) ^ 2 = 1 := by rw [neg_one_pow hm hn, ← pow_mul, mul_comm, pow_mul, neg_one_sq, one_pow] /-- `qr_sign` is multiplicative in the first argument. -/ lemma mul_left (m₁ m₂ n : ℕ) : qr_sign (m₁ * m₂) n = qr_sign m₁ n * qr_sign m₂ n := by simp_rw [qr_sign, nat.cast_mul, map_mul, jacobi_sym.mul_left] /-- `qr_sign` is multiplicative in the second argument. -/ lemma mul_right (m n₁ n₂ : ℕ) [ne_zero n₁] [ne_zero n₂] : qr_sign m (n₁ * n₂) = qr_sign m n₁ * qr_sign m n₂ := jacobi_sym.mul_right (χ₄ m) n₁ n₂ /-- `qr_sign` is symmetric when both arguments are odd. -/ protected lemma symm {m n : ℕ} (hm : odd m) (hn : odd n) : qr_sign m n = qr_sign n m := by rw [neg_one_pow hm hn, neg_one_pow hn hm, mul_comm (m / 2)] /-- We can move `qr_sign m n` from one side of an equality to the other when `m` and `n` are odd. -/ lemma eq_iff_eq {m n : ℕ} (hm : odd m) (hn : odd n) (x y : ℤ) : qr_sign m n * x = y ↔ x = qr_sign m n * y := by refine ⟨λ h', let h := h'.symm in _, λ h, _⟩; rw [h, ← mul_assoc, ← pow_two, sq_eq_one hm hn, one_mul] end qr_sign namespace jacobi_sym /-- The Law of Quadratic Reciprocity for the Jacobi symbol, version with `qr_sign` -/ lemma quadratic_reciprocity' {a b : ℕ} (ha : odd a) (hb : odd b) : J(a | b) = qr_sign b a * J(b | a) := begin -- define the right hand side for fixed `a` as a `ℕ →* ℤ` let rhs : ℕ → ℕ →* ℤ := λ a, { to_fun := λ x, qr_sign x a * J(x | a), map_one' := by { convert ← mul_one _, symmetry, all_goals { apply one_left } }, map_mul' := λ x y, by rw [qr_sign.mul_left, nat.cast_mul, mul_left, mul_mul_mul_comm] }, have rhs_apply : ∀ (a b : ℕ), rhs a b = qr_sign b a * J(b | a) := λ a b, rfl, refine value_at a (rhs a) (λ p pp hp, eq.symm _) hb, have hpo := pp.eq_two_or_odd'.resolve_left hp, rw [@legendre_sym.to_jacobi_sym p ⟨pp⟩, rhs_apply, nat.cast_id, qr_sign.eq_iff_eq hpo ha, qr_sign.symm hpo ha], refine value_at p (rhs p) (λ q pq hq, _) ha, have hqo := pq.eq_two_or_odd'.resolve_left hq, rw [rhs_apply, nat.cast_id, ← @legendre_sym.to_jacobi_sym p ⟨pp⟩, qr_sign.symm hqo hpo, qr_sign.neg_one_pow hpo hqo, @legendre_sym.quadratic_reciprocity' p q ⟨pp⟩ ⟨pq⟩ hp hq], end /-- The Law of Quadratic Reciprocity for the Jacobi symbol -/ lemma quadratic_reciprocity {a b : ℕ} (ha : odd a) (hb : odd b) : J(a | b) = (-1) ^ ((a / 2) * (b / 2)) * J(b | a) := by rw [← qr_sign.neg_one_pow ha hb, qr_sign.symm ha hb, quadratic_reciprocity' ha hb] /-- The Law of Quadratic Reciprocity for the Jacobi symbol: if `a` and `b` are natural numbers with `a % 4 = 1` and `b` odd, then `J(a | b) = J(b | a)`. -/ theorem quadratic_reciprocity_one_mod_four {a b : ℕ} (ha : a % 4 = 1) (hb : odd b) : J(a | b) = J(b | a) := by rw [quadratic_reciprocity (odd_iff.mpr (odd_of_mod_four_eq_one ha)) hb, pow_mul, neg_one_pow_div_two_of_one_mod_four ha, one_pow, one_mul] /-- The Law of Quadratic Reciprocity for the Jacobi symbol: if `a` and `b` are natural numbers with `a` odd and `b % 4 = 1`, then `J(a | b) = J(b | a)`. -/ theorem quadratic_reciprocity_one_mod_four' {a b : ℕ} (ha : odd a) (hb : b % 4 = 1) : J(a | b) = J(b | a) := (quadratic_reciprocity_one_mod_four hb ha).symm /-- The Law of Quadratic Reciprocityfor the Jacobi symbol: if `a` and `b` are natural numbers both congruent to `3` mod `4`, then `J(a | b) = -J(b | a)`. -/ theorem quadratic_reciprocity_three_mod_four {a b : ℕ} (ha : a % 4 = 3) (hb : b % 4 = 3) : J(a | b) = - J(b | a) := let nop := @neg_one_pow_div_two_of_three_mod_four in begin rw [quadratic_reciprocity, pow_mul, nop ha, nop hb, neg_one_mul]; rwa [odd_iff, odd_of_mod_four_eq_three], end /-- The Jacobi symbol `J(a | b)` depends only on `b` mod `4*a` (version for `a : ℕ`). -/ lemma mod_right' (a : ℕ) {b : ℕ} (hb : odd b) : J(a | b) = J(a | b % (4 * a)) := begin rcases eq_or_ne a 0 with rfl | ha₀, { rw [mul_zero, mod_zero], }, have hb' : odd (b % (4 * a)) := hb.mod_even (even.mul_right (by norm_num) _), rcases exists_eq_pow_mul_and_not_dvd ha₀ 2 (by norm_num) with ⟨e, a', ha₁', ha₂⟩, have ha₁ := odd_iff.mpr (two_dvd_ne_zero.mp ha₁'), nth_rewrite 1 [ha₂], nth_rewrite 0 [ha₂], rw [nat.cast_mul, mul_left, mul_left, quadratic_reciprocity' ha₁ hb, quadratic_reciprocity' ha₁ hb', nat.cast_pow, pow_left, pow_left, nat.cast_two, at_two hb, at_two hb'], congr' 1, swap, congr' 1, { simp_rw [qr_sign], rw [χ₄_nat_mod_four, χ₄_nat_mod_four (b % (4 * a)), mod_mod_of_dvd b (dvd_mul_right 4 a) ] }, { rw [mod_left ↑(b % _), mod_left b, int.coe_nat_mod, int.mod_mod_of_dvd b], simp only [ha₂, nat.cast_mul, ← mul_assoc], exact dvd_mul_left a' _, }, cases e, { refl }, { rw [χ₈_nat_mod_eight, χ₈_nat_mod_eight (b % (4 * a)), mod_mod_of_dvd b], use 2 ^ e * a', rw [ha₂, pow_succ], ring, } end /-- The Jacobi symbol `J(a | b)` depends only on `b` mod `4*a`. -/ lemma mod_right (a : ℤ) {b : ℕ} (hb : odd b) : J(a | b) = J(a | b % (4 * a.nat_abs)) := begin cases int.nat_abs_eq a with ha ha; nth_rewrite 1 [ha]; nth_rewrite 0 [ha], { exact mod_right' a.nat_abs hb, }, { have hb' : odd (b % (4 * a.nat_abs)) := hb.mod_even (even.mul_right (by norm_num) _), rw [jacobi_sym.neg _ hb, jacobi_sym.neg _ hb', mod_right' _ hb, χ₄_nat_mod_four, χ₄_nat_mod_four (b % (4 * _)), mod_mod_of_dvd b (dvd_mul_right 4 _)], } end end jacobi_sym end jacobi
25bd00d058a40a42bd0e426ec00729f6a7c81dbd
63abd62053d479eae5abf4951554e1064a4c45b4
/src/control/traversable/derive.lean
4b87bd762a4a6205156b94c901f2599b13ea668b
[ "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
17,017
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Automation to construct `traversable` instances -/ import control.traversable.lemmas import data.list.basic namespace tactic.interactive open tactic list monad functor meta def with_prefix : option name → name → name | none n := n | (some p) n := p ++ n /-- similar to `nested_traverse` but for `functor` -/ meta def nested_map (f v : expr) : expr → tactic expr | t := do t ← instantiate_mvars t, mcond (succeeds $ is_def_eq t v) (pure f) (if ¬ v.occurs (t.app_fn) then do cl ← mk_app ``functor [t.app_fn], _inst ← mk_instance cl, f' ← nested_map t.app_arg, mk_mapp ``functor.map [t.app_fn,_inst,none,none,f'] else fail format!"type {t} is not a functor with respect to variable {v}") /-- similar to `traverse_field` but for `functor` -/ meta def map_field (n : name) (cl f α β e : expr) : tactic expr := do t ← infer_type e >>= whnf, if t.get_app_fn.const_name = n then fail "recursive types not supported" else if α =ₐ e then pure β else if α.occurs t then do f' ← nested_map f α t, pure $ f' e else (is_def_eq t.app_fn cl >> mk_app ``comp.mk [e]) <|> pure e /-- similar to `traverse_constructor` but for `functor` -/ meta def map_constructor (c n : name) (f α β : expr) (args₀ : list expr) (args₁ : list (bool × expr)) (rec_call : list expr) : tactic expr := do g ← target, (_, args') ← mmap_accuml (λ (x : list expr) (y : bool × expr), if y.1 then pure (x.tail,x.head) else prod.mk rec_call <$> map_field n g.app_fn f α β y.2) rec_call args₁, constr ← mk_const c, let r := constr.mk_app (args₀ ++ args'), return r /-- derive the `map` definition of a `functor` -/ meta def mk_map (type : name) := do ls ← local_context, [α,β,f,x] ← tactic.intro_lst [`α,`β,`f,`x], et ← infer_type x, xs ← tactic.induction x, xs.mmap' (λ (x : name × list expr × list (name × expr)), do let (c,args,_) := x, (args,rec_call) ← args.mpartition $ λ e, (bnot ∘ β.occurs) <$> infer_type e, args₀ ← args.mmap $ λ a, do { b ← et.occurs <$> infer_type a, pure (b,a) }, map_constructor c type f α β (ls ++ [β]) args₀ rec_call >>= tactic.exact) meta def mk_mapp_aux' : expr → expr → list expr → tactic expr | fn (expr.pi n bi d b) (a::as) := do infer_type a >>= unify d, fn ← head_beta (fn a), t ← whnf (b.instantiate_var a), mk_mapp_aux' fn t as | fn _ _ := pure fn meta def mk_mapp' (fn : expr) (args : list expr) : tactic expr := do t ← infer_type fn >>= whnf, mk_mapp_aux' fn t args /-- derive the equations for a specific `map` definition -/ meta def derive_map_equations (pre : option name) (n : name) (vs : list expr) (tgt : expr) : tactic unit := do e ← get_env, ((e.constructors_of n).enum_from 1).mmap' $ λ ⟨i,c⟩, do { mk_meta_var tgt >>= set_goals ∘ pure, vs ← intro_lst $ vs.map expr.local_pp_name, [α,β,f] ← tactic.intro_lst [`α,`β,`f] >>= mmap instantiate_mvars, c' ← mk_mapp c $ vs.map some ++ [α], tgt' ← infer_type c' >>= pis vs, mk_meta_var tgt' >>= set_goals ∘ pure, vs ← tactic.intro_lst $ vs.map expr.local_pp_name, vs' ← tactic.intros, c' ← mk_mapp c $ vs.map some ++ [α], arg ← mk_mapp' c' vs', n_map ← mk_const (with_prefix pre n <.> "map"), let call_map := λ x, mk_mapp' n_map (vs ++ [α,β,f,x]), lhs ← call_map arg, args ← vs'.mmap $ λ a, do { t ← infer_type a, pure ((expr.const_name (expr.get_app_fn t) = n : bool),a) }, let rec_call := args.filter_map $ λ ⟨b, e⟩, guard b >> pure e, rec_call ← rec_call.mmap call_map, rhs ← map_constructor c n f α β (vs ++ [β]) args rec_call, monad.join $ unify <$> infer_type lhs <*> infer_type rhs, eqn ← mk_app ``eq [lhs,rhs], let ws := eqn.list_local_consts, eqn ← pis ws.reverse eqn, eqn ← instantiate_mvars eqn, (_,pr) ← solve_aux eqn (tactic.intros >> refine ``(rfl)), let eqn_n := (with_prefix pre n <.> "map" <.> "equations" <.> "_eqn").append_after i, pr ← instantiate_mvars pr, add_decl $ declaration.thm eqn_n eqn.collect_univ_params eqn (pure pr), return () }, set_goals [], return () meta def derive_functor (pre : option name) : tactic unit := do vs ← local_context, `(functor %%f) ← target, env ← get_env, let n := f.get_app_fn.const_name, d ← get_decl n, refine ``( { functor . map := _ , .. } ), tgt ← target, extract_def (with_prefix pre n <.> "map") d.is_trusted $ mk_map n, when (d.is_trusted) $ do tgt ← pis vs tgt, derive_map_equations pre n vs tgt /-- `seq_apply_constructor f [x,y,z]` synthesizes `f <*> x <*> y <*> z` -/ private meta def seq_apply_constructor : expr → list (expr ⊕ expr) → tactic (list (tactic expr) × expr) | e (sum.inr x :: xs) := prod.map (cons intro1) id <$> (to_expr ``(%%e <*> %%x) >>= flip seq_apply_constructor xs) | e (sum.inl x :: xs) := prod.map (cons $ pure x) id <$> seq_apply_constructor e xs | e [] := return ([],e) /-- ``nested_traverse f α (list (array n (list α)))`` synthesizes the expression `traverse (traverse (traverse f))`. `nested_traverse` assumes that `α` appears in `(list (array n (list α)))` -/ meta def nested_traverse (f v : expr) : expr → tactic expr | t := do t ← instantiate_mvars t, mcond (succeeds $ is_def_eq t v) (pure f) (if ¬ v.occurs (t.app_fn) then do cl ← mk_app ``traversable [t.app_fn], _inst ← mk_instance cl, f' ← nested_traverse t.app_arg, mk_mapp ``traversable.traverse [t.app_fn,_inst,none,none,none,none,f'] else fail format!"type {t} is not traversable with respect to variable {v}") /-- For a sum type `inductive foo (α : Type) | foo1 : list α → ℕ → foo | ...` ``traverse_field `foo appl_inst f `α `(x : list α)`` synthesizes `traverse f x` as part of traversing `foo1`. -/ meta def traverse_field (n : name) (appl_inst cl f v e : expr) : tactic (expr ⊕ expr) := do t ← infer_type e >>= whnf, if t.get_app_fn.const_name = n then fail "recursive types not supported" else if v.occurs t then do f' ← nested_traverse f v t, pure $ sum.inr $ f' e else (is_def_eq t.app_fn cl >> sum.inr <$> mk_app ``comp.mk [e]) <|> pure (sum.inl e) /-- For a sum type `inductive foo (α : Type) | foo1 : list α → ℕ → foo | ...` ``traverse_constructor `foo1 `foo appl_inst f `α `β [`(x : list α), `(y : ℕ)]`` synthesizes `foo1 <$> traverse f x <*> pure y.` -/ meta def traverse_constructor (c n : name) (appl_inst f α β : expr) (args₀ : list expr) (args₁ : list (bool × expr)) (rec_call : list expr) : tactic expr := do g ← target, args' ← mmap (traverse_field n appl_inst g.app_fn f α) args₀, (_, args') ← mmap_accuml (λ (x : list expr) (y : bool × _), if y.1 then pure (x.tail, sum.inr x.head) else prod.mk x <$> traverse_field n appl_inst g.app_fn f α y.2) rec_call args₁, constr ← mk_const c, v ← mk_mvar, constr' ← to_expr ``(@pure _ (%%appl_inst).to_has_pure _ %%v), (vars_intro,r) ← seq_apply_constructor constr' (args₀.map sum.inl ++ args'), gs ← get_goals, set_goals [v], vs ← vars_intro.mmap id, tactic.exact (constr.mk_app vs), done, set_goals gs, return r /-- derive the `traverse` definition of a `traversable` instance -/ meta def mk_traverse (type : name) := do do ls ← local_context, [m,appl_inst,α,β,f,x] ← tactic.intro_lst [`m,`appl_inst,`α,`β,`f,`x], et ← infer_type x, reset_instance_cache, xs ← tactic.induction x, xs.mmap' (λ (x : name × list expr × list (name × expr)), do let (c,args,_) := x, (args,rec_call) ← args.mpartition $ λ e, (bnot ∘ β.occurs) <$> infer_type e, args₀ ← args.mmap $ λ a, do { b ← et.occurs <$> infer_type a, pure (b,a) }, traverse_constructor c type appl_inst f α β (ls ++ [β]) args₀ rec_call >>= tactic.exact) open applicative /-- derive the equations for a specific `traverse` definition -/ meta def derive_traverse_equations (pre : option name) (n : name) (vs : list expr) (tgt : expr) : tactic unit := do e ← get_env, ((e.constructors_of n).enum_from 1).mmap' $ λ ⟨i,c⟩, do { mk_meta_var tgt >>= set_goals ∘ pure, vs ← intro_lst $ vs.map expr.local_pp_name, [m,appl_inst,α,β,f] ← tactic.intro_lst [`m,`appl_inst,`α,`β,`f] >>= mmap instantiate_mvars, c' ← mk_mapp c $ vs.map some ++ [α], tgt' ← infer_type c' >>= pis vs, mk_meta_var tgt' >>= set_goals ∘ pure, vs ← tactic.intro_lst $ vs.map expr.local_pp_name, c' ← mk_mapp c $ vs.map some ++ [α], vs' ← tactic.intros, arg ← mk_mapp' c' vs', n_map ← mk_const (with_prefix pre n <.> "traverse"), let call_traverse := λ x, mk_mapp' n_map (vs ++ [m,appl_inst,α,β,f,x]), lhs ← call_traverse arg, args ← vs'.mmap $ λ a, do { t ← infer_type a, pure ((expr.const_name (expr.get_app_fn t) = n : bool),a) }, let rec_call := args.filter_map $ λ ⟨b, e⟩, guard b >> pure e, rec_call ← rec_call.mmap call_traverse, rhs ← traverse_constructor c n appl_inst f α β (vs ++ [β]) args rec_call, monad.join $ unify <$> infer_type lhs <*> infer_type rhs, eqn ← mk_app ``eq [lhs,rhs], let ws := eqn.list_local_consts, eqn ← pis ws.reverse eqn, eqn ← instantiate_mvars eqn, (_,pr) ← solve_aux eqn (tactic.intros >> refine ``(rfl)), let eqn_n := (with_prefix pre n <.> "traverse" <.> "equations" <.> "_eqn").append_after i, pr ← instantiate_mvars pr, add_decl $ declaration.thm eqn_n eqn.collect_univ_params eqn (pure pr), return () }, set_goals [], return () meta def derive_traverse (pre : option name) : tactic unit := do vs ← local_context, `(traversable %%f) ← target, env ← get_env, let n := f.get_app_fn.const_name, d ← get_decl n, constructor, tgt ← target, extract_def (with_prefix pre n <.> "traverse") d.is_trusted $ mk_traverse n, when (d.is_trusted) $ do tgt ← pis vs tgt, derive_traverse_equations pre n vs tgt meta def mk_one_instance (n : name) (cls : name) (tac : tactic unit) (namesp : option name) (mk_inst : name → expr → tactic expr := λ n arg, mk_app n [arg]) : tactic unit := do decl ← get_decl n, cls_decl ← get_decl cls, env ← get_env, guard (env.is_inductive n) <|> fail format!"failed to derive '{cls}', '{n}' is not an inductive type", let ls := decl.univ_params.map $ λ n, level.param n, -- incrementally build up target expression `Π (hp : p) [cls hp] ..., cls (n.{ls} hp ...)` -- where `p ...` are the inductive parameter types of `n` let tgt : expr := expr.const n ls, ⟨params, _⟩ ← open_pis (decl.type.instantiate_univ_params (decl.univ_params.zip ls)), let params := params.init, let tgt := tgt.mk_app params, tgt ← mk_inst cls tgt, tgt ← params.enum.mfoldr (λ ⟨i, param⟩ tgt, do -- add typeclass hypothesis for each inductive parameter tgt ← do { guard $ i < env.inductive_num_params n, param_cls ← mk_app cls [param], pure $ expr.pi `a binder_info.inst_implicit param_cls tgt } <|> pure tgt, pure $ tgt.bind_pi param ) tgt, () <$ mk_instance tgt <|> do (_, val) ← tactic.solve_aux tgt (do tactic.intros >> tac), val ← instantiate_mvars val, let trusted := decl.is_trusted ∧ cls_decl.is_trusted, let inst_n := with_prefix namesp n ++ cls, add_decl (declaration.defn inst_n decl.univ_params tgt val reducibility_hints.abbrev trusted), set_basic_attribute `instance inst_n namesp.is_none open interactive meta def get_equations_of (n : name) : tactic (list pexpr) := do e ← get_env, let pre := n <.> "equations", let x := e.fold [] $ λ d xs, if pre.is_prefix_of d.to_name then d.to_name :: xs else xs, x.mmap resolve_name meta def derive_lawful_functor (pre : option name) : tactic unit := do `(@is_lawful_functor %%f %%d) ← target, refine ``( { .. } ), let n := f.get_app_fn.const_name, let rules := λ r, [simp_arg_type.expr r, simp_arg_type.all_hyps], let goal := loc.ns [none], solve1 (do vs ← tactic.intros, try $ dunfold [``functor.map] (loc.ns [none]), dunfold [with_prefix pre n <.> "map",``id] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp none ff (rules ``(functor.map_id)) [] goal), focus1 (do vs ← tactic.intros, try $ dunfold [``functor.map] (loc.ns [none]), dunfold [with_prefix pre n <.> "map",``id] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp none ff (rules ``(functor.map_comp_map)) [] goal), return () meta def simp_functor (rs : list simp_arg_type := []) : tactic unit := simp none ff rs [`functor_norm] (loc.ns [none]) meta def traversable_law_starter (rs : list simp_arg_type) := do vs ← tactic.intros, resetI, dunfold [``traversable.traverse,``functor.map] (loc.ns [none]), () <$ tactic.induction vs.ilast; simp_functor rs meta def derive_lawful_traversable (pre : option name) : tactic unit := do `(@is_lawful_traversable %%f %%d) ← target, let n := f.get_app_fn.const_name, eqns ← get_equations_of (with_prefix pre n <.> "traverse"), eqns' ← get_equations_of (with_prefix pre n <.> "map"), let def_eqns := eqns.map simp_arg_type.expr ++ eqns'.map simp_arg_type.expr ++ [simp_arg_type.all_hyps], let comp_def := [ simp_arg_type.expr ``(function.comp) ], let tr_map := list.map simp_arg_type.expr [``(traversable.traverse_eq_map_id')], let natur := λ (η : expr), [simp_arg_type.expr ``(traversable.naturality_pf %%η)], let goal := loc.ns [none], constructor; [ traversable_law_starter def_eqns; refl, traversable_law_starter def_eqns; (refl <|> simp_functor (def_eqns ++ comp_def)), traversable_law_starter def_eqns; (refl <|> simp none tt tr_map [] goal ), traversable_law_starter def_eqns; (refl <|> do η ← get_local `η <|> do { t ← mk_const ``is_lawful_traversable.naturality >>= infer_type >>= pp, fail format!"expecting an `applicative_transformation` called `η` in\nnaturality : {t}"}, simp none tt (natur η) [] goal) ]; refl, return () open function meta def guard_class (cls : name) (hdl : derive_handler) : derive_handler := λ p n, if p.is_constant_of cls then hdl p n else pure ff meta def higher_order_derive_handler (cls : name) (tac : tactic unit) (deps : list derive_handler := []) (namesp : option name) (mk_inst : name → expr → tactic expr := λ n arg, mk_app n [arg]) : derive_handler := λ p n, do mmap' (λ f : derive_handler, f p n) deps, mk_one_instance n cls tac namesp mk_inst, pure tt meta def functor_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``functor (derive_functor nspace) [] nspace @[derive_handler] meta def functor_derive_handler : derive_handler := guard_class ``functor functor_derive_handler' meta def traversable_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``traversable (derive_traverse nspace) [functor_derive_handler' nspace] nspace @[derive_handler] meta def traversable_derive_handler : derive_handler := guard_class ``traversable traversable_derive_handler' meta def lawful_functor_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``is_lawful_functor (derive_lawful_functor nspace) [traversable_derive_handler' nspace] nspace (λ n arg, mk_mapp n [arg,none]) @[derive_handler] meta def lawful_functor_derive_handler : derive_handler := guard_class ``is_lawful_functor lawful_functor_derive_handler' meta def lawful_traversable_derive_handler' (nspace : option name := none) : derive_handler := higher_order_derive_handler ``is_lawful_traversable (derive_lawful_traversable nspace) [traversable_derive_handler' nspace, lawful_functor_derive_handler' nspace] nspace (λ n arg, mk_mapp n [arg,none]) @[derive_handler] meta def lawful_traversable_derive_handler : derive_handler := guard_class ``is_lawful_traversable lawful_traversable_derive_handler' end tactic.interactive
b3ab30cb4987896e2d5cddb01a17779f01a4d57a
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Command.lean
81b367251792fbc29930d19de44bcd14ca74dedf
[ "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
20,540
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Log import Lean.Parser.Command import Lean.ResolveName import Lean.Meta.Reduce import Lean.Elab.Term import Lean.Elab.Tactic.Cache import Lean.Elab.Binders import Lean.Elab.SyntheticMVars import Lean.Elab.DeclModifiers import Lean.Elab.InfoTree import Lean.Elab.SetOption namespace Lean.Elab.Command structure Scope where header : String opts : Options := {} currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] levelNames : List Name := [] /-- section variables -/ varDecls : Array (TSyntax ``Parser.Term.bracketedBinder) := #[] /-- Globally unique internal identifiers for the `varDecls` -/ varUIds : Array Name := #[] /-- noncomputable sections automatically add the `noncomputable` modifier to any declaration we cannot generate code for. -/ isNoncomputable : Bool := false deriving Inhabited structure State where env : Environment messages : MessageLog := {} scopes : List Scope := [{ header := "" }] nextMacroScope : Nat := firstFrontendMacroScope + 1 maxRecDepth : Nat nextInstIdx : Nat := 1 -- for generating anonymous instance names ngen : NameGenerator := {} infoState : InfoState := {} traceState : TraceState := {} deriving Inhabited structure Context where fileName : String fileMap : FileMap currRecDepth : Nat := 0 cmdPos : String.Pos := 0 macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope ref : Syntax := Syntax.missing tacticCache? : Option (IO.Ref Tactic.Cache) abbrev CommandElabCoreM (ε) := ReaderT Context $ StateRefT State $ EIO ε abbrev CommandElabM := CommandElabCoreM Exception abbrev CommandElab := Syntax → CommandElabM Unit abbrev Linter := Syntax → CommandElabM Unit -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad CommandElabM := let i := inferInstanceAs (Monad CommandElabM); { pure := i.pure, bind := i.bind } def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := { env := env messages := messages scopes := [{ header := "", opts := opts }] maxRecDepth := maxRecDepth.get opts } /- Linters should be loadable as plugins, so store in a global IO ref instead of an attribute managed by the environment (which only contains `import`ed objects). -/ builtin_initialize lintersRef : IO.Ref (Array Linter) ← IO.mkRef #[] def addLinter (l : Linter) : IO Unit := do let ls ← lintersRef.get lintersRef.set (ls.push l) instance : MonadInfoTree CommandElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } instance : MonadEnv CommandElabM where getEnv := do pure (← get).env modifyEnv f := modify fun s => { s with env := f s.env } instance : MonadOptions CommandElabM where getOptions := do pure (← get).scopes.head!.opts protected def getRef : CommandElabM Syntax := return (← read).ref instance : AddMessageContext CommandElabM where addMessageContext := addMessageContextPartial instance : MonadRef CommandElabM where getRef := Command.getRef withRef ref x := withReader (fun ctx => { ctx with ref := ref }) x instance : MonadTrace CommandElabM where getTraceState := return (← get).traceState modifyTraceState f := modify fun s => { s with traceState := f s.traceState } instance : AddErrorMessageContext CommandElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack return (ref, msg) def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := let pos := ref.getPos?.getD ctx.cmdPos let endPos := ref.getTailPos?.getD pos mkMessageCore ctx.fileName ctx.fileMap msgData severity pos endPos private def mkCoreContext (ctx : Context) (s : State) (heartbeats : Nat) : Core.Context := let scope := s.scopes.head! { fileName := ctx.fileName fileMap := ctx.fileMap options := scope.opts currRecDepth := ctx.currRecDepth maxRecDepth := s.maxRecDepth ref := ctx.ref currNamespace := scope.currNamespace openDecls := scope.openDecls initHeartbeats := heartbeats currMacroScope := ctx.currMacroScope } private def addTraceAsMessagesCore (ctx : Context) (log : MessageLog) (traceState : TraceState) : MessageLog := traceState.traces.foldl (init := log) fun (log : MessageLog) traceElem => let ref := replaceRef traceElem.ref ctx.ref let pos := ref.getPos?.getD 0 let endPos := ref.getTailPos?.getD pos log.add (mkMessageCore ctx.fileName ctx.fileMap traceElem.msg MessageSeverity.information pos endPos) private def addTraceAsMessages : CommandElabM Unit := do let ctx ← read modify fun s => { s with messages := addTraceAsMessagesCore ctx s.messages s.traceState traceState.traces := {} } def liftCoreM (x : CoreM α) : CommandElabM α := do let s ← get let ctx ← read let heartbeats ← IO.getNumHeartbeats let Eα := Except Exception α let x : CoreM Eα := try let a ← x; pure <| Except.ok a catch ex => pure <| Except.error ex let x : EIO Exception (Eα × Core.State) := (ReaderT.run x (mkCoreContext ctx s heartbeats)).run { env := s.env, ngen := s.ngen, traceState := s.traceState, messages := {}, infoState.enabled := s.infoState.enabled } let (ea, coreS) ← liftM x modify fun s => { s with env := coreS.env ngen := coreS.ngen messages := addTraceAsMessagesCore ctx (s.messages ++ coreS.messages) coreS.traceState traceState := coreS.traceState infoState.trees := s.infoState.trees.append coreS.infoState.trees } match ea with | Except.ok a => pure a | Except.error e => throw e private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message := let ref := getBetterRef ref ctx.macroStack mkMessageAux ctx ref (toString err) MessageSeverity.error @[inline] def liftEIO {α} (x : EIO Exception α) : CommandElabM α := liftM x @[inline] def liftIO {α} (x : IO α) : CommandElabM α := do let ctx ← read IO.toEIO (fun (ex : IO.Error) => Exception.error ctx.ref ex.toString) x instance : MonadLiftT IO CommandElabM where monadLift := liftIO def getScope : CommandElabM Scope := do pure (← get).scopes.head! instance : MonadResolveName CommandElabM where getCurrNamespace := return (← getScope).currNamespace getOpenDecls := return (← getScope).openDecls instance : MonadLog CommandElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName hasErrors := return (← get).messages.hasErrors logMessage msg := do let currNamespace ← getCurrNamespace let openDecls ← getOpenDecls let msg := { msg with data := MessageData.withNamingContext { currNamespace := currNamespace, openDecls := openDecls } msg.data } modify fun s => { s with messages := s.messages.add msg } def runLinters (stx : Syntax) : CommandElabM Unit := do profileitM Exception "linting" (← getOptions) do let linters ← lintersRef.get unless linters.isEmpty do for linter in linters do let savedState ← get try linter stx catch ex => logException ex finally modify fun s => { savedState with messages := s.messages } protected def getCurrMacroScope : CommandElabM Nat := do pure (← read).currMacroScope protected def getMainModule : CommandElabM Name := do pure (← getEnv).mainModule protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do let fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation CommandElabM where getCurrMacroScope := Command.getCurrMacroScope getMainModule := Command.getMainModule withFreshMacroScope := Command.withFreshMacroScope unsafe def mkCommandElabAttributeUnsafe : IO (KeyedDeclsAttribute CommandElab) := mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command" @[implementedBy mkCommandElabAttributeUnsafe] opaque mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab) builtin_initialize commandElabAttribute : KeyedDeclsAttribute CommandElab ← mkCommandElabAttribute private def mkInfoTree (elaborator : Name) (stx : Syntax) (trees : Std.PersistentArray InfoTree) : CommandElabM InfoTree := do let ctx ← read let s ← get let scope := s.scopes.head! let tree := InfoTree.node (Info.ofCommandInfo { elaborator, stx }) trees return InfoTree.context { env := s.env, fileMap := ctx.fileMap, mctx := {}, currNamespace := scope.currNamespace, openDecls := scope.openDecls, options := scope.opts, ngen := s.ngen } tree private def elabCommandUsing (s : State) (stx : Syntax) : List (KeyedDeclsAttribute.AttributeEntry CommandElab) → CommandElabM Unit | [] => withInfoTreeContext (mkInfoTree := mkInfoTree `no_elab stx) <| throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => catchInternalId unsupportedSyntaxExceptionId (withInfoTreeContext (mkInfoTree := mkInfoTree elabFn.declName stx) <| elabFn.value stx) (fun _ => do set s; elabCommandUsing s stx elabFns) /-- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α := withInfoContext (mkInfo := pure <| .ofMacroExpansionInfo { stx := beforeStx, output := afterStx, lctx := .empty }) do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x instance : MonadMacroAdapter CommandElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← get).nextMacroScope setNextMacroScope next := modify fun s => { s with nextMacroScope := next } instance : MonadRecDepth CommandElabM where withRecDepth d x := withReader (fun ctx => { ctx with currRecDepth := d }) x getRecDepth := return (← read).currRecDepth getMaxRecDepth := return (← get).maxRecDepth register_builtin_option showPartialSyntaxErrors : Bool := { defValue := false descr := "show elaboration errors from partial syntax trees (i.e. after parser recovery)" } builtin_initialize registerTraceClass `Elab.command partial def elabCommand (stx : Syntax) : CommandElabM Unit := do withLogging <| withRef stx <| withIncRecDepth <| withFreshMacroScope do match stx with | Syntax.node _ k args => if k == nullKind then -- list of commands => elaborate in order -- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones args.forM elabCommand else do trace `Elab.command fun _ => stx; let s ← get match (← liftMacroM <| expandMacroImpl? s.env stx) with | some (decl, stxNew?) => withInfoTreeContext (mkInfoTree := mkInfoTree decl stx) do let stxNew ← liftMacroM <| liftExcept stxNew? withMacroExpansion stx stxNew do elabCommand stxNew | _ => match commandElabAttribute.getEntries s.env k with | [] => withInfoTreeContext (mkInfoTree := mkInfoTree `no_elab stx) <| throwError "elaboration function for '{k}' has not been implemented" | elabFns => elabCommandUsing s stx elabFns | _ => throwError "unexpected command" builtin_initialize registerTraceClass `Elab.input /-- `elabCommand` wrapper that should be used for the initial invocation, not for recursive calls after macro expansion etc. -/ def elabCommandTopLevel (stx : Syntax) : CommandElabM Unit := withRef stx do trace[Elab.input] stx let initMsgs ← modifyGet fun st => (st.messages, { st with messages := {} }) let initInfoTrees ← getResetInfoTrees -- We should *not* factor out `elabCommand`'s `withLogging` to here since it would make its error -- recovery more coarse. In particular, If `c` in `set_option ... in $c` fails, the remaining -- `end` command of the `in` macro would be skipped and the option would be leaked to the outside! elabCommand stx withLogging do runLinters stx -- note the order: first process current messages & info trees, then add back old messages & trees, -- then convert new traces to messages let mut msgs := (← get).messages -- `stx.hasMissing` should imply `initMsgs.hasErrors`, but the latter should be cheaper to check in general if !showPartialSyntaxErrors.get (← getOptions) && initMsgs.hasErrors && stx.hasMissing then -- discard elaboration errors, except for a few important and unlikely misleading ones, on parse error msgs := ⟨msgs.msgs.filter fun msg => msg.data.hasTag (fun tag => tag == `Elab.synthPlaceholder || tag == `Tactic.unsolvedGoals || (`_traceMsg).isSuffixOf tag)⟩ for tree in (← getInfoTrees) do trace[Elab.info] (← tree.format) modify fun st => { st with messages := initMsgs ++ msgs infoState := { st.infoState with trees := initInfoTrees ++ st.infoState.trees } } addTraceAsMessages /-- Adapt a syntax transformation to a regular, command-producing elaborator. -/ def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' <| elabCommand stx' private def getVarDecls (s : State) : Array Syntax := s.scopes.head!.varDecls instance {α} : Inhabited (CommandElabM α) where default := throw default private def mkMetaContext : Meta.Context := { config := { foApprox := true, ctxApprox := true, quasiPatternApprox := true } } /-- Return identifier names in the given bracketed binder. -/ def getBracketedBinderIds : Syntax → Array Name | `(bracketedBinder|($ids* $[: $ty?]? $(_annot?)?)) => ids.map Syntax.getId | `(bracketedBinder|{$ids* $[: $ty?]?}) => ids.map Syntax.getId | `(bracketedBinder|[$id : $_]) => #[id.getId] | `(bracketedBinder|[$_]) => #[Name.anonymous] | _ => #[] private def mkTermContext (ctx : Context) (s : State) : Term.Context := Id.run do let scope := s.scopes.head! let mut sectionVars := {} for id in scope.varDecls.concatMap getBracketedBinderIds, uid in scope.varUIds do sectionVars := sectionVars.insert id uid { macroStack := ctx.macroStack sectionVars := sectionVars isNoncomputableSection := scope.isNoncomputable tacticCache? := ctx.tacticCache? } /-- Lift the `TermElabM` monadic action `x` into a `CommandElabM` monadic action. Note that `x` is executed with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands. If you need to access the free variables corresponding to the ones declared using the `variable` command, consider using `runTermElabM`. Recall that `TermElabM` actions can automatically lift `MetaM` and `CoreM` actions. Example: ``` import Lean open Lean Elab Command Meta def printExpr (e : Expr) : MetaM Unit := do IO.println s!"{← ppExpr e} : {← ppExpr (← inferType e)}" #eval liftTermElabM do printExpr (mkConst ``Nat) ``` -/ def liftTermElabM (x : TermElabM α) : CommandElabM α := do let ctx ← read let s ← get let heartbeats ← IO.getNumHeartbeats -- dbg_trace "heartbeats: {heartbeats}" let scope := s.scopes.head! -- We execute `x` with an empty message log. Thus, `x` cannot modify/view messages produced by previous commands. -- This is useful for implementing `runTermElabM` where we use `Term.resetMessageLog` let x : TermElabM _ := withSaveInfoContext x let x : MetaM _ := (observing x).run (mkTermContext ctx s) { levelNames := scope.levelNames } let x : CoreM _ := x.run mkMetaContext {} let x : EIO _ _ := x.run (mkCoreContext ctx s heartbeats) { env := s.env, ngen := s.ngen, nextMacroScope := s.nextMacroScope, infoState.enabled := s.infoState.enabled } let (((ea, _), _), coreS) ← liftEIO x modify fun s => { s with env := coreS.env nextMacroScope := coreS.nextMacroScope ngen := coreS.ngen infoState.trees := s.infoState.trees.append coreS.infoState.trees messages := addTraceAsMessagesCore ctx (s.messages ++ coreS.messages) coreS.traceState } match ea with | Except.ok a => pure a | Except.error ex => throw ex /-- Execute the monadic action `elabFn xs` as a `CommandElabM` monadic action, where `xs` are free variables corresponding to all active scoped variables declared using the `variable` command. This method is similar to `liftTermElabM`, but it elaborates all scoped variables declared using the `variable` command. Example: ``` import Lean open Lean Elab Command Meta variable {α : Type u} {f : α → α} variable (n : Nat) #eval runTermElabM fun xs => do for x in xs do IO.println s!"{← ppExpr x} : {← ppExpr (← inferType x)}" ``` -/ def runTermElabM (elabFn : Array Expr → TermElabM α) : CommandElabM α := do let scope ← getScope liftTermElabM <| Term.withAutoBoundImplicit <| Term.elabBinders scope.varDecls fun xs => do -- We need to synthesize postponed terms because this is a checkpoint for the auto-bound implicit feature -- If we don't use this checkpoint here, then auto-bound implicits in the postponed terms will not be handled correctly. Term.synthesizeSyntheticMVarsNoPostponing let mut sectionFVars := {} for uid in scope.varUIds, x in xs do sectionFVars := sectionFVars.insert uid x withReader ({ · with sectionFVars := sectionFVars }) do -- We don't want to store messages produced when elaborating `(getVarDecls s)` because they have already been saved when we elaborated the `variable`(s) command. -- So, we use `Core.resetMessageLog`. Core.resetMessageLog let someType := mkSort levelZero Term.addAutoBoundImplicits' xs someType fun xs _ => Term.withoutAutoBoundImplicit <| elabFn xs @[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx ref => EIO.catchExceptions (withLogging x ctx ref) (fun _ => pure ()) private def liftAttrM {α} (x : AttrM α) : CommandElabM α := do liftCoreM x def getScopes : CommandElabM (List Scope) := do pure (← get).scopes def modifyScope (f : Scope → Scope) : CommandElabM Unit := modify fun s => { s with scopes := match s.scopes with | h::t => f h :: t | [] => unreachable! } def withScope (f : Scope → Scope) (x : CommandElabM α) : CommandElabM α := do match (← get).scopes with | [] => x | h :: t => try modify fun s => { s with scopes := f h :: t } x finally modify fun s => { s with scopes := h :: t } def getLevelNames : CommandElabM (List Name) := return (← getScope).levelNames def addUnivLevel (idStx : Syntax) : CommandElabM Unit := withRef idStx do let id := idStx.getId let levelNames ← getLevelNames if levelNames.elem id then throwAlreadyDeclaredUniverseLevel id else modifyScope fun scope => { scope with levelNames := id :: scope.levelNames } def expandDeclId (declId : Syntax) (modifiers : Modifiers) : CommandElabM ExpandDeclIdResult := do let currNamespace ← getCurrNamespace let currLevelNames ← getLevelNames let r ← Elab.expandDeclId currNamespace currLevelNames declId modifiers for id in (← getScope).varDecls.concatMap getBracketedBinderIds do if id == r.shortName then throwError "invalid declaration name '{r.shortName}', there is a section variable with the same name" return r end Elab.Command export Elab.Command (Linter addLinter) end Lean
8263362e37082fb263023d46338032b1bb3d25b1
690889011852559ee5ac4dfea77092de8c832e7e
/src/category_theory/monad/limits.lean
5ae1880dfacc3a686f00533aa87b6f1e1d148473
[ "Apache-2.0" ]
permissive
williamdemeo/mathlib
f6df180148f8acc91de9ba5e558976ab40a872c7
1fa03c29f9f273203bbffb79d10d31f696b3d317
refs/heads/master
1,584,785,260,929
1,572,195,914,000
1,572,195,913,000
138,435,193
0
0
Apache-2.0
1,529,789,739,000
1,529,789,739,000
null
UTF-8
Lean
false
false
4,305
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monad.adjunction import category_theory.adjunction.limits namespace category_theory open category open category_theory.limits universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace monad variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 variables {T : C ⥤ C} [monad.{v₁} T] variables {J : Type v₁} [𝒥 : small_category J] include 𝒥 namespace forget_creates_limits variables (D : J ⥤ algebra T) [has_limit.{v₁} (D ⋙ forget T)] @[simps] def γ : (D ⋙ forget T ⋙ T) ⟶ (D ⋙ forget T) := { app := λ j, (D.obj j).a } @[simps] def c : cone (D ⋙ forget T) := { X := T.obj (limit (D ⋙ forget T)), π := (functor.const_comp _ _ T).inv ≫ whisker_right (limit.cone (D ⋙ forget T)).π T ≫ (γ D) } @[simps] def cone_point (D : J ⥤ algebra T) [has_limit.{v₁} (D ⋙ forget T)] : algebra T := { A := limit (D ⋙ forget T), a := limit.lift _ (c D), unit' := begin ext1, rw [category.assoc, limit.lift_π], dsimp, erw [id_comp, ←category.assoc, ←nat_trans.naturality, id_comp, category.assoc, algebra.unit, comp_id], refl, end, assoc' := begin ext1, dsimp, simp only [limit.lift_π, γ_app, c_π, limit.cone_π, functor.const_comp, whisker_right.app, nat_trans.comp_app, category.assoc], dsimp, simp only [id_comp], conv { to_rhs, rw [←category.assoc, ←T.map_comp, limit.lift_π], dsimp [c], rw [id_comp], }, conv { to_lhs, rw [←category.assoc, ←nat_trans.naturality, category.assoc], erw [algebra.assoc (D.obj j), ←category.assoc, ←T.map_comp], }, end } end forget_creates_limits -- Theorem 5.6.5 from [Riehl][riehl2017] def forget_creates_limits (D : J ⥤ algebra T) [has_limit.{v₁} (D ⋙ forget T)] : has_limit D := { cone := { X := forget_creates_limits.cone_point D, π := { app := λ j, { f := limit.π (D ⋙ forget T) j }, naturality' := λ X Y f, by { ext, dsimp, erw [id_comp, limit.w] } } }, is_limit := { lift := λ s, { f := limit.lift _ ((forget T).map_cone s), h' := begin ext, dsimp, simp only [limit.lift_π, limit.cone_π, forget_map, id_comp, functor.const_comp, whisker_right.app, nat_trans.comp_app, category.assoc, functor.map_cone_π], dsimp, rw [id_comp, ←category.assoc, ←T.map_comp], simp only [limit.lift_π, monad.forget_map, algebra.hom.h, functor.map_cone_π], end }, uniq' := λ s m w, by { ext1, ext1, simpa using congr_arg algebra.hom.f (w j) } } } end monad variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₁} [𝒟 : category.{v₁} D] include 𝒞 𝒟 variables {J : Type v₁} [𝒥 : small_category J] include 𝒥 instance comp_comparison_forget_has_limit (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit.{v₁} (F ⋙ R)] : has_limit ((F ⋙ monad.comparison R) ⋙ monad.forget ((left_adjoint R) ⋙ R)) := (@has_limit_of_iso _ _ _ _ (F ⋙ R) _ _ (iso_whisker_left F (monad.comparison_forget R).symm)) instance comp_comparison_has_limit (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit.{v₁} (F ⋙ R)] : has_limit (F ⋙ monad.comparison R) := monad.forget_creates_limits (F ⋙ monad.comparison R) def monadic_creates_limits (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit.{v₁} (F ⋙ R)] : has_limit F := adjunction.has_limit_of_comp_equivalence _ (monad.comparison R) omit 𝒥 section def has_limits_of_reflective (R : D ⥤ C) [reflective R] [has_limits.{v₁} C] : has_limits.{v₁} D := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, monadic_creates_limits F R } } local attribute [instance] has_limits_of_reflective include 𝒥 -- We verify that, even jumping through these monadic hoops, -- the limit is actually calculated in the obvious way: example (R : D ⥤ C) [reflective R] [has_limits.{v₁} C] (F : J ⥤ D) : limit F = (left_adjoint R).obj (limit (F ⋙ R)) := rfl end end category_theory
866dedc582e18e0a407ba869fce537712488d665
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/SimpLemmas.lean
3d1cecdf326a51c49d43e78dda13aa7d8a00b6e5
[ "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
9,931
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude import Init.Core @[simp] theorem eq_self (a : α) : (a = a) = True := propext <| Iff.intro (fun _ => trivial) (fun _ => rfl) theorem of_eq_true (h : p = True) : p := h ▸ trivial theorem eq_true (h : p) : p = True := propext <| Iff.intro (fun _ => trivial) (fun _ => h) theorem eq_false (h : ¬ p) : p = False := propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h') theorem eq_false' (h : p → False) : p = False := propext <| Iff.intro (fun h' => absurd h' h) (fun h' => False.elim h') theorem eq_true_of_decide {p : Prop} {_ : Decidable p} (h : decide p = true) : p = True := propext <| Iff.intro (fun _ => trivial) (fun _ => of_decide_eq_true h) theorem eq_false_of_decide {p : Prop} {_ : Decidable p} (h : decide p = false) : p = False := propext <| Iff.intro (fun h' => absurd h' (of_decide_eq_false h)) (fun h => False.elim h) theorem implies_congr {p₁ p₂ : Sort u} {q₁ q₂ : Sort v} (h₁ : p₁ = p₂) (h₂ : q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) := h₁ ▸ h₂ ▸ rfl theorem implies_congr_ctx {p₁ p₂ q₁ q₂ : Prop} (h₁ : p₁ = p₂) (h₂ : p₂ → q₁ = q₂) : (p₁ → q₁) = (p₂ → q₂) := propext <| Iff.intro (fun h hp₂ => have : p₁ := h₁ ▸ hp₂ have : q₁ := h this h₂ hp₂ ▸ this) (fun h hp₁ => have hp₂ : p₂ := h₁ ▸ hp₁ have : q₂ := h hp₂ h₂ hp₂ ▸ this) theorem implies_dep_congr_ctx {p₁ p₂ q₁ : Prop} (h₁ : p₁ = p₂) {q₂ : p₂ → Prop} (h₂ : (h : p₂) → q₁ = q₂ h) : (p₁ → q₁) = ((h : p₂) → q₂ h) := propext <| Iff.intro (fun hl hp₂ => Eq.mp (h₂ hp₂) (hl (Eq.mpr h₁ hp₂))) (fun hr hp₁ => Eq.mpr (h₂ (Eq.mp h₁ hp₁)) (hr (Eq.mp h₁ hp₁))) theorem forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a = q a)) : (∀ a, p a) = (∀ a, q a) := have : p = q := funext h this ▸ rfl theorem let_congr {α : Sort u} {β : Sort v} {a a' : α} {b b' : α → β} (h₁ : a = a') (h₂ : ∀ x, b x = b' x) : (let x := a; b x) = (let x := a'; b' x) := by subst h₁ have : b = b' := funext h₂ subst this rfl theorem let_val_congr {α : Sort u} {β : Sort v} {a a' : α} (b : α → β) (h : a = a') : (let x := a; b x) = (let x := a'; b x) := by subst h rfl theorem let_body_congr {α : Sort u} {β : α → Sort v} {b b' : (a : α) → β a} (a : α) (h : ∀ x, b x = b' x) : (let x := a; b x) = (let x := a; b' x) := by have : b = b' := funext h subst this rfl @[congr] theorem ite_congr {x y u v : α} {s : Decidable b} [Decidable c] (h₁ : b = c) (h₂ : c → x = u) (h₃ : ¬ c → y = v) : ite b x y = ite c u v := by cases Decidable.em c with | inl h => rw [if_pos h]; subst b; rw[if_pos h]; exact h₂ h | inr h => rw [if_neg h]; subst b; rw[if_neg h]; exact h₃ h theorem Eq.mpr_prop {p q : Prop} (h₁ : p = q) (h₂ : q) : p := h₁ ▸ h₂ theorem Eq.mpr_not {p q : Prop} (h₁ : p = q) (h₂ : ¬q) : ¬p := h₁ ▸ h₂ @[congr] theorem dite_congr {s : Decidable b} [Decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h₁ : b = c) (h₂ : (h : c) → x (Eq.mpr_prop h₁ h) = u h) (h₃ : (h : ¬c) → y (Eq.mpr_not h₁ h) = v h) : dite b x y = dite c u v := by cases Decidable.em c with | inl h => rw [dif_pos h]; subst b; rw [dif_pos h]; exact h₂ h | inr h => rw [dif_neg h]; subst b; rw [dif_neg h]; exact h₃ h @[simp] theorem ne_eq (a b : α) : (a ≠ b) = Not (a = b) := rfl @[simp] theorem ite_true (a b : α) : (if True then a else b) = a := rfl @[simp] theorem ite_false (a b : α) : (if False then a else b) = b := rfl @[simp] theorem dite_true {α : Sort u} {t : True → α} {e : ¬ True → α} : (dite True t e) = t True.intro := rfl @[simp] theorem dite_false {α : Sort u} {t : False → α} {e : ¬ False → α} : (dite False t e) = e not_false := rfl @[simp] theorem ite_self {α : Sort u} {c : Prop} {d : Decidable c} (a : α) : ite c a a = a := by cases d <;> rfl @[simp] theorem and_self (p : Prop) : (p ∧ p) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, h⟩) @[simp] theorem and_true (p : Prop) : (p ∧ True) = p := propext <| Iff.intro (fun h => h.1) (fun h => ⟨h, trivial⟩) @[simp] theorem true_and (p : Prop) : (True ∧ p) = p := propext <| Iff.intro (fun h => h.2) (fun h => ⟨trivial, h⟩) @[simp] theorem and_false (p : Prop) : (p ∧ False) = False := propext <| Iff.intro (fun h => h.2) (fun h => False.elim h) @[simp] theorem false_and (p : Prop) : (False ∧ p) = False := propext <| Iff.intro (fun h => h.1) (fun h => False.elim h) @[simp] theorem or_self (p : Prop) : (p ∨ p) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => h) (fun h => Or.inl h) @[simp] theorem or_true (p : Prop) : (p ∨ True) = True := propext <| Iff.intro (fun _ => trivial) (fun _ => Or.inr trivial) @[simp] theorem true_or (p : Prop) : (True ∨ p) = True := propext <| Iff.intro (fun _ => trivial) (fun _ => Or.inl trivial) @[simp] theorem or_false (p : Prop) : (p ∨ False) = p := propext <| Iff.intro (fun | Or.inl h => h | Or.inr h => False.elim h) (fun h => Or.inl h) @[simp] theorem false_or (p : Prop) : (False ∨ p) = p := propext <| Iff.intro (fun | Or.inr h => h | Or.inl h => False.elim h) (fun h => Or.inr h) @[simp] theorem iff_self (p : Prop) : (p ↔ p) = True := propext <| Iff.intro (fun _ => trivial) (fun _ => Iff.intro id id) @[simp] theorem iff_true (p : Prop) : (p ↔ True) = p := propext <| Iff.intro (fun h => h.mpr trivial) (fun h => Iff.intro (fun _ => trivial) (fun _ => h)) @[simp] theorem true_iff (p : Prop) : (True ↔ p) = p := propext <| Iff.intro (fun h => h.mp trivial) (fun h => Iff.intro (fun _ => h) (fun _ => trivial)) @[simp] theorem iff_false (p : Prop) : (p ↔ False) = ¬p := propext <| Iff.intro (fun h hp => h.mp hp) (fun h => Iff.intro h False.elim) @[simp] theorem false_iff (p : Prop) : (False ↔ p) = ¬p := propext <| Iff.intro (fun h hp => h.mpr hp) (fun h => Iff.intro False.elim h) @[simp] theorem false_implies (p : Prop) : (False → p) = True := propext <| Iff.intro (fun _ => trivial) (by intros; trivial) @[simp] theorem implies_true (α : Sort u) : (α → True) = True := propext <| Iff.intro (fun _ => trivial) (by intros; trivial) @[simp] theorem true_implies (p : Prop) : (True → p) = p := propext <| Iff.intro (fun h => h trivial) (by intros; trivial) @[simp] theorem Bool.or_false (b : Bool) : (b || false) = b := by cases b <;> rfl @[simp] theorem Bool.or_true (b : Bool) : (b || true) = true := by cases b <;> rfl @[simp] theorem Bool.false_or (b : Bool) : (false || b) = b := by cases b <;> rfl @[simp] theorem Bool.true_or (b : Bool) : (true || b) = true := by cases b <;> rfl @[simp] theorem Bool.or_self (b : Bool) : (b || b) = b := by cases b <;> rfl @[simp] theorem Bool.or_eq_true (a b : Bool) : ((a || b) = true) = (a = true ∨ b = true) := by cases a <;> cases b <;> decide @[simp] theorem Bool.and_false (b : Bool) : (b && false) = false := by cases b <;> rfl @[simp] theorem Bool.and_true (b : Bool) : (b && true) = b := by cases b <;> rfl @[simp] theorem Bool.false_and (b : Bool) : (false && b) = false := by cases b <;> rfl @[simp] theorem Bool.true_and (b : Bool) : (true && b) = b := by cases b <;> rfl @[simp] theorem Bool.and_self (b : Bool) : (b && b) = b := by cases b <;> rfl @[simp] theorem Bool.and_eq_true (a b : Bool) : ((a && b) = true) = (a = true ∧ b = true) := by cases a <;> cases b <;> decide @[simp] theorem Bool.not_not (b : Bool) : (!!b) = b := by cases b <;> rfl @[simp] theorem Bool.not_true : (!true) = false := by decide @[simp] theorem Bool.not_false : (!false) = true := by decide @[simp] theorem Bool.not_beq_true (b : Bool) : (!(b == true)) = (b == false) := by cases b <;> rfl @[simp] theorem Bool.not_beq_false (b : Bool) : (!(b == false)) = (b == true) := by cases b <;> rfl @[simp] theorem Bool.beq_to_eq (a b : Bool) : ((a == b) = true) = (a = b) := by cases a <;> cases b <;> decide @[simp] theorem Bool.not_beq_to_not_eq (a b : Bool) : ((!(a == b)) = true) = ¬(a = b) := by cases a <;> cases b <;> decide @[simp] theorem Bool.not_eq_true (b : Bool) : (¬ (b = true)) = (b = false) := by cases b <;> decide @[simp] theorem Bool.not_eq_false (b : Bool) : (¬ (b = false)) = (b = true) := by cases b <;> decide @[simp] theorem decide_eq_true_eq [Decidable p] : (decide p = true) = p := propext <| Iff.intro of_decide_eq_true decide_eq_true @[simp] theorem decide_not [h : Decidable p] : decide (¬ p) = !decide p := by cases h <;> rfl @[simp] theorem not_decide_eq_true [h : Decidable p] : ((!decide p) = true) = ¬ p := by cases h <;> simp [decide, *] @[simp] theorem heq_eq_eq {α : Sort u} (a b : α) : HEq a b = (a = b) := propext <| Iff.intro eq_of_heq heq_of_eq @[simp] theorem cond_true (a b : α) : cond true a b = a := rfl @[simp] theorem cond_false (a b : α) : cond false a b = b := rfl @[simp] theorem beq_self_eq_true [BEq α] [LawfulBEq α] (a : α) : (a == a) = true := LawfulBEq.rfl @[simp] theorem beq_self_eq_true' [DecidableEq α] (a : α) : (a == a) = true := by simp [BEq.beq] @[simp] theorem bne_self_eq_false [BEq α] [LawfulBEq α] (a : α) : (a != a) = false := by simp [bne] @[simp] theorem bne_self_eq_false' [DecidableEq α] (a : α) : (a != a) = false := by simp [bne] @[simp] theorem Nat.le_zero_eq (a : Nat) : (a ≤ 0) = (a = 0) := propext <| Iff.intro (fun h => Nat.le_antisymm h (Nat.zero_le ..)) (fun h => by simp [h]) @[simp] theorem decide_False : decide False = false := rfl @[simp] theorem decide_True : decide True = true := rfl
539ec0b3d4c4d890fc2ca8b94de09d5a4c4e7777
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/linear_algebra/dimension.lean
ace45df305003c69ff64f1da23e0ac6e1000927d
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,051
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen -/ import linear_algebra.basis import linear_algebra.std_basis import set_theory.cardinal_ordinal /-! # Dimension of modules and vector spaces ## Main definitions * The rank of a module is defined as `module.rank : cardinal`. This is currently only defined for vector spaces, i.e., when the base semiring is a field. ## Main statements * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. * `dim_quotient_add_dim`: if V₁ is a submodule of V, then `module.rank (V/V₁) + module.rank V₁ = module.rank V`. * `dim_range_add_dim_ker`: the rank-nullity theorem. ## Implementation notes Many theorems in this file are not universe-generic when they relate dimensions in different universes. They should be as general as they can be without inserting `lift`s. The types `V`, `V'`, ... all live in different universes, and `V₁`, `V₂`, ... all live in the same universe. -/ noncomputable theory universes u v v' v'' u₁' w w' variables {K : Type u} {V V₁ V₂ V₃ : Type v} {V' V'₁ : Type v'} {V'' : Type v''} variables {ι : Type w} {ι' : Type w'} {η : Type u₁'} {φ : η → Type*} open_locale classical big_operators section module variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] include K open submodule function set variables (K V) /-- The rank of a module, defined as a term of type `cardinal`. In a vector space, this is the same as the dimension of the space. TODO: this is currently only defined for vector spaces, as the cardinality of the basis set. It should be generalized to modules in general. The definition is marked as protected to avoid conflicts with `_root_.rank`, the rank of a linear map. -/ protected def module.rank : cardinal := cardinal.min (nonempty_subtype.2 (@exists_is_basis K V _ _ _)) (λ b, cardinal.mk b.1) variables {K V} section theorem is_basis.le_span {v : ι → V} {J : set V} (hv : is_basis K v) (hJ : span K J = ⊤) : cardinal.mk (range v) ≤ cardinal.mk J := begin cases le_or_lt cardinal.omega (cardinal.mk J) with oJ oJ, { have := cardinal.mk_range_eq_of_injective (linear_independent.injective hv.1), let S : J → set ι := λ j, ↑(is_basis.repr hv j).support, let S' : J → set V := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span K J ≤ comap hv.repr (finsupp.supported K K (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : hv.repr (v i) ∈ (finsupp.supported K K (⋃ j, S j)) := this trivial, rw [hv.repr_eq_single, finsupp.mem_supported, finsupp.support_single_ne_zero one_ne_zero] at this, { subst b, rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩, exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ }, { apply_instance } }, refine le_of_not_lt (λ IJ, _), suffices : cardinal.mk (⋃ j, S' j) < cardinal.mk (range v), { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, cardinal.omega) _)) _, { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ (finset.finite_to_set _).image _) }, { rwa [cardinal.sum_const, cardinal.mul_eq_max oJ (le_refl _), max_eq_left oJ] } }, { rcases exists_finite_card_le_of_finite_of_linear_independent_of_span (cardinal.lt_omega_iff_finite.1 oJ) hv.1.to_subtype_range _ with ⟨fI, hi⟩, { rwa [← cardinal.nat_cast_le, cardinal.finset_card, set.finite.coe_to_finset, cardinal.finset_card, set.finite.coe_to_finset] at hi, }, { rw hJ, apply set.subset_univ } }, end end /-- dimension theorem -/ theorem mk_eq_mk_of_basis {v : ι → V} {v' : ι' → V} (hv : is_basis K v) (hv' : is_basis K v') : cardinal.lift.{w w'} (cardinal.mk ι) = cardinal.lift.{w' w} (cardinal.mk ι') := begin rw ←cardinal.lift_inj.{(max w w') v}, rw [cardinal.lift_lift, cardinal.lift_lift], apply le_antisymm, { convert cardinal.lift_le.{v (max w w')}.2 (hv.le_span hv'.2), { rw cardinal.lift_max.{w v w'}, apply (cardinal.mk_range_eq_of_injective hv.injective).symm, }, { rw cardinal.lift_max.{w' v w}, apply (cardinal.mk_range_eq_of_injective hv'.injective).symm, }, }, { convert cardinal.lift_le.{v (max w w')}.2 (hv'.le_span hv.2), { rw cardinal.lift_max.{w' v w}, apply (cardinal.mk_range_eq_of_injective hv'.injective).symm, }, { rw cardinal.lift_max.{w v w'}, apply (cardinal.mk_range_eq_of_injective hv.injective).symm, }, } end theorem mk_eq_mk_of_basis' {ι' : Type w} {v : ι → V} {v' : ι' → V} (hv : is_basis K v) (hv' : is_basis K v') : cardinal.mk ι = cardinal.mk ι' := cardinal.lift_inj.1 $ mk_eq_mk_of_basis hv hv' theorem is_basis.mk_eq_dim'' {ι : Type v} {v : ι → V} (h : is_basis K v) : cardinal.mk ι = module.rank K V := begin obtain ⟨v', e : module.rank K V = _⟩ := cardinal.min_eq _ _, rw e, rw ← cardinal.mk_range_eq _ h.injective, exact mk_eq_mk_of_basis' h.range v'.2 end theorem is_basis.mk_range_eq_dim {v : ι → V} (h : is_basis K v) : cardinal.mk (range v) = module.rank K V := h.range.mk_eq_dim'' theorem is_basis.mk_eq_dim {v : ι → V} (h : is_basis K v) : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (module.rank K V) := by rw [←h.mk_range_eq_dim, cardinal.mk_range_eq_of_injective h.injective] theorem {m} is_basis.mk_eq_dim' {v : ι → V} (h : is_basis K v) : cardinal.lift.{w (max v m)} (cardinal.mk ι) = cardinal.lift.{v (max w m)} (module.rank K V) := by simpa using h.mk_eq_dim theorem dim_le {n : ℕ} (H : ∀ s : finset V, linear_independent K (λ i : (↑s : set V), (i : V)) → s.card ≤ n) : module.rank K V ≤ n := let ⟨b, hb⟩ := exists_is_basis K V in hb.mk_eq_dim'' ▸ cardinal.card_le_of (λ s, @finset.card_map _ _ ⟨_, subtype.val_injective⟩ s ▸ H _ (by { refine hb.1.mono (λ y h, _), rw [finset.mem_coe, finset.mem_map] at h, rcases h with ⟨x, hx, rfl⟩, exact x.2 } )) variables [add_comm_group V'] [module K V'] /-- Two linearly equivalent vector spaces have the same dimension, a version with different universes. -/ theorem linear_equiv.lift_dim_eq (f : V ≃ₗ[K] V') : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V') := let ⟨b, hb⟩ := exists_is_basis K V in calc cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v v'} (cardinal.mk b) : congr_arg _ hb.mk_eq_dim''.symm ... = cardinal.lift.{v' v} (module.rank K V') : (f.is_basis hb).mk_eq_dim /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : V ≃ₗ[K] V₁) : module.rank K V = module.rank K V₁ := cardinal.lift_inj.1 f.lift_dim_eq /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_lift_dim_eq (cond : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin obtain ⟨B, h⟩ := exists_is_basis K V, obtain ⟨B', h'⟩ := exists_is_basis K V', have : cardinal.lift.{v v'} (cardinal.mk B) = cardinal.lift.{v' v} (cardinal.mk B'), by rw [h.mk_eq_dim'', cond, h'.mk_eq_dim''], exact (cardinal.lift_mk_eq.{v v' 0}.1 this).map (linear_equiv_of_is_basis h h') end /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_dim_eq (cond : module.rank K V = module.rank K V₁) : nonempty (V ≃ₗ[K] V₁) := nonempty_linear_equiv_of_lift_dim_eq $ congr_arg _ cond section variables (V V' V₁) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_lift_dim_eq (cond : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V')) : V ≃ₗ[K] V' := classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_dim_eq (cond : module.rank K V = module.rank K V₁) : V ≃ₗ[K] V₁ := classical.choice (nonempty_linear_equiv_of_dim_eq cond) end /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq : nonempty (V ≃ₗ[K] V') ↔ cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K V') := ⟨λ ⟨h⟩, linear_equiv.lift_dim_eq h, λ h, nonempty_linear_equiv_of_lift_dim_eq h⟩ /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_dim_eq : nonempty (V ≃ₗ[K] V₁) ↔ module.rank K V = module.rank K V₁ := ⟨λ ⟨h⟩, linear_equiv.dim_eq h, λ h, nonempty_linear_equiv_of_dim_eq h⟩ @[simp] lemma dim_bot : module.rank K (⊥ : submodule K V) = 0 := by letI := classical.dec_eq V; rw [← cardinal.lift_inj, ← (is_basis_empty (⊥ : submodule K V) not_nonempty_pempty).mk_eq_dim, cardinal.mk_pempty] @[simp] lemma dim_top : module.rank K (⊤ : submodule K V) = module.rank K V := linear_equiv.dim_eq (linear_equiv.of_top _ rfl) lemma dim_of_field (K : Type*) [field K] : module.rank K K = 1 := by rw [←cardinal.lift_inj, ← (@is_basis_singleton_one punit K _ _).mk_eq_dim, cardinal.mk_punit] lemma dim_span {v : ι → V} (hv : linear_independent K v) : module.rank K ↥(span K (range v)) = cardinal.mk (range v) := by rw [←cardinal.lift_inj, ← (is_basis_span hv).mk_eq_dim, cardinal.mk_range_eq_of_injective (@linear_independent.injective ι K V v _ _ _ _ hv)] lemma dim_span_set {s : set V} (hs : linear_independent K (λ x, x : s → V)) : module.rank K ↥(span K s) = cardinal.mk s := by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs } lemma {m} cardinal_lift_le_dim_of_linear_independent {ι : Type w} {v : ι → V} (hv : linear_independent K v) : cardinal.lift.{w (max v m)} (cardinal.mk ι) ≤ cardinal.lift.{v (max w m)} (module.rank K V) := begin obtain ⟨ι', v', is⟩ := exists_sum_is_basis hv, rw [← cardinal.lift_umax, ← cardinal.lift_umax.{v}], simpa using le_trans (cardinal.lift_mk_le.{w _ (max v m)}.2 ⟨@function.embedding.inl ι ι'⟩) (le_of_eq $ is_basis.mk_eq_dim'.{_ _ _ (max w m)} is), end lemma cardinal_le_dim_of_linear_independent {ι : Type v} {v : ι → V} (hv : linear_independent K v) : cardinal.mk ι ≤ module.rank K V := by simpa using cardinal_lift_le_dim_of_linear_independent hv lemma cardinal_le_dim_of_linear_independent' {s : set V} (hs : linear_independent K (λ x, x : s → V)) : cardinal.mk s ≤ module.rank K V := cardinal_le_dim_of_linear_independent hs lemma dim_span_le (s : set V) : module.rank K (span K s) ≤ cardinal.mk s := begin classical, rcases exists_linear_independent (linear_independent_empty K V) (set.empty_subset s) with ⟨b, hb, _, hsb, hlib⟩, have hsab : span K s = span K b, from span_eq_of_le _ hsb (span_le.2 (λ x hx, subset_span (hb hx))), convert cardinal.mk_le_mk_of_subset hb, rw [hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : module.rank K (span K (↑s : set V)) < cardinal.omega := calc module.rank K (span K (↑s : set V)) ≤ cardinal.mk (↑s : set V) : dim_span_le ↑s ... = s.card : by rw ←cardinal.finset_card ... < cardinal.omega : cardinal.nat_lt_omega _ theorem dim_prod : module.rank K (V × V₁) = module.rank K V + module.rank K V₁ := begin rcases exists_is_basis K V with ⟨b, hb⟩, rcases exists_is_basis K V₁ with ⟨c, hc⟩, rw [← cardinal.lift_inj, ← @is_basis.mk_eq_dim K (V × V₁) _ _ _ _ _ (is_basis_inl_union_inr hb hc), cardinal.lift_add, cardinal.lift_mk, ← hb.mk_eq_dim, ← hc.mk_eq_dim, cardinal.lift_mk, cardinal.lift_mk, cardinal.add_def (ulift b) (ulift c)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr (@equiv.ulift b) (@equiv.ulift c)).symm ⟩), end theorem dim_quotient_add_dim (p : submodule K V) : module.rank K p.quotient + module.rank K p = module.rank K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq theorem dim_quotient_le (p : submodule K V) : module.rank K p.quotient ≤ module.rank K V := by { rw ← dim_quotient_add_dim p, exact self_le_add_right _ _ } /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₁) : module.rank K f.range + module.rank K f.ker = module.rank K V := begin haveI := λ (p : submodule K V), classical.dec_eq p.quotient, rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_range_le (f : V →ₗ[K] V₁) : module.rank K f.range ≤ module.rank K V := by { rw ← dim_range_add_dim_ker f, exact self_le_add_right _ _ } lemma dim_map_le (f : V →ₗ V₁) (p : submodule K V) : module.rank K (p.map f) ≤ module.rank K p := begin have h := dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_range_of_surjective (f : V →ₗ[K] V') (h : surjective f) : module.rank K f.range = module.rank K V' := by rw [linear_map.range_eq_top.2 h, dim_top] lemma dim_eq_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) : module.rank K V = module.rank K V₁ + module.rank K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] lemma dim_le_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) : module.rank K V₁ ≤ module.rank K V := by { rw [dim_eq_of_surjective f h], refine self_le_add_right _ _ } lemma dim_eq_of_injective (f : V →ₗ[K] V₁) (h : injective f) : module.rank K V = module.rank K f.range := by rw [← dim_range_add_dim_ker f, linear_map.ker_eq_bot.2 h]; simp [dim_bot] lemma dim_submodule_le (s : submodule K V) : module.rank K s ≤ module.rank K V := by { rw ← dim_quotient_add_dim s, exact self_le_add_left _ _ } lemma dim_le_of_injective (f : V →ₗ[K] V₁) (h : injective f) : module.rank K V ≤ module.rank K V₁ := by { rw [dim_eq_of_injective f h], exact dim_submodule_le _ } lemma dim_le_of_submodule (s t : submodule K V) (h : s ≤ t) : module.rank K s ≤ module.rank K t := dim_le_of_injective (of_le h) $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq lemma linear_independent_le_dim {v : ι → V} (hv : linear_independent K v) : cardinal.lift.{w v} (cardinal.mk ι) ≤ cardinal.lift.{v w} (module.rank K V) := calc cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (cardinal.mk (set.range v)) : (cardinal.mk_range_eq_of_injective (linear_independent.injective hv)).symm ... = cardinal.lift.{v w} (module.rank K (submodule.span K (set.range v))) : by rw (dim_span hv).symm ... ≤ cardinal.lift.{v w} (module.rank K V) : cardinal.lift_le.2 (dim_submodule_le (submodule.span K _)) theorem {u₁} linear_independent_le_dim' {v : ι → V} (hs : linear_independent K v) : ((cardinal.mk ι).lift : cardinal.{(max w v u₁)}) ≤ ((module.rank K V).lift : cardinal.{(max v w u₁)}) := cardinal.mk_range_eq_lift hs.injective ▸ dim_span hs ▸ cardinal.lift_le.2 (dim_submodule_le _) section variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V₃] [module K V₃] open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₂ →ₗ[K] V) (eb : V₃ →ₗ[K] V) (cd : V₁ →ₗ[K] V₂) (ce : V₁ →ₗ[K] V₃) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : module.rank K V + module.rank K V₁ = module.rank K V₂ + module.rank K V₃ := have hf : surjective (coprod db eb), begin refine (range_eq_top.1 $ top_unique $ _), rwa [← map_top, ← prod_top, map_coprod_prod, ←range_eq_map, ←range_eq_map] end, begin conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, refine linear_equiv.of_bijective _ _ _, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, prod_apply, mem_ker, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, prod_apply, mem_ker, set_like.mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) + module.rank K (s ⊓ t : submodule K V) = module.rank K s + module.rank K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_refl _ end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, have : b₁ = b₂ := congr_arg subtype.val eq, subst this, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) ≤ module.rank K s + module.rank K t := by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ } end section fintype variable [fintype η] variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)] open linear_map lemma dim_pi : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) := begin choose b hb using assume i, exists_is_basis K (φ i), have : is_basis K (λ (ji : Σ j, b j), std_basis K (λ j, φ j) ji.fst ji.snd.val), by apply pi.is_basis_std_basis _ hb, rw [←cardinal.lift_inj, ← this.mk_eq_dim], simp [λ i, (hb i).mk_range_eq_dim.symm, cardinal.sum_mk] end lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [module K V] : module.rank K (η → V) = fintype.card η * module.rank K V := by rw [dim_pi, cardinal.sum_const, cardinal.fintype_card] lemma dim_fun_eq_lift_mul : module.rank K (η → V) = (fintype.card η : cardinal.{max u₁' v}) * cardinal.lift.{v u₁'} (module.rank K V) := by rw [dim_pi, cardinal.sum_const_eq_lift_mul, cardinal.fintype_card, cardinal.lift_nat_cast] lemma dim_fun' : module.rank K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_of_field K, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : module.rank K (fin n → K) = n := by simp [dim_fun'] end fintype lemma exists_mem_ne_zero_of_ne_bot {s : submodule K V} (h : s ≠ ⊥) : ∃ b : V, b ∈ s ∧ b ≠ 0 := begin classical, by_contradiction hex, have : ∀x∈s, (x:V) = 0, { simpa only [not_exists, not_and, not_not, ne.def] using hex }, exact (h $ bot_unique $ assume s hs, (submodule.mem_bot K).2 $ this s hs) end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < module.rank K s) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h lemma exists_is_basis_fintype (h : module.rank K V < cardinal.omega) : ∃ s : (set V), (is_basis K (subtype.val : s → V)) ∧ nonempty (fintype s) := begin cases exists_is_basis K V with s hs, rw [←cardinal.lift_lt, ← is_basis.mk_eq_dim hs, cardinal.lift_lt, cardinal.lt_omega_iff_fintype] at h, exact ⟨s, hs, h⟩ end section rank /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V') : cardinal := module.rank K f.range lemma rank_le_domain (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V := by { rw [← dim_range_add_dim_ker f], exact self_le_add_right _ _ } lemma rank_le_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ := dim_submodule_le _ lemma rank_add_le (f g : V →ₗ[K] V') : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ module.rank K (f.range ⊔ g.range : submodule K V') : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V'), from mem_sup.2 ⟨_, ⟨x, rfl⟩, _, ⟨x, rfl⟩, rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ @[simp] lemma rank_zero : rank (0 : V →ₗ[K] V') = 0 := by rw [rank, linear_map.range_zero, dim_bot] lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V') : rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _)) variables [add_comm_group V''] [module K V''] lemma rank_comp_le1 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'') : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact linear_map.map_le_range, end variables [add_comm_group V'₁] [module K V'₁] lemma rank_comp_le2 (g : V →ₗ[K] V') (f : V' →ₗ V'₁) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end rank lemma dim_zero_iff_forall_zero : module.rank K V = 0 ↔ ∀ x : V, x = 0 := begin split, { intros h x, cases exists_is_basis K V with w hw, have card_mk_range := hw.mk_range_eq_dim, rw [h, cardinal.mk_emptyc_iff, subtype.range_coe] at card_mk_range, simpa [card_mk_range] using hw.mem_span x }, { intro h, have : (⊤ : submodule K V) = ⊥, { ext x, simp [h x] }, rw [←dim_top, this, dim_bot] } end lemma dim_zero_iff : module.rank K V = 0 ↔ subsingleton V := dim_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm lemma is_basis_of_dim_eq_zero {ι : Type*} (h : ¬ nonempty ι) (hV : module.rank K V = 0) : is_basis K (λ x : ι, (0 : V)) := begin haveI : subsingleton V := dim_zero_iff.1 hV, exact is_basis_empty _ h end lemma is_basis_of_dim_eq_zero' (hV : module.rank K V = 0) : is_basis K (λ x : fin 0, (0 : V)) := is_basis_of_dim_eq_zero (finset.univ_eq_empty.mp rfl) hV lemma dim_pos_iff_exists_ne_zero : 0 < module.rank K V ↔ ∃ x : V, x ≠ 0 := begin rw ←not_iff_not, simpa using dim_zero_iff_forall_zero end lemma dim_pos_iff_nontrivial : 0 < module.rank K V ↔ nontrivial V := dim_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm lemma dim_pos [h : nontrivial V] : 0 < module.rank K V := dim_pos_iff_nontrivial.2 h lemma le_dim_iff_exists_linear_independent {c : cardinal} : c ≤ module.rank K V ↔ ∃ s : set V, cardinal.mk s = c ∧ linear_independent K (coe : s → V) := begin split, { intro h, rcases exists_is_basis K V with ⟨t, ht⟩, rw [← ht.mk_eq_dim'', cardinal.le_mk_iff_exists_subset] at h, rcases h with ⟨s, hst, hsc⟩, exact ⟨s, hsc, ht.1.mono hst⟩ }, { rintro ⟨s, rfl, si⟩, exact cardinal_le_dim_of_linear_independent si } end lemma le_dim_iff_exists_linear_independent_finset {n : ℕ} : ↑n ≤ module.rank K V ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (coe : (s : set V) → V) := begin simp only [le_dim_iff_exists_linear_independent, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end lemma le_rank_iff_exists_linear_independent {c : cardinal} {f : V →ₗ[K] V'} : c ≤ rank f ↔ ∃ s : set V, cardinal.lift.{v v'} (cardinal.mk s) = cardinal.lift.{v' v} c ∧ linear_independent K (λ x : s, f x) := begin rcases f.range_restrict.exists_right_inverse_of_surjective f.range_range_restrict with ⟨g, hg⟩, have fg : left_inverse f.range_restrict g, from linear_map.congr_fun hg, refine ⟨λ h, _, _⟩, { rcases le_dim_iff_exists_linear_independent.1 h with ⟨s, rfl, si⟩, refine ⟨g '' s, cardinal.mk_image_eq_lift _ _ fg.injective, _⟩, replace fg : ∀ x, f (g x) = x, by { intro x, convert congr_arg subtype.val (fg x) }, replace si : linear_independent K (λ x : s, f (g x)), by simpa only [fg] using si.map' _ (ker_subtype _), exact si.image_of_comp s g f }, { rintro ⟨s, hsc, si⟩, have : linear_independent K (λ x : s, f.range_restrict x), from linear_independent.of_comp (f.range.subtype) (by convert si), convert cardinal_le_dim_of_linear_independent this.image, rw [← cardinal.lift_inj, ← hsc, cardinal.mk_image_eq_of_inj_on_lift], exact inj_on_iff_injective.2 this.injective } end lemma le_rank_iff_exists_linear_independent_finset {n : ℕ} {f : V →ₗ[K] V'} : ↑n ≤ rank f ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (λ x : (s : set V), f x) := begin simp only [le_rank_iff_exists_linear_independent, cardinal.lift_nat_cast, cardinal.lift_eq_nat_iff, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end /-- A vector space has dimension at most `1` if and only if there is a single vector of which all vectors are multiples. -/ lemma dim_le_one_iff : module.rank K V ≤ 1 ↔ ∃ v₀ : V, ∀ v, ∃ r : K, r • v₀ = v := begin obtain ⟨b, h⟩ := exists_is_basis K V, split, { intro hd, rw [←is_basis.mk_eq_dim'' h, cardinal.le_one_iff_subsingleton, subsingleton_coe] at hd, rcases eq_empty_or_nonempty b with rfl | ⟨⟨v₀, hv₀⟩⟩, { use 0, have h' : ∀ v : V, v = 0, { simpa [submodule.eq_bot_iff] using h.2.symm }, intro v, simp [h' v] }, { use v₀, have h' : (K ∙ v₀) = ⊤, { simpa [hd.eq_singleton_of_mem hv₀] using h.2 }, intro v, have hv : v ∈ (⊤ : submodule K V) := mem_top, rwa [←h', mem_span_singleton] at hv } }, { rintros ⟨v₀, hv₀⟩, have h : (K ∙ v₀) = ⊤, { ext, simp [mem_span_singleton, hv₀] }, rw [←dim_top, ←h], convert dim_span_le _, simp } end /-- A submodule has dimension at most `1` if and only if there is a single vector in the submodule such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀ ∈ s, s ≤ K ∙ v₀ := begin simp_rw [dim_le_one_iff, le_span_singleton_iff], split, { rintro ⟨⟨v₀, hv₀⟩, h⟩, use [v₀, hv₀], intros v hv, obtain ⟨r, hr⟩ := h ⟨v, hv⟩, use r, simp_rw [subtype.ext_iff, coe_smul, coe_mk] at hr, exact hr }, { rintro ⟨v₀, hv₀, h⟩, use ⟨v₀, hv₀⟩, rintro ⟨v, hv⟩, obtain ⟨r, hr⟩ := h v hv, use r, simp_rw [subtype.ext_iff, coe_smul, coe_mk], exact hr } end /-- A submodule has dimension at most `1` if and only if there is a single vector, not necessarily in the submodule, such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff' (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀, s ≤ K ∙ v₀ := begin rw dim_submodule_le_one_iff, split, { rintros ⟨v₀, hv₀, h⟩, exact ⟨v₀, h⟩ }, { rintros ⟨v₀, h⟩, by_cases hw : ∃ w : V, w ∈ s ∧ w ≠ 0, { rcases hw with ⟨w, hw, hw0⟩, use [w, hw], rcases mem_span_singleton.1 (h hw) with ⟨r', rfl⟩, have h0 : r' ≠ 0, { rintro rfl, simpa using hw0 }, rwa span_singleton_smul_eq _ h0 }, { push_neg at hw, rw ←submodule.eq_bot_iff at hw, simp [hw] } } end end module section unconstrained_universes variables {E : Type v'} variables [field K] [add_comm_group V] [module K V] [add_comm_group E] [module K E] open module /-- Version of linear_equiv.dim_eq without universe constraints. -/ theorem linear_equiv.dim_eq_lift (f : V ≃ₗ[K] E) : cardinal.lift.{v v'} (module.rank K V) = cardinal.lift.{v' v} (module.rank K E) := begin cases exists_is_basis K V with b hb, rw [← cardinal.lift_inj.1 hb.mk_eq_dim, ← (f.is_basis hb).mk_eq_dim, cardinal.lift_mk], end end unconstrained_universes
dda19688d75616f3388698b332001fa12b837440
618003631150032a5676f229d13a079ac875ff77
/src/topology/uniform_space/complete_separated.lean
5e8a25a0f37de63232718b9b7a5183a9cf81c8bf
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
1,341
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel Theory of complete separated uniform spaces. This file is for elementary lemmas that depend on both Cauchy filters and separation. -/ import topology.uniform_space.cauchy import topology.uniform_space.separation import topology.dense_embedding open filter open_locale topological_space variables {α : Type*} /-In a separated space, a complete set is closed -/ lemma is_closed_of_is_complete [uniform_space α] [separated α] {s : set α} (h : is_complete s) : is_closed s := is_closed_iff_nhds.2 $ λ a ha, begin let f := 𝓝 a ⊓ principal s, have : cauchy f := cauchy_downwards (cauchy_nhds) ha (inf_le_left), rcases h f this (inf_le_right) with ⟨y, ys, fy⟩, rwa (tendsto_nhds_unique ha inf_le_left fy : a = y) end namespace dense_inducing open filter variables [topological_space α] {β : Type*} [topological_space β] variables {γ : Type*} [uniform_space γ] [complete_space γ] [separated γ] lemma continuous_extend_of_cauchy {e : α → β} {f : α → γ} (de : dense_inducing e) (h : ∀ b : β, cauchy (map f (comap e $ 𝓝 b))) : continuous (de.extend f) := de.continuous_extend $ λ b, complete_space.complete (h b) end dense_inducing
c58b805e3f7f26304c195aee8aab074e4b748fce
4fa161becb8ce7378a709f5992a594764699e268
/src/order/ideal.lean
780472f723d6c60aee30b5d250d701ebaca491cf
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
4,937
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import order.basic import data.equiv.encodable /-! # Order ideals, cofinal sets, and the Rasiowa–Sikorski lemma ## Main definitions We work with a preorder `P` throughout. - `ideal P`: the type of upward directed, downward closed subsets of `P`. Dual to the notion of a filter on a preorder. - `cofinal P`: the type of subsets of `P` containing arbitrarily large elements. Dual to the notion of 'dense set' used in forcing. - `ideal_of_cofinals p 𝒟`, where `p : P`, and `𝒟` is a countable family of cofinal subsets of P: an ideal in `P` which contains `p` and intersects every set in `𝒟`. ## References - https://en.wikipedia.org/wiki/Ideal_(order_theory) - https://en.wikipedia.org/wiki/Cofinal_(mathematics) - https://en.wikipedia.org/wiki/Rasiowa–Sikorski_lemma Note that for the Rasiowa–Sikorski lemma, Wikipedia uses the opposite ordering on `P`, in line with most presentations of forcing. ## Tags ideal, cofinal, dense, countable, generic -/ namespace order variables {P : Type*} [preorder P] /-- An ideal on a preorder `P` is a subset of `P` that is - nonempty - upward directed - downward closed. -/ structure ideal (P) [preorder P] := (carrier : set P) (nonempty : carrier.nonempty) (directed : directed_on (≤) carrier) (mem_of_le : ∀ {x y : P}, x ≤ y → y ∈ carrier → x ∈ carrier) namespace ideal /-- The smallest ideal containing a given element. -/ def principal (p : P) : ideal P := { carrier := { x | x ≤ p }, nonempty := ⟨p, le_refl _⟩, directed := λ x hx y hy, ⟨p, le_refl _, hx, hy⟩, mem_of_le := λ x y hxy hy, le_trans hxy hy, } instance [inhabited P] : inhabited (ideal P) := ⟨ideal.principal $ default P⟩ instance : has_mem P (ideal P) := ⟨λ x I, x ∈ I.carrier⟩ end ideal /-- For a preorder `P`, `cofinal P` is the type of subsets of `P` containing arbitrarily large elements. They are the dense sets in the topology whose open sets are terminal segments. -/ structure cofinal (P) [preorder P] := (carrier : set P) (mem_gt : ∀ x : P, ∃ y ∈ carrier, x ≤ y) instance : inhabited (cofinal P) := ⟨{ carrier := set.univ, mem_gt := λ x, ⟨x, trivial, le_refl _⟩}⟩ instance : has_mem P (cofinal P) := ⟨λ x D, x ∈ D.carrier⟩ namespace cofinal variables (D : cofinal P) (x : P) /-- A (noncomputable) element of a cofinal set lying above a given element. -/ noncomputable def above : P := classical.some $ D.mem_gt x lemma above_mem : D.above x ∈ D := exists.elim (classical.some_spec $ D.mem_gt x) $ λ a _, a lemma le_above : x ≤ D.above x := exists.elim (classical.some_spec $ D.mem_gt x) $ λ _ b, b end cofinal section ideal_of_cofinals variables (p : P) {ι : Type*} [encodable ι] (𝒟 : ι → cofinal P) /-- Given a starting point, and a countable family of cofinal sets, this is an increasing sequence that intersects each cofinal set. -/ noncomputable def sequence_of_cofinals : ℕ → P | 0 := p | (n+1) := match encodable.decode ι n with | none := sequence_of_cofinals n | some i := (𝒟 i).above (sequence_of_cofinals n) end lemma sequence_of_cofinals.monotone : monotone (sequence_of_cofinals p 𝒟) := by { apply monotone_of_monotone_nat, intros n, dunfold sequence_of_cofinals, cases encodable.decode ι n, { refl }, { apply cofinal.le_above }, } lemma sequence_of_cofinals.encode_mem (i : ι) : sequence_of_cofinals p 𝒟 (encodable.encode i + 1) ∈ 𝒟 i := by { dunfold sequence_of_cofinals, rw encodable.encodek, apply cofinal.above_mem, } /-- Given an element `p : P` and a family `𝒟` of cofinal subsets of a preorder `P`, indexed by a countable type, `ideal_of_cofinals p 𝒟` is an ideal in `P` which - contains `p`, according to `mem_ideal_of_cofinals p 𝒟`, and - intersects every set in `𝒟`, according to `cofinal_meets_ideal_of_cofinals p 𝒟`. This proves the Rasiowa–Sikorski lemma. -/ def ideal_of_cofinals : ideal P := { carrier := { x : P | ∃ n, x ≤ sequence_of_cofinals p 𝒟 n }, nonempty := ⟨p, 0, le_refl _⟩, directed := λ x ⟨n, hn⟩ y ⟨m, hm⟩, ⟨_, ⟨max n m, le_refl _⟩, le_trans hn $ sequence_of_cofinals.monotone p 𝒟 (le_max_left _ _), le_trans hm $ sequence_of_cofinals.monotone p 𝒟 (le_max_right _ _) ⟩, mem_of_le := λ x y hxy ⟨n, hn⟩, ⟨n, le_trans hxy hn⟩, } lemma mem_ideal_of_cofinals : p ∈ ideal_of_cofinals p 𝒟 := ⟨0, le_refl _⟩ /-- `ideal_of_cofinals p 𝒟` is `𝒟`-generic. -/ lemma cofinal_meets_ideal_of_cofinals (i : ι) : ∃ x : P, x ∈ 𝒟 i ∧ x ∈ ideal_of_cofinals p 𝒟 := ⟨_, sequence_of_cofinals.encode_mem p 𝒟 i, _, le_refl _⟩ end ideal_of_cofinals end order
28a2c7157c81adf5272de8a1294c9ef122a9200f
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/library/theories/analysis/normed_space.lean
21c9e46f73e3266d15dbfa112c80ff759599782f
[ "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
9,489
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Normed spaces. -/ import algebra.module .metric_space open real nat classical noncomputable theory structure has_norm [class] (M : Type) : Type := (norm : M → ℝ) namespace analysis definition norm {M : Type} [has_normM : has_norm M] (v : M) : ℝ := has_norm.norm v notation `∥`v`∥` := norm v end analysis /- real vector spaces -/ -- where is the right place to put this? structure real_vector_space [class] (V : Type) extends vector_space ℝ V section variables {V : Type} [real_vector_space V] -- these specializations help the elaborator when it is hard to infer the ring, e.g. with numerals proposition smul_left_distrib_real (a : ℝ) (u v : V) : a • (u + v) = a • u + a • v := smul_left_distrib a u v proposition smul_right_distrib_real (a b : ℝ) (u : V) : (a + b) • u = a • u + b • u := smul_right_distrib a b u proposition mul_smul_real (a : ℝ) (b : ℝ) (u : V) : (a * b) • u = a • (b • u) := mul_smul a b u proposition one_smul_real (u : V) : (1 : ℝ) • u = u := one_smul u proposition zero_smul_real (u : V) : (0 : ℝ) • u = 0 := zero_smul u proposition smul_zero_real (a : ℝ) : a • (0 : V) = 0 := smul_zero a proposition neg_smul_real (a : ℝ) (u : V) : (-a) • u = - (a • u) := neg_smul a u proposition neg_one_smul_real (u : V) : -(1 : ℝ) • u = -u := neg_one_smul u proposition smul_neg_real (a : ℝ) (u : V) : a • (-u) = -(a • u) := smul_neg a u end /- real normed vector spaces -/ structure normed_vector_space [class] (V : Type) extends real_vector_space V, has_norm V := (norm_zero : norm zero = 0) (eq_zero_of_norm_eq_zero : ∀ u : V, norm u = 0 → u = zero) (norm_triangle : ∀ u v, norm (add u v) ≤ norm u + norm v) (norm_smul : ∀ (a : ℝ) (v : V), norm (smul a v) = abs a * norm v) namespace analysis variable {V : Type} variable [normed_vector_space V] proposition norm_zero : ∥ (0 : V) ∥ = 0 := !normed_vector_space.norm_zero proposition eq_zero_of_norm_eq_zero {u : V} (H : ∥ u ∥ = 0) : u = 0 := !normed_vector_space.eq_zero_of_norm_eq_zero H proposition norm_triangle (u v : V) : ∥ u + v ∥ ≤ ∥ u ∥ + ∥ v ∥ := !normed_vector_space.norm_triangle proposition norm_smul (a : ℝ) (v : V) : ∥ a • v ∥ = abs a * ∥ v ∥ := !normed_vector_space.norm_smul proposition norm_neg (v : V) : ∥ -v ∥ = ∥ v ∥ := have abs (1 : ℝ) = 1, from abs_of_nonneg zero_le_one, by+ rewrite [-@neg_one_smul ℝ V, norm_smul, abs_neg, this, one_mul] proposition norm_sub (u v : V) : ∥u - v∥ = ∥v - u∥ := by rewrite [-norm_neg, neg_sub] end analysis section open analysis variable {V : Type} variable [normed_vector_space V] private definition nvs_dist [reducible] (u v : V) := ∥ u - v ∥ private lemma nvs_dist_self (u : V) : nvs_dist u u = 0 := by rewrite [↑nvs_dist, sub_self, norm_zero] private lemma eq_of_nvs_dist_eq_zero (u v : V) (H : nvs_dist u v = 0) : u = v := have u - v = 0, from eq_zero_of_norm_eq_zero H, eq_of_sub_eq_zero this private lemma nvs_dist_triangle (u v w : V) : nvs_dist u w ≤ nvs_dist u v + nvs_dist v w := calc nvs_dist u w = ∥ (u - v) + (v - w) ∥ : by rewrite [↑nvs_dist, *sub_eq_add_neg, add.assoc, neg_add_cancel_left] ... ≤ ∥ u - v ∥ + ∥ v - w ∥ : norm_triangle private lemma nvs_dist_comm (u v : V) : nvs_dist u v = nvs_dist v u := by rewrite [↑nvs_dist, -norm_neg, neg_sub] definition normed_vector_space_to_metric_space [reducible] [trans_instance] (V : Type) [nvsV : normed_vector_space V] : metric_space V := ⦃ metric_space, dist := nvs_dist, dist_self := nvs_dist_self, eq_of_dist_eq_zero := eq_of_nvs_dist_eq_zero, dist_comm := nvs_dist_comm, dist_triangle := nvs_dist_triangle ⦄ open nat proposition converges_to_seq_norm_elim {X : ℕ → V} {x : V} (H : X ⟶ x in ℕ) : ∀ {ε : ℝ}, ε > 0 → ∃ N₁ : ℕ, ∀ {n : ℕ}, n ≥ N₁ → ∥ X n - x ∥ < ε := H proposition dist_eq_norm_sub (u v : V) : dist u v = ∥ u - v ∥ := rfl proposition norm_eq_dist_zero (u : V) : ∥ u ∥ = dist u 0 := by rewrite [dist_eq_norm_sub, sub_zero] proposition norm_nonneg (u : V) : ∥ u ∥ ≥ 0 := by rewrite norm_eq_dist_zero; apply !dist_nonneg end structure banach_space [class] (V : Type) extends nvsV : normed_vector_space V := (complete : ∀ X, @analysis.cauchy V (@normed_vector_space_to_metric_space V nvsV) X → @analysis.converges_seq V (@normed_vector_space_to_metric_space V nvsV) X) definition banach_space_to_metric_space [reducible] [trans_instance] (V : Type) [bsV : banach_space V] : complete_metric_space V := ⦃ complete_metric_space, normed_vector_space_to_metric_space V, complete := banach_space.complete ⦄ namespace analysis variable {V : Type} variable [normed_vector_space V] variables {X Y : ℕ → V} variables {x y : V} proposition add_converges_to_seq (HX : X ⟶ x in ℕ) (HY : Y ⟶ y in ℕ) : (λ n, X n + Y n) ⟶ x + y in ℕ := take ε : ℝ, suppose ε > 0, have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos, obtain (N₁ : ℕ) (HN₁ : ∀ {n}, n ≥ N₁ → ∥ X n - x ∥ < ε / 2), from converges_to_seq_norm_elim HX e2pos, obtain (N₂ : ℕ) (HN₂ : ∀ {n}, n ≥ N₂ → ∥ Y n - y ∥ < ε / 2), from converges_to_seq_norm_elim HY e2pos, let N := max N₁ N₂ in exists.intro N (take n, suppose n ≥ N, have ngtN₁ : n ≥ N₁, from nat.le_trans !le_max_left `n ≥ N`, have ngtN₂ : n ≥ N₂, from nat.le_trans !le_max_right `n ≥ N`, show ∥ (X n + Y n) - (x + y) ∥ < ε, from calc ∥ (X n + Y n) - (x + y) ∥ = ∥ (X n - x) + (Y n - y) ∥ : by rewrite [sub_add_eq_sub_sub, *sub_eq_add_neg, *add.assoc, add.left_comm (-x)] ... ≤ ∥ X n - x ∥ + ∥ Y n - y ∥ : norm_triangle ... < ε / 2 + ε / 2 : add_lt_add (HN₁ ngtN₁) (HN₂ ngtN₂) ... = ε : add_halves) private lemma smul_converges_to_seq_aux {c : ℝ} (cnz : c ≠ 0) (HX : X ⟶ x in ℕ) : (λ n, c • X n) ⟶ c • x in ℕ := take ε : ℝ, suppose ε > 0, have abscpos : abs c > 0, from abs_pos_of_ne_zero cnz, have epos : ε / abs c > 0, from div_pos_of_pos_of_pos `ε > 0` abscpos, obtain N (HN : ∀ {n}, n ≥ N → norm (X n - x) < ε / abs c), from converges_to_seq_norm_elim HX epos, exists.intro N (take n, suppose n ≥ N, have H : norm (X n - x) < ε / abs c, from HN this, show norm (c • X n - c • x) < ε, from calc norm (c • X n - c • x) = abs c * norm (X n - x) : by rewrite [-smul_sub_left_distrib, norm_smul] ... < abs c * (ε / abs c) : mul_lt_mul_of_pos_left H abscpos ... = ε : mul_div_cancel' (ne_of_gt abscpos)) proposition smul_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) : (λ n, c • X n) ⟶ c • x in ℕ := by_cases (assume cz : c = 0, have (λ n, c • X n) = (λ n, 0), from funext (take x, by rewrite [cz, zero_smul]), begin+ rewrite [this, cz, zero_smul], apply converges_to_seq_constant end) (suppose c ≠ 0, smul_converges_to_seq_aux this HX) proposition neg_converges_to_seq (HX : X ⟶ x in ℕ) : (λ n, - X n) ⟶ - x in ℕ := take ε, suppose ε > 0, obtain N (HN : ∀ {n}, n ≥ N → norm (X n - x) < ε), from converges_to_seq_norm_elim HX this, exists.intro N (take n, suppose n ≥ N, show norm (- X n - (- x)) < ε, by rewrite [-neg_neg_sub_neg, *neg_neg, norm_neg]; exact HN `n ≥ N`) proposition neg_converges_to_seq_iff : ((λ n, - X n) ⟶ - x in ℕ) ↔ (X ⟶ x in ℕ) := have aux : X = λ n, (- (- X n)), from funext (take n, by rewrite neg_neg), iff.intro (assume H : (λ n, -X n)⟶ -x in ℕ, show X ⟶ x in ℕ, by+ rewrite [aux, -neg_neg x]; exact neg_converges_to_seq H) neg_converges_to_seq proposition norm_converges_to_seq_zero (HX : X ⟶ 0 in ℕ) : (λ n, norm (X n)) ⟶ 0 in ℕ := take ε, suppose ε > 0, obtain N (HN : ∀ n, n ≥ N → norm (X n - 0) < ε), from HX `ε > 0`, exists.intro N (take n, assume Hn : n ≥ N, have norm (X n) < ε, begin rewrite -(sub_zero (X n)), apply HN n Hn end, show abs (norm (X n) - 0) < ε, using this, by rewrite [sub_zero, abs_of_nonneg !norm_nonneg]; apply this) proposition converges_to_seq_zero_of_norm_converges_to_seq_zero (HX : (λ n, norm (X n)) ⟶ 0 in ℕ) : X ⟶ 0 in ℕ := take ε, suppose ε > 0, obtain N (HN : ∀ n, n ≥ N → abs (norm (X n) - 0) < ε), from HX `ε > 0`, exists.intro (N : ℕ) (take n : ℕ, assume Hn : n ≥ N, have HN' : abs (norm (X n) - 0) < ε, from HN n Hn, have norm (X n) < ε, by+ rewrite [sub_zero at HN', abs_of_nonneg !norm_nonneg at HN']; apply HN', show norm (X n - 0) < ε, using this, by rewrite sub_zero; apply this) proposition norm_converges_to_seq_zero_iff (X : ℕ → V) : ((λ n, norm (X n)) ⟶ 0 in ℕ) ↔ (X ⟶ 0 in ℕ) := iff.intro converges_to_seq_zero_of_norm_converges_to_seq_zero norm_converges_to_seq_zero end analysis
5e9d862bc5d60552c96833617be1fe2e845777e5
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/group_theory/perm/list.lean
603eb7c5ddbade5ac26c98658c1888066e84bf7e
[ "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
16,377
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.list.rotate import group_theory.perm.support /-! # Permutations from a list A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. When there are duplicate elements in `l`, how and in what arrangement with respect to the other elements they appear in the list determines the formed permutation. This is because `list.form_perm` is implemented as a product of `equiv.swap`s. That means that presence of a sublist of two adjacent duplicates like `[..., x, x, ...]` will produce the same permutation as if the adjacent duplicates were not present. The `list.form_perm` definition is meant to primarily be used with `nodup l`, so that the resulting permutation is cyclic (if `l` has at least two elements). The presence of duplicates in a particular placement can lead `list.form_perm` to produce a nontrivial permutation that is noncyclic. -/ namespace list variables {α β : Type*} section form_perm variables [decidable_eq α] (l : list α) open equiv equiv.perm /-- A list `l : list α` can be interpreted as a `equiv.perm α` where each element in the list is permuted to the next one, defined as `form_perm`. When we have that `nodup l`, we prove that `equiv.perm.support (form_perm l) = l.to_finset`, and that `form_perm l` is rotationally invariant, in `form_perm_rotate`. -/ def form_perm : equiv.perm α := (zip_with equiv.swap l l.tail).prod @[simp] lemma form_perm_nil : form_perm ([] : list α) = 1 := rfl @[simp] lemma form_perm_singleton (x : α) : form_perm [x] = 1 := rfl @[simp] lemma form_perm_cons_cons (x y : α) (l : list α) : form_perm (x :: y :: l) = swap x y * form_perm (y :: l) := prod_cons lemma form_perm_pair (x y : α) : form_perm [x, y] = swap x y := rfl lemma form_perm_apply_of_not_mem (x : α) (l : list α) (h : x ∉ l) : form_perm l x = x := begin cases l with y l, { simp }, induction l with z l IH generalizing x y, { simp }, { specialize IH x z (mt (mem_cons_of_mem y) h), simp only [not_or_distrib, mem_cons_iff] at h, simp [IH, swap_apply_of_ne_of_ne, h] } end lemma form_perm_apply_mem_of_mem (x : α) (l : list α) (h : x ∈ l) : form_perm l x ∈ l := begin cases l with y l, { simpa }, induction l with z l IH generalizing x y, { simpa using h }, { by_cases hx : x ∈ z :: l, { rw [form_perm_cons_cons, mul_apply, swap_apply_def], split_ifs; simp [IH _ _ hx] }, { replace h : x = y := or.resolve_right h hx, simp [form_perm_apply_of_not_mem _ _ hx, ←h] } } end @[simp] lemma form_perm_cons_concat_apply_last (x y : α) (xs : list α) : form_perm (x :: (xs ++ [y])) y = x := begin induction xs with z xs IH generalizing x y, { simp }, { simp [IH] } end @[simp] lemma form_perm_apply_last (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).last (cons_ne_nil x xs)) = x := begin induction xs using list.reverse_rec_on with xs y IH generalizing x; simp end @[simp] lemma form_perm_apply_nth_le_length (x : α) (xs : list α) : form_perm (x :: xs) ((x :: xs).nth_le xs.length (by simp)) = x := by rw [nth_le_cons_length, form_perm_apply_last] lemma form_perm_apply_head (x y : α) (xs : list α) (h : nodup (x :: y :: xs)) : form_perm (x :: y :: xs) x = y := by simp [form_perm_apply_of_not_mem _ _ (not_mem_of_nodup_cons h)] lemma form_perm_apply_nth_le_zero (l : list α) (h : nodup l) (hl : 1 < l.length) : form_perm l (l.nth_le 0 (zero_lt_one.trans hl)) = l.nth_le 1 hl := begin rcases l with (_|⟨x, _|⟨y, tl⟩⟩), { simp }, { simp }, { simpa using form_perm_apply_head _ _ _ h } end lemma form_perm_eq_head_iff_eq_last (x y : α) : form_perm (y :: l) x = y ↔ x = last (y :: l) (cons_ne_nil _ _) := iff.trans (by rw form_perm_apply_last) (form_perm (y :: l)).injective.eq_iff lemma zip_with_swap_prod_support' (l l' : list α) : {x | (zip_with swap l l').prod x ≠ x} ≤ l.to_finset ⊔ l'.to_finset := begin simp only [set.sup_eq_union, set.le_eq_subset], induction l with y l hl generalizing l', { simp }, { cases l' with z l', { simp }, { intro x, simp only [set.union_subset_iff, mem_cons_iff, zip_with_cons_cons, foldr, prod_cons, mul_apply], intro hx, by_cases h : x ∈ {x | (zip_with swap l l').prod x ≠ x}, { specialize hl l' h, refine set.mem_union.elim hl (λ hm, _) (λ hm, _); { simp only [finset.coe_insert, set.mem_insert_iff, finset.mem_coe, to_finset_cons, mem_to_finset] at hm ⊢, simp [hm] } }, { simp only [not_not, set.mem_set_of_eq] at h, simp only [h, set.mem_set_of_eq] at hx, rw swap_apply_ne_self_iff at hx, rcases hx with ⟨hyz, rfl|rfl⟩; simp } } } end lemma zip_with_swap_prod_support [fintype α] (l l' : list α) : (zip_with swap l l').prod.support ≤ l.to_finset ⊔ l'.to_finset := begin intros x hx, have hx' : x ∈ {x | (zip_with swap l l').prod x ≠ x} := by simpa using hx, simpa using zip_with_swap_prod_support' _ _ hx' end lemma support_form_perm_le' : {x | form_perm l x ≠ x} ≤ l.to_finset := begin refine (zip_with_swap_prod_support' l l.tail).trans _, simpa [finset.subset_iff] using tail_subset l end lemma support_form_perm_le [fintype α] : support (form_perm l) ≤ l.to_finset := begin intros x hx, have hx' : x ∈ {x | form_perm l x ≠ x} := by simpa using hx, simpa using support_form_perm_le' _ hx' end lemma form_perm_apply_lt (xs : list α) (h : nodup xs) (n : ℕ) (hn : n + 1 < xs.length) : form_perm xs (xs.nth_le n ((nat.lt_succ_self n).trans hn)) = xs.nth_le (n + 1) hn := begin induction n with n IH generalizing xs, { simpa using form_perm_apply_nth_le_zero _ h _ }, { rcases xs with (_|⟨x, _|⟨y, l⟩⟩), { simp }, { simp }, { specialize IH (y :: l) (nodup_of_nodup_cons h) _, { simpa [nat.succ_lt_succ_iff] using hn }, simp only [swap_apply_eq_iff, coe_mul, form_perm_cons_cons, nth_le], generalize_proofs at IH, rw [IH, swap_apply_of_ne_of_ne, nth_le]; { rintro rfl, simpa [nth_le_mem _ _ _] using h } } } end lemma form_perm_apply_nth_le (xs : list α) (h : nodup xs) (n : ℕ) (hn : n < xs.length) : form_perm xs (xs.nth_le n hn) = xs.nth_le ((n + 1) % xs.length) (nat.mod_lt _ (n.zero_le.trans_lt hn)) := begin cases xs with x xs, { simp }, { have : n ≤ xs.length, { refine nat.le_of_lt_succ _, simpa using hn }, rcases this.eq_or_lt with rfl|hn', { simp }, { simp [form_perm_apply_lt, h, nat.mod_eq_of_lt, nat.succ_lt_succ hn'] } } end lemma support_form_perm_of_nodup' (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : {x | form_perm l x ≠ x} = l.to_finset := begin apply le_antisymm, { exact support_form_perm_le' l }, { intros x hx, simp only [finset.mem_coe, mem_to_finset] at hx, obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx, rw [set.mem_set_of_eq, form_perm_apply_nth_le _ h], intro H, rw nodup_iff_nth_le_inj at h, specialize h _ _ _ _ H, cases (nat.succ_le_of_lt hn).eq_or_lt with hn' hn', { simp only [←hn', nat.mod_self] at h, refine not_exists.mpr h' _, simpa [←h, eq_comm, length_eq_one] using hn' }, { simpa [nat.mod_eq_of_lt hn'] using h } } end lemma support_form_perm_of_nodup [fintype α] (l : list α) (h : nodup l) (h' : ∀ (x : α), l ≠ [x]) : support (form_perm l) = l.to_finset := begin rw ←finset.coe_inj, convert support_form_perm_of_nodup' _ h h', simp [set.ext_iff] end lemma form_perm_rotate_one (l : list α) (h : nodup l) : form_perm (l.rotate 1) = form_perm l := begin have h' : nodup (l.rotate 1), { simpa using h }, by_cases hl : ∀ (x : α), l ≠ [x], { have hl' : ∀ (x : α), l.rotate 1 ≠ [x], { intro, rw [ne.def, rotate_eq_iff], simpa using hl _ }, ext x, by_cases hx : x ∈ l.rotate 1, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ h', nth_le_rotate l, nth_le_rotate l, form_perm_apply_nth_le _ h], simp }, { rw [form_perm_apply_of_not_mem _ _ hx, form_perm_apply_of_not_mem], simpa using hx } }, { push_neg at hl, obtain ⟨x, rfl⟩ := hl, simp } end lemma form_perm_rotate (l : list α) (h : nodup l) (n : ℕ) : form_perm (l.rotate n) = form_perm l := begin induction n with n hn, { simp }, { rw [nat.succ_eq_add_one, ←rotate_rotate, form_perm_rotate_one, hn], rwa is_rotated.nodup_iff, exact is_rotated.forall l n } end lemma form_perm_eq_of_is_rotated {l l' : list α} (hd : nodup l) (h : l ~r l') : form_perm l = form_perm l' := begin obtain ⟨n, rfl⟩ := h, exact (form_perm_rotate l hd n).symm end lemma form_perm_reverse (l : list α) (h : nodup l) : form_perm l.reverse = (form_perm l)⁻¹ := begin -- Let's show `form_perm l` is an inverse to `form_perm l.reverse`. rw [eq_comm, inv_eq_iff_mul_eq_one], ext x, -- We only have to check for `x ∈ l` that `form_perm l (form_perm l.reverse x)` rw [mul_apply, one_apply], by_cases hx : x ∈ l, swap, { rw [form_perm_apply_of_not_mem x l.reverse, form_perm_apply_of_not_mem _ _ hx], simpa using hx }, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem (mem_reverse.mpr hx), rw [form_perm_apply_nth_le l.reverse (nodup_reverse.mpr h), nth_le_reverse', form_perm_apply_nth_le _ h, nth_le_reverse'], { congr, rw [length_reverse, ←nat.succ_le_iff, nat.succ_eq_add_one] at hk, cases hk.eq_or_lt with hk' hk', { simp [←hk'] }, { rw [length_reverse, nat.mod_eq_of_lt hk', ←nat.sub_add_comm (nat.le_pred_of_lt hk'), nat.mod_eq_of_lt], { simp }, { rw nat.sub_add_cancel, refine nat.sub_lt_self _ (nat.zero_lt_succ _), all_goals { simpa using (nat.zero_le _).trans_lt hk' } } } }, all_goals { rw [nat.sub_sub, ←length_reverse], refine nat.sub_lt_self _ (zero_lt_one.trans_le (le_add_right le_rfl)), exact k.zero_le.trans_lt hk } }, end lemma form_perm_pow_apply_nth_le (l : list α) (h : nodup l) (n k : ℕ) (hk : k < l.length) : (form_perm l ^ n) (l.nth_le k hk) = l.nth_le ((k + n) % l.length) (nat.mod_lt _ (k.zero_le.trans_lt hk)) := begin induction n with n hn, { simp [nat.mod_eq_of_lt hk] }, { simp [pow_succ, mul_apply, hn, form_perm_apply_nth_le _ h, nat.succ_eq_add_one, ←nat.add_assoc] } end lemma form_perm_pow_apply_head (x : α) (l : list α) (h : nodup (x :: l)) (n : ℕ) : (form_perm (x :: l) ^ n) x = (x :: l).nth_le (n % (x :: l).length) (nat.mod_lt _ (nat.zero_lt_succ _)) := by { convert form_perm_pow_apply_nth_le _ h n 0 _; simp } lemma form_perm_ext_iff {x y x' y' : α} {l l' : list α} (hd : nodup (x :: y :: l)) (hd' : nodup (x' :: y' :: l')) : form_perm (x :: y :: l) = form_perm (x' :: y' :: l') ↔ (x :: y :: l) ~r (x' :: y' :: l') := begin refine ⟨λ h, _, λ hr, form_perm_eq_of_is_rotated hd hr⟩, rw equiv.perm.ext_iff at h, have hx : x' ∈ (x :: y :: l), { have : x' ∈ {z | form_perm (x :: y :: l) z ≠ z}, { rw [set.mem_set_of_eq, h x', form_perm_apply_head _ _ _ hd'], simp only [mem_cons_iff, nodup_cons] at hd', push_neg at hd', exact hd'.left.left.symm }, simpa using support_form_perm_le' _ this }, obtain ⟨n, hn, hx'⟩ := nth_le_of_mem hx, have hl : (x :: y :: l).length = (x' :: y' :: l').length, { rw [←erase_dup_eq_self.mpr hd, ←erase_dup_eq_self.mpr hd', ←card_to_finset, ←card_to_finset], refine congr_arg finset.card _, rw [←finset.coe_inj, ←support_form_perm_of_nodup' _ hd (by simp), ←support_form_perm_of_nodup' _ hd' (by simp)], simp only [h] }, use n, apply list.ext_le, { rw [length_rotate, hl] }, { intros k hk hk', rw nth_le_rotate, induction k with k IH, { simp_rw [nat.zero_add, nat.mod_eq_of_lt hn], simpa }, { have : k.succ = (k + 1) % (x' :: y' :: l').length, { rw [←nat.succ_eq_add_one, nat.mod_eq_of_lt hk'] }, simp_rw this, rw [←form_perm_apply_nth_le _ hd' k (k.lt_succ_self.trans hk'), ←IH (k.lt_succ_self.trans hk), ←h, form_perm_apply_nth_le _ hd], congr' 1, have h1 : 1 = 1 % (x' :: y' :: l').length := by simp, rw [hl, nat.mod_eq_of_lt hk', h1, ←nat.add_mod, nat.succ_add] } } end lemma form_perm_apply_mem_eq_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x = x ↔ length l ≤ 1 := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, rw [form_perm_apply_nth_le _ hl, hl.nth_le_inj_iff], cases hn : l.length, { exact absurd k.zero_le (hk.trans_le hn.le).not_le }, { rw hn at hk, cases (nat.le_of_lt_succ hk).eq_or_lt with hk' hk', { simp [←hk', nat.succ_le_succ_iff, eq_comm] }, { simpa [nat.mod_eq_of_lt (nat.succ_lt_succ hk'), nat.succ_lt_succ_iff] using k.zero_le.trans_lt hk' } } end lemma form_perm_apply_mem_ne_self_iff (hl : nodup l) (x : α) (hx : x ∈ l) : form_perm l x ≠ x ↔ 2 ≤ l.length := begin rw [ne.def, form_perm_apply_mem_eq_self_iff _ hl x hx, not_le], exact ⟨nat.succ_le_of_lt, nat.lt_of_succ_le⟩ end lemma mem_of_form_perm_ne_self (l : list α) (x : α) (h : form_perm l x ≠ x) : x ∈ l := begin suffices : x ∈ {y | form_perm l y ≠ y}, { rw ←mem_to_finset, exact support_form_perm_le' _ this }, simpa using h end lemma form_perm_eq_self_of_not_mem (l : list α) (x : α) (h : x ∉ l) : form_perm l x = x := by_contra (λ H, h $ mem_of_form_perm_ne_self _ _ H) lemma form_perm_eq_one_iff (hl : nodup l) : form_perm l = 1 ↔ l.length ≤ 1 := begin cases l with hd tl, { simp }, { rw ←form_perm_apply_mem_eq_self_iff _ hl hd (mem_cons_self _ _), split, { simp {contextual := tt} }, { intro h, simp only [(hd :: tl).form_perm_apply_mem_eq_self_iff hl hd (mem_cons_self hd tl), add_le_iff_nonpos_left, length, nonpos_iff_eq_zero, length_eq_zero] at h, simp [h] } } end lemma form_perm_eq_form_perm_iff {l l' : list α} (hl : l.nodup) (hl' : l'.nodup) : l.form_perm = l'.form_perm ↔ l ~r l' ∨ l.length ≤ 1 ∧ l'.length ≤ 1 := begin rcases l with (_ | ⟨x, _ | ⟨y, l⟩⟩), { suffices : l'.length ≤ 1 ↔ l' = nil ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero] }, refine ⟨λ h, or.inr h, _⟩, rintro (rfl | h), { simp }, { exact h } }, { suffices : l'.length ≤ 1 ↔ [x] ~r l' ∨ l'.length ≤ 1, { simpa [eq_comm, form_perm_eq_one_iff, hl, hl', length_eq_zero, le_rfl] }, refine ⟨λ h, or.inr h, _⟩, rintro (h | h), { simp [←h.perm.length_eq] }, { exact h } }, { rcases l' with (_ | ⟨x', _ | ⟨y', l'⟩⟩), { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, { suffices : ¬ (x :: y :: l) ~r [x'], { simp [form_perm_eq_one_iff, hl, -form_perm_cons_cons] }, intro h, simpa using h.perm.length_eq }, { simp [-form_perm_cons_cons, form_perm_ext_iff hl hl'] } } end lemma form_perm_gpow_apply_mem_imp_mem (l : list α) (x : α) (hx : x ∈ l) (n : ℤ) : ((form_perm l) ^ n) x ∈ l := begin by_cases h : (l.form_perm ^ n) x = x, { simpa [h] using hx }, { have : x ∈ {x | (l.form_perm ^ n) x ≠ x} := h, rw ←set_support_apply_mem at this, replace this := set_support_gpow_subset _ _ this, simpa using support_form_perm_le' _ this } end lemma form_perm_pow_length_eq_one_of_nodup (hl : nodup l) : (form_perm l) ^ (length l) = 1 := begin ext x, by_cases hx : x ∈ l, { obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx, simp [form_perm_pow_apply_nth_le _ hl, nat.mod_eq_of_lt hk] }, { have : x ∉ {x | (l.form_perm ^ l.length) x ≠ x}, { intros H, refine hx _, replace H := set_support_gpow_subset l.form_perm l.length H, simpa using support_form_perm_le' _ H }, simpa } end end form_perm end list
9390f896577a9b0b9f8b11134f89053d965de432
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category_theory/endomorphism.lean
cbb9d263996cc35698b1e13291ec53c13a8f0b8e
[ "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
3,187
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Scott Morrison, Simon Hudon Definition and basic properties of endomorphisms and automorphisms of an object in a category. -/ import category_theory.category category_theory.isomorphism category_theory.groupoid category_theory.functor import algebra.group.units data.equiv.algebra universes v v' u u' namespace category_theory /-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with `function.comp`, not with `category.comp`. -/ def End {C : Type u} [𝒞_struct : category_struct.{v+1} C] (X : C) := X ⟶ X namespace End section struct variables {C : Type u} [𝒞_struct : category_struct.{v+1} C] (X : C) include 𝒞_struct instance has_one : has_one (End X) := ⟨𝟙 X⟩ /-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/ instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩ variable {X} @[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl @[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl end struct /-- Endomorphisms of an object form a monoid -/ instance monoid {C : Type u} [category.{v+1} C] {X : C} : monoid (End X) := { mul_one := category.id_comp C, one_mul := category.comp_id C, mul_assoc := λ x y z, (category.assoc C z y x).symm, ..End.has_mul X, ..End.has_one X } /-- In a groupoid, endomorphisms form a group -/ instance group {C : Type u} [groupoid.{v+1} C] (X : C) : group (End X) := { mul_left_inv := groupoid.comp_inv C, inv := groupoid.inv, ..End.monoid } end End def Aut {C : Type u} [𝒞 : category.{v+1} C] (X : C) := X ≅ X attribute [extensionality Aut] iso.ext namespace Aut variables {C : Type u} [𝒞 : category.{v+1} C] (X : C) include 𝒞 instance: group (Aut X) := by refine { one := iso.refl X, inv := iso.symm, mul := flip iso.trans, .. } ; dunfold flip; obviously def units_End_eqv_Aut : units (End X) ≃* Aut X := { to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩, inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩, left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl, right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl, map_mul' := λ f g, by rcases f; rcases g; refl } end Aut namespace functor variables {C : Type u} [𝒞 : category.{v+1} C] {D : Type u'} [𝒟 : category.{v'+1} D] (f : C ⥤ D) {X : C} include 𝒞 𝒟 def map_End : End X → End (f.obj X) := functor.map f instance map_End.is_monoid_hom : is_monoid_hom (f.map_End : End X → End (f.obj X)) := { map_mul := λ x y, f.map_comp y x, map_one := f.map_id X } def map_Aut : Aut X → Aut (f.obj X) := functor.map_iso f instance map_Aut.is_group_hom : is_group_hom (f.map_Aut : Aut X → Aut (f.obj X)) := { map_mul := λ x y, f.map_iso_trans y x } end functor instance functor.map_End_is_group_hom {C : Type u} [𝒞 : groupoid.{v+1} C] {D : Type u'} [𝒟 : groupoid.{v'+1} D] (f : C ⥤ D) {X : C} : is_group_hom (f.map_End : End X → End (f.obj X)) := { ..functor.map_End.is_monoid_hom f } end category_theory
2559474803d129ae8ec32b83c8ccca6e9a0b37c2
f4bff2062c030df03d65e8b69c88f79b63a359d8
/world_plans/supinf.lean
06b66198fcca9e6e79bc76279495f269cec864a3
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,207
lean
import defs instance : has_add (set ℝ) := ⟨λ S T, {u : ℝ | ∃ (s ∈ S) (t ∈ T), u = s + t}⟩ /- Goal: state and prove Richard Thomas' problem sheet question. -/ namespace real_number_game def is_nonempty (S : set ℝ) : Prop := ∃ s : ℝ, s ∈ S def is_bounded_above (S : set ℝ) : Prop := ∃ b : ℝ, ∀ x ∈ S, x ≤ b -- hide this from them instance foo {S : set ℝ} [nonemptyP S] (x : ℝ) : nonemptyP {t : ℝ | ∃ s ∈ S, t = s + x} := ⟨ begin cases nonemptyP.thm S with s hs, use s + x, use s, use hs -- , refl end⟩ -- they can do this example (S : set ℝ) (hS : is_nonempty S) (x : ℝ) : is_nonempty {t : ℝ | ∃ s ∈ S, t = s + x} := begin cases hS with s hs, use s + x, use s, use hs, -- , refl end -- hide this from them instance foo' {S : set ℝ} [bounded_aboveP S] (x : ℝ) : bounded_aboveP {t : ℝ | ∃ s ∈ S, t = s + x} := ⟨ begin cases bounded_aboveP.thm S with b hb, use b + x, intros t ht, rcases ht with ⟨s, hs, ht⟩, have hsb : s ≤ b, exact hb s hs, linarith, end⟩ -- they can do this example (S : set ℝ) (hs : is_bounded_above S) (x : ℝ) : is_bounded_above {t : ℝ | ∃ s ∈ S, t = s + x} := begin cases hs with b hb, use b + x, intros t ht, rcases ht with ⟨s, hs, ht⟩, have hsb : s ≤ b, exact hb s hs, linarith, end -- they can do this theorem Sup_add_real {S : set ℝ} [nonemptyP S] [bounded_aboveP S] (x : ℝ) : Sup {t : ℝ | ∃ s ∈ S, t = s + x} = Sup S + x := begin apply le_antisymm, { apply Sup_le, intros t ht, rcases ht with ⟨s, hs, ht2⟩, have hs2 : s ≤ Sup S, exact le_Sup s hs, linarith, }, { apply add_le_of_le_sub_right, apply Sup_le, intros s hs, apply le_sub_right_of_add_le, apply le_Sup, use s, use hs, } end -- theorems which need to be done. -- theorem --THIS NEEDS TO BE TAUGHT. Don't need contradiction? theorem exists_gt_of_lt_Sup (S : set ℝ) [nonemptyP S] [bounded_aboveP S] : ∀ c, c < Sup S → ∃ s ∈ S, c < s := begin intros c hc, apply classical.by_contradiction, intro h, push_neg at h, have h2 := Sup_le c h, linarith, end theorem gt_Sup_minus_eps (S : set ℝ) [nonemptyP S] [bounded_aboveP S] : ∀ ε, 0 < ε → ∃ s ∈ S, Sup S - ε < s := begin intros ε hε, apply exists_gt_of_lt_Sup, linarith, end -- too hard? instance (X Y : set ℝ) [nonemptyT X] [nonemptyT Y] : nonemptyT (X + Y) := { x := nonemptyT.x X + nonemptyT.x Y, thm := ⟨nonemptyT.x X, nonemptyT.thm X, nonemptyT.x Y, nonemptyT.thm Y, rfl⟩ } -- too hard? instance (X Y : set ℝ) [nonemptyP X] [nonemptyP Y] : nonemptyP (X + Y) := ⟨ begin cases nonemptyP.thm X with a ha, cases nonemptyP.thm Y with b hb, use a + b, use a, use ha, use b, use hb, end⟩ -- What they can do: theorem nonempty.add (X Y : set ℝ) (hX : is_nonempty X) (hY : is_nonempty Y) : is_nonempty (X + Y) := begin cases hX with a ha, cases hY with b hb, use a + b, use a, use ha, use b, use hb, -- no refl :- end -- too hard :-( without chat about instances instance bounded_above.sum (X Y : set ℝ) [bounded_aboveT X] [bounded_aboveT Y] : bounded_aboveT (X + Y) := { b := bounded_aboveT.b X + bounded_aboveT.b Y, thm := begin rintro _ ⟨x, hx, y, hy, rfl⟩, have : x ≤ _ := bounded_aboveT.thm X x hx, have : y ≤ _ := bounded_aboveT.thm Y y hy, linarith end } instance bounded_aboveP.sum (X Y : set ℝ) [bounded_aboveP X] [bounded_aboveP Y] : bounded_aboveP (X + Y) := ⟨ begin cases bounded_aboveP.thm X with a ha, cases bounded_aboveP.thm Y with b hb, use a + b, rintro _ ⟨x, hx, y, hy, rfl⟩, have : x ≤ a := ha x hx, have : y ≤ b := hb y hy, linarith end⟩ -- What they can do: example (X Y : set ℝ) (hX : is_bounded_above X) (hY : is_bounded_above Y) : is_bounded_above (X + Y) := begin cases hX with a ha, cases hY with b hb, use a + b, intros z hz, rcases hz with ⟨x, hx, y, hy, h⟩, have h1 : x ≤ a := ha x hx, have h2 : y ≤ b := hb y hy, linarith, end -- Or maybe this? def is_bounded_above_by (S : set ℝ) (b : ℝ) := ∀ s ∈ S, s ≤ b example (X Y : set ℝ) (a b : ℝ) (haX : is_bounded_above_by X a) (hbY : is_bounded_above_by Y b) : is_bounded_above_by (X + Y) (a + b) := begin intros s hs, rcases hs with ⟨x, hx, y, hy, h⟩, have h1 : x ≤ a := haX x hx, have h2 : y ≤ b := hbY y hy, linarith, end -- theorem -- THIS NEEDS TO BE TAUGHT; this proof is *long*. -- Probably should prove each direction separately theorem real.Sup_add -- (X : set ℝ) [h1X : nonemptyP X] [h2X : bounded_aboveP X] (Y : set ℝ) [h2Y : nonemptyP Y] [h2Y : bounded_aboveP Y] : Sup (X + Y) = Sup X + Sup Y := begin apply le_antisymm, { apply Sup_le, unfold is_upper_bound, intros s hs, rcases hs with ⟨x, hx, y, hy, h⟩, rw h, have h1 : x ≤ Sup X, exact le_Sup x hx, have h2 : y ≤ Sup Y, exact le_Sup y hy, linarith, }, { by_contradiction h, push_neg at h, set ε := (Sup X + Sup Y) - Sup (X + Y) with hε, have h1 : 0 < ε/2, linarith, have h2 := gt_Sup_minus_eps X (ε/2) h1, have h3 := gt_Sup_minus_eps Y (ε/2) h1, rcases h2 with ⟨a, ha, h4⟩, rcases h3 with ⟨b, hb, h5⟩, have h6 : a + b ∈ X + Y, use a, use ha, use b, use hb, have h7 := le_Sup (a + b) h6, linarith, } end -- now onto Richard Thomas' question about sup{sup(S1),sup(S2),sup(S3),...}=sup(union of S_i) -- Hmm, we need a shedload of instances to make this make sense. -- this is horrible, why not use ereal? If I used ereal then this is always true. -- let me just start ploughing through this instance foo3 (f : ℕ → set ℝ) (n : ℕ) [nonemptyP (f n)] : nonemptyP (⋃ i, f i) := ⟨ begin cases nonemptyP.thm (f n) with x hx, use x, rw set.mem_Union, use n, assumption end⟩ -- still more typeclass issues with this. example (f : ℕ → set ℝ) [∀ n, nonemptyP (f n)] [bounded_aboveP (⋃ i, f i)] : Sup (⋃ i, f i) = Sup (set.range (λ n, Sup (f n))) := sorry end real_number_game
f4c0da904037d054f617c0795ef92d32986df949
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/eq_to_hom.lean
0ae887d5de67404c9246b7ac3675c452b6918bd2
[ "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,075
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison -/ import category_theory.opposites /-! # Morphisms from equations between objects. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. When working categorically, sometimes one encounters an equation `h : X = Y` between objects. Your initial aversion to this is natural and appropriate: you're in for some trouble, and if there is another way to approach the problem that won't rely on this equality, it may be worth pursuing. You have two options: 1. Use the equality `h` as one normally would in Lean (e.g. using `rw` and `subst`). This may immediately cause difficulties, because in category theory everything is dependently typed, and equations between objects quickly lead to nasty goals with `eq.rec`. 2. Promote `h` to a morphism using `eq_to_hom h : X ⟶ Y`, or `eq_to_iso h : X ≅ Y`. This file introduces various `simp` lemmas which in favourable circumstances result in the various `eq_to_hom` morphisms to drop out at the appropriate moment! -/ universes v₁ v₂ v₃ u₁ u₂ u₃ -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory open opposite variables {C : Type u₁} [category.{v₁} C] /-- An equality `X = Y` gives us a morphism `X ⟶ Y`. It is typically better to use this, rather than rewriting by the equality then using `𝟙 _` which usually leads to dependent type theory hell. -/ def eq_to_hom {X Y : C} (p : X = Y) : X ⟶ Y := by rw p; exact 𝟙 _ @[simp] lemma eq_to_hom_refl (X : C) (p : X = X) : eq_to_hom p = 𝟙 X := rfl @[simp, reassoc] lemma eq_to_hom_trans {X Y Z : C} (p : X = Y) (q : Y = Z) : eq_to_hom p ≫ eq_to_hom q = eq_to_hom (p.trans q) := by { cases p, cases q, simp, } lemma comp_eq_to_hom_iff {X Y Y' : C} (p : Y = Y') (f : X ⟶ Y) (g : X ⟶ Y') : f ≫ eq_to_hom p = g ↔ f = g ≫ eq_to_hom p.symm := { mp := λ h, h ▸ by simp, mpr := λ h, by simp [eq_whisker h (eq_to_hom p)] } lemma eq_to_hom_comp_iff {X X' Y : C} (p : X = X') (f : X ⟶ Y) (g : X' ⟶ Y) : eq_to_hom p ≫ g = f ↔ g = eq_to_hom p.symm ≫ f := { mp := λ h, h ▸ by simp, mpr := λ h, h ▸ by simp [whisker_eq _ h] } /-- If we (perhaps unintentionally) perform equational rewriting on the source object of a morphism, we can replace the resulting `_.mpr f` term by a composition with an `eq_to_hom`. It may be advisable to introduce any necessary `eq_to_hom` morphisms manually, rather than relying on this lemma firing. -/ @[simp] lemma congr_arg_mpr_hom_left {X Y Z : C} (p : X = Y) (q : Y ⟶ Z) : (congr_arg (λ W : C, W ⟶ Z) p).mpr q = eq_to_hom p ≫ q := by { cases p, simp, } /-- If we (perhaps unintentionally) perform equational rewriting on the target object of a morphism, we can replace the resulting `_.mpr f` term by a composition with an `eq_to_hom`. It may be advisable to introduce any necessary `eq_to_hom` morphisms manually, rather than relying on this lemma firing. -/ @[simp] lemma congr_arg_mpr_hom_right {X Y Z : C} (p : X ⟶ Y) (q : Z = Y) : (congr_arg (λ W : C, X ⟶ W) q).mpr p = p ≫ eq_to_hom q.symm := by { cases q, simp, } /-- An equality `X = Y` gives us an isomorphism `X ≅ Y`. It is typically better to use this, rather than rewriting by the equality then using `iso.refl _` which usually leads to dependent type theory hell. -/ def eq_to_iso {X Y : C} (p : X = Y) : X ≅ Y := ⟨eq_to_hom p, eq_to_hom p.symm, by simp, by simp⟩ @[simp] lemma eq_to_iso.hom {X Y : C} (p : X = Y) : (eq_to_iso p).hom = eq_to_hom p := rfl @[simp] lemma eq_to_iso.inv {X Y : C} (p : X = Y) : (eq_to_iso p).inv = eq_to_hom p.symm := rfl @[simp] lemma eq_to_iso_refl {X : C} (p : X = X) : eq_to_iso p = iso.refl X := rfl @[simp] lemma eq_to_iso_trans {X Y Z : C} (p : X = Y) (q : Y = Z) : eq_to_iso p ≪≫ eq_to_iso q = eq_to_iso (p.trans q) := by ext; simp @[simp] lemma eq_to_hom_op {X Y : C} (h : X = Y) : (eq_to_hom h).op = eq_to_hom (congr_arg op h.symm) := by { cases h, refl, } @[simp] lemma eq_to_hom_unop {X Y : Cᵒᵖ} (h : X = Y) : (eq_to_hom h).unop = eq_to_hom (congr_arg unop h.symm) := by { cases h, refl, } instance {X Y : C} (h : X = Y) : is_iso (eq_to_hom h) := is_iso.of_iso (eq_to_iso h) @[simp] lemma inv_eq_to_hom {X Y : C} (h : X = Y) : inv (eq_to_hom h) = eq_to_hom h.symm := by { ext, simp, } variables {D : Type u₂} [category.{v₂} D] namespace functor /-- Proving equality between functors. This isn't an extensionality lemma, because usually you don't really want to do this. -/ lemma ext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ X Y f, F.map f = eq_to_hom (h_obj X) ≫ G.map f ≫ eq_to_hom (h_obj Y).symm) : F = G := begin cases F with F_obj _ _ _, cases G with G_obj _ _ _, obtain rfl : F_obj = G_obj, by { ext X, apply h_obj }, congr, funext X Y f, simpa using h_map X Y f end /-- Two morphisms are conjugate via eq_to_hom if and only if they are heterogeneously equal. -/ lemma conj_eq_to_hom_iff_heq {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) (h : W = Y) (h' : X = Z) : f = eq_to_hom h ≫ g ≫ eq_to_hom h'.symm ↔ f == g := by { cases h, cases h', simp } /-- Proving equality between functors using heterogeneous equality. -/ lemma hext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ X Y (f : X ⟶ Y), F.map f == G.map f) : F = G := functor.ext h_obj (λ _ _ f, (conj_eq_to_hom_iff_heq _ _ (h_obj _) (h_obj _)).2 $ h_map _ _ f) -- Using equalities between functors. lemma congr_obj {F G : C ⥤ D} (h : F = G) (X) : F.obj X = G.obj X := by subst h lemma congr_hom {F G : C ⥤ D} (h : F = G) {X Y} (f : X ⟶ Y) : F.map f = eq_to_hom (congr_obj h X) ≫ G.map f ≫ eq_to_hom (congr_obj h Y).symm := by subst h; simp lemma congr_inv_of_congr_hom (F G : C ⥤ D) {X Y : C} (e : X ≅ Y) (hX : F.obj X = G.obj X) (hY : F.obj Y = G.obj Y) (h₂ : F.map e.hom = eq_to_hom (by rw hX) ≫ G.map e.hom ≫ eq_to_hom (by rw hY)) : F.map e.inv = eq_to_hom (by rw hY) ≫ G.map e.inv ≫ eq_to_hom (by rw hX) := by simp only [← is_iso.iso.inv_hom e, functor.map_inv, h₂, is_iso.inv_comp, inv_eq_to_hom, category.assoc] lemma congr_map (F : C ⥤ D) {X Y : C} {f g : X ⟶ Y} (h : f = g) : F.map f = F.map g := by rw h section heq /- Composition of functors and maps w.r.t. heq -/ variables {E : Type u₃} [category.{v₃} E] {F G : C ⥤ D} {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} lemma map_comp_heq (hx : F.obj X = G.obj X) (hy : F.obj Y = G.obj Y) (hz : F.obj Z = G.obj Z) (hf : F.map f == G.map f) (hg : F.map g == G.map g) : F.map (f ≫ g) == G.map (f ≫ g) := by { rw [F.map_comp, G.map_comp], congr' } lemma map_comp_heq' (hobj : ∀ X : C, F.obj X = G.obj X) (hmap : ∀ {X Y} (f : X ⟶ Y), F.map f == G.map f) : F.map (f ≫ g) == G.map (f ≫ g) := by rw functor.hext hobj (λ _ _, hmap) lemma precomp_map_heq (H : E ⥤ C) (hmap : ∀ {X Y} (f : X ⟶ Y), F.map f == G.map f) {X Y : E} (f : X ⟶ Y) : (H ⋙ F).map f == (H ⋙ G).map f := hmap _ lemma postcomp_map_heq (H : D ⥤ E) (hx : F.obj X = G.obj X) (hy : F.obj Y = G.obj Y) (hmap : F.map f == G.map f) : (F ⋙ H).map f == (G ⋙ H).map f := by { dsimp, congr' } lemma postcomp_map_heq' (H : D ⥤ E) (hobj : ∀ X : C, F.obj X = G.obj X) (hmap : ∀ {X Y} (f : X ⟶ Y), F.map f == G.map f) : (F ⋙ H).map f == (G ⋙ H).map f := by rw functor.hext hobj (λ _ _, hmap) lemma hcongr_hom {F G : C ⥤ D} (h : F = G) {X Y} (f : X ⟶ Y) : F.map f == G.map f := by subst h end heq end functor /-- This is not always a good idea as a `@[simp]` lemma, as we lose the ability to use results that interact with `F`, e.g. the naturality of a natural transformation. In some files it may be appropriate to use `local attribute [simp] eq_to_hom_map`, however. -/ lemma eq_to_hom_map (F : C ⥤ D) {X Y : C} (p : X = Y) : F.map (eq_to_hom p) = eq_to_hom (congr_arg F.obj p) := by cases p; simp /-- See the note on `eq_to_hom_map` regarding using this as a `simp` lemma. -/ lemma eq_to_iso_map (F : C ⥤ D) {X Y : C} (p : X = Y) : F.map_iso (eq_to_iso p) = eq_to_iso (congr_arg F.obj p) := by ext; cases p; simp @[simp] lemma eq_to_hom_app {F G : C ⥤ D} (h : F = G) (X : C) : (eq_to_hom h : F ⟶ G).app X = eq_to_hom (functor.congr_obj h X) := by subst h; refl lemma nat_trans.congr {F G : C ⥤ D} (α : F ⟶ G) {X Y : C} (h : X = Y) : α.app X = F.map (eq_to_hom h) ≫ α.app Y ≫ G.map (eq_to_hom h.symm) := by { rw [α.naturality_assoc], simp [eq_to_hom_map], } lemma eq_conj_eq_to_hom {X Y : C} (f : X ⟶ Y) : f = eq_to_hom rfl ≫ f ≫ eq_to_hom rfl := by simp only [category.id_comp, eq_to_hom_refl, category.comp_id] lemma dcongr_arg {ι : Type*} {F G : ι → C} (α : ∀ i, F i ⟶ G i) {i j : ι} (h : i = j) : α i = eq_to_hom (congr_arg F h) ≫ α j ≫ eq_to_hom (congr_arg G h.symm) := by { subst h, simp } end category_theory
cf9381a393fed3c9591f29aa19ea2b3ccf341a88
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/category/Semigroup/basic.lean
ad3ebe18aa566c567a60e19851fd96f4e3d74030
[ "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
7,284
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import algebra.pempty_instances import algebra.hom.equiv import category_theory.concrete_category.bundled_hom import category_theory.functor.reflects_isomorphisms import category_theory.elementwise /-! # Category instances for has_mul, has_add, semigroup and add_semigroup We introduce the bundled categories: * `Magma` * `AddMagma` * `Semigroup` * `AddSemigroup` along with the relevant forgetful functors between them. This closely follows `algebra.category.Mon.basic`. ## TODO * Limits in these categories * free/forgetful adjunctions -/ universes u v open category_theory /-- The category of magmas and magma morphisms. -/ @[to_additive AddMagma] def Magma : Type (u+1) := bundled has_mul /-- The category of additive magmas and additive magma morphisms. -/ add_decl_doc AddMagma namespace Magma @[to_additive] instance bundled_hom : bundled_hom @mul_hom := ⟨@mul_hom.to_fun, @mul_hom.id, @mul_hom.comp, @mul_hom.coe_inj⟩ attribute [derive [large_category, concrete_category]] Magma attribute [to_additive] Magma.large_category Magma.concrete_category @[to_additive] instance : has_coe_to_sort Magma Type* := bundled.has_coe_to_sort /-- Construct a bundled `Magma` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [has_mul M] : Magma := bundled.of M /-- Construct a bundled `AddMagma` from the underlying type and typeclass. -/ add_decl_doc AddMagma.of /-- Typecheck a `mul_hom` as a morphism in `Magma`. -/ @[to_additive] def of_hom {X Y : Type u} [has_mul X] [has_mul Y] (f : X →ₙ* Y) : of X ⟶ of Y := f /-- Typecheck a `add_hom` as a morphism in `AddMagma`. -/ add_decl_doc AddMagma.of_hom @[simp, to_additive] lemma of_hom_apply {X Y : Type u} [has_mul X] [has_mul Y] (f : X →ₙ* Y) (x : X) : of_hom f x = f x := rfl @[to_additive] instance : inhabited Magma := ⟨Magma.of pempty⟩ @[to_additive] instance (M : Magma) : has_mul M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [has_mul R] : (Magma.of R : Type u) = R := rfl end Magma /-- The category of semigroups and semigroup morphisms. -/ @[to_additive AddSemigroup] def Semigroup : Type (u+1) := bundled semigroup /-- The category of additive semigroups and semigroup morphisms. -/ add_decl_doc AddSemigroup namespace Semigroup @[to_additive] instance : bundled_hom.parent_projection semigroup.to_has_mul := ⟨⟩ attribute [derive [large_category, concrete_category]] Semigroup attribute [to_additive] Semigroup.large_category Semigroup.concrete_category @[to_additive] instance : has_coe_to_sort Semigroup Type* := bundled.has_coe_to_sort /-- Construct a bundled `Semigroup` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [semigroup M] : Semigroup := bundled.of M /-- Construct a bundled `AddSemigroup` from the underlying type and typeclass. -/ add_decl_doc AddSemigroup.of /-- Typecheck a `mul_hom` as a morphism in `Semigroup`. -/ @[to_additive] def of_hom {X Y : Type u} [semigroup X] [semigroup Y] (f : X →ₙ* Y) : of X ⟶ of Y := f /-- Typecheck a `add_hom` as a morphism in `AddSemigroup`. -/ add_decl_doc AddSemigroup.of_hom @[simp, to_additive] lemma of_hom_apply {X Y : Type u} [semigroup X] [semigroup Y] (f : X →ₙ* Y) (x : X) : of_hom f x = f x := rfl @[to_additive] instance : inhabited Semigroup := ⟨Semigroup.of pempty⟩ @[to_additive] instance (M : Semigroup) : semigroup M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [semigroup R] : (Semigroup.of R : Type u) = R := rfl @[to_additive has_forget_to_AddMagma] instance has_forget_to_Magma : has_forget₂ Semigroup Magma := bundled_hom.forget₂ _ _ end Semigroup variables {X Y : Type u} section variables [has_mul X] [has_mul Y] /-- Build an isomorphism in the category `Magma` from a `mul_equiv` between `has_mul`s. -/ @[to_additive add_equiv.to_AddMagma_iso "Build an isomorphism in the category `AddMagma` from an `add_equiv` between `has_add`s.", simps] def mul_equiv.to_Magma_iso (e : X ≃* Y) : Magma.of X ≅ Magma.of Y := { hom := e.to_mul_hom, inv := e.symm.to_mul_hom } end section variables [semigroup X] [semigroup Y] /-- Build an isomorphism in the category `Semigroup` from a `mul_equiv` between `semigroup`s. -/ @[to_additive add_equiv.to_AddSemigroup_iso "Build an isomorphism in the category `AddSemigroup` from an `add_equiv` between `add_semigroup`s.", simps] def mul_equiv.to_Semigroup_iso (e : X ≃* Y) : Semigroup.of X ≅ Semigroup.of Y := { hom := e.to_mul_hom, inv := e.symm.to_mul_hom } end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Magma`. -/ @[to_additive AddMagma_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMagma`."] def Magma_iso_to_mul_equiv {X Y : Magma} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, by simp, right_inv := λ y, by simp, map_mul' := by simp } /-- Build a `mul_equiv` from an isomorphism in the category `Semigroup`. -/ @[to_additive "Build an `add_equiv` from an isomorphism in the category `AddSemigroup`."] def Semigroup_iso_to_mul_equiv {X Y : Semigroup} (i : X ≅ Y) : X ≃* Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, by simp, right_inv := λ y, by simp, map_mul' := by simp } end category_theory.iso /-- multiplicative equivalences between `has_mul`s are the same as (isomorphic to) isomorphisms in `Magma` -/ @[to_additive add_equiv_iso_AddMagma_iso "additive equivalences between `has_add`s are the same as (isomorphic to) isomorphisms in `AddMagma`"] def mul_equiv_iso_Magma_iso {X Y : Type u} [has_mul X] [has_mul Y] : (X ≃* Y) ≅ (Magma.of X ≅ Magma.of Y) := { hom := λ e, e.to_Magma_iso, inv := λ i, i.Magma_iso_to_mul_equiv } /-- multiplicative equivalences between `semigroup`s are the same as (isomorphic to) isomorphisms in `Semigroup` -/ @[to_additive add_equiv_iso_AddSemigroup_iso "additive equivalences between `add_semigroup`s are the same as (isomorphic to) isomorphisms in `AddSemigroup`"] def mul_equiv_iso_Semigroup_iso {X Y : Type u} [semigroup X] [semigroup Y] : (X ≃* Y) ≅ (Semigroup.of X ≅ Semigroup.of Y) := { hom := λ e, e.to_Semigroup_iso, inv := λ i, i.Semigroup_iso_to_mul_equiv } @[to_additive] instance Magma.forget_reflects_isos : reflects_isomorphisms (forget Magma.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Magma).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_Magma_iso).1⟩, end } @[to_additive] instance Semigroup.forget_reflects_isos : reflects_isomorphisms (forget Semigroup.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Semigroup).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_Semigroup_iso).1⟩, end } /-! Once we've shown that the forgetful functors to type reflect isomorphisms, we automatically obtain that the `forget₂` functors between our concrete categories reflect isomorphisms. -/ example : reflects_isomorphisms (forget₂ Semigroup Magma) := by apply_instance
8f2964122e71ddec349fce4336abe3879e39e6d0
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Elab/Extra.lean
f282b120b78743d3ad662f8980c6b0ec8e4d3dba
[ "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
20,313
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.App import Lean.Elab.BuiltinNotation /-! # Auxiliary elaboration functions: AKA custom elaborators -/ namespace Lean.Elab.Term open Meta private def getMonadForIn (expectedType? : Option Expr) : TermElabM Expr := do match expectedType? with | none => throwError "invalid 'for_in%' notation, expected type is not available" | some expectedType => match (← isTypeApp? expectedType) with | some (m, _) => return m | none => throwError "invalid 'for_in%' notation, expected type is not of of the form `M α`{indentExpr expectedType}" private def throwForInFailure (forInInstance : Expr) : TermElabM Expr := throwError "failed to synthesize instance for 'for_in%' notation{indentExpr forInInstance}" @[builtinTermElab forInMacro] def elabForIn : TermElab := fun stx expectedType? => do match stx with | `(for_in% $col $init $body) => match (← isLocalIdent? col) with | none => elabTerm (← `(let col := $col; for_in% col $init $body)) expectedType? | some colFVar => tryPostponeIfNoneOrMVar expectedType? let m ← getMonadForIn expectedType? let colType ← inferType colFVar let elemType ← mkFreshExprMVar (mkSort (mkLevelSucc (← mkFreshLevelMVar))) let forInInstance ← try mkAppM ``ForIn #[m, colType, elemType] catch _ => tryPostpone; throwError "failed to construct 'ForIn' instance for collection{indentExpr colType}\nand monad{indentExpr m}" match (← trySynthInstance forInInstance) with | .some inst => let forInFn ← mkConst ``forIn elabAppArgs forInFn (namedArgs := #[{ name := `m, val := Arg.expr m}, { name := `α, val := Arg.expr elemType }, { name := `self, val := Arg.expr inst }]) (args := #[Arg.stx col, Arg.stx init, Arg.stx body]) (expectedType? := expectedType?) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) | .undef => tryPostpone; throwForInFailure forInInstance | .none => throwForInFailure forInInstance | _ => throwUnsupportedSyntax @[builtinTermElab forInMacro'] def elabForIn' : TermElab := fun stx expectedType? => do match stx with | `(for_in'% $col $init $body) => match (← isLocalIdent? col) with | none => elabTerm (← `(let col := $col; for_in'% col $init $body)) expectedType? | some colFVar => tryPostponeIfNoneOrMVar expectedType? let m ← getMonadForIn expectedType? let colType ← inferType colFVar let elemType ← mkFreshExprMVar (mkSort (mkLevelSucc (← mkFreshLevelMVar))) let forInInstance ← try let memType ← mkFreshExprMVar (← mkAppM ``Membership #[elemType, colType]) mkAppM ``ForIn' #[m, colType, elemType, memType] catch _ => tryPostpone; throwError "failed to construct `ForIn'` instance for collection{indentExpr colType}\nand monad{indentExpr m}" match (← trySynthInstance forInInstance) with | .some inst => let forInFn ← mkConst ``forIn' elabAppArgs forInFn (namedArgs := #[{ name := `m, val := Arg.expr m}, { name := `α, val := Arg.expr elemType}, { name := `self, val := Arg.expr inst }]) (args := #[Arg.expr colFVar, Arg.stx init, Arg.stx body]) (expectedType? := expectedType?) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) | .undef => tryPostpone; throwForInFailure forInInstance | .none => throwForInFailure forInInstance | _ => throwUnsupportedSyntax namespace BinOp /-! The elaborator for `binop%` terms works as follows: 1- Expand macros. 2- Convert `Syntax` object corresponding to the `binop%` term into a `Tree`. The `toTree` method visits nested `binop%` terms and parentheses. 3- Synthesize pending metavariables without applying default instances and using the `(mayPostpone := true)`. 4- Tries to compute a maximal type for the tree computed at step 2. We say a type α is smaller than type β if there is a (nondependent) coercion from α to β. We are currently ignoring the case we may have cycles in the coercion graph. If there are "uncomparable" types α and β in the tree, we skip the next step. We say two types are "uncomparable" if there isn't a coercion between them. Note that two types may be "uncomparable" because some typing information may still be missing. 5- We traverse the tree and inject coercions to the "maximal" type when needed. Recall that the coercions are expanded eagerly by the elaborator. Properties: a) Given `n : Nat` and `i : Nat`, it can successfully elaborate `n + i` and `i + n`. Recall that Lean 3 fails on the former. b) The coercions are inserted in the "leaves" like in Lean 3. c) There are no coercions "hidden" inside instances, and we can elaborate ``` axiom Int.add_comm (i j : Int) : i + j = j + i example (n : Nat) (i : Int) : n + i = i + n := by rw [Int.add_comm] ``` Recall that the `rw` tactic used to fail because our old `binop%` elaborator would hide coercions inside of a `HAdd` instance. Remarks: In the new `binop%` elaborator the decision whether a coercion will be inserted or not is made at `binop%` elaboration time. This was not the case in the old elaborator. For example, an instance, such as `HAdd Int ?m ?n`, could be created when executing the `binop%` elaborator, and only resolved much later. We try to minimize this problem by synthesizing pending metavariables at step 3. For types containing heterogeneous operators (e.g., matrix multiplication), step 4 will fail and we will skip coercion insertion. For example, `x : Matrix Real 5 4` and `y : Matrix Real 4 8`, there is no coercion `Matrix Real 5 4` from `Matrix Real 4 8` and vice-versa, but `x * y` is elaborated successfully and has type `Matrix Real 5 8`. -/ private inductive Tree where | /-- Leaf of the tree. We store the `infoTrees` generated when elaborating `val`. These trees become subtrees of the infotree nodes generated for `op` nodes. -/ term (ref : Syntax) (infoTrees : Std.PersistentArray InfoTree) (val : Expr) | /-- `ref` is the original syntax that expanded into `binop%`. `macroName` is the `macro_rule` that produce the expansion. We store this information here to make sure "go to definition" behaves similarly to notation defined without using `binop%` helper elaborator. -/ op (ref : Syntax) (macroName : Name) (lazy : Bool) (f : Expr) (lhs rhs : Tree) private partial def toTree (s : Syntax) : TermElabM Tree := do /- Remark: ew used to use `expandMacros` here, but this is a bad idiom because we do not record the macro expansion information in the info tree. We now manually expand the notation in the `go` function, and save the macro declaration names in the `op` nodes. -/ let result ← go s synthesizeSyntheticMVars (mayPostpone := true) return result where go (s : Syntax) := do match s with | `(binop% $f $lhs $rhs) => processOp (lazy := false) s .anonymous f lhs rhs | `(binop_lazy% $f $lhs $rhs) => processOp (lazy := true) s .anonymous f lhs rhs | `(($e)) => if hasCDot e then processLeaf s else go e | _ => match (← liftMacroM <| expandMacroImpl? (← getEnv) s) with | some (macroName, s?) => let s' ← liftMacroM <| liftExcept s? match s' with | `(binop% $f $lhs $rhs) => processOp (lazy := false) s macroName f lhs rhs | `(binop_lazy% $f $lhs $rhs) => processOp (lazy := true) s macroName f lhs rhs | _ => processLeaf s | none => processLeaf s processOp (ref : Syntax) (declName : Name) (f lhs rhs : Syntax) (lazy : Bool) := do let some f ← resolveId? f | throwUnknownConstant f.getId return .op (lazy := lazy) ref declName f (← go lhs) (← go rhs) processLeaf (s : Syntax) := do let e ← elabTerm s none let info ← getResetInfoTrees return .term s info e -- Auxiliary function used at `analyze` private def hasCoe (fromType toType : Expr) : TermElabM Bool := do if (← getEnv).contains ``CoeHTCT then let u ← getLevel fromType let v ← getLevel toType let coeInstType := mkAppN (Lean.mkConst ``CoeHTCT [u, v]) #[fromType, toType] match ← trySynthInstance coeInstType (some (maxCoeSize.get (← getOptions))) with | .some _ => return true | .none => return false | .undef => return false -- TODO: should we do something smarter here? else return false private structure AnalyzeResult where max? : Option Expr := none hasUncomparable : Bool := false -- `true` if there are two types `α` and `β` where we don't have coercions in any direction. private def isUnknow : Expr → Bool | .mvar .. => true | .app f _ => isUnknow f | .letE _ _ _ b _ => isUnknow b | .mdata _ b => isUnknow b | _ => false private def analyze (t : Tree) (expectedType? : Option Expr) : TermElabM AnalyzeResult := do let max? ← match expectedType? with | none => pure none | some expectedType => let expectedType ← instantiateMVars expectedType if isUnknow expectedType then pure none else pure (some expectedType) (go t *> get).run' { max? } where go (t : Tree) : StateRefT AnalyzeResult TermElabM Unit := do unless (← get).hasUncomparable do match t with | .op _ _ _ _ lhs rhs => go lhs; go rhs | .term _ _ val => let type ← instantiateMVars (← inferType val) unless isUnknow type do match (← get).max? with | none => modify fun s => { s with max? := type } | some max => unless (← withNewMCtxDepth <| isDefEqGuarded max type) do if (← hasCoe type max) then return () else if (← hasCoe max type) then modify fun s => { s with max? := type } else trace[Elab.binop] "uncomparable types: {max}, {type}" modify fun s => { s with hasUncomparable := true } private def mkOp (f : Expr) (lhs rhs : Expr) : TermElabM Expr := do elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] (expectedType? := none) (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) private def toExprCore (t : Tree) : TermElabM Expr := do match t with | .term _ trees e => modifyInfoState (fun s => { s with trees := s.trees ++ trees }); return e | .op ref macroName true f lhs rhs => withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo macroName ref) do mkOp f (← toExprCore lhs) (← mkFunUnit (← toExprCore rhs)) | .op ref macroName false f lhs rhs => withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo macroName ref) do mkOp f (← toExprCore lhs) (← toExprCore rhs) /-- Auxiliary function to decide whether we should coerce `f`'s argument to `maxType` or not. - `f` is a binary operator. - `lhs == true` (`lhs == false`) if are trying to coerce the left-argument (right-argument). This function assumes `f` is a heterogeneous operator (e.g., `HAdd.hAdd`, `HMul.hMul`, etc). It returns true IF - `f` is a constant of the form `Cls.op` where `Cls` is a class name, and - `maxType` is of the form `C ...` where `C` is a constant, and - There are more than one default instance. That is, it assumes the class `Cls` for the heterogeneous operator `f`, and always has the monomorphic instance. (e.g., for `HAdd`, we have `instance [Add α] : HAdd α α α`), and - If `lhs == true`, then there is a default instance of the form `Cls _ (C ..) _`, and - If `lhs == false`, then there is a default instance of the form `Cls (C ..) _ _`. The motivation is to support default instances such as ``` @[defaultInstance high] instance [Mul α] : HMul α (Array α) (Array α) where hMul a as := as.map (a * ·) #eval 2 * #[3, 4, 5] ``` If the type of an argument is unknown we should not coerce it to `maxType` because it would prevent the default instance above from being even tried. -/ private def hasHeterogeneousDefaultInstances (f : Expr) (maxType : Expr) (lhs : Bool) : MetaM Bool := do let .const fName .. := f | return false let .const typeName .. := maxType.getAppFn | return false let className := fName.getPrefix let defInstances ← getDefaultInstances className if defInstances.length ≤ 1 then return false for (instName, _) in defInstances do if let .app (.app (.app _heteroClass lhsType) rhsType) _resultType := (← getConstInfo instName).type.getForallBody then if lhs && rhsType.isAppOf typeName then return true if !lhs && lhsType.isAppOf typeName then return true return false /-- Return `true` if polymorphic function `f` has a homogenous instance of `maxType`. The coercions to `maxType` only makes sense if such instance exists. For example, suppose `maxType` is `Int`, and `f` is `HPow.hPow`. Then, adding coercions to `maxType` only make sense if we have an instance `HPow Int Int Int`. -/ private def hasHomogeneousInstance (f : Expr) (maxType : Expr) : MetaM Bool := do let .const fName .. := f | return false let className := fName.getPrefix try let inst ← mkAppM className #[maxType, maxType, maxType] return (← trySynthInstance inst) matches .some _ catch _ => return false mutual /-- Try to coerce elements in the `t` to `maxType` when needed. If the type of an element in `t` is unknown we only coerce it to `maxType` if `maxType` does not have heterogeneous default instances. This extra check is approximated by `hasHeterogeneousDefaultInstances`. Remark: If `maxType` does not implement heterogeneous default instances, we do want to assign unknown types `?m` to `maxType` because it produces better type information propagation. Our test suite has many tests that would break if we don't do this. For example, consider the term ``` eq_of_isEqvAux a b hsz (i+1) (Nat.succ_le_of_lt h) heqv.2 ``` `Nat.succ_le_of_lt h` type depends on `i+1`, but `i+1` only reduces to `Nat.succ i` if we know that `1` is a `Nat`. There are several other examples like that in our test suite, and one can find them by just replacing the `← hasHeterogeneousDefaultInstances f maxType lhs` test with `true` Remark: if `hasHeterogeneousDefaultInstances` implementation is not good enough we should refine it in the future. -/ private partial def applyCoe (t : Tree) (maxType : Expr) (isPred : Bool) : TermElabM Tree := do go t none false isPred where go (t : Tree) (f? : Option Expr) (lhs : Bool) (isPred : Bool) : TermElabM Tree := do match t with | .op ref macroName lazy f lhs rhs => /- We only keep applying coercions to `maxType` if `f` is predicate or `f` has a homogenous instance with `maxType`. See `hasHomogeneousInstance` for additional details. Remark: We assume `binrel%` elaborator is only used with homogenous predicates. -/ if (← pure isPred <||> hasHomogeneousInstance f maxType) then return Tree.op ref macroName lazy f (← go lhs f true false) (← go rhs f false false) else let r ← withRef ref <| withInfoContext' ref (mkInfo := mkTermInfo macroName ref) do mkOp f (← toExpr lhs none) (← toExpr rhs none) let infoTrees ← getResetInfoTrees return .term ref infoTrees r | .term ref trees e => let type ← instantiateMVars (← inferType e) trace[Elab.binop] "visiting {e} : {type} =?= {maxType}" if isUnknow type then if let some f := f? then if (← hasHeterogeneousDefaultInstances f maxType lhs) then -- See comment at `hasHeterogeneousDefaultInstances` return t if (← isDefEqGuarded maxType type) then return t else trace[Elab.binop] "added coercion: {e} : {type} => {maxType}" withRef ref <| return .term ref trees (← mkCoe maxType type e) private partial def toExpr (tree : Tree) (expectedType? : Option Expr) : TermElabM Expr := do let r ← analyze tree expectedType? trace[Elab.binop] "hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}" if r.hasUncomparable || r.max?.isNone then let result ← toExprCore tree ensureHasType expectedType? result else let result ← toExprCore (← applyCoe tree r.max?.get! (isPred := false)) trace[Elab.binop] "result: {result}" ensureHasType expectedType? result end @[builtinTermElab binop] def elabBinOp : TermElab := fun stx expectedType? => do toExpr (← toTree stx) expectedType? @[builtinTermElab binop_lazy] def elabBinOpLazy : TermElab := elabBinOp /-- Elaboration functionf for `binrel%` and `binrel_no_prop%` notations. We use the infrastructure for `binop%` to make sure we propagate information between the left and right hand sides of a binary relation. Recall that the `binrel_no_prop%` notation is used for relations such as `==` which do not support `Prop`, but we still want to be able to write `(5 > 2) == (2 > 1)`. -/ def elabBinRelCore (noProp : Bool) (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← resolveId? stx[1]) with | some f => withSynthesize (mayPostpone := true) do let lhs ← withRef stx[2] <| toTree stx[2] let rhs ← withRef stx[3] <| toTree stx[3] let tree := Tree.op (lazy := false) stx .anonymous f lhs rhs let r ← analyze tree none trace[Elab.binrel] "hasUncomparable: {r.hasUncomparable}, maxType: {r.max?}" if r.hasUncomparable || r.max?.isNone then -- Use default elaboration strategy + `toBoolIfNecessary` let lhs ← toExprCore lhs let rhs ← toExprCore rhs let lhs ← toBoolIfNecessary lhs let rhs ← toBoolIfNecessary rhs let lhsType ← inferType lhs let rhs ← ensureHasType lhsType rhs elabAppArgs f #[] #[Arg.expr lhs, Arg.expr rhs] expectedType? (explicit := false) (ellipsis := false) (resultIsOutParamSupport := false) else let mut maxType := r.max?.get! /- If `noProp == true` and `maxType` is `Prop`, then set `maxType := Bool`. `See toBoolIfNecessary` -/ if noProp then if (← withNewMCtxDepth <| isDefEq maxType (mkSort levelZero)) then maxType := Lean.mkConst ``Bool let result ← toExprCore (← applyCoe tree maxType (isPred := true)) trace[Elab.binrel] "result: {result}" return result | none => throwUnknownConstant stx[1].getId where /-- If `noProp == true` and `e` has type `Prop`, then coerce it to `Bool`. -/ toBoolIfNecessary (e : Expr) : TermElabM Expr := do if noProp then -- We use `withNewMCtxDepth` to make sure metavariables are not assigned if (← withNewMCtxDepth <| isDefEq (← inferType e) (mkSort levelZero)) then return (← ensureHasType (Lean.mkConst ``Bool) e) return e @[builtinTermElab binrel] def elabBinRel : TermElab := elabBinRelCore false @[builtinTermElab binrel_no_prop] def elabBinRelNoProp : TermElab := elabBinRelCore true @[builtinTermElab defaultOrOfNonempty] def elabDefaultOrNonempty : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | none => throwError "invalid 'default_or_ofNonempty%', expected type is not known" | some expectedType => try mkDefault expectedType catch ex => try mkOfNonempty expectedType catch _ => if stx[1].isNone then throw ex else -- It is in the context of an `unsafe` constant. We can use sorry instead. -- Another option is to make a recursive application since it is unsafe. mkSorry expectedType false builtin_initialize registerTraceClass `Elab.binop registerTraceClass `Elab.binrel end BinOp end Lean.Elab.Term
dff9438f71740c92c092e622dc630411c8b8bb8f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Tactic.lean
45026cc2261a1f2fbd5f32fb3ffd91f469f61879
[ "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
771
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Elab.Term import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Induction import Lean.Elab.Tactic.Generalize import Lean.Elab.Tactic.Injection import Lean.Elab.Tactic.Match import Lean.Elab.Tactic.Rewrite import Lean.Elab.Tactic.Location import Lean.Elab.Tactic.Simp import Lean.Elab.Tactic.BuiltinTactic import Lean.Elab.Tactic.Split import Lean.Elab.Tactic.Conv import Lean.Elab.Tactic.Delta import Lean.Elab.Tactic.Meta import Lean.Elab.Tactic.Unfold import Lean.Elab.Tactic.Cache import Lean.Elab.Tactic.Calc import Lean.Elab.Tactic.Congr