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
96ecb08532855d1800fcb4fa52b40e81e0016505
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/group_theory/presented_group.lean
eeaf9f3ee73f75a7044d547506bb37edafafa837
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
2,840
lean
/- Copyright (c) 2019 Michael Howes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Howes Defining a group given by generators and relations -/ import group_theory.free_group group_theory.quotient_group variables {α : Type} /-- Given a set of relations, rels, over a type α, presented_group constructs the group with generators α and relations rels as a quotient of free_group α.-/ def presented_group (rels : set (free_group α)) : Type := quotient_group.quotient $ group.normal_closure rels namespace presented_group instance (rels : set (free_group α)) : group (presented_group (rels)) := quotient_group.group _ /-- `of x` is the canonical map from α to a presented group with generators α. The term x is mapped to the equivalence class of the image of x in free_group α. -/ def of {rels : set (free_group α)} (x : α) : presented_group rels := quotient_group.mk (free_group.of x) section to_group /- Presented groups satisfy a universal property. If β is a group and f : α → β is a map such that the images of f satisfy all the given relations, then f extends uniquely to a group homomorphism from presented_group rels to β -/ variables {β : Type} [group β] {f : α → β} {rels : set (free_group α)} local notation `F` := free_group.to_group f variable (h : ∀ r ∈ rels, F r = 1) lemma closure_rels_subset_ker : group.normal_closure rels ⊆ is_group_hom.ker F := group.normal_closure_subset (λ x w, (is_group_hom.mem_ker F).2 (h x w)) lemma to_group_eq_one_of_mem_closure : ∀ x ∈ group.normal_closure rels, F x = 1 := λ x w, (is_group_hom.mem_ker F).1 ((closure_rels_subset_ker h) w) /-- The extension of a map f : α → β that satisfies the given relations to a group homomorphism from presented_group rels → β. -/ def to_group : presented_group rels → β := quotient_group.lift (group.normal_closure rels) F (to_group_eq_one_of_mem_closure h) instance to_group.is_group_hom : is_group_hom (to_group h) := quotient_group.is_group_hom_quotient_lift _ _ _ @[simp] lemma to_group.of {x : α} : to_group h (of x) = f x := free_group.to_group.of @[simp] lemma to_group.mul {x y} : to_group h (x * y) = to_group h x * to_group h y := is_mul_hom.map_mul _ _ _ @[simp] lemma to_group.one : to_group h 1 = 1 := is_group_hom.map_one _ @[simp] lemma to_group.inv {x}: to_group h x⁻¹ = (to_group h x)⁻¹ := is_group_hom.map_inv _ _ theorem to_group.unique (g : presented_group rels → β) [is_group_hom g] (hg : ∀ x : α, g (of x) = f x) : ∀ {x}, g x = to_group h x := have is_group_hom (λ x, g (quotient_group.mk x)) := is_group_hom.comp _ _, by exactI λ x, quotient_group.induction_on x (λ _, free_group.to_group.unique (λ (x : free_group α), g (quotient_group.mk x)) hg) end to_group end presented_group
a6ce61c736274330ae5af8ea8ee7c943bc0d6806
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/local_ref_bugs.lean
613504d744e8189545054243ca2815b07a1c204f
[ "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
710
lean
set_option pp.all true section parameter α : Type inductive foo : Type | a : α → foo | b #check (foo.b : foo) open foo #check (foo.b : foo) #check (b : foo) open tactic include α example : true := by do e ← to_expr ```(b), t ← infer_type e, trace "-------", trace e, trace t, trace "-------", triv def ex : foo := begin trace_state, exact b end end namespace bla section parameter α : Type inductive foo : Type | a : α → foo | b #check (foo.b : foo) open foo #check (foo.b : foo) #check (b : foo) end end bla namespace boo section parameter α : Type inductive foo : Type | a : α → foo | b #check (foo.b : foo) open foo (b) #check (foo.b : foo) #check (b : foo) end end boo
2097c0188d89cd2a6917a4eacb3d526a8876a9a4
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/linear_algebra/tensor_product.lean
9f31518e6ec3131e0efcbb4fdf692b14457a82ff
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
14,957
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro Tensor product of modules over commutative rings. -/ import group_theory.free_abelian_group import linear_algebra.direct_sum_module variables {R : Type*} [comm_ring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q] variables [module R M] [module R N] [module R P] [module R Q] include R set_option class.instance_max_depth 100 namespace linear_map def mk₂ (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ c m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ c m n, f m (c • n) = c • f m n) : M →ₗ N →ₗ P := ⟨λ m, ⟨f m, H3 m, λ c, H4 c m⟩, λ m₁ m₂, linear_map.ext $ H1 m₁ m₂, λ c m, linear_map.ext $ H2 c m⟩ @[simp] theorem mk₂_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂ f H1 H2 H3 H4 : M →ₗ N →ₗ P) m n = f m n := rfl variables (f : M →ₗ N →ₗ P) theorem ext₂ {f g : M →ₗ N →ₗ P} (H : ∀ m n, f m n = g m n) : f = g := linear_map.ext (λ m, linear_map.ext $ λ n, H m n) def flip : N →ₗ M →ₗ P := mk₂ (λ n m, f m n) (λ n₁ n₂ m, (f m).map_add _ _) (λ c n m, (f m).map_smul _ _) (λ n m₁ m₂, by rw f.map_add; refl) (λ c n m, by rw f.map_smul; refl) @[simp] theorem flip_apply (m : M) (n : N) : flip f n m = f m n := rfl theorem flip_inj {f g : M →ₗ N →ₗ P} (H : flip f = flip g) : f = g := ext₂ $ λ m n, show flip f n m = flip g n m, by rw H variables (R M N P) def lflip : (M →ₗ N →ₗ P) →ₗ N →ₗ M →ₗ P := ⟨flip, λ _ _, rfl, λ _ _, rfl⟩ variables {R M N P} @[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl theorem map_zero₂ (y) : f 0 y = 0 := (flip f y).map_zero theorem map_neg₂ (x y) : f (-x) y = -f x y := (flip f y).map_neg _ theorem map_add₂ (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _ theorem map_smul₂ (r x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _ variables (P) def lcomp (f : M →ₗ N) : (N →ₗ P) →ₗ M →ₗ P := flip $ (flip id).comp f variables {P} @[simp] theorem lcomp_apply (f : M →ₗ N) (g : N →ₗ P) (x : M) : lcomp P f g x = g (f x) := rfl variables (M N P) def llcomp : (N →ₗ P) →ₗ (M →ₗ N) →ₗ M →ₗ P := flip ⟨lcomp P, λ f f', ext₂ $ λ g x, g.map_add _ _, λ c f, ext₂ $ λ g x, g.map_smul _ _⟩ variables {M N P} section @[simp] theorem llcomp_apply (f : N →ₗ P) (g : M →ₗ N) (x : M) : llcomp M N P f g x = f (g x) := rfl end def compl₂ (g : Q →ₗ N) : M →ₗ Q →ₗ P := (lcomp _ g).comp f @[simp] theorem compl₂_apply (g : Q →ₗ N) (m : M) (q : Q) : f.compl₂ g m q = f m (g q) := rfl def compr₂ (g : P →ₗ Q) : M →ₗ N →ₗ Q := linear_map.comp (llcomp N P Q g) f @[simp] theorem compr₂_apply (g : P →ₗ Q) (m : M) (n : N) : f.compr₂ g m n = g (f m n) := rfl variables (R M) def lsmul : R →ₗ M →ₗ M := mk₂ (•) add_smul (λ _ _ _, eq.symm $ smul_smul _ _ _) smul_add (λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm]) variables {R M} @[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl end linear_map variables (M N) namespace tensor_product section open free_abelian_group def relators : set (free_abelian_group (M × N)) := add_group.closure { x : free_abelian_group (M × N) | (∃ (m₁ m₂ : M) (n : N), x = of (m₁, n) + of (m₂, n) - of (m₁ + m₂, n)) ∨ (∃ (m : M) (n₁ n₂ : N), x = of (m, n₁) + of (m, n₂) - of (m, n₁ + n₂)) ∨ (∃ (r : R) (m : M) (n : N), x = of (r • m, n) - of (m, r • n)) } end namespace relators instance : normal_add_subgroup (relators M N) := by unfold relators; apply normal_add_subgroup_of_add_comm_group end relators end tensor_product def tensor_product : Type* := quotient_add_group.quotient (tensor_product.relators M N) local infix ` ⊗ `:100 := tensor_product namespace tensor_product section module local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup instance : add_comm_group (M ⊗ N) := quotient_add_group.add_comm_group _ instance quotient.mk.is_add_group_hom : is_add_group_hom (quotient.mk : free_abelian_group (M × N) → M ⊗ N) := quotient_add_group.is_add_group_hom _ variables {M N} def tmul (m : M) (n : N) : M ⊗ N := quotient_add_group.mk $ free_abelian_group.of (m, n) infix ` ⊗ₜ `:100 := tmul lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ n := eq.symm $ sub_eq_zero.1 $ eq.symm $ quotient.sound $ group.in_closure.basic $ or.inl $ ⟨m₁, m₂, n, rfl⟩ lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ n₂ := eq.symm $ sub_eq_zero.1 $ eq.symm $ quotient.sound $ group.in_closure.basic $ or.inr $ or.inl $ ⟨m, n₁, n₂, rfl⟩ lemma smul_tmul (r : R) (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ (r • n) := sub_eq_zero.1 $ eq.symm $ quotient.sound $ group.in_closure.basic $ or.inr $ or.inr $ ⟨r, m, n, rfl⟩ local attribute [instance] quotient_add_group.is_add_group_hom_quotient_lift def smul.aux (r : R) : free_abelian_group (M × N) → M ⊗ N := free_abelian_group.lift (λ (y : M × N), (r • y.1) ⊗ₜ y.2) instance (r : R) : is_add_group_hom (smul.aux r : _ → M ⊗ N) := by unfold smul.aux; apply_instance instance : has_scalar R (M ⊗ N) := ⟨λ r, quotient_add_group.lift _ (smul.aux r) $ λ x hx, begin refine (is_add_group_hom.mem_ker (smul.aux r : _ → M ⊗ N)).1 (add_group.closure_subset _ hx), clear hx x, rintro x (⟨m₁, m₂, n, rfl⟩ | ⟨m, n₁, n₂, rfl⟩ | ⟨q, m, n, rfl⟩); simp only [smul.aux, is_add_group_hom.mem_ker, -sub_eq_add_neg, sub_self, add_tmul, tmul_add, smul_tmul, smul_add, smul_smul, mul_comm, free_abelian_group.lift.of, free_abelian_group.lift.add, free_abelian_group.lift.sub] end⟩ instance smul.is_add_group_hom (r : R) : is_add_group_hom ((•) r : M ⊗ N → M ⊗ N) := by unfold has_scalar.smul; apply_instance protected theorem smul_add (r : R) (x y : M ⊗ N) : r • (x + y) = r • x + r • y := is_add_group_hom.add _ _ _ instance : module R (M ⊗ N) := module.of_core { smul := (•), smul_add := tensor_product.smul_add, add_smul := begin intros r s x, apply quotient_add_group.induction_on' x, intro z, symmetry, refine @free_abelian_group.lift.unique _ _ _ _ _ ⟨λ p q, _⟩ _ z, { simp [tensor_product.smul_add] }, rintro ⟨m, n⟩, change (r • m) ⊗ₜ n + (s • m) ⊗ₜ n = ((r + s) • m) ⊗ₜ n, rw [add_smul, add_tmul] end, mul_smul := begin intros r s x, apply quotient_add_group.induction_on' x, intro z, symmetry, refine @free_abelian_group.lift.unique _ _ _ _ _ ⟨λ p q, _⟩ _ z, { simp [tensor_product.smul_add] }, rintro ⟨m, n⟩, change r • s • (m ⊗ₜ n) = ((r * s) • m) ⊗ₜ n, rw mul_smul, refl end, one_smul := λ x, quotient.induction_on x $ λ _, eq.symm $ free_abelian_group.lift.unique _ _ $ λ ⟨p, q⟩, by rw one_smul; refl } @[simp] lemma tmul_smul (r : R) (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ y) := (smul_tmul _ _ _).symm variables (R M N) def mk : M →ₗ N →ₗ M ⊗ N := linear_map.mk₂ (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul variables {R M N} @[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl lemma zero_tmul (n : N) : (0 ⊗ₜ n : M ⊗ N) = 0 := (mk R M N).map_zero₂ _ lemma tmul_zero (m : M) : (m ⊗ₜ 0 : M ⊗ N) = 0 := (mk R M N _).map_zero lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ n) := (mk R M N).map_neg₂ _ _ lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ n) := (mk R M N _).map_neg _ end module local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup @[elab_as_eliminator] protected theorem induction_on {C : M ⊗ N → Prop} (z : M ⊗ N) (C0 : C 0) (C1 : ∀ x y, C $ x ⊗ₜ y) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := quotient.induction_on z $ λ x, free_abelian_group.induction_on x C0 (λ ⟨p, q⟩, C1 p q) (λ ⟨p, q⟩ _, show C (-(p ⊗ₜ q)), by rw ← neg_tmul; from C1 (-p) q) (λ _ _, Cp _ _) section UMP variables {M N P Q} variables (f : M →ₗ N →ₗ P) local attribute [instance] free_abelian_group.lift.is_add_group_hom def lift_aux : M ⊗ N → P := quotient_add_group.lift _ (free_abelian_group.lift $ λ z, f z.1 z.2) $ λ x hx, begin refine (is_add_group_hom.mem_ker _).1 (add_group.closure_subset _ hx), clear hx x, rintro x (⟨m₁, m₂, n, rfl⟩ | ⟨m, n₁, n₂, rfl⟩ | ⟨q, m, n, rfl⟩); simp [is_add_group_hom.mem_ker, -sub_eq_add_neg, f.map_add, f.map_add₂, f.map_smul, f.map_smul₂, sub_self], end variable {f} local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup @[simp] lemma lift_aux.add (x y) : lift_aux f (x + y) = lift_aux f x + lift_aux f y := quotient.induction_on₂ x y $ λ m n, free_abelian_group.lift.add _ _ _ @[simp] lemma lift_aux.smul (r x) : lift_aux f (r • x) = r • lift_aux f x := tensor_product.induction_on _ _ x (smul_zero _).symm (λ p q, by rw [← tmul_smul]; simp [lift_aux, tmul]) (λ p q ih1 ih2, by simp [@smul_add _ _ _ _ _ _ p _, lift_aux.add, ih1, ih2, smul_add]) variable (f) def lift : M ⊗ N →ₗ P := { to_fun := lift_aux f, add := lift_aux.add, smul := lift_aux.smul } variable {f} @[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := zero_add _ @[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := lift.tmul _ _ theorem lift.unique {g : linear_map (M ⊗ N) P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := linear_map.ext $ λ z, begin apply quotient_add_group.induction_on' z, intro z, refine @free_abelian_group.lift.unique _ _ _ _ _ ⟨λ p q, _⟩ _ z, { simp [g.2] }, exact λ ⟨m, n⟩, H m n end theorem lift_mk : lift (mk R M N) = linear_map.id := eq.symm $ lift.unique $ λ x y, rfl theorem lift_compr₂ (g : P →ₗ Q) : lift (f.compr₂ g) = g.comp (lift f) := eq.symm $ lift.unique $ λ x y, by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂, lift_mk, linear_map.comp_id] theorem ext {g h : M ⊗ N →ₗ P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := by rw ← lift_mk_compr₂ h; exact lift.unique H theorem mk_compr₂_inj {g h : M ⊗ N →ₗ P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] example : M → N → (M → N → P) → P := λ m, flip $ λ f, f m variables (M N P) def uncurry : (M →ₗ N →ₗ P) →ₗ M ⊗ N →ₗ P := linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp linear_map.id.flip variables {M N P} @[simp] theorem uncurry_apply (f : M →ₗ N →ₗ P) (m : M) (n : N) : uncurry M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl variables (M N P) def lift.equiv : (M →ₗ N →ₗ P) ≃ₗ (M ⊗ N →ₗ P) := { inv_fun := λ f, (mk R M N).compr₂ f, left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _, right_inv := λ f, ext $ λ m n, lift.tmul _ _, .. uncurry M N P } def lcurry : (M ⊗ N →ₗ P) →ₗ M →ₗ N →ₗ P := (lift.equiv M N P).symm variables {M N P} @[simp] theorem lcurry_apply (f : M ⊗ N →ₗ P) (m : M) (n : N) : lcurry M N P f m n = f (m ⊗ₜ n) := rfl def curry (f : M ⊗ N →ₗ P) : M →ₗ N →ₗ P := lcurry M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl end UMP variables {M N} protected def lid : R ⊗ M ≃ₗ M := linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1) (linear_map.ext $ λ _, by simp) (ext $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one]) protected def comm : M ⊗ N ≃ₗ N ⊗ M := linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext $ λ m n, rfl) (ext $ λ m n, rfl) open linear_map protected def assoc : (M ⊗ N) ⊗ P ≃ₗ M ⊗ (N ⊗ P) := begin refine linear_equiv.of_linear (lift $ lift $ comp (lcurry _ _ _) $ mk _ _ _) (lift $ comp (uncurry _ _ _) $ curry $ mk _ _ _) (mk_compr₂_inj $ linear_map.ext $ λ m, ext $ λ n p, _) (mk_compr₂_inj $ flip_inj $ linear_map.ext $ λ p, ext $ λ m n, _); repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|> rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|> rw uncurry_apply <|> rw curry_apply <|> rw id_apply } end def map (f : M →ₗ P) (g : N →ₗ Q) : M ⊗ N →ₗ P ⊗ Q := lift $ comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ P) (g : N →ₗ Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl def congr (f : M ≃ₗ P) (g : N ≃ₗ Q) : M ⊗ N ≃ₗ P ⊗ Q := linear_equiv.of_linear (map f g) (map f.symm g.symm) (ext $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply]) (ext $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply]) variables (ι₁ : Type*) (ι₂ : Type*) variables [decidable_eq ι₁] [decidable_eq ι₂] variables (β₁ : ι₁ → Type*) (β₂ : ι₂ → Type*) variables [Π i₁, add_comm_group (β₁ i₁)] [Π i₂, add_comm_group (β₂ i₂)] variables [Π i₁, module R (β₁ i₁)] [Π i₂, module R (β₂ i₂)] def direct_sum : direct_sum R ι₁ β₁ ⊗ direct_sum R ι₂ β₂ ≃ₗ direct_sum R (ι₁ × ι₂) (λ i, β₁ i.1 ⊗ β₂ i.2) := begin refine linear_equiv.of_linear (lift $ direct_sum.to_module $ λ i₁, flip $ direct_sum.to_module $ λ i₂, flip $ curry $ direct_sum.of (λ i : ι₁ × ι₂, β₁ i.1 ⊗ β₂ i.2) (i₁, i₂)) (direct_sum.to_module $ λ i, map (direct_sum.of _ _) (direct_sum.of _ _)) (linear_map.ext $ direct_sum.to_module.ext $ λ i, mk_compr₂_inj $ linear_map.ext $ λ x₁, linear_map.ext $ λ x₂, _) (mk_compr₂_inj $ linear_map.ext $ direct_sum.to_module.ext $ λ i₁, linear_map.ext $ λ x₁, linear_map.ext $ direct_sum.to_module.ext $ λ i₂, linear_map.ext $ λ x₂, _); repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|> rw direct_sum.to_module.of <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|> rw curry_apply }, cases i; refl end end tensor_product
007c1f1b3947d4fef74d3aabd354b6a5dc69fc16
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/const.lean
78a6411ac0cdc0e776e69143ef7b5af4ce0537e2
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
2,814
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.opposites universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation open category_theory namespace category_theory.functor variables (J : Type u₁) [category.{v₁} J] variables {C : Type u₂} [category.{v₂} C] /-- The functor sending `X : C` to the constant functor `J ⥤ C` sending everything to `X`. -/ def const : C ⥤ (J ⥤ C) := { obj := λ X, { obj := λ j, X, map := λ j j' f, 𝟙 X }, map := λ X Y f, { app := λ j, f } } namespace const open opposite variables {J} @[simp] lemma obj_obj (X : C) (j : J) : ((const J).obj X).obj j = X := rfl @[simp] lemma obj_map (X : C) {j j' : J} (f : j ⟶ j') : ((const J).obj X).map f = 𝟙 X := rfl @[simp] lemma map_app {X Y : C} (f : X ⟶ Y) (j : J) : ((const J).map f).app j = f := rfl /-- The contant functor `Jᵒᵖ ⥤ Cᵒᵖ` sending everything to `op X` is (naturally isomorphic to) the opposite of the constant functor `J ⥤ C` sending everything to `X`. -/ def op_obj_op (X : C) : (const Jᵒᵖ).obj (op X) ≅ ((const J).obj X).op := { hom := { app := λ j, 𝟙 _ }, inv := { app := λ j, 𝟙 _ } } @[simp] lemma op_obj_op_hom_app (X : C) (j : Jᵒᵖ) : (op_obj_op X).hom.app j = 𝟙 _ := rfl @[simp] lemma op_obj_op_inv_app (X : C) (j : Jᵒᵖ) : (op_obj_op X).inv.app j = 𝟙 _ := rfl /-- The contant functor `Jᵒᵖ ⥤ C` sending everything to `unop X` is (naturally isomorphic to) the opposite of the constant functor `J ⥤ Cᵒᵖ` sending everything to `X`. -/ def op_obj_unop (X : Cᵒᵖ) : (const Jᵒᵖ).obj (unop X) ≅ ((const J).obj X).left_op := { hom := { app := λ j, 𝟙 _ }, inv := { app := λ j, 𝟙 _ } } -- Lean needs some help with universes here. @[simp] lemma op_obj_unop_hom_app (X : Cᵒᵖ) (j : Jᵒᵖ) : (op_obj_unop.{v₁ v₂} X).hom.app j = 𝟙 _ := rfl @[simp] lemma op_obj_unop_inv_app (X : Cᵒᵖ) (j : Jᵒᵖ) : (op_obj_unop.{v₁ v₂} X).inv.app j = 𝟙 _ := rfl @[simp] lemma unop_functor_op_obj_map (X : Cᵒᵖ) {j₁ j₂ : J} (f : j₁ ⟶ j₂) : (unop ((functor.op (const J)).obj X)).map f = 𝟙 (unop X) := rfl end const section variables {D : Type u₃} [category.{v₃} D] /-- These are actually equal, of course, but not definitionally equal (the equality requires F.map (𝟙 _) = 𝟙 _). A natural isomorphism is more convenient than an equality between functors (compare id_to_iso). -/ @[simps] def const_comp (X : C) (F : C ⥤ D) : (const J).obj X ⋙ F ≅ (const J).obj (F.obj X) := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } } end end category_theory.functor
daec594cddd9e82536e39f7b00abaf9ed095ad80
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/error_pos.lean
ef4706d2e32b2fd38aae2ddfa6e1c6c55450b56e
[ "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
491
lean
example (A : Type) (B : A → Type) (b : B) : true := trivial example : ∀ (A : Type) (B : A → Type) (b : B), true := begin intros, trivial end #check λ (A : Type) (B : A → Type) (b : B), true #check λ (A : Type) (B : A → Type), B → true #check λ (A : Type) (B : A → Type) b, (b : B) example {A : Type} {B : Type} {a₁ a₂ : B} {b₁ b₂ : A → B} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : A := a₁ in b₁ x) = (let x : A := a₂ in b₂ x) := sorry
e2b1cb1d4f6a223fd8a509ec8528b0b78bded12b
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/matrix/notation.lean
32585fcf769c580533455582e464088f16be1966
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,732
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.fintype.card import data.matrix.basic import tactic.fin_cases /-! # Matrix and vector notation This file defines notation for vectors and matrices. Given `a b c d : α`, the notation allows us to write `![a, b, c, d] : fin 4 → α`. Nesting vectors gives a matrix, so `![![a, b], ![c, d]] : matrix (fin 2) (fin 2) α`. This file includes `simp` lemmas for applying operations in `data.matrix.basic` to values built out of this notation. ## Main definitions * `vec_empty` is the empty vector (or `0` by `n` matrix) `![]` * `vec_cons` prepends an entry to a vector, so `![a, b]` is `vec_cons a (vec_cons b vec_empty)` ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations The main new notation is `![a, b]`, which gets expanded to `vec_cons a (vec_cons b vec_empty)`. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace matrix universe u variables {α : Type u} open_locale matrix section matrix_notation /-- `![]` is the vector with no entries. -/ def vec_empty : fin 0 → α := fin_zero_elim /-- `vec_cons h t` prepends an entry `h` to a vector `t`. The inverse functions are `vec_head` and `vec_tail`. The notation `![a, b, ...]` expands to `vec_cons a (vec_cons b ...)`. -/ def vec_cons {n : ℕ} (h : α) (t : fin n → α) : fin n.succ → α := fin.cons h t notation `![` l:(foldr `, ` (h t, vec_cons h t) vec_empty `]`) := l /-- `vec_head v` gives the first entry of the vector `v` -/ def vec_head {n : ℕ} (v : fin n.succ → α) : α := v 0 /-- `vec_tail v` gives a vector consisting of all entries of `v` except the first -/ def vec_tail {n : ℕ} (v : fin n.succ → α) : fin n → α := v ∘ fin.succ variables {m n : ℕ} /-- Use `![...]` notation for displaying a vector `fin n → α`, for example: ``` #eval ![1, 2] + ![3, 4] -- ![4, 6] ``` -/ instance [has_repr α] : has_repr (fin n → α) := { repr := λ f, "![" ++ (string.intercalate ", " ((list.fin_range n).map (λ n, repr (f n)))) ++ "]" } /-- Use `![...]` notation for displaying a `fin`-indexed matrix, for example: ``` #eval ![![1, 2], ![3, 4]] + ![![3, 4], ![5, 6]] -- ![![4, 6], ![8, 10]] ``` -/ instance [has_repr α] : has_repr (matrix (fin m) (fin n) α) := (by apply_instance : has_repr (fin m → fin n → α)) end matrix_notation variables {m n o : ℕ} {m' n' o' : Type*} lemma empty_eq (v : fin 0 → α) : v = ![] := by { ext i, fin_cases i } section val @[simp] lemma head_fin_const (a : α) : vec_head (λ (i : fin (n + 1)), a) = a := rfl @[simp] lemma cons_val_zero (x : α) (u : fin m → α) : vec_cons x u 0 = x := rfl lemma cons_val_zero' (h : 0 < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨0, h⟩ = x := rfl @[simp] lemma cons_val_succ (x : α) (u : fin m → α) (i : fin m) : vec_cons x u i.succ = u i := by simp [vec_cons] @[simp] lemma cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨i.succ, h⟩ = u ⟨i, nat.lt_of_succ_lt_succ h⟩ := by simp only [vec_cons, fin.cons, fin.cases_succ'] @[simp] lemma head_cons (x : α) (u : fin m → α) : vec_head (vec_cons x u) = x := rfl @[simp] lemma tail_cons (x : α) (u : fin m → α) : vec_tail (vec_cons x u) = u := by { ext, simp [vec_tail] } @[simp] lemma empty_val' {n' : Type*} (j : n') : (λ i, (![] : fin 0 → n' → α) i j) = ![] := empty_eq _ @[simp] lemma cons_val' (v : n' → α) (B : matrix (fin m) n' α) (i j) : vec_cons v B i j = vec_cons (v j) (λ i, B i j) i := by { refine fin.cases _ _ i; simp } @[simp] lemma head_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_head (λ i, B i j) = vec_head B j := rfl @[simp] lemma tail_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_tail (λ i, B i j) = λ i, vec_tail B i j := by { ext, simp [vec_tail] } @[simp] lemma cons_head_tail (u : fin m.succ → α) : vec_cons (vec_head u) (vec_tail u) = u := fin.cons_self_tail _ @[simp] lemma range_cons (x : α) (u : fin n → α) : set.range (vec_cons x u) = {x} ∪ set.range u := set.ext $ λ y, by simp [fin.exists_fin_succ, eq_comm] @[simp] lemma range_empty (u : fin 0 → α) : set.range u = ∅ := set.range_eq_empty _ @[simp] lemma vec_cons_const (a : α) : vec_cons a (λ k : fin n, a) = λ _, a := funext $ fin.forall_fin_succ.2 ⟨rfl, cons_val_succ _ _⟩ lemma vec_single_eq_const (a : α) : ![a] = λ _, a := funext $ unique.forall_iff.2 rfl /-- `![a, b, ...] 1` is equal to `b`. The simplifier needs a special lemma for length `≥ 2`, in addition to `cons_val_succ`, because `1 : fin 1 = 0 : fin 1`. -/ @[simp] lemma cons_val_one (x : α) (u : fin m.succ → α) : vec_cons x u 1 = vec_head u := by { rw [← fin.succ_zero_eq_one, cons_val_succ], refl } @[simp] lemma cons_val_fin_one (x : α) (u : fin 0 → α) (i : fin 1) : vec_cons x u i = x := by { fin_cases i, refl } lemma cons_fin_one (x : α) (u : fin 0 → α) : vec_cons x u = (λ _, x) := funext (cons_val_fin_one x u) /-! ### Numeral (`bit0` and `bit1`) indices The following definitions and `simp` lemmas are to allow any numeral-indexed element of a vector given with matrix notation to be extracted by `simp` (even when the numeral is larger than the number of elements in the vector, which is taken modulo that number of elements by virtue of the semantics of `bit0` and `bit1` and of addition on `fin n`). -/ @[simp] lemma empty_append (v : fin n → α) : fin.append (zero_add _).symm ![] v = v := by { ext, simp [fin.append] } @[simp] lemma cons_append (ho : o + 1 = m + 1 + n) (x : α) (u : fin m → α) (v : fin n → α) : fin.append ho (vec_cons x u) v = vec_cons x (fin.append (by rwa [add_assoc, add_comm 1, ←add_assoc, add_right_cancel_iff] at ho) u v) := begin ext i, simp_rw [fin.append], split_ifs with h, { rcases i with ⟨⟨⟩ | i, hi⟩, { simp }, { simp only [nat.succ_eq_add_one, add_lt_add_iff_right, fin.coe_mk] at h, simp [h] } }, { rcases i with ⟨⟨⟩ | i, hi⟩, { simpa using h }, { rw [not_lt, fin.coe_mk, nat.succ_eq_add_one, add_le_add_iff_right] at h, simp [h] } } end /-- `vec_alt0 v` gives a vector with half the length of `v`, with only alternate elements (even-numbered). -/ def vec_alt0 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k, hm.symm ▸ add_lt_add k.property k.property⟩ /-- `vec_alt1 v` gives a vector with half the length of `v`, with only alternate elements (odd-numbered). -/ def vec_alt1 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k + 1, hm.symm ▸ nat.add_succ_lt_add k.property k.property⟩ lemma vec_alt0_append (v : fin n → α) : vec_alt0 rfl (fin.append rfl v v) = v ∘ bit0 := begin ext i, simp_rw [function.comp, bit0, vec_alt0, fin.append], split_ifs with h; congr, { rw fin.coe_mk at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], exact (nat.mod_eq_of_lt h).symm }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw sub_lt_iff_left h, exact add_lt_add i.property i.property } end lemma vec_alt1_append (v : fin (n + 1) → α) : vec_alt1 rfl (fin.append rfl v v) = v ∘ bit1 := begin ext i, simp_rw [function.comp, vec_alt1, fin.append], cases n, { simp, congr }, { split_ifs with h; simp_rw [bit1, bit0]; congr, { simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], rw fin.coe_mk at h, rw fin.coe_one, rw nat.mod_eq_of_lt (nat.lt_of_succ_lt h), rw nat.mod_eq_of_lt h }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_add_mod, fin.coe_one, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw sub_lt_iff_left h, exact nat.add_succ_lt_add i.property i.property } } end @[simp] lemma vec_head_vec_alt0 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt0 hm v) = v 0 := rfl @[simp] lemma vec_head_vec_alt1 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt1 hm v) = v 1 := by simp [vec_head, vec_alt1] @[simp] lemma cons_vec_bit0_eq_alt0 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit0 i) = vec_alt0 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt0_append @[simp] lemma cons_vec_bit1_eq_alt1 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit1 i) = vec_alt1 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt1_append @[simp] lemma cons_vec_alt0 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt0 h (vec_cons x (vec_cons y u)) = vec_cons x (vec_alt0 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt0], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt0, nat.add_succ, nat.succ_add] } end -- Although proved by simp, extracting element 8 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt0 (α) {h} : vec_alt0 h (![] : fin 0 → α) = ![] := by simp @[simp] lemma cons_vec_alt1 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt1 h (vec_cons x (vec_cons y u)) = vec_cons y (vec_alt1 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt1], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt1, nat.add_succ, nat.succ_add] } end -- Although proved by simp, extracting element 9 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt1 (α) {h} : vec_alt1 h (![] : fin 0 → α) = ![] := by simp end val section dot_product variables [add_comm_monoid α] [has_mul α] @[simp] lemma dot_product_empty (v w : fin 0 → α) : dot_product v w = 0 := finset.sum_empty @[simp] lemma cons_dot_product (x : α) (v : fin n → α) (w : fin n.succ → α) : dot_product (vec_cons x v) w = x * vec_head w + dot_product v (vec_tail w) := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] @[simp] lemma dot_product_cons (v : fin n.succ → α) (x : α) (w : fin n → α) : dot_product v (vec_cons x w) = vec_head v * x + dot_product (vec_tail v) w := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] end dot_product section col_row @[simp] lemma col_empty (v : fin 0 → α) : col v = vec_empty := empty_eq _ @[simp] lemma col_cons (x : α) (u : fin m → α) : col (vec_cons x u) = vec_cons (λ _, x) (col u) := by { ext i j, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma row_empty : row (vec_empty : fin 0 → α) = λ _, vec_empty := by { ext, refl } @[simp] lemma row_cons (x : α) (u : fin m → α) : row (vec_cons x u) = λ _, vec_cons x u := by { ext, refl } end col_row section transpose @[simp] lemma transpose_empty_rows (A : matrix m' (fin 0) α) : Aᵀ = ![] := empty_eq _ @[simp] lemma transpose_empty_cols : (![] : matrix (fin 0) m' α)ᵀ = λ i, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_transpose (v : n' → α) (A : matrix (fin m) n' α) : (vec_cons v A)ᵀ = λ i, vec_cons (v i) (Aᵀ i) := by { ext i j, refine fin.cases _ _ j; simp } @[simp] lemma head_transpose (A : matrix m' (fin n.succ) α) : vec_head (Aᵀ) = vec_head ∘ A := rfl @[simp] lemma tail_transpose (A : matrix m' (fin n.succ) α) : vec_tail (Aᵀ) = (vec_tail ∘ A)ᵀ := by { ext i j, refl } end transpose section mul variables [semiring α] @[simp] lemma empty_mul [fintype n'] (A : matrix (fin 0) n' α) (B : matrix n' o' α) : A ⬝ B = ![] := empty_eq _ @[simp] lemma empty_mul_empty (A : matrix m' (fin 0) α) (B : matrix (fin 0) o' α) : A ⬝ B = 0 := rfl @[simp] lemma mul_empty [fintype n'] (A : matrix m' n' α) (B : matrix n' (fin 0) α) : A ⬝ B = λ _, ![] := funext (λ _, empty_eq _) lemma mul_val_succ [fintype n'] (A : matrix (fin m.succ) n' α) (B : matrix n' o' α) (i : fin m) (j : o') : (A ⬝ B) i.succ j = (vec_tail A ⬝ B) i j := rfl @[simp] lemma cons_mul [fintype n'] (v : n' → α) (A : matrix (fin m) n' α) (B : matrix n' o' α) : vec_cons v A ⬝ B = vec_cons (vec_mul v B) (A ⬝ B) := by { ext i j, refine fin.cases _ _ i, { refl }, simp [mul_val_succ] } end mul section vec_mul variables [semiring α] @[simp] lemma empty_vec_mul (v : fin 0 → α) (B : matrix (fin 0) o' α) : vec_mul v B = 0 := rfl @[simp] lemma vec_mul_empty [fintype n'] (v : n' → α) (B : matrix n' (fin 0) α) : vec_mul v B = ![] := empty_eq _ @[simp] lemma cons_vec_mul (x : α) (v : fin n → α) (B : matrix (fin n.succ) o' α) : vec_mul (vec_cons x v) B = x • (vec_head B) + vec_mul v (vec_tail B) := by { ext i, simp [vec_mul] } @[simp] lemma vec_mul_cons (v : fin n.succ → α) (w : o' → α) (B : matrix (fin n) o' α) : vec_mul v (vec_cons w B) = vec_head v • w + vec_mul (vec_tail v) B := by { ext i, simp [vec_mul] } end vec_mul section mul_vec variables [semiring α] @[simp] lemma empty_mul_vec [fintype n'] (A : matrix (fin 0) n' α) (v : n' → α) : mul_vec A v = ![] := empty_eq _ @[simp] lemma mul_vec_empty (A : matrix m' (fin 0) α) (v : fin 0 → α) : mul_vec A v = 0 := rfl @[simp] lemma cons_mul_vec [fintype n'] (v : n' → α) (A : fin m → n' → α) (w : n' → α) : mul_vec (vec_cons v A) w = vec_cons (dot_product v w) (mul_vec A w) := by { ext i, refine fin.cases _ _ i; simp [mul_vec] } @[simp] lemma mul_vec_cons {α} [comm_semiring α] (A : m' → (fin n.succ) → α) (x : α) (v : fin n → α) : mul_vec A (vec_cons x v) = (x • vec_head ∘ A) + mul_vec (vec_tail ∘ A) v := by { ext i, simp [mul_vec, mul_comm] } end mul_vec section vec_mul_vec variables [semiring α] @[simp] lemma empty_vec_mul_vec (v : fin 0 → α) (w : n' → α) : vec_mul_vec v w = ![] := empty_eq _ @[simp] lemma vec_mul_vec_empty (v : m' → α) (w : fin 0 → α) : vec_mul_vec v w = λ _, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_vec_mul_vec (x : α) (v : fin m → α) (w : n' → α) : vec_mul_vec (vec_cons x v) w = vec_cons (x • w) (vec_mul_vec v w) := by { ext i, refine fin.cases _ _ i; simp [vec_mul_vec] } @[simp] lemma vec_mul_vec_cons (v : m' → α) (x : α) (w : fin n → α) : vec_mul_vec v (vec_cons x w) = λ i, v i • vec_cons x w := by { ext i j, simp [vec_mul_vec]} end vec_mul_vec section smul variables [semiring α] @[simp] lemma smul_empty (x : α) (v : fin 0 → α) : x • v = ![] := empty_eq _ @[simp] lemma smul_mat_empty {m' : Type*} (x : α) (A : fin 0 → m' → α) : x • A = ![] := empty_eq _ @[simp] lemma smul_cons (x y : α) (v : fin n → α) : x • vec_cons y v = vec_cons (x * y) (x • v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma smul_mat_cons (x : α) (v : n' → α) (A : matrix (fin m) n' α) : x • vec_cons v A = vec_cons (x • v) (x • A) := by { ext i, refine fin.cases _ _ i; simp } end smul section add variables [has_add α] @[simp] lemma empty_add_empty (v w : fin 0 → α) : v + w = ![] := empty_eq _ @[simp] lemma cons_add (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v + w = vec_cons (x + vec_head w) (v + vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma add_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v + vec_cons y w = vec_cons (vec_head v + y) (vec_tail v + w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_add (a b : fin n.succ → α) : vec_head (a + b) = vec_head a + vec_head b := rfl @[simp] lemma tail_add (a b : fin n.succ → α) : vec_tail (a + b) = vec_tail a + vec_tail b := rfl end add section sub variables [has_sub α] @[simp] lemma empty_sub_empty (v w : fin 0 → α) : v - w = ![] := empty_eq _ @[simp] lemma cons_sub (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v - w = vec_cons (x - vec_head w) (v - vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma sub_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v - vec_cons y w = vec_cons (vec_head v - y) (vec_tail v - w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_sub (a b : fin n.succ → α) : vec_head (a - b) = vec_head a - vec_head b := rfl @[simp] lemma tail_sub (a b : fin n.succ → α) : vec_tail (a - b) = vec_tail a - vec_tail b := rfl end sub section zero variables [has_zero α] @[simp] lemma zero_empty : (0 : fin 0 → α) = ![] := empty_eq _ @[simp] lemma cons_zero_zero : vec_cons (0 : α) (0 : fin n → α) = 0 := by { ext i j, refine fin.cases _ _ i, { refl }, simp } @[simp] lemma head_zero : vec_head (0 : fin n.succ → α) = 0 := rfl @[simp] lemma tail_zero : vec_tail (0 : fin n.succ → α) = 0 := rfl @[simp] lemma cons_eq_zero_iff {v : fin n → α} {x : α} : vec_cons x v = 0 ↔ x = 0 ∧ v = 0 := ⟨ λ h, ⟨ congr_fun h 0, by { convert congr_arg vec_tail h, simp } ⟩, λ ⟨hx, hv⟩, by simp [hx, hv] ⟩ open_locale classical lemma cons_nonzero_iff {v : fin n → α} {x : α} : vec_cons x v ≠ 0 ↔ (x ≠ 0 ∨ v ≠ 0) := ⟨ λ h, not_and_distrib.mp (h ∘ cons_eq_zero_iff.mpr), λ h, mt cons_eq_zero_iff.mp (not_and_distrib.mpr h) ⟩ end zero section neg variables [has_neg α] @[simp] lemma neg_empty (v : fin 0 → α) : -v = ![] := empty_eq _ @[simp] lemma neg_cons (x : α) (v : fin n → α) : -(vec_cons x v) = vec_cons (-x) (-v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma head_neg (a : fin n.succ → α) : vec_head (-a) = -vec_head a := rfl @[simp] lemma tail_neg (a : fin n.succ → α) : vec_tail (-a) = -vec_tail a := rfl end neg section minor @[simp] lemma minor_empty (A : matrix m' n' α) (row : fin 0 → m') (col : o' → n') : minor A row col = ![] := empty_eq _ @[simp] lemma minor_cons_row (A : matrix m' n' α) (i : m') (row : fin m → m') (col : o' → n') : minor A (vec_cons i row) col = vec_cons (λ j, A i (col j)) (minor A row col) := by { ext i j, refine fin.cases _ _ i; simp [minor] } end minor end matrix
dae07152693644608827b75c5d019383ff005e3b
3618c6e11aa822fd542440674dfb9a7b9921dba0
/scratch/coprod/free_group.lean
3c47af6e9857a644f994c1af124174e811d0b08f
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
16,607
lean
import data.list.chain data.int.basic tactic data.list.basic variables {α : Type*} open list def reduced (l : list (α × ℤ)) : Prop := l.chain' (λ a b, a.1 ≠ b.1) ∧ ∀ a : α × ℤ, a ∈ l → a.2 ≠ 0 @[simp] lemma reduced_nil : reduced ([] : list (α × ℤ)) := ⟨list.chain'_nil, λ _, false.elim⟩ lemma reduced_of_reduced_cons {a : α × ℤ} {l : list (α × ℤ)} (h : reduced (a :: l)) : reduced l := ⟨(list.chain'_cons'.1 h.1).2, λ b hb, h.2 _ (mem_cons_of_mem _ hb)⟩ lemma reduced_cons_of_reduced_cons {a : α} {i j : ℤ} {l : list (α × ℤ)} (h : reduced ((a, i) :: l)) (hj : j ≠ 0) : reduced ((a, j) :: l) := ⟨chain'_cons'.2 (chain'_cons'.1 h.1), begin rintros ⟨b, k⟩ hb, cases (mem_cons_iff _ _ _).1 hb with hb hb, { cc }, { exact h.2 _ (mem_cons_of_mem _ hb) } end⟩ lemma reduced_cons_cons {a b : α} {i j : ℤ} {l : list (α × ℤ)} (hab : a ≠ b) (hi : i ≠ 0) (hbl : reduced ((b, j) :: l)) : reduced ((a, i) :: (b, j) :: l) := ⟨chain'_cons.2 ⟨hab, hbl.1⟩, begin rintros ⟨c, k⟩ hc, cases (mem_cons_iff _ _ _).1 hc with hc hc, { cc }, { exact hbl.2 _ hc } end⟩ lemma reduced_reverse {l : list (α × ℤ)} (h : reduced l) : reduced l.reverse := ⟨chain'_reverse.2 $ by {convert h.1, simp [function.funext_iff, eq_comm] }, by simpa using h.2⟩ @[simp] lemma reduced_reverse_iff {l : list (α × ℤ)} : reduced l.reverse ↔ reduced l := ⟨λ h, by convert reduced_reverse h; simp, reduced_reverse⟩ variable (α) def free_group : Type* := {l : list (α × ℤ) // reduced l} namespace free_group instance : has_one (free_group α) := ⟨⟨[], trivial, by simp⟩⟩ variables {α} [decidable_eq α] def rcons : α × ℤ → list (α × ℤ) → list (α × ℤ) | a [] := [a] | a (b::l) := if a.1 = b.1 then let k := a.2 + b.2 in if k = 0 then l else (a.1, k) :: l else a :: b :: l -- def rconcat (a : α × ℤ) (l : list (α × ℤ)) : list (α × ℤ) := -- (rcons a l.reverse).reverse def reduce : list (α × ℤ) → list (α × ℤ) | [] := [] | (a :: l) := if a.2 = 0 then reduce l else rcons a (reduce l) lemma reduced_rcons : ∀ {a : α × ℤ} {l : list (α × ℤ)}, a.2 ≠ 0 → reduced l → reduced (rcons a l) | (a, i) [] ha h := ⟨list.chain'_singleton _, by simp [rcons]; cc⟩ | (a, i) ((b, j) :: l) ha h := begin simp [rcons], split_ifs, { exact reduced_of_reduced_cons h }, { subst h_1, exact reduced_cons_of_reduced_cons h h_2 }, { exact reduced_cons_cons h_1 ha h } end -- lemma reduced_rconcat {a : α × ℤ} {l : list (α × ℤ)} -- (ha : a.2 ≠ 0) (hl : reduced l) : reduced (rconcat a l) := -- begin -- rw [rconcat, reduced_reverse_iff], -- exact reduced_rcons ha (reduced_reverse hl) -- end lemma reduced_reduce : ∀ l : list (α × ℤ), reduced (reduce l) | [] := reduced_nil | (a::l) := begin rw reduce, split_ifs, { exact reduced_reduce l }, { exact reduced_rcons h (reduced_reduce l) } end lemma rcons_eq_cons : ∀ {a : α × ℤ} {l : list (α × ℤ)}, reduced (a :: l) → rcons a l = a :: l | a [] h := rfl | a (b::l) h := if_neg (chain'_cons.1 h.1).1 -- lemma rconcat_eq_concat {a : α × ℤ} {l : list (α × ℤ)} -- (h : reduced (l ++ [a])) : rconcat a l = l ++ [a] := -- begin -- rw [rconcat, rcons_eq_cons], simp, -- convert reduced_reverse h, simp, -- end lemma rcons_reduce_eq_reduce_cons : ∀ {a : α × ℤ} {l : list (α × ℤ)}, a.2 ≠ 0 → rcons a (reduce l) = reduce (a :: l) | a [] ha := by simp [rcons, reduce, ha] | a (b::l) ha := begin rw [reduce], split_ifs, { rw [reduce, if_neg ha, reduce, if_pos h] }, { rw [reduce, if_neg ha, reduce, if_neg h] } end -- inductive rel : list (α × ℤ) → list (α × ℤ) → Prop -- | refl : ∀ l, rel l l -- | zero : ∀ {a : α}, rel [(a, 0)] [] -- | add : ∀ {a i j}, rel [(a, i), (a, j)] [(a, i + j)] -- | append : ∀ {l₁ l₂ l₃ l₄}, rel l₁ l₂ → rel l₃ l₄ → rel (l₁ ++ l₃) (l₂ ++ l₄) -- | symm : ∀ {l₁ l₂}, rel l₁ l₂ → rel l₂ l₁ -- | trans : ∀ {l₁ l₂ l₃}, rel l₁ l₂ → rel l₂ l₃ → rel l₁ l₃ -- attribute [refl] rel.refl -- attribute [symm] rel.symm -- attribute [trans] rel.trans -- -- @[refl] lemma rel.refl : ∀ l : list (α × ℤ), rel l l := sorry -- lemma rel_rcons_cons : ∀ (a : α × ℤ) (l : list (α × ℤ)), -- rel (rcons a l) (a::l) -- | a [] := rel.refl _ -- | (a, i) ((b,j)::l) := begin -- rw rcons, -- split_ifs, -- { replace h : a = b := h, subst h, -- show rel ([] ++ l) ([(a,i), (a, j)] ++ l), -- refine rel.append _ (rel.refl _), -- symmetry, -- exact rel.add.trans (h_1.symm ▸ rel.zero) }, -- { replace h : a = b := h, subst h, -- show rel ([(a, i + j)] ++ l) ([(a, i), (a, j)] ++ l), -- exact rel.append rel.add.symm (rel.refl _) }, -- { refl }, -- end -- lemma rel_cons_of_rel {l₁ l₂ : list (α × ℤ)} (h : rel l₁ l₂) (a : α × ℤ) : -- rel (a :: l₁) (a :: l₂) := -- show rel ([a] ++ l₁) ([a] ++ l₂), from rel.append (rel.refl _) h -- lemma rel_rcons_cons_of_rel {a : α × ℤ} {l₁ l₂ : list (α × ℤ)} (h : rel l₁ l₂) : -- rel (rcons a l₁) (a ::l₂) := -- (rel_rcons_cons a l₁).trans (rel_cons_of_rel h _) -- lemma rel_reduce : ∀ l : list (α × ℤ), rel l (reduce l) -- | [] := rel.refl _ -- | ((a, i)::l) := begin -- rw reduce, -- split_ifs, -- { replace h : i = 0 := h, subst h, -- show rel ([(a, 0)] ++ l) ([] ++ reduce l), -- exact rel.append rel.zero (rel_reduce _) }, -- { exact (rel_rcons_cons_of_rel (rel_reduce _).symm).symm } -- end -- lemma reduce_eq_reduce_of_rel {l₁ l₂ : list (α × ℤ)} (h : rel l₁ l₂) : reduce l₁ = reduce l₂ := -- begin -- induction h, -- { refl }, -- { simp [reduce] }, -- { simp only [reduce], -- split_ifs, -- { refl }, -- { simp * at * }, -- { exfalso, omega }, -- { simp [rcons, *] }, -- { exfalso, omega }, -- { simp [rcons, *] }, -- { simp [rcons, *] }, -- { simp [rcons, *] } }, -- { } -- end lemma reduce_eq_self_of_reduced : ∀ {l : list (α × ℤ)}, reduced l → reduce l = l | [] h := rfl | (a::l) h := by rw [← rcons_reduce_eq_reduce_cons (h.2 a (mem_cons_self _ _)), reduce_eq_self_of_reduced (reduced_of_reduced_cons h), rcons_eq_cons h] lemma rcons_eq_reduce_cons {a : α × ℤ} {l : list (α × ℤ)} (ha : a.2 ≠ 0) (hl : reduced l) : rcons a l = reduce (a :: l) := by rw [← rcons_reduce_eq_reduce_cons ha, reduce_eq_self_of_reduced hl] @[simp] lemma reduce_reduce (l : list (α × ℤ)) : reduce (reduce l) = reduce l := reduce_eq_self_of_reduced (reduced_reduce l) @[simp] lemma reduce_cons_reduce_eq_reduce_cons (a : α × ℤ) (l : list (α × ℤ)) : reduce (a :: reduce l) = reduce (a :: l) := if ha : a.2 = 0 then by rw [reduce, if_pos ha, reduce, if_pos ha, reduce_reduce] else by rw [← rcons_reduce_eq_reduce_cons ha, ← rcons_reduce_eq_reduce_cons ha, reduce_reduce] lemma length_rcons_le : ∀ (a : α × ℤ) (l : list (α × ℤ)), (rcons a l).length ≤ (a::l : list _).length | a [] := le_refl _ | (a,i) ((b,j)::l) := begin simp [rcons], split_ifs, { linarith }, { simp }, { simp } end lemma length_reduce_le : ∀ (l : list (α × ℤ)), (reduce l).length ≤ l.length | [] := le_refl _ | [a] := by { simp [reduce], split_ifs; simp [rcons] } | (a::b::l) := begin simp only [reduce, rcons], split_ifs, { exact le_trans (length_reduce_le _) (le_trans (nat.le_succ _) (nat.le_succ _)) }, { exact le_trans (length_rcons_le _ _) (nat.succ_le_succ (le_trans (length_reduce_le _) (nat.le_succ _))) }, { exact le_trans (length_rcons_le _ _) (nat.succ_le_succ (le_trans (length_reduce_le _) (nat.le_succ _))) }, { exact le_trans (length_rcons_le _ _) (nat.succ_le_succ (le_trans (length_rcons_le _ _) (nat.succ_le_succ (length_reduce_le _)))) } end lemma length_rcons_lt_or_eq_rcons : ∀ (a : α × ℤ) (l : list (α × ℤ)), (rcons a l).length < (a :: l : list _).length ∨ rcons a l = (a::l) | a [] := or.inr rfl | a (b::l) := begin simp only [rcons], split_ifs, { exact or.inl (nat.lt_succ_of_le (nat.le_succ _)) }, { exact or.inl (nat.lt_succ_self _) }, { simp } end lemma length_reduce_lt_or_eq_reduce : ∀ (l : list (α × ℤ)), (reduce l).length < l.length ∨ reduce l = l | [] := or.inr rfl | (a::l) := begin simp only [reduce], split_ifs, { exact or.inl (nat.lt_succ_of_le (length_reduce_le _)) }, { cases length_rcons_lt_or_eq_rcons a (reduce l) with h h, { exact or.inl (lt_of_lt_of_le h (nat.succ_le_succ (length_reduce_le _))) }, { rw h, cases length_reduce_lt_or_eq_reduce l with h h, { exact or.inl (nat.succ_lt_succ h) }, { rw h, right, refl } } } end lemma rcons_append : ∀ {a b : α × ℤ} {l₁ l₂ : list (α × ℤ)}, rcons a ((b::l₁) ++ l₂) = rcons a (b::l₁) ++ l₂ | a b [] l₂ := begin simp [rcons], split_ifs; simp end | a b (c::l₁) l₂ := begin rw [cons_append, rcons], dsimp, split_ifs, { simp [rcons, *] }, { simp [rcons, *] }, { simp [rcons, *] } end lemma rcons_rcons_of_add_eq_zero {a : α} {i j : ℤ} : ∀ {l : list (α × ℤ)}, i + j = 0 → reduced l → rcons (a, i) (rcons (a, j) l) = l | [] hij hl := by simp [rcons, hij] | ((b, k)::l) hij hl := begin simp only [rcons], split_ifs, { rw [← rcons_eq_cons hl, show a = b, from h, show i = k, by omega] }, { simp only [rcons, if_pos rfl], rw [if_neg, ← add_assoc, hij, zero_add, show a = b, from h], have hk0 : k ≠ 0 := hl.2 (b, k) (mem_cons_self _ _), omega }, { rw [rcons, if_pos rfl], dsimp, rw [if_pos hij] } end lemma rcons_rcons_of_add_ne_zero {a : α} {i j : ℤ} : ∀ {l : list (α × ℤ)}, i + j ≠ 0 → i ≠ 0 → reduced l → rcons (a, i) (rcons (a, j) l) = rcons (a, i + j) l | [] hij hi hl := by simp [rcons, hij] | [(b, k)] hij hi hl := begin simp only [rcons], split_ifs, { exfalso, omega }, { simp [rcons], omega }, { simp only [rcons, ← add_assoc, *, if_pos rfl] }, { simp only [rcons, if_pos rfl, ← add_assoc, *], simp }, { simp [rcons, if_neg hij, if_pos rfl] } end | ((b, k)::(c, m)::l) hij hi hl := begin have hbc : b ≠ c, from (chain'_cons.1 hl.1).1, simp only [rcons], split_ifs, { exfalso, omega }, { simp [*, rcons] at *, omega }, { simp [*, rcons, ← add_assoc] at * }, { simp [*, rcons, ← add_assoc] }, { simp [*, rcons] } end lemma reduce_rcons : ∀ {a : α × ℤ} (l : list (α × ℤ)), a.2 ≠ 0 → reduce (rcons a l) = rcons a (reduce l) | a [] ha := by simp [rcons, reduce, ha] | (a, i) [(b, j)] hi := begin replace hi : i ≠ 0 := hi, simp only [reduce, rcons], split_ifs; simp [reduce, rcons, *] at * end | (a,i) ((b,j)::l) hi := begin simp only [rcons], split_ifs, { rw [reduce, if_neg, h, rcons_rcons_of_add_eq_zero h_1 (reduced_reduce _)], omega }, { simp only [reduce, if_neg h_1, reduce], split_ifs, { simp [h_2] }, { rw [h, rcons_rcons_of_add_ne_zero h_1 hi (reduced_reduce _)] } }, { rw [rcons_eq_reduce_cons hi (reduced_reduce _), reduce_cons_reduce_eq_reduce_cons] } end @[simp] lemma reduce_reduce_append_eq_reduce_append : ∀ (l₁ l₂ : list (α × ℤ)), reduce (reduce l₁ ++ l₂) = reduce (l₁ ++ l₂) | [] l₂ := rfl | (a::l₁) l₂ := begin simp only [reduce, cons_append], split_ifs with ha ha, { exact reduce_reduce_append_eq_reduce_append _ _ }, { rw [← reduce_reduce_append_eq_reduce_append l₁ l₂], induction h : reduce l₁, { simp [rcons, rcons_eq_reduce_cons ha (reduced_reduce _)] }, { rw [← rcons_append, reduce_rcons _ ha] } } end @[simp] lemma reduce_append_reduce_eq_reduce_append : ∀ {l₁ l₂ : list (α × ℤ)}, reduce (l₁ ++ reduce l₂) = reduce (l₁ ++ l₂) | [] l₂ := by simp | (a::l₁) l₂ := by rw [cons_append, ← reduce_cons_reduce_eq_reduce_cons, reduce_append_reduce_eq_reduce_append, reduce_cons_reduce_eq_reduce_cons, cons_append] /- TODO: Speed up, not the best definition, no need to reduce entire first list. -/ def mul_aux : list (α × ℤ) → list (α × ℤ) → list (α × ℤ) | [] l₂ := l₂ | (a :: l₁) l₂ := rcons a (mul_aux l₁ l₂) lemma reduced_mul_aux : ∀ {l₁ l₂ : list (α × ℤ)}, reduced l₁ → reduced l₂ → reduced (mul_aux l₁ l₂) | [] l₂ _ h := h | (a::l₁) l₂ h₁ h₂ := reduced_rcons (h₁.2 _ (mem_cons_self _ _)) (reduced_mul_aux (reduced_of_reduced_cons h₁) h₂) lemma mul_aux_eq_reduce_append : ∀ {l₁ l₂ : list (α × ℤ)}, reduced l₁ → reduced l₂ → mul_aux l₁ l₂ = reduce (l₁ ++ l₂) | [] l₂ _ h := by simp [reduce, mul_aux, reduce_eq_self_of_reduced h] | (a::l₁) l₂ h₁ h₂ := by rw [mul_aux, mul_aux_eq_reduce_append (reduced_of_reduced_cons h₁) h₂, rcons_reduce_eq_reduce_cons (h₁.2 a (mem_cons_self _ _)), cons_append] lemma mul_aux_assoc {l₁ l₂ l₃ : list (α × ℤ)} (h₁ : reduced l₁) (h₂ : reduced l₂) (h₃ : reduced l₃) : mul_aux (mul_aux l₁ l₂) l₃ = mul_aux l₁ (mul_aux l₂ l₃) := begin rw [mul_aux_eq_reduce_append h₁ h₂, mul_aux_eq_reduce_append h₂ h₃, mul_aux_eq_reduce_append (reduced_reduce _) h₃, mul_aux_eq_reduce_append h₁ (reduced_reduce _)], simp [append_assoc] end instance : has_mul (free_group α) := ⟨λ a b : free_group α, ⟨mul_aux a.1 b.1, reduced_mul_aux a.2 b.2⟩⟩ def inv_aux (l : list (α × ℤ)) : list (α × ℤ) := l.reverse.map (λ a, (a.1, -a.2)) lemma inv_aux_cons (a : α) (i : ℤ) (l : list (α × ℤ)) : inv_aux ((a, i) :: l) = inv_aux l ++ [(a, -i)] := by simp [inv_aux] lemma reduced_inv_aux {l : list (α × ℤ)} (hl : reduced l) : reduced (inv_aux l) := ⟨(list.chain'_map _).2 (list.chain'_reverse.2 begin convert hl.1, simp [function.funext_iff, eq_comm], end), begin rintros ⟨a, i⟩ ha, have := hl.2 (a, -i), finish [inv_aux] end⟩ instance : has_inv (free_group α) := ⟨λ a, ⟨inv_aux a.1, reduced_inv_aux a.2⟩⟩ lemma mul_aux_inv_aux_cancel : ∀ {l : list (α × ℤ)}, reduced l → mul_aux l (inv_aux l) = [] | [] hl := rfl | ((a, i)::l) hal := have hi : i ≠ 0, from hal.2 (a, i) (mem_cons_self _ _), have hl : reduced l, from reduced_of_reduced_cons hal, begin rw [mul_aux_eq_reduce_append hal (reduced_inv_aux hal), inv_aux_cons, cons_append, ← append_assoc, ← reduce_cons_reduce_eq_reduce_cons, ← reduce_reduce_append_eq_reduce_append, reduce_cons_reduce_eq_reduce_cons, ← mul_aux_eq_reduce_append hl (reduced_inv_aux hl), mul_aux_inv_aux_cancel hl], simp [reduce, hi, rcons] end instance : group (free_group α) := { mul := (*), inv := has_inv.inv, one := 1, mul_assoc := λ a b c, subtype.eq (mul_aux_assoc a.2 b.2 c.2), one_mul := λ ⟨_, _⟩, rfl, mul_one := λ ⟨_, _⟩, sorry, mul_left_inv := sorry } lemma mul_def (a b : free_group α) : a * b = ⟨mul_aux a.1 b.1, reduced_mul_aux a.2 b.2⟩ := rfl def of (a : α) : free_group α := ⟨[(a, 1)], by simp [reduced] { contextual := tt }⟩ @[elab_as_eliminator] lemma induction_on {P : free_group α → Prop} (g : free_group α) (h1 : P 1) (atom : ∀ a, P (of a)) (atom_inv : ∀ a, P (of a)⁻¹) (hmul : ∀ a g, P g → P (of a * g)) : P g := begin cases g with l hl, induction l with a l ihl, { exact h1 }, { cases a with a i, induction i using int.induction_on with i ihi i ihi, { simpa [reduced] using hl }, { by_cases hi : i = 0, { subst i, convert hmul a ⟨l, reduced_of_reduced_cons hl⟩ (ihl (reduced_of_reduced_cons hl)), rw [mul_aux_eq_reduce_append (of a).2 (reduced_of_reduced_cons hl), of, cons_append, nil_append, ← reduce_eq_self_of_reduced hl, int.coe_nat_zero, zero_add] }, { have hil : reduced ((a, i) :: l), from reduced_cons_of_reduced_cons hl (by norm_cast; exact hi), convert hmul a ⟨(a, i) :: l, hil⟩ (ihi hil), rw [mul_aux_eq_reduce_append (of a).2 hil, of, cons_append, nil_append, reduce, if_neg, reduce, if_neg, rcons_rcons_of_add_ne_zero], }, } } end variables {β : Type*} [decidable_eq β] (e : α → β) def map : free_group α →* free_group β := { to_fun := λ ⟨l, hl⟩, ⟨l.map e, _⟩ } end free_group
dc7798b568a8172410eec9a7a76ae25c288162b0
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/omin/presheaf3.lean
9e89d58e103e24240c7f3e9f3553e46162f66509
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
791
lean
import .presheaf2 universes v u namespace o_minimal variables {R : Type} (S : struc R) class psh' (X : Type v) := (definable : Π {K : Def S}, (K → X) → Sort v) -- restriction -- coherence instance (X : Type) [definable_psh S X] : psh' S X := { definable := λ K f, definable_psh.definable f } instance Type.psh' : psh' S Type := { definable := λ K X, Π {L : Def S} (z : Hom L K), (Π l, X (z l)) → Prop } -- plus coherence instance function.psh' (X : Type) (Y : Type 1) [psh' S X] [psh' S Y] : psh' S (X → Y) := { definable := λ K Φ, Π {L : Def.{0} S} (z : Hom L K) (f : L → X), psh'.definable f → psh'.definable (λ l, Φ (z l) (f l)) } -- plus coherence instance Pi.psh' (X : Type) [psh' S X] (Y : X → Type) : psh' S (Π (x : X), Y x) := sorry end o_minimal
b9eac421b55bebb2b89778675b6c0efa4d51813f
6b10c15e653d49d146378acda9f3692e9b5b1950
/examples/basic_skills/unnamed_813.lean
fe9c1e2571f831aa54ae4136a1da298ae4aaaf2f
[]
no_license
gebner/mathematics_in_lean
3cf7f18767208ea6c3307ec3a67c7ac266d8514d
6d1462bba46d66a9b948fc1aef2714fd265cde0b
refs/heads/master
1,655,301,945,565
1,588,697,505,000
1,588,697,505,000
261,523,603
0
0
null
1,588,695,611,000
1,588,695,610,000
null
UTF-8
Lean
false
false
183
lean
namespace my_ring variables {R : Type*} [ring R] -- BEGIN lemma one_add_one_eq_two : 1 + 1 = (2 : R) := by refl theorem two_mul (a : R) : 2 * a = a + a := sorry -- END end my_ring
7bdec28216d032c6bd0dc47855fe55cc95a5cf2d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebraic_geometry/prime_spectrum.lean
d1e458e19e3e4ac7896ffc16932d8e8acfa253f8
[ "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
20,167
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import topology.opens import ring_theory.ideal.prod import linear_algebra.finsupp import algebra.punit_instances /-! # Prime spectrum of a commutative ring The prime spectrum of a commutative ring is the type of all prime ideals. It is naturally endowed with a topology: the Zariski topology. (It is also naturally endowed with a sheaf of rings, which is constructed in `algebraic_geometry.structure_sheaf`.) ## Main definitions * `prime_spectrum R`: The prime spectrum of a commutative ring `R`, i.e., the set of all prime ideals of `R`. * `zero_locus s`: The zero locus of a subset `s` of `R` is the subset of `prime_spectrum R` consisting of all prime ideals that contain `s`. * `vanishing_ideal t`: The vanishing ideal of a subset `t` of `prime_spectrum R` is the intersection of points in `t` (viewed as prime ideals). ## Conventions We denote subsets of rings with `s`, `s'`, etc... whereas we denote subsets of prime spectra with `t`, `t'`, etc... ## Inspiration/contributors The contents of this file draw inspiration from <https://github.com/ramonfmir/lean-scheme> which has contributions from Ramon Fernandez Mir, Kevin Buzzard, Kenny Lau, and Chris Hughes (on an earlier repository). -/ noncomputable theory open_locale classical universe variables u v variables (R : Type u) [comm_ring R] /-- The prime spectrum of a commutative ring `R` is the type of all prime ideals of `R`. It is naturally endowed with a topology (the Zariski topology), and a sheaf of commutative rings (see `algebraic_geometry.structure_sheaf`). It is a fundamental building block in algebraic geometry. -/ @[nolint has_inhabited_instance] def prime_spectrum := {I : ideal R // I.is_prime} variable {R} namespace prime_spectrum /-- A method to view a point in the prime spectrum of a commutative ring as an ideal of that ring. -/ abbreviation as_ideal (x : prime_spectrum R) : ideal R := x.val instance is_prime (x : prime_spectrum R) : x.as_ideal.is_prime := x.2 /-- The prime spectrum of the zero ring is empty. -/ lemma punit (x : prime_spectrum punit) : false := x.1.ne_top_iff_one.1 x.2.1 $ subsingleton.elim (0 : punit) 1 ▸ x.1.zero_mem section variables (R) (S : Type v) [comm_ring S] /-- The prime spectrum of `R × S` is in bijection with the disjoint unions of the prime spectrum of `R` and the prime spectrum of `S`. -/ noncomputable def prime_spectrum_prod : prime_spectrum (R × S) ≃ prime_spectrum R ⊕ prime_spectrum S := ideal.prime_ideals_equiv R S variables {R S} @[simp] lemma prime_spectrum_prod_symm_inl_as_ideal (x : prime_spectrum R) : ((prime_spectrum_prod R S).symm (sum.inl x)).as_ideal = ideal.prod x.as_ideal ⊤ := by { cases x, refl } @[simp] lemma prime_spectrum_prod_symm_inr_as_ideal (x : prime_spectrum S) : ((prime_spectrum_prod R S).symm (sum.inr x)).as_ideal = ideal.prod ⊤ x.as_ideal := by { cases x, refl } end @[ext] lemma ext {x y : prime_spectrum R} : x = y ↔ x.as_ideal = y.as_ideal := subtype.ext_iff_val /-- The zero locus of a set `s` of elements of a commutative ring `R` is the set of all prime ideals of the ring that contain the set `s`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `zero_locus s` is exactly the subset of `prime_spectrum R` where all "functions" in `s` vanish simultaneously. -/ def zero_locus (s : set R) : set (prime_spectrum R) := {x | s ⊆ x.as_ideal} @[simp] lemma mem_zero_locus (x : prime_spectrum R) (s : set R) : x ∈ zero_locus s ↔ s ⊆ x.as_ideal := iff.rfl @[simp] lemma zero_locus_span (s : set R) : zero_locus (ideal.span s : set R) = zero_locus s := by { ext x, exact (submodule.gi R R).gc s x.as_ideal } /-- The vanishing ideal of a set `t` of points of the prime spectrum of a commutative ring `R` is the intersection of all the prime ideals in the set `t`. An element `f` of `R` can be thought of as a dependent function on the prime spectrum of `R`. At a point `x` (a prime ideal) the function (i.e., element) `f` takes values in the quotient ring `R` modulo the prime ideal `x`. In this manner, `vanishing_ideal t` is exactly the ideal of `R` consisting of all "functions" that vanish on all of `t`. -/ def vanishing_ideal (t : set (prime_spectrum R)) : ideal R := ⨅ (x : prime_spectrum R) (h : x ∈ t), x.as_ideal lemma coe_vanishing_ideal (t : set (prime_spectrum R)) : (vanishing_ideal t : set R) = {f : R | ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal} := begin ext f, rw [vanishing_ideal, set_like.mem_coe, submodule.mem_infi], apply forall_congr, intro x, rw [submodule.mem_infi], end lemma mem_vanishing_ideal (t : set (prime_spectrum R)) (f : R) : f ∈ vanishing_ideal t ↔ ∀ x : prime_spectrum R, x ∈ t → f ∈ x.as_ideal := by rw [← set_like.mem_coe, coe_vanishing_ideal, set.mem_set_of_eq] @[simp] lemma vanishing_ideal_singleton (x : prime_spectrum R) : vanishing_ideal ({x} : set (prime_spectrum R)) = x.as_ideal := by simp [vanishing_ideal] lemma subset_zero_locus_iff_le_vanishing_ideal (t : set (prime_spectrum R)) (I : ideal R) : t ⊆ zero_locus I ↔ I ≤ vanishing_ideal t := ⟨λ h f k, (mem_vanishing_ideal _ _).mpr (λ x j, (mem_zero_locus _ _).mpr (h j) k), λ h, λ x j, (mem_zero_locus _ _).mpr (le_trans h (λ f h, ((mem_vanishing_ideal _ _).mp h) x j))⟩ section gc variable (R) /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc : @galois_connection (ideal R) (order_dual (set (prime_spectrum R))) _ _ (λ I, zero_locus I) (λ t, vanishing_ideal t) := λ I t, subset_zero_locus_iff_le_vanishing_ideal t I /-- `zero_locus` and `vanishing_ideal` form a galois connection. -/ lemma gc_set : @galois_connection (set R) (order_dual (set (prime_spectrum R))) _ _ (λ s, zero_locus s) (λ t, vanishing_ideal t) := have ideal_gc : galois_connection (ideal.span) coe := (submodule.gi R R).gc, by simpa [zero_locus_span, function.comp] using galois_connection.compose _ _ _ _ ideal_gc (gc R) lemma subset_zero_locus_iff_subset_vanishing_ideal (t : set (prime_spectrum R)) (s : set R) : t ⊆ zero_locus s ↔ s ⊆ vanishing_ideal t := (gc_set R) s t end gc lemma subset_vanishing_ideal_zero_locus (s : set R) : s ⊆ vanishing_ideal (zero_locus s) := (gc_set R).le_u_l s lemma le_vanishing_ideal_zero_locus (I : ideal R) : I ≤ vanishing_ideal (zero_locus I) := (gc R).le_u_l I @[simp] lemma vanishing_ideal_zero_locus_eq_radical (I : ideal R) : vanishing_ideal (zero_locus (I : set R)) = I.radical := ideal.ext $ λ f, begin rw [mem_vanishing_ideal, ideal.radical_eq_Inf, submodule.mem_Inf], exact ⟨(λ h x hx, h ⟨x, hx.2⟩ hx.1), (λ h x hx, h x.1 ⟨hx, x.2⟩)⟩ end @[simp] lemma zero_locus_radical (I : ideal R) : zero_locus (I.radical : set R) = zero_locus I := vanishing_ideal_zero_locus_eq_radical I ▸ congr_fun (gc R).l_u_l_eq_l I lemma subset_zero_locus_vanishing_ideal (t : set (prime_spectrum R)) : t ⊆ zero_locus (vanishing_ideal t) := (gc R).l_u_le t lemma zero_locus_anti_mono {s t : set R} (h : s ⊆ t) : zero_locus t ⊆ zero_locus s := (gc_set R).monotone_l h lemma zero_locus_anti_mono_ideal {s t : ideal R} (h : s ≤ t) : zero_locus (t : set R) ⊆ zero_locus (s : set R) := (gc R).monotone_l h lemma vanishing_ideal_anti_mono {s t : set (prime_spectrum R)} (h : s ⊆ t) : vanishing_ideal t ≤ vanishing_ideal s := (gc R).monotone_u h lemma zero_locus_subset_zero_locus_iff (I J : ideal R) : zero_locus (I : set R) ⊆ zero_locus (J : set R) ↔ J ≤ I.radical := ⟨λ h, ideal.radical_le_radical_iff.mp (vanishing_ideal_zero_locus_eq_radical I ▸ vanishing_ideal_zero_locus_eq_radical J ▸ vanishing_ideal_anti_mono h), λ h, zero_locus_radical I ▸ zero_locus_anti_mono_ideal h⟩ lemma zero_locus_subset_zero_locus_singleton_iff (f g : R) : zero_locus ({f} : set R) ⊆ zero_locus {g} ↔ g ∈ (ideal.span ({f} : set R)).radical := by rw [← zero_locus_span {f}, ← zero_locus_span {g}, zero_locus_subset_zero_locus_iff, ideal.span_le, set.singleton_subset_iff, set_like.mem_coe] lemma zero_locus_bot : zero_locus ((⊥ : ideal R) : set R) = set.univ := (gc R).l_bot @[simp] lemma zero_locus_singleton_zero : zero_locus ({0} : set R) = set.univ := zero_locus_bot @[simp] lemma zero_locus_empty : zero_locus (∅ : set R) = set.univ := (gc_set R).l_bot @[simp] lemma vanishing_ideal_univ : vanishing_ideal (∅ : set (prime_spectrum R)) = ⊤ := by simpa using (gc R).u_top lemma zero_locus_empty_of_one_mem {s : set R} (h : (1:R) ∈ s) : zero_locus s = ∅ := begin rw set.eq_empty_iff_forall_not_mem, intros x hx, rw mem_zero_locus at hx, have x_prime : x.as_ideal.is_prime := by apply_instance, have eq_top : x.as_ideal = ⊤, { rw ideal.eq_top_iff_one, exact hx h }, apply x_prime.ne_top eq_top, end @[simp] lemma zero_locus_singleton_one : zero_locus ({1} : set R) = ∅ := zero_locus_empty_of_one_mem (set.mem_singleton (1 : R)) lemma zero_locus_empty_iff_eq_top {I : ideal R} : zero_locus (I : set R) = ∅ ↔ I = ⊤ := begin split, { contrapose!, intro h, apply set.ne_empty_iff_nonempty.mpr, rcases ideal.exists_le_maximal I h with ⟨M, hM, hIM⟩, exact ⟨⟨M, hM.is_prime⟩, hIM⟩ }, { rintro rfl, apply zero_locus_empty_of_one_mem, trivial } end @[simp] lemma zero_locus_univ : zero_locus (set.univ : set R) = ∅ := zero_locus_empty_of_one_mem (set.mem_univ 1) lemma zero_locus_sup (I J : ideal R) : zero_locus ((I ⊔ J : ideal R) : set R) = zero_locus I ∩ zero_locus J := (gc R).l_sup lemma zero_locus_union (s s' : set R) : zero_locus (s ∪ s') = zero_locus s ∩ zero_locus s' := (gc_set R).l_sup lemma vanishing_ideal_union (t t' : set (prime_spectrum R)) : vanishing_ideal (t ∪ t') = vanishing_ideal t ⊓ vanishing_ideal t' := (gc R).u_inf lemma zero_locus_supr {ι : Sort*} (I : ι → ideal R) : zero_locus ((⨆ i, I i : ideal R) : set R) = (⋂ i, zero_locus (I i)) := (gc R).l_supr lemma zero_locus_Union {ι : Sort*} (s : ι → set R) : zero_locus (⋃ i, s i) = (⋂ i, zero_locus (s i)) := (gc_set R).l_supr lemma zero_locus_bUnion (s : set (set R)) : zero_locus (⋃ s' ∈ s, s' : set R) = ⋂ s' ∈ s, zero_locus s' := by simp only [zero_locus_Union] lemma vanishing_ideal_Union {ι : Sort*} (t : ι → set (prime_spectrum R)) : vanishing_ideal (⋃ i, t i) = (⨅ i, vanishing_ideal (t i)) := (gc R).u_infi lemma zero_locus_inf (I J : ideal R) : zero_locus ((I ⊓ J : ideal R) : set R) = zero_locus I ∪ zero_locus J := set.ext $ λ x, by simpa using x.2.inf_le lemma union_zero_locus (s s' : set R) : zero_locus s ∪ zero_locus s' = zero_locus ((ideal.span s) ⊓ (ideal.span s') : ideal R) := by { rw zero_locus_inf, simp } lemma zero_locus_mul (I J : ideal R) : zero_locus ((I * J : ideal R) : set R) = zero_locus I ∪ zero_locus J := set.ext $ λ x, by simpa using x.2.mul_le lemma zero_locus_singleton_mul (f g : R) : zero_locus ({f * g} : set R) = zero_locus {f} ∪ zero_locus {g} := set.ext $ λ x, by simpa using x.2.mul_mem_iff_mem_or_mem @[simp] lemma zero_locus_pow (I : ideal R) {n : ℕ} (hn : 0 < n) : zero_locus ((I ^ n : ideal R) : set R) = zero_locus I := zero_locus_radical (I ^ n) ▸ (I.radical_pow n hn).symm ▸ zero_locus_radical I @[simp] lemma zero_locus_singleton_pow (f : R) (n : ℕ) (hn : 0 < n) : zero_locus ({f ^ n} : set R) = zero_locus {f} := set.ext $ λ x, by simpa using x.2.pow_mem_iff_mem n hn lemma sup_vanishing_ideal_le (t t' : set (prime_spectrum R)) : vanishing_ideal t ⊔ vanishing_ideal t' ≤ vanishing_ideal (t ∩ t') := begin intros r, rw [submodule.mem_sup, mem_vanishing_ideal], rintro ⟨f, hf, g, hg, rfl⟩ x ⟨hxt, hxt'⟩, rw mem_vanishing_ideal at hf hg, apply submodule.add_mem; solve_by_elim end lemma mem_compl_zero_locus_iff_not_mem {f : R} {I : prime_spectrum R} : I ∈ (zero_locus {f} : set (prime_spectrum R))ᶜ ↔ f ∉ I.as_ideal := by rw [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff]; refl /-- The Zariski topology on the prime spectrum of a commutative ring is defined via the closed sets of the topology: they are exactly those sets that are the zero locus of a subset of the ring. -/ instance zariski_topology : topological_space (prime_spectrum R) := topological_space.of_closed (set.range prime_spectrum.zero_locus) (⟨set.univ, by simp⟩) begin intros Zs h, rw set.sInter_eq_Inter, let f : Zs → set R := λ i, classical.some (h i.2), have hf : ∀ i : Zs, ↑i = zero_locus (f i) := λ i, (classical.some_spec (h i.2)).symm, simp only [hf], exact ⟨_, zero_locus_Union _⟩ end (by { rintro _ _ ⟨s, rfl⟩ ⟨t, rfl⟩, exact ⟨_, (union_zero_locus s t).symm⟩ }) lemma is_open_iff (U : set (prime_spectrum R)) : is_open U ↔ ∃ s, Uᶜ = zero_locus s := by simp only [@eq_comm _ Uᶜ]; refl lemma is_closed_iff_zero_locus (Z : set (prime_spectrum R)) : is_closed Z ↔ ∃ s, Z = zero_locus s := by rw [← is_open_compl_iff, is_open_iff, compl_compl] lemma is_closed_zero_locus (s : set R) : is_closed (zero_locus s) := by { rw [is_closed_iff_zero_locus], exact ⟨s, rfl⟩ } lemma zero_locus_vanishing_ideal_eq_closure (t : set (prime_spectrum R)) : zero_locus (vanishing_ideal t : set R) = closure t := begin apply set.subset.antisymm, { rintro x hx t' ⟨ht', ht⟩, obtain ⟨fs, rfl⟩ : ∃ s, t' = zero_locus s, by rwa [is_closed_iff_zero_locus] at ht', rw [subset_zero_locus_iff_subset_vanishing_ideal] at ht, exact set.subset.trans ht hx }, { rw (is_closed_zero_locus _).closure_subset_iff, exact subset_zero_locus_vanishing_ideal t } end lemma vanishing_ideal_closure (t : set (prime_spectrum R)) : vanishing_ideal (closure t) = vanishing_ideal t := zero_locus_vanishing_ideal_eq_closure t ▸ congr_fun (gc R).u_l_u_eq_u t section comap variables {S : Type v} [comm_ring S] {S' : Type*} [comm_ring S'] /-- The function between prime spectra of commutative rings induced by a ring homomorphism. This function is continuous. -/ def comap (f : R →+* S) : prime_spectrum S → prime_spectrum R := λ y, ⟨ideal.comap f y.as_ideal, infer_instance⟩ variables (f : R →+* S) @[simp] lemma comap_as_ideal (y : prime_spectrum S) : (comap f y).as_ideal = ideal.comap f y.as_ideal := rfl @[simp] lemma comap_id : comap (ring_hom.id R) = id := funext $ λ _, subtype.ext $ ideal.ext $ λ _, iff.rfl @[simp] lemma comap_comp (f : R →+* S) (g : S →+* S') : comap (g.comp f) = comap f ∘ comap g := funext $ λ _, subtype.ext $ ideal.ext $ λ _, iff.rfl @[simp] lemma preimage_comap_zero_locus (s : set R) : (comap f) ⁻¹' (zero_locus s) = zero_locus (f '' s) := begin ext x, simp only [mem_zero_locus, set.mem_preimage, comap_as_ideal, set.image_subset_iff], refl end lemma comap_continuous (f : R →+* S) : continuous (comap f) := begin rw continuous_iff_is_closed, simp only [is_closed_iff_zero_locus], rintro _ ⟨s, rfl⟩, exact ⟨_, preimage_comap_zero_locus f s⟩ end end comap section basic_open /-- `basic_open r` is the open subset containing all prime ideals not containing `r`. -/ def basic_open (r : R) : topological_space.opens (prime_spectrum R) := { val := { x | r ∉ x.as_ideal }, property := ⟨{r}, set.ext $ λ x, set.singleton_subset_iff.trans $ not_not.symm⟩ } @[simp] lemma mem_basic_open (f : R) (x : prime_spectrum R) : x ∈ basic_open f ↔ f ∉ x.as_ideal := iff.rfl lemma is_open_basic_open {a : R} : is_open ((basic_open a) : set (prime_spectrum R)) := (basic_open a).property @[simp] lemma basic_open_eq_zero_locus_compl (r : R) : (basic_open r : set (prime_spectrum R)) = (zero_locus {r})ᶜ := set.ext $ λ x, by simpa only [set.mem_compl_eq, mem_zero_locus, set.singleton_subset_iff] @[simp] lemma basic_open_one : basic_open (1 : R) = ⊤ := topological_space.opens.ext $ by {simp, refl} @[simp] lemma basic_open_zero : basic_open (0 : R) = ⊥ := topological_space.opens.ext $ by {simp, refl} lemma basic_open_le_basic_open_iff (f g : R) : basic_open f ≤ basic_open g ↔ f ∈ (ideal.span ({g} : set R)).radical := by rw [topological_space.opens.le_def, basic_open_eq_zero_locus_compl, basic_open_eq_zero_locus_compl, set.le_eq_subset, set.compl_subset_compl, zero_locus_subset_zero_locus_singleton_iff] lemma basic_open_mul (f g : R) : basic_open (f * g) = basic_open f ⊓ basic_open g := topological_space.opens.ext $ by {simp [zero_locus_singleton_mul]} lemma basic_open_mul_le_left (f g : R) : basic_open (f * g) ≤ basic_open f := by { rw basic_open_mul f g, exact inf_le_left } lemma basic_open_mul_le_right (f g : R) : basic_open (f * g) ≤ basic_open g := by { rw basic_open_mul f g, exact inf_le_right } @[simp] lemma basic_open_pow (f : R) (n : ℕ) (hn : 0 < n) : basic_open (f ^ n) = basic_open f := topological_space.opens.ext $ by simpa using zero_locus_singleton_pow f n hn lemma is_topological_basis_basic_opens : topological_space.is_topological_basis (set.range (λ (r : R), (basic_open r : set (prime_spectrum R)))) := begin apply topological_space.is_topological_basis_of_open_of_nhds, { rintros _ ⟨r, rfl⟩, exact is_open_basic_open }, { rintros p U hp ⟨s, hs⟩, rw [← compl_compl U, set.mem_compl_eq, ← hs, mem_zero_locus, set.not_subset] at hp, obtain ⟨f, hfs, hfp⟩ := hp, refine ⟨basic_open f, ⟨f, rfl⟩, hfp, _⟩, rw [← set.compl_subset_compl, ← hs, basic_open_eq_zero_locus_compl, compl_compl], exact zero_locus_anti_mono (set.singleton_subset_iff.mpr hfs) } end lemma is_compact_basic_open (f : R) : is_compact (basic_open f : set (prime_spectrum R)) := is_compact_of_finite_subfamily_closed $ λ ι Z hZc hZ, begin let I : ι → ideal R := λ i, vanishing_ideal (Z i), have hI : ∀ i, Z i = zero_locus (I i) := λ i, by simpa only [zero_locus_vanishing_ideal_eq_closure] using (hZc i).closure_eq.symm, rw [basic_open_eq_zero_locus_compl f, set.inter_comm, ← set.diff_eq, set.diff_eq_empty, funext hI, ← zero_locus_supr] at hZ, obtain ⟨n, hn⟩ : f ∈ (⨆ (i : ι), I i).radical, { rw ← vanishing_ideal_zero_locus_eq_radical, apply vanishing_ideal_anti_mono hZ, exact (subset_vanishing_ideal_zero_locus {f} (set.mem_singleton f)) }, rcases submodule.exists_finset_of_mem_supr I hn with ⟨s, hs⟩, use s, -- Using simp_rw here, because `hI` and `zero_locus_supr` need to be applied underneath binders simp_rw [basic_open_eq_zero_locus_compl f, set.inter_comm, ← set.diff_eq, set.diff_eq_empty, hI, ← zero_locus_supr], rw ← zero_locus_radical, -- this one can't be in `simp_rw` because it would loop apply zero_locus_anti_mono, rw set.singleton_subset_iff, exact ⟨n, hs⟩ end end basic_open /-- The prime spectrum of a commutative ring is a compact topological space. -/ instance : compact_space (prime_spectrum R) := { compact_univ := by { convert is_compact_basic_open (1 : R), rw basic_open_one, refl } } section order /-! ## The specialization order We endow `prime_spectrum R` with a partial order, where `x ≤ y` if and only if `y ∈ closure {x}`. TODO: maybe define sober topological spaces, and generalise this instance to those -/ instance : partial_order (prime_spectrum R) := subtype.partial_order _ @[simp] lemma as_ideal_le_as_ideal (x y : prime_spectrum R) : x.as_ideal ≤ y.as_ideal ↔ x ≤ y := subtype.coe_le_coe @[simp] lemma as_ideal_lt_as_ideal (x y : prime_spectrum R) : x.as_ideal < y.as_ideal ↔ x < y := subtype.coe_lt_coe lemma le_iff_mem_closure (x y : prime_spectrum R) : x ≤ y ↔ y ∈ closure ({x} : set (prime_spectrum R)) := by rw [← as_ideal_le_as_ideal, ← zero_locus_vanishing_ideal_eq_closure, mem_zero_locus, vanishing_ideal_singleton, set_like.coe_subset_coe] end order end prime_spectrum
b75e1e9ccb7a459762d1d50be74cc6fb24644eb3
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/order/directed.lean
0ad66c03c30ebbd7b95f93d58f15fd73b3f652db
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
3,083
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import order.lattice import data.set.basic universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} (r : α → α → Prop) local infix ` ≼ ` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z variables {r} theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) alias directed_on_iff_directed ↔ directed_on.directed_coe _ theorem directed_on_image {s} {f : β → α} : directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s := by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage] theorem directed_on.mono {s : set α} (h : directed_on r s) {r' : α → α → Prop} (H : ∀ {a b}, r a b → r' a b) : directed_on r' s := λ x hx y hy, let ⟨z, zs, xz, yz⟩ := h x hx y hy in ⟨z, zs, H xz, H yz⟩ theorem directed_comp {ι} {f : ι → β} {g : β → α} : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α} (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α} (hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) : directed rb (g ∘ f) := directed_comp.2 $ hf.mono hg /-- A monotone function on a sup-semilattice is directed. -/ lemma directed_of_sup [semilattice_sup α] {f : α → β} {r : β → β → Prop} (H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : directed r f := λ a b, ⟨a ⊔ b, H le_sup_left, H le_sup_right⟩ /-- An antimonotone function on an inf-semilattice is directed. -/ lemma directed_of_inf [semilattice_inf α] {r : β → β → Prop} {f : α → β} (hf : ∀a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f := assume x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A `preorder` is a `directed_order` if for any two elements `i`, `j` there is an element `k` such that `i ≤ k` and `j ≤ k`. -/ class directed_order (α : Type u) extends preorder α := (directed : ∀ i j : α, ∃ k, i ≤ k ∧ j ≤ k) instance linear_order.to_directed_order (α) [linear_order α] : directed_order α := ⟨λ i j, or.cases_on (le_total i j) (λ hij, ⟨j, hij, le_refl j⟩) (λ hji, ⟨i, le_refl i, hji⟩)⟩ end prio
1d6446bb5b2ac4800470ccf2498d0a280c56adcf
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Meta/Tactic/Rewrite.lean
87ffadfd08761e0602ef2aefc67f43a0840bf080
[ "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
2,560
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.KAbstract import Lean.Meta.Check import Lean.Meta.Tactic.Apply namespace Lean namespace Meta structure RewriteResult := (eNew : Expr) (eqProof : Expr) (mvarIds : List MVarId) -- new goals def rewrite (mvarId : MVarId) (e : Expr) (heq : Expr) (symm : Bool := false) (occs : Occurrences := Occurrences.all) : MetaM RewriteResult := withMVarContext mvarId $ do checkNotAssigned mvarId `rewrite; heqType ← inferType heq; (newMVars, binderInfos, heqType) ← forallMetaTelescopeReducing heqType; let heq := mkAppN heq newMVars; let continue (heq heqType : Expr) : MetaM RewriteResult := match heqType.eq? with | none => throwTacticEx `rewrite mvarId ("equality of iff proof expected") | some (α, lhs, rhs) => let continue (heq heqType lhs rhs : Expr) : MetaM RewriteResult := do { when lhs.getAppFn.isMVar $ throwTacticEx `rewrite mvarId ("pattern is a metavariable " ++ indentExpr lhs ++ Format.line ++ "from equation" ++ indentExpr heqType); e ← instantiateMVars e; eAbst ← kabstract e lhs occs; unless eAbst.hasLooseBVars $ throwTacticEx `rewrite mvarId ("did not find instance of the pattern in the target expression"); -- construct rewrite proof let eNew := eAbst.instantiate1 rhs; eNew ← instantiateMVars eNew; eEqE ← mkEq e e; let eEqEAbst := mkApp eEqE.appFn! eAbst; let motive := Lean.mkLambda `_a BinderInfo.default α eEqEAbst; unlessM (isTypeCorrect motive) $ throwTacticEx `rewrite mvarId ("motive is not type correct"); eqRefl ← mkEqRefl e; eqPrf ← mkEqNDRec motive eqRefl heq; postprocessAppMVars `rewrite mvarId newMVars binderInfos; newMVars ← newMVars.filterM $ fun mvar => not <$> isExprMVarAssigned mvar.mvarId!; pure { eNew := eNew, eqProof := eqPrf, mvarIds := newMVars.toList.map Expr.mvarId! } }; match symm with | false => continue heq heqType lhs rhs | true => do { heq ← mkEqSymm heq; heqType ← mkEq rhs lhs; continue heq heqType rhs lhs }; match heqType.iff? with | some (lhs, rhs) => do heqType ← mkEq lhs rhs; let heq := mkApp3 (mkConst `propext) lhs rhs heq; continue heq heqType | none => continue heq heqType end Meta end Lean
6e6a8cd05e0b65e618c1bc7a917fb30ae8b5e516
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/continuous_on.lean
0a3c6b24c34ef70bb5f3cb70710aca7571695a2c
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
24,277
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.constructions /-! # Neighborhoods and continuity relative to a subset This file defines relative versions `nhds_within` of `nhds` `continuous_on` of `continuous` `continuous_within_at` of `continuous_at` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] /-- The "neighborhood within" filter. Elements of `nhds_within a s` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ principal s theorem nhds_within_eq (a : α) (s : set α) : nhds_within a s = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, principal (t ∩ s) := have set.univ ∈ {s : set α | a ∈ s ∧ is_open s}, from ⟨set.mem_univ _, is_open_univ⟩, begin rw [nhds_within, nhds, binfi_inf]; try { exact this }, simp only [inf_principal] end theorem nhds_within_univ (a : α) : nhds_within a set.univ = 𝓝 a := by rw [nhds_within, principal_univ, inf_top_eq] lemma nhds_within_has_basis {p : β → Prop} {s : β → set α} {a : α} (h : (𝓝 a).has_basis p s) (t : set α) : (nhds_within a t).has_basis p (λ i, s i ∩ t) := h.inf_principal t lemma nhds_within_basis_open (a : α) (t : set α) : (nhds_within a t).has_basis (λ u, a ∈ u ∧ is_open u) (λ u, u ∩ t) := nhds_within_has_basis (nhds_basis_opens a) t theorem mem_nhds_within {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t := by simpa only [exists_prop, and_assoc, and_comm] using nhds_within_basis_open a s t lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} : t ∈ nhds_within a s ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t := nhds_within_has_basis (𝓝 a).basis_sets s t lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ nhds_within a t := mem_inf_sets_of_left h theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ nhds_within a s := mem_inf_sets_of_right (mem_principal_self s) theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ nhds_within a s := inter_mem_sets (mem_inf_sets_of_right (mem_principal_self s)) (mem_inf_sets_of_left h) theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : nhds_within a s ≤ nhds_within a t := inf_le_inf (le_refl _) (principal_mono.mpr h) lemma mem_of_mem_nhds_within {a : α} {s t : set α} (ha : a ∈ s) (ht : t ∈ nhds_within a s) : a ∈ t := let ⟨u, hu, H⟩ := mem_nhds_within.1 ht in H.2 ⟨H.1, ha⟩ lemma filter.eventually.self_of_nhds_within {p : α → Prop} {s : set α} {x : α} (h : ∀ᶠ y in nhds_within x s, p y) (hx : x ∈ s) : p x := mem_of_mem_nhds_within hx h theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ nhds_within a s) : nhds_within a s = nhds_within a (s ∩ t) := le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem_sets self_mem_nhds_within h))) (inf_le_inf (le_refl _) (principal_mono.mpr (set.inter_subset_left _ _))) theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict'' s $ mem_inf_sets_of_left h theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) : nhds_within a s = nhds_within a (s ∩ t) := nhds_within_restrict' s (mem_nhds_sets h₁ h₀) theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ nhds_within a t) : nhds_within a t ≤ nhds_within a s := begin rcases mem_nhds_within.1 h with ⟨u, u_open, au, uts⟩, have : nhds_within a t = nhds_within a (t ∩ u) := nhds_within_restrict _ au u_open, rw [this, inter_comm], exact nhds_within_mono _ uts end theorem nhds_within_eq_nhds_within {a : α} {s t u : set α} (h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) : nhds_within a t = nhds_within a u := by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂] theorem nhds_within_eq_of_open {a : α} {s : set α} (h₀ : a ∈ s) (h₁ : is_open s) : nhds_within a s = 𝓝 a := by rw [←nhds_within_univ]; apply nhds_within_eq_nhds_within h₀ h₁; rw [set.univ_inter, set.inter_self] @[simp] theorem nhds_within_empty (a : α) : nhds_within a {} = ⊥ := by rw [nhds_within, principal_empty, inf_bot_eq] theorem nhds_within_union (a : α) (s t : set α) : nhds_within a (s ∪ t) = nhds_within a s ⊔ nhds_within a t := by unfold nhds_within; rw [←inf_sup_left, sup_principal] theorem nhds_within_inter (a : α) (s t : set α) : nhds_within a (s ∩ t) = nhds_within a s ⊓ nhds_within a t := by unfold nhds_within; rw [inf_left_comm, inf_assoc, inf_principal, ←inf_assoc, inf_idem] theorem nhds_within_inter' (a : α) (s t : set α) : nhds_within a (s ∩ t) = (nhds_within a s) ⊓ principal t := by { unfold nhds_within, rw [←inf_principal, inf_assoc] } lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β] (a : α) (b : β) (s : set α) (t : set β) : nhds_within (a, b) (s.prod t) = (nhds_within a s).prod (nhds_within b t) := by { unfold nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] } theorem tendsto_if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (nhds_within a (s ∩ p)) l) (h₁ : tendsto g (nhds_within a (s ∩ {x | ¬ p x})) l) : tendsto (λ x, if p x then f x else g x) (nhds_within a s) l := by apply tendsto_if; rw [←nhds_within_inter']; assumption lemma map_nhds_within (f : α → β) (a : α) (s : set α) : map f (nhds_within a s) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, principal (set.image f (t ∩ s)) := ((nhds_within_basis_open a s).map f).eq_binfi theorem tendsto_nhds_within_mono_left {f : α → β} {a : α} {s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (nhds_within a t) l) : tendsto f (nhds_within a s) l := tendsto_le_left (nhds_within_mono a hst) h theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β} {a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (nhds_within a s)) : tendsto f l (nhds_within a t) := tendsto_le_right (nhds_within_mono a hst) h theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α} {s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) : tendsto f (nhds_within a s) l := by rw [←nhds_within_univ] at h; exact tendsto_nhds_within_mono_left (set.subset_univ _) h theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) : principal t = comap subtype.val (principal (subtype.val '' t)) := by rw comap_principal; rw set.preimage_image_eq; apply subtype.val_injective lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} : x ∈ closure s ↔ nhds_within x s ≠ ⊥ := mem_closure_iff_nhds.trans (nhds_within_has_basis (𝓝 x).basis_sets s).forall_nonempty_iff_ne_bot lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) : nhds_within x s ≠ ⊥ := mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s) {x : α} (hx : nhds_within x s ≠ ⊥) : x ∈ s := by simpa only [closure_eq_of_is_closed hs] using mem_closure_iff_nhds_within_ne_bot.2 hx /- nhds_within and subtypes -/ theorem mem_nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t u : set {x // x ∈ s}) : t ∈ nhds_within a u ↔ t ∈ comap (@subtype.val _ s) (nhds_within a.val (subtype.val '' u)) := by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within] theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : nhds_within a t = comap (@subtype.val _ s) (nhds_within a.val (subtype.val '' t)) := filter_eq $ by ext u; rw mem_nhds_within_subtype theorem nhds_within_eq_map_subtype_val {s : set α} {a : α} (h : a ∈ s) : nhds_within a s = map subtype.val (𝓝 ⟨a, h⟩) := have h₀ : s ∈ nhds_within a s, by { rw [mem_nhds_within], existsi set.univ, simp [set.diff_eq] }, have h₁ : ∀ y ∈ s, ∃ x, @subtype.val _ s x = y, from λ y h, ⟨⟨y, h⟩, rfl⟩, begin rw [←nhds_within_univ, nhds_within_subtype, subtype.val_image_univ], exact (map_comap_of_surjective' h₀ h₁).symm, end theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) : tendsto f (nhds_within a s) l ↔ tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l := by { simp only [tendsto, nhds_within_eq_map_subtype_val h, filter.map_map], refl } variables [topological_space β] [topological_space γ] /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop := tendsto f (nhds_within x s) (𝓝 (f x)) /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `tendsto.comp` as `continuous_within_at.comp` will have a different meaning. -/ lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) : tendsto f (nhds_within x s) (𝓝 (f x)) := h /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x lemma continuous_on.continuous_within_at {f : α → β} {s : set α} {x : α} (hf : continuous_on f s) (hx : x ∈ s) : continuous_within_at f s x := hf x hx theorem continuous_within_at_univ (f : α → β) (x : α) : continuous_within_at f set.univ x ↔ continuous_at f x := by rw [continuous_at, continuous_within_at, nhds_within_univ] theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α} (h : x ∈ s) : continuous_within_at f s x ↔ continuous_at (s.restrict f) ⟨x, h⟩ := tendsto_nhds_within_iff_subtype h f _ theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α} (h : continuous_within_at f s x) : tendsto f (nhds_within x s) (nhds_within (f x) (f '' s)) := tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_sets_of_right $ mem_principal_sets.2 $ λ x, mem_image_of_mem _⟩ theorem continuous_on_iff {f : α → β} {s : set α} : continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within] theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} : continuous_on f s ↔ continuous (s.restrict f) := begin rw [continuous_on, continuous_iff_continuous_at], split, { rintros h ⟨x, xs⟩, exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) }, intros h x xs, exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩) end theorem continuous_on_iff' {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_open (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_open_induced_iff, set.restrict_eq, set.preimage_comp], simp only [preimage_coe_eq_preimage_coe_iff], split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ } end, by rw [continuous_on_iff_continuous_restrict, continuous]; simp only [this] theorem continuous_on_iff_is_closed {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_closed (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_closed_induced_iff, set.restrict_eq, set.preimage_comp], simp only [preimage_coe_eq_preimage_coe_iff] end, by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this] lemma continuous_on_empty (f : α → β) : continuous_on f ∅ := λ x, false.elim theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) : nhds_within x s ≤ comap f (nhds_within (f x) (f '' s)) := map_le_iff_le_comap.1 ctsf.tendsto_nhds_within_image theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} : continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) := tendsto_iff_ptendsto _ _ _ _ lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ := by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at, nhds_within_univ] lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : s ⊆ t) : continuous_within_at f s x := tendsto_le_left (nhds_within_mono x hs) h lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ nhds_within x s) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict'' s h] lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict' s h] lemma continuous_within_at.union {f : α → β} {s t : set α} {x : α} (hs : continuous_within_at f s x) (ht : continuous_within_at f t x) : continuous_within_at f (s ∪ t) x := by simp only [continuous_within_at, nhds_within_union, tendsto, map_sup, sup_le_iff.2 ⟨hs, ht⟩] lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := mem_closure_of_tendsto (mem_closure_iff_nhds_within_ne_bot.1 hx) h $ mem_sets_of_superset self_mem_nhds_within (subset_preimage_image f s) lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β} (h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : s ⊆ f⁻¹' A) : f x ∈ closure A := closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx) lemma continuous_within_at.image_closure {f : α → β} {s : set α} (hf : ∀ x ∈ closure s, continuous_within_at f s x) : f '' (closure s) ⊆ closure (f '' s) := begin rintros _ ⟨x, hx, rfl⟩, exact (hf x hx).mem_closure_image hx end theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α} (h : is_open_map (s.restrict f)) {finv : β → α} (hleft : left_inv_on finv f s) : continuous_on finv (f '' s) := begin rintros _ ⟨x, xs, rfl⟩ t ht, rw [hleft xs] at ht, replace h := h.nhds_le ⟨x, xs⟩, apply mem_nhds_within_of_mem_nhds, apply h, erw [map_compose.symm, function.comp, mem_map, ← nhds_within_eq_map_subtype_val], apply mem_sets_of_superset (inter_mem_nhds_within _ ht), assume y hy, rw [mem_set_of_eq, mem_preimage, hleft hy.1], exact hy.2 end theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f) {finv : β → α} (hleft : function.left_inverse finv f) : continuous_on finv (range f) := begin rw [← image_univ], exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x) end lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s) (h' : ∀x ∈ s₁, g x = f x) (h₁ : s₁ ⊆ s) : continuous_on g s₁ := begin assume x hx, unfold continuous_within_at, have A := (h x (h₁ hx)).mono h₁, unfold continuous_within_at at A, rw ← h' x hx at A, have : {x : α | g x = f x} ∈ nhds_within x s₁ := mem_inf_sets_of_right h', apply tendsto.congr' _ A, convert this, ext, finish end lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : ∀x ∈ s, g x = f x) : continuous_on g s := h.congr_mono h' (subset.refl _) lemma continuous_on_congr {f g : α → β} {s : set α} (h' : ∀x ∈ s, g x = f x) : continuous_on g s ↔ continuous_on f s := ⟨λ h, continuous_on.congr h (λx hx, (h' x hx).symm), λ h, continuous_on.congr h h'⟩ lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) : continuous_within_at f s x := continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _) lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x := begin have : s = univ ∩ s, by rw univ_inter, rwa [this, continuous_within_at_inter hs, continuous_within_at_univ] at h end lemma continuous_on.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_on f s) (hx : s ∈ 𝓝 x) : continuous_at f x := (h x (mem_of_nhds hx)).continuous_at hx lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : s ⊆ f ⁻¹' t) : continuous_within_at (g ∘ f) s x := begin have : tendsto f (principal s) (principal t), by { rw tendsto_principal_principal, exact λx hx, h hx }, have : tendsto f (nhds_within x s) (principal t) := tendsto_le_left inf_le_right this, have : tendsto f (nhds_within x s) (nhds_within (f x) t) := tendsto_inf.2 ⟨hf, this⟩, exact tendsto.comp hg this end lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) (h : s ⊆ f ⁻¹' t) : continuous_on (g ∘ f) s := λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) : continuous_on f t := λx hx, tendsto_le_left (nhds_within_mono _ h) (hf x (h hx)) lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) : continuous_on f s := begin rw continuous_iff_continuous_on_univ at h, exact h.mono (subset_univ _) end lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) : continuous_within_at f s x := tendsto_le_left inf_le_left (h.tendsto x) lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α} (hg : continuous g) (hf : continuous_on f s) : continuous_on (g ∘ f) s := hg.continuous_on.comp hf subset_preimage_univ lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ nhds_within x s := h ht lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ nhds_within (f x) (f '' s)) : f ⁻¹' t ∈ nhds_within x s := begin rw mem_nhds_within at ht, rcases ht with ⟨u, u_open, fxu, hu⟩, have : f ⁻¹' u ∩ s ∈ nhds_within x s := filter.inter_mem_sets (h (mem_nhds_sets u_open fxu)) self_mem_nhds_within, apply mem_sets_of_superset this, calc f ⁻¹' u ∩ s ⊆ f ⁻¹' u ∩ f ⁻¹' (f '' s) : inter_subset_inter_right _ (subset_preimage_image f s) ... = f ⁻¹' (u ∩ f '' s) : rfl ... ⊆ f ⁻¹' t : preimage_mono hu end lemma continuous_within_at.congr_of_mem_nhds_within {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : {y | f₁ y = f y} ∈ nhds_within x s) (hx : f₁ x = f x) : continuous_within_at f₁ s x := by rwa [continuous_within_at, filter.tendsto, hx, filter.map_cong h₁] lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : continuous_within_at f₁ s x := h.congr_of_mem_nhds_within (mem_sets_of_superset self_mem_nhds_within h₁) hx lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s := continuous_const.continuous_on lemma continuous_within_at_const {b : β} {s : set α} {x : α} : continuous_within_at (λ _:α, b) s x := continuous_const.continuous_within_at lemma continuous_on_id {s : set α} : continuous_on id s := continuous_id.continuous_on lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x := continuous_id.continuous_within_at lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) := begin rw continuous_on_iff', split, { assume h t ht, rcases h t ht with ⟨u, u_open, hu⟩, rw [inter_comm, hu], apply is_open_inter u_open hs }, { assume h t ht, refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩, rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] } end lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) := (continuous_on_open_iff hs).1 hf t ht lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) := begin rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩, rw [inter_comm, hu.2], apply is_closed_inter hu.1 hs end lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) := calc s ∩ f ⁻¹' (interior t) = interior (s ∩ f ⁻¹' (interior t)) : (interior_eq_of_open (hf.preimage_open_of_open hs is_open_interior)).symm ... ⊆ interior (s ∩ f ⁻¹' t) : interior_mono (inter_subset_inter (subset.refl _) (preimage_mono interior_subset)) ... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, interior_eq_of_open hs] lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α} (h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s := begin assume x xs, rcases h x xs with ⟨t, open_t, xt, ct⟩, have := ct x ⟨xs, xt⟩, rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this end lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β} (hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) : @continuous_on α β _ (topological_space.generate_from T) f s := begin rw continuous_on_open_iff, assume t ht, induction ht with u hu u v Tu Tv hu hv U hU hU', { exact h u hu }, { simp only [preimage_univ, inter_univ], exact hs }, { have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v), by { ext x, simp, split, finish, finish }, rw this, exact is_open_inter hu hv }, { rw [preimage_sUnion, inter_bUnion], exact is_open_bUnion hU' }, { exact hs } end lemma continuous_within_at.prod {f : α → β} {g : α → γ} {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.prod_mk_nhds hg lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s := λx hx, continuous_within_at.prod (hf x hx) (hg x hx)
b5aecb49e0c9617852e6960383e24222e3e00e97
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/types/identifier_types.lean
653fd5a04f29740ebf21403b6e5f601a69a24d3e
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
412
lean
/- Identifiers, bindings, types -/ /- Identifiers are terms in Lean. All terms have types. So identifiers have types. The type of an identifier is the type of the term to which the identifier is bound. -/ def b' : bool := (tt : bool) -- types explicit def b := tt -- types inferred -- type inference def s : string := "I love logic!" def n : ℕ := 1 def n' := 1 -- Lean assumes (1 : ℕ)
0072dffae043948ea70d89681af40a26d7bf29f1
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/data/equiv/list.lean
bb378be238a5230f12c228c8c5521e69d2795182
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
10,362
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Additional equiv and encodable instances for lists, finsets, and fintypes. -/ import data.equiv.denumerable data.nat.pairing order.order_iso data.array.lemmas data.fintype open nat list namespace encodable variables {α : Type*} section list variable [encodable α] def encode_list : list α → ℕ | [] := 0 | (a::l) := succ (mkpair (encode a) (encode_list l)) def decode_list : ℕ → option (list α) | 0 := some [] | (succ v) := match unpair v, unpair_le_right v with | (v₁, v₂), h := have v₂ < succ v, from lt_succ_of_le h, (::) <$> decode α v₁ <*> decode_list v₂ end instance list : encodable (list α) := ⟨encode_list, decode_list, λ l, by induction l with a l IH; simp [encode_list, decode_list, unpair_mkpair, encodek, *]⟩ @[simp] theorem encode_list_nil : encode (@nil α) = 0 := rfl @[simp] theorem encode_list_cons (a : α) (l : list α) : encode (a :: l) = succ (mkpair (encode a) (encode l)) := rfl @[simp] theorem decode_list_zero : decode (list α) 0 = some [] := rfl @[simp] theorem decode_list_succ (v : ℕ) : decode (list α) (succ v) = (::) <$> decode α v.unpair.1 <*> decode (list α) v.unpair.2 := show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], refl end theorem length_le_encode : ∀ (l : list α), length l ≤ encode l | [] := _root_.zero_le _ | (a :: l) := succ_le_succ $ le_trans (length_le_encode l) (le_mkpair_right _ _) end list section finset variables [encodable α] private def enle : α → α → Prop := encode ⁻¹'o (≤) private lemma enle.is_linear_order : is_linear_order α enle := (order_embedding.preimage ⟨encode, encode_injective⟩ (≤)).is_linear_order private def decidable_enle (a b : α) : decidable (enle a b) := by unfold enle order.preimage; apply_instance local attribute [instance] enle.is_linear_order decidable_enle def encode_multiset (s : multiset α) : ℕ := encode (s.sort enle) def decode_multiset (n : ℕ) : option (multiset α) := coe <$> decode (list α) n instance multiset : encodable (multiset α) := ⟨encode_multiset, decode_multiset, λ s, by simp [encode_multiset, decode_multiset, encodek]⟩ end finset def encodable_of_list [decidable_eq α] (l : list α) (H : ∀ x, x ∈ l) : encodable α := ⟨λ a, index_of a l, l.nth, λ a, index_of_nth (H _)⟩ def trunc_encodable_of_fintype (α : Type*) [decidable_eq α] [fintype α] : trunc (encodable α) := @@quot.rec_on_subsingleton _ (λ s : multiset α, (∀ x:α, x ∈ s) → trunc (encodable α)) _ finset.univ.1 (λ l H, trunc.mk $ encodable_of_list l H) finset.mem_univ instance vector [encodable α] {n} : encodable (vector α n) := encodable.subtype instance fin_arrow [encodable α] {n} : encodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance fin_pi (n) (π : fin n → Type*) [∀i, encodable (π i)] : encodable (Πi, π i) := of_equiv _ (equiv.pi_equiv_subtype_sigma (fin n) π) instance array [encodable α] {n} : encodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) instance finset [encodable α] : encodable (finset α) := by haveI := decidable_eq_of_encodable α; exact of_equiv {s : multiset α // s.nodup} ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ def fintype_arrow (α : Type*) (β : Type*) [fintype α] [decidable_eq α] [encodable β] : trunc (encodable (α → β)) := (fintype.equiv_fin α).map $ λf, encodable.of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr f (equiv.refl _) def fintype_pi (α : Type*) (π : α → Type*) [fintype α] [decidable_eq α] [∀a, encodable (π a)] : trunc (encodable (Πa, π a)) := (encodable.trunc_encodable_of_fintype α).bind $ λa, (@fintype_arrow α (Σa, π a) _ _ (@encodable.sigma _ _ a _)).bind $ λf, trunc.mk $ @encodable.of_equiv _ _ (@encodable.subtype _ _ f _) (equiv.pi_equiv_subtype_sigma α π) /-- The elements of a `fintype` as a sorted list. -/ def sorted_univ (α) [fintype α] [encodable α] : list α := finset.univ.sort (encodable.encode' α ⁻¹'o (≤)) theorem mem_sorted_univ {α} [fintype α] [encodable α] (x : α) : x ∈ sorted_univ α := (finset.mem_sort _).2 (finset.mem_univ _) theorem length_sorted_univ {α} [fintype α] [encodable α] : (sorted_univ α).length = fintype.card α := finset.length_sort _ theorem sorted_univ_nodup {α} [fintype α] [encodable α] : (sorted_univ α).nodup := finset.sort_nodup _ _ /-- An encodable `fintype` is equivalent a `fin`.-/ def fintype_equiv_fin {α} [fintype α] [encodable α] : α ≃ fin (fintype.card α) := begin haveI : decidable_eq α := encodable.decidable_eq_of_encodable _, transitivity, { exact fintype.equiv_fin_of_forall_mem_list mem_sorted_univ (@sorted_univ_nodup α _ _) }, exact equiv.cast (congr_arg _ (@length_sorted_univ α _ _)) end instance fintype_arrow_of_encodable {α β : Type*} [encodable α] [fintype α] [encodable β] : encodable (α → β) := of_equiv (fin (fintype.card α) → β) $ equiv.arrow_congr fintype_equiv_fin (equiv.refl _) end encodable namespace denumerable variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable section list theorem denumerable_list_aux : ∀ n : ℕ, ∃ a ∈ @decode_list α _ n, encode_list a = n | 0 := ⟨_, rfl, rfl⟩ | (succ v) := begin cases e : unpair v with v₁ v₂, have h := unpair_le_right v, rw e at h, rcases have v₂ < succ v, from lt_succ_of_le h, denumerable_list_aux v₂ with ⟨a, h₁, h₂⟩, simp at h₁, simp [decode_list, e, h₂, h₁, encode_list, mkpair_unpair' e] end instance denumerable_list : denumerable (list α) := ⟨denumerable_list_aux⟩ @[simp] theorem list_of_nat_zero : of_nat (list α) 0 = [] := rfl @[simp] theorem list_of_nat_succ (v : ℕ) : of_nat (list α) (succ v) = of_nat α v.unpair.1 :: of_nat (list α) v.unpair.2 := of_nat_of_decode $ show decode_list (succ v) = _, begin cases e : unpair v with v₁ v₂, simp [decode_list, e], rw [show decode_list v₂ = decode (list α) v₂, from rfl, decode_eq_of_nat]; refl end end list section multiset def lower : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower l m def raise : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise l (m + n) lemma lower_raise : ∀ l n, lower (raise l n) n = l | [] n := rfl | (m :: l) n := by simp [raise, lower, nat.add_sub_cancel, lower_raise] lemma raise_lower : ∀ {l n}, list.sorted (≤) (n :: l) → raise (lower l n) n = l | [] n h := rfl | (m :: l) n h := have n ≤ m, from list.rel_of_sorted_cons h _ (l.mem_cons_self _), by simp [raise, lower, nat.sub_add_cancel this, raise_lower (list.sorted_of_sorted_cons h)] lemma raise_chain : ∀ l n, list.chain (≤) n (raise l n) | [] n := list.chain.nil | (m :: l) n := list.chain.cons (nat.le_add_left _ _) (raise_chain _ _) lemma raise_sorted : ∀ l n, list.sorted (≤) (raise l n) | [] n := list.sorted_nil | (m :: l) n := (list.chain_iff_pairwise (@le_trans _ _)).1 (raise_chain _ _) /- Warning: this is not the same encoding as used in `encodable` -/ instance multiset : denumerable (multiset α) := mk' ⟨ λ s : multiset α, encode $ lower ((s.map encode).sort (≤)) 0, λ n, multiset.map (of_nat α) (raise (of_nat (list ℕ) n) 0), λ s, by have := raise_lower (list.sorted_cons.2 ⟨λ n _, zero_le n, (s.map encode).sort_sorted _⟩); simp [-multiset.coe_map, this], λ n, by simp [-multiset.coe_map, list.merge_sort_eq_self _ (raise_sorted _ _), lower_raise]⟩ end multiset section finset def lower' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m - n) :: lower' l (m + 1) def raise' : list ℕ → ℕ → list ℕ | [] n := [] | (m :: l) n := (m + n) :: raise' l (m + n + 1) lemma lower_raise' : ∀ l n, lower' (raise' l n) n = l | [] n := rfl | (m :: l) n := by simp [raise', lower', nat.add_sub_cancel, lower_raise'] lemma raise_lower' : ∀ {l n}, (∀ m ∈ l, n ≤ m) → list.sorted (<) l → raise' (lower' l n) n = l | [] n h₁ h₂ := rfl | (m :: l) n h₁ h₂ := have n ≤ m, from h₁ _ (l.mem_cons_self _), by simp [raise', lower', nat.sub_add_cancel this, raise_lower' (list.rel_of_sorted_cons h₂ : ∀ a ∈ l, m < a) (list.sorted_of_sorted_cons h₂)] lemma raise'_chain : ∀ l {m n}, m < n → list.chain (<) m (raise' l n) | [] m n h := list.chain.nil | (a :: l) m n h := list.chain.cons (lt_of_lt_of_le h (nat.le_add_left _ _)) (raise'_chain _ (lt_succ_self _)) lemma raise'_sorted : ∀ l n, list.sorted (<) (raise' l n) | [] n := list.sorted_nil | (m :: l) n := (list.chain_iff_pairwise (@lt_trans _ _)).1 (raise'_chain _ (lt_succ_self _)) def raise'_finset (l : list ℕ) (n : ℕ) : finset ℕ := ⟨raise' l n, (raise'_sorted _ _).imp (@ne_of_lt _ _)⟩ /- Warning: this is not the same encoding as used in `encodable` -/ instance finset : denumerable (finset α) := mk' ⟨ λ s : finset α, encode $ lower' ((s.map (eqv α).to_embedding).sort (≤)) 0, λ n, finset.map (eqv α).symm.to_embedding (raise'_finset (of_nat (list ℕ) n) 0), λ s, finset.eq_of_veq $ by simp [-multiset.coe_map, raise'_finset, raise_lower' (λ n _, zero_le n) (finset.sort_sorted_lt _)], λ n, by simp [-multiset.coe_map, finset.map, raise'_finset, finset.sort, list.merge_sort_eq_self (≤) ((raise'_sorted _ _).imp (@le_of_lt _ _)), lower_raise']⟩ end finset end denumerable namespace equiv /-- The type lists on unit is canonically equivalent to the natural numbers. -/ def list_unit_equiv : list unit ≃ ℕ := { to_fun := list.length, inv_fun := list.repeat (), left_inv := λ u, list.injective_length (by simp), right_inv := λ n, list.length_repeat () n } def list_nat_equiv_nat : list ℕ ≃ ℕ := denumerable.eqv _ def list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : list α ≃ α := calc list α ≃ list ℕ : list_equiv_of_equiv e ... ≃ ℕ : list_nat_equiv_nat ... ≃ α : e.symm end equiv
58db610ea8e067c723c1318f25981418f78f9a4e
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/linear_algebra/basic.lean
e5b380bf5488b5a436913372b9cfeabd322ed287
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
78,692
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 -/ import algebra.pi_instances data.finsupp data.equiv.mul_add order.order_iso /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module.lean`. ## Main definitions * Many constructors for linear maps, including `prod` and `coprod` * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`: that is, elements of `M` are identified if their difference is in `p`. This is itself a module. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * `linear_equiv M M₂`, the type of linear equivalences between `M` and `M₂`, is a structure that extends `linear_map` and `equiv`. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. ## Main statements * The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and `sup_quotient_equiv_quotient_inf`. ## Notations * We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the ring `R`. * We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `linear_equiv M M₂`. In the first, the ring `R` is implicit. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`prod`, `coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## Tags linear algebra, vector space, module -/ open function reserve infix ` ≃ₗ `:25 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} namespace finsupp lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y} [has_zero β] [ring R] [add_comm_group M] [module R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type u} [fintype ι] {R : Type v} [semiring R] (x : ι → R) : x = finset.sum finset.univ (λi:ι, x i • (λj, if i = j then 1 else 0)) := begin ext k, rw pi.finset_sum_apply, have : finset.sum finset.univ (λ (x_1 : ι), x x_1 * ite (k = x_1) 1 0) = x k, by { have := finset.sum_mul_boole finset.univ x k, rwa if_pos (finset.mem_univ _) at this }, rw ← this, apply finset.sum_congr rfl (λl hl, _), simp only [smul_eq_mul, mul_ite, pi.smul_apply], conv_lhs { rw eq_comm } end end namespace linear_map section variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables (f g : M →ₗ[R] M₂) include R @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) : (cod_restrict p f h x : M) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) : (cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact ⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂], λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩ /-- The constant 0 map is linear. -/ instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩ instance : inhabited (M →ₗ[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp [add_comm], by simp⟩⟩ @[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp [add_comm, add_left_comm], by simp [smul_add]⟩⟩ @[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₗ[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] instance linear_map.is_add_group_hom : is_add_group_hom f := { map_add := f.add } instance linear_map_apply_is_add_group_hom (a : M) : is_add_group_hom (λ f : M →ₗ[R] M₂, f a) := { map_add := λ f g, linear_map.add_apply f g a } lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) : t.sum f b = t.sum (λd, f d b) := (t.sum_hom (λ g : M →ₗ[R] M₂, g b)).symm @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl /-- `λb, f b • x` is a linear map. -/ def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M := ⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩. @[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_right f x : M₂ → M) c = f c • x := rfl instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩ instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩ @[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl @[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero] @[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 := rfl section variables (R M) include M instance endomorphism_ring : ring (M →ₗ[R] M) := by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..}; { intros, apply linear_map.ext, simp } end section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = finset.sum finset.univ (λi:ι, x i • (f (λj, if i = j then 1 else 0))) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩ /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ 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. -/ def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ := { to_fun := λ x, (f x, g x), add := λ x y, by simp only [prod.mk_add_mk, map_add], smul := λ c x, by simp only [prod.smul_mk, map_smul] } @[simp] theorem prod_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) : prod f g x = (f x, g x) := rfl @[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 section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl] /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr] 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 /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := { to_fun := λ x, f x.1 + g x.2, add := λ x y, by simp only [map_add, prod.snd_add, prod.fst_add]; cc, smul := λ x y, by simp only [smul_add, prod.smul_snd, prod.smul_fst, map_smul] } @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) : coprod f g (x, y) = f x + g y := 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 ⟨x, y⟩; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext ⟨x, y⟩; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext ⟨x, y⟩; simp 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 /-- `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 end section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f g : M →ₗ[R] M₂) include R instance : has_scalar R (M →ₗ[R] M₂) := ⟨λ a f, ⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩ @[simp] lemma smul_apply (a : R) (x : M) : (a • f) x = a • f x := rfl instance : module R (M →ₗ[R] M₂) := module.of_core $ by refine { smul := (•), ..}; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := ⟨linear_map.comp f, λ _ _, linear_map.ext $ λ _, f.2 _ _, λ _ _, linear_map.ext $ λ _, f.3 _ _⟩ theorem smul_comp (g : M₂ →ₗ[R] M₃) (a : R) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) := ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, add := λ m m', by { ext, apply smul_add, }, smul := λ c m, by { ext, apply smul_comm, } }, add := λ f f', by { ext, apply add_smul, }, smul := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ R) →ₗ M →ₗ M₂ →ₗ M) f x c = (f c) • x := rfl end comm_ring end linear_map namespace submodule variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set instance : partial_order (submodule R M) := partial_order.lift (coe : submodule R M → set M) (λ a b, ext') (by apply_instance) variables {p p'} lemma le_def : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl lemma le_def' : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl lemma lt_def : p < p' ↔ (p : set M) ⊂ p' := iff.rfl lemma not_le_iff_exists : ¬ (p ≤ p') ↔ ∃ x ∈ p, x ∉ p' := not_subset lemma exists_of_lt {p p' : submodule R M} : p < p' → ∃ x ∈ p', x ∉ p := exists_of_ssubset lemma lt_iff_le_and_exists : p < p' ↔ p ≤ p' ∧ ∃ x ∈ p', x ∉ p := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If two submodules p and p' satisfy p ⊆ p', then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨by split; try {exact {0}}; simp {contextual := tt}⟩ instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl section variables (R) @[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff end instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..submodule.partial_order } /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨by split; try {exact set.univ}; simp⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl @[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ := by ext x; simp [semimodule.eq_zero_of_zero_eq_one x zero_eq_one] instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..submodule.partial_order } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, ↑s, zero := by simp, add := by simp [add_mem] {contextual := tt}, smul := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S := subset_bInter instance : has_inf (submodule R M) := ⟨λ p p', { carrier := p ∩ p', zero := by simp, add := by simp [add_mem] {contextual := tt}, smul := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, subset_inter, inf_le_left := λ a b, inter_subset_left _ _, inf_le_right := λ a b, inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.order_top, ..submodule.order_bot } instance : add_comm_monoid (submodule R M) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm } @[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl @[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩ @[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl @[simp] theorem mem_inf {p p' : submodule R M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] theorem mem_infi {ι} (p : ι → submodule R M) : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← mem_coe, infi_coe, mem_Inter]; refl theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ := { carrier := f '' p, zero := ⟨0, p.zero_mem, f.map_zero⟩, add := by rintro _ _ ⟨b₁, hb₁, rfl⟩ ⟨b₂, hb₂, rfl⟩; exact ⟨_, p.add_mem hb₁ hb₂, f.map_add _ _⟩, smul := by rintro a _ ⟨b, hb, rfl⟩; exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩ } lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma map_id : map linear_map.id p = p := submodule.ext $ λ a, by simp lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) : map (g.comp f) p = map g (map f p) := submodule.ext' $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M := { carrier := f ⁻¹' p, zero := by simp, add := λ x y h₁ h₂, by simp [p.add_mem h₁ h₂], smul := λ a x h, by simp [p.smul_mem _ h] } @[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := submodule.ext' rfl lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) : comap (g.comp f) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr @[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ := ext $ by simp lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂} {p : submodule R M} {p' : submodule R M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end lemma mem_supr_of_mem {ι : Sort*} {b : M} (p : ι → submodule R M) (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, rw [Sup_eq_supr, supr_subtype', mem_supr_of_directed, subtype.exists], exact (directed_on_iff_directed _).1 hdir end section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ end lemma mem_span_singleton {y : M} : x ∈ span R ({y} : set M) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma span_singleton_eq_range (y : M) : (span R ({y} : set M) : set M) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (span K {x}) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin rw [← union_singleton, span_union, mem_sup], simp [mem_span_singleton, add_comm, add_left_comm], split, { rintro ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩, exact ⟨a, z, hz, rfl⟩ }, { rintro ⟨a, z, hz, rfl⟩, exact ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩ } end lemma mem_span_insert' {y} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ lemma span_singleton_eq_bot : span R ({x} : set M) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma linear_eq_on (s : set M) {f g : M →ₗ[R] M₂} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} lemma supr_eq_span {ι : Sort w} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem _ i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : span R {m} ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, mem_coe] lemma mem_supr {ι : Sort w} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M₂) := { carrier := set.prod p q, zero := ⟨zero_mem _, zero_mem _⟩, add := by rintro ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ ⟨hx₁, hy₁⟩ ⟨hx₂, hy₂⟩; exact ⟨add_mem _ hx₁ hx₂, add_mem _ hy₁ hy₂⟩, smul := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩ } @[simp] lemma prod_coe : (prod p q : set (M × M₂)) = set.prod p q := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M₂) : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') := ext' set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [le_def'], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end -- TODO(Mario): Factor through add_subgroup /-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/ def quotient_rel : setoid M := ⟨λ x y, x - y ∈ p, λ x, by simp, λ x y h, by simpa using neg_mem _ h, λ x y z h₁ h₂, by simpa [sub_eq_add_neg, add_left_comm] using add_mem _ h₁ h₂⟩ /-- The quotient of a module `M` by a submodule `p ⊆ M`. -/ def quotient : Type* := quotient (quotient_rel p) namespace quotient /-- Map associating to an element of `M` the corresponding element of `M/p`, when `p` is a submodule of `M`. -/ def mk {p : submodule R M} : M → quotient p := quotient.mk' @[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl @[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl @[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq' instance : has_zero (quotient p) := ⟨mk 0⟩ instance : inhabited (quotient p) := ⟨0⟩ @[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl @[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p := by simpa using (quotient.eq p : mk x = 0 ↔ _) instance : has_add (quotient p) := ⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa [sub_eq_add_neg, add_left_comm, add_comm] using add_mem p h₁ h₂⟩ @[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl instance : has_neg (quotient p) := ⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $ λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩ @[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl instance : add_comm_group (quotient p) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; repeat {rintro ⟨⟩}; simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]; cc instance : has_scalar R (quotient p) := ⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $ λ x y h, (quotient.eq p).2 $ by simpa [smul_sub] using smul_mem p a h⟩ @[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl instance : module R (quotient p) := module.of_core $ by refine {smul := (•), ..}; repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul, -mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm] end quotient end submodule namespace submodule variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end set_option class.instance_max_depth 40 lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open submodule @[simp] lemma finsupp_sum {R M M₂ γ} [ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂] [has_zero γ] (f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/ def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤ theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ @[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x := (set.ext_iff _ _).1 (range_coe f). @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _ theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) := map_comp _ _ _ theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g := by rw range_comp; exact map_mono le_top theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f := by rw [← submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range, map_le_iff_le_comap, eq_top_iff] lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f := map_mono le_top lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := begin refine eq_top_iff'.2 (λ x, mem_sup.2 _), rcases x with ⟨x₁, x₂⟩ , have h₁ : prod.mk x₁ (0 : M₂) ∈ (inl R M M₂).range, by simp, have h₂ : prod.mk (0 : M) x₂ ∈ (inr R M M₂).range, by simp, use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂], simp end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) := by rw ker_comp; exact comap_mono bot_le theorem sub_mem_ker_iff {f : M →ₗ[R] M₂} {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem disjoint_ker' {f : M →ₗ[R] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) 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 ker_eq_bot {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot' {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := have h : (∀ m ∈ (⊤ : submodule R M), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0), from ⟨λ h m, h m mem_top, λ h m _, h m⟩, by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤ lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := map_cod_restrict _ _ _ _ lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) : map f (comap f q) = q := by rw [map_comap_eq, inf_of_le_right h] lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [comap_map_eq, sup_of_le_left h] @[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ := submodule.map_zero _ theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top lemma range_le_ker_iff {f : M →ₗ[R] M₂} {g : M₂ →ₗ[R] M₃} : range f ≤ ker g ↔ g.comp f = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ mem_map_of_mem trivial, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y ⟨_, hy⟩, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem map_le_map_iff {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := ⟨λ H x hx, let ⟨y, hy, e⟩ := H ⟨x, hx, rfl⟩ in ker_eq_bot.1 hf e ▸ hy, map_mono⟩ theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff hf).1 (le_of_eq h)) ((map_le_map_iff hf).1 (ge_of_eq h)) theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) 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 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 (prod.inl '' s ∪ prod.inr '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl 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 end linear_map namespace linear_map variables [field K] variables [add_comm_group V] [vector_space K V] variables [add_comm_group V₂] [vector_space K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := submodule.map_smul' f _ a end linear_map namespace is_linear_map lemma is_linear_map_add {R M : Type*} [ring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [ring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p p' : submodule R M) (q : submodule R M₂) include T open linear_map @[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl @[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot.2 $ λ x y, subtype.eq' @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] lemma disjoint_iff_comap_eq_bot (p q : submodule R M) : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff p.ker_subtype, map_bot, map_comap_subtype]; refl /-- If N ⊆ M then submodules of N are the same as submodules of M contained in N -/ def map_subtype.order_iso : ((≤) : submodule R p → submodule R p → Prop) ≃o ((≤) : {p' : submodule R M // p' ≤ p} → {p' : submodule R M // p' ≤ p} → Prop) := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq], ord := λ p₁ p₂, (map_le_map_iff $ ker_subtype _).symm } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of M. -/ def map_subtype.le_order_embedding : ((≤) : submodule R p → submodule R p → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.le_order_embedding p p' = map p.subtype p' := rfl /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of M. -/ def map_subtype.lt_order_embedding : ((<) : submodule R p → submodule R p → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (map_subtype.le_order_embedding p).lt_embedding_of_le_embedding @[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, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range, ← prod_top, prod_map_snd] /-- The map from a module `M` to the quotient of `M` by a submodule `p` as a linear map. -/ def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩ @[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl /-- The map from the quotient of `M` by a submodule `p` to `M₂` induced by a linear map `f : M → M₂` vanishing on `p`, as a linear map. -/ def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ := ⟨λ x, _root_.quotient.lift_on' x f $ λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab, by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y, by rintro a ⟨x⟩; exact f.map_smul a x⟩ @[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) : p.liftq f h (quotient.mk x) = f x := rfl @[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f := by ext; refl @[simp] theorem range_mkq : p.mkq.range = ⊤ := eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩ @[simp] theorem ker_mkq : p.mkq.ker = p := by ext; simp lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' := by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p') @[simp] theorem mkq_map_self : map p.mkq p = ⊥ := by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _ @[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' := by simp [comap_map_eq, sup_comm] /-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along `f : M → M₂` is linear. -/ def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient := p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h @[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) : mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f := by ext x; refl theorem comap_liftq (f : M →ₗ[R] M₂) (h) : q.comap (p.liftq f h) = (q.comap f).map (mkq p) := le_antisymm (by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩) (by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _) theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) : q.map (p.liftq f h) = (q.comap p.mkq).map f := le_antisymm (by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩) (by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩) theorem ker_liftq (f : M →ₗ[R] M₂) (h) : ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _ theorem range_liftq (f : M →ₗ[R] M₂) (h) : range (p.liftq f h) = range f := map_liftq _ _ _ _ theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ := by rw [ker_liftq, le_antisymm h h', mkq_map_self] /-- The correspondence theorem for modules: there is an order isomorphism between submodules of the quotient of `M` by `p`, and submodules of `M` larger than `p`. -/ def comap_mkq.order_iso : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≃o ((≤) : {p' : submodule R M // p ≤ p'} → {p' : submodule R M // p ≤ p'} → Prop) := { to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩, inv_fun := λ q, map p.mkq q, left_inv := λ p', map_comap_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [comap_map_mkq p, sup_of_le_right hq], ord := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm } /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.le_order_embedding : ((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) := (order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _) @[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) : comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl /-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules of `M`. -/ def comap_mkq.lt_order_embedding : ((<) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) := (comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding end submodule section set_option old_structure_cmd true /-- A linear equivalence is an invertible linear map. -/ @[nolint doc_blame has_inhabited_instance] structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w) [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] extends M →ₗ[R] M₂, M ≃ M₂ end infix ` ≃ₗ ` := linear_equiv _ notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂ namespace linear_equiv section ring variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] section variables [module R M] [module R M₂] include R instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ -- see Note [function coercion] instance : has_coe_to_fun (M ≃ₗ[R] M₂) := ⟨_, λ f, f.to_fun⟩ lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) := λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h) end section variables {module_M : module R M} {module_M₂ : module R M₂} variables (e e' : M ≃ₗ[R] M₂) @[simp] theorem coe_apply (b : M) : (e : M →ₗ[R] M₂) b = e b := rfl section variables {e e'} @[ext] lemma ext (h : (e : M → M₂) = e') : e = e' := to_equiv_injective (equiv.eq_of_to_fun_eq h) end section variables (M R) /-- The identity map is a linear equivalence. -/ @[refl] def refl [module R M] : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M } end @[simp] lemma refl_apply [module R M] (x : M) : refl R M x = x := rfl /-- Linear equivalences are symmetric. -/ @[symm] def symm : M₂ ≃ₗ[R] M := { .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv, .. e.to_equiv.symm } variables {module_M₃ : module R M₃} (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) /-- Linear equivalences are transitive. -/ @[trans] def trans : M ≃ₗ[R] M₃ := { .. e₂.to_linear_map.comp e₁.to_linear_map, .. e₁.to_equiv.trans e₂.to_equiv } /-- A linear equivalence is an additive equivalence. -/ def to_add_equiv : M ≃+ M₂ := { map_add' := e.add, .. e } @[simp] theorem trans_apply (c : M) : (e₁.trans e₂) c = e₂ (e₁ c) := rfl @[simp] theorem apply_symm_apply (c : M₂) : e (e.symm c) = c := e.6 c @[simp] theorem symm_apply_apply (b : M) : e.symm (e b) = b := e.5 b @[simp] theorem map_add (a b : M) : e (a + b) = e a + e b := e.add a b @[simp] theorem map_zero : e 0 = 0 := e.to_linear_map.map_zero @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b @[simp] theorem map_smul (c : R) (x : M) : e (c • x) = c • e x := e.smul c x @[simp] theorem map_eq_zero_iff {x : M} : e x = 0 ↔ x = 0 := e.to_add_equiv.map_eq_zero_iff theorem map_ne_zero_iff {x : M} : e x ≠ 0 ↔ x ≠ 0 := e.to_add_equiv.map_ne_zero_iff @[simp] theorem symm_symm : e.symm.symm = e := by { cases e, refl } @[simp] theorem symm_symm_apply (x : M) : e.symm.symm x = e x := by { cases e, refl } protected lemma bijective : function.bijective e := e.to_equiv.bijective protected lemma injective : function.injective e := e.to_equiv.injective protected lemma surjective : function.surjective e := e.to_equiv.surjective end section prod variables [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₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { add := λ x y, prod.ext (e₁.map_add _ _) (e₂.map_add _ _), 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 /-- 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 prod section variables {module_M : module R M} {module_M₂ : module R M₂} variables (f : M →ₗ[R] M₂) /-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that the kernel of `f` is `{0}` and the range is the universal set. -/ noncomputable def of_bijective (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ := { ..f, ..@equiv.of_bijective _ _ f ⟨linear_map.ker_eq_bot.1 hf₁, linear_map.range_eq_top.1 hf₂⟩ } @[simp] theorem of_bijective_apply {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl variables (g : M₂ →ₗ[R] M) /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl variables (e : M ≃ₗ[R] M₂) @[simp] protected theorem ker : (e : M →ₗ[R] M₂).ker = ⊥ := linear_map.ker_eq_bot.2 e.to_equiv.injective @[simp] protected theorem range : (e : M →ₗ[R] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective variables (p : submodule R M) /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl lemma eq_bot_of_equiv [module R M₂] (e : p ≃ₗ[R] (⊥ : submodule R M₂)) : p = ⊥ := begin refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _), have := e.symm_apply_apply ⟨b, hb⟩, rw [← e.coe_apply, submodule.eq_zero_of_bot_submodule ((e : p →ₗ[R] (⊥ : submodule R M₂)) ⟨b, hb⟩), ← e.symm.coe_apply, linear_map.map_zero] at this, exact congr_arg (coe : p → M) this.symm end end end ring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] include R open linear_map set_option class.instance_max_depth 39 /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R] [add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f, e₂.to_linear_map.comp $ f.comp e₁.symm.to_linear_map, inv_fun := λ f, e₂.symm.to_linear_map.comp $ f.comp e₁.to_linear_map, left_inv := λ f, by { ext x, unfold_coes, change e₂.inv_fun (e₂.to_fun $ f.to_fun $ e₁.inv_fun $ e₁.to_fun x) = _, rw [e₁.left_inv, e₂.left_inv] }, right_inv := λ f, by { ext x, unfold_coes, change e₂.to_fun (e₂.inv_fun $ f.to_fun $ e₁.to_fun $ e₁.inv_fun x) = _, rw [e₁.right_inv, e₂.right_inv] }, add := λ f g, by { ext x, change e₂.to_fun ((f + g) (e₁.inv_fun x)) = _, rw [linear_map.add_apply, e₂.add], refl }, smul := λ c f, by { ext x, change e₂.to_fun ((c • f) (e₁.inv_fun x)) = _, rw [linear_map.smul_apply, e₂.smul], refl } } /-- If M₂ and M₃ are linearly isomorphic then the two spaces of linear maps from M into M₂ and M into M₃ are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl R M) f /-- If M and M₂ are linearly isomorphic then the two spaces of linear maps from M and M₂ to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e end comm_ring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variable (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha end field end linear_equiv namespace submodule variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] variables (p : submodule R M) (q : submodule R M₂) lemma comap_le_comap_smul (f : M →ₗ[R] M₂) (c : R) : comap f q ≤ comap (c • f) q := begin rw le_def', intros m h, change c • (f m) ∈ q, change f m ∈ q at h, apply submodule.smul _ _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₗ[R] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw le_def', intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply submodule.add _ h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (M →ₗ[R] M₂) := { carrier := {f | p ≤ comap f q}, zero := by { change p ≤ comap 0 q, rw comap_zero, refine le_top, }, add := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add q f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul := λ c f h, le_trans h (comap_le_comap_smul q f c), } /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the natural map $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \} \to Hom(M/p, M₂/q)$ is linear. -/ def mapq_linear : compatible_maps p q →ₗ[R] p.quotient →ₗ[R] q.quotient := { to_fun := λ f, mapq _ _ f.val f.property, add := λ x y, by { ext m', apply quotient.induction_on' m', intros m, refl, }, smul := λ c f, by { ext m', apply quotient.induction_on' m', intros m, refl, } } end submodule namespace equiv variables [ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { add := h.add, smul := h.smul, .. e} end equiv namespace linear_map variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (f : M →ₗ[R] M₂) /-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly equivalent to the range of `f`. -/ noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range := have hr : ∀ x : f.range, ∃ y, f y = ↑x := λ x, x.2.imp $ λ _, and.right, let F : f.ker.quotient →ₗ[R] f.range := f.ker.liftq (cod_restrict f.range f $ λ x, ⟨x, trivial, rfl⟩) (λ x hx, by simp; apply subtype.coe_ext.2; simpa using hx) in { inv_fun := λx, submodule.quotient.mk (classical.some (hr x)), left_inv := by rintro ⟨x⟩; exact (submodule.quotient.eq _).2 (sub_mem_ker_iff.2 $ classical.some_spec $ hr $ F $ submodule.quotient.mk x), right_inv := λ x : range f, subtype.eq $ classical.some_spec (hr x), .. F } open submodule /-- Canonical linear map from the quotient p/(p ∩ p') to (p+p')/p', mapping x + (p ∩ p') to x + p', where p and p' are submodules of an ambient module. -/ def sup_quotient_to_quotient_inf (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient := (comap p.subtype (p ⊓ p')).liftq ((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype], exact comap_mono (inf_le_inf le_sup_left (le_refl _)) end set_option class.instance_max_depth 41 /-- Second Isomorphism Law : the canonical map from p/(p ∩ p') to (p+p')/p' as a linear isomorphism. -/ noncomputable def sup_quotient_equiv_quotient_inf (p p' : submodule R M) : (comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient := { .. sup_quotient_to_quotient_inf p p', .. show (comap p.subtype (p ⊓ p')).quotient ≃ (comap (p ⊔ p').subtype p').quotient, from @equiv.of_bijective _ _ (sup_quotient_to_quotient_inf p p') begin constructor, { rw [← ker_eq_bot, sup_quotient_to_quotient_inf, ker_liftq_eq_bot], rw [ker_comp, ker_mkq], rintros ⟨x, hx1⟩ hx2, exact ⟨hx1, hx2⟩ }, rw [← range_eq_top, sup_quotient_to_quotient_inf, range_liftq, eq_top_iff'], rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩, use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2, change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff] end } section prod lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] : is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) := ⟨λu v, rfl, λc u, rfl⟩ end prod section pi universe i variables {φ : ι → Type i} variables [∀i, add_comm_group (φ i)] [∀i, module R (φ i)] /-- `pi` construction for linear functions. From a family of linear functions it produces a linear function into a family of modules. -/ def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) := ⟨λc i, f i c, assume c d, funext $ assume i, (f i).add _ _, assume c d, funext $ assume i, (f i).smul _ _⟩ @[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) : pi f c i = f i c := rfl lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) := by ext c; simp [funext_iff]; refl lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of modules are linear maps. -/ def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i := ⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := bot_unique $ submodule.le_def'.2 $ assume a h, begin simp only [mem_infi, mem_ker, proj_apply] at h, exact (mem_bot _).2 (funext $ assume i, h i) end section variables (R φ) /-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) := begin refine linear_equiv.of_linear (pi $ λi, (proj (i:ι)).comp (submodule.subtype _)) (cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _, { assume b, simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply], assume j hjJ, have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩, rw [dif_neg this, zero_apply] }, { simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.val_prop'], ext b ⟨j, hj⟩, refl }, { ext ⟨b, hb⟩, apply subtype.coe_ext.2, ext j, have hb : ∀i ∈ J, b i = 0, { simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb }, simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply], split_ifs, { rw [dif_pos h], refl }, { rw [dif_neg h], exact (hb _ $ (hu trivial).resolve_left h).symm } } end end section variable [decidable_eq ι] /-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/ def diag (i j : ι) : φ i →ₗ[R] φ j := @function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) : (update f i b j) c = update (λi, f i c) i (b c) j := begin by_cases j = i, { rw [h, update_same, update_same] }, { rw [update_noteq h, update_noteq h] } end end section variable [decidable_eq ι] variables (R φ) /-- The standard basis of the product of `φ`. -/ def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i) lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b := by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl @[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b := by rw [std_basis_apply, update_same] lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 := by rw [std_basis_apply, update_noteq h]; refl lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ := ker_eq_bot.2 $ assume f g hfg, have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl, by simpa only [std_basis_same] lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i := by rw [std_basis, proj_pi] lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id := by ext b; simp lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 := by ext b; simp [std_basis_ne R φ _ _ h] lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) : (⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) := begin refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _), simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi], assume b hb j hj, have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩, rw [proj_std_basis_ne R φ j i this.symm, zero_apply] end lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) : (⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) := submodule.le_def'.2 begin assume b hb, simp only [mem_infi, mem_ker, proj_apply] at hb, rw ← show I.sum (λi, std_basis R φ i (b i)) = b, { ext i, rw [pi.finset_sum_apply, ← std_basis_same R φ i (b i)], refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _, assume hiI, rw [std_basis_same], exact hb _ ((hu trivial).resolve_left hiI) }, exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $ linear_map.mem_range.2 ⟨_, rfl⟩) end lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι} (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) : (⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) := begin refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _, have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [finset.coe_to_finset] }, refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _), rw [← finset.mem_coe, finset.coe_to_finset], exact le_refl _ end lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ := have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty], begin apply top_unique, convert (infi_ker_proj_le_supr_range_std_basis R φ this), exact infi_emptyset.symm, exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm) end lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) : disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) := begin refine disjoint.mono (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I) (supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _, simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply, funext_iff], rintros b ⟨hI, hJ⟩ i, classical, by_cases hiI : i ∈ I, { by_cases hiJ : i ∈ J, { exact (h ⟨hiI, hiJ⟩).elim }, { exact hJ i hiJ } }, { exact hI i hiI } end lemma std_basis_eq_single {a : R} : (λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) := begin ext i j, rw [std_basis_apply, finsupp.single_apply], split_ifs, { rw [h, function.update_same] }, { rw [function.update_noteq (ne.symm h)], refl }, end end end pi variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } instance automorphism_group.to_linear_map_is_monoid_hom : is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) := { map_one := rfl, map_mul := λ f g, rfl } /-- The group of invertible linear maps from `M` to itself -/ def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : group (general_linear_group R M) := by delta general_linear_group; apply_instance instance : inhabited (general_linear_group R M) := ⟨1⟩ /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := f.symm, val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, begin delta to_linear_equiv of_linear_equiv, cases f with f f_inv, cases f, cases f_inv, congr end, right_inv := λ f, begin delta to_linear_equiv of_linear_equiv, cases f, congr end, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : ((general_linear_equiv R M).to_equiv f).to_linear_map = f.val := by {ext, refl} end general_linear_group end linear_map
06c3269dbabd7accff0aab0941b2869f58d51e4d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Util/MonadBacktrack.lean
e9b1262e0d4a4e4c96ee41d1d367c66b4cdb0dfb
[ "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,215
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 -/ namespace Lean /-- Similar to `MonadState`, but it retrieves/restores only the "backtrackable" part of the state -/ class MonadBacktrack (s : outParam Type) (m : Type → Type) where saveState : m s restoreState : s → m Unit export MonadBacktrack (saveState restoreState) /-- Execute `x?`, but backtrack state if result is `none` or an exception was thrown. -/ def commitWhenSome? [Monad m] [MonadBacktrack s m] [MonadExcept ε m] (x? : m (Option α)) : m (Option α) := do let s ← saveState try match (← x?) with | some a => return some a | none => restoreState s return none catch ex => restoreState s throw ex /-- Execute `x?`, but backtrack state if result is `none` or an exception was thrown. If an exception is thrown, `none` is returned. That is, this function is similar to `commitWhenSome?`, but swallows the exception and returns `none`. -/ def commitWhenSomeNoEx? [Monad m] [MonadBacktrack s m] [MonadExcept ε m] (x? : m (Option α)) : m (Option α) := try commitWhenSome? x? catch _ => return none def commitWhen [Monad m] [MonadBacktrack s m] [MonadExcept ε m] (x : m Bool) : m Bool := do let s ← saveState try match (← x) with | true => pure true | false => restoreState s pure false catch ex => restoreState s throw ex def commitIfNoEx [Monad m] [MonadBacktrack s m] [MonadExcept ε m] (x : m α) : m α := do let s ← saveState try x catch ex => restoreState s throw ex def withoutModifyingState [Monad m] [MonadFinally m] [MonadBacktrack s m] (x : m α) : m α := do let s ← saveState try x finally restoreState s def observing? [Monad m] [MonadBacktrack s m] [MonadExcept ε m] (x : m α) : m (Option α) := do let s ← saveState try x catch _ => restoreState s return none instance [MonadBacktrack s m] [Monad m] : MonadBacktrack s (ExceptT ε m) where saveState := ExceptT.lift saveState restoreState s := ExceptT.lift <| restoreState s end Lean
cf01c3a08852437d75c8de42a8227b0886f98a89
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/class6.lean
3b75c188e863495e114900bf211da5542c0b991f
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
294
lean
import logic data.prod open prod inductive t1 : Type := mk1 : t1 inductive t2 : Type := mk2 : t2 theorem inhabited_t1 : inhabited t1 := inhabited.mk t1.mk1 theorem inhabited_t2 : inhabited t2 := inhabited.mk t2.mk2 instance inhabited_t1 inhabited_t2 theorem T : inhabited (t1 × t2) := _
eb5512b139e5a4dd1fa72c033b31bfb8e22fae0b
94e33a31faa76775069b071adea97e86e218a8ee
/src/set_theory/ordinal/arithmetic.lean
2f30eb33d62a759d47a7692db2cb755b841ba806
[ "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
95,991
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn, Violeta Hernández Palacios -/ import set_theory.ordinal.basic import tactic.by_contra /-! # Ordinal arithmetic Ordinals have an addition (corresponding to disjoint union) that turns them into an additive monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns them into a monoid. One can also define correspondingly a subtraction, a division, a successor function, a power function and a logarithm function. We also define limit ordinals and prove the basic induction principle on ordinals separating successor ordinals and limit ordinals, in `limit_rec_on`. ## Main definitions and results * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. * `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`. * `o₁ * o₂` is the lexicographic order on `o₂ × o₁`. * `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the divisibility predicate, and a modulo operation. * `order.succ o = o + 1` is the successor of `o`. * `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`. We also define the power function and the logarithm function on ordinals, and discuss the properties of casts of natural numbers of and of `ω` with respect to these operations. Some properties of the operations are also used to discuss general tools on ordinals: * `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor. * `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by induction at successor ordinals and at limit ordinals, then it holds for all ordinals. * `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for `a < o`. * `enum_ord`: enumerates an unbounded set of ordinals by the ordinals themselves. * `sup`, `lsub`: the supremum / least strict upper bound of an indexed family of ordinals in `Type u`, as an ordinal in `Type u`. * `bsup`, `blsub`: the supremum / least strict upper bound of a set of ordinals indexed by ordinals less than a given ordinal `o`. Various other basic arithmetic results are given in `principal.lean` instead. -/ noncomputable theory open function cardinal set equiv order open_locale classical cardinal ordinal universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} namespace ordinal /-! ### Further properties of addition on ordinals -/ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans (rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _) (rel_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := by { rw [←add_one_eq_succ, lift_add, lift_one], refl } instance add_contravariant_class_le : contravariant_class ordinal.{u} ordinal.{u} (+) (≤) := ⟨λ a b c, induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a, by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply] using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂) ((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a, have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin intro b, cases e : f (sum.inr b), { rw ← fl at e, have := f.inj' e, contradiction }, { exact ⟨_, rfl⟩ } end, let g (b) := (this b).1 in have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2, ⟨⟨⟨g, λ x y h, by injection f.inj' (by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩, λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding, initial_seg.coe_fn_to_rel_embedding, embedding.coe_fn_mk] using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩, λ a b H, begin rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩, { rw fl at h, cases h }, { rw fr at h, exact ⟨a', sum.inr.inj h⟩ } end⟩⟩⟩ theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) := (add_assoc _ _ _).symm @[simp] theorem succ_zero : succ (0 : ordinal) = 1 := zero_add 1 @[simp] theorem succ_one : succ (1 : ordinal) = 2 := rfl theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o := by rw [← succ_zero, succ_le_iff] theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 := by rw [one_le_iff_pos, ordinal.pos_iff_ne_zero] theorem succ_pos (o : ordinal) : 0 < succ o := (ordinal.zero_le o).trans_lt (lt_succ o) theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 := ne_of_gt $ succ_pos o @[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 := by simp only [←add_one_eq_succ, card_add, card_one] theorem nat_cast_succ (n : ℕ) : ↑n.succ = succ (n : ordinal) := rfl theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c := by simp only [le_antisymm_iff, add_le_add_iff_left] theorem lt_one_iff_zero {a : ordinal} : a < 1 ↔ a = 0 := by rw [←succ_zero, lt_succ_iff, ordinal.le_zero] private theorem add_lt_add_iff_left' (a) {b c : ordinal} : a + b < a + c ↔ b < c := by rw [← not_le, ← not_le, add_le_add_iff_left] instance add_covariant_class_lt : covariant_class ordinal.{u} ordinal.{u} (+) (<) := ⟨λ a b c, (add_lt_add_iff_left' a).2⟩ instance add_contravariant_class_lt : contravariant_class ordinal.{u} ordinal.{u} (+) (<) := ⟨λ a b c, (add_lt_add_iff_left' a).1⟩ instance add_swap_contravariant_class_lt : contravariant_class ordinal.{u} ordinal.{u} (swap (+)) (<) := ⟨λ a b c, lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _)⟩ theorem add_le_add_iff_right {a b : ordinal} : ∀ n : ℕ, a + n ≤ b + n ↔ a ≤ b | 0 := by simp | (n+1) := by rw [nat_cast_succ, add_succ, add_succ, succ_le_succ_iff, add_le_add_iff_right] theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b := by simp only [le_antisymm_iff, add_le_add_iff_right] /-! ### The zero ordinal -/ @[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ h, begin refine le_antisymm (le_of_not_lt $ λ hn, mk_ne_zero_iff.2 _ h) (ordinal.zero_le _), rw [← succ_le_iff, succ_zero] at hn, cases hn with f, exact ⟨f punit.star⟩ end, λ e, by simp only [e, card_zero]⟩ protected lemma one_ne_zero : (1 : ordinal) ≠ 0 := type_ne_zero_of_nonempty _ instance : nontrivial ordinal.{u} := ⟨⟨1, 0, ordinal.one_ne_zero⟩⟩ @[simp] theorem zero_lt_one : (0 : ordinal) < 1 := lt_iff_le_and_ne.2 ⟨ordinal.zero_le _, ordinal.one_ne_zero.symm⟩ instance : zero_le_one_class ordinal := ⟨zero_lt_one.le⟩ instance unique_out_one : unique (1 : ordinal).out.α := { default := enum (<) 0 (by simp), uniq := λ a, begin rw ←enum_typein (<) a, unfold default, congr, rw ←lt_one_iff_zero, apply typein_lt_self end } theorem one_out_eq (x : (1 : ordinal).out.α) : x = enum (<) 0 (by simp) := unique.eq_default x @[simp] theorem typein_one_out (x : (1 : ordinal).out.α) : typein (<) x = 0 := by rw [one_out_eq x, typein_enum] theorem le_one_iff {a : ordinal} : a ≤ 1 ↔ a = 0 ∨ a = 1 := begin refine ⟨λ ha, _, _⟩, { rcases eq_or_lt_of_le ha with rfl | ha, exacts [or.inr rfl, or.inl (lt_one_iff_zero.1 ha)], }, { rintro (rfl | rfl), exacts [zero_le_one, le_rfl], } end theorem add_eq_zero_iff {a b : ordinal} : a + b = 0 ↔ (a = 0 ∧ b = 0) := induction_on a $ λ α r _, induction_on b $ λ β s _, begin simp_rw [←type_sum_lex, type_eq_zero_iff_is_empty], exact is_empty_sum end theorem left_eq_zero_of_add_eq_zero {a b : ordinal} (h : a + b = 0) : a = 0 := (add_eq_zero_iff.1 h).1 theorem right_eq_zero_of_add_eq_zero {a b : ordinal} (h : a + b = 0) : b = 0 := (add_eq_zero_iff.1 h).2 /-! ### The predecessor of an ordinal -/ /-- The ordinal predecessor of `o` is `o'` if `o = succ o'`, and `o` otherwise. -/ def pred (o : ordinal) : ordinal := if h : ∃ a, o = succ a then classical.some h else o @[simp] theorem pred_succ (o) : pred (succ o) = o := by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩; simpa only [pred, dif_pos h] using (succ_injective $ classical.some_spec h).symm theorem pred_le_self (o) : pred o ≤ o := if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in by rw [e, pred_succ]; exact le_succ a else by rw [pred, dif_neg h] theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a := ⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact (lt_succ a).ne e, λ h, dif_neg h⟩ theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a := iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le]) (iff_not_comm.1 pred_eq_iff_not_succ).symm theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a := ⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩ theorem succ_lt_of_not_succ {o b : ordinal} (h : ¬ ∃ a, o = succ a) : succ b < o ↔ b < o := ⟨(lt_succ b).trans, λ l, lt_of_le_of_ne (succ_le_of_lt l) (λ e, h ⟨_, e.symm⟩)⟩ theorem lt_pred {a b} : a < pred b ↔ succ a < b := if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in by rw [e, pred_succ, succ_lt_succ_iff] else by simp only [pred, dif_neg h, succ_lt_of_not_succ h] theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b := le_iff_le_iff_lt_iff_lt.2 lt_pred @[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) := ⟨λ ⟨a, h⟩, let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $ h.symm ▸ lt_succ a in ⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩, λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩ @[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) := if h : ∃ a, o = succ a then by cases h with a e; simp only [e, pred_succ, lift_succ] else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)] /-! ### Limit ordinals -/ /-- A limit ordinal is an ordinal which is not zero and not a successor. -/ def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o theorem not_zero_is_limit : ¬ is_limit 0 | ⟨h, _⟩ := h rfl theorem not_succ_is_limit (o) : ¬ is_limit (succ o) | ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ o)) theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a | ⟨a, e⟩ := not_succ_is_limit a (e ▸ h) theorem succ_lt_of_is_limit {o a : ordinal} (h : is_limit o) : succ a < o ↔ a < o := ⟨(lt_succ a).trans, h.2 _⟩ theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a := le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a := ⟨λ h x l, l.le.trans h, λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn, not_lt_of_le (H _ hn) (lt_succ a)⟩ theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x := by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a) @[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o := and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0) ⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h), λ H a h, begin obtain ⟨a', rfl⟩ := lift_down h.le, rw [←lift_succ, lift_lt], exact H a' (lift_lt.1 h) end⟩ theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o := lt_of_le_of_ne (ordinal.zero_le _) h.1.symm theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o := by simpa only [succ_zero] using h.2 _ h.pos theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := h.pos | (n+1) := h.2 _ (is_limit.nat_lt n) theorem zero_or_succ_or_limit (o : ordinal) : o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o := if o0 : o = 0 then or.inl o0 else if h : ∃ a, o = succ a then or.inr (or.inl h) else or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ /-- Main induction principle of ordinals: if one can prove a property by induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/ @[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*} (o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o)) (H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o := lt_wf.fix (λ o IH, if o0 : o = 0 then by rw o0; exact H₁ else if h : ∃ a, o = succ a then by rw ← succ_pred_iff_is_succ.2 h; exact H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h) else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o @[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ := by rw [limit_rec_on, lt_wf.fix_eq, dif_pos rfl]; refl @[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) : @limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) := begin have h : ∃ a, succ o = succ a := ⟨_, rfl⟩, rw [limit_rec_on, lt_wf.fix_eq, dif_neg (succ_ne_zero o), dif_pos h], generalize : limit_rec_on._proof_2 (succ o) h = h₂, generalize : limit_rec_on._proof_3 (succ o) h = h₃, revert h₂ h₃, generalize e : pred (succ o) = o', intros, rw pred_succ at e, subst o', refl end @[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) : @limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) := by rw [limit_rec_on, lt_wf.fix_eq, dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl instance order_top_out_succ (o : ordinal) : order_top (succ o).out.α := ⟨_, le_enum_succ⟩ theorem enum_succ_eq_top {o : ordinal} : enum (<) o (by { rw type_lt, exact lt_succ o }) = (⊤ : (succ o).out.α) := rfl lemma has_succ_of_type_succ_lt {α} {r : α → α → Prop} [wo : is_well_order α r] (h : ∀ a < type r, succ a < type r) (x : α) : ∃ y, r x y := begin use enum r (succ (typein r x)) (h _ (typein_lt_type r x)), convert (enum_lt_enum (typein_lt_type r x) _).mpr (lt_succ _), rw [enum_typein] end theorem out_no_max_of_succ_lt {o : ordinal} (ho : ∀ a < o, succ a < o) : no_max_order o.out.α := ⟨has_succ_of_type_succ_lt (by rwa type_lt)⟩ lemma bounded_singleton {r : α → α → Prop} [is_well_order α r] (hr : (type r).is_limit) (x) : bounded r {x} := begin refine ⟨enum r (succ (typein r x)) (hr.2 _ (typein_lt_type r x)), _⟩, intros b hb, rw mem_singleton_iff.1 hb, nth_rewrite 0 ←enum_typein r x, rw @enum_lt_enum _ r, apply lt_succ end lemma type_subrel_lt (o : ordinal.{u}) : type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u+1} o := begin refine quotient.induction_on o _, rintro ⟨α, r, wo⟩, resetI, apply quotient.sound, constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (enum_iso r).symm end lemma mk_initial_seg (o : ordinal.{u}) : #{o' : ordinal | o' < o} = cardinal.lift.{u+1} o.card := by rw [lift_card, ←type_subrel_lt, card_type] /-! ### Normal ordinal functions -/ /-- A normal ordinal function is a strictly increasing function which is order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for `a < o`. -/ def is_normal (f : ordinal → ordinal) : Prop := (∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o → ∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2 theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} : a < f o ↔ ∃ b < o, a < f b := not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a theorem is_normal.strict_mono {f} (H : is_normal f) : strict_mono f := λ a b, limit_rec_on b (not.elim (not_lt_of_le $ ordinal.zero_le _)) (λ b IH h, (lt_or_eq_of_le (le_of_lt_succ h)).elim (λ h, (IH h).trans (H.1 _)) (λ e, e ▸ H.1 _)) (λ b l IH h, lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 le_rfl _ (l.2 _ h))) theorem is_normal.monotone {f} (H : is_normal f) : monotone f := H.strict_mono.monotone theorem is_normal_iff_strict_mono_limit (f : ordinal → ordinal) : is_normal f ↔ (strict_mono f ∧ ∀ o, is_limit o → ∀ a, (∀ b < o, f b ≤ a) → f o ≤ a) := ⟨λ hf, ⟨hf.strict_mono, λ a ha c, (hf.2 a ha c).2⟩, λ ⟨hs, hl⟩, ⟨λ a, hs (lt_succ a), λ a ha c, ⟨λ hac b hba, ((hs hba).trans_le hac).le, hl a ha c⟩⟩⟩ theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b := strict_mono.lt_iff_lt $ H.strict_mono theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_iff theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b := by simp only [le_antisymm_iff, H.le_iff] theorem is_normal.self_le {f} (H : is_normal f) (a) : a ≤ f a := lt_wf.self_le_of_strict_mono H.strict_mono a theorem is_normal.le_set {f} (H : is_normal f) (p : set ordinal) (p0 : p.nonempty) (b) (H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, a ≤ o) {o : ordinal} : f b ≤ o ↔ ∀ a ∈ p, f a ≤ o := ⟨λ h a pa, (H.le_iff.2 ((H₂ _).1 le_rfl _ pa)).trans h, λ h, begin revert H₂, refine limit_rec_on b (λ H₂, _) (λ S _ H₂, _) (λ S L _ H₂, (H.2 _ L _).2 (λ a h', _)), { cases p0 with x px, have := ordinal.le_zero.1 ((H₂ _).1 (ordinal.zero_le _) _ px), rw this at px, exact h _ px }, { rcases not_ball.1 (mt (H₂ S).2 $ (lt_succ S).not_le) with ⟨a, h₁, h₂⟩, exact (H.le_iff.2 $ succ_le_of_lt $ not_le.1 h₂).trans (h _ h₁) }, { rcases not_ball.1 (mt (H₂ a).2 h'.not_le) with ⟨b, h₁, h₂⟩, exact (H.le_iff.2 $ (not_le.1 h₂).le).trans (h _ h₁) } end⟩ theorem is_normal.le_set' {f} (H : is_normal f) (p : set α) (g : α → ordinal) (p0 : p.nonempty) (b) (H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, g a ≤ o) {o} : f b ≤ o ↔ ∀ a ∈ p, f (g a) ≤ o := (H.le_set (λ x, ∃ y, p y ∧ x = g y) (let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _ (λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1, λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans ⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩ theorem is_normal.refl : is_normal id := ⟨lt_succ, λ o l a, limit_le l⟩ theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) : is_normal (λ x, f (g x)) := ⟨λ x, H₁.lt_iff.2 (H₂.1 _), λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩ theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) : is_limit (f o) := ⟨ne_of_gt $ (ordinal.zero_le _).trans_lt $ H.lt_iff.2 l.pos, λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in (succ_le_of_lt h₂).trans_lt (H.lt_iff.2 h₁)⟩ theorem is_normal.le_iff_eq {f} (H : is_normal f) {a} : f a ≤ a ↔ f a = a := (H.self_le a).le_iff_eq theorem add_le_of_limit {a b c : ordinal} (h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c := ⟨λ h b' l, (add_le_add_left l.le _).trans h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin resetI, suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l), { cases enum _ _ l with x x, { cases this (enum s 0 h.pos) }, { exact irrefl _ (this _) } }, intros x, rw [←typein_lt_typein (sum.lex r s), typein_enum], have := H _ (h.2 _ (typein_lt_type s x)), rw [add_succ, succ_le_iff] at this, refine (type_le'.2 ⟨rel_embedding.of_monotone (λ a, _) (λ a b, _)⟩).trans_lt this, { rcases a with ⟨a | b, h⟩, { exact sum.inl a }, { exact sum.inr ⟨b, by cases h; assumption⟩ } }, { rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂; rintro ⟨⟩; constructor; assumption } end) h H⟩ theorem add_is_normal (a : ordinal) : is_normal ((+) a) := ⟨λ b, (add_lt_add_iff_left a).2 (lt_succ b), λ b l c, add_le_of_limit l⟩ theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) := (add_is_normal a).is_limit /-! ### Subtraction on ordinals-/ /-- The set in the definition of subtraction is nonempty. -/ theorem sub_nonempty {a b : ordinal} : {o | a ≤ b + o}.nonempty := ⟨a, le_add_left _ _⟩ /-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/ instance : has_sub ordinal := ⟨λ a b, Inf {o | a ≤ b + o}⟩ theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) := Inf_mem sub_nonempty theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c := ⟨λ h, (le_add_sub a b).trans (add_le_add_left h _), λ h, cInf_le' h⟩ theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le sub_le theorem add_sub_cancel (a b : ordinal) : a + b - a = b := le_antisymm (sub_le.2 $ le_rfl) ((add_le_add_iff_left a).1 $ le_add_sub _ _) theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b := h ▸ add_sub_cancel _ _ theorem sub_le_self (a b : ordinal) : a - b ≤ a := sub_le.2 $ le_add_left _ _ protected theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a := (le_add_sub a b).antisymm' begin rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l, { simp only [e, add_zero, h] }, { rw [e, add_succ, succ_le_iff, ← lt_sub, e], exact lt_succ c }, { exact (add_le_of_limit l).2 (λ c l, (lt_sub.1 l).le) } end instance : has_exists_add_of_le ordinal := ⟨λ a b h, ⟨_, (ordinal.add_sub_cancel_of_le h).symm⟩⟩ @[simp] theorem sub_zero (a : ordinal) : a - 0 = a := by simpa only [zero_add] using add_sub_cancel 0 a @[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 := by rw ← ordinal.le_zero; apply sub_le_self @[simp] theorem sub_self (a : ordinal) : a - a = 0 := by simpa only [add_zero] using add_sub_cancel a 0 protected theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b := ⟨λ h, by simpa only [h, add_zero] using le_add_sub a b, λ h, by rwa [← ordinal.le_zero, sub_le, add_zero]⟩ theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) := eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc] theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c := by rw [← sub_sub, add_sub_cancel] theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) := ⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero, λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩ @[simp] theorem one_add_omega : 1 + ω = ω := begin refine le_antisymm _ (le_add_left _ _), rw [omega, ← lift_one.{0}, ← lift_add, lift_le, ← type_unit, ← type_sum_lex], refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩, { apply sum.rec, exact λ _, 0, exact nat.succ }, { intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H; [cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] } end @[simp, priority 990] theorem one_add_of_omega_le {o} (h : ω ≤ o) : 1 + o = o := by rw [← ordinal.add_sub_cancel_of_le h, ← add_assoc, one_add_omega] /-! ### Multiplication of ordinals-/ /-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on `o₂ × o₁`. -/ instance : monoid ordinal.{u} := { mul := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.prod_lex_congr g f⟩, one := 1, mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin rcases a with ⟨⟨a₁, a₂⟩, a₃⟩, rcases b with ⟨⟨b₁, b₂⟩, b₃⟩, simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc] end⟩⟩, mul_one := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩; simp only [prod.lex_def, empty_relation, false_or]; simp only [eq_self_iff_true, true_and]; refl⟩⟩, one_mul := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩; simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ } @[simp] theorem type_prod_lex {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type (prod.lex s r) = type r * type s := rfl private theorem mul_eq_zero' {a b : ordinal} : a * b = 0 ↔ a = 0 ∨ b = 0 := induction_on a $ λ α _ _, induction_on b $ λ β _ _, begin simp_rw [←type_prod_lex, type_eq_zero_iff_is_empty], rw or_comm, exact is_empty_prod end instance : monoid_with_zero ordinal := { zero := 0, mul_zero := λ a, mul_eq_zero'.2 $ or.inr rfl, zero_mul := λ a, mul_eq_zero'.2 $ or.inl rfl, ..ordinal.monoid } instance : no_zero_divisors ordinal := ⟨λ a b, mul_eq_zero'.1⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans (rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _) (rel_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem card_mul (a b) : card (a * b) = card a * card b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, mul_comm (mk β) (mk α) instance : left_distrib_class ordinal.{u} := ⟨λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def, sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr, sum_prod_distrib_apply_left, sum_prod_distrib_apply_right]; simp only [sum.inl.inj_iff, true_or, false_and, false_or] end⟩⟩⟩ theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one a b instance mul_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (*) (≤) := ⟨λ c a b, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, (f a.1, a.2)) (λ a b h, _)⟩, clear_, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.2 h') }, { exact prod.lex.right _ h' } end⟩ instance mul_swap_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (swap (*)) (≤) := ⟨λ c a b, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, (a.1, f a.2)) (λ a b h, _)⟩, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ h' }, { exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.2 h') } end⟩ theorem le_mul_left (a : ordinal) {b : ordinal} (hb : 0 < b) : a ≤ a * b := by { convert mul_le_mul_left' (one_le_iff_pos.2 hb) a, rw mul_one a } theorem le_mul_right (a : ordinal) {b : ordinal} (hb : 0 < b) : a ≤ b * a := by { convert mul_le_mul_right' (one_le_iff_pos.2 hb) a, rw one_mul a } private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s] {c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c) (l : c < type r * type s) : false := begin suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l), { cases enum _ _ l with b a, exact irrefl _ (this _ _) }, intros a b, rw [←typein_lt_typein (prod.lex s r), typein_enum], have := H _ (h.2 _ (typein_lt_type s b)), rw mul_succ at this, have := ((add_lt_add_iff_left _).2 (typein_lt_type _ a)).trans_le this, refine (type_le'.2 _).trans_lt this, constructor, refine rel_embedding.of_monotone (λ a, _) (λ a b, _), { rcases a with ⟨⟨b', a'⟩, h⟩, by_cases e : b = b', { refine sum.inr ⟨a', _⟩, subst e, cases h with _ _ _ _ h _ _ _ h, { exact (irrefl _ h).elim }, { exact h } }, { refine sum.inl (⟨b', _⟩, a'), cases h with _ _ _ _ h _ _ _ h, { exact h }, { exact (e rfl).elim } } }, { rcases a with ⟨⟨b₁, a₁⟩, h₁⟩, rcases b with ⟨⟨b₂, a₂⟩, h₂⟩, intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂, { substs b₁ b₂, simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true, dif_pos, sum.lex_inr_inr] using h }, { subst b₁, simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true, or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢, cases h₂; [exact asymm h h₂_h, exact e₂ rfl] }, { simp [e₂, dif_neg e₁, show b₂ ≠ b₁, by cc] }, { simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk, sum.lex_inl_inl] using h } } end theorem mul_le_of_limit {a b c : ordinal} (h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c := ⟨λ h b' l, (mul_le_mul_left' l.le _).trans h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _, by exactI mul_le_of_limit_aux) h H⟩ theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) := ⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h, λ b l c, mul_le_of_limit l⟩ theorem lt_mul_of_limit {a b c : ordinal} (h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' := by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h) theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c := (mul_is_normal a0).lt_iff theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c := (mul_is_normal a0).le_iff theorem mul_lt_mul_of_pos_left {a b c : ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b := (mul_lt_mul_iff_left c0).2 h theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b := by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁ theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := by simpa only [ordinal.pos_iff_ne_zero] using mul_pos theorem le_of_mul_le_mul_left {a b c : ordinal} (h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b := le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c := (mul_is_normal a0).inj theorem mul_is_limit {a b : ordinal} (a0 : 0 < a) : is_limit b → is_limit (a * b) := (mul_is_normal a0).is_limit theorem mul_is_limit_left {a b : ordinal} (l : is_limit a) (b0 : 0 < b) : is_limit (a * b) := begin rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb, { exact b0.false.elim }, { rw mul_succ, exact add_is_limit _ l }, { exact mul_is_limit l.pos lb } end theorem smul_eq_mul : ∀ (n : ℕ) (a : ordinal), n • a = a * n | 0 a := by rw [zero_smul, nat.cast_zero, mul_zero] | (n + 1) a := by rw [succ_nsmul', nat.cast_add, mul_add, nat.cast_one, mul_one, smul_eq_mul] /-! ### Division on ordinals -/ /-- The set in the definition of division is nonempty. -/ theorem div_nonempty {a b : ordinal} (h : b ≠ 0) : {o | a < b * succ o}.nonempty := ⟨a, succ_le_iff.1 $ by simpa only [succ_zero, one_mul] using mul_le_mul_right' (succ_le_of_lt (ordinal.pos_iff_ne_zero.2 h)) (succ a)⟩ /-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_div ordinal := ⟨λ a b, if h : b = 0 then 0 else Inf {o | a < b * succ o}⟩ @[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl lemma div_def (a) {b : ordinal} (h : b ≠ 0) : a / b = Inf {o | a < b * succ o} := dif_neg h theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) := by rw div_def a h; exact Inf_mem (div_nonempty h) theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b := by simpa only [mul_succ] using lt_mul_succ_div a h theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c := ⟨λ h, (lt_mul_succ_div a b0).trans_le (mul_le_mul_left' (succ_le_succ_iff.2 h) _), λ h, by rw div_def a b0; exact cInf_le' h⟩ theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b := by rw [← not_le, div_le c0, not_lt] theorem le_div {a b c : ordinal} (c0 : c ≠ 0) : a ≤ b / c ↔ c * a ≤ b := begin apply limit_rec_on a, { simp only [mul_zero, ordinal.zero_le] }, { intros, rw [succ_le_iff, lt_div c0] }, { simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} } end theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) : a / b < c ↔ a < b * c := lt_iff_lt_of_le_iff_le $ le_div b0 theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c := if b0 : b = 0 then by simp only [b0, div_zero, ordinal.zero_le] else (div_le b0).2 $ h.trans_lt $ mul_lt_mul_of_pos_left (lt_succ c) (ordinal.pos_iff_ne_zero.2 b0) theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b := lt_imp_lt_of_le_imp_le div_le_of_le_mul @[simp] theorem zero_div (a : ordinal) : 0 / a = 0 := ordinal.le_zero.1 $ div_le_of_le_mul $ ordinal.zero_le _ theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a := if b0 : b = 0 then by simp only [b0, zero_mul, ordinal.zero_le] else (le_div b0).1 le_rfl theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b := begin apply le_antisymm, { apply (div_le b0).2, rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left], apply lt_mul_div_add _ b0 }, { rw [le_div b0, mul_add, add_le_add_iff_left], apply mul_div_le } end theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 := begin rw [←ordinal.le_zero, div_le $ ordinal.pos_iff_ne_zero.1 $ (ordinal.zero_le _).trans_lt h], simpa only [succ_zero, mul_one] using h end @[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a := by simpa only [add_zero, zero_div] using mul_add_div a b0 0 @[simp] theorem div_one (a : ordinal) : a / 1 = a := by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero @[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 := by simpa only [mul_one] using mul_div_cancel 1 h theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c := if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else eq_of_forall_ge_iff $ λ d, by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0] theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) := begin split; intro h, { by_cases h' : b = 0, { rw [h', add_zero] at h, right, exact ⟨h', h⟩ }, left, rw [←add_sub_cancel a b], apply sub_is_limit h, suffices : a + 0 < a + b, simpa only [add_zero], rwa [add_lt_add_iff_left, ordinal.pos_iff_ne_zero] }, rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero] end theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c) | a _ c ⟨b, rfl⟩ := ⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩ theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b | a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0] theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b | a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left' (one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0)) a theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b := if a0 : a = 0 then by subst a; exact (eq_zero_of_zero_dvd h₁).symm else if b0 : b = 0 then by subst b; exact eq_zero_of_zero_dvd h₂ else (le_of_dvd b0 h₁).antisymm (le_of_dvd a0 h₂) instance : is_antisymm ordinal (∣) := ⟨@dvd_antisymm⟩ /-- `a % b` is the unique ordinal `o'` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩ theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl @[simp] theorem mod_zero (a : ordinal) : a % 0 = a := by simp only [mod_def, div_zero, zero_mul, sub_zero] theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a := by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero] @[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 := by simp only [mod_def, zero_div, mul_zero, sub_self] theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a := ordinal.add_sub_cancel_of_le $ mul_div_le _ _ theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b := (add_lt_add_iff_left (b * (a / b))).1 $ by rw div_add_mod; exact lt_mul_div_add a h @[simp] theorem mod_self (a : ordinal) : a % a = 0 := if a0 : a = 0 then by simp only [a0, zero_mod] else by simp only [mod_def, div_self a0, mul_one, sub_self] @[simp] theorem mod_one (a : ordinal) : a % 1 = 0 := by simp only [mod_def, div_one, one_mul, sub_self] theorem dvd_of_mod_eq_zero {a b : ordinal} (H : a % b = 0) : b ∣ a := ⟨a / b, by simpa [H] using (div_add_mod a b).symm⟩ theorem mod_eq_zero_of_dvd {a b : ordinal} (H : b ∣ a) : a % b = 0 := begin rcases H with ⟨c, rfl⟩, rcases eq_or_ne b 0 with rfl | hb, { simp }, { simp [mod_def, hb] } end theorem dvd_iff_mod_eq_zero {a b : ordinal} : b ∣ a ↔ a % b = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-! ### Families of ordinals There are two kinds of indexed families that naturally arise when dealing with ordinals: those indexed by some type in the appropriate universe, and those indexed by ordinals less than another. The following API allows one to convert from one kind of family to the other. In many cases, this makes it easy to prove claims about one kind of family via the corresponding claim on the other. -/ /-- Converts a family indexed by a `Type u` to one indexed by an `ordinal.{u}` using a specified well-ordering. -/ def bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) : Π a < type r, α := λ a ha, f (enum r a ha) /-- Converts a family indexed by a `Type u` to one indexed by an `ordinal.{u}` using a well-ordering given by the axiom of choice. -/ def bfamily_of_family {ι : Type u} : (ι → α) → Π a < type (@well_ordering_rel ι), α := bfamily_of_family' well_ordering_rel /-- Converts a family indexed by an `ordinal.{u}` to one indexed by an `Type u` using a specified well-ordering. -/ def family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f : Π a < o, α) : ι → α := λ i, f (typein r i) (by { rw ←ho, exact typein_lt_type r i }) /-- Converts a family indexed by an `ordinal.{u}` to one indexed by a `Type u` using a well-ordering given by the axiom of choice. -/ def family_of_bfamily (o : ordinal) (f : Π a < o, α) : o.out.α → α := family_of_bfamily' (<) (type_lt o) f @[simp] theorem bfamily_of_family'_typein {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) (i) : bfamily_of_family' r f (typein r i) (typein_lt_type r i) = f i := by simp only [bfamily_of_family', enum_typein] @[simp] theorem bfamily_of_family_typein {ι} (f : ι → α) (i) : bfamily_of_family f (typein _ i) (typein_lt_type _ i) = f i := bfamily_of_family'_typein _ f i @[simp] theorem family_of_bfamily'_enum {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f : Π a < o, α) (i hi) : family_of_bfamily' r ho f (enum r i (by rwa ho)) = f i hi := by simp only [family_of_bfamily', typein_enum] @[simp] theorem family_of_bfamily_enum (o : ordinal) (f : Π a < o, α) (i hi) : family_of_bfamily o f (enum (<) i (by { convert hi, exact type_lt _ })) = f i hi := family_of_bfamily'_enum _ (type_lt o) f _ _ /-- The range of a family indexed by ordinals. -/ def brange (o : ordinal) (f : Π a < o, α) : set α := {a | ∃ i hi, f i hi = a} theorem mem_brange {o : ordinal} {f : Π a < o, α} {a} : a ∈ brange o f ↔ ∃ i hi, f i hi = a := iff.rfl theorem mem_brange_self {o} (f : Π a < o, α) (i hi) : f i hi ∈ brange o f := ⟨i, hi, rfl⟩ @[simp] theorem range_family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f : Π a < o, α) : range (family_of_bfamily' r ho f) = brange o f := begin refine set.ext (λ a, ⟨_, _⟩), { rintro ⟨b, rfl⟩, apply mem_brange_self }, { rintro ⟨i, hi, rfl⟩, exact ⟨_, family_of_bfamily'_enum _ _ _ _ _⟩ } end @[simp] theorem range_family_of_bfamily {o} (f : Π a < o, α) : range (family_of_bfamily o f) = brange o f := range_family_of_bfamily' _ _ f @[simp] theorem brange_bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) : brange _ (bfamily_of_family' r f) = range f := begin refine set.ext (λ a, ⟨_, _⟩), { rintro ⟨i, hi, rfl⟩, apply mem_range_self }, { rintro ⟨b, rfl⟩, exact ⟨_, _, bfamily_of_family'_typein _ _ _⟩ }, end @[simp] theorem brange_bfamily_of_family {ι : Type u} (f : ι → α) : brange _ (bfamily_of_family f) = range f := brange_bfamily_of_family' _ _ @[simp] theorem brange_const {o : ordinal} (ho : o ≠ 0) {c : α} : brange o (λ _ _, c) = {c} := begin rw ←range_family_of_bfamily, exact @set.range_const _ o.out.α (out_nonempty_iff_ne_zero.2 ho) c end theorem comp_bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) (g : α → β) : (λ i hi, g (bfamily_of_family' r f i hi)) = bfamily_of_family' r (g ∘ f) := rfl theorem comp_bfamily_of_family {ι : Type u} (f : ι → α) (g : α → β) : (λ i hi, g (bfamily_of_family f i hi)) = bfamily_of_family (g ∘ f) := rfl theorem comp_family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f : Π a < o, α) (g : α → β) : g ∘ (family_of_bfamily' r ho f) = family_of_bfamily' r ho (λ i hi, g (f i hi)) := rfl theorem comp_family_of_bfamily {o} (f : Π a < o, α) (g : α → β) : g ∘ (family_of_bfamily o f) = family_of_bfamily o (λ i hi, g (f i hi)) := rfl /-! ### Supremum of a family of ordinals -/ /-- The supremum of a family of ordinals -/ def sup {ι : Type u} (f : ι → ordinal.{max u v}) : ordinal.{max u v} := supr f @[simp] theorem Sup_eq_sup {ι : Type u} (f : ι → ordinal.{max u v}) : Sup (set.range f) = sup f := rfl /-- The range of an indexed ordinal function, whose outputs live in a higher universe than the inputs, is always bounded above. See `ordinal.lsub` for an explicit bound. -/ theorem bdd_above_range {ι : Type u} (f : ι → ordinal.{max u v}) : bdd_above (set.range f) := ⟨(supr (succ ∘ card ∘ f)).ord, begin rintros a ⟨i, rfl⟩, exact le_of_lt (cardinal.lt_ord.2 ((lt_succ _).trans_le (le_csupr (bdd_above_range _) _))) end⟩ theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f := λ i, le_cSup (bdd_above_range f) (mem_range_self i) theorem sup_le_iff {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := (cSup_le_iff' (bdd_above_range f)).trans (by simp) theorem sup_le {ι} {f : ι → ordinal} {a} : (∀ i, f i ≤ a) → sup f ≤ a := sup_le_iff.2 theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i := by simpa only [not_forall, not_le] using not_congr (@sup_le_iff _ f a) theorem ne_sup_iff_lt_sup {ι} {f : ι → ordinal} : (∀ i, f i ≠ sup f) ↔ ∀ i, f i < sup f := ⟨λ hf _, lt_of_le_of_ne (le_sup _ _) (hf _), λ hf _, ne_of_lt (hf _)⟩ theorem sup_not_succ_of_ne_sup {ι} {f : ι → ordinal} (hf : ∀ i, f i ≠ sup f) {a} (hao : a < sup f) : succ a < sup f := begin by_contra' hoa, exact hao.not_le (sup_le $ λ i, le_of_lt_succ $ (lt_of_le_of_ne (le_sup _ _) (hf i)).trans_le hoa) end @[simp] theorem sup_eq_zero_iff {ι} {f : ι → ordinal} : sup f = 0 ↔ ∀ i, f i = 0 := begin refine ⟨λ h i, _, λ h, le_antisymm (sup_le (λ i, ordinal.le_zero.2 (h i))) (ordinal.zero_le _)⟩, rw [←ordinal.le_zero, ←h], exact le_sup f i end theorem is_normal.sup {f} (H : is_normal f) {ι} (g : ι → ordinal) (h : nonempty ι) : f (sup g) = sup (f ∘ g) := eq_of_forall_ge_iff $ λ a, by rw [sup_le_iff, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)]; intros; simp only [sup_le_iff, true_implies_iff]; tauto @[simp] theorem sup_empty {ι} [is_empty ι] (f : ι → ordinal) : sup f = 0 := csupr_of_empty f @[simp] theorem sup_const {ι} [hι : nonempty ι] (o : ordinal) : sup (λ _ : ι, o) = o := csupr_const @[simp] theorem sup_unique {ι} [unique ι] (f : ι → ordinal) : sup f = f default := supr_unique theorem sup_le_of_range_subset {ι ι'} {f : ι → ordinal} {g : ι' → ordinal} (h : set.range f ⊆ set.range g) : sup.{u (max v w)} f ≤ sup.{v (max u w)} g := sup_le $ λ i, match h (mem_range_self i) with ⟨j, hj⟩ := hj ▸ le_sup _ _ end theorem sup_eq_of_range_eq {ι ι'} {f : ι → ordinal} {g : ι' → ordinal} (h : set.range f = set.range g) : sup.{u (max v w)} f = sup.{v (max u w)} g := (sup_le_of_range_subset h.le).antisymm (sup_le_of_range_subset.{v u w} h.ge) lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α) (h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) := (not_bounded_iff _).1 $ λ ⟨x, hx⟩, not_lt_of_le h $ lt_of_le_of_lt (sup_le $ λ y, le_of_lt $ (typein_lt_typein r).2 $ hx _ $ mem_range_self y) (typein_lt_type r x) theorem le_sup_shrink_equiv {s : set ordinal.{u}} (hs : small.{u} s) (a) (ha : a ∈ s) : a ≤ sup.{u u} (λ x, ((@equiv_shrink s hs).symm x).val) := by { convert le_sup.{u u} _ ((@equiv_shrink s hs) ⟨a, ha⟩), rw symm_apply_apply } theorem small_Iio (o : ordinal.{u}) : small.{u} (set.Iio o) := let f : o.out.α → set.Iio o := λ x, ⟨typein (<) x, typein_lt_self x⟩ in let hf : surjective f := λ b, ⟨enum (<) b.val (by { rw type_lt, exact b.prop }), subtype.ext (typein_enum _ _)⟩ in small_of_surjective hf theorem bdd_above_iff_small {s : set ordinal.{u}} : bdd_above s ↔ small.{u} s := ⟨λ ⟨a, h⟩, @small_subset _ _ _ (by exact λ b hb, lt_succ_iff.2 (h hb)) (small_Iio (succ a)), λ h, ⟨sup.{u u} (λ x, ((@equiv_shrink s h).symm x).val), le_sup_shrink_equiv h⟩⟩ theorem sup_eq_Sup {s : set ordinal.{u}} (hs : small.{u} s) : sup.{u u} (λ x, (@equiv_shrink s hs).symm x) = Sup s := let hs' := bdd_above_iff_small.2 hs in ((cSup_le_iff' hs').2 (le_sup_shrink_equiv hs)).antisymm' (sup_le (λ x, le_cSup hs' (subtype.mem _))) theorem Sup_ord {s : set cardinal.{u}} (hs : bdd_above s) : (Sup s).ord = Sup (ord '' s) := eq_of_forall_ge_iff $ λ a, begin rw [cSup_le_iff' (bdd_above_iff_small.2 (@small_image _ _ _ s (cardinal.bdd_above_iff_small.1 hs))), ord_le, cSup_le_iff' hs], simp [ord_le] end theorem supr_ord {ι} {f : ι → cardinal} (hf : bdd_above (range f)) : (supr f).ord = ⨆ i, (f i).ord := by { unfold supr, convert Sup_ord hf, rw range_comp } private theorem sup_le_sup {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop) [is_well_order ι r] [is_well_order ι' r'] {o} (ho : type r = o) (ho' : type r' = o) (f : Π a < o, ordinal) : sup (family_of_bfamily' r ho f) ≤ sup (family_of_bfamily' r' ho' f) := sup_le $ λ i, begin cases typein_surj r' (by { rw [ho', ←ho], exact typein_lt_type r i }) with j hj, simp_rw [family_of_bfamily', ←hj], apply le_sup end theorem sup_eq_sup {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop) [is_well_order ι r] [is_well_order ι' r'] {o : ordinal.{u}} (ho : type r = o) (ho' : type r' = o) (f : Π a < o, ordinal.{max u v}) : sup (family_of_bfamily' r ho f) = sup (family_of_bfamily' r' ho' f) := sup_eq_of_range_eq.{u u v} (by simp) /-- The supremum of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. This is a special case of `sup` over the family provided by `family_of_bfamily`. -/ def bsup (o : ordinal.{u}) (f : Π a < o, ordinal.{max u v}) : ordinal.{max u v} := sup (family_of_bfamily o f) @[simp] theorem sup_eq_bsup {o} (f : Π a < o, ordinal) : sup (family_of_bfamily o f) = bsup o f := rfl @[simp] theorem sup_eq_bsup' {o ι} (r : ι → ι → Prop) [is_well_order ι r] (ho : type r = o) (f) : sup (family_of_bfamily' r ho f) = bsup o f := sup_eq_sup r _ ho _ f @[simp] theorem Sup_eq_bsup {o} (f : Π a < o, ordinal) : Sup (brange o f) = bsup o f := by { congr, rw range_family_of_bfamily } @[simp] theorem bsup_eq_sup' {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → ordinal) : bsup _ (bfamily_of_family' r f) = sup f := by simp only [←sup_eq_bsup' r, enum_typein, family_of_bfamily', bfamily_of_family'] theorem bsup_eq_bsup {ι : Type u} (r r' : ι → ι → Prop) [is_well_order ι r] [is_well_order ι r'] (f : ι → ordinal) : bsup _ (bfamily_of_family' r f) = bsup _ (bfamily_of_family' r' f) := by rw [bsup_eq_sup', bsup_eq_sup'] @[simp] theorem bsup_eq_sup {ι} (f : ι → ordinal) : bsup _ (bfamily_of_family f) = sup f := bsup_eq_sup' _ f @[congr] lemma bsup_congr {o₁ o₂ : ordinal} (f : Π a < o₁, ordinal) (ho : o₁ = o₂) : bsup o₁ f = bsup o₂ (λ a h, f a (h.trans_eq ho.symm)) := by subst ho theorem bsup_le_iff {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a := sup_le_iff.trans ⟨λ h i hi, by { rw ←family_of_bfamily_enum o f, exact h _ }, λ h i, h _ _⟩ theorem bsup_le {o : ordinal} {f : Π b < o, ordinal} {a} : (∀ i h, f i h ≤ a) → bsup.{u v} o f ≤ a := bsup_le_iff.2 theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f := bsup_le_iff.1 le_rfl _ _ theorem lt_bsup {o} (f : Π a < o, ordinal) {a} : a < bsup o f ↔ ∃ i hi, a < f i hi := by simpa only [not_forall, not_le] using not_congr (@bsup_le_iff _ f a) theorem is_normal.bsup {f} (H : is_normal f) {o} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0), f (bsup o g) = bsup o (λ a h, f (g a h)) := induction_on o $ λ α r _ g h, by { resetI, rw [←sup_eq_bsup' r, H.sup _ (type_ne_zero_iff_nonempty.1 h), ←sup_eq_bsup' r]; refl } theorem lt_bsup_of_ne_bsup {o : ordinal} {f : Π a < o, ordinal} : (∀ i h, f i h ≠ o.bsup f) ↔ ∀ i h, f i h < o.bsup f := ⟨λ hf _ _, lt_of_le_of_ne (le_bsup _ _ _) (hf _ _), λ hf _ _, ne_of_lt (hf _ _)⟩ theorem bsup_not_succ_of_ne_bsup {o} {f : Π a < o, ordinal} (hf : ∀ {i : ordinal} (h : i < o), f i h ≠ o.bsup f) (a) : a < bsup o f → succ a < bsup o f := by { rw ←sup_eq_bsup at *, exact sup_not_succ_of_ne_sup (λ i, hf _) } @[simp] theorem bsup_eq_zero_iff {o} {f : Π a < o, ordinal} : bsup o f = 0 ↔ ∀ i hi, f i hi = 0 := begin refine ⟨λ h i hi, _, λ h, le_antisymm (bsup_le (λ i hi, ordinal.le_zero.2 (h i hi))) (ordinal.zero_le _)⟩, rw [←ordinal.le_zero, ←h], exact le_bsup f i hi, end theorem lt_bsup_of_limit {o : ordinal} {f : Π a < o, ordinal} (hf : ∀ {a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha') (ho : ∀ a < o, succ a < o) (i h) : f i h < bsup o f := (hf _ _ $ lt_succ i).trans_le (le_bsup f (succ i) $ ho _ h) theorem bsup_succ_of_mono {o : ordinal} {f : Π a < succ o, ordinal} (hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : bsup _ f = f o (lt_succ o) := le_antisymm (bsup_le $ λ i hi, hf _ _ $ le_of_lt_succ hi) (le_bsup _ _ _) @[simp] theorem bsup_zero (f : Π a < (0 : ordinal), ordinal) : bsup 0 f = 0 := bsup_eq_zero_iff.2 (λ i hi, (ordinal.not_lt_zero i hi).elim) theorem bsup_const {o : ordinal} (ho : o ≠ 0) (a : ordinal) : bsup o (λ _ _, a) = a := le_antisymm (bsup_le (λ _ _, le_rfl)) (le_bsup _ 0 (ordinal.pos_iff_ne_zero.2 ho)) @[simp] theorem bsup_one (f : Π a < (1 : ordinal), ordinal) : bsup 1 f = f 0 zero_lt_one := by simp_rw [←sup_eq_bsup, sup_unique, family_of_bfamily, family_of_bfamily', typein_one_out] theorem bsup_le_of_brange_subset {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : brange o f ⊆ brange o' g) : bsup.{u (max v w)} o f ≤ bsup.{v (max u w)} o' g := bsup_le $ λ i hi, begin obtain ⟨j, hj, hj'⟩ := h ⟨i, hi, rfl⟩, rw ←hj', apply le_bsup end theorem bsup_eq_of_brange_eq {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : brange o f = brange o' g) : bsup.{u (max v w)} o f = bsup.{v (max u w)} o' g := (bsup_le_of_brange_subset h.le).antisymm (bsup_le_of_brange_subset.{v u w} h.ge) /-- The least strict upper bound of a family of ordinals. -/ def lsub {ι} (f : ι → ordinal) : ordinal := sup (succ ∘ f) @[simp] theorem sup_eq_lsub {ι} (f : ι → ordinal) : sup (succ ∘ f) = lsub f := rfl theorem lsub_le_iff {ι} {f : ι → ordinal} {a} : lsub f ≤ a ↔ ∀ i, f i < a := by { convert sup_le_iff, simp only [succ_le_iff] } theorem lsub_le {ι} {f : ι → ordinal} {a} : (∀ i, f i < a) → lsub f ≤ a := lsub_le_iff.2 theorem lt_lsub {ι} (f : ι → ordinal) (i) : f i < lsub f := succ_le_iff.1 (le_sup _ i) theorem lt_lsub_iff {ι} {f : ι → ordinal} {a} : a < lsub f ↔ ∃ i, a ≤ f i := by simpa only [not_forall, not_lt, not_le] using not_congr (@lsub_le_iff _ f a) theorem sup_le_lsub {ι} (f : ι → ordinal) : sup f ≤ lsub f := sup_le $ λ i, (lt_lsub f i).le theorem lsub_le_sup_succ {ι} (f : ι → ordinal) : lsub f ≤ succ (sup f) := lsub_le $ λ i, lt_succ_iff.2 (le_sup f i) theorem sup_eq_lsub_or_sup_succ_eq_lsub {ι} (f : ι → ordinal) : sup f = lsub f ∨ succ (sup f) = lsub f := begin cases eq_or_lt_of_le (sup_le_lsub f), { exact or.inl h }, { exact or.inr ((succ_le_of_lt h).antisymm (lsub_le_sup_succ f)) } end theorem sup_succ_le_lsub {ι} (f : ι → ordinal) : succ (sup f) ≤ lsub f ↔ ∃ i, f i = sup f := begin refine ⟨λ h, _, _⟩, { by_contra' hf, exact (succ_le_iff.1 h).ne ((sup_le_lsub f).antisymm (lsub_le (ne_sup_iff_lt_sup.1 hf))) }, rintro ⟨_, hf⟩, rw [succ_le_iff, ←hf], exact lt_lsub _ _ end theorem sup_succ_eq_lsub {ι} (f : ι → ordinal) : succ (sup f) = lsub f ↔ ∃ i, f i = sup f := (lsub_le_sup_succ f).le_iff_eq.symm.trans (sup_succ_le_lsub f) theorem sup_eq_lsub_iff_succ {ι} (f : ι → ordinal) : sup f = lsub f ↔ ∀ a < lsub f, succ a < lsub f := begin refine ⟨λ h, _, λ hf, le_antisymm (sup_le_lsub f) (lsub_le (λ i, _))⟩, { rw ←h, exact λ a, sup_not_succ_of_ne_sup (λ i, (lsub_le_iff.1 (le_of_eq h.symm) i).ne) }, by_contra' hle, have heq := (sup_succ_eq_lsub f).2 ⟨i, le_antisymm (le_sup _ _) hle⟩, have := hf _ (by { rw ←heq, exact lt_succ (sup f) }), rw heq at this, exact this.false end theorem sup_eq_lsub_iff_lt_sup {ι} (f : ι → ordinal) : sup f = lsub f ↔ ∀ i, f i < sup f := ⟨λ h i, (by { rw h, apply lt_lsub }), λ h, le_antisymm (sup_le_lsub f) (lsub_le h)⟩ @[simp] lemma lsub_empty {ι} [h : is_empty ι] (f : ι → ordinal) : lsub f = 0 := by { rw [←ordinal.le_zero, lsub_le_iff], exact h.elim } lemma lsub_pos {ι} [h : nonempty ι] (f : ι → ordinal) : 0 < lsub f := h.elim $ λ i, (ordinal.zero_le _).trans_lt (lt_lsub f i) @[simp] theorem lsub_eq_zero_iff {ι} {f : ι → ordinal} : lsub f = 0 ↔ is_empty ι := begin refine ⟨λ h, ⟨λ i, _⟩, λ h, @lsub_empty _ h _⟩, have := @lsub_pos _ ⟨i⟩ f, rw h at this, exact this.false end @[simp] theorem lsub_const {ι} [hι : nonempty ι] (o : ordinal) : lsub (λ _ : ι, o) = succ o := sup_const (succ o) @[simp] theorem lsub_unique {ι} [hι : unique ι] (f : ι → ordinal) : lsub f = succ (f default) := sup_unique _ theorem lsub_le_of_range_subset {ι ι'} {f : ι → ordinal} {g : ι' → ordinal} (h : set.range f ⊆ set.range g) : lsub.{u (max v w)} f ≤ lsub.{v (max u w)} g := sup_le_of_range_subset (by convert set.image_subset _ h; apply set.range_comp) theorem lsub_eq_of_range_eq {ι ι'} {f : ι → ordinal} {g : ι' → ordinal} (h : set.range f = set.range g) : lsub.{u (max v w)} f = lsub.{v (max u w)} g := (lsub_le_of_range_subset h.le).antisymm (lsub_le_of_range_subset.{v u w} h.ge) theorem lsub_not_mem_range {ι} (f : ι → ordinal) : lsub f ∉ set.range f := λ ⟨i, h⟩, h.not_lt (lt_lsub f i) theorem nonempty_compl_range {ι : Type u} (f : ι → ordinal.{max u v}) : (set.range f)ᶜ.nonempty := ⟨_, lsub_not_mem_range f⟩ @[simp] theorem lsub_typein (o : ordinal) : lsub.{u u} (typein ((<) : o.out.α → o.out.α → Prop)) = o := (lsub_le.{u u} typein_lt_self).antisymm begin by_contra' h, nth_rewrite 0 ←type_lt o at h, simpa [typein_enum] using lt_lsub.{u u} (typein (<)) (enum (<) _ h) end theorem sup_typein_limit {o : ordinal} (ho : ∀ a, a < o → succ a < o) : sup.{u u} (typein ((<) : o.out.α → o.out.α → Prop)) = o := by rw (sup_eq_lsub_iff_succ.{u u} (typein (<))).2; rwa lsub_typein o @[simp] theorem sup_typein_succ {o : ordinal} : sup.{u u} (typein ((<) : (succ o).out.α → (succ o).out.α → Prop)) = o := begin cases sup_eq_lsub_or_sup_succ_eq_lsub.{u u} (typein ((<) : (succ o).out.α → (succ o).out.α → Prop)) with h h, { rw sup_eq_lsub_iff_succ at h, simp only [lsub_typein] at h, exact (h o (lt_succ o)).false.elim }, rw [←succ_eq_succ_iff, h], apply lsub_typein end /-- The least strict upper bound of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. This is to `lsub` as `bsup` is to `sup`. -/ def blsub (o : ordinal.{u}) (f : Π a < o, ordinal.{max u v}) : ordinal.{max u v} := o.bsup (λ a ha, succ (f a ha)) @[simp] theorem bsup_eq_blsub (o : ordinal) (f : Π a < o, ordinal) : bsup o (λ a ha, succ (f a ha)) = blsub o f := rfl theorem lsub_eq_blsub' {ι} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f) : lsub (family_of_bfamily' r ho f) = blsub o f := sup_eq_bsup' r ho (λ a ha, succ (f a ha)) theorem lsub_eq_lsub {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop) [is_well_order ι r] [is_well_order ι' r'] {o} (ho : type r = o) (ho' : type r' = o) (f : Π a < o, ordinal) : lsub (family_of_bfamily' r ho f) = lsub (family_of_bfamily' r' ho' f) := by rw [lsub_eq_blsub', lsub_eq_blsub'] @[simp] theorem lsub_eq_blsub {o} (f : Π a < o, ordinal) : lsub (family_of_bfamily o f) = blsub o f := lsub_eq_blsub' _ _ _ @[simp] theorem blsub_eq_lsub' {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → ordinal) : blsub _ (bfamily_of_family' r f) = lsub f := bsup_eq_sup' r (succ ∘ f) theorem blsub_eq_blsub {ι : Type u} (r r' : ι → ι → Prop) [is_well_order ι r] [is_well_order ι r'] (f : ι → ordinal) : blsub _ (bfamily_of_family' r f) = blsub _ (bfamily_of_family' r' f) := by rw [blsub_eq_lsub', blsub_eq_lsub'] @[simp] theorem blsub_eq_lsub {ι} (f : ι → ordinal) : blsub _ (bfamily_of_family f) = lsub f := blsub_eq_lsub' _ _ @[congr] lemma blsub_congr {o₁ o₂ : ordinal} (f : Π a < o₁, ordinal) (ho : o₁ = o₂) : blsub o₁ f = blsub o₂ (λ a h, f a (h.trans_eq ho.symm)) := by subst ho theorem blsub_le_iff {o f a} : blsub o f ≤ a ↔ ∀ i h, f i h < a := by { convert bsup_le_iff, simp [succ_le_iff] } theorem blsub_le {o : ordinal} {f : Π b < o, ordinal} {a} : (∀ i h, f i h < a) → blsub o f ≤ a := blsub_le_iff.2 theorem lt_blsub {o} (f : Π a < o, ordinal) (i h) : f i h < blsub o f := blsub_le_iff.1 le_rfl _ _ theorem lt_blsub_iff {o f a} : a < blsub o f ↔ ∃ i hi, a ≤ f i hi := by simpa only [not_forall, not_lt, not_le] using not_congr (@blsub_le_iff _ f a) theorem bsup_le_blsub {o} (f : Π a < o, ordinal) : bsup o f ≤ blsub o f := bsup_le (λ i h, (lt_blsub f i h).le) theorem blsub_le_bsup_succ {o} (f : Π a < o, ordinal) : blsub o f ≤ succ (bsup o f) := blsub_le (λ i h, lt_succ_iff.2 (le_bsup f i h)) theorem bsup_eq_blsub_or_succ_bsup_eq_blsub {o} (f : Π a < o, ordinal) : bsup o f = blsub o f ∨ succ (bsup o f) = blsub o f := by { rw [←sup_eq_bsup, ←lsub_eq_blsub], exact sup_eq_lsub_or_sup_succ_eq_lsub _ } theorem bsup_succ_le_blsub {o} (f : Π a < o, ordinal) : succ (bsup o f) ≤ blsub o f ↔ ∃ i hi, f i hi = bsup o f := begin refine ⟨λ h, _, _⟩, { by_contra' hf, exact ne_of_lt (succ_le_iff.1 h) (le_antisymm (bsup_le_blsub f) (blsub_le (lt_bsup_of_ne_bsup.1 hf))) }, rintro ⟨_, _, hf⟩, rw [succ_le_iff, ←hf], exact lt_blsub _ _ _ end theorem bsup_succ_eq_blsub {o} (f : Π a < o, ordinal) : succ (bsup o f) = blsub o f ↔ ∃ i hi, f i hi = bsup o f := (blsub_le_bsup_succ f).le_iff_eq.symm.trans (bsup_succ_le_blsub f) theorem bsup_eq_blsub_iff_succ {o} (f : Π a < o, ordinal) : bsup o f = blsub o f ↔ ∀ a < blsub o f, succ a < blsub o f := by { rw [←sup_eq_bsup, ←lsub_eq_blsub], apply sup_eq_lsub_iff_succ } theorem bsup_eq_blsub_iff_lt_bsup {o} (f : Π a < o, ordinal) : bsup o f = blsub o f ↔ ∀ i hi, f i hi < bsup o f := ⟨λ h i, (by { rw h, apply lt_blsub }), λ h, le_antisymm (bsup_le_blsub f) (blsub_le h)⟩ theorem bsup_eq_blsub_of_lt_succ_limit {o} (ho : is_limit o) {f : Π a < o, ordinal} (hf : ∀ a ha, f a ha < f (succ a) (ho.2 a ha)) : bsup o f = blsub o f := begin rw bsup_eq_blsub_iff_lt_bsup, exact λ i hi, (hf i hi).trans_le (le_bsup f _ _) end theorem blsub_succ_of_mono {o : ordinal} {f : Π a < succ o, ordinal} (hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : blsub _ f = succ (f o (lt_succ o)) := bsup_succ_of_mono $ λ i j hi hj h, succ_le_succ (hf hi hj h) @[simp] theorem blsub_eq_zero_iff {o} {f : Π a < o, ordinal} : blsub o f = 0 ↔ o = 0 := by { rw [←lsub_eq_blsub, lsub_eq_zero_iff], exact out_empty_iff_eq_zero } @[simp] lemma blsub_zero (f : Π a < (0 : ordinal), ordinal) : blsub 0 f = 0 := by rwa blsub_eq_zero_iff lemma blsub_pos {o : ordinal} (ho : 0 < o) (f : Π a < o, ordinal) : 0 < blsub o f := (ordinal.zero_le _).trans_lt (lt_blsub f 0 ho) theorem blsub_type (r : α → α → Prop) [is_well_order α r] (f) : blsub (type r) f = lsub (λ a, f (typein r a) (typein_lt_type _ _)) := eq_of_forall_ge_iff $ λ o, by rw [blsub_le_iff, lsub_le_iff]; exact ⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩ theorem blsub_const {o : ordinal} (ho : o ≠ 0) (a : ordinal) : blsub.{u v} o (λ _ _, a) = succ a := bsup_const.{u v} ho (succ a) @[simp] theorem blsub_one (f : Π a < (1 : ordinal), ordinal) : blsub 1 f = succ (f 0 zero_lt_one) := bsup_one _ @[simp] theorem blsub_id : ∀ o, blsub.{u u} o (λ x _, x) = o := lsub_typein theorem bsup_id_limit {o : ordinal} : (∀ a < o, succ a < o) → bsup.{u u} o (λ x _, x) = o := sup_typein_limit @[simp] theorem bsup_id_succ (o) : bsup.{u u} (succ o) (λ x _, x) = o := sup_typein_succ theorem blsub_le_of_brange_subset {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : brange o f ⊆ brange o' g) : blsub.{u (max v w)} o f ≤ blsub.{v (max u w)} o' g := bsup_le_of_brange_subset $ λ a ⟨b, hb, hb'⟩, begin obtain ⟨c, hc, hc'⟩ := h ⟨b, hb, rfl⟩, simp_rw ←hc' at hb', exact ⟨c, hc, hb'⟩ end theorem blsub_eq_of_brange_eq {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : {o | ∃ i hi, f i hi = o} = {o | ∃ i hi, g i hi = o}) : blsub.{u (max v w)} o f = blsub.{v (max u w)} o' g := (blsub_le_of_brange_subset h.le).antisymm (blsub_le_of_brange_subset.{v u w} h.ge) theorem bsup_comp {o o' : ordinal} {f : Π a < o, ordinal} (hf : ∀ {i j} (hi) (hj), i ≤ j → f i hi ≤ f j hj) {g : Π a < o', ordinal} (hg : blsub o' g = o) : bsup o' (λ a ha, f (g a ha) (by { rw ←hg, apply lt_blsub })) = bsup o f := begin apply le_antisymm; refine bsup_le (λ i hi, _), { apply le_bsup }, { rw [←hg, lt_blsub_iff] at hi, rcases hi with ⟨j, hj, hj'⟩, exact (hf _ _ hj').trans (le_bsup _ _ _) } end theorem blsub_comp {o o' : ordinal} {f : Π a < o, ordinal} (hf : ∀ {i j} (hi) (hj), i ≤ j → f i hi ≤ f j hj) {g : Π a < o', ordinal} (hg : blsub o' g = o) : blsub o' (λ a ha, f (g a ha) (by { rw ←hg, apply lt_blsub })) = blsub o f := @bsup_comp o _ (λ a ha, succ (f a ha)) (λ i j _ _ h, succ_le_succ_iff.2 (hf _ _ h)) g hg theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) : bsup.{u} o (λ x _, f x) = f o := by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id_limit h.2] } theorem is_normal.blsub_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) : blsub.{u} o (λ x _, f x) = f o := by { rw [←H.bsup_eq h, bsup_eq_blsub_of_lt_succ_limit h], exact (λ a _, H.1 a) } theorem is_normal_iff_lt_succ_and_bsup_eq {f} : is_normal f ↔ (∀ a, f a < f (succ a)) ∧ ∀ o, is_limit o → bsup o (λ x _, f x) = f o := ⟨λ h, ⟨h.1, @is_normal.bsup_eq f h⟩, λ ⟨h₁, h₂⟩, ⟨h₁, λ o ho a, (by {rw ←h₂ o ho, exact bsup_le_iff})⟩⟩ theorem is_normal_iff_lt_succ_and_blsub_eq {f} : is_normal f ↔ (∀ a, f a < f (succ a)) ∧ ∀ o, is_limit o → blsub o (λ x _, f x) = f o := begin rw [is_normal_iff_lt_succ_and_bsup_eq, and.congr_right_iff], intro h, split; intros H o ho; have := H o ho; rwa ←bsup_eq_blsub_of_lt_succ_limit ho (λ a _, h a) at * end theorem is_normal.eq_iff_zero_and_succ {f g : ordinal.{u} → ordinal.{u}} (hf : is_normal f) (hg : is_normal g) : f = g ↔ f 0 = g 0 ∧ ∀ a, f a = g a → f (succ a) = g (succ a) := ⟨λ h, by simp [h], λ ⟨h₁, h₂⟩, funext (λ a, begin apply a.limit_rec_on, assumption', intros o ho H, rw [←is_normal.bsup_eq.{u u} hf ho, ←is_normal.bsup_eq.{u u} hg ho], congr, ext b hb, exact H b hb end)⟩ /-! ### Minimum excluded ordinals -/ /-- The minimum excluded ordinal in a family of ordinals. -/ def mex {ι : Type u} (f : ι → ordinal.{max u v}) : ordinal := Inf (set.range f)ᶜ theorem mex_not_mem_range {ι : Type u} (f : ι → ordinal.{max u v}) : mex f ∉ set.range f := Inf_mem (nonempty_compl_range f) theorem ne_mex {ι} (f : ι → ordinal) : ∀ i, f i ≠ mex f := by simpa using mex_not_mem_range f theorem mex_le_of_ne {ι} {f : ι → ordinal} {a} (ha : ∀ i, f i ≠ a) : mex f ≤ a := cInf_le' (by simp [ha]) theorem exists_of_lt_mex {ι} {f : ι → ordinal} {a} (ha : a < mex f) : ∃ i, f i = a := by { by_contra' ha', exact ha.not_le (mex_le_of_ne ha') } theorem mex_le_lsub {ι} (f : ι → ordinal) : mex f ≤ lsub f := cInf_le' (lsub_not_mem_range f) theorem mex_monotone {α β} {f : α → ordinal} {g : β → ordinal} (h : set.range f ⊆ set.range g) : mex f ≤ mex g := begin refine mex_le_of_ne (λ i hi, _), cases h ⟨i, rfl⟩ with j hj, rw ←hj at hi, exact ne_mex g j hi end theorem mex_lt_ord_succ_mk {ι} (f : ι → ordinal) : mex f < (succ (#ι)).ord := begin by_contra' h, apply (lt_succ (#ι)).not_le, have H := λ a, exists_of_lt_mex ((typein_lt_self a).trans_le h), let g : (succ (#ι)).ord.out.α → ι := λ a, classical.some (H a), have hg : injective g := λ a b h', begin have Hf : ∀ x, f (g x) = typein (<) x := λ a, classical.some_spec (H a), apply_fun f at h', rwa [Hf, Hf, typein_inj] at h' end, convert cardinal.mk_le_of_injective hg, rw cardinal.mk_ord_out end /-- The minimum excluded ordinal of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. This is a special case of `mex` over the family provided by `family_of_bfamily`. This is to `mex` as `bsup` is to `sup`. -/ def bmex (o : ordinal) (f : Π a < o, ordinal) : ordinal := mex (family_of_bfamily o f) theorem bmex_not_mem_brange {o : ordinal} (f : Π a < o, ordinal) : bmex o f ∉ brange o f := by { rw ←range_family_of_bfamily, apply mex_not_mem_range } theorem ne_bmex {o : ordinal} (f : Π a < o, ordinal) {i} (hi) : f i hi ≠ bmex o f := begin convert ne_mex _ (enum (<) i (by rwa type_lt)), rw family_of_bfamily_enum end theorem bmex_le_of_ne {o : ordinal} {f : Π a < o, ordinal} {a} (ha : ∀ i hi, f i hi ≠ a) : bmex o f ≤ a := mex_le_of_ne (λ i, ha _ _) theorem exists_of_lt_bmex {o : ordinal} {f : Π a < o, ordinal} {a} (ha : a < bmex o f) : ∃ i hi, f i hi = a := begin cases exists_of_lt_mex ha with i hi, exact ⟨_, typein_lt_self i, hi⟩ end theorem bmex_le_blsub {o : ordinal} (f : Π a < o, ordinal) : bmex o f ≤ blsub o f := mex_le_lsub _ theorem bmex_monotone {o o' : ordinal} {f : Π a < o, ordinal} {g : Π a < o', ordinal} (h : brange o f ⊆ brange o' g) : bmex o f ≤ bmex o' g := mex_monotone (by rwa [range_family_of_bfamily, range_family_of_bfamily]) theorem bmex_lt_ord_succ_card {o : ordinal} (f : Π a < o, ordinal) : bmex o f < (succ o.card).ord := by { rw ←mk_ordinal_out, exact (mex_lt_ord_succ_mk (family_of_bfamily o f)) } end ordinal /-! ### Results about injectivity and surjectivity -/ lemma not_surjective_of_ordinal {α : Type u} (f : α → ordinal.{u}) : ¬ surjective f := λ h, ordinal.lsub_not_mem_range.{u u} f (h _) lemma not_injective_of_ordinal {α : Type u} (f : ordinal.{u} → α) : ¬ injective f := λ h, not_surjective_of_ordinal _ (inv_fun_surjective h) lemma not_surjective_of_ordinal_of_small {α : Type v} [small.{u} α] (f : α → ordinal.{u}) : ¬ surjective f := λ h, not_surjective_of_ordinal _ (h.comp (equiv_shrink _).symm.surjective) lemma not_injective_of_ordinal_of_small {α : Type v} [small.{u} α] (f : ordinal.{u} → α) : ¬ injective f := λ h, not_injective_of_ordinal _ ((equiv_shrink _).injective.comp h) /-- The type of ordinals in universe `u` is not `small.{u}`. This is the type-theoretic analog of the Burali-Forti paradox. -/ theorem not_small_ordinal : ¬ small.{u} ordinal.{max u v} := λ h, @not_injective_of_ordinal_of_small _ h _ (λ a b, ordinal.lift_inj.1) /-! ### Enumerating unbounded sets of ordinals with ordinals -/ namespace ordinal section /-- Enumerator function for an unbounded set of ordinals. -/ def enum_ord (S : set ordinal.{u}) : ordinal → ordinal := lt_wf.fix (λ o f, Inf (S ∩ set.Ici (blsub.{u u} o f))) variables {S : set ordinal.{u}} /-- The equation that characterizes `enum_ord` definitionally. This isn't the nicest expression to work with, so consider using `enum_ord_def` instead. -/ theorem enum_ord_def' (o) : enum_ord S o = Inf (S ∩ set.Ici (blsub.{u u} o (λ a _, enum_ord S a))) := lt_wf.fix_eq _ _ /-- The set in `enum_ord_def'` is nonempty. -/ theorem enum_ord_def'_nonempty (hS : unbounded (<) S) (a) : (S ∩ set.Ici a).nonempty := let ⟨b, hb, hb'⟩ := hS a in ⟨b, hb, le_of_not_gt hb'⟩ private theorem enum_ord_mem_aux (hS : unbounded (<) S) (o) : (enum_ord S o) ∈ S ∩ set.Ici (blsub.{u u} o (λ c _, enum_ord S c)) := by { rw enum_ord_def', exact Inf_mem (enum_ord_def'_nonempty hS _) } theorem enum_ord_mem (hS : unbounded (<) S) (o) : enum_ord S o ∈ S := (enum_ord_mem_aux hS o).left theorem blsub_le_enum_ord (hS : unbounded (<) S) (o) : blsub.{u u} o (λ c _, enum_ord S c) ≤ enum_ord S o := (enum_ord_mem_aux hS o).right theorem enum_ord_strict_mono (hS : unbounded (<) S) : strict_mono (enum_ord S) := λ _ _ h, (lt_blsub.{u u} _ _ h).trans_le (blsub_le_enum_ord hS _) /-- A more workable definition for `enum_ord`. -/ theorem enum_ord_def (o) : enum_ord S o = Inf (S ∩ {b | ∀ c, c < o → enum_ord S c < b}) := begin rw enum_ord_def', congr, ext, exact ⟨λ h a hao, (lt_blsub.{u u} _ _ hao).trans_le h, blsub_le⟩ end /-- The set in `enum_ord_def` is nonempty. -/ lemma enum_ord_def_nonempty (hS : unbounded (<) S) {o} : {x | x ∈ S ∧ ∀ c, c < o → enum_ord S c < x}.nonempty := (⟨_, enum_ord_mem hS o, λ _ b, enum_ord_strict_mono hS b⟩) @[simp] theorem enum_ord_range {f : ordinal → ordinal} (hf : strict_mono f) : enum_ord (range f) = f := funext (λ o, begin apply ordinal.induction o, intros a H, rw enum_ord_def a, have Hfa : f a ∈ range f ∩ {b | ∀ c, c < a → enum_ord (range f) c < b} := ⟨mem_range_self a, λ b hb, (by {rw H b hb, exact hf hb})⟩, refine (cInf_le' Hfa).antisymm ((le_cInf_iff'' ⟨_, Hfa⟩).2 _), rintros _ ⟨⟨c, rfl⟩, hc : ∀ b < a, enum_ord (range f) b < f c⟩, rw hf.le_iff_le, contrapose! hc, exact ⟨c, hc, (H c hc).ge⟩, end) @[simp] theorem enum_ord_univ : enum_ord set.univ = id := by { rw ←range_id, exact enum_ord_range strict_mono_id } @[simp] theorem enum_ord_zero : enum_ord S 0 = Inf S := by { rw enum_ord_def, simp [ordinal.not_lt_zero] } theorem enum_ord_succ_le {a b} (hS : unbounded (<) S) (ha : a ∈ S) (hb : enum_ord S b < a) : enum_ord S (succ b) ≤ a := begin rw enum_ord_def, exact cInf_le' ⟨ha, λ c hc, ((enum_ord_strict_mono hS).monotone (le_of_lt_succ hc)).trans_lt hb⟩ end theorem enum_ord_le_of_subset {S T : set ordinal} (hS : unbounded (<) S) (hST : S ⊆ T) (a) : enum_ord T a ≤ enum_ord S a := begin apply ordinal.induction a, intros b H, rw enum_ord_def, exact cInf_le' ⟨hST (enum_ord_mem hS b), λ c h, (H c h).trans_lt (enum_ord_strict_mono hS h)⟩ end theorem enum_ord_surjective (hS : unbounded (<) S) : ∀ s ∈ S, ∃ a, enum_ord S a = s := λ s hs, ⟨Sup {a | enum_ord S a ≤ s}, begin apply le_antisymm, { rw enum_ord_def, refine cInf_le' ⟨hs, λ a ha, _⟩, have : enum_ord S 0 ≤ s := by { rw enum_ord_zero, exact cInf_le' hs }, rcases exists_lt_of_lt_cSup (by exact ⟨0, this⟩) ha with ⟨b, hb, hab⟩, exact (enum_ord_strict_mono hS hab).trans_le hb }, { by_contra' h, exact (le_cSup ⟨s, λ a, (lt_wf.self_le_of_strict_mono (enum_ord_strict_mono hS) a).trans⟩ (enum_ord_succ_le hS hs h)).not_lt (lt_succ _) } end⟩ /-- An order isomorphism between an unbounded set of ordinals and the ordinals. -/ def enum_ord_order_iso (hS : unbounded (<) S) : ordinal ≃o S := strict_mono.order_iso_of_surjective (λ o, ⟨_, enum_ord_mem hS o⟩) (enum_ord_strict_mono hS) (λ s, let ⟨a, ha⟩ := enum_ord_surjective hS s s.prop in ⟨a, subtype.eq ha⟩) theorem range_enum_ord (hS : unbounded (<) S) : range (enum_ord S) = S := by { rw range_eq_iff, exact ⟨enum_ord_mem hS, enum_ord_surjective hS⟩ } /-- A characterization of `enum_ord`: it is the unique strict monotonic function with range `S`. -/ theorem eq_enum_ord (f : ordinal → ordinal) (hS : unbounded (<) S) : strict_mono f ∧ range f = S ↔ f = enum_ord S := begin split, { rintro ⟨h₁, h₂⟩, rwa [←lt_wf.eq_strict_mono_iff_eq_range h₁ (enum_ord_strict_mono hS), range_enum_ord hS] }, { rintro rfl, exact ⟨enum_ord_strict_mono hS, range_enum_ord hS⟩ } end end /-! ### Ordinal exponential -/ /-- The ordinal exponential, defined by transfinite recursion. -/ instance : has_pow ordinal ordinal := ⟨λ a b, if a = 0 then 1 - b else limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b)⟩ local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem opow_def (a b : ordinal) : a ^ b = if a = 0 then 1 - b else limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b) := rfl theorem zero_opow' (a : ordinal) : 0 ^ a = 1 - a := by simp only [opow_def, if_pos rfl] @[simp] theorem zero_opow {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 := by rwa [zero_opow', ordinal.sub_eq_zero_iff_le, one_le_iff_ne_zero] @[simp] theorem opow_zero (a : ordinal) : a ^ 0 = 1 := by by_cases a = 0; [simp only [opow_def, if_pos h, sub_zero], simp only [opow_def, if_neg h, limit_rec_on_zero]] @[simp] theorem opow_succ (a b : ordinal) : a ^ succ b = a ^ b * a := if h : a = 0 then by subst a; simp only [zero_opow (succ_ne_zero _), mul_zero] else by simp only [opow_def, limit_rec_on_succ, if_neg h] theorem opow_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b = bsup.{u u} b (λ c _, a ^ c) := by simp only [opow_def, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl theorem opow_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c := by rw [opow_limit a0 h, bsup_le_iff] theorem lt_opow_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) : a < b ^ c ↔ ∃ c' < c, a < b ^ c' := by rw [← not_iff_not, not_exists]; simp only [not_lt, opow_le_of_limit b0 h, exists_prop, not_and] @[simp] theorem opow_one (a : ordinal) : a ^ 1 = a := by rw [← succ_zero, opow_succ]; simp only [opow_zero, one_mul] @[simp] theorem one_opow (a : ordinal) : 1 ^ a = 1 := begin apply limit_rec_on a, { simp only [opow_zero] }, { intros _ ih, simp only [opow_succ, ih, mul_one] }, refine λ b l IH, eq_of_forall_ge_iff (λ c, _), rw [opow_le_of_limit ordinal.one_ne_zero l], exact ⟨λ H, by simpa only [opow_zero] using H 0 l.pos, λ H b' h, by rwa IH _ h⟩, end theorem opow_pos {a : ordinal} (b) (a0 : 0 < a) : 0 < a ^ b := begin have h0 : 0 < a ^ 0, {simp only [opow_zero, zero_lt_one]}, apply limit_rec_on b, { exact h0 }, { intros b IH, rw [opow_succ], exact mul_pos IH a0 }, { exact λ b l _, (lt_opow_of_limit (ordinal.pos_iff_ne_zero.1 a0) l).2 ⟨0, l.pos, h0⟩ }, end theorem opow_ne_zero {a : ordinal} (b) (a0 : a ≠ 0) : a ^ b ≠ 0 := ordinal.pos_iff_ne_zero.1 $ opow_pos b $ ordinal.pos_iff_ne_zero.2 a0 theorem opow_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) := have a0 : 0 < a, from zero_lt_one.trans h, ⟨λ b, by simpa only [mul_one, opow_succ] using (mul_lt_mul_iff_left (opow_pos b a0)).2 h, λ b l c, opow_le_of_limit (ne_of_gt a0) l⟩ theorem opow_lt_opow_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b < a ^ c ↔ b < c := (opow_is_normal a1).lt_iff theorem opow_le_opow_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c := (opow_is_normal a1).le_iff theorem opow_right_inj {a b c : ordinal} (a1 : 1 < a) : a ^ b = a ^ c ↔ b = c := (opow_is_normal a1).inj theorem opow_is_limit {a b : ordinal} (a1 : 1 < a) : is_limit b → is_limit (a ^ b) := (opow_is_normal a1).is_limit theorem opow_is_limit_left {a b : ordinal} (l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) := begin rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l', { exact absurd e hb }, { rw opow_succ, exact mul_is_limit (opow_pos _ l.pos) l }, { exact opow_is_limit l.one_lt l' } end theorem opow_le_opow_right {a b c : ordinal} (h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c := begin cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁, { exact (opow_le_opow_iff_right h₁).2 h₂ }, { subst a, simp only [one_opow] } end theorem opow_le_opow_left {a b : ordinal} (c) (ab : a ≤ b) : a ^ c ≤ b ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, { subst c, simp only [opow_zero] }, { simp only [zero_opow c0, ordinal.zero_le] } }, { apply limit_rec_on c, { simp only [opow_zero] }, { intros c IH, simpa only [opow_succ] using mul_le_mul' IH ab }, { exact λ c l IH, (opow_le_of_limit a0 l).2 (λ b' h, (IH _ h).trans (opow_le_opow_right ((ordinal.pos_iff_ne_zero.2 a0).trans_le ab) h.le)) } } end theorem left_le_opow (a : ordinal) {b : ordinal} (b1 : 0 < b) : a ≤ a ^ b := begin nth_rewrite 0 ←opow_one a, cases le_or_gt a 1 with a1 a1, { cases lt_or_eq_of_le a1 with a0 a1, { rw lt_one_iff_zero at a0, rw [a0, zero_opow ordinal.one_ne_zero], exact ordinal.zero_le _ }, rw [a1, one_opow, one_opow] }, rwa [opow_le_opow_iff_right a1, one_le_iff_pos] end theorem right_le_opow {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b := (opow_is_normal a1).self_le _ theorem opow_lt_opow_left_of_succ {a b c : ordinal} (ab : a < b) : a ^ succ c < b ^ succ c := by { rw [opow_succ, opow_succ], exact (mul_le_mul_right' (opow_le_opow_left c ab.le) a).trans_lt (mul_lt_mul_of_pos_left ab (opow_pos c ((ordinal.zero_le a).trans_lt ab))) } theorem opow_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c := begin rcases eq_or_ne a 0 with rfl | a0, { rcases eq_or_ne c 0 with rfl | c0, { simp }, have : b + c ≠ 0 := ((ordinal.pos_iff_ne_zero.2 c0).trans_le (le_add_left _ _)).ne', simp only [zero_opow c0, zero_opow this, mul_zero] }, rcases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with rfl | a1, { simp only [one_opow, mul_one] }, apply limit_rec_on c, { simp }, { intros c IH, rw [add_succ, opow_succ, IH, opow_succ, mul_assoc] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((opow_is_normal a1).trans (add_is_normal b)).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (((mul_is_normal $ opow_pos b (ordinal.pos_iff_ne_zero.2 a0)).trans (opow_is_normal a1)).limit_le l).symm } end theorem opow_one_add (a b : ordinal) : a ^ (1 + b) = a * a ^ b := by rw [opow_add, opow_one] theorem opow_dvd_opow (a) {b c : ordinal} (h : b ≤ c) : a ^ b ∣ a ^ c := by { rw [← ordinal.add_sub_cancel_of_le h, opow_add], apply dvd_mul_right } theorem opow_dvd_opow_iff {a b c : ordinal} (a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c := ⟨λ h, le_of_not_lt $ λ hn, not_le_of_lt ((opow_lt_opow_iff_right a1).2 hn) $ le_of_dvd (opow_ne_zero _ $ one_le_iff_ne_zero.1 $ a1.le) h, opow_dvd_opow _⟩ theorem opow_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c := begin by_cases b0 : b = 0, {simp only [b0, zero_mul, opow_zero, one_opow]}, by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, mul_zero, opow_zero]}, simp only [zero_opow b0, zero_opow c0, zero_opow (mul_ne_zero b0 c0)] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_opow] }, apply limit_rec_on c, { simp only [mul_zero, opow_zero] }, { intros c IH, rw [mul_succ, opow_add, IH, opow_succ] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((opow_is_normal a1).trans (mul_is_normal (ordinal.pos_iff_ne_zero.2 b0))).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (opow_le_of_limit (opow_ne_zero _ a0) l).symm } end /-! ### Ordinal logarithm -/ /-- The ordinal logarithm is the solution `u` to the equation `x = b ^ u * v + w` where `v < b` and `w < b ^ u`. -/ @[pp_nodot] def log (b : ordinal) (x : ordinal) : ordinal := if h : 1 < b then pred (Inf {o | x < b ^ o}) else 0 /-- The set in the definition of `log` is nonempty. -/ theorem log_nonempty {b x : ordinal} (h : 1 < b) : {o | x < b ^ o}.nonempty := ⟨_, succ_le_iff.1 (right_le_opow _ h)⟩ theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x = pred (Inf {o | x < b ^ o}) := by simp only [log, dif_pos b1] theorem log_of_not_one_lt_left {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 := by simp only [log, dif_neg b1] theorem log_of_left_le_one {b : ordinal} (b1 : b ≤ 1) : ∀ x, log b x = 0 := log_of_not_one_lt_left b1.not_lt @[simp] lemma log_zero_left : ∀ b, log 0 b = 0 := log_of_left_le_one zero_le_one @[simp] theorem log_zero_right (b : ordinal) : log b 0 = 0 := if b1 : 1 < b then begin rw [log_def b1, ← ordinal.le_zero, pred_le], apply cInf_le', dsimp, rw [succ_zero, opow_one], exact zero_lt_one.trans b1 end else by simp only [log_of_not_one_lt_left b1] @[simp] theorem log_one_left : ∀ b, log 1 b = 0 := log_of_left_le_one le_rfl theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) = Inf {o | x < b ^ o} := begin let t := Inf {o | x < b ^ o}, have : x < b ^ t := Inf_mem (log_nonempty b1), rcases zero_or_succ_or_limit t with h|h|h, { refine ((one_le_iff_pos.2 x0).not_lt _).elim, simpa only [h, opow_zero] }, { rw [show log b x = pred t, from log_def b1 x, succ_pred_iff_is_succ.2 h] }, { rcases (lt_opow_of_limit (zero_lt_one.trans b1).ne' h).1 this with ⟨a, h₁, h₂⟩, exact h₁.not_le.elim ((le_cInf_iff'' (log_nonempty b1)).1 le_rfl a h₂) } end theorem lt_opow_succ_log_self {b : ordinal} (b1 : 1 < b) (x : ordinal) : x < b ^ succ (log b x) := begin cases lt_or_eq_of_le (ordinal.zero_le x) with x0 x0, { rw [succ_log_def b1 x0], exact Inf_mem (log_nonempty b1) }, { subst x, apply opow_pos _ (zero_lt_one.trans b1) } end theorem opow_log_le_self (b) {x : ordinal} (x0 : 0 < x) : b ^ log b x ≤ x := begin rcases eq_or_ne b 0 with rfl | b0, { rw zero_opow', refine (sub_le_self _ _).trans (one_le_iff_pos.2 x0) }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine le_of_not_lt (λ h, (lt_succ (log b x)).not_le _), have := @cInf_le' _ _ {o | x < b ^ o} _ h, rwa ←succ_log_def b1 x0 at this }, { rw [←b1, one_opow], exact one_le_iff_pos.2 x0 } end /-- `opow b` and `log b` (almost) form a Galois connection. -/ theorem opow_le_iff_le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : b ^ c ≤ x ↔ c ≤ log b x := ⟨λ h, le_of_not_lt $ λ hn, (lt_opow_succ_log_self b1 x).not_le $ ((opow_le_opow_iff_right b1).2 (succ_le_of_lt hn)).trans h, λ h, ((opow_le_opow_iff_right b1).2 h).trans (opow_log_le_self b x0)⟩ theorem lt_opow_iff_log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : x < b ^ c ↔ log b x < c := lt_iff_lt_of_le_iff_le (opow_le_iff_le_log b1 x0) @[mono] theorem log_mono_right (b) {x y : ordinal} (xy : x ≤ y) : log b x ≤ log b y := if x0 : x = 0 then by simp only [x0, log_zero_right, ordinal.zero_le] else have x0 : 0 < x, from ordinal.pos_iff_ne_zero.2 x0, if b1 : 1 < b then (opow_le_iff_le_log b1 (lt_of_lt_of_le x0 xy)).1 $ (opow_log_le_self _ x0).trans xy else by simp only [log_of_not_one_lt_left b1, ordinal.zero_le] theorem log_le_self (b x : ordinal) : log b x ≤ x := if x0 : x = 0 then by simp only [x0, log_zero_right, ordinal.zero_le] else if b1 : 1 < b then (right_le_opow _ b1).trans (opow_log_le_self b (ordinal.pos_iff_ne_zero.2 x0)) else by simp only [log_of_not_one_lt_left b1, ordinal.zero_le] @[simp] theorem log_one_right (b : ordinal) : log b 1 = 0 := if hb : 1 < b then by rwa [←lt_one_iff_zero, ←lt_opow_iff_log_lt hb zero_lt_one, opow_one] else log_of_not_one_lt_left hb 1 theorem mod_opow_log_lt_self {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : o % b ^ log b o < o := (mod_lt _ $ opow_ne_zero _ b0).trans_le (opow_log_le_self _ $ ordinal.pos_iff_ne_zero.2 o0) lemma opow_mul_add_pos {b v : ordinal} (hb : 0 < b) (u) (hv : 0 < v) (w) : 0 < b ^ u * v + w := (opow_pos u hb).trans_le ((le_mul_left _ hv).trans (le_add_right _ _)) lemma opow_mul_add_lt_opow_mul_succ {b u w : ordinal} (v : ordinal) (hw : w < b ^ u) : b ^ u * v + w < b ^ u * (succ v) := by rwa [mul_succ, add_lt_add_iff_left] lemma opow_mul_add_lt_opow_succ {b u v w : ordinal} (hvb : v < b) (hw : w < b ^ u) : b ^ u * v + w < b ^ (succ u) := begin convert (opow_mul_add_lt_opow_mul_succ v hw).trans_le (mul_le_mul_left' (succ_le_of_lt hvb) _), exact opow_succ b u end theorem log_opow_mul_add {b u v w : ordinal} (hb : 1 < b) (hv : 0 < v) (hvb : v < b) (hw : w < b ^ u) : log b (b ^ u * v + w) = u := begin have hpos := opow_mul_add_pos (zero_lt_one.trans hb) u hv w, by_contra' hne, cases lt_or_gt_of_ne hne with h h, { rw ←lt_opow_iff_log_lt hb hpos at h, exact h.not_le ((le_mul_left _ hv).trans (le_add_right _ _)) }, { change _ < _ at h, rw [←succ_le_iff, ←opow_le_iff_le_log hb hpos] at h, exact (not_lt_of_le h) (opow_mul_add_lt_opow_succ hvb hw) } end @[simp] theorem log_opow {b : ordinal} (hb : 1 < b) (x : ordinal) : log b (b ^ x) = x := begin convert log_opow_mul_add hb zero_lt_one hb (opow_pos x (zero_lt_one.trans hb)), rw [add_zero, mul_one] end theorem add_log_le_log_mul {x y : ordinal} (b : ordinal) (x0 : 0 < x) (y0 : 0 < y) : log b x + log b y ≤ log b (x * y) := begin by_cases hb : 1 < b, { rw [←opow_le_iff_le_log hb (mul_pos x0 y0), opow_add], exact mul_le_mul' (opow_log_le_self b x0) (opow_log_le_self b y0) }, simp only [log_of_not_one_lt_left hb, zero_add] end /-! ### Casting naturals into ordinals, compatibility with operations -/ @[simp, norm_cast] theorem nat_cast_mul (m : ℕ) : ∀ n : ℕ, ((m * n : ℕ) : ordinal) = m * n | 0 := by simp | (n+1) := by rw [nat.mul_succ, nat.cast_add, nat_cast_mul, nat.cast_succ, mul_add_one] @[simp, norm_cast] theorem nat_cast_opow (m : ℕ) : ∀ n : ℕ, ((pow m n : ℕ) : ordinal) = m ^ n | 0 := by simp | (n+1) := by rw [pow_succ', nat_cast_mul, nat_cast_opow, nat.cast_succ, add_one_eq_succ, opow_succ] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n := by rw [←cardinal.ord_nat, ←cardinal.ord_nat, cardinal.ord_le_ord, cardinal.nat_cast_le] @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n := by simp only [lt_iff_le_not_le, nat_cast_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n := by simp only [le_antisymm_iff, nat_cast_le] @[simp, norm_cast] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 := @nat_cast_inj n 0 theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 := not_congr nat_cast_eq_zero @[simp, norm_cast] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n := @nat_cast_lt 0 n @[simp, norm_cast] theorem nat_cast_sub (m n : ℕ) : ((m - n : ℕ) : ordinal) = m - n := begin cases le_total m n with h h, { rw [tsub_eq_zero_iff_le.2 h, ordinal.sub_eq_zero_iff_le.2 (nat_cast_le.2 h)], refl }, { apply (add_left_cancel n).1, rw [←nat.cast_add, add_tsub_cancel_of_le h, ordinal.add_sub_cancel_of_le (nat_cast_le.2 h)] } end @[simp, norm_cast] theorem nat_cast_div (m n : ℕ) : ((m / n : ℕ) : ordinal) = m / n := begin rcases eq_or_ne n 0 with rfl | hn, { simp }, { have hn' := nat_cast_ne_zero.2 hn, apply le_antisymm, { rw [le_div hn', ←nat_cast_mul, nat_cast_le, mul_comm], apply nat.div_mul_le_self }, { rw [div_le hn', ←add_one_eq_succ, ←nat.cast_succ, ←nat_cast_mul, nat_cast_lt, mul_comm, ←nat.div_lt_iff_lt_mul (nat.pos_of_ne_zero hn)], apply nat.lt_succ_self } } end @[simp, norm_cast] theorem nat_cast_mod (m n : ℕ) : ((m % n : ℕ) : ordinal) = m % n := by rw [←add_left_cancel, div_add_mod, ←nat_cast_div, ←nat_cast_mul, ←nat.cast_add, nat.div_add_mod] @[simp] theorem lift_nat_cast : ∀ n : ℕ, lift.{u v} n = n | 0 := by simp | (n+1) := by simp [lift_nat_cast n] end ordinal /-! ### Properties of `omega` -/ namespace cardinal open ordinal @[simp] theorem ord_aleph_0 : ord.{u} ℵ₀ = ω := le_antisymm (ord_le.2 $ le_rfl) $ le_of_forall_lt $ λ o h, begin rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩, rw [lt_ord, ←lift_card, ←lift_aleph_0.{0 u}, lift_lt, ←typein_enum (<) h'], exact lt_aleph_0_iff_fintype.2 ⟨set.fintype_lt_nat _⟩ end @[simp] theorem add_one_of_aleph_0_le {c} (h : ℵ₀ ≤ c) : c + 1 = c := begin rw [add_comm, ←card_ord c, ←card_one, ←card_add, one_add_of_omega_le], rwa [←ord_aleph_0, ord_le_ord] end end cardinal namespace ordinal theorem lt_add_of_limit {a b c : ordinal.{u}} (h : is_limit c) : a < b + c ↔ ∃ c' < c, a < b + c' := by rw [←is_normal.bsup_eq.{u u} (add_is_normal b) h, lt_bsup] theorem lt_omega {o : ordinal} : o < ω ↔ ∃ n : ℕ, o = n := by simp_rw [←cardinal.ord_aleph_0, cardinal.lt_ord, lt_aleph_0, card_eq_nat] theorem nat_lt_omega (n : ℕ) : ↑n < ω := lt_omega.2 ⟨_, rfl⟩ theorem omega_pos : 0 < ω := nat_lt_omega 0 theorem omega_ne_zero : ω ≠ 0 := omega_pos.ne' theorem one_lt_omega : 1 < ω := by simpa only [nat.cast_one] using nat_lt_omega 1 theorem omega_is_limit : is_limit ω := ⟨omega_ne_zero, λ o h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e]; exact nat_lt_omega (n+1)⟩ theorem omega_le {o : ordinal} : ω ≤ o ↔ ∀ n : ℕ, ↑n ≤ o := ⟨λ h n, (nat_lt_omega _).le.trans h, λ H, le_of_forall_lt $ λ a h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e, ←succ_le_iff]; exact H (n+1)⟩ @[simp] theorem sup_nat_cast : sup nat.cast = ω := (sup_le $ λ n, (nat_lt_omega n).le).antisymm $ omega_le.2 $ le_sup _ theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, ↑n < o | 0 := lt_of_le_of_ne (ordinal.zero_le o) h.1.symm | (n+1) := h.2 _ (nat_lt_limit n) theorem omega_le_of_is_limit {o} (h : is_limit o) : ω ≤ o := omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ ω ∣ a := begin refine ⟨λ l, ⟨l.1, ⟨a / ω, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩, { refine (limit_le l).2 (λ x hx, le_of_lt _), rw [←div_lt omega_ne_zero, ←succ_le_iff, le_div omega_ne_zero, mul_succ, add_le_of_limit omega_is_limit], intros b hb, rcases lt_omega.1 hb with ⟨n, rfl⟩, exact (add_le_add_right (mul_div_le _ _) _).trans (lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _).le }, { rcases h with ⟨a0, b, rfl⟩, refine mul_is_limit_left omega_is_limit (ordinal.pos_iff_ne_zero.2 $ mt _ a0), intro e, simp only [e, mul_zero] } end theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a) (l : is_limit c) (IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c := le_antisymm ((mul_le_of_limit l).2 $ λ c' h, begin apply (mul_le_mul_left' (le_succ c') _).trans, rw IH _ h, apply (add_le_add_left _ _).trans, { rw ← mul_succ, exact mul_le_mul_left' (succ_le_of_lt $ l.2 _ h) _ }, { apply_instance }, { rw ← ba, exact le_add_right _ _ } end) (mul_le_mul_right' (le_add_right _ _) _) theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := begin apply limit_rec_on c, { simp only [succ_zero, mul_one] }, { intros c IH, rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] }, { intros c l IH, have := add_mul_limit_aux ba l IH, rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] } end theorem add_mul_limit {a b c : ordinal} (ba : b + a = a) (l : is_limit c) : (a + b) * c = a * c := add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba) theorem add_le_of_forall_add_lt {a b c : ordinal} (hb : 0 < b) (h : ∀ d < b, a + d < c) : a + b ≤ c := begin have H : a + (c - a) = c := ordinal.add_sub_cancel_of_le (by {rw ←add_zero a, exact (h _ hb).le}), rw ←H, apply add_le_add_left _ a, by_contra' hb, exact (h _ hb).ne H end theorem is_normal.apply_omega {f : ordinal.{u} → ordinal.{u}} (hf : is_normal f) : sup.{0 u} (f ∘ nat.cast) = f ω := by rw [←sup_nat_cast, is_normal.sup.{0 u u} hf _ ⟨0⟩] @[simp] theorem sup_add_nat (o : ordinal) : sup (λ n : ℕ, o + n) = o + ω := (add_is_normal o).apply_omega @[simp] theorem sup_mul_nat (o : ordinal) : sup (λ n : ℕ, o * n) = o * ω := begin rcases eq_zero_or_pos o with rfl | ho, { rw zero_mul, exact sup_eq_zero_iff.2 (λ n, zero_mul n) }, { exact (mul_is_normal ho).apply_omega } end local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem sup_opow_nat {o : ordinal} (ho : 0 < o) : sup (λ n : ℕ, o ^ n) = o ^ ω := begin rcases lt_or_eq_of_le (one_le_iff_pos.2 ho) with ho₁ | rfl, { exact (opow_is_normal ho₁).apply_omega }, { rw one_opow, refine le_antisymm (sup_le (λ n, by rw one_opow)) _, convert le_sup _ 0, rw [nat.cast_zero, opow_zero] } end end ordinal
d6c1f90214798a63df7cf4254e4d9c4ecfb508a7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/data/lazy_list_auto.lean
e6e15040b2c3c4547c3feee1505983fb00239149
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,590
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default universes u l v w namespace Mathlib inductive lazy_list (α : Type u) where | nil : lazy_list α | cons : α → thunk (lazy_list α) → lazy_list α namespace lazy_list def singleton {α : Type u} : α → lazy_list α := sorry def of_list {α : Type u} : List α → lazy_list α := sorry def to_list {α : Type u} : lazy_list α → List α := sorry def head {α : Type u} [Inhabited α] : lazy_list α → α := sorry def tail {α : Type u} : lazy_list α → lazy_list α := sorry def append {α : Type u} : lazy_list α → thunk (lazy_list α) → lazy_list α := sorry def map {α : Type u} {β : Type v} (f : α → β) : lazy_list α → lazy_list β := sorry def map₂ {α : Type u} {β : Type v} {δ : Type w} (f : α → β → δ) : lazy_list α → lazy_list β → lazy_list δ := sorry def zip {α : Type u} {β : Type v} : lazy_list α → lazy_list β → lazy_list (α × β) := map₂ Prod.mk def join {α : Type u} : lazy_list (lazy_list α) → lazy_list α := sorry def for {α : Type u} {β : Type v} (l : lazy_list α) (f : α → β) : lazy_list β := map f l def approx {α : Type u} : ℕ → lazy_list α → List α := sorry def filter {α : Type u} (p : α → Prop) [decidable_pred p] : lazy_list α → lazy_list α := sorry def nth {α : Type u} : lazy_list α → ℕ → Option α := sorry end Mathlib
f438a8b3910682d6ad6f51bf2b375a56b439b0ef
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/euclidean/basic.lean
57d4ced0134472fee9ffe6f08c4c74ab255965dd
[ "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
41,868
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Manuel Candales -/ import analysis.inner_product_space.projection import algebra.quadratic_discriminant /-! # Euclidean spaces This file makes some definitions and proves very basic geometrical results about real inner product spaces and Euclidean affine spaces. Results about real inner product spaces that involve the norm and inner product but not angles generally go in `analysis.normed_space.inner_product`. Results with longer proofs or more geometrical content generally go in separate files. ## Main definitions * `euclidean_geometry.orthogonal_projection` is the orthogonal projection of a point onto an affine subspace. * `euclidean_geometry.reflection` is the reflection of a point in an affine subspace. ## Implementation notes To declare `P` as the type of points in a Euclidean affine space with `V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]`. This works better with `out_param` to make `V` implicit in most cases than having a separate type alias for Euclidean affine spaces. Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ noncomputable theory open_locale big_operators open_locale classical open_locale real_inner_product_space namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] include V /-- The midpoint of the segment AB is the same distance from A as it is from B. -/ lemma dist_left_midpoint_eq_dist_right_midpoint (p1 p2 : P) : dist p1 (midpoint ℝ p1 p2) = dist p2 (midpoint ℝ p1 p2) := by rw [dist_left_midpoint p1 p2, dist_right_midpoint p1 p2] /-- The inner product of two vectors given with `weighted_vsub`, in terms of the pairwise distances. -/ lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪s₁.weighted_vsub p₁ w₁, s₂.weighted_vsub p₂ w₂⟫ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 := begin rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply, inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂], simp_rw [vsub_sub_vsub_cancel_right], rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂) end /-- The distance between two points given with `affine_combination`, in terms of the pairwise distances between the points in that combination. -/ lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P) (h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) : by have a₁ := s.affine_combination p w₁; have a₂ := s.affine_combination p w₂; exact dist a₁ a₂ * dist a₁ a₂ = (-∑ i₁ in s, ∑ i₂ in s, (w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 := begin rw [dist_eq_norm_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂), ←inner_self_eq_norm_mul_norm, finset.affine_combination_vsub], have h : ∑ i in s, (w₁ - w₂) i = 0, { simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] }, exact inner_weighted_vsub p h p h end /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := begin have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0, { conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁, skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ }, rw [sub_add_sub_comm, inner_sub_left], conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂, skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ }, rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁, dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂, simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add, neg_add_eq_sub, hc₁, hc₂, sub_zero] }, simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h end /-- The squared distance between points on a line (expressed as a multiple of a fixed vector added to a point) and another point, expressed as a quadratic. -/ lemma dist_smul_vadd_sq (r : ℝ) (v : V) (p₁ p₂ : P) : dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ = ⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ := begin rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_mul_norm, vadd_vsub_assoc, real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right], ring end /-- The condition for two points on a line to be equidistant from another point. -/ lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) : dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) := begin conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_sq, ←sub_eq_zero, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂, ←real_inner_self_eq_norm_mul_norm, sub_self] }, have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv, have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 = (2 * ⟪v, p₁ -ᵥ p₂⟫) * (2 * ⟪v, p₁ -ᵥ p₂⟫), { rw discrim, ring }, rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul, ←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc, mul_div_mul_left, mul_div_assoc], norm_num end open affine_subspace finite_dimensional /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in a two-dimensional subspace containing those points (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two {s : affine_subspace ℝ P} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P} (hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hp₂c₁.symm) (hp₁c₂.trans hp₂c₂.symm), have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hpc₁.symm) (hp₁c₂.trans hpc₂.symm), let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁], have hb : linear_independent ℝ b, { refine linear_independent_of_ne_zero_of_inner_eq_zero _ _, { intro i, fin_cases i; simp [b, hc.symm, hp.symm], }, { intros i j hij, fin_cases i; fin_cases j; try { exact false.elim (hij rfl) }, { exact ho }, { rw real_inner_comm, exact ho } } }, have hbs : submodule.span ℝ (set.range b) = s.direction, { refine eq_of_le_of_finrank_eq _ _, { rw [submodule.span_le, set.range_subset_iff], intro i, fin_cases i, { exact vsub_mem_direction hc₂s hc₁s }, { exact vsub_mem_direction hp₂s hp₁s } }, { rw [finrank_span_eq_card hb, fintype.card_fin, hd] } }, have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁), { intros v hv, have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁}, { have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial, rw [←fintype.coe_image_univ, hu], simp, refl }, rw [←hbs, hr, submodule.mem_span_insert] at hv, rcases hv with ⟨t₁, v', hv', hv⟩, rw submodule.mem_span_singleton at hv', rcases hv' with ⟨t₂, rfl⟩, exact ⟨t₁, t₂, hv⟩ }, rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩, simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero, inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop, rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt, subst hpt, have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] }, have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] }, rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂, simp only [one_ne_zero, false_or] at hp₂, rw hp₂.symm at hpc₁, cases hpc₁; simp [hpc₁] end /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_finrank_eq_two [finite_dimensional ℝ V] (hd : finrank ℝ V = 2) {c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have hd' : finrank ℝ (⊤ : affine_subspace ℝ P).direction = 2, { rw [direction_top, finrank_top], exact hd }, exact eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two hd' (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂ end variables {V} /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : P := classical.some $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin rw direction_mk' p s.directionᗮ, exact submodule.is_compl_orthogonal_of_complete_space, end /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection_fn` of that point onto the subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection_fn s p} := classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin rw direction_mk' p s.directionᗮ, exact submodule.is_compl_orthogonal_of_complete_space end /-- The `orthogonal_projection_fn` lies in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ s := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_left _ _ end /-- The `orthogonal_projection_fn` lies in the orthogonal subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ mk' p s.directionᗮ := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_right _ _ end /-- Subtracting `p` from its `orthogonal_projection_fn` produces a result in the orthogonal direction. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p -ᵥ p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (self_mem_mk' _ _) local attribute [instance] affine_subspace.to_add_torsor /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. -/ def orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P →ᵃ[ℝ] s := { to_fun := λ p, ⟨orthogonal_projection_fn s p, orthogonal_projection_fn_mem p⟩, linear := orthogonal_projection s.direction, map_vadd' := λ p v, begin have hs : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ s := vadd_mem_of_mem_direction (orthogonal_projection s.direction v).2 (orthogonal_projection_fn_mem p), have ho : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ mk' (v +ᵥ p) s.directionᗮ, { rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk', vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc], refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal p) _, rw submodule.mem_orthogonal', intros w hw, rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ w hw, neg_zero], }, have hm : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ ({orthogonal_projection_fn s (v +ᵥ p)} : set P), { rw ←inter_eq_singleton_orthogonal_projection_fn (v +ᵥ p), exact set.mem_inter hs ho }, rw set.mem_singleton_iff at hm, ext, exact hm.symm end } @[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p = orthogonal_projection s p := rfl /-- The linear map corresponding to `orthogonal_projection`. -/ @[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] : (orthogonal_projection s).linear = _root_.orthogonal_projection s.direction := rfl /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection` of that point onto the subspace. -/ lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection s p} := begin rw ←orthogonal_projection_fn_eq, exact inter_eq_singleton_orthogonal_projection_fn p end /-- The `orthogonal_projection` lies in the given subspace. -/ lemma orthogonal_projection_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ s := (orthogonal_projection s p).2 /-- The `orthogonal_projection` lies in the orthogonal subspace. -/ lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ mk' p s.directionᗮ := orthogonal_projection_fn_mem_orthogonal p /-- Subtracting a point in the given subspace from the `orthogonal_projection` produces a result in the direction of the given subspace. -/ lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction) ∈ s.direction := (orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction).2 /-- Subtracting the `orthogonal_projection` from a point in the given subspace produces a result in the direction of the given subspace. -/ lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction) ∈ s.direction := ((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction).2 /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : ↑(orthogonal_projection s p) = p ↔ p ∈ s := begin split, { exact λ h, h ▸ orthogonal_projection_mem p }, { intro h, have hp : p ∈ ((s : set P) ∩ mk' p s.directionᗮ) := ⟨h, self_mem_mk' p _⟩, rw [inter_eq_singleton_orthogonal_projection p] at hp, symmetry, exact hp } end @[simp] lemma orthogonal_projection_mem_subspace_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : s) : orthogonal_projection s p = p := begin ext, rw orthogonal_projection_eq_self_iff, exact p.2 end /-- Orthogonal projection is idempotent. -/ @[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p := begin ext, rw orthogonal_projection_eq_self_iff, exact orthogonal_projection_mem p, end lemma eq_orthogonal_projection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (orthogonal_projection s p : P) = (orthogonal_projection s' p : P) := begin change orthogonal_projection_fn s p = orthogonal_projection_fn s' p, congr, exact h end /-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/ lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : dist p (orthogonal_projection s p) = 0 ↔ p ∈ s := by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff] /-- The distance between a point and its orthogonal projection is nonzero if it does not lie in the subspace. -/ lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∉ s) : dist p (orthogonal_projection s p) ≠ 0 := mt dist_orthogonal_projection_eq_zero_iff.mp hp /-- Subtracting `p` from its `orthogonal_projection` produces a result in the orthogonal direction. -/ lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : (orthogonal_projection s p : P) -ᵥ p ∈ s.directionᗮ := orthogonal_projection_fn_vsub_mem_direction_orthogonal p /-- Subtracting the `orthogonal_projection` from `p` produces a result in the orthogonal direction. -/ lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : p -ᵥ orthogonal_projection s p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p) /-- Subtracting the `orthogonal_projection` from `p` produces a result in the kernel of the linear part of the orthogonal projection. -/ lemma orthogonal_projection_vsub_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : _root_.orthogonal_projection s.direction (p -ᵥ orthogonal_projection s p) = 0 := begin apply orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero, intros c hc, rw [← neg_vsub_eq_vsub_rev, inner_neg_right, (orthogonal_projection_vsub_mem_direction_orthogonal s p c hc), neg_zero] end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector was in the orthogonal direction. -/ lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : orthogonal_projection s (v +ᵥ p) = ⟨p, hp⟩ := begin have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p), rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h, refine (eq_of_vsub_eq_zero _).symm, ext, refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h, exact (_ : s.direction).2 end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) : orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_eq_self hp (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) /-- The square of the distance from a point in `s` to `p2` equals the sum of the squares of the distances of the two points to the `orthogonal_projection`. -/ lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : dist p1 p2 * dist p1 p2 = dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) + dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) := begin rw [dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2, norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero], exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal s p2), end /-- The square of the distance between two points constructed by adding multiples of the same orthogonal vector to points in the same subspace. -/ lemma dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V} (hv : v ∈ s.directionᗮ) : dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (‖v‖ * ‖v‖) := calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = ‖(p1 -ᵥ p2) + (r1 - r2) • v‖ * ‖(p1 -ᵥ p2) + (r1 - r2) • v‖ : by rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul, add_comm, add_sub_assoc] ... = ‖p1 -ᵥ p2‖ * ‖p1 -ᵥ p2‖ + ‖(r1 - r2) • v‖ * ‖(r1 - r2) • v‖ : norm_add_sq_eq_norm_sq_add_norm_sq_real (submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2) (submodule.smul_mem _ _ hv)) ... = ‖(p1 -ᵥ p2 : V)‖ * ‖(p1 -ᵥ p2 : V)‖ + |r1 - r2| * |r1 - r2| * ‖v‖ * ‖v‖ : by { rw [norm_smul, real.norm_eq_abs], ring } ... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (‖v‖ * ‖v‖) : by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] } /-- Reflection in an affine subspace, which is expected to be nonempty and complete. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in an affine subspace, is a more general sense of the word that includes both those common cases. -/ def reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P ≃ᵃⁱ[ℝ] P := affine_isometry_equiv.mk' (λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p) (_root_.reflection s.direction) ↑(classical.arbitrary s) begin intros p, let v := p -ᵥ ↑(classical.arbitrary s), let a : V := _root_.orthogonal_projection s.direction v, let b : P := ↑(classical.arbitrary s), have key : a +ᵥ b -ᵥ (v +ᵥ b) +ᵥ (a +ᵥ b) = a + a - v +ᵥ (b -ᵥ b +ᵥ b), { rw [← add_vadd, vsub_vadd_eq_vsub_sub, vsub_vadd, vadd_vsub], congr' 1, abel }, have : p = v +ᵥ ↑(classical.arbitrary s) := (vsub_vadd p ↑(classical.arbitrary s)).symm, simpa only [coe_vadd, reflection_apply, affine_map.map_vadd, orthogonal_projection_linear, orthogonal_projection_mem_subspace_eq_self, vadd_vsub, continuous_linear_map.coe_coe, continuous_linear_equiv.coe_coe, this] using key, end /-- The result of reflecting. -/ lemma reflection_apply (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s p = (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p := rfl lemma eq_reflection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (reflection s p : P) = (reflection s' p : P) := by unfreezingI { subst h } /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s (reflection s p) = p := begin have : ∀ a : s, ∀ b : V, (_root_.orthogonal_projection s.direction) b = 0 → reflection s (reflection s (b +ᵥ a)) = b +ᵥ a, { intros a b h, have : (a:P) -ᵥ (b +ᵥ a) = - b, { rw [vsub_vadd_eq_vsub_sub, vsub_self, zero_sub] }, simp [reflection, h, this] }, rw ← vsub_vadd p (orthogonal_projection s p), exact this (orthogonal_projection s p) _ (orthogonal_projection_vsub_orthogonal_projection s p), end /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : (reflection s).symm = reflection s := by { ext, rw ← (reflection s).injective.eq_iff, simp } /-- Reflection is involutive. -/ lemma reflection_involutive (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : function.involutive (reflection s) := reflection_reflection s /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : reflection s p = p ↔ p ∈ s := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, ←two_smul ℝ (↑(orthogonal_projection s p) -ᵥ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, simp [h] } end /-- Reflecting a point in two subspaces produces the same result if and only if the point has the same orthogonal projection in each of those subspaces. -/ lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P) [nonempty s₁] [nonempty s₂] [complete_space s₁.direction] [complete_space s₂.direction] (p : P) : reflection s₁ p = reflection s₂ p ↔ (orthogonal_projection s₁ p : P) = orthogonal_projection s₂ p := begin rw [reflection_apply, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, vsub_sub_vsub_cancel_right, ←two_smul ℝ ((orthogonal_projection s₁ p : P) -ᵥ orthogonal_projection s₂ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, rw h } end /-- The distance between `p₁` and the reflection of `p₂` equals that between the reflection of `p₁` and `p₂`. -/ lemma dist_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p₁ p₂ : P) : dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ := begin conv_lhs { rw ←reflection_reflection s p₁ }, exact (reflection s).dist_map _ _ end /-- A point in the subspace is equidistant from another point and its reflection. -/ lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) : dist p₁ (reflection s p₂) = dist p₁ p₂ := begin rw ←reflection_eq_self_iff p₁ at hp₁, convert (reflection s).dist_map p₁ p₂, rw hp₁ end /-- The reflection of a point in a subspace is contained in any larger subspace containing both the point and the subspace reflected in. -/ lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} [nonempty s₁] [complete_space s₁.direction] (hle : s₁ ≤ s₂) {p : P} (hp : p ∈ s₂) : reflection s₁ p ∈ s₂ := begin rw [reflection_apply], have ho : ↑(orthogonal_projection s₁ p) ∈ s₂ := hle (orthogonal_projection_mem p), exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho end /-- Reflecting an orthogonal vector plus a point in the subspace produces the negation of that vector plus the point. -/ lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : reflection s (v +ᵥ p) = -v +ᵥ p := begin rw [reflection_apply, orthogonal_projection_vadd_eq_self hp hv, vsub_vadd_eq_vsub_sub], simp end /-- Reflecting a vector plus a point in the subspace produces the negation of that vector plus the point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) : reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) = -(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ := reflection_orthogonal_vadd hp₁ (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) omit V variables (P) /-- A `sphere P` bundles a `center` and `radius`. This definition does not require the radius to be positive; that should be given as a hypothesis to lemmas that require it. -/ @[ext] structure sphere := (center : P) (radius : ℝ) variables {P} instance [nonempty P] : nonempty (sphere P) := ⟨⟨classical.arbitrary P, 0⟩⟩ instance : has_coe (sphere P) (set P) := ⟨λ s, metric.sphere s.center s.radius⟩ instance : has_mem P (sphere P) := ⟨λ p s, p ∈ (s : set P)⟩ lemma sphere.mk_center (c : P) (r : ℝ) : (⟨c, r⟩ : sphere P).center = c := rfl lemma sphere.mk_radius (c : P) (r : ℝ) : (⟨c, r⟩ : sphere P).radius = r := rfl @[simp] lemma sphere.mk_center_radius (s : sphere P) : (⟨s.center, s.radius⟩ : sphere P) = s := by ext; refl lemma sphere.coe_def (s : sphere P) : (s : set P) = metric.sphere s.center s.radius := rfl @[simp] lemma sphere.coe_mk (c : P) (r : ℝ) : ↑(⟨c, r⟩ : sphere P) = metric.sphere c r := rfl @[simp] lemma sphere.mem_coe {p : P} {s : sphere P} : p ∈ (s : set P) ↔ p ∈ s := iff.rfl lemma mem_sphere {p : P} {s : sphere P} : p ∈ s ↔ dist p s.center = s.radius := iff.rfl lemma mem_sphere' {p : P} {s : sphere P} : p ∈ s ↔ dist s.center p = s.radius := metric.mem_sphere' lemma subset_sphere {ps : set P} {s : sphere P} : ps ⊆ s ↔ ∀ p ∈ ps, p ∈ s := iff.rfl lemma dist_of_mem_subset_sphere {p : P} {ps : set P} {s : sphere P} (hp : p ∈ ps) (hps : ps ⊆ (s : set P)) : dist p s.center = s.radius := mem_sphere.1 (sphere.mem_coe.1 (set.mem_of_mem_of_subset hp hps)) lemma dist_of_mem_subset_mk_sphere {p c : P} {ps : set P} {r : ℝ} (hp : p ∈ ps) (hps : ps ⊆ ↑(⟨c, r⟩ : sphere P)) : dist p c = r := dist_of_mem_subset_sphere hp hps lemma sphere.ne_iff {s₁ s₂ : sphere P} : s₁ ≠ s₂ ↔ s₁.center ≠ s₂.center ∨ s₁.radius ≠ s₂.radius := by rw [←not_and_distrib, ←sphere.ext_iff] lemma sphere.center_eq_iff_eq_of_mem {s₁ s₂ : sphere P} {p : P} (hs₁ : p ∈ s₁) (hs₂ : p ∈ s₂) : s₁.center = s₂.center ↔ s₁ = s₂ := begin refine ⟨λ h, sphere.ext _ _ h _, λ h, h ▸ rfl⟩, rw mem_sphere at hs₁ hs₂, rw [←hs₁, ←hs₂, h] end lemma sphere.center_ne_iff_ne_of_mem {s₁ s₂ : sphere P} {p : P} (hs₁ : p ∈ s₁) (hs₂ : p ∈ s₂) : s₁.center ≠ s₂.center ↔ s₁ ≠ s₂ := (sphere.center_eq_iff_eq_of_mem hs₁ hs₂).not lemma dist_center_eq_dist_center_of_mem_sphere {p₁ p₂ : P} {s : sphere P} (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) : dist p₁ s.center = dist p₂ s.center := by rw [mem_sphere.1 hp₁, mem_sphere.1 hp₂] lemma dist_center_eq_dist_center_of_mem_sphere' {p₁ p₂ : P} {s : sphere P} (hp₁ : p₁ ∈ s) (hp₂ : p₂ ∈ s) : dist s.center p₁ = dist s.center p₂ := by rw [mem_sphere'.1 hp₁, mem_sphere'.1 hp₂] /-- A set of points is cospherical if they are equidistant from some point. In two dimensions, this is the same thing as being concyclic. -/ def cospherical (ps : set P) : Prop := ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius /-- The definition of `cospherical`. -/ lemma cospherical_def (ps : set P) : cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := iff.rfl /-- A set of points is cospherical if and only if they lie in some sphere. -/ lemma cospherical_iff_exists_sphere {ps : set P} : cospherical ps ↔ ∃ s : sphere P, ps ⊆ (s : set P) := begin refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨c, r, h⟩, exact ⟨⟨c, r⟩, h⟩ }, { rcases h with ⟨s, h⟩, exact ⟨s.center, s.radius, h⟩ } end /-- The set of points in a sphere is cospherical. -/ lemma sphere.cospherical (s : sphere P) : cospherical (s : set P) := cospherical_iff_exists_sphere.2 ⟨s, set.subset.rfl⟩ /-- A subset of a cospherical set is cospherical. -/ lemma cospherical.subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) : cospherical ps₁ := begin rcases hc with ⟨c, r, hcr⟩, exact ⟨c, r, λ p hp, hcr p (hs hp)⟩ end include V /-- The empty set is cospherical. -/ lemma cospherical_empty : cospherical (∅ : set P) := begin use add_torsor.nonempty.some, simp, end omit V /-- A single point is cospherical. -/ lemma cospherical_singleton (p : P) : cospherical ({p} : set P) := begin use p, simp end include V /-- Two points are cospherical. -/ lemma cospherical_pair (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) := begin use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)], intro p, rw [set.mem_insert_iff, set.mem_singleton_iff], rintro ⟨_|_⟩, { rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul, dist_eq_norm_vsub V p₂], simp }, { rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂], conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) }, rw [←sub_smul, norm_smul], norm_num } end /-- Any three points in a cospherical set are affinely independent. -/ lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rw affine_independent_iff_not_collinear, intro hc, rw collinear_iff_of_mem (set.mem_range_self (0 : fin 3)) at hc, rcases hc with ⟨v, hv⟩, rw set.forall_range_iff at hv, have hv0 : v ≠ 0, { intro h, have he : p 1 = p 0, by simpa [h] using hv 1, exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) }, rcases hs with ⟨c, r, hs⟩, have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps), choose f hf using hv, have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r, { intro i, rw ←hf, exact hs' i }, have hf0 : f 0 = 0, { have hf0' := hf 0, rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0', simpa [hv0] using hf0' }, have hfi : function.injective f, { intros i j h, have hi := hf i, rw [h, ←hf j] at hi, exact hpi hi }, simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd, have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2, have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫, { intros i hi, have hsdi := hsd i, simpa [hfn0, hi] using hsdi }, have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] }, exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12) end /-- Suppose that `p₁` and `p₂` lie in spheres `s₁` and `s₂`. Then the vector between the centers of those spheres is orthogonal to that between `p₁` and `p₂`; this is a version of `inner_vsub_vsub_of_dist_eq_of_dist_eq` for bundled spheres. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ lemma inner_vsub_vsub_of_mem_sphere_of_mem_sphere {p₁ p₂ : P} {s₁ s₂ : sphere P} (hp₁s₁ : p₁ ∈ s₁) (hp₂s₁ : p₂ ∈ s₁) (hp₁s₂ : p₁ ∈ s₂) (hp₂s₂ : p₂ ∈ s₂) : ⟪s₂.center -ᵥ s₁.center, p₂ -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (dist_center_eq_dist_center_of_mem_sphere hp₁s₁ hp₂s₁) (dist_center_eq_dist_center_of_mem_sphere hp₁s₂ hp₂s₂) /-- Two spheres intersect in at most two points in a two-dimensional subspace containing their centers; this is a version of `eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two` for bundled spheres. -/ lemma eq_of_mem_sphere_of_mem_sphere_of_mem_of_finrank_eq_two {s : affine_subspace ℝ P} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = 2) {s₁ s₂ : sphere P} {p₁ p₂ p : P} (hs₁ : s₁.center ∈ s) (hs₂ : s₂.center ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) (hs : s₁ ≠ s₂) (hp : p₁ ≠ p₂) (hp₁s₁ : p₁ ∈ s₁) (hp₂s₁ : p₂ ∈ s₁) (hps₁ : p ∈ s₁) (hp₁s₂ : p₁ ∈ s₂) (hp₂s₂ : p₂ ∈ s₂) (hps₂ : p ∈ s₂) : p = p₁ ∨ p = p₂ := eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two hd hs₁ hs₂ hp₁s hp₂s hps ((sphere.center_ne_iff_ne_of_mem hps₁ hps₂).2 hs) hp hp₁s₁ hp₂s₁ hps₁ hp₁s₂ hp₂s₂ hps₂ /-- Two spheres intersect in at most two points in two-dimensional space; this is a version of `eq_of_dist_eq_of_dist_eq_of_finrank_eq_two` for bundled spheres. -/ lemma eq_of_mem_sphere_of_mem_sphere_of_finrank_eq_two [finite_dimensional ℝ V] (hd : finrank ℝ V = 2) {s₁ s₂ : sphere P} {p₁ p₂ p : P} (hs : s₁ ≠ s₂) (hp : p₁ ≠ p₂) (hp₁s₁ : p₁ ∈ s₁) (hp₂s₁ : p₂ ∈ s₁) (hps₁ : p ∈ s₁) (hp₁s₂ : p₁ ∈ s₂) (hp₂s₂ : p₂ ∈ s₂) (hps₂ : p ∈ s₂) : p = p₁ ∨ p = p₂ := eq_of_dist_eq_of_dist_eq_of_finrank_eq_two hd ((sphere.center_ne_iff_ne_of_mem hps₁ hps₂).2 hs) hp hp₁s₁ hp₂s₁ hps₁ hp₁s₂ hp₂s₂ hps₂ /-- A set of points is concyclic if it is cospherical and coplanar. (Most results are stated directly in terms of `cospherical` instead of using `concyclic`.) -/ structure concyclic (ps : set P) : Prop := (cospherical : cospherical ps) (coplanar : coplanar ℝ ps) /-- A subset of a concyclic set is concyclic. -/ lemma concyclic.subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (h : concyclic ps₂) : concyclic ps₁ := ⟨h.1.subset hs, h.2.subset hs⟩ /-- The empty set is concyclic. -/ lemma concyclic_empty : concyclic (∅ : set P) := ⟨cospherical_empty, coplanar_empty ℝ P⟩ /-- A single point is concyclic. -/ lemma concyclic_singleton (p : P) : concyclic ({p} : set P) := ⟨cospherical_singleton p, coplanar_singleton ℝ p⟩ /-- Two points are concyclic. -/ lemma concyclic_pair (p₁ p₂ : P) : concyclic ({p₁, p₂} : set P) := ⟨cospherical_pair p₁ p₂, coplanar_pair ℝ p₁ p₂⟩ end euclidean_geometry
fdd829f86cba93b67264b19be004acc2b323b51c
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/omega/coeffs.lean
769ca23c08e6bee8458443d8abf2ff2619521dd9
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
10,603
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek Non-constant terms of linear constraints are represented by storing their coefficients in integer lists. -/ import data.list.func import tactic.ring import tactic.omega.misc namespace omega namespace coeffs open list.func variable {v : nat → int} /-- `val_between v as l o` is the value (under valuation `v`) of the term obtained taking the term represented by `(0, as)` and dropping all subterms that include variables outside the range `[l,l+o)` -/ @[simp] def val_between (v : nat → int) (as : list int) (l : nat) : nat → int | 0 := 0 | (o+1) := (val_between o) + (get (l+o) as * v (l+o)) @[simp] lemma val_between_nil {l : nat} : ∀ m, val_between v [] l m = 0 | 0 := by simp only [val_between] | (m+1) := by simp only [val_between_nil m, omega.coeffs.val_between, get_nil, zero_add, zero_mul, int.default_eq_zero] /-- Evaluation of the nonconstant component of a normalized linear arithmetic term. -/ def val (v : nat → int) (as : list int) : int := val_between v as 0 as.length @[simp] lemma val_nil : val v [] = 0 := rfl lemma val_between_eq_of_le {as : list int} {l : nat} : ∀ m, as.length ≤ l + m → val_between v as l m = val_between v as l (as.length - l) | 0 h1 := begin rw (nat.sub_eq_zero_iff_le.elim_right _), apply h1 end | (m+1) h1 := begin rw le_iff_eq_or_lt at h1, cases h1, { rw [h1, add_comm l, nat.add_sub_cancel] }, have h2 : list.length as ≤ l + m, { rw ← nat.lt_succ_iff, apply h1 }, simpa [ get_eq_default_of_le _ h2, zero_mul, add_zero, val_between ] using val_between_eq_of_le _ h2 end lemma val_eq_of_le {as : list int} {k : nat} : as.length ≤ k → val v as = val_between v as 0 k := begin intro h1, unfold val, rw [val_between_eq_of_le k _], refl, rw zero_add, exact h1 end lemma val_between_eq_val_between {v w : nat → int} {as bs : list int} {l : nat} : ∀ {m}, (∀ x, l ≤ x → x < l + m → v x = w x) → (∀ x, l ≤ x → x < l + m → get x as = get x bs) → val_between v as l m = val_between w bs l m | 0 h1 h2 := rfl | (m+1) h1 h2 := begin unfold val_between, have h3 : l + m < l + (m + 1), { rw ← add_assoc, apply lt_add_one }, apply fun_mono_2, apply val_between_eq_val_between; intros x h4 h5, { apply h1 _ h4 (lt_trans h5 h3) }, { apply h2 _ h4 (lt_trans h5 h3) }, rw [h1 _ _ h3, h2 _ _ h3]; apply nat.le_add_right end open_locale list.func lemma val_between_set {a : int} {l n : nat} : ∀ {m}, l ≤ n → n < l + m → val_between v ([] {n ↦ a}) l m = a * v n | 0 h1 h2 := begin exfalso, apply lt_irrefl l (lt_of_le_of_lt h1 h2) end | (m+1) h1 h2 := begin rw [← add_assoc, nat.lt_succ_iff, le_iff_eq_or_lt] at h2, cases h2; unfold val_between, { have h3 : val_between v ([] {l + m ↦ a}) l m = 0, { apply @eq.trans _ _ (val_between v [] l m), { apply val_between_eq_val_between, { intros, refl }, { intros x h4 h5, rw [get_nil, get_set_eq_of_ne, get_nil], apply ne_of_lt h5 } }, apply val_between_nil }, rw h2, simp only [h3, zero_add, list.func.get_set] }, { have h3 : l + m ≠ n, { apply ne_of_gt h2 }, rw [@val_between_set m h1 h2, get_set_eq_of_ne _ _ h3], simp only [h3, get_nil, add_zero, zero_mul, int.default_eq_zero] } end @[simp] lemma val_set {m : nat} {a : int} : val v ([] {m ↦ a}) = a * v m := begin apply val_between_set, apply zero_le, apply lt_of_lt_of_le (lt_add_one _), simp only [length_set, zero_add, le_max_right], end lemma val_between_neg {as : list int} {l : nat} : ∀ {o}, val_between v (neg as) l o = -(val_between v as l o) | 0 := rfl | (o+1) := begin unfold val_between, rw [neg_add, neg_mul_eq_neg_mul], apply fun_mono_2, apply val_between_neg, apply fun_mono_2 _ rfl, apply get_neg end @[simp] lemma val_neg {as : list int} : val v (neg as) = -(val v as) := by simpa only [val, length_neg] using val_between_neg lemma val_between_add {is js : list int} {l : nat} : ∀ m, val_between v (add is js) l m = (val_between v is l m) + (val_between v js l m) | 0 := rfl | (m+1) := by { simp only [val_between, val_between_add m, list.func.get, get_add], ring } @[simp] lemma val_add {is js : list int} : val v (add is js) = (val v is) + (val v js) := begin unfold val, rw val_between_add, apply fun_mono_2; apply val_between_eq_of_le; rw [zero_add, length_add], apply le_max_left, apply le_max_right end lemma val_between_sub {is js : list int} {l : nat} : ∀ m, val_between v (sub is js) l m = (val_between v is l m) - (val_between v js l m) | 0 := rfl | (m+1) := by { simp only [val_between, val_between_sub m, list.func.get, get_sub], ring } @[simp] lemma val_sub {is js : list int} : val v (sub is js) = (val v is) - (val v js) := begin unfold val, rw val_between_sub, apply fun_mono_2; apply val_between_eq_of_le; rw [zero_add, length_sub], apply le_max_left, apply le_max_right end /-- `val_except k v as` is the value (under valuation `v`) of the term obtained taking the term represented by `(0, as)` and dropping the subterm that includes the `k`th variable. -/ def val_except (k : nat) (v : nat → int) (as) := val_between v as 0 k + val_between v as (k+1) (as.length - (k+1)) lemma val_except_eq_val_except {k : nat} {is js : list int} {v w : nat → int} : (∀ x ≠ k, v x = w x) → (∀ x ≠ k, get x is = get x js) → val_except k v is = val_except k w js := begin intros h1 h2, unfold val_except, apply fun_mono_2, { apply val_between_eq_val_between; intros x h3 h4; [ {apply h1}, {apply h2} ]; apply ne_of_lt; rw zero_add at h4; apply h4 }, { repeat { rw ← val_between_eq_of_le ((max is.length js.length) - (k+1)) }, { apply val_between_eq_val_between; intros x h3 h4; [ {apply h1}, {apply h2} ]; apply ne.symm; apply ne_of_lt; rw nat.lt_iff_add_one_le; exact h3 }, repeat { rw add_comm, apply le_trans _ (nat.le_sub_add _ _), { apply le_max_right <|> apply le_max_left } } } end open_locale omega lemma val_except_update_set {n : nat} {as : list int} {i j : int} : val_except n (v⟨n ↦ i⟩) (as {n ↦ j}) = val_except n v as := by apply val_except_eq_val_except update_eq_of_ne (get_set_eq_of_ne _) lemma val_between_add_val_between {as : list int} {l m : nat} : ∀ {n}, val_between v as l m + val_between v as (l+m) n = val_between v as l (m+n) | 0 := by simp only [val_between, add_zero] | (n+1) := begin rw ← add_assoc, unfold val_between, rw add_assoc, rw ← @val_between_add_val_between n, ring, end lemma val_except_add_eq (n : nat) {as : list int} : (val_except n v as) + ((get n as) * (v n)) = val v as := begin unfold val_except, unfold val, by_cases h1 : n + 1 ≤ as.length, { have h4 := @val_between_add_val_between v as 0 (n+1) (as.length - (n+1)), have h5 : n + 1 + (as.length - (n + 1)) = as.length, { rw [add_comm, nat.sub_add_cancel h1] }, rw h5 at h4, apply eq.trans _ h4, simp only [val_between, zero_add], ring }, have h2 : (list.length as - (n + 1)) = 0, { apply nat.sub_eq_zero_of_le (le_trans (not_lt.1 h1) (nat.le_add_right _ _)) }, have h3 : val_between v as 0 (list.length as) = val_between v as 0 (n + 1), { simpa only [val] using @val_eq_of_le v as (n+1) (le_trans (not_lt.1 h1) (nat.le_add_right _ _)) }, simp only [add_zero, val_between, zero_add, h2, h3] end @[simp] lemma val_between_map_mul {i : int} {as: list int} {l : nat} : ∀ {m}, val_between v (list.map ((*) i) as) l m = i * val_between v as l m | 0 := by simp only [val_between, mul_zero, list.map] | (m+1) := begin unfold val_between, rw [@val_between_map_mul m, mul_add], apply fun_mono_2 rfl, by_cases h1 : l + m < as.length, { rw [get_map h1, mul_assoc] }, rw not_lt at h1, rw [get_eq_default_of_le, get_eq_default_of_le]; try {simp}; apply h1 end lemma forall_val_dvd_of_forall_mem_dvd {i : int} {as : list int} : (∀ x ∈ as, i ∣ x) → (∀ n, i ∣ get n as) | h1 n := by { apply forall_val_of_forall_mem _ h1, apply dvd_zero } lemma dvd_val_between {i} {as: list int} {l : nat} : ∀ {m}, (∀ x ∈ as, i ∣ x) → (i ∣ val_between v as l m) | 0 h1 := dvd_zero _ | (m+1) h1 := begin unfold val_between, apply dvd_add, apply dvd_val_between h1, apply dvd_mul_of_dvd_left, by_cases h2 : get (l+m) as = 0, { rw h2, apply dvd_zero }, apply h1, apply mem_get_of_ne_zero h2 end lemma dvd_val {as : list int} {i : int} : (∀ x ∈ as, i ∣ x) → (i ∣ val v as) := by apply dvd_val_between @[simp] lemma val_between_map_div {as: list int} {i : int} {l : nat} (h1 : ∀ x ∈ as, i ∣ x) : ∀ {m}, val_between v (list.map (λ x, x / i) as) l m = (val_between v as l m) / i | 0 := by simp only [int.zero_div, val_between, list.map] | (m+1) := begin unfold val_between, rw [@val_between_map_div m, int.add_div_of_dvd (dvd_val_between h1)], apply fun_mono_2 rfl, { apply calc get (l + m) (list.map (λ (x : ℤ), x / i) as) * v (l + m) = ((get (l + m) as) / i) * v (l + m) : begin apply fun_mono_2 _ rfl, rw get_map', apply int.zero_div end ... = get (l + m) as * v (l + m) / i : begin repeat {rw mul_comm _ (v (l+m))}, rw int.mul_div_assoc, apply forall_val_dvd_of_forall_mem_dvd h1 end }, apply dvd_mul_of_dvd_left, apply forall_val_dvd_of_forall_mem_dvd h1, end @[simp] lemma val_map_div {as : list int} {i : int} : (∀ x ∈ as, i ∣ x) → val v (list.map (λ x, x / i) as) = (val v as) / i := by {intro h1, simpa only [val, list.length_map] using val_between_map_div h1} lemma val_between_eq_zero {is: list int} {l : nat} : ∀ {m}, (∀ x : int, x ∈ is → x = 0) → val_between v is l m = 0 | 0 h1 := rfl | (m+1) h1 := begin have h2 := @forall_val_of_forall_mem _ _ is (λ x, x = 0) rfl h1, simpa only [val_between, h2 (l+m), zero_mul, add_zero] using @val_between_eq_zero m h1, end lemma val_eq_zero {is : list int} : (∀ x : int, x ∈ is → x = 0) → val v is = 0 := by apply val_between_eq_zero end coeffs end omega
576e55cbd7dee927fa3dded6f8fd063cd1630403
abd85493667895c57a7507870867b28124b3998f
/src/data/real/cau_seq.lean
15b55497af7825d61bbe3ac55c6861d4701a228e
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
24,856
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.big_operators /-! # Cauchy sequences A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where applicable, lemmas that will be reused in other contexts have been stated in extra generality. There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology. This is a concrete implementation that is useful for simplicity and computability reasons. ## Important definitions * `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val * `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy. ## Tags sequence, cauchy, abs val, absolute value -/ /-- A function f is an absolute value if it is nonnegative, zero only at 0, additive, and multiplicative. -/ class is_absolute_value {α} [discrete_linear_ordered_field α] {β} [ring β] (f : β → α) : Prop := (abv_nonneg [] : ∀ x, 0 ≤ f x) (abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0) (abv_add [] : ∀ x y, f (x + y) ≤ f x + f y) (abv_mul [] : ∀ x y, f (x * y) = f x * f y) namespace is_absolute_value variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl theorem abv_one' (h : (1:β) ≠ 0) : abv 1 = 1 := (domain.mul_right_inj $ mt (abv_eq_zero abv).1 h).1 $ by rw [← abv_mul abv, mul_one, mul_one] theorem abv_one {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] : abv 1 = 1 := abv_one' abv one_ne_zero theorem abv_pos {a : β} : 0 < abv a ↔ a ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv] theorem abv_neg (a : β) : abv (-a) = abv a := by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _), ← abv_mul abv, ← abv_mul abv]; simp theorem abv_sub (a b : β) : abv (a - b) = abv (b - a) := by rw [← neg_sub, abv_neg abv] theorem abv_inv {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a : β) : abv a⁻¹ = (abv a)⁻¹ := classical.by_cases (λ h : a = 0, by simp [h, abv_zero abv]) (λ h, (domain.mul_left_inj (mt (abv_eq_zero abv).1 h)).1 $ by rw [← abv_mul abv]; simp [h, mt (abv_eq_zero abv).1 h, abv_one abv]) theorem abv_div {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] (a b : β) : abv (a / b) = abv a / abv b := by rw [division_def, abv_mul abv, abv_inv abv]; refl lemma abv_sub_le (a b c : β) : abv (a - c) ≤ abv (a - b) + abv (b - c) := by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c) lemma sub_abv_le_abv_sub (a b : β) : abv a - abv b ≤ abv (a - b) := sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b lemma abs_abv_sub_le_abv_sub (a b : β) : abs (abv a - abv b) ≤ abv (a - b) := abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _, by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩ lemma abv_pow {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] (a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n := by induction n; simp [abv_mul abv, pow_succ, abv_one abv, *] end is_absolute_value instance abs_is_absolute_value {α} [discrete_linear_ordered_field α] : is_absolute_value (abs : α → α) := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} : (∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) → ∃ i, ∀ j ≥ i, P j ∧ Q j | ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in ⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩ section variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) [is_absolute_value abv] theorem rat_add_continuous_lemma {ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε := ⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂, by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩ theorem rat_mul_continuous_lemma {ε K₁ K₂ : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ → abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε := begin have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _), have εK := div_pos (half_pos ε0) K0, refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩, replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)), replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)), have := add_lt_add (mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK) (mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK), rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this, simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm] using lt_of_le_of_lt (abv_add abv _ _) this end theorem rat_inv_continuous_lemma {β : Type*} [field β] (abv : β → α) [is_absolute_value abv] {ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) : ∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b → abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε := begin have KK := mul_pos K0 K0, have εK := mul_pos ε0 KK, refine ⟨_, εK, λ a b ha hb h, _⟩, have a0 := lt_of_lt_of_le K0 ha, have b0 := lt_of_lt_of_le K0 hb, rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0), abv_div abv, abv_mul abv, mul_comm, abv_sub abv, ← mul_div_cancel ε (ne_of_gt KK)], exact div_lt_div h (mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _)) (le_of_lt $ mul_pos ε0 KK) KK end end /-- A sequence is Cauchy if the distance between its entries tends to zero. -/ def is_cau_seq {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] (abv : β → α) (f : ℕ → β) := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε namespace is_cau_seq variables {α : Type*} [discrete_linear_ordered_field α] {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β} theorem cauchy₂ (hf : is_cau_seq abv f) {ε:α} (ε0 : ε > 0) : ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := begin refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _), rw ← add_halves ε, refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _), rw abv_sub abv, exact hi _ ik end theorem cauchy₃ (hf : is_cau_seq abv f) {ε:α} (ε0 : ε > 0) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩ end is_cau_seq def cau_seq {α : Type*} [discrete_linear_ordered_field α] (β : Type*) [ring β] (abv : β → α) := {f : ℕ → β // is_cau_seq abv f} namespace cau_seq variables {α : Type*} [discrete_linear_ordered_field α] section ring variables {β : Type*} [ring β] {abv : β → α} instance : has_coe_to_fun (cau_seq β abv) := ⟨_, subtype.val⟩ @[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) : @coe_fn (cau_seq β abv) _ ⟨f, hf⟩ = f := rfl theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g := subtype.eq (funext h) theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2 theorem cauchy (f : cau_seq β abv) : ∀ {ε}, ε > 0 → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2 def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv := ⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩ variable [is_absolute_value abv] theorem cauchy₂ (f : cau_seq β abv) {ε:α} : ε > 0 → ∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂ theorem cauchy₃ (f : cau_seq β abv) {ε:α} : ε > 0 → ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃ theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r := begin cases f.cauchy zero_lt_one with i h, let R := (finset.range (i+1)).sum (λ j, abv (f j)), have : ∀ j ≤ i, abv (f j) ≤ R, { intros j ij, change (λ j, abv (f j)) j ≤ R, apply finset.single_le_sum, { intros, apply abv_nonneg abv }, { rwa [finset.mem_range, nat.lt_succ_iff] } }, refine ⟨R + 1, λ j, _⟩, cases lt_or_le j i with ij ij, { exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) }, { have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)), rw [add_sub, add_comm] at this, simpa } end theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r := let ⟨r, h⟩ := f.bounded in ⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _), λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩ instance : has_add (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl variable (abv) /-- The constant Cauchy sequence. -/ def const (x : β) : cau_seq β abv := ⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩ variable {abv} local notation `const` := const abv @[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y := ⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩ instance : has_zero (cau_seq β abv) := ⟨const 0⟩ instance : has_one (cau_seq β abv) := ⟨const 1⟩ instance : inhabited (cau_seq β abv) := ⟨0⟩ @[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl @[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl theorem const_add (x y : β) : const (x + y) = const x + const y := ext $ λ i, rfl instance : has_mul (cau_seq β abv) := ⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0, let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0, ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0, ⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩ @[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl theorem const_mul (x y : β) : const (x * y) = const x * const y := ext $ λ i, rfl instance : has_neg (cau_seq β abv) := ⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩ @[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl theorem const_neg (x : β) : const (-x) = -const x := ext $ λ i, rfl instance : ring (cau_seq β abv) := by refine {neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, ..}; { intros, apply ext, simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm] } instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] : comm_ring (cau_seq β abv) := { mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm], ..cau_seq.ring } theorem const_sub (x y : β) : const (x - y) = const x - const y := by rw [sub_eq_add_neg, const_add, const_neg, sub_eq_add_neg] @[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl /-- `lim_zero f` holds when `f` approaches 0. -/ def lim_zero (f : cau_seq β abv) := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε theorem add_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g) | ε ε0 := (exists_forall_ge_and (hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $ λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂) theorem mul_lim_zero_right (f : cau_seq β abv) {g} (hg : lim_zero g) : lim_zero (f * g) | ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in (hg _ $ div_pos ε0 F0).imp $ λ i H j ij, by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0; rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this theorem mul_lim_zero_left {f} (g : cau_seq β abv) (hg : lim_zero f) : lim_zero (f * g) | ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in (hg _ $ div_pos ε0 G0).imp $ λ i H j ij, by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _); rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) := by rw ← neg_one_mul; exact mul_lim_zero_right _ hf theorem sub_lim_zero {f g : cau_seq β abv} (hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) := add_lim_zero hf (neg_lim_zero hg) theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) := by simpa using neg_lim_zero hfg theorem zero_lim_zero : lim_zero (0 : cau_seq β abv) | ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩ theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 := ⟨λ H, (abv_eq_zero abv).1 $ eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $ λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _), λ e, e.symm ▸ zero_lim_zero⟩ instance equiv : setoid (cau_seq β abv) := ⟨λ f g, lim_zero (f - g), ⟨λ f, by simp [zero_lim_zero], λ f g h, by simpa using neg_lim_zero h, λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩ theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε:α} (ε0 : 0 < ε) : ∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε := (exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $ λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk)); rwa [sub_add_sub_cancel', add_halves] at this theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g := ⟨λ l, by simpa using add_lim_zero (setoid.symm h) l, λ l, by simpa using add_lim_zero h l⟩ theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) := begin haveI := classical.prop_decidable, by_contra nk, refine hf (λ ε ε0, _), simp [not_forall] at nk, cases f.cauchy₃ (half_pos ε0) with i hi, rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩, refine ⟨j, λ k jk, _⟩, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj), rwa [sub_add_cancel, add_halves] at this end theorem of_near (f : ℕ → β) (g : cau_seq β abv) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f | ε ε0 := let ⟨i, hi⟩ := exists_forall_ge_and (h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in ⟨i, λ j ij, begin cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁, have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁), have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)), rwa [add_halves, add_halves, add_right_comm, sub_add_sub_cancel, sub_add_sub_cancel] at this end⟩ lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f := assume : lim_zero f, have lim_zero (f - 0), by simpa, hf this lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 := have lim_zero (f - 0), from hf, have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa, show lim_zero (g*f - 0), by simpa lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 := assume : lim_zero (f*g - 0), have hlz : lim_zero (f*g), by simpa, have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf), have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg), begin rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩, rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩, have : a1 * a2 > 0, from mul_pos ha1 ha2, cases hlz _ this with N hN, let i := max N (max N1 N2), have hN' := hN i (le_max_left _ _), have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)), have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)), apply not_le_of_lt hN', change _ ≤ abv (_ * _), rw is_absolute_value.abv_mul abv, apply mul_le_mul; try { assumption }, { apply le_of_lt ha2 }, { apply is_absolute_value.abv_nonneg abv } end theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y := show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero] end ring section comm_ring variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 := by rw mul_comm; apply mul_equiv_zero _ hf end comm_ring section integral_domain variables {β : Type*} [integral_domain β] (abv : β → α) [is_absolute_value abv] lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) := assume h, have ∀ ε > 0, ∃ i, ∀ k, k ≥ i → abv (1 - 0) < ε, from h, have h1 : abv 1 ≤ 0, from le_of_not_gt $ assume h2 : abv 1 > 0, exists.elim (this _ h2) $ λ i hi, lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _), have h2 : abv 1 ≥ 0, from is_absolute_value.abv_nonneg _ _, have abv 1 = 0, from le_antisymm h1 h2, have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this, absurd this one_ne_zero end integral_domain section field variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 := let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf, ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0, ⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in ⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩ def inv (f) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩ @[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 := λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in ⟨i, λ j ij, by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)), abv_zero abv] using ε0⟩ theorem const_inv {x : β} (hx : x ≠ 0) : const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) := ext (assume n, by simp[inv_apply, const_apply]) end field section abs local notation `const` := const abs /-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/ def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0), ⟨h₁, h₂⟩ := h _ (le_refl _) in not_lt_of_le h₁ (abs_lt.1 h₂).2 theorem const_pos {x : α} : pos (const x) ↔ 0 < x := ⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)), λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩ theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.add_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩ theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g) | ⟨F, F0, hF⟩ H := let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in ⟨_, half_pos F0, i, λ j ij, begin cases h j ij with h₁ h₂, have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1), rwa [← sub_eq_add_neg, sub_self_div_two] at this end⟩ protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g) | ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ := let ⟨i, h⟩ := exists_forall_ge_and hF hG in ⟨_, _root_.mul_pos F0 G0, i, λ j ij, let ⟨h₁, h₂⟩ := h _ ij in mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩ theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) := begin cases classical.em (lim_zero f); simp *, rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩, rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩, refine (le_total 0 (f i)).imp _ _; refine (λ h, ⟨K, K0, i, λ j ij, _⟩); have := (hi _ ij).1; cases hi _ (le_refl _) with h₁ h₂, { rwa abs_of_nonneg at this, rw abs_of_nonneg h at h₁, exact (le_add_iff_nonneg_right _).1 (le_trans h₁ $ neg_le_sub_iff_le_add'.1 $ le_of_lt (abs_lt.1 $ h₂ _ ij).1) }, { rwa abs_of_nonpos at this, rw abs_of_nonpos h at h₁, rw [← sub_le_sub_iff_right, zero_sub], exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ } end instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩ instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩ theorem lt_of_lt_of_eq {f g h : cau_seq α abs} (fg : f < g) (gh : g ≈ h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh) theorem lt_of_eq_of_lt {f g h : cau_seq α abs} (fg : f ≈ g) (gh : g < h) : f < h := by have := pos_add_lim_zero gh (neg_lim_zero fg); rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h := by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f | h := not_lim_zero_of_pos h (by simp [zero_lim_zero]) lemma le_of_eq_of_le {f g h : cau_seq α abs} (hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h := hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg) (or.inr ∘ setoid.trans hfg) lemma le_of_le_of_eq {f g h : cau_seq α abs} (hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h := hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh)) (λ h, or.inr (setoid.trans h hgh)) instance : preorder (cau_seq α abs) := { lt := (<), le := λ f g, f < g ∨ f ≈ g, le_refl := λ f, or.inr (setoid.refl _), le_trans := λ f g h fg, match fg with | or.inl fg, or.inl gh := or.inl $ lt_trans fg gh | or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh | or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh | or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh end, lt_iff_le_not_le := λ f g, ⟨λ h, ⟨or.inl h, not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_right (mt (λ h, or.inr (setoid.symm h)) h₂)⟩ } theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g := fg.resolve_left (not_lt_of_le gf) theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f := (trichotomy (g - f)).imp_right (λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h)) theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f := (or.assoc.2 (lt_total f g)).imp_right or.inl theorem const_lt {x y : α} : const x < const y ↔ x < y := show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos] theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y := by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv lemma le_of_exists {f g : cau_seq α abs} (h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g := let ⟨i, hi⟩ := h in (or.assoc.2 (cau_seq.lt_total f g)).elim id (λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in not_lt_of_ge (hi (max i j) (le_max_left _ _)) (sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _)))))) theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a := let ⟨K, H⟩ := f.bounded in ⟨K + 1, 1, zero_lt_one, 0, λ i _, begin rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right], exact le_of_lt (abs_lt.1 (H _)).2 end⟩ theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f := let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _, by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩ end abs end cau_seq
a4d568037f415dd89a400c795ed7a017944a03c6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/100-theorems-list/37_solution_of_cubic.lean
efa87d1353b091e1308c82d3ca18777dcbcd3caf
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,896
lean
/- Copyright (c) 2022 Jeoff Lee. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeoff Lee -/ import tactic.linear_combination import ring_theory.roots_of_unity import ring_theory.polynomial.cyclotomic.basic /-! # The Solution of a Cubic This file proves Theorem 37 from the [100 Theorems List](https://www.cs.ru.nl/~freek/100/). In this file, we give the solutions to the cubic equation `a * x^3 + b * x^2 + c * x + d = 0` over a field `K` that has characteristic neither 2 nor 3, that has a third primitive root of unity, and in which certain other quantities admit square and cube roots. This is based on the [Cardano's Formula](https://en.wikipedia.org/wiki/Cubic_equation#Cardano's_formula). ## Main statements - `cubic_eq_zero_iff` : gives the roots of the cubic equation where the discriminant `p = 3 * a * c - b^2` is nonzero. - `cubic_eq_zero_iff_of_p_eq_zero` : gives the roots of the cubic equation where the discriminant equals zero. ## References Originally ported from Isabelle/HOL. The [original file](https://isabelle.in.tum.de/dist/library/HOL/HOL-ex/Cubic_Quartic.html) was written by Amine Chaieb. ## Tags polynomial, cubic, root -/ section field open polynomial variables {K : Type*} [field K] variables [invertible (2 : K)] [invertible (3 : K)] variables (a b c d : K) variables {ω p q r s t : K} lemma cube_root_of_unity_sum (hω : is_primitive_root ω 3) : 1 + ω + ω^2 = 0 := begin convert hω.is_root_cyclotomic (nat.succ_pos _), simp only [cyclotomic_prime, eval_geom_sum], simp [finset.sum_range_succ] end /-- The roots of a monic cubic whose quadratic term is zero and whose discriminant is nonzero. -/ lemma cubic_basic_eq_zero_iff (hω : is_primitive_root ω 3) (hp_nonzero : p ≠ 0) (hr : r^2 = q^2 + p^3) (hs3 : s^3 = q + r) (ht : t * s = p) (x : K) : x^3 + 3 * p * x - 2 * q = 0 ↔ x = s - t ∨ x = s * ω - t * ω^2 ∨ x = s * ω^2 - t * ω := begin have h₁ : ∀ x a₁ a₂ a₃ : K, x = a₁ ∨ x = a₂ ∨ x = a₃ ↔ (x - a₁) * (x - a₂) * (x - a₃) = 0, { intros, simp only [mul_eq_zero, sub_eq_zero, or.assoc] }, rw h₁, refine eq.congr _ rfl, have hs_nonzero : s ≠ 0, { contrapose! hp_nonzero with hs_nonzero, linear_combination -1*ht + t*hs_nonzero }, rw ← mul_left_inj' (pow_ne_zero 3 hs_nonzero), have H := cube_root_of_unity_sum hω, linear_combination hr + (- q + r + s ^ 3) * hs3 - (3 * x * s ^ 3 + (t * s) ^ 2 + (t * s) * p + p ^ 2) * ht + ((x ^ 2 * (s - t) + x * (- ω * (s ^ 2 + t ^ 2) + s * t * (3 + ω ^ 2 - ω)) - (-(s ^ 3 - t ^ 3) * (ω - 1) + s^2 * t * ω ^ 2 - s * t^2 * ω ^ 2)) * s ^ 3) * H, end /-- Roots of a monic cubic whose discriminant is nonzero. -/ lemma cubic_monic_eq_zero_iff (hω : is_primitive_root ω 3) (hp : p = (3 * c - b^2) / 9) (hp_nonzero : p ≠ 0) (hq : q = (9 * b * c - 2 * b^3 - 27 * d) / 54) (hr : r^2 = q^2 + p^3) (hs3 : s^3 = q + r) (ht : t * s = p) (x : K) : x^3 + b * x^2 + c * x + d = 0 ↔ x = s - t - b / 3 ∨ x = s * ω - t * ω^2 - b / 3 ∨ x = s * ω^2 - t * ω - b / 3 := begin let y := x + b / 3, have hi2 : (2 : K) ≠ 0 := nonzero_of_invertible _, have hi3 : (3 : K) ≠ 0 := nonzero_of_invertible _, have h9 : (9 : K) = 3^2 := by norm_num, have h54 : (54 : K) = 2*3^3 := by norm_num, have h₁ : x^3 + b * x^2 + c * x + d = y^3 + 3 * p * y - 2 * q, { dsimp only [y], rw [hp, hq], field_simp [h9, h54], ring, }, rw [h₁, cubic_basic_eq_zero_iff hω hp_nonzero hr hs3 ht y], dsimp only [y], simp_rw [eq_sub_iff_add_eq], end /-- **The Solution of Cubic**. The roots of a cubic polynomial whose discriminant is nonzero. -/ theorem cubic_eq_zero_iff (ha : a ≠ 0) (hω : is_primitive_root ω 3) (hp : p = (3 * a * c - b^2) / (9 * a^2)) (hp_nonzero : p ≠ 0) (hq : q = (9 * a * b * c - 2 * b^3 - 27 * a^2 * d) / (54 * a^3)) (hr : r^2 = q^2 + p^3) (hs3 : s^3 = q + r) (ht : t * s = p) (x : K) : a * x^3 + b * x^2 + c * x + d = 0 ↔ x = s - t - b / (3 * a) ∨ x = s * ω - t * ω^2 - b / (3 * a) ∨ x = s * ω^2 - t * ω - b / (3 * a) := begin have hi2 : (2 : K) ≠ 0 := nonzero_of_invertible _, have hi3 : (3 : K) ≠ 0 := nonzero_of_invertible _, have h9 : (9 : K) = 3^2 := by norm_num, have h54 : (54 : K) = 2*3^3 := by norm_num, have h₁ : a * x^3 + b * x^2 + c * x + d = a * (x^3 + b/a * x^2 + c/a * x + d/a), { field_simp, ring }, have h₂ : ∀ x, a * x = 0 ↔ x = 0, { intros x, simp [ha], }, have hp' : p = (3 * (c/a) - (b/a) ^ 2) / 9, { field_simp [hp, h9], ring_nf }, have hq' : q = (9 * (b/a) * (c/a) - 2 * (b/a) ^ 3 - 27 * (d/a)) / 54, { field_simp [hq, h54], ring_nf }, rw [h₁, h₂, cubic_monic_eq_zero_iff (b/a) (c/a) (d/a) hω hp' hp_nonzero hq' hr hs3 ht x], have h₄ := calc b / a / 3 = b / (a * 3) : by { field_simp [ha] } ... = b / (3 * a) : by rw mul_comm, rw [h₄], end /-- the solution of the cubic equation when p equals zero. -/ lemma cubic_eq_zero_iff_of_p_eq_zero (ha : a ≠ 0) (hω : is_primitive_root ω 3) (hpz : 3 * a * c - b^2 = 0) (hq : q = (9 * a * b * c - 2 * b^3 - 27 * a^2 * d) / (54 * a^3)) (hs3 : s^3 = 2 * q) (x : K) : a * x^3 + b * x^2 + c * x + d = 0 ↔ x = s - b / (3 * a) ∨ x = s * ω - b / (3 * a) ∨ x = s * ω^2 - b / (3 * a) := begin have h₁ : ∀ x a₁ a₂ a₃ : K, x = a₁ ∨ x = a₂ ∨ x = a₃ ↔ (x - a₁) * (x - a₂) * (x - a₃) = 0, { intros, simp only [mul_eq_zero, sub_eq_zero, or.assoc] }, have hi2 : (2 : K) ≠ 0 := nonzero_of_invertible _, have hi3 : (3 : K) ≠ 0 := nonzero_of_invertible _, have h54 : (54 : K) = 2*3^3 := by norm_num, have hb2 : b^2 = 3 * a * c, { rw sub_eq_zero at hpz, rw hpz }, have hb3 : b^3 = 3 * a * b * c, { rw [pow_succ, hb2], ring }, have h₂ := calc a * x^3 + b * x^2 + c * x + d = a * (x + b/(3*a))^3 + (c - b^2/(3*a)) * x + (d - b^3*a/(3*a)^3) : by { field_simp, ring } ... = a * (x + b/(3*a))^3 + (d - (9*a*b*c-2*b^3)*a/(3*a)^3) : by { simp only [hb2, hb3], field_simp, ring } ... = a * ((x + b/(3*a))^3 - s^3) : by { rw [hs3, hq], field_simp [h54], ring, }, have h₃ : ∀ x, a * x = 0 ↔ x = 0, { intro x, simp [ha] }, have h₄ : ∀ x : K, x^3 - s^3 = (x - s) * (x - s * ω) * (x - s * ω^2), { intro x, calc x^3 - s^3 = (x - s) * (x^2 + x*s + s^2) : by ring ... = (x - s) * (x^2 - (ω+ω^2)*x*s + (1+ω+ω^2)*x*s + s^2) : by ring ... = (x - s) * (x^2 - (ω+ω^2)*x*s + ω^3*s^2) : by { rw [hω.pow_eq_one, cube_root_of_unity_sum hω], simp, } ... = (x - s) * (x - s * ω) * (x - s * ω^2) : by ring }, rw [h₁, h₂, h₃, h₄ (x + b/(3*a))], ring_nf, end end field
85163aae0ef8d3a8698d3ffe3647bc6f84d990bf
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/model_theory/skolem.lean
517db8987361f380bbe45d6daf5e52e17f206b08
[ "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,154
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import model_theory.elementary_maps /-! # Skolem Functions and Downward Löwenheim–Skolem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main Definitions * `first_order.language.skolem₁` is a language consisting of Skolem functions for another language. ## Main Results * `first_order.language.exists_elementary_substructure_card_eq` is the Downward Löwenheim–Skolem theorem: If `s` is a set in an `L`-structure `M` and `κ` an infinite cardinal such that `max (# s, L.card) ≤ κ` and `κ ≤ # M`, then `M` has an elementary substructure containing `s` of cardinality `κ`. ## TODO * Use `skolem₁` recursively to construct an actual Skolemization of a language. -/ universes u v w w' namespace first_order namespace language open Structure cardinal open_locale cardinal variables (L : language.{u v}) {M : Type w} [nonempty M] [L.Structure M] /-- A language consisting of Skolem functions for another language. Called `skolem₁` because it is the first step in building a Skolemization of a language. -/ @[simps] def skolem₁ : language := ⟨λ n, L.bounded_formula empty (n + 1), λ _, empty⟩ variables {L} theorem card_functions_sum_skolem₁ : # (Σ n, (L.sum L.skolem₁).functions n) = # (Σ n, L.bounded_formula empty (n + 1)) := begin simp only [card_functions_sum, skolem₁_functions, lift_id', mk_sigma, sum_add_distrib'], rw [add_comm, add_eq_max, max_eq_left], { refine sum_le_sum _ _ (λ n, _), rw [← lift_le, lift_lift, lift_mk_le], refine ⟨⟨λ f, (func f default).bd_equal (func f default), λ f g h, _⟩⟩, rcases h with ⟨rfl, ⟨rfl⟩⟩, refl }, { rw ← mk_sigma, exact infinite_iff.1 (infinite.of_injective (λ n, ⟨n, ⊥⟩) (λ x y xy, (sigma.mk.inj xy).1)) } end theorem card_functions_sum_skolem₁_le : # (Σ n, (L.sum L.skolem₁).functions n) ≤ max ℵ₀ L.card := begin rw card_functions_sum_skolem₁, transitivity # (Σ n, L.bounded_formula empty n), { exact ⟨⟨sigma.map nat.succ (λ _, id), nat.succ_injective.sigma_map (λ _, function.injective_id)⟩⟩ }, { refine trans bounded_formula.card_le (lift_le.1 _), simp only [mk_empty, lift_zero, lift_uzero, zero_add] } end /-- The structure assigning each function symbol of `L.skolem₁` to a skolem function generated with choice. -/ noncomputable instance skolem₁_Structure : L.skolem₁.Structure M := ⟨λ n φ x, classical.epsilon (λ a, φ.realize default (fin.snoc x a : _ → M)), λ _ r, empty.elim r⟩ namespace substructure lemma skolem₁_reduct_is_elementary (S : (L.sum L.skolem₁).substructure M) : (Lhom.sum_inl.substructure_reduct S).is_elementary := begin apply (Lhom.sum_inl.substructure_reduct S).is_elementary_of_exists, intros n φ x a h, let φ' : (L.sum L.skolem₁).functions n := (Lhom.sum_inr.on_function φ), exact ⟨⟨fun_map φ' (coe ∘ x), S.fun_mem (Lhom.sum_inr.on_function φ) (coe ∘ x) (λ i, (x i).2)⟩, classical.epsilon_spec ⟨a, h⟩⟩, end /-- Any `L.sum L.skolem₁`-substructure is an elementary `L`-substructure. -/ noncomputable def elementary_skolem₁_reduct (S : (L.sum L.skolem₁).substructure M) : L.elementary_substructure M := ⟨Lhom.sum_inl.substructure_reduct S, S.skolem₁_reduct_is_elementary⟩ lemma coe_sort_elementary_skolem₁_reduct (S : (L.sum L.skolem₁).substructure M) : (S.elementary_skolem₁_reduct : Type w) = S := rfl end substructure open substructure variables (L) (M) instance : small (⊥ : (L.sum L.skolem₁).substructure M).elementary_skolem₁_reduct := begin rw [coe_sort_elementary_skolem₁_reduct], apply_instance, end theorem exists_small_elementary_substructure : ∃ (S : L.elementary_substructure M), small.{max u v} S := ⟨substructure.elementary_skolem₁_reduct ⊥, infer_instance⟩ variables {M} /-- The Downward Löwenheim–Skolem theorem : If `s` is a set in an `L`-structure `M` and `κ` an infinite cardinal such that `max (# s, L.card) ≤ κ` and `κ ≤ # M`, then `M` has an elementary substructure containing `s` of cardinality `κ`. -/ theorem exists_elementary_substructure_card_eq (s : set M) (κ : cardinal.{w'}) (h1 : ℵ₀ ≤ κ) (h2 : cardinal.lift.{w'} (# s) ≤ cardinal.lift.{w} κ) (h3 : cardinal.lift.{w'} L.card ≤ cardinal.lift.{max u v} κ) (h4 : cardinal.lift.{w} κ ≤ cardinal.lift.{w'} (# M)) : ∃ (S : L.elementary_substructure M), s ⊆ S ∧ cardinal.lift.{w'} (# S) = cardinal.lift.{w} κ := begin obtain ⟨s', hs'⟩ := cardinal.le_mk_iff_exists_set.1 h4, rw ← aleph_0_le_lift at h1, rw ← hs' at *, refine ⟨elementary_skolem₁_reduct (closure (L.sum L.skolem₁) (s ∪ (equiv.ulift '' s'))), (s.subset_union_left _).trans subset_closure, _⟩, have h := mk_image_eq_lift _ s' equiv.ulift.injective, rw [lift_umax, lift_id'] at h, rw [coe_sort_elementary_skolem₁_reduct, ← h, lift_inj], refine le_antisymm (lift_le.1 (lift_card_closure_le.trans _)) (mk_le_mk_of_subset ((set.subset_union_right _ _).trans subset_closure)), rw [max_le_iff, aleph_0_le_lift, ← aleph_0_le_lift, h, add_eq_max, max_le_iff, lift_le], refine ⟨h1, (mk_union_le _ _).trans _, (lift_le.2 card_functions_sum_skolem₁_le).trans _⟩, { rw [← lift_le, lift_add, h, add_comm, add_eq_max h1], exact max_le le_rfl h2 }, { rw [lift_max, lift_aleph_0, max_le_iff, aleph_0_le_lift, and_comm, ← lift_le.{_ w'}, lift_lift, lift_lift, ← aleph_0_le_lift, h], refine ⟨_, h1⟩, simp only [← lift_lift, lift_umax, lift_umax'], rw [lift_lift, ← lift_lift.{w' w} L.card], refine trans ((lift_le.{_ w}).2 h3) _, rw [lift_lift, ← lift_lift.{w (max u v)}, ← hs', ← h, lift_lift, lift_lift, lift_lift] }, { refine trans _ (lift_le.2 (mk_le_mk_of_subset (set.subset_union_right _ _))), rw [aleph_0_le_lift, ← aleph_0_le_lift, h], exact h1 } end end language end first_order
b5962b4e41515861b60d968f269bef7302f9daa1
367134ba5a65885e863bdc4507601606690974c1
/src/algebraic_geometry/stalks.lean
afb7eb2c5e230dead3e4958905aa5ca9ae91f5a5
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
2,853
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 algebraic_geometry.presheafed_space import topology.sheaves.stalks /-! # Stalks for presheaved spaces This file lifts constructions of stalks and pushforwards of stalks to work with the category of presheafed spaces. -/ noncomputable theory universes v u v' u' open category_theory open category_theory.limits category_theory.category category_theory.functor open algebraic_geometry open topological_space variables {C : Type u} [category.{v} C] [has_colimits C] local attribute [tidy] tactic.op_induction' open Top.presheaf namespace algebraic_geometry.PresheafedSpace /-- The stalk at `x` of a `PresheafedSpace`. -/ def stalk (X : PresheafedSpace C) (x : X) : C := X.presheaf.stalk x /-- A morphism of presheafed spaces induces a morphism of stalks. -/ def stalk_map {X Y : PresheafedSpace C} (α : X ⟶ Y) (x : X) : Y.stalk (α.base x) ⟶ X.stalk x := (stalk_functor C (α.base x)).map (α.c) ≫ X.presheaf.stalk_pushforward C α.base x section restrict -- PROJECT: restriction preserves stalks. -- We'll want to define cofinal functors, show precomposing with a cofinal functor preserves -- colimits, and (easily) verify that "open neighbourhoods of x within U" is cofinal in "open -- neighbourhoods of x". /- def restrict_stalk_iso {U : Top} (X : PresheafedSpace C) (f : U ⟶ (X : Top.{v})) (h : open_embedding f) (x : U) : (X.restrict f h).stalk x ≅ X.stalk (f x) := begin dsimp only [stalk, Top.presheaf.stalk, stalk_functor], dsimp [colim], sorry end -- TODO `restrict_stalk_iso` is compatible with `germ`. -/ end restrict namespace stalk_map @[simp] lemma id (X : PresheafedSpace C) (x : X) : stalk_map (𝟙 X) x = 𝟙 (X.stalk x) := begin dsimp [stalk_map], simp only [stalk_pushforward.id], rw [←map_comp], convert (stalk_functor C x).map_id X.presheaf, tidy, end -- TODO understand why this proof is still gross (i.e. requires using `erw`) @[simp] lemma comp {X Y Z : PresheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (x : X) : stalk_map (α ≫ β) x = (stalk_map β (α.base x) : Z.stalk (β.base (α.base x)) ⟶ Y.stalk (α.base x)) ≫ (stalk_map α x : Y.stalk (α.base x) ⟶ X.stalk x) := begin dsimp [stalk_map, stalk_functor, stalk_pushforward], ext U, op_induction U, cases U, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre, whisker_left_app, whisker_right_app, assoc, id_comp, map_id, map_comp], dsimp, simp only [map_id, assoc, pushforward.comp_inv_app], -- FIXME Why doesn't simp do this: erw [category_theory.functor.map_id], erw [category_theory.functor.map_id], erw [id_comp, id_comp, id_comp], end end stalk_map end algebraic_geometry.PresheafedSpace
9b748685611b20b54d7e594bea5fd88b08448778
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/topology/algebra/module.lean
1bd3d014e0e7d6306d4a19bb084e223ed247e440
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
41,545
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov -/ import topology.algebra.ring import topology.uniform_space.uniform_embedding import ring_theory.algebra import linear_algebra.projection /-! # Theory of topological modules and continuous linear maps. We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`, as extensions of the corresponding algebraic classes where the algebraic operations are continuous. We also define continuous linear maps, as linear maps between topological modules which are continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is denoted by `M →L[R] M₂`. Continuous linear equivalences are denoted by `M ≃L[R] M₂`. ## Implementation notes Topological vector spaces are defined as an `abbreviation` for topological modules, if the base ring is a field. This has as advantage that topological vector spaces are completely transparent for type class inference, which means that all instances for topological modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend topological vector spaces. The solution is to extend `topological_module` instead. -/ open filter open_locale topological_space big_operators universes u v w u' section prio set_option default_priority 100 -- see Note [default priority] /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, R will be a topological semiring and M a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (R : Type u) (M : Type v) [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] : Prop := (continuous_smul : continuous (λp : R × M, p.1 • p.2)) end prio section variables {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] lemma continuous_smul : continuous (λp:R×M, p.1 • p.2) := topological_semimodule.continuous_smul lemma continuous.smul {α : Type*} [topological_space α] {f : α → R} {g : α → M} (hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) := continuous_smul.comp (hf.prod_mk hg) lemma tendsto_smul {c : R} {x : M} : tendsto (λp:R×M, p.fst • p.snd) (𝓝 (c, x)) (𝓝 (c • x)) := continuous_smul.tendsto _ lemma filter.tendsto.smul {α : Type*} {l : filter α} {f : α → R} {g : α → M} {c : R} {x : M} (hf : tendsto f l (𝓝 c)) (hg : tendsto g l (𝓝 x)) : tendsto (λ a, f a • g a) l (𝓝 (c • x)) := tendsto_smul.comp (hf.prod_mk_nhds hg) end section prio set_option default_priority 100 -- see Note [default priority] /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a topological additive group, but this is not needed for the definition -/ class topological_module (R : Type u) (M : Type v) [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] extends topological_semimodule R M : Prop /-- A topological vector space is a topological module over a field. -/ abbreviation topological_vector_space (R : Type u) (M : Type v) [field R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] := topological_module R M end prio section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] /-- Scalar multiplication by a unit is a homeomorphism from a topological module onto itself. -/ protected def homeomorph.smul_of_unit (a : units R) : M ≃ₜ M := { to_fun := λ x, (a : R) • x, inv_fun := λ x, ((a⁻¹ : units R) : R) • x, right_inv := λ x, calc (a : R) • ((a⁻¹ : units R) : R) • x = x : by rw [smul_smul, units.mul_inv, one_smul], left_inv := λ x, calc ((a⁻¹ : units R) : R) • (a : R) • x = x : by rw [smul_smul, units.inv_mul, one_smul], continuous_to_fun := continuous_const.smul continuous_id, continuous_inv_fun := continuous_const.smul continuous_id } lemma is_open_map_smul_of_unit (a : units R) : is_open_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_open_map lemma is_closed_map_smul_of_unit (a : units R) : is_closed_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_closed_map /-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then `⊤` is the only submodule of `M` with a nonempty interior. This is the case, e.g., if `R` is a nondiscrete normed field. -/ lemma submodule.eq_top_of_nonempty_interior' [has_continuous_add M] [ne_bot (nhds_within (0:R) {x | is_unit x})] (s : submodule R M) (hs : (interior (s:set M)).nonempty) : s = ⊤ := begin rcases hs with ⟨y, hy⟩, refine (submodule.eq_top_iff'.2 $ λ x, _), rw [mem_interior_iff_mem_nhds] at hy, have : tendsto (λ c:R, y + c • x) (nhds_within 0 {x | is_unit x}) (𝓝 (y + (0:R) • x)), from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul tendsto_const_nhds), rw [zero_smul, add_zero] at this, rcases nonempty_of_mem_sets (inter_mem_sets (mem_map.1 (this hy)) self_mem_nhds_within) with ⟨_, hu, u, rfl⟩, have hy' : y ∈ ↑s := mem_of_nhds hy, exact (s.smul_mem_iff' _).1 ((s.add_mem_iff_right hy').1 hu) end end section variables {R : Type*} {M : Type*} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] /-- Scalar multiplication by a non-zero field element is a homeomorphism from a topological vector space onto itself. -/ protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : M ≃ₜ M := {.. homeomorph.smul_of_unit (units.mk0 a ha)} lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_open_map lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_closed_map end /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map (R : Type*) [semiring R] (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends linear_map R M M₂ := (cont : continuous to_fun) notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map R M M₂ /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ @[nolint has_inhabited_instance] structure continuous_linear_equiv (R : Type*) [semiring R] (M : Type*) [topological_space M] [add_comm_monoid M] (M₂ : Type*) [topological_space M₂] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] extends linear_equiv R M M₂ := (continuous_to_fun : continuous to_fun) (continuous_inv_fun : continuous inv_fun) notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂ namespace continuous_linear_map section semiring /- Properties that hold for non-necessarily commutative semirings. -/ variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ /-- Coerce continuous linear maps to functions. -/ -- see Note [function coercion] instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨λ _, M → M₂, λ f, f⟩ @[simp] lemma coe_mk (f : M →ₗ[R] M₂) (h) : (mk f h : M →ₗ[R] M₂) = f := rfl @[simp] lemma coe_mk' (f : M →ₗ[R] M₂) (h) : (mk f h : M → M₂) = f := rfl protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2 theorem coe_injective : function.injective (coe : (M →L[R] M₂) → (M →ₗ[R] M₂)) := by { intros f g H, cases f, cases g, congr' 1, exact H } theorem coe_injective' ⦃f g : M →L[R] M₂⦄ (H : (f : M → M₂) = g) : f = g := coe_injective $ linear_map.coe_injective H @[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g := coe_injective' $ funext h theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : M) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _ @[simp, norm_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl /-- The continuous map that is constantly zero. -/ instance: has_zero (M →L[R] M₂) := ⟨⟨0, continuous_const⟩⟩ instance : inhabited (M →L[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] M₂) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[norm_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl section variables (R M) /-- the identity map as a continuous linear map. -/ def id : M →L[R] M := ⟨linear_map.id, continuous_id⟩ end instance : has_one (M →L[R] M) := ⟨id R M⟩ lemma id_apply : id R M x = x := rfl @[simp, norm_cast] lemma coe_id : (id R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma coe_id' : (id R M : M → M) = _root_.id := rfl @[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl section add variables [has_continuous_add M₂] instance : has_add (M →L[R] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, norm_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) + g := rfl @[norm_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl instance : add_comm_monoid (M →L[R] M₂) := by { refine {zero := 0, add := (+), ..}; intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm] } lemma sum_apply {ι : Type*} (t : finset ι) (f : ι → M →L[R] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := begin haveI : is_add_monoid_hom (λ (g : M →L[R] M₂), g b) := { map_add := λ f g, continuous_linear_map.add_apply f g b, map_zero := by simp }, exact (finset.sum_hom t (λ g : M →L[R] M₂, g b)).symm end end add /-- Composition of bounded linear maps. -/ def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ := ⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩ @[simp, norm_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl @[simp, norm_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl @[simp] theorem comp_id : f.comp (id R M) = f := ext $ λ x, rfl @[simp] theorem id_comp : (id R M₂).comp f = f := ext $ λ x, rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [has_continuous_add M₂] [has_continuous_add M₃] (g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [has_continuous_add M₃] (g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } theorem comp_assoc (h : M₃ →L[R] M₄) (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : (h.comp g).comp f = h.comp (g.comp f) := rfl instance : has_mul (M →L[R] M) := ⟨comp⟩ lemma mul_def (f g : M →L[R] M) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : M →L[R] M) : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (f g : M →L[R] M) (x : M) : (f * g) x = f (g x) := rfl /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ protected def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) := { cont := f₁.2.prod_mk f₂.2, ..f₁.to_linear_map.prod f₂.to_linear_map } @[simp, norm_cast] lemma coe_prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : (f₁.prod f₂ : M →ₗ[R] M₂ × M₃) = linear_map.prod f₁ f₂ := rfl @[simp, norm_cast] lemma prod_apply (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) (x : M) : f₁.prod f₂ x = (f₁ x, f₂ x) := rfl /-- Kernel of a continuous linear map. -/ def ker (f : M →L[R] M₂) : submodule R M := (f : M →ₗ[R] M₂).ker @[norm_cast] lemma ker_coe : (f : M →ₗ[R] M₂).ker = f.ker := rfl @[simp] lemma mem_ker {f : M →L[R] M₂} {x} : x ∈ f.ker ↔ f x = 0 := linear_map.mem_ker lemma is_closed_ker [t1_space M₂] : is_closed (f.ker : set M) := continuous_iff_is_closed.1 f.cont _ is_closed_singleton @[simp] lemma apply_ker (x : f.ker) : f x = 0 := mem_ker.1 x.2 lemma is_complete_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [semimodule R M'] [t1_space M₂] (f : M' →L[R] M₂) : is_complete (f.ker : set M') := f.is_closed_ker.is_complete instance complete_space_ker {M' : Type*} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [semimodule R M'] [t1_space M₂] (f : M' →L[R] M₂) : complete_space f.ker := f.is_closed_ker.complete_space_coe @[simp] lemma ker_prod (f : M →L[R] M₂) (g : M →L[R] M₃) : ker (f.prod g) = ker f ⊓ ker g := linear_map.ker_prod f g /-- Range of a continuous linear map. -/ def range (f : M →L[R] M₂) : submodule R M₂ := (f : M →ₗ[R] M₂).range lemma range_coe : (f.range : set M₂) = set.range f := linear_map.range_coe _ lemma mem_range {f : M →L[R] M₂} {y} : y ∈ f.range ↔ ∃ x, f x = y := linear_map.mem_range lemma range_prod_le (f : M →L[R] M₂) (g : M →L[R] M₃) : range (f.prod g) ≤ (range f).prod (range g) := (f : M →ₗ[R] M₂).range_prod_le g /-- Restrict codomain of a continuous linear map. -/ def cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : M →L[R] p := { cont := continuous_subtype_mk h f.continuous, to_linear_map := (f : M →ₗ[R] M₂).cod_restrict p h} @[norm_cast] lemma coe_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : (f.cod_restrict p h : M →ₗ[R] p) = (f : M →ₗ[R] M₂).cod_restrict p h := rfl @[simp] lemma coe_cod_restrict_apply (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) (x) : (f.cod_restrict p h x : M₂) = f x := rfl @[simp] lemma ker_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : ker (f.cod_restrict p h) = ker f := (f : M →ₗ[R] M₂).ker_cod_restrict p h /-- Embedding of a submodule into the ambient space as a continuous linear map. -/ def subtype_val (p : submodule R M) : p →L[R] M := { cont := continuous_subtype_val, to_linear_map := p.subtype } @[simp, norm_cast] lemma coe_subtype_val (p : submodule R M) : (subtype_val p : p →ₗ[R] M) = p.subtype := rfl @[simp, norm_cast] lemma subtype_val_apply (p : submodule R M) (x : p) : (subtype_val p : p → M) x = x := rfl variables (R M M₂) /-- `prod.fst` as a `continuous_linear_map`. -/ def fst : M × M₂ →L[R] M := { cont := continuous_fst, to_linear_map := linear_map.fst R M M₂ } /-- `prod.snd` as a `continuous_linear_map`. -/ def snd : M × M₂ →L[R] M₂ := { cont := continuous_snd, to_linear_map := linear_map.snd R M M₂ } variables {R M M₂} @[simp, norm_cast] lemma coe_fst : (fst R M M₂ : M × M₂ →ₗ[R] M) = linear_map.fst R M M₂ := rfl @[simp, norm_cast] lemma coe_fst' : (fst R M M₂ : M × M₂ → M) = prod.fst := rfl @[simp, norm_cast] lemma coe_snd : (snd R M M₂ : M × M₂ →ₗ[R] M₂) = linear_map.snd R M M₂ := rfl @[simp, norm_cast] lemma coe_snd' : (snd R M M₂ : M × M₂ → M₂) = prod.snd := rfl @[simp] lemma fst_prod_snd : (fst R M M₂).prod (snd R M M₂) = id R (M × M₂) := ext $ λ ⟨x, y⟩, rfl /-- `prod.map` of two continuous linear maps. -/ def prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : (M × M₃) →L[R] (M₂ × M₄) := (f₁.comp (fst R M M₃)).prod (f₂.comp (snd R M M₃)) @[simp, norm_cast] lemma coe_prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : (f₁.prod_map f₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = ((f₁ : M →ₗ[R] M₂).prod_map (f₂ : M₃ →ₗ[R] M₄)) := rfl @[simp, norm_cast] lemma coe_prod_map' (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : ⇑(f₁.prod_map f₂) = prod.map f₁ f₂ := rfl /-- The continuous linear map given by `(x, y) ↦ f₁ x + f₂ y`. -/ def coprod [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) : (M × M₂) →L[R] M₃ := ⟨linear_map.coprod f₁ f₂, (f₁.cont.comp continuous_fst).add (f₂.cont.comp continuous_snd)⟩ @[norm_cast, simp] lemma coe_coprod [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) : (f₁.coprod f₂ : (M × M₂) →ₗ[R] M₃) = linear_map.coprod f₁ f₂ := rfl @[simp] lemma coprod_apply [has_continuous_add M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) (x) : f₁.coprod f₂ x = f₁ x.1 + f₂ x.2 := rfl variables [topological_space R] [topological_semimodule R M₂] /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`) -/ def smul_right (c : M →L[R] R) (f : M₂) : M →L[R] M₂ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : M →L[R] R} {f : M₂} {x : M} : (smul_right c f : M → M₂) x = (c : M → R) x • f := rfl @[simp] lemma smul_right_one_one (c : R →L[R] M₂) : smul_right 1 ((c : R → M₂) 1) = c := by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R →L[R] R) f = smul_right 1 f' ↔ f = f' := ⟨λ h, have (smul_right (1 : R →L[R] R) f : R → M₂) 1 = (smul_right (1 : R →L[R] R) f' : R → M₂) 1, by rw h, by simp at this; assumption, by cc⟩ lemma smul_right_comp [topological_semimodule R R] {x : M₂} {c : R} : (smul_right 1 x : R →L[R] M₂).comp (smul_right 1 c : R →L[R] R) = smul_right 1 (c • x) := by { ext, simp [mul_smul] } end semiring section pi variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] [semimodule R M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] [semimodule R M₂] {ι : Type*} {φ : ι → Type*} [∀i, topological_space (φ i)] [∀i, add_comm_monoid (φ i)] [∀i, semimodule R (φ i)] /-- `pi` construction for continuous linear functions. From a family of continuous linear functions it produces a continuous linear function into a family of topological modules. -/ def pi (f : Πi, M →L[R] φ i) : M →L[R] (Πi, φ i) := ⟨linear_map.pi (λ i, (f i : M →ₗ[R] φ i)), continuous_pi (λ i, (f i).continuous)⟩ @[simp] lemma pi_apply (f : Πi, M →L[R] φ i) (c : M) (i : ι) : pi f c i = f i c := rfl lemma pi_eq_zero (f : Πi, M →L[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) := by simp only [ext_iff, pi_apply, function.funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩ lemma pi_zero : pi (λi, 0 : Πi, M →L[R] φ i) = 0 := by ext; refl lemma pi_comp (f : Πi, M →L[R] φ i) (g : M₂ →L[R] M) : (pi f).comp g = pi (λi, (f i).comp g) := rfl /-- The projections from a family of topological modules are continuous linear maps. -/ def proj (i : ι) : (Πi, φ i) →L[R] φ i := ⟨linear_map.proj i, continuous_apply _⟩ @[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →L[R] φ i) b = b i := rfl lemma proj_pi (f : Πi, M₂ →L[R] φ i) (i : ι) : (proj i).comp (pi f) = f i := ext $ assume c, rfl lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ := linear_map.infi_ker_proj variables (R φ) /-- If `I` and `J` are complementary index sets, the product of the kernels of the `J`th projections of `φ` is linearly equivalent to the product over `I`. -/ def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)] (hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) : (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃L[R] (Πi:I, φ i) := ⟨ linear_map.infi_ker_proj_equiv R φ hd hu, continuous_pi (λ i, begin have := @continuous_subtype_coe _ _ (λ x, x ∈ (⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i))), have := continuous.comp (by exact continuous_apply i) this, exact this end), continuous_subtype_mk _ (continuous_pi (λ i, begin dsimp, split_ifs; [apply continuous_apply, exact continuous_const] end)) ⟩ end pi section ring variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma sub_apply' (x : M) : ((f : M →ₗ[R] M₂) - g) x = f x - g x := rfl lemma range_prod_eq {f : M →L[R] M₂} {g : M →L[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (f.prod g) = (range f).prod (range g) := linear_map.range_prod_eq h section variables [topological_add_group M₂] instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, norm_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl @[norm_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl instance : add_comm_group (M →L[R] M₂) := by { refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm] } lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl @[simp, norm_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) - g := rfl @[simp, norm_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl end instance [topological_add_group M] : ring (M →L[R] M) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } lemma smul_right_one_pow [topological_space R] [topological_add_group R] [topological_semimodule R R] (c : R) (n : ℕ) : (smul_right 1 c : R →L[R] R)^n = smul_right 1 (c^n) := begin induction n with n ihn, { ext, simp }, { rw [pow_succ, ihn, mul_def, smul_right_comp, smul_eq_mul, pow_succ'] } end /-- Given a right inverse `f₂ : M₂ →L[R] M` to `f₁ : M →L[R] M₂`, `proj_ker_of_right_inverse f₁ f₂ h` is the projection `M →L[R] f₁.ker` along `f₂.range`. -/ def proj_ker_of_right_inverse [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M →L[R] f₁.ker := (id R M - f₂.comp f₁).cod_restrict f₁.ker $ λ x, by simp [h (f₁ x)] @[simp] lemma coe_proj_ker_of_right_inverse_apply [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (f₁.proj_ker_of_right_inverse f₂ h x : M) = x - f₂ (f₁ x) := rfl @[simp] lemma proj_ker_of_right_inverse_apply_idem [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : f₁.ker) : f₁.proj_ker_of_right_inverse f₂ h x = x := subtype.ext_iff_val.2 $ by simp @[simp] lemma proj_ker_of_right_inverse_comp_inv [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂) : f₁.proj_ker_of_right_inverse f₂ h (f₂ y) = 0 := subtype.ext_iff_val.2 $ by simp [h y] end ring section comm_ring variables {R : Type*} [comm_ring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] [topological_module R M₃] instance : has_scalar R (M →L[R] M₃) := ⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩ variables (c : R) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M) @[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl variable [topological_module R M₂] @[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, norm_cast] lemma coe_apply : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • (f : M →ₗ[R] M₂) := rfl @[norm_cast] lemma coe_apply' : (((c • f) : M →L[R] M₂) : M → M₂) = c • (f : M → M₂) := rfl @[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp } variable [topological_add_group M₂] instance : module R (M →L[R] M₂) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } instance : algebra R (M₂ →L[R] M₂) := algebra.of_semimodule' (λ c f, ext $ λ x, rfl) (λ c f, ext $ λ x, f.map_smul c x) end comm_ring end continuous_linear_map namespace continuous_linear_equiv section add_comm_monoid variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_monoid M] {M₂ : Type*} [topological_space M₂] [add_comm_monoid M₂] {M₃ : Type*} [topological_space M₃] [add_comm_monoid M₃] {M₄ : Type*} [topological_space M₄] [add_comm_monoid M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] M₂ := { cont := e.continuous_to_fun, ..e.to_linear_equiv.to_linear_map } /-- Coerce continuous linear equivs to continuous linear maps. -/ instance : has_coe (M ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩ /-- Coerce continuous linear equivs to maps. -/ -- see Note [function coercion] instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨λ _, M → M₂, λ f, f⟩ @[simp] theorem coe_def_rev (e : M ≃L[R] M₂) : e.to_continuous_linear_map = e := rfl @[simp] theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl @[norm_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl @[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g := begin cases f; cases g, simp only, ext x, induction h, refl end /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { ..e } -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero @[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y := (e : M →L[R] M₂).map_add x y @[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) := (e : M →L[R] M₂).map_smul c x @[simp] lemma map_eq_zero_iff (e : M ≃L[R] M₂) {x : M} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff protected lemma continuous (e : M ≃L[R] M₂) : continuous (e : M → M₂) := e.continuous_to_fun protected lemma continuous_on (e : M ≃L[R] M₂) {s : set M} : continuous_on (e : M → M₂) s := e.continuous.continuous_on protected lemma continuous_at (e : M ≃L[R] M₂) {x : M} : continuous_at (e : M → M₂) x := e.continuous.continuous_at protected lemma continuous_within_at (e : M ≃L[R] M₂) {s : set M} {x : M} : continuous_within_at (e : M → M₂) s x := e.continuous.continuous_within_at lemma comp_continuous_on_iff {α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) (s : set α) : continuous_on (e ∘ f) s ↔ continuous_on f s := e.to_homeomorph.comp_continuous_on_iff _ _ lemma comp_continuous_iff {α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) : continuous (e ∘ f) ↔ continuous f := e.to_homeomorph.comp_continuous_iff _ /-- An extensionality lemma for `R ≃L[R] M`. -/ lemma ext₁ [topological_space R] {f g : R ≃L[R] M} (h : f 1 = g 1) : f = g := ext $ funext $ λ x, mul_one x ▸ by rw [← smul_eq_mul, map_smul, h, map_smul] section variables (R M) /-- The identity map as a continuous linear equivalence. -/ @[refl] protected def refl : M ≃L[R] M := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. linear_equiv.refl R M } end @[simp, norm_cast] lemma coe_refl : (continuous_linear_equiv.refl R M : M →L[R] M) = continuous_linear_map.id R M := rfl @[simp, norm_cast] lemma coe_refl' : (continuous_linear_equiv.refl R M : M → M) = id := rfl /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } @[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] M₃ := { continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun, continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun, .. e₁.to_linear_equiv.trans e₂.to_linear_equiv } @[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } /-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/ def prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) : (M × M₃) ≃L[R] (M₂ × M₄) := { continuous_to_fun := e.continuous_to_fun.prod_map e'.continuous_to_fun, continuous_inv_fun := e.continuous_inv_fun.prod_map e'.continuous_inv_fun, .. e.to_linear_equiv.prod e'.to_linear_equiv } @[simp, norm_cast] lemma prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (x) : e.prod e' x = (e x.1, e' x.2) := rfl @[simp, norm_cast] lemma coe_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) : (e.prod e' : (M × M₃) →L[R] (M₂ × M₄)) = (e : M →L[R] M₂).prod_map (e' : M₃ →L[R] M₄) := rfl theorem bijective (e : M ≃L[R] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective theorem injective (e : M ≃L[R] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective theorem surjective (e : M ≃L[R] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective @[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.6 c @[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.5 b @[simp] theorem coe_comp_coe_symm (e : M ≃L[R] M₂) : (e : M →L[R] M₂).comp (e.symm : M₂ →L[R] M) = continuous_linear_map.id R M₂ := continuous_linear_map.ext e.apply_symm_apply @[simp] theorem coe_symm_comp_coe (e : M ≃L[R] M₂) : (e.symm : M₂ →L[R] M).comp (e : M →L[R] M₂) = continuous_linear_map.id R M := continuous_linear_map.ext e.symm_apply_apply lemma symm_comp_self (e : M ≃L[R] M₂) : (e.symm : M₂ → M) ∘ (e : M → M₂) = id := by{ ext x, exact symm_apply_apply e x } lemma self_comp_symm (e : M ≃L[R] M₂) : (e : M → M₂) ∘ (e.symm : M₂ → M) = id := by{ ext x, exact apply_symm_apply e x } @[simp] lemma symm_comp_self' (e : M ≃L[R] M₂) : ((e.symm : M₂ →L[R] M) : M₂ → M) ∘ ((e : M →L[R] M₂) : M → M₂) = id := symm_comp_self e @[simp] lemma self_comp_symm' (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) ∘ ((e.symm : M₂ →L[R] M) : M₂ → M) = id := self_comp_symm e @[simp] theorem symm_symm (e : M ≃L[R] M₂) : e.symm.symm = e := by { ext x, refl } theorem symm_symm_apply (e : M ≃L[R] M₂) (x : M) : e.symm.symm x = e x := rfl lemma symm_apply_eq (e : M ≃L[R] M₂) {x y} : e.symm x = y ↔ x = e y := e.to_linear_equiv.symm_apply_eq lemma eq_symm_apply (e : M ≃L[R] M₂) {x y} : y = e.symm x ↔ e y = x := e.to_linear_equiv.eq_symm_apply /-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are inverse of each other. -/ def equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h₁ : function.left_inverse f₂ f₁) (h₂ : function.right_inverse f₂ f₁) : M ≃L[R] M₂ := { to_fun := f₁, continuous_to_fun := f₁.continuous, inv_fun := f₂, continuous_inv_fun := f₂.continuous, left_inv := h₁, right_inv := h₂, .. f₁ } @[simp] lemma equiv_of_inverse_apply (f₁ : M →L[R] M₂) (f₂ h₁ h₂ x) : equiv_of_inverse f₁ f₂ h₁ h₂ x = f₁ x := rfl @[simp] lemma symm_equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ h₁ h₂) : (equiv_of_inverse f₁ f₂ h₁ h₂).symm = equiv_of_inverse f₂ f₁ h₂ h₁ := rfl end add_comm_monoid section add_comm_group variables {R : Type*} [semiring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [semimodule R M] [semimodule R M₂] [semimodule R M₃] [semimodule R M₄] variables [topological_add_group 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. -/ def skew_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) : (M × M₃) ≃L[R] M₂ × M₄ := { continuous_to_fun := (e.continuous_to_fun.comp continuous_fst).prod_mk ((e'.continuous_to_fun.comp continuous_snd).add $ f.continuous.comp continuous_fst), continuous_inv_fun := (e.continuous_inv_fun.comp continuous_fst).prod_mk (e'.continuous_inv_fun.comp $ continuous_snd.sub $ f.continuous.comp $ e.continuous_inv_fun.comp continuous_fst), .. e.to_linear_equiv.skew_prod e'.to_linear_equiv ↑f } @[simp] lemma skew_prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[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 (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[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 add_comm_group section ring variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] [semimodule R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [semimodule R M₂] @[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →L[R] M₂).map_sub x y @[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x section variables (R) [topological_space R] [topological_module R R] /-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `units R`. -/ def units_equiv_aut : units R ≃ (R ≃L[R] R) := { to_fun := λ u, equiv_of_inverse (continuous_linear_map.smul_right 1 ↑u) (continuous_linear_map.smul_right 1 ↑u⁻¹) (λ x, by simp) (λ x, by simp), inv_fun := λ e, ⟨e 1, e.symm 1, by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, symm_apply_apply], by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, apply_symm_apply]⟩, left_inv := λ u, units.ext $ by simp, right_inv := λ e, ext₁ $ by simp } variable {R} @[simp] lemma units_equiv_aut_apply (u : units R) (x : R) : units_equiv_aut R u x = x * u := rfl @[simp] lemma units_equiv_aut_apply_symm (u : units R) (x : R) : (units_equiv_aut R u).symm x = x * ↑u⁻¹ := rfl @[simp] lemma units_equiv_aut_symm_apply (e : R ≃L[R] R) : ↑((units_equiv_aut R).symm e) = e 1 := rfl end variables [topological_add_group M] open continuous_linear_map (id fst snd subtype_val mem_ker) /-- A pair of continuous linear maps such that `f₁ ∘ f₂ = id` generates a continuous linear equivalence `e` between `M` and `M₂ × f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`, `(e x).1 = f₁ x`, and `(e (f₂ y)).2 = 0`. The map is given by `e x = (f₁ x, x - f₂ (f₁ x))`. -/ def equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M ≃L[R] M₂ × f₁.ker := equiv_of_inverse (f₁.prod (f₁.proj_ker_of_right_inverse f₂ h)) (f₂.coprod (subtype_val f₁.ker)) (λ x, by simp) (λ ⟨x, y⟩, by simp [h x]) @[simp] lemma fst_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (equiv_of_right_inverse f₁ f₂ h x).1 = f₁ x := rfl @[simp] lemma snd_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : ((equiv_of_right_inverse f₁ f₂ h x).2 : M) = x - f₂ (f₁ x) := rfl @[simp] lemma equiv_of_right_inverse_symm_apply (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂ × f₁.ker) : (equiv_of_right_inverse f₁ f₂ h).symm y = f₂ y.1 + y.2 := rfl end ring end continuous_linear_equiv namespace submodule variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂] open continuous_linear_map /-- A submodule `p` is called *complemented* if there exists a continuous projection `M →ₗ[R] p`. -/ def closed_complemented (p : submodule R M) : Prop := ∃ f : M →L[R] p, ∀ x : p, f x = x lemma closed_complemented.has_closed_complement {p : submodule R M} [t1_space p] (h : closed_complemented p) : ∃ (q : submodule R M) (hq : is_closed (q : set M)), is_compl p q := exists.elim h $ λ f hf, ⟨f.ker, f.is_closed_ker, linear_map.is_compl_of_proj hf⟩ protected lemma closed_complemented.is_closed [topological_add_group M] [t1_space M] {p : submodule R M} (h : closed_complemented p) : is_closed (p : set M) := begin rcases h with ⟨f, hf⟩, have : ker (id R M - (subtype_val p).comp f) = p := linear_map.ker_id_sub_eq_of_proj hf, exact this ▸ (is_closed_ker _) end @[simp] lemma closed_complemented_bot : closed_complemented (⊥ : submodule R M) := ⟨0, λ x, by simp only [zero_apply, eq_zero_of_bot_submodule x]⟩ @[simp] lemma closed_complemented_top : closed_complemented (⊤ : submodule R M) := ⟨(id R M).cod_restrict ⊤ (λ x, trivial), λ x, subtype.ext_iff_val.2 $ by simp⟩ end submodule lemma continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : f₁.ker.closed_complemented := ⟨f₁.proj_ker_of_right_inverse f₂ h, f₁.proj_ker_of_right_inverse_apply_idem f₂ h⟩
861d9bf953dfde8690fc1239ee4aef95347eb43c
abd85493667895c57a7507870867b28124b3998f
/src/category_theory/fully_faithful.lean
22672639a22a0fffe537f7804d7fa3bc25da99a1
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
6,454
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import logic.function.basic import category_theory.natural_isomorphism universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] /-- A functor `F : C ⥤ D` is full if for each `X Y : C`, `F.map` is surjective. In fact, we use a constructive definition, so the `full F` typeclass contains data, specifying a particular preimage of each `f : F.obj X ⟶ F.obj Y`. -/ class full (F : C ⥤ D) := (preimage : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), X ⟶ Y) (witness' : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), F.map (preimage f) = f . obviously) restate_axiom full.witness' attribute [simp] full.witness /-- A functor `F : C ⥤ D` is faithful if for each `X Y : C`, `F.map` is injective.-/ class faithful (F : C ⥤ D) : Prop := (injectivity' [] : ∀ {X Y : C}, function.injective (@functor.map _ _ _ _ F X Y) . obviously) restate_axiom faithful.injectivity' namespace functor lemma injectivity (F : C ⥤ D) [faithful F] {X Y : C} : function.injective $ @functor.map _ _ _ _ F X Y := faithful.injectivity F /-- The specified preimage of a morphism under a full functor. -/ def preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : X ⟶ Y := full.preimage.{v₁ v₂} f @[simp] lemma image_preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : F.map (preimage F f) = f := by unfold preimage; obviously end functor variables {F : C ⥤ D} [full F] [faithful F] {X Y Z : C} @[simp] lemma preimage_id : F.preimage (𝟙 (F.obj X)) = 𝟙 X := F.injectivity (by simp) @[simp] lemma preimage_comp (f : F.obj X ⟶ F.obj Y) (g : F.obj Y ⟶ F.obj Z) : F.preimage (f ≫ g) = F.preimage f ≫ F.preimage g := F.injectivity (by simp) @[simp] lemma preimage_map (f : X ⟶ Y) : F.preimage (F.map f) = f := F.injectivity (by simp) /-- If `F : C ⥤ D` is fully faithful, every isomorphism `F.obj X ≅ F.obj Y` has a preimage. -/ def preimage_iso (f : (F.obj X) ≅ (F.obj Y)) : X ≅ Y := { hom := F.preimage f.hom, inv := F.preimage f.inv, hom_inv_id' := F.injectivity (by simp), inv_hom_id' := F.injectivity (by simp), } @[simp] lemma preimage_iso_hom (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).hom = F.preimage f.hom := rfl @[simp] lemma preimage_iso_inv (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).inv = F.preimage (f.inv) := rfl @[simp] lemma preimage_iso_map_iso (f : X ≅ Y) : preimage_iso (F.map_iso f) = f := by tidy variables (F) def is_iso_of_fully_faithful (f : X ⟶ Y) [is_iso (F.map f)] : is_iso f := { inv := F.preimage (inv (F.map f)), hom_inv_id' := F.injectivity (by simp), inv_hom_id' := F.injectivity (by simp) } end category_theory namespace category_theory variables {C : Type u₁} [category.{v₁} C] instance full.id : full (𝟭 C) := { preimage := λ _ _ f, f } instance faithful.id : faithful (𝟭 C) := by obviously variables {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] variables (F F' : C ⥤ D) (G : D ⥤ E) instance faithful.comp [faithful F] [faithful G] : faithful (F ⋙ G) := { injectivity' := λ _ _ _ _ p, F.injectivity (G.injectivity p) } lemma faithful.of_comp [faithful $ F ⋙ G] : faithful F := { injectivity' := λ X Y, (F ⋙ G).injectivity.of_comp } section variables {F F'} lemma faithful.of_iso [faithful F] (α : F ≅ F') : faithful F' := { injectivity' := λ X Y f f' h, F.injectivity (by rw [←nat_iso.naturality_1 α.symm, h, nat_iso.naturality_1 α.symm]) } end variables {F G} lemma faithful.of_comp_iso {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G ≅ H) : faithful F := @faithful.of_comp _ _ _ _ _ _ F G (faithful.of_iso h.symm) alias faithful.of_comp_iso ← category_theory.iso.faithful_of_comp -- We could prove this from `faithful.of_comp_iso` using `eq_to_iso`, -- but that would introduce a cyclic import. lemma faithful.of_comp_eq {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G = H) : faithful F := @faithful.of_comp _ _ _ _ _ _ F G (h.symm ▸ ℋ) alias faithful.of_comp_eq ← eq.faithful_of_comp variables (F G) /-- “Divide” a functor by a faithful functor. -/ protected def faithful.div (F : C ⥤ E) (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : C ⥤ D := { obj := obj, map := @map, map_id' := begin assume X, apply G.injectivity, apply eq_of_heq, transitivity F.map (𝟙 X), from h_map, rw [F.map_id, G.map_id, h_obj X] end, map_comp' := begin assume X Y Z f g, apply G.injectivity, apply eq_of_heq, transitivity F.map (f ≫ g), from h_map, rw [F.map_comp, G.map_comp], congr' 1; try { exact (h_obj _).symm }; exact h_map.symm end } -- This follows immediately from `functor.hext` (`functor.hext h_obj @h_map`), -- but importing `category_theory.eq_to_hom` causes an import loop: -- category_theory.eq_to_hom → category_theory.opposites → -- category_theory.equivalence → category_theory.fully_faithful lemma faithful.div_comp (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : (faithful.div F G obj @h_obj @map @h_map) ⋙ G = F := begin tactic.unfreeze_local_instances, cases F with F_obj _ _ _; cases G with G_obj _ _ _, unfold faithful.div functor.comp, unfold_projs at h_obj, have: F_obj = G_obj ∘ obj := (funext h_obj).symm, subst this, congr, funext, exact eq_of_heq h_map end lemma faithful.div_faithful (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : faithful (faithful.div F G obj @h_obj @map @h_map) := (faithful.div_comp F G _ h_obj _ @h_map).faithful_of_comp instance full.comp [full F] [full G] : full (F ⋙ G) := { preimage := λ _ _ f, F.preimage (G.preimage f) } end category_theory
7c35a064f43645070cde6b7148ac4241a59ce680
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0315.lean
83aedc001d115d351c0b91f3edc4058b32d5ccce
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
77
lean
variables p q : Prop example (hp : p) (hnp: ¬p) : q := false.elim (hnp hp)
5036688b16849a34d3fb7a52aab9e72d767bc98f
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/polynomial/coeff.lean
ffe52898e3a2f79f5f7e12f22f954e6e115721fc
[ "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
5,267
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.monomial import data.finset.nat_antidiagonal /-! # Theory of univariate polynomials The theorems include formulas for computing coefficients, such as `coeff_add`, `coeff_sum`, `coeff_mul` -/ noncomputable theory open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v variables {R : Type u} {S : Type v} {a b : R} {n m : ℕ} variables [semiring R] {p q r : polynomial R} section coeff lemma coeff_one (n : ℕ) : coeff (1 : polynomial R) n = if 0 = n then 1 else 0 := coeff_monomial @[simp] lemma coeff_add (p q : polynomial R) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl lemma coeff_sum [semiring S] (n : ℕ) (f : ℕ → R → polynomial S) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply @[simp] lemma coeff_smul (p : polynomial R) (r : R) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply variable (R) /-- The nth coefficient, as a linear map. -/ def lcoeff (n : ℕ) : polynomial R →ₗ[R] R := { to_fun := λ f, coeff f n, map_add' := λ f g, coeff_add f g n, map_smul' := λ r p, coeff_smul p r n } variable {R} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial R) : lcoeff R n f = coeff f n := rfl lemma coeff_mul (p q : polynomial R) (n : ℕ) : coeff (p * q) n = ∑ x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 := have hite : ∀ a : ℕ × ℕ, ite (a.1 + a.2 = n) (coeff p (a.fst) * coeff q (a.snd)) 0 ≠ 0 → a.1 + a.2 = n, from λ a ha, by_contradiction (λ h, absurd (eq.refl (0 : R)) (by rwa if_neg h at ha)), calc coeff (p * q) n = ∑ a in p.support, ∑ b in q.support, ite (a + b = n) (coeff p a * coeff q b) 0 : by { simp only [mul_def, coeff_sum, coeff_single], refl } ... = ∑ v in p.support.product q.support, ite (v.1 + v.2 = n) (coeff p v.1 * coeff q v.2) 0 : by rw sum_product ... = ∑ x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 : begin refine sum_bij_ne_zero (λ x _ _, x) (λ x _ hx, nat.mem_antidiagonal.2 (hite x hx)) (λ _ _ _ _ _ _ h, h) (λ x h₁ h₂, ⟨x, _, _, rfl⟩) _, { rw [mem_product, mem_support_iff, mem_support_iff], exact ne_zero_and_ne_zero_of_mul h₂ }, { rw nat.mem_antidiagonal at h₁, rwa [if_pos h₁] }, { intros x h hx, rw [if_pos (hite x hx)] } end @[simp] lemma mul_coeff_zero (p q : polynomial R) : coeff (p * q) 0 = coeff p 0 * coeff q 0 := by simp [coeff_mul] lemma coeff_mul_X_zero (p : polynomial R) : coeff (p * X) 0 = 0 := by simp lemma coeff_X_mul_zero (p : polynomial R) : coeff (X * p) 0 = 0 := by simp lemma coeff_C_mul_X (x : R) (k n : ℕ) : coeff (C x * X^k : polynomial R) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [monomial, single, eq_comm, coeff]; congr @[simp] lemma coeff_C_mul (p : polynomial R) : coeff (C a * p) n = a * coeff p n := begin conv in (a * _) { rw [← @sum_single _ _ _ p, coeff_sum] }, rw [mul_def, ←monomial_zero_left, monomial, sum_single_index], { simp only [coeff_single, finsupp.mul_sum, coeff_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, { simp [finsupp.sum] } end @[simp] lemma coeff_mul_C (p : polynomial R) (n : ℕ) (a : R) : coeff (p * C a) n = coeff p n * a := begin conv_rhs { rw [← @finsupp.sum_single _ _ _ p, coeff_sum] }, rw [mul_def, ←monomial_zero_left], simp_rw [sum_single_index], { simp only [coeff_single, finsupp.sum_mul, coeff_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h], }, end lemma monomial_one_eq_X_pow : ∀{n}, monomial n (1 : R) = X^n | 0 := rfl | (n+1) := calc monomial (n + 1) (1 : R) = monomial n 1 * X : by rw [X, monomial_mul_monomial, mul_one] ... = X^n * X : by rw [monomial_one_eq_X_pow] ... = X^(n+1) : by simp only [pow_add, pow_one] lemma monomial_eq_smul_X {n} : monomial n (a : R) = a • X^n := begin calc monomial n a = monomial n (a * 1) : by simp ... = a • monomial n 1 : (smul_single' _ _ _).symm ... = a • X^n : by rw monomial_one_eq_X_pow end lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial R) n = if n = k then 1 else 0 := by rw [← monomial_one_eq_X_pow]; simp [monomial, single, eq_comm, coeff]; congr @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff (X^n : polynomial R) n = 1 := by simp [coeff_X_pow] theorem coeff_mul_X_pow (p : polynomial R) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end @[simp] theorem coeff_mul_X (p : polynomial R) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial R} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n) end coeff end polynomial
a2d29ce6d333e4fbb11e6da3351d6aeed510befa
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/field_theory/splitting_field.lean
5b91a3dd6dade1ec6f8f58a5a9beee9070464fdb
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
8,905
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import data.polynomial import ring_theory.principal_ideal_domain universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial noncomputable theory open_locale classical big_operators variables [field α] [field β] [field γ] open polynomial section splits variables (i : α →+* β) /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (classical.not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tautology)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_domain.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_map_iff (j : β →+* γ) {f : polynomial α} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_X_sub_C {x : α} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_id_iff_splits {f : polynomial α} : (f.map i).splits (ring_hom.id β) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : polynomial α} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end theorem splits_prod_iff {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := is_noetherian_ring.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (by rw [ne.def, map_eq_zero]; exact hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, is_noetherian_ring.irreducible_induction_on (f.map i) (λ _, ⟨{37}, by simp [i.map_zero]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 :: s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, domain.mul_left_inj hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit hp.ne_zero, mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 hp.ne_zero), one_mul], end⟩) section UFD local attribute [instance, priority 10] principal_ideal_domain.to_unique_factorization_domain local infix ` ~ᵤ ` : 50 := associated open unique_factorization_domain associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := unique (λ p hp, irreducible_factors (mt (map_eq_zero i).1 hf0) _ hp) (λ p' m, begin obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m, exact irreducible_of_degree_eq_one (degree_X_sub_C _), end) (associated.symm $ calc _ ~ᵤ f.map i : ⟨(units.map' C : units β →* units (polynomial β)) (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (mt (map_eq_zero i).1 hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_domain.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits (ring_hom.id _) f → splits i f := unique_factorization_domain.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β →+* γ) {f : polynomial α} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end end splits end polynomial
158019ddb9cb864296516ea6d43f3315d3019192
690889011852559ee5ac4dfea77092de8c832e7e
/src/meta/expr.lean
a7e184993a7705481352f9e66e0b467ecd35a497
[ "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
20,596
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 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 /- 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 /-- 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 := [] /-- 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 in the second argument `e` by expressions from the first argument `es`. If the length of `es` is larger than the number of lambdas in `e`, then the term is applied to the remaining terms -/ meta def instantiate_lambdas_or_apps : list expr → expr → expr | (e'::es) (lam n bi t e) := instantiate_lambdas_or_apps es (e.instantiate_var e') | es e := mk_app e es 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 /-- Checks whether for all elements `(nm, val)` in the list we have `val = nm.{univs} args` -/ 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 /-- Checks whether there is an expression `e` such that for all elements `(nm, val)` in the list `val = nm ... e` where `...` denotes the same list of parameters for all applications. Returns e if it exists. -/ 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 /-- Checks whether there is an expression `e` such that for all *non-propositional* elements `(nm, val)` in the list `val = e ... nm` where `...` denotes the same list of parameters for all applications. Also checks whether the resulting expression unifies with the given one -/ 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 /-- Checks whether there is an expression `e` such that `val` is the eta-expansion of `e`. 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 /-- 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
ffc3bc82bc62f73e0c50d28ba3a3f462bdf39f67
e5c11e5a7d990ce404047c2bd848eeafac3c0a85
/src/defs.lean
df42a970c9eec179f8b4df5ba314af4ca5231782
[ "LPPL-1.3c" ]
permissive
lean-forward/class-number
9ec63c24845e46efc8fa8b15324d0815918292c7
4fccf36d5e0e16accae84c16df77a3839ad964e4
refs/heads/main
1,686,927,014,542
1,624,886,724,000
1,624,886,724,000
327,319,245
2
0
null
null
null
null
UTF-8
Lean
false
false
7,971
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.equiv.basic import algebra.group.defs import algebra.group.hom import logic.embedding /-! # Definitions of group actions This file defines a hierarchy of group action type-classes: * `has_scalar α β` * `mul_action α β` * `distrib_mul_action α β` The hierarchy is extended further by `semimodule`, defined elsewhere. Also provided are type-classes regarding the interaction of different group actions, * `smul_comm_class M N α` * `is_scalar_tower M N α` ## Notation `a • b` is used as notation for `smul a b`. ## Implementation details This file should avoid depending on other parts of `group_theory`, to avoid import cycles. More sophisticated lemmas belong in `group_theory.group_action`. -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open function /-- Typeclass for types with a scalar multiplication operation, denoted `•` (`\bu`) -/ class has_scalar (α : Type u) (γ : Type v) := (smul : α → γ → γ) infixr ` • `:73 := has_scalar.smul /-- Typeclass for multiplicative actions by monoids. This generalizes group actions. -/ @[protect_proj] class mul_action (α : Type u) (β : Type v) [monoid α] extends has_scalar α β := (one_smul : ∀ b : β, (1 : α) • b = b) (mul_smul : ∀ (x y : α) (b : β), (x * y) • b = x • y • b) /-- A typeclass mixin saying that two actions on the same space commute. -/ class smul_comm_class (M N α : Type*) [has_scalar M α] [has_scalar N α] : Prop := (smul_comm : ∀ (m : M) (n : N) (a : α), m • n • a = n • m • a) export mul_action (mul_smul) smul_comm_class (smul_comm) /-- Commutativity of actions is a symmetric relation. This lemma can't be an instance because this would cause a loop in the instance search graph. -/ lemma smul_comm_class.symm (M N α : Type*) [has_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class N M α := ⟨λ a' a b, (smul_comm a a' b).symm⟩ instance smul_comm_class_self (M α : Type*) [comm_monoid M] [mul_action M α] : smul_comm_class M M α := ⟨λ a a' b, by rw [← mul_smul, mul_comm, mul_smul]⟩ /-- An instance of `is_scalar_tower M N α` states that the multiplicative action of `M` on `α` is determined by the multiplicative actions of `M` on `N` and `N` on `α`. -/ class is_scalar_tower (M N α : Type*) [has_scalar M N] [has_scalar N α] [has_scalar M α] : Prop := (smul_assoc : ∀ (x : M) (y : N) (z : α), (x • y) • z = x • (y • z)) @[simp] lemma smul_assoc {M N} [has_scalar M N] [has_scalar N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : N) (z : α) : (x • y) • z = x • y • z := is_scalar_tower.smul_assoc x y z section variables [monoid α] [mul_action α β] lemma smul_smul (a₁ a₂ : α) (b : β) : a₁ • a₂ • b = (a₁ * a₂) • b := (mul_smul _ _ _).symm variable (α) @[simp] theorem one_smul (b : β) : (1 : α) • b = b := mul_action.one_smul _ variables {α} /-- Pullback a multiplicative action along an injective map respecting `•`. -/ protected def function.injective.mul_action [has_scalar α γ] (f : γ → β) (hf : injective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : mul_action α γ := { smul := (•), one_smul := λ x, hf $ (smul _ _).trans $ one_smul _ (f x), mul_smul := λ c₁ c₂ x, hf $ by simp only [smul, mul_smul] } /-- Pushforward a multiplicative action along a surjective map respecting `•`. -/ protected def function.surjective.mul_action [has_scalar α γ] (f : β → γ) (hf : surjective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : mul_action α γ := { smul := (•), one_smul := λ y, by { rcases hf y with ⟨x, rfl⟩, rw [← smul, one_smul] }, mul_smul := λ c₁ c₂ y, by { rcases hf y with ⟨x, rfl⟩, simp only [← smul, mul_smul] } } section ite variables (p : Prop) [decidable p] lemma ite_smul (a₁ a₂ : α) (b : β) : (ite p a₁ a₂) • b = ite p (a₁ • b) (a₂ • b) := by split_ifs; refl lemma smul_ite (a : α) (b₁ b₂ : β) : a • (ite p b₁ b₂) = ite p (a • b₁) (a • b₂) := by split_ifs; refl end ite namespace mul_action variables (α) /-- The regular action of a monoid on itself by left multiplication. -/ def regular : mul_action α α := { smul := λ a₁ a₂, a₁ * a₂, one_smul := λ a, one_mul a, mul_smul := λ a₁ a₂ a₃, mul_assoc _ _ _, } section regular local attribute [instance] regular instance is_scalar_tower.left : is_scalar_tower α α β := ⟨λ x y z, mul_smul x y z⟩ end regular variables (α β) /-- Embedding induced by action. -/ def to_fun : β ↪ (α → β) := ⟨λ y x, x • y, λ y₁ y₂ H, one_smul α y₁ ▸ one_smul α y₂ ▸ by convert congr_fun H 1⟩ variables {α β} @[simp] lemma to_fun_apply (x : α) (y : β) : mul_action.to_fun α β y x = x • y := rfl variable (β) /-- An action of `α` on `β` and a monoid homomorphism `γ → α` induce an action of `γ` on `β`. -/ def comp_hom [monoid γ] (g : γ →* α) : mul_action γ β := { smul := λ x b, (g x) • b, one_smul := by simp [g.map_one, mul_action.one_smul], mul_smul := by simp [g.map_mul, mul_action.mul_smul] } end mul_action end section compatible_scalar @[simp] lemma smul_one_smul {M} (N) [monoid N] [has_scalar M N] [mul_action N α] [has_scalar M α] [is_scalar_tower M N α] (x : M) (y : α) : (x • (1 : N)) • y = x • y := by rw [smul_assoc, one_smul] end compatible_scalar /-- Typeclass for multiplicative actions on additive structures. This generalizes group modules. -/ class distrib_mul_action (α : Type u) (β : Type v) [monoid α] [add_monoid β] extends mul_action α β := (smul_add : ∀(r : α) (x y : β), r • (x + y) = r • x + r • y) (smul_zero : ∀(r : α), r • (0 : β) = 0) section variables [monoid α] [add_monoid β] [distrib_mul_action α β] theorem smul_add (a : α) (b₁ b₂ : β) : a • (b₁ + b₂) = a • b₁ + a • b₂ := distrib_mul_action.smul_add _ _ _ @[simp] theorem smul_zero (a : α) : a • (0 : β) = 0 := distrib_mul_action.smul_zero _ /-- Pullback a distributive multiplicative action along an injective additive monoid homomorphism. -/ protected def function.injective.distrib_mul_action [add_monoid γ] [has_scalar α γ] (f : γ →+ β) (hf : injective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : distrib_mul_action α γ := { smul := (•), smul_add := λ c x y, hf $ by simp only [smul, f.map_add, smul_add], smul_zero := λ c, hf $ by simp only [smul, f.map_zero, smul_zero], .. hf.mul_action f smul } /-- Pushforward a distributive multiplicative action along a surjective additive monoid homomorphism.-/ protected def function.surjective.distrib_mul_action [add_monoid γ] [has_scalar α γ] (f : β →+ γ) (hf : surjective f) (smul : ∀ (c : α) x, f (c • x) = c • f x) : distrib_mul_action α γ := { smul := (•), smul_add := λ c x y, by { rcases hf x with ⟨x, rfl⟩, rcases hf y with ⟨y, rfl⟩, simp only [smul_add, ← smul, ← f.map_add] }, smul_zero := λ c, by simp only [← f.map_zero, ← smul, smul_zero], .. hf.mul_action f smul } variable (β) /-- Scalar multiplication by `r` as an `add_monoid_hom`. -/ def const_smul_hom (r : α) : β →+ β := { to_fun := (•) r, map_zero' := smul_zero r, map_add' := smul_add r } variable {β} @[simp] lemma const_smul_hom_apply (r : α) (x : β) : const_smul_hom β r x = r • x := rfl end section variables [monoid α] [add_group β] [distrib_mul_action α β] @[simp] theorem smul_neg (r : α) (x : β) : r • (-x) = -(r • x) := eq_neg_of_add_eq_zero $ by rw [← smul_add, neg_add_self, smul_zero] theorem smul_sub (r : α) (x y : β) : r • (x - y) = r • x - r • y := by rw [sub_eq_add_neg, sub_eq_add_neg, smul_add, smul_neg] end
fb17afbb87eb2932e6083d33b4bc89acf4b11234
0d4c30038160d9c35586ce4dace36fe26a35023b
/src/analysis/calculus/deriv.lean
a091080593086e38ef9f3f756c977700114dba22
[ "Apache-2.0" ]
permissive
b-mehta/mathlib
b0c8ec929ec638447e4262f7071570d23db52e14
ce72cde867feabe5bb908cf9e895acc0e11bf1eb
refs/heads/master
1,599,457,264,781
1,586,969,260,000
1,586,969,260,000
220,672,634
0
0
Apache-2.0
1,583,944,480,000
1,573,317,991,000
Lean
UTF-8
Lean
false
false
57,102
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv data.polynomial /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. -/ universes u v w noncomputable theory open_locale classical topological_space open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) set_option class.instance_max_depth 100 variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (nhds_within x s) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := by simp [has_deriv_within_at, has_deriv_at_filter, has_fderiv_within_at] /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := by simp [has_deriv_at, has_deriv_at_filter, has_fderiv_at] /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ principal (-{x})) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), rw mem_inf_principal, refine univ_mem_sets' (λ z hz, _), have : z ≠ x, by simpa [function.comp] using hz, simp only [mem_set_of_eq], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 this), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (s \ {x})) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x s) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (-{x})) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ nhds_within x s) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } section congr /-! ### Congruence properties of derivatives -/ theorem has_deriv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := has_fderiv_at_filter_congr_of_mem_sets hx h₀ (by simp [h₁]) lemma has_deriv_at_filter.congr_of_mem_sets (h : has_deriv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa has_deriv_at_filter_congr_of_mem_sets hx hL rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_mem_nhds_within (h : has_deriv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_mem_sets h h₁ hx lemma has_deriv_at.congr_of_mem_nhds (h : has_deriv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma deriv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr_of_mem_nhds_within hs hL hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma deriv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : deriv f₁ x = deriv f x := by { unfold deriv, rwa fderiv_congr_of_mem_nhds } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (is_o_zero _ _).congr_left $ by simp theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := by { unfold deriv_within, rw fderiv_within_id, simp, assumption } end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (is_o_zero _ _).congr_left $ λ _, by simp [continuous_linear_map.zero_apply, sub_self] theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := by { rw (differentiable_at_const _).deriv_within hxs, apply deriv_const } end const section is_linear_map /-! ### Derivative of linear maps -/ variables (s x L) [is_linear_map 𝕜 f] lemma is_linear_map.has_deriv_at_filter : has_deriv_at_filter f (f 1) x L := (is_o_zero _ _).congr_left begin intro y, simp only [sub_smul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply], rw ← is_linear_map.smul f x, rw ← is_linear_map.smul f y, simp end lemma is_linear_map.has_deriv_within_at : has_deriv_within_at f (f 1) s x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.has_deriv_at : has_deriv_at f (f 1) x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.differentiable_at : differentiable_at 𝕜 f x := (is_linear_map.has_deriv_at _).differentiable_at lemma is_linear_map.differentiable_within_at : differentiable_within_at 𝕜 f s x := (is_linear_map.differentiable_at _).differentiable_within_at @[simp] lemma is_linear_map.deriv : deriv f x = f 1 := has_deriv_at.deriv (is_linear_map.has_deriv_at _) lemma is_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f 1 := begin rw differentiable_at.deriv_within (is_linear_map.differentiable_at _) hxs, apply is_linear_map.deriv, assumption end lemma is_linear_map.differentiable : differentiable 𝕜 f := λ x, is_linear_map.differentiable_at _ lemma is_linear_map.differentiable_on : differentiable_on 𝕜 f s := is_linear_map.differentiable.differentiable_on end is_linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ by simp [add_smul, smul_add] theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := (hf.has_deriv_within_at.add_const c).deriv_within hxs lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : deriv (λy, f y + c) x = deriv f x := (hf.has_deriv_at.add_const c).deriv theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c + f y) s x = deriv_within f s x := (hf.has_deriv_within_at.const_add c).deriv_within hxs lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λy, c + f y) x = deriv f x := (hf.has_deriv_at.const_add c).deriv end add section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := begin show has_fderiv_within_at _ _ _ _, convert has_fderiv_within_at.smul hc hf, ext, simp [smul_add, (mul_smul _ _ _).symm, mul_comm] end theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := h.neg.congr (by simp) (by simp) theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := h.has_deriv_within_at.neg.deriv_within hxs lemma deriv_neg : deriv (λy, -f y) x = - deriv f x := if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg, by simp only [deriv_zero_of_not_differentiable_at h, deriv_zero_of_not_differentiable_at this, neg_zero] @[simp] lemma deriv_neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv_neg end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := (hf.has_deriv_within_at.sub_const c).deriv_within hxs lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, f y - c) x = deriv f x := (hf.has_deriv_at.sub_const c).deriv theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c - f y) s x = -deriv_within f s x := (hf.has_deriv_within_at.const_sub c).deriv_within hxs lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c - f y) x = -deriv f x := (hf.has_deriv_at.const_sub c).deriv end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := has_fderiv_at_filter.tendsto_nhds hL h theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := have (smul_right 1 g' : 𝕜 →L[𝕜] _).comp (smul_right 1 h' : 𝕜 →L[𝕜] _) = smul_right 1 (h' • g'), by { ext, simp [mul_smul] }, begin unfold has_deriv_at_filter, rw ← this, exact has_fderiv_at_filter.comp x hg hh, end theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin apply has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg _) hh, calc map h (nhds_within x s) ≤ nhds_within (h x) (h '' s) : hh.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (h x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ lemma has_deriv_at_inv_one : has_deriv_at (λx, x⁻¹) (-1) (1 : 𝕜) := begin rw has_deriv_at_iff_is_o_nhds_zero, have : is_o (λ (h : 𝕜), h^2 * (1 + h)⁻¹) (λ (h : 𝕜), h * 1) (𝓝 0), { have : tendsto (λ (h : 𝕜), (1 + h)⁻¹) (𝓝 0) (𝓝 (1 + 0)⁻¹) := ((tendsto_const_nhds).add tendsto_id).inv' (by norm_num), exact is_o.mul_is_O (is_o_pow_id one_lt_two) (is_O_one_of_tendsto _ this) }, apply this.congr' _ _, { have : metric.ball (0 : 𝕜) 1 ∈ 𝓝 (0 : 𝕜), from metric.ball_mem_nhds 0 zero_lt_one, filter_upwards [this], assume h hx, have : 0 < ∥1 + h∥ := calc 0 < ∥(1:𝕜)∥ - ∥-h∥ : by rwa [norm_neg, sub_pos, ← dist_zero_right h, normed_field.norm_one] ... ≤ ∥1 - -h∥ : norm_sub_norm_le _ _ ... = ∥1 + h∥ : by simp, have : 1 + h ≠ 0 := norm_pos_iff.mp this, simp, rw ← eq_div_iff_mul_eq _ _ (inv_ne_zero this), field_simp, simp [right_distrib, sub_mul, (show (1 + h)⁻¹ * (1 + h) = 1, by rw mul_comm; exact field.mul_inv_cancel this)], ring }, { exact univ_mem_sets' mul_one } end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := begin have A : has_deriv_at (λy, y⁻¹) (-1) (x⁻¹ * x : 𝕜), by { simp only [inv_mul_cancel x_ne_zero, has_deriv_at_inv_one] }, have B : has_deriv_at (λy, x⁻¹ * y) (x⁻¹) x, by simpa only [mul_one] using (has_deriv_at_id x).const_mul x⁻¹, convert (A.comp x B : _).const_mul x⁻¹, { ext y, rw [function.comp_apply, mul_inv', inv_inv', mul_comm, mul_assoc, mul_inv_cancel x_ne_zero, mul_one] }, { field_simp [pow_two] } end theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul', pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv end division end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma continuous : continuous (λx, p.eval x) := p.differentiable.continuous protected lemma continuous_on : continuous_on (λx, p.eval x) s := p.continuous.continuous_on protected lemma continuous_at : continuous_at (λx, p.eval x) x := p.continuous.continuous_at protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x := p.continuous_at.continuous_within_at protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} variable {n : ℕ } lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C 1 * (polynomial.X)^n).has_deriv_at x, { simp }, { rw [polynomial.derivative_monomial], simp } end theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, nat.sub_zero, nat.cast_one] }, { simp only [nat.iterate_succ', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div_eq_inv, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_deriv_at_const] }, { exact this m hm } end theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = ((finset.range k).prod (λ i, m - i):ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [nat.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], apply deriv_congr_of_mem_nhds, apply eventually.mono _ @ihk, exact mem_nhds_sets (is_open_neg $ is_closed_eq continuous_id continuous_const) hx } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in nhds_within x (s \ {x}), (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in nhds_within x s, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r := (hf.limsup_slope_le' (lt_irrefl x) hr).frequently (nhds_within_Ioi_self_ne_bot x) end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in nhds_within x (s \ {x}), ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in nhds_within x {x}, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [mem_set_of_eq, norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.limsup_norm_slope_le hr).frequently (nhds_within_Ioi_self_ne_bot x) /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.limsup_slope_norm_le hr).frequently (nhds_within_Ioi_self_ne_bot x), refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
f8ab1d20cc8169bc55b0d9282b064b77fe14cc0a
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/run/proj.lean
a21d773b07c70e583f299dc6d36864c7fcc9a9a8
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
353
lean
import logic.eq inductive sigma2 {A : Type} (B : A → Type) := mk : Π (a : A), B a → sigma2 B #projections sigma2 :: proj1 proj2 check sigma2.proj1 check sigma2.proj2 variables {A : Type} {B : A → Type} variables (a : A) (b : B a) theorem tst1 : sigma2.proj1 (sigma2.mk a b) = a := rfl theorem tst2 : sigma2.proj2 (sigma2.mk a b) = b := rfl
910562f60440084caefe027e49f6087c4fc15bbc
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/myring/basic.lean
7807263989a37bbc6fd3fe8cb631c11b1efd8bb3
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
5,526
lean
namespace hidden -- Commutative Unitary Ring class myring (α : Type) extends has_add α, has_zero α, has_neg α, has_mul α, has_one α := (decidable_eq : ∀ a b : α, decidable (a = b)) (add_assoc (a b c : α) : a + b + c = a + (b + c)) (add_zero (a : α) : a + 0 = a) (add_neg (a : α) : a + -a = 0) (mul_assoc (a b c : α) : a * b * c = a * (b * c)) (mul_comm (a b : α) : a * b = b * a) (mul_one (a : α) : a * 1 = a) (mul_add (a b c : α) : a * (b + c) = a * b + a * c) namespace myring variables {α : Type} [myring α] (a b c : α) instance (a b : α) : decidable (a = b) := decidable_eq a b theorem one_mul : 1 * a = a := begin rw [mul_comm], from mul_one _, end theorem add_mul : (a + b) * c = a * c + b * c := by rw [mul_comm, mul_comm _ c, mul_comm _ c, mul_add] theorem add_cancel_right : a + c = b + c → a = b := begin assume h, rw [←add_zero a, ←add_zero b, ←add_neg c, ←add_assoc, ←add_assoc, h], end theorem add_cancel_right_iff: a + c = b + c ↔ a = b := begin split, { from add_cancel_right _ _ _, }, { assume hbc, rw hbc, }, end theorem zero_add : 0 + a = a := begin apply add_cancel_right _ _ (-a), rw [add_assoc, add_neg, add_zero], end theorem neg_zero : -(0 : α) = 0 := begin rw [←zero_add (-(0 : α)), add_neg], end private lemma important_first_lemma : a + b = 0 → b + a = 0 := begin assume h, apply add_cancel_right _ _ b, rw [add_assoc, h, zero_add, add_zero], end theorem neg_add : -a + a = 0 := begin apply important_first_lemma, rw add_neg, end theorem add_cancel_left : a + b = a + c → b = c := begin assume h, rw [←zero_add b, ←zero_add c, ←neg_add a, add_assoc, add_assoc, h], end theorem add_cancel_left_iff: a + b = a + c ↔ b = c := begin split, { from add_cancel_left _ _ _, }, { assume hbc, rw hbc, }, end theorem neg_neg : -(-a) = a := begin apply add_cancel_right _ _ (-a), rw [add_neg, neg_add], end theorem neg_unique : a + b = 0 ↔ a = -b := begin split, assume h, rw [←add_zero a, ←add_neg b, ←add_assoc], conv { to_rhs, rw ←zero_add (-b), }, congr, assumption, assume h, subst h, from neg_add b, end private theorem neg_distr_swap : -(a + b) = -b + -a := begin symmetry, rw [←neg_unique, add_assoc, ←add_assoc (-a), neg_add, zero_add, neg_add], end theorem mul_zero : a * 0 = 0 := begin apply add_cancel_left (a * 0), rw [←mul_add a, zero_add, add_zero], end theorem zero_mul : 0 * a = 0 := by rw [mul_comm, mul_zero] theorem neg_eq_mul_neg_one : -a = -1 * a := begin symmetry, conv { to_rhs, rw ←mul_one a, }, rw [←neg_unique, mul_comm, ←mul_add, neg_add, mul_zero], end theorem neg_mul : (-a) * b = -(a * b) := begin rw [←neg_unique, mul_comm (-a), mul_comm a, ←mul_add, neg_add, mul_zero], end theorem mul_neg : a * (-b) = -(a * b) := begin rw [mul_comm a (-b), mul_comm a b], apply neg_mul, end theorem neg_mul_neg : (-a) * (-b) = a * b := by rw [mul_neg, neg_mul, neg_neg] theorem neg_distr : -(a + b) = -a + -b := by rw [neg_eq_mul_neg_one a, neg_eq_mul_neg_one b, ←mul_add, ←neg_eq_mul_neg_one] -- "Negate Equality" theorem neg_eq : a = b ↔ -a = -b := begin split; assume h, congr, assumption, rw [←neg_neg a, ←neg_neg b, h], end theorem add_comm : a + b = b + a := by rw [neg_eq, neg_distr, neg_distr_swap] theorem add_cancel_left_to_zero : a + b = b → a = 0 := begin assume h, apply add_cancel_right _ _ b, rwa zero_add, end theorem add_cancel_left_to_zero_iff: a + b = b ↔ a = 0 := begin split, { from add_cancel_left_to_zero _ _, }, { assume ha0, rw ha0, rw zero_add, }, end theorem add_cancel_right_to_zero : a + b = a → b = 0 := λ h, add_cancel_left_to_zero b a (by rwa add_comm at h) theorem add_cancel_right_to_zero_iff: a + b = a ↔ b = 0 := begin split, { from add_cancel_right_to_zero _ _, }, { assume hb0, rw hb0, rw add_zero, }, end theorem add_left : a = b → c + a = c + b := begin assume h, congr, assumption, end theorem add_right : a = b → a + c = b + c := begin assume h, congr, assumption, end theorem one_eq_zero_impl_all_zero : (1 : α) = 0 → ∀ x : α, x = 0 := begin assume h10, intro x, rw [←one_mul x, h10, zero_mul], end def sub : α → α → α := λ a b, a + (-b) instance: has_sub α := ⟨sub⟩ theorem sub_def : a - b = a + -b := rfl theorem sub_self : a - a = 0 := begin change a + -a = 0, apply add_neg, end theorem sub_zero : a - 0 = a := by rw [sub_def, neg_zero, add_zero] theorem zero_sub : 0 - a = -a := by rw [sub_def, zero_add] theorem mul_sub : a * (b - c) = a * b - a * c := begin change a * (b + (-c)) = a * b + -(a * c), rw [mul_add, ←mul_neg], end theorem neg_sub : -(a - b) = b - a := by rw [sub_def, sub_def, neg_distr, neg_neg, add_comm] theorem sub_mul : (a - b) * c = a * c - b * c:= by rw [mul_comm, mul_sub, mul_comm a, mul_comm b] -- This is handy imo -- Imma have to firmly agree, bro theorem sub_to_zero_iff_eq : a - b = 0 ↔ a = b := begin split; assume h, { symmetry, rwa [neg_eq, ←neg_unique, add_comm], }, { change a + -b = 0, rwa [neg_unique, neg_neg], }, end instance add_is_assoc: is_associative α (+) := ⟨add_assoc⟩ instance add_is_comm: is_commutative α (+) := ⟨add_comm⟩ instance mul_is_assoc: is_associative α (*) := ⟨mul_assoc⟩ instance mul_is_comm: is_commutative α (*) := ⟨mul_comm⟩ end myring end hidden
42b74fb2aabb75d5a1e238d8202862877470b7e3
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/category_theory/limits/shapes/types.lean
52068c9106ad267339290a401cbec574892104a5
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
8,173
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.types import category_theory.limits.shapes.products import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal /-! # Special shapes for limits in `Type`. The general shape (co)limits defined in `category_theory.limits.types` are intended for use through the limits API, and the actual implementation should mostly be considered "sealed". In this file, we provide definitions of the "standard" special shapes of limits in `Type`, giving the expected definitional implementation: * the terminal object is `punit` * the binary product of `X` and `Y` is `X × Y` * the product of a family `f : J → Type` is `Π j, f j`. Because these are not intended for use with the `has_limit` API, we instead construct terms of `limit_data`. As an example, when setting up the monoidal category structure on `Type` we use the `types_has_terminal` and `types_has_binary_products` instances. -/ universes u open category_theory open category_theory.limits namespace category_theory.limits.types /-- A restatement of `types.lift_π_apply` that uses `pi.π` and `pi.lift`. -/ @[simp] lemma pi_lift_π_apply {β : Type u} (f : β → Type u) {P : Type u} (s : Π b, P ⟶ f b) (b : β) (x : P) : (pi.π f b : (∏ f) → f b) (@pi.lift β _ _ f _ P s x) = s b x := congr_fun (limit.lift_π (fan.mk P s) b) x /-- A restatement of `types.map_π_apply` that uses `pi.π` and `pi.map`. -/ @[simp] lemma pi_map_π_apply {β : Type u} {f g : β → Type u} (α : Π j, f j ⟶ g j) (b : β) (x) : (pi.π g b : (∏ g) → g b) (pi.map α x) = α b ((pi.π f b : (∏ f) → f b) x) := limit.map_π_apply _ _ _ /-- The category of types has `punit` as a terminal object. -/ def terminal_limit_cone : limits.limit_cone (functor.empty (Type u)) := { cone := { X := punit, π := by tidy, }, is_limit := by tidy, } /-- The category of types has `pempty` as an initial object. -/ def initial_limit_cone : limits.colimit_cocone (functor.empty (Type u)) := { cocone := { X := pempty, ι := by tidy, }, is_colimit := by tidy, } open category_theory.limits.walking_pair /-- The product type `X × Y` forms a cone for the binary product of `X` and `Y`. -/ -- We manually generate the other projection lemmas since the simp-normal form for the legs is -- otherwise not created correctly. @[simps X] def binary_product_cone (X Y : Type u) : binary_fan X Y := binary_fan.mk prod.fst prod.snd @[simp] lemma binary_product_cone_fst (X Y : Type u) : (binary_product_cone X Y).fst = prod.fst := rfl @[simp] lemma binary_product_cone_snd (X Y : Type u) : (binary_product_cone X Y).snd = prod.snd := rfl /-- The product type `X × Y` is a binary product for `X` and `Y`. -/ @[simps] def binary_product_limit (X Y : Type u) : is_limit (binary_product_cone X Y) := { lift := λ (s : binary_fan X Y) x, (s.fst x, s.snd x), fac' := λ s j, walking_pair.cases_on j rfl rfl, uniq' := λ s m w, funext $ λ x, prod.ext (congr_fun (w left) x) (congr_fun (w right) x) } /-- The category of types has `X × Y`, the usual cartesian product, as the binary product of `X` and `Y`. -/ @[simps] def binary_product_limit_cone (X Y : Type u) : limits.limit_cone (pair X Y) := ⟨_, binary_product_limit X Y⟩ /-- The functor which sends `X, Y` to the product type `X × Y`. -/ -- We add the option `type_md` to tell `@[simps]` to not treat homomorphisms `X ⟶ Y` in `Type*` as -- a function type @[simps {type_md := reducible}] def binary_product_functor : Type u ⥤ Type u ⥤ Type u := { obj := λ X, { obj := λ Y, X × Y, map := λ Y₁ Y₂ f, (binary_product_limit X Y₂).lift (binary_fan.mk prod.fst (prod.snd ≫ f)) }, map := λ X₁ X₂ f, { app := λ Y, (binary_product_limit X₂ Y).lift (binary_fan.mk (prod.fst ≫ f) prod.snd) } } /-- The product functor given by the instance `has_binary_products (Type u)` is isomorphic to the explicit binary product functor given by the product type. -/ noncomputable def binary_product_iso_prod : binary_product_functor ≅ (prod.functor : Type u ⥤ _) := begin apply nat_iso.of_components (λ X, _) _, { apply nat_iso.of_components (λ Y, _) _, { exact ((limit.is_limit _).cone_point_unique_up_to_iso (binary_product_limit X Y)).symm }, { intros Y₁ Y₂ f, ext1; simp } }, { intros X₁ X₂ g, ext : 3; simp } end /-- The sum type `X ⊕ Y` forms a cocone for the binary coproduct of `X` and `Y`. -/ @[simps] def binary_coproduct_cocone (X Y : Type u) : cocone (pair X Y) := binary_cofan.mk sum.inl sum.inr /-- The sum type `X ⊕ Y` is a binary coproduct for `X` and `Y`. -/ @[simps] def binary_coproduct_colimit (X Y : Type u) : is_colimit (binary_coproduct_cocone X Y) := { desc := λ (s : binary_cofan X Y), sum.elim s.inl s.inr, fac' := λ s j, walking_pair.cases_on j rfl rfl, uniq' := λ s m w, funext $ λ x, sum.cases_on x (congr_fun (w left)) (congr_fun (w right)) } /-- The category of types has `X ⊕ Y`, as the binary coproduct of `X` and `Y`. -/ def binary_coproduct_colimit_cocone (X Y : Type u) : limits.colimit_cocone (pair X Y) := ⟨_, binary_coproduct_colimit X Y⟩ /-- The category of types has `Π j, f j` as the product of a type family `f : J → Type`. -/ def product_limit_cone {J : Type u} (F : J → Type u) : limits.limit_cone (discrete.functor F) := { cone := { X := Π j, F j, π := { app := λ j f, f j }, }, is_limit := { lift := λ s x j, s.π.app j x, uniq' := λ s m w, funext $ λ x, funext $ λ j, (congr_fun (w j) x : _) } } /-- The category of types has `Σ j, f j` as the coproduct of a type family `f : J → Type`. -/ def coproduct_colimit_cocone {J : Type u} (F : J → Type u) : limits.colimit_cocone (discrete.functor F) := { cocone := { X := Σ j, F j, ι := { app := λ j x, ⟨j, x⟩ }, }, is_colimit := { desc := λ s x, s.ι.app x.1 x.2, uniq' := λ s m w, begin ext ⟨j, x⟩, have := congr_fun (w j) x, exact this, end }, } section fork variables {X Y Z : Type u} (f : X ⟶ Y) {g h : Y ⟶ Z} (w : f ≫ g = f ≫ h) /-- Show the given fork in `Type u` is an equalizer given that any element in the "difference kernel" comes from `X`. The converse of `unique_of_type_equalizer`. -/ noncomputable def type_equalizer_of_unique (t : ∀ (y : Y), g y = h y → ∃! (x : X), f x = y) : is_limit (fork.of_ι _ w) := fork.is_limit.mk' _ $ λ s, begin refine ⟨λ i, _, _, _⟩, { apply classical.some (t (s.ι i) _), apply congr_fun s.condition i }, { ext i, apply (classical.some_spec (t (s.ι i) _)).1 }, { intros m hm, ext i, apply (classical.some_spec (t (s.ι i) _)).2, apply congr_fun hm i }, end /-- The converse of `type_equalizer_of_unique`. -/ lemma unique_of_type_equalizer (t : is_limit (fork.of_ι _ w)) (y : Y) (hy : g y = h y) : ∃! (x : X), f x = y := begin let y' : punit ⟶ Y := λ _, y, have hy' : y' ≫ g = y' ≫ h := funext (λ _, hy), refine ⟨(fork.is_limit.lift' t _ hy').1 ⟨⟩, congr_fun (fork.is_limit.lift' t y' _).2 ⟨⟩, _⟩, intros x' hx', suffices : (λ (_ : punit), x') = (fork.is_limit.lift' t y' hy').1, rw ← this, apply fork.is_limit.hom_ext t, ext ⟨⟩, apply hx'.trans (congr_fun (fork.is_limit.lift' t _ hy').2 ⟨⟩).symm, end lemma type_equalizer_iff_unique : nonempty (is_limit (fork.of_ι _ w)) ↔ (∀ (y : Y), g y = h y → ∃! (x : X), f x = y) := ⟨λ i, unique_of_type_equalizer _ _ (classical.choice i), λ k, ⟨type_equalizer_of_unique f w k⟩⟩ /-- Show that the subtype `{x : Y // g x = h x}` is an equalizer for the pair `(g,h)`. -/ def equalizer_limit : limits.limit_cone (parallel_pair g h) := { cone := fork.of_ι (subtype.val : {x : Y // g x = h x} → Y) (funext subtype.prop), is_limit := fork.is_limit.mk' _ $ λ s, ⟨λ i, ⟨s.ι i, by apply congr_fun s.condition i⟩, rfl, λ m hm, funext $ λ x, subtype.ext (congr_fun hm x)⟩ } end fork end category_theory.limits.types
a8941b385dda0e256b2eb9122df397f2e8cdc3a6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/presheaf.lean
d91f2030933606d907530c0cb29514d0312b07df
[ "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
16,018
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.adjunction.limits import category_theory.adjunction.opposites import category_theory.elements import category_theory.limits.functor_category import category_theory.limits.kan_extension import category_theory.limits.preserves.limits import category_theory.limits.shapes.terminal import category_theory.limits.types /-! # Colimit of representables This file constructs an adjunction `yoneda_adjunction` between `(Cᵒᵖ ⥤ Type u)` and `ℰ` given a functor `A : C ⥤ ℰ`, where the right adjoint sends `(E : ℰ)` to `c ↦ (A.obj c ⟶ E)` (provided `ℰ` has colimits). This adjunction is used to show that every presheaf is a colimit of representables. Further, the left adjoint `colimit_adj.extend_along_yoneda : (Cᵒᵖ ⥤ Type u) ⥤ ℰ` satisfies `yoneda ⋙ L ≅ A`, that is, an extension of `A : C ⥤ ℰ` to `(Cᵒᵖ ⥤ Type u) ⥤ ℰ` through `yoneda : C ⥤ Cᵒᵖ ⥤ Type u`. It is the left Kan extension of `A` along the yoneda embedding, sometimes known as the Yoneda extension, as proved in `extend_along_yoneda_iso_Kan`. `unique_extension_along_yoneda` shows `extend_along_yoneda` is unique amongst cocontinuous functors with this property, establishing the presheaf category as the free cocompletion of a small category. ## Tags colimit, representable, presheaf, free cocompletion ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] * https://ncatlab.org/nlab/show/Yoneda+extension -/ namespace category_theory noncomputable theory open category limits universes u₁ u₂ variables {C : Type u₁} [small_category C] variables {ℰ : Type u₂} [category.{u₁} ℰ] variable (A : C ⥤ ℰ) namespace colimit_adj /-- The functor taking `(E : ℰ) (c : Cᵒᵖ)` to the homset `(A.obj C ⟶ E)`. It is shown in `L_adjunction` that this functor has a left adjoint (provided `E` has colimits) given by taking colimits over categories of elements. In the case where `ℰ = Cᵒᵖ ⥤ Type u` and `A = yoneda`, this functor is isomorphic to the identity. Defined as in [MM92], Chapter I, Section 5, Theorem 2. -/ @[simps] def restricted_yoneda : ℰ ⥤ (Cᵒᵖ ⥤ Type u₁) := yoneda ⋙ (whiskering_left _ _ (Type u₁)).obj (functor.op A) /-- The functor `restricted_yoneda` is isomorphic to the identity functor when evaluated at the yoneda embedding. -/ def restricted_yoneda_yoneda : restricted_yoneda (yoneda : C ⥤ Cᵒᵖ ⥤ Type u₁) ≅ 𝟭 _ := nat_iso.of_components (λ P, nat_iso.of_components (λ X, yoneda_sections_small X.unop _) (λ X Y f, funext $ λ x, begin dsimp, rw ← functor_to_types.naturality _ _ x f (𝟙 _), dsimp, simp, end)) (λ _ _ _, rfl) /-- (Implementation). The equivalence of homsets which helps construct the left adjoint to `colimit_adj.restricted_yoneda`. It is shown in `restrict_yoneda_hom_equiv_natural` that this is a natural bijection. -/ def restrict_yoneda_hom_equiv (P : Cᵒᵖ ⥤ Type u₁) (E : ℰ) {c : cocone ((category_of_elements.π P).left_op ⋙ A)} (t : is_colimit c) : (c.X ⟶ E) ≃ (P ⟶ (restricted_yoneda A).obj E) := ((ulift_trivial _).symm ≪≫ t.hom_iso' E).to_equiv.trans { to_fun := λ k, { app := λ c p, k.1 (opposite.op ⟨_, p⟩), naturality' := λ c c' f, funext $ λ p, (k.2 (quiver.hom.op ⟨f, rfl⟩ : (opposite.op ⟨c', P.map f p⟩ : P.elementsᵒᵖ) ⟶ opposite.op ⟨c, p⟩)).symm }, inv_fun := λ τ, { val := λ p, τ.app p.unop.1 p.unop.2, property := λ p p' f, begin simp_rw [← f.unop.2], apply (congr_fun (τ.naturality f.unop.1) p'.unop.2).symm, end }, left_inv := begin rintro ⟨k₁, k₂⟩, ext, dsimp, congr' 1, simp, end, right_inv := begin rintro ⟨_, _⟩, refl, end } /-- (Implementation). Show that the bijection in `restrict_yoneda_hom_equiv` is natural (on the right). -/ lemma restrict_yoneda_hom_equiv_natural (P : Cᵒᵖ ⥤ Type u₁) (E₁ E₂ : ℰ) (g : E₁ ⟶ E₂) {c : cocone _} (t : is_colimit c) (k : c.X ⟶ E₁) : restrict_yoneda_hom_equiv A P E₂ t (k ≫ g) = restrict_yoneda_hom_equiv A P E₁ t k ≫ (restricted_yoneda A).map g := begin ext _ X p, apply (assoc _ _ _).symm, end variables [has_colimits ℰ] /-- The left adjoint to the functor `restricted_yoneda` (shown in `yoneda_adjunction`). It is also an extension of `A` along the yoneda embedding (shown in `is_extension_along_yoneda`), in particular it is the left Kan extension of `A` through the yoneda embedding. -/ def extend_along_yoneda : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ := adjunction.left_adjoint_of_equiv (λ P E, restrict_yoneda_hom_equiv A P E (colimit.is_colimit _)) (λ P E E' g, restrict_yoneda_hom_equiv_natural A P E E' g _) @[simp] lemma extend_along_yoneda_obj (P : Cᵒᵖ ⥤ Type u₁) : (extend_along_yoneda A).obj P = colimit ((category_of_elements.π P).left_op ⋙ A) := rfl lemma extend_along_yoneda_map {X Y : Cᵒᵖ ⥤ Type u₁} (f : X ⟶ Y) : (extend_along_yoneda A).map f = colimit.pre ((category_of_elements.π Y).left_op ⋙ A) (category_of_elements.map f).op := begin ext J, erw colimit.ι_pre ((category_of_elements.π Y).left_op ⋙ A) (category_of_elements.map f).op, dsimp only [extend_along_yoneda, restrict_yoneda_hom_equiv, is_colimit.hom_iso', is_colimit.hom_iso, ulift_trivial], simpa end /-- Show `extend_along_yoneda` is left adjoint to `restricted_yoneda`. The construction of [MM92], Chapter I, Section 5, Theorem 2. -/ def yoneda_adjunction : extend_along_yoneda A ⊣ restricted_yoneda A := adjunction.adjunction_of_equiv_left _ _ /-- The initial object in the category of elements for a representable functor. In `is_initial` it is shown that this is initial. -/ def elements.initial (A : C) : (yoneda.obj A).elements := ⟨opposite.op A, 𝟙 _⟩ /-- Show that `elements.initial A` is initial in the category of elements for the `yoneda` functor. -/ def is_initial (A : C) : is_initial (elements.initial A) := { desc := λ s, ⟨s.X.2.op, comp_id _⟩, uniq' := λ s m w, begin simp_rw ← m.2, dsimp [elements.initial], simp, end, fac' := by rintros s ⟨⟨⟩⟩, } /-- `extend_along_yoneda A` is an extension of `A` to the presheaf category along the yoneda embedding. `unique_extension_along_yoneda` shows it is unique among functors preserving colimits with this property (up to isomorphism). The first part of [MM92], Chapter I, Section 5, Corollary 4. See Property 1 of <https://ncatlab.org/nlab/show/Yoneda+extension#properties>. -/ def is_extension_along_yoneda : (yoneda : C ⥤ Cᵒᵖ ⥤ Type u₁) ⋙ extend_along_yoneda A ≅ A := nat_iso.of_components (λ X, (colimit.is_colimit _).cocone_point_unique_up_to_iso (colimit_of_diagram_terminal (terminal_op_of_initial (is_initial _)) _)) begin intros X Y f, change (colimit.desc _ ⟨_, _⟩ ≫ colimit.desc _ _) = colimit.desc _ _ ≫ _, apply colimit.hom_ext, intro j, rw [colimit.ι_desc_assoc, colimit.ι_desc_assoc], change (colimit.ι _ _ ≫ 𝟙 _) ≫ colimit.desc _ _ = _, rw [comp_id, colimit.ι_desc], dsimp, rw ← A.map_comp, congr' 1, end /-- See Property 2 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ instance : preserves_colimits (extend_along_yoneda A) := (yoneda_adjunction A).left_adjoint_preserves_colimits /-- Show that the images of `X` after `extend_along_yoneda` and `Lan yoneda` are indeed isomorphic. This follows from `category_theory.category_of_elements.costructured_arrow_yoneda_equivalence`. -/ @[simps] def extend_along_yoneda_iso_Kan_app (X) : (extend_along_yoneda A).obj X ≅ ((Lan yoneda : (_ ⥤ ℰ) ⥤ _).obj A).obj X := let eq := category_of_elements.costructured_arrow_yoneda_equivalence X in { hom := colimit.pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A X) eq.functor, inv := colimit.pre ((category_of_elements.π X).left_op ⋙ A) eq.inverse, hom_inv_id' := begin erw colimit.pre_pre ((category_of_elements.π X).left_op ⋙ A) eq.inverse, transitivity colimit.pre ((category_of_elements.π X).left_op ⋙ A) (𝟭 _), congr, { exact congr_arg functor.op (category_of_elements.from_to_costructured_arrow_eq X) }, { ext, simp only [colimit.ι_pre], erw category.comp_id, congr } end, inv_hom_id' := begin erw colimit.pre_pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A X) eq.functor, transitivity colimit.pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A X) (𝟭 _), congr, { exact category_of_elements.to_from_costructured_arrow_eq X }, { ext, simp only [colimit.ι_pre], erw category.comp_id, congr } end } /-- Verify that `extend_along_yoneda` is indeed the left Kan extension along the yoneda embedding. -/ @[simps] def extend_along_yoneda_iso_Kan : extend_along_yoneda A ≅ (Lan yoneda : (_ ⥤ ℰ) ⥤ _).obj A := nat_iso.of_components (extend_along_yoneda_iso_Kan_app A) begin intros X Y f, simp, rw extend_along_yoneda_map, erw colimit.pre_pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A Y) (costructured_arrow.map f), erw colimit.pre_pre (Lan.diagram (yoneda : C ⥤ _ ⥤ Type u₁) A Y) (category_of_elements.costructured_arrow_yoneda_equivalence Y).functor, congr' 1, apply category_of_elements.costructured_arrow_yoneda_equivalence_naturality, end /-- extending `F ⋙ yoneda` along the yoneda embedding is isomorphic to `Lan F.op`. -/ @[simps] def extend_of_comp_yoneda_iso_Lan {D : Type u₁} [small_category D] (F : C ⥤ D) : extend_along_yoneda (F ⋙ yoneda) ≅ Lan F.op := adjunction.nat_iso_of_right_adjoint_nat_iso (yoneda_adjunction (F ⋙ yoneda)) (Lan.adjunction (Type u₁) F.op) (iso_whisker_right curried_yoneda_lemma' ((whiskering_left Cᵒᵖ Dᵒᵖ (Type u₁)).obj F.op : _)) end colimit_adj open colimit_adj /-- `F ⋙ yoneda` is naturally isomorphic to `yoneda ⋙ Lan F.op`. -/ @[simps] def comp_yoneda_iso_yoneda_comp_Lan {D : Type u₁} [small_category D] (F : C ⥤ D) : F ⋙ yoneda ≅ yoneda ⋙ Lan F.op := (is_extension_along_yoneda (F ⋙ yoneda)).symm ≪≫ iso_whisker_left yoneda (extend_of_comp_yoneda_iso_Lan F) /-- Since `extend_along_yoneda A` is adjoint to `restricted_yoneda A`, if we use `A = yoneda` then `restricted_yoneda A` is isomorphic to the identity, and so `extend_along_yoneda A` is as well. -/ def extend_along_yoneda_yoneda : extend_along_yoneda (yoneda : C ⥤ _) ≅ 𝟭 _ := adjunction.nat_iso_of_right_adjoint_nat_iso (yoneda_adjunction _) adjunction.id restricted_yoneda_yoneda /-- A functor to the presheaf category in which everything in the image is representable (witnessed by the fact that it factors through the yoneda embedding). `cocone_of_representable` gives a cocone for this functor which is a colimit and has point `P`. -/ -- Maybe this should be reducible or an abbreviation? def functor_to_representables (P : Cᵒᵖ ⥤ Type u₁) : (P.elements)ᵒᵖ ⥤ Cᵒᵖ ⥤ Type u₁ := (category_of_elements.π P).left_op ⋙ yoneda /-- This is a cocone with point `P` for the functor `functor_to_representables P`. It is shown in `colimit_of_representable P` that this cocone is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The construction of [MM92], Chapter I, Section 5, Corollary 3. -/ def cocone_of_representable (P : Cᵒᵖ ⥤ Type u₁) : cocone (functor_to_representables P) := cocone.extend (colimit.cocone _) (extend_along_yoneda_yoneda.hom.app P) @[simp] lemma cocone_of_representable_X (P : Cᵒᵖ ⥤ Type u₁) : (cocone_of_representable P).X = P := rfl /-- An explicit formula for the legs of the cocone `cocone_of_representable`. -/ -- Marking this as a simp lemma seems to make things more awkward. lemma cocone_of_representable_ι_app (P : Cᵒᵖ ⥤ Type u₁) (j : (P.elements)ᵒᵖ): (cocone_of_representable P).ι.app j = (yoneda_sections_small _ _).inv j.unop.2 := colimit.ι_desc _ _ /-- The legs of the cocone `cocone_of_representable` are natural in the choice of presheaf. -/ lemma cocone_of_representable_naturality {P₁ P₂ : Cᵒᵖ ⥤ Type u₁} (α : P₁ ⟶ P₂) (j : (P₁.elements)ᵒᵖ) : (cocone_of_representable P₁).ι.app j ≫ α = (cocone_of_representable P₂).ι.app ((category_of_elements.map α).op.obj j) := begin ext T f, simpa [cocone_of_representable_ι_app] using functor_to_types.naturality _ _ α f.op _, end /-- The cocone with point `P` given by `the_cocone` is a colimit: that is, we have exhibited an arbitrary presheaf `P` as a colimit of representables. The result of [MM92], Chapter I, Section 5, Corollary 3. -/ def colimit_of_representable (P : Cᵒᵖ ⥤ Type u₁) : is_colimit (cocone_of_representable P) := begin apply is_colimit.of_point_iso (colimit.is_colimit (functor_to_representables P)), change is_iso (colimit.desc _ (cocone.extend _ _)), rw [colimit.desc_extend, colimit.desc_cocone], apply_instance, end /-- Given two functors L₁ and L₂ which preserve colimits, if they agree when restricted to the representable presheaves then they agree everywhere. -/ def nat_iso_of_nat_iso_on_representables (L₁ L₂ : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) [preserves_colimits L₁] [preserves_colimits L₂] (h : yoneda ⋙ L₁ ≅ yoneda ⋙ L₂) : L₁ ≅ L₂ := begin apply nat_iso.of_components _ _, { intro P, refine (is_colimit_of_preserves L₁ (colimit_of_representable P)).cocone_points_iso_of_nat_iso (is_colimit_of_preserves L₂ (colimit_of_representable P)) _, apply functor.associator _ _ _ ≪≫ _, exact iso_whisker_left (category_of_elements.π P).left_op h }, { intros P₁ P₂ f, apply (is_colimit_of_preserves L₁ (colimit_of_representable P₁)).hom_ext, intro j, dsimp only [id.def, is_colimit.cocone_points_iso_of_nat_iso_hom, iso_whisker_left_hom], have : (L₁.map_cocone (cocone_of_representable P₁)).ι.app j ≫ L₁.map f = (L₁.map_cocone (cocone_of_representable P₂)).ι.app ((category_of_elements.map f).op.obj j), { dsimp, rw [← L₁.map_comp, cocone_of_representable_naturality], refl }, rw [reassoc_of this, is_colimit.ι_map_assoc, is_colimit.ι_map], dsimp, rw [← L₂.map_comp, cocone_of_representable_naturality], refl } end variable [has_colimits ℰ] /-- Show that `extend_along_yoneda` is the unique colimit-preserving functor which extends `A` to the presheaf category. The second part of [MM92], Chapter I, Section 5, Corollary 4. See Property 3 of https://ncatlab.org/nlab/show/Yoneda+extension#properties. -/ def unique_extension_along_yoneda (L : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) (hL : yoneda ⋙ L ≅ A) [preserves_colimits L] : L ≅ extend_along_yoneda A := nat_iso_of_nat_iso_on_representables _ _ (hL ≪≫ (is_extension_along_yoneda _).symm) /-- If `L` preserves colimits and `ℰ` has them, then it is a left adjoint. This is a special case of `is_left_adjoint_of_preserves_colimits` used to prove that. -/ def is_left_adjoint_of_preserves_colimits_aux (L : (Cᵒᵖ ⥤ Type u₁) ⥤ ℰ) [preserves_colimits L] : is_left_adjoint L := { right := restricted_yoneda (yoneda ⋙ L), adj := (yoneda_adjunction _).of_nat_iso_left ((unique_extension_along_yoneda _ L (iso.refl _)).symm) } /-- If `L` preserves colimits and `ℰ` has them, then it is a left adjoint. Note this is a (partial) converse to `left_adjoint_preserves_colimits`. -/ def is_left_adjoint_of_preserves_colimits (L : (C ⥤ Type u₁) ⥤ ℰ) [preserves_colimits L] : is_left_adjoint L := let e : (_ ⥤ Type u₁) ≌ (_ ⥤ Type u₁) := (op_op_equivalence C).congr_left, t := is_left_adjoint_of_preserves_colimits_aux (e.functor ⋙ L : _) in by exactI adjunction.left_adjoint_of_nat_iso (e.inv_fun_id_assoc _) end category_theory
7db03ad94d94ac812e97620328db87ce6b47d0be
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/category_theory/concrete_category/bundled_hom.lean
82130073462e72aa8888346977a60d7d117d248e
[ "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
5,581
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Yury Kudryashov -/ import category_theory.concrete_category.basic import category_theory.concrete_category.bundled /-! # Category instances for algebraic structures that use bundled homs. Many algebraic structures in Lean initially used unbundled homs (e.g. a bare function between types, along with an `is_monoid_hom` typeclass), but the general trend is towards using bundled homs. This file provides a basic infrastructure to define concrete categories using bundled homs, and define forgetful functors between them. -/ universes u namespace category_theory variables {c : Type u → Type u} (hom : Π ⦃α β : Type u⦄ (Iα : c α) (Iβ : c β), Type u) /-- Class for bundled homs. Note that the arguments order follows that of lemmas for `monoid_hom`. This way we can use `⟨@monoid_hom.to_fun, @monoid_hom.id ...⟩` in an instance. -/ structure bundled_hom := (to_fun : Π {α β : Type u} (Iα : c α) (Iβ : c β), hom Iα Iβ → α → β) (id : Π {α : Type u} (I : c α), hom I I) (comp : Π {α β γ : Type u} (Iα : c α) (Iβ : c β) (Iγ : c γ), hom Iβ Iγ → hom Iα Iβ → hom Iα Iγ) (hom_ext : ∀ {α β : Type u} (Iα : c α) (Iβ : c β), function.injective (to_fun Iα Iβ) . obviously) (id_to_fun : ∀ {α : Type u} (I : c α), to_fun I I (id I) = _root_.id . obviously) (comp_to_fun : ∀ {α β γ : Type u} (Iα : c α) (Iβ : c β) (Iγ : c γ) (f : hom Iα Iβ) (g : hom Iβ Iγ), to_fun Iα Iγ (comp Iα Iβ Iγ g f) = (to_fun Iβ Iγ g) ∘ (to_fun Iα Iβ f) . obviously) attribute [class] bundled_hom attribute [simp] bundled_hom.id_to_fun bundled_hom.comp_to_fun namespace bundled_hom variable [𝒞 : bundled_hom hom] include 𝒞 /-- Every `@bundled_hom c _` defines a category with objects in `bundled c`. This instance generates the type-class problem `bundled_hom ?m` (which is why this is marked as `[nolint]`). Currently that is not a problem, as there are almost no instances of `bundled_hom`. -/ @[nolint dangerous_instance] instance category : category (bundled c) := by refine { hom := λ X Y, @hom X Y X.str Y.str, id := λ X, @bundled_hom.id c hom 𝒞 X X.str, comp := λ X Y Z f g, @bundled_hom.comp c hom 𝒞 X Y Z X.str Y.str Z.str g f, comp_id' := _, id_comp' := _, assoc' := _}; intros; apply 𝒞.hom_ext; simp only [𝒞.id_to_fun, 𝒞.comp_to_fun, function.left_id, function.right_id] /-- A category given by `bundled_hom` is a concrete category. This instance generates the type-class problem `bundled_hom ?m` (which is why this is marked as `[nolint]`). Currently that is not a problem, as there are almost no instances of `bundled_hom`. -/ @[nolint dangerous_instance] instance : concrete_category (bundled c) := { forget := { obj := λ X, X, map := λ X Y f, 𝒞.to_fun X.str Y.str f, map_id' := λ X, 𝒞.id_to_fun X.str, map_comp' := by intros; erw 𝒞.comp_to_fun; refl }, forget_faithful := { map_injective' := by intros; apply 𝒞.hom_ext } } variables {hom} local attribute [instance] concrete_category.has_coe_to_fun /-- A version of `has_forget₂.mk'` for categories defined using `@bundled_hom`. -/ def mk_has_forget₂ {d : Type u → Type u} {hom_d : Π ⦃α β : Type u⦄ (Iα : d α) (Iβ : d β), Type u} [bundled_hom hom_d] (obj : Π ⦃α⦄, c α → d α) (map : Π {X Y : bundled c}, (X ⟶ Y) → ((bundled.map obj X) ⟶ (bundled.map obj Y))) (h_map : ∀ {X Y : bundled c} (f : X ⟶ Y), (map f : X → Y) = f) : has_forget₂ (bundled c) (bundled d) := has_forget₂.mk' (bundled.map @obj) (λ _, rfl) @map (by intros; apply heq_of_eq; apply h_map) variables {d : Type u → Type u} variables (hom) section omit 𝒞 /-- The `hom` corresponding to first forgetting along `F`, then taking the `hom` associated to `c`. For typical usage, see the construction of `CommMon` from `Mon`. -/ @[reducible] def map_hom (F : Π {α}, d α → c α) : Π ⦃α β : Type u⦄ (Iα : d α) (Iβ : d β), Type u := λ α β iα iβ, hom (F iα) (F iβ) end /-- Construct the `bundled_hom` induced by a map between type classes. This is useful for building categories such as `CommMon` from `Mon`. -/ def map (F : Π {α}, d α → c α) : bundled_hom (map_hom hom @F) := { to_fun := λ α β iα iβ f, 𝒞.to_fun (F iα) (F iβ) f, id := λ α iα, 𝒞.id (F iα), comp := λ α β γ iα iβ iγ f g, 𝒞.comp (F iα) (F iβ) (F iγ) f g, hom_ext := λ α β iα iβ f g h, 𝒞.hom_ext (F iα) (F iβ) h } section omit 𝒞 /-- We use the empty `parent_projection` class to label functions like `comm_monoid.to_monoid`, which we would like to use to automatically construct `bundled_hom` instances from. Once we've set up `Mon` as the category of bundled monoids, this allows us to set up `CommMon` by defining an instance ```instance : parent_projection (comm_monoid.to_monoid) := ⟨⟩``` -/ class parent_projection (F : Π {α}, d α → c α) end @[nolint unused_arguments] -- The `parent_projection` typeclass is just a marker, so won't be used. instance bundled_hom_of_parent_projection (F : Π {α}, d α → c α) [parent_projection @F] : bundled_hom (map_hom hom @F) := map hom @F instance forget₂ (F : Π {α}, d α → c α) [parent_projection @F] : has_forget₂ (bundled d) (bundled c) := { forget₂ := { obj := λ X, ⟨X, F X.2⟩, map := λ X Y f, f } } end bundled_hom end category_theory
df2f0e0368e335d2b11659e5bd90271b46949841
f7315930643edc12e76c229a742d5446dad77097
/tests/lean/run/tactic5.lean
268cdc81e770a365154123225fba21fbcad89288
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
186
lean
import logic open tactic (renaming id->id_tac) definition id {A : Type} (a : A) := a theorem tst {A B : Prop} (H1 : A) (H2 : B) : id A := by !(unfold id; state); assumption check tst
2ac3127eba97c1eb4096fea80e60665d86f8ccdf
e61a235b8468b03aee0120bf26ec615c045005d2
/tests/lean/run/termElab.lean
1901a93a5cfe68daa0928f8aeb74b8aff7a6ca1a
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
687
lean
import Init.Lean open Lean open Lean.Elab open Lean.Elab.Term set_option trace.Elab.debug true def tst1 : TermElabM Unit := do opt ← getOptions; stx ← `(forall (a b : Nat), Nat); dbgTrace "message 1"; -- This message goes direct to stdio. It will be displayed before trace messages. e ← elabTermAndSynthesize stx none; logDbgTrace (">>> " ++ e); -- display message when `trace.Elab.debug` is true dbgTrace "message 2" #eval tst1 def tst2 : TermElabM Unit := do opt ← getOptions; let a := mkTermId `a; let b := mkTermId `b; stx ← `((fun ($a : Type) (x : $a) => @id $a x) _ 1); e ← elabTermAndSynthesize stx none; logDbgTrace (">>> " ++ e); throwErrorIfErrors #eval tst2
d64a947bf55fba0a2dcf9c3edbe2eea6bc515d14
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/simp21.lean
495221b86d3c162b85f383829a682244503d00a2
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
257
lean
variable vec : Nat → Type rewrite_set simple add_rewrite Nat::add_assoc Nat::add_zeror eq_id : simple variable n : Nat (* local t = parse_lean([[ vec n = vec (n + 0) ]]) print(t) print("===>") local t2, pr = simplify(t, "simple") print(t2) print(pr) *)
f729fc80880973a7fc98395bbf6608b6be355e62
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Meta/DiscrTree.lean
f000aff5544ad7d5287d3464db5130f4eebf8200
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
18,237
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.Basic import Lean.Meta.FunInfo import Lean.Meta.InferType namespace Lean.Meta.DiscrTree /- (Imperfect) discrimination trees. We use a hybrid representation. - A `PersistentHashMap` for the root node which usually contains many children. - A sorted array of key/node pairs for inner nodes. The edges are labeled by keys: - Constant names (and arity). Universe levels are ignored. - Free variables (and arity). Thus, an entry in the discrimination tree may reference hypotheses from the local context. - Literals - Star/Wildcard. We use them to represent metavariables and terms we want to ignore. We ignore implicit arguments and proofs. - Other. We use to represent other kinds of terms (e.g., nested lambda, forall, sort, etc). We reduce terms using `TransparencyMode.reducible`. Thus, all reducible definitions in an expression `e` are unfolded before we insert it into the discrimination tree. Recall that projections from classes are **NOT** reducible. For example, the expressions `Add.add α (ringAdd ?α ?s) ?x ?x` and `Add.add Nat Nat.hasAdd a b` generates paths with the following keys respctively ``` ⟨Add.add, 4⟩, *, *, *, * ⟨Add.add, 4⟩, *, *, ⟨a,0⟩, ⟨b,0⟩ ``` That is, we don't reduce `Add.add Nat inst a b` into `Nat.add a b`. We say the `Add.add` applications are the de-facto canonical forms in the metaprogramming framework. Moreover, it is the metaprogrammer's responsibility to re-pack applications such as `Nat.add a b` into `Add.add Nat inst a b`. Remark: we store the arity in the keys 1- To be able to implement the "skip" operation when retrieving "candidate" unifiers. 2- Distinguish partial applications `f a`, `f a b`, and `f a b c`. -/ def Key.ctorIdx : Key → Nat | Key.star => 0 | Key.other => 1 | Key.lit _ => 2 | Key.fvar _ _ => 3 | Key.const _ _ => 4 | Key.arrow => 5 def Key.lt : Key → Key → Bool | Key.lit v₁, Key.lit v₂ => v₁ < v₂ | Key.fvar n₁ a₁, Key.fvar n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | Key.const n₁ a₁, Key.const n₂ a₂ => Name.quickLt n₁ n₂ || (n₁ == n₂ && a₁ < a₂) | k₁, k₂ => k₁.ctorIdx < k₂.ctorIdx instance : HasLess Key := ⟨fun a b => Key.lt a b⟩ instance (a b : Key) : Decidable (a < b) := inferInstanceAs (Decidable (Key.lt a b)) def Key.format : Key → Format | Key.star => "*" | Key.other => "◾" | Key.lit (Literal.natVal v) => fmt v | Key.lit (Literal.strVal v) => repr v | Key.const k _ => fmt k | Key.fvar k _ => fmt k | Key.arrow => "→" instance : ToFormat Key := ⟨Key.format⟩ def Key.arity : Key → Nat | Key.const _ a => a | Key.fvar _ a => a | Key.arrow => 2 | _ => 0 instance : Inhabited (Trie α) := ⟨Trie.node #[] #[]⟩ def empty : DiscrTree α := { root := {} } partial def Trie.format [ToFormat α] : Trie α → Format | Trie.node vs cs => Format.group $ Format.paren $ "node" ++ (if vs.isEmpty then Format.nil else " " ++ fmt vs) ++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (fmt k ++ " => " ++ format c)) instance [ToFormat α] : ToFormat (Trie α) := ⟨Trie.format⟩ partial def format [ToFormat α] (d : DiscrTree α) : Format := let (_, r) := d.root.foldl (fun (p : Bool × Format) k c => (false, p.2 ++ (if p.1 then Format.nil else Format.line) ++ Format.paren (fmt k ++ " => " ++ fmt c))) (true, Format.nil) Format.group r instance [ToFormat α] : ToFormat (DiscrTree α) := ⟨format⟩ /- The discrimination tree ignores implicit arguments and proofs. We use the following auxiliary id as a "mark". -/ private def tmpMVarId : MVarId := `_discr_tree_tmp private def tmpStar := mkMVar tmpMVarId instance : Inhabited (DiscrTree α) where default := {} /-- Return true iff the argument should be treated as a "wildcard" by the discrimination tree. - We ignore proofs because of proof irrelevance. It doesn't make sense to try to index their structure. - We ignore instance implicit arguments (e.g., `[Add α]`) because they are "morally" canonical. Moreover, we may have many definitionally equal terms floating around. Example: `Ring.hasAdd Int Int.isRing` and `Int.hasAdd`. - We considered ignoring implicit arguments (e.g., `{α : Type}`) since users don't "see" them, and may not even understand why some simplification rule is not firing. However, in type class resolution, we have instance such as `Decidable (@Eq Nat x y)`, where `Nat` is an implicit argument. Thus, we would add the path ``` Decidable -> Eq -> * -> * -> * -> [Nat.decEq] ``` to the discrimination tree IF we ignored the implict `Nat` argument. This would be BAD since **ALL** decidable equality instances would be in the same path. So, we index implicit arguments if they are types. This setting seems sensible for simplification lemmas such as: ``` forall (x y : Unit), (@Eq Unit x y) = true ``` If we ignore the implicit argument `Unit`, the `DiscrTree` will say it is a candidate simplification lemma for any equality in our goal. Remark: if users have problems with the solution above, we may provide a `noIndexing` annotation, and `ignoreArg` would return true for any term of the form `noIndexing t`. -/ private def ignoreArg (a : Expr) (i : Nat) (infos : Array ParamInfo) : MetaM Bool := do if h : i < infos.size then let info := infos.get ⟨i, h⟩ if info.instImplicit then return true else if info.implicit then return not (← isType a) else isProof a else isProof a private partial def pushArgsAux (infos : Array ParamInfo) : Nat → Expr → Array Expr → MetaM (Array Expr) | i, Expr.app f a _, todo => do if (← ignoreArg a i infos) then pushArgsAux infos (i-1) f (todo.push tmpStar) else pushArgsAux infos (i-1) f (todo.push a) | _, _, todo => return todo private partial def whnfEta (e : Expr) : MetaM Expr := do let e ← whnf e match e.etaExpandedStrict? with | some e => whnfEta e | none => return e /-- Return true if `e` is one of the following - A nat literal (numeral) - `Nat.zero` - `Nat.succ x` where `isNumeral x` - `OfNat.ofNat _ x _` where `isNumeral x` -/ private partial def isNumeral (e : Expr) : Bool := if e.isNatLit then true else let f := e.getAppFn if !f.isConst then false else let fName := f.constName! if fName == ``Nat.succ && e.getAppNumArgs == 1 then isNumeral e.appArg! else if fName == ``OfNat.ofNat && e.getAppNumArgs == 3 then isNumeral (e.getArg! 1) else if fName == ``Nat.zero && e.getAppNumArgs == 0 then true else false private def isNatType (e : Expr) : MetaM Bool := return (← whnf e).isConstOf ``Nat /-- Return true if `e` is one of the following - `Nat.add _ k` where `isNumeral k` - `Add.add Nat _ _ k` where `isNumeral k` - `HAdd.hAdd _ Nat _ _ k` where `isNumeral k` - `Nat.succ _` This function assumes `e.isAppOf fName` -/ private def isOffset (fName : Name) (e : Expr) : MetaM Bool := do if fName == ``Nat.add && e.getAppNumArgs == 2 then return isNumeral e.appArg! else if fName == ``Add.add && e.getAppNumArgs == 4 then if (← isNatType (e.getArg! 0)) then return isNumeral e.appArg! else return false else if fName == ``HAdd.hAdd && e.getAppNumArgs == 6 then if (← isNatType (e.getArg! 1)) then return isNumeral e.appArg! else return false else return fName == ``Nat.succ && e.getAppNumArgs == 1 /- TODO: add hook for users adding their own functions for controlling `shouldAddAsStar` Different `DiscrTree` users may populate this set using, for example, attributes. Remark: we currently tag `Nat.zero` and "offset" terms to avoid having to add special support for `Expr.lit` and offset terms. Example, suppose the discrimination tree contains the entry `Nat.succ ?m |-> v`, and we are trying to retrieve the matches for `Expr.lit (Literal.natVal 1) _`. In this scenario, we want to retrieve `Nat.succ ?m |-> v` -/ private def shouldAddAsStar (fName : Name) (e : Expr) : MetaM Bool := do if fName == `Nat.zero then return true else isOffset fName e def mkNoindexAnnotation (e : Expr) : Expr := mkAnnotation `noindex e def hasNoindexAnnotation (e : Expr) : Bool := annotation? `noindex e |>.isSome /- Remark: we use `shouldAddAsStar` only for nested terms, and `root == false` for nested terms -/ private def pushArgs (root : Bool) (todo : Array Expr) (e : Expr) : MetaM (Key × Array Expr) := do if hasNoindexAnnotation e then return (Key.star, todo) else let e ← whnfEta e let fn := e.getAppFn let push (k : Key) (nargs : Nat) : MetaM (Key × Array Expr) := do let info ← getFunInfoNArgs fn nargs let todo ← pushArgsAux info.paramInfo (nargs-1) e todo return (k, todo) match fn with | Expr.lit v _ => return (Key.lit v, todo) | Expr.const c _ _ => unless root do if (← shouldAddAsStar c e) then return (Key.star, todo) let nargs := e.getAppNumArgs push (Key.const c nargs) nargs | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs push (Key.fvar fvarId nargs) nargs | Expr.mvar mvarId _ => if mvarId == tmpMVarId then -- We use `tmp to mark implicit arguments and proofs return (Key.star, todo) else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then return (Key.other, todo) else return (Key.star, todo) | Expr.forallE _ d b _ => if b.hasLooseBVars then return (Key.other, todo) else return (Key.arrow, todo.push d |>.push b) | _ => return (Key.other, todo) partial def mkPathAux (root : Bool) (todo : Array Expr) (keys : Array Key) : MetaM (Array Key) := do if todo.isEmpty then return keys else let e := todo.back let todo := todo.pop let (k, todo) ← pushArgs root todo e mkPathAux false todo (keys.push k) private def initCapacity := 8 def mkPath (e : Expr) : MetaM (Array Key) := do withReducible do let todo : Array Expr := Array.mkEmpty initCapacity let keys : Array Key := Array.mkEmpty initCapacity mkPathAux (root := true) (todo.push e) keys private partial def createNodes (keys : Array Key) (v : α) (i : Nat) : Trie α := if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := createNodes keys v (i+1) Trie.node #[] #[(k, c)] else Trie.node #[v] #[] private def insertVal [BEq α] (vs : Array α) (v : α) : Array α := if vs.contains v then vs else vs.push v private partial def insertAux [BEq α] (keys : Array Key) (v : α) : Nat → Trie α → Trie α | i, Trie.node vs cs => if h : i < keys.size then let k := keys.get ⟨i, h⟩ let c := Id.run $ cs.binInsertM (fun a b => a.1 < b.1) (fun ⟨_, s⟩ => let c := insertAux keys v (i+1) s; (k, c)) -- merge with existing (fun _ => let c := createNodes keys v (i+1); (k, c)) (k, arbitrary) Trie.node vs c else Trie.node (insertVal vs v) cs def insertCore [BEq α] (d : DiscrTree α) (keys : Array Key) (v : α) : DiscrTree α := if keys.isEmpty then panic! "invalid key sequence" else let k := keys[0] match d.root.find? k with | none => let c := createNodes keys v 1 { root := d.root.insert k c } | some c => let c := insertAux keys v 1 c { root := d.root.insert k c } def insert [BEq α] (d : DiscrTree α) (e : Expr) (v : α) : MetaM (DiscrTree α) := do let keys ← mkPath e return d.insertCore keys v private def getKeyArgs (e : Expr) (isMatch : Bool) : MetaM (Key × Array Expr) := do let e ← whnfEta e match e.getAppFn with | Expr.lit v _ => return (Key.lit v, #[]) | Expr.const c _ _ => let nargs := e.getAppNumArgs return (Key.const c nargs, e.getAppRevArgs) | Expr.fvar fvarId _ => let nargs := e.getAppNumArgs return (Key.fvar fvarId nargs, e.getAppRevArgs) | Expr.mvar mvarId _ => if isMatch then return (Key.other, #[]) else do let ctx ← read if ctx.config.isDefEqStuckEx then /- When the configuration flag `isDefEqStuckEx` is set to true, we want `isDefEq` to throw an exception whenever it tries to assign a read-only metavariable. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. The method `DiscrTree.getUnify e` returns candidates `c` that may "unify" with `e`. That is, `isDefEq c e` may return true. Now, consider `DiscrTree.getUnify d (Add ?m)` where `?m` is a read-only metavariable, and the discrimination tree contains the keys `HadAdd Nat` and `Add Int`. If `isDefEqStuckEx` is set to true, we must treat `?m` as a regular metavariable here, otherwise we return the empty set of candidates. This is incorrect because it is equivalent to saying that there is no solution even if the caller assigns `?m` and try again. -/ return (Key.star, #[]) else if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then return (Key.other, #[]) else return (Key.star, #[]) | Expr.forallE _ d b _ => if b.hasLooseBVars then return (Key.other, #[]) else return (Key.arrow, #[d, b]) | _ => return (Key.other, #[]) private abbrev getMatchKeyArgs (e : Expr) : MetaM (Key × Array Expr) := getKeyArgs e (isMatch := true) private abbrev getUnifyKeyArgs (e : Expr) : MetaM (Key × Array Expr) := getKeyArgs e (isMatch := false) private def getStarResult (d : DiscrTree α) : Array α := let result : Array α := Array.mkEmpty initCapacity match d.root.find? Key.star with | none => result | some (Trie.node vs _) => result ++ vs private abbrev findKey (cs : Array (Key × Trie α)) (k : Key) : Option (Key × Trie α) := cs.binSearch (k, arbitrary) (fun a b => a.1 < b.1) partial def getMatch (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withReducible do let result := getStarResult d let (k, args) ← getMatchKeyArgs e match k with | Key.star => return result | _ => match d.root.find? k with | none => return result | some c => process args c result where process (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do match c with | Trie.node vs cs => if todo.isEmpty then return result ++ vs else if cs.isEmpty then return result else let e := todo.back let todo := todo.pop let first := cs[0] /- Recall that `Key.star` is the minimal key -/ let (k, args) ← getMatchKeyArgs e /- We must always visit `Key.star` edges since they are wildcards. Thus, `todo` is not used linearly when there is `Key.star` edge and there is an edge for `k` and `k != Key.star`. -/ let visitStar (result : Array α) : MetaM (Array α) := if first.1 == Key.star then process todo first.2 result else return result let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) := match findKey cs k with | none => result | some c => process (todo ++ args) c.2 result let result ← visitStar result match k with | Key.star => result /- Recall that dependent arrows are `(Key.other, #[])`, and non-dependent arrows are `(Key.arrow, #[a, b])`. A non-dependent arrow may be an instance of a dependent arrow (stored at `DiscrTree`). Thus, we also visit the `Key.other` child. -/ | Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args result) | _ => visitNonStar k args result partial def getUnify (d : DiscrTree α) (e : Expr) : MetaM (Array α) := withReducible do let (k, args) ← getUnifyKeyArgs e match k with | Key.star => d.root.foldlM (init := #[]) fun result k c => process k.arity #[] c result | _ => let result := getStarResult d match d.root.find? k with | none => return result | some c => process 0 args c result where process (skip : Nat) (todo : Array Expr) (c : Trie α) (result : Array α) : MetaM (Array α) := do match skip, c with | skip+1, Trie.node vs cs => if cs.isEmpty then return result else cs.foldlM (init := result) fun result ⟨k, c⟩ => process (skip + k.arity) todo c result | 0, Trie.node vs cs => do if todo.isEmpty then return result ++ vs else if cs.isEmpty then return result else let e := todo.back let todo := todo.pop let (k, args) ← getUnifyKeyArgs e let visitStar (result : Array α) : MetaM (Array α) := let first := cs[0] if first.1 == Key.star then process 0 todo first.2 result else return result let visitNonStar (k : Key) (args : Array Expr) (result : Array α) : MetaM (Array α) := match findKey cs k with | none => result | some c => process 0 (todo ++ args) c.2 result match k with | Key.star => cs.foldlM (init := result) fun result ⟨k, c⟩ => process k.arity todo c result -- See comment a `getMatch` regarding non-dependent arrows vs dependent arrows | Key.arrow => visitNonStar Key.other #[] (← visitNonStar k args (← visitStar result)) | _ => visitNonStar k args (← visitStar result) end Lean.Meta.DiscrTree
57e6194e87671df00dd5143bf5ddb6747b1c5b58
947b78d97130d56365ae2ec264df196ce769371a
/src/Init/Control/Reader.lean
8690305af56a2a24f556baeef9cf3dd6b5e6e37f
[ "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
7,071
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich The Reader monad transformer for passing immutable State. -/ prelude import Init.Control.MonadControl import Init.Control.Id import Init.Control.Alternative import Init.Control.Except universes u v w /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance ReaderT.inhabited (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) := ⟨fun _ => arbitrary _⟩ @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r @[reducible] def Reader (ρ : Type u) := ReaderT ρ id namespace ReaderT section variables {ρ : Type u} {m : Type u → Type v} {α : Type u} @[inline] protected def lift (a : m α) : ReaderT ρ m α := fun r => a instance : MonadLift m (ReaderT ρ m) := ⟨@ReaderT.lift ρ m⟩ instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) := { throw := fun α => ReaderT.lift ∘ throwThe ε, catch := fun α x c r => catchThe ε (x r) (fun e => (c e) r) } @[inline] protected def orelse [Alternative m] {α : Type u} (x₁ x₂ : ReaderT ρ m α) : ReaderT ρ m α := fun s => x₁ s <|> x₂ s @[inline] protected def failure [Alternative m] {α : Type u} : ReaderT ρ m α := fun s => failure end section variables {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => do a ← x r; f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => f <$> x r instance : Monad (ReaderT ρ m) := { pure := @ReaderT.pure _ _ _, bind := @ReaderT.bind _ _ _, map := @ReaderT.map _ _ _ } instance (ρ m m') [Monad m] [Monad m'] : MonadFunctor m m' (ReaderT ρ m) (ReaderT ρ m') := ⟨fun _ f x r => f (x r)⟩ @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) instance [Alternative m] : Alternative (ReaderT ρ m) := { ReaderT.Monad with failure := @ReaderT.failure _ _ _, orelse := @ReaderT.orelse _ _ _ } end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) := (lift {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ReaderT ρ m α) → n α) ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) := (read : m ρ) @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) := (read : m ρ) export MonadReader (read) instance MonadReaderOf.isMonadReader (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m := ⟨readThe ρ⟩ instance monadReaderTrans {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadReaderOf ρ m] [MonadLift m n] : MonadReaderOf ρ n := ⟨monadLift (MonadReader.read : m ρ)⟩ instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) := ⟨ReaderT.read⟩ /-- Adapt a Monad stack, changing the Type of its top-most environment. This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify), but does not use lenses (why would it), and is derived automatically for any transformer implementing `MonadFunctor`. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReaderFunctor (ρ ρ' : outParam (Type u)) (n n' : Type u → Type u) := (map {α : Type u} : (∀ {m : Type u → Type u} [Monad m], ReaderT ρ m α → ReaderT ρ' m α) → n α → n' α) ``` -/ class MonadReaderAdapterOf (ρ : outParam (Type u)) (ρ' : Type u) (m m' : Type u → Type v) := (adaptReader {α : Type u} : (ρ' → ρ) → m α → m' α) @[inline] def adaptTheReader {ρ : Type u} (ρ' : Type u) {m m' : Type u → Type v} [MonadReaderAdapterOf ρ ρ' m m'] {α} : (ρ' → ρ) → m α → m' α := MonadReaderAdapterOf.adaptReader /-- Similar to `MonadReaderAdapterOf`, but `ρ'` is an `outParam` for convenience -/ class MonadReaderAdapter (ρ ρ' : outParam (Type u)) (m m' : Type u → Type v) := (adaptReader {α : Type u} : (ρ' → ρ) → m α → m' α) export MonadReaderAdapter (adaptReader) instance MonadReaderAdapterOf.isMonadReaderAdapter (ρ ρ' : Type u) (m m' : Type u → Type v) [MonadReaderAdapterOf ρ ρ' m m'] : MonadReaderAdapter ρ ρ' m m' := ⟨fun α => adaptTheReader ρ'⟩ section variables {ρ ρ' : Type u} {m m' : Type u → Type v} instance monadReaderAdapterTrans {n n' : Type u → Type v} [MonadReaderAdapterOf ρ ρ' m m'] [MonadFunctor m m' n n'] : MonadReaderAdapterOf ρ ρ' n n' := ⟨fun α f => monadMap (fun α => (adaptReader f : m α → m' α))⟩ instance [Monad m] : MonadReaderAdapterOf ρ ρ' (ReaderT ρ m) (ReaderT ρ' m) := ⟨fun α => ReaderT.adapt⟩ end instance (ρ : Type u) (m out) [MonadRun out m] : MonadRun (fun α => ρ → out α) (ReaderT ρ m) := ⟨fun α x => run ∘ x⟩ class MonadReaderRunner (ρ : Type u) (m m' : Type u → Type u) := (runReader {α : Type u} : m α → ρ → m' α) export MonadReaderRunner (runReader) section variables {ρ ρ' : Type u} {m m' : Type u → Type u} instance monadReaderRunnerTrans {n n' : Type u → Type u} [MonadReaderRunner ρ m m'] [MonadFunctor m m' n n'] : MonadReaderRunner ρ n n' := ⟨fun α x r => monadMap (fun (α) (y : m α) => (runReader y r : m' α)) x⟩ instance ReaderT.MonadStateRunner [Monad m] : MonadReaderRunner ρ (ReaderT ρ m) m := ⟨fun α x r => x r⟩ end instance ReaderT.monadControl (ρ : Type u) (m : Type u → Type v) : MonadControl m (ReaderT ρ m) := { stM := fun α => α, liftWith := fun α f ctx => f fun β x => x ctx, restoreM := fun α x ctx => x, } instance ReaderT.finally {m : Type u → Type v} {ρ : Type u} [MonadFinally m] [Monad m] : MonadFinally (ReaderT ρ m) := { finally' := fun α β x h ctx => finally' (x ctx) (fun a? => h a? ctx) }
058ef31ce7d1b365de4dbc249d88eb80c97c148f
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/quadratic_discriminant.lean
096cf464351051640dcc04190e1b9fe33e1c3408
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,785
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 algebra.char_p.invertible import order.filter.at_top_bot import tactic.linarith /-! # Quadratic discriminants and roots of a quadratic This file defines the discriminant of a quadratic and gives the solution to a quadratic equation. ## Main definition - `discrim a b c`: the discriminant of a quadratic `a * x * x + b * x + c` is `b * b - 4 * a * c`. ## Main statements - `quadratic_eq_zero_iff`: roots of a quadratic can be written as `(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is a square root of the discriminant. - `quadratic_ne_zero_of_discrim_ne_square`: if the discriminant has no square root, then the corresponding quadratic has no root. - `discrim_le_zero`: if a quadratic is always non-negative, then its discriminant is non-positive. ## Tags polynomial, quadratic, discriminant, root -/ open filter section ring variables {R : Type*} /-- Discriminant of a quadratic -/ def discrim [ring R] (a b c : R) : R := b^2 - 4 * a * c variables [integral_domain R] {a b c : R} /-- A quadratic has roots if and only if its discriminant equals some square. -/ lemma quadratic_eq_zero_iff_discrim_eq_square (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (x : R) : a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b) ^ 2 := begin split, { assume h, calc discrim a b c = 4 * a * (a * x * x + b * x + c) + b * b - 4 * a * c : by { rw [h, discrim], ring } ... = (2*a*x + b)^2 : by ring }, { assume h, have ha : 2 * 2 * a ≠ 0 := mul_ne_zero (mul_ne_zero h2 h2) ha, apply mul_left_cancel' ha, calc 2 * 2 * a * (a * x * x + b * x + c) = (2 * a * x + b) ^ 2 - (b ^ 2 - 4 * a * c) : by ring ... = 0 : by { rw [← h, discrim], ring } ... = 2*2*a*0 : by ring } end /-- A quadratic has no root if its discriminant has no square root. -/ lemma quadratic_ne_zero_of_discrim_ne_square (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (h : ∀ s : R, discrim a b c ≠ s * s) (x : R) : a * x * x + b * x + c ≠ 0 := begin assume h', rw [quadratic_eq_zero_iff_discrim_eq_square h2 ha, pow_two] at h', exact h _ h' end end ring section field variables {K : Type*} [field K] [invertible (2 : K)] {a b c x : K} /-- Roots of a quadratic -/ lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : K} (h : discrim a b c = s * s) (x : K) : a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := begin have h2 : (2 : K) ≠ 0 := nonzero_of_invertible 2, rw [quadratic_eq_zero_iff_discrim_eq_square h2 ha, h, pow_two, mul_self_eq_mul_self_iff], have ne : 2 * a ≠ 0 := mul_ne_zero h2 ha, have : x = 2 * a * x / (2 * a) := (mul_div_cancel_left x ne).symm, have h₁ : 2 * a * ((-b + s) / (2 * a)) = -b + s := mul_div_cancel' _ ne, have h₂ : 2 * a * ((-b - s) / (2 * a)) = -b - s := mul_div_cancel' _ ne, split, { intro h', rcases h', { left, rw h', simpa [add_comm] }, { right, rw h', simpa [add_comm, sub_eq_add_neg] } }, { intro h', rcases h', { left, rw [h', h₁], ring }, { right, rw [h', h₂], ring } } end /-- A quadratic has roots if its discriminant has square roots -/ lemma exists_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) : ∃ x, a * x * x + b * x + c = 0 := begin rcases h with ⟨s, hs⟩, use (-b + s) / (2 * a), rw quadratic_eq_zero_iff ha hs, simp end /-- Root of a quadratic when its discriminant equals zero -/ lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) (x : K) : a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) := begin have : discrim a b c = 0 * 0, by rw [h, mul_zero], rw [quadratic_eq_zero_iff ha this, add_zero, sub_zero, or_self] end end field section linear_ordered_field variables {K : Type*} [linear_ordered_field K] {a b c : K} /-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/ lemma discrim_le_zero (h : ∀ x : K, 0 ≤ a * x * x + b * x + c) : discrim a b c ≤ 0 := begin rw [discrim, pow_two], obtain ha|rfl|ha : a < 0 ∨ a = 0 ∨ 0 < a := lt_trichotomy a 0, -- if a < 0 { have : tendsto (λ x, (a * x + b) * x + c) at_top at_bot := tendsto_at_bot_add_const_right _ c ((tendsto_at_bot_add_const_right _ b (tendsto_id.neg_const_mul_at_top ha)).at_bot_mul_at_top tendsto_id), rcases (this.eventually (eventually_lt_at_bot 0)).exists with ⟨x, hx⟩, exact false.elim ((h x).not_lt $ by rwa ← add_mul) }, -- if a = 0 { rcases em (b = 0) with (rfl|hb), { simp }, { have := h ((-c - 1) / b), rw [mul_div_cancel' _ hb] at this, linarith } }, -- if a > 0 { have := calc 4 * a * (a * (-(b / a) * (1 / 2)) * (-(b / a) * (1 / 2)) + b * (-(b / a) * (1 / 2)) + c) = (a * (b / a)) * (a * (b / a)) - 2 * (a * (b / a)) * b + 4 * a * c : by ring ... = -(b * b - 4 * a * c) : by { simp only [mul_div_cancel' b (ne_of_gt ha)], ring }, have ha' : 0 ≤ 4 * a, by linarith, have h := (mul_nonneg ha' (h (-(b / a) * (1 / 2)))), rw this at h, rwa ← neg_nonneg } end /-- If a polynomial of degree 2 is always positive, then its discriminant is negative, at least when the coefficient of the quadratic term is nonzero. -/ lemma discrim_lt_zero (ha : a ≠ 0) (h : ∀ x : K, 0 < a * x * x + b * x + c) : discrim a b c < 0 := begin have : ∀ x : K, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x), refine lt_of_le_of_ne (discrim_le_zero this) _, assume h', have := h (-b / (2 * a)), have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0, { rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] }, linarith end end linear_ordered_field
8a64843b272ff389d189b313bc465ccf2001d9fb
b147e1312077cdcfea8e6756207b3fa538982e12
/data/list/basic.lean
894b1ce7df5b7940a2bcfff5417592094ec38055
[ "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
153,451
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Basic properties of lists. -/ import tactic.interactive tactic.mk_iff_of_inductive_prop tactic.split_ifs logic.basic logic.function logic.relation algebra.group order.basic data.nat.basic data.option data.bool data.prod data.sigma data.fin open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} @[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → h₁ = h₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq) theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} : (h₁::t₁) = (h₂::t₂) → t₁ = t₂ := assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe @[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /- mem -/ theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil | [] := assume h, rfl | (b :: l') := assume h, absurd (mem_cons_self b l') (h b) theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _ theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b := assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, this) (assume : a ∈ [], absurd this (not_mem_nil a)) @[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b := ⟨eq_of_mem_singleton, by intro h; simp [h]⟩ theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l := assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl) (assume : a = b, begin subst a, exact binl end) (assume : a ∈ l, this) theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t := mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩ theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] := by intro e; rw e at h; cases h theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] := ⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩ theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l | (b::l) _ := zero_lt_succ _ theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l | (b::l) _ := ⟨b, mem_cons_self _ _⟩ theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l := ⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩ theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] := ⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩ theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih; simp at h; cases h with h h, { subst h, exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, e⟩, subst l, exact ⟨b::s, t, rfl⟩ } end theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l := or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r) theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b := assume nin aeqb, absurd (or.inl aeqb) nin theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l := assume nin nainl, absurd (or.inr nainl) nin theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l := assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2)) theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l := assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p) theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l := begin induction l with b l' ih, {simp at h, contradiction }, {simp, simp at h, cases h with h h, {simp *}, {exact or.inr (ih h)}} end theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) : ∃ a, a ∈ l ∧ f a = b := begin induction l with c l' ih, {simp at h, contradiction}, {cases (eq_or_mem_of_mem_cons h) with h h, {existsi c, simp [h]}, {rcases ih h with ⟨a, ha₁, ha₂⟩, existsi a, simp * }} end @[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b := ⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : injective f) {a : α} {l : list α} : f a ∈ map f l ↔ a ∈ l := ⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩ @[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l | [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩ | (c :: L) := by simp [join, @mem_join L, or_and_distrib_right, exists_or_distrib] theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l := mem_join.1 theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L := mem_join.2 ⟨l, lL, al⟩ @[simp] theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a := iff.trans mem_join ⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩, λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩ theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a := mem_bind.1 theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) : b ∈ list.bind l f := mem_bind.2 ⟨a, al, h⟩ lemma bind_map {g : α → list β} {f : β → γ} : ∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f) | [] := rfl | (a::l) := by simp [bind_map l] /- list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_app_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_right _ _ @[simp] theorem cons_subset {a : α} {l m : list α} : a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem cons_subset_of_subset_of_mem {a : α} {l m : list α} (ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m := cons_subset.2 ⟨ainm, lsubm⟩ theorem app_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) : l₁ ++ l₂ ⊆ l := λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _) theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = [] | [] s := rfl | (a::l) s := false.elim $ s $ mem_cons_self a l theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l := show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩ theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ := λ x, by simp [mem_map]; exact λ a h e, ⟨a, H h, e⟩ /- append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] := by induction s; intros; contradiction theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t := by {induction s with b s H generalizing a, refl, simp [foldl], rw H _} theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s := by {induction s with b s H generalizing a, refl, simp [foldr], rw H _} @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp @[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] := by rw [eq_comm, append_eq_nil] lemma append_eq_cons_iff {a b c : list α} {x : α} : a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by cases a; simp [and_assoc, @eq_comm _ c] lemma cons_eq_append_iff {a b c : list α} {x : α} : (x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) := by rw [eq_comm, append_eq_cons_iff] lemma append_eq_append_iff {a b c d : list α} : a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) := begin induction a generalizing c, case nil { simp [nil_eq_append_iff, iff_def, or_imp_distrib] {contextual := tt} }, case cons : a as ih { cases c, { simp, exact eq_comm }, { simp [ih, @eq_comm _ a, and_assoc, and_or_distrib_left] } } end /-- Split a list at an index. `split 2 [a, b, c] = ([a, b], [c])` -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) @[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l) | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp [split_at, split_at_eq_take_drop n xs] @[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l | 0 a := rfl | (succ n) [] := rfl | (succ n) (x :: xs) := by simp [take_append_drop n xs] -- TODO(Leo): cleanup proof after arith dec proc theorem append_inj : ∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂ | [] [] t₁ t₂ h hl := ⟨rfl, h⟩ | (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl | [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm | (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap, let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩ theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : t₁ = t₂ := (append_inj h hl).right theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length s₁ = length s₂) : s₁ = s₂ := (append_inj h hl).left theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ ∧ t₁ = t₂ := append_inj h $ @nat.add_right_cancel _ (length t₁) _ $ let hap := congr_arg length h in by simp at hap; rwa [← hl] at hap theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : t₁ = t₂ := (append_inj' h hl).right theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) : s₁ = s₂ := (append_inj' h hl).left theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ := append_inj_left h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_right' h rfl theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_right_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ := ⟨append_right_cancel, congr_arg _⟩ theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β} (h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ := begin have := h, rw [← take_append_drop (length s₁) l] at this ⊢, rw map_append at this, refine ⟨_, _, rfl, append_inj this _⟩, rw [length_map, length_take, min_eq_left], rw [← length_map f l, h, length_append], apply le_add_right end /- join -/ attribute [simp] join @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; simp * /- repeat -/ @[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a | (n+1) h := or.elim h id $ @eq_of_mem_repeat _ theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length | [] H := rfl | (b::l) H := have b = a ∧ ∀ (x : α), x ∈ l → x = a, by simpa [or_imp_distrib, forall_and_distrib] using H, by dsimp; congr; [exact this.1, exact eq_repeat_of_mem this.2] theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩ theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a := ⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n := by induction m; simp [*, repeat, nat.succ_add, -add_comm] theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] := λ b h, mem_singleton.2 (eq_of_mem_repeat h) @[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length := by induction l; simp [repeat, -add_comm, *] theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := by rw map_const at h; exact eq_of_mem_repeat h @[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n := by induction n; simp * @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl /- bind -/ @[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) : l >>= f = l.bind f := rfl @[simp] theorem bind_append {α β} (f : α → list β) (l₁ l₂ : list α) : (l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f := by simp [bind] /- concat -/ /-- Concatenate an element at the end of a list. `concat [a, b] c = [a, b, c]` -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a @[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl @[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by induction l; intro h; contradiction @[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by induction l₁ with b l₁ ih; [simp, simp [ih]] @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp [*, concat] @[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp [succ_eq_add_one] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by induction l₂ with b l₂ ih; simp /- reverse -/ @[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl local attribute [simp] reverse_core @[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] := have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]), by intro l₁; induction l₁; simp *, (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; simp * theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp @[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl @[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) := by induction s; simp * @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; simp * theorem reverse_injective : injective (@reverse α) := injective_of_left_inverse reverse_reverse @[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ := reverse_injective.eq_iff @[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] := @reverse_inj _ l [] theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) := by simp @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; simp * @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; simp * theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp [reverse_core_eq] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; simp [*, or_comm] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp, λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ @[elab_as_eliminator] theorem reverse_rec_on {C : list α → Sort*} (l : list α) (H0 : C []) (H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l := begin rw ← reverse_reverse l, induction reverse l, { exact H0 }, { simp, exact H1 _ _ ih } end /- last -/ @[simp] theorem last_cons {a : α} {l : list α} : ∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ := by {induction l; intros, contradiction, simp *, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp *] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp * @[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl @[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) : last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head and tail -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl @[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl @[simp] theorem tail_nil : tail (@nil α) = [] := rfl @[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl @[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) : head (s ++ t) = head s := by {induction s, contradiction, simp} theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, simp} /- map -/ lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := have f a = g a, from h _ (mem_cons_self _ _), have map f l = map g l, from map_congr $ assume a', h _ ∘ mem_cons_of_mem _, show f a :: map f l = g a :: map g l, by simp [*] theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; simp * theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; simp * @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) : foldl f a (map g l) = foldl (λx y, f x (g y)) a l := by revert a; induction l; intros; simp * @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) : foldr f a (map g l) = foldr (f ∘ g) a l := by revert a; induction l; intros; simp * theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α) (h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l := by revert a; induction l; intros; simp * theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α) (h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l := by revert a; induction l; intros; simp * theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero (begin rw [← length_map f l], simp [h] end) @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; simp * theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by simp [list.bind]; induction l; simp [list.ret, join, *] @[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl @[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) := by cases l; refl /- map₂ -/ theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] := by cases l; refl theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] := by cases l; refl /- sublists -/ @[simp] theorem nil_sublist : Π (l : list α), [] <+ l | [] := sublist.slnil | (a :: l) := sublist.cons _ _ a (nil_sublist l) @[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l | [] := sublist.slnil | (a :: l) := sublist.cons2 _ _ a (sublist.refl l) @[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ := sublist.rec_on h₂ (λ_ s, s) (λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁)) (λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁ (λ_, nil_sublist _) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons _ _ _ (IH _ h₁) end) (λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ := sublist.cons2 _ _ _ (IH _ h₁) end) rfl) l₁ h₁ @[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l := sublist.cons _ _ _ (sublist.refl l) theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ := sublist.trans (sublist_cons a l₁) theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ := sublist.cons2 _ _ _ s @[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂ | [] l₂ := nil_sublist _ | (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂) @[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂ | [] l₂ := sublist.refl _ | (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂) theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ := sublist.cons _ _ _ theorem sublist_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_app_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ := s.trans $ sublist_append_right _ _ theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂ | ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s | ._ (sublist.cons2 ._ ._ a s) := s theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ := ⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩ @[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂ | [] := iff.rfl | (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l) theorem append_sublist_append_of_sublist_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l := begin induction h with _ _ a _ ih _ _ a _ ih, { refl }, { apply sublist_cons_of_sublist a ih }, { apply cons_sublist_cons a ih } end theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) : l <+ l₁ ++ l₂ ∨ a ∈ l := begin induction l₁ with b l₁ IH generalizing l, { cases h; simp * }, { cases h with _ _ _ h _ _ _ h, { exact or.imp_left (sublist_cons_of_sublist _) (IH h) }, { exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } } end theorem reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih; simp, { exact sublist_app_of_sublist_left ih }, { exact append_sublist_append_of_sublist_right ih [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp at this; assumption, reverse_sublist⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp at this; assumption, λ h, append_sublist_append_of_sublist_right h l⟩ theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist s h) | ._ ._ (sublist.cons2 l₁ l₂ a s) b h := match eq_or_mem_of_mem_cons h with | or.inl h := h ▸ mem_cons_self _ _ | or.inr h := mem_cons_of_mem _ (subset_of_sublist s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, subset_of_sublist h (mem_singleton_self _), λ h, let ⟨s, t, e⟩ := mem_split h in e.symm ▸ (cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩ theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] := eq_nil_of_subset_nil $ subset_of_sublist s theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa using length_le_of_sublist h, λ h, by induction h; [apply sublist.refl, simp [*, sublist.cons]] ⟩ theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂ | ._ ._ sublist.slnil h := rfl | ._ ._ (sublist.cons l₁ l₂ a s) h := absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self | ._ ._ (sublist.cons2 l₁ l₂ a s) h := by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) : l₁ = l₂ := eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h) theorem sublist_antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ := eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂) instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂) | [] l₂ := is_true $ nil_sublist _ | (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h | (a::l₁) (b::l₂) := if h : a = b then decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $ by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩ else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂) ⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with | a, l₁, sublist.cons ._ ._ ._ s', h := s' | ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h end⟩ /- index_of -/ section index_of variable [decidable_eq α] @[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl theorem index_of_cons (a b : α) (l : list α) : index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 := assume e, if_pos e @[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 := index_of_cons_eq _ rfl @[simp] theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) := assume n, if_neg n theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l := begin induction l with b l ih; simp [-add_comm], by_cases h : a = b; simp [h, -add_comm], { intro, contradiction }, { rw ← ih, exact ⟨succ_inj, congr_arg _⟩ } end @[simp] theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l := index_of_eq_length.2 theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l := begin induction l with b l ih; simp [-add_comm, index_of_cons], by_cases h : a = b; simp [h, -add_comm, zero_le], exact succ_le_succ ih end theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l := ⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al, λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩ end index_of /- nth element -/ theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a | a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩ | a (b :: l) (or.inr m) := let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩ theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h) | (a :: l) 0 h := rfl | (a :: l) (n+1) h := @nth_le_nth l n _ theorem nth_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_ge_len (le_of_succ_le_succ h) theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a := ⟨λ e, have h : n < length l, from lt_of_not_ge $ λ hn, by rw nth_ge_len hn at e; contradiction, ⟨h, by rw nth_le_nth h at e; injection e with e; apply nth_le_mem⟩, λ ⟨h, e⟩, e ▸ nth_le_nth _⟩ theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a := let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩ theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l | (a :: l) 0 h := mem_cons_self _ _ | (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _) theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l := let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _ theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a := ⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩ theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a := mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm @[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f | [] n := rfl | (a :: l) 0 := rfl | (a :: l) (n+1) := nth_map l n theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) := option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl @[simp] theorem nth_le_map' (f : α → β) {l n} (H) : nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) := nth_le_map f _ _ @[extensionality] theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂ | [] [] h := rfl | (a::l₁) [] h := by have h0 := h 0; contradiction | [] (a'::l₂) h := by have h0 := h 0; contradiction | (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa; simp [*, ext (λn, h (n+1))] theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂) (h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ := ext $ λn, if h₁ : n < length l₁ then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])] else let h₁ := le_of_not_gt h₁ in by rw [nth_ge_len h₁, nth_ge_len (by rwa [← hl])] @[simp] theorem index_of_nth_le [decidable_eq α] {a : α} : ∀ {l : list α} h, nth_le l (index_of a l) h = a | (b::l) h := by by_cases h' : a = b; simp * @[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : nth l (index_of a l) = some a := by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)] theorem nth_le_reverse_aux1 : ∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2 | [] r i := λh1 h2, rfl | (a :: l) r i := by rw (show i + length (a :: l) = i + 1 + length l, by simp); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2), nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2 | [] r i h1 h2 := absurd h2 (not_lt_zero _) | (a :: l) r 0 h1 h2 := begin have aux := nth_le_reverse_aux1 l (a :: r) 0, rw zero_add at aux, exact aux _ (zero_lt_succ _) end | (a :: l) r (i+1) h1 h2 := begin have aux := nth_le_reverse_aux2 l (a :: r) i, have heq := calc length (a :: l) - 1 - (i + 1) = length l - (1 + i) : by rw add_comm; refl ... = length l - 1 - i : by rw nat.sub_sub, rw [← heq] at aux, apply aux end @[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) : nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 := nth_le_reverse_aux2 _ _ _ _ _ /-- Convert a list into an array (whose length is the length of `l`) -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /- nth tail operation -/ /-- Apply a function to the nth tail of `l`. `modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c]`. Returns the input without using `f` if the index is larger than the length of the list. -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _) theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α), update_nth l n a = modify_nth (λ _, a) n l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _) theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α), modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l | 0 l := by cases l; refl | (n+1) [] := rfl | (n+1) (b::l) := (congr_arg (cons b) (modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m, nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m | n l 0 := by cases l; cases n; refl | n [] (m+1) := by cases n; refl | 0 (a::l) (m+1) := by cases nth l m; refl | (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $ by cases nth l m with b; by_cases n = m; simp [h, mt succ_inj] theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) : ∀ n l, length (modify_nth_tail f n l) = length l | 0 l := H _ | (n+1) [] := rfl | (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _) @[simp] theorem modify_nth_length (f : α → α) : ∀ n l, length (modify_nth f n l) = length l := modify_nth_tail_length _ (λ l, by cases l; refl) @[simp] theorem update_nth_length (l : list α) (n) (a : α) : length (update_nth l n a) = length l := by simp [update_nth_eq_modify_nth] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp [nth_modify_nth] @[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) : nth (modify_nth f m l) n = nth l n := by simp [nth_modify_nth, h]; cases nth l n; refl theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp [update_nth_eq_modify_nth] theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) : nth (update_nth l n a) n = some a := by rw [nth_update_nth_eq, nth_le_nth h]; refl theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) : nth (update_nth l m a) n = nth l n := by simp [update_nth_eq_modify_nth, h] /- take, drop -/ @[simp] theorem take_zero : ∀ (l : list α), take 0 l = [] := begin intros, reflexivity end @[simp] theorem take_nil : ∀ n, take n [] = ([] : list α) | 0 := rfl | (n+1) := rfl theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl theorem take_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → take n l = l | 0 [] h := rfl | 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _)) | (n+1) [] h := rfl | (n+1) (a::l) h := begin change a :: take n l = a :: l, rw [take_all_of_ge (le_of_succ_le_succ h)] end @[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁ | [] l₂ := rfl | (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂) theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take n (l₁ ++ l₂) = l₁ := by rw ← h; apply take_left theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l | n 0 l := by rw [min_zero, take_zero, take_nil] | 0 m l := by simp | (succ n) (succ m) nil := by simp | (succ n) (succ m) (a::l) := by simp [min_succ_succ, take_take] @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l | [] := rfl | (a :: l) := rfl theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l) | m 0 l := rfl | m (n+1) [] := (drop_nil _).symm | m (n+1) (a::l) := drop_add m n _ @[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂ | [] l₂ := rfl | (a::l₁) l₂ := drop_left l₁ l₂ theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : drop n (l₁ ++ l₂) = l₂ := by rw ← h; apply drop_left theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h, drop n l = nth_le l n h :: drop (n+1) l | 0 (a::l) h := rfl | (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _ theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) : ∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l) | 0 l := rfl | (n+1) [] := H.symm | (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l) theorem modify_nth_eq_take_drop (f : α → α) : ∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) := modify_nth_tail_eq_take_drop _ rfl theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) : modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l := by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) : update_nth l n a = take n l ++ a :: drop (n+1) l := by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp [update_nth] section take' variable [inhabited α] def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail @[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n | 0 l := rfl | (n+1) l := congr_arg succ (take'_length _ _) @[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n | 0 := rfl | (n+1) := congr_arg (cons _) (take'_nil _) theorem take'_eq_take : ∀ {n} {l : list α}, n ≤ length l → take' n l = take n l | 0 l h := rfl | (n+1) (a::l) h := congr_arg (cons _) $ take'_eq_take $ le_of_succ_le_succ h @[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ := (take'_eq_take (by simp [le_add_right])).trans (take_left _ _) theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) : take' n (l₁ ++ l₂) = l₁ := by rw ← h; apply take'_left end take' /- take_while -/ /-- Get the longest initial segment of the list whose members all satisfy `p`. `take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2]` -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /- foldl, foldr, scanl, scanr -/ lemma foldl_ext (f g : α → β → α) (a : α) {l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) : foldl f a l = foldl g a l := by induction l generalizing a; simp * {contextual := tt} lemma foldr_ext (f g : α → β → β) (b : β) {l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) : foldr f b l = foldr g b l := by induction l; simp * {contextual := tt} @[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl @[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) : foldl f a (b::l) = foldl f (f a b) l := rfl @[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : foldr f b (a::l) = f a (foldr f b l) := rfl @[simp] theorem foldl_append (f : α → β → α) : ∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂ | a [] l₂ := rfl | a (b::l₁) l₂ := by simp [foldl_append] @[simp] theorem foldr_append (f : α → β → β) : ∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁ | b [] l₂ := rfl | b (a::l₁) l₂ := by simp [foldr_append] @[simp] theorem foldl_join (f : α → β → α) : ∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L | a [] := rfl | a (l::L) := by simp [foldl_join] @[simp] theorem foldr_join (f : α → β → β) : ∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L | a [] := rfl | a (l::L) := by simp [foldr_join] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; simp [*, foldr] theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) : foldr f a (reverse l) = foldl (λx y, f y x) a l := let t := foldl_reverse (λx y, f y x) a (reverse l) in by rw reverse_reverse l at t; rwa t @[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l | [] := rfl | (x::l) := by simp [foldr_eta l] /-- Fold a function `f` over the list from the left, returning the list of partial results. `scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6]` -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. `scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0]` -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' @[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl @[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α), scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l) | a [] := rfl | a (x::l) := let t := scanr_aux_cons x l in by simp [scanr, scanr_aux] at t; simp [scanr, scanr_aux, t] @[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) : scanr f b (a::l) = foldr f b (a::l) :: scanr f b l := by simp [scanr] section foldl_eq_foldr -- foldl and foldr coincide when f is commutative and associative variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f) include hassoc theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l) | a b nil := rfl | a b (c :: l) := by simp [foldl1_eq_foldr1 _ _ l]; rw hassoc include hcomm theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l) | a b nil := hcomm a b | a b (c::l) := by simp; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; simp theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp [foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr section variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l include ha lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂) | [] a₁ a₂ := by simp | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp [ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc]; simp lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := by simp | (a :: l) a₁ a₂ := by simp [foldl_assoc, ha.assoc]; rw [foldl_op_eq_op_foldr_assoc] include hc lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) := by rw [foldl_cons, hc.comm, foldl_assoc] end /- sum -/ /-- Product of a list. `prod [a, b, c] = ((1 * a) * b) * c` -/ @[to_additive list.sum] def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1 section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive list.sum_nil] theorem prod_nil : ([] : list α).prod = 1 := rfl @[simp, to_additive list.sum_cons] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp [list.prod] ... = _ : foldl_assoc @[simp, to_additive list.sum_append] theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[simp, to_additive list.sum_join] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; simp [list.join, *] at * end monoid @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; simp [*, nat.mul_succ] @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; simp * @[simp] theorem length_bind (l : list α) (f : α → list β) : length (list.bind l f) = sum (map (length ∘ f) l) := by rw [list.bind, length_join, map_map] /- lexicographic ordering -/ inductive lex (r : α → α → Prop) : list α → list α → Prop | nil {} {a l} : lex [] (a :: l) | cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂) | rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂) namespace lex theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} : lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ := ⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h; [exact h, exact (irrefl_of r a h).elim], lex.cons⟩ instance is_order_connected (r : α → α → Prop) [is_order_connected α r] [is_trichotomous α r] : is_order_connected (list α) (lex r) := ⟨λ l₁, match l₁ with | _, [], c::l₃, nil := or.inr nil | _, [], c::l₃, rel _ := or.inr nil | _, [], c::l₃, cons _ := or.inr nil | _, b::l₂, c::l₃, nil := or.inl nil | a::l₁, b::l₂, c::l₃, rel h := (is_order_connected.conn _ b _ h).imp rel rel | a::l₁, b::l₂, _::l₃, cons h := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match _ l₂ _ h).imp cons cons }, { exact or.inr (rel ab) } end end⟩ instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] : is_trichotomous (list α) (lex r) := ⟨λ l₁, match l₁ with | [], [] := or.inr (or.inl rfl) | [], b::l₂ := or.inl nil | a::l₁, [] := or.inr (or.inr nil) | a::l₁, b::l₂ := begin rcases trichotomous_of r a b with ab | rfl | ab, { exact or.inl (rel ab) }, { exact (_match l₁ l₂).imp cons (or.imp (congr_arg _) cons) }, { exact or.inr (or.inr (rel ab)) } end end⟩ instance is_asymm (r : α → α → Prop) [is_asymm α r] : is_asymm (list α) (lex r) := ⟨λ l₁, match l₁ with | a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂ | a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁ | a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂ | a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ := by exact _match _ _ h₁ h₂ end⟩ instance is_strict_total_order (r : α → α → Prop) [is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) := {..is_strict_weak_order_of_is_order_connected} instance decidable_rel [decidable_eq α] (r : α → α → Prop) [decidable_rel r] : decidable_rel (lex r) | l₁ [] := is_false $ λ h, by cases h | [] (b::l₂) := is_true lex.nil | (a::l₁) (b::l₂) := begin haveI := decidable_rel l₁ l₂, refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩, { rcases h with h | ⟨rfl, h⟩, { exact lex.rel h }, { exact lex.cons h } }, { rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩, { exact or.inr ⟨rfl, h⟩ }, { exact or.inl h } } end theorem append_right (r : α → α → Prop) : ∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t) | _ _ t nil := nil | _ _ t (cons h) := cons (append_right _ h) | _ _ t (rel r) := rel r theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) : ∀ s, lex R (s ++ t₁) (s ++ t₂) | [] := h | (a::l) := cons (append_left l) theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) : ∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂ | _ _ nil := nil | _ _ (cons h) := cons (imp _ _ h) | _ _ (rel r) := rel (H _ _ r) theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂ | _ _ (cons h) e := to_ne h (list.cons.inj e).2 | _ _ (rel r) e := r (list.cons.inj e).1 theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) : lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ := ⟨to_ne, λ h, begin induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂, { contradiction }, { apply nil }, { exact (not_lt_of_ge H).elim (succ_pos _) }, { cases classical.em (a = b) with ab ab, { subst b, apply cons, exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) }, { exact rel ab } } end⟩ end lex --Note: this overrides an instance in core lean instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩ theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l := lex.nil instance [linear_order α] : linear_order (list α) := linear_order_of_STO' (lex (<)) --Note: this overrides an instance in core lean instance has_le' [linear_order α] : has_le (list α) := preorder.to_has_le _ instance [decidable_linear_order α] : decidable_linear_order (list α) := decidable_linear_order_of_STO' (lex (<)) /- all & any, bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := by simp @[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} : (∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp [or_imp_distrib, forall_and_distrib] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∀ x ∈ a :: l, p x) : ∀ x ∈ l, p x := (forall_mem_cons.1 h).2 theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a := by simp theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp [or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x := by simp theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (by simp) h theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) : ∃ x ∈ a :: l, p x := bex.elim h (λ x xl px, bex.intro x (by simp [xl]) px) theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) : p a ∨ ∃ x ∈ l, p x := bex.elim h (λ x xal px, or.elim (eq_or_mem_of_mem_cons xal) (assume : x = a, begin rw ←this, simp [px] end) (assume : x ∈ l, or.inr (bex.intro x this px))) @[simp] theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x := iff.intro or_exists_of_exists_mem_cons (assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists) @[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl @[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) : all (a::l) p = (p a && all l p) := rfl theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a := by induction l with a l; simp [forall_and_distrib, *] theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp [all_iff_forall] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a::l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a := by induction l with a l; simp [or_and_distrib_right, exists_or_distrib, *] theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p] {l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop /- map for partial functions -/ /-- Partial map. If `f : Π a, p a → β` is a partial function defined on `a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l` but is defined only when all members of `l` satisfy `p`, using the proof to apply `f`. -/ @[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β | [] H := [] | (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2 /-- "Attach" the proof that the elements of `l` are in `l` to produce a new list with the same elements but in the type `{x // x ∈ l}`. -/ def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id) theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; simp * theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f l H₁ = pmap g l H₂ := by induction l with _ _ ih; simp *; apply ih theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H := by induction l; simp * theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) := by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl) theorem attach_map_val (l : list α) : l.attach.map subtype.val = l := by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l) @[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ := by have := mem_map.1 (by rw [attach_map_val]; exact h); { rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m } @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b := by simp [pmap_eq_map_attach] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; simp * /- find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := find_indexes_aux p l 0 @[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none := rfl @[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a := if_pos h @[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l := if_neg h @[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x := begin induction l with a l IH, {simp}, by_cases p a; simp [h, IH] end @[simp] theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases p b; simp [h] at H, { subst b, assumption }, { exact IH H } end @[simp] theorem find_mem (H : find p l = some a) : a ∈ l := begin induction l with b l IH, {contradiction}, by_cases p b; simp [h] at H, { subst b, apply mem_cons_self }, { exact mem_cons_of_mem _ (IH H) } end end find /-- `indexes_of a l` is the list of all indexes of `a` in `l`. `indexes_of a [a, b, a, a] = [0, 2, 3]` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /- filter_map -/ @[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) : filter_map f (a :: l) = filter_map f l := by simp [filter_map, h] @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (l : list α) {b : β} (h : f a = some b) : filter_map f (a :: l) = b :: filter_map f l := by simp [filter_map, h] theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {simp}, simp [filter_map_cons_some (some ∘ f) _ _ rfl, IH] end theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := begin funext l, induction l with a l IH, {simp}, by_cases pa : p a; simp [filter_map, option.guard, pa, IH] end theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) : filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l := begin induction l with a l IH, {refl}, cases h : f a with b, { rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH], simp [h, option.bind] }, rw filter_map_cons_some _ _ _ h, cases h' : g b with c; [ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH], rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ]; simp [h, h', option.bind] end theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) : map g (filter_map f l) = filter_map (λ x, (f x).map g) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) : filter_map g (map f l) = filter_map (g ∘ f) l := by rw [← filter_map_eq_map, filter_map_filter_map]; refl theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) : filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l := by rw [← filter_map_eq_filter, filter_map_filter_map]; refl theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) : filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l := begin rw [← filter_map_eq_filter, filter_map_filter_map], congr, funext x, show (option.guard p x).bind f = ite (p x) (f x) none, by_cases p x; simp [h, option.guard, option.bind] end @[simp] theorem filter_map_some (l : list α) : filter_map some l = l := by rw filter_map_eq_map; apply map_id @[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} : b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b := begin induction l with a l IH, {simp}, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp [filter_map_cons_none _ _ h, IH, or_and_distrib_right, exists_or_distrib, this] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp [filter_map_cons_some _ _ _ h, IH, or_and_distrib_right, exists_or_distrib, this] } end theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (l : list α) : map g (filter_map f l) = l := by simp [map_filter_map, H] theorem filter_map_sublist_filter_map (f : α → option β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ := by induction s with l₁ l₂ a s IH l₁ l₂ a s IH; simp [filter_map]; cases f a with b; simp [filter_map, IH, sublist.cons, sublist.cons2] theorem map_sublist_map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s /- filter -/ section filter variables {p : α → Prop} [decidable_pred p] lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] : ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l | [] _ := rfl | (a::l) h := by simp at h; by_cases pa : p a; [simp [pa, h.1.1 pa, filter_congr h.2], simp [pa, mt h.1.2 pa, filter_congr h.2]] @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := subset_of_sublist $ filter_sublist l theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | [] ain := absurd ain (not_mem_nil a) | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, begin simp [pb] at ain, assumption end, or.elim (eq_or_mem_of_mem_cons this) (assume : a = b, begin rw [← this] at pb, exact pb end) (assume : a ∈ filter p l, of_mem_filter this) else begin simp [pb] at ain, exact (of_mem_filter ain) end theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l := filter_subset l h theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l | [] ain pa := absurd ain (not_mem_nil a) | (b::l) ain pa := if pb : p b then or.elim (eq_or_mem_of_mem_cons ain) (assume : a = b, by simp [pb, this]) (assume : a ∈ l, begin simp [pb], exact (mem_cons_of_mem _ (mem_filter_of_mem this pa)) end) else or.elim (eq_or_mem_of_mem_cons ain) (assume : a = b, begin simp [this] at pa, contradiction end) --absurd (this ▸ pa) pb) (assume : a ∈ l, by simp [pa, pb, mem_filter_of_mem this]) @[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a := ⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩ theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a := begin induction l with a l, {simp}, by_cases p a; simp [filter, *], show filter p l ≠ a :: l, intro e, have := filter_sublist l, rw e at this, exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) end theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a := by simp [-and.comm, eq_nil_iff_forall_not_mem, mem_filter] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) := by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl @[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), span p l = (take_while p l, drop_while p l) | [] := rfl | (a::l) := by by_cases pa : p a; simp [span, take_while, drop_while, pa, span_eq_take_drop l] @[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] : ∀ (l : list α), take_while p l ++ drop_while p l = l | [] := rfl | (a::l) := by by_cases pa : p a; simp [take_while, drop_while, pa, take_while_append_drop l] /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs @[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 := if_pos pa @[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l := if_neg pa theorem countp_eq_length_filter (l) : countp p l = length (filter p l) := by induction l with x l; [refl, by_cases (p x)]; simp [*, -add_comm] local attribute [simp] countp_eq_length_filter @[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ := by simp theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp [countp_eq_length_filter, length_pos_iff_exists_mem] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa using length_le_of_sublist (filter_sublist_filter s) end filter /- count -/ section count variable [decidable_eq α] /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count (a : α) : list α → nat := countp (eq a) @[simp] theorem count_nil (a : α) : count a [] = 0 := rfl theorem count_cons (a b : α) (l : list α) : count a (b :: l) = if a = b then succ (count a l) else count a l := rfl theorem count_cons' (a b : α) (l : list α) : count a (b :: l) = count a l + (if a = b then 1 else 0) := begin rw count_cons, split_ifs; refl end @[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) := if_pos rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ := countp_le_of_sublist theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) := count_le_of_sublist _ (sublist_cons _ _) theorem count_singleton (a : α) : count a [a] = 1 := by simp @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append @[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by rw [concat_eq_append, count_append, count_singleton] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l := λ h', ne_of_gt (count_pos.2 h') h @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat]; exact λ b m, (eq_of_mem_repeat m).symm theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} : n ≤ count a l ↔ repeat a n <+ l := ⟨λ h, ((repeat_sublist_repeat a).2 h).trans $ have filter (eq a) l = repeat a (count a l), from eq_repeat.2 ⟨by simp [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa using count_le_of_sublist a h⟩ end count /- prefix, suffix, infix -/ /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix @[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩ @[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩ @[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩ theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩ @[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩ @[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩ @[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a] @[simp] theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨[], t, h⟩ theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ := λ⟨t, h⟩, ⟨t, [], by simp [h]⟩ @[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ := λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩ @[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃ | l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, by simp⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, by simp⟩ @[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃ | l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp⟩ theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ := λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _) theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_prefix theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ := sublist_of_infix ∘ infix_of_suffix theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ := ⟨λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩, λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩ theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ := by rw ← reverse_suffix; simp theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ := length_le_of_sublist $ sublist_of_infix s theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] := eq_nil_of_sublist_nil $ sublist_of_infix s theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] := eq_nil_of_infix_nil $ infix_of_prefix s theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] := eq_nil_of_infix_nil $ infix_of_suffix s theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ := ⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩, λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩ theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_infix s theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_prefix s theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) : length l₁ = length l₂ → l₁ = l₂ := eq_of_sublist_of_length_eq $ sublist_of_suffix s theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂ | [] l₂ l₃ h₁ h₂ _ := nil_prefix _ | (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin injection e with _ e', subst b, rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩ (le_of_succ_le_succ ll) with ⟨r₃, rfl⟩, exact ⟨r₃, rfl⟩ end theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α} (h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ := (le_total (length l₁) (length l₂)).imp (prefix_of_prefix_length_le h₁ h₂) (prefix_of_prefix_length_le h₂ h₁) theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ := reverse_prefix.1 $ prefix_of_prefix_length_le (reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll]) theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α} (h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ := (prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp reverse_prefix.1 reverse_prefix.1 theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L | (_ :: L) l (or.inl rfl) := infix_append [] _ _ | (l' :: L) l (or.inr h) := is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _ theorem prefix_append_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_left_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_left_inj [a] theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩ theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩ theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨λ h, let ⟨r, e⟩ := h in begin rwa append_inj_left ((take_append_drop (length l₁) l₂).trans e.symm) _, simp [min_eq_left, length_le_of_sublist (sublist_of_prefix h)], end, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨λ ⟨r, e⟩, begin rwa append_inj_right ((take_append_drop (length l₂ - length l₁) l₂).trans e.symm) _, simp [min_eq_left, nat.sub_le, e.symm], apply nat.add_sub_cancel_left end, λ e, ⟨_, e⟩⟩ theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ := ⟨λ h, append_right_cancel $ (prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ take_prefix _ _⟩ theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ := ⟨λ h, append_left_cancel $ (suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm, λ e, e.symm ▸ drop_suffix _ _⟩ instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂) | [] l₂ := is_true ⟨l₂, rfl⟩ | (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te | (a::l₁) (b::l₂) := if h : a = b then @decidable_of_iff _ _ (by rw [← h, prefix_cons_inj]) (decidable_prefix l₁ l₂) else is_false $ λ ⟨t, te⟩, h $ by injection te -- Alternatively, use mem_tails instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂) | [] l₂ := is_true ⟨l₂, append_nil _⟩ | (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial | l₁ l₂ := let len1 := length l₁, len2 := length l₂ in if hl : len1 ≤ len2 then decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h /-- `inits l` is the list of initial segments of `l`. `inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]]` -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa, ⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩ | s (a::t) := suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa, ⟨λo, match s, o with | ._, or.inl rfl := ⟨_, rfl⟩ | s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in by rw [← hs, ← ht]; exact ⟨s, rfl⟩ end, λmi, match s, mi with | [], ⟨._, rfl⟩ := or.inl rfl | (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $ by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩ end⟩ /-- `tails l` is the list of terminal segments of `l`. `tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []]` -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp [mem_tails s t]; exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from ⟨λo, match s, t, o with | ._, t, or.inl rfl := suffix_refl _ | s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩ end, λe, match s, t, e with | ._, t, ⟨[], rfl⟩ := or.inl rfl | s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩) end⟩ instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂) | [] l₂ := is_true ⟨[], l₂, rfl⟩ | (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $ append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h | l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $ by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm; exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩ /- sublists -/ def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. `sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]` -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) : map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) := by induction l generalizing f r; simp! * theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) : sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' := by induction l generalizing f r; simp! * theorem sublists'_aux_eq_sublists' (l f r) : @sublists'_aux α β l f r = map f (sublists' l) ++ r := by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl @[simp] theorem sublists'_cons (a : α) (l : list α) : sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) := by rw [sublists', sublists'_aux]; simp [sublists'_aux_eq_sublists'] @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s; simp, { exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ (IH.1 h) }, { exact cons_sublist_cons _ (IH.1 h) }, { cases h with _ _ _ h s _ _ h, { exact or.inl (IH.2 h) }, { exact or.inr ⟨s, IH.2 h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp [-add_comm, *]; rw [← two_mul, mul_comm]; refl def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`. `sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]` -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β), sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r) | [] f := rfl | (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp * theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) : sublists_aux l cons = sublists_aux₁ l (λ x, [x]) := by rw [sublists_aux₁_eq_sublists_aux]; refl theorem sublists_aux_eq_foldr.aux {a : α} {l : list α} (IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons)) (IH₂ : ∀ (f : list α → list (list α) → list (list α)), sublists_aux l f = foldr f [] (sublists_aux l cons)) (f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) := begin simp [sublists_aux], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih; simp * end theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons) := suffices _ ∧ ∀ f : list α → list (list α) → list (list α), sublists_aux l f = foldr f [] (sublists_aux l cons), from this.1, begin induction l with a l IH, {split; intro; refl}, exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2, sublists_aux_eq_foldr.aux IH.2 IH.2⟩ end theorem sublists_aux_cons_cons (l : list α) (a : α) : sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) := by rw [← sublists_aux_eq_foldr]; refl theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β), sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++ sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x))) | [] l₂ f := by simp [sublists_aux₁] | (a::l₁) l₂ f := by simp [sublists_aux₁]; rw [sublists_aux₁_append]; simp theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) : sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++ f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) := by simp [sublists_aux₁_append, sublists_aux₁] theorem sublists_aux₁_bind : ∀ (l : list α) (f : list α → list β) (g : β → list γ), (sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g) | [] f g := by simp [sublists_aux₁] | (a::l) f g := by simp [sublists_aux₁]; rw [sublists_aux₁_bind]; simp theorem sublists_aux_cons_append (l₁ l₂ : list α) : sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++ (do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) := begin simp [sublists, sublists_aux_cons_eq_sublists_aux₁], rw [sublists_aux₁_append, sublists_aux₁_bind], congr, funext x, simp, rw [← bind_ret_eq_map, sublists_aux₁_bind], simp [list.ret] end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp [sublists_aux_cons_append, sublists, map_id'] @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by simp [sublists_append]; rw [sublists, sublists_aux_cons_eq_sublists_aux₁]; simp [map_id', sublists_aux₁] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l; simp [(∘), *] theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) := by rw [← sublists_reverse, reverse_reverse] theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) := by simp [sublists_eq_sublists', map_id'] theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) := by rw [← sublists'_reverse, reverse_reverse] theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons | [] := id | (a::l) := begin rw [sublists_aux_cons_cons], refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _, have := sublists_aux_ne_nil l, revert this, induction sublists_aux l cons; intro; simp [not_or_distrib], exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩ end @[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t := by rw [← reverse_sublist_iff, ← mem_sublists', sublists'_reverse, mem_map_of_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp [sublists_eq_sublists', length_sublists'] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp; exact ((append_sublist_append_left _).2 (singleton_sublist.2 $ mem_map.2 ⟨[], by simp [list.ret]⟩)).trans ((append_sublist_append_right _).2 IH) /- transpose -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. `transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]]` -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /- forall₂ -/ section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator relation inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil {} : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff attribute [simp] forall₂.nil @[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} : forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := ⟨λ h, by cases h with h₁ h₂; simp *, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩ lemma forall₂_flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ (forall₂_flip h₂) lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l | [] _ := forall₂.nil | (a::as) h := forall₂.cons (h _ (mem_cons_self _ _)) (forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha) lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l := forall₂_same $ assume a h, is_refl.refl _ _ lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) := begin funext a b, apply propext, split, { assume h, induction h; simp * }, { assume h, subst h, exact forall₂_refl _ } end @[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil := by rw [forall₂_iff]; simp @[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil := by rw [forall₂_iff]; simp lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_cons_right_iff {b l u} : forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) @[simp] lemma forall₂_map_left_iff {f : γ → α} : ∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u | [] _ := by simp | (a::l) _ := by simp [forall₂_cons_left_iff, forall₂_map_left_iff] @[simp] lemma forall₂_map_right_iff {f : γ → β} : ∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u | _ [] := by simp | _ (b::u) := by simp [forall₂_cons_right_iff, forall₂_map_right_iff] lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r) | a₀ nil a₁ forall₂.nil forall₂.nil := rfl | (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r) | nil a₀ a₁ forall₂.nil forall₂.nil := rfl | (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) := ⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩ theorem forall₂_length_eq {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂ | _ _ forall₂.nil := rfl | _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂) theorem forall₂_zip {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b | _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁ | _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃ theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b := ⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩, λ h, begin cases h with h₁ h₂, induction l₁ with a l₁ IH generalizing l₂, { simp [length_eq_zero.1 h₁.symm] }, { cases l₂ with b l₂; injection h₁ with h₁, exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) } end⟩ lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp | a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂) lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map | f g h [] [] forall₂.nil := by simp [forall₂.nil] | f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂) lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append | [] [] h l₁ l₂ hl := hl | (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl) lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join | [] [] forall₂.nil := by simp [forall₂.nil] | (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂) lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind := assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁) lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs) lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : (r ⇒ (↔)) p q) : (forall₂ r ⇒ forall₂ r) (filter p) (filter q) | _ _ forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := begin by_cases p a, { have : q b, { rwa [← hpq h₁] }, simp [h, this, h₁, rel_filter h₂], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp [h, this, h₁, rel_filter h₂], }, end theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { simp [filter_map_cons_none _ _ eq]}, { simp [filter_map_cons_some _ _ _ eq]}, end lemma rel_filter_map {f : α → option γ} {q : β → option δ} : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive list.rel_sum] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := assume a b, rel_foldl (assume a b, hf) h end forall₂ /- sections -/ /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L := begin refine ⟨λ h, _, λ h, _⟩, { induction L generalizing f; simp [sections] at h; casesm* [Exists _, _ ∧ _, _ = _]; simp * }, { induction h with a l f L al fL fs; simp [sections], exact ⟨_, fs, _, al, rfl, rfl⟩ } end theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L := forall₂_length_eq (mem_sections.1 h) lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections | _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil | _ _ (forall₂.cons h₀ h₁) := rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀) /- permutations -/ section permutations def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by simp [permutations_aux, permutations_aux.rec] @[simp] theorem permutations_aux_cons (t : α) (ts is : list α) : permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2) (permutations_aux ts (t::is)) (permutations is) := by simp [permutations_aux, permutations_aux.rec, permutations] end permutations /- insert -/ section insert variable [decidable_eq α] @[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl @[simp] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp [insert.def, h] @[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp [insert.def, h] @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l; simp [h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; simp * @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) @[simp] theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l := mem_insert_iff.2 (or.inr h) theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l := mem_insert_iff.1 h @[simp] theorem length_insert_of_mem {a : α} [decidable_eq α] {l : list α} (h : a ∈ l) : length (insert a l) = length l := by simp [h] @[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by simp [h] end insert /- erase -/ section erase variable [decidable_eq α] @[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl theorem erase_cons (a b : α) (l : list α) : (b :: l).erase a = if b = a then l else b :: l.erase a := rfl @[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l := by simp [erase_cons] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp [erase_cons, h] @[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by induction l with _ _ ih; [refl, simp [(ne_of_not_mem_cons h).symm, ih (not_mem_of_not_mem_cons h)]] theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) : ∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ := by induction l with b l ih; [cases h, { simp at h, by_cases e : b = a, { subst b, exact ⟨[], l, not_mem_nil _, rfl, by simp⟩ }, { exact let ⟨l₁, l₂, h₁, h₂, h₃⟩ := ih (h.resolve_left (ne.symm e)) in ⟨b::l₁, l₂, not_mem_cons_of_ne_of_not_mem (ne.symm e) h₁, by rw h₂; refl, by simp [e, h₃]⟩ } }] @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := match l, l.erase a, exists_erase_eq h with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp [-add_comm]; refl end theorem erase_append_left {a : α} : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erase a = l₁.erase a ++ l₂ | (x::xs) l₂ h := begin by_cases h' : x = a; simp [h'], rw erase_append_left l₂ (mem_of_ne_of_mem (ne.symm h') h) end theorem erase_append_right {a : α} : ∀ {l₁ : list α} (l₂), a ∉ l₁ → (l₁++l₂).erase a = l₁ ++ l₂.erase a | [] l₂ h := rfl | (x::xs) l₂ h := by simp [*, (ne_of_not_mem_cons h).symm, (not_mem_of_not_mem_cons h)] theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := if h : a ∈ l then match l, l.erase a, exists_erase_eq h with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp end else by simp [h] theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := subset_of_sublist (erase_sublist a l) theorem erase_sublist_erase (a : α) : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → l₁.erase a <+ l₂.erase a | ._ ._ sublist.slnil := sublist.slnil | ._ ._ (sublist.cons l₁ l₂ b s) := if h : b = a then by rw [h, erase_cons_head]; exact (erase_sublist _ _).trans s else by rw erase_cons_tail _ h; exact (erase_sublist_erase s).cons _ _ _ | ._ ._ (sublist.cons2 l₁ l₂ b s) := if h : b = a then by rw [h, erase_cons_head, erase_cons_head]; exact s else by rw [erase_cons_tail _ h, erase_cons_tail _ h]; exact (erase_sublist_erase s).cons2 _ _ _ theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l := @erase_subset _ _ _ _ _ @[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l := ⟨mem_of_mem_erase, λ al, if h : b ∈ l then match l, l.erase b, exists_erase_eq h, al with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩, al := by simpa [ab] using al end else by simp [h, al]⟩ theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by simp [ab] else if ha : a ∈ l then if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with | ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb := if h₁ : b ∈ l₁ then by rw [erase_append_left _ h₁, erase_append_left _ h₁, erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head] else by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha', erase_cons_tail _ ab, erase_cons_head] end else by simp [hb, mt mem_of_mem_erase hb] else by simp [ha, mt mem_of_mem_erase ha] theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α} : ∀ (l : list α), map f (l.erase a) = (map f l).erase (f a) | [] := by simp [list.erase] | (b::l) := if h : f b = f a then by simp [h, finj h] else by simp [h, mt (congr_arg f) h, map_erase l] theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ := by induction l₂ generalizing l₁; simp [map_erase finj, *] end erase /- diff -/ section diff variable [decidable_eq α] @[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl @[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ := by by_cases a ∈ l₁; simp [list.diff, h] theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂ | l₁ [] := rfl | l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _) @[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ := by simp [diff_eq_foldl] @[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} : map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) := by simp [diff_eq_foldl, map_foldl_erase finj] end diff /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp [zip_unzip l] /- enum -/ theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l | n [] := rfl | n (a::l) := congr_arg nat.succ (length_enum_from _ _) theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _ @[simp] theorem enum_from_nth : ∀ n (l : list α) m, nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m | n [] m := rfl | n (a :: l) 0 := rfl | n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $ by rw [add_right_comm]; refl @[simp] theorem enum_nth : ∀ (l : list α) n, nth (enum l) n = (λ a, (n, a)) <$> nth l n := by simp [enum] @[simp] theorem enum_from_map_snd : ∀ n (l : list α), map prod.snd (enum_from n l) = l | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _) @[simp] theorem enum_map_snd : ∀ (l : list α), map prod.snd (enum l) = l := enum_from_map_snd _ /- product -/ /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a @[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl @[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β) : product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl @[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = [] | [] := rfl | (a::l) := by rw [product_cons, product_nil]; refl @[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} : (a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ := by simp [product, and.left_comm] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; simp [*, right_distrib] /- sigma -/ section variable {σ : α → Type*} /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [5, 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a @[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl @[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a)) : (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl @[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = [] | [] := rfl | (a::l) := by rw [sigma_cons, sigma_nil]; refl @[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} : sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a := by simp [list.sigma, and.left_comm] theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum := by induction l₁ with x l₁ IH; simp * end /- of_fn -/ def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] theorem length_of_fn_aux {n} (f : fin n → α) : ∀ m h l, length (of_fn_aux f m h l) = length l + m | 0 h l := rfl | (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _) theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : _ then some (f ⟨i, h⟩) else none theorem nth_of_fn_aux {n} (f : fin n → α) (i) : ∀ m h l, (∀ i, nth l i = of_fn_nth_val f (i + m)) → nth (of_fn_aux f m h l) i = of_fn_nth_val f i | 0 h l H := H i | (succ m) h l H := nth_of_fn_aux m _ _ begin intro j, cases j with j, { simp [of_fn_nth_val, show m < n, from h], refl }, { simp [H, succ_add, -add_comm] } end @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = of_fn_nth_val f i := nth_of_fn_aux f _ _ _ _ $ λ i, by simp [of_fn_nth_val, not_lt.2 (le_add_right n i)] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) : nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i := option.some.inj $ by rw [← nth_le_nth]; simp [of_fn_nth_val, i.2]; cases i; refl theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read := suffices ∀ {m h l}, d_array.rev_iterate_aux a (λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, simp [d_array.rev_iterate_aux, of_fn_aux, IH] end theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl theorem of_fn_succ {n} (f : fin (succ n) → α) : of_fn f = f 0 :: of_fn (λ i, f i.succ) := suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l = f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, rw [of_fn_aux, IH], refl end theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l | [] := rfl | (a::l) := by rw of_fn_succ; congr; simp; exact of_fn_nth_le l /- disjoint -/ section disjoint /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ := disjoint_comm theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) : disjoint l₁ l₂ | x m₁ := d (ss m₁) theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) : disjoint l₁ l₂ | x m m₁ := d m (ss m₁) theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ := disjoint_of_subset_left (list.subset_cons _ _) theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ := disjoint_of_subset_right (list.subset_cons _ _) @[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_append_right {l₁ l₂ l : list α} : disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} : disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ := (@disjoint_append_left _ [a] l₁ l₂).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₁ l := (disjoint_append_left.1 d).1 theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) : disjoint l₂ l := (disjoint_append_left.1 d).2 theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₁ := (disjoint_append_right.1 d).1 theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) : disjoint l l₂ := (disjoint_append_right.1 d).2 end disjoint /- union -/ section union variable [decidable_eq α] @[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl @[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl @[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ := by induction l₁; simp [*, or_assoc] theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inl h) theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ := mem_union.2 (or.inr h) theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂ | [] l₂ := ⟨[], by refl, rfl⟩ | (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in by simp [e.symm]; by_cases h : a ∈ t ++ l₂; [existsi t, existsi a::t]; simp [h]; [apply sublist_cons_of_sublist _ s, apply cons_sublist_cons _ s] theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ := (sublist_suffix_of_union l₁ l₂).imp (λ a, and.right) theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in e ▸ (append_sublist_append_right _).2 s theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp [or_imp_distrib, forall_and_distrib] theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x := (forall_mem_union.1 h).1 theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α} (h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x := (forall_mem_union.1 h).2 end union /- inter -/ section inter variable [decidable_eq α] @[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl @[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : (a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) := if_pos h @[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) : (a::l₁) ∩ l₂ = l₁ ∩ l₂ := if_neg h theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ := mem_of_mem_filter theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ := of_mem_filter theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ := mem_filter_of_mem @[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ := mem_filter theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ := filter_subset _ theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ := λ a, mem_of_mem_inter_right theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ := λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩ theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ := by simp [eq_nil_iff_forall_not_mem]; refl theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x) (l₂ : list α) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_left) h theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α} (h : ∀ x ∈ l₂, p x) : ∀ x, x ∈ l₁ ∩ l₂ → p x := ball.imp_left (λ x, mem_of_mem_inter_right) h end inter /- bag_inter -/ section bag_inter variable [decidable_eq α] @[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] := by cases l; refl @[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] := by cases l; refl @[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) : (a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) := by cases l₂; exact if_pos h @[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) : (a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ := by cases l₂; simp [h, list.bag_inter] theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ | [] l₂ := by simp | (b::l₁) l₂ := by by_cases b ∈ l₂; simp [*, and_or_distrib_left]; by_cases ba : a = b; simp * theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁ | [] l₂ := by simp [nil_sublist] | (b::l₁) l₂ := begin by_cases b ∈ l₂; simp [h], { apply cons_sublist_cons, apply bag_inter_sublist_left }, { apply sublist_cons_of_sublist, apply bag_inter_sublist_left } end end bag_inter /- pairwise relation (generalized no duplicate) -/ section pairwise variable (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) attribute [simp] pairwise.nil run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pariwise_iff variable {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; simp * theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; simp [*, or_imp_distrib, forall_and_distrib, and_assoc, and.left_comm] theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp | (b::l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp, by simp *; rw this theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp, induction l with a l IH; simp, cases e : f a with b; simp [e, IH], rw [filter_map_cons_some _ _ _ e], simp [IH], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, simp end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp [pairwise_append, IH, this], simp [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [simp, simpa [pairwise_append, IH] using h] theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp; exact λ i j h, (not_lt_zero j).elim h | (a::l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (not_lt_zero _).elim h₂}, cases i with i, { apply H.1, simp [nth_le_mem] }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ (pairwise.nil _) := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp [pairwise_append, pairwise_map], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this variable [decidable_rel R] instance decidable_pairwise (l : list α) : decidable (pairwise R l) := by induction l; simp; resetI; apply_instance /- pairwise reduct -/ /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function, and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 5, 6] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := subset_of_sublist (pw_filter_sublist _) theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {simp}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH; simp *, by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp [pw_filter_cons_of_pos h], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end pairwise /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. `chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d` -/ inductive chain : α → list α → Prop | nil (a : α) : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) attribute [simp] chain.nil run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := by induction p with _ a b l r p IH; constructor; [exact H _ _ r, exact IH] theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {S : α → α → Prop} {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp [*, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp * theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a; simp, simp at r, simp [r], show chain R b l, from IH r' end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {simp}, apply IH.cons _, simp [r], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp; resetI; apply_instance end chain /- no duplicates predicate -/ /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) section nodup @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_nil : @nodup α [] := pairwise.nil _ @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp [nodup] lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp | _ _ (forall₂.cons hab h) := by simpa using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin induction l with a l IH; intro h, {simp}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp [nodup_append, and.left_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp [nodup_append, not_or_distrib, and.left_comm, and_assoc] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) := nodup_map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup_of_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp [nodup, eq_comm] instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH; simp [list.erase, list.filter], by_cases b = a; simp *, subst b, show l = filter (λ a', ¬ a' = a) l, rw filter_eq_self.2, simpa only [eq_comm] using m end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [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_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp [nodup, pairwise_join, disjoint_left.symm] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, by simp] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂, d₁.imp (λ a₁ a₂ n x, suffices ∀ (b₁ : β), b₁ ∈ l₂ → (a₁, b₁) = x → ∀ (b₂ : β), b₂ ∈ l₂ → (a₂, b₂) ≠ x, by simpa, λ b₁ mb₁ e b₂ mb₂ e', by subst e'; injection e; contradiction)⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), d₁.imp (λ a₁ a₂ n x, suffices ∀ (b₁ : σ a₁), sigma.mk a₁ b₁ = x → b₁ ∈ l₂ a₁ → ∀ (b₂ : σ a₂), sigma.mk a₂ b₂ = x → b₂ ∉ l₂ a₂, by simpa [and_comm], λ b₁ e mb₁ b₂ e' mb₂, by subst e'; injection e; contradiction)⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by simp; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := by by_cases h' : a ∈ l; simp [h', h]; apply nodup_cons h' h theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, simp, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] end nodup /- erase duplicates function -/ section erase_dup variable [decidable_eq α] /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). erase_dup [1, 2, 2, 0, 1] = [1, 2, 0] -/ def erase_dup : list α → list α := pw_filter (≠) @[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) : erase_dup (a::l) = erase_dup l := pw_filter_cons_of_neg $ by simpa using h theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) : erase_dup (a::l) = a :: erase_dup l := pw_filter_cons_of_pos $ by simpa using h @[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l := by simpa using not_congr (@forall_mem_pw_filter α (≠) _ (λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l) @[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) : erase_dup (a::l) = erase_dup l := erase_dup_cons_of_mem' $ mem_erase_dup.2 h @[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) : erase_dup (a::l) = a :: erase_dup l := erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l := λ a, mem_erase_dup.2 theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self @[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l := pw_filter_idempotent theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ := begin induction l₁ with a l₁ IH; simp, rw ← IH, show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)), by_cases a ∈ erase_dup (l₁ ++ l₂); [ rw [erase_dup_cons_of_mem' h, insert_of_mem h], rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]] end end erase_dup /- iota and range -/ /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n @[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n | s 0 := rfl | s (n+1) := congr_arg succ (length_range' _ _) @[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n | s 0 := by simp | s (n+1) := have m = s → m < s + (n + 1), from λ e, e ▸ lt_succ_of_le (le_add_right _ _), have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m, by simpa [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm, by simp [@mem_range' (s+1) n, or_and_distrib_left, or_iff_right_of_imp this, l] theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n | s 0 := rfl | s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n) theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil _ _ | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil _ | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa using length_le_of_sublist h, λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩ theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n := ⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $ (mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2, λ h, subset_of_sublist (range'_sublist_right.2 h)⟩ theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m) | s 0 (n+1) _ := by simp | s (m+1) (n+1) h := by simp [nth_range' (s+1) (lt_of_add_lt_add_right h)] theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] := by rw add_comm n 1; exact (range'_append s n 1).symm theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s) | 0 n := rfl | (s+1) n := by rw [show n+(s+1) = n+1+s, by simp]; exact range_core_range' s (n+1) theorem range_eq_range' (n : ℕ) : range n = range' 0 n := (range_core_range' n 0).trans $ by rw zero_add theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) := by rw [range_eq_range', range_eq_range', range', add_comm, ← map_add_range']; congr; exact funext one_add theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) := by rw [range_eq_range', map_add_range']; refl @[simp] theorem length_range (n : ℕ) : length (range n) = n := by simp [range_eq_range'] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp [range_eq_range', zero_le] @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := mt mem_range.1 $ lt_irrefl _ theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m := by simp [range_eq_range', nth_range' _ h] theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] := by simp [range_eq_range', range'_concat] theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp [iota, range'_concat, iota_eq_reverse_range' n] @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp [iota_eq_reverse_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp [iota_eq_reverse_range', pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp [iota_eq_reverse_range', nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp [iota_eq_reverse_range', lt_succ_iff] theorem reverse_range' : ∀ s n : ℕ, reverse (range' s n) = map (λ i, s + n - 1 - i) (range n) | s 0 := rfl | s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map]; simpa [show s + (n + 1) - 1 = s + n, from rfl, (∘), λ a i, show a - 1 - i = a - succ i, by rw [nat.sub_sub, add_comm]; refl] using reverse_range' s n @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp [enum, range_eq_range'] end list theorem option.to_list_nodup {α} (o : option α) : o.to_list.nodup := by cases o; simp [option.to_list]
644667384e2d634e30e1e4c5d1ad2ae0acc08122
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/glue_data.lean
94b388c7c0448bb3d444ba865f9387317f265d50
[ "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
12,673
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import tactic.elementwise import category_theory.limits.shapes.multiequalizer import category_theory.limits.constructions.epi_mono import category_theory.limits.preserves.limits import category_theory.limits.shapes.types /-! # Gluing data > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define `glue_data` as a family of data needed to glue topological spaces, schemes, etc. We provide the API to realize it as a multispan diagram, and also states lemmas about its interaction with a functor that preserves certain pullbacks. -/ noncomputable theory open category_theory.limits namespace category_theory universes v u₁ u₂ variables (C : Type u₁) [category.{v} C] {C' : Type u₂} [category.{v} C'] /-- A gluing datum consists of 1. An index type `J` 2. An object `U i` for each `i : J`. 3. An object `V i j` for each `i j : J`. 4. A monomorphism `f i j : V i j ⟶ U i` for each `i j : J`. 5. A transition map `t i j : V i j ⟶ V j i` for each `i j : J`. such that 6. `f i i` is an isomorphism. 7. `t i i` is the identity. 8. The pullback for `f i j` and `f i k` exists. 9. `V i j ×[U i] V i k ⟶ V i j ⟶ V j i` factors through `V j k ×[U j] V j i ⟶ V j i` via some `t' : V i j ×[U i] V i k ⟶ V j k ×[U j] V j i`. 10. `t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _`. -/ @[nolint has_nonempty_instance] structure glue_data := (J : Type v) (U : J → C) (V : J × J → C) (f : Π i j, V (i, j) ⟶ U i) (f_mono : ∀ i j, mono (f i j) . tactic.apply_instance) (f_has_pullback : ∀ i j k, has_pullback (f i j) (f i k) . tactic.apply_instance) (f_id : ∀ i, is_iso (f i i) . tactic.apply_instance) (t : Π i j, V (i, j) ⟶ V (j, i)) (t_id : ∀ i, t i i = 𝟙 _) (t' : Π i j k, pullback (f i j) (f i k) ⟶ pullback (f j k) (f j i)) (t_fac : ∀ i j k, t' i j k ≫ pullback.snd = pullback.fst ≫ t i j) (cocycle : ∀ i j k , t' i j k ≫ t' j k i ≫ t' k i j = 𝟙 _) attribute [simp] glue_data.t_id attribute [instance] glue_data.f_id glue_data.f_mono glue_data.f_has_pullback attribute [reassoc] glue_data.t_fac glue_data.cocycle namespace glue_data variables {C} (D : glue_data C) @[simp] lemma t'_iij (i j : D.J) : D.t' i i j = (pullback_symmetry _ _).hom := begin have eq₁ := D.t_fac i i j, have eq₂ := (is_iso.eq_comp_inv (D.f i i)).mpr (@pullback.condition _ _ _ _ _ _ (D.f i j) _), rw [D.t_id, category.comp_id, eq₂] at eq₁, have eq₃ := (is_iso.eq_comp_inv (D.f i i)).mp eq₁, rw [category.assoc, ←pullback.condition, ←category.assoc] at eq₃, exact mono.right_cancellation _ _ ((mono.right_cancellation _ _ eq₃).trans (pullback_symmetry_hom_comp_fst _ _).symm) end lemma t'_jii (i j : D.J) : D.t' j i i = pullback.fst ≫ D.t j i ≫ inv pullback.snd := by { rw [←category.assoc, ←D.t_fac], simp } lemma t'_iji (i j : D.J) : D.t' i j i = pullback.fst ≫ D.t i j ≫ inv pullback.snd := by { rw [←category.assoc, ←D.t_fac], simp } @[simp, reassoc, elementwise] lemma t_inv (i j : D.J) : D.t i j ≫ D.t j i = 𝟙 _ := begin have eq : (pullback_symmetry (D.f i i) (D.f i j)).hom = pullback.snd ≫ inv pullback.fst, { simp }, have := D.cocycle i j i, rw [D.t'_iij, D.t'_jii, D.t'_iji, fst_eq_snd_of_mono_eq, eq] at this, simp only [category.assoc, is_iso.inv_hom_id_assoc] at this, rw [←is_iso.eq_inv_comp, ←category.assoc, is_iso.comp_inv_eq] at this, simpa using this, end lemma t'_inv (i j k : D.J) : D.t' i j k ≫ (pullback_symmetry _ _).hom ≫ D.t' j i k ≫ (pullback_symmetry _ _).hom = 𝟙 _ := begin rw ← cancel_mono (pullback.fst : pullback (D.f i j) (D.f i k) ⟶ _), simp [t_fac, t_fac_assoc] end instance t_is_iso (i j : D.J) : is_iso (D.t i j) := ⟨⟨D.t j i, D.t_inv _ _, D.t_inv _ _⟩⟩ instance t'_is_iso (i j k : D.J) : is_iso (D.t' i j k) := ⟨⟨D.t' j k i ≫ D.t' k i j, D.cocycle _ _ _, (by simpa using D.cocycle _ _ _)⟩⟩ @[reassoc] lemma t'_comp_eq_pullback_symmetry (i j k : D.J) : D.t' j k i ≫ D.t' k i j = (pullback_symmetry _ _).hom ≫ D.t' j i k ≫ (pullback_symmetry _ _).hom := begin transitivity inv (D.t' i j k), { exact is_iso.eq_inv_of_hom_inv_id (D.cocycle _ _ _) }, { rw ← cancel_mono (pullback.fst : pullback (D.f i j) (D.f i k) ⟶ _), simp [t_fac, t_fac_assoc] } end /-- (Implementation) The disjoint union of `U i`. -/ def sigma_opens [has_coproduct D.U] : C := ∐ D.U /-- (Implementation) The diagram to take colimit of. -/ def diagram : multispan_index C := { L := D.J × D.J, R := D.J, fst_from := _root_.prod.fst, snd_from := _root_.prod.snd, left := D.V, right := D.U, fst := λ ⟨i, j⟩, D.f i j, snd := λ ⟨i, j⟩, D.t i j ≫ D.f j i } @[simp] lemma diagram_L : D.diagram.L = (D.J × D.J) := rfl @[simp] lemma diagram_R : D.diagram.R = D.J := rfl @[simp] lemma diagram_fst_from (i j : D.J) : D.diagram.fst_from ⟨i, j⟩ = i := rfl @[simp] lemma diagram_snd_from (i j : D.J) : D.diagram.snd_from ⟨i, j⟩ = j := rfl @[simp] lemma diagram_fst (i j : D.J) : D.diagram.fst ⟨i, j⟩ = D.f i j := rfl @[simp] lemma diagram_snd (i j : D.J) : D.diagram.snd ⟨i, j⟩ = D.t i j ≫ D.f j i := rfl @[simp] lemma diagram_left : D.diagram.left = D.V := rfl @[simp] lemma diagram_right : D.diagram.right = D.U := rfl section variable [has_multicoequalizer D.diagram] /-- The glued object given a family of gluing data. -/ def glued : C := multicoequalizer D.diagram /-- The map `D.U i ⟶ D.glued` for each `i`. -/ def ι (i : D.J) : D.U i ⟶ D.glued := multicoequalizer.π D.diagram i @[simp, elementwise] lemma glue_condition (i j : D.J) : D.t i j ≫ D.f j i ≫ D.ι j = D.f i j ≫ D.ι i := (category.assoc _ _ _).symm.trans (multicoequalizer.condition D.diagram ⟨i, j⟩).symm /-- The pullback cone spanned by `V i j ⟶ U i` and `V i j ⟶ U j`. This will often be a pullback diagram. -/ def V_pullback_cone (i j : D.J) : pullback_cone (D.ι i) (D.ι j) := pullback_cone.mk (D.f i j) (D.t i j ≫ D.f j i) (by simp) variables [has_colimits C] /-- The projection `∐ D.U ⟶ D.glued` given by the colimit. -/ def π : D.sigma_opens ⟶ D.glued := multicoequalizer.sigma_π D.diagram instance π_epi : epi D.π := by { unfold π, apply_instance } end lemma types_π_surjective (D : glue_data Type*) : function.surjective D.π := (epi_iff_surjective _).mp infer_instance lemma types_ι_jointly_surjective (D : glue_data Type*) (x : D.glued) : ∃ i (y : D.U i), D.ι i y = x := begin delta category_theory.glue_data.ι, simp_rw ← multicoequalizer.ι_sigma_π D.diagram, rcases D.types_π_surjective x with ⟨x', rfl⟩, have := colimit.iso_colimit_cocone (types.coproduct_colimit_cocone _), rw ← (show (colimit.iso_colimit_cocone (types.coproduct_colimit_cocone _)).inv _ = x', from concrete_category.congr_hom ((colimit.iso_colimit_cocone (types.coproduct_colimit_cocone _)).hom_inv_id) x'), rcases (colimit.iso_colimit_cocone (types.coproduct_colimit_cocone _)).hom x' with ⟨i, y⟩, exact ⟨i, y, by { simpa [← multicoequalizer.ι_sigma_π, -multicoequalizer.ι_sigma_π] }⟩ end variables (F : C ⥤ C') [H : ∀ i j k, preserves_limit (cospan (D.f i j) (D.f i k)) F] include H instance (i j k : D.J) : has_pullback (F.map (D.f i j)) (F.map (D.f i k)) := ⟨⟨⟨_, is_limit_of_has_pullback_of_preserves_limit F (D.f i j) (D.f i k)⟩⟩⟩ /-- A functor that preserves the pullbacks of `f i j` and `f i k` can map a family of glue data. -/ @[simps] def map_glue_data : glue_data C' := { J := D.J, U := λ i, F.obj (D.U i), V := λ i, F.obj (D.V i), f := λ i j, F.map (D.f i j), f_mono := λ i j, preserves_mono_of_preserves_limit _ _, f_id := λ i, infer_instance, t := λ i j, F.map (D.t i j), t_id := λ i, by { rw D.t_id i, simp }, t' := λ i j k, (preserves_pullback.iso F (D.f i j) (D.f i k)).inv ≫ F.map (D.t' i j k) ≫ (preserves_pullback.iso F (D.f j k) (D.f j i)).hom, t_fac := λ i j k, by simpa [iso.inv_comp_eq] using congr_arg (λ f, F.map f) (D.t_fac i j k), cocycle := λ i j k, by simp only [category.assoc, iso.hom_inv_id_assoc, ← functor.map_comp_assoc, D.cocycle, iso.inv_hom_id, category_theory.functor.map_id, category.id_comp] } /-- The diagram of the image of a `glue_data` under a functor `F` is naturally isomorphic to the original diagram of the `glue_data` via `F`. -/ def diagram_iso : D.diagram.multispan ⋙ F ≅ (D.map_glue_data F).diagram.multispan := nat_iso.of_components (λ x, match x with | walking_multispan.left a := iso.refl _ | walking_multispan.right b := iso.refl _ end) (begin rintros (⟨_,_⟩|_) _ (_|_|_), { erw [category.comp_id, category.id_comp, functor.map_id], refl }, { erw [category.comp_id, category.id_comp], refl }, { erw [category.comp_id, category.id_comp, functor.map_comp], refl }, { erw [category.comp_id, category.id_comp, functor.map_id], refl }, end) @[simp] lemma diagram_iso_app_left (i : D.J × D.J) : (D.diagram_iso F).app (walking_multispan.left i) = iso.refl _ := rfl @[simp] lemma diagram_iso_app_right (i : D.J) : (D.diagram_iso F).app (walking_multispan.right i) = iso.refl _ := rfl @[simp] lemma diagram_iso_hom_app_left (i : D.J × D.J) : (D.diagram_iso F).hom.app (walking_multispan.left i) = 𝟙 _ := rfl @[simp] lemma diagram_iso_hom_app_right (i : D.J) : (D.diagram_iso F).hom.app (walking_multispan.right i) = 𝟙 _ := rfl @[simp] lemma diagram_iso_inv_app_left (i : D.J × D.J) : (D.diagram_iso F).inv.app (walking_multispan.left i) = 𝟙 _ := rfl @[simp] lemma diagram_iso_inv_app_right (i : D.J) : (D.diagram_iso F).inv.app (walking_multispan.right i) = 𝟙 _ := rfl variables [has_multicoequalizer D.diagram] [preserves_colimit D.diagram.multispan F] omit H lemma has_colimit_multispan_comp : has_colimit (D.diagram.multispan ⋙ F) := ⟨⟨⟨_,preserves_colimit.preserves (colimit.is_colimit _)⟩⟩⟩ include H local attribute [instance] has_colimit_multispan_comp lemma has_colimit_map_glue_data_diagram : has_multicoequalizer (D.map_glue_data F).diagram := has_colimit_of_iso (D.diagram_iso F).symm local attribute [instance] has_colimit_map_glue_data_diagram /-- If `F` preserves the gluing, we obtain an iso between the glued objects. -/ def glued_iso : F.obj D.glued ≅ (D.map_glue_data F).glued := preserves_colimit_iso F D.diagram.multispan ≪≫ (limits.has_colimit.iso_of_nat_iso (D.diagram_iso F)) @[simp, reassoc] lemma ι_glued_iso_hom (i : D.J) : F.map (D.ι i) ≫ (D.glued_iso F).hom = (D.map_glue_data F).ι i := by { erw ι_preserves_colimits_iso_hom_assoc, rw has_colimit.iso_of_nat_iso_ι_hom, erw category.id_comp, refl } @[simp, reassoc] lemma ι_glued_iso_inv (i : D.J) : (D.map_glue_data F).ι i ≫ (D.glued_iso F).inv = F.map (D.ι i) := by rw [iso.comp_inv_eq, ι_glued_iso_hom] /-- If `F` preserves the gluing, and reflects the pullback of `U i ⟶ glued` and `U j ⟶ glued`, then `F` reflects the fact that `V_pullback_cone` is a pullback. -/ def V_pullback_cone_is_limit_of_map (i j : D.J) [reflects_limit (cospan (D.ι i) (D.ι j)) F] (hc : is_limit ((D.map_glue_data F).V_pullback_cone i j)) : is_limit (D.V_pullback_cone i j) := begin apply is_limit_of_reflects F, apply (is_limit_map_cone_pullback_cone_equiv _ _).symm _, let e : cospan (F.map (D.ι i)) (F.map (D.ι j)) ≅ cospan ((D.map_glue_data F).ι i) ((D.map_glue_data F).ι j), exact nat_iso.of_components (λ x, by { cases x, exacts [D.glued_iso F, iso.refl _] }) (by rintros (_|_) (_|_) (_|_|_); simp), apply is_limit.postcompose_hom_equiv e _ _, apply hc.of_iso_limit, refine cones.ext (iso.refl _) _, { rintro (_|_|_), change _ = _ ≫ (_ ≫ _) ≫ _, all_goals { change _ = 𝟙 _ ≫ _ ≫ _, simpa } } end omit H /-- If there is a forgetful functor into `Type` that preserves enough (co)limits, then `D.ι` will be jointly surjective. -/ lemma ι_jointly_surjective (F : C ⥤ Type v) [preserves_colimit D.diagram.multispan F] [Π (i j k : D.J), preserves_limit (cospan (D.f i j) (D.f i k)) F] (x : F.obj (D.glued)) : ∃ i (y : F.obj (D.U i)), F.map (D.ι i) y = x := begin let e := D.glued_iso F, obtain ⟨i, y, eq⟩ := (D.map_glue_data F).types_ι_jointly_surjective (e.hom x), replace eq := congr_arg e.inv eq, change ((D.map_glue_data F).ι i ≫ e.inv) y = (e.hom ≫ e.inv) x at eq, rw [e.hom_inv_id, D.ι_glued_iso_inv] at eq, exact ⟨i, y, eq⟩ end end glue_data end category_theory
25067ca8a3eff26424ba55004ea39dca1ccd4998
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/homotopy/interval.hlean
05bb96132c8345d97b64af2cd21a5406e9493439
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
3,398
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the interval -/ import .susp types.eq types.prod cubical.square open eq susp unit equiv equiv.ops is_trunc nat prod definition interval : Type₀ := susp unit namespace interval definition zero : interval := north definition one : interval := south definition seg : zero = one := merid star protected definition rec {P : interval → Type} (P0 : P zero) (P1 : P one) (Ps : P0 =[seg] P1) (x : interval) : P x := begin fapply susp.rec_on x, { exact P0}, { exact P1}, { intro x, cases x, exact Ps} end protected definition rec_on [reducible] {P : interval → Type} (x : interval) (P0 : P zero) (P1 : P one) (Ps : P0 =[seg] P1) : P x := interval.rec P0 P1 Ps x theorem rec_seg {P : interval → Type} (P0 : P zero) (P1 : P one) (Ps : P0 =[seg] P1) : apdo (interval.rec P0 P1 Ps) seg = Ps := !rec_merid protected definition elim {P : Type} (P0 P1 : P) (Ps : P0 = P1) (x : interval) : P := interval.rec P0 P1 (pathover_of_eq Ps) x protected definition elim_on [reducible] {P : Type} (x : interval) (P0 P1 : P) (Ps : P0 = P1) : P := interval.elim P0 P1 Ps x theorem elim_seg {P : Type} (P0 P1 : P) (Ps : P0 = P1) : ap (interval.elim P0 P1 Ps) seg = Ps := begin apply eq_of_fn_eq_fn_inv !(pathover_constant seg), rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑interval.elim,rec_seg], end protected definition elim_type (P0 P1 : Type) (Ps : P0 ≃ P1) (x : interval) : Type := interval.elim P0 P1 (ua Ps) x protected definition elim_type_on [reducible] (x : interval) (P0 P1 : Type) (Ps : P0 ≃ P1) : Type := interval.elim_type P0 P1 Ps x theorem elim_type_seg (P0 P1 : Type) (Ps : P0 ≃ P1) : transport (interval.elim_type P0 P1 Ps) seg = Ps := by rewrite [tr_eq_cast_ap_fn,↑interval.elim_type,elim_seg];apply cast_ua_fn definition is_contr_interval [instance] [priority 900] : is_contr interval := is_contr.mk zero (λx, interval.rec_on x idp seg !pathover_eq_r_idp) open is_equiv equiv definition naive_funext_of_interval : naive_funext := λA P f g p, ap (λ(i : interval) (x : A), interval.elim_on i (f x) (g x) (p x)) seg end interval open interval definition cube : ℕ → Type₀ | cube 0 := unit | cube (succ n) := cube n × interval abbreviation square := cube (succ (succ nat.zero)) definition cube_one_equiv_interval : cube 1 ≃ interval := !prod_comm_equiv ⬝e !prod_unit_equiv definition prod_square {A B : Type} {a a' : A} {b b' : B} (p : a = a') (q : b = b') : square (pair_eq p idp) (pair_eq p idp) (pair_eq idp q) (pair_eq idp q) := by cases p; cases q; exact ids namespace square definition tl : square := (star, zero, zero) definition tr : square := (star, one, zero) definition bl : square := (star, zero, one ) definition br : square := (star, one, one ) -- s stands for "square" in the following definitions definition st : tl = tr := pair_eq (pair_eq idp seg) idp definition sb : bl = br := pair_eq (pair_eq idp seg) idp definition sl : tl = bl := pair_eq idp seg definition sr : tr = br := pair_eq idp seg definition sfill : square st sb sl sr := !prod_square definition fill : st ⬝ sr = sl ⬝ sb := !square_equiv_eq sfill end square
2b1bb42f79c60fee2ae2f1026c220c0e27907331
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/analysis/normed_space/real_inner_product.lean
875e8e789e1cf535b09ef9e5ccc3699ff27e43c9
[ "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
22,029
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 algebra.quadratic_discriminant import analysis.special_functions.pow import tactic.monotonicity /-! # Inner Product Space This file defines real inner product space and proves its basic properties. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. ## Main statements Existence of orthogonal projection onto nonempty complete subspace: Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. The point `v` is usually called the orthogonal projection of `u` onto `K`. ## Implementation notes We decide to develop the theory of real inner product spaces and that of complex inner product spaces separately. ## Tags inner product space, norm, orthogonal projection ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open real set open_locale topological_space universes u v w variables {α : Type u} {F : Type v} {G : Type w} class has_inner (α : Type*) := (inner : α → α → ℝ) export has_inner (inner) section prio set_option default_priority 100 -- see Note [default priority] -- see Note[vector space definition] for why we extend `module`. /-- An inner product space is a real vector space with an additional operation called inner product. Inner product spaces over complex vector space will be defined in another file. -/ class inner_product_space (α : Type*) extends add_comm_group α, module ℝ α, has_inner α := (comm : ∀ x y, inner x y = inner y x) (nonneg : ∀ x, 0 ≤ inner x x) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = r * inner x y) end prio variables [inner_product_space α] section basic_properties lemma inner_comm (x y : α) : inner x y = inner y x := inner_product_space.comm x y lemma inner_self_nonneg {x : α} : 0 ≤ inner x x := inner_product_space.nonneg _ lemma inner_add_left {x y z : α} : inner (x + y) z = inner x z + inner y z := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : α} : inner x (y + z) = inner x y + inner x z := by { rw [inner_comm, inner_add_left], simp [inner_comm] } lemma inner_smul_left {x y : α} {r : ℝ} : inner (r • x) y = r * inner x y := inner_product_space.smul_left _ _ _ lemma inner_smul_right {x y : α} {r : ℝ} : inner x (r • y) = r * inner x y := by { rw [inner_comm, inner_smul_left, inner_comm] } @[simp] lemma inner_zero_left {x : α} : inner 0 x = 0 := by { rw [← zero_smul ℝ (0:α), inner_smul_left, zero_mul] } @[simp] lemma inner_zero_right {x : α} : inner x 0 = 0 := by { rw [inner_comm, inner_zero_left] } lemma inner_self_eq_zero (x : α) : inner x x = 0 ↔ x = 0 := iff.intro (inner_product_space.definite _) (by { rintro rfl, exact inner_zero_left }) @[simp] lemma inner_neg_left {x y : α} : inner (-x) y = -inner x y := by { rw [← neg_one_smul ℝ x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : α} : inner x (-y) = -inner x y := by { rw [inner_comm, inner_neg_left, inner_comm] } @[simp] lemma inner_neg_neg {x y : α} : inner (-x) (-y) = inner x y := by simp lemma inner_sub_left {x y z : α} : inner (x - y) z = inner x z - inner y z := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : α} : inner x (y - z) = inner x y - inner x z := by { simp [sub_eq_add_neg, inner_add_right] } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : α} : inner (x + y) (x + y) = inner x x + 2 * inner x y + inner y y := by simpa [inner_add_left, inner_add_right, two_mul, add_assoc] using inner_comm _ _ /-- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : α} : inner (x - y) (x - y) = inner x x - 2 * inner x y + inner y y := begin simp only [inner_sub_left, inner_sub_right, two_mul], simpa [sub_eq_add_neg, add_comm, add_left_comm] using inner_comm _ _ end /-- Parallelogram law -/ lemma parallelogram_law {x y : α} : inner (x + y) (x + y) + inner (x - y) (x - y) = 2 * (inner x x + inner y y) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality -/ lemma inner_mul_inner_self_le (x y : α) : inner x y * inner x y ≤ inner x x * inner y y := begin have : ∀ t, 0 ≤ inner y y * t * t + 2 * inner x y * t + inner x x, from assume t, calc 0 ≤ inner (x+t•y) (x+t•y) : inner_self_nonneg ... = inner y y * t * t + 2 * inner x y * t + inner x x : by { simp only [inner_add_add_self, inner_smul_right, inner_smul_left], ring }, have := discriminant_le_zero this, rw discrim at this, have h : (2 * inner x y)^2 - 4 * inner y y * inner x x = 4 * (inner x y * inner x y - inner x x * inner y y) := by ring, rw h at this, linarith end end basic_properties section norm /-- An inner product naturally induces a norm. -/ @[priority 100] -- see Note [lower instance priority] instance inner_product_space_has_norm : has_norm α := ⟨λx, sqrt (inner x x)⟩ lemma norm_eq_sqrt_inner {x : α} : ∥x∥ = sqrt (inner x x) := rfl lemma inner_self_eq_norm_square (x : α) : inner x x = ∥x∥ * ∥x∥ := (mul_self_sqrt inner_self_nonneg).symm /-- Expand the square -/ lemma norm_add_pow_two {x y : α} : ∥x + y∥^2 = ∥x∥^2 + 2 * inner x y + ∥y∥^2 := by { repeat {rw [pow_two, ← inner_self_eq_norm_square]}, exact inner_add_add_self } /-- Same lemma as above but in a different form -/ lemma norm_add_mul_self {x y : α} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * inner x y + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_add_pow_two } /-- Expand the square -/ lemma norm_sub_pow_two {x y : α} : ∥x - y∥^2 = ∥x∥^2 - 2 * inner x y + ∥y∥^2 := by { repeat {rw [pow_two, ← inner_self_eq_norm_square]}, exact inner_sub_sub_self } /-- Same lemma as above but in a different form -/ lemma norm_sub_mul_self {x y : α} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * inner x y + ∥y∥ * ∥y∥ := by { repeat {rw [← pow_two]}, exact norm_sub_pow_two } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : α) : abs (inner x y) ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_squares_le (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin rw abs_mul_abs_self, have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = inner x x * inner y y, simp only [inner_self_eq_norm_square], ring, rw this, exact inner_mul_inner_self_le _ _ end lemma parallelogram_law_with_norm {x y : α} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { simp only [(inner_self_eq_norm_square _).symm], exact parallelogram_law } /-- An inner product space forms a normed group w.r.t. its associated norm. -/ @[priority 100] -- see Note [lower instance priority] instance inner_product_space_is_normed_group : normed_group α := normed_group.of_core α { norm_eq_zero_iff := assume x, iff.intro (λ h : sqrt (inner x x) = 0, (inner_self_eq_zero x).1 $ (sqrt_eq_zero inner_self_nonneg).1 h ) (by {rintro rfl, show sqrt (inner (0:α) 0) = 0, simp }), triangle := assume x y, begin have := calc ∥x + y∥ * ∥x + y∥ = inner (x + y) (x + y) : (inner_self_eq_norm_square _).symm ... = inner x x + 2 * inner x y + inner y y : inner_add_add_self ... ≤ inner x x + 2 * (∥x∥ * ∥y∥) + inner y y : by linarith [abs_inner_le_norm x y, le_abs_self (inner x y)] ... = (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥) : by { simp only [inner_self_eq_norm_square], ring }, exact nonneg_le_nonneg_of_squares_le (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λx, show sqrt (inner (-x) (-x)) = sqrt (inner x x), by simp } /-- An inner product space forms a normed space over reals w.r.t. its associated norm. -/ instance inner_product_space_is_normed_space : normed_space ℝ α := { norm_smul_le := assume r x, le_of_eq $ begin rw [norm_eq_sqrt_inner, sqrt_eq_iff_mul_self_eq, inner_smul_left, inner_smul_right, inner_self_eq_norm_square], exact calc abs(r) * ∥x∥ * (abs(r) * ∥x∥) = (abs(r) * abs(r)) * (∥x∥ * ∥x∥) : by ring ... = r * (r * (∥x∥ * ∥x∥)) : by { rw abs_mul_abs_self, ring }, exact inner_self_nonneg, exact mul_nonneg (abs_nonneg _) (sqrt_nonneg _) end } end norm section orthogonal open filter /-- Existence of minimizers Let `u` be a point in an inner product space, and let `K` be a nonempty complete convex subset. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. -/ -- FIXME this monolithic proof causes a deterministic timeout with `-T50000` -- It should be broken in a sequence of more manageable pieces, -- perhaps with individual statements for the three steps below. theorem exists_norm_eq_infi_of_complete_convex {K : set α} (ne : K.nonempty) (h₁ : is_complete K) (h₂ : convex K) : ∀ u : α, ∃ v ∈ K, ∥u - v∥ = ⨅ w : K, ∥u - w∥ := assume u, begin let δ := ⨅ w : K, ∥u - w∥, letI : nonempty K := ne.to_subtype, have zero_le_δ : 0 ≤ δ := le_cinfi (λ _, norm_nonneg _), have δ_le : ∀ w : K, δ ≤ ∥u - w∥, from cinfi_le ⟨0, forall_range_iff.2 $ λ _, norm_nonneg _⟩, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, -- Step 1: since `δ` is the infimum, can find a sequence `w : ℕ → K` in `K` -- such that `∥u - w n∥ < δ + 1 / (n + 1)` (which implies `∥u - w n∥ --> δ`); -- maybe this should be a separate lemma have exists_seq : ∃ w : ℕ → K, ∀ n, ∥u - w n∥ < δ + 1 / (n + 1), { have hδ : ∀n:ℕ, δ < δ + 1 / (n + 1), from λ n, lt_add_of_le_of_pos (le_refl _) nat.one_div_pos_of_nat, have h := λ n, exists_lt_of_cinfi_lt (hδ n), let w : ℕ → K := λ n, classical.some (h n), exact ⟨w, λ n, classical.some_spec (h n)⟩ }, rcases exists_seq with ⟨w, hw⟩, have norm_tendsto : tendsto (λ n, ∥u - w n∥) at_top (𝓝 δ), { have h : tendsto (λ n:ℕ, δ) at_top (𝓝 δ) := tendsto_const_nhds, have h' : tendsto (λ n:ℕ, δ + 1 / (n + 1)) at_top (𝓝 δ), { convert h.add tendsto_one_div_add_at_top_nhds_0_nat, simp only [add_zero] }, exact tendsto_of_tendsto_of_tendsto_of_le_of_le h h' (λ x, δ_le _) (λ x, le_of_lt (hw _)) }, -- Step 2: Prove that the sequence `w : ℕ → K` is a Cauchy sequence have seq_is_cauchy : cauchy_seq (λ n, ((w n):α)), { rw cauchy_seq_iff_le_tendsto_0, -- splits into three goals let b := λ n:ℕ, (8 * δ * (1/(n+1)) + 4 * (1/(n+1)) * (1/(n+1))), use (λn, sqrt (b n)), split, -- first goal : `∀ (n : ℕ), 0 ≤ sqrt (b n)` assume n, exact sqrt_nonneg _, split, -- second goal : `∀ (n m N : ℕ), N ≤ n → N ≤ m → dist ↑(w n) ↑(w m) ≤ sqrt (b N)` assume p q N hp hq, let wp := ((w p):α), let wq := ((w q):α), let a := u - wq, let b := u - wp, let half := 1 / (2:ℝ), let div := 1 / ((N:ℝ) + 1), have : 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) := calc 4 * ∥u - half•(wq + wp)∥ * ∥u - half•(wq + wp)∥ + ∥wp - wq∥ * ∥wp - wq∥ = (2*∥u - half•(wq + wp)∥) * (2 * ∥u - half•(wq + wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by ring ... = (abs((2:ℝ)) * ∥u - half•(wq + wp)∥) * (abs((2:ℝ)) * ∥u - half•(wq+wp)∥) + ∥wp-wq∥*∥wp-wq∥ : by { rw abs_of_nonneg, exact add_nonneg zero_le_one zero_le_one } ... = ∥(2:ℝ) • (u - half • (wq + wp))∥ * ∥(2:ℝ) • (u - half • (wq + wp))∥ + ∥wp-wq∥ * ∥wp-wq∥ : by { rw [norm_smul], refl } ... = ∥a + b∥ * ∥a + b∥ + ∥a - b∥ * ∥a - b∥ : begin rw [smul_sub, smul_smul, mul_one_div_cancel (two_ne_zero : (2 : ℝ) ≠ 0), ← one_add_one_eq_two, add_smul], simp only [one_smul], have eq₁ : wp - wq = a - b, show wp - wq = (u - wq) - (u - wp), abel, have eq₂ : u + u - (wq + wp) = a + b, show u + u - (wq + wp) = (u - wq) + (u - wp), abel, rw [eq₁, eq₂], end ... = 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) : parallelogram_law_with_norm, have eq : δ ≤ ∥u - half • (wq + wp)∥, { rw smul_add, apply δ_le', apply h₂, repeat {exact subtype.mem _}, repeat {exact le_of_lt one_half_pos}, exact add_halves 1 }, have eq₁ : 4 * δ * δ ≤ 4 * ∥u - half • (wq + wp)∥ * ∥u - half • (wq + wp)∥, { mono, mono, norm_num, apply mul_nonneg, norm_num, exact norm_nonneg _ }, have eq₂ : ∥a∥ * ∥a∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw q) (add_le_add_left (nat.one_div_le_one_div hq) _)), have eq₂' : ∥b∥ * ∥b∥ ≤ (δ + div) * (δ + div) := mul_self_le_mul_self (norm_nonneg _) (le_trans (le_of_lt $ hw p) (add_le_add_left (nat.one_div_le_one_div hp) _)), rw dist_eq_norm, apply nonneg_le_nonneg_of_squares_le, { exact sqrt_nonneg _ }, rw mul_self_sqrt, exact calc ∥wp - wq∥ * ∥wp - wq∥ = 2 * (∥a∥*∥a∥ + ∥b∥*∥b∥) - 4 * ∥u - half • (wq+wp)∥ * ∥u - half • (wq+wp)∥ : by { rw ← this, simp } ... ≤ 2 * (∥a∥ * ∥a∥ + ∥b∥ * ∥b∥) - 4 * δ * δ : sub_le_sub_left eq₁ _ ... ≤ 2 * ((δ + div) * (δ + div) + (δ + div) * (δ + div)) - 4 * δ * δ : sub_le_sub_right (mul_le_mul_of_nonneg_left (add_le_add eq₂ eq₂') (by norm_num)) _ ... = 8 * δ * div + 4 * div * div : by ring, exact add_nonneg (mul_nonneg (mul_nonneg (by norm_num) zero_le_δ) (le_of_lt nat.one_div_pos_of_nat)) (mul_nonneg (mul_nonneg (by norm_num) (le_of_lt nat.one_div_pos_of_nat)) (le_of_lt nat.one_div_pos_of_nat)), -- third goal : `tendsto (λ (n : ℕ), sqrt (b n)) at_top (𝓝 0)` apply tendsto.comp, { convert continuous_sqrt.continuous_at, exact sqrt_zero.symm }, have eq₁ : tendsto (λ (n : ℕ), 8 * δ * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (8 * δ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert (@tendsto_const_nhds _ _ _ (4:ℝ) _).mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, have eq₂ : tendsto (λ (n : ℕ), (4:ℝ) * (1 / (n + 1)) * (1 / (n + 1))) at_top (𝓝 (0:ℝ)), { convert this.mul tendsto_one_div_add_at_top_nhds_0_nat, simp only [mul_zero] }, convert eq₁.add eq₂, simp only [add_zero] }, -- Step 3: By completeness of `K`, let `w : ℕ → K` converge to some `v : K`. -- Prove that it satisfies all requirements. rcases cauchy_seq_tendsto_of_is_complete h₁ (λ n, _) seq_is_cauchy with ⟨v, hv, w_tendsto⟩, use v, use hv, have h_cont : continuous (λ v, ∥u - v∥) := continuous.comp continuous_norm (continuous.sub continuous_const continuous_id), have : tendsto (λ n, ∥u - w n∥) at_top (𝓝 ∥u - v∥), convert (tendsto.comp h_cont.continuous_at w_tendsto), exact tendsto_nhds_unique at_top_ne_bot this norm_tendsto, exact subtype.mem _ end /-- Characterization of minimizers in the above theorem -/ theorem norm_eq_infi_iff_inner_le_zero {K : set α} (h : convex K) {u : α} {v : α} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : K, ∥u - w∥) ↔ ∀ w ∈ K, inner (u - v) (w - v) ≤ 0 := iff.intro begin assume eq w hw, let δ := ⨅ w : K, ∥u - w∥, let p := inner (u - v) (w - v), let q := ∥w - v∥^2, letI : nonempty K := ⟨⟨v, hv⟩⟩, have zero_le_δ : 0 ≤ δ, apply le_cinfi, intro, exact norm_nonneg _, have δ_le : ∀ w : K, δ ≤ ∥u - w∥, assume w, apply cinfi_le, use (0:ℝ), rintros _ ⟨_, rfl⟩, exact norm_nonneg _, have δ_le' : ∀ w ∈ K, δ ≤ ∥u - w∥ := assume w hw, δ_le ⟨w, hw⟩, have : ∀θ:ℝ, 0 < θ → θ ≤ 1 → 2 * p ≤ θ * q, assume θ hθ₁ hθ₂, have : ∥u - v∥^2 ≤ ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 := calc ∥u - v∥^2 ≤ ∥u - (θ•w + (1-θ)•v)∥^2 : begin simp only [pow_two], apply mul_self_le_mul_self (norm_nonneg _), rw [eq], apply δ_le', apply h hw hv, exacts [le_of_lt hθ₁, sub_nonneg.2 hθ₂, add_sub_cancel'_right _ _], end ... = ∥(u - v) - θ • (w - v)∥^2 : begin have : u - (θ•w + (1-θ)•v) = (u - v) - θ • (w - v), { rw [smul_sub, sub_smul, one_smul], simp only [sub_eq_add_neg, add_comm, add_left_comm, add_assoc, neg_add_rev] }, rw this end ... = ∥u - v∥^2 - 2 * θ * inner (u - v) (w - v) + θ*θ*∥w - v∥^2 : begin rw [norm_sub_pow_two, inner_smul_right, norm_smul], simp only [pow_two], show ∥u-v∥*∥u-v∥-2*(θ*inner(u-v)(w-v))+abs(θ)*∥w-v∥*(abs(θ)*∥w-v∥)= ∥u-v∥*∥u-v∥-2*θ*inner(u-v)(w-v)+θ*θ*(∥w-v∥*∥w-v∥), rw abs_of_pos hθ₁, ring end, have eq₁ : ∥u-v∥^2-2*θ*inner(u-v)(w-v)+θ*θ*∥w-v∥^2=∥u-v∥^2+(θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)), abel, rw [eq₁, le_add_iff_nonneg_right] at this, have eq₂ : θ*θ*∥w-v∥^2-2*θ*inner(u-v)(w-v)=θ*(θ*∥w-v∥^2-2*inner(u-v)(w-v)), ring, rw eq₂ at this, have := le_of_sub_nonneg (nonneg_of_mul_nonneg_left this hθ₁), exact this, by_cases hq : q = 0, { rw hq at this, have : p ≤ 0, have := this (1:ℝ) (by norm_num) (by norm_num), linarith, exact this }, { have q_pos : 0 < q, apply lt_of_le_of_ne, exact pow_two_nonneg _, intro h, exact hq h.symm, by_contradiction hp, rw not_le at hp, let θ := min (1:ℝ) (p / q), have eq₁ : θ*q ≤ p := calc θ*q ≤ (p/q) * q : mul_le_mul_of_nonneg_right (min_le_right _ _) (pow_two_nonneg _) ... = p : div_mul_cancel _ hq, have : 2 * p ≤ p := calc 2 * p ≤ θ*q : by { refine this θ (lt_min (by norm_num) (div_pos hp q_pos)) (by norm_num) } ... ≤ p : eq₁, linarith } end begin assume h, letI : nonempty K := ⟨⟨v, hv⟩⟩, apply le_antisymm, { apply le_cinfi, assume w, apply nonneg_le_nonneg_of_squares_le (norm_nonneg _), have := h w w.2, exact calc ∥u - v∥ * ∥u - v∥ ≤ ∥u - v∥ * ∥u - v∥ - 2 * inner (u - v) ((w:α) - v) : by linarith ... ≤ ∥u - v∥^2 - 2 * inner (u - v) ((w:α) - v) + ∥(w:α) - v∥^2 : by { rw pow_two, refine le_add_of_nonneg_right _, exact pow_two_nonneg _ } ... = ∥(u - v) - (w - v)∥^2 : norm_sub_pow_two.symm ... = ∥u - w∥ * ∥u - w∥ : by { have : (u - v) - (w - v) = u - w, abel, rw [this, pow_two] } }, { show (⨅ (w : K), ∥u - w∥) ≤ (λw:K, ∥u - w∥) ⟨v, hv⟩, apply cinfi_le, use 0, rintros y ⟨z, rfl⟩, exact norm_nonneg _ } end /-- Existence of minimizers. Let `u` be a point in an inner product space, and let `K` be a nonempty complete subspace. Then there exists a unique `v` in `K` that minimizes the distance `∥u - v∥` to `u`. This point `v` is usually called the orthogonal projection of `u` onto `K`. -/ theorem exists_norm_eq_infi_of_complete_subspace (K : subspace ℝ α) (h : is_complete (↑K : set α)) : ∀ u : α, ∃ v ∈ K, ∥u - v∥ = ⨅ w : (↑K : set α), ∥u - w∥ := exists_norm_eq_infi_of_complete_convex ⟨0, K.zero⟩ h K.convex /-- Characterization of minimizers in the above theorem. Let `u` be a point in an inner product space, and let `K` be a nonempty subspace. Then point `v` minimizes the distance `∥u - v∥` if and only if for all `w ∈ K`, `inner (u - v) w = 0` (i.e., `u - v` is orthogonal to the subspace `K`) -/ theorem norm_eq_infi_iff_inner_eq_zero (K : subspace ℝ α) {u : α} {v : α} (hv : v ∈ K) : ∥u - v∥ = (⨅ w : (↑K : set α), ∥u - w∥) ↔ ∀ w ∈ K, inner (u - v) w = 0 := iff.intro begin assume h, have h : ∀ w ∈ K, inner (u - v) (w - v) ≤ 0, { rwa [norm_eq_infi_iff_inner_le_zero] at h, exacts [K.convex, hv] }, assume w hw, have le : inner (u - v) w ≤ 0, let w' := w + v, have : w' ∈ K := submodule.add_mem _ hw hv, have h₁ := h w' this, have h₂ : w' - v = w, simp only [add_neg_cancel_right, sub_eq_add_neg], rw h₂ at h₁, exact h₁, have ge : inner (u - v) w ≥ 0, let w'' := -w + v, have : w'' ∈ K := submodule.add_mem _ (submodule.neg_mem _ hw) hv, have h₁ := h w'' this, have h₂ : w'' - v = -w, simp only [neg_inj', add_neg_cancel_right, sub_eq_add_neg], rw [h₂, inner_neg_right] at h₁, linarith, exact le_antisymm le ge end begin assume h, have : ∀ w ∈ K, inner (u - v) (w - v) ≤ 0, assume w hw, let w' := w - v, have : w' ∈ K := submodule.sub_mem _ hw hv, have h₁ := h w' this, exact le_of_eq h₁, rwa norm_eq_infi_iff_inner_le_zero, exacts [submodule.convex _, hv] end end orthogonal
22923a25d6de53403f9c5b71838435009eeda7bc
fa01e273a2a9f22530e6adb1ed7d4f54bb15c8d7
/src/N2O/Data/Bytes.lean
8b3f6385e4d3d8648a6fa4b675395d48d0cbc719
[ "LicenseRef-scancode-mit-taylor-variant", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
o89/n2o
4c99afb11fff0a1e3dae6b3bc8a3b7fc42c314ac
58c1fbf4ef892ed86bdc6b78ec9ca5a403715c2d
refs/heads/master
1,670,314,676,229
1,669,086,375,000
1,669,086,375,000
200,506,953
16
6
null
null
null
null
UTF-8
Lean
false
false
816
lean
def UInt16.nthByte (x : UInt16) (n : Nat) : UInt8 := (UInt16.land (x.shiftRight $ 8 * UInt16.ofNat n) 255).toUInt8 def UInt32.nthByte (x : UInt32) (n : Nat) : UInt8 := (UInt32.land (x.shiftRight $ 8 * UInt32.ofNat n) 255).toUInt8 def iotaZero : Nat → List Nat | 0 => [0] | n + 1 => (n + 1) :: iotaZero n def UInt16.toBytes (x : UInt16) : ByteArray := List.toByteArray (List.map (UInt16.nthByte x) (iotaZero 1)) def UInt32.toBytes (x : UInt32) : ByteArray := List.toByteArray (List.map (UInt32.nthByte x) (iotaZero 3)) def UInt8.shiftl16 (x : UInt8) (y : UInt16) : UInt16 := UInt16.shiftRight x.toUInt16 y def UInt8.shiftl32 (x : UInt8) (y : UInt32) : UInt32 := UInt32.shiftRight x.toUInt32 y def String.bytes (x : String) : ByteArray := List.toByteArray (List.map (UInt8.ofNat ∘ Char.toNat) x.toList)
2a5ac1581b39c94c641579c96065a8956406bda9
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/qpf/multivariate/constructions/fix.lean
c4042efdb0ddfcc2e08984be1040caf65e30f47d
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,880
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import data.pfunctor.multivariate.W import data.qpf.multivariate.basic universes u v /-! # The initial algebra of a multivariate qpf is again a qpf. For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with regards to its last argument `αₙ`. The result is a `n`-ary functor: `fix F (α₀,..,αₙ₋₁)`. Making `fix F` into a functor allows us to take the fixed point, compose with other functors and take a fixed point again. ## Main definitions * `fix.mk` - constructor * `fix.dest - destructor * `fix.rec` - recursor: basis for defining functions by structural recursion on `fix F α` * `fix.drec` - dependent recursor: generalization of `fix.rec` where the result type of the function is allowed to depend on the `fix F α` value * `fix.rec_eq` - defining equation for `recursor` * `fix.ind` - induction principle for `fix F α` ## Implementation notes For `F` a QPF`, we define `fix F α` in terms of the W-type of the polynomial functor `P` of `F`. We define the relation `Wequiv` and take its quotient as the definition of `fix F α`. ```lean inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop | ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) : (∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁) | abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) : abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ → Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁) | trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w ``` See [avigad-carneiro-hudon2019] for more details. ## Reference * [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ namespace mvqpf open typevec open mvfunctor (liftp liftr) open_locale mvfunctor variables {n : ℕ} {F : typevec.{u} (n+1) → Type u} [mvfunctor F] [q : mvqpf F] include q /-- `recF` is used as a basis for defining the recursor on `fix F α`. `recF` traverses recursively the W-type generated by `q.P` using a function on `F` as a recursive step -/ def recF {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) : q.P.W α → β := q.P.W_rec (λ a f' f rec, g (abs ⟨a, split_fun f' rec⟩)) theorem recF_eq {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : recF g (q.P.W_mk a f' f) = g (abs ⟨a, split_fun f' (recF g ∘ f)⟩) := by rw [recF, mvpfunctor.W_rec_eq]; refl theorem recF_eq' {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) (x : q.P.W α) : recF g x = g (abs ((append_fun id (recF g)) <$$> q.P.W_dest' x)) := begin apply q.P.W_cases _ x, intros a f' f, rw [recF_eq, q.P.W_dest'_W_mk, mvpfunctor.map_eq, append_fun_comp_split_fun, typevec.id_comp] end /-- Equivalence relation on W-types that represent the same `fix F` value -/ inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop | ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) : (∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁) | abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) : abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ → Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁) | trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w theorem recF_eq_of_Wequiv (α : typevec n) {β : Type*} (u : F (α.append1 β) → β) (x y : q.P.W α) : Wequiv x y → recF u x = recF u y := begin apply q.P.W_cases _ x, intros a₀ f'₀ f₀, apply q.P.W_cases _ y, intros a₁ f'₁ f₁, intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { simp only [recF_eq, function.comp, ih] }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { simp only [recF_eq', abs_map, mvpfunctor.W_dest'_W_mk, h] }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact eq.trans ih₁ ih₂ } end theorem Wequiv.abs' {α : typevec n} (x y : q.P.W α) (h : abs (q.P.W_dest' x) = abs (q.P.W_dest' y)) : Wequiv x y := begin revert h, apply q.P.W_cases _ x, intros a₀ f'₀ f₀, apply q.P.W_cases _ y, intros a₁ f'₁ f₁, apply Wequiv.abs end theorem Wequiv.refl {α : typevec n} (x : q.P.W α) : Wequiv x x := by apply q.P.W_cases _ x; intros a f' f; exact Wequiv.abs a f' f a f' f rfl theorem Wequiv.symm {α : typevec n} (x y : q.P.W α) : Wequiv x y → Wequiv y x := begin intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { exact Wequiv.ind _ _ _ _ ih }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { exact Wequiv.abs _ _ _ _ _ _ h.symm }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact mvqpf.Wequiv.trans _ _ _ ih₂ ih₁} end /-- maps every element of the W type to a canonical representative -/ def Wrepr {α : typevec n} : q.P.W α → q.P.W α := recF (q.P.W_mk' ∘ repr) theorem Wrepr_W_mk {α : typevec n} (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : Wrepr (q.P.W_mk a f' f) = q.P.W_mk' (repr (abs ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩))) := by rw [Wrepr, recF_eq', q.P.W_dest'_W_mk]; refl theorem Wrepr_equiv {α : typevec n} (x : q.P.W α) : Wequiv (Wrepr x) x := begin apply q.P.W_ind _ x, intros a f' f ih, apply Wequiv.trans _ (q.P.W_mk' ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩)), { apply Wequiv.abs', rw [Wrepr_W_mk, q.P.W_dest'_W_mk', q.P.W_dest'_W_mk', abs_repr] }, rw [q.P.map_eq, mvpfunctor.W_mk', append_fun_comp_split_fun, id_comp], apply Wequiv.ind, exact ih end theorem Wequiv_map {α β : typevec n} (g : α ⟹ β) (x y : q.P.W α) : Wequiv x y → Wequiv (g <$$> x) (g <$$> y) := begin intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.ind, apply ih }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.abs, show abs (q.P.obj_append1 a₀ (g ⊚ f'₀) (λ x, q.P.W_map g (f₀ x))) = abs (q.P.obj_append1 a₁ (g ⊚ f'₁) (λ x, q.P.W_map g (f₁ x))), rw [←q.P.map_obj_append1, ←q.P.map_obj_append1, abs_map, abs_map, h] }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { apply mvqpf.Wequiv.trans, apply ih₁, apply ih₂ } end /-- Define the fixed point as the quotient of trees under the equivalence relation. -/ def W_setoid (α : typevec n) : setoid (q.P.W α) := ⟨Wequiv, @Wequiv.refl _ _ _ _ _, @Wequiv.symm _ _ _ _ _, @Wequiv.trans _ _ _ _ _⟩ local attribute [instance] W_setoid /-- Least fixed point of functor F. The result is a functor with one fewer parameters than the input. For `F a b c` a ternary functor, fix F is a binary functor such that ```lean fix F a b = F a b (fix F a b) ``` -/ def fix {n : ℕ} (F : typevec (n+1) → Type*) [mvfunctor F] [q : mvqpf F] (α : typevec n) := quotient (W_setoid α : setoid (q.P.W α)) attribute [nolint has_inhabited_instance] fix /-- `fix F` is a functor -/ def fix.map {α β : typevec n} (g : α ⟹ β) : fix F α → fix F β := quotient.lift (λ x : q.P.W α, ⟦q.P.W_map g x⟧) (λ a b h, quot.sound (Wequiv_map _ _ _ h)) instance fix.mvfunctor : mvfunctor (fix F) := { map := @fix.map _ _ _ _} variable {α : typevec.{u} n} /-- Recursor for `fix F` -/ def fix.rec {β : Type u} (g : F (α ::: β) → β) : fix F α → β := quot.lift (recF g) (recF_eq_of_Wequiv α g) /-- Access W-type underlying `fix F` -/ def fix_to_W : fix F α → q.P.W α := quotient.lift Wrepr (recF_eq_of_Wequiv α (λ x, q.P.W_mk' (repr x))) /-- Constructor for `fix F` -/ def fix.mk (x : F (append1 α (fix F α))) : fix F α := quot.mk _ (q.P.W_mk' (append_fun id fix_to_W <$$> repr x)) /-- Destructor for `fix F` -/ def fix.dest : fix F α → F (append1 α (fix F α)) := fix.rec (mvfunctor.map (append_fun id fix.mk)) theorem fix.rec_eq {β : Type u} (g : F (append1 α β) → β) (x : F (append1 α (fix F α))) : fix.rec g (fix.mk x) = g (append_fun id (fix.rec g) <$$> x) := have recF g ∘ fix_to_W = fix.rec g, by { apply funext, apply quotient.ind, intro x, apply recF_eq_of_Wequiv, apply Wrepr_equiv }, begin conv { to_lhs, rw [fix.rec, fix.mk], dsimp }, cases h : repr x with a f, rw [mvpfunctor.map_eq, recF_eq', ←mvpfunctor.map_eq, mvpfunctor.W_dest'_W_mk'], rw [←mvpfunctor.comp_map, abs_map, ←h, abs_repr, ←append_fun_comp, id_comp, this] end theorem fix.ind_aux (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦q.P.W_mk a f' f⟧ := have fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦Wrepr (q.P.W_mk a f' f)⟧, begin apply quot.sound, apply Wequiv.abs', rw [mvpfunctor.W_dest'_W_mk', abs_map, abs_repr, ←abs_map, mvpfunctor.map_eq], conv { to_rhs, rw [Wrepr_W_mk, q.P.W_dest'_W_mk', abs_repr, mvpfunctor.map_eq] }, congr' 2, rw [mvpfunctor.append_contents, mvpfunctor.append_contents], rw [append_fun, append_fun, ←split_fun_comp, ←split_fun_comp], reflexivity end, by { rw this, apply quot.sound, apply Wrepr_equiv } theorem fix.ind_rec {β : Type*} (g₁ g₂ : fix F α → β) (h : ∀ x : F (append1 α (fix F α)), (append_fun id g₁) <$$> x = (append_fun id g₂) <$$> x → g₁ (fix.mk x) = g₂ (fix.mk x)) : ∀ x, g₁ x = g₂ x := begin apply quot.ind, intro x, apply q.P.W_ind _ x, intros a f' f ih, show g₁ ⟦q.P.W_mk a f' f⟧ = g₂ ⟦q.P.W_mk a f' f⟧, rw [←fix.ind_aux a f' f], apply h, rw [←abs_map, ←abs_map, mvpfunctor.map_eq, mvpfunctor.map_eq], congr' 2, rw [mvpfunctor.append_contents, append_fun, append_fun, ←split_fun_comp, ←split_fun_comp], have : g₁ ∘ (λ x, ⟦f x⟧) = g₂ ∘ (λ x, ⟦f x⟧), { ext x, exact ih x }, rw this end theorem fix.rec_unique {β : Type*} (g : F (append1 α β) → β) (h : fix F α → β) (hyp : ∀ x, h (fix.mk x) = g (append_fun id h <$$> x)) : fix.rec g = h := begin ext x, apply fix.ind_rec, intros x hyp', rw [hyp, ←hyp', fix.rec_eq] end theorem fix.mk_dest (x : fix F α) : fix.mk (fix.dest x) = x := begin change (fix.mk ∘ fix.dest) x = x, apply fix.ind_rec, intro x, dsimp, rw [fix.dest, fix.rec_eq, ←comp_map, ←append_fun_comp, id_comp], intro h, rw h, show fix.mk (append_fun id id <$$> x) = fix.mk x, rw [append_fun_id_id, mvfunctor.id_map] end theorem fix.dest_mk (x : F (append1 α (fix F α))) : fix.dest (fix.mk x) = x := begin unfold fix.dest, rw [fix.rec_eq, ←fix.dest, ←comp_map], conv { to_rhs, rw ←(mvfunctor.id_map x) }, rw [←append_fun_comp, id_comp], have : fix.mk ∘ fix.dest = id, {ext x, apply fix.mk_dest }, rw [this, append_fun_id_id] end theorem fix.ind {α : typevec n} (p : fix F α → Prop) (h : ∀ x : F (α.append1 (fix F α)), liftp (pred_last α p) x → p (fix.mk x)) : ∀ x, p x := begin apply quot.ind, intro x, apply q.P.W_ind _ x, intros a f' f ih, change p ⟦q.P.W_mk a f' f⟧, rw [←fix.ind_aux a f' f], apply h, rw mvqpf.liftp_iff, refine ⟨_, _, rfl, _⟩, intros i j, cases i, { apply ih }, { triv }, end instance mvqpf_fix : mvqpf (fix F) := { P := q.P.Wp, abs := λ α, quot.mk Wequiv, repr := λ α, fix_to_W, abs_repr := by { intros α, apply quot.ind, intro a, apply quot.sound, apply Wrepr_equiv }, abs_map := begin intros α β g x, conv { to_rhs, dsimp [mvfunctor.map]}, rw fix.map, apply quot.sound, apply Wequiv.refl end } /-- Dependent recursor for `fix F` -/ def fix.drec {β : fix F α → Type u} (g : Π x : F (α ::: sigma β), β (fix.mk $ (id ::: sigma.fst) <$$> x)) (x : fix F α) : β x := let y := @fix.rec _ F _ _ α (sigma β) (λ i, ⟨_,g i⟩) x in have x = y.1, by { symmetry, dsimp [y], apply fix.ind_rec _ id _ x, intros x' ih, rw fix.rec_eq, dsimp, simp [append_fun_id_id] at ih, congr, conv { to_rhs, rw [← ih] }, rw [mvfunctor.map_map,← append_fun_comp,id_comp], }, cast (by rw this) y.2 end mvqpf
111fda742b0233eec0c324d2a64e1d9ff89c4e6e
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/polynomial/group_ring_action.lean
b1d42107295c785d763d5fcf73b822222c425103
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
5,318
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 data.polynomial.monic import data.polynomial.algebra_map import algebra.group_ring_action import algebra.group_action_hom /-! # Group action on rings applied to polynomials This file contains instances and definitions relating `mul_semiring_action` to `polynomial`. -/ variables (M : Type*) [monoid M] namespace polynomial variables (R : Type*) [semiring R] variables {M} lemma smul_eq_map [mul_semiring_action M R] (m : M) : ((•) m) = map (mul_semiring_action.to_ring_hom M R m) := begin suffices : distrib_mul_action.to_add_monoid_hom M (polynomial R) m = (map_ring_hom (mul_semiring_action.to_ring_hom M R m)).to_add_monoid_hom, { ext1 r, exact add_monoid_hom.congr_fun this r, }, ext n r : 2, change m • monomial n r = map (mul_semiring_action.to_ring_hom M R m) (monomial n r), simpa only [polynomial.map_monomial, polynomial.smul_monomial], end variables (M) noncomputable instance [mul_semiring_action M R] : mul_semiring_action M (polynomial R) := { smul := (•), smul_one := λ m, (smul_eq_map R m).symm ▸ map_one (mul_semiring_action.to_ring_hom M R m), smul_mul := λ m p q, (smul_eq_map R m).symm ▸ map_mul (mul_semiring_action.to_ring_hom M R m), ..polynomial.distrib_mul_action } noncomputable instance [faithful_mul_semiring_action M R] : faithful_mul_semiring_action M (polynomial R) := { eq_of_smul_eq_smul' := λ m₁ m₂ h, eq_of_smul_eq_smul R $ λ s, C_inj.1 $ calc C (m₁ • s) = m₁ • C s : (smul_C _ _).symm ... = m₂ • C s : h (C s) ... = C (m₂ • s) : smul_C _ _, .. polynomial.mul_semiring_action M R } variables {M R} variables [mul_semiring_action M R] @[simp] lemma smul_X (m : M) : (m • X : polynomial R) = X := (smul_eq_map R m).symm ▸ map_X _ variables (S : Type*) [comm_semiring S] [mul_semiring_action M S] theorem smul_eval_smul (m : M) (f : polynomial S) (x : S) : (m • f).eval (m • x) = m • f.eval x := polynomial.induction_on f (λ r, by rw [smul_C, eval_C, eval_C]) (λ f g ihf ihg, by rw [smul_add, eval_add, ihf, ihg, eval_add, smul_add]) (λ n r ih, by rw [smul_mul', smul_pow, smul_C, smul_X, eval_mul, eval_C, eval_pow, eval_X, eval_mul, eval_C, eval_pow, eval_X, smul_mul', smul_pow]) variables (G : Type*) [group G] theorem eval_smul' [mul_semiring_action G S] (g : G) (f : polynomial S) (x : S) : f.eval (g • x) = g • (g⁻¹ • f).eval x := by rw [← smul_eval_smul, smul_inv_smul] theorem smul_eval [mul_semiring_action G S] (g : G) (f : polynomial S) (x : S) : (g • f).eval x = g • f.eval (g⁻¹ • x) := by rw [← smul_eval_smul, smul_inv_smul] end polynomial section comm_ring variables (G : Type*) [group G] [fintype G] variables (R : Type*) [comm_ring R] [mul_semiring_action G R] open mul_action open_locale classical /-- the product of `(X - g • x)` over distinct `g • x`. -/ noncomputable def prod_X_sub_smul (x : R) : polynomial R := (finset.univ : finset (quotient_group.quotient $ mul_action.stabilizer G x)).prod $ λ g, polynomial.X - polynomial.C (of_quotient_stabilizer G x g) theorem prod_X_sub_smul.monic (x : R) : (prod_X_sub_smul G R x).monic := polynomial.monic_prod_of_monic _ _ $ λ g _, polynomial.monic_X_sub_C _ theorem prod_X_sub_smul.eval (x : R) : (prod_X_sub_smul G R x).eval x = 0 := (monoid_hom.map_prod ((polynomial.aeval x).to_ring_hom.to_monoid_hom : polynomial R →* R) _ _).trans $ finset.prod_eq_zero (finset.mem_univ $ quotient_group.mk 1) $ by simp theorem prod_X_sub_smul.smul (x : R) (g : G) : g • prod_X_sub_smul G R x = prod_X_sub_smul G R x := (smul_prod _ _ _ _ _).trans $ fintype.prod_bijective _ (mul_action.bijective g) _ _ (λ g', by rw [of_quotient_stabilizer_smul, smul_sub, polynomial.smul_X, polynomial.smul_C]) theorem prod_X_sub_smul.coeff (x : R) (g : G) (n : ℕ) : g • (prod_X_sub_smul G R x).coeff n = (prod_X_sub_smul G R x).coeff n := by rw [← polynomial.coeff_smul, prod_X_sub_smul.smul] end comm_ring namespace mul_semiring_action_hom variables {M} variables {P : Type*} [comm_semiring P] [mul_semiring_action M P] variables {Q : Type*} [comm_semiring Q] [mul_semiring_action M Q] open polynomial /-- An equivariant map induces an equivariant map on polynomials. -/ protected noncomputable def polynomial (g : P →+*[M] Q) : polynomial P →+*[M] polynomial Q := { to_fun := map g, map_smul' := λ m p, polynomial.induction_on p (λ b, by rw [smul_C, map_C, coe_fn_coe, g.map_smul, map_C, coe_fn_coe, smul_C]) (λ p q ihp ihq, by rw [smul_add, polynomial.map_add, ihp, ihq, polynomial.map_add, smul_add]) (λ n b ih, by rw [smul_mul', smul_C, smul_pow, smul_X, polynomial.map_mul, map_C, polynomial.map_pow, map_X, coe_fn_coe, g.map_smul, polynomial.map_mul, map_C, polynomial.map_pow, map_X, smul_mul', smul_C, smul_pow, smul_X, coe_fn_coe]), map_zero' := polynomial.map_zero g, map_add' := λ p q, polynomial.map_add g, map_one' := polynomial.map_one g, map_mul' := λ p q, polynomial.map_mul g } @[simp] theorem coe_polynomial (g : P →+*[M] Q) : (g.polynomial : polynomial P → polynomial Q) = map g := rfl end mul_semiring_action_hom
ff3cc894db79d9bcfd054f5e410fc876956cb9ce
b7b549d2cf38ac9d4e49372b7ad4d37f70449409
/src/LeanLLVM/Driver.lean
cf4eed10dedb43ea914f90ecdc05dc26b7a2b42f
[ "Apache-2.0" ]
permissive
GaloisInc/lean-llvm
7cc196172fe02ff3554edba6cc82f333c30fdc2b
36e2ec604ae22d8ec1b1b66eca0f8887880db6c6
refs/heads/master
1,637,359,020,356
1,629,332,114,000
1,629,402,464,000
146,700,234
29
1
Apache-2.0
1,631,225,695,000
1,535,607,191,000
Lean
UTF-8
Lean
false
false
1,908
lean
import Init.Data.RBMap import Init.Control.Except import Galois.Data.Bitvec import LeanLLVM.AST import LeanLLVM.PP import LeanLLVM.DataLayout import LeanLLVM.LLVMLib import LeanLLVM.LLVMOutput import LeanLLVM.SimMonad import LeanLLVM.Simulate open LLVM. def readmainActual (x:String) : IO UInt32 := do ctx ← FFI.newContext; mb ← FFI.newMemoryBufferFromFile x; m ← FFI.parseBitcodeFile mb ctx >>= loadModule; dl <- match computeDataLayout m.dataLayout with | (Except.error msg) => throw (IO.userError msg) | (Except.ok dl) => pure dl; IO.println (ppLLVM m); st0 <- runInitializers m dl [(Symbol.mk "arr", bitvec.of_nat 64 0x202000) ]; --let st0 := initializeState m dl; -- let res := -- sim.runFunc (Symbol.mk "add_offset") -- [ sim.value.bv 64 (bv.from_nat 64 8) -- , sim.value.bv 32 (bv.from_nat 32 8) -- ] -- st0; res <- Sim.runFuncPrintTrace (Symbol.mk "run_test") [ ] st0; match res with | (Sim.Value.bv x, _) => do IO.println ("0x" ++ (Nat.toDigits 16 x.to_nat).asString); pure 0 | _ => pure 0 def readmain (xs : List String) : IO UInt32 := match xs with | [x] => readmainActual x | _ => throw (IO.userError "expected a single command line argument") def testModule : LLVM.Module := LLVM.Module.mk (some "testmodule") [] Array.empty -- types Array.empty -- named md Array.empty -- unnamed md RBMap.empty -- comdat Array.empty -- globals Array.empty -- declares Array.empty -- defines Array.empty -- inline ASM Array.empty -- global aliases def buildmain (xs : List String) : IO UInt32 := do ctx <- FFI.newContext; (_,mod) <- Output.run (outputModule ctx testModule); FFI.printModule mod; pure 0 --def main := buildmain def main := readmain
1b39bc0bdf8f90318f320042b60f9bdd83953c22
9028d228ac200bbefe3a711342514dd4e4458bff
/src/data/set/finite.lean
671a1b373e3c8ec42633aaed235b1daaf679c966
[ "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
25,213
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 data.fintype.basic /-! # Finite sets This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some basic facts about finite sets. -/ open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s /-- The subtype corresponding to a finite set is a finite type. Note that because `finite` isn't a typeclass, this will not fire if it is made into an instance -/ noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ h.fintype @[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] theorem finite.to_finset.nonempty {s : set α} (h : finite s) : h.to_finset.nonempty ↔ s.nonempty := show (∃ x, x ∈ h.to_finset) ↔ (∃ x, x ∈ s), from exists_congr (λ _, finite.mem_to_finset) @[simp] lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s := @set.coe_to_finset _ s h.fintype theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := ⟨hs.to_finset, hs.coe_to_finset⟩ /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) := { coe := coe, cond := finite, prf := λ s hs, hs.exists_finset_coe } theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype.of_finset s (λ _, iff.rfl)⟩ theorem finite.of_fintype [fintype α] (s : set α) : finite s := by classical; exact ⟨set_fintype s⟩ theorem exists_finite_iff_finset {p : set α → Prop} : (∃ s, finite s ∧ p s) ↔ ∃ s : finset α, p ↑s := ⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩, λ ⟨s, hs⟩, ⟨↑s, finite_mem_finset s, hs⟩⟩ /-- Membership of a subset of a finite type is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ instance finite.inhabited : inhabited {s : set α // finite s} := ⟨⟨∅, finite_empty⟩⟩ /-- A `fintype` structure on `insert a s`. -/ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a ::ₘ s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert' s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h section local attribute [instance] decidable_mem_of_fintype instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h end @[simp] theorem finite.insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (hs.insert a).to_finset = insert a hs.to_finset := finset.ext $ by simp @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (h.insert a)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := unique.fintype @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton theorem finite_pure (a : α) : finite (pure a : set α) := ⟨set.fintype_pure a⟩ instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α $ (equiv.set.univ α).symm theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩ theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α := ⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ $ @fintype.of_equiv _ _ h₂ $ equiv.set.univ _⟩ theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) := infinite_univ_iff.2 h theorem infinite_coe_iff {s : set α} : _root_.infinite s ↔ infinite s := ⟨λ ⟨h₁⟩ h₂, h₁ h₂.some, λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩⟩ theorem infinite.to_subtype {s : set α} (h : infinite s) : _root_.infinite s := infinite_coe_iff.2 h /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def infinite.nat_embedding (s : set α) (h : infinite s) : ℕ ↪ s := by { haveI := h.to_subtype, exact infinite.nat_embedding s } lemma infinite.exists_subset_card_eq {s : set α} (hs : infinite s) (n : ℕ) : ∃ t : finset α, ↑t ⊆ s ∧ t.card = n := ⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩ instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp theorem finite.union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) := set.fintype_sep s t /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t := by rw ← inter_eq_self_of_subset_right h; apply_instance theorem finite.subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ theorem infinite_mono {s t : set α} (h : s ⊆ t) : infinite s → infinite t := mt (λ ht, ht.subset h) instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype.of_finset (finset.univ.image f) $ by simp [range] theorem finite_range (f : α → β) [fintype α] : finite (range f) := by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩ theorem finite.image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ lemma finite.dependent_image {s : set α} (hs : finite s) {F : Π i ∈ s, β} {t : set β} (H : ∀ y ∈ t, ∃ x (hx : x ∈ s), y = F x hx) : set.finite t := begin let G : s → β := λ x, F x.1 x.2, have A : t ⊆ set.range G, { assume y hy, rcases H y hy with ⟨x, hx, xy⟩, refine ⟨⟨x, hx⟩, xy.symm⟩ }, letI : fintype s := finite.fintype hs, exact (finite_range G).subset A end instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image theorem finite.map {α β} {s : set α} : ∀ (f : α → β), finite s → finite (f <$> s) := finite.image /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end theorem finite_of_finite_image {s : set α} {f : α → β} (hi : set.inj_on f s) : finite (f '' s) → finite s | ⟨h⟩ := ⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $ assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq⟩ theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := ⟨finite_of_finite_image hi, finite.image _⟩ theorem finite.preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (h.subset (image_preimage_subset f s)) instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) := by rw bUnion_eq_Union; exact @set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi) instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) := fintype_bUnion _ (λ i _, H i) theorem finite.sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H theorem finite.bUnion {α} {ι : Type*} {s : set ι} {f : Π i ∈ s, set α} : finite s → (∀ i ∈ s, finite (f i ‹_›)) → finite (⋃ i∈s, f i ‹_›) | ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _ _) instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype.of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite.prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ /-- `image2 f s t` is finitype if `s` and `t` are. -/ instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) := by { rw ← image_prod, apply set.fintype_image } lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) : finite (image2 f s t) := by { rw ← image_prod, exact (hs.prod ht).image _ } /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion _ H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := fintype_bind _ _ (λ i _, H i) theorem finite_bind {α β} {s : set α} {f : α → set β} : finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f) | ⟨hs⟩ H := ⟨@fintype_bind _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩ instance fintype_seq {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := by rw seq_eq_bind_map; apply set.fintype_bind' theorem finite.seq {α β : Type u} {f : set (α → β)} {s : set α} : finite f → finite s → finite (f <*> s) | ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ } /-- There are finitely many subsets of a given finite set -/ lemma finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} := begin -- we just need to translate the result, already known for finsets, -- to the language of finite sets let s : set (set α) := coe '' (↑(finset.powerset (finite.to_finset h)) : set (finset α)), have : finite s := (finite_mem_finset _).image _, apply this.subset, refine λ b hb, ⟨(h.subset hb).to_finset, _, finite.coe_to_finset _⟩, simpa [finset.subset_iff] end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_min_image f ⟨x, finite.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_max_image f ⟨x, finite.mem_to_finset.2 hx⟩ end set namespace finset variables [decidable_eq β] variables {s : finset α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma finite_to_set_to_finset {α : Type*} (s : finset α) : (finite_to_set s).to_finset = s := by { ext, rw [set.finite.mem_to_finset, mem_coe] } end finset namespace set lemma finite_subset_Union {s : set α} (hs : finite s) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i := begin casesI hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, _⟩, rintro x hx, simp, exact ⟨x, ⟨hx, hf _⟩⟩, end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, tfin.subset (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ /-- An increasing union distributes over finite intersection. -/ lemma Union_Inter_of_monotone {ι ι' α : Type*} [fintype ι] [decidable_linear_order ι'] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := begin ext x, refine ⟨λ hx, Union_Inter_subset hx, λ hx, _⟩, simp only [mem_Inter, mem_Union, mem_Inter] at hx ⊢, choose j hj using hx, obtain ⟨j₀⟩ := show nonempty ι', by apply_instance, refine ⟨finset.univ.fold max j₀ j, λ i, hs i _ (hj i)⟩, rw [finset.fold_op_rel_iff_or (@le_max_iff _ _)], exact or.inr ⟨i, finset.mem_univ i, le_rfl⟩ end instance nat.fintype_Iio (n : ℕ) : fintype (Iio n) := fintype.of_finset (finset.range n) $ by simp /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ lemma seq_of_forall_finite_exists {γ : Type*} {P : γ → set γ → Prop} (h : ∀ t, finite t → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := ⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h (range $ λ m : Iio n, ih m.1 m.2) (finite_range _), λ n, begin classical, refine nat.strong_rec_on' n (λ n ih, _), rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _), ext x, split, { rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ }, { rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ } end⟩ lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f)) (hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) := (hf.union hg).subset range_ite_subset lemma finite_range_const {c : β} : finite (range (λ x : α, c)) := (finite_singleton c).subset range_const_subset lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}: range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) := by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] } lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : finite (range (λ x, nat.find_greatest (P x) b)) := (finset.range (b + 1)).finite_to_set.subset range_find_greatest_subset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := begin rw [← s.coe_to_finset, ← t.coe_to_finset, finset.coe_ssubset] at h, rw [fintype.card_of_finset' _ (λ x, mem_to_finset), fintype.card_of_finset' _ (λ x, mem_to_finset)], exact finset.card_lt_card h, end lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := calc fintype.card s = s.to_finset.card : fintype.card_of_finset' _ (by simp) ... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *) ... = fintype.card t : eq.symm (fintype.card_of_finset' _ (by simp)) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.set.range f hf lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' := begin classical, refine h.induction_on _ _, { assume h, exact absurd h empty_not_nonempty }, assume a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset.card = fintype.card s := by { rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], congr' 2, funext, rw set.finite.mem_to_finset } section local attribute [instance, priority 1] classical.prop_decidable lemma to_finset_inter {α : Type*} [fintype α] (s t : set α) : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by ext; simp end section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ protected lemma finite.bdd_above (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ protected lemma finite.bdd_below (hs : finite s) : bdd_below s := @finite.bdd_above (order_dual α) _ _ _ hs /--A finite union of sets which are all bounded below is still bounded below.-/ lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := @finite.bdd_above_bUnion (order_dual α) _ _ _ _ _ H end end set namespace finset /-- A finset is bounded above. -/ protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := s.finite_to_set.bdd_above /-- A finset is bounded below. -/ protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := s.finite_to_set.bdd_below end finset lemma fintype.exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := begin rcases set.finite_univ.exists_maximal_wrt f _ univ_nonempty with ⟨x, _, hx⟩, exact ⟨x, λ y, (le_total (f x) (f y)).elim (λ h, ge_of_eq $ hx _ trivial h) id⟩ end
e7c1a94ecd2625a42f2fa8cb9f81c6fb6792491e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/class4.lean
c66da2bd2c05697a5186156fb796804ae3adad58
[ "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
2,469
lean
prelude import logic namespace experiment inductive nat : Type := | zero : nat | succ : nat → nat open eq namespace nat definition add (x y : nat) := nat.rec x (λ n r, succ r) y infixl `+` := add theorem add.left_id (x : nat) : x + zero = x := refl _ theorem succ_add (x y : nat) : x + (succ y) = succ (x + y) := refl _ definition is_zero (x : nat) := nat.rec true (λ n r, false) x theorem is_zero_zero : is_zero zero := of_eq_true (refl _) theorem not_is_zero_succ (x : nat) : ¬ is_zero (succ x) := not_of_eq_false (refl _) theorem dichotomy (m : nat) : m = zero ∨ (∃ n, m = succ n) := nat.rec (or.intro_left _ (refl zero)) (λ m H, or.intro_right _ (exists.intro m (refl (succ m)))) m theorem is_zero_to_eq (x : nat) (H : is_zero x) : x = zero := or.elim (dichotomy x) (assume Hz : x = zero, Hz) (assume Hs : (∃ n, x = succ n), exists.elim Hs (λ (w : nat) (Hw : x = succ w), absurd H (eq.subst (symm Hw) (not_is_zero_succ w)))) theorem is_not_zero_to_eq {x : nat} (H : ¬ is_zero x) : ∃ n, x = succ n := or.elim (dichotomy x) (assume Hz : x = zero, absurd (eq.subst (symm Hz) is_zero_zero) H) (assume Hs, Hs) theorem not_zero_add (x y : nat) (H : ¬ is_zero y) : ¬ is_zero (x + y) := exists.elim (is_not_zero_to_eq H) (λ (w : nat) (Hw : y = succ w), have H1 : x + y = succ (x + w), from calc x + y = x + succ w : {Hw} ... = succ (x + w) : refl _, have H2 : ¬ is_zero (succ (x + w)), from not_is_zero_succ (x+w), subst (symm H1) H2) inductive not_zero [class] (x : nat) : Prop := intro : ¬ is_zero x → not_zero x theorem not_zero_not_is_zero {x : nat} (H : not_zero x) : ¬ is_zero x := not_zero.rec (λ H1, H1) H theorem not_zero_add_right [instance] (x y : nat) (H : not_zero y) : not_zero (x + y) := not_zero.intro (not_zero_add x y (not_zero_not_is_zero H)) theorem not_zero_succ [instance] (x : nat) : not_zero (succ x) := not_zero.intro (not_is_zero_succ x) constant dvd : Π (x y : nat) {H : not_zero y}, nat constants a b : nat set_option pp.implicit true attribute add [reducible] check dvd a (succ b) check (λ H : not_zero b, dvd a b) check (succ zero) check a + (succ zero) check dvd a (a + (succ b)) attribute add [irreducible] check dvd a (a + (succ b)) attribute add [reducible] check dvd a (a + (succ b)) attribute add [irreducible] check dvd a (a + (succ b)) end nat end experiment
0ec0e261b5cbfaebe8a88da2756e344de8c661e9
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/ring_theory/ideal/operations.lean
25dfa32d00f421ba5d712a1e9aec09a7443745e4
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
89,968
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.operations import algebra.ring.equiv import data.nat.choose.sum import ring_theory.coprime.lemmas import ring_theory.ideal.quotient import ring_theory.non_zero_divisors /-! # More operations on modules and ideals -/ universes u v w x open_locale big_operators pointwise namespace submodule variables {R : Type u} {M : Type v} {F : Type*} {G : Type*} section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [module R M] open_locale pointwise instance has_smul' : has_smul (ideal R) (submodule R M) := ⟨submodule.map₂ (linear_map.lsmul R M)⟩ /-- This duplicates the global `smul_eq_mul`, but doesn't have to unfold anywhere near as much to apply. -/ protected lemma _root_.ideal.smul_eq_mul (I J : ideal R) : I • J = I * J := rfl /-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker variables {I J : ideal R} {N P : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ lemma mem_annihilator_span (s : set M) (r : R) : r ∈ (submodule.span R s).annihilator ↔ ∀ n : s, r • (n : M) = 0 := begin rw submodule.mem_annihilator, split, { intros h n, exact h _ (submodule.subset_span n.prop) }, { intros h n hn, apply submodule.span_induction hn, { intros x hx, exact h ⟨x, hx⟩ }, { exact smul_zero _ }, { intros x y hx hy, rw [smul_add, hx, hy, zero_add] }, { intros a x hx, rw [smul_comm, hx, smul_zero] } } end lemma mem_annihilator_span_singleton (g : M) (r : R) : r ∈ (submodule.span R ({g} : set M)).annihilator ↔ r • g = 0 := by simp [mem_annihilator_span] theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := apply_mem_map₂ _ hr hn theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := map₂_le @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H1 : ∀ x y, p x → p y → p (x + y)) : p x := begin have H0 : p 0 := by simpa only [zero_smul] using Hb 0 I.zero_mem 0 N.zero_mem, refine submodule.supr_induction _ H _ H0 H1, rintros ⟨i, hi⟩ m ⟨j, hj, (rfl : i • _ = m) ⟩, exact Hb _ hi _ hj, end theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩) (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := map₂_le_map₂ hij hnp theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := map₂_le_map₂_left h theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := map₂_le_map₂_right h lemma map_le_smul_top (I : ideal R) (f : R →ₗ[R] M) : submodule.map f I ≤ I • (⊤ : submodule R M) := begin rintros _ ⟨y, hy, rfl⟩, rw [← mul_one y, ← smul_eq_mul, f.map_smul], exact smul_mem_smul hy mem_top end @[simp] theorem annihilator_smul (N : submodule R M) : annihilator N • N = ⊥ := eq_bot_iff.2 (smul_le.2 (λ r, mem_annihilator.1)) @[simp] theorem annihilator_mul (I : ideal R) : annihilator I * I = ⊥ := annihilator_smul I @[simp] theorem mul_annihilator (I : ideal R) : I * annihilator I = ⊥ := by rw [mul_comm, annihilator_mul] variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := map₂_bot_right _ _ @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := map₂_bot_left _ _ @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := map₂_sup_right _ _ _ _ theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := map₂_sup_left _ _ _ _ protected theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) lemma smul_inf_le (M₁ M₂ : submodule R M) : I • (M₁ ⊓ M₂) ≤ I • M₁ ⊓ I • M₂ := le_inf (submodule.smul_mono_right inf_le_left) (submodule.smul_mono_right inf_le_right) lemma smul_supr {ι : Sort*} {I : ideal R} {t : ι → submodule R M} : I • supr t = ⨆ i, I • t i := map₂_supr_right _ _ _ lemma smul_infi_le {ι : Sort*} {I : ideal R} {t : ι → submodule R M} : I • infi t ≤ ⨅ i, I • t i := le_infi (λ i, smul_mono_right (infi_le _ _)) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := (map₂_span_span _ _ _ _).trans $ congr_arg _ $ set.image2_eq_Union _ _ _ lemma ideal_span_singleton_smul (r : R) (N : submodule R M) : (ideal.span {r} : ideal R) • N = r • N := begin have : span R (⋃ (t : M) (x : t ∈ N), {r • t}) = r • N, { convert span_eq _, exact (set.image_eq_Union _ (N : set M)).symm }, conv_lhs { rw [← span_eq N, span_smul_span] }, simpa end lemma span_smul_eq (r : R) (s : set M) : span R (r • s) = r • span R s := by rw [← ideal_span_singleton_smul, span_smul_span, ←set.image2_eq_Union, set.image2_singleton_left, set.image_smul] lemma mem_of_span_top_of_smul_mem (M' : submodule R M) (s : set R) (hs : ideal.span s = ⊤) (x : M) (H : ∀ r : s, (r : R) • x ∈ M') : x ∈ M' := begin suffices : (⊤ : ideal R) • (span R ({x} : set M)) ≤ M', { rw top_smul at this, exact this (subset_span (set.mem_singleton x)) }, rw [← hs, span_smul_span, span_le], simpa using H end /-- Given `s`, a generating set of `R`, to check that an `x : M` falls in a submodule `M'` of `x`, we only need to show that `r ^ n • x ∈ M'` for some `n` for each `r : s`. -/ lemma mem_of_span_eq_top_of_smul_pow_mem (M' : submodule R M) (s : set R) (hs : ideal.span s = ⊤) (x : M) (H : ∀ r : s, ∃ (n : ℕ), (r ^ n : R) • x ∈ M') : x ∈ M' := begin obtain ⟨s', hs₁, hs₂⟩ := (ideal.span_eq_top_iff_finite _).mp hs, replace H : ∀ r : s', ∃ (n : ℕ), (r ^ n : R) • x ∈ M' := λ r, H ⟨_, hs₁ r.prop⟩, choose n₁ n₂ using H, let N := s'.attach.sup n₁, have hs' := ideal.span_pow_eq_top (s' : set R) hs₂ N, apply M'.mem_of_span_top_of_smul_mem _ hs', rintro ⟨_, r, hr, rfl⟩, convert M'.smul_mem (r ^ (N - n₁ ⟨r, hr⟩)) (n₂ ⟨r, hr⟩) using 1, simp only [subtype.coe_mk, smul_smul, ← pow_add], rw tsub_add_cancel_of_le (finset.le_sup (s'.mem_attach _) : n₁ ⟨r, hr⟩ ≤ N), end variables {M' : Type w} [add_comm_monoid M'] [module R M'] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f, from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $ smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) variables {I} lemma mem_smul_span {s : set M} {x : M} : x ∈ I • submodule.span R s ↔ x ∈ submodule.span R (⋃ (a ∈ I) (b ∈ s), ({a • b} : set M)) := by rw [← I.span_eq, submodule.span_smul_span, I.span_eq]; refl variables (I) /-- If `x` is an `I`-multiple of the submodule spanned by `f '' s`, then we can write `x` as an `I`-linear combination of the elements of `f '' s`. -/ lemma mem_ideal_smul_span_iff_exists_sum {ι : Type*} (f : ι → M) (x : M) : x ∈ I • span R (set.range f) ↔ ∃ (a : ι →₀ R) (ha : ∀ i, a i ∈ I), a.sum (λ i c, c • f i) = x := begin split, swap, { rintro ⟨a, ha, rfl⟩, exact submodule.sum_mem _ (λ c _, smul_mem_smul (ha c) $ subset_span $ set.mem_range_self _) }, refine λ hx, span_induction (mem_smul_span.mp hx) _ _ _ _, { simp only [set.mem_Union, set.mem_range, set.mem_singleton_iff], rintros x ⟨y, hy, x, ⟨i, rfl⟩, rfl⟩, refine ⟨finsupp.single i y, λ j, _, _⟩, { letI := classical.dec_eq ι, rw finsupp.single_apply, split_ifs, { assumption }, { exact I.zero_mem } }, refine @finsupp.sum_single_index ι R M _ _ i _ (λ i y, y • f i) _, simp }, { exact ⟨0, λ i, I.zero_mem, finsupp.sum_zero_index⟩ }, { rintros x y ⟨ax, hax, rfl⟩ ⟨ay, hay, rfl⟩, refine ⟨ax + ay, λ i, I.add_mem (hax i) (hay i), finsupp.sum_add_index _ _⟩; intros; simp only [zero_smul, add_smul] }, { rintros c x ⟨a, ha, rfl⟩, refine ⟨c • a, λ i, I.mul_mem_left c (ha i), _⟩, rw [finsupp.sum_smul_index, finsupp.smul_sum]; intros; simp only [zero_smul, mul_smul] }, end theorem mem_ideal_smul_span_iff_exists_sum' {ι : Type*} (s : set ι) (f : ι → M) (x : M) : x ∈ I • span R (f '' s) ↔ ∃ (a : s →₀ R) (ha : ∀ i, a i ∈ I), a.sum (λ i c, c • f i) = x := by rw [← submodule.mem_ideal_smul_span_iff_exists_sum, ← set.image_eq_range] @[simp] lemma smul_comap_le_comap_smul (f : M →ₗ[R] M') (S : submodule R M') (I : ideal R) : I • S.comap f ≤ (I • S).comap f := begin refine (submodule.smul_le.mpr (λ r hr x hx, _)), rw [submodule.mem_comap] at ⊢ hx, rw f.map_smul, exact submodule.smul_mem_smul hr hx end end comm_semiring section comm_ring variables [comm_ring R] [add_comm_group M] [module R M] variables {N N₁ N₂ P P₁ P₂ : submodule R M} /-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/ def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) end comm_ring end submodule namespace ideal section add variables {R : Type u} [semiring R] @[simp] lemma add_eq_sup {I J : ideal R} : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl end add section mul_and_radical variables {R : Type u} {ι : Type*} [comm_semiring R] variables {I J K L : ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_range, linear_map.range_id] theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs lemma pow_mem_pow {x : R} (hx : x ∈ I) (n : ℕ) : x ^ n ∈ I ^ n := submodule.pow_mem_pow _ hx _ lemma prod_mem_prod {ι : Type*} {s : finset ι} {I : ι → ideal R} {x : ι → R} : (∀ i ∈ s, x i ∈ I i) → ∏ i in s, x i ∈ ∏ i in s, I i := begin classical, apply finset.induction_on s, { intro _, rw [finset.prod_empty, finset.prod_empty, one_eq_top], exact submodule.mem_top }, { intros a s ha IH h, rw [finset.prod_insert ha, finset.prod_insert ha], exact mul_mem_mul (h a $ finset.mem_insert_self a s) (IH $ λ i hi, h i $ finset.mem_insert_of_mem hi) } end theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, J.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, I.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) := by { unfold span, rw submodule.span_mul_span, } lemma span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : ideal R) := by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton], } lemma span_singleton_pow (s : R) (n : ℕ): span {s} ^ n = (span {s ^ n} : ideal R) := begin induction n with n ih, { simp [set.singleton_one], }, simp only [pow_succ, ih, span_singleton_mul_span_singleton], end lemma mem_mul_span_singleton {x y : R} {I : ideal R} : x ∈ I * span {y} ↔ ∃ z ∈ I, z * y = x := submodule.mem_smul_span_singleton lemma mem_span_singleton_mul {x y : R} {I : ideal R} : x ∈ span {y} * I ↔ ∃ z ∈ I, y * z = x := by simp only [mul_comm, mem_mul_span_singleton] lemma le_span_singleton_mul_iff {x : R} {I J : ideal R} : I ≤ span {x} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI := show (∀ {zI} (hzI : zI ∈ I), zI ∈ span {x} * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI, by simp only [mem_span_singleton_mul] lemma span_singleton_mul_le_iff {x : R} {I J : ideal R} : span {x} * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J := begin simp only [mul_le, mem_span_singleton_mul, mem_span_singleton], split, { intros h zI hzI, exact h x (dvd_refl x) zI hzI }, { rintros h _ ⟨z, rfl⟩ zI hzI, rw [mul_comm x z, mul_assoc], exact J.mul_mem_left _ (h zI hzI) }, end lemma span_singleton_mul_le_span_singleton_mul {x y : R} {I J : ideal R} : span {x} * I ≤ span {y} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ := by simp only [span_singleton_mul_le_iff, mem_span_singleton_mul, eq_comm] lemma eq_span_singleton_mul {x : R} (I J : ideal R) : I = span {x} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ (∀ z ∈ J, x * z ∈ I)) := by simp only [le_antisymm_iff, le_span_singleton_mul_iff, span_singleton_mul_le_iff] lemma span_singleton_mul_eq_span_singleton_mul {x y : R} (I J : ideal R) : span {x} * I = span {y} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ) ∧ (∀ zJ ∈ J, ∃ zI ∈ I, x * zI = y * zJ)) := by simp only [le_antisymm_iff, span_singleton_mul_le_span_singleton_mul, eq_comm] lemma prod_span {ι : Type*} (s : finset ι) (I : ι → set R) : (∏ i in s, ideal.span (I i)) = ideal.span (∏ i in s, I i) := submodule.prod_span s I lemma prod_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) : (∏ i in s, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} := submodule.prod_span_singleton s I lemma finset_inf_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) (hI : set.pairwise ↑s (is_coprime on I)) : (s.inf $ λ i, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} := begin ext x, simp only [submodule.mem_finset_inf, ideal.mem_span_singleton], exact ⟨finset.prod_dvd_of_coprime hI, λ h i hi, (finset.dvd_prod_of_mem _ hi).trans h⟩ end lemma infi_span_singleton {ι : Type*} [fintype ι] (I : ι → R) (hI : ∀ i j (hij : i ≠ j), is_coprime (I i) (I j)): (⨅ i, ideal.span ({I i} : set R)) = ideal.span {∏ i, I i} := begin rw [← finset.inf_univ_eq_infi, finset_inf_span_singleton], rwa [finset.coe_univ, set.pairwise_univ] end lemma sup_eq_top_iff_is_coprime {R : Type*} [comm_semiring R] (x y : R) : span ({x} : set R) ⊔ span {y} = ⊤ ↔ is_coprime x y := begin rw [eq_top_iff_one, submodule.mem_sup], split, { rintro ⟨u, hu, v, hv, h1⟩, rw mem_span_singleton' at hu hv, rw [← hu.some_spec, ← hv.some_spec] at h1, exact ⟨_, _, h1⟩ }, { exact λ ⟨u, v, h1⟩, ⟨_, mem_span_singleton'.mpr ⟨_, rfl⟩, _, mem_span_singleton'.mpr ⟨_, rfl⟩, h1⟩ }, end theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩ theorem multiset_prod_le_inf {s : multiset (ideal R)} : s.prod ≤ s.inf := begin classical, refine s.induction_on _ _, { rw [multiset.inf_zero], exact le_top }, intros a s ih, rw [multiset.prod_cons, multiset.inf_cons], exact le_trans mul_le_inf (inf_le_inf le_rfl ih) end theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f := multiset_prod_le_inf theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) lemma sup_mul_eq_of_coprime_left (h : I ⊔ J = ⊤) : I ⊔ (J * K) = I ⊔ K := le_antisymm (sup_le_sup_left mul_le_left _) $ λ i hi, begin rw eq_top_iff_one at h, rw submodule.mem_sup at h hi ⊢, obtain ⟨i1, hi1, j, hj, h⟩ := h, obtain ⟨i', hi', k, hk, hi⟩ := hi, refine ⟨_, add_mem hi' (mul_mem_right k _ hi1), _, mul_mem_mul hj hk, _⟩, rw [add_assoc, ← add_mul, h, one_mul, hi] end lemma sup_mul_eq_of_coprime_right (h : I ⊔ K = ⊤) : I ⊔ (J * K) = I ⊔ J := by { rw mul_comm, exact sup_mul_eq_of_coprime_left h } lemma mul_sup_eq_of_coprime_left (h : I ⊔ J = ⊤) : (I * K) ⊔ J = K ⊔ J := by { rw sup_comm at h, rw [sup_comm, sup_mul_eq_of_coprime_left h, sup_comm] } lemma mul_sup_eq_of_coprime_right (h : K ⊔ J = ⊤) : (I * K) ⊔ J = I ⊔ J := by { rw sup_comm at h, rw [sup_comm, sup_mul_eq_of_coprime_right h, sup_comm] } lemma sup_prod_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → I ⊔ J i = ⊤) : I ⊔ ∏ i in s, J i = ⊤ := finset.prod_induction _ (λ J, I ⊔ J = ⊤) (λ J K hJ hK, (sup_mul_eq_of_coprime_left hJ).trans hK) (by rw [one_eq_top, sup_top_eq]) h lemma sup_infi_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → I ⊔ J i = ⊤) : I ⊔ (⨅ i ∈ s, J i) = ⊤ := eq_top_iff.mpr $ le_of_eq_of_le (sup_prod_eq_top h).symm $ sup_le_sup_left (le_of_le_of_eq prod_le_inf $ finset.inf_eq_infi _ _) _ lemma prod_sup_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → J i ⊔ I = ⊤) : (∏ i in s, J i) ⊔ I = ⊤ := sup_comm.trans (sup_prod_eq_top $ λ i hi, sup_comm.trans $ h i hi) lemma infi_sup_eq_top {s : finset ι} {J : ι → ideal R} (h : ∀ i, i ∈ s → J i ⊔ I = ⊤) : (⨅ i ∈ s, J i) ⊔ I = ⊤ := sup_comm.trans (sup_infi_eq_top $ λ i hi, sup_comm.trans $ h i hi) lemma sup_pow_eq_top {n : ℕ} (h : I ⊔ J = ⊤) : I ⊔ (J ^ n) = ⊤ := by { rw [← finset.card_range n, ← finset.prod_const], exact sup_prod_eq_top (λ _ _, h) } lemma pow_sup_eq_top {n : ℕ} (h : I ⊔ J = ⊤) : (I ^ n) ⊔ J = ⊤ := by { rw [← finset.card_range n, ← finset.prod_const], exact prod_sup_eq_top (λ _ _, h) } lemma pow_sup_pow_eq_top {m n : ℕ} (h : I ⊔ J = ⊤) : (I ^ m) ⊔ (J ^ n) = ⊤ := sup_pow_eq_top (pow_sup_eq_top h) variables (I) @[simp] theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I @[simp] theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I @[simp] theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I @[simp] theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end lemma pow_le_self {n : ℕ} (hn : n ≠ 0) : I^n ≤ I := calc I^n ≤ I ^ 1 : pow_le_pow (nat.pos_of_ne_zero hn) ... = I : pow_one _ lemma pow_mono {I J : ideal R} (e : I ≤ J) (n : ℕ) : I ^ n ≤ J ^ n := begin induction n, { rw [pow_zero, pow_zero], exact rfl.le }, { rw [pow_succ, pow_succ], exact ideal.mul_mono e n_ih } end lemma mul_eq_bot {R : Type*} [comm_semiring R] [no_zero_divisors R] {I J : ideal R} : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj, let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)), λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩ instance {R : Type*} [comm_semiring R] [no_zero_divisors R] : no_zero_divisors (ideal R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ I J, mul_eq_bot.1 } /-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/ lemma prod_eq_bot {R : Type*} [comm_ring R] [is_domain R] {s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ := prod_zero_iff_exists_zero /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right _ $ I.mul_mem_left _ $ nat.add_comm n m ▸ (add_tsub_assoc_of_le hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni) (λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ add_tsub_cancel_of_le hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right _ hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r^n) hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) @[simp] theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J := ⟨λ h, le_trans le_radical h, λ h, radical_idem J ▸ radical_mono h⟩ theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm, (pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn_nonempty_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm) (m.mul_mem_left _ hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr @[simp] lemma radical_bot_of_is_domain {R : Type u} [comm_semiring R] [no_zero_divisors R] : radical (⊥ : ideal R) = ⊥ := eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn)) instance : comm_semiring (ideal R) := submodule.comm_semiring variables (R) theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ := nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul] variables {R} variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : by { rw pow_succ, exact radical_mul _ _ } ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) : I * J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in (hp.mem_or_mem $ h $ mul_mem_mul hi hj).resolve_left hip, λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left) (le_trans $ le_trans mul_le_inf inf_le_right)⟩ theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) : I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h, λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩ theorem is_prime.multiset_prod_le {s : multiset (ideal R)} {P : ideal R} (hp : is_prime P) (hne : s ≠ 0) : s.prod ≤ P ↔ ∃ I ∈ s, I ≤ P := suffices s.prod ≤ P → ∃ I ∈ s, I ≤ P, from ⟨this, λ ⟨i, his, hip⟩, le_trans multiset_prod_le_inf $ le_trans (multiset.inf_le his) hip⟩, begin classical, obtain ⟨b, hb⟩ : ∃ b, b ∈ s := multiset.exists_mem_of_ne_zero hne, obtain ⟨t, rfl⟩ : ∃ t, s = b ::ₘ t, from ⟨s.erase b, (multiset.cons_erase hb).symm⟩, refine t.induction_on _ _, { simp only [exists_prop, ←multiset.singleton_eq_cons, multiset.prod_singleton, multiset.mem_singleton, exists_eq_left, imp_self] }, intros a s ih h, rw [multiset.cons_swap, multiset.prod_cons, hp.mul_le] at h, rw multiset.cons_swap, cases h, { exact ⟨a, multiset.mem_cons_self a _, h⟩ }, obtain ⟨I, hI, ih⟩ : ∃ I ∈ b ::ₘ s, I ≤ P := ih h, exact ⟨I, multiset.mem_cons_of_mem hI, ih⟩ end theorem is_prime.multiset_prod_map_le {s : multiset ι} (f : ι → ideal R) {P : ideal R} (hp : is_prime P) (hne : s ≠ 0) : (s.map f).prod ≤ P ↔ ∃ i ∈ s, f i ≤ P := begin rw hp.multiset_prod_le (mt multiset.map_eq_zero.mp hne), simp_rw [exists_prop, multiset.mem_map, exists_exists_and_eq_and], end theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hne : s.nonempty) : s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P := hp.multiset_prod_map_le f (mt finset.val_eq_zero.mp hne.ne_empty) theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hsne: s.nonempty) : s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P := ⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h, λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩ theorem subset_union {R : Type u} [ring R] {I J K : ideal R} : (I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K := ⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi, let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk, or.cases_on (h $ I.add_mem hri hsi) (λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk)) (λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)), λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K) (λ h, set.subset.trans h $ set.subset_union_right J K)⟩ theorem subset_union_prime' {R : Type u} [comm_ring R] {s : finset ι} {f : ι → ideal R} {a b : ι} (hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} : (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) → I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i, from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_left _ _) (set.subset_union_left _ _)) $ λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_right _ _) (set.subset_union_left _ _)) $ λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $ set.subset_union_right _ _); exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩, begin generalize hn : s.card = n, intros h, unfreezingI { induction n with n ih generalizing a b s }, { clear hp, rw finset.card_eq_zero at hn, subst hn, rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h, simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] }, classical, replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n := finset.card_eq_succ.1 hn, unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ }, replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp, by_cases Ht : ∃ j ∈ t, f j ≤ f i, { obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht, obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t, { exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ }, have hp' : ∀ k ∈ insert i u, is_prime (f k), { rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ }, have hiu : i ∉ u := mt finset.mem_insert_of_mem hit, have hn' : (insert i u).card = n, { rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] }, have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k), { rw finset.coe_insert at h ⊢, rw finset.coe_insert at h, simp only [set.bUnion_insert] at h ⊢, rw [← set.union_assoc ↑(f i)] at h, erw [set.union_eq_self_of_subset_right hfji] at h, exact h }, specialize @ih a b (insert i u) hp' hn' h', refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop], exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id }, by_cases Ha : f a ≤ f i, { have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_right_comm ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Ha] at h, exact h }, specialize @ih i b t hp.2 hn h', right, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ }, { exact or.inl ih }, { exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, by_cases Hb : f b ≤ f i, { have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Hb] at h, exact h }, specialize @ih a i t hp.2 hn h', rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inl ih }, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) }, { exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } }, by_cases Hi : I ≤ f i, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) }, have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i, { rcases t.eq_empty_or_nonempty with (rfl | hsne), { rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib], exact ⟨⟨Hi, Ha⟩, Hb⟩ }, simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib], exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ }, rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩, by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j, { specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { left, exact ih }, { right, left, exact ih }, { right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩, rw [finset.coe_insert, set.bUnion_insert] at h, have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs), rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht, { exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) }, { exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) }, { exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) }, { rw set.mem_Union₂ at ht, rcases ht with ⟨j, hjt, hj⟩, simp only [finset.inf_eq_infi, set_like.mem_coe, submodule.mem_infi] at hr, exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) } end /-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/ theorem subset_union_prime {R : Type u} [comm_ring R] {s : finset ι} {f : ι → ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i, from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $ show i ∈ (↑s : set ι), from his⟩, assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i), begin classical, by_cases has : a ∈ s, { unfreezingI { obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s := ⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩ }, by_cases hbt : b ∈ t, { unfreezingI { obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t := ⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩ }, have hp' : ∀ i ∈ u, is_prime (f i), { intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _; unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert, ← set.union_assoc, subset_union_prime' hp', bex_def] at h, rwa [finset.exists_mem_insert, finset.exists_mem_insert] }, { have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } }, { by_cases hbs : b ∈ s, { unfreezingI { obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s := ⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩ }, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert }, cases s.eq_empty_or_nonempty with hse hsne, { substI hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h, have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem), exact absurd h this }, { cases hsne.bex with i his, unfreezingI { obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s := ⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩ }, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } } end section dvd /-- If `I` divides `J`, then `I` contains `J`. In a Dedekind domain, to divide and contain are equivalent, see `ideal.dvd_iff_le`. -/ lemma le_of_dvd {I J : ideal R} : I ∣ J → J ≤ I | ⟨K, h⟩ := h.symm ▸ le_trans mul_le_inf inf_le_left lemma is_unit_iff {I : ideal R} : is_unit I ↔ I = ⊤ := is_unit_iff_dvd_one.trans ((@one_eq_top R _).symm ▸ ⟨λ h, eq_top_iff.mpr (ideal.le_of_dvd h), λ h, ⟨⊤, by rw [mul_top, h]⟩⟩) instance unique_units : unique ((ideal R)ˣ) := { default := 1, uniq := λ u, units.ext (show (u : ideal R) = 1, by rw [is_unit_iff.mp u.is_unit, one_eq_top]) } end dvd end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} section semiring variables {F : Type*} [semiring R] [semiring S] variables [rc : ring_hom_class F R S] variables (f : F) variables {I J : ideal R} {K L : ideal S} include rc /-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than the image itself. -/ def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, add_mem' := λ x y hx hy, by simp only [set.mem_preimage, set_like.mem_coe, map_add, add_mem hx hy] at *, zero_mem' := by simp only [set.mem_preimage, map_zero, set_like.mem_coe, submodule.zero_mem], smul_mem' := λ c x hx, by { simp only [smul_eq_mul, set.mem_preimage, map_mul, set_like.mem_coe] at *, exact mul_mem_left I _ hx } } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem (f : F) {I : ideal R} {x : R} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ lemma apply_coe_mem_map (f : F) (I : ideal R) (x : I) : f x ∈ I.map f := mem_map_of_mem f x.prop theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, map_one]; exact (ne_top_iff_one _).1 hK variables {G : Type*} [rcg : ring_hom_class G S R] include rcg lemma map_le_comap_of_inv_on (g : G) (I : ideal R) (hf : set.left_inv_on g f I) : I.map f ≤ I.comap g := begin refine ideal.span_le.2 _, rintros x ⟨x, hx, rfl⟩, rw [set_like.mem_coe, mem_comap, hf hx], exact hx, end lemma comap_le_map_of_inv_on (g : G) (I : ideal S) (hf : set.left_inv_on g f (f ⁻¹' I)) : I.comap f ≤ I.map g := λ x (hx : f x ∈ I), hf hx ▸ ideal.mem_map_of_mem g hx /-- The `ideal` version of `set.image_subset_preimage_of_inverse`. -/ lemma map_le_comap_of_inverse (g : G) (I : ideal R) (h : function.left_inverse g f) : I.map f ≤ I.comap g := map_le_comap_of_inv_on _ _ _ $ h.left_inv_on _ /-- The `ideal` version of `set.preimage_subset_image_of_inverse`. -/ lemma comap_le_map_of_inverse (g : G) (I : ideal S) (h : function.left_inverse g f) : I.comap f ≤ I.map g := comap_le_map_of_inv_on _ _ _ $ h.left_inv_on _ omit rcg instance is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, map_one f⟩ variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap omit rc @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [semiring T] {I : ideal T} (f : R →+* S) (g : S →+* T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [semiring T] {I : ideal R} (f : R →+* S) (g : S →+* T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) include rc lemma map_span (f : F) (s : set R) : map f (span s) = span (f '' s) := symm $ submodule.span_eq_of_le _ (λ y ⟨x, hy, x_eq⟩, x_eq ▸ mem_map_of_mem f (subset_span hy)) (map_le_iff_le_comap.2 $ span_le.2 $ set.image_subset_iff.1 subset_span) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (map_one f ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f : galois_connection (map f) (comap f)).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f : galois_connection (map f) (comap f)).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f : galois_connection (map f) (comap f)).u_Inf lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I := trans (comap_Inf f s) (by rw infi_image) theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) := ⟨comap_ne_top f H.ne_top, λ x y h, H.mem_or_mem $ by rwa [mem_comap, map_mul] at h⟩ variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f : galois_connection (map f) (comap f)).monotone_l.map_inf_le _ _ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f : galois_connection (map f) (comap f)).monotone_u.le_map_sup _ _ omit rc @[simp] lemma smul_top_eq_map {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S] (I : ideal R) : I • (⊤ : submodule R S) = (I.map (algebra_map R S)).restrict_scalars R := begin refine le_antisymm (submodule.smul_le.mpr (λ r hr y _, _) ) (λ x hx, submodule.span_induction hx _ _ _ _), { rw algebra.smul_def, exact mul_mem_right _ _ (mem_map_of_mem _ hr) }, { rintros _ ⟨x, hx, rfl⟩, rw [← mul_one (algebra_map R S x), ← algebra.smul_def], exact submodule.smul_mem_smul hx submodule.mem_top }, { exact submodule.zero_mem _ }, { intros x y, exact submodule.add_mem _ }, intros a x hx, refine submodule.smul_induction_on hx _ _, { intros r hr s hs, rw smul_comm, exact submodule.smul_mem_smul hr submodule.mem_top }, { intros x y hx hy, rw smul_add, exact submodule.add_mem _ hx hy }, end section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 le_rfl) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem f $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, map_zero f⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ map_add f _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d * x, I.mul_mem_left _ hxi, hdc ▸ hxy ▸ map_mul f _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem f hx.left)⟩ lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h end surjective section injective variables (hf : function.injective f) include hf lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective end semiring section ring variables {F : Type*} [ring R] [ring S] variables [ring_hom_class F R S] (f : F) {I : ideal R} section surjective variables (hf : function.surjective f) include hf theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 le_rfl) (comap_mono bot_le)) /-- Correspondence theorem -/ def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le le_rfl I.2) le_sup_left, map_rel_iff' := λ I1 I2, ⟨λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H, comap_mono⟩ } /-- The map on ideals induced by a surjective map preserves inclusion. -/ def order_embedding_of_surjective : ideal S ↪o ideal R := (rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _) theorem map_eq_top_or_is_maximal_of_surjective {I : ideal R} (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine or_iff_not_imp_left.2 (λ ne_top, ⟨⟨λ h, ne_top h, λ J hJ, _⟩⟩), { refine (rel_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.1.2 (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end theorem comap_is_maximal_of_surjective {K : ideal S} [H : is_maximal K] : is_maximal (comap f K) := begin refine ⟨⟨comap_ne_top _ H.1.1, λ J hJ, _⟩⟩, suffices : map f J = ⊤, { replace this := congr_arg (comap f) this, rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this, rw eq_top_iff, exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) }, refine H.1.2 (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ)) (λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))), rw [comap_map_of_surjective _ hf, sup_eq_left], exact le_trans (comap_mono bot_le) (le_of_lt hJ) end theorem comap_le_comap_iff_of_surjective (I J : ideal S) : comap f I ≤ comap f J ↔ I ≤ J := ⟨λ h, (map_comap_of_surjective f hf I).symm.le.trans (map_le_of_le_comap h), λ h, le_comap_of_map_le ((map_comap_of_surjective f hf I).le.trans h)⟩ end surjective /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f (map f.symm) = I`. -/ @[simp] lemma map_of_equiv (I : ideal R) (f : R ≃+* S) : (I.map (f : R →+* S)).map (f.symm : S →+* R) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, map_map] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `comap f.symm (comap f) = I`. -/ @[simp] lemma comap_of_equiv (I : ideal R) (f : R ≃+* S) : (I.comap (f.symm : S →+* R)).comap (f : R →+* S) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, comap_comap] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f I = comap f.symm I`. -/ lemma map_comap_of_equiv (I : ideal R) (f : R ≃+* S) : I.map (f : R →+* S) = I.comap f.symm := le_antisymm (le_comap_of_map_le (map_of_equiv I f).le) (le_map_of_comap_le_of_surjective _ f.surjective (comap_of_equiv I f).le) section bijective variables (hf : function.bijective f) include hf /-- Special case of the correspondence theorem for isomorphic rings -/ def rel_iso_of_bijective : ideal S ≃o ideal R := { to_fun := comap f, inv_fun := map f, left_inv := (rel_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' } lemma comap_le_iff_le_map {I : ideal R} {K : ideal S} : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal {I : ideal R} (H : is_maximal I) : is_maximal (map f I) := by refine or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.1.1 _); calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top end bijective lemma ring_equiv.bot_maximal_iff (e : R ≃+* S) : (⊥ : ideal R).is_maximal ↔ (⊥ : ideal S).is_maximal := ⟨λ h, (@map_bot _ _ _ _ _ _ e.to_ring_hom) ▸ map.is_maximal e.to_ring_hom e.bijective h, λ h, (@map_bot _ _ _ _ _ _ e.symm.to_ring_hom) ▸ map.is_maximal e.symm.to_ring_hom e.symm.bijective h⟩ end ring section comm_ring variables {F : Type*} [comm_ring R] [comm_ring S] variables [rc : ring_hom_class F R S] variables (f : F) variables {I J : ideal R} {K L : ideal S} variables (I J K L) include rc theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw map_mul; exact mul_mem_mul (mem_map_of_mem f hri) (mem_map_of_mem f hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.Union₂_subset $ λ i ⟨r, hri, hfri⟩, set.Union₂_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← map_mul]; exact mem_map_of_mem f (mul_mem_mul hri hsj)) /-- The pushforward `ideal.map` as a monoid-with-zero homomorphism. -/ @[simps] def map_hom : ideal R →*₀ ideal S := { to_fun := map f, map_mul' := λ I J, ideal.map_mul f I J, map_one' := by convert ideal.map_top f; exact one_eq_top, map_zero' := ideal.map_bot } protected theorem map_pow (n : ℕ) : map f (I^n) = (map f I)^n := map_pow (map_hom f) I n theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (map_pow f r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, map_pow f r n ▸ hfrnk⟩) omit rc @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot (R ⧸ I)).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} include rc theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, map_pow f r n ▸ mem_map_of_mem f hrni⟩ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_rfl) (map_le_iff_le_comap.2 $ le_rfl) lemma le_comap_pow (n : ℕ) : (K.comap f) ^ n ≤ (K ^ n).comap f := begin induction n, { rw [pow_zero, pow_zero, ideal.one_eq_top, ideal.one_eq_top], exact rfl.le }, { rw [pow_succ, pow_succ], exact (ideal.mul_mono_right n_ih).trans (ideal.le_comap_mul f) } end omit rc end comm_ring end map_and_comap section is_primary variables {R : Type u} [comm_semiring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_prime.is_primary {I : ideal R} (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.mem_or_mem hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary section total variables (ι : Type*) variables (M : Type*) [add_comm_group M] {R : Type*} [comm_ring R] [module R M] (I : ideal R) variables (v : ι → M) (hv : submodule.span R (set.range v) = ⊤) open_locale big_operators /-- A variant of `finsupp.total` that takes in vectors valued in `I`. -/ noncomputable def finsupp_total : (ι →₀ I) →ₗ[R] M := (finsupp.total ι M R v).comp (finsupp.map_range.linear_map I.subtype) variables {ι M v} lemma finsupp_total_apply (f : ι →₀ I) : finsupp_total ι M I v f = f.sum (λ i x, (x : R) • v i) := begin dsimp [finsupp_total], rw [finsupp.total_apply, finsupp.sum_map_range_index], exact λ _, zero_smul _ _ end lemma finsupp_total_apply_eq_of_fintype [fintype ι] (f : ι →₀ I) : finsupp_total ι M I v f = ∑ i, (f i : R) • v i := by { rw [finsupp_total_apply, finsupp.sum_fintype], exact λ _, zero_smul _ _ } lemma range_finsupp_total : (finsupp_total ι M I v).range = I • (submodule.span R (set.range v)) := begin ext, rw submodule.mem_ideal_smul_span_iff_exists_sum, refine ⟨λ ⟨f, h⟩, ⟨finsupp.map_range.linear_map I.subtype f, λ i, (f i).2, h⟩, _⟩, rintro ⟨a, ha, rfl⟩, classical, refine ⟨a.map_range (λ r, if h : r ∈ I then ⟨r, h⟩ else 0) (by split_ifs; refl), _⟩, rw [finsupp_total_apply, finsupp.sum_map_range_index], { apply finsupp.sum_congr, intros i _, rw dif_pos (ha i), refl }, { exact λ _, zero_smul _ _ }, end end total end ideal lemma associates.mk_ne_zero' {R : Type*} [comm_semiring R] {r : R} : (associates.mk (ideal.span {r} : ideal R)) ≠ 0 ↔ (r ≠ 0):= by rw [associates.mk_ne_zero, ideal.zero_eq_bot, ne.def, ideal.span_singleton_eq_bot] namespace ring_hom variables {R : Type u} {S : Type v} {T : Type v} section semiring variables {F : Type*} {G : Type*} [semiring R] [semiring S] [semiring T] variables [rcf : ring_hom_class F R S] [rcg : ring_hom_class G T S] (f : F) (g : G) include rcf /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = set.preimage f {0} := rfl lemma ker_eq_comap_bot (f : F) : ker f = ideal.comap f ⊥ := rfl omit rcf lemma comap_ker (f : S →+* R) (g : T →+* S) : f.ker.comap g = (f.comp g).ker := by rw [ring_hom.ker_eq_comap_bot, ideal.comap_comap, ring_hom.ker_eq_comap_bot] include rcf /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : F) : (1:R) ∉ ker f := by { rw [mem_ker, map_one], exact one_ne_zero } lemma ker_ne_top [nontrivial S] (f : F) : ker f ≠ ⊤ := (ideal.ne_top_iff_one _).mpr $ not_one_mem_ker f omit rcf end semiring section ring variables {F : Type*} [ring R] [semiring S] [rc : ring_hom_class F R S] (f : F) include rc lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by { rw [set_like.ext'_iff, ker_eq, set.ext_iff], exact injective_iff_map_eq_zero' f } lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by { rw [← injective_iff_map_eq_zero f, injective_iff_ker_eq_bot] } omit rc @[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using equiv_like.injective f @[simp] lemma ker_equiv {F' : Type*} [ring_equiv_class F' R S] (f : F') : ker f = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using equiv_like.injective f end ring section comm_ring variables [comm_ring R] [comm_ring S] (f : R →+* S) /-- The induced map from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) / is surjective (`quotient_ker_equiv_of_surjective`). -/ def ker_lift (f : R →+* S) : R ⧸ f.ker →+* S := ideal.quotient.lift _ f $ λ r, f.mem_ker.mp @[simp] lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r := ideal.quotient.lift_mk _ _ _ /-- The induced map from the quotient by the kernel is injective. -/ lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) := assume a b, quotient.induction_on₂' a b $ assume a b (h : f a = f b), ideal.quotient.eq.2 $ show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self] variable {f} /-- The **first isomorphism theorem** for commutative rings, computable version. -/ def quotient_ker_equiv_of_right_inverse {g : S → R} (hf : function.right_inverse g f) : R ⧸ f.ker ≃+* S := { to_fun := ker_lift f, inv_fun := (ideal.quotient.mk f.ker) ∘ g, left_inv := begin rintro ⟨x⟩, apply ker_lift_injective, simp [hf (f x)], end, right_inv := hf, ..ker_lift f} @[simp] lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f) (x : R ⧸ f.ker) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl @[simp] lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f) (x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl /-- The **first isomorphism theorem** for commutative rings. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) : R ⧸ f.ker ≃+* S := quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) end comm_ring /-- The kernel of a homomorphism to a domain is a prime ideal. -/ lemma ker_is_prime {F : Type*} [ring R] [ring S] [is_domain S] [ring_hom_class F R S] (f : F) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ /-- The kernel of a homomorphism to a field is a maximal ideal. -/ lemma ker_is_maximal_of_surjective {R K F : Type*} [ring R] [field K] [ring_hom_class F R K] (f : F) (hf : function.surjective f) : (ker f).is_maximal := begin refine ideal.is_maximal_iff.mpr ⟨λ h1, @one_ne_zero K _ _ $ map_one f ▸ (mem_ker f).mp h1, λ J x hJ hxf hxJ, _⟩, obtain ⟨y, hy⟩ := hf (f x)⁻¹, have H : 1 = y * x - (y * x - 1) := (sub_sub_cancel _ _).symm, rw H, refine J.sub_mem (J.mul_mem_left _ hxJ) (hJ _), rw mem_ker, simp only [hy, map_sub, map_one, map_mul, inv_mul_cancel (mt (mem_ker f).mpr hxf), sub_self], end end ring_hom namespace ideal variables {R : Type*} {S : Type*} {F : Type*} section semiring variables [semiring R] [semiring S] [rc : ring_hom_class F R S] include rc lemma map_eq_bot_iff_le_ker {I : ideal R} (f : F) : I.map f = ⊥ ↔ I ≤ (ring_hom.ker f) := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_le_comap {K : ideal S} (f : F) : ring_hom.ker f ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) end semiring section ring variables [ring R] [ring S] [rc : ring_hom_class F R S] include rc lemma map_Inf {A : set (ideal R)} {f : F} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem f (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, refine hx ▸ (mem_map_of_mem f _), have : ∀ I ∈ A, y ∈ map f I, by simpa using hy, rw [submodule.mem_Inf], intros J hJ, rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩, have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, map_sub, hx, sub_self] }, simpa only [sub_add_cancel] using J.add_mem this hx' } end theorem map_is_prime_of_surjective {f : F} (hf : function.surjective f) {I : ideal R} [H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) := begin refine ⟨λ h, H.ne_top (eq_top_iff.2 _), λ x y, _⟩, { replace h := congr_arg (comap f) h, rw [comap_map_of_surjective _ hf, comap_top] at h, exact h ▸ sup_le (le_of_eq rfl) hk }, { refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)), rw [← ha, ← hb, ← _root_.map_mul f, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ ring_hom.ker f)), abel }, exact (H.mem_or_mem this).imp (λ h, ha ▸ mem_map_of_mem f h) (λ h, hb ▸ mem_map_of_mem f h) } end omit rc theorem map_is_prime_of_equiv {F' : Type*} [ring_equiv_class F' R S] (f : F') {I : ideal R} [is_prime I] : is_prime (map f I) := map_is_prime_of_surjective (equiv_like.surjective f) $ by simp only [ring_hom.ker_equiv, bot_le] end ring section comm_ring variables [comm_ring R] [comm_ring S] @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] lemma map_mk_eq_bot_of_le {I J : ideal R} (h : I ≤ J) : I.map (J^.quotient.mk) = ⊥ := by { rw [map_eq_bot_iff_le_ker, mk_ker], exact h } lemma ker_quotient_lift {S : Type v} [comm_ring S] {I : ideal R} (f : R →+* S) (H : I ≤ f.ker) : (ideal.quotient.lift I f H).ker = (f.ker).map I^.quotient.mk := begin ext x, split, { intro hx, obtain ⟨y, hy⟩ := quotient.mk_surjective x, rw [ring_hom.mem_ker, ← hy, ideal.quotient.lift_mk, ← ring_hom.mem_ker] at hx, rw [← hy, mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective], exact ⟨y, hx, rfl⟩ }, { intro hx, rw mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective at hx, obtain ⟨y, hy⟩ := hx, rw [ring_hom.mem_ker, ← hy.right, ideal.quotient.lift_mk, ← (ring_hom.mem_ker f)], exact hy.left }, end theorem map_eq_iff_sup_ker_eq_of_surjective {I J : ideal R} (f : R →+* S) (hf : function.surjective f) : map f I = map f J ↔ I ⊔ f.ker = J ⊔ f.ker := by rw [← (comap_injective_of_surjective f hf).eq_iff, comap_map_of_surjective f hf, comap_map_of_surjective f hf, ring_hom.ker_eq_comap_bot] theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} (h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical := begin rw [radical_eq_Inf, radical_eq_Inf], have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, convert map_Inf hf this, refine funext (λ j, propext ⟨_, _⟩), { rintros ⟨hj, hj'⟩, haveI : j.is_prime := hj', exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩, map_comap_of_surjective f hf j⟩⟩ }, { rintro ⟨J, ⟨hJ, hJ'⟩⟩, haveI : J.is_prime := hJ.right, refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ }, end @[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) : (⊥ : ideal (R ⧸ I)).is_maximal ↔ I.is_maximal := ⟨λ hI, (@mk_ker _ _ I) ▸ @comap_is_maximal_of_surjective _ _ _ _ _ _ (quotient.mk I) quotient.mk_surjective ⊥ hI, λ hI, @bot_is_maximal _ (@field.to_division_ring _ (@quotient.field _ _ I hI)) ⟩ /-- See also `ideal.mem_quotient_iff_mem` in case `I ≤ J`. -/ @[simp] lemma mem_quotient_iff_mem_sup {I J : ideal R} {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J ⊔ I := by rw [← mem_comap, comap_map_of_surjective (quotient.mk I) quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot, mk_ker] /-- See also `ideal.mem_quotient_iff_mem_sup` if the assumption `I ≤ J` is not available. -/ lemma mem_quotient_iff_mem {I J : ideal R} (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := by rw [mem_quotient_iff_mem_sup, sup_eq_left.mpr hIJ] section quotient_algebra variables (R₁ R₂ : Type*) {A B : Type*} variables [comm_semiring R₁] [comm_semiring R₂] [comm_ring A] [comm_ring B] variables [algebra R₁ A] [algebra R₂ A] [algebra R₁ B] /-- The `R₁`-algebra structure on `A/I` for an `R₁`-algebra `A` -/ instance quotient.algebra {I : ideal A} : algebra R₁ (A ⧸ I) := { to_fun := λ x, ideal.quotient.mk I (algebra_map R₁ A x), smul := (•), smul_def' := λ r x, quotient.induction_on' x $ λ x, ((quotient.mk I).congr_arg $ algebra.smul_def _ _).trans (ring_hom.map_mul _ _ _), commutes' := λ _ _, mul_comm _ _, .. ring_hom.comp (ideal.quotient.mk I) (algebra_map R₁ A) } -- Lean can struggle to find this instance later if we don't provide this shortcut instance quotient.is_scalar_tower [has_smul R₁ R₂] [is_scalar_tower R₁ R₂ A] (I : ideal A) : is_scalar_tower R₁ R₂ (A ⧸ I) := by apply_instance /-- The canonical morphism `A →ₐ[R₁] A ⧸ I` as morphism of `R₁`-algebras, for `I` an ideal of `A`, where `A` is an `R₁`-algebra. -/ def quotient.mkₐ (I : ideal A) : A →ₐ[R₁] A ⧸ I := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩ lemma quotient.alg_map_eq (I : ideal A) : algebra_map R₁ (A ⧸ I) = (algebra_map A (A ⧸ I)).comp (algebra_map R₁ A) := rfl lemma quotient.mkₐ_to_ring_hom (I : ideal A) : (quotient.mkₐ R₁ I).to_ring_hom = ideal.quotient.mk I := rfl @[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) : ⇑(quotient.mkₐ R₁ I) = ideal.quotient.mk I := rfl @[simp] lemma quotient.algebra_map_eq (I : ideal R) : algebra_map R (R ⧸ I) = I^.quotient.mk := rfl @[simp] lemma quotient.mk_comp_algebra_map (I : ideal A) : (quotient.mk I).comp (algebra_map R₁ A) = algebra_map R₁ (A ⧸ I) := rfl @[simp] lemma quotient.mk_algebra_map (I : ideal A) (x : R₁) : quotient.mk I (algebra_map R₁ A x) = algebra_map R₁ (A ⧸ I) x := rfl /-- The canonical morphism `A →ₐ[R₁] I.quotient` is surjective. -/ lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R₁ I) := surjective_quot_mk _ /-- The kernel of `A →ₐ[R₁] I.quotient` is `I`. -/ @[simp] lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R₁ I : A →+* A ⧸ I).ker = I := ideal.mk_ker variables {R₁} /-- `ideal.quotient.lift` as an `alg_hom`. -/ def quotient.liftₐ (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) : A ⧸ I →ₐ[R₁] B := { commutes' := λ r, begin -- this is is_scalar_tower.algebra_map_apply R₁ A (A ⧸ I) but the file `algebra.algebra.tower` -- imports this file. have : algebra_map R₁ (A ⧸ I) r = algebra_map A (A ⧸ I) (algebra_map R₁ A r), { simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] }, rw [this, ideal.quotient.algebra_map_eq, ring_hom.to_fun_eq_coe, ideal.quotient.lift_mk, alg_hom.coe_to_ring_hom, algebra.algebra_map_eq_smul_one, algebra.algebra_map_eq_smul_one, map_smul, map_one], end ..(ideal.quotient.lift I (f : A →+* B) hI) } @[simp] lemma quotient.liftₐ_apply (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) (x) : ideal.quotient.liftₐ I f hI x = ideal.quotient.lift I (f : A →+* B) hI x := rfl lemma quotient.liftₐ_comp (I : ideal A) (f : A →ₐ[R₁] B) (hI : ∀ (a : A), a ∈ I → f a = 0) : (ideal.quotient.liftₐ I f hI).comp (ideal.quotient.mkₐ R₁ I) = f := alg_hom.ext (λ x, (ideal.quotient.lift_mk I (f : A →+* B) hI : _)) lemma ker_lift.map_smul (f : A →ₐ[R₁] B) (r : R₁) (x : A ⧸ f.to_ring_hom.ker) : f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x := begin obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R₁ _ x, rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk], exact f.map_smul _ _ end /-- The induced algebras morphism from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) / is surjective (`quotient_ker_alg_equiv_of_surjective`). -/ def ker_lift_alg (f : A →ₐ[R₁] B) : (A ⧸ f.to_ring_hom.ker) →ₐ[R₁] B := alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _) @[simp] lemma ker_lift_alg_mk (f : A →ₐ[R₁] B) (a : A) : ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl @[simp] lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R₁] B) : (ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl /-- The induced algebra morphism from the quotient by the kernel is injective. -/ lemma ker_lift_alg_injective (f : A →ₐ[R₁] B) : function.injective (ker_lift_alg f) := ring_hom.ker_lift_injective f /-- The **first isomorphism** theorem for algebras, computable version. -/ def quotient_ker_alg_equiv_of_right_inverse {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) : (A ⧸ f.to_ring_hom.ker) ≃ₐ[R₁] B := { ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x), ..ker_lift_alg f} @[simp] lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) (x : A ⧸ f.to_ring_hom.ker) : quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl @[simp] lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) (x : B) : (quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R₁ f.to_ring_hom.ker (g x) := rfl /-- The **first isomorphism theorem** for algebras. -/ noncomputable def quotient_ker_alg_equiv_of_surjective {f : A →ₐ[R₁] B} (hf : function.surjective f) : (A ⧸ f.to_ring_hom.ker) ≃ₐ[R₁] B := quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) /-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : R ⧸ I →+* S ⧸ J := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) @[simp] lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} {x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) := quotient.lift_mk J _ _ @[simp] lemma quotient_map_algebra_map {J : ideal A} {I : ideal S} {f : A →+* S} {H : J ≤ I.comap f} {x : R₁} : quotient_map I f H (algebra_map R₁ (A ⧸ J) x) = quotient.mk I (f (algebra_map _ _ x)) := quotient.lift_mk J _ _ lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) : (quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f := ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk]) /-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/ @[simps] def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) : R ⧸ I ≃+* S ⧸ J := { inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}), left_inv := by {rintro ⟨r⟩, simp }, right_inv := by {rintro ⟨s⟩, simp }, ..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _ _ _}) } @[simp] lemma quotient_equiv_mk (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) (x : R) : quotient_equiv I J f hIJ (ideal.quotient.mk I x) = ideal.quotient.mk J (f x) := rfl @[simp] lemma quotient_equiv_symm_mk (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) (x : S) : (quotient_equiv I J f hIJ).symm (ideal.quotient.mk J x) = ideal.quotient.mk I (f.symm x) := rfl /-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/ lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (h : I.comap f ≤ J) : function.injective (quotient_map I f H) := begin refine (injective_iff_map_eq_zero (quotient_map I f H)).2 (λ a ha, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha, exact (quotient.eq_zero_iff_mem).mpr (h ha), end /-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/ lemma quotient_map_injective {I : ideal S} {f : R →+* S} : function.injective (quotient_map I f le_rfl) := quotient_map_injective' le_rfl lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (hf : function.surjective f) : function.surjective (quotient_map I f H) := λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩ /-- Commutativity of a square is preserved when taking quotients by an ideal. -/ lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S'] {f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f) (I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) = (quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g (le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) := begin refine ring_hom.ext (λ a, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, simp only [ring_hom.comp_apply, quotient_map_mk], exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))), end /-- The algebra hom `A/I →+* B/J` induced by an algebra hom `f : A →ₐ[R₁] B` with `I ≤ f⁻¹(J)`. -/ def quotient_mapₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (hIJ : I ≤ J.comap f) : A ⧸ I →ₐ[R₁] B ⧸ J := { commutes' := λ r, by simp, ..quotient_map J (f : A →+* B) hIJ } @[simp] lemma quotient_map_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) {x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R₁ J (f x) := rfl lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) : (quotient_mapₐ J f H).comp (quotient.mkₐ R₁ I) = (quotient.mkₐ R₁ J).comp f := alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply]) /-- The algebra equiv `A/I ≃ₐ[R] B/J` induced by an algebra equiv `f : A ≃ₐ[R] B`, where`J = f(I)`. -/ def quotient_equiv_alg (I : ideal A) (J : ideal B) (f : A ≃ₐ[R₁] B) (hIJ : J = I.map (f : A →+* B)) : (A ⧸ I) ≃ₐ[R₁] B ⧸ J := { commutes' := λ r, by simp, ..quotient_equiv I J (f : A ≃+* B) hIJ } @[priority 100] instance quotient_algebra {I : ideal A} [algebra R A] : algebra (R ⧸ I.comap (algebra_map R A)) (A ⧸ I) := (quotient_map I (algebra_map R A) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective {I : ideal A} [algebra R A]: function.injective (algebra_map (R ⧸ I.comap (algebra_map R A)) (A ⧸ I)) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end end quotient_algebra end comm_ring end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_semiring R] [add_comm_monoid M] [module R M] -- TODO: show `[algebra R A] : algebra (ideal R) A` too instance module_submodule : module (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := submodule.smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule namespace ring_hom variables {A B C : Type*} [ring A] [ring B] [ring C] variables (f : A →+* B) (f_inv : B → A) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) : B →+* C := { to_fun := λ b, g (f_inv b), map_one' := begin rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one], exact hf 1 end, map_mul' := begin intros x y, rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul], simp only [hf _], end, .. add_monoid_hom.lift_of_right_inverse f.to_add_monoid_hom f_inv hf ⟨g.to_add_monoid_hom, hg⟩ } @[simp] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f a) = g a := f.to_add_monoid_hom.lift_of_right_inverse_comp_apply f_inv hf ⟨g.to_add_monoid_hom, hg⟩ a /-- `lift_of_right_inverse f hf g hg` is the unique ring homomorphism `φ` * such that `φ.comp f = g` (`ring_hom.lift_of_right_inverse_comp`), * where `f : A →+* B` is has a right_inverse `f_inv` (`hf`), * and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`. See `ring_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` A . | \ f | \ g | \ v \⌟ B ----> C ∃!φ ``` -/ def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `ring_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) (x : A) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := ring_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end ring_hom namespace double_quot open ideal variables {R : Type u} [comm_ring R] (I J : ideal R) /-- The obvious ring hom `R/I → R/(I ⊔ J)` -/ def quot_left_to_quot_sup : R ⧸ I →+* R ⧸ (I ⊔ J) := ideal.quotient.factor I (I ⊔ J) le_sup_left /-- The kernel of `quot_left_to_quot_sup` -/ lemma ker_quot_left_to_quot_sup : (quot_left_to_quot_sup I J).ker = J.map (ideal.quotient.mk I) := by simp only [mk_ker, sup_idem, sup_comm, quot_left_to_quot_sup, quotient.factor, ker_quotient_lift, map_eq_iff_sup_ker_eq_of_surjective I^.quotient.mk quotient.mk_surjective, ← sup_assoc] /-- The ring homomorphism `(R/I)/J' -> R/(I ⊔ J)` induced by `quot_left_to_quot_sup` where `J'` is the image of `J` in `R/I`-/ def quot_quot_to_quot_sup : (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) →+* R ⧸ I ⊔ J := by exact ideal.quotient.lift (J.map (ideal.quotient.mk I)) (quot_left_to_quot_sup I J) (ker_quot_left_to_quot_sup I J).symm.le /-- The composite of the maps `R → (R/I)` and `(R/I) → (R/I)/J'` -/ def quot_quot_mk : R →+* ((R ⧸ I) ⧸ J.map I^.quotient.mk) := by exact ((J.map I^.quotient.mk)^.quotient.mk).comp I^.quotient.mk /-- The kernel of `quot_quot_mk` -/ lemma ker_quot_quot_mk : (quot_quot_mk I J).ker = I ⊔ J := by rw [ring_hom.ker_eq_comap_bot, quot_quot_mk, ← comap_comap, ← ring_hom.ker, mk_ker, comap_map_of_surjective (ideal.quotient.mk I) (quotient.mk_surjective), ← ring_hom.ker, mk_ker, sup_comm] /-- The ring homomorphism `R/(I ⊔ J) → (R/I)/J' `induced by `quot_quot_mk` -/ def lift_sup_quot_quot_mk (I J : ideal R) : R ⧸ (I ⊔ J) →+* (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) := ideal.quotient.lift (I ⊔ J) (quot_quot_mk I J) (ker_quot_quot_mk I J).symm.le /-- `quot_quot_to_quot_add` and `lift_sup_double_qot_mk` are inverse isomorphisms -/ def quot_quot_equiv_quot_sup : (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) ≃+* R ⧸ I ⊔ J := ring_equiv.of_hom_inv (quot_quot_to_quot_sup I J) (lift_sup_quot_quot_mk I J) (by { ext z, refl }) (by { ext z, refl }) @[simp] lemma quot_quot_equiv_quot_sup_quot_quot_mk (x : R) : quot_quot_equiv_quot_sup I J (quot_quot_mk I J x) = ideal.quotient.mk (I ⊔ J) x := rfl @[simp] lemma quot_quot_equiv_quot_sup_symm_quot_quot_mk (x : R) : (quot_quot_equiv_quot_sup I J).symm (ideal.quotient.mk (I ⊔ J) x) = quot_quot_mk I J x := rfl /-- The obvious isomorphism `(R/I)/J' → (R/J)/I' ` -/ def quot_quot_equiv_comm : (R ⧸ I) ⧸ J.map I^.quotient.mk ≃+* (R ⧸ J) ⧸ I.map J^.quotient.mk := ((quot_quot_equiv_quot_sup I J).trans (quot_equiv_of_eq sup_comm)).trans (quot_quot_equiv_quot_sup J I).symm @[simp] lemma quot_quot_equiv_comm_quot_quot_mk (x : R) : quot_quot_equiv_comm I J (quot_quot_mk I J x) = quot_quot_mk J I x := rfl @[simp] lemma quot_quot_equiv_comm_comp_quot_quot_mk : ring_hom.comp ↑(quot_quot_equiv_comm I J) (quot_quot_mk I J) = quot_quot_mk J I := ring_hom.ext $ quot_quot_equiv_comm_quot_quot_mk I J @[simp] lemma quot_quot_equiv_comm_symm : (quot_quot_equiv_comm I J).symm = quot_quot_equiv_comm J I := rfl end double_quot
c71af327df1c963b7df3cb0f16412a0b498bfa80
e21db629d2e37a833531fdcb0b37ce4d71825408
/src/def_lookup.lean
a672400c2e5848bfa1f31f9a575ef8b4440d4567
[]
no_license
fischerman/GPU-transformation-verifier
614a28cb4606a05a0eb27e8d4eab999f4f5ea60c
75a5016f05382738ff93ce5859c4cfa47ccb63c1
refs/heads/master
1,586,985,789,300
1,579,290,514,000
1,579,290,514,000
165,031,073
1
0
null
null
null
null
UTF-8
Lean
false
false
102
lean
import ..alt.def_lookup import parlang import mcl import syncablep meta def main := def_lookup.main
cb86eadda7bfe0951d8414827b3ec62a7c82696b
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/linarith/parsing.lean
c31cdc3b9fcee330dd77d25d9e169ff29f4a44b3
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
7,534
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 tactic.linarith.datatypes /-! # Parsing input expressions into linear form `linarith` computes the linear form of its input expressions, assuming (without justification) that the type of these expressions is a commutative semiring. It identifies atoms up to ring-equivalence: that is, `(y*3)*x` will be identified `3*(x*y)`, where the monomial `x*y` is the linear atom. * Variables are represented by natural numbers. * Monomials are represented by `monom := rb_map ℕ ℕ`. The monomial `1` is represented by the empty map. * Linear combinations of monomials are represented by `sum := rb_map monom ℤ`. All input expressions are converted to `sum`s, preserving the map from expressions to variables. We then discard the monomial information, mapping each distinct monomial to a natural number. The resulting `rb_map ℕ ℤ` represents the ring-normalized linear form of the expression. This is ultimately converted into a `linexp` in the obvious way. `linear_forms_and_vars` is the main entry point into this file. Everything else is contained. -/ open native linarith.ineq tactic namespace linarith /-! ### Parsing datatypes -/ /-- Variables (represented by natural numbers) map to their power. -/ @[reducible] meta def monom : Type := rb_map ℕ ℕ /-- `1` is represented by the empty monomial, the product of no variables. -/ meta def monom.one : monom := rb_map.mk _ _ /-- Compare monomials by first comparing their keys and then their powers. -/ @[reducible] meta def monom.lt : monom → monom → Prop := λ a b, (a.keys < b.keys) || ((a.keys = b.keys) && (a.values < b.values)) meta instance : has_lt monom := ⟨monom.lt⟩ /-- Linear combinations of monomials are represented by mapping monomials to coefficients. -/ @[reducible] meta def sum : Type := rb_map monom ℤ /-- `1` is represented as the singleton sum of the monomial `monom.one` with coefficient 1. -/ meta def sum.one : sum := rb_map.of_list [(monom.one, 1)] /-- `sum.scale_by_monom s m` multiplies every monomial in `s` by `m`. -/ meta def sum.scale_by_monom (s : sum) (m : monom) : sum := s.fold mk_rb_map $ λ m' coeff sm, sm.insert (m.add m') coeff /-- `sum.mul s1 s2` distributes the multiplication of two sums.` -/ meta def sum.mul (s1 s2 : sum) : sum := s1.fold mk_rb_map $ λ mn coeff sm, sm.add $ (s2.scale_by_monom mn).scale coeff /-- The `n`th power of `s : sum` is the `n`-fold product of `s`, with `s.pow 0 = sum.one`. -/ meta def sum.pow (s : sum) : ℕ → sum | 0 := sum.one | (k+1) := s.mul (sum.pow k) /-- `sum_of_monom m` lifts `m` to a sum with coefficient `1`. -/ meta def sum_of_monom (m : monom) : sum := mk_rb_map.insert m 1 /-- The unit monomial `one` is represented by the empty rb map. -/ meta def one : monom := mk_rb_map /-- A scalar `z` is represented by a `sum` with coefficient `z` and monomial `one` -/ meta def scalar (z : ℤ) : sum := mk_rb_map.insert one z /-- A single variable `n` is represented by a sum with coefficient `1` and monomial `n`. -/ meta def var (n : ℕ) : sum := mk_rb_map.insert (mk_rb_map.insert n 1) 1 /-! ### Parsing algorithms -/ local notation `exmap` := list (expr × ℕ) /-- `linear_form_of_atom red map e` is the atomic case for `linear_form_of_expr`. If `e` appears with index `k` in `map`, it returns the singleton sum `var k`. Otherwise it updates `map`, adding `e` with index `n`, and returns the singleton sum `var n`. -/ meta def linear_form_of_atom (red : transparency) (m : exmap) (e : expr) : tactic (exmap × sum) := (do (_, k) ← m.find_defeq red e, return (m, var k)) <|> (let n := m.length + 1 in return ((e, n)::m, var n)) /-- `linear_form_of_expr red map e` computes the linear form of `e`. `map` is a lookup map from atomic expressions to variable numbers. If a new atomic expression is encountered, it is added to the map with a new number. It matches atomic expressions up to reducibility given by `red`. Because it matches up to definitional equality, this function must be in the `tactic` monad, and forces some functions that call it into `tactic` as well. -/ meta def linear_form_of_expr (red : transparency) : exmap → expr → tactic (exmap × sum) | m e@`(%%e1 * %%e2) := do (m', comp1) ← linear_form_of_expr m e1, (m', comp2) ← linear_form_of_expr m' e2, return (m', comp1.mul comp2) | m `(%%e1 + %%e2) := do (m', comp1) ← linear_form_of_expr m e1, (m', comp2) ← linear_form_of_expr m' e2, return (m', comp1.add comp2) | m `(%%e1 - %%e2) := do (m', comp1) ← linear_form_of_expr m e1, (m', comp2) ← linear_form_of_expr m' e2, return (m', comp1.add (comp2.scale (-1))) | m `(-%%e) := do (m', comp) ← linear_form_of_expr m e, return (m', comp.scale (-1)) | m p@`(@has_pow.pow _ ℕ _ %%e %%n) := match n.to_nat with | some k := do (m', comp) ← linear_form_of_expr m e, return (m', comp.pow k) | none := linear_form_of_atom red m p end | m e := match e.to_int with | some 0 := return ⟨m, mk_rb_map⟩ | some z := return ⟨m, scalar z⟩ | none := linear_form_of_atom red m e end /-- `sum_to_lf s map` eliminates the monomial level of the `sum` `s`. `map` is a lookup map from monomials to variable numbers. The output `rb_map ℕ ℤ` has the same structure as `sum`, but each monomial key is replaced with its index according to `map`. If any new monomials are encountered, they are assigned variable numbers and `map` is updated. -/ meta def sum_to_lf (s : sum) (m : rb_map monom ℕ) : rb_map monom ℕ × rb_map ℕ ℤ := s.fold (m, mk_rb_map) $ λ mn coeff ⟨map, out⟩, match map.find mn with | some n := ⟨map, out.insert n coeff⟩ | none := let n := map.size in ⟨map.insert mn n, out.insert n coeff⟩ end /-- `to_comp red e e_map monom_map` converts an expression of the form `t < 0`, `t ≤ 0`, or `t = 0` into a `comp` object. `e_map` maps atomic expressions to indices; `monom_map` maps monomials to indices. Both of these are updated during processing and returned. -/ meta def to_comp (red : transparency) (e : expr) (e_map : exmap) (monom_map : rb_map monom ℕ) : tactic (comp × exmap × rb_map monom ℕ) := do (iq, e) ← parse_into_comp_and_expr e, (m', comp') ← linear_form_of_expr red e_map e, let ⟨nm, mm'⟩ := sum_to_lf comp' monom_map, return ⟨⟨iq, mm'.to_list⟩, m', nm⟩ /-- `to_comp_fold red e_map exprs monom_map` folds `to_comp` over `exprs`, updating `e_map` and `monom_map` as it goes. -/ meta def to_comp_fold (red : transparency) : exmap → list expr → rb_map monom ℕ → tactic (list comp × exmap × rb_map monom ℕ) | m [] mm := return ([], m, mm) | m (h::t) mm := do (c, m', mm') ← to_comp red h m mm, (l, mp, mm') ← to_comp_fold m' t mm', return (c::l, mp, mm') /-- `linear_forms_and_vars red pfs` is the main interface for computing the linear forms of a list of expressions. Given a list `pfs` of proofs of comparisons, it produces a list `c` of `comps` of the same length, such that `c[i]` represents the linear form of the type of `pfs[i]`. It also returns the largest variable index that appears in comparisons in `c`. -/ meta def linear_forms_and_max_var (red : transparency) (pfs : list expr) : tactic (list comp × ℕ) := do pftps ← pfs.mmap infer_type, (l, _, map) ← to_comp_fold red [] pftps mk_rb_map, return (l, map.size - 1) end linarith
b8ee5ee0752ccc49ee6df6ab8cb293e1479543df
3fed20a6f59e2663e48ee3bfc33dbc79256b4a50
/src/sequent.lean
8a171961bf631498dbd3fffedb64e9bea79476b1
[]
no_license
arademaker/alc-lean
575203dae75f466cc686831d8b0d230fc3c00ced
46d5b582d4272493a26d6d47c0bfa0622c52aae4
refs/heads/master
1,622,696,540,378
1,618,442,995,000
1,618,442,995,000
37,130,780
4
3
null
1,618,365,416,000
1,433,853,111,000
Lean
UTF-8
Lean
false
false
15,566
lean
import alc import data.multiset open ALC open ALC.Concept -- the labeled concepts inductive Label : Type | Forall : Role → Label | Exists : Role → Label structure LConcept : Type := mk :: (roles : list Label) (concept : Concept) open LConcept open Label def isAx : Label → Prop | (Forall _) := true | (Exists _) := false def isEx : Label → Prop | (Forall _) := false | (Exists _) := true def every {a : Type} : (a → Prop) → (list a) → Prop | f [] := true | f (x::xs) := (f x) ∧ (every f xs) def negLabel : list Label → list Label | [] := [] | ((Forall a)::L) := Exists a :: negLabel L | ((Exists a)::L) := Forall a :: negLabel L #check (⟨[Forall R#0, Exists R#1], (Concept.Bot)⟩ : LConcept) open LConcept open Label def sigma_aux : list Label -> Concept -> Concept | [] c := c | ((Forall r) :: ls) c := Every r (sigma_aux ls c) | ((Exists r) :: ls) c := Some r (sigma_aux ls c) def sigma' : LConcept -> Concept | ⟨ roles , concept ⟩ := sigma_aux roles concept #reduce sigma' (⟨[Forall R#0, Exists R#1], (Concept.Bot)⟩) -- sequent calculus for ALC structure Sequent : Type := mk :: (lhs : list LConcept) (rhs : list LConcept) local infix ` ⇒ `:51 := Sequent.mk -- \=> #check [LConcept.mk [Forall R#0] (Concept.Bot)] ⇒ [LConcept.mk [Forall R#0, Exists R#1] (Concept.Bot)] #check list.map (λ x, LConcept.mk (Forall R#1 :: LConcept.roles x) (x.concept)) [LConcept.mk [Forall R#0] (Concept.Bot)] inductive proof : list Sequent → Sequent → Type infix ` ⊢ ` : 25 := proof | ax : ∀ Ω α, Ω ⊢ [α] ⇒ [α] | ax_theory : ∀ Ω s, (s ∈ Ω) → Ω ⊢ s -- the only real use of Ω | ax_falsum : ∀ Ω α, Ω ⊢ [⟨ [], ⊥ ⟩] ⇒ [α] | weak_l : ∀ Ω Δ Γ δ, Ω ⊢ (Δ ⇒ Γ) → Ω ⊢ (δ::Δ) ⇒ Γ | weak_r : ∀ Ω Δ Γ γ, Ω ⊢ (Δ ⇒ Γ) → Ω ⊢ Δ ⇒ (γ::Γ) | contraction_l : ∀ Ω Δ Γ δ, Ω ⊢ (δ::δ::Δ) ⇒ Γ → Ω ⊢ (δ::Δ) ⇒ Γ | contraction_r : ∀ Ω Δ Γ γ, Ω ⊢ Δ ⇒ (γ::γ::Γ) → Ω ⊢ Δ ⇒ (γ::Γ) | perm_l : ∀ Ω Δ₁ Δ₂ Γ δ₁ δ₂, Ω ⊢ Δ₁ ++ (δ₁ :: δ₂ :: Δ₂) ⇒ Γ → Ω ⊢ Δ₁ ++ (δ₂::δ₁::Δ₂) ⇒ Γ | perm_r : ∀ Ω Δ Γ₁ Γ₂ γ₁ γ₂, Ω ⊢ Δ ⇒ Γ₁ ++ (γ₁::γ₂::Γ₂) → Ω ⊢ Δ ⇒ Γ₁ ++ (γ₂::γ₁::Γ₂) | cut : ∀ Ω Δ₁ Δ₂ Γ₁ Γ₂ α, Ω ⊢ Δ₁ ⇒ α :: Γ₁ → Ω ⊢ α :: Δ₂ ⇒ Γ₂ → Ω ⊢ Δ₁ ++ Δ₂ ⇒ Γ₁ ++ Γ₂ | and_l : ∀ Ω Δ Γ α β L, (every isAx L) → Ω ⊢ (⟨L, α⟩ :: ⟨L,β⟩ :: Δ) ⇒ Γ → Ω ⊢ (⟨ L, α ⊓ β⟩ :: Δ) ⇒ Γ | and_r : ∀ Ω₁ Ω₂ Δ Γ α β L, (every isAx L) → Ω₁ ⊢ Δ ⇒ (⟨L, α⟩ :: Γ) → Ω₂ ⊢ Δ ⇒ (⟨L, β⟩ :: Γ) → Ω₁ ++ Ω₂ ⊢ Δ ⇒ (⟨L, α ⊓ β⟩ :: Γ) | all_r : ∀ Ω Δ Γ L α R, Ω ⊢ Δ ⇒ ⟨ L ++ [Forall R], α⟩ :: Γ → Ω ⊢ Δ ⇒ ⟨ L, Ax R : α⟩ :: Γ | all_l : ∀ Ω Δ Γ L α R, Ω ⊢ ⟨ L ++ [Forall R], α⟩ :: Δ ⇒ Γ → Ω ⊢ ⟨ L, Ax R : α ⟩ :: Δ ⇒ Γ | exists_r : ∀ Ω Δ Γ L α R, Ω ⊢ Δ ⇒ ⟨ (Exists R) :: L, α⟩ :: Γ → Ω ⊢ Δ ⇒ ⟨ L, Ex R : α⟩ :: Γ | or_l : ∀ Ω Δ Γ α β L, (every isEx L) → Ω ⊢ Δ ⇒ (⟨L, α⟩ :: Γ) → Ω ⊢ Δ ⇒ (⟨L, β⟩ :: Γ) → Ω ⊢ Δ ⇒ (⟨L, α ⊔ β⟩ :: Γ) | or_r : ∀ Ω Δ Γ α β L, (every isEx L) → Ω ⊢ Δ ⇒ ⟨L, α⟩ :: ⟨L,β⟩ :: Γ → Ω ⊢ Δ ⇒ ⟨L, α ⊓ β⟩ :: Γ | neg_l : ∀ Ω Δ Γ α L L1, L1 = negLabel L → Ω ⊢ Δ ⇒ ⟨L,α⟩ :: Γ → Ω ⊢ ⟨L1, ¬ₐα⟩ :: Δ ⇒ Γ | neg_r : ∀ Ω Δ Γ α L L1, L1 = negLabel L → Ω ⊢ Δ ++ [⟨L,α⟩] ⇒ Γ → Ω ⊢ Δ ⇒ ⟨L1, ¬ₐα⟩ :: Γ | prom_ex : ∀ Ω δ Γ R, Ω ⊢ [δ] ⇒ Γ → Ω ⊢ [⟨ Exists R :: LConcept.roles δ, LConcept.concept δ⟩] ⇒ (list.map (λ x, ⟨ (Exists R) :: LConcept.roles x, LConcept.concept x⟩) Γ) | prom_ax : ∀ Ω γ Δ R, Ω ⊢ Δ ⇒ [γ] → Ω ⊢ (list.map (λ x, ⟨ Forall R :: LConcept.roles x, LConcept.concept x ⟩) Δ) ⇒ [⟨ Forall R :: LConcept.roles γ, LConcept.concept γ⟩] infix ` ⊢ ` := proof -- \vdash def doctor := C#1 def child := R#1 lemma l1 : proof [] ([LConcept.mk [Forall child] doctor] ⇒ [LConcept.mk [Forall child] doctor]) := begin have S := proof.ax [] ⟨[] , doctor⟩, exact proof.prom_ax [] _ _ child S, end lemma l2 : proof [] ([⟨[], ⊤⟩, LConcept.mk [Forall child] doctor] ⇒ [LConcept.mk [Forall child] doctor]) := begin apply proof.weak_l, exact l1, end example : proof [] ([⟨[], ⊤⟩] ⇒ [LConcept.mk [] (Concept.Some R#1 (Concept.Negation C#1)), LConcept.mk [Forall R#1] C#1]) := begin have S₁ := proof.ax [] ⟨ [] , C#1 ⟩, have S₂ := proof.prom_ax _ _ _ R#1 S₁, simp at S₂, have J₁ := proof.weak_l [] [{roles := [Forall R#1], concept := C#1}] [{roles := [Forall R#1], concept := C#1}] ⟨[],⊤⟩ S₂, have J₂ := proof.neg_r [] [{roles := ([] : list Label), concept := ⊤}] [{roles := [Forall R#1], concept := C#1}] C#1 [Forall R#1] [Exists R#1] _ J₁, clear S₁ S₂ J₁, exact proof.exists_r [] [⟨[], ⊤⟩] [{roles := [Forall R#1], concept := C#1}] [] (¬ₐ C#1) R#1 J₂, tauto, end example : proof [] ([LConcept.mk ([] : list Label) (Ex R#1 : ⊤)] ⇒ [(LConcept.mk [Exists R#1] ¬ₐ C#1), (LConcept.mk [Exists R#1,Forall R#1] C#1)]) := begin apply proof.neg_r [] [{roles := ([] : list Label), concept := Ex R#1:⊤}] [{roles := [Exists R#1, Forall R#1], concept := C#1}] C#1 [Forall R#1] [Exists R#1], rw [negLabel, negLabel], sorry end lemma in_map {α β} {x : α} {A : list α} (x ∈ A) (f : α → β) : (f x) ∈ (list.map f A) := begin finish, end lemma head_out_map {α β} {a : α } {A : list α} {f : α → β} : list.map f (a::A) = (f a) :: list.map f A := begin finish, end def subseteq_imp_inter_subseteq {α} {A C : set α} {B : set α} : A ⊆ C → (A ∩ B) ⊆ C := begin intro h, have h1 : A ∩ B ⊆ A, exact set.inter_subset_left A B, exact set.subset.trans h1 h, end def subseteq_imp_union_subseteq {α} {A C : set α} {B : set α} : A ⊆ C → A ⊆ B ∪ C := begin intro h, have h1 : C ⊆ B ∪ C, exact set.subset_union_right B C, exact set.subset.trans h h1, end def foldl_inter : list LConcept → Concept | [] := ⊤ | [a] := sigma' a | (a::ls) := sigma' a ⊓ (foldl_inter ls) def foldl_union : list LConcept → Concept | [] := ⊥ | [a] := sigma' a | (a::ls) := sigma' a ⊔ (foldl_union ls) def seq_to_stmt : Sequent → Statement | (Δ ⇒ Γ) := Statement.Subsumption (foldl_inter Δ) (foldl_union Γ) lemma interp_foldl_inter_append {xs a I}: interp I (foldl_inter (xs ++ [a])) = interp I (foldl_inter (a::xs)) := begin sorry, end lemma interp_foldl_union_reverse {xs I} : interp I (foldl_inter xs) = interp I (foldl_inter (list.reverse xs)) := begin sorry, end lemma interp_stmt_weak_l {Δ Γ I} ( δ : LConcept) : (interp_stmt I (seq_to_stmt(Δ ⇒ Γ))) → (interp_stmt I (seq_to_stmt(δ::Δ ⇒ Γ))) := begin intro a, induction Δ with δ₁ Δ₂ Δh, induction Γ with γ₁ Γ₂ Γh, unfold seq_to_stmt interp_stmt foldl_union interp at *, rw ← set.eq_empty_of_subset_empty a, exact set.subset_univ (interp I (foldl_inter [δ])), unfold seq_to_stmt interp_stmt interp at *, rw (set.eq_univ_of_univ_subset a), exact (interp I (foldl_inter [δ])).subset_univ, induction Γ with γ₁ Γ₂ Γh, unfold seq_to_stmt interp_stmt interp foldl_inter at *, rw set.inter_comm, exact subseteq_imp_inter_subseteq a, unfold seq_to_stmt interp_stmt foldl_union foldl_inter at *, unfold1 interp, rw set.inter_comm, exact subseteq_imp_inter_subseteq a, end lemma gen_interp_stmt_weak_l {Δ₁ Δ₂ Γ I} : (interp_stmt I (seq_to_stmt(Δ₂ ⇒ Γ))) → (interp_stmt I (seq_to_stmt(Δ₁++Δ₂ ⇒ Γ))) := begin intro h, induction Δ₁ with Δ₁0 Δ₁1 Δ₁h, simp, exact h, exact interp_stmt_weak_l Δ₁0 Δ₁h, end lemma interp_stmt_weak_r {Δ Γ I} ( γ : LConcept) : (interp_stmt I (seq_to_stmt(Δ ⇒ Γ))) → (interp_stmt I (seq_to_stmt(Δ ⇒ γ::Γ))) := begin intro a, induction Δ with δ₁ Δ₂ Δh, induction Γ with γ₁ Γ₂ Γh, unfold seq_to_stmt interp_stmt foldl_union interp at *, rw set.eq_empty_of_subset_empty a, exact (interp I (sigma' γ)).empty_subset, unfold seq_to_stmt interp_stmt interp foldl_union at *, exact subseteq_imp_union_subseteq a, induction Γ with γ₁ Γ₂ Γh, unfold seq_to_stmt interp_stmt interp foldl_union at *, rw set.eq_empty_of_subset_empty a, exact set.empty_subset (interp I (sigma' γ)), unfold seq_to_stmt interp_stmt foldl_union foldl_inter at *, unfold interp, exact subseteq_imp_union_subseteq a, end lemma gen_interp_stmt_weak_r {Δ Γ₁ Γ₂ I} : (interp_stmt I (seq_to_stmt(Δ ⇒ Γ₂))) → (interp_stmt I (seq_to_stmt(Δ ⇒ Γ₁++Γ₂))) := begin intro h, induction Γ₁ with Γ₁0 Γ₁1 Γ₁h, simp, exact h, exact interp_stmt_weak_r Γ₁0 Γ₁h, end #check is_commutative lemma interp_stmt_contract_l {Δ Γ I} {δ : LConcept} : (interp_stmt I (seq_to_stmt(δ::δ::Δ ⇒ Γ))) → (interp_stmt I (seq_to_stmt(δ::Δ ⇒ Γ))) := begin intro h, unfold seq_to_stmt foldl_inter interp at *, induction Δ with Δ0 Δ1, unfold foldl_inter interp_stmt interp at *, rw set.inter_self at h, exact h, unfold foldl_inter interp_stmt interp at *, rw ← set.inter_assoc at h , rw set.inter_self at h, exact h, end lemma interp_stmt_contract_r {Δ Γ I} {γ : LConcept} : (interp_stmt I (seq_to_stmt(Δ ⇒ γ::γ::Γ))) → (interp_stmt I (seq_to_stmt(Δ ⇒ γ::Γ))) := begin intro h, unfold seq_to_stmt foldl_inter interp at *, induction Γ with Γ0 Γ1, unfold foldl_union interp_stmt interp at *, rw set.union_self at h, exact h, unfold foldl_union interp_stmt interp at *, rw ← set.union_assoc at h , rw set.union_self at h, exact h, end lemma interp_stmt_perm_l {Δ₁ Δ₂ Γ I δ₁ δ₂} : interp_stmt I (seq_to_stmt (Δ₁ ++ δ₁ :: δ₂ :: Δ₂ ⇒ Γ)) → interp_stmt I (seq_to_stmt (Δ₁ ++ δ₂ :: δ₁ :: Δ₂ ⇒ Γ)) := begin intro h, unfold seq_to_stmt at *, induction Δ₁ with Δ₁0 Δ₁1, simp at *, unfold foldl_inter interp_stmt interp at *, induction Δ₂ with Δ₂0 Δ₂1, unfold foldl_inter at *, rw set.inter_comm at h, exact h, unfold foldl_inter interp at *, rw ← set.inter_assoc at h, nth_rewrite 1 set.inter_comm at h, rw set.inter_assoc at h, exact h, sorry end theorem soundness {Ω : list Sequent} : ∀ {Δ Γ}, (proof Ω (Δ ⇒ Γ)) → models (list.map seq_to_stmt Ω) (seq_to_stmt (Δ ⇒ Γ)) | _ _ (proof.ax Ω₁ α₁) := by {unfold models, intros h1 h2, unfold seq_to_stmt foldl_inter foldl_union interp_stmt, } | _ _ (proof.ax_theory Ω₁ (lhs ⇒ rhs) S) := by {unfold models, intros h1 h2, unfold satisfies at h2, have h3 := h2 (seq_to_stmt(lhs ⇒ rhs )), have h4 := in_map (lhs ⇒ rhs) S seq_to_stmt, exact h2 (seq_to_stmt(lhs ⇒ rhs )) h4, exact (lhs ⇒ rhs), } | _ _ (proof.ax_falsum Ω₁ α₁) := by {unfold models, intros h1 h2, unfold seq_to_stmt foldl_inter foldl_union interp_stmt sigma' sigma_aux interp at *, exact set.empty_subset (interp h1 (sigma' α₁)), } | _ _ (proof.weak_l Ω₁ Δ Γ δ h) := by { unfold models, intros I h2, unfold satisfies at h2, have h4 := soundness h, unfold models at h4, have h5 := h4 I, unfold satisfies at h5, have h6 := h5 h2, exact interp_stmt_weak_l δ h6, } | _ _ (proof.weak_r Ω₁ Δ Γ γ h) := by { unfold models, intros I h2, unfold satisfies at h2, have h4 := soundness h, unfold models at h4, have h5 := h4 I, unfold satisfies at h5, have h6 := h5 h2, exact interp_stmt_weak_r γ h6, } | _ _ (proof.contraction_l Ω₁ Δ Γ δ h) := by { unfold models, intros I h1, unfold satisfies at h1, have h2 := soundness h, unfold models at h2, have h3 := h2 I, unfold satisfies at h3, have h4:= h3 h1, exact interp_stmt_contract_l h4, } | _ _ (proof.contraction_r Ω₁ Δ Γ δ h) := by { unfold models, intros I h1, unfold satisfies at h1, have h2 := soundness h, unfold models at h2, have h3 := h2 I, unfold satisfies at h3, have h4:= h3 h1, exact interp_stmt_contract_r h4, } | _ _ (proof.perm_l Ω Δ₁ Δ₂ Γ δ₁ δ₂ h) := by { unfold models, intros I h1, unfold satisfies at h1, have h2 := soundness h, unfold models at h2, have h3 := h2 I, unfold satisfies at h3, have h4:= h3 h1, sorry, } /- reserve infix ` ⊢ `:26 inductive Sequent : list LConcept → list LConcept → Type infix ⊢ := Sequent | One : ∀ L, L ⊢ L | Neg : ∀ L, [LConcept.mk [] Concept.Bot] ⊢ L | Ins : ∀ L₁ A, A ∈ L₁ → L₁ ⊢ [A] | WeL : ∀ L₁ L₂ A, A ∈ L₁ → L₁ ⊢ L₂ → A::L₁ ⊢ L₂ | WeR : ∀ L₁ L₂ B, B ∈ L₂ → L₁ ⊢ L₂ → L₁ ⊢ B::L₂ | CoL : ∀ L₁ L₂ A, A::A::L₁ ⊢ L₂ → (A::L₁) ⊢ L₂ | CoR : ∀ L₁ L₂ B, L₁ ⊢ (B::L₂) → L₁ ⊢ (B::L₂) | PeL : ∀ AL₁ A₁ B₁ BL₁ L₂, AL₁ ++ [A₁,B₁] ++ BL₁ ⊢ L₂ → AL₁ ++ [B₁,A₁] ++ BL₁ ⊢ L₂ | PeR : ∀ AL₂ A₂ B₂ BL₂ L₁, L₁ ⊢ AL₂ ++ [A₂,B₂] ++ BL₂ → L₁ ⊢ AL₂ ++ [B₂,A₂] ++ BL₂ | CuT : ∀ AL₁ BL₁ B AL₂ CL₂, AL₁ ⊢ BL₁ ++ [B] → B::AL₂ ⊢ CL₂ → AL₁ ++ AL₂ ⊢ BL₁ ++ CL₂ #check Sequent instance Concept_Intersection_is_commutative {AC AR : Type}: @is_commutative (Concept AC AR) Concept.Intersection := ⟨λ a b, by⟩ this is the idea for the implementation, we can use folds in multiset, but I still have to prove commutative to use it, but I am having trouble as it is... def inter_LConcepts {AC AR : Type} (as : list (qLConcept AC AR)) := list.foldl (Concept.Intersection) (sigma_exhaust (list.head as)) (list.map sigma_exhaust (list.tail as)) def union_LConcepts {AC AR : Type} (as : list (LConcept AC AR)) := list.foldl (Concept.Union) (sigma_exhaust (list.head as)) (list.map sigma_exhaust (list.tail as)) def sequent {AC AR : Type} (as : list (LConcept AC AR)) (bs : list (LConcept AC AR)) := subsumption (inter_LConcepts as) (union_LConcepts bs) #reduce list.foldl (λ x y, Concept.Intersection x y) (Concept.Top) [Concept.Bot] lemma weak_l_srule {AC AR : Type} {as bs : list (LConcept AC AR)} (a : LConcept AC AR) (h1 : list.mem a as) (h : subsequent as bs) : subsequent (a::as) bs := begin unfold subsequent at *, unfold subsumption at *, intro I, have hn : interp I (inter_LConcepts as) ⊆ interp I (union_LConcepts bs), from h I, end pure logic! Sequent Calculus: Man |- Person Person |- Casado ---------------------------------- cut Man |- Casado dependent types: h1 : Man |- Person h2 : Person |- Casado cut h1 h2 : Man |- Casado -/
b0600877c7dedeb5405849e7a938be0a197f5415
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/preadditive/single_obj.lean
00e2af87425d6c0cf2016a1c2714e0ce6febb495
[ "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
721
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.default import category_theory.single_obj /-! # `single_obj α` is preadditive when `α` is a ring. -/ namespace category_theory variables {α : Type*} [ring α] instance (X Y : single_obj α) : add_comm_group (X ⟶ Y) := by { change add_comm_group α, apply_instance, } instance : preadditive (single_obj α) := { add_comp' := λ _ _ _ f f' g, mul_add g f f', comp_add' := λ _ _ _ f g g', add_mul g g' f, } -- TODO define `PreAddCat` (with additive functors as morphisms), and `Ring ⥤ PreAddCat`. end category_theory
74c21c147277cb8b9649cb0f24615a63103be9cd
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/types/pi.hlean
28dfa92c9896b587af3cfce494896598a54d6905
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
12,058
hlean
/- Copyright (c) 2014-15 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about pi-types (dependent function spaces) -/ import types.sigma arity open eq equiv is_equiv funext sigma unit bool is_trunc prod namespace pi variables {A A' : Type} {B : A → Type} {B' : A' → Type} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a} /- Paths -/ /- Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ~ g]. This equivalence, however, is just the combination of [apd10] and function extensionality [funext], and as such, [eq_of_homotopy] Now we show how these things compute. -/ definition apd10_eq_of_homotopy (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h := apd10 (right_inv apd10 h) definition eq_of_homotopy_eta (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p definition eq_of_homotopy_idp (f : Πa, B a) : eq_of_homotopy (λx : A, refl (f x)) = refl f := !eq_of_homotopy_eta /- The identification of the path space of a dependent function space, up to equivalence, is of course just funext. -/ definition eq_equiv_homotopy (f g : Πx, B x) : (f = g) ≃ (f ~ g) := equiv.mk apd10 _ definition pi_eq_equiv (f g : Πx, B x) : (f = g) ≃ (f ~ g) := !eq_equiv_homotopy definition is_equiv_eq_of_homotopy (f g : Πx, B x) : is_equiv (eq_of_homotopy : f ~ g → f = g) := _ definition homotopy_equiv_eq (f g : Πx, B x) : (f ~ g) ≃ (f = g) := equiv.mk eq_of_homotopy _ /- Transport -/ definition pi_transport (p : a = a') (f : Π(b : B a), C a b) : (transport (λa, Π(b : B a), C a b) p f) ~ (λb, !tr_inv_tr ▸ (p ▸D (f (p⁻¹ ▸ b)))) := by induction p; reflexivity /- A special case of [transport_pi] where the type [B] does not depend on [A], and so it is just a fixed type [B]. -/ definition pi_transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) (b : A') : (transport _ p f) b = p ▸ (f b) := by induction p; reflexivity /- Pathovers -/ definition pi_pathover {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[apo011 C p q] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_left {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b : B a), f b =[apo011 C p !pathover_tr] g (p ▸ b)) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_right {f : Πb, C a b} {g : Πb', C a' b'} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[apo011 C p !tr_pathover] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, apply r end definition pi_pathover_constant {C : A → A' → Type} {f : Π(b : A'), C a b} {g : Π(b : A'), C a' b} {p : a = a'} (r : Π(b : A'), f b =[p] g b) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, exact eq_of_pathover_idp (r b), end -- a version where C is uncurried, but where the conclusion of r is still a proper pathover -- instead of a heterogenous equality definition pi_pathover' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b : B a) (b' : B a') (q : b =[p] b'), f b =[dpair_eq_dpair p q] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply (@eq_of_pathover_idp _ C), exact (r b b (pathover.idpatho b)), end definition pi_pathover_left' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b : B a), f b =[dpair_eq_dpair p !pathover_tr] g (p ▸ b)) : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, esimp at r, exact !pathover_ap (r b) end definition pi_pathover_right' {C : (Σa, B a) → Type} {f : Πb, C ⟨a, b⟩} {g : Πb', C ⟨a', b'⟩} {p : a = a'} (r : Π(b' : B a'), f (p⁻¹ ▸ b') =[dpair_eq_dpair p !tr_pathover] g b') : f =[p] g := begin cases p, apply pathover_idp_of_eq, apply eq_of_homotopy, intro b, apply eq_of_pathover_idp, esimp at r, exact !pathover_ap (r b) end /- Maps on paths -/ /- The action of maps given by lambda. -/ definition ap_lambdaD {C : A' → Type} (p : a = a') (f : Πa b, C b) : ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) := begin apply (eq.rec_on p), apply inverse, apply eq_of_homotopy_idp end /- Dependent paths -/ /- with more implicit arguments the conclusion of the following theorem is (Π(b : B a), transportD B C p b (f b) = g (transport B p b)) ≃ (transport (λa, Π(b : B a), C a b) p f = g) -/ definition heq_piD (p : a = a') (f : Π(b : B a), C a b) (g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, !homotopy_equiv_eq) g definition heq_pi {C : A → Type} (p : a = a') (f : Π(b : B a), C a) (g : Π(b' : B a'), C a') : (Π(b : B a), p ▸ (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, !homotopy_equiv_eq) g section open sigma sigma.ops /- more implicit arguments: (Π(b : B a), transport C (sigma_eq p idp) (f b) = g (p ▸ b)) ≃ (Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (transport B p b)) -/ definition heq_pi_sigma {C : (Σa, B a) → Type} (p : a = a') (f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) : (Π(b : B a), (sigma_eq p !pathover_tr) ▸ (f b) = g (p ▸ b)) ≃ (Π(b : B a), p ▸D (f b) = g (p ▸ b)) := eq.rec_on p (λg, !equiv.refl) g end /- Functorial action -/ variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') /- The functoriality of [forall] is slightly subtle: it is contravariant in the domain type and covariant in the codomain, but the codomain is dependent on the domain. -/ definition pi_functor [unfold_full] : (Π(a:A), B a) → (Π(a':A'), B' a') := λg a', f1 a' (g (f0 a')) definition pi_functor_left [unfold_full] (B : A → Type) : (Π(a:A), B a) → (Π(a':A'), B (f0 a')) := pi_functor f0 (λa, id) definition pi_functor_right [unfold_full] {B' : A → Type} (f1 : Π(a:A), B a → B' a) : (Π(a:A), B a) → (Π(a:A), B' a) := pi_functor id f1 definition ap_pi_functor {g g' : Π(a:A), B a} (h : g ~ g') : ap (pi_functor f0 f1) (eq_of_homotopy h) = eq_of_homotopy (λa':A', (ap (f1 a') (h (f0 a')))) := begin apply (is_equiv_rect (@apd10 A B g g')), intro p, clear h, cases p, apply concat, exact (ap (ap (pi_functor f0 f1)) (eq_of_homotopy_idp g)), apply symm, apply eq_of_homotopy_idp end /- Equivalences -/ definition is_equiv_pi_functor [instance] [constructor] [H0 : is_equiv f0] [H1 : Πa', is_equiv (f1 a')] : is_equiv (pi_functor f0 f1) := begin apply (adjointify (pi_functor f0 f1) (pi_functor f0⁻¹ (λ(a : A) (b' : B' (f0⁻¹ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))), begin intro h, apply eq_of_homotopy, intro a', esimp, rewrite [adj f0 a',-tr_compose,fn_tr_eq_tr_fn _ f1,right_inv (f1 _)], apply apd end, begin intro h, apply eq_of_homotopy, intro a, esimp, rewrite [left_inv (f1 _)], apply apd end end definition pi_equiv_pi_of_is_equiv [constructor] [H : is_equiv f0] [H1 : Πa', is_equiv (f1 a')] : (Πa, B a) ≃ (Πa', B' a') := equiv.mk (pi_functor f0 f1) _ definition pi_equiv_pi [constructor] (f0 : A' ≃ A) (f1 : Πa', (B (to_fun f0 a') ≃ B' a')) : (Πa, B a) ≃ (Πa', B' a') := pi_equiv_pi_of_is_equiv (to_fun f0) (λa', to_fun (f1 a')) definition pi_equiv_pi_right [constructor] {P Q : A → Type} (g : Πa, P a ≃ Q a) : (Πa, P a) ≃ (Πa, Q a) := pi_equiv_pi equiv.refl g /- Equivalence if one of the types is contractible -/ definition pi_equiv_of_is_contr_left [constructor] (B : A → Type) [H : is_contr A] : (Πa, B a) ≃ B (center A) := begin fapply equiv.MK, { intro f, exact f (center A)}, { intro b a, exact (center_eq a) ▸ b}, { intro b, rewrite [prop_eq_of_is_contr (center_eq (center A)) idp]}, { intro f, apply eq_of_homotopy, intro a, induction (center_eq a), rewrite [prop_eq_of_is_contr (center_eq (center A)) idp]} end definition pi_equiv_of_is_contr_right [constructor] [H : Πa, is_contr (B a)] : (Πa, B a) ≃ unit := begin fapply equiv.MK, { intro f, exact star}, { intro u a, exact !center}, { intro u, induction u, reflexivity}, { intro f, apply eq_of_homotopy, intro a, apply is_prop.elim} end /- Interaction with other type constructors -/ -- most of these are in the file of the other type constructor definition pi_empty_left [constructor] (B : empty → Type) : (Πx, B x) ≃ unit := begin fapply equiv.MK, { intro f, exact star}, { intro x y, contradiction}, { intro x, induction x, reflexivity}, { intro f, apply eq_of_homotopy, intro y, contradiction}, end definition pi_unit_left [constructor] (B : unit → Type) : (Πx, B x) ≃ B star := !pi_equiv_of_is_contr_left definition pi_bool_left [constructor] (B : bool → Type) : (Πx, B x) ≃ B ff × B tt := begin fapply equiv.MK, { intro f, exact (f ff, f tt)}, { intro x b, induction x, induction b: assumption}, { intro x, induction x, reflexivity}, { intro f, apply eq_of_homotopy, intro b, induction b: reflexivity}, end /- Truncatedness: any dependent product of n-types is an n-type -/ theorem is_trunc_pi (B : A → Type) (n : trunc_index) [H : ∀a, is_trunc n (B a)] : is_trunc n (Πa, B a) := begin revert B H, eapply (trunc_index.rec_on n), {intro B H, fapply is_contr.mk, intro a, apply center, intro f, apply eq_of_homotopy, intro x, apply (center_eq (f x))}, {intro n IH B H, fapply is_trunc_succ_intro, intro f g, fapply is_trunc_equiv_closed, apply equiv.symm, apply eq_equiv_homotopy, apply IH, intro a, show is_trunc n (f a = g a), from is_trunc_eq n (f a) (g a)} end local attribute is_trunc_pi [instance] theorem is_trunc_pi_eq [instance] [priority 500] (n : trunc_index) (f g : Πa, B a) [H : ∀a, is_trunc n (f a = g a)] : is_trunc n (f = g) := begin apply is_trunc_equiv_closed_rev, apply eq_equiv_homotopy end theorem is_trunc_not [instance] (n : trunc_index) (A : Type) : is_trunc (n.+1) ¬A := by unfold not;exact _ theorem is_prop_pi_eq [instance] [priority 490] (a : A) : is_prop (Π(a' : A), a = a') := is_prop_of_imp_is_contr ( assume (f : Πa', a = a'), have is_contr A, from is_contr.mk a f, by exact _) /- force type clas resolution -/ theorem is_prop_neg (A : Type) : is_prop (¬A) := _ local attribute ne [reducible] theorem is_prop_ne [instance] {A : Type} (a b : A) : is_prop (a ≠ b) := _ /- Symmetry of Π -/ definition is_equiv_flip [instance] {P : A → A' → Type} : is_equiv (@function.flip A A' P) := begin fapply is_equiv.mk, exact (@function.flip _ _ (function.flip P)), repeat (intro f; apply idp) end definition pi_comm_equiv {P : A → A' → Type} : (Πa b, P a b) ≃ (Πb a, P a b) := equiv.mk (@function.flip _ _ P) _ end pi attribute pi.is_trunc_pi [instance] [priority 1520]
0783893cddf9eff3f69f0a43ba62ed01cc4a11ac
367134ba5a65885e863bdc4507601606690974c1
/src/analysis/asymptotics/specific_asymptotics.lean
eb6b3c4b0aa279cab8f59f4e83ad7ac957192125
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
2,631
lean
/- Copyright (c) 2021 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.normed_space.ordered import analysis.asymptotics.asymptotics /-! # A collection of specific asymptotic results This file contains specific lemmas about asymptotics which don't have their place in the general theory developped in `analysis.asymptotics.asymptotics`. -/ open filter asymptotics open_locale topological_space section linear_ordered_field variables {𝕜 : Type*} [linear_ordered_field 𝕜] lemma pow_div_pow_eventually_eq_at_top {p q : ℕ} : (λ x : 𝕜, x^p / x^q) =ᶠ[at_top] (λ x, x^((p : ℤ) -q)) := begin apply ((eventually_gt_at_top (0 : 𝕜)).mono (λ x hx, _)), simp [fpow_sub hx.ne'], end lemma pow_div_pow_eventually_eq_at_bot {p q : ℕ} : (λ x : 𝕜, x^p / x^q) =ᶠ[at_bot] (λ x, x^((p : ℤ) -q)) := begin apply ((eventually_lt_at_bot (0 : 𝕜)).mono (λ x hx, _)), simp [fpow_sub hx.ne'.symm], end lemma tendsto_fpow_at_top_at_top {n : ℤ} (hn : 0 < n) : tendsto (λ x : 𝕜, x^n) at_top at_top := begin lift n to ℕ using hn.le, exact tendsto_pow_at_top (nat.succ_le_iff.mpr $int.coe_nat_pos.mp hn) end lemma tendsto_pow_div_pow_at_top_at_top {p q : ℕ} (hpq : q < p) : tendsto (λ x : 𝕜, x^p / x^q) at_top at_top := begin rw tendsto_congr' pow_div_pow_eventually_eq_at_top, apply tendsto_fpow_at_top_at_top, linarith end lemma tendsto_pow_div_pow_at_top_zero [topological_space 𝕜] [order_topology 𝕜] {p q : ℕ} (hpq : p < q) : tendsto (λ x : 𝕜, x^p / x^q) at_top (𝓝 0) := begin rw tendsto_congr' pow_div_pow_eventually_eq_at_top, apply tendsto_fpow_at_top_zero, linarith end end linear_ordered_field section normed_linear_ordered_field variables {𝕜 : Type*} [normed_linear_ordered_field 𝕜] lemma asymptotics.is_o_pow_pow_at_top_of_lt [order_topology 𝕜] {p q : ℕ} (hpq : p < q) : is_o (λ x : 𝕜, x^p) (λ x, x^q) at_top := begin refine (is_o_iff_tendsto' _).mpr (tendsto_pow_div_pow_at_top_zero hpq), exact (eventually_gt_at_top 0).mono (λ x hx hxq, (pow_ne_zero q hx.ne' hxq).elim), end lemma asymptotics.is_O.trans_tendsto_norm_at_top {α : Type*} {u v : α → 𝕜} {l : filter α} (huv : is_O u v l) (hu : tendsto (λ x, ∥u x∥) l at_top) : tendsto (λ x, ∥v x∥) l at_top := begin rcases huv.exists_pos with ⟨c, hc, hcuv⟩, rw is_O_with at hcuv, convert tendsto.at_top_div_const hc (tendsto_at_top_mono' l hcuv hu), ext x, rw mul_div_cancel_left _ hc.ne.symm, end end normed_linear_ordered_field
2b7f3e4ca2100f797e81dd361dc6085b9ab84e90
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Server/Watchdog.lean
2402ede8ecb4d3d6c22266aa6e93a376129830e1
[ "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
24,001
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Init.Data.ByteArray import Std.Data.RBMap import Lean.Elab.Import import Lean.Data.Lsp import Lean.Server.FileSource import Lean.Server.Utils /-! For general server architecture, see `README.md`. This module implements the watchdog process. ## Watchdog state Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes to the header and thus restart the corresponding worker, freeing its imports. TODO(WN): We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed (continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic, users may be confused about why the server seemingly stopped working for a single file. ## Watchdog <-> worker communication The watchdog process and its file worker processes communicate via LSP. If the necessity arises, we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications are forwarded to the corresponding file worker process, with the exception of these notifications: - textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to asynchronously receive LSP packets from the worker (e.g. request responses). - textDocument/didChange: Update the local file state. If the header was mutated, signal a shutdown to the file worker by closing the I/O channels. Then restart the file worker. Otherwise, forward the `didChange` notification. - textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state. Moreover, we don't implement the full protocol at this level: - Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker. - After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of the file. No additional `didOpen` notifications will be forwarded to the worker process. - `$/cancelRequest` notifications are forwarded to all file workers. - File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request. Similarly, they never receive a `didClose` notification. ## Watchdog <-> client communication The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add non-standard extensions in case they're needed, for example to communicate tactic state. -/ namespace Lean.Server.Watchdog open IO open Std (RBMap RBMap.empty) open Lsp open JsonRpc section Utils structure OpenDocument where meta : DocumentMeta headerAst : Syntax def workerCfg : Process.StdioConfig := { stdin := Process.Stdio.piped stdout := Process.Stdio.piped -- We pass workers' stderr through to the editor. stderr := Process.Stdio.inherit } /-- Events that worker-specific tasks signal to the main thread. -/ inductive WorkerEvent where /- A synthetic event signalling that the grouped edits should be processed. -/ | processGroupedEdits | terminated | crashed (e : IO.Error) | ioError (e : IO.Error) inductive WorkerState where /- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker and when reading a request reply. In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task. Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored. Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file worker arrives. -/ | crashed (queuedMsgs : Array JsonRpc.Message) | running abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message (fun a b => Decidable.decide (a < b)) private def parseHeaderAst (input : String) : IO Syntax := do let inputCtx := Parser.mkInputContext input "<input>" let (stx, _, _) ← Parser.parseHeader inputCtx return stx end Utils section FileWorker /-- A group of edits which will be processed at a future instant. -/ structure GroupedEdits where /-- When to process the edits. -/ applyTime : Nat params : DidChangeTextDocumentParams /-- Signals when `applyTime` has been reached. -/ signalTask : Task WorkerEvent structure FileWorker where doc : OpenDocument proc : Process.Child workerCfg commTask : Task WorkerEvent state : WorkerState -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state pendingRequestsRef : IO.Ref PendingRequestMap groupedEditsRef : IO.Ref (Option GroupedEdits) namespace FileWorker variable [ToJson α] def stdin (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdin def stdout (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdout def readMessage (fw : FileWorker) : IO JsonRpc.Message := do let msg ← fw.stdout.readLspMessage if let Message.response id _ := msg then fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.erase id) if let Message.responseError id _ _ _ := msg then fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.erase id) return msg def writeMessage (fw : FileWorker) (msg : JsonRpc.Message) : IO Unit := fw.stdin.writeLspMessage msg def writeNotification (fw : FileWorker) (n : Notification α) : IO Unit := fw.stdin.writeLspNotification n def writeRequest (fw : FileWorker) (r : Request α) : IO Unit := do fw.stdin.writeLspRequest r fw.pendingRequestsRef.modify (fun pendingRequests => pendingRequests.insert r.id r) def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty)) for ⟨id, _⟩ in pendingRequests do hError.writeLspResponseError { id := id, code := code, message := msg } partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do let rec loopAction : IO WorkerEvent := do let now ← monoMsNow let some ge ← fw.groupedEditsRef.get | throwServerError "Internal error: empty grouped edits reference in signal task" if ge.applyTime ≤ now then return WorkerEvent.processGroupedEdits else IO.sleep <| UInt32.ofNat <| ge.applyTime - now loopAction let t ← IO.asTask loopAction return t.map fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e end FileWorker end FileWorker section ServerM abbrev FileWorkerMap := RBMap DocumentUri FileWorker (fun a b => Decidable.decide (a < b)) structure ServerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream /-- Command line arguments. -/ args : List String fileWorkersRef : IO.Ref FileWorkerMap /-- We store these to pass them to workers. -/ initParams : InitializeParams editDelay : Nat workerPath : String abbrev ServerM := ReaderT ServerContext IO def updateFileWorkers (val : FileWorker) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val) def findFileWorker (uri : DocumentUri) : ServerM FileWorker := do match (←(←read).fileWorkersRef.get).find? uri with | some fw => fw | none => throwServerError s!"Got unknown document URI ({uri})" def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri) def log (msg : String) : ServerM Unit := do let st ← read st.hLog.putStrLn msg st.hLog.flush /-- Creates a Task which forwards a worker's messages into the output stream until an event which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/ private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do let o := (←read).hOut let rec loop : ServerM WorkerEvent := do try let msg ← fw.readMessage -- Writes to Lean I/O channels are atomic, so these won't trample on each other. o.writeLspMessage msg catch err => -- If writeLspMessage from above errors we will block here, but the main task will -- quit eventually anyways if that happens let exitCode ← fw.proc.wait if exitCode = 0 then -- Worker was terminated fw.errorPendingRequests o ErrorCode.contentModified ("The file worker has been terminated. Either the header has changed," ++ " or the file was closed, or the server is shutting down.") return WorkerEvent.terminated else -- Worker crashed fw.errorPendingRequests o ErrorCode.internalError s!"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then "see stderr for exception" else "likely due to a stack overflow in user code"}." return WorkerEvent.crashed err loop let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated task.map $ fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e def startFileWorker (m : DocumentMeta) : ServerM Unit := do let st ← read let headerAst ← parseHeaderAst m.text.source let workerProc ← Process.spawn { toStdioConfig := workerCfg cmd := st.workerPath args := #["--worker"] ++ st.args.toArray } let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap) -- The task will never access itself, so this is fine let fw : FileWorker := { doc := ⟨m, headerAst⟩ proc := workerProc commTask := Task.pure WorkerEvent.terminated state := WorkerState.running pendingRequestsRef := pendingRequestsRef groupedEditsRef := ← IO.mkRef none } let commTask ← forwardMessages fw let fw : FileWorker := { fw with commTask := commTask } fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩ fw.writeNotification { method := "textDocument/didOpen" param := { textDocument := { uri := m.uri languageId := "lean" version := m.version text := m.text.source } : DidOpenTextDocumentParams } } updateFileWorkers fw def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do /- The file worker must have crashed just when we were about to terminate it! That's fine - just forget about it then. (on didClose we won't need the crashed file worker anymore, when the header changed we'll start a new one right after anyways and when we're shutting down the server it's over either way.) -/ try (←findFileWorker uri).writeMessage (Message.notification "exit" none) catch err => () eraseFileWorker uri def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do updateFileWorkers { ←findFileWorker uri with state := WorkerState.crashed queuedMsgs } /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed and restarts the file worker if the `crashed` flag was already set. Messages that couldn't be sent can be queued up via the queueFailedMessage flag and will be discharged after the FileWorker is restarted. -/ def tryWriteMessage [Coe α JsonRpc.Message] (uri : DocumentUri) (msg : α) (writeAction : FileWorker → α → IO Unit) (queueFailedMessage := true) (restartCrashedWorker := false) : ServerM Unit := do let fw ← findFileWorker uri match fw.state with | WorkerState.crashed queuedMsgs => let mut queuedMsgs := queuedMsgs if queueFailedMessage then queuedMsgs := queuedMsgs.push msg if !restartCrashedWorker then return -- restart the crashed FileWorker eraseFileWorker uri startFileWorker fw.doc.meta let newFw ← findFileWorker uri let mut crashedMsgs := #[] -- try to discharge all queued msgs, tracking the ones that we can't discharge for msg in queuedMsgs do try newFw.writeMessage msg catch _ => crashedMsgs := crashedMsgs.push msg if ¬ crashedMsgs.isEmpty then handleCrash uri crashedMsgs | WorkerState.running => let initialQueuedMsgs := if queueFailedMessage then #[msg] else #[] try writeAction fw msg catch _ => handleCrash uri (initialQueuedMsgs.map Coe.coe) end ServerM section NotificationHandling def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit := let doc := p.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩ def handleEdits (fw : FileWorker) : ServerM Unit := do let some ge ← fw.groupedEditsRef.modifyGet (·, none) | throwServerError "Internal error: empty grouped edits reference" let doc := ge.params.textDocument let changes := ge.params.contentChanges let oldDoc := fw.doc let some newVersion ← pure doc.version? | throwServerError "Expected version number" if newVersion <= oldDoc.meta.version then throwServerError "Got outdated version number" if changes.isEmpty then return let (newDocText, _) := foldDocumentChanges changes oldDoc.meta.text let newMeta : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩ let newHeaderAst ← parseHeaderAst newDocText.source if newHeaderAst != oldDoc.headerAst then terminateFileWorker doc.uri startFileWorker newMeta else let newDoc : OpenDocument := ⟨newMeta, oldDoc.headerAst⟩ updateFileWorkers { fw with doc := newDoc } tryWriteMessage doc.uri ⟨"textDocument/didChange", ge.params⟩ FileWorker.writeNotification (restartCrashedWorker := true) def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit := terminateFileWorker p.textDocument.uri def handleCancelRequest (p : CancelParams) : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, fw⟩ in fileWorkers do let req? ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests.find? p.id, pendingRequests.erase p.id)) if let some req := req? then tryWriteMessage uri ⟨"$/cancelRequest", p⟩ FileWorker.writeNotification (queueFailedMessage := false) end NotificationHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | some parsed => pure parsed | none => throwServerError s!"Got param with wrong structure: {params.compress}" def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let handle := fun α [FromJson α] [ToJson α] [FileSource α] => do let parsedParams ← parseParams α params let uri := fileSource parsedParams tryWriteMessage uri ⟨id, method, parsedParams⟩ FileWorker.writeRequest match method with | "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParams | "textDocument/hover" => handle HoverParams | "textDocument/declaration" => handle DeclarationParams | "textDocument/definition" => handle DefinitionParams | "textDocument/typeDefinition" => handle TypeDefinitionParams | "textDocument/documentHighlight" => handle DocumentHighlightParams | "textDocument/documentSymbol" => handle DocumentSymbolParams | "$/lean/plainGoal" => handle PlainGoalParams | _ => (←read).hOut.writeLspResponseError { id := id code := ErrorCode.methodNotFound message := s!"Unsupported request method: {method}" } def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler) match method with | "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen /- NOTE: textDocument/didChange is handled in the main loop. -/ | "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose | "$/cancelRequest" => handle CancelParams handleCancelRequest | _ => (←read).hLog.putStrLn s!"Got unsupported notification: {method}" end MessageHandling section MainLoop def shutdown : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, _⟩ in fileWorkers do terminateFileWorker uri for ⟨_, fw⟩ in fileWorkers do discard <| IO.wait fw.commTask inductive ServerEvent where | workerEvent (fw : FileWorker) (ev : WorkerEvent) | clientMsg (msg : JsonRpc.Message) | clientError (e : IO.Error) def runClientTask : ServerM (Task ServerEvent) := do let st ← read let readMsgAction : IO ServerEvent := do /- Runs asynchronously. -/ let msg ← st.hIn.readLspMessage ServerEvent.clientMsg msg let clientTask := (←IO.asTask readMsgAction).map $ fun | Except.ok ev => ev | Except.error e => ServerEvent.clientError e return clientTask partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do let st ← read let workers ← st.fileWorkersRef.get let mut workerTasks := #[] for (_, fw) in workers do if let WorkerState.running := fw.state then workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw) if let some ge ← fw.groupedEditsRef.get then workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw) let ev ← IO.waitAny (workerTasks.push clientTask |>.toList) match ev with | ServerEvent.clientMsg msg => match msg with | Message.request id "shutdown" _ => shutdown st.hOut.writeLspResponse ⟨id, Json.null⟩ | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop (←runClientTask) | Message.notification "textDocument/didChange" (some params) => let p ← parseParams DidChangeTextDocumentParams (toJson params) let fw ← findFileWorker p.textDocument.uri let now ← monoMsNow /- We wait `editDelay`ms since last edit before applying the changes. -/ let applyTime := now + st.editDelay let startingGroup? ← fw.groupedEditsRef.modifyGet fun | some ge => (false, some { ge with applyTime := applyTime params.textDocument := p.textDocument params.contentChanges := ge.params.contentChanges ++ p.contentChanges } ) | none => (true, some { applyTime := applyTime params := p /- This is overwritten just below. -/ signalTask := Task.pure WorkerEvent.processGroupedEdits } ) if startingGroup? then let t ← fw.runEditsSignalTask fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } ) mainLoop (←runClientTask) | Message.notification method (some params) => handleNotification method (toJson params) mainLoop (←runClientTask) | _ => throwServerError "Got invalid JSON-RPC message" | ServerEvent.clientError e => throw e | ServerEvent.workerEvent fw ev => match ev with | WorkerEvent.processGroupedEdits => handleEdits fw mainLoop clientTask | WorkerEvent.ioError e => throwServerError s!"IO error while processing events for {fw.doc.meta.uri}: {e}" | WorkerEvent.crashed e => handleCrash fw.doc.meta.uri #[] mainLoop clientTask | WorkerEvent.terminated => throwServerError "Internal server error: got termination event for worker that should have been removed" end MainLoop def mkLeanServerCapabilities : ServerCapabilities := { textDocumentSync? := some { openClose := true change := TextDocumentSyncKind.incremental willSave := false willSaveWaitUntil := false save? := none } hoverProvider := true declarationProvider := true definitionProvider := true typeDefinitionProvider := true documentHighlightProvider := true documentSymbolProvider := true } def initAndRunWatchdogAux : ServerM Unit := do let st ← read try discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams let clientTask ← runClientTask mainLoop clientTask let Message.notification "exit" none ← st.hIn.readLspMessage | throwServerError "Expected an exit notification" catch err => shutdown throw err def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do let mut workerPath ← IO.appPath if let some path := (←IO.getEnv "LEAN_SYSROOT") then workerPath := s!"{path}/bin/lean{System.FilePath.exeSuffix}" if let some path := (←IO.getEnv "LEAN_WORKER_PATH") then workerPath := path let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap) let i ← maybeTee "wdIn.txt" false i let o ← maybeTee "wdOut.txt" true o let e ← maybeTee "wdErr.txt" true e let initRequest ← i.readLspRequestAs "initialize" InitializeParams o.writeLspResponse { id := initRequest.id result := { capabilities := mkLeanServerCapabilities serverInfo? := some { name := "Lean 4 server" version? := "0.0.1" } : InitializeResult } } ReaderT.run initAndRunWatchdogAux { hIn := i hOut := o hLog := e args := args fileWorkersRef := fileWorkersRef initParams := initRequest.param editDelay := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200 workerPath := workerPath : ServerContext } @[export lean_server_watchdog_main] def watchdogMain (args : List String) : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWatchdog args i o e return 0 catch err => e.putStrLn s!"Watchdog error: {err}" return 1 end Lean.Server.Watchdog
a13143f9b43fbef62622ca83c5f2e5b60265390c
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/gcd_monoid.lean
849561f47a7d123f3d2c8cdafd1b05799d3627e9
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
35,161
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, Jens Wagemaker TODO: Provide a GCD monoid instance for `ℕ`, port GCD facts about nats TODO: Generalize normalization monoids commutative (cancellative) monoids with or without zero TODO: Generalize GCD monoid to not require normalization in all cases -/ import algebra.associated /-! # Monoids with normalization functions, `gcd`, and `lcm` This file defines extra structures on `comm_cancel_monoid_with_zero`s, including `integral_domain`s. ## Main Definitions * `normalization_monoid` * `gcd_monoid` * `gcd_monoid_of_exists_gcd` * `gcd_monoid_of_exists_lcm` ## Implementation Notes * `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This definition as currently implemented does casework on `0`. * `gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains, and monoids without zero. * `gcd_monoid_of_gcd` noncomputably constructs a `gcd_monoid` structure just from the `gcd` and its properties. * `gcd_monoid_of_exists_gcd` noncomputably constructs a `gcd_monoid` structure just from a proof that any two elements have a (not necessarily normalized) `gcd`. * `gcd_monoid_of_lcm` noncomputably constructs a `gcd_monoid` structure just from the `lcm` and its properties. * `gcd_monoid_of_exists_lcm` noncomputably constructs a `gcd_monoid` structure just from a proof that any two elements have a (not necessarily normalized) `lcm`. ## TODO * Provide a GCD monoid instance for `ℕ`, port GCD facts about nats, definition of coprime * Generalize normalization monoids to commutative (cancellative) monoids with or without zero * Generalize GCD monoid to not require normalization in all cases ## Tags divisibility, gcd, lcm, normalize -/ variables {α : Type*} set_option old_structure_cmd true /-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated elements. -/ @[protect_proj] class normalization_monoid (α : Type*) [nontrivial α] [comm_cancel_monoid_with_zero α] := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 /-- Chooses an element of each associate class, by multiplying by `norm_unit` -/ def normalize : monoid_with_zero_hom α α := { to_fun := λ x, x * norm_unit x, map_zero' := by simp, map_one' := by rw [norm_unit_one, units.coe_one, mul_one], map_mul' := λ x y, classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy, by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], } theorem associated_normalize {x : α} : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated {x : α} : associated (normalize x) x := associated_normalize.symm lemma associates.mk_normalize {x : α} : associates.mk (normalize x) = associates.mk x := associates.mk_eq_mk_iff_associated.2 normalize_associated @[simp] lemma normalize_apply {x : α} : normalize x = x * norm_unit x := rfl @[simp] lemma normalize_zero : normalize (0 : α) = 0 := normalize.map_zero @[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by simp lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩ @[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $ assume h, by rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba --can be proven by simp lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := units.dvd_mul_right --can be proven by simp lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := units.mul_right_dvd end normalization_monoid namespace comm_group_with_zero variables [decidable_eq α] [comm_group_with_zero α] @[priority 100] -- see Note [lower instance priority] instance : normalization_monoid α := { norm_unit := λ x, if h : x = 0 then 1 else (units.mk0 x h)⁻¹, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ x y x0 y0, units.eq_iff.1 (by simp [x0, y0, mul_inv']), norm_unit_coe_units := λ u, by { rw [dif_neg (units.ne_zero _), units.mk0_coe], apply_instance } } @[simp] lemma coe_norm_unit {a : α} (h0 : a ≠ 0) : (↑(norm_unit a) : α) = a⁻¹ := by simp [norm_unit, h0] end comm_group_with_zero namespace associates variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] local attribute [instance] associated.setoid /-- Maps an element of `associates` back to the normalized element of its associate class -/ protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates /-- GCD monoid: a `comm_cancel_monoid_with_zero` with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the corresponding `lcm` facts from `gcd`. -/ @[protect_proj] class gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] extends normalization_monoid α := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] @[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b := gcd_monoid.normalize_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) := gcd_monoid.gcd_mul_lcm section gcd theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) instance : is_commutative α gcd := ⟨gcd_comm⟩ instance : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd) @[simp] theorem gcd_same (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize.map_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) @[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _) theorem gcd_eq_of_associated_left {m n : α} (h : associated m n) (k : α) : gcd m k = gcd n k := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (gcd_dvd_gcd (dvd_of_associated h) (dvd_refl _)) (gcd_dvd_gcd (dvd_of_associated h.symm) (dvd_refl _)) theorem gcd_eq_of_associated_right {m n : α} (h : associated m n) (k : α) : gcd k m = gcd k n := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (gcd_dvd_gcd (dvd_refl _) (dvd_of_associated h)) (gcd_dvd_gcd (dvd_refl _) (dvd_of_associated h.symm)) lemma dvd_gcd_mul_of_dvd_mul {m n k : α} (H : k ∣ m * n) : k ∣ (gcd k m) * n := begin transitivity gcd k m * normalize n, { rw ← gcd_mul_right, exact dvd_gcd (dvd_mul_right _ _) H }, { apply dvd.intro ↑(norm_unit n)⁻¹, rw [normalize_apply, mul_assoc, mul_assoc, ← units.coe_mul], simp } end lemma dvd_mul_gcd_of_dvd_mul {m n k : α} (H : k ∣ m * n) : k ∣ m * gcd k n := by { rw mul_comm at H ⊢, exact dvd_gcd_mul_of_dvd_mul H } /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. Note: In general, this representation is highly non-unique. -/ lemma exists_dvd_and_dvd_of_dvd_mul {m n k : α} (H : k ∣ m * n) : ∃ d₁ (hd₁ : d₁ ∣ m) d₂ (hd₂ : d₂ ∣ n), k = d₁ * d₂ := begin by_cases h0 : gcd k m = 0, { rw gcd_eq_zero_iff at h0, rcases h0 with ⟨rfl, rfl⟩, refine ⟨0, dvd_refl 0, n, dvd_refl n, _⟩, simp }, { obtain ⟨a, ha⟩ := gcd_dvd_left k m, refine ⟨gcd k m, gcd_dvd_right _ _, a, _, ha⟩, suffices h : gcd k m * a ∣ gcd k m * n, { cases h with b hb, use b, rw mul_assoc at hb, apply mul_left_cancel' h0 hb }, rw ← ha, exact dvd_gcd_mul_of_dvd_mul H } end theorem gcd_mul_dvd_mul_gcd (k m n : α) : gcd k (m * n) ∣ gcd k m * gcd k n := begin obtain ⟨m', hm', n', hn', h⟩ := (exists_dvd_and_dvd_of_dvd_mul $ gcd_dvd_right k (m * n)), replace h : gcd k (m * n) = m' * n' := h, rw h, have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _, apply mul_dvd_mul, { have hm'k : m' ∣ k := dvd_trans (dvd_mul_right m' n') hm'n', exact dvd_gcd hm'k hm' }, { have hn'k : n' ∣ k := dvd_trans (dvd_mul_left n' m') hm'n', exact dvd_gcd hn'k hn' } end theorem gcd_pow_right_dvd_pow_gcd {a b : α} {k : ℕ} : gcd a (b ^ k) ∣ (gcd a b) ^ k := begin by_cases hg : gcd a b = 0, { rw gcd_eq_zero_iff at hg, rcases hg with ⟨rfl, rfl⟩, simp }, { induction k with k hk, simp, rw [pow_succ, pow_succ], transitivity gcd a b * gcd a (b ^ k), apply gcd_mul_dvd_mul_gcd a b (b ^ k), refine (mul_dvd_mul_iff_left hg).mpr hk } end theorem gcd_pow_left_dvd_pow_gcd {a b : α} {k : ℕ} : gcd (a ^ k) b ∣ (gcd a b) ^ k := by { rw [gcd_comm, gcd_comm a b], exact gcd_pow_right_dvd_pow_gcd } theorem pow_dvd_of_mul_eq_pow {a b c d₁ d₂ : α} (ha : a ≠ 0) (hab : gcd a b = 1) {k : ℕ} (h : a * b = c ^ k) (hc : c = d₁ * d₂) (hd₁ : d₁ ∣ a) : d₁ ^ k ≠ 0 ∧ d₁ ^ k ∣ a := begin have h1 : gcd (d₁ ^ k) b = 1, { rw ← normalize_gcd (d₁ ^ k) b, rw normalize_eq_one, apply is_unit_of_dvd_one, transitivity (gcd d₁ b) ^ k, { exact gcd_pow_left_dvd_pow_gcd }, { apply is_unit.dvd, apply is_unit.pow, apply is_unit_of_dvd_one, rw ← hab, apply gcd_dvd_gcd hd₁ (dvd_refl b) } }, have h2 : d₁ ^ k ∣ a * b, { use d₂ ^ k, rw [h, hc], exact mul_pow d₁ d₂ k }, rw mul_comm at h2, have h3 : d₁ ^ k ∣ a, { rw [← one_mul a, ← h1], apply dvd_gcd_mul_of_dvd_mul h2 }, have h4 : d₁ ^ k ≠ 0, { intro hdk, rw hdk at h3, apply absurd (zero_dvd_iff.mp h3) ha }, tauto end theorem exists_associated_pow_of_mul_eq_pow {a b c : α} (hab : gcd a b = 1) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : α), associated (d ^ k) a := begin by_cases ha : a = 0, { use 0, rw ha, by_cases hk : k = 0, { exfalso, revert h, rw [ha, hk, zero_mul, pow_zero], apply zero_ne_one }, { rw zero_pow (nat.pos_of_ne_zero hk) }}, by_cases hb : b = 0, { rw [hb, gcd_zero_right] at hab, use 1, rw one_pow, apply (associated_one_iff_is_unit.mpr (normalize_eq_one.mp hab)).symm }, by_cases hk : k = 0, { use 1, rw [hk, pow_zero] at h ⊢, use units.mk_of_mul_eq_one _ _ h, rw [units.coe_mk_of_mul_eq_one, one_mul] }, have hc : c ∣ a * b, { rw h, refine dvd_pow (dvd_refl c) hk }, obtain ⟨d₁, hd₁, d₂, hd₂, hc⟩ := exists_dvd_and_dvd_of_dvd_mul hc, use d₁, obtain ⟨h0₁, ⟨a', ha'⟩⟩ := pow_dvd_of_mul_eq_pow ha hab h hc hd₁, rw [mul_comm] at h hc, rw [gcd_comm] at hab, obtain ⟨h0₂, ⟨b', hb'⟩⟩ := pow_dvd_of_mul_eq_pow hb hab h hc hd₂, rw [ha', hb', hc, mul_pow] at h, have h' : a' * b' = 1, { apply (mul_right_inj' h0₁).mp, rw mul_one, apply (mul_right_inj' h0₂).mp, rw ← h, rw [mul_assoc, mul_comm a', ← mul_assoc (d₁ ^ k), ← mul_assoc _ (d₁ ^ k), mul_comm b'] }, use units.mk_of_mul_eq_one _ _ h', rw [units.coe_mk_of_mul_eq_one, ha'] end end gcd section lcm lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := classical.by_cases (assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt}) (assume this : ¬ (a = 0 ∨ b = 0), let ⟨h1, h2⟩ := not_or_distrib.1 this in have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff, normalize.map_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2 lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have normalize (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa only [normalize_eq_zero, mul_eq_zero, units.ne_zero, or_false]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b := classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $ assume h_lcm : lcm a b ≠ 0, have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff]; rintros ⟨rfl, rfl⟩; left; refl) h_lcm, have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b, by rw [gcd_mul_lcm, normalize_idem], by simpa only [normalize.map_mul, normalize_gcd, one_mul, mul_right_inj' h1] using h2 theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _))) (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _))) (lcm_dvd (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance : is_commutative α lcm := ⟨lcm_comm⟩ instance : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd units.coe_dvd (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize.map_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _) theorem lcm_eq_of_associated_left {m n : α} (h : associated m n) (k : α) : lcm m k = lcm n k := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd_lcm (dvd_of_associated h) (dvd_refl _)) (lcm_dvd_lcm (dvd_of_associated h.symm) (dvd_refl _)) theorem lcm_eq_of_associated_right {m n : α} (h : associated m n) (k : α) : lcm k m = lcm k n := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd_lcm (dvd_refl _) (dvd_of_associated h)) (lcm_dvd_lcm (dvd_refl _) (dvd_of_associated h.symm)) end lcm namespace gcd_monoid theorem prime_of_irreducible {x : α} (hi: irreducible x) : prime x := ⟨hi.ne_zero, ⟨hi.1, λ a b h, begin cases gcd_dvd_left x a with y hy, cases hi.is_unit_or_is_unit hy with hu hu; cases hu with u hu, { right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h, rw gcd_mul_right, rw ← hu, apply dvd_of_associated, transitivity (normalize b), symmetry, use u, apply mul_comm, apply normalize_associated, }, { left, rw [hy, ← hu], transitivity, {apply dvd_of_associated, symmetry, use u}, apply gcd_dvd_right, } end ⟩⟩ theorem irreducible_iff_prime {p : α} : irreducible p ↔ prime p := ⟨prime_of_irreducible, irreducible_of_prime⟩ end gcd_monoid end gcd_monoid section unique_unit variables [comm_cancel_monoid_with_zero α] [unique (units α)] lemma units_eq_one (u : units α) : u = 1 := subsingleton.elim u 1 variable [nontrivial α] @[priority 100] -- see Note [lower instance priority] instance normalization_monoid_of_unique_units : normalization_monoid α := { norm_unit := λ x, 1, norm_unit_zero := rfl, norm_unit_mul := λ x y hx hy, (mul_one 1).symm, norm_unit_coe_units := λ u, subsingleton.elim _ _ } @[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl @[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x end unique_unit section integral_domain variables [integral_domain α] [gcd_monoid α] lemma gcd_eq_of_dvd_sub_right {a b c : α} (h : a ∣ b - c) : gcd a b = gcd a c := begin apply dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _); rw dvd_gcd_iff; refine ⟨gcd_dvd_left _ _, _⟩, { rcases h with ⟨d, hd⟩, rcases gcd_dvd_right a b with ⟨e, he⟩, rcases gcd_dvd_left a b with ⟨f, hf⟩, use e - f * d, rw [mul_sub, ← he, ← mul_assoc, ← hf, ← hd, sub_sub_cancel] }, { rcases h with ⟨d, hd⟩, rcases gcd_dvd_right a c with ⟨e, he⟩, rcases gcd_dvd_left a c with ⟨f, hf⟩, use e + f * d, rw [mul_add, ← he, ← mul_assoc, ← hf, ← hd, ← add_sub_assoc, add_comm c b, add_sub_cancel] } end lemma gcd_eq_of_dvd_sub_left {a b c : α} (h : a ∣ b - c) : gcd b a = gcd c a := by rw [gcd_comm _ a, gcd_comm _ a, gcd_eq_of_dvd_sub_right h] end integral_domain section constructors noncomputable theory open associates variables [comm_cancel_monoid_with_zero α] [nontrivial α] private lemma map_mk_unit_aux [decidable_eq α] {f : associates α →* α} (hinv : function.right_inverse f associates.mk) (a : α) : a * ↑(classical.some (associated_map_mk hinv a)) = f (associates.mk a) := classical.some_spec (associated_map_mk hinv a) /-- Define `normalization_monoid` on a structure from a `monoid_hom` inverse to `associates.mk`. -/ def normalization_monoid_of_monoid_hom_right_inverse [decidable_eq α] (f : associates α →* α) (hinv : function.right_inverse f associates.mk) : normalization_monoid α := { norm_unit := λ a, if a = 0 then 1 else classical.some (associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm), norm_unit_zero := if_pos rfl, norm_unit_mul := λ a b ha hb, by { rw [if_neg (mul_ne_zero ha hb), if_neg ha, if_neg hb, units.ext_iff, units.coe_mul], suffices : (a * b) * ↑(classical.some (associated_map_mk hinv (a * b))) = (a * ↑(classical.some (associated_map_mk hinv a))) * (b * ↑(classical.some (associated_map_mk hinv b))), { apply mul_left_cancel' (mul_ne_zero ha hb) _, simpa only [mul_assoc, mul_comm, mul_left_comm] using this }, rw [map_mk_unit_aux hinv a, map_mk_unit_aux hinv (a * b), map_mk_unit_aux hinv b, ← monoid_hom.map_mul, associates.mk_mul_mk] }, norm_unit_coe_units := λ u, by { rw [if_neg (units.ne_zero u), units.ext_iff], apply mul_left_cancel' (units.ne_zero u), rw [units.mul_inv, map_mk_unit_aux hinv u, associates.mk_eq_mk_iff_associated.2 (associated_one_iff_is_unit.2 ⟨u, rfl⟩), associates.mk_one, monoid_hom.map_one] } } variable [normalization_monoid α] /-- Define `gcd_monoid` on a structure just from the `gcd` and its properties. -/ noncomputable def gcd_monoid_of_gcd [decidable_eq α] (gcd : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) : gcd_monoid α := { gcd := gcd, gcd_dvd_left := gcd_dvd_left, gcd_dvd_right := gcd_dvd_right, dvd_gcd := λ a b c, dvd_gcd, normalize_gcd := normalize_gcd, lcm := λ a b, if a = 0 then 0 else classical.some (dvd_normalize_iff.2 (dvd.trans (gcd_dvd_left a b) (dvd.intro b rfl))), gcd_mul_lcm := λ a b, by { split_ifs with a0, { rw [mul_zero, a0, zero_mul, normalize_zero] }, { exact (classical.some_spec (dvd_normalize_iff.2 (dvd.trans (gcd_dvd_left a b) (dvd.intro b rfl)))).symm } }, lcm_zero_left := λ a, if_pos rfl, lcm_zero_right := λ a, by { split_ifs with a0, { refl }, rw ← normalize_eq_zero at a0, have h := (classical.some_spec (dvd_normalize_iff.2 (dvd.trans (gcd_dvd_left a 0) (dvd.intro 0 rfl)))).symm, have gcd0 : gcd a 0 = normalize a, { rw ← normalize_gcd, exact normalize_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_zero a)) }, rw ← gcd0 at a0, apply or.resolve_left (mul_eq_zero.1 _) a0, rw [h, mul_zero, normalize_zero] }, .. (infer_instance : normalization_monoid α) } /-- Define `gcd_monoid` on a structure just from the `lcm` and its properties. -/ noncomputable def gcd_monoid_of_lcm [decidable_eq α] (lcm : α → α → α) (dvd_lcm_left : ∀a b, a ∣ lcm a b) (dvd_lcm_right : ∀a b, b ∣ lcm a b) (lcm_dvd : ∀{a b c}, c ∣ a → b ∣ a → lcm c b ∣ a) (normalize_lcm : ∀a b, normalize (lcm a b) = lcm a b) : gcd_monoid α := let exists_gcd := λ a b, dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl)) in { lcm := lcm, gcd := λ a b, if a = 0 then normalize b else (if b = 0 then normalize a else classical.some (exists_gcd a b)), gcd_mul_lcm := λ a b, by { split_ifs, { rw [h, zero_dvd_iff.1 (dvd_lcm_left _ _), mul_zero, zero_mul, normalize_zero] }, { rw [h_1, zero_dvd_iff.1 (dvd_lcm_right _ _), mul_zero, mul_zero, normalize_zero] }, apply eq.trans (mul_comm _ _) (classical.some_spec (dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl)))).symm }, normalize_gcd := λ a b, by { split_ifs, { apply normalize_idem }, { apply normalize_idem }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, apply mul_left_cancel' h0, refine trans _ (classical.some_spec (exists_gcd a b)), conv_lhs { congr, rw [← normalize_lcm a b] }, erw [← normalize.map_mul, ← classical.some_spec (exists_gcd a b), normalize_idem] }, lcm_zero_left := λ a, zero_dvd_iff.1 (dvd_lcm_left _ _), lcm_zero_right := λ a, zero_dvd_iff.1 (dvd_lcm_right _ _), gcd_dvd_left := λ a b, by { split_ifs, { rw h, apply dvd_zero }, { apply dvd_of_associated normalize_associated }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b), normalize_dvd_iff, mul_comm, mul_dvd_mul_iff_right h], apply dvd_lcm_right }, gcd_dvd_right := λ a b, by { split_ifs, { apply dvd_of_associated normalize_associated }, { rw h_1, apply dvd_zero }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b), normalize_dvd_iff, mul_dvd_mul_iff_right h_1], apply dvd_lcm_left }, dvd_gcd := λ a b c ac ab, by { split_ifs, { apply dvd_normalize_iff.2 ab }, { apply dvd_normalize_iff.2 ac }, have h0 : lcm c b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl))), dvd_normalize_iff], rcases ab with ⟨d, rfl⟩, rw mul_eq_zero at h_1, push_neg at h_1, rw [mul_comm a, ← mul_assoc, mul_dvd_mul_iff_right h_1.1], apply lcm_dvd (dvd.intro d rfl), rw [mul_comm, mul_dvd_mul_iff_right h_1.2], apply ac }, .. (infer_instance : normalization_monoid α) } /-- Define a `gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/ noncomputable def gcd_monoid_of_exists_gcd [decidable_eq α] (h : ∀ a b : α, ∃ c : α, ∀ d : α, d ∣ a ∧ d ∣ b ↔ d ∣ c) : gcd_monoid α := gcd_monoid_of_gcd (λ a b, normalize (classical.some (h a b))) (λ a b, normalize_dvd_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 (dvd_refl _))).1) (λ a b, normalize_dvd_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 (dvd_refl _))).2) (λ a b c ac ab, dvd_normalize_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩)) (λ a b, normalize_idem _) /-- Define a `gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/ noncomputable def gcd_monoid_of_exists_lcm [decidable_eq α] (h : ∀ a b : α, ∃ c : α, ∀ d : α, a ∣ d ∧ b ∣ d ↔ c ∣ d) : gcd_monoid α := gcd_monoid_of_lcm (λ a b, normalize (classical.some (h a b))) (λ a b, dvd_normalize_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 (dvd_refl _))).1) (λ a b, dvd_normalize_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 (dvd_refl _))).2) (λ a b c ac ab, normalize_dvd_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩)) (λ a b, normalize_idem _) end constructors
0d26a82f9e40fc47d9ce70c45a110a287128a311
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/field_theory/splitting_field.lean
33c09232c3624680e3feeb2a6d7b991b7ebdbdc9
[ "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
7,795
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import ring_theory.unique_factorization_domain import data.polynomial ring_theory.principal_ideal_domain algebra.euclidean_domain universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial noncomputable theory local attribute [instance, priority 0] classical.prop_decidable variables [discrete_field α] [discrete_field β] [discrete_field γ] open polynomial section splits variables (i : α → β) [is_field_hom i] /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _ _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 (is_field_hom.injective i) _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (classical.not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tautology)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_domain.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_map_iff (j : β → γ) [is_field_hom j] {f : polynomial α} : splits j (f.map i) ↔ splits (λ x, j (i x)) f := by simp [splits, polynomial.map_map] lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := is_noetherian_ring.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (by rw [ne.def, map_eq_zero]; exact hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits id (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, is_noetherian_ring.irreducible_induction_on (f.map i) (λ _, ⟨{37}, by simp [is_ring_hom.map_zero i]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero (nonzero_of_irreducible hp) hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 :: s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, domain.mul_right_inj hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit (nonzero_of_irreducible hp), mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 (nonzero_of_irreducible hp)), one_mul], end⟩) section UFD local attribute [instance, priority 0] principal_ideal_domain.to_unique_factorization_domain local infix ` ~ᵤ ` : 50 := associated open unique_factorization_domain associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := unique (λ p hp, irreducible_factors (mt (map_eq_zero i).1 hf0) _ hp) (λ p, by simp [@eq_comm _ _ p, -sub_eq_add_neg, irreducible_of_degree_eq_one (degree_X_sub_C _)] {contextual := tt}) (associated.symm $ calc _ ~ᵤ f.map i : ⟨units.map C (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (mt (map_eq_zero i).1 hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_domain.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits id f → splits i f := unique_factorization_domain.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β → γ) [is_field_hom j] {f : polynomial α} (h : splits i f) : splits (λ x, j (i x)) f := begin change i with (λ x, id (i x)) at h, rw [← splits_map_iff], rw [← splits_map_iff i id] at h, exact splits_of_splits_id _ h end end splits end polynomial
fa8770dcd382d6effc07640f388770d40b1359e8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/metric_space/gromov_hausdorff_realized.lean
1245c6d4a86c0f9edb64abfa751a223f32a0368b
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
27,335
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 topology.metric_space.gluing import topology.metric_space.hausdorff_distance import topology.continuous_function.bounded /-! # The Gromov-Hausdorff distance is realized In this file, we construct of a good coupling between nonempty compact metric spaces, minimizing their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff distance between nonempty compact metric spaces. Given two nonempty compact metric spaces `X` and `Y`, we define `optimal_GH_coupling X Y` as a compact metric space, together with two isometric embeddings `optimal_GH_injl` and `optimal_GH_injr` respectively of `X` and `Y` into `optimal_GH_coupling X Y`. The main property of the optimal coupling is that the Hausdorff distance between `X` and `Y` in `optimal_GH_coupling X Y` is smaller than the corresponding distance in any other coupling. We do not prove completely this fact in this file, but we show a good enough approximation of this fact in `Hausdorff_dist_optimal_le_HD`, that will suffice to obtain the full statement once the Gromov-Hausdorff distance is properly defined, in `Hausdorff_dist_optimal`. The key point in the construction is that the set of possible distances coming from isometric embeddings of `X` and `Y` in metric spaces is a set of equicontinuous functions. By Arzela-Ascoli, it is compact, and one can find such a distance which is minimal. This distance defines a premetric space structure on `X ⊕ Y`. The corresponding metric quotient is `optimal_GH_coupling X Y`. -/ noncomputable theory open_locale classical topological_space nnreal universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section Gromov_Hausdorff_realized /- This section shows that the Gromov-Hausdorff distance is realized. For this, we consider candidate distances on the disjoint union `X ⊕ Y` of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff distance, and show that they form a compact family by applying Arzela-Ascoli theorem. The existence of a minimizer follows. -/ section definitions variables (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] @[reducible] private def prod_space_fun : Type* := ((X ⊕ Y) × (X ⊕ Y)) → ℝ @[reducible] private def Cb : Type* := bounded_continuous_function ((X ⊕ Y) × (X ⊕ Y)) ℝ private def max_var : ℝ≥0 := 2 * ⟨diam (univ : set X), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set Y), diam_nonneg⟩ private lemma one_le_max_var : 1 ≤ max_var X Y := calc (1 : real) = 2 * 0 + 1 + 2 * 0 : by simp ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num /-- The set of functions on `X ⊕ Y` that are candidates distances to realize the minimum of the Hausdorff distances between `X` and `Y` in a coupling -/ def candidates : set (prod_space_fun X Y) := {f | (((((∀ x y : X, f (sum.inl x, sum.inl y) = dist x y) ∧ (∀ x y : Y, f (sum.inr x, sum.inr y) = dist x y)) ∧ (∀ x y, f (x, y) = f (y, x))) ∧ (∀ x y z, f (x, z) ≤ f (x, y) + f (y, z))) ∧ (∀ x, f (x, x) = 0)) ∧ (∀ x y, f (x, y) ≤ max_var X Y) } /-- Version of the set of candidates in bounded_continuous_functions, to apply Arzela-Ascoli -/ private def candidates_b : set (Cb X Y) := {f : Cb X Y | (f : _ → ℝ) ∈ candidates X Y} end definitions --section section constructions variables {X : Type u} {Y : Type v} [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] {f : prod_space_fun X Y} {x y z t : X ⊕ Y} local attribute [instance, priority 10] inhabited_of_nonempty' private lemma max_var_bound : dist x y ≤ max_var X Y := calc dist x y ≤ diam (univ : set (X ⊕ Y)) : dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _) ... = diam (inl '' (univ : set X) ∪ inr '' (univ : set Y)) : by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self] ... ≤ diam (inl '' (univ : set X)) + dist (inl default) (inr default) + diam (inr '' (univ : set Y)) : diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _)) ... = diam (univ : set X) + (dist default default + 1 + dist default default) + diam (univ : set Y) : by { rw [isometry_inl.diam_image, isometry_inr.diam_image], refl } ... = 1 * diam (univ : set X) + 1 + 1 * diam (univ : set Y) : by simp ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : begin apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl], norm_num, norm_num end private lemma candidates_symm (fA : f ∈ candidates X Y) : f (x, y) = f (y, x) := fA.1.1.1.2 x y private lemma candidates_triangle (fA : f ∈ candidates X Y) : f (x, z) ≤ f (x, y) + f (y, z) := fA.1.1.2 x y z private lemma candidates_refl (fA : f ∈ candidates X Y) : f (x, x) = 0 := fA.1.2 x private lemma candidates_nonneg (fA : f ∈ candidates X Y) : 0 ≤ f (x, y) := begin have : 0 ≤ 2 * f (x, y) := calc 0 = f (x, x) : (candidates_refl fA).symm ... ≤ f (x, y) + f (y, x) : candidates_triangle fA ... = f (x, y) + f (x, y) : by rw [candidates_symm fA] ... = 2 * f (x, y) : by ring, by linarith end private lemma candidates_dist_inl (fA : f ∈ candidates X Y) (x y: X) : f (inl x, inl y) = dist x y := fA.1.1.1.1.1 x y private lemma candidates_dist_inr (fA : f ∈ candidates X Y) (x y : Y) : f (inr x, inr y) = dist x y := fA.1.1.1.1.2 x y private lemma candidates_le_max_var (fA : f ∈ candidates X Y) : f (x, y) ≤ max_var X Y := fA.2 x y /-- candidates are bounded by `max_var X Y` -/ private lemma candidates_dist_bound (fA : f ∈ candidates X Y) : ∀ {x y : X ⊕ Y}, f (x, y) ≤ max_var X Y * dist x y | (inl x) (inl y) := calc f (inl x, inl y) = dist x y : candidates_dist_inl fA x y ... = dist (inl x) (inl y) : by { rw @sum.dist_eq X Y, refl } ... = 1 * dist (inl x) (inl y) : by simp ... ≤ max_var X Y * dist (inl x) (inl y) : mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg | (inl x) (inr y) := calc f (inl x, inr y) ≤ max_var X Y : candidates_le_max_var fA ... = max_var X Y * 1 : by simp ... ≤ max_var X Y * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y)) | (inr x) (inl y) := calc f (inr x, inl y) ≤ max_var X Y : candidates_le_max_var fA ... = max_var X Y * 1 : by simp ... ≤ max_var X Y * dist (inl x) (inr y) : mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y)) | (inr x) (inr y) := calc f (inr x, inr y) = dist x y : candidates_dist_inr fA x y ... = dist (inr x) (inr y) : by { rw @sum.dist_eq X Y, refl } ... = 1 * dist (inr x) (inr y) : by simp ... ≤ max_var X Y * dist (inr x) (inr y) : mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg /-- Technical lemma to prove that candidates are Lipschitz -/ private lemma candidates_lipschitz_aux (fA : f ∈ candidates X Y) : f (x, y) - f (z, t) ≤ 2 * max_var X Y * dist (x, y) (z, t) := calc f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _ ... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) : sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _ ... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc] ... ≤ max_var X Y * dist x z + max_var X Y * dist t y : add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA) ... ≤ max_var X Y * max (dist x z) (dist t y) + max_var X Y * max (dist x z) (dist t y) : begin apply add_le_add, apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var X Y)), apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y)) (zero_le_one.trans (one_le_max_var X Y)), end ... = 2 * max_var X Y * max (dist x z) (dist y t) : by { simp [dist_comm], ring } ... = 2 * max_var X Y * dist (x, y) (z, t) : by refl /-- Candidates are Lipschitz -/ private lemma candidates_lipschitz (fA : f ∈ candidates X Y) : lipschitz_with (2 * max_var X Y) f := begin apply lipschitz_with.of_dist_le_mul, rintros ⟨x, y⟩ ⟨z, t⟩, rw [real.dist_eq, abs_sub_le_iff], use candidates_lipschitz_aux fA, rw [dist_comm], exact candidates_lipschitz_aux fA end /-- candidates give rise to elements of bounded_continuous_functions -/ def candidates_b_of_candidates (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) : Cb X Y := bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩ lemma candidates_b_of_candidates_mem (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) : candidates_b_of_candidates f fA ∈ candidates_b X Y := fA /-- The distance on `X ⊕ Y` is a candidate -/ private lemma dist_mem_candidates : (λp : (X ⊕ Y) × (X ⊕ Y), dist p.1 p.2) ∈ candidates X Y := begin simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true, and_self, sum.forall, set.mem_set_of_eq, dist_self], repeat { split <|> exact (λa y z, dist_triangle_left _ _ _) <|> exact (λx y, by refl) <|> exact (λx y, max_var_bound) } end /-- The distance on `X ⊕ Y` as a candidate -/ def candidates_b_dist (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [inhabited X] [metric_space Y] [compact_space Y] [inhabited Y] : Cb X Y := candidates_b_of_candidates _ dist_mem_candidates lemma candidates_b_dist_mem_candidates_b : candidates_b_dist X Y ∈ candidates_b X Y := candidates_b_of_candidates_mem _ _ private lemma candidates_b_nonempty : (candidates_b X Y).nonempty := ⟨_, candidates_b_dist_mem_candidates_b⟩ /-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/ private lemma closed_candidates_b : is_closed (candidates_b X Y) := begin have I1 : ∀ x y, is_closed {f : Cb X Y | f (inl x, inl y) = dist x y} := λx y, is_closed_eq continuous_eval_const continuous_const, have I2 : ∀ x y, is_closed {f : Cb X Y | f (inr x, inr y) = dist x y } := λx y, is_closed_eq continuous_eval_const continuous_const, have I3 : ∀ x y, is_closed {f : Cb X Y | f (x, y) = f (y, x)} := λx y, is_closed_eq continuous_eval_const continuous_eval_const, have I4 : ∀ x y z, is_closed {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)} := λx y z, is_closed_le continuous_eval_const (continuous_eval_const.add continuous_eval_const), have I5 : ∀ x, is_closed {f : Cb X Y | f (x, x) = 0} := λx, is_closed_eq continuous_eval_const continuous_const, have I6 : ∀ x y, is_closed {f : Cb X Y | f (x, y) ≤ max_var X Y} := λx y, is_closed_le continuous_eval_const continuous_const, have : candidates_b X Y = (⋂x y, {f : Cb X Y | f ((@inl X Y x), (@inl X Y y)) = dist x y}) ∩ (⋂x y, {f : Cb X Y | f ((@inr X Y x), (@inr X Y y)) = dist x y}) ∩ (⋂x y, {f : Cb X Y | f (x, y) = f (y, x)}) ∩ (⋂x y z, {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)}) ∩ (⋂x, {f : Cb X Y | f (x, x) = 0}) ∩ (⋂x y, {f : Cb X Y | f (x, y) ≤ max_var X Y}), { ext, simp only [candidates_b, candidates, mem_inter_iff, mem_Inter, mem_set_of_eq] }, rw this, repeat { apply is_closed.inter _ _ <|> apply is_closed_Inter _ <|> apply I1 _ _ <|> apply I2 _ _ <|> apply I3 _ _ <|> apply I4 _ _ _ <|> apply I5 _ <|> apply I6 _ _ <|> assume x }, end /-- Compactness of candidates (in bounded_continuous_functions) follows. -/ private lemma is_compact_candidates_b : is_compact (candidates_b X Y) := begin refine arzela_ascoli₂ (Icc 0 (max_var X Y)) is_compact_Icc (candidates_b X Y) closed_candidates_b _ _, { rintros f ⟨x1, x2⟩ hf, simp only [set.mem_Icc], exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ }, { refine equicontinuous_of_continuity_modulus (λt, 2 * max_var X Y * t) _ _ _, { have : tendsto (λ (t : ℝ), 2 * (max_var X Y : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var X Y * 0)) := tendsto_const_nhds.mul tendsto_id, simpa using this }, { assume x y f hf, exact (candidates_lipschitz hf).dist_le_mul _ _ } } end /-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not in a metric space setting, so we need to define our custom version of Hausdorff distance, called HD, and prove its basic properties. -/ def HD (f : Cb X Y) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y)) /- We will show that HD is continuous on bounded_continuous_functions, to deduce that its minimum on the compact set candidates_b is attained. Since it is defined in terms of infimum and supremum on `ℝ`, which is only conditionnally complete, we will need all the time to check that the defining sets are bounded below or above. This is done in the next few technical lemmas -/ lemma HD_below_aux1 {f : Cb X Y} (C : ℝ) {x : X} : bdd_below (range (λ (y : Y), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux1 (f : Cb X Y) (C : ℝ) : bdd_above (range (λ (x : X), ⨅ y, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩, calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr default) + C : cinfi_le (HD_below_aux1 C) default ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) le_rfl end lemma HD_below_aux2 {f : Cb X Y} (C : ℝ) {y : Y} : bdd_below (range (λ (x : X), f (inl x, inr y) + C)) := let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1 in ⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩ private lemma HD_bound_aux2 (f : Cb X Y) (C : ℝ) : bdd_above (range (λ (y : Y), ⨅ x, f (inl x, inr y) + C)) := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).2 with ⟨Cf, hCf⟩, refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩, calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl default, inr y) + C : cinfi_le (HD_below_aux2 C) default ... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) le_rfl end /-- Explicit bound on `HD (dist)`. This means that when looking for minimizers it will be sufficient to look for functions with `HD(f)` bounded by this bound. -/ lemma HD_candidates_b_dist_le : HD (candidates_b_dist X Y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := begin refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)), { have A : (⨅ y, candidates_b_dist X Y (inl x, inr y)) ≤ candidates_b_dist X Y (inl x, inr default) := cinfi_le (by simpa using HD_below_aux1 0) default, have B : dist (inl x) (inr default) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc dist (inl x) (inr (default : Y)) = dist x (default : X) + 1 + dist default default : rfl ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : begin apply add_le_add (add_le_add _ le_rfl), exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _), any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ }, any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ }, exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _), end, exact le_trans A B }, { have A : (⨅ x, candidates_b_dist X Y (inl x, inr y)) ≤ candidates_b_dist X Y (inl default, inr y) := cinfi_le (by simpa using HD_below_aux2 0) default, have B : dist (inl default) (inr y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc dist (inl (default : X)) (inr y) = dist default default + 1 + dist default y : rfl ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : begin apply add_le_add (add_le_add _ le_rfl), exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _), any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ }, any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ }, exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _) end, exact le_trans A B }, end /- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/ private lemma HD_lipschitz_aux1 (f g : Cb X Y) : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 g.bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g := csupr_mono (HD_bound_aux1 _ (dist f g)) (λx, cinfi_mono ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀ x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g, { assume x, refine monotone.map_cinfi_of_continuous_at (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λ (y : Y), g (inl x, inr y))), from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } }, have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g, { refine monotone.map_csupr_of_continuous_at (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { simpa using HD_bound_aux1 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1, function.comp] end private lemma HD_lipschitz_aux2 (f g : Cb X Y) : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g := begin rcases (real.bounded_iff_bdd_below_bdd_above.1 g.bounded_range).1 with ⟨cg, hcg⟩, have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x), rcases (real.bounded_iff_bdd_below_bdd_above.1 f.bounded_range).1 with ⟨cf, hcf⟩, have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x), -- prove the inequality but with `dist f g` inside, by using inequalities comparing -- supr to supr and infi to infi have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g := csupr_mono (HD_bound_aux2 _ (dist f g)) (λy, cinfi_mono ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)), -- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps -- (here the addition of `dist f g`) preserve infimum and supremum have E1 : ∀ y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g, { assume y, refine monotone.map_cinfi_of_continuous_at (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { show bdd_below (range (λx:X, g (inl x, inr y))), from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } }, have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g, { refine monotone.map_csupr_of_continuous_at (continuous_at_id.add continuous_at_const) _ _, { assume x y hx, simpa }, { simpa using HD_bound_aux2 _ 0 } }, -- deduce the result from the above two steps simpa [E2, E1] end private lemma HD_lipschitz_aux3 (f g : Cb X Y) : HD f ≤ HD g + dist f g := max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _)) (le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _)) /-- Conclude that HD, being Lipschitz, is continuous -/ private lemma HD_continuous : continuous (HD : Cb X Y → ℝ) := lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3) end constructions --section section consequences variables (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y] /- Now that we have proved that the set of candidates is compact, and that HD is continuous, we can finally select a candidate minimizing HD. This will be the candidate realizing the optimal coupling. -/ private lemma exists_minimizer : ∃ f ∈ candidates_b X Y, ∀ g ∈ candidates_b X Y, HD f ≤ HD g := is_compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on private definition optimal_GH_dist : Cb X Y := classical.some (exists_minimizer X Y) private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist X Y ∈ candidates_b X Y := by cases (classical.some_spec (exists_minimizer X Y)); assumption private lemma HD_optimal_GH_dist_le (g : Cb X Y) (hg : g ∈ candidates_b X Y) : HD (optimal_GH_dist X Y) ≤ HD g := let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer X Y) in Z2 g hg /-- With the optimal candidate, construct a premetric space structure on `X ⊕ Y`, on which the predistance is given by the candidate. Then, we will identify points at `0` predistance to obtain a genuine metric space -/ def premetric_optimal_GH_dist : pseudo_metric_space (X ⊕ Y) := { dist := λp q, optimal_GH_dist X Y (p, q), dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b X Y), dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b X Y), dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b X Y) } local attribute [instance] premetric_optimal_GH_dist pseudo_metric.dist_setoid /-- A metric space which realizes the optimal coupling between `X` and `Y` -/ @[derive metric_space, nolint has_nonempty_instance] definition optimal_GH_coupling : Type* := pseudo_metric_quot (X ⊕ Y) /-- Injection of `X` in the optimal coupling between `X` and `Y` -/ def optimal_GH_injl (x : X) : optimal_GH_coupling X Y := ⟦inl x⟧ /-- The injection of `X` in the optimal coupling between `X` and `Y` is an isometry. -/ lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl X Y) := begin refine isometry.of_dist_eq (λx y, _), change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y, exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b X Y) _ _, end /-- Injection of `Y` in the optimal coupling between `X` and `Y` -/ def optimal_GH_injr (y : Y) : optimal_GH_coupling X Y := ⟦inr y⟧ /-- The injection of `Y` in the optimal coupling between `X` and `Y` is an isometry. -/ lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr X Y) := begin refine isometry.of_dist_eq (λx y, _), change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y, exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b X Y) _ _, end /-- The optimal coupling between two compact spaces `X` and `Y` is still a compact space -/ instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling X Y) := ⟨begin have : (univ : set (optimal_GH_coupling X Y)) = (optimal_GH_injl X Y '' univ) ∪ (optimal_GH_injr X Y '' univ), { refine subset.antisymm (λxc hxc, _) (subset_univ _), rcases quotient.exists_rep xc with ⟨x, hx⟩, cases x; rw ← hx, { have : ⟦inl x⟧ = optimal_GH_injl X Y x := rfl, rw this, exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) }, { have : ⟦inr x⟧ = optimal_GH_injr X Y x := rfl, rw this, exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } }, rw this, exact (is_compact_univ.image (isometry_optimal_GH_injl X Y).continuous).union (is_compact_univ.image (isometry_optimal_GH_injr X Y).continuous) end⟩ /-- For any candidate `f`, `HD(f)` is larger than or equal to the Hausdorff distance in the optimal coupling. This follows from the fact that HD of the optimal candidate is exactly the Hausdorff distance in the optimal coupling, although we only prove here the inequality we need. -/ lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b X Y) : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD f := begin refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le X Y f h), have A : ∀ x ∈ range (optimal_GH_injl X Y), ∃ y ∈ range (optimal_GH_injr X Y), dist x y ≤ r, { assume x hx, rcases mem_range.1 hx with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y)) < r := lt_of_le_of_lt (le_max_left _ _) hr, have I2 : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) ≤ ⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y) := le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _), have I : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injr X Y z', mem_range_self _], have : (optimal_GH_dist X Y) (inl z, inr z') ≤ r, by { rw hz', exact le_of_lt hr' }, exact this }, refine Hausdorff_dist_le_of_mem_dist _ A _, { rcases exists_mem_of_nonempty X with ⟨xX, _⟩, have : optimal_GH_injl X Y xX ∈ range (optimal_GH_injl X Y) := mem_range_self _, rcases A _ this with ⟨y, yrange, hy⟩, exact le_trans dist_nonneg hy }, { assume y hy, rcases mem_range.1 hy with ⟨z, hz⟩, rw ← hz, have I1 : (⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y)) < r := lt_of_le_of_lt (le_max_right _ _) hr, have I2 : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) ≤ ⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y) := le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _), have I : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) < r := lt_of_le_of_lt I2 I1, rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩, rcases mem_range.1 r'range with ⟨z', hz'⟩, existsi [optimal_GH_injl X Y z', mem_range_self _], have : (optimal_GH_dist X Y) (inl z', inr z) ≤ r, by { rw hz', exact le_of_lt hr' }, rw dist_comm, exact this } end end consequences /- We are done with the construction of the optimal coupling -/ end Gromov_Hausdorff_realized end Gromov_Hausdorff
644f7c39670503afeba6c4d1cafaaa2ac5cb7332
4727251e0cd73359b15b664c3170e5d754078599
/src/logic/function/iterate.lean
d07e04274f4c6e102c1358a962933381992edf9d
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
6,427
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import logic.function.conjugate /-! # Iterations of a function In this file we prove simple properties of `nat.iterate f n` a.k.a. `f^[n]`: * `iterate_zero`, `iterate_succ`, `iterate_succ'`, `iterate_add`, `iterate_mul`: formulas for `f^[0]`, `f^[n+1]` (two versions), `f^[n+m]`, and `f^[n*m]`; * `iterate_id` : `id^[n]=id`; * `injective.iterate`, `surjective.iterate`, `bijective.iterate` : iterates of an injective/surjective/bijective function belong to the same class; * `left_inverse.iterate`, `right_inverse.iterate`, `commute.iterate_left`, `commute.iterate_right`, `commute.iterate_iterate`: some properties of pairs of functions survive under iterations * `iterate_fixed`, `semiconj.iterate_*`, `semiconj₂.iterate`: if `f` fixes a point (resp., semiconjugates unary/binary operarations), then so does `f^[n]`. -/ universes u v variables {α : Type u} {β : Type v} namespace function variable (f : α → α) @[simp] theorem iterate_zero : f^[0] = id := rfl theorem iterate_zero_apply (x : α) : f^[0] x = x := rfl @[simp] theorem iterate_succ (n : ℕ) : f^[n.succ] = (f^[n]) ∘ f := rfl theorem iterate_succ_apply (n : ℕ) (x : α) : f^[n.succ] x = (f^[n]) (f x) := rfl @[simp] theorem iterate_id (n : ℕ) : (id : α → α)^[n] = id := nat.rec_on n rfl $ λ n ihn, by rw [iterate_succ, ihn, comp.left_id] theorem iterate_add : ∀ (m n : ℕ), f^[m + n] = (f^[m]) ∘ (f^[n]) | m 0 := rfl | m (nat.succ n) := by rw [nat.add_succ, iterate_succ, iterate_succ, iterate_add] theorem iterate_add_apply (m n : ℕ) (x : α) : f^[m + n] x = (f^[m] (f^[n] x)) := by rw iterate_add @[simp] theorem iterate_one : f^[1] = f := funext $ λ a, rfl lemma iterate_mul (m : ℕ) : ∀ n, f^[m * n] = (f^[m]^[n]) | 0 := by simp only [nat.mul_zero, iterate_zero] | (n + 1) := by simp only [nat.mul_succ, nat.mul_one, iterate_one, iterate_add, iterate_mul n] variable {f} theorem iterate_fixed {x} (h : f x = x) (n : ℕ) : f^[n] x = x := nat.rec_on n rfl $ λ n ihn, by rw [iterate_succ_apply, h, ihn] theorem injective.iterate (Hinj : injective f) (n : ℕ) : injective (f^[n]) := nat.rec_on n injective_id $ λ n ihn, ihn.comp Hinj theorem surjective.iterate (Hsurj : surjective f) (n : ℕ) : surjective (f^[n]) := nat.rec_on n surjective_id $ λ n ihn, ihn.comp Hsurj theorem bijective.iterate (Hbij : bijective f) (n : ℕ) : bijective (f^[n]) := ⟨Hbij.1.iterate n, Hbij.2.iterate n⟩ namespace semiconj lemma iterate_right {f : α → β} {ga : α → α} {gb : β → β} (h : semiconj f ga gb) (n : ℕ) : semiconj f (ga^[n]) (gb^[n]) := nat.rec_on n id_right $ λ n ihn, ihn.comp_right h lemma iterate_left {g : ℕ → α → α} (H : ∀ n, semiconj f (g n) (g $ n + 1)) (n k : ℕ) : semiconj (f^[n]) (g k) (g $ n + k) := begin induction n with n ihn generalizing k, { rw [nat.zero_add], exact id_left }, { rw [nat.succ_eq_add_one, nat.add_right_comm, nat.add_assoc], exact (H k).comp_left (ihn (k + 1)) } end end semiconj namespace commute variable {g : α → α} lemma iterate_right (h : commute f g) (n : ℕ) : commute f (g^[n]) := h.iterate_right n lemma iterate_left (h : commute f g) (n : ℕ) : commute (f^[n]) g := (h.symm.iterate_right n).symm lemma iterate_iterate (h : commute f g) (m n : ℕ) : commute (f^[m]) (g^[n]) := (h.iterate_left m).iterate_right n lemma iterate_eq_of_map_eq (h : commute f g) (n : ℕ) {x} (hx : f x = g x) : f^[n] x = (g^[n]) x := nat.rec_on n rfl $ λ n ihn, by simp only [iterate_succ_apply, hx, (h.iterate_left n).eq, ihn, ((refl g).iterate_right n).eq] lemma comp_iterate (h : commute f g) (n : ℕ) : (f ∘ g)^[n] = (f^[n]) ∘ (g^[n]) := begin induction n with n ihn, { refl }, funext x, simp only [ihn, (h.iterate_right n).eq, iterate_succ, comp_app] end variable (f) lemma iterate_self (n : ℕ) : commute (f^[n]) f := (refl f).iterate_left n lemma self_iterate (n : ℕ) : commute f (f^[n]) := (refl f).iterate_right n lemma iterate_iterate_self (m n : ℕ) : commute (f^[m]) (f^[n]) := (refl f).iterate_iterate m n end commute lemma semiconj₂.iterate {f : α → α} {op : α → α → α} (hf : semiconj₂ f op op) (n : ℕ) : semiconj₂ (f^[n]) op op := nat.rec_on n (semiconj₂.id_left op) (λ n ihn, ihn.comp hf) variable (f) theorem iterate_succ' (n : ℕ) : f^[n.succ] = f ∘ (f^[n]) := by rw [iterate_succ, (commute.self_iterate f n).comp_eq] theorem iterate_succ_apply' (n : ℕ) (x : α) : f^[n.succ] x = f (f^[n] x) := by rw [iterate_succ'] theorem iterate_pred_comp_of_pos {n : ℕ} (hn : 0 < n) : f^[n.pred] ∘ f = (f^[n]) := by rw [← iterate_succ, nat.succ_pred_eq_of_pos hn] theorem comp_iterate_pred_of_pos {n : ℕ} (hn : 0 < n) : f ∘ (f^[n.pred]) = (f^[n]) := by rw [← iterate_succ', nat.succ_pred_eq_of_pos hn] /-- A recursor for the iterate of a function. -/ def iterate.rec (p : α → Sort*) {f : α → α} (h : ∀ a, p a → p (f a)) {a : α} (ha : p a) (n : ℕ) : p (f^[n] a) := nat.rec ha (λ m, by { rw iterate_succ', exact h _ }) n lemma iterate.rec_zero (p : α → Sort*) {f : α → α} (h : ∀ a, p a → p (f a)) {a : α} (ha : p a) : iterate.rec p h ha 0 = ha := rfl variable {f} theorem left_inverse.iterate {g : α → α} (hg : left_inverse g f) (n : ℕ) : left_inverse (g^[n]) (f^[n]) := nat.rec_on n (λ _, rfl) $ λ n ihn, by { rw [iterate_succ', iterate_succ], exact ihn.comp hg } theorem right_inverse.iterate {g : α → α} (hg : right_inverse g f) (n : ℕ) : right_inverse (g^[n]) (f^[n]) := hg.iterate n lemma iterate_comm (f : α → α) (m n : ℕ) : f^[n]^[m] = (f^[m]^[n]) := (iterate_mul _ _ _).symm.trans (eq.trans (by rw nat.mul_comm) (iterate_mul _ _ _)) lemma iterate_commute (m n : ℕ) : commute (λ f : α → α, f^[m]) (λ f, f^[n]) := λ f, iterate_comm f m n end function namespace list open function theorem foldl_const (f : α → α) (a : α) (l : list β) : l.foldl (λ b _, f b) a = (f^[l.length]) a := begin induction l with b l H generalizing a, { refl }, { rw [length_cons, foldl, iterate_succ_apply, H] } end theorem foldr_const (f : β → β) (b : β) : Π l : list α, l.foldr (λ _, f) b = (f^[l.length]) b | [] := rfl | (a::l) := by rw [length_cons, foldr, foldr_const l, iterate_succ_apply'] end list
534f48d115894ca06ebace83e5546ec6582b87a2
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/mismatch.lean
eaa1bfd94e270b40f7cebc08ac1dc0ff6ffdb53a
[ "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
55
lean
definition id {A : Type} {a : A} := a check @id nat 1
ac9186f1ea3390063689893925d8c67f2007d648
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/quote_bas.lean
9c42f2764f10be0f86d930256dbe40697efa615d
[ "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
2,506
lean
universes u v w namespace quote_bas inductive Expr (V : Type u) | One {} : Expr | Var (v : V) : Expr | Mult (a b : Expr) : Expr @[reducible] def Value := nat def Env (V : Type u) := V → Value open Expr def evalExpr {V} (vs : Env V) : Expr V → Value | One := 1 | (Var v) := vs v | (Mult a b) := evalExpr a * evalExpr b def novars : Env empty := empty.rec _ def singlevar (x : Value) : Env unit := λ _, x open sum def merge {A : Type u} {B : Type v} (a : Env A) (b : Env B) : Env (sum A B) | (inl j) := a j | (inr j) := b j def map_var {A : Type u} {B : Type v} (f : A → B) : Expr A → Expr B | One := One | (Var v) := Var (f v) | (Mult a b) := Mult (map_var a) (map_var b) def sum_assoc {A : Type u} {B : Type v} {C : Type w} : sum (sum A B) C → sum A (sum B C) | (inl (inl a)) := inl a | (inl (inr b)) := inr (inl b) | (inr c) := inr (inr c) attribute [simp] evalExpr map_var sum_assoc merge @[simp] lemma eval_map_var_shift {A : Type u} {B : Type v} (v : Env A) (v' : Env B) (e : Expr A) : evalExpr (merge v v') (map_var inl e) = evalExpr v e := begin induction e, reflexivity, reflexivity, simp_using_hs end @[simp] lemma eval_map_var_sum_assoc {A : Type u} {B : Type v} {C : Type w} (v : Env A) (v' : Env B) (v'' : Env C) (e : Expr (sum (sum A B) C)) : evalExpr (merge v (merge v' v'')) (map_var sum_assoc e) = evalExpr (merge (merge v v') v'') e := begin induction e, reflexivity, { cases v_1 with v₁, cases v₁, all_goals {simp} }, { simp_using_hs } end class Quote {V : inout Type u} (l : inout Env V) (n : Value) {V' : inout Type v} (r : inout Env V') := (quote : Expr (sum V V')) (eval_quote : evalExpr (merge l r) quote = n) def quote {V : Type u} {l : Env V} (n : nat) {V' : Type v} {r : Env V'} [Quote l n r] : Expr (sum V V') := Quote.quote l n r @[simp] lemma eval_quote {V : Type u} {l : Env V} (n : nat) {V' : Type v} {r : Env V'} [Quote l n r] : evalExpr (merge l r) (quote n) = n := Quote.eval_quote l n r instance quote_one V (v : Env V) : Quote v 1 novars := { quote := One, eval_quote := rfl } instance quote_mul {V : Type u} (v : Env V) n {V' : Type v} (v' : Env V') m {V'' : Type w} (v'' : Env V'') [Quote v n v'] [Quote (merge v v') m v''] : Quote v (n * m) (merge v' v'') := { quote := Mult (map_var sum_assoc (map_var inl (quote n))) (map_var sum_assoc (quote m)), eval_quote := by simp } end quote_bas
a8a17f54e97b04c3b8d42b623cc5727d6663bf13
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/polynomial/algebra_map.lean
58a367498c46d594b26ae4fd085cb1894116f976
[ "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
10,507
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.eval import algebra.algebra.tower /-! # Theory of univariate polynomials We show that `polynomial A` is an R-algebra when `A` is an R-algebra. We promote `eval₂` to an algebra hom in `aeval`. -/ noncomputable theory open finset open_locale big_operators namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_semiring variables [comm_semiring R] {p q r : polynomial R} variables [semiring A] [algebra R A] /-- Note that this instance also provides `algebra R (polynomial R)`. -/ instance algebra_of_algebra : algebra R (polynomial A) := { smul_def' := λ r p, begin rcases p, simp only [C, monomial, monomial_fun, ring_hom.coe_mk, ring_hom.to_fun_eq_coe, function.comp_app, ring_hom.coe_comp, smul_to_finsupp, mul_to_finsupp], exact algebra.smul_def' _ _, end, commutes' := λ r p, begin rcases p, simp only [C, monomial, monomial_fun, ring_hom.coe_mk, ring_hom.to_fun_eq_coe, function.comp_app, ring_hom.coe_comp, mul_to_finsupp], convert algebra.commutes' r p, end, .. C.comp (algebra_map R A) } lemma algebra_map_apply (r : R) : algebra_map R (polynomial A) r = C (algebra_map R A r) := rfl /-- When we have `[comm_ring R]`, the function `C` is the same as `algebra_map R (polynomial R)`. (But note that `C` is defined when `R` is not necessarily commutative, in which case `algebra_map` is not available.) -/ lemma C_eq_algebra_map {R : Type*} [comm_ring R] (r : R) : C r = algebra_map R (polynomial R) r := rfl instance [nontrivial A] : nontrivial (subalgebra R (polynomial A)) := ⟨⟨⊥, ⊤, begin rw [ne.def, set_like.ext_iff, not_forall], refine ⟨X, _⟩, simp only [algebra.mem_bot, not_exists, set.mem_range, iff_true, algebra.mem_top, algebra_map_apply, not_forall], intro x, rw [ext_iff, not_forall], refine ⟨1, _⟩, simp [coeff_C], end⟩⟩ @[simp] lemma alg_hom_eval₂_algebra_map {R A B : Type*} [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] (p : polynomial R) (f : A →ₐ[R] B) (a : A) : f (eval₂ (algebra_map R A) a p) = eval₂ (algebra_map R B) (f a) p := begin dsimp [eval₂, sum], simp only [f.map_sum, f.map_mul, f.map_pow, ring_hom.eq_int_cast, ring_hom.map_int_cast, alg_hom.commutes], end @[simp] lemma eval₂_algebra_map_X {R A : Type*} [comm_ring R] [ring A] [algebra R A] (p : polynomial R) (f : polynomial R →ₐ[R] A) : eval₂ (algebra_map R A) (f X) p = f p := begin conv_rhs { rw [←polynomial.sum_C_mul_X_eq p], }, dsimp [eval₂, sum], simp only [f.map_sum, f.map_mul, f.map_pow, ring_hom.eq_int_cast, ring_hom.map_int_cast], simp [polynomial.C_eq_algebra_map], end @[simp] lemma ring_hom_eval₂_algebra_map_int {R S : Type*} [ring R] [ring S] (p : polynomial ℤ) (f : R →+* S) (r : R) : f (eval₂ (algebra_map ℤ R) r p) = eval₂ (algebra_map ℤ S) (f r) p := alg_hom_eval₂_algebra_map p f.to_int_alg_hom r @[simp] lemma eval₂_algebra_map_int_X {R : Type*} [ring R] (p : polynomial ℤ) (f : polynomial ℤ →+* R) : eval₂ (algebra_map ℤ R) (f X) p = f p := -- Unfortunately `f.to_int_alg_hom` doesn't work here, as typeclasses don't match up correctly. eval₂_algebra_map_X p { commutes' := λ n, by simp, .. f } end comm_semiring section aeval variables [comm_semiring R] {p q : polynomial R} variables [semiring A] [algebra R A] variables {B : Type*} [semiring B] [algebra R B] variables (x : A) /-- Given a valuation `x` of the variable in an `R`-algebra `A`, `aeval R A x` is the unique `R`-algebra homomorphism from `R[X]` to `A` sending `X` to `x`. -/ def aeval : polynomial R →ₐ[R] A := { commutes' := λ r, eval₂_C _ _, ..eval₂_ring_hom' (algebra_map R A) x (λ a, algebra.commutes _ _) } variables {R A} @[ext] lemma alg_hom_ext {f g : polynomial R →ₐ[R] A} (h : f X = g X) : f = g := begin ext p, rw [← sum_monomial_eq p], simp [sum, f.map_sum, g.map_sum, monomial_eq_smul_X, h], end theorem aeval_def (p : polynomial R) : aeval x p = eval₂ (algebra_map R A) x p := rfl @[simp] lemma aeval_zero : aeval x (0 : polynomial R) = 0 := alg_hom.map_zero (aeval x) @[simp] lemma aeval_X : aeval x (X : polynomial R) = x := eval₂_X _ x @[simp] lemma aeval_C (r : R) : aeval x (C r) = algebra_map R A r := eval₂_C _ x @[simp] lemma aeval_monomial {n : ℕ} {r : R} : aeval x (monomial n r) = (algebra_map _ _ r) * x^n := eval₂_monomial _ _ @[simp] lemma aeval_X_pow {n : ℕ} : aeval x ((X : polynomial R)^n) = x^n := eval₂_X_pow _ _ @[simp] lemma aeval_add : aeval x (p + q) = aeval x p + aeval x q := alg_hom.map_add _ _ _ @[simp] lemma aeval_one : aeval x (1 : polynomial R) = 1 := alg_hom.map_one _ @[simp] lemma aeval_bit0 : aeval x (bit0 p) = bit0 (aeval x p) := alg_hom.map_bit0 _ _ @[simp] lemma aeval_bit1 : aeval x (bit1 p) = bit1 (aeval x p) := alg_hom.map_bit1 _ _ @[simp] lemma aeval_nat_cast (n : ℕ) : aeval x (n : polynomial R) = n := alg_hom.map_nat_cast _ _ lemma aeval_mul : aeval x (p * q) = aeval x p * aeval x q := alg_hom.map_mul _ _ _ lemma aeval_comp {A : Type*} [comm_semiring A] [algebra R A] (x : A) : aeval x (p.comp q) = (aeval (aeval x q) p) := eval₂_comp (algebra_map R A) @[simp] lemma aeval_map {A : Type*} [comm_semiring A] [algebra R A] [algebra A B] [is_scalar_tower R A B] (b : B) (p : polynomial R) : aeval b (p.map (algebra_map R A)) = aeval b p := by rw [aeval_def, eval₂_map, ←is_scalar_tower.algebra_map_eq, ←aeval_def] theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map R A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [φ.map_add, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, φ.map_mul, eval₂_mul_noncomm (algebra_map R A) _ (λ k, algebra.commutes _ _), eval₂_X, ih] } end theorem aeval_alg_hom (f : A →ₐ[R] B) (x : A) : aeval (f x) = f.comp (aeval x) := alg_hom.ext $ λ p, by rw [eval_unique (f.comp (aeval x)), alg_hom.comp_apply, aeval_X, aeval_def] theorem aeval_alg_hom_apply (f : A →ₐ[R] B) (x : A) (p : polynomial R) : aeval (f x) p = f (aeval x p) := alg_hom.ext_iff.1 (aeval_alg_hom f x) p lemma aeval_algebra_map_apply (x : R) (p : polynomial R) : aeval (algebra_map R A x) p = algebra_map R A (p.eval x) := aeval_alg_hom_apply (algebra.of_id R A) x p @[simp] lemma coe_aeval_eq_eval (r : R) : (aeval r : polynomial R → R) = eval r := rfl @[simp] lemma aeval_fn_apply {X : Type*} (g : polynomial R) (f : X → R) (x : X) : ((aeval f) g) x = aeval (f x) g := (aeval_alg_hom_apply (pi.eval_alg_hom _ _ x) f g).symm @[norm_cast] lemma aeval_subalgebra_coe (g : polynomial R) {A : Type*} [semiring A] [algebra R A] (s : subalgebra R A) (f : s) : (aeval f g : A) = aeval (f : A) g := (aeval_alg_hom_apply s.val f g).symm lemma coeff_zero_eq_aeval_zero (p : polynomial R) : p.coeff 0 = aeval 0 p := by simp [coeff_zero_eq_eval_zero] variables [comm_ring S] {f : R →+* S} lemma is_root_of_eval₂_map_eq_zero (hf : function.injective f) {r : R} : eval₂ f (f r) p = 0 → p.is_root r := begin intro h, apply hf, rw [←eval₂_hom, h, f.map_zero], end lemma is_root_of_aeval_algebra_map_eq_zero [algebra R S] {p : polynomial R} (inj : function.injective (algebra_map R S)) {r : R} (hr : aeval (algebra_map R S r) p = 0) : p.is_root r := is_root_of_eval₂_map_eq_zero inj hr lemma dvd_term_of_dvd_eval_of_dvd_terms {z p : S} {f : polynomial S} (i : ℕ) (dvd_eval : p ∣ f.eval z) (dvd_terms : ∀ (j ≠ i), p ∣ f.coeff j * z ^ j) : p ∣ f.coeff i * z ^ i := begin by_cases hf : f = 0, { simp [hf] }, by_cases hi : i ∈ f.support, { rw [eval, eval₂, sum] at dvd_eval, rw [←finset.insert_erase hi, finset.sum_insert (finset.not_mem_erase _ _)] at dvd_eval, refine (dvd_add_left _).mp dvd_eval, apply finset.dvd_sum, intros j hj, exact dvd_terms j (finset.ne_of_mem_erase hj) }, { convert dvd_zero p, rw not_mem_support_iff at hi, simp [hi] } end lemma dvd_term_of_is_root_of_dvd_terms {r p : S} {f : polynomial S} (i : ℕ) (hr : f.is_root r) (h : ∀ (j ≠ i), p ∣ f.coeff j * r ^ j) : p ∣ f.coeff i * r ^ i := dvd_term_of_dvd_eval_of_dvd_terms i (eq.symm hr ▸ dvd_zero p) h lemma aeval_eq_sum_range [algebra R S] {p : polynomial R} (x : S) : aeval x p = ∑ i in finset.range (p.nat_degree + 1), p.coeff i • x ^ i := by { simp_rw algebra.smul_def, exact eval₂_eq_sum_range (algebra_map R S) x } lemma aeval_eq_sum_range' [algebra R S] {p : polynomial R} {n : ℕ} (hn : p.nat_degree < n) (x : S) : aeval x p = ∑ i in finset.range n, p.coeff i • x ^ i := by { simp_rw algebra.smul_def, exact eval₂_eq_sum_range' (algebra_map R S) hn x } end aeval section ring variables [ring R] /-- The evaluation map is not generally multiplicative when the coefficient ring is noncommutative, but nevertheless any polynomial of the form `p * (X - monomial 0 r)` is sent to zero when evaluated at `r`. This is the key step in our proof of the Cayley-Hamilton theorem. -/ lemma eval_mul_X_sub_C {p : polynomial R} (r : R) : (p * (X - C r)).eval r = 0 := begin simp only [eval, eval₂, ring_hom.id_apply], have bound := calc (p * (X - C r)).nat_degree ≤ p.nat_degree + (X - C r).nat_degree : nat_degree_mul_le ... ≤ p.nat_degree + 1 : add_le_add_left nat_degree_X_sub_C_le _ ... < p.nat_degree + 2 : lt_add_one _, rw sum_over_range' _ _ (p.nat_degree + 2) bound, swap, { simp, }, rw sum_range_succ', conv_lhs { congr, apply_congr, skip, rw [coeff_mul_X_sub_C, sub_mul, mul_assoc, ←pow_succ], }, simp [sum_range_sub', coeff_monomial], end theorem not_is_unit_X_sub_C [nontrivial R] {r : R} : ¬ is_unit (X - C r) := λ ⟨⟨_, g, hfg, hgf⟩, rfl⟩, @zero_ne_one R _ _ $ by erw [← eval_mul_X_sub_C, hgf, eval_one] end ring lemma aeval_endomorphism {M : Type*} [comm_ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) (v : M) (p : polynomial R) : aeval f p v = p.sum (λ n b, b • (f ^ n) v) := begin rw [aeval_def, eval₂], exact (finset.sum_hom p.support (λ h : M →ₗ[R] M, h v)).symm end end polynomial
20970ae6ac82d24a3154ba182a680ec9d4ac1741
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/caching_user_attribute.lean
b5459dc53bcf24790ece326c925dc68e73b88109
[ "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
648
lean
@[user_attribute] meta def foo_attr : user_attribute string := { name := `foo, descr := "bar", cache_cfg := { mk_cache := λ ns, return $ string.join (list.map (λ n, to_string n ++ "\n") ns), dependencies := []} } attribute [foo] eq.refl eq.mp set_option trace.user_attributes_cache true run_cmd do s : string ← foo_attr.get_cache, tactic.trace s, s : string ← foo_attr.get_cache, tactic.trace s, foo_attr.set `eq.mpr () tt, s : string ← foo_attr.get_cache, tactic.trace s, tactic.set_basic_attribute `reducible ``eq.mp, -- should not affect [foo] cache s : string ← foo_attr.get_cache, tactic.trace s
fc95e9024ed9a7b4f860533d838df001b52aeeca
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Elab/Do.lean
28196eb1d14cbeb3fd033ffede32db521d452345
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
70,313
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term import Lean.Elab.BindersUtil import Lean.Elab.PatternVar import Lean.Elab.Quotation.Util import Lean.Parser.Do -- HACK: avoid code explosion until heuristics are improved set_option compiler.reuse false namespace Lean.Elab.Term open Lean.Parser.Term open Meta private def getDoSeqElems (doSeq : Syntax) : List Syntax := if doSeq.getKind == ``Lean.Parser.Term.doSeqBracketed then doSeq[1].getArgs.toList.map fun arg => arg[0] else if doSeq.getKind == ``Lean.Parser.Term.doSeqIndent then doSeq[0].getArgs.toList.map fun arg => arg[0] else [] private def getDoSeq (doStx : Syntax) : Syntax := doStx[1] @[builtinTermElab liftMethod] def elabLiftMethod : TermElab := fun stx _ => throwErrorAt stx "invalid use of `(<- ...)`, must be nested inside a 'do' expression" /-- Return true if we should not lift `(<- ...)` actions nested in the syntax nodes with the given kind. -/ private def liftMethodDelimiter (k : SyntaxNodeKind) : Bool := k == ``Lean.Parser.Term.do || k == ``Lean.Parser.Term.doSeqIndent || k == ``Lean.Parser.Term.doSeqBracketed || k == ``Lean.Parser.Term.termReturn || k == ``Lean.Parser.Term.termUnless || k == ``Lean.Parser.Term.termTry || k == ``Lean.Parser.Term.termFor /-- Given `stx` which is a `letPatDecl`, `letEqnsDecl`, or `letIdDecl`, return true if it has binders. -/ private def letDeclArgHasBinders (letDeclArg : Syntax) : Bool := let k := letDeclArg.getKind if k == ``Lean.Parser.Term.letPatDecl then false else if k == ``Lean.Parser.Term.letEqnsDecl then true else if k == ``Lean.Parser.Term.letIdDecl then -- letIdLhs := ident >> checkWsBefore "expected space before binders" >> many (ppSpace >> (simpleBinderWithoutType <|> bracketedBinder)) >> optType let binders := letDeclArg[1] binders.getNumArgs > 0 else false /-- Return `true` if the given `letDecl` contains binders. -/ private def letDeclHasBinders (letDecl : Syntax) : Bool := letDeclArgHasBinders letDecl[0] /-- Return true if we should generate an error message when lifting a method over this kind of syntax. -/ private def liftMethodForbiddenBinder (stx : Syntax) : Bool := let k := stx.getKind if k == ``Lean.Parser.Term.fun || k == ``Lean.Parser.Term.matchAlts || k == ``Lean.Parser.Term.doLetRec || k == ``Lean.Parser.Term.letrec then -- It is never ok to lift over this kind of binder true -- The following kinds of `let`-expressions require extra checks to decide whether they contain binders or not else if k == ``Lean.Parser.Term.let then letDeclHasBinders stx[1] else if k == ``Lean.Parser.Term.doLet then letDeclHasBinders stx[2] else if k == ``Lean.Parser.Term.doLetArrow then letDeclArgHasBinders stx[2] else false private partial def hasLiftMethod : Syntax → Bool | Syntax.node k args => if liftMethodDelimiter k then false -- NOTE: We don't check for lifts in quotations here, which doesn't break anything but merely makes this rare case a -- bit slower else if k == ``Lean.Parser.Term.liftMethod then true else args.any hasLiftMethod | _ => false structure ExtractMonadResult where m : Expr α : Expr hasBindInst : Expr expectedType : Expr isPure : Bool -- `true` when it is a pure `do` block. That is, Lean implicitly inserted the `Id` Monad. private def mkIdBindFor (type : Expr) : TermElabM ExtractMonadResult := do let u ← getDecLevel type let id := Lean.mkConst ``Id [u] let idBindVal := Lean.mkConst ``Id.hasBind [u] pure { m := id, hasBindInst := idBindVal, α := type, expectedType := mkApp id type, isPure := true } private partial def extractBind (expectedType? : Option Expr) : TermElabM ExtractMonadResult := do match expectedType? with | none => throwError "invalid 'do' notation, expected type is not available" | some expectedType => let extractStep? (type : Expr) : MetaM (Option ExtractMonadResult) := do match type with | Expr.app m α _ => try let bindInstType ← mkAppM ``Bind #[m] let bindInstVal ← Meta.synthInstance bindInstType return some { m := m, hasBindInst := bindInstVal, α := α, expectedType := expectedType, isPure := false } catch _ => return none | _ => return none let rec extract? (type : Expr) : MetaM (Option ExtractMonadResult) := do match (← extractStep? type) with | some r => return r | none => let typeNew ← whnfCore type if typeNew != type then extract? typeNew else if typeNew.getAppFn.isMVar then throwError "invalid 'do' notation, expected type is not available" match (← unfoldDefinition? typeNew) with | some typeNew => extract? typeNew | none => return none match (← extract? expectedType) with | some r => return r | none => mkIdBindFor expectedType namespace Do /- A `doMatch` alternative. `vars` is the array of variables declared by `patterns`. -/ structure Alt (σ : Type) where ref : Syntax vars : Array Name patterns : Syntax rhs : σ deriving Inhabited /- Auxiliary datastructure for representing a `do` code block, and compiling "reassignments" (e.g., `x := x + 1`). We convert `Code` into a `Syntax` term representing the: - `do`-block, or - the visitor argument for the `forIn` combinator. We say the following constructors are terminals: - `break`: for interrupting a `for x in s` - `continue`: for interrupting the current iteration of a `for x in s` - `return e`: for returning `e` as the result for the whole `do` computation block - `action a`: for executing action `a` as a terminal - `ite`: if-then-else - `match`: pattern matching - `jmp` a goto to a join-point We say the terminals `break`, `continue`, `action`, and `return` are "exit points" Note that, `return e` is not equivalent to `action (pure e)`. Here is an example: ``` def f (x : Nat) : IO Unit := do if x == 0 then return () IO.println "hello" ``` Executing `#eval f 0` will not print "hello". Now, consider ``` def g (x : Nat) : IO Unit := do if x == 0 then pure () IO.println "hello" ``` The `if` statement is essentially a noop, and "hello" is printed when we execute `g 0`. - `decl` represents all declaration-like `doElem`s (e.g., `let`, `have`, `let rec`). The field `stx` is the actual `doElem`, `vars` is the array of variables declared by it, and `cont` is the next instruction in the `do` code block. `vars` is an array since we have declarations such as `let (a, b) := s`. - `reassign` is an reassignment-like `doElem` (e.g., `x := x + 1`). - `joinpoint` is a join point declaration: an auxiliary `let`-declaration used to represent the control-flow. - `seq a k` executes action `a`, ignores its result, and then executes `k`. We also store the do-elements `dbg_trace` and `assert!` as actions in a `seq`. A code block `C` is well-formed if - For every `jmp ref j as` in `C`, there is a `joinpoint j ps b k` and `jmp ref j as` is in `k`, and `ps.size == as.size` -/ inductive Code where | decl (xs : Array Name) (doElem : Syntax) (k : Code) | reassign (xs : Array Name) (doElem : Syntax) (k : Code) /- The Boolean value in `params` indicates whether we should use `(x : typeof! x)` when generating term Syntax or not -/ | joinpoint (name : Name) (params : Array (Name × Bool)) (body : Code) (k : Code) | seq (action : Syntax) (k : Code) | action (action : Syntax) | «break» (ref : Syntax) | «continue» (ref : Syntax) | «return» (ref : Syntax) (val : Syntax) /- Recall that an if-then-else may declare a variable using `optIdent` for the branches `thenBranch` and `elseBranch`. We store the variable name at `var?`. -/ | ite (ref : Syntax) (h? : Option Name) (optIdent : Syntax) (cond : Syntax) (thenBranch : Code) (elseBranch : Code) | «match» (ref : Syntax) (gen : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt Code)) | jmp (ref : Syntax) (jpName : Name) (args : Array Syntax) deriving Inhabited /- A code block, and the collection of variables updated by it. -/ structure CodeBlock where code : Code uvars : NameSet := {} -- set of variables updated by `code` private def nameSetToArray (s : NameSet) : Array Name := s.fold (fun (xs : Array Name) x => xs.push x) #[] private def varsToMessageData (vars : Array Name) : MessageData := MessageData.joinSep (vars.toList.map fun n => MessageData.ofName (n.simpMacroScopes)) " " partial def CodeBlocl.toMessageData (codeBlock : CodeBlock) : MessageData := let us := MessageData.ofList $ (nameSetToArray codeBlock.uvars).toList.map MessageData.ofName let rec loop : Code → MessageData | Code.decl xs _ k => m!"let {varsToMessageData xs} := ...\n{loop k}" | Code.reassign xs _ k => m!"{varsToMessageData xs} := ...\n{loop k}" | Code.joinpoint n ps body k => m!"let {n.simpMacroScopes} {varsToMessageData (ps.map Prod.fst)} := {indentD (loop body)}\n{loop k}" | Code.seq e k => m!"{e}\n{loop k}" | Code.action e => e | Code.ite _ _ _ c t e => m!"if {c} then {indentD (loop t)}\nelse{loop e}" | Code.jmp _ j xs => m!"jmp {j.simpMacroScopes} {xs.toList}" | Code.«break» _ => m!"break {us}" | Code.«continue» _ => m!"continue {us}" | Code.«return» _ v => m!"return {v} {us}" | Code.«match» _ _ ds t alts => m!"match {ds} with" ++ alts.foldl (init := m!"") fun acc alt => acc ++ m!"\n| {alt.patterns} => {loop alt.rhs}" loop codeBlock.code /- Return true if the give code contains an exit point that satisfies `p` -/ partial def hasExitPointPred (c : Code) (p : Code → Bool) : Bool := let rec loop : Code → Bool | Code.decl _ _ k => loop k | Code.reassign _ _ k => loop k | Code.joinpoint _ _ b k => loop b || loop k | Code.seq _ k => loop k | Code.ite _ _ _ _ t e => loop t || loop e | Code.«match» _ _ _ _ alts => alts.any (loop ·.rhs) | Code.jmp _ _ _ => false | c => p c loop c def hasExitPoint (c : Code) : Bool := hasExitPointPred c fun c => true def hasReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«return» _ _ => true | _ => false def hasTerminalAction (c : Code) : Bool := hasExitPointPred c fun | Code.«action» _ => true | _ => false def hasBreakContinue (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | _ => false def hasBreakContinueReturn (c : Code) : Bool := hasExitPointPred c fun | Code.«break» _ => true | Code.«continue» _ => true | Code.«return» _ _ => true | _ => false def mkAuxDeclFor {m} [Monad m] [MonadQuotation m] (e : Syntax) (mkCont : Syntax → m Code) : m Code := withRef e <| withFreshMacroScope do let y ← `(y) let yName := y.getId let doElem ← `(doElem| let y ← $e:term) -- Add elaboration hint for producing sane error message let y ← `(ensureExpectedType% "type mismatch, result value" $y) let k ← mkCont y pure $ Code.decl #[yName] doElem k /- Convert `action _ e` instructions in `c` into `let y ← e; jmp _ jp (xs y)`. -/ partial def convertTerminalActionIntoJmp (code : Code) (jp : Name) (xs : Array Name) : MacroM Code := let rec loop : Code → MacroM Code | Code.decl xs stx k => do Code.decl xs stx (← loop k) | Code.reassign xs stx k => do Code.reassign xs stx (← loop k) | Code.joinpoint n ps b k => do Code.joinpoint n ps (← loop b) (← loop k) | Code.seq e k => do Code.seq e (← loop k) | Code.ite ref x? h c t e => do Code.ite ref x? h c (← loop t) (← loop e) | Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← loop alt.rhs) }) | Code.action e => mkAuxDeclFor e fun y => let ref := e -- We jump to `jp` with xs **and** y let jmpArgs := xs.map $ mkIdentFrom ref let jmpArgs := jmpArgs.push y pure $ Code.jmp ref jp jmpArgs | c => pure c loop code structure JPDecl where name : Name params : Array (Name × Bool) body : Code def attachJP (jpDecl : JPDecl) (k : Code) : Code := Code.joinpoint jpDecl.name jpDecl.params jpDecl.body k def attachJPs (jpDecls : Array JPDecl) (k : Code) : Code := jpDecls.foldr attachJP k def mkFreshJP (ps : Array (Name × Bool)) (body : Code) : TermElabM JPDecl := do let ps ← if ps.isEmpty then let y ← mkFreshUserName `y pure #[(y, false)] else pure ps -- Remark: the compiler frontend implemented in C++ currently detects jointpoints created by -- the "do" notation by testing the name. See hack at method `visit_let` at `lcnf.cpp` -- We will remove this hack when we re-implement the compiler frontend in Lean. let name ← mkFreshUserName `_do_jp pure { name := name, params := ps, body := body } def mkFreshJP' (xs : Array Name) (body : Code) : TermElabM JPDecl := mkFreshJP (xs.map fun x => (x, true)) body def addFreshJP (ps : Array (Name × Bool)) (body : Code) : StateRefT (Array JPDecl) TermElabM Name := do let jp ← mkFreshJP ps body modify fun (jps : Array JPDecl) => jps.push jp pure jp.name def insertVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.insert ·) rs def eraseVars (rs : NameSet) (xs : Array Name) : NameSet := xs.foldl (·.erase ·) rs def eraseOptVar (rs : NameSet) (x? : Option Name) : NameSet := match x? with | none => rs | some x => rs.insert x /- Create a new jointpoint for `c`, and jump to it with the variables `rs` -/ def mkSimpleJmp (ref : Syntax) (rs : NameSet) (c : Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let jp ← addFreshJP (xs.map fun x => (x, true)) c if xs.isEmpty then let unit ← ``(Unit.unit) return Code.jmp ref jp #[unit] else return Code.jmp ref jp (xs.map $ mkIdentFrom ref) /- Create a new joinpoint that takes `rs` and `val` as arguments. `val` must be syntax representing a pure value. The body of the joinpoint is created using `mkJPBody yFresh`, where `yFresh` is a fresh variable created by this method. -/ def mkJmp (ref : Syntax) (rs : NameSet) (val : Syntax) (mkJPBody : Syntax → MacroM Code) : StateRefT (Array JPDecl) TermElabM Code := do let xs := nameSetToArray rs let args := xs.map $ mkIdentFrom ref let args := args.push val let yFresh ← mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (yFresh, false) let jpBody ← liftMacroM $ mkJPBody (mkIdentFrom ref yFresh) let jp ← addFreshJP ps jpBody pure $ Code.jmp ref jp args /- `pullExitPointsAux rs c` auxiliary method for `pullExitPoints`, `rs` is the set of update variable in the current path. -/ partial def pullExitPointsAux : NameSet → Code → StateRefT (Array JPDecl) TermElabM Code | rs, Code.decl xs stx k => do Code.decl xs stx (← pullExitPointsAux (eraseVars rs xs) k) | rs, Code.reassign xs stx k => do Code.reassign xs stx (← pullExitPointsAux (insertVars rs xs) k) | rs, Code.joinpoint j ps b k => do Code.joinpoint j ps (← pullExitPointsAux rs b) (← pullExitPointsAux rs k) | rs, Code.seq e k => do Code.seq e (← pullExitPointsAux rs k) | rs, Code.ite ref x? o c t e => do Code.ite ref x? o c (← pullExitPointsAux (eraseOptVar rs x?) t) (← pullExitPointsAux (eraseOptVar rs x?) e) | rs, Code.«match» ref g ds t alts => do Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← pullExitPointsAux (eraseVars rs alt.vars) alt.rhs) }) | rs, c@(Code.jmp _ _ _) => pure c | rs, Code.«break» ref => mkSimpleJmp ref rs (Code.«break» ref) | rs, Code.«continue» ref => mkSimpleJmp ref rs (Code.«continue» ref) | rs, Code.«return» ref val => mkJmp ref rs val (fun y => pure $ Code.«return» ref y) | rs, Code.action e => -- We use `mkAuxDeclFor` because `e` is not pure. mkAuxDeclFor e fun y => let ref := e mkJmp ref rs y (fun yFresh => do pure $ Code.action (← ``(Pure.pure $yFresh))) /- Auxiliary operation for adding new variables to the collection of updated variables in a CodeBlock. When a new variable is not already in the collection, but is shadowed by some declaration in `c`, we create auxiliary join points to make sure we preserve the semantics of the code block. Example: suppose we have the code block `print x; let x := 10; return x`. And we want to extend it with the reassignment `x := x + 1`. We first use `pullExitPoints` to create ``` let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` and then we add the reassignment ``` x := x + 1 let jp (x!1) := return x!1; print x; let x := 10; jmp jp x ``` Note that we created a fresh variable `x!1` to avoid accidental name capture. As another example, consider ``` print x; let x := 10 y := y + 1; return x; ``` We transform it into ``` let jp (y x!1) := return x!1; print x; let x := 10 y := y + 1; jmp jp y x ``` and then we add the reassignment as in the previous example. We need to include `y` in the jump, because each exit point is implicitly returning the set of update variables. We implement the method as follows. Let `us` be `c.uvars`, then 1- for each `return _ y` in `c`, we create a join point `let j (us y!1) := return y!1` and replace the `return _ y` with `jmp us y` 2- for each `break`, we create a join point `let j (us) := break` and replace the `break` with `jmp us`. 3- Same as 2 for `continue`. -/ def pullExitPoints (c : Code) : TermElabM Code := do if hasExitPoint c then let (c, jpDecls) ← (pullExitPointsAux {} c).run #[] pure $ attachJPs jpDecls c else pure c partial def extendUpdatedVarsAux (c : Code) (ws : NameSet) : TermElabM Code := let rec update : Code → TermElabM Code | Code.joinpoint j ps b k => do Code.joinpoint j ps (← update b) (← update k) | Code.seq e k => do Code.seq e (← update k) | c@(Code.«match» ref g ds t alts) => do if alts.any fun alt => alt.vars.any fun x => ws.contains x then -- If a pattern variable is shadowing a variable in ws, we `pullExitPoints` pullExitPoints c else Code.«match» ref g ds t (← alts.mapM fun alt => do pure { alt with rhs := (← update alt.rhs) }) | Code.ite ref none o c t e => do Code.ite ref none o c (← update t) (← update e) | c@(Code.ite ref (some h) o cond t e) => do if ws.contains h then -- if the `h` at `if h:c then t else e` shadows a variable in `ws`, we `pullExitPoints` pullExitPoints c else Code.ite ref (some h) o cond (← update t) (← update e) | Code.reassign xs stx k => do Code.reassign xs stx (← update k) | c@(Code.decl xs stx k) => do if xs.any fun x => ws.contains x then -- One the declared variables is shadowing a variable in `ws` pullExitPoints c else Code.decl xs stx (← update k) | c => pure c update c /- Extend the set of updated variables. It assumes `ws` is a super set of `c.uvars`. We **cannot** simply update the field `c.uvars`, because `c` may have shadowed some variable in `ws`. See discussion at `pullExitPoints`. -/ partial def extendUpdatedVars (c : CodeBlock) (ws : NameSet) : TermElabM CodeBlock := do if ws.any fun x => !c.uvars.contains x then -- `ws` contains a variable that is not in `c.uvars`, but in `c.dvars` (i.e., it has been shadowed) pure { code := (← extendUpdatedVarsAux c.code ws), uvars := ws } else pure { c with uvars := ws } private def union (s₁ s₂ : NameSet) : NameSet := s₁.fold (·.insert ·) s₂ /- Given two code blocks `c₁` and `c₂`, make sure they have the same set of updated variables. Let `ws` the union of the updated variables in `c₁‵ and ‵c₂`. We use `extendUpdatedVars c₁ ws` and `extendUpdatedVars c₂ ws` -/ def homogenize (c₁ c₂ : CodeBlock) : TermElabM (CodeBlock × CodeBlock) := do let ws := union c₁.uvars c₂.uvars let c₁ ← extendUpdatedVars c₁ ws let c₂ ← extendUpdatedVars c₂ ws pure (c₁, c₂) /- Extending code blocks with variable declarations: `let x : t := v` and `let x : t ← v`. We remove `x` from the collection of updated varibles. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `let (x, y) := t` -/ def mkVarDeclCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : CodeBlock := { code := Code.decl xs stx c.code, uvars := eraseVars c.uvars xs } /- Extending code blocks with reassignments: `x : t := v` and `x : t ← v`. Remark: `stx` is the syntax for the declaration (e.g., `letDecl`), and `xs` are the variables declared by it. It is an array because we have let-declarations that declare multiple variables. Example: `(x, y) ← t` -/ def mkReassignCore (xs : Array Name) (stx : Syntax) (c : CodeBlock) : TermElabM CodeBlock := do let us := c.uvars let ws := insertVars us xs -- If `xs` contains a new updated variable, then we must use `extendUpdatedVars`. -- See discussion at `pullExitPoints` let code ← if xs.any fun x => !us.contains x then extendUpdatedVarsAux c.code ws else pure c.code pure { code := Code.reassign xs stx code, uvars := ws } def mkSeq (action : Syntax) (c : CodeBlock) : CodeBlock := { c with code := Code.seq action c.code } def mkTerminalAction (action : Syntax) : CodeBlock := { code := Code.action action } def mkReturn (ref : Syntax) (val : Syntax) : CodeBlock := { code := Code.«return» ref val } def mkBreak (ref : Syntax) : CodeBlock := { code := Code.«break» ref } def mkContinue (ref : Syntax) : CodeBlock := { code := Code.«continue» ref } def mkIte (ref : Syntax) (optIdent : Syntax) (cond : Syntax) (thenBranch : CodeBlock) (elseBranch : CodeBlock) : TermElabM CodeBlock := do let x? := if optIdent.isNone then none else some optIdent[0].getId let (thenBranch, elseBranch) ← homogenize thenBranch elseBranch pure { code := Code.ite ref x? optIdent cond thenBranch.code elseBranch.code, uvars := thenBranch.uvars, } private def mkUnit : MacroM Syntax := ``((⟨⟩ : PUnit)) private def mkPureUnit : MacroM Syntax := ``(pure PUnit.unit) def mkPureUnitAction : MacroM CodeBlock := do mkTerminalAction (← mkPureUnit) def mkUnless (cond : Syntax) (c : CodeBlock) : MacroM CodeBlock := do let thenBranch ← mkPureUnitAction pure { c with code := Code.ite (← getRef) none mkNullNode cond thenBranch.code c.code } def mkMatch (ref : Syntax) (genParam : Syntax) (discrs : Syntax) (optType : Syntax) (alts : Array (Alt CodeBlock)) : TermElabM CodeBlock := do -- nary version of homogenize let ws := alts.foldl (union · ·.rhs.uvars) {} let alts ← alts.mapM fun alt => do let rhs ← extendUpdatedVars alt.rhs ws pure { ref := alt.ref, vars := alt.vars, patterns := alt.patterns, rhs := rhs.code : Alt Code } pure { code := Code.«match» ref genParam discrs optType alts, uvars := ws } /- Return a code block that executes `terminal` and then `k` with the value produced by `terminal`. This method assumes `terminal` is a terminal -/ def concat (terminal : CodeBlock) (kRef : Syntax) (y? : Option Name) (k : CodeBlock) : TermElabM CodeBlock := do unless hasTerminalAction terminal.code do throwErrorAt kRef "'do' element is unreachable" let (terminal, k) ← homogenize terminal k let xs := nameSetToArray k.uvars let y ← match y? with | some y => pure y | none => mkFreshUserName `y let ps := xs.map fun x => (x, true) let ps := ps.push (y, false) let jpDecl ← mkFreshJP ps k.code let jp := jpDecl.name let terminal ← liftMacroM $ convertTerminalActionIntoJmp terminal.code jp xs pure { code := attachJP jpDecl terminal, uvars := k.uvars } def getLetIdDeclVar (letIdDecl : Syntax) : Name := letIdDecl[0].getId -- support both regular and syntax match def getPatternVarsEx (pattern : Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternVars pattern <|> Array.map Syntax.getId <$> Quotation.getPatternVars pattern def getPatternsVarsEx (patterns : Array Syntax) : TermElabM (Array Name) := getPatternVarNames <$> getPatternsVars patterns <|> Array.map Syntax.getId <$> Quotation.getPatternsVars patterns def getLetPatDeclVars (letPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := letPatDecl[0] getPatternVarsEx pattern def getLetEqnsDeclVar (letEqnsDecl : Syntax) : Name := letEqnsDecl[0].getId def getLetDeclVars (letDecl : Syntax) : TermElabM (Array Name) := do let arg := letDecl[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == ``Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else if arg.getKind == ``Lean.Parser.Term.letEqnsDecl then pure #[getLetEqnsDeclVar arg] else throwError "unexpected kind of let declaration" def getDoLetVars (doLet : Syntax) : TermElabM (Array Name) := -- leading_parser "let " >> optional "mut " >> letDecl getLetDeclVars doLet[2] def getDoHaveVar (doHave : Syntax) : Name := /- `leading_parser "have " >> Term.haveDecl` where ``` haveDecl := leading_parser optIdent >> termParser >> (haveAssign <|> fromTerm <|> byTactic) optIdent := optional (try (ident >> " : ")) ``` -/ let optIdent := doHave[1][0] if optIdent.isNone then `this else optIdent[0].getId def getDoLetRecVars (doLetRec : Syntax) : TermElabM (Array Name) := do -- letRecDecls is an array of `(group (optional attributes >> letDecl))` let letRecDecls := doLetRec[1][0].getSepArgs let letDecls := letRecDecls.map fun p => p[2] let mut allVars := #[] for letDecl in letDecls do let vars ← getLetDeclVars letDecl allVars := allVars ++ vars pure allVars -- ident >> optType >> leftArrow >> termParser def getDoIdDeclVar (doIdDecl : Syntax) : Name := doIdDecl[0].getId -- termParser >> leftArrow >> termParser >> optional (" | " >> termParser) def getDoPatDeclVars (doPatDecl : Syntax) : TermElabM (Array Name) := do let pattern := doPatDecl[0] getPatternVarsEx pattern -- leading_parser "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) def getDoLetArrowVars (doLetArrow : Syntax) : TermElabM (Array Name) := do let decl := doLetArrow[2] if decl.getKind == ``Lean.Parser.Term.doIdDecl then pure #[getDoIdDeclVar decl] else if decl.getKind == ``Lean.Parser.Term.doPatDecl then getDoPatDeclVars decl else throwError "unexpected kind of 'do' declaration" def getDoReassignVars (doReassign : Syntax) : TermElabM (Array Name) := do let arg := doReassign[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then pure #[getLetIdDeclVar arg] else if arg.getKind == ``Lean.Parser.Term.letPatDecl then getLetPatDeclVars arg else throwError "unexpected kind of reassignment" def mkDoSeq (doElems : Array Syntax) : Syntax := mkNode `Lean.Parser.Term.doSeqIndent #[mkNullNode $ doElems.map fun doElem => mkNullNode #[doElem, mkNullNode]] def mkSingletonDoSeq (doElem : Syntax) : Syntax := mkDoSeq #[doElem] /- If the given syntax is a `doIf`, return an equivalente `doIf` that has an `else` but no `else if`s or `if let`s. -/ private def expandDoIf? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(doElem|if $p:doIfProp then $t else $e) => pure none | `(doElem|if%$i $cond:doIfCond then $t $[else if%$is $conds:doIfCond then $ts]* $[else $e?]?) => withRef stx do let mut e := e?.getD (← `(doSeq|pure PUnit.unit)) let mut eIsSeq := true for (i, cond, t) in Array.zip (is.reverse.push i) (Array.zip (conds.reverse.push cond) (ts.reverse.push t)) do e ← if eIsSeq then e else `(doSeq|$e:doElem) e ← withRef cond <| match cond with | `(doIfCond|let $pat := $d) => `(doElem| match%$i $d:term with | $pat:term => $t | _ => $e) | `(doIfCond|let $pat ← $d) => `(doElem| match%$i ← $d with | $pat:term => $t | _ => $e) | `(doIfCond|$cond:doIfProp) => `(doElem| if%$i $cond:doIfProp then $t else $e) | _ => `(doElem| if%$i $(Syntax.missing) then $t else $e) eIsSeq := false return some e | _ => pure none structure DoIfView where ref : Syntax optIdent : Syntax cond : Syntax thenBranch : Syntax elseBranch : Syntax /- This method assumes `expandDoIf?` is not applicable. -/ private def mkDoIfView (doIf : Syntax) : MacroM DoIfView := do pure { ref := doIf, optIdent := doIf[1][0], cond := doIf[1][1], thenBranch := doIf[3], elseBranch := doIf[5][1] } /- We use `MProd` instead of `Prod` to group values when expanding the `do` notation. `MProd` is a universe monomorphic product. The motivation is to generate simpler universe constraints in code that was not written by the user. Note that we are not restricting the macro power since the `Bind.bind` combinator already forces values computed by monadic actions to be in the same universe. -/ private def mkTuple (elems : Array Syntax) : MacroM Syntax := do if elems.size == 0 then mkUnit else if elems.size == 1 then pure elems[0] else (elems.extract 0 (elems.size - 1)).foldrM (fun elem tuple => ``(MProd.mk $elem $tuple)) (elems.back) /- Return `some action` if `doElem` is a `doExpr <action>`-/ def isDoExpr? (doElem : Syntax) : Option Syntax := if doElem.getKind == ``Lean.Parser.Term.doExpr then some doElem[0] else none /-- Given `uvars := #[a_1, ..., a_n, a_{n+1}]` construct term ``` let a_1 := x.1 let x := x.2 let a_2 := x.1 let x := x.2 ... let a_n := x.1 let a_{n+1} := x.2 body ``` Special cases - `uvars := #[]` => `body` - `uvars := #[a]` => `let a := x; body` We use this method when expanding the `for-in` notation. -/ private def destructTuple (uvars : Array Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do if uvars.size == 0 then return body else if uvars.size == 1 then `(let $(← mkIdentFromRef uvars[0]):ident := $x; $body) else destruct uvars.toList x body where destruct (as : List Name) (x : Syntax) (body : Syntax) : MacroM Syntax := do match as with | [a, b] => `(let $(← mkIdentFromRef a):ident := $x.1; let $(← mkIdentFromRef b):ident := $x.2; $body) | a :: as => withFreshMacroScope do let rest ← destruct as (← `(x)) body `(let $(← mkIdentFromRef a):ident := $x.1; let x := $x.2; $rest) | _ => unreachable! /- The procedure `ToTerm.run` converts a `CodeBlock` into a `Syntax` term. We use this method to convert 1- The `CodeBlock` for a root `do ...` term into a `Syntax` term. This kind of `CodeBlock` never contains `break` nor `continue`. Moreover, the collection of updated variables is not packed into the result. Thus, we have two kinds of exit points - `Code.action e` which is converted into `e` - `Code.return _ e` which is converted into `pure e` We use `Kind.regular` for this case. 2- The `CodeBlock` for `b` at `for x in xs do b`. In this case, we need to generate a `Syntax` term representing a function for the `xs.forIn` combinator. a) If `b` contain a `Code.return _ a` exit point. The generated `Syntax` term has type `m (ForInStep (Option α × σ))`, where `a : α`, and the `σ` is the type of the tuple of variables reassigned by `b`. We use `Kind.forInWithReturn` for this case b) If `b` does not contain a `Code.return _ a` exit point. Then, the generated `Syntax` term has type `m (ForInStep σ)`. We use `Kind.forIn` for this case. 3- The `CodeBlock` `c` for a `do` sequence nested in a monadic combinator (e.g., `MonadExcept.tryCatch`). The generated `Syntax` term for `c` must inform whether `c` "exited" using `Code.action`, `Code.return`, `Code.break` or `Code.continue`. We use the auxiliary types `DoResult`s for storing this information. For example, the auxiliary type `DoResultPBC α σ` is used for a code block that exits with `Code.action`, **and** `Code.break`/`Code.continue`, `α` is the type of values produced by the exit `action`, and `σ` is the type of the tuple of reassigned variables. The type `DoResult α β σ` is usedf for code blocks that exit with `Code.action`, `Code.return`, **and** `Code.break`/`Code.continue`, `β` is the type of the returned values. We don't use `DoResult α β σ` for all cases because: a) The elaborator would not be able to infer all type parameters without extra annotations. For example, if the code block does not contain `Code.return _ _`, the elaborator will not be able to infer `β`. b) We need to pattern match on the result produced by the combinator (e.g., `MonadExcept.tryCatch`), but we don't want to consider "unreachable" cases. We do not distinguish between cases that contain `break`, but not `continue`, and vice versa. When listing all cases, we use `a` to indicate the code block contains `Code.action _`, `r` for `Code.return _ _`, and `b/c` for a code block that contains `Code.break _` or `Code.continue _`. - `a`: `Kind.regular`, type `m (α × σ)` - `r`: `Kind.regular`, type `m (α × σ)` Note that the code that pattern matches on the result will behave differently in this case. It produces `return a` for this case, and `pure a` for the previous one. - `b/c`: `Kind.nestedBC`, type `m (DoResultBC σ)` - `a` and `r`: `Kind.nestedPR`, type `m (DoResultPR α β σ)` - `a` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` - `r` and `bc`: `Kind.nestedSBC`, type `m (DoResultSBC α σ)` Again the code that pattern matches on the result will behave differently in this case and the previous one. It produces `return a` for the constructor `DoResultSPR.pureReturn a u` for this case, and `pure a` for the previous case. - `a`, `r`, `b/c`: `Kind.nestedPRBC`, type type `m (DoResultPRBC α β σ)` Here is the recipe for adding new combinators with nested `do`s. Example: suppose we want to support `repeat doSeq`. Assuming we have `repeat : m α → m α` 1- Convert `doSeq` into `codeBlock : CodeBlock` 2- Create term `term` using `mkNestedTerm code m uvars a r bc` where `code` is `codeBlock.code`, `uvars` is an array containing `codeBlock.uvars`, `m` is a `Syntax` representing the Monad, and `a` is true if `code` contains `Code.action _`, `r` is true if `code` contains `Code.return _ _`, `bc` is true if `code` contains `Code.break _` or `Code.continue _`. Remark: for combinators such as `repeat` that take a single `doSeq`, all arguments, but `m`, are extracted from `codeBlock`. 3- Create the term `repeat $term` 4- and then, convert it into a `doSeq` using `matchNestedTermResult ref (repeat $term) uvsar a r bc` -/ namespace ToTerm inductive Kind where | regular | forIn | forInWithReturn | nestedBC | nestedPR | nestedSBC | nestedPRBC instance : Inhabited Kind := ⟨Kind.regular⟩ def Kind.isRegular : Kind → Bool | Kind.regular => true | _ => false structure Context where m : Syntax -- Syntax to reference the monad associated with the do notation. uvars : Array Name kind : Kind abbrev M := ReaderT Context MacroM def mkUVarTuple : M Syntax := do let ctx ← read let uvarIdents ← ctx.uvars.mapM mkIdentFromRef mkTuple uvarIdents def returnToTerm (val : Syntax) : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then ``(Pure.pure $val) else ``(Pure.pure (MProd.mk $val $u)) | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk (some $val) $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Pure.pure (DoResultPR.«return» $val $u)) | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«pureReturn» $val $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«return» $val $u)) def continueToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«continue» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«continue» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«continue» $u)) def breakToTerm : M Syntax := do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => unreachable! | Kind.forIn => ``(Pure.pure (ForInStep.done $u)) | Kind.forInWithReturn => ``(Pure.pure (ForInStep.done (MProd.mk none $u))) | Kind.nestedBC => ``(Pure.pure (DoResultBC.«break» $u)) | Kind.nestedPR => unreachable! | Kind.nestedSBC => ``(Pure.pure (DoResultSBC.«break» $u)) | Kind.nestedPRBC => ``(Pure.pure (DoResultPRBC.«break» $u)) def actionTerminalToTerm (action : Syntax) : M Syntax := withRef action <| withFreshMacroScope do let ctx ← read let u ← mkUVarTuple match ctx.kind with | Kind.regular => if ctx.uvars.isEmpty then pure action else ``(Bind.bind $action fun y => Pure.pure (MProd.mk y $u)) | Kind.forIn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield $u)) | Kind.forInWithReturn => ``(Bind.bind $action fun (_ : PUnit) => Pure.pure (ForInStep.yield (MProd.mk none $u))) | Kind.nestedBC => unreachable! | Kind.nestedPR => ``(Bind.bind $action fun y => (Pure.pure (DoResultPR.«pure» y $u))) | Kind.nestedSBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultSBC.«pureReturn» y $u))) | Kind.nestedPRBC => ``(Bind.bind $action fun y => (Pure.pure (DoResultPRBC.«pure» y $u))) def seqToTerm (action : Syntax) (k : Syntax) : M Syntax := withRef action <| withFreshMacroScope do if action.getKind == ``Lean.Parser.Term.doDbgTrace then let msg := action[1] `(dbg_trace $msg; $k) else if action.getKind == ``Lean.Parser.Term.doAssert then let cond := action[1] `(assert! $cond; $k) else let action ← withRef action ``(($action : $((←read).m) PUnit)) ``(Bind.bind $action (fun (_ : PUnit) => $k)) def declToTerm (decl : Syntax) (k : Syntax) : M Syntax := withRef decl <| withFreshMacroScope do let kind := decl.getKind if kind == ``Lean.Parser.Term.doLet then let letDecl := decl[2] `(let $letDecl:letDecl; $k) else if kind == ``Lean.Parser.Term.doLetRec then let letRecToken := decl[0] let letRecDecls := decl[1] pure $ mkNode ``Lean.Parser.Term.letrec #[letRecToken, letRecDecls, mkNullNode, k] else if kind == ``Lean.Parser.Term.doLetArrow then let arg := decl[2] let ref := arg if arg.getKind == ``Lean.Parser.Term.doIdDecl then let id := arg[0] let type := expandOptType id arg[1] let doElem := arg[3] -- `doElem` must be a `doExpr action`. See `doLetArrowToCode` match isDoExpr? doElem with | some action => let action ← withRef action `(($action : $((← read).m) $type)) ``(Bind.bind $action (fun ($id:ident : $type) => $k)) | none => Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" else if kind == ``Lean.Parser.Term.doHave then -- The `have` term is of the form `"have " >> haveDecl >> optSemicolon termParser` let args := decl.getArgs let args := args ++ #[mkNullNode /- optional ';' -/, k] pure $ mkNode `Lean.Parser.Term.«have» args else Macro.throwErrorAt decl "unexpected kind of 'do' declaration" def reassignToTerm (reassign : Syntax) (k : Syntax) : MacroM Syntax := withRef reassign <| withFreshMacroScope do let kind := reassign.getKind if kind == ``Lean.Parser.Term.doReassign then -- doReassign := leading_parser (letIdDecl <|> letPatDecl) let arg := reassign[0] if arg.getKind == ``Lean.Parser.Term.letIdDecl then -- letIdDecl := leading_parser ident >> many (ppSpace >> bracketedBinder) >> optType >> " := " >> termParser let x := arg[0] let val := arg[4] let newVal ← `(ensureTypeOf% $x $(quote "invalid reassignment, value") $val) let arg := arg.setArg 4 newVal let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- TODO: ensure the types did not change let letDecl := mkNode `Lean.Parser.Term.letDecl #[arg] `(let $letDecl:letDecl; $k) else -- Note that `doReassignArrow` is expanded by `doReassignArrowToCode Macro.throwErrorAt reassign "unexpected kind of 'do' reassignment" def mkIte (optIdent : Syntax) (cond : Syntax) (thenBranch : Syntax) (elseBranch : Syntax) : MacroM Syntax := do if optIdent.isNone then ``(ite $cond $thenBranch $elseBranch) else let h := optIdent[0] ``(dite $cond (fun $h => $thenBranch) (fun $h => $elseBranch)) def mkJoinPoint (j : Name) (ps : Array (Name × Bool)) (body : Syntax) (k : Syntax) : M Syntax := withRef body <| withFreshMacroScope do let pTypes ← ps.mapM fun ⟨id, useTypeOf⟩ => do if useTypeOf then `(typeOf% $(← mkIdentFromRef id)) else `(_) let ps ← ps.mapM fun ⟨id, useTypeOf⟩ => mkIdentFromRef id /- We use `let_delayed` instead of `let` for joinpoints to make sure `$k` is elaborated before `$body`. By elaborating `$k` first, we "learn" more about `$body`'s type. For example, consider the following example `do` expression ``` def f (x : Nat) : IO Unit := do if x > 0 then IO.println "x is not zero" -- Error is here IO.mkRef true ``` it is expanded into ``` def f (x : Nat) : IO Unit := do let jp (u : Unit) : IO _ := IO.mkRef true; if x > 0 then IO.println "not zero" jp () else jp () ``` If we use the regular `let` instead of `let_delayed`, the joinpoint `jp` will be elaborated and its type will be inferred to be `Unit → IO (IO.Ref Bool)`. Then, we get a typing error at `jp ()`. By using `let_delayed`, we first elaborate `if x > 0 ...` and learn that `jp` has type `Unit → IO Unit`. Then, we get the expected type mismatch error at `IO.mkRef true`. -/ `(let_delayed $(← mkIdentFromRef j):ident $[($ps : $pTypes)]* : $((← read).m) _ := $body; $k) def mkJmp (ref : Syntax) (j : Name) (args : Array Syntax) : Syntax := Syntax.mkApp (mkIdentFrom ref j) args partial def toTerm : Code → M Syntax | Code.«return» ref val => withRef ref <| returnToTerm val | Code.«continue» ref => withRef ref continueToTerm | Code.«break» ref => withRef ref breakToTerm | Code.action e => actionTerminalToTerm e | Code.joinpoint j ps b k => do mkJoinPoint j ps (← toTerm b) (← toTerm k) | Code.jmp ref j args => pure $ mkJmp ref j args | Code.decl _ stx k => do declToTerm stx (← toTerm k) | Code.reassign _ stx k => do reassignToTerm stx (← toTerm k) | Code.seq stx k => do seqToTerm stx (← toTerm k) | Code.ite ref _ o c t e => withRef ref <| do mkIte o c (← toTerm t) (← toTerm e) | Code.«match» ref genParam discrs optType alts => do let mut termAlts := #[] for alt in alts do let rhs ← toTerm alt.rhs let termAlt := mkNode `Lean.Parser.Term.matchAlt #[mkAtomFrom alt.ref "|", alt.patterns, mkAtomFrom alt.ref "=>", rhs] termAlts := termAlts.push termAlt let termMatchAlts := mkNode `Lean.Parser.Term.matchAlts #[mkNullNode termAlts] pure $ mkNode `Lean.Parser.Term.«match» #[mkAtomFrom ref "match", genParam, discrs, optType, mkAtomFrom ref "with", termMatchAlts] def run (code : Code) (m : Syntax) (uvars : Array Name := #[]) (kind := Kind.regular) : MacroM Syntax := do let term ← toTerm code { m := m, kind := kind, uvars := uvars } pure term /- Given - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point generate Kind. See comment at the beginning of the `ToTerm` namespace. -/ def mkNestedKind (a r bc : Bool) : Kind := match a, r, bc with | true, false, false => Kind.regular | false, true, false => Kind.regular | false, false, true => Kind.nestedBC | true, true, false => Kind.nestedPR | true, false, true => Kind.nestedSBC | false, true, true => Kind.nestedSBC | true, true, true => Kind.nestedPRBC | false, false, false => unreachable! def mkNestedTerm (code : Code) (m : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM Syntax := do ToTerm.run code m uvars (mkNestedKind a r bc) /- Given a term `term` produced by `ToTerm.run`, pattern match on its result. See comment at the beginning of the `ToTerm` namespace. - `a` is true if the code block has a `Code.action _` exit point - `r` is true if the code block has a `Code.return _ _` exit point - `bc` is true if the code block has a `Code.break _` or `Code.continue _` exit point The result is a sequence of `doElem` -/ def matchNestedTermResult (term : Syntax) (uvars : Array Name) (a r bc : Bool) : MacroM (List Syntax) := do let toDoElems (auxDo : Syntax) : List Syntax := getDoSeqElems (getDoSeq auxDo) let u ← mkTuple (← uvars.mapM mkIdentFromRef) match a, r, bc with | true, false, false => if uvars.isEmpty then toDoElems (← `(do $term:term)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; pure r.1)) | false, true, false => if uvars.isEmpty then toDoElems (← `(do let r ← $term:term; return r)) else toDoElems (← `(do let r ← $term:term; $u:term := r.2; return r.1)) | false, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultBC.«break» u => $u:term := u; break | DoResultBC.«continue» u => $u:term := u; continue) | true, true, false => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPR.«pure» a u => $u:term := u; pure a | DoResultPR.«return» b u => $u:term := u; return b) | true, false, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; pure a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | false, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultSBC.«pureReturn» a u => $u:term := u; return a | DoResultSBC.«break» u => $u:term := u; break | DoResultSBC.«continue» u => $u:term := u; continue) | true, true, true => toDoElems <$> `(do let r ← $term:term; match r with | DoResultPRBC.«pure» a u => $u:term := u; pure a | DoResultPRBC.«return» a u => $u:term := u; return a | DoResultPRBC.«break» u => $u:term := u; break | DoResultPRBC.«continue» u => $u:term := u; continue) | false, false, false => unreachable! end ToTerm def isMutableLet (doElem : Syntax) : Bool := let kind := doElem.getKind (kind == `Lean.Parser.Term.doLetArrow || kind == `Lean.Parser.Term.doLet) && !doElem[1].isNone namespace ToCodeBlock structure Context where ref : Syntax m : Syntax -- Syntax representing the monad associated with the do notation. mutableVars : NameSet := {} insideFor : Bool := false abbrev M := ReaderT Context TermElabM def withNewMutableVars {α} (newVars : Array Name) (mutable : Bool) (x : M α) : M α := withReader (fun ctx => if mutable then { ctx with mutableVars := insertVars ctx.mutableVars newVars } else ctx) x def checkReassignable (xs : Array Name) : M Unit := do let throwInvalidReassignment (x : Name) : M Unit := throwError "'{x.simpMacroScopes}' cannot be reassigned" let ctx ← read for x in xs do unless ctx.mutableVars.contains x do throwInvalidReassignment x def checkNotShadowingMutable (xs : Array Name) : M Unit := do let throwInvalidShadowing (x : Name) : M Unit := throwError "mutable variable '{x.simpMacroScopes}' cannot be shadowed" let ctx ← read for x in xs do if ctx.mutableVars.contains x then throwInvalidShadowing x def withFor {α} (x : M α) : M α := withReader (fun ctx => { ctx with insideFor := true }) x structure ToForInTermResult where uvars : Array Name term : Syntax def mkForInBody (x : Syntax) (forInBody : CodeBlock) : M ToForInTermResult := do let ctx ← read let uvars := forInBody.uvars let uvars := nameSetToArray uvars let term ← liftMacroM $ ToTerm.run forInBody.code ctx.m uvars (if hasReturn forInBody.code then ToTerm.Kind.forInWithReturn else ToTerm.Kind.forIn) pure ⟨uvars, term⟩ def ensureInsideFor : M Unit := unless (← read).insideFor do throwError "invalid 'do' element, it must be inside 'for'" def ensureEOS (doElems : List Syntax) : M Unit := unless doElems.isEmpty do throwError "must be last element in a 'do' sequence" private partial def expandLiftMethodAux (inQuot : Bool) (inBinder : Bool) : Syntax → StateT (List Syntax) M Syntax | stx@(Syntax.node k args) => if liftMethodDelimiter k then return stx else if k == ``Lean.Parser.Term.liftMethod && !inQuot then withFreshMacroScope do if inBinder then throwErrorAt stx "cannot lift `(<- ...)` over a binder, this error usually happens when you are trying to lift a method nested in a `fun`, `let`, or `match`-alternative, and it can often be fixed by adding a missing `do`" let term := args[1] let term ← expandLiftMethodAux inQuot inBinder term let auxDoElem ← `(doElem| let a ← $term:term) modify fun s => s ++ [auxDoElem] `(a) else do let inAntiquot := stx.isAntiquot && !stx.isEscapedAntiquot let inBinder := inBinder || (!inQuot && liftMethodForbiddenBinder stx) let args ← args.mapM (expandLiftMethodAux (inQuot && !inAntiquot || stx.isQuot) inBinder) return Syntax.node k args | stx => pure stx def expandLiftMethod (doElem : Syntax) : M (List Syntax × Syntax) := do if !hasLiftMethod doElem then pure ([], doElem) else let (doElem, doElemsNew) ← (expandLiftMethodAux false false doElem).run [] pure (doElemsNew, doElem) def checkLetArrowRHS (doElem : Syntax) : M Unit := do let kind := doElem.getKind if kind == ``Lean.Parser.Term.doLetArrow || kind == ``Lean.Parser.Term.doLet || kind == ``Lean.Parser.Term.doLetRec || kind == ``Lean.Parser.Term.doHave || kind == ``Lean.Parser.Term.doReassign || kind == ``Lean.Parser.Term.doReassignArrow then throwErrorAt doElem "invalid kind of value '{kind}' in an assignment" /- Generate `CodeBlock` for `doReturn` which is of the form ``` "return " >> optional termParser ``` `doElems` is only used for sanity checking. -/ def doReturnToCode (doReturn : Syntax) (doElems: List Syntax) : M CodeBlock := withRef doReturn do ensureEOS doElems let argOpt := doReturn[1] let arg ← if argOpt.isNone then liftMacroM mkUnit else pure argOpt[0] return mkReturn (← getRef) arg structure Catch where x : Syntax optType : Syntax codeBlock : CodeBlock def getTryCatchUpdatedVars (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) : NameSet := let ws := tryCode.uvars let ws := catches.foldl (fun ws alt => union alt.codeBlock.uvars ws) ws let ws := match finallyCode? with | none => ws | some c => union c.uvars ws ws def tryCatchPred (tryCode : CodeBlock) (catches : Array Catch) (finallyCode? : Option CodeBlock) (p : Code → Bool) : Bool := p tryCode.code || catches.any (fun «catch» => p «catch».codeBlock.code) || match finallyCode? with | none => false | some finallyCode => p finallyCode.code mutual /- "Concatenate" `c` with `doSeqToCode doElems` -/ partial def concatWith (c : CodeBlock) (doElems : List Syntax) : M CodeBlock := match doElems with | [] => pure c | nextDoElem :: _ => do let k ← doSeqToCode doElems let ref := nextDoElem concat c ref none k /- Generate `CodeBlock` for `doLetArrow; doElems` `doLetArrow` is of the form ``` "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) ``` where ``` def doIdDecl := leading_parser ident >> optType >> leftArrow >> doElemParser def doPatDecl := leading_parser termParser >> leftArrow >> doElemParser >> optional (" | " >> doElemParser) ``` -/ partial def doLetArrowToCode (doLetArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doLetArrow let decl := doLetArrow[2] if decl.getKind == ``Lean.Parser.Term.doIdDecl then let y := decl[0].getId checkNotShadowingMutable #[y] let doElem := decl[3] let k ← withNewMutableVars #[y] (isMutableLet doLetArrow) (doSeqToCode doElems) match isDoExpr? doElem with | some action => pure $ mkVarDeclCore #[y] doLetArrow k | none => checkLetArrowRHS doElem let c ← doSeqToCode [doElem] match doElems with | [] => pure c | kRef::_ => concat c kRef y k else if decl.getKind == ``Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← if isMutableLet doLetArrow then `(do let discr ← $doElem; let mut $pattern:term := discr) else `(do let discr ← $doElem; let $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if isMutableLet doLetArrow then throwError "'mut' is currently not supported in let-decls with 'else' case" let contSeq := mkDoSeq doElems.toArray let elseSeq := mkSingletonDoSeq optElse[1] let auxDo ← `(do let discr ← $doElem; match discr with | $pattern:term => $contSeq | _ => $elseSeq) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else throwError "unexpected kind of 'do' declaration" /- Generate `CodeBlock` for `doReassignArrow; doElems` `doReassignArrow` is of the form ``` (doIdDecl <|> doPatDecl) ``` -/ partial def doReassignArrowToCode (doReassignArrow : Syntax) (doElems : List Syntax) : M CodeBlock := do let ref := doReassignArrow let decl := doReassignArrow[0] if decl.getKind == ``Lean.Parser.Term.doIdDecl then let doElem := decl[3] let y := decl[0] let auxDo ← `(do let r ← $doElem; $y:ident := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else if decl.getKind == ``Lean.Parser.Term.doPatDecl then let pattern := decl[0] let doElem := decl[2] let optElse := decl[3] if optElse.isNone then withFreshMacroScope do let auxDo ← `(do let discr ← $doElem; $pattern:term := discr) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems else throwError "reassignment with `|` (i.e., \"else clause\") is not currently supported" else throwError "unexpected kind of 'do' reassignment" /- Generate `CodeBlock` for `doIf; doElems` `doIf` is of the form ``` "if " >> optIdent >> termParser >> " then " >> doSeq >> many (group (try (group (" else " >> " if ")) >> optIdent >> termParser >> " then " >> doSeq)) >> optional (" else " >> doSeq) ``` -/ partial def doIfToCode (doIf : Syntax) (doElems : List Syntax) : M CodeBlock := do let view ← liftMacroM $ mkDoIfView doIf let thenBranch ← doSeqToCode (getDoSeqElems view.thenBranch) let elseBranch ← doSeqToCode (getDoSeqElems view.elseBranch) let ite ← mkIte view.ref view.optIdent view.cond thenBranch elseBranch concatWith ite doElems /- Generate `CodeBlock` for `doUnless; doElems` `doUnless` is of the form ``` "unless " >> termParser >> "do " >> doSeq ``` -/ partial def doUnlessToCode (doUnless : Syntax) (doElems : List Syntax) : M CodeBlock := withRef doUnless do let ref := doUnless let cond := doUnless[1] let doSeq := doUnless[3] let body ← doSeqToCode (getDoSeqElems doSeq) let unlessCode ← liftMacroM <| mkUnless cond body concatWith unlessCode doElems /- Generate `CodeBlock` for `doFor; doElems` `doFor` is of the form ``` def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq ``` -/ partial def doForToCode (doFor : Syntax) (doElems : List Syntax) : M CodeBlock := do let doForDecls := doFor[1].getSepArgs if doForDecls.size > 1 then /- Expand ``` for x in xs, y in ys do body ``` into ``` let s := toStream ys for x in xs do match Stream.next? s with | none => break | some (y, s') => s := s' body ``` -/ -- Extract second element let doForDecl := doForDecls[1] let y := doForDecl[0] let ys := doForDecl[2] let doForDecls := doForDecls.eraseIdx 1 let body := doFor[3] withFreshMacroScope do let toStreamFn ← withRef ys ``(toStream) let auxDo ← `(do let mut s := $toStreamFn:ident $ys for $doForDecls:doForDecl,* do match Stream.next? s with | none => break | some ($y, s') => s := s' do $body) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else withRef doFor do let x := doForDecls[0][0] withRef x <| checkNotShadowingMutable (← getPatternVarsEx x) let xs := doForDecls[0][2] let forElems := getDoSeqElems doFor[3] let forInBodyCodeBlock ← withFor (doSeqToCode forElems) let ⟨uvars, forInBody⟩ ← mkForInBody x forInBodyCodeBlock let uvarsTuple ← liftMacroM do mkTuple (← uvars.mapM mkIdentFromRef) if hasReturn forInBodyCodeBlock.code then let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) (MProd.mk none $uvarsTuple) fun $x r => let r := r.2; $forInBody) let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r.2; match r.1 with | none => Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit) | some a => return ensureExpectedType% "type mismatch, 'for'" a) doSeqToCode (getDoSeqElems (getDoSeq auxDo) ++ doElems) else let forInBody ← liftMacroM <| destructTuple uvars (← `(r)) forInBody let forInTerm ← `(forIn% $(xs) $uvarsTuple fun $x r => $forInBody) if doElems.isEmpty then let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r; Pure.pure (ensureExpectedType% "type mismatch, 'for'" PUnit.unit)) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) else let auxDo ← `(do let r ← $forInTerm:term; $uvarsTuple:term := r) doSeqToCode <| getDoSeqElems (getDoSeq auxDo) ++ doElems /-- Generate `CodeBlock` for `doMatch; doElems` -/ partial def doMatchToCode (doMatch : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doMatch let genParam := doMatch[1] let discrs := doMatch[2] let optType := doMatch[3] let matchAlts := doMatch[5][0].getArgs -- Array of `doMatchAlt` let alts ← matchAlts.mapM fun matchAlt => do let patterns := matchAlt[1] let vars ← getPatternsVarsEx patterns.getSepArgs withRef patterns <| checkNotShadowingMutable vars let rhs := matchAlt[3] let rhs ← doSeqToCode (getDoSeqElems rhs) pure { ref := matchAlt, vars := vars, patterns := patterns, rhs := rhs : Alt CodeBlock } let matchCode ← mkMatch ref genParam discrs optType alts concatWith matchCode doElems /-- Generate `CodeBlock` for `doTry; doElems` ``` def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally def doCatch := leading_parser "catch " >> binderIdent >> optional (":" >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq ``` -/ partial def doTryToCode (doTry : Syntax) (doElems: List Syntax) : M CodeBlock := do let ref := doTry let tryCode ← doSeqToCode (getDoSeqElems doTry[1]) let optFinally := doTry[3] let catches ← doTry[2].getArgs.mapM fun catchStx => do if catchStx.getKind == ``Lean.Parser.Term.doCatch then let x := catchStx[1] if x.isIdent then withRef x <| checkNotShadowingMutable #[x.getId] let optType := catchStx[2] let c ← doSeqToCode (getDoSeqElems catchStx[4]) pure { x := x, optType := optType, codeBlock := c : Catch } else if catchStx.getKind == ``Lean.Parser.Term.doCatchMatch then let matchAlts := catchStx[1] let x ← `(ex) let auxDo ← `(do match ex with $matchAlts) let c ← doSeqToCode (getDoSeqElems (getDoSeq auxDo)) pure { x := x, codeBlock := c, optType := mkNullNode : Catch } else throwError "unexpected kind of 'catch'" let finallyCode? ← if optFinally.isNone then pure none else some <$> doSeqToCode (getDoSeqElems optFinally[0][1]) if catches.isEmpty && finallyCode?.isNone then throwError "invalid 'try', it must have a 'catch' or 'finally'" let ctx ← read let ws := getTryCatchUpdatedVars tryCode catches finallyCode? let uvars := nameSetToArray ws let a := tryCatchPred tryCode catches finallyCode? hasTerminalAction let r := tryCatchPred tryCode catches finallyCode? hasReturn let bc := tryCatchPred tryCode catches finallyCode? hasBreakContinue let toTerm (codeBlock : CodeBlock) : M Syntax := do let codeBlock ← liftM $ extendUpdatedVars codeBlock ws liftMacroM $ ToTerm.mkNestedTerm codeBlock.code ctx.m uvars a r bc let term ← toTerm tryCode let term ← catches.foldlM (fun term «catch» => do let catchTerm ← toTerm «catch».codeBlock if catch.optType.isNone then ``(MonadExcept.tryCatch $term (fun $(«catch».x):ident => $catchTerm)) else let type := «catch».optType[1] ``(tryCatchThe $type $term (fun $(«catch».x):ident => $catchTerm))) term let term ← match finallyCode? with | none => pure term | some finallyCode => withRef optFinally do unless finallyCode.uvars.isEmpty do throwError "'finally' currently does not support reassignments" if hasBreakContinueReturn finallyCode.code then throwError "'finally' currently does 'return', 'break', nor 'continue'" let finallyTerm ← liftMacroM <| ToTerm.run finallyCode.code ctx.m {} ToTerm.Kind.regular ``(tryFinally $term $finallyTerm) let doElemsNew ← liftMacroM <| ToTerm.matchNestedTermResult term uvars a r bc doSeqToCode (doElemsNew ++ doElems) partial def doSeqToCode : List Syntax → M CodeBlock | [] => do liftMacroM mkPureUnitAction | doElem::doElems => withIncRecDepth <| withRef doElem do checkMaxHeartbeats "'do'-expander" match (← liftMacroM <| expandMacro? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => match (← liftMacroM <| expandDoIf? doElem) with | some doElem => doSeqToCode (doElem::doElems) | none => let (liftedDoElems, doElem) ← expandLiftMethod doElem if !liftedDoElems.isEmpty then doSeqToCode (liftedDoElems ++ [doElem] ++ doElems) else let ref := doElem let concatWithRest (c : CodeBlock) : M CodeBlock := concatWith c doElems let k := doElem.getKind if k == ``Lean.Parser.Term.doLet then let vars ← getDoLetVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> withNewMutableVars vars (isMutableLet doElem) (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doHave then let var := getDoHaveVar doElem checkNotShadowingMutable #[var] mkVarDeclCore #[var] doElem <$> (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doLetRec then let vars ← getDoLetRecVars doElem checkNotShadowingMutable vars mkVarDeclCore vars doElem <$> (doSeqToCode doElems) else if k == ``Lean.Parser.Term.doReassign then let vars ← getDoReassignVars doElem checkReassignable vars let k ← doSeqToCode doElems mkReassignCore vars doElem k else if k == ``Lean.Parser.Term.doLetArrow then doLetArrowToCode doElem doElems else if k == ``Lean.Parser.Term.doReassignArrow then doReassignArrowToCode doElem doElems else if k == ``Lean.Parser.Term.doIf then doIfToCode doElem doElems else if k == ``Lean.Parser.Term.doUnless then doUnlessToCode doElem doElems else if k == ``Lean.Parser.Term.doFor then withFreshMacroScope do doForToCode doElem doElems else if k == ``Lean.Parser.Term.doMatch then doMatchToCode doElem doElems else if k == ``Lean.Parser.Term.doTry then doTryToCode doElem doElems else if k == ``Lean.Parser.Term.doBreak then ensureInsideFor ensureEOS doElems return mkBreak ref else if k == ``Lean.Parser.Term.doContinue then ensureInsideFor ensureEOS doElems return mkContinue ref else if k == ``Lean.Parser.Term.doReturn then doReturnToCode doElem doElems else if k == ``Lean.Parser.Term.doDbgTrace then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Lean.Parser.Term.doAssert then return mkSeq doElem (← doSeqToCode doElems) else if k == ``Lean.Parser.Term.doNested then let nestedDoSeq := doElem[1] doSeqToCode (getDoSeqElems nestedDoSeq ++ doElems) else if k == ``Lean.Parser.Term.doExpr then let term := doElem[0] if doElems.isEmpty then return mkTerminalAction term else return mkSeq term (← doSeqToCode doElems) else throwError "unexpected do-element of kind {doElem.getKind}:\n{doElem}" end def run (doStx : Syntax) (m : Syntax) : TermElabM CodeBlock := (doSeqToCode <| getDoSeqElems <| getDoSeq doStx).run { ref := doStx, m } end ToCodeBlock /- Create a synthetic metavariable `?m` and assign `m` to it. We use `?m` to refer to `m` when expanding the `do` notation. -/ private def mkMonadAlias (m : Expr) : TermElabM Syntax := do let result ← `(?m) let mType ← inferType m let mvar ← elabTerm result mType assignExprMVar mvar.mvarId! m pure result private partial def ensureArrowNotUsed : Syntax → MacroM Unit | stx@(Syntax.node k args) => do if k == ``Parser.Term.liftMethod || k == ``Parser.Term.doLetArrow || k == ``Parser.Term.doReassignArrow || k == ``Parser.Term.doIfLetBind then Macro.throwErrorAt stx "`←` and `<-` are not allowed in pure `do` blocks, i.e., blocks where Lean implicitly used the `Id` monad" args.forM ensureArrowNotUsed | _ => pure () @[builtinTermElab «do»] def elabDo : TermElab := fun stx expectedType? => do tryPostponeIfNoneOrMVar expectedType? let bindInfo ← extractBind expectedType? if bindInfo.isPure then liftMacroM <| ensureArrowNotUsed stx let m ← mkMonadAlias bindInfo.m let codeBlock ← ToCodeBlock.run stx m let stxNew ← liftMacroM $ ToTerm.run codeBlock.code m trace[Elab.do] stxNew withMacroExpansion stx stxNew $ elabTermEnsuringType stxNew bindInfo.expectedType end Do builtin_initialize registerTraceClass `Elab.do private def toDoElem (newKind : SyntaxNodeKind) : Macro := fun stx => do let stx := stx.setKind newKind withRef stx `(do $stx:doElem) @[builtinMacro Lean.Parser.Term.termFor] def expandTermFor : Macro := toDoElem ``Lean.Parser.Term.doFor @[builtinMacro Lean.Parser.Term.termTry] def expandTermTry : Macro := toDoElem ``Lean.Parser.Term.doTry @[builtinMacro Lean.Parser.Term.termUnless] def expandTermUnless : Macro := toDoElem ``Lean.Parser.Term.doUnless @[builtinMacro Lean.Parser.Term.termReturn] def expandTermReturn : Macro := toDoElem ``Lean.Parser.Term.doReturn end Lean.Elab.Term
218dc4c48a27df2fc8be26b4d427a07f76da5b94
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/LeftSpindle_Shelf.lean
50b206d5f0ef5e363695896ff87fe8fd6b021891
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
9,515
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section LeftSpindle_Shelf structure LeftSpindle_Shelf (A : Type) : Type := (linv : (A → (A → A))) (leftDistributive : (∀ {x y z : A} , (linv x (linv y z)) = (linv (linv x y) (linv x z)))) (idempotent_linv : (∀ {x : A} , (linv x x) = x)) (rinv : (A → (A → A))) (rightDistributive : (∀ {x y z : A} , (rinv (rinv y z) x) = (rinv (rinv y x) (rinv z x)))) open LeftSpindle_Shelf structure Sig (AS : Type) : Type := (linvS : (AS → (AS → AS))) (rinvS : (AS → (AS → AS))) structure Product (A : Type) : Type := (linvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (rinvP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (leftDistributiveP : (∀ {xP yP zP : (Prod A A)} , (linvP xP (linvP yP zP)) = (linvP (linvP xP yP) (linvP xP zP)))) (idempotent_linvP : (∀ {xP : (Prod A A)} , (linvP xP xP) = xP)) (rightDistributiveP : (∀ {xP yP zP : (Prod A A)} , (rinvP (rinvP yP zP) xP) = (rinvP (rinvP yP xP) (rinvP zP xP)))) structure Hom {A1 : Type} {A2 : Type} (Le1 : (LeftSpindle_Shelf A1)) (Le2 : (LeftSpindle_Shelf A2)) : Type := (hom : (A1 → A2)) (pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Le1) x1 x2)) = ((linv Le2) (hom x1) (hom x2)))) (pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Le1) x1 x2)) = ((rinv Le2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Le1 : (LeftSpindle_Shelf A1)) (Le2 : (LeftSpindle_Shelf A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Le1) x1 x2) ((linv Le2) y1 y2)))))) (interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Le1) x1 x2) ((rinv Le2) y1 y2)))))) inductive LeftSpindle_ShelfTerm : Type | linvL : (LeftSpindle_ShelfTerm → (LeftSpindle_ShelfTerm → LeftSpindle_ShelfTerm)) | rinvL : (LeftSpindle_ShelfTerm → (LeftSpindle_ShelfTerm → LeftSpindle_ShelfTerm)) open LeftSpindle_ShelfTerm inductive ClLeftSpindle_ShelfTerm (A : Type) : Type | sing : (A → ClLeftSpindle_ShelfTerm) | linvCl : (ClLeftSpindle_ShelfTerm → (ClLeftSpindle_ShelfTerm → ClLeftSpindle_ShelfTerm)) | rinvCl : (ClLeftSpindle_ShelfTerm → (ClLeftSpindle_ShelfTerm → ClLeftSpindle_ShelfTerm)) open ClLeftSpindle_ShelfTerm inductive OpLeftSpindle_ShelfTerm (n : ℕ) : Type | v : ((fin n) → OpLeftSpindle_ShelfTerm) | linvOL : (OpLeftSpindle_ShelfTerm → (OpLeftSpindle_ShelfTerm → OpLeftSpindle_ShelfTerm)) | rinvOL : (OpLeftSpindle_ShelfTerm → (OpLeftSpindle_ShelfTerm → OpLeftSpindle_ShelfTerm)) open OpLeftSpindle_ShelfTerm inductive OpLeftSpindle_ShelfTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpLeftSpindle_ShelfTerm2) | sing2 : (A → OpLeftSpindle_ShelfTerm2) | linvOL2 : (OpLeftSpindle_ShelfTerm2 → (OpLeftSpindle_ShelfTerm2 → OpLeftSpindle_ShelfTerm2)) | rinvOL2 : (OpLeftSpindle_ShelfTerm2 → (OpLeftSpindle_ShelfTerm2 → OpLeftSpindle_ShelfTerm2)) open OpLeftSpindle_ShelfTerm2 def simplifyCl {A : Type} : ((ClLeftSpindle_ShelfTerm A) → (ClLeftSpindle_ShelfTerm A)) | (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2)) | (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpLeftSpindle_ShelfTerm n) → (OpLeftSpindle_ShelfTerm n)) | (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2)) | (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpLeftSpindle_ShelfTerm2 n A) → (OpLeftSpindle_ShelfTerm2 n A)) | (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2)) | (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((LeftSpindle_Shelf A) → (LeftSpindle_ShelfTerm → A)) | Le (linvL x1 x2) := ((linv Le) (evalB Le x1) (evalB Le x2)) | Le (rinvL x1 x2) := ((rinv Le) (evalB Le x1) (evalB Le x2)) def evalCl {A : Type} : ((LeftSpindle_Shelf A) → ((ClLeftSpindle_ShelfTerm A) → A)) | Le (sing x1) := x1 | Le (linvCl x1 x2) := ((linv Le) (evalCl Le x1) (evalCl Le x2)) | Le (rinvCl x1 x2) := ((rinv Le) (evalCl Le x1) (evalCl Le x2)) def evalOpB {A : Type} {n : ℕ} : ((LeftSpindle_Shelf A) → ((vector A n) → ((OpLeftSpindle_ShelfTerm n) → A))) | Le vars (v x1) := (nth vars x1) | Le vars (linvOL x1 x2) := ((linv Le) (evalOpB Le vars x1) (evalOpB Le vars x2)) | Le vars (rinvOL x1 x2) := ((rinv Le) (evalOpB Le vars x1) (evalOpB Le vars x2)) def evalOp {A : Type} {n : ℕ} : ((LeftSpindle_Shelf A) → ((vector A n) → ((OpLeftSpindle_ShelfTerm2 n A) → A))) | Le vars (v2 x1) := (nth vars x1) | Le vars (sing2 x1) := x1 | Le vars (linvOL2 x1 x2) := ((linv Le) (evalOp Le vars x1) (evalOp Le vars x2)) | Le vars (rinvOL2 x1 x2) := ((rinv Le) (evalOp Le vars x1) (evalOp Le vars x2)) def inductionB {P : (LeftSpindle_ShelfTerm → Type)} : ((∀ (x1 x2 : LeftSpindle_ShelfTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → ((∀ (x1 x2 : LeftSpindle_ShelfTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : LeftSpindle_ShelfTerm) , (P x)))) | plinvl prinvl (linvL x1 x2) := (plinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2)) | plinvl prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2)) def inductionCl {A : Type} {P : ((ClLeftSpindle_ShelfTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClLeftSpindle_ShelfTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → ((∀ (x1 x2 : (ClLeftSpindle_ShelfTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClLeftSpindle_ShelfTerm A)) , (P x))))) | psing plinvcl prinvcl (sing x1) := (psing x1) | psing plinvcl prinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2)) | psing plinvcl prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2)) def inductionOpB {n : ℕ} {P : ((OpLeftSpindle_ShelfTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpLeftSpindle_ShelfTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → ((∀ (x1 x2 : (OpLeftSpindle_ShelfTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpLeftSpindle_ShelfTerm n)) , (P x))))) | pv plinvol prinvol (v x1) := (pv x1) | pv plinvol prinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2)) | pv plinvol prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpLeftSpindle_ShelfTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpLeftSpindle_ShelfTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → ((∀ (x1 x2 : (OpLeftSpindle_ShelfTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpLeftSpindle_ShelfTerm2 n A)) , (P x)))))) | pv2 psing2 plinvol2 prinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 plinvol2 prinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 plinvol2 prinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2)) | pv2 psing2 plinvol2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2)) def stageB : (LeftSpindle_ShelfTerm → (Staged LeftSpindle_ShelfTerm)) | (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2)) | (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClLeftSpindle_ShelfTerm A) → (Staged (ClLeftSpindle_ShelfTerm A))) | (sing x1) := (Now (sing x1)) | (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2)) | (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpLeftSpindle_ShelfTerm n) → (Staged (OpLeftSpindle_ShelfTerm n))) | (v x1) := (const (code (v x1))) | (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2)) | (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpLeftSpindle_ShelfTerm2 n A) → (Staged (OpLeftSpindle_ShelfTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2)) | (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (linvT : ((Repr A) → ((Repr A) → (Repr A)))) (rinvT : ((Repr A) → ((Repr A) → (Repr A)))) end LeftSpindle_Shelf
e6aa9e31f8ad83f3fc5c11a46b73fbaf15fc63c8
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0211.lean
0e62130052721f18ccce773fed7bef641d0424ca
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
78
lean
variables p q : Prop variable hp : p theorem t1 : q → p := λ (hq : q), hp
a701b4d3d9fc1b81e9a6d4b81a8201a1fb7217e4
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/sites/closed.lean
8e8c0cc40eafe5af580de71e11333228b314909b
[ "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
12,156
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.sheaf_of_types import order.closure /-! # Closed sieves A natural closure operator on sieves is a closure operator on `sieve X` for each `X` which commutes with pullback. We show that a Grothendieck topology `J` induces a natural closure operator, and define what the closed sieves are. The collection of `J`-closed sieves forms a presheaf which is a sheaf for `J`, and further this presheaf can be used to determine the Grothendieck topology from the sheaf predicate. Finally we show that a natural closure operator on sieves induces a Grothendieck topology, and hence that natural closure operators are in bijection with Grothendieck topologies. ## Main definitions * `category_theory.grothendieck_topology.close`: Sends a sieve `S` on `X` to the set of arrows which it covers. This has all the usual properties of a closure operator, as well as commuting with pullback. * `category_theory.grothendieck_topology.closure_operator`: The bundled `closure_operator` given by `category_theory.grothendieck_topology.close`. * `category_theory.grothendieck_topology.closed`: A sieve `S` on `X` is closed for the topology `J` if it contains every arrow it covers. * `category_theory.functor.closed_sieves`: The presheaf sending `X` to the collection of `J`-closed sieves on `X`. This is additionally shown to be a sheaf for `J`, and if this is a sheaf for a different topology `J'`, then `J' ≤ J`. * `category_theory.grothendieck_topology.topology_of_closure_operator`: A closure operator on the set of sieves on every object which commutes with pullback additionally induces a Grothendieck topology, giving a bijection with `category_theory.grothendieck_topology.closure_operator`. ## Tags closed sieve, closure, Grothendieck topology ## References * [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92] -/ universes v u namespace category_theory variables {C : Type u} [category.{v} C] variables (J₁ J₂ : grothendieck_topology C) namespace grothendieck_topology /-- The `J`-closure of a sieve is the collection of arrows which it covers. -/ @[simps] def close {X : C} (S : sieve X) : sieve X := { arrows := λ Y f, J₁.covers S f, downward_closed' := λ Y Z f hS, J₁.arrow_stable _ _ hS } /-- Any sieve is smaller than its closure. -/ lemma le_close {X : C} (S : sieve X) : S ≤ J₁.close S := λ Y g hg, J₁.covering_of_eq_top (S.pullback_eq_top_of_mem hg) /-- A sieve is closed for the Grothendieck topology if it contains every arrow it covers. In the case of the usual topology on a topological space, this means that the open cover contains every open set which it covers. Note this has no relation to a closed subset of a topological space. -/ def is_closed {X : C} (S : sieve X) : Prop := ∀ ⦃Y : C⦄ (f : Y ⟶ X), J₁.covers S f → S f /-- If `S` is `J₁`-closed, then `S` covers exactly the arrows it contains. -/ lemma covers_iff_mem_of_closed {X : C} {S : sieve X} (h : J₁.is_closed S) {Y : C} (f : Y ⟶ X) : J₁.covers S f ↔ S f := ⟨h _, J₁.arrow_max _ _⟩ /-- Being `J`-closed is stable under pullback. -/ lemma is_closed_pullback {X Y : C} (f : Y ⟶ X) (S : sieve X) : J₁.is_closed S → J₁.is_closed (S.pullback f) := λ hS Z g hg, hS (g ≫ f) (by rwa [J₁.covers_iff, sieve.pullback_comp]) /-- The closure of a sieve `S` is the largest closed sieve which contains `S` (justifying the name "closure"). -/ lemma le_close_of_is_closed {X : C} {S T : sieve X} (h : S ≤ T) (hT : J₁.is_closed T) : J₁.close S ≤ T := λ Y f hf, hT _ (J₁.superset_covering (sieve.pullback_monotone f h) hf) /-- The closure of a sieve is closed. -/ lemma close_is_closed {X : C} (S : sieve X) : J₁.is_closed (J₁.close S) := λ Y g hg, J₁.arrow_trans g _ S hg (λ Z h hS, hS) /-- The sieve `S` is closed iff its closure is equal to itself. -/ lemma is_closed_iff_close_eq_self {X : C} (S : sieve X) : J₁.is_closed S ↔ J₁.close S = S := begin split, { intro h, apply le_antisymm, { intros Y f hf, rw ← J₁.covers_iff_mem_of_closed h, apply hf }, { apply J₁.le_close } }, { intro e, rw ← e, apply J₁.close_is_closed } end lemma close_eq_self_of_is_closed {X : C} {S : sieve X} (hS : J₁.is_closed S) : J₁.close S = S := (J₁.is_closed_iff_close_eq_self S).1 hS /-- Closing under `J` is stable under pullback. -/ lemma pullback_close {X Y : C} (f : Y ⟶ X) (S : sieve X) : J₁.close (S.pullback f) = (J₁.close S).pullback f := begin apply le_antisymm, { refine J₁.le_close_of_is_closed (sieve.pullback_monotone _ (J₁.le_close S)) _, apply J₁.is_closed_pullback _ _ (J₁.close_is_closed _) }, { intros Z g hg, change _ ∈ J₁ _, rw ← sieve.pullback_comp, apply hg } end @[mono] lemma monotone_close {X : C} : monotone (J₁.close : sieve X → sieve X) := λ S₁ S₂ h, J₁.le_close_of_is_closed (h.trans (J₁.le_close _)) (J₁.close_is_closed S₂) @[simp] lemma close_close {X : C} (S : sieve X) : J₁.close (J₁.close S) = J₁.close S := le_antisymm (J₁.le_close_of_is_closed (le_refl _) (J₁.close_is_closed S)) (J₁.monotone_close (J₁.le_close _)) /-- The sieve `S` is in the topology iff its closure is the maximal sieve. This shows that the closure operator determines the topology. -/ lemma close_eq_top_iff_mem {X : C} (S : sieve X) : J₁.close S = ⊤ ↔ S ∈ J₁ X := begin split, { intro h, apply J₁.transitive (J₁.top_mem X), intros Y f hf, change J₁.close S f, rwa h }, { intro hS, rw eq_top_iff, intros Y f hf, apply J₁.pullback_stable _ hS } end /-- A Grothendieck topology induces a natural family of closure operators on sieves. -/ @[simps {rhs_md := semireducible}] def closure_operator (X : C) : closure_operator (sieve X) := closure_operator.mk' J₁.close (λ S₁ S₂ h, J₁.le_close_of_is_closed (h.trans (J₁.le_close _)) (J₁.close_is_closed S₂)) J₁.le_close (λ S, J₁.le_close_of_is_closed (le_refl _) (J₁.close_is_closed S)) @[simp] lemma closed_iff_closed {X : C} (S : sieve X) : S ∈ (J₁.closure_operator X).closed ↔ J₁.is_closed S := (J₁.is_closed_iff_close_eq_self S).symm end grothendieck_topology /-- The presheaf sending each object to the set of `J`-closed sieves on it. This presheaf is a `J`-sheaf (and will turn out to be a subobject classifier for the category of `J`-sheaves). -/ @[simps] def functor.closed_sieves : Cᵒᵖ ⥤ Type (max v u) := { obj := λ X, {S : sieve X.unop // J₁.is_closed S}, map := λ X Y f S, ⟨S.1.pullback f.unop, J₁.is_closed_pullback f.unop _ S.2⟩ } /-- The presheaf of `J`-closed sieves is a `J`-sheaf. The proof of this is adapted from [MM92], Chatper III, Section 7, Lemma 1. -/ lemma classifier_is_sheaf : presieve.is_sheaf J₁ (functor.closed_sieves J₁) := begin intros X S hS, rw ← presieve.is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, refine ⟨_, _⟩, { rintro x ⟨M, hM⟩ ⟨N, hN⟩ hM₂ hN₂, ext, dsimp only [subtype.coe_mk], rw [← J₁.covers_iff_mem_of_closed hM, ← J₁.covers_iff_mem_of_closed hN], have q : ∀ ⦃Z : C⦄ (g : Z ⟶ X) (hg : S g), M.pullback g = N.pullback g, { intros Z g hg, apply congr_arg subtype.val ((hM₂ g hg).trans (hN₂ g hg).symm) }, have MSNS : M ⊓ S = N ⊓ S, { ext Z g, rw [sieve.inter_apply, sieve.inter_apply, and_comm (N g), and_comm], apply and_congr_right, intro hg, rw [sieve.pullback_eq_top_iff_mem, sieve.pullback_eq_top_iff_mem, q g hg] }, split, { intro hf, rw J₁.covers_iff, apply J₁.superset_covering (sieve.pullback_monotone f inf_le_left), rw ← MSNS, apply J₁.arrow_intersect f M S hf (J₁.pullback_stable _ hS) }, { intro hf, rw J₁.covers_iff, apply J₁.superset_covering (sieve.pullback_monotone f inf_le_left), rw MSNS, apply J₁.arrow_intersect f N S hf (J₁.pullback_stable _ hS) } }, { intros x hx, rw presieve.compatible_iff_sieve_compatible at hx, let M := sieve.bind S (λ Y f hf, (x f hf).1), have : ∀ ⦃Y⦄ (f : Y ⟶ X) (hf : S f), M.pullback f = (x f hf).1, { intros Y f hf, apply le_antisymm, { rintro Z u ⟨W, g, f', hf', (hg : (x f' hf').1 _), c⟩, rw [sieve.pullback_eq_top_iff_mem, ←(show (x (u ≫ f) _).1 = (x f hf).1.pullback u, from congr_arg subtype.val (hx f u hf))], simp_rw ← c, rw (show (x (g ≫ f') _).1 = _, from congr_arg subtype.val (hx f' g hf')), apply sieve.pullback_eq_top_of_mem _ hg }, { apply sieve.le_pullback_bind S (λ Y f hf, (x f hf).1) } }, refine ⟨⟨_, J₁.close_is_closed M⟩, _⟩, { intros Y f hf, ext1, dsimp, rw [← J₁.pullback_close, this _ hf], apply le_antisymm (J₁.le_close_of_is_closed (le_refl _) (x f hf).2) (J₁.le_close _) } }, end /-- If presheaf of `J₁`-closed sieves is a `J₂`-sheaf then `J₁ ≤ J₂`. Note the converse is true by `classifier_is_sheaf` and `is_sheaf_of_le`. -/ lemma le_topology_of_closed_sieves_is_sheaf {J₁ J₂ : grothendieck_topology C} (h : presieve.is_sheaf J₁ (functor.closed_sieves J₂)) : J₁ ≤ J₂ := λ X S hS, begin rw ← J₂.close_eq_top_iff_mem, have : J₂.is_closed (⊤ : sieve X), { intros Y f hf, trivial }, suffices : (⟨J₂.close S, J₂.close_is_closed S⟩ : subtype _) = ⟨⊤, this⟩, { rw subtype.ext_iff at this, exact this }, apply (h S hS).is_separated_for.ext, { intros Y f hf, ext1, dsimp, rw [sieve.pullback_top, ← J₂.pullback_close, S.pullback_eq_top_of_mem hf, J₂.close_eq_top_iff_mem], apply J₂.top_mem }, end /-- If being a sheaf for `J₁` is equivalent to being a sheaf for `J₂`, then `J₁ = J₂`. -/ lemma topology_eq_iff_same_sheaves {J₁ J₂ : grothendieck_topology C} : J₁ = J₂ ↔ (∀ (P : Cᵒᵖ ⥤ Type (max v u)), presieve.is_sheaf J₁ P ↔ presieve.is_sheaf J₂ P) := begin split, { rintro rfl, intro P, refl }, { intro h, apply le_antisymm, { apply le_topology_of_closed_sieves_is_sheaf, rw h, apply classifier_is_sheaf }, { apply le_topology_of_closed_sieves_is_sheaf, rw ← h, apply classifier_is_sheaf } } end /-- A closure (increasing, inflationary and idempotent) operation on sieves that commutes with pullback induces a Grothendieck topology. In fact, such operations are in bijection with Grothendieck topologies. -/ @[simps] def topology_of_closure_operator (c : Π (X : C), closure_operator (sieve X)) (hc : Π ⦃X Y : C⦄ (f : Y ⟶ X) (S : sieve X), c _ (S.pullback f) = (c _ S).pullback f) : grothendieck_topology C := { sieves := λ X, {S | c X S = ⊤}, top_mem' := λ X, top_unique ((c X).le_closure _), pullback_stable' := λ X Y S f hS, begin rw set.mem_set_of_eq at hS, rw [set.mem_set_of_eq, hc, hS, sieve.pullback_top], end, transitive' := λ X S hS R hR, begin rw set.mem_set_of_eq at hS, rw [set.mem_set_of_eq, ←(c X).idempotent, eq_top_iff, ←hS], apply (c X).monotone (λ Y f hf, _), rw [sieve.pullback_eq_top_iff_mem, ←hc], apply hR hf, end } /-- The topology given by the closure operator `J.close` on a Grothendieck topology is the same as `J`. -/ lemma topology_of_closure_operator_self : topology_of_closure_operator J₁.closure_operator (λ X Y, J₁.pullback_close) = J₁ := begin ext X S, apply grothendieck_topology.close_eq_top_iff_mem, end lemma topology_of_closure_operator_close (c : Π (X : C), closure_operator (sieve X)) (pb : Π ⦃X Y : C⦄ (f : Y ⟶ X) (S : sieve X), c Y (S.pullback f) = (c X S).pullback f) (X : C) (S : sieve X) : (topology_of_closure_operator c pb).close S = c X S := begin ext, change c _ (sieve.pullback f S) = ⊤ ↔ c _ S f, rw [pb, sieve.pullback_eq_top_iff_mem], end end category_theory
30fa0a6eaca08fcdb5ee54f130445ed6e1e22d87
048b0801f6dafb6486ca4f22bd0957671c3002ff
/src/basic/list.lean
628ee62c142eb0a528b297016fe4442cd0136a24
[ "Apache-2.0" ]
permissive
Scikud/lean-gym
e0782e36389ecfa1605a0c12dc95f67014a0fa05
a1ca851b7c09eca1f72be2d059e3ed5536348b0b
refs/heads/main
1,693,940,033,482
1,633,522,864,000
1,633,522,864,000
419,793,692
0
0
null
null
null
null
UTF-8
Lean
false
false
6,638
lean
/- Author: E.W.Ayers © 2019. Copied from the lean-tpe projcet: https://github.com/jesse-michael-han/lean-tpe-public Some additional helpers for working with lists. I suspect that I have duplicated some functionality here. -/ import data.list basic.control universe u namespace list variables {α β : Type u} {T : Type u → Type u} def mmapi_core [applicative T] (f : nat → α → T β) : nat → list α → T (list β) | n [] := pure [] | n (h :: t) := pure (::) <*> f n h <*> mmapi_core (n+1) t def mmapi [applicative T] (f : nat → α → T β) : list α → T (list β) := mmapi_core f 0 def mpicki_core [alternative T] (p : nat → α → T β) : nat → list α → T β | i [] := failure | i (h :: t) := p i h <|> mpicki_core (i+1) t def mpicki [alternative T] (p : nat → α → T β) : list α → T β := mpicki_core p 0 def picki (p : nat → α → option β) : list α → option β := mpicki p def mpick [alternative T] (p : α → T β) : list α → T β := mpicki_core (λ _, p) 0 def pick (p : α → option β) : list α → option β := mpick p /-- Returns true if at least one item returns true under `p`.-/ def m_some {T : Type → Type u} [monad T] (p : α → T bool) : list α → T bool | [] := pure ff | (h :: t) := do b ← p h, if b then pure tt else m_some t def m_all {T : Type → Type u} [monad T] (p : α → T bool) : list α → T bool | l := bnot <$> (m_some (λ x, bnot <$> p x) l) def find_with_index_core (p : α → Prop) [decidable_pred p] : nat → list α → option (α × nat) | i [] := none | i (h :: t) := if p h then some ⟨h,i⟩ else find_with_index_core (i+1) t def mfind_with_index (p : α → Prop) [decidable_pred p] : list α → option (α × nat) := find_with_index_core p 0 private def partition_sum_fold : α ⊕ β → list α × list β → list α × list β | (sum.inl a) (as,bs) := (a::as,bs) | (sum.inr b) (as,bs) := (as,b::bs) def partition_sum : list (α ⊕ β) → list α × list β | l := foldr partition_sum_fold ([],[]) l def ohead : list α → option α | [] := none | (h :: t) := some h def olast : list α → option α | [x] := some x | [] := none | (h :: t) := olast t /-- Find the maximum according to the given function. -/ def max_by (f : α → int) (l : list α) : option α := prod.fst <$> foldl (λ (acc : option(α×ℤ)) x, let m := f x in option.cases_on acc (some ⟨x,m⟩) (λ ⟨_,m'⟩, if m < m' then acc else some ⟨x,m⟩)) none l def min_by (f : α → int) (l : list α) : option α := max_by (has_neg.neg ∘ f) l def achoose [alternative T] (f : α → T β) : list α → T (list β) | [] := pure [] | (h :: t) := ((pure cons <*> f h) <|> pure id) <*> achoose t def apick [monad T] [alternative T] (f : α → T β) : list α → T β | [] := failure | (h :: t) := f h <|> (pure (punit.star) >>= λ _, apick t) def mchoose [applicative T] (f : α → T (option β)) : list α → T (list β) | [] := pure [] | (h :: t) := pure (@option.rec β (λ _, list β → list β) id cons) <*> f h <*> mchoose t /-- Same as filter but explicitly takes a boolean.-/ def bfilter : (α → bool) → list α → list α | f a := filter (λ x, f x) a def bfind : (α → bool) → list α → option α | f a := find (λ x, f x) a def bfind_index (f : α → bool) : list α → option nat | [] := none | (h :: t) := if f h then some 0 else nat.succ <$> bfind_index t /-- `subtract x y` is some `z` when `∃ z, x = y ++ z` -/ def subtract [decidable_eq α]: (list α) → (list α) → option (list α) | a [] := some a -- [] ++ a = a | [] _ := none -- (h::t) ++ _ ≠ [] -- if t₂ ++ z = t₁ then (h₁ :: t₁) ++ z = (h₁ :: t₂) | (h₁ :: t₁) (h₂ :: t₂) := if h₁ = h₂ then subtract t₁ t₂ else none def opartition (f : α → option β) : list α → list β × list α := foldr (λ x, option.rec_on (f x) (prod.map id $ cons x) $ λ b, prod.map (cons b) id) ([],[]) def apartition [alternative T] (f : α → T β) : list α → T (list β × list α) | [] := pure $ ([],[]) | (h::rest) := pure (λ (o : option β) p, option.rec_on o (prod.map id (cons h) p) (λ b, prod.map (cons b) id p)) <*> ((some <$> f h) <|> pure none) <*> apartition rest def eq_by (e : α → α → bool) : list α → list α → bool | [] [] := tt | [] (_ :: _) := ff | (_ :: _) [] := ff | (a₁ :: l₁) (a₂ :: l₂) := e a₁ a₂ ∧ eq_by l₁ l₂ def collect {β} (f : α → list β) : list α → list β | l := bind l f def mcollect {T} [monad T] (f : α → T (list β)) : list α → T (list β) |l := mfoldl (λ acc x, (++ acc) <$> f x) [] l def msome {T} [monad T] {α} (f : α → T bool) : list α → T bool |[] := pure ff |(h::t) := f h >>= λ x, if x then pure tt else msome t /-- `skip n l` returns `l` with the first `n` elements removed. If `n > l.length` it returns the empty list -/ def skip {α} : ℕ → list α → list α |0 l := l |(n+1) [] := [] |(n+1) (h::t) := skip n t meta def get_equivalence_classes {T : Type → Type} [monad T] {α : Type} (rel : α → α → T bool) : list α → T(list (list α)) | l := do x ← mfoldl (λ table h, do pr : option ((α × list α) × nat) ← @mpicki _ _ (T ∘ option) _ (λ i e, ((do b ← rel (prod.fst e) h, pure $ if b then some (e,i) else none ) : T (option _)) ) table, pure $ match pr with | none := (h,[h]) :: table | (some ⟨x,i⟩) := table.update_nth i $ prod.map id (cons h) x end ) [] $ l, pure $ reverse $ map (reverse ∘ prod.snd) $ x /-- Perform the given pair reduction to neighbours in the list until you can't anymore. -/ meta def pair_rewrite {m : Type u → Type} [monad m] [alternative m] (rr : α → α → m (α)) : list α → m (list α) | [] := pure [] | [x] := pure [x] | (x :: y :: rest) := do (do z ← rr x y, pair_rewrite (z :: rest) ) <|> (do res ← pair_rewrite (y :: rest), match res with | [] := pure [x] | (y2 :: rest2) := (do z ← rr x y2, pair_rewrite (z :: rest2) ) <|> (pure $ x :: y2 :: rest2) end ) def with_indices : list α → list (nat × α) := list.map_with_index prod.mk def msplit {T : Type u → Type u} [monad T] {α β γ : Type u} (p : α → T (β ⊕ γ)) : list α → T (list β × list γ) | l := do ⟨xs,ys⟩ ← l.mfoldl (λ (xsys : list β × list γ) a, do ⟨xs,ys⟩ ← pure xsys, r ← p a, pure $ sum.rec_on r (λ x, ⟨x::xs,ys⟩) (λ y, ⟨xs,y::ys⟩) ) (⟨[],[]⟩), pure ⟨xs.reverse,ys.reverse⟩ end list
00b3eb3e729e1ea39be0423806ff87c8a307b867
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/tactic/custom_wf.lean
db23ae0d622761eef57dc51f40229b1c422ff4a6
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
595
lean
namespace tactic open well_founded_tactics /-- `fst_dec_tac`, but without the `abstract` (and thus zeta reducing). -/ meta def fst_dec_tac' : tactic unit := do clear_internals, unfold_wf_rel, process_lex (unfold_sizeof >> try (tactic.dunfold_target [``psigma.fst]) >> cancel_nat_add_lt >> trivial_nat_lt) /-- An alternative version of `dec_tac` which also unfolds .fst indexing. This is required for the various proofs which skip the implicit context argument. -/ meta def fst_dec_tac : tactic unit := abstract fst_dec_tac' end tactic
bbdb6da9fe9b27960bde0a78eece1d4f260d56ee
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/projection_auto.lean
789081aa54a8f6d1a8cbf5f8f2999a3d99053a97
[]
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
11,539
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.basic import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Projection to a subspace In this file we define * `linear_proj_of_is_compl (p q : submodule R E) (h : is_compl p q)`: the projection of a module `E` to a submodule `p` along its complement `q`; it is the unique linear map `f : E → p` such that `f x = x` for `x ∈ p` and `f x = 0` for `x ∈ q`. * `is_compl_equiv_proj p`: equivalence between submodules `q` such that `is_compl p q` and projections `f : E → p`, `∀ x ∈ p, f x = x`. We also provide some lemmas justifying correctness of our definitions. ## Tags projection, complement subspace -/ namespace linear_map theorem ker_id_sub_eq_of_proj {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {f : linear_map R E ↥p} (hf : ∀ (x : ↥p), coe_fn f ↑x = x) : ker (id - comp (submodule.subtype p) f) = p := sorry theorem range_eq_of_proj {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {f : linear_map R E ↥p} (hf : ∀ (x : ↥p), coe_fn f ↑x = x) : range f = ⊤ := iff.mpr range_eq_top fun (x : ↥p) => Exists.intro (↑x) (hf x) theorem is_compl_of_proj {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {f : linear_map R E ↥p} (hf : ∀ (x : ↥p), coe_fn f ↑x = x) : is_compl p (ker f) := sorry end linear_map namespace submodule /-- If `q` is a complement of `p`, then `M/p ≃ q`. -/ def quotient_equiv_of_is_compl {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) : linear_equiv R (quotient p) ↥q := linear_equiv.symm (linear_equiv.of_bijective (linear_map.comp (mkq p) (submodule.subtype q)) sorry sorry) @[simp] theorem quotient_equiv_of_is_compl_symm_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) (x : ↥q) : coe_fn (linear_equiv.symm (quotient_equiv_of_is_compl p q h)) x = quotient.mk ↑x := rfl @[simp] theorem quotient_equiv_of_is_compl_apply_mk_coe {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) (x : ↥q) : coe_fn (quotient_equiv_of_is_compl p q h) (quotient.mk ↑x) = x := linear_equiv.apply_symm_apply (quotient_equiv_of_is_compl p q h) x @[simp] theorem mk_quotient_equiv_of_is_compl_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) (x : quotient p) : quotient.mk ↑(coe_fn (quotient_equiv_of_is_compl p q h) x) = x := linear_equiv.symm_apply_apply (quotient_equiv_of_is_compl p q h) x /-- If `q` is a complement of `p`, then `p × q` is isomorphic to `E`. It is the unique linear map `f : E → p` such that `f x = x` for `x ∈ p` and `f x = 0` for `x ∈ q`. -/ def prod_equiv_of_is_compl {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) : linear_equiv R (↥p × ↥q) E := linear_equiv.of_bijective (linear_map.coprod (submodule.subtype p) (submodule.subtype q)) sorry sorry @[simp] theorem coe_prod_equiv_of_is_compl {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) : ↑(prod_equiv_of_is_compl p q h) = linear_map.coprod (submodule.subtype p) (submodule.subtype q) := rfl @[simp] theorem coe_prod_equiv_of_is_compl' {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) (x : ↥p × ↥q) : coe_fn (prod_equiv_of_is_compl p q h) x = ↑(prod.fst x) + ↑(prod.snd x) := rfl @[simp] theorem prod_equiv_of_is_compl_symm_apply_left {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) (x : ↥p) : coe_fn (linear_equiv.symm (prod_equiv_of_is_compl p q h)) ↑x = (x, 0) := sorry @[simp] theorem prod_equiv_of_is_compl_symm_apply_right {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) (x : ↥q) : coe_fn (linear_equiv.symm (prod_equiv_of_is_compl p q h)) ↑x = (0, x) := sorry @[simp] theorem prod_equiv_of_is_compl_symm_apply_fst_eq_zero {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) {x : E} : prod.fst (coe_fn (linear_equiv.symm (prod_equiv_of_is_compl p q h)) x) = 0 ↔ x ∈ q := sorry @[simp] theorem prod_equiv_of_is_compl_symm_apply_snd_eq_zero {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) {x : E} : prod.snd (coe_fn (linear_equiv.symm (prod_equiv_of_is_compl p q h)) x) = 0 ↔ x ∈ p := sorry /-- Projection to a submodule along its complement. -/ def linear_proj_of_is_compl {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : submodule R E) (h : is_compl p q) : linear_map R E ↥p := linear_map.comp (linear_map.fst R ↥p ↥q) ↑(linear_equiv.symm (prod_equiv_of_is_compl p q h)) @[simp] theorem linear_proj_of_is_compl_apply_left {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {q : submodule R E} (h : is_compl p q) (x : ↥p) : coe_fn (linear_proj_of_is_compl p q h) ↑x = x := sorry @[simp] theorem linear_proj_of_is_compl_range {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {q : submodule R E} (h : is_compl p q) : linear_map.range (linear_proj_of_is_compl p q h) = ⊤ := linear_map.range_eq_of_proj (linear_proj_of_is_compl_apply_left h) @[simp] theorem linear_proj_of_is_compl_apply_eq_zero_iff {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {q : submodule R E} (h : is_compl p q) {x : E} : coe_fn (linear_proj_of_is_compl p q h) x = 0 ↔ x ∈ q := sorry theorem linear_proj_of_is_compl_apply_right' {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {q : submodule R E} (h : is_compl p q) (x : E) (hx : x ∈ q) : coe_fn (linear_proj_of_is_compl p q h) x = 0 := iff.mpr (linear_proj_of_is_compl_apply_eq_zero_iff h) hx @[simp] theorem linear_proj_of_is_compl_apply_right {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {q : submodule R E} (h : is_compl p q) (x : ↥q) : coe_fn (linear_proj_of_is_compl p q h) ↑x = 0 := linear_proj_of_is_compl_apply_right' h (↑x) (subtype.property x) @[simp] theorem linear_proj_of_is_compl_ker {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {q : submodule R E} (h : is_compl p q) : linear_map.ker (linear_proj_of_is_compl p q h) = q := ext fun (x : E) => iff.trans linear_map.mem_ker (linear_proj_of_is_compl_apply_eq_zero_iff h) theorem linear_proj_of_is_compl_comp_subtype {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {q : submodule R E} (h : is_compl p q) : linear_map.comp (linear_proj_of_is_compl p q h) (submodule.subtype p) = linear_map.id := linear_map.ext (linear_proj_of_is_compl_apply_left h) theorem linear_proj_of_is_compl_idempotent {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} {q : submodule R E} (h : is_compl p q) (x : E) : coe_fn (linear_proj_of_is_compl p q h) ↑(coe_fn (linear_proj_of_is_compl p q h) x) = coe_fn (linear_proj_of_is_compl p q h) x := linear_proj_of_is_compl_apply_left h (coe_fn (linear_proj_of_is_compl p q h) x) end submodule namespace linear_map @[simp] theorem linear_proj_of_is_compl_of_proj {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {p : submodule R E} (f : linear_map R E ↥p) (hf : ∀ (x : ↥p), coe_fn f ↑x = x) : submodule.linear_proj_of_is_compl p (ker f) (is_compl_of_proj hf) = f := sorry /-- If `f : E →ₗ[R] F` and `g : E →ₗ[R] G` are two surjective linear maps and their kernels are complement of each other, then `x ↦ (f x, g x)` defines a linear equivalence `E ≃ₗ[R] F × G`. -/ def equiv_prod_of_surjective_of_is_compl {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {F : Type u_3} [add_comm_group F] [module R F] {G : Type u_4} [add_comm_group G] [module R G] (f : linear_map R E F) (g : linear_map R E G) (hf : range f = ⊤) (hg : range g = ⊤) (hfg : is_compl (ker f) (ker g)) : linear_equiv R E (F × G) := linear_equiv.of_bijective (prod f g) sorry sorry @[simp] theorem coe_equiv_prod_of_surjective_of_is_compl {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {F : Type u_3} [add_comm_group F] [module R F] {G : Type u_4} [add_comm_group G] [module R G] {f : linear_map R E F} {g : linear_map R E G} (hf : range f = ⊤) (hg : range g = ⊤) (hfg : is_compl (ker f) (ker g)) : ↑(equiv_prod_of_surjective_of_is_compl f g hf hg hfg) = prod f g := rfl @[simp] theorem equiv_prod_of_surjective_of_is_compl_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] {F : Type u_3} [add_comm_group F] [module R F] {G : Type u_4} [add_comm_group G] [module R G] {f : linear_map R E F} {g : linear_map R E G} (hf : range f = ⊤) (hg : range g = ⊤) (hfg : is_compl (ker f) (ker g)) (x : E) : coe_fn (equiv_prod_of_surjective_of_is_compl f g hf hg hfg) x = (coe_fn f x, coe_fn g x) := rfl end linear_map namespace submodule /-- Equivalence between submodules `q` such that `is_compl p q` and linear maps `f : E →ₗ[R] p` such that `∀ x : p, f x = x`. -/ def is_compl_equiv_proj {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) : (Subtype fun (q : submodule R E) => is_compl p q) ≃ Subtype fun (f : linear_map R E ↥p) => ∀ (x : ↥p), coe_fn f ↑x = x := equiv.mk (fun (q : Subtype fun (q : submodule R E) => is_compl p q) => { val := linear_proj_of_is_compl p ↑q sorry, property := sorry }) (fun (f : Subtype fun (f : linear_map R E ↥p) => ∀ (x : ↥p), coe_fn f ↑x = x) => { val := linear_map.ker ↑f, property := sorry }) sorry sorry @[simp] theorem coe_is_compl_equiv_proj_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (q : Subtype fun (q : submodule R E) => is_compl p q) : ↑(coe_fn (is_compl_equiv_proj p) q) = linear_proj_of_is_compl p (↑q) (subtype.property q) := rfl @[simp] theorem coe_is_compl_equiv_proj_symm_apply {R : Type u_1} [ring R] {E : Type u_2} [add_comm_group E] [module R E] (p : submodule R E) (f : Subtype fun (f : linear_map R E ↥p) => ∀ (x : ↥p), coe_fn f ↑x = x) : ↑(coe_fn (equiv.symm (is_compl_equiv_proj p)) f) = linear_map.ker ↑f := rfl end Mathlib
5ab9f377bb438dff9dc424c6a433318dd1692850
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/special_functions/trigonometric/bounds.lean
a781e5dd416f6538ae9e70df3ab68814bd0fe3a6
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,431
lean
/- Copyright (c) 2022 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import analysis.special_functions.trigonometric.basic import analysis.special_functions.trigonometric.deriv import analysis.special_functions.trigonometric.arctan_deriv /-! # Polynomial bounds for trigonometric functions ## Main statements This file contains upper and lower bounds for real trigonometric functions in terms of polynomials. See `trigonometric.basic` for more elementary inequalities, establishing the ranges of these functions, and their monotonicity in suitable intervals. Here we prove the following: * `sin_lt`: for `x > 0` we have `sin x < x`. * `sin_gt_sub_cube`: For `0 < x ≤ 1` we have `x - x ^ 3 / 4 < sin x`. * `lt_tan`: for `0 < x < π/2` we have `x < tan x`. ## Tags sin, cos, tan, angle -/ noncomputable theory open set namespace real open_locale real /-- For 0 < x, we have sin x < x. -/ lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases lt_or_le 1 x with h' h', { exact (sin_le_one x).trans_lt h' }, have hx : |x| = x := abs_of_nonneg h.le, have := le_of_abs_le (sin_bound $ show |x| ≤ 1, by rwa [hx]), rw [sub_le_iff_le_add', hx] at this, apply this.trans_lt, rw [sub_add, sub_lt_self_iff, sub_pos, div_eq_mul_inv (x ^ 3)], refine mul_lt_mul' _ (by norm_num) (by norm_num) (pow_pos h 3), apply pow_le_pow_of_le_one h.le h', norm_num end /-- For 0 < x ≤ 1 we have x - x ^ 3 / 4 < sin x. This is also true for x > 1, but it's nontrivial for x just above 1. This inequality is not tight; the tighter inequality is sin x > x - x ^ 3 / 6 for all x > 0, but this inequality has a simpler proof. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x := begin have hx : |x| = x := abs_of_nonneg h.le, have := neg_le_of_abs_le (sin_bound $ show |x| ≤ 1, by rwa [hx]), rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, have : x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 * 12⁻¹ := by norm_num [div_eq_mul_inv, ← mul_sub], rw [add_comm, sub_add, sub_neg_eq_add, sub_lt_sub_iff_left, ←lt_sub_iff_add_lt', this], refine mul_lt_mul' _ (by norm_num) (by norm_num) (pow_pos h 3), apply pow_le_pow_of_le_one h.le h', norm_num end /-- The derivative of `tan x - x` is `1/(cos x)^2 - 1` away from the zeroes of cos. -/ lemma deriv_tan_sub_id (x : ℝ) (h : cos x ≠ 0) : deriv (λ y : ℝ, tan y - y) x = 1 / cos x ^ 2 - 1 := has_deriv_at.deriv $ by simpa using (has_deriv_at_tan h).add (has_deriv_at_id x).neg /-- For all `0 ≤ x < π/2` we have `x < tan x`. This is proved by checking that the function `tan x - x` vanishes at zero and has non-negative derivative. -/ theorem lt_tan (x : ℝ) (h1 : 0 < x) (h2 : x < π / 2) : x < tan x := begin let U := Ico 0 (π / 2), have intU : interior U = Ioo 0 (π / 2) := interior_Ico, have half_pi_pos : 0 < π / 2 := div_pos pi_pos two_pos, have cos_pos : ∀ {y : ℝ}, y ∈ U → 0 < cos y, { intros y hy, exact cos_pos_of_mem_Ioo (Ico_subset_Ioo_left (neg_lt_zero.mpr half_pi_pos) hy) }, have sin_pos : ∀ {y : ℝ}, y ∈ interior U → 0 < sin y, { intros y hy, rw intU at hy, exact sin_pos_of_mem_Ioo (Ioo_subset_Ioo_right (div_le_self pi_pos.le one_le_two) hy) }, have tan_cts_U : continuous_on tan U, { apply continuous_on.mono continuous_on_tan, intros z hz, simp only [mem_set_of_eq], exact (cos_pos hz).ne' }, have tan_minus_id_cts : continuous_on (λ y : ℝ, tan y - y) U := tan_cts_U.sub continuous_on_id, have deriv_pos : ∀ y : ℝ, y ∈ interior U → 0 < deriv (λ y' : ℝ, tan y' - y') y, { intros y hy, have := cos_pos (interior_subset hy), simp only [deriv_tan_sub_id y this.ne', one_div, gt_iff_lt, sub_pos], have bd2 : cos y ^ 2 < 1, { apply lt_of_le_of_ne y.cos_sq_le_one, rw cos_sq', simpa only [ne.def, sub_eq_self, pow_eq_zero_iff, nat.succ_pos'] using (sin_pos hy).ne' }, rwa [lt_inv, inv_one], { exact zero_lt_one }, simpa only [sq, mul_self_pos] using this.ne' }, have mono := convex.strict_mono_on_of_deriv_pos (convex_Ico 0 (π / 2)) tan_minus_id_cts deriv_pos, have zero_in_U : (0 : ℝ) ∈ U, { rwa left_mem_Ico }, have x_in_U : x ∈ U := ⟨h1.le, h2⟩, simpa only [tan_zero, sub_zero, sub_pos] using mono zero_in_U x_in_U h1 end end real
5f1cbbc68db53d00166f430e321de025b1d91817
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/schur_zassenhaus.lean
d7523f51d3821e51be09470eaa224fd8f64fa67f
[ "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
8,736
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import group_theory.complement import group_theory.index /-! # Complements In this file we prove the Schur-Zassenhaus theorem for abelian normal subgroups. ## Main results - `exists_right_complement_of_coprime` : **Schur-Zassenhaus** for abelian normal subgroups: If `H : subgroup G` is abelian, normal, and has order coprime to its index, then there exists a subgroup `K` which is a (right) complement of `H`. - `exists_left_complement_of_coprime` : **Schur-Zassenhaus** for abelian normal subgroups: If `H : subgroup G` is abelian, normal, and has order coprime to its index, then there exists a subgroup `K` which is a (left) complement of `H`. -/ open_locale big_operators namespace subgroup variables {G : Type*} [group G] {H : subgroup G} @[to_additive] instance : mul_action G (left_transversals (H : set G)) := { smul := λ g T, ⟨left_coset g T, mem_left_transversals_iff_exists_unique_inv_mul_mem.mpr (λ g', by { obtain ⟨t, ht1, ht2⟩ := mem_left_transversals_iff_exists_unique_inv_mul_mem.mp T.2 (g⁻¹ * g'), simp_rw [←mul_assoc, ←mul_inv_rev] at ht1 ht2, refine ⟨⟨g * t, mem_left_coset g t.2⟩, ht1, _⟩, rintros ⟨_, t', ht', rfl⟩ h, exact subtype.ext ((mul_right_inj g).mpr (subtype.ext_iff.mp (ht2 ⟨t', ht'⟩ h))) })⟩, one_smul := λ T, subtype.ext (one_left_coset T), mul_smul := λ g g' T, subtype.ext (left_coset_assoc ↑T g g').symm } lemma smul_symm_apply_eq_mul_symm_apply_inv_smul (g : G) (α : left_transversals (H : set G)) (q : quotient_group.quotient H) : ↑((equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp (g • α).2)).symm q) = g * ((equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)).symm (g⁻¹ • q : quotient_group.quotient H)) := begin let w := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)), let y := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp (g • α).2)), change ↑(y.symm q) = ↑(⟨_, mem_left_coset g (subtype.mem _)⟩ : (g • α).1), refine subtype.ext_iff.mp (y.symm_apply_eq.mpr _), change q = g • (w (w.symm (g⁻¹ • q : quotient_group.quotient H))), rw [equiv.apply_symm_apply, ←mul_smul, mul_inv_self, one_smul], end variables [is_commutative H] [fintype (quotient_group.quotient H)] variables (α β γ : left_transversals (H : set G)) /-- The difference of two left transversals -/ @[to_additive "The difference of two left transversals"] noncomputable def diff [hH : normal H] : H := let α' := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp α.2)).symm, β' := (equiv.of_bijective _ (mem_left_transversals_iff_bijective.mp β.2)).symm in ∏ (q : quotient_group.quotient H), ⟨(α' q) * (β' q)⁻¹, hH.mem_comm (quotient.exact' ((β'.symm_apply_apply q).trans (α'.symm_apply_apply q).symm))⟩ @[to_additive] lemma diff_mul_diff [normal H] : diff α β * diff β γ = diff α γ := finset.prod_mul_distrib.symm.trans (finset.prod_congr rfl (λ x hx, subtype.ext (by rw [coe_mul, coe_mk, coe_mk, coe_mk, mul_assoc, inv_mul_cancel_left]))) @[to_additive] lemma diff_self [normal H] : diff α α = 1 := mul_right_eq_self.mp (diff_mul_diff α α α) @[to_additive] lemma diff_inv [normal H]: (diff α β)⁻¹ = diff β α := inv_eq_of_mul_eq_one ((diff_mul_diff α β α).trans (diff_self α)) lemma smul_diff_smul [hH : normal H] (g : G) : diff (g • α) (g • β) = ⟨g * diff α β * g⁻¹, hH.conj_mem (diff α β).1 (diff α β).2 g⟩ := begin let ϕ : H →* H := { to_fun := λ h, ⟨g * h * g⁻¹, hH.conj_mem h.1 h.2 g⟩, map_one' := subtype.ext (by rw [coe_mk, coe_one, mul_one, mul_inv_self]), map_mul' := λ h₁ h₂, subtype.ext (by rw [coe_mk, coe_mul, coe_mul, coe_mk, coe_mk, mul_assoc, mul_assoc, mul_assoc, mul_assoc, mul_assoc, inv_mul_cancel_left]) }, refine eq.trans (finset.prod_bij' (λ q _, (↑g)⁻¹ * q) (λ _ _, finset.mem_univ _) (λ q _, subtype.ext _) (λ q _, ↑g * q) (λ _ _, finset.mem_univ _) (λ q _, mul_inv_cancel_left g q) (λ q _, inv_mul_cancel_left g q)) (ϕ.map_prod _ _).symm, change _ * _ = g * (_ * _) * g⁻¹, simp_rw [smul_symm_apply_eq_mul_symm_apply_inv_smul, mul_inv_rev, mul_assoc], refl, end lemma smul_diff [H.normal] (h : H) : diff (h • α) β = h ^ H.index * diff α β := begin rw [diff, diff, index_eq_card, ←finset.card_univ, ←finset.prod_const, ←finset.prod_mul_distrib], refine finset.prod_congr rfl (λ q _, _), rw [subtype.ext_iff, coe_mul, coe_mk, coe_mk, ←mul_assoc, mul_right_cancel_iff], rw [show h • α = (h : G) • α, from rfl, smul_symm_apply_eq_mul_symm_apply_inv_smul], rw [mul_left_cancel_iff, ←subtype.ext_iff, equiv.apply_eq_iff_eq, inv_smul_eq_iff], exact self_eq_mul_left.mpr ((quotient_group.eq_one_iff _).mpr h.2), end variables (H) instance setoid_diff [H.normal] : setoid (left_transversals (H : set G)) := setoid.mk (λ α β, diff α β = 1) ⟨λ α, diff_self α, λ α β h₁, by rw [←diff_inv, h₁, one_inv], λ α β γ h₁ h₂, by rw [←diff_mul_diff, h₁, h₂, one_mul]⟩ /-- The quotient of the transversals of an abelian normal `N` by the `diff` relation -/ def quotient_diff [H.normal] := quotient H.setoid_diff instance [H.normal] : inhabited H.quotient_diff := quotient.inhabited variables {H} instance [H.normal] : mul_action G H.quotient_diff := { smul := λ g, quotient.map (λ α, g • α) (λ α β h, (smul_diff_smul α β g).trans (subtype.ext (mul_inv_eq_one.mpr (mul_right_eq_self.mpr (subtype.ext_iff.mp h))))), mul_smul := λ g₁ g₂ q, quotient.induction_on q (λ α, congr_arg quotient.mk (mul_smul g₁ g₂ α)), one_smul := λ q, quotient.induction_on q (λ α, congr_arg quotient.mk (one_smul G α)) } variables [fintype H] lemma exists_smul_eq [H.normal] (α β : H.quotient_diff) (hH : nat.coprime (fintype.card H) H.index) : ∃ h : H, h • α = β := quotient.induction_on α (quotient.induction_on β (λ β α, exists_imp_exists (λ n, quotient.sound) ⟨(pow_coprime hH).symm (diff α β)⁻¹, by { change diff ((_ : H) • _) _ = 1, rw smul_diff, change pow_coprime hH ((pow_coprime hH).symm (diff α β)⁻¹) * (diff α β) = 1, rw [equiv.apply_symm_apply, inv_mul_self] }⟩)) lemma smul_left_injective [H.normal] (α : H.quotient_diff) (hH : nat.coprime (fintype.card H) H.index) : function.injective (λ h : H, h • α) := λ h₁ h₂, begin refine quotient.induction_on α (λ α hα, _), replace hα : diff (h₁ • α) (h₂ • α) = 1 := quotient.exact hα, rw [smul_diff, ←diff_inv, smul_diff, diff_self, mul_one, mul_inv_eq_one] at hα, exact (pow_coprime hH).injective hα, end lemma is_complement'_stabilizer_of_coprime [fintype G] [H.normal] {α : H.quotient_diff} (hH : nat.coprime (fintype.card H) H.index) : is_complement' H (mul_action.stabilizer G α) := begin classical, let ϕ : H ≃ mul_action.orbit G α := equiv.of_bijective (λ h, ⟨h • α, h, rfl⟩) ⟨λ h₁ h₂ hh, smul_left_injective α hH (subtype.ext_iff.mp hh), λ β, exists_imp_exists (λ h hh, subtype.ext hh) (exists_smul_eq α β hH)⟩, have key := card_eq_card_quotient_mul_card_subgroup (mul_action.stabilizer G α), rw ← fintype.card_congr (ϕ.trans (mul_action.orbit_equiv_quotient_stabilizer G α)) at key, apply is_complement'_of_coprime key.symm, rw [card_eq_card_quotient_mul_card_subgroup H, mul_comm, mul_right_inj'] at key, { rwa [←key, ←index_eq_card] }, { rw [←pos_iff_ne_zero, fintype.card_pos_iff], apply_instance }, end /-- **Schur-Zassenhaus** for abelian normal subgroups: If `H : subgroup G` is abelian, normal, and has order coprime to its index, then there exists a subgroup `K` which is a (right) complement of `H`. -/ theorem exists_right_complement'_of_coprime [fintype G] [H.normal] (hH : nat.coprime (fintype.card H) H.index) : ∃ K : subgroup G, is_complement' H K := nonempty_of_inhabited.elim (λ α : H.quotient_diff, ⟨mul_action.stabilizer G α, is_complement'_stabilizer_of_coprime hH⟩) /-- **Schur-Zassenhaus** for abelian normal subgroups: If `H : subgroup G` is abelian, normal, and has order coprime to its index, then there exists a subgroup `K` which is a (left) complement of `H`. -/ theorem exists_left_complement'_of_coprime [fintype G] [H.normal] (hH : nat.coprime (fintype.card H) H.index) : ∃ K : subgroup G, is_complement' K H := Exists.imp (λ _, is_complement'.symm) (exists_right_complement'_of_coprime hH) end subgroup
7bd58453d1e4dfbad14db0fcf91fd6abb4eabf9b
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Data/List/Control.lean
fb9e329f358d4e02577185fc5c9d6202dcdd98a1
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,185
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Control.Monad import Init.Control.Alternative import Init.Data.List.Basic namespace List universes u v w u₁ u₂ /- Remark: we can define `mapM`, `mapM₂` and `forM` using `Applicative` instead of `Monad`. Example: ``` def mapM {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β) | [] => pure [] | a::as => List.cons <$> (f a) <*> mapM as ``` However, we consider `f <$> a <*> b` an anti-idiom because the generated code may produce unnecessary closure allocations. Suppose `m` is a `Monad`, and it uses the default implementation for `Applicative.seq`. Then, the compiler expands `f <$> a <*> b <*> c` into something equivalent to ``` (Functor.map f a >>= fun g_1 => Functor.map g_1 b) >>= fun g_2 => Functor.map g_2 c ``` In an ideal world, the compiler may eliminate the temporary closures `g_1` and `g_2` after it inlines `Functor.map` and `Monad.bind`. However, this can easily fail. For example, suppose `Functor.map f a >>= fun g_1 => Functor.map g_1 b` expanded into a match-expression. This is not unreasonable and can happen in many different ways, e.g., we are using a monad that may throw exceptions. Then, the compiler has to decide whether it will create a join-point for the continuation of the match or float it. If the compiler decides to float, then it will be able to eliminate the closures, but it may not be feasible since floating match expressions may produce exponential blowup in the code size. Finally, we rarely use `mapM` with something that is not a `Monad`. Users that want to use `mapM` with `Applicative` should use `mapA` instead. -/ @[specialize] def mapM {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β) | [] => pure [] | a::as => do b ← f a; bs ← mapM as; pure (b :: bs) @[specialize] def mapM₂ {m : Type u → Type v} [Monad m] {α : Type u₁} {β : Type u₂} {γ : Type u} (f : α → β → m γ) : List α → List β → m (List γ) | a::as, b::bs => do c ← f a b; cs ← mapM₂ as bs; pure (c :: cs) | _, _ => pure [] @[specialize] def mapA {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m (List β) | [] => pure [] | a::as => List.cons <$> f a <*> mapA as @[specialize] def mapA₂ {m : Type u → Type v} [Applicative m] {α : Type u₁} {β : Type u₂} {γ : Type u} (f : α → β → m γ) : List α → List β → m (List γ) | a::as, b::bs => List.cons <$> f a b <*> mapA₂ as bs | _, _ => pure [] @[specialize] def forM {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m β) : List α → m PUnit | [] => pure ⟨⟩ | h :: t => do f h; forM t @[specialize] def forM₂ {m : Type u → Type v} [Monad m] {α : Type u₁} {β : Type u₂} {γ : Type u} (f : α → β → m γ) : List α → List β → m PUnit | a::as, b::bs => do f a b; forM₂ as bs | _, _ => pure ⟨⟩ @[specialize] def forA {m : Type u → Type v} [Applicative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m PUnit | [] => pure ⟨⟩ | h :: t => f h *> forA t @[specialize] def forA₂ {m : Type u → Type v} [Applicative m] {α : Type u₁} {β : Type u₂} {γ : Type u} (f : α → β → m γ) : List α → List β → m PUnit | a::as, b::bs => f a b *> forA₂ as bs | _, _ => pure ⟨⟩ @[specialize] def filterAuxM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) : List α → List α → m (List α) | [], acc => pure acc | h :: t, acc => do b ← f h; filterAuxM t (cond b (h :: acc) acc) @[inline] def filterM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) := do as ← filterAuxM f as []; pure as.reverse @[inline] def filterRevM {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) (as : List α) : m (List α) := filterAuxM f as.reverse [] @[specialize] def foldlM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (s → α → m s) → s → List α → m s | f, s, [] => pure s | f, s, h :: r => do s' ← f s h; foldlM f s' r @[specialize] def foldrM {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} : (α → s → m s) → s → List α → m s | f, s, [] => pure s | f, s, h :: r => do s' ← foldrM f s r; f h s' @[specialize] def firstM {m : Type u → Type v} [Monad m] [Alternative m] {α : Type w} {β : Type u} (f : α → m β) : List α → m β | [] => failure | a::as => f a <|> firstM as @[specialize] def anyM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool | [] => pure false | a::as => do b ← f a; match b with | true => pure true | false => anyM as @[specialize] def allM {m : Type → Type u} [Monad m] {α : Type v} (f : α → m Bool) : List α → m Bool | [] => pure true | a::as => do b ← f a; match b with | true => allM as | false => pure false end List
bb407b7dc9139f61dd6042b1f7e3aa098e58356f
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/lp_space.lean
3475758e81576870e5264ddb716ed1ab7442e3fd
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
97,621
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import analysis.normed_space.indicator_function import analysis.normed_space.normed_group_hom import measure_theory.ess_sup import measure_theory.ae_eq_fun import measure_theory.mean_inequalities import topology.continuous_function.compact /-! # ℒp space and Lp space This file describes properties of almost everywhere measurable functions with finite seminorm, denoted by `snorm f p μ` and defined for `p:ℝ≥0∞` as `0` if `p=0`, `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and `ess_sup ∥f∥ μ` for `p=∞`. The Prop-valued `mem_ℒp f p μ` states that a function `f : α → E` has finite seminorm. The space `Lp E p μ` is the subtype of elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. For `1 ≤ p`, `snorm` defines a norm and `Lp` is a complete metric space. ## Main definitions * `snorm' f p μ` : `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `f : α → F` and `p : ℝ`, where `α` is a measurable space and `F` is a normed group. * `snorm_ess_sup f μ` : seminorm in `ℒ∞`, equal to the essential supremum `ess_sup ∥f∥ μ`. * `snorm f p μ` : for `p : ℝ≥0∞`, seminorm in `ℒp`, equal to `0` for `p=0`, to `snorm' f p μ` for `0 < p < ∞` and to `snorm_ess_sup f μ` for `p = ∞`. * `mem_ℒp f p μ` : property that the function `f` is almost everywhere measurable and has finite p-seminorm for measure `μ` (`snorm f p μ < ∞`) * `Lp E p μ` : elements of `α →ₘ[μ] E` (see ae_eq_fun) such that `snorm f p μ` is finite. Defined as an `add_subgroup` of `α →ₘ[μ] E`. Lipschitz functions vanishing at zero act by composition on `Lp`. We define this action, and prove that it is continuous. In particular, * `continuous_linear_map.comp_Lp` defines the action on `Lp` of a continuous linear map. * `Lp.pos_part` is the positive part of an `Lp` function. * `Lp.neg_part` is the negative part of an `Lp` function. When `α` is a topological space equipped with a finite Borel measure, there is a bounded linear map from the normed space of bounded continuous functions (`α →ᵇ E`) to `Lp E p μ`. We construct this as `bounded_continuous_function.to_Lp`. ## Notations * `α →₁[μ] E` : the type `Lp E 1 μ`. * `α →₂[μ] E` : the type `Lp E 2 μ`. ## Implementation Since `Lp` is defined as an `add_subgroup`, dot notation does not work. Use `Lp.measurable f` to say that the coercion of `f` to a genuine function is measurable, instead of the non-working `f.measurable`. To prove that two `Lp` elements are equal, it suffices to show that their coercions to functions coincide almost everywhere (this is registered as an `ext` rule). This can often be done using `filter_upwards`. For instance, a proof from first principles that `f + (g + h) = (f + g) + h` could read (in the `Lp` namespace) ``` example (f g h : Lp E p μ) : (f + g) + h = f + (g + h) := begin ext1, filter_upwards [coe_fn_add (f + g) h, coe_fn_add f g, coe_fn_add f (g + h), coe_fn_add g h], assume a ha1 ha2 ha3 ha4, simp only [ha1, ha2, ha3, ha4, add_assoc], end ``` The lemma `coe_fn_add` states that the coercion of `f + g` coincides almost everywhere with the sum of the coercions of `f` and `g`. All such lemmas use `coe_fn` in their name, to distinguish the function coercion from the coercion to almost everywhere defined functions. -/ noncomputable theory open topological_space measure_theory filter open_locale nnreal ennreal big_operators topological_space lemma fact_one_le_one_ennreal : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_refl _⟩ lemma fact_one_le_two_ennreal : fact ((1 : ℝ≥0∞) ≤ 2) := ⟨ennreal.coe_le_coe.2 (show (1 : ℝ≥0) ≤ 2, by norm_num)⟩ lemma fact_one_le_top_ennreal : fact ((1 : ℝ≥0∞) ≤ ∞) := ⟨le_top⟩ local attribute [instance] fact_one_le_one_ennreal fact_one_le_two_ennreal fact_one_le_top_ennreal variables {α E F G : Type*} [measurable_space α] {p : ℝ≥0∞} {q : ℝ} {μ : measure α} [measurable_space E] [normed_group E] [normed_group F] [normed_group G] namespace measure_theory section ℒp /-! ### ℒp seminorm We define the ℒp seminorm, denoted by `snorm f p μ`. For real `p`, it is given by an integral formula (for which we use the notation `snorm' f p μ`), and for `p = ∞` it is the essential supremum (for which we use the notation `snorm_ess_sup f μ`). We also define a predicate `mem_ℒp f p μ`, requesting that a function is almost everywhere measurable and has finite `snorm f p μ`. This paragraph is devoted to the basic properties of these definitions. It is constructed as follows: for a given property, we prove it for `snorm'` and `snorm_ess_sup` when it makes sense, deduce it for `snorm`, and translate it in terms of `mem_ℒp`. -/ section ℒp_space_definition /-- `(∫ ∥f a∥^q ∂μ) ^ (1/q)`, which is a seminorm on the space of measurable functions for which this quantity is finite -/ def snorm' (f : α → F) (q : ℝ) (μ : measure α) : ℝ≥0∞ := (∫⁻ a, (nnnorm (f a))^q ∂μ) ^ (1/q) /-- seminorm for `ℒ∞`, equal to the essential supremum of `∥f∥`. -/ def snorm_ess_sup (f : α → F) (μ : measure α) := ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) μ /-- `ℒp` seminorm, equal to `0` for `p=0`, to `(∫ ∥f a∥^p ∂μ) ^ (1/p)` for `0 < p < ∞` and to `ess_sup ∥f∥ μ` for `p = ∞`. -/ def snorm (f : α → F) (p : ℝ≥0∞) (μ : measure α) : ℝ≥0∞ := if p = 0 then 0 else (if p = ∞ then snorm_ess_sup f μ else snorm' f (ennreal.to_real p) μ) lemma snorm_eq_snorm' (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} : snorm f p μ = snorm' f (ennreal.to_real p) μ := by simp [snorm, hp_ne_zero, hp_ne_top] lemma snorm_eq_lintegral_rpow_nnnorm (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) {f : α → F} : snorm f p μ = (∫⁻ x, (nnnorm (f x)) ^ p.to_real ∂μ) ^ (1 / p.to_real) := by rw [snorm_eq_snorm' hp_ne_zero hp_ne_top, snorm'] lemma snorm_one_eq_lintegral_nnnorm {f : α → F} : snorm f 1 μ = ∫⁻ x, nnnorm (f x) ∂μ := by simp_rw [snorm_eq_lintegral_rpow_nnnorm one_ne_zero ennreal.coe_ne_top, ennreal.one_to_real, one_div_one, ennreal.rpow_one] @[simp] lemma snorm_exponent_top {f : α → F} : snorm f ∞ μ = snorm_ess_sup f μ := by simp [snorm] /-- The property that `f:α→E` is ae_measurable and `(∫ ∥f a∥^p ∂μ)^(1/p)` is finite if `p < ∞`, or `ess_sup f < ∞` if `p = ∞`. -/ def mem_ℒp (f : α → E) (p : ℝ≥0∞) (μ : measure α) : Prop := ae_measurable f μ ∧ snorm f p μ < ∞ lemma mem_ℒp.ae_measurable {f : α → E} {p : ℝ≥0∞} {μ : measure α} (h : mem_ℒp f p μ) : ae_measurable f μ := h.1 lemma lintegral_rpow_nnnorm_eq_rpow_snorm' {f : α → F} (hq0_lt : 0 < q) : ∫⁻ a, (nnnorm (f a)) ^ q ∂μ = (snorm' f q μ) ^ q := begin rw [snorm', ←ennreal.rpow_mul, one_div, inv_mul_cancel, ennreal.rpow_one], exact (ne_of_lt hq0_lt).symm, end end ℒp_space_definition section top lemma mem_ℒp.snorm_lt_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ < ∞ := hfp.2 lemma mem_ℒp.snorm_ne_top {f : α → E} (hfp : mem_ℒp f p μ) : snorm f p μ ≠ ∞ := ne_of_lt (hfp.2) lemma lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top {f : α → F} (hq0_lt : 0 < q) (hfq : snorm' f q μ < ∞) : ∫⁻ a, (nnnorm (f a)) ^ q ∂μ < ∞ := begin rw lintegral_rpow_nnnorm_eq_rpow_snorm' hq0_lt, exact ennreal.rpow_lt_top_of_nonneg (le_of_lt hq0_lt) (ne_of_lt hfq), end lemma lintegral_rpow_nnnorm_lt_top_of_snorm_lt_top {f : α → F} (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hfp : snorm f p μ < ∞) : ∫⁻ a, (nnnorm (f a)) ^ p.to_real ∂μ < ∞ := begin apply lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top, { exact ennreal.to_real_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr hp_ne_zero, hp_ne_top⟩ }, { simpa [snorm_eq_snorm' hp_ne_zero hp_ne_top] using hfp } end lemma snorm_lt_top_iff_lintegral_rpow_nnnorm_lt_top {f : α → F} (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : snorm f p μ < ∞ ↔ ∫⁻ a, (nnnorm (f a)) ^ p.to_real ∂μ < ∞ := ⟨lintegral_rpow_nnnorm_lt_top_of_snorm_lt_top hp_ne_zero hp_ne_top, begin intros h, have hp' := ennreal.to_real_pos_iff.mpr ⟨bot_lt_iff_ne_bot.mpr hp_ne_zero, hp_ne_top⟩, have : 0 < 1 / p.to_real := div_pos zero_lt_one hp', simpa [snorm_eq_lintegral_rpow_nnnorm hp_ne_zero hp_ne_top] using ennreal.rpow_lt_top_of_nonneg (le_of_lt this) (ne_of_lt h) end⟩ end top section zero @[simp] lemma snorm'_exponent_zero {f : α → F} : snorm' f 0 μ = 1 := by rw [snorm', div_zero, ennreal.rpow_zero] @[simp] lemma snorm_exponent_zero {f : α → F} : snorm f 0 μ = 0 := by simp [snorm] lemma mem_ℒp_zero_iff_ae_measurable {f : α → E} : mem_ℒp f 0 μ ↔ ae_measurable f μ := by simp [mem_ℒp, snorm_exponent_zero] @[simp] lemma snorm'_zero (hp0_lt : 0 < q) : snorm' (0 : α → F) q μ = 0 := by simp [snorm', hp0_lt] @[simp] lemma snorm'_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) : snorm' (0 : α → F) q μ = 0 := begin cases le_or_lt 0 q with hq0 hq_neg, { exact snorm'_zero (lt_of_le_of_ne hq0 hq0_ne.symm), }, { simp [snorm', ennreal.rpow_eq_zero_iff, hμ, hq_neg], }, end @[simp] lemma snorm_ess_sup_zero : snorm_ess_sup (0 : α → F) μ = 0 := begin simp_rw [snorm_ess_sup, pi.zero_apply, nnnorm_zero, ennreal.coe_zero, ←ennreal.bot_eq_zero], exact ess_sup_const_bot, end @[simp] lemma snorm_zero : snorm (0 : α → F) p μ = 0 := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp only [h_top, snorm_exponent_top, snorm_ess_sup_zero], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma zero_mem_ℒp : mem_ℒp (0 : α → E) p μ := ⟨measurable_zero.ae_measurable, by { rw snorm_zero, exact ennreal.coe_lt_top, } ⟩ lemma snorm'_measure_zero_of_pos {f : α → F} (hq_pos : 0 < q) : snorm' f q 0 = 0 := by simp [snorm', hq_pos] lemma snorm'_measure_zero_of_exponent_zero {f : α → F} : snorm' f 0 0 = 1 := by simp [snorm'] lemma snorm'_measure_zero_of_neg {f : α → F} (hq_neg : q < 0) : snorm' f q 0 = ∞ := by simp [snorm', hq_neg] @[simp] lemma snorm_ess_sup_measure_zero {f : α → F} : snorm_ess_sup f 0 = 0 := by simp [snorm_ess_sup] @[simp] lemma snorm_measure_zero {f : α → F} : snorm f p 0 = 0 := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top], }, rw ←ne.def at h0, simp [snorm_eq_snorm' h0 h_top, snorm', ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end end zero section const lemma snorm'_const (c : F) (hq_pos : 0 < q) : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) := begin rw [snorm', lintegral_const, ennreal.mul_rpow_of_nonneg _ _ (by simp [hq_pos.le] : 0 ≤ 1 / q)], congr, rw ←ennreal.rpow_mul, suffices hq_cancel : q * (1/q) = 1, by rw [hq_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel (ne_of_lt hq_pos).symm], end lemma snorm'_const' [finite_measure μ] (c : F) (hc_ne_zero : c ≠ 0) (hq_ne_zero : q ≠ 0) : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/q) := begin rw [snorm', lintegral_const, ennreal.mul_rpow_of_ne_top _ (measure_ne_top μ set.univ)], { congr, rw ←ennreal.rpow_mul, suffices hp_cancel : q * (1/q) = 1, by rw [hp_cancel, ennreal.rpow_one], rw [one_div, mul_inv_cancel hq_ne_zero], }, { rw [ne.def, ennreal.rpow_eq_top_iff, auto.not_or_eq, auto.not_and_eq, auto.not_and_eq], split, { left, rwa [ennreal.coe_eq_zero, nnnorm_eq_zero], }, { exact or.inl ennreal.coe_ne_top, }, }, end lemma snorm_ess_sup_const (c : F) (hμ : μ ≠ 0) : snorm_ess_sup (λ x : α, c) μ = (nnnorm c : ℝ≥0∞) := by rw [snorm_ess_sup, ess_sup_const _ hμ] lemma snorm'_const_of_probability_measure (c : F) (hq_pos : 0 < q) [probability_measure μ] : snorm' (λ x : α , c) q μ = (nnnorm c : ℝ≥0∞) := by simp [snorm'_const c hq_pos, measure_univ] lemma snorm_const (c : F) (h0 : p ≠ 0) (hμ : μ ≠ 0) : snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) := begin by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup_const c hμ], }, simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma snorm_const' (c : F) (h0 : p ≠ 0) (h_top: p ≠ ∞) : snorm (λ x : α , c) p μ = (nnnorm c : ℝ≥0∞) * (μ set.univ) ^ (1/(ennreal.to_real p)) := begin simp [snorm_eq_snorm' h0 h_top, snorm'_const, ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩], end lemma mem_ℒp_const (c : E) [finite_measure μ] : mem_ℒp (λ a:α, c) p μ := begin refine ⟨measurable_const.ae_measurable, _⟩, by_cases h0 : p = 0, { simp [h0], }, by_cases hμ : μ = 0, { simp [hμ], }, rw snorm_const c h0 hμ, refine ennreal.mul_lt_top ennreal.coe_lt_top _, refine ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ), simp, end end const lemma snorm'_mono_ae {f : α → F} {g : α → G} (hq : 0 ≤ q) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : snorm' f q μ ≤ snorm' g q μ := begin rw [snorm'], refine ennreal.rpow_le_rpow _ (one_div_nonneg.2 hq), refine lintegral_mono_ae (h.mono $ λ x hx, _), exact ennreal.rpow_le_rpow (ennreal.coe_le_coe.2 hx) hq end lemma snorm'_congr_norm_ae {f g : α → F} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) : snorm' f q μ = snorm' g q μ := begin have : (λ x, (nnnorm (f x) ^ q : ℝ≥0∞)) =ᵐ[μ] (λ x, nnnorm (g x) ^ q), from hfg.mono (λ x hx, by { simp only [← coe_nnnorm, nnreal.coe_eq] at hx, simp [hx] }), simp only [snorm', lintegral_congr_ae this] end lemma snorm'_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm' f q μ = snorm' g q μ := snorm'_congr_norm_ae (hfg.fun_comp _) lemma snorm_ess_sup_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm_ess_sup f μ = snorm_ess_sup g μ := ess_sup_congr_ae (hfg.fun_comp (coe ∘ nnnorm)) lemma snorm_mono_ae {f : α → F} {g : α → G} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : snorm f p μ ≤ snorm g p μ := begin simp only [snorm], split_ifs, { exact le_rfl }, { refine ess_sup_mono_ae (h.mono $ λ x hx, _), exact_mod_cast hx }, { exact snorm'_mono_ae ennreal.to_real_nonneg h } end lemma snorm_ess_sup_le_of_ae_bound {f : α → F} {C : ℝ} (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : snorm_ess_sup f μ ≤ ennreal.of_real C:= begin simp_rw [snorm_ess_sup, ← of_real_norm_eq_coe_nnnorm], refine ess_sup_le_of_ae_le (ennreal.of_real C) (hfC.mono (λ x hx, _)), exact ennreal.of_real_le_of_real hx, end lemma snorm_ess_sup_lt_top_of_ae_bound {f : α → F} {C : ℝ} (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : snorm_ess_sup f μ < ∞ := (snorm_ess_sup_le_of_ae_bound hfC).trans_lt ennreal.of_real_lt_top lemma snorm_le_of_ae_bound {f : α → F} {C : ℝ} (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : snorm f p μ ≤ ((μ set.univ) ^ p.to_real⁻¹) * (ennreal.of_real C) := begin by_cases hμ : μ = 0, { simp [hμ] }, haveI : μ.ae.ne_bot := ae_ne_bot.mpr hμ, by_cases hp : p = 0, { simp [hp] }, have hC : 0 ≤ C, from le_trans (norm_nonneg _) hfC.exists.some_spec, have hC' : ∥C∥ = C := by rw [real.norm_eq_abs, abs_eq_self.mpr hC], have : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥(λ _, C) x∥, from hfC.mono (λ x hx, hx.trans (le_of_eq hC'.symm)), convert snorm_mono_ae this, rw [snorm_const _ hp hμ, mul_comm, ← of_real_norm_eq_coe_nnnorm, hC', one_div] end lemma snorm_congr_norm_ae {f : α → F} {g : α → G} (hfg : ∀ᵐ x ∂μ, ∥f x∥ = ∥g x∥) : snorm f p μ = snorm g p μ := le_antisymm (snorm_mono_ae $ eventually_eq.le hfg) (snorm_mono_ae $ (eventually_eq.symm hfg).le) @[simp] lemma snorm'_norm {f : α → F} : snorm' (λ a, ∥f a∥) q μ = snorm' f q μ := by simp [snorm'] @[simp] lemma snorm_norm (f : α → F) : snorm (λ x, ∥f x∥) p μ = snorm f p μ := snorm_congr_norm_ae $ eventually_of_forall $ λ x, norm_norm _ lemma snorm'_norm_rpow (f : α → F) (p q : ℝ) (hq_pos : 0 < q) : snorm' (λ x, ∥f x∥ ^ q) p μ = (snorm' f (p * q) μ) ^ q := begin simp_rw snorm', rw [← ennreal.rpow_mul, ←one_div_mul_one_div], simp_rw one_div, rw [mul_assoc, inv_mul_cancel hq_pos.ne.symm, mul_one], congr, ext1 x, simp_rw ← of_real_norm_eq_coe_nnnorm, rw [real.norm_eq_abs, abs_eq_self.mpr (real.rpow_nonneg_of_nonneg (norm_nonneg _) _), mul_comm, ← ennreal.of_real_rpow_of_nonneg (norm_nonneg _) hq_pos.le, ennreal.rpow_mul], end lemma snorm_norm_rpow (f : α → F) (hq_pos : 0 < q) : snorm (λ x, ∥f x∥ ^ q) p μ = (snorm f (p * ennreal.of_real q) μ) ^ q := begin by_cases h0 : p = 0, { simp [h0, ennreal.zero_rpow_of_pos hq_pos], }, by_cases hp_top : p = ∞, { simp only [hp_top, snorm_exponent_top, ennreal.top_mul, hq_pos.not_le, ennreal.of_real_eq_zero, if_false, snorm_exponent_top, snorm_ess_sup], have h_rpow : ess_sup (λ (x : α), (nnnorm (∥f x∥ ^ q) : ℝ≥0∞)) μ = ess_sup (λ (x : α), (↑(nnnorm (f x))) ^ q) μ, { congr, ext1 x, nth_rewrite 1 ← nnnorm_norm, rw [ennreal.coe_rpow_of_nonneg _ hq_pos.le, ennreal.coe_eq_coe], ext, push_cast, rw real.norm_rpow_of_nonneg (norm_nonneg _), }, rw h_rpow, have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hq_pos, have h_rpow_surj := (ennreal.rpow_left_bijective hq_pos.ne.symm).2, let iso := h_rpow_mono.order_iso_of_surjective _ h_rpow_surj, exact (iso.ess_sup_apply (λ x, ((nnnorm (f x)) : ℝ≥0∞)) μ).symm, }, rw [snorm_eq_snorm' h0 hp_top, snorm_eq_snorm' _ _], swap, { refine mul_ne_zero h0 _, rwa [ne.def, ennreal.of_real_eq_zero, not_le], }, swap, { exact ennreal.mul_ne_top hp_top ennreal.of_real_ne_top, }, rw [ennreal.to_real_mul, ennreal.to_real_of_real hq_pos.le], exact snorm'_norm_rpow f p.to_real q hq_pos, end lemma snorm_congr_ae {f g : α → F} (hfg : f =ᵐ[μ] g) : snorm f p μ = snorm g p μ := snorm_congr_norm_ae $ hfg.mono (λ x hx, hx ▸ rfl) lemma mem_ℒp_congr_ae {f g : α → E} (hfg : f =ᵐ[μ] g) : mem_ℒp f p μ ↔ mem_ℒp g p μ := by simp only [mem_ℒp, snorm_congr_ae hfg, ae_measurable_congr hfg] lemma mem_ℒp.ae_eq {f g : α → E} (hfg : f =ᵐ[μ] g) (hf_Lp : mem_ℒp f p μ) : mem_ℒp g p μ := (mem_ℒp_congr_ae hfg).1 hf_Lp lemma mem_ℒp.of_le [measurable_space F] {f : α → E} {g : α → F} (hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : mem_ℒp f p μ := ⟨hf, (snorm_mono_ae hfg).trans_lt hg.snorm_lt_top⟩ lemma mem_ℒp_top_of_bound {f : α → E} (hf : ae_measurable f μ) (C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : mem_ℒp f ∞ μ := ⟨hf, by { rw snorm_exponent_top, exact snorm_ess_sup_lt_top_of_ae_bound hfC, }⟩ lemma mem_ℒp.of_bound [finite_measure μ] {f : α → E} (hf : ae_measurable f μ) (C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : mem_ℒp f p μ := (mem_ℒp_const C).of_le hf (hfC.mono (λ x hx, le_trans hx (le_abs_self _))) @[mono] lemma snorm'_mono_measure {μ ν : measure α} (f : α → F) (hμν : ν ≤ μ) (hq : 0 ≤ q) : snorm' f q ν ≤ snorm' f q μ := begin simp_rw snorm', suffices h_integral_mono : (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q ∂ν) ≤ ∫⁻ a, (nnnorm (f a)) ^ q ∂μ, from ennreal.rpow_le_rpow h_integral_mono (by simp [hq]), exact lintegral_mono' hμν le_rfl, end @[mono] lemma snorm_ess_sup_mono_measure {μ ν : measure α} (f : α → F) (hμν : ν ≪ μ) : snorm_ess_sup f ν ≤ snorm_ess_sup f μ := by { simp_rw snorm_ess_sup, exact ess_sup_mono_measure hμν, } @[mono] lemma snorm_mono_measure {μ ν : measure α} (f : α → F) (hμν : ν ≤ μ) : snorm f p ν ≤ snorm f p μ := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hp_top : p = ∞, { simp [hp_top, snorm_ess_sup_mono_measure f (measure.absolutely_continuous_of_le hμν)], }, simp_rw snorm_eq_snorm' hp0 hp_top, exact snorm'_mono_measure f hμν ennreal.to_real_nonneg, end lemma mem_ℒp.mono_measure {μ ν : measure α} {f : α → E} (hμν : ν ≤ μ) (hf : mem_ℒp f p μ) : mem_ℒp f p ν := ⟨hf.1.mono_measure hμν, (snorm_mono_measure f hμν).trans_lt hf.2⟩ lemma mem_ℒp.restrict (s : set α) {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp f p (μ.restrict s) := hf.mono_measure measure.restrict_le_self section opens_measurable_space variable [opens_measurable_space E] lemma mem_ℒp.norm {f : α → E} (h : mem_ℒp f p μ) : mem_ℒp (λ x, ∥f x∥) p μ := h.of_le h.ae_measurable.norm (eventually_of_forall (λ x, by simp)) lemma snorm'_eq_zero_of_ae_zero {f : α → F} (hq0_lt : 0 < q) (hf_zero : f =ᵐ[μ] 0) : snorm' f q μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero hq0_lt] lemma snorm'_eq_zero_of_ae_zero' (hq0_ne : q ≠ 0) (hμ : μ ≠ 0) {f : α → F} (hf_zero : f =ᵐ[μ] 0) : snorm' f q μ = 0 := by rw [snorm'_congr_ae hf_zero, snorm'_zero' hq0_ne hμ] lemma ae_eq_zero_of_snorm'_eq_zero {f : α → E} (hq0 : 0 ≤ q) (hf : ae_measurable f μ) (h : snorm' f q μ = 0) : f =ᵐ[μ] 0 := begin rw [snorm', ennreal.rpow_eq_zero_iff] at h, cases h, { rw lintegral_eq_zero_iff' (hf.ennnorm.pow_const q) at h, refine h.left.mono (λ x hx, _), rw [pi.zero_apply, ennreal.rpow_eq_zero_iff] at hx, cases hx, { cases hx with hx _, rwa [←ennreal.coe_zero, ennreal.coe_eq_coe, nnnorm_eq_zero] at hx, }, { exact absurd hx.left ennreal.coe_ne_top, }, }, { exfalso, rw [one_div, inv_lt_zero] at h, exact hq0.not_lt h.right }, end lemma snorm'_eq_zero_iff (hq0_lt : 0 < q) {f : α → E} (hf : ae_measurable f μ) : snorm' f q μ = 0 ↔ f =ᵐ[μ] 0 := ⟨ae_eq_zero_of_snorm'_eq_zero (le_of_lt hq0_lt) hf, snorm'_eq_zero_of_ae_zero hq0_lt⟩ lemma coe_nnnorm_ae_le_snorm_ess_sup (f : α → F) (μ : measure α) : ∀ᵐ x ∂μ, (nnnorm (f x) : ℝ≥0∞) ≤ snorm_ess_sup f μ := ennreal.ae_le_ess_sup (λ x, (nnnorm (f x) : ℝ≥0∞)) @[simp] lemma snorm_ess_sup_eq_zero_iff {f : α → F} : snorm_ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 := by simp [eventually_eq, snorm_ess_sup] lemma snorm_eq_zero_iff {f : α → E} (hf : ae_measurable f μ) (h0 : p ≠ 0) : snorm f p μ = 0 ↔ f =ᵐ[μ] 0 := begin by_cases h_top : p = ∞, { rw [h_top, snorm_exponent_top, snorm_ess_sup_eq_zero_iff], }, rw snorm_eq_snorm' h0 h_top, exact snorm'_eq_zero_iff (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩) hf, end section trim variables {β : Type*} {m m0 : measurable_space β} {ν : measure β} lemma snorm'_trim (hm : m ≤ m0) {f : β → E} (hf : @measurable _ _ m _ f) : @snorm' β E m _ f q (ν.trim hm) = snorm' f q ν := begin simp_rw snorm', congr' 1, refine lintegral_trim hm _, refine @measurable.pow_const _ _ _ _ _ _ _ m _ (@measurable.coe_nnreal_ennreal _ m _ _) _, exact @measurable.nnnorm E _ _ _ _ m _ hf, end lemma limsup_trim (hm : m ≤ m0) {f : β → ℝ≥0∞} (hf : @measurable _ _ m _ f) : (@measure.ae _ m (ν.trim hm)).limsup f = ν.ae.limsup f := begin simp_rw limsup_eq, suffices h_set_eq : {a : ℝ≥0∞ | filter.eventually (λ n, f n ≤ a) (@measure.ae _ m (ν.trim hm))} = {a : ℝ≥0∞ | ∀ᵐ n ∂ν, f n ≤ a}, by rw h_set_eq, ext1 a, suffices h_meas_eq : ν {x | ¬ f x ≤ a} = ν.trim hm {x | ¬ f x ≤ a}, by simp_rw [set.mem_set_of_eq, ae_iff, h_meas_eq], refine (trim_measurable_set_eq hm _).symm, refine @measurable_set.compl _ _ m (@measurable_set_le ℝ≥0∞ _ _ _ _ m _ _ _ _ _ hf _), exact @measurable_const _ _ _ m _, end lemma ess_sup_trim (hm : m ≤ m0) {f : β → ℝ≥0∞} (hf : @measurable _ _ m _ f) : @ess_sup _ _ m _ f (ν.trim hm) = ess_sup f ν := by { simp_rw ess_sup, exact limsup_trim hm hf, } lemma snorm_ess_sup_trim (hm : m ≤ m0) {f : β → E} (hf : @measurable _ _ m _ f) : @snorm_ess_sup _ E m _ f (ν.trim hm) = snorm_ess_sup f ν := ess_sup_trim hm (@measurable.coe_nnreal_ennreal _ m _ (@measurable.nnnorm E _ _ _ _ m _ hf)) lemma snorm_trim (hm : m ≤ m0) {f : β → E} (hf : @measurable _ _ m _ f) : @snorm _ E m _ f p (ν.trim hm) = snorm f p ν := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simpa only [h_top, snorm_exponent_top] using snorm_ess_sup_trim hm hf, }, simpa only [snorm_eq_snorm' h0 h_top] using snorm'_trim hm hf, end lemma snorm_trim_ae (hm : m ≤ m0) {f : β → E} (hf : @ae_measurable _ _ m _ f (ν.trim hm)) : @snorm _ E m _ f p (ν.trim hm) = snorm f p ν := begin let g := @ae_measurable.mk _ _ m _ _ _ hf, have hg_meas : @measurable _ _ m _ g, from @ae_measurable.measurable_mk _ _ m _ _ _ hf, have hfg := @ae_measurable.ae_eq_mk _ _ m _ _ _ hf, rw @snorm_congr_ae _ _ m _ _ _ _ _ hfg, rw snorm_congr_ae (ae_eq_of_ae_eq_trim hfg), exact snorm_trim hm hg_meas, end lemma mem_ℒp_of_mem_ℒp_trim (hm : m ≤ m0) {f : β → E} (hf : @mem_ℒp _ E m _ _ f p (ν.trim hm)) : mem_ℒp f p ν := ⟨ae_measurable_of_ae_measurable_trim hm hf.1, (le_of_eq (snorm_trim_ae hm hf.1).symm).trans_lt hf.2⟩ end trim end opens_measurable_space @[simp] lemma snorm'_neg {f : α → F} : snorm' (-f) q μ = snorm' f q μ := by simp [snorm'] @[simp] lemma snorm_neg {f : α → F} : snorm (-f) p μ = snorm f p μ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup], }, simp [snorm_eq_snorm' h0 h_top], end section borel_space variable [borel_space E] lemma mem_ℒp.neg {f : α → E} (hf : mem_ℒp f p μ) : mem_ℒp (-f) p μ := ⟨ae_measurable.neg hf.1, by simp [hf.right]⟩ lemma snorm'_le_snorm'_mul_rpow_measure_univ {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) := begin have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq, by_cases hpq_eq : p = q, { rw [hpq_eq, sub_self, ennreal.rpow_zero, mul_one], exact le_refl _, }, have hpq : p < q, from lt_of_le_of_ne hpq hpq_eq, let g := λ a : α, (1 : ℝ≥0∞), have h_rw : ∫⁻ a, ↑(nnnorm (f a))^p ∂ μ = ∫⁻ a, (nnnorm (f a) * (g a))^p ∂ μ, from lintegral_congr (λ a, by simp), repeat {rw snorm'}, rw h_rw, let r := p * q / (q - p), have hpqr : 1/p = 1/q + 1/r, { field_simp [(ne_of_lt hp0_lt).symm, (ne_of_lt hq0_lt).symm], ring, }, calc (∫⁻ (a : α), (↑(nnnorm (f a)) * g a) ^ p ∂μ) ^ (1/p) ≤ (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1/r) : ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hf.ennnorm ae_measurable_const ... = (∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ) ^ (1/q) * μ set.univ ^ (1/p - 1/q) : by simp [hpqr], end lemma snorm'_le_snorm_ess_sup_mul_rpow_measure_univ (hq_pos : 0 < q) {f : α → F} : snorm' f q μ ≤ snorm_ess_sup f μ * (μ set.univ) ^ (1/q) := begin have h_le : ∫⁻ (a : α), ↑(nnnorm (f a)) ^ q ∂μ ≤ ∫⁻ (a : α), (snorm_ess_sup f μ) ^ q ∂μ, { refine lintegral_mono_ae _, have h_nnnorm_le_snorm_ess_sup := coe_nnnorm_ae_le_snorm_ess_sup f μ, refine h_nnnorm_le_snorm_ess_sup.mono (λ x hx, ennreal.rpow_le_rpow hx (le_of_lt hq_pos)), }, rw [snorm', ←ennreal.rpow_one (snorm_ess_sup f μ)], nth_rewrite 1 ←mul_inv_cancel (ne_of_lt hq_pos).symm, rw [ennreal.rpow_mul, one_div, ←ennreal.mul_rpow_of_nonneg _ _ (by simp [hq_pos.le] : 0 ≤ q⁻¹)], refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le]), rwa lintegral_const at h_le, end lemma snorm_le_snorm_mul_rpow_measure_univ {p q : ℝ≥0∞} (hpq : p ≤ q) {f : α → E} (hf : ae_measurable f μ) : snorm f p μ ≤ snorm f q μ * (μ set.univ) ^ (1/p.to_real - 1/q.to_real) := begin by_cases hp0 : p = 0, { simp [hp0, zero_le], }, rw ← ne.def at hp0, have hp0_lt : 0 < p, from lt_of_le_of_ne (zero_le _) hp0.symm, have hq0_lt : 0 < q, from lt_of_lt_of_le hp0_lt hpq, by_cases hq_top : q = ∞, { simp only [hq_top, div_zero, one_div, ennreal.top_to_real, sub_zero, snorm_exponent_top, inv_zero], by_cases hp_top : p = ∞, { simp only [hp_top, ennreal.rpow_zero, mul_one, ennreal.top_to_real, sub_zero, inv_zero, snorm_exponent_top], exact le_rfl, }, rw snorm_eq_snorm' hp0 hp_top, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨hp0_lt, hp_top⟩, refine (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos).trans (le_of_eq _), congr, exact one_div _, }, have hp_lt_top : p < ∞, from hpq.trans_lt (lt_top_iff_ne_top.mpr hq_top), have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨hp0_lt, hp_lt_top.ne⟩, rw [snorm_eq_snorm' hp0_lt.ne.symm hp_lt_top.ne, snorm_eq_snorm' hq0_lt.ne.symm hq_top], have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_lt_top.ne hq_top, exact snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq_real hf, end lemma snorm'_le_snorm'_of_exponent_le {p q : ℝ} (hp0_lt : 0 < p) (hpq : p ≤ q) (μ : measure α) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm' f p μ ≤ snorm' f q μ := begin have h_le_μ := snorm'_le_snorm'_mul_rpow_measure_univ hp0_lt hpq hf, rwa [measure_univ, ennreal.one_rpow, mul_one] at h_le_μ, end lemma snorm'_le_snorm_ess_sup (hq_pos : 0 < q) {f : α → F} [probability_measure μ] : snorm' f q μ ≤ snorm_ess_sup f μ := le_trans (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hq_pos) (le_of_eq (by simp [measure_univ])) lemma snorm_le_snorm_of_exponent_le {p q : ℝ≥0∞} (hpq : p ≤ q) [probability_measure μ] {f : α → E} (hf : ae_measurable f μ) : snorm f p μ ≤ snorm f q μ := (snorm_le_snorm_mul_rpow_measure_univ hpq hf).trans (le_of_eq (by simp [measure_univ])) lemma snorm'_lt_top_of_snorm'_lt_top_of_exponent_le {p q : ℝ} [finite_measure μ] {f : α → E} (hf : ae_measurable f μ) (hfq_lt_top : snorm' f q μ < ∞) (hp_nonneg : 0 ≤ p) (hpq : p ≤ q) : snorm' f p μ < ∞ := begin cases le_or_lt p 0 with hp_nonpos hp_pos, { rw le_antisymm hp_nonpos hp_nonneg, simp, }, have hq_pos : 0 < q, from lt_of_lt_of_le hp_pos hpq, calc snorm' f p μ ≤ snorm' f q μ * (μ set.univ) ^ (1/p - 1/q) : snorm'_le_snorm'_mul_rpow_measure_univ hp_pos hpq hf ... < ∞ : begin rw ennreal.mul_lt_top_iff, refine or.inl ⟨hfq_lt_top, ennreal.rpow_lt_top_of_nonneg _ (measure_ne_top μ set.univ)⟩, rwa [le_sub, sub_zero, one_div, one_div, inv_le_inv hq_pos hp_pos], end end lemma mem_ℒp.mem_ℒp_of_exponent_le {p q : ℝ≥0∞} [finite_measure μ] {f : α → E} (hfq : mem_ℒp f q μ) (hpq : p ≤ q) : mem_ℒp f p μ := begin cases hfq with hfq_m hfq_lt_top, by_cases hp0 : p = 0, { rwa [hp0, mem_ℒp_zero_iff_ae_measurable], }, rw ←ne.def at hp0, refine ⟨hfq_m, _⟩, by_cases hp_top : p = ∞, { have hq_top : q = ∞, by rwa [hp_top, top_le_iff] at hpq, rw [hp_top], rwa hq_top at hfq_lt_top, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, by_cases hq_top : q = ∞, { rw snorm_eq_snorm' hp0 hp_top, rw [hq_top, snorm_exponent_top] at hfq_lt_top, refine lt_of_le_of_lt (snorm'_le_snorm_ess_sup_mul_rpow_measure_univ hp_pos) _, refine ennreal.mul_lt_top hfq_lt_top _, exact ennreal.rpow_lt_top_of_nonneg (by simp [le_of_lt hp_pos]) (measure_ne_top μ set.univ), }, have hq0 : q ≠ 0, { by_contra hq_eq_zero, push_neg at hq_eq_zero, have hp_eq_zero : p = 0, from le_antisymm (by rwa hq_eq_zero at hpq) (zero_le _), rw [hp_eq_zero, ennreal.zero_to_real] at hp_pos, exact (lt_irrefl _) hp_pos, }, have hpq_real : p.to_real ≤ q.to_real, by rwa ennreal.to_real_le_to_real hp_top hq_top, rw snorm_eq_snorm' hp0 hp_top, rw snorm_eq_snorm' hq0 hq_top at hfq_lt_top, exact snorm'_lt_top_of_snorm'_lt_top_of_exponent_le hfq_m hfq_lt_top (le_of_lt hp_pos) hpq_real, end lemma snorm'_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hq1 : 1 ≤ q) : snorm' (f + g) q μ ≤ snorm' f q μ + snorm' g q μ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞)) + (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) : begin refine ennreal.rpow_le_rpow _ (by simp [le_trans zero_le_one hq1] : 0 ≤ 1 / q), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ (le_trans zero_le_one hq1)), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ snorm' f q μ + snorm' g q μ : ennreal.lintegral_Lp_add_le hf.ennnorm hg.ennnorm hq1 lemma snorm_ess_sup_add_le {f g : α → F} : snorm_ess_sup (f + g) μ ≤ snorm_ess_sup f μ + snorm_ess_sup g μ := begin refine le_trans (ess_sup_mono_ae (eventually_of_forall (λ x, _))) (ennreal.ess_sup_add_le _ _), simp_rw [pi.add_apply, ←ennreal.coe_add, ennreal.coe_le_coe], exact nnnorm_add_le _ _, end lemma snorm_add_le {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : snorm (f + g) p μ ≤ snorm f p μ + snorm g p μ := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hp_top : p = ∞, { simp [hp_top, snorm_ess_sup_add_le], }, have hp1_real : 1 ≤ p.to_real, by rwa [← ennreal.one_to_real, ennreal.to_real_le_to_real ennreal.one_ne_top hp_top], repeat { rw snorm_eq_snorm' hp0 hp_top, }, exact snorm'_add_le hf hg hp1_real, end lemma snorm'_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι} (hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hq1 : 1 ≤ q) : snorm' (∑ i in s, f i) q μ ≤ ∑ i in s, snorm' (f i) q μ := finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm' f q μ) (λ f, ae_measurable f μ) (snorm'_zero (zero_lt_one.trans_le hq1)) (λ f g hf hg, snorm'_add_le hf hg hq1) (λ x y, ae_measurable.add) _ hfs lemma snorm_sum_le [second_countable_topology E] {ι} {f : ι → α → E} {s : finset ι} (hfs : ∀ i, i ∈ s → ae_measurable (f i) μ) (hp1 : 1 ≤ p) : snorm (∑ i in s, f i) p μ ≤ ∑ i in s, snorm (f i) p μ := finset.le_sum_of_subadditive_on_pred (λ (f : α → E), snorm f p μ) (λ f, ae_measurable f μ) snorm_zero (λ f g hf hg, snorm_add_le hf hg hp1) (λ x y, ae_measurable.add) _ hfs lemma snorm_add_lt_top_of_one_le {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) (hq1 : 1 ≤ p) : snorm (f + g) p μ < ∞ := lt_of_le_of_lt (snorm_add_le hf.1 hg.1 hq1) (ennreal.add_lt_top.mpr ⟨hf.2, hg.2⟩) lemma snorm'_add_lt_top_of_le_one {f g : α → E} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_snorm : snorm' f q μ < ∞) (hg_snorm : snorm' g q μ < ∞) (hq_pos : 0 < q) (hq1 : q ≤ 1) : snorm' (f + g) q μ < ∞ := calc (∫⁻ a, ↑(nnnorm ((f + g) a)) ^ q ∂μ) ^ (1 / q) ≤ (∫⁻ a, (((λ a, (nnnorm (f a) : ℝ≥0∞)) + (λ a, (nnnorm (g a) : ℝ≥0∞))) a) ^ q ∂μ) ^ (1 / q) : begin refine ennreal.rpow_le_rpow _ (by simp [hq_pos.le] : 0 ≤ 1 / q), refine lintegral_mono (λ a, ennreal.rpow_le_rpow _ hq_pos.le), simp [←ennreal.coe_add, nnnorm_add_le], end ... ≤ (∫⁻ a, (nnnorm (f a) : ℝ≥0∞) ^ q + (nnnorm (g a) : ℝ≥0∞) ^ q ∂μ) ^ (1 / q) : begin refine ennreal.rpow_le_rpow (lintegral_mono (λ a, _)) (by simp [hq_pos.le] : 0 ≤ 1 / q), exact ennreal.rpow_add_le_add_rpow _ _ hq_pos hq1, end ... < ∞ : begin refine ennreal.rpow_lt_top_of_nonneg (by simp [hq_pos.le] : 0 ≤ 1 / q) _, rw [lintegral_add' (hf.ennnorm.pow_const q) (hg.ennnorm.pow_const q), ennreal.add_ne_top, ←lt_top_iff_ne_top, ←lt_top_iff_ne_top], exact ⟨lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hf_snorm, lintegral_rpow_nnnorm_lt_top_of_snorm'_lt_top hq_pos hg_snorm⟩, end lemma snorm_add_lt_top {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : snorm (f + g) p μ < ∞ := begin by_cases h0 : p = 0, { simp [h0], }, rw ←ne.def at h0, cases le_total 1 p with hp1 hp1, { exact snorm_add_lt_top_of_one_le hf hg hp1, }, have hp_top : p ≠ ∞, from (lt_of_le_of_lt hp1 ennreal.coe_lt_top).ne, have hp_pos : 0 < p.to_real, { rw [← ennreal.zero_to_real, @ennreal.to_real_lt_to_real 0 p ennreal.coe_ne_top hp_top], exact ((zero_le p).lt_of_ne h0.symm), }, have hp1_real : p.to_real ≤ 1, { rwa [← ennreal.one_to_real, @ennreal.to_real_le_to_real p 1 hp_top ennreal.coe_ne_top], }, rw snorm_eq_snorm' h0 hp_top, rw [mem_ℒp, snorm_eq_snorm' h0 hp_top] at hf hg, exact snorm'_add_lt_top_of_le_one hf.1 hg.1 hf.2 hg.2 hp_pos hp1_real, end section second_countable_topology variable [second_countable_topology E] lemma mem_ℒp.add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f + g) p μ := ⟨ae_measurable.add hf.1 hg.1, snorm_add_lt_top hf hg⟩ lemma mem_ℒp.sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : mem_ℒp (f - g) p μ := by { rw sub_eq_add_neg, exact hf.add hg.neg } end second_countable_topology end borel_space section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] lemma snorm'_const_smul {f : α → F} (c : 𝕜) (hq_pos : 0 < q) : snorm' (c • f) q μ = (nnnorm c : ℝ≥0∞) * snorm' f q μ := begin rw snorm', simp_rw [pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.mul_rpow_of_nonneg _ _ hq_pos.le], suffices h_integral : ∫⁻ a, ↑(nnnorm c) ^ q * ↑(nnnorm (f a)) ^ q ∂μ = (nnnorm c : ℝ≥0∞)^q * ∫⁻ a, (nnnorm (f a)) ^ q ∂μ, { apply_fun (λ x, x ^ (1/q)) at h_integral, rw [h_integral, ennreal.mul_rpow_of_nonneg _ _ (by simp [hq_pos.le] : 0 ≤ 1 / q)], congr, simp_rw [←ennreal.rpow_mul, one_div, mul_inv_cancel hq_pos.ne.symm, ennreal.rpow_one], }, rw lintegral_const_mul', rw ennreal.coe_rpow_of_nonneg _ hq_pos.le, exact ennreal.coe_ne_top, end lemma snorm_ess_sup_const_smul {f : α → F} (c : 𝕜) : snorm_ess_sup (c • f) μ = (nnnorm c : ℝ≥0∞) * snorm_ess_sup f μ := by simp_rw [snorm_ess_sup, pi.smul_apply, nnnorm_smul, ennreal.coe_mul, ennreal.ess_sup_const_mul] lemma snorm_const_smul {f : α → F} (c : 𝕜) : snorm (c • f) p μ = (nnnorm c : ℝ≥0∞) * snorm f p μ := begin by_cases h0 : p = 0, { simp [h0], }, by_cases h_top : p = ∞, { simp [h_top, snorm_ess_sup_const_smul], }, repeat { rw snorm_eq_snorm' h0 h_top, }, rw ←ne.def at h0, exact snorm'_const_smul c (ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) h0.symm, h_top⟩), end lemma mem_ℒp.const_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] [borel_space E] {f : α → E} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (c • f) p μ := ⟨ae_measurable.const_smul hf.1 c, lt_of_le_of_lt (le_of_eq (snorm_const_smul c)) (ennreal.mul_lt_top ennreal.coe_lt_top hf.2)⟩ lemma mem_ℒp.const_mul [measurable_space 𝕜] [borel_space 𝕜] {f : α → 𝕜} (hf : mem_ℒp f p μ) (c : 𝕜) : mem_ℒp (λ x, c * f x) p μ := hf.const_smul c lemma snorm'_smul_le_mul_snorm' [opens_measurable_space E] [measurable_space 𝕜] [opens_measurable_space 𝕜] {p q r : ℝ} {f : α → E} (hf : ae_measurable f μ) {φ : α → 𝕜} (hφ : ae_measurable φ μ) (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) : snorm' (φ • f) p μ ≤ snorm' φ q μ * snorm' f r μ := begin simp_rw [snorm', pi.smul_apply', nnnorm_smul, ennreal.coe_mul], exact ennreal.lintegral_Lp_mul_le_Lq_mul_Lr hp0_lt hpq hpqr μ hφ.ennnorm hf.ennnorm, end end normed_space section monotonicity lemma snorm_le_mul_snorm_aux_of_nonneg {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : 0 ≤ c) (p : ℝ≥0∞) : snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ := begin lift c to ℝ≥0 using hc, rw [ennreal.of_real_coe_nnreal, ← c.nnnorm_eq, ← snorm_norm g, ← snorm_const_smul (c : ℝ)], swap, apply_instance, refine snorm_mono_ae _, simpa end lemma snorm_le_mul_snorm_aux_of_neg {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (hc : c < 0) (p : ℝ≥0∞) : snorm f p μ = 0 ∧ snorm g p μ = 0 := begin suffices : f =ᵐ[μ] 0 ∧ g =ᵐ[μ] 0, by simp [snorm_congr_ae this.1, snorm_congr_ae this.2], refine ⟨h.mono $ λ x hx, _, h.mono $ λ x hx, _⟩, { refine norm_le_zero_iff.1 (hx.trans _), exact mul_nonpos_of_nonpos_of_nonneg hc.le (norm_nonneg _) }, { refine norm_le_zero_iff.1 (nonpos_of_mul_nonneg_right _ hc), exact (norm_nonneg _).trans hx } end lemma snorm_le_mul_snorm_of_ae_le_mul {f : α → F} {g : α → G} {c : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) (p : ℝ≥0∞) : snorm f p μ ≤ (ennreal.of_real c) * snorm g p μ := begin cases le_or_lt 0 c with hc hc, { exact snorm_le_mul_snorm_aux_of_nonneg h hc p }, { simp [snorm_le_mul_snorm_aux_of_neg h hc p] } end lemma mem_ℒp.of_le_mul [measurable_space F] {f : α → E} {g : α → F} {c : ℝ} (hg : mem_ℒp g p μ) (hf : ae_measurable f μ) (hfg : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : mem_ℒp f p μ := begin simp only [mem_ℒp, hf, true_and], apply lt_of_le_of_lt (snorm_le_mul_snorm_of_ae_le_mul hfg p), simp [lt_top_iff_ne_top, hg.snorm_ne_top], end end monotonicity end ℒp /-! ### Lp space The space of equivalence classes of measurable functions for which `snorm f p μ < ∞`. -/ @[simp] lemma snorm_ae_eq_fun {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hf : ae_measurable f μ) : snorm (ae_eq_fun.mk f hf) p μ = snorm f p μ := snorm_congr_ae (ae_eq_fun.coe_fn_mk _ _) lemma mem_ℒp.snorm_mk_lt_top {α E : Type*} [measurable_space α] {μ : measure α} [measurable_space E] [normed_group E] {p : ℝ≥0∞} {f : α → E} (hfp : mem_ℒp f p μ) : snorm (ae_eq_fun.mk f hfp.1) p μ < ∞ := by simp [hfp.2] /-- Lp space -/ def Lp {α} (E : Type*) [measurable_space α] [measurable_space E] [normed_group E] [borel_space E] [second_countable_topology E] (p : ℝ≥0∞) (μ : measure α) : add_subgroup (α →ₘ[μ] E) := { carrier := {f | snorm f p μ < ∞}, zero_mem' := by simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero], add_mem' := λ f g hf hg, by simp [snorm_congr_ae (ae_eq_fun.coe_fn_add _ _), snorm_add_lt_top ⟨f.ae_measurable, hf⟩ ⟨g.ae_measurable, hg⟩], neg_mem' := λ f hf, by rwa [set.mem_set_of_eq, snorm_congr_ae (ae_eq_fun.coe_fn_neg _), snorm_neg] } localized "notation α ` →₁[`:25 μ `] ` E := measure_theory.Lp E 1 μ" in measure_theory localized "notation α ` →₂[`:25 μ `] ` E := measure_theory.Lp E 2 μ" in measure_theory namespace mem_ℒp variables [borel_space E] [second_countable_topology E] /-- make an element of Lp from a function verifying `mem_ℒp` -/ def to_Lp (f : α → E) (h_mem_ℒp : mem_ℒp f p μ) : Lp E p μ := ⟨ae_eq_fun.mk f h_mem_ℒp.1, h_mem_ℒp.snorm_mk_lt_top⟩ lemma coe_fn_to_Lp {f : α → E} (hf : mem_ℒp f p μ) : hf.to_Lp f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk _ _ @[simp] lemma to_Lp_eq_to_Lp_iff {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : hf.to_Lp f = hg.to_Lp g ↔ f =ᵐ[μ] g := by simp [to_Lp] @[simp] lemma to_Lp_zero (h : mem_ℒp (0 : α → E) p μ ) : h.to_Lp 0 = 0 := rfl lemma to_Lp_add {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : (hf.add hg).to_Lp (f + g) = hf.to_Lp f + hg.to_Lp g := rfl lemma to_Lp_neg {f : α → E} (hf : mem_ℒp f p μ) : hf.neg.to_Lp (-f) = - hf.to_Lp f := rfl lemma to_Lp_sub {f g : α → E} (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : (hf.sub hg).to_Lp (f - g) = hf.to_Lp f - hg.to_Lp g := rfl end mem_ℒp namespace Lp variables [borel_space E] [second_countable_topology E] instance : has_coe_to_fun (Lp E p μ) := ⟨λ _, α → E, λ f, ((f : α →ₘ[μ] E) : α → E)⟩ @[ext] lemma ext {f g : Lp E p μ} (h : f =ᵐ[μ] g) : f = g := begin cases f, cases g, simp only [subtype.mk_eq_mk], exact ae_eq_fun.ext h end lemma ext_iff {f g : Lp E p μ} : f = g ↔ f =ᵐ[μ] g := ⟨λ h, by rw h, λ h, ext h⟩ lemma mem_Lp_iff_snorm_lt_top {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ snorm f p μ < ∞ := iff.refl _ lemma mem_Lp_iff_mem_ℒp {f : α →ₘ[μ] E} : f ∈ Lp E p μ ↔ mem_ℒp f p μ := by simp [mem_Lp_iff_snorm_lt_top, mem_ℒp, f.measurable.ae_measurable] lemma antimono [finite_measure μ] {p q : ℝ≥0∞} (hpq : p ≤ q) : Lp E q μ ≤ Lp E p μ := λ f hf, (mem_ℒp.mem_ℒp_of_exponent_le ⟨f.ae_measurable, hf⟩ hpq).2 @[simp] lemma coe_fn_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) : ((⟨f, hf⟩ : Lp E p μ) : α → E) = f := rfl @[simp] lemma coe_mk {f : α →ₘ[μ] E} (hf : snorm f p μ < ∞) : ((⟨f, hf⟩ : Lp E p μ) : α →ₘ[μ] E) = f := rfl @[simp] lemma to_Lp_coe_fn (f : Lp E p μ) (hf : mem_ℒp f p μ) : hf.to_Lp f = f := by { cases f, simp [mem_ℒp.to_Lp] } lemma snorm_lt_top (f : Lp E p μ) : snorm f p μ < ∞ := f.prop lemma snorm_ne_top (f : Lp E p μ) : snorm f p μ ≠ ∞ := (snorm_lt_top f).ne @[measurability] protected lemma measurable (f : Lp E p μ) : measurable f := f.val.measurable @[measurability] protected lemma ae_measurable (f : Lp E p μ) : ae_measurable f μ := f.val.ae_measurable protected lemma mem_ℒp (f : Lp E p μ) : mem_ℒp f p μ := ⟨Lp.ae_measurable f, f.prop⟩ variables (E p μ) lemma coe_fn_zero : ⇑(0 : Lp E p μ) =ᵐ[μ] 0 := ae_eq_fun.coe_fn_zero variables {E p μ} lemma coe_fn_neg (f : Lp E p μ) : ⇑(-f) =ᵐ[μ] -f := ae_eq_fun.coe_fn_neg _ lemma coe_fn_add (f g : Lp E p μ) : ⇑(f + g) =ᵐ[μ] f + g := ae_eq_fun.coe_fn_add _ _ lemma coe_fn_sub (f g : Lp E p μ) : ⇑(f - g) =ᵐ[μ] f - g := ae_eq_fun.coe_fn_sub _ _ lemma mem_Lp_const (α) [measurable_space α] (μ : measure α) (c : E) [finite_measure μ] : @ae_eq_fun.const α _ _ μ _ c ∈ Lp E p μ := (mem_ℒp_const c).snorm_mk_lt_top instance : has_norm (Lp E p μ) := { norm := λ f, ennreal.to_real (snorm f p μ) } instance : has_dist (Lp E p μ) := { dist := λ f g, ∥f - g∥} instance : has_edist (Lp E p μ) := { edist := λ f g, ennreal.of_real (dist f g) } lemma norm_def (f : Lp E p μ) : ∥f∥ = ennreal.to_real (snorm f p μ) := rfl @[simp] lemma norm_to_Lp (f : α → E) (hf : mem_ℒp f p μ) : ∥hf.to_Lp f∥ = ennreal.to_real (snorm f p μ) := by rw [norm_def, snorm_congr_ae (mem_ℒp.coe_fn_to_Lp hf)] lemma dist_def (f g : Lp E p μ) : dist f g = (snorm (f - g) p μ).to_real := begin simp_rw [dist, norm_def], congr' 1, apply snorm_congr_ae (coe_fn_sub _ _), end lemma edist_def (f g : Lp E p μ) : edist f g = snorm (f - g) p μ := begin simp_rw [edist, dist, norm_def, ennreal.of_real_to_real (snorm_ne_top _)], exact snorm_congr_ae (coe_fn_sub _ _) end @[simp] lemma edist_to_Lp_to_Lp (f g : α → E) (hf : mem_ℒp f p μ) (hg : mem_ℒp g p μ) : edist (hf.to_Lp f) (hg.to_Lp g) = snorm (f - g) p μ := by { rw edist_def, exact snorm_congr_ae (hf.coe_fn_to_Lp.sub hg.coe_fn_to_Lp) } @[simp] lemma edist_to_Lp_zero (f : α → E) (hf : mem_ℒp f p μ) : edist (hf.to_Lp f) 0 = snorm f p μ := by { convert edist_to_Lp_to_Lp f 0 hf zero_mem_ℒp, simp } @[simp] lemma norm_zero : ∥(0 : Lp E p μ)∥ = 0 := begin change (snorm ⇑(0 : α →ₘ[μ] E) p μ).to_real = 0, simp [snorm_congr_ae ae_eq_fun.coe_fn_zero, snorm_zero] end lemma norm_eq_zero_iff {f : Lp E p μ} (hp : 0 < p) : ∥f∥ = 0 ↔ f = 0 := begin refine ⟨λ hf, _, λ hf, by simp [hf]⟩, rw [norm_def, ennreal.to_real_eq_zero_iff] at hf, cases hf, { rw snorm_eq_zero_iff (Lp.ae_measurable f) hp.ne.symm at hf, exact subtype.eq (ae_eq_fun.ext (hf.trans ae_eq_fun.coe_fn_zero.symm)), }, { exact absurd hf (snorm_ne_top f), }, end lemma eq_zero_iff_ae_eq_zero {f : Lp E p μ} : f = 0 ↔ f =ᵐ[μ] 0 := begin split, { assume h, rw h, exact ae_eq_fun.coe_fn_const _ _ }, { assume h, ext1, filter_upwards [h, ae_eq_fun.coe_fn_const α (0 : E)], assume a ha h'a, rw ha, exact h'a.symm } end @[simp] lemma norm_neg {f : Lp E p μ} : ∥-f∥ = ∥f∥ := by rw [norm_def, norm_def, snorm_congr_ae (coe_fn_neg _), snorm_neg] lemma norm_le_mul_norm_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F] {c : ℝ} {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : ∥f∥ ≤ c * ∥g∥ := begin by_cases pzero : p = 0, { simp [pzero, norm_def] }, cases le_or_lt 0 c with hc hc, { have := snorm_le_mul_snorm_aux_of_nonneg h hc p, rw [← ennreal.to_real_le_to_real, ennreal.to_real_mul, ennreal.to_real_of_real hc] at this, { exact this }, { exact (Lp.mem_ℒp _).snorm_ne_top }, { simp [(Lp.mem_ℒp _).snorm_ne_top] } }, { have := snorm_le_mul_snorm_aux_of_neg h hc p, simp only [snorm_eq_zero_iff (Lp.ae_measurable _) pzero, ← eq_zero_iff_ae_eq_zero] at this, simp [this] } end lemma norm_le_norm_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F] {f : Lp E p μ} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : ∥f∥ ≤ ∥g∥ := begin rw [norm_def, norm_def, ennreal.to_real_le_to_real (snorm_ne_top _) (snorm_ne_top _)], exact snorm_mono_ae h end lemma mem_Lp_of_ae_le_mul [second_countable_topology F] [measurable_space F] [borel_space F] {c : ℝ} {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ c * ∥g x∥) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le_mul (Lp.mem_ℒp g) f.ae_measurable h lemma mem_Lp_of_ae_le [second_countable_topology F] [measurable_space F] [borel_space F] {f : α →ₘ[μ] E} {g : Lp F p μ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ ∥g x∥) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_le (Lp.mem_ℒp g) f.ae_measurable h lemma mem_Lp_of_ae_bound [finite_measure μ] {f : α →ₘ[μ] E} (C : ℝ) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : f ∈ Lp E p μ := mem_Lp_iff_mem_ℒp.2 $ mem_ℒp.of_bound f.ae_measurable _ hfC lemma norm_le_of_ae_bound [finite_measure μ] {f : Lp E p μ} {C : ℝ} (hC : 0 ≤ C) (hfC : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : ∥f∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * C := begin by_cases hμ : μ = 0, { by_cases hp : p.to_real⁻¹ = 0, { simpa [hp, hμ, norm_def] using hC }, { simp [hμ, norm_def, real.zero_rpow hp] } }, let A : ℝ≥0 := (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * ⟨C, hC⟩, suffices : snorm f p μ ≤ A, { exact ennreal.to_real_le_coe_of_le_coe this }, convert snorm_le_of_ae_bound hfC, rw [← coe_measure_univ_nnreal μ, ennreal.coe_rpow_of_ne_zero (measure_univ_nnreal_pos hμ).ne', ennreal.coe_mul], congr, rw max_eq_left hC end instance [hp : fact (1 ≤ p)] : normed_group (Lp E p μ) := normed_group.of_core _ { norm_eq_zero_iff := λ f, norm_eq_zero_iff (ennreal.zero_lt_one.trans_le hp.1), triangle := begin assume f g, simp only [norm_def], rw ← ennreal.to_real_add (snorm_ne_top f) (snorm_ne_top g), suffices h_snorm : snorm ⇑(f + g) p μ ≤ snorm ⇑f p μ + snorm ⇑g p μ, { rwa ennreal.to_real_le_to_real (snorm_ne_top (f + g)), exact ennreal.add_ne_top.mpr ⟨snorm_ne_top f, snorm_ne_top g⟩, }, rw [snorm_congr_ae (coe_fn_add _ _)], exact snorm_add_le (Lp.ae_measurable f) (Lp.ae_measurable g) hp.1, end, norm_neg := by simp } instance normed_group_L1 : normed_group (Lp E 1 μ) := by apply_instance instance normed_group_L2 : normed_group (Lp E 2 μ) := by apply_instance instance normed_group_Ltop : normed_group (Lp E ∞ μ) := by apply_instance section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma mem_Lp_const_smul (c : 𝕜) (f : Lp E p μ) : c • ↑f ∈ Lp E p μ := begin rw [mem_Lp_iff_snorm_lt_top, snorm_congr_ae (ae_eq_fun.coe_fn_smul _ _), snorm_const_smul, ennreal.mul_lt_top_iff], exact or.inl ⟨ennreal.coe_lt_top, f.prop⟩, end variables (E p μ 𝕜) /-- The `𝕜`-submodule of elements of `α →ₘ[μ] E` whose `Lp` norm is finite. This is `Lp E p μ`, with extra structure. -/ def Lp_submodule : submodule 𝕜 (α →ₘ[μ] E) := { smul_mem' := λ c f hf, by simpa using mem_Lp_const_smul c ⟨f, hf⟩, .. Lp E p μ } variables {E p μ 𝕜} lemma coe_Lp_submodule : (Lp_submodule E p μ 𝕜).to_add_subgroup = Lp E p μ := rfl instance : module 𝕜 (Lp E p μ) := { .. (Lp_submodule E p μ 𝕜).module } lemma coe_fn_smul (c : 𝕜) (f : Lp E p μ) : ⇑(c • f) =ᵐ[μ] c • f := ae_eq_fun.coe_fn_smul _ _ lemma norm_const_smul (c : 𝕜) (f : Lp E p μ) : ∥c • f∥ = ∥c∥ * ∥f∥ := by rw [norm_def, snorm_congr_ae (coe_fn_smul _ _), snorm_const_smul c, ennreal.to_real_mul, ennreal.coe_to_real, coe_nnnorm, norm_def] instance [fact (1 ≤ p)] : normed_space 𝕜 (Lp E p μ) := { norm_smul_le := λ _ _, by simp [norm_const_smul] } instance normed_space_L1 : normed_space 𝕜 (Lp E 1 μ) := by apply_instance instance normed_space_L2 : normed_space 𝕜 (Lp E 2 μ) := by apply_instance instance normed_space_Ltop : normed_space 𝕜 (Lp E ∞ μ) := by apply_instance end normed_space end Lp namespace mem_ℒp variables [borel_space E] [second_countable_topology E] {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] lemma to_Lp_const_smul {f : α → E} (c : 𝕜) (hf : mem_ℒp f p μ) : (hf.const_smul c).to_Lp (c • f) = c • hf.to_Lp f := rfl end mem_ℒp /-! ### Indicator of a set as an element of Lᵖ For a set `s` with `(hs : measurable_set s)` and `(hμs : μ s < ∞)`, we build `indicator_const_Lp p hs hμs c`, the element of `Lp` corresponding to `s.indicator (λ x, c)`. -/ section indicator variables {s : set α} {hs : measurable_set s} {c : E} {f : α → E} {hf : ae_measurable f μ} lemma snorm_ess_sup_indicator_le (s : set α) (f : α → G) : snorm_ess_sup (s.indicator f) μ ≤ snorm_ess_sup f μ := begin refine ess_sup_mono_ae (eventually_of_forall (λ x, _)), rw [ennreal.coe_le_coe, nnnorm_indicator_eq_indicator_nnnorm], exact set.indicator_le_self s _ x, end lemma snorm_ess_sup_indicator_const_le (s : set α) (c : G) : snorm_ess_sup (s.indicator (λ x : α , c)) μ ≤ ∥c∥₊ := begin by_cases hμ0 : μ = 0, { rw [hμ0, snorm_ess_sup_measure_zero, ennreal.coe_nonneg], exact zero_le', }, { exact (snorm_ess_sup_indicator_le s (λ x, c)).trans (snorm_ess_sup_const c hμ0).le, }, end lemma snorm_ess_sup_indicator_const_eq (s : set α) (c : G) (hμs : μ s ≠ 0) : snorm_ess_sup (s.indicator (λ x : α , c)) μ = ∥c∥₊ := begin refine le_antisymm (snorm_ess_sup_indicator_const_le s c) _, by_contra h, push_neg at h, have h' := ae_iff.mp (ae_lt_of_ess_sup_lt h), push_neg at h', refine hμs (measure_mono_null (λ x hx_mem, _) h'), rw [set.mem_set_of_eq, set.indicator_of_mem hx_mem], exact le_rfl, end variables (hs) lemma snorm_indicator_le {E : Type*} [normed_group E] (f : α → E) : snorm (s.indicator f) p μ ≤ snorm f p μ := begin refine snorm_mono_ae (eventually_of_forall (λ x, _)), suffices : ∥s.indicator f x∥₊ ≤ ∥f x∥₊, { exact nnreal.coe_mono this }, rw nnnorm_indicator_eq_indicator_nnnorm, exact s.indicator_le_self _ x, end variables {hs} lemma snorm_indicator_const {c : G} (hs : measurable_set s) (hp : p ≠ 0) (hp_top : p ≠ ∞) : snorm (s.indicator (λ x, c)) p μ = ∥c∥₊ * (μ s) ^ (1 / p.to_real) := begin have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp.symm, hp_top⟩, rw snorm_eq_lintegral_rpow_nnnorm hp hp_top, simp_rw [nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator], have h_indicator_pow : (λ a : α, s.indicator (λ (x : α), (∥c∥₊ : ℝ≥0∞)) a ^ p.to_real) = s.indicator (λ (x : α), ↑∥c∥₊ ^ p.to_real), { rw set.comp_indicator_const (∥c∥₊ : ℝ≥0∞) (λ x, x ^ p.to_real) _, simp [hp_pos], }, rw [h_indicator_pow, lintegral_indicator _ hs, set_lintegral_const, ennreal.mul_rpow_of_nonneg], { rw [← ennreal.rpow_mul, mul_one_div_cancel hp_pos.ne.symm, ennreal.rpow_one], }, { simp [hp_pos.le], }, end lemma snorm_indicator_const' {c : G} (hs : measurable_set s) (hμs : μ s ≠ 0) (hp : p ≠ 0) : snorm (s.indicator (λ _, c)) p μ = ∥c∥₊ * (μ s) ^ (1 / p.to_real) := begin by_cases hp_top : p = ∞, { simp [hp_top, snorm_ess_sup_indicator_const_eq s c hμs], }, { exact snorm_indicator_const hs hp hp_top, }, end lemma mem_ℒp.indicator (hs : measurable_set s) (hf : mem_ℒp f p μ) : mem_ℒp (s.indicator f) p μ := ⟨hf.ae_measurable.indicator hs, lt_of_le_of_lt (snorm_indicator_le f) hf.snorm_lt_top⟩ lemma mem_ℒp_indicator_const (p : ℝ≥0∞) (hs : measurable_set s) (c : E) (hμsc : c = 0 ∨ μ s ≠ ∞) : mem_ℒp (s.indicator (λ _, c)) p μ := begin cases hμsc with hc hμs, { simp only [hc, set.indicator_zero], exact zero_mem_ℒp, }, refine ⟨(ae_measurable_indicator_iff hs).mpr ae_measurable_const, _⟩, by_cases hp0 : p = 0, { simp only [hp0, snorm_exponent_zero, with_top.zero_lt_top], }, by_cases hp_top : p = ∞, { rw [hp_top, snorm_exponent_top], exact (snorm_ess_sup_indicator_const_le s c).trans_lt ennreal.coe_lt_top, }, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) (ne.symm hp0), hp_top⟩, rw snorm_lt_top_iff_lintegral_rpow_nnnorm_lt_top hp0 hp_top, simp_rw [nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator], have h_indicator_pow : (λ a : α, s.indicator (λ _, (∥c∥₊ : ℝ≥0∞)) a ^ p.to_real) = s.indicator (λ _, ↑∥c∥₊ ^ p.to_real), { rw set.comp_indicator_const (∥c∥₊ : ℝ≥0∞) (λ x, x ^ p.to_real) _, simp [hp_pos], }, rw [h_indicator_pow, lintegral_indicator _ hs, set_lintegral_const], refine ennreal.mul_lt_top _ (lt_top_iff_ne_top.mpr hμs), exact ennreal.rpow_lt_top_of_nonneg hp_pos.le ennreal.coe_ne_top, end end indicator section indicator_const_Lp open set function variables {s : set α} {hs : measurable_set s} {hμs : μ s ≠ ∞} {c : E} [borel_space E] [second_countable_topology E] /-- Indicator of a set as an element of `Lp`. -/ def indicator_const_Lp (p : ℝ≥0∞) (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) : Lp E p μ := mem_ℒp.to_Lp (s.indicator (λ _, c)) (mem_ℒp_indicator_const p hs c (or.inr hμs)) lemma indicator_const_Lp_coe_fn : ⇑(indicator_const_Lp p hs hμs c) =ᵐ[μ] s.indicator (λ _, c) := mem_ℒp.coe_fn_to_Lp (mem_ℒp_indicator_const p hs c (or.inr hμs)) lemma indicator_const_Lp_coe_fn_mem : ∀ᵐ (x : α) ∂μ, x ∈ s → indicator_const_Lp p hs hμs c x = c := indicator_const_Lp_coe_fn.mono (λ x hx hxs, hx.trans (set.indicator_of_mem hxs _)) lemma indicator_const_Lp_coe_fn_nmem : ∀ᵐ (x : α) ∂μ, x ∉ s → indicator_const_Lp p hs hμs c x = 0 := indicator_const_Lp_coe_fn.mono (λ x hx hxs, hx.trans (set.indicator_of_not_mem hxs _)) lemma norm_indicator_const_Lp (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : ∥indicator_const_Lp p hs hμs c∥ = ∥c∥ * (μ s).to_real ^ (1 / p.to_real) := by rw [Lp.norm_def, snorm_congr_ae indicator_const_Lp_coe_fn, snorm_indicator_const hs hp_ne_zero hp_ne_top, ennreal.to_real_mul, ennreal.to_real_rpow, ennreal.coe_to_real, coe_nnnorm] lemma norm_indicator_const_Lp_top (hμs_ne_zero : μ s ≠ 0) : ∥indicator_const_Lp ∞ hs hμs c∥ = ∥c∥ := by rw [Lp.norm_def, snorm_congr_ae indicator_const_Lp_coe_fn, snorm_indicator_const' hs hμs_ne_zero ennreal.top_ne_zero, ennreal.top_to_real, div_zero, ennreal.rpow_zero, mul_one, ennreal.coe_to_real, coe_nnnorm] lemma norm_indicator_const_Lp' (hp_pos : p ≠ 0) (hμs_pos : μ s ≠ 0) : ∥indicator_const_Lp p hs hμs c∥ = ∥c∥ * (μ s).to_real ^ (1 / p.to_real) := begin by_cases hp_top : p = ∞, { rw [hp_top, ennreal.top_to_real, div_zero, real.rpow_zero, mul_one], exact norm_indicator_const_Lp_top hμs_pos, }, { exact norm_indicator_const_Lp hp_pos hp_top, }, end @[simp] lemma indicator_const_empty : indicator_const_Lp p measurable_set.empty (by simp : μ ∅ ≠ ∞) c = 0 := begin rw Lp.eq_zero_iff_ae_eq_zero, convert indicator_const_Lp_coe_fn, simp [set.indicator_empty'], end lemma mem_ℒp_add_of_disjoint {f g : α → E} (h : disjoint (support f) (support g)) (hf : measurable f) (hg : measurable g) : mem_ℒp (f + g) p μ ↔ mem_ℒp f p μ ∧ mem_ℒp g p μ := begin refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩, { rw ← indicator_add_eq_left h, exact hfg.indicator (measurable_set_support hf) }, { rw ← indicator_add_eq_right h, exact hfg.indicator (measurable_set_support hg) } end /-- The indicator of a disjoint union of two sets is the sum of the indicators of the sets. -/ lemma indicator_const_Lp_disjoint_union {s t : set α} (hs : measurable_set s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (hst : s ∩ t = ∅) (c : E) : (indicator_const_Lp p (hs.union ht) ((measure_union_le s t).trans_lt (lt_top_iff_ne_top.mpr (ennreal.add_ne_top.mpr ⟨hμs, hμt⟩))).ne c) = indicator_const_Lp p hs hμs c + indicator_const_Lp p ht hμt c := begin ext1, refine indicator_const_Lp_coe_fn.trans (eventually_eq.trans _ (Lp.coe_fn_add _ _).symm), refine eventually_eq.trans _ (eventually_eq.add indicator_const_Lp_coe_fn.symm indicator_const_Lp_coe_fn.symm), rw set.indicator_union_of_disjoint (set.disjoint_iff_inter_eq_empty.mpr hst) _, end end indicator_const_Lp end measure_theory open measure_theory /-! ### Composition on `L^p` We show that Lipschitz functions vanishing at zero act by composition on `L^p`, and specialize this to the composition with continuous linear maps, and to the definition of the positive part of an `L^p` function. -/ section composition variables [second_countable_topology E] [borel_space E] [second_countable_topology F] [measurable_space F] [borel_space F] {g : E → F} {c : ℝ≥0} namespace lipschitz_with lemma mem_ℒp_comp_iff_of_antilipschitz {α E F} {K K'} [measurable_space α] {μ : measure α} [measurable_space E] [measurable_space F] [normed_group E] [normed_group F] [borel_space E] [borel_space F] [complete_space E] {f : α → E} {g : E → F} (hg : lipschitz_with K g) (hg' : antilipschitz_with K' g) (g0 : g 0 = 0) : mem_ℒp (g ∘ f) p μ ↔ mem_ℒp f p μ := begin have := ae_measurable_comp_iff_of_closed_embedding g (hg'.closed_embedding hg.uniform_continuous), split, { assume H, have A : ∀ᵐ x ∂μ, ∥f x∥ ≤ K' * ∥g (f x)∥, { apply filter.eventually_of_forall (λ x, _), rw [← dist_zero_right, ← dist_zero_right, ← g0], apply hg'.le_mul_dist }, exact H.of_le_mul (this.1 H.ae_measurable) A }, { assume H, have A : ∀ᵐ x ∂μ, ∥g (f x)∥ ≤ K * ∥f x∥, { apply filter.eventually_of_forall (λ x, _), rw [← dist_zero_right, ← dist_zero_right, ← g0], apply hg.dist_le_mul }, exact H.of_le_mul (this.2 H.ae_measurable) A } end /-- When `g` is a Lipschitz function sending `0` to `0` and `f` is in `Lp`, then `g ∘ f` is well defined as an element of `Lp`. -/ def comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : Lp F p μ := ⟨ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E), begin suffices : ∀ᵐ x ∂μ, ∥ae_eq_fun.comp g hg.continuous.measurable (f : α →ₘ[μ] E) x∥ ≤ c * ∥f x∥, { exact Lp.mem_Lp_of_ae_le_mul this }, filter_upwards [ae_eq_fun.coe_fn_comp g hg.continuous.measurable (f : α →ₘ[μ] E)], assume a ha, simp only [ha], rw [← dist_zero_right, ← dist_zero_right, ← g0], exact hg.dist_le_mul (f a) 0, end⟩ lemma coe_fn_comp_Lp (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : hg.comp_Lp g0 f =ᵐ[μ] g ∘ f := ae_eq_fun.coe_fn_comp _ _ _ @[simp] lemma comp_Lp_zero (hg : lipschitz_with c g) (g0 : g 0 = 0) : hg.comp_Lp g0 (0 : Lp E p μ) = 0 := begin rw Lp.eq_zero_iff_ae_eq_zero, apply (coe_fn_comp_Lp _ _ _).trans, filter_upwards [Lp.coe_fn_zero E p μ], assume a ha, simp [ha, g0] end lemma norm_comp_Lp_sub_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f f' : Lp E p μ) : ∥hg.comp_Lp g0 f - hg.comp_Lp g0 f'∥ ≤ c * ∥f - f'∥ := begin apply Lp.norm_le_mul_norm_of_ae_le_mul, filter_upwards [hg.coe_fn_comp_Lp g0 f, hg.coe_fn_comp_Lp g0 f', Lp.coe_fn_sub (hg.comp_Lp g0 f) (hg.comp_Lp g0 f'), Lp.coe_fn_sub f f'], assume a ha1 ha2 ha3 ha4, simp [ha1, ha2, ha3, ha4, ← dist_eq_norm], exact hg.dist_le_mul (f a) (f' a) end lemma norm_comp_Lp_le (hg : lipschitz_with c g) (g0 : g 0 = 0) (f : Lp E p μ) : ∥hg.comp_Lp g0 f∥ ≤ c * ∥f∥ := by simpa using hg.norm_comp_Lp_sub_le g0 f 0 lemma lipschitz_with_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) : lipschitz_with c (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) := lipschitz_with.of_dist_le_mul $ λ f g, by simp [dist_eq_norm, norm_comp_Lp_sub_le] lemma continuous_comp_Lp [fact (1 ≤ p)] (hg : lipschitz_with c g) (g0 : g 0 = 0) : continuous (hg.comp_Lp g0 : Lp E p μ → Lp F p μ) := (lipschitz_with_comp_Lp hg g0).continuous end lipschitz_with namespace continuous_linear_map variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] /-- Composing `f : Lp ` with `L : E →L[𝕜] F`. -/ def comp_Lp (L : E →L[𝕜] F) (f : Lp E p μ) : Lp F p μ := L.lipschitz.comp_Lp (map_zero L) f lemma coe_fn_comp_Lp (L : E →L[𝕜] F) (f : Lp E p μ) : ∀ᵐ a ∂μ, (L.comp_Lp f) a = L (f a) := lipschitz_with.coe_fn_comp_Lp _ _ _ lemma norm_comp_Lp_le (L : E →L[𝕜] F) (f : Lp E p μ) : ∥L.comp_Lp f∥ ≤ ∥L∥ * ∥f∥ := lipschitz_with.norm_comp_Lp_le _ _ _ variables (μ p) [measurable_space 𝕜] [opens_measurable_space 𝕜] /-- Composing `f : Lp E p μ` with `L : E →L[𝕜] F`, seen as a `𝕜`-linear map on `Lp E p μ`. -/ def comp_Lpₗ (L : E →L[𝕜] F) : (Lp E p μ) →ₗ[𝕜] (Lp F p μ) := { to_fun := λ f, L.comp_Lp f, map_add' := begin intros f g, ext1, filter_upwards [Lp.coe_fn_add f g, coe_fn_comp_Lp L (f + g), coe_fn_comp_Lp L f, coe_fn_comp_Lp L g, Lp.coe_fn_add (L.comp_Lp f) (L.comp_Lp g)], assume a ha1 ha2 ha3 ha4 ha5, simp only [ha1, ha2, ha3, ha4, ha5, map_add, pi.add_apply], end, map_smul' := begin intros c f, ext1, filter_upwards [Lp.coe_fn_smul c f, coe_fn_comp_Lp L (c • f), Lp.coe_fn_smul c (L.comp_Lp f), coe_fn_comp_Lp L f], assume a ha1 ha2 ha3 ha4, simp only [ha1, ha2, ha3, ha4, map_smul, pi.smul_apply], end } /-- Composing `f : Lp E p μ` with `L : E →L[𝕜] F`, seen as a continuous `𝕜`-linear map on `Lp E p μ`. See also the similar * `linear_map.comp_left` for functions, * `continuous_linear_map.comp_left_continuous` for continuous functions, * `continuous_linear_map.comp_left_continuous_bounded` for bounded continuous functions, * `continuous_linear_map.comp_left_continuous_compact` for continuous functions on compact spaces. -/ def comp_LpL [fact (1 ≤ p)] (L : E →L[𝕜] F) : (Lp E p μ) →L[𝕜] (Lp F p μ) := linear_map.mk_continuous (L.comp_Lpₗ p μ) ∥L∥ L.norm_comp_Lp_le lemma norm_compLpL_le [fact (1 ≤ p)] (L : E →L[𝕜] F) : ∥L.comp_LpL p μ∥ ≤ ∥L∥ := linear_map.mk_continuous_norm_le _ (norm_nonneg _) _ end continuous_linear_map namespace measure_theory namespace Lp section pos_part lemma lipschitz_with_pos_part : lipschitz_with 1 (λ (x : ℝ), max x 0) := lipschitz_with.of_dist_le_mul $ λ x y, by simp [dist, abs_max_sub_max_le_abs] /-- Positive part of a function in `L^p`. -/ def pos_part (f : Lp ℝ p μ) : Lp ℝ p μ := lipschitz_with_pos_part.comp_Lp (max_eq_right (le_refl _)) f /-- Negative part of a function in `L^p`. -/ def neg_part (f : Lp ℝ p μ) : Lp ℝ p μ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : Lp ℝ p μ) : (pos_part f : α →ₘ[μ] ℝ) = (f : α →ₘ[μ] ℝ).pos_part := rfl lemma coe_fn_pos_part (f : Lp ℝ p μ) : ⇑(pos_part f) =ᵐ[μ] λ a, max (f a) 0 := ae_eq_fun.coe_fn_pos_part _ lemma coe_fn_neg_part_eq_max (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = max (- f a) 0 := begin rw neg_part, filter_upwards [coe_fn_pos_part (-f), coe_fn_neg f], assume a h₁ h₂, rw [h₁, h₂, pi.neg_apply] end lemma coe_fn_neg_part (f : Lp ℝ p μ) : ∀ᵐ a ∂μ, neg_part f a = - min (f a) 0 := (coe_fn_neg_part_eq_max f).mono $ assume a h, by rw [h, ← max_neg_neg, neg_zero] lemma continuous_pos_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, pos_part f) := lipschitz_with.continuous_comp_Lp _ _ lemma continuous_neg_part [fact (1 ≤ p)] : continuous (λf : Lp ℝ p μ, neg_part f) := have eq : (λf : Lp ℝ p μ, neg_part f) = (λf : Lp ℝ p μ, pos_part (-f)) := rfl, by { rw eq, exact continuous_pos_part.comp continuous_neg } end pos_part end Lp end measure_theory end composition /-! ## `L^p` is a complete space We show that `L^p` is a complete space for `1 ≤ p`. -/ section complete_space variables [borel_space E] [second_countable_topology E] namespace measure_theory namespace Lp lemma snorm'_lim_eq_lintegral_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G} {p : ℝ} (hp_nonneg : 0 ≤ p) {f_lim : α → G} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm' f_lim p μ = (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ) ^ (1/p) := begin suffices h_no_pow : (∫⁻ a, (nnnorm (f_lim a)) ^ p ∂μ) = (∫⁻ a, at_top.liminf (λ m, (nnnorm (f m a) : ℝ≥0∞)^p) ∂μ), { rw [snorm', h_no_pow], }, refine lintegral_congr_ae (h_lim.mono (λ a ha, _)), rw tendsto.liminf_eq, simp_rw [ennreal.coe_rpow_of_nonneg _ hp_nonneg, ennreal.tendsto_coe], refine ((nnreal.continuous_rpow_const hp_nonneg).tendsto (nnnorm (f_lim a))).comp _, exact (continuous_nnnorm.tendsto (f_lim a)).comp ha, end lemma snorm'_lim_le_liminf_snorm' {E} [measurable_space E] [normed_group E] [borel_space E] {f : ℕ → α → E} {p : ℝ} (hp_pos : 0 < p) (hf : ∀ n, ae_measurable (f n) μ) {f_lim : α → E} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm' f_lim p μ ≤ at_top.liminf (λ n, snorm' (f n) p μ) := begin rw snorm'_lim_eq_lintegral_liminf hp_pos.le h_lim, rw [←ennreal.le_rpow_one_div_iff (by simp [hp_pos] : 0 < 1 / p), one_div_one_div], refine (lintegral_liminf_le' (λ m, ((hf m).ennnorm.pow_const _))).trans_eq _, have h_pow_liminf : at_top.liminf (λ n, snorm' (f n) p μ) ^ p = at_top.liminf (λ n, (snorm' (f n) p μ) ^ p), { have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos hp_pos, have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2, refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _, all_goals { is_bounded_default }, }, rw h_pow_liminf, simp_rw [snorm', ← ennreal.rpow_mul, one_div, inv_mul_cancel hp_pos.ne.symm, ennreal.rpow_one], end lemma snorm_exponent_top_lim_eq_ess_sup_liminf {ι} [nonempty ι] [linear_order ι] {f : ι → α → G} {f_lim : α → G} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim ∞ μ = ess_sup (λ x, at_top.liminf (λ m, (nnnorm (f m x) : ℝ≥0∞))) μ := begin rw [snorm_exponent_top, snorm_ess_sup], refine ess_sup_congr_ae (h_lim.mono (λ x hx, _)), rw tendsto.liminf_eq, rw ennreal.tendsto_coe, exact (continuous_nnnorm.tendsto (f_lim x)).comp hx, end lemma snorm_exponent_top_lim_le_liminf_snorm_exponent_top {ι} [nonempty ι] [encodable ι] [linear_order ι] {f : ι → α → F} {f_lim : α → F} (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim ∞ μ ≤ at_top.liminf (λ n, snorm (f n) ∞ μ) := begin rw snorm_exponent_top_lim_eq_ess_sup_liminf h_lim, simp_rw [snorm_exponent_top, snorm_ess_sup], exact ennreal.ess_sup_liminf_le (λ n, (λ x, (nnnorm (f n x) : ℝ≥0∞))), end lemma snorm_lim_le_liminf_snorm {E} [measurable_space E] [normed_group E] [borel_space E] {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (f_lim : α → E) (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : snorm f_lim p μ ≤ at_top.liminf (λ n, snorm (f n) p μ) := begin by_cases hp0 : p = 0, { simp [hp0], }, rw ← ne.def at hp0, by_cases hp_top : p = ∞, { simp_rw [hp_top], exact snorm_exponent_top_lim_le_liminf_snorm_exponent_top h_lim, }, simp_rw snorm_eq_snorm' hp0 hp_top, have hp_pos : 0 < p.to_real, from ennreal.to_real_pos_iff.mpr ⟨lt_of_le_of_ne (zero_le _) hp0.symm, hp_top⟩, exact snorm'_lim_le_liminf_snorm' hp_pos hf h_lim, end /-! ### `Lp` is complete iff Cauchy sequences of `ℒp` have limits in `ℒp` -/ lemma tendsto_Lp_iff_tendsto_ℒp' {ι} {fi : filter ι} [fact (1 ≤ p)] (f : ι → Lp E p μ) (f_lim : Lp E p μ) : fi.tendsto f (𝓝 f_lim) ↔ fi.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin rw tendsto_iff_dist_tendsto_zero, simp_rw dist_def, rw [← ennreal.zero_to_real, ennreal.tendsto_to_real_iff (λ n, _) ennreal.zero_ne_top], rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm, exact Lp.snorm_ne_top _, end lemma tendsto_Lp_iff_tendsto_ℒp {ι} {fi : filter ι} [fact (1 ≤ p)] (f : ι → Lp E p μ) (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ) : fi.tendsto f (𝓝 (f_lim_ℒp.to_Lp f_lim)) ↔ fi.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin rw tendsto_Lp_iff_tendsto_ℒp', suffices h_eq : (λ n, snorm (f n - mem_ℒp.to_Lp f_lim f_lim_ℒp) p μ) = (λ n, snorm (f n - f_lim) p μ), by rw h_eq, exact funext (λ n, snorm_congr_ae (eventually_eq.rfl.sub (mem_ℒp.coe_fn_to_Lp f_lim_ℒp))), end lemma tendsto_Lp_iff_tendsto_ℒp'' {ι} {fi : filter ι} [fact (1 ≤ p)] (f : ι → α → E) (f_ℒp : ∀ n, mem_ℒp (f n) p μ) (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ) : fi.tendsto (λ n, (f_ℒp n).to_Lp (f n)) (𝓝 (f_lim_ℒp.to_Lp f_lim)) ↔ fi.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin convert Lp.tendsto_Lp_iff_tendsto_ℒp' _ _, ext1 n, apply snorm_congr_ae, filter_upwards [((f_ℒp n).sub f_lim_ℒp).coe_fn_to_Lp, Lp.coe_fn_sub ((f_ℒp n).to_Lp (f n)) (f_lim_ℒp.to_Lp f_lim)], intros x hx₁ hx₂, rw ← hx₂, exact hx₁.symm end lemma tendsto_Lp_of_tendsto_ℒp {ι} {fi : filter ι} [hp : fact (1 ≤ p)] {f : ι → Lp E p μ} (f_lim : α → E) (f_lim_ℒp : mem_ℒp f_lim p μ) (h_tendsto : fi.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : fi.tendsto f (𝓝 (f_lim_ℒp.to_Lp f_lim)) := (tendsto_Lp_iff_tendsto_ℒp f f_lim f_lim_ℒp).mpr h_tendsto lemma cauchy_seq_Lp_iff_cauchy_seq_ℒp {ι} [nonempty ι] [semilattice_sup ι] [hp : fact (1 ≤ p)] (f : ι → Lp E p μ) : cauchy_seq f ↔ tendsto (λ (n : ι × ι), snorm (f n.fst - f n.snd) p μ) at_top (𝓝 0) := begin simp_rw [cauchy_seq_iff_tendsto_dist_at_top_0, dist_def], rw [← ennreal.zero_to_real, ennreal.tendsto_to_real_iff (λ n, _) ennreal.zero_ne_top], rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm, exact snorm_ne_top _, end lemma complete_space_Lp_of_cauchy_complete_ℒp [hp : fact (1 ≤ p)] (H : ∀ (f : ℕ → α → E) (hf : ∀ n, mem_ℒp (f n) p μ) (B : ℕ → ℝ≥0∞) (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N), ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : complete_space (Lp E p μ) := begin let B := λ n : ℕ, ((1:ℝ) / 2) ^ n, have hB_pos : ∀ n, 0 < B n, from λ n, pow_pos (div_pos zero_lt_one zero_lt_two) n, refine metric.complete_of_convergent_controlled_sequences B hB_pos (λ f hf, _), suffices h_limit : ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0), { rcases h_limit with ⟨f_lim, hf_lim_meas, h_tendsto⟩, exact ⟨hf_lim_meas.to_Lp f_lim, tendsto_Lp_of_tendsto_ℒp f_lim hf_lim_meas h_tendsto⟩, }, have hB : summable B, from summable_geometric_two, cases hB with M hB, let B1 := λ n, ennreal.of_real (B n), have hB1_has : has_sum B1 (ennreal.of_real M), { have h_tsum_B1 : ∑' i, B1 i = (ennreal.of_real M), { change (∑' (n : ℕ), ennreal.of_real (B n)) = ennreal.of_real M, rw ←hB.tsum_eq, exact (ennreal.of_real_tsum_of_nonneg (λ n, le_of_lt (hB_pos n)) hB.summable).symm, }, have h_sum := (@ennreal.summable _ B1).has_sum, rwa h_tsum_B1 at h_sum, }, have hB1 : ∑' i, B1 i < ∞, by {rw hB1_has.tsum_eq, exact ennreal.of_real_lt_top, }, let f1 : ℕ → α → E := λ n, f n, refine H f1 (λ n, Lp.mem_ℒp (f n)) B1 hB1 (λ N n m hn hm, _), specialize hf N n m hn hm, rw dist_def at hf, simp_rw [f1, B1], rwa ennreal.lt_of_real_iff_to_real_lt, rw snorm_congr_ae (Lp.coe_fn_sub _ _).symm, exact Lp.snorm_ne_top _, end /-! ### Prove that controlled Cauchy sequences of `ℒp` have limits in `ℒp` -/ private lemma snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) (n : ℕ) : snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i := begin let f_norm_diff := λ i x, norm (f (i + 1) x - f i x), have hgf_norm_diff : ∀ n, (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) = ∑ i in finset.range (n + 1), f_norm_diff i, from λ n, funext (λ x, by simp [f_norm_diff]), rw hgf_norm_diff, refine (snorm'_sum_le (λ i _, ((hf (i+1)).sub (hf i)).norm) hp1).trans _, simp_rw [←pi.sub_apply, snorm'_norm], refine (finset.sum_le_sum _).trans (sum_le_tsum _ (λ m _, zero_le _) ennreal.summable), exact λ m _, (h_cau m (m + 1) m (nat.le_succ m) (le_refl m)).le, end private lemma lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (n : ℕ) (hn : snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i) : ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, rw [←one_div_one_div p, @ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [hp_pos]), one_div_one_div p], simp_rw snorm' at hn, have h_nnnorm_nonneg : (λ a, (nnnorm (∑ i in finset.range (n + 1), ∥f (i + 1) a - f i a∥) : ℝ≥0∞) ^ p) = λ a, (∑ i in finset.range (n + 1), (nnnorm(f (i + 1) a - f i a) : ℝ≥0∞)) ^ p, { ext1 a, congr, simp_rw ←of_real_norm_eq_coe_nnnorm, rw ←ennreal.of_real_sum_of_nonneg, { rw real.norm_of_nonneg _, exact finset.sum_nonneg (λ x hx, norm_nonneg _), }, { exact λ x hx, norm_nonneg _, }, }, change (∫⁻ a, (λ x, ↑(nnnorm (∑ i in finset.range (n + 1), ∥f (i+1) x - f i x∥))^p) a ∂μ)^(1/p) ≤ ∑' i, B i at hn, rwa h_nnnorm_nonneg at hn, end private lemma lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (h : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p) : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, suffices h_pow : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p, by rwa [←ennreal.le_rpow_one_div_iff (by simp [hp_pos] : 0 < 1 / p), one_div_one_div], have h_tsum_1 : ∀ g : ℕ → ℝ≥0∞, ∑' i, g i = at_top.liminf (λ n, ∑ i in finset.range (n + 1), g i), by { intro g, rw [ennreal.tsum_eq_liminf_sum_nat, ← liminf_nat_add _ 1], }, simp_rw h_tsum_1 _, rw ← h_tsum_1, have h_liminf_pow : ∫⁻ a, at_top.liminf (λ n, ∑ i in finset.range (n + 1), (nnnorm (f (i + 1) a - f i a)))^p ∂μ = ∫⁻ a, at_top.liminf (λ n, (∑ i in finset.range (n + 1), (nnnorm (f (i + 1) a - f i a)))^p) ∂μ, { refine lintegral_congr (λ x, _), have h_rpow_mono := ennreal.rpow_left_strict_mono_of_pos (zero_lt_one.trans_le hp1), have h_rpow_surj := (ennreal.rpow_left_bijective hp_pos.ne.symm).2, refine (h_rpow_mono.order_iso_of_surjective _ h_rpow_surj).liminf_apply _ _ _ _, all_goals { is_bounded_default }, }, rw h_liminf_pow, refine (lintegral_liminf_le' _).trans _, { exact λ n, (finset.ae_measurable_sum (finset.range (n+1)) (λ i _, ((hf (i+1)).sub (hf i)).ennnorm)).pow_const _, }, { exact liminf_le_of_frequently_le' (frequently_of_forall h), }, end private lemma tsum_nnnorm_sub_ae_lt_top {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) {p : ℝ} (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i) : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞ := begin have hp_pos : 0 < p := zero_lt_one.trans_le hp1, have h_integral : ∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ < ∞, { have h_tsum_lt_top : (∑' i, B i) ^ p < ∞, from ennreal.rpow_lt_top_of_nonneg hp_pos.le (lt_top_iff_ne_top.mp hB), refine lt_of_le_of_lt _ h_tsum_lt_top, rwa [←ennreal.le_rpow_one_div_iff (by simp [hp_pos] : 0 < 1 / p), one_div_one_div] at h, }, have rpow_ae_lt_top : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞)^p < ∞, { refine ae_lt_top' (ae_measurable.pow_const _ _) h_integral, exact ae_measurable.ennreal_tsum (λ n, ((hf (n+1)).sub (hf n)).ennnorm), }, refine rpow_ae_lt_top.mono (λ x hx, _), rwa [←ennreal.lt_rpow_one_div_iff hp_pos, ennreal.top_rpow_of_pos (by simp [hp_pos] : 0 < 1 / p)] at hx, end lemma ae_tendsto_of_cauchy_snorm' [complete_space E] {f : ℕ → α → E} {p : ℝ} (hf : ∀ n, ae_measurable (f n) μ) (hp1 : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) p μ < B N) : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) := begin have h_summable : ∀ᵐ x ∂μ, summable (λ (i : ℕ), f (i + 1) x - f i x), { have h1 : ∀ n, snorm' (λ x, ∑ i in finset.range (n + 1), norm (f (i + 1) x - f i x)) p μ ≤ ∑' i, B i, from snorm'_sum_norm_sub_le_tsum_of_cauchy_snorm' hf hp1 h_cau, have h2 : ∀ n, ∫⁻ a, (∑ i in finset.range (n + 1), nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ ≤ (∑' i, B i) ^ p, from λ n, lintegral_rpow_sum_coe_nnnorm_sub_le_rpow_tsum hf hp1 n (h1 n), have h3 : (∫⁻ a, (∑' i, nnnorm (f (i + 1) a - f i a) : ℝ≥0∞)^p ∂μ) ^ (1/p) ≤ ∑' i, B i, from lintegral_rpow_tsum_coe_nnnorm_sub_le_tsum hf hp1 h2, have h4 : ∀ᵐ x ∂μ, (∑' i, nnnorm (f (i + 1) x - f i x) : ℝ≥0∞) < ∞, from tsum_nnnorm_sub_ae_lt_top hf hp1 hB h3, exact h4.mono (λ x hx, summable_of_summable_nnnorm (ennreal.tsum_coe_ne_top_iff_summable.mp (lt_top_iff_ne_top.mp hx))), }, have h : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) (𝓝 l), { refine h_summable.mono (λ x hx, _), let hx_sum := hx.has_sum.tendsto_sum_nat, exact ⟨∑' i, (f (i + 1) x - f i x), hx_sum⟩, }, refine h.mono (λ x hx, _), cases hx with l hx, have h_rw_sum : (λ n, ∑ i in finset.range n, (f (i + 1) x - f i x)) = λ n, f n x - f 0 x, { ext1 n, change ∑ (i : ℕ) in finset.range n, ((λ m, f m x) (i + 1) - (λ m, f m x) i) = f n x - f 0 x, rw finset.sum_range_sub, }, rw h_rw_sum at hx, have hf_rw : (λ n, f n x) = λ n, f n x - f 0 x + f 0 x, by { ext1 n, abel, }, rw hf_rw, exact ⟨l + f 0 x, tendsto.add_const _ hx⟩, end lemma ae_tendsto_of_cauchy_snorm [complete_space E] {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (hp : 1 ≤ p) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) : ∀ᵐ x ∂μ, ∃ l : E, at_top.tendsto (λ n, f n x) (𝓝 l) := begin by_cases hp_top : p = ∞, { simp_rw [hp_top] at *, have h_cau_ae : ∀ᵐ x ∂μ, ∀ N n m, N ≤ n → N ≤ m → (nnnorm ((f n - f m) x) : ℝ≥0∞) < B N, { simp_rw [ae_all_iff, ae_imp_iff], exact λ N n m hnN hmN, ae_lt_of_ess_sup_lt (h_cau N n m hnN hmN), }, simp_rw [snorm_exponent_top, snorm_ess_sup] at h_cau, refine h_cau_ae.mono (λ x hx, cauchy_seq_tendsto_of_complete _), refine cauchy_seq_of_le_tendsto_0 (λ n, (B n).to_real) _ _, { intros n m N hnN hmN, specialize hx N n m hnN hmN, rw [dist_eq_norm, ←ennreal.to_real_of_real (norm_nonneg _), ennreal.to_real_le_to_real ennreal.of_real_ne_top ((ennreal.ne_top_of_tsum_ne_top (lt_top_iff_ne_top.mp hB)) N)], rw ←of_real_norm_eq_coe_nnnorm at hx, exact hx.le, }, { rw ← ennreal.zero_to_real, exact tendsto.comp (ennreal.tendsto_to_real ennreal.zero_ne_top) (ennreal.tendsto_at_top_zero_of_tsum_lt_top hB), }, }, have hp1 : 1 ≤ p.to_real, { rw [← ennreal.of_real_le_iff_le_to_real hp_top, ennreal.of_real_one], exact hp, }, have h_cau' : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm' (f n - f m) (p.to_real) μ < B N, { intros N n m hn hm, specialize h_cau N n m hn hm, rwa snorm_eq_snorm' (ennreal.zero_lt_one.trans_le hp).ne.symm hp_top at h_cau, }, exact ae_tendsto_of_cauchy_snorm' hf hp1 hB h_cau', end lemma cauchy_tendsto_of_tendsto {f : ℕ → α → E} (hf : ∀ n, ae_measurable (f n) μ) (f_lim : α → E) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) (h_lim : ∀ᵐ (x : α) ∂μ, tendsto (λ n, f n x) at_top (𝓝 (f_lim x))) : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin rw ennreal.tendsto_at_top_zero, intros ε hε, have h_B : ∃ (N : ℕ), B N ≤ ε, { suffices h_tendsto_zero : ∃ (N : ℕ), ∀ n : ℕ, N ≤ n → B n ≤ ε, from ⟨h_tendsto_zero.some, h_tendsto_zero.some_spec _ (le_refl _)⟩, exact (ennreal.tendsto_at_top_zero.mp (ennreal.tendsto_at_top_zero_of_tsum_lt_top hB)) ε hε, }, cases h_B with N h_B, refine ⟨N, λ n hn, _⟩, have h_sub : snorm (f n - f_lim) p μ ≤ at_top.liminf (λ m, snorm (f n - f m) p μ), { refine snorm_lim_le_liminf_snorm (λ m, (hf n).sub (hf m)) (f n - f_lim) _, refine h_lim.mono (λ x hx, _), simp_rw sub_eq_add_neg, exact tendsto.add tendsto_const_nhds (tendsto.neg hx), }, refine h_sub.trans _, refine liminf_le_of_frequently_le' (frequently_at_top.mpr _), refine λ N1, ⟨max N N1, le_max_right _ _, _⟩, exact (h_cau N n (max N N1) hn (le_max_left _ _)).le.trans h_B, end lemma mem_ℒp_of_cauchy_tendsto (hp : 1 ≤ p) {f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ) (f_lim : α → E) (h_lim_meas : ae_measurable f_lim μ) (h_tendsto : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0)) : mem_ℒp f_lim p μ := begin refine ⟨h_lim_meas, _⟩, rw ennreal.tendsto_at_top_zero at h_tendsto, cases (h_tendsto 1 ennreal.zero_lt_one) with N h_tendsto_1, specialize h_tendsto_1 N (le_refl N), have h_add : f_lim = f_lim - f N + f N, by abel, rw h_add, refine lt_of_le_of_lt (snorm_add_le (h_lim_meas.sub (hf N).1) (hf N).1 hp) _, rw ennreal.add_lt_top, split, { refine lt_of_le_of_lt _ ennreal.one_lt_top, have h_neg : f_lim - f N = -(f N - f_lim), by simp, rwa [h_neg, snorm_neg], }, { exact (hf N).2, }, end lemma cauchy_complete_ℒp [complete_space E] (hp : 1 ≤ p) {f : ℕ → α → E} (hf : ∀ n, mem_ℒp (f n) p μ) {B : ℕ → ℝ≥0∞} (hB : ∑' i, B i < ∞) (h_cau : ∀ (N n m : ℕ), N ≤ n → N ≤ m → snorm (f n - f m) p μ < B N) : ∃ (f_lim : α → E) (hf_lim_meas : mem_ℒp f_lim p μ), at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0) := begin obtain ⟨f_lim, h_f_lim_meas, h_lim⟩ : ∃ (f_lim : α → E) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, tendsto (λ n, f n x) at_top (nhds (f_lim x)), from measurable_limit_of_tendsto_metric_ae (λ n, (hf n).1) (ae_tendsto_of_cauchy_snorm (λ n, (hf n).1) hp hB h_cau), have h_tendsto' : at_top.tendsto (λ n, snorm (f n - f_lim) p μ) (𝓝 0), from cauchy_tendsto_of_tendsto (λ m, (hf m).1) f_lim hB h_cau h_lim, have h_ℒp_lim : mem_ℒp f_lim p μ, from mem_ℒp_of_cauchy_tendsto hp hf f_lim h_f_lim_meas.ae_measurable h_tendsto', exact ⟨f_lim, h_ℒp_lim, h_tendsto'⟩, end /-! ### `Lp` is complete for `1 ≤ p` -/ instance [complete_space E] [hp : fact (1 ≤ p)] : complete_space (Lp E p μ) := complete_space_Lp_of_cauchy_complete_ℒp (λ f hf B hB h_cau, cauchy_complete_ℒp hp.elim hf hB h_cau) end Lp end measure_theory end complete_space /-! ### Continuous functions in `Lp` -/ open_locale bounded_continuous_function open bounded_continuous_function variables [borel_space E] [second_countable_topology E] [topological_space α] [borel_space α] variables (E p μ) /-- An additive subgroup of `Lp E p μ`, consisting of the equivalence classes which contain a bounded continuous representative. -/ def measure_theory.Lp.bounded_continuous_function : add_subgroup (Lp E p μ) := add_subgroup.add_subgroup_of ((continuous_map.to_ae_eq_fun_add_hom μ).comp (forget_boundedness_add_hom α E)).range (Lp E p μ) variables {E p μ} /-- By definition, the elements of `Lp.bounded_continuous_function E p μ` are the elements of `Lp E p μ` which contain a bounded continuous representative. -/ lemma measure_theory.Lp.mem_bounded_continuous_function_iff {f : (Lp E p μ)} : f ∈ measure_theory.Lp.bounded_continuous_function E p μ ↔ ∃ f₀ : (α →ᵇ E), f₀.to_continuous_map.to_ae_eq_fun μ = (f : α →ₘ[μ] E) := add_subgroup.mem_add_subgroup_of namespace bounded_continuous_function variables [finite_measure μ] /-- A bounded continuous function on a finite-measure space is in `Lp`. -/ lemma mem_Lp (f : α →ᵇ E) : f.to_continuous_map.to_ae_eq_fun μ ∈ Lp E p μ := begin refine Lp.mem_Lp_of_ae_bound (∥f∥) _, filter_upwards [f.to_continuous_map.coe_fn_to_ae_eq_fun μ], intros x hx, convert f.norm_coe_le_norm x end /-- The `Lp`-norm of a bounded continuous function is at most a constant (depending on the measure of the whole space) times its sup-norm. -/ lemma Lp_norm_le (f : α →ᵇ E) : ∥(⟨f.to_continuous_map.to_ae_eq_fun μ, mem_Lp f⟩ : Lp E p μ)∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ * ∥f∥ := begin apply Lp.norm_le_of_ae_bound (norm_nonneg f), { refine (f.to_continuous_map.coe_fn_to_ae_eq_fun μ).mono _, intros x hx, convert f.norm_coe_le_norm x }, { apply_instance } end variables (p μ) /-- The normed group homomorphism of considering a bounded continuous function on a finite-measure space as an element of `Lp`. -/ def to_Lp_hom [fact (1 ≤ p)] : normed_group_hom (α →ᵇ E) (Lp E p μ) := { bound' := ⟨_, Lp_norm_le⟩, .. add_monoid_hom.cod_restrict ((continuous_map.to_ae_eq_fun_add_hom μ).comp (forget_boundedness_add_hom α E)) (Lp E p μ) mem_Lp } lemma range_to_Lp_hom [fact (1 ≤ p)] : ((to_Lp_hom p μ).range : add_subgroup (Lp E p μ)) = measure_theory.Lp.bounded_continuous_function E p μ := begin symmetry, convert add_monoid_hom.add_subgroup_of_range_eq_of_le ((continuous_map.to_ae_eq_fun_add_hom μ).comp (forget_boundedness_add_hom α E)) (by { rintros - ⟨f, rfl⟩, exact mem_Lp f } : _ ≤ Lp E p μ), end variables (𝕜 : Type*) [measurable_space 𝕜] /-- The bounded linear map of considering a bounded continuous function on a finite-measure space as an element of `Lp`. -/ def to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] : (α →ᵇ E) →L[𝕜] (Lp E p μ) := linear_map.mk_continuous (linear_map.cod_restrict (Lp.Lp_submodule E p μ 𝕜) ((continuous_map.to_ae_eq_fun_linear_map μ).comp (forget_boundedness_linear_map α E 𝕜)) mem_Lp) _ Lp_norm_le variables {𝕜} lemma range_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] : ((to_Lp p μ 𝕜).range.to_add_subgroup : add_subgroup (Lp E p μ)) = measure_theory.Lp.bounded_continuous_function E p μ := range_to_Lp_hom p μ variables {p} lemma coe_fn_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] (f : α →ᵇ E) : to_Lp p μ 𝕜 f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk f _ lemma to_Lp_norm_le [nondiscrete_normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] [fact (1 ≤ p)] : ∥(to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] (Lp E p μ))∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ := linear_map.mk_continuous_norm_le _ ((measure_univ_nnreal μ) ^ (p.to_real)⁻¹).coe_nonneg _ end bounded_continuous_function namespace continuous_map variables [compact_space α] [finite_measure μ] variables (𝕜 : Type*) [measurable_space 𝕜] (p μ) [fact (1 ≤ p)] /-- The bounded linear map of considering a continuous function on a compact finite-measure space `α` as an element of `Lp`. By definition, the norm on `C(α, E)` is the sup-norm, transferred from the space `α →ᵇ E` of bounded continuous functions, so this construction is just a matter of transferring the structure from `bounded_continuous_function.to_Lp` along the isometry. -/ def to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] : C(α, E) →L[𝕜] (Lp E p μ) := (bounded_continuous_function.to_Lp p μ 𝕜).comp (linear_isometry_bounded_of_compact α E 𝕜).to_linear_isometry.to_continuous_linear_map variables {𝕜} lemma range_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] : ((to_Lp p μ 𝕜).range.to_add_subgroup : add_subgroup (Lp E p μ)) = measure_theory.Lp.bounded_continuous_function E p μ := begin refine set_like.ext' _, have := (linear_isometry_bounded_of_compact α E 𝕜).surjective, convert function.surjective.range_comp this (bounded_continuous_function.to_Lp p μ 𝕜), rw ← bounded_continuous_function.range_to_Lp p μ, refl, end variables {p} lemma coe_fn_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : C(α, E)) : to_Lp p μ 𝕜 f =ᵐ[μ] f := ae_eq_fun.coe_fn_mk f _ lemma to_Lp_def [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : C(α, E)) : to_Lp p μ 𝕜 f = bounded_continuous_function.to_Lp p μ 𝕜 (linear_isometry_bounded_of_compact α E 𝕜 f) := rfl @[simp] lemma to_Lp_comp_forget_boundedness [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : α →ᵇ E) : to_Lp p μ 𝕜 (bounded_continuous_function.forget_boundedness α E f) = bounded_continuous_function.to_Lp p μ 𝕜 f := rfl @[simp] lemma coe_to_Lp [normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] (f : C(α, E)) : (to_Lp p μ 𝕜 f : α →ₘ[μ] E) = f.to_ae_eq_fun μ := rfl variables [nondiscrete_normed_field 𝕜] [opens_measurable_space 𝕜] [normed_space 𝕜 E] lemma to_Lp_norm_eq_to_Lp_norm_coe : ∥(to_Lp p μ 𝕜 : C(α, E) →L[𝕜] (Lp E p μ))∥ = ∥(bounded_continuous_function.to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] (Lp E p μ))∥ := continuous_linear_map.op_norm_comp_linear_isometry_equiv _ _ /-- Bound for the operator norm of `continuous_map.to_Lp`. -/ lemma to_Lp_norm_le : ∥(to_Lp p μ 𝕜 : C(α, E) →L[𝕜] (Lp E p μ))∥ ≤ (measure_univ_nnreal μ) ^ (p.to_real)⁻¹ := by { rw to_Lp_norm_eq_to_Lp_norm_coe, exact bounded_continuous_function.to_Lp_norm_le μ } end continuous_map --(to_Lp p μ 𝕜 : (α →ᵇ E) →L[𝕜] (Lp E p μ))
55bebd02c42cf0a66e97cec8dcd9f00e975f8912
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/polynomial/monic.lean
77cad7c1143cfa71dfa21dc192a04f147e13a001
[ "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
17,558
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.reverse import algebra.regular.smul /-! # Theory of monic polynomials We give several tools for proving that polynomials are monic, e.g. `monic.mul`, `monic.map`, `monic.pow`. -/ noncomputable theory open finset open_locale big_operators classical polynomial namespace polynomial universes u v y variables {R : Type u} {S : Type v} {a b : R} {m n : ℕ} {ι : Type y} section semiring variables [semiring R] {p q r : R[X]} lemma monic_zero_iff_subsingleton : monic (0 : R[X]) ↔ subsingleton R := subsingleton_iff_zero_eq_one lemma not_monic_zero_iff : ¬ monic (0 : R[X]) ↔ (0 : R) ≠ 1 := (monic_zero_iff_subsingleton.trans subsingleton_iff_zero_eq_one.symm).not lemma monic_zero_iff_subsingleton' : monic (0 : R[X]) ↔ (∀ f g : R[X], f = g) ∧ (∀ a b : R, a = b) := polynomial.monic_zero_iff_subsingleton.trans ⟨by { introI, simp }, λ h, subsingleton_iff.mpr h.2⟩ lemma monic.as_sum (hp : p.monic) : p = X^(p.nat_degree) + (∑ i in range p.nat_degree, C (p.coeff i) * X^i) := begin conv_lhs { rw [p.as_sum_range_C_mul_X_pow, sum_range_succ_comm] }, suffices : C (p.coeff p.nat_degree) = 1, { rw [this, one_mul] }, exact congr_arg C hp end lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 := begin rintro rfl, rw [monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma monic.map [semiring S] (f : R →+* S) (hp : monic p) : monic (p.map f) := begin nontriviality, have : f (leading_coeff p) ≠ 0, { rw [show _ = _, from hp, f.map_one], exact one_ne_zero, }, rw [monic, leading_coeff, coeff_map], suffices : p.coeff (map f p).nat_degree = 1, { simp [this], }, rwa nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f this), end lemma monic_C_mul_of_mul_leading_coeff_eq_one {b : R} (hp : b * p.leading_coeff = 1) : monic (C b * p) := by { nontriviality, rw [monic, leading_coeff_mul' _]; simp [leading_coeff_C b, hp] } lemma monic_mul_C_of_leading_coeff_mul_eq_one {b : R} (hp : p.leading_coeff * b = 1) : monic (p * C b) := by { nontriviality, rw [monic, leading_coeff_mul' _]; simp [leading_coeff_C b, hp] } theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, eq_of_zero_eq_one (H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : R) : monic (X + C x) := pow_one (X : R[X]) ▸ monic_X_pow_add degree_C_le lemma monic.mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : R) = 1 then by haveI := subsingleton_of_zero_eq_one h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic.pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := by { rw pow_succ, exact hp.mul (monic.pow n) } lemma monic.add_of_left (hp : monic p) (hpq : degree q < degree p) : monic (p + q) := by rwa [monic, add_comm, leading_coeff_add_of_degree_lt hpq] lemma monic.add_of_right (hq : monic q) (hpq : degree p < degree q) : monic (p + q) := by rwa [monic, leading_coeff_add_of_degree_lt hpq] lemma monic.of_mul_monic_left (hp : p.monic) (hpq : (p * q).monic) : q.monic := begin contrapose! hpq, rw monic.def at hpq ⊢, rwa leading_coeff_monic_mul hp, end lemma monic.of_mul_monic_right (hq : q.monic) (hpq : (p * q).monic) : p.monic := begin contrapose! hpq, rw monic.def at hpq ⊢, rwa leading_coeff_mul_monic hq, end namespace monic @[simp] lemma nat_degree_eq_zero_iff_eq_one (hp : p.monic) : p.nat_degree = 0 ↔ p = 1 := begin split; intro h, swap, { rw h, exact nat_degree_one }, have : p = C (p.coeff 0), { rw ← polynomial.degree_le_zero_iff, rwa polynomial.nat_degree_eq_zero_iff_degree_le_zero at h }, rw this, convert C_1, rw ← h, apply hp, end @[simp] lemma degree_le_zero_iff_eq_one (hp : p.monic) : p.degree ≤ 0 ↔ p = 1 := by rw [←hp.nat_degree_eq_zero_iff_eq_one, nat_degree_eq_zero_iff_degree_le_zero] lemma nat_degree_mul (hp : p.monic) (hq : q.monic) : (p * q).nat_degree = p.nat_degree + q.nat_degree := begin nontriviality R, apply nat_degree_mul', simp [hp.leading_coeff, hq.leading_coeff] end lemma degree_mul_comm (hp : p.monic) (q : R[X]) : (p * q).degree = (q * p).degree := begin by_cases h : q = 0, { simp [h] }, rw [degree_mul', hp.degree_mul], { exact add_comm _ _ }, { rwa [hp.leading_coeff, one_mul, leading_coeff_ne_zero] } end lemma nat_degree_mul' (hp : p.monic) (hq : q ≠ 0) : (p * q).nat_degree = p.nat_degree + q.nat_degree := begin rw [nat_degree_mul', add_comm], simpa [hp.leading_coeff, leading_coeff_ne_zero] end lemma nat_degree_mul_comm (hp : p.monic) (q : R[X]) : (p * q).nat_degree = (q * p).nat_degree := begin by_cases h : q = 0, { simp [h] }, rw [hp.nat_degree_mul' h, polynomial.nat_degree_mul', add_comm], simpa [hp.leading_coeff, leading_coeff_ne_zero] end lemma not_dvd_of_nat_degree_lt (hp : monic p) (h0 : q ≠ 0) (hl : nat_degree q < nat_degree p) : ¬ p ∣ q := begin rintro ⟨r, rfl⟩, rw [hp.nat_degree_mul' $ right_ne_zero_of_mul h0] at hl, exact hl.not_le (nat.le_add_right _ _) end lemma not_dvd_of_degree_lt (hp : monic p) (h0 : q ≠ 0) (hl : degree q < degree p) : ¬ p ∣ q := monic.not_dvd_of_nat_degree_lt hp h0 $ nat_degree_lt_nat_degree h0 hl lemma next_coeff_mul (hp : monic p) (hq : monic q) : next_coeff (p * q) = next_coeff p + next_coeff q := begin nontriviality, simp only [← coeff_one_reverse], rw reverse_mul; simp [coeff_mul, nat.antidiagonal, hp.leading_coeff, hq.leading_coeff, add_comm] end lemma eq_one_of_map_eq_one {S : Type*} [semiring S] [nontrivial S] (f : R →+* S) (hp : p.monic) (map_eq : p.map f = 1) : p = 1 := begin nontriviality R, have hdeg : p.degree = 0, { rw [← degree_map_eq_of_leading_coeff_ne_zero f _, map_eq, degree_one], { rw [hp.leading_coeff, f.map_one], exact one_ne_zero } }, have hndeg : p.nat_degree = 0 := with_bot.coe_eq_coe.mp ((degree_eq_nat_degree hp.ne_zero).symm.trans hdeg), convert eq_C_of_degree_eq_zero hdeg, rw [← hndeg, ← polynomial.leading_coeff, hp.leading_coeff, C.map_one] end lemma nat_degree_pow (hp : p.monic) (n : ℕ) : (p ^ n).nat_degree = n * p.nat_degree := begin induction n with n hn, { simp }, { rw [pow_succ, hp.nat_degree_mul (hp.pow n), hn], ring } end end monic @[simp] lemma nat_degree_pow_X_add_C [nontrivial R] (n : ℕ) (r : R) : ((X + C r) ^ n).nat_degree = n := by rw [(monic_X_add_C r).nat_degree_pow, nat_degree_X_add_C, mul_one] lemma monic.eq_one_of_is_unit (hm : monic p) (hpu : is_unit p) : p = 1 := begin nontriviality R, obtain ⟨q, h⟩ := hpu.exists_right_inv, have := hm.nat_degree_mul' (right_ne_zero_of_mul_eq_one h), rw [h, nat_degree_one, eq_comm, add_eq_zero_iff] at this, exact hm.nat_degree_eq_zero_iff_eq_one.mp this.1, end lemma monic.is_unit_iff (hm : p.monic) : is_unit p ↔ p = 1 := ⟨hm.eq_one_of_is_unit, λ h, h.symm ▸ is_unit_one⟩ end semiring section comm_semiring variables [comm_semiring R] {p : R[X]} lemma monic_multiset_prod_of_monic (t : multiset ι) (f : ι → R[X]) (ht : ∀ i ∈ t, monic (f i)) : monic (t.map f).prod := begin revert ht, refine t.induction_on _ _, { simp }, intros a t ih ht, rw [multiset.map_cons, multiset.prod_cons], exact (ht _ (multiset.mem_cons_self _ _)).mul (ih (λ _ hi, ht _ (multiset.mem_cons_of_mem hi))) end lemma monic_prod_of_monic (s : finset ι) (f : ι → R[X]) (hs : ∀ i ∈ s, monic (f i)) : monic (∏ i in s, f i) := monic_multiset_prod_of_monic s.1 f hs lemma monic.next_coeff_multiset_prod (t : multiset ι) (f : ι → R[X]) (h : ∀ i ∈ t, monic (f i)) : next_coeff (t.map f).prod = (t.map (λ i, next_coeff (f i))).sum := begin revert h, refine multiset.induction_on t _ (λ a t ih ht, _), { simp only [multiset.not_mem_zero, forall_prop_of_true, forall_prop_of_false, multiset.map_zero, multiset.prod_zero, multiset.sum_zero, not_false_iff, forall_true_iff], rw ← C_1, rw next_coeff_C_eq_zero }, { rw [multiset.map_cons, multiset.prod_cons, multiset.map_cons, multiset.sum_cons, monic.next_coeff_mul, ih], exacts [λ i hi, ht i (multiset.mem_cons_of_mem hi), ht a (multiset.mem_cons_self _ _), monic_multiset_prod_of_monic _ _ (λ b bs, ht _ (multiset.mem_cons_of_mem bs))] } end lemma monic.next_coeff_prod (s : finset ι) (f : ι → R[X]) (h : ∀ i ∈ s, monic (f i)) : next_coeff (∏ i in s, f i) = ∑ i in s, next_coeff (f i) := monic.next_coeff_multiset_prod s.1 f h end comm_semiring section semiring variables [semiring R] @[simp] lemma monic.nat_degree_map [semiring S] [nontrivial S] {P : R[X]} (hmo : P.monic) (f : R →+* S) : (P.map f).nat_degree = P.nat_degree := begin refine le_antisymm (nat_degree_map_le _ _) (le_nat_degree_of_ne_zero _), rw [coeff_map, monic.coeff_nat_degree hmo, ring_hom.map_one], exact one_ne_zero end @[simp] lemma monic.degree_map [semiring S] [nontrivial S] {P : R[X]} (hmo : P.monic) (f : R →+* S) : (P.map f).degree = P.degree := begin by_cases hP : P = 0, { simp [hP] }, { refine le_antisymm (degree_map_le _ _) _, rw [degree_eq_nat_degree hP], refine le_degree_of_ne_zero _, rw [coeff_map, monic.coeff_nat_degree hmo, ring_hom.map_one], exact one_ne_zero } end section injective open function variables [semiring S] {f : R →+* S} (hf : injective f) include hf lemma degree_map_eq_of_injective (p : R[X]) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← f.map_zero]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma nat_degree_map_eq_of_injective (p : R[X]) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map_eq_of_injective hf p) lemma leading_coeff_map' (p : R[X]) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map_eq_of_injective hf p], end lemma next_coeff_map (p : R[X]) : (p.map f).next_coeff = f p.next_coeff := begin unfold next_coeff, rw nat_degree_map_eq_of_injective hf, split_ifs; simp end lemma leading_coeff_of_injective (p : R[X]) : leading_coeff (p.map f) = f (leading_coeff p) := begin delta leading_coeff, rw [coeff_map f, nat_degree_map_eq_of_injective hf p] end lemma monic_of_injective {p : R[X]} (hp : (p.map f).monic) : p.monic := begin apply hf, rw [← leading_coeff_of_injective hf, hp.leading_coeff, f.map_one] end end injective end semiring section ring variables [ring R] {p : R[X]} theorem monic_X_sub_C (x : R) : monic (X - C x) := by simpa only [sub_eq_add_neg, C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := by simpa [sub_eq_add_neg] using monic_X_pow_add (show degree (-p) ≤ n, by rwa ←degree_neg p at H) /-- `X ^ n - a` is monic. -/ lemma monic_X_pow_sub_C {R : Type u} [ring R] (a : R) {n : ℕ} (h : n ≠ 0) : (X ^ n - C a).monic := begin obtain ⟨k, hk⟩ := nat.exists_eq_succ_of_ne_zero h, convert monic_X_pow_sub _, exact le_trans degree_C_le nat.with_bot.coe_nonneg, end lemma not_is_unit_X_pow_sub_one (R : Type*) [comm_ring R] [nontrivial R] (n : ℕ) : ¬ is_unit (X ^ n - 1 : R[X]) := begin intro h, rcases eq_or_ne n 0 with rfl | hn, { simpa using h }, apply hn, rw [←@nat_degree_one R, ←(monic_X_pow_sub_C _ hn).eq_one_of_is_unit h, nat_degree_X_pow_sub_C], end lemma monic.sub_of_left {p q : R[X]} (hp : monic p) (hpq : degree q < degree p) : monic (p - q) := by { rw sub_eq_add_neg, apply hp.add_of_left, rwa degree_neg } lemma monic.sub_of_right {p q : R[X]} (hq : q.leading_coeff = -1) (hpq : degree p < degree q) : monic (p - q) := have (-q).coeff (-q).nat_degree = 1 := by rw [nat_degree_neg, coeff_neg, show q.coeff q.nat_degree = -1, from hq, neg_neg], by { rw sub_eq_add_neg, apply monic.add_of_right this, rwa degree_neg } end ring section nonzero_semiring variables [semiring R] [nontrivial R] {p q : R[X]} @[simp] lemma not_monic_zero : ¬monic (0 : R[X]) := not_monic_zero_iff.mp zero_ne_one end nonzero_semiring section not_zero_divisor -- TODO: using gh-8537, rephrase lemmas that involve commutation around `*` using the op-ring variables [semiring R] {p : R[X]} lemma monic.mul_left_ne_zero (hp : monic p) {q : R[X]} (hq : q ≠ 0) : q * p ≠ 0 := begin by_cases h : p = 1, { simpa [h] }, rw [ne.def, ←degree_eq_bot, hp.degree_mul, with_bot.add_eq_bot, not_or_distrib, degree_eq_bot], refine ⟨hq, _⟩, rw [←hp.degree_le_zero_iff_eq_one, not_le] at h, refine (lt_trans _ h).ne', simp end lemma monic.mul_right_ne_zero (hp : monic p) {q : R[X]} (hq : q ≠ 0) : p * q ≠ 0 := begin by_cases h : p = 1, { simpa [h] }, rw [ne.def, ←degree_eq_bot, hp.degree_mul_comm, hp.degree_mul, with_bot.add_eq_bot, not_or_distrib, degree_eq_bot], refine ⟨hq, _⟩, rw [←hp.degree_le_zero_iff_eq_one, not_le] at h, refine (lt_trans _ h).ne', simp end lemma monic.mul_nat_degree_lt_iff (h : monic p) {q : R[X]} : (p * q).nat_degree < p.nat_degree ↔ p ≠ 1 ∧ q = 0 := begin by_cases hq : q = 0, { suffices : 0 < p.nat_degree ↔ p.nat_degree ≠ 0, { simpa [hq, ←h.nat_degree_eq_zero_iff_eq_one] }, exact ⟨λ h, h.ne', λ h, lt_of_le_of_ne (nat.zero_le _) h.symm ⟩ }, { simp [h.nat_degree_mul', hq] } end lemma monic.mul_right_eq_zero_iff (h : monic p) {q : R[X]} : p * q = 0 ↔ q = 0 := begin by_cases hq : q = 0; simp [h.mul_right_ne_zero, hq] end lemma monic.mul_left_eq_zero_iff (h : monic p) {q : R[X]} : q * p = 0 ↔ q = 0 := begin by_cases hq : q = 0; simp [h.mul_left_ne_zero, hq] end lemma monic.is_regular {R : Type*} [ring R] {p : R[X]} (hp : monic p) : is_regular p := begin split, { intros q r h, rw [←sub_eq_zero, ←hp.mul_right_eq_zero_iff, mul_sub, h, sub_self] }, { intros q r h, simp only at h, rw [←sub_eq_zero, ←hp.mul_left_eq_zero_iff, sub_mul, h, sub_self] } end lemma degree_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R] {k : S} (p : R[X]) (h : is_smul_regular R k) : (k • p).degree = p.degree := begin refine le_antisymm _ _, { rw degree_le_iff_coeff_zero, intros m hm, rw degree_lt_iff_coeff_zero at hm, simp [hm m le_rfl] }, { rw degree_le_iff_coeff_zero, intros m hm, rw degree_lt_iff_coeff_zero at hm, refine h _, simpa using hm m le_rfl }, end lemma nat_degree_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R] {k : S} (p : R[X]) (h : is_smul_regular R k) : (k • p).nat_degree = p.nat_degree := begin by_cases hp : p = 0, { simp [hp] }, rw [←with_bot.coe_eq_coe, ←degree_eq_nat_degree hp, ←degree_eq_nat_degree, degree_smul_of_smul_regular p h], contrapose! hp, rw ←smul_zero k at hp, exact h.polynomial hp end lemma leading_coeff_smul_of_smul_regular {S : Type*} [monoid S] [distrib_mul_action S R] {k : S} (p : R[X]) (h : is_smul_regular R k) : (k • p).leading_coeff = k • p.leading_coeff := by rw [leading_coeff, leading_coeff, coeff_smul, nat_degree_smul_of_smul_regular p h] lemma monic_of_is_unit_leading_coeff_inv_smul (h : is_unit p.leading_coeff) : monic (h.unit⁻¹ • p) := begin rw [monic.def, leading_coeff_smul_of_smul_regular _ (is_smul_regular_of_group _), units.smul_def], obtain ⟨k, hk⟩ := h, simp only [←hk, smul_eq_mul, ←units.coe_mul, units.coe_eq_one, inv_mul_eq_iff_eq_mul], simp [units.ext_iff, is_unit.unit_spec] end lemma is_unit_leading_coeff_mul_right_eq_zero_iff (h : is_unit p.leading_coeff) {q : R[X]} : p * q = 0 ↔ q = 0 := begin split, { intro hp, rw ←smul_eq_zero_iff_eq (h.unit)⁻¹ at hp, have : (h.unit)⁻¹ • (p * q) = ((h.unit)⁻¹ • p) * q, { ext, simp only [units.smul_def, coeff_smul, coeff_mul, smul_eq_mul, mul_sum], refine sum_congr rfl (λ x hx, _), rw ←mul_assoc }, rwa [this, monic.mul_right_eq_zero_iff] at hp, exact monic_of_is_unit_leading_coeff_inv_smul _ }, { rintro rfl, simp } end lemma is_unit_leading_coeff_mul_left_eq_zero_iff (h : is_unit p.leading_coeff) {q : R[X]} : q * p = 0 ↔ q = 0 := begin split, { intro hp, replace hp := congr_arg (* C ↑(h.unit)⁻¹) hp, simp only [zero_mul] at hp, rwa [mul_assoc, monic.mul_left_eq_zero_iff] at hp, refine monic_mul_C_of_leading_coeff_mul_eq_one _, simp [units.mul_inv_eq_iff_eq_mul, is_unit.unit_spec] }, { rintro rfl, rw zero_mul } end end not_zero_divisor end polynomial
717360f92745c3258c2eedffbae23b4ede35b584
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/nat_bug.lean
51fc2f301a4860e8f2b8df794229401107a26c04
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
789
lean
import logic using decidable inductive nat : Type := zero : nat, succ : nat → nat definition refl := @eq.refl namespace nat definition pred (n : nat) := nat.rec zero (fun m x, m) n theorem pred_zero : pred zero = zero := refl _ theorem pred_succ (n : nat) : pred (succ n) = n := refl _ theorem zero_or_succ (n : nat) : n = zero ∨ n = succ (pred n) := induction_on n (or.intro_left _ (refl zero)) (take m IH, or.intro_right _ (show succ m = succ (pred (succ m)), from congr_arg succ (symm (pred_succ m)))) theorem zero_or_succ2 (n : nat) : n = zero ∨ n = succ (pred n) := @induction_on _ n (or.intro_left _ (refl zero)) (take m IH, or.intro_right _ (show succ m = succ (pred (succ m)), from congr_arg succ (symm (pred_succ m)))) end nat end experiment
d7ba017e2e22b3b6f6d1d94dad9de16ed5d49dce
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/run_parser.lean
11103ec6722e04f00c75ec19660fc1da46938850
[ "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
312
lean
import tactic.core open tactic lean.parser interactive.types run_parser do e ← with_input texpr "λ x:ℕ, x", e ← to_expr e.1, guard (e =ₐ `(λ x:ℕ, x)), emit_code_here "def foo := 1" example : foo = 1 := rfl -- check that `emit_code_here` terminates properly run_parser emit_code_here "\n"
3c718dc00112f0f6924d76e9631a7799082c89be
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/paracompact.lean
9e5aa0e7903451d901cd47fadeeeed699c36d0e0
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
15,311
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Yury Kudryashov -/ import topology.subset_properties import topology.separation import data.option.basic /-! # Paracompact topological spaces A topological space `X` is said to be paracompact if every open covering of `X` admits a locally finite refinement. The definition requires that each set of the new covering is a subset of one of the sets of the initial covering. However, one can ensure that each open covering `s : ι → set X` admits a *precise* locally finite refinement, i.e., an open covering `t : ι → set X` with the same index set such that `∀ i, t i ⊆ s i`, see lemma `precise_refinement`. We also provide a convenience lemma `precise_refinement_set` that deals with open coverings of a closed subset of `X` instead of the whole space. We also prove the following facts. * Every compact space is paracompact, see instance `paracompact_of_compact`. * A locally compact sigma compact Hausdorff space is paracompact, see instance `paracompact_of_locally_compact_sigma_compact`. Moreover, we can choose a locally finite refinement with sets in a given collection of filter bases of `𝓝 x, `x : X`, see `refinement_of_locally_compact_sigma_compact_of_nhds_basis`. For example, in a proper metric space every open covering `⋃ i, s i` admits a refinement `⋃ i, metric.ball (c i) (r i)`. * Every paracompact Hausdorff space is normal. This statement is not an instance to avoid loops in the instance graph. * Every `emetric_space` is a paracompact space, see instance `emetric_space.paracompact_space` in `topology/metric_space/emetric_space`. ## TODO * Define partition of unity. * Prove (some of) [Michael's theorems](https://ncatlab.org/nlab/show/Michael%27s+theorem). ## Tags compact space, paracompact space, locally finite covering -/ open set filter function open_locale filter topological_space universes u v /-- A topological space is called paracompact, if every open covering of this space admits a locally finite refinement. We use the same universe for all types in the definition to avoid creating a class like `paracompact_space.{u v}`. Due to lemma `precise_refinement` below, every open covering `s : α → set X` indexed on `α : Type v` has a *precise* locally finite refinement, i.e., a locally finite refinement `t : α → set X` indexed on the same type such that each `∀ i, t i ⊆ s i`. -/ class paracompact_space (X : Type v) [topological_space X] : Prop := (locally_finite_refinement : ∀ (α : Type v) (s : α → set X) (ho : ∀ a, is_open (s a)) (hc : (⋃ a, s a) = univ), ∃ (β : Type v) (t : β → set X) (ho : ∀ b, is_open (t b)) (hc : (⋃ b, t b) = univ), locally_finite t ∧ ∀ b, ∃ a, t b ⊆ s a) variables {ι : Type u} {X : Type v} [topological_space X] /-- Any open cover of a paracompact space has a locally finite *precise* refinement, that is, one indexed on the same type with each open set contained in the corresponding original one. -/ lemma precise_refinement [paracompact_space X] (u : ι → set X) (uo : ∀ a, is_open (u a)) (uc : (⋃ i, u i) = univ) : ∃ v : ι → set X, (∀ a, is_open (v a)) ∧ (⋃ i, v i) = univ ∧ locally_finite v ∧ (∀ a, v a ⊆ u a) := begin -- Apply definition to `range u`, then turn existence quantifiers into functions using `choose` have := paracompact_space.locally_finite_refinement (range u) coe (set_coe.forall.2 $ forall_range_iff.2 uo) (by rwa [← sUnion_range, subtype.range_coe]), simp only [set_coe.exists, subtype.coe_mk, exists_range_iff', Union_eq_univ_iff, exists_prop] at this, choose α t hto hXt htf ind hind, choose t_inv ht_inv using hXt, choose U hxU hU using htf, -- Send each `i` to the union of `t a` over `a ∈ ind ⁻¹' {i}` refine ⟨λ i, ⋃ (a : α) (ha : ind a = i), t a, _, _, _, _⟩, { exact λ a, is_open_Union (λ a, is_open_Union $ λ ha, hto a) }, { simp only [eq_univ_iff_forall, mem_Union], exact λ x, ⟨ind (t_inv x), _, rfl, ht_inv _⟩ }, { refine λ x, ⟨U x, hxU x, ((hU x).image ind).subset _⟩, simp only [subset_def, mem_Union, mem_set_of_eq, set.nonempty, mem_inter_eq], rintro i ⟨y, ⟨a, rfl, hya⟩, hyU⟩, exact mem_image_of_mem _ ⟨y, hya, hyU⟩ }, { simp only [subset_def, mem_Union], rintro i x ⟨a, rfl, hxa⟩, exact hind _ hxa } end /-- In a paracompact space, every open covering of a closed set admits a locally finite refinement indexed by the same type. -/ lemma precise_refinement_set [paracompact_space X] {s : set X} (hs : is_closed s) (u : ι → set X) (uo : ∀ i, is_open (u i)) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, (∀ i, is_open (v i)) ∧ (s ⊆ ⋃ i, v i) ∧ locally_finite v ∧ (∀ i, v i ⊆ u i) := begin rcases precise_refinement (λ i, option.elim i sᶜ u) (option.forall.2 ⟨is_open_compl_iff.2 hs, uo⟩) _ with ⟨v, vo, vc, vf, vu⟩, refine ⟨v ∘ some, λ i, vo _, _, vf.comp_injective (option.some_injective _), λ i, vu _⟩, { simp only [Union_option, ← compl_subset_iff_union] at vc, exact subset.trans (subset_compl_comm.1 $ vu option.none) vc }, { simpa only [Union_option, option.elim, ← compl_subset_iff_union, compl_compl] } end /-- A compact space is paracompact. -/ @[priority 100] -- See note [lower instance priority] instance paracompact_of_compact [compact_space X] : paracompact_space X := begin -- the proof is trivial: we choose a finite subcover using compactness, and use it refine ⟨λ ι s ho hu, _⟩, rcases compact_univ.elim_finite_subcover _ ho hu.ge with ⟨T, hT⟩, have := hT, simp only [subset_def, mem_Union] at this, choose i hiT hi using λ x, this x (mem_univ x), refine ⟨(T : set ι), λ t, s t, λ t, ho _, _, locally_finite_of_fintype _, λ t, ⟨t, subset.rfl⟩⟩, rwa [Union_subtype, finset.set_bUnion_coe, ← univ_subset_iff], end /-- Let `X` be a locally compact sigma compact Hausdorff topological space, let `s` be a closed set in `X`. Suppose that for each `x ∈ s` the sets `B x : ι x → set X` with the predicate `p x : ι x → Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering `λ i, B (c i) (r i)` of `s` such that all “centers” `c i` belong to `s` and each `r i` satisfies `p (c i)`. The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to `nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see the proof of `paracompact_of_locally_compact_sigma_compact` for an example. The formalization is based on two [ncatlab](https://ncatlab.org/) proofs: * [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact); * [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds). See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a version of this lemma dealing with a covering of the whole space. In most cases (namely, if `B c r ∪ B c r'` is again a set of the form `B c r''`) it is possible to choose `α = X`. This fact is not yet formalized in `mathlib`. -/ theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis_set [locally_compact_space X] [sigma_compact_space X] [t2_space X] {ι : X → Type u} {p : Π x, ι x → Prop} {B : Π x, ι x → set X} {s : set X} (hs : is_closed s) (hB : ∀ x ∈ s, (𝓝 x).has_basis (p x) (B x)) : ∃ (α : Type v) (c : α → X) (r : Π a, ι (c a)), (∀ a, c a ∈ s ∧ p (c a) (r a)) ∧ (s ⊆ ⋃ a, B (c a) (r a)) ∧ locally_finite (λ a, B (c a) (r a)) := begin classical, -- For technical reasons we prepend two empty sets to the sequence `compact_exhaustion.choice X` set K' : compact_exhaustion X := compact_exhaustion.choice X, set K : compact_exhaustion X := K'.shiftr.shiftr, set Kdiff := λ n, K (n + 1) \ interior (K n), -- Now we restate some properties of `compact_exhaustion` for `K`/`Kdiff` have hKcov : ∀ x, x ∈ Kdiff (K'.find x + 1), { intro x, simpa only [K'.find_shiftr] using diff_subset_diff_right interior_subset (K'.shiftr.mem_diff_shiftr_find x) }, have Kdiffc : ∀ n, is_compact (Kdiff n ∩ s), from λ n, ((K.is_compact _).diff is_open_interior).inter_right hs, -- Next we choose a finite covering `B (c n i) (r n i)` of each -- `Kdiff (n + 1) ∩ s` such that `B (c n i) (r n i) ∩ s` is disjoint with `K n` have : ∀ n (x : Kdiff (n + 1) ∩ s), (K n)ᶜ ∈ 𝓝 (x : X), from λ n x, is_open.mem_nhds (K.is_closed n).is_open_compl (λ hx', x.2.1.2 $ K.subset_interior_succ _ hx'), haveI : ∀ n (x : Kdiff n ∩ s), nonempty (ι x) := λ n x, (hB x x.2.2).nonempty, choose! r hrp hr using (λ n (x : Kdiff (n + 1) ∩ s), (hB x x.2.2).mem_iff.1 (this n x)), have hxr : ∀ n x (hx : x ∈ Kdiff (n + 1) ∩ s), B x (r n ⟨x, hx⟩) ∈ 𝓝 x, from λ n x hx, (hB x hx.2).mem_of_mem (hrp _ ⟨x, hx⟩), choose T hT using λ n, (Kdiffc (n + 1)).elim_nhds_subcover' _ (hxr n), set T' : Π n, set ↥(Kdiff (n + 1) ∩ s) := λ n, T n, -- Finally, we take the union of all these coverings refine ⟨Σ n, T' n, λ a, a.2, λ a, r a.1 a.2, _, _, _⟩, { rintro ⟨n, x, hx⟩, exact ⟨x.2.2, hrp _ _⟩ }, { refine (λ x hx, mem_Union.2 _), rcases mem_bUnion_iff.1 (hT _ ⟨hKcov x, hx⟩) with ⟨⟨c, hc⟩, hcT, hcx⟩, exact ⟨⟨_, ⟨c, hc⟩, hcT⟩, hcx⟩ }, { intro x, refine ⟨interior (K (K'.find x + 3)), is_open.mem_nhds is_open_interior (K.subset_interior_succ _ (hKcov x).1), _⟩, have : (⋃ k ≤ K'.find x + 2, (range $ sigma.mk k) : set (Σ n, T' n)).finite, from (finite_le_nat _).bUnion (λ k hk, finite_range _), apply this.subset, rintro ⟨k, c, hc⟩, simp only [mem_Union, mem_set_of_eq, mem_image_eq, subtype.coe_mk], rintro ⟨x, hxB : x ∈ B c (r k c), hxK⟩, refine ⟨k, _, ⟨c, hc⟩, rfl⟩, have := (mem_compl_iff _ _).1 (hr k c hxB), contrapose! this with hnk, exact K.subset hnk (interior_subset hxK) }, end /-- Let `X` be a locally compact sigma compact Hausdorff topological space. Suppose that for each `x` the sets `B x : ι x → set X` with the predicate `p x : ι x → Prop` form a basis of the filter `𝓝 x`. Then there exists a locally finite covering `λ i, B (c i) (r i)` of `X` such that each `r i` satisfies `p (c i)` The notation is inspired by the case `B x r = metric.ball x r` but the theorem applies to `nhds_basis_opens` as well. If the covering must be subordinate to some open covering of `s`, then the user should use a basis obtained by `filter.has_basis.restrict_subset` or a similar lemma, see the proof of `paracompact_of_locally_compact_sigma_compact` for an example. The formalization is based on two [ncatlab](https://ncatlab.org/) proofs: * [locally compact and sigma compact spaces are paracompact](https://ncatlab.org/nlab/show/locally+compact+and+sigma-compact+spaces+are+paracompact); * [open cover of smooth manifold admits locally finite refinement by closed balls](https://ncatlab.org/nlab/show/partition+of+unity#ExistenceOnSmoothManifolds). See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis_set` for a version of this lemma dealing with a covering of a closed set. In most cases (namely, if `B c r ∪ B c r'` is again a set of the form `B c r''`) it is possible to choose `α = X`. This fact is not yet formalized in `mathlib`. -/ theorem refinement_of_locally_compact_sigma_compact_of_nhds_basis [locally_compact_space X] [sigma_compact_space X] [t2_space X] {ι : X → Type u} {p : Π x, ι x → Prop} {B : Π x, ι x → set X} (hB : ∀ x, (𝓝 x).has_basis (p x) (B x)) : ∃ (α : Type v) (c : α → X) (r : Π a, ι (c a)), (∀ a, p (c a) (r a)) ∧ (⋃ a, B (c a) (r a)) = univ ∧ locally_finite (λ a, B (c a) (r a)) := let ⟨α, c, r, hp, hU, hfin⟩ := refinement_of_locally_compact_sigma_compact_of_nhds_basis_set is_closed_univ (λ x _, hB x) in ⟨α, c, r, λ a, (hp a).2, univ_subset_iff.1 hU, hfin⟩ /-- A locally compact sigma compact Hausdorff space is paracompact. See also `refinement_of_locally_compact_sigma_compact_of_nhds_basis` for a more precise statement. -/ @[priority 100] -- See note [lower instance priority] instance paracompact_of_locally_compact_sigma_compact [locally_compact_space X] [sigma_compact_space X] [t2_space X] : paracompact_space X := begin refine ⟨λ α s ho hc, _⟩, choose i hi using Union_eq_univ_iff.1 hc, have : ∀ x : X, (𝓝 x).has_basis (λ t : set X, (x ∈ t ∧ is_open t) ∧ t ⊆ s (i x)) id, from λ x : X, (nhds_basis_opens x).restrict_subset (is_open.mem_nhds (ho (i x)) (hi x)), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis this with ⟨β, c, t, hto, htc, htf⟩, exact ⟨β, t, λ x, (hto x).1.2, htc, htf, λ b, ⟨i $ c b, (hto b).2⟩⟩ end /- Dieudonné‘s theorem: a paracompact Hausdorff space is normal. Formalization is based on the proof at [ncatlab](https://ncatlab.org/nlab/show/paracompact+Hausdorff+spaces+are+normal). -/ lemma normal_of_paracompact_t2 [t2_space X] [paracompact_space X] : normal_space X := begin /- First we show how to go from points to a set on one side. -/ have : ∀ (s t : set X), is_closed s → is_closed t → (∀ x ∈ s, ∃ u v, is_open u ∧ is_open v ∧ x ∈ u ∧ t ⊆ v ∧ disjoint u v) → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v, { /- For each `x ∈ s` we choose open disjoint `u x ∋ x` and `v x ⊇ t`. The sets `u x` form an open covering of `s`. We choose a locally finite refinement `u' : s → set X`, then `⋃ i, u' i` and `(closure (⋃ i, u' i))ᶜ` are disjoint open neighborhoods of `s` and `t`. -/ intros s t hs ht H, choose u v hu hv hxu htv huv using set_coe.forall'.1 H, rcases precise_refinement_set hs u hu (λ x hx, mem_Union.2 ⟨⟨x, hx⟩, hxu _⟩) with ⟨u', hu'o, hcov', hu'fin, hsub⟩, refine ⟨⋃ i, u' i, (closure (⋃ i, u' i))ᶜ, is_open_Union hu'o, is_closed_closure.is_open_compl, hcov', _, disjoint_compl_right.mono le_rfl (compl_le_compl subset_closure)⟩, rw [hu'fin.closure_Union, compl_Union, subset_Inter_iff], refine λ i x hxt hxu, absurd (htv i hxt) (closure_minimal _ (is_closed_compl_iff.2 $ hv _) hxu), exact λ y hyu hyv, huv i ⟨hsub _ hyu, hyv⟩ }, /- Now we apply the lemma twice: first to `s` and `t`, then to `t` and each point of `s`. -/ refine ⟨λ s t hs ht hst, this s t hs ht (λ x hx, _)⟩, rcases this t {x} ht is_closed_singleton (λ y hyt, _) with ⟨v, u, hv, hu, htv, hxu, huv⟩, { exact ⟨u, v, hu, hv, singleton_subset_iff.1 hxu, htv, huv.symm⟩ }, { have : x ≠ y, by { rintro rfl, exact hst ⟨hx, hyt⟩ }, rcases t2_separation this with ⟨v, u, hv, hu, hxv, hyu, hd⟩, exact ⟨u, v, hu, hv, hyu, singleton_subset_iff.2 hxv, disjoint.symm hd.le⟩ } end
e0593980375044a634c4ecf1abff3d0db8b8e820
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/tactic.lean
b2c74c1474d4897e08f30e8265c9ecc43a54aebd
[ "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
466
lean
import Lean.Meta open Lean open Lean.Meta axiom simple : forall {p q : Prop}, p → q → p def print (msg : MessageData) : MetaM Unit := do trace[Meta.Tactic] msg def tst1 : MetaM Unit := do let cinfo ← getConstInfo `simple let mvar ← mkFreshExprSyntheticOpaqueMVar cinfo.type let mvarId := mvar.mvarId! let (_, mvarId) ← introN mvarId 4 assumption mvarId let result ← instantiateMVars mvar print result set_option trace.Meta.Tactic true #eval tst1
214fecde25de25a09438d8fd6f6172a3f678bfa8
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/IR/CallingConvention.lean
e7ec83e8e11803304ba55bf104b1d206bb8461a5
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,540
lean
import Papyrus.Internal.Enum namespace Papyrus open Internal /-- LLVM calling conventions. Note that LLVM IR allows arbitrary numbers as calling convention identifiers. -/ enum CallingConvention : UInt32 | /-- The default llvm calling convention, compatible with C. This convention is the only calling convention that supports `vararg` calls. As with typical C calling conventions, the callee/caller have to tolerate certain amounts of prototype mismatch. -/ c := 0 | /-- This calling convention attempts to make calls as fast as possible (e.g., by passing things in registers). -/ fast := 8 | /-- This calling convention attempts to make code in the caller as efficient as possible under the assumption that the call is not commonly executed. As such, these calls often preserve all registers so that the call does not break any live ranges in the caller side. -/ cold := 9 | /-- Calling convention used by the Glasgow Haskell Compiler (GHC) -/ ghc := 10 | /-- Calling convention used by the High-Performance Erlang Compiler (HiPE).-/ hipe := 11 | /-- Calling convention for stack based JavaScript calls. -/ webKitJS := 12 | /-- Calling convention for dynamic register based calls (e.g., `stackmap` and `patchpoint` intrinsics). -/ anyReg := 13 | /-- Calling convention for runtime calls that preserves most registers. -/ preserveMost := 14 | /-- Calling convention for runtime calls that preserves (almost) all registers. -/ preserveAll := 15 | /-- Calling convention for Swift. -/ swift := 16 | /-- Calling convention for access functions. -/ cxxFastTLS := 17 | /-- This calling convention attempts to make calls as fast as possible while guaranteeing that tail call optimization can always be performed. -/ tail := 18 | /-- Calling convention on Windows for the Control Guard Check ICall function. The function takes exactly one argument (the address of the target function) passed in the first argument register, and has no return value. All register values are preserved. -/ cfGuardCheck := 19 | /-- This follows the Swift calling convention in how arguments are passed but guarantees tail calls will be made by making the callee clean up their stack. -/ swiftTail := 20 | /-- `stdcall` is the calling conventions mostly used by the Win32 API. It is basically the same as the C convention with the difference in that the callee is responsible for popping the arguments from the stack. -/ x86StdCall := 64 | /-- `fast` analog of `x86StdCall`. Passes first two arguments in `ECX`:`EDX` registers, others - via stack. Callee is responsible for stack cleaning. -/ x86FastCall := 65 | /-- ARM Procedure Calling Standard calling convention (obsolete, but still used on some targets). -/ armAPCS := 55 | /-- ARM Architecture Procedure Calling Standard calling convention (aka EABI). Soft floating point ABI. -/ armAAPCS := 67 | /-- ARM Architecture Procedure Calling Standard calling convention (aka EABI). Hard floating point ABI. -/ armAAPCSVFP := 68 | /-- Calling convention used for MSP430 interrupt routines. -/ msp430Intr := 69 | /-- Similar to `x86StdCall`. Passes first argument in ECX, others via stack. Callee is responsible for stack cleaning. MSVC uses this by default for methods in its ABI. -/ x86ThisCall := 70 | /-- Call to a PTX kernel. Passes all arguments in parameter space. -/ ptxKernel := 71 | /-- Call to a PTX device function. Passes all arguments in register or parameter space. -/ ptxDevice := 72 | /-- Calling convention for SPIR non-kernel device functions. * No lowering or expansion of arguments. * Structures are passed as a pointer to a struct with the `byval` attribute. * Functions can only call `spirFunc` and `spirKernel` functions. * Functions can only have zero or one return values. * Variable arguments are not allowed, except for `printf`. * How arguments/return values are lowered are not specified. * Functions are only visible to the devices. -/ spirFunc := 75 | /-- Calling convention for SPIR kernel functions. Inherits the restrictions of `spirFunc`, except: * Cannot have non-void return values. * Cannot have variable arguments. * Can also be called by the host. * Is externally visible. -/ spirKernel := 76 | /-- Calling conventions for Intel OpenCL built-ins. -/ intelOCLBuiltin := 77 | /-- The C convention as specified in the x86-64 supplement to the System V ABI, used on most non-Windows systems. -/ x8664SysV := 78 | /-- The C convention as implemented on Windows/x86-64 and AArch64. This convention differs from the more common `x8664SysV` convention in a number of ways, most notably in that XMM registers used to pass arguments are shadowed by GPRs, and vice versa. On AArch64, this is identical to the normal C (AAPCS) calling convention for normal functions, but floats are passed in integer registers to variadic functions. -/ win64 := 79 | /-- MSVC calling convention that passes vectors and vector aggregates in SSE registers. -/ x86VectorCall := 80 | /-- Calling convention used by HipHop Virtual Machine (HHVM) to perform calls to and from translation cache and for calling PHP functions. The HHVM calling convention supports tail/sibling call elimination. -/ hhvm := 81 | /-- HHVM calling convention for invoking C/C++ helpers. -/ hhvmC := 82 | /-- x86 hardware interrupt context. Callee may take one or two parameters, where the 1st represents a pointer to hardware context frame and the 2nd represents hardware error code, the presence of the later depends on the interrupt vector taken. Valid for both 32- and 64-bit subtargets. -/ x86Intr := 83 | /-- Calling convention used for AVR interrupt routines. -/ avrIntr := 84 | /-- Calling convention used for AVR signal routines. -/ avrSignal := 85 | /-- Calling convention used for special AVR rtlib functions which have an "optimized" convention to preserve registers. -/ avrBuiltin := 86 | /-- Calling convention used for Mesa vertex shaders, or AMDPAL last shader stage before rasterization (vertex shader if tessellation and geometry are not in use, or otherwise copy shader if one is needed). -/ amdGpuVS := 87 | /-- Calling convention used for Mesa/AMDPAL geometry shaders. -/ amdGpuGS := 88 | /-- Calling convention used for Mesa/AMDPAL pixel shaders. -/ amdGpuPS := 89 | /-- Calling convention used for Mesa/AMDPAL compute shaders. -/ amdGpuCS := 90 | /-- Calling convention for AMDGPU code object kernels. -/ amdGpuKernel := 91 | /-- Register calling convention used for parameters transfer optimization. -/ x86RegCall := 92 | /-- Calling convention used for Mesa/AMDPAL hull shaders (= tessellation control shaders). -/ amdGpuHs := 93 | /-- Calling convention used for special MSP430 rtlib functions which have an "optimized" convention using additional registers. -/ msp430Builtin := 94 | /-- Calling convention used for AMDPAL vertex shader if tessellation is in use. -/ amdGpuLs := 95 | /-- Calling convention used for AMDPAL shader stage before geometry shader if geometry is in use. So either the domain (= tessellation evaluation) shader if tessellation is in use, or otherwise the vertex shader. -/ amdGpuES := 96 | /-- Calling convention between AArch64 Advanced SIMD functions -/ aarch64VectorCall := 97 | /-- Calling convention between AArch64 SVE functions. -/ aarch64SVEVectorCall := 98 | /-- Calling convention for `emscripten __invoke_*` functions. The first argument is required to be the function ptr being indirectly called. The remainder matches the regular calling convention. -/ wasmEmscriptenInvoke := 99 | /-- Calling convention used for AMD graphics targets. -/ amdGpuGfx := 100 | /-- Calling convention used for M68k interrupt routines. -/ m68kIntr := 101 deriving BEq, DecidableEq, Repr namespace CallingConvention /-- The default calling convention (i.e., `c`). -/ def default := c /-- The start of the target-specific calling conventions (e.g., `x86FastCall`). -/ def firstTargetVal : UInt32 := 63 /-- The highest possible calling convention ID. -/ def maxVal : UInt32 := 1023 end CallingConvention instance : Inhabited CallingConvention := ⟨CallingConvention.default⟩
762e3a235bbcee13dcff3c13fa03011b8a91d9eb
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Meta/PPGoal.lean
34de76d95f05a65c74bf91cb0bf902b9d0fce2ed
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
9,306
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ import Lean.Meta.InferType import Lean.Meta.MatchUtil namespace Lean.Meta register_builtin_option pp.auxDecls : Bool := { defValue := false group := "pp" descr := "display auxiliary declarations used to compile recursive functions" } register_builtin_option pp.inaccessibleNames : Bool := { defValue := false group := "pp" descr := "display inaccessible declarations in the local context" } def withPPInaccessibleNamesImp (flag : Bool) (x : MetaM α) : MetaM α := withTheReader Core.Context (fun ctx => { ctx with options := pp.inaccessibleNames.setIfNotSet ctx.options flag }) x def withPPInaccessibleNames [MonadControlT MetaM m] [Monad m] (x : m α) (flag := true) : m α := mapMetaM (withPPInaccessibleNamesImp flag) x namespace ToHide structure State where hiddenInaccessibleProp : FVarIdSet := {} -- FVarIds of Propostions with inaccessible names but containing only visible names. We show only their types hiddenInaccessible : FVarIdSet := {} -- FVarIds with inaccessible names, but not in hiddenInaccessibleProp modified : Bool := false structure Context where goalTarget : Expr abbrev M := ReaderT Context $ StateRefT State MetaM /- Return true if `fvarId` is marked as an hidden inaccessible or inaccessible proposition -/ def isMarked (fvarId : FVarId) : M Bool := do let s ← get return s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId /- If `fvarId` isMarked, then unmark it. -/ def unmark (fvarId : FVarId) : M Unit := do modify fun s => { hiddenInaccessible := s.hiddenInaccessible.erase fvarId hiddenInaccessibleProp := s.hiddenInaccessibleProp.erase fvarId modified := true } def moveToHiddeProp (fvarId : FVarId) : M Unit := do modify fun s => { hiddenInaccessible := s.hiddenInaccessible.erase fvarId hiddenInaccessibleProp := s.hiddenInaccessibleProp.insert fvarId modified := true } /- Return true if the given local declaration has a "visible dependency", that is, it contains a free variable that is `hiddenInaccessible` Recall that hiddenInaccessibleProps are visible, only their names are hidden -/ def hasVisibleDep (localDecl : LocalDecl) : M Bool := do let s ← get return (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId => !s.hiddenInaccessible.contains fvarId /- Return true if the given local declaration has a "nonvisible dependency", that is, it contains a free variable that is `hiddenInaccessible` or `hiddenInaccessibleProp` -/ def hasInaccessibleNameDep (localDecl : LocalDecl) : M Bool := do let s ← get return (← getMCtx).findLocalDeclDependsOn localDecl fun fvarId => s.hiddenInaccessible.contains fvarId || s.hiddenInaccessibleProp.contains fvarId /- If `e` is visible, then any inaccessible in `e` marked as hidden should be unmarked. -/ partial def visitVisibleExpr (e : Expr) : M Unit := do visit (← instantiateMVars e) |>.run where visit (e : Expr) : MonadCacheT Expr Unit M Unit := do if e.hasFVar then checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId _ => if (← isMarked fvarId) then unmark fvarId | _ => pure () def fixpointStep : M Unit := do visitVisibleExpr (← read).goalTarget -- The goal target is a visible forward dependency (← getLCtx).forM fun localDecl => do let fvarId := localDecl.fvarId if (← get).hiddenInaccessible.contains fvarId then if (← hasVisibleDep localDecl) then /- localDecl is marked to be hidden, but it has a (backward) visible dependency. -/ unmark fvarId if (← isProp localDecl.type) then unless (← hasInaccessibleNameDep localDecl) do moveToHiddeProp fvarId else visitVisibleExpr localDecl.type match localDecl.value? with | some value => visitVisibleExpr value | _ => pure () partial def fixpoint : M Unit := do modify fun s => { s with modified := false } fixpointStep if (← get).modified then fixpoint /- If pp.inaccessibleNames == false, then collect two sets of `FVarId`s : `hiddenInaccessible` and `hiddenInaccessibleProp` 1- `hiddenInaccessible` contains `FVarId`s of free variables with inaccessible names that a) are not propositions or are propositions containing "visible" names. 2- `hiddenInaccessibleProp` contains `FVarId`s of free variables with inaccessible names that are propositions containing "visible" names. Both sets do not contain `FVarId`s that contain visible backward or forward dependencies. The `goalTarget` counts as a forward dependency. We say a name is visible if it is a free variable with FVarId not in `hiddenInaccessible` nor `hiddenInaccessibleProp` -/ def collect (goalTarget : Expr) : MetaM (FVarIdSet × FVarIdSet) := do if pp.inaccessibleNames.get (← getOptions) then /- Don't hide inaccessible names when `pp.inaccessibleNames` is set to true. -/ return ({}, {}) else let lctx ← getLCtx let hiddenInaccessible := lctx.foldl (init := {}) fun hiddenInaccessible localDecl => do if localDecl.userName.isInaccessibleUserName then hiddenInaccessible.insert localDecl.fvarId else hiddenInaccessible let (_, s) ← fixpoint.run { goalTarget := goalTarget } |>.run { hiddenInaccessible := hiddenInaccessible } return (s.hiddenInaccessible, s.hiddenInaccessibleProp) end ToHide private def addLine (fmt : Format) : Format := if fmt.isNil then fmt else fmt ++ Format.line def ppGoal (mvarId : MVarId) : MetaM Format := do match (← getMCtx).findDecl? mvarId with | none => pure "unknown goal" | some mvarDecl => do let indent := 2 -- Use option let ppAuxDecls := pp.auxDecls.get (← getOptions) let lctx := mvarDecl.lctx let lctx := lctx.sanitizeNames.run' { options := (← getOptions) } withLCtx lctx mvarDecl.localInstances do let (hidden, hiddenProp) ← ToHide.collect mvarDecl.type -- The followint two `let rec`s are being used to control the generated code size. -- Then should be remove after we rewrite the compiler in Lean let rec pushPending (ids : List Name) (type? : Option Expr) (fmt : Format) : MetaM Format := if ids.isEmpty then pure fmt else let fmt := addLine fmt match type? with | none => pure fmt | some type => do let typeFmt ← ppExpr type pure $ fmt ++ (Format.joinSep ids.reverse (format " ") ++ " :" ++ Format.nest indent (Format.line ++ typeFmt)).group let rec ppVars (varNames : List Name) (prevType? : Option Expr) (fmt : Format) (localDecl : LocalDecl) : MetaM (List Name × Option Expr × Format) := do if hiddenProp.contains localDecl.fvarId then let fmt ← pushPending varNames prevType? fmt let fmt := addLine fmt let type ← instantiateMVars localDecl.type let typeFmt ← ppExpr type let fmt := fmt ++ " : " ++ typeFmt pure ([], none, fmt) else match localDecl with | LocalDecl.cdecl _ _ varName type _ => let varName := varName.simpMacroScopes let type ← instantiateMVars type if prevType? == none || prevType? == some type then pure (varName :: varNames, some type, fmt) else do let fmt ← pushPending varNames prevType? fmt pure ([varName], some type, fmt) | LocalDecl.ldecl _ _ varName type val _ => do let varName := varName.simpMacroScopes let fmt ← pushPending varNames prevType? fmt let fmt := addLine fmt let type ← instantiateMVars type let val ← instantiateMVars val let typeFmt ← ppExpr type let valFmt ← ppExpr val let fmt := fmt ++ (format varName ++ " : " ++ typeFmt ++ " :=" ++ Format.nest indent (Format.line ++ valFmt)).group pure ([], none, fmt) let (varNames, type?, fmt) ← lctx.foldlM (init := ([], none, Format.nil)) fun (varNames, prevType?, fmt) (localDecl : LocalDecl) => if !ppAuxDecls && localDecl.isAuxDecl || hidden.contains localDecl.fvarId then pure (varNames, prevType?, fmt) else ppVars varNames prevType? fmt localDecl let fmt ← pushPending varNames type? fmt let fmt := addLine fmt let typeFmt ← ppExpr (← instantiateMVars mvarDecl.type) let fmt := fmt ++ "⊢ " ++ Format.nest indent typeFmt match mvarDecl.userName with | Name.anonymous => pure fmt | name => return "case " ++ format name.eraseMacroScopes ++ Format.line ++ fmt end Lean.Meta
95766917039192b6d74ee1d5dc249e60bbf474ae
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/doIssue.lean
ba487ccb8b9602ab4e6cf8c4c00d144f6e0a31cb
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
466
lean
def f (x : Nat) : IO Unit := do x -- Error IO.println x def f' (x : Nat) : IO Unit := do discard x IO.println x def g (xs : Array Nat) : IO Unit := do xs.set! 0 1 -- Error IO.println xs def g' (xs : Array Nat) : IO Unit := do discard <| xs.set! 0 1 -- Error IO.println xs def h (xs : Array Nat) : IO Unit := do pure (xs.set! 0 1) -- Error IO.println xs def h' (xs : Array Nat) : IO Unit := do discard <| pure (xs.set! 0 1) IO.println xs
44a1a90164f226283107d65079dc0b38ee701c79
5c5878e769950eabe897ad08485b3ba1a619cea9
/src/categories/isomorphism.lean
d210c26c64898f6db76aa5960d21d69d62eccac2
[ "Apache-2.0" ]
permissive
semorrison/lean-category-theory-pr
39dc2077fcb41b438e61be1685e4cbca298767ed
7adc8d91835e883db0fe75aa33661bc1480dbe55
refs/heads/master
1,583,748,682,010
1,535,111,040,000
1,535,111,040,000
128,731,071
1
2
Apache-2.0
1,528,069,880,000
1,523,258,452,000
Lean
UTF-8
Lean
false
false
6,187
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.category import category_theory.functor import .tactics universes u v namespace category_theory structure iso {C : Type u} [category.{u v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id : inv ≫ hom = 𝟙 Y . obviously) restate_axiom iso.hom_inv_id restate_axiom iso.inv_hom_id attribute [simp,ematch] iso.hom_inv_id_lemma iso.inv_hom_id_lemma infixr ` ≅ `:10 := iso -- type as \cong variables {C : Type u} [𝒞 : category.{u v} C] include 𝒞 variables {X Y Z : C} namespace iso instance : has_coe (iso.{u v} X Y) (X ⟶ Y) := { coe := iso.hom } -- -- These lemmas are quite common, to help us avoid having to muck around with associativity. -- -- If anyone has a suggestion for automating them away, I would be very appreciative. -- @[simp,ematch] lemma hom_inv_id_assoc_lemma (I : X ≅ Y) (f : X ⟶ Z) : I.hom ≫ I.inv ≫ f = f := -- begin -- -- `obviously'` says: -- rw [←category.assoc_lemma, iso.hom_inv_id_lemma, category.id_comp_lemma] -- end -- @[simp,ematch] lemma inv_hom_id_assoc_lemma (I : X ≅ Y) (f : Y ⟶ Z) : I.inv ≫ I.hom ≫ f = f := -- begin -- -- `obviously'` says: -- rw [←category.assoc_lemma, iso.inv_hom_id_lemma, category.id_comp_lemma] -- end @[extensionality] lemma ext (α β : X ≅ Y) (w : α.hom = β.hom) : α = β := begin induction α with f g wα1 wα2, induction β with h k wβ1 wβ2, simp at w, have p : g = k, begin induction w, dsimp at *, rw [← category.id_comp_lemma C k, ←wα2, category.assoc_lemma, wβ1, category.comp_id_lemma] end, -- `obviously'` says: induction p, induction w, refl end @[refl] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X, hom_inv_id := begin /- `obviously'` says: -/ simp end, inv_hom_id := begin /- `obviously'` says: -/ simp end } -- TODO maybe these can have ematch? @[simp] lemma refl_map (X : C) : (iso.refl X).hom = 𝟙 X := rfl @[simp] lemma refl_inv (X : C) : (iso.refl X).inv = 𝟙 X := rfl @[trans] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := α.hom ≫ β.hom, inv := β.inv ≫ α.inv, hom_inv_id := begin /- `obviously'` says: -/ erw [category.assoc_lemma], conv { to_lhs, congr, skip, rw ← category.assoc_lemma }, rw iso.hom_inv_id_lemma, rw category.id_comp_lemma, rw iso.hom_inv_id_lemma end, inv_hom_id := begin /- `obviously'` says: -/ erw [category.assoc_lemma], conv { to_lhs, congr, skip, rw ← category.assoc_lemma }, rw iso.inv_hom_id_lemma, rw category.id_comp_lemma, rw iso.inv_hom_id_lemma end } infixr ` ♢ `:80 := iso.trans -- type as \diamonds @[simp,ematch] lemma trans_hom (α : X ≅ Y) (β : Y ≅ Z) : (α ♢ β).hom = α.hom ≫ β.hom := rfl @[simp,ematch] lemma trans_inv (α : X ≅ Y) (β : Y ≅ Z) : (α ♢ β).inv = β.inv ≫ α.inv := rfl @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id := begin /- `obviously'` says: -/ simp end, inv_hom_id := begin /- `obviously'` says: -/ simp end } end iso class is_iso (f : X ⟶ Y) := (inv : Y ⟶ X) (hom_inv_id : f ≫ inv = 𝟙 X . obviously) (inv_hom_id : inv ≫ f = 𝟙 Y . obviously) restate_axiom is_iso.hom_inv_id restate_axiom is_iso.inv_hom_id attribute [simp,ematch] is_iso.hom_inv_id_lemma is_iso.inv_hom_id_lemma namespace is_iso instance (X : C) : is_iso (𝟙 X) := { inv := 𝟙 X, hom_inv_id := by obviously', inv_hom_id := by obviously' } instance of_iso (f : X ≅ Y) : is_iso f.hom := { inv := f.inv, hom_inv_id := begin /- `obviously'` says: -/ simp end, inv_hom_id := begin /- `obviously'` says: -/ simp end } instance of_iso_inverse (f : X ≅ Y) : is_iso f.inv := { inv := f.hom, hom_inv_id := begin /- `obviously'` says: -/ simp end, inv_hom_id := begin /- `obviously'` says: -/ simp end } end is_iso class epi (f : X ⟶ Y) := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) class mono (f : X ⟶ Y) := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := begin -- This is an interesting test case for better rewrite automation. intros, rw [←category.id_comp_lemma C g, ←category.id_comp_lemma C h], rw [← is_iso.inv_hom_id_lemma f], erw [category.assoc_lemma, w, category.assoc_lemma], end } instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := begin intros, rw [←category.comp_id_lemma C g, ←category.comp_id_lemma C h], rw [← is_iso.hom_inv_id_lemma f], erw [←category.assoc_lemma, w, ←category.assoc_lemma] end } @[simp] lemma cancel_epi (f : X ⟶ Y) [epi f] (g h : Y ⟶ Z) : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin /- `obviously'` says: -/ intros, cases a, refl end ⟩ @[simp] lemma cancel_mono (f : X ⟶ Y) [mono f] (g h : Z ⟶ X) : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin /- `obviously'` says: -/ intros, cases a, refl end ⟩ namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [𝒟 : category.{u₂ v₂} D] include 𝒟 def on_isos (F : C ↝ D) {X Y : C} (i : X ≅ Y) : (F X) ≅ (F Y) := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id := by obviously', inv_hom_id := by obviously' } @[simp,ematch] lemma on_isos_hom (F : C ↝ D) {X Y : C} (i : X ≅ Y) : (F.on_isos i).hom = F.map i.hom := rfl @[simp,ematch] lemma on_isos_inv (F : C ↝ D) {X Y : C} (i : X ≅ Y) : (F.on_isos i).inv = F.map i.inv := rfl end functor end category_theory
09c3070065737d8c2a1eb609957f66db576b761d
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/algebra/uniform_group.lean
7a8f7faf8dea85efebbe7bfe2487009eb6388249
[ "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
20,527
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Uniform structure on topological groups: * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) * `add_group_with_zero_nhd`: construct the topological structure from a group with a neighbourhood around zero. Then with `topological_add_group.to_uniform_space` one can derive a `uniform_space`. -/ import topology.uniform_space.uniform_embedding topology.uniform_space.separation topology.algebra.group noncomputable theory local attribute [instance, priority 0] classical.prop_decidable local notation `𝓤` := uniformity section uniform_add_group open filter set variables {α : Type*} {β : Type*} /-- A uniform (additive) group is a group in which the addition and negation are uniformly continuous. -/ class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) theorem uniform_add_group.mk' {α} [uniform_space α] [add_group α] (h₁ : uniform_continuous (λp:α×α, p.1 + p.2)) (h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α := ⟨(uniform_continuous_fst.prod_mk (uniform_continuous_snd.comp h₂)).comp h₁⟩ variables [uniform_space α] [add_group α] [uniform_add_group α] lemma uniform_continuous_sub' : uniform_continuous (λp:α×α, p.1 - p.2) := uniform_add_group.uniform_continuous_sub α lemma uniform_continuous_sub [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x - g x) := (hf.prod_mk hg).comp uniform_continuous_sub' lemma uniform_continuous_neg [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, - f x) := have uniform_continuous (λx, 0 - f x), from uniform_continuous_sub uniform_continuous_const hf, by simp * at * lemma uniform_continuous_neg' : uniform_continuous (λx:α, - x) := uniform_continuous_neg uniform_continuous_id lemma uniform_continuous_add [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x + g x) := have uniform_continuous (λx, f x - - g x), from uniform_continuous_sub hf $ uniform_continuous_neg hg, by simp * at * lemma uniform_continuous_add' : uniform_continuous (λp:α×α, p.1 + p.2) := uniform_continuous_add uniform_continuous_fst uniform_continuous_snd instance uniform_add_group.to_topological_add_group : topological_add_group α := { continuous_add := uniform_continuous_add'.continuous, continuous_neg := uniform_continuous_neg'.continuous } instance [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) := ⟨uniform_continuous.prod_mk (uniform_continuous_sub (uniform_continuous_fst.comp uniform_continuous_fst) (uniform_continuous_snd.comp uniform_continuous_fst)) (uniform_continuous_sub (uniform_continuous_fst.comp uniform_continuous_snd) (uniform_continuous_snd.comp uniform_continuous_snd)) ⟩ lemma uniformity_translate (a : α) : (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) = 𝓤 α := le_antisymm (uniform_continuous_add uniform_continuous_id uniform_continuous_const) (calc 𝓤 α = ((𝓤 α).map (λx:α×α, (x.1 + -a, x.2 + -a))).map (λx:α×α, (x.1 + a, x.2 + a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) : filter.map_mono (uniform_continuous_add uniform_continuous_id uniform_continuous_const)) lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) := begin refine ⟨assume x y, eq_of_add_eq_add_right, _⟩, rw [← uniformity_translate a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end section variables (α) lemma uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λx:α×α, x.2 - x.1) (nhds (0:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap_comp], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invarant uniform_continuous_sub' hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_sets_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invarant uniform_continuous_add' hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 0 (b - a) a } end end lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x - y ∈ closure ({0} : set α) := have embedding (λa, a + (y - x)), from (uniform_embedding_translate (y - x)).embedding, show (x, y) ∈ ⋂₀ (𝓤 α).sets ↔ x - y ∈ closure ({0} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_zero α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_eq_empty] end lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : tendsto f (nhds 0) (nhds 0)) : uniform_continuous f := begin have : ((λx:β×β, x.2 - x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 - x.1)), { simp only [is_add_group_hom.map_sub f] }, rw [uniform_continuous, uniformity_eq_comap_nhds_zero α, uniformity_eq_comap_nhds_zero β, tendsto_comap_iff, this], exact tendsto.comp tendsto_comap h end lemma uniform_continuous_of_continuous [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_zero $ suffices tendsto f (nhds 0) (nhds (f 0)), by rwa [is_add_group_hom.map_zero f] at this, h.tendsto 0 end uniform_add_group section topological_add_comm_group universes u v w x open filter variables {G : Type u} [add_comm_group G] [topological_space G] [topological_add_group G] variable (G) def topological_add_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 - p.1) (nhds 0), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 0)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto ((λp, -p) ∘ (λp:G×G, p.2 - p.1)) (comap (λp:G×G, p.2 - p.1) (nhds 0)) (nhds (-0)), { simpa [(∘), tendsto_comap_iff] }, exact tendsto.comp tendsto_comap (tendsto_neg tendsto_id) end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_half U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 - p.1) ⁻¹' V), have H : (λp:G×G, p.2 - p.1) ⁻¹' V ∈ comap (λp:G×G, p.2 - p.1) (nhds (0 : G)), by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 - p.1) ⁻¹' V) ((λp:G×G, p.2 - p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 - p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa using V_sum _ _ Hz1 Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ comap (λp:G×G, p.2 - p.1) (nhds (0 : G)), rw [is_open_iff_mem_nhds], refine forall_congr (assume a, forall_congr (assume ha, _)), rw [← nhds_translation a, mem_comap_sets, mem_comap_sets], refine exists_congr (assume t, exists_congr (assume ht, _)), show (λ (y : G), y - a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd - p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } section local attribute [instance] topological_add_group.to_uniform_space lemma uniformity_eq_comap_nhds_zero' : 𝓤 G = comap (λp:G×G, p.2 - p.1) (nhds (0 : G)) := rfl variable {G} lemma topological_add_group_is_uniform : uniform_add_group G := have tendsto ((λp:(G×G), p.1 - p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((nhds 0).prod (nhds 0))) (nhds (0 - 0)) := tendsto_comap.comp (tendsto_sub tendsto_fst tendsto_snd), begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_zero' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘)] end end lemma to_uniform_space_eq {α : Type*} [u : uniform_space α] [add_comm_group α] [uniform_add_group α]: topological_add_group.to_uniform_space α = u := begin ext : 1, show @uniformity α (topological_add_group.to_uniform_space α) = 𝓤 α, rw [uniformity_eq_comap_nhds_zero' α, uniformity_eq_comap_nhds_zero α] end end topological_add_comm_group namespace add_comm_group section Z_bilin variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [add_comm_group α] [add_comm_group β] [add_comm_group γ] /- TODO: when modules are changed to have more explicit base ring, then change replace `is_Z_bilin` by using `is_bilinear_map ℤ` from `tensor_product`. -/ class is_Z_bilin (f : α × β → γ) : Prop := (add_left : ∀ a a' b, f (a + a', b) = f (a, b) + f (a', b)) (add_right : ∀ a b b', f (a, b + b') = f (a, b) + f (a, b')) variables (f : α × β → γ) [is_Z_bilin f] instance is_Z_bilin.comp_hom {g : γ → δ} [add_comm_group δ] [is_add_group_hom g] : is_Z_bilin (g ∘ f) := by constructor; simp [(∘), is_Z_bilin.add_left f, is_Z_bilin.add_right f, is_add_group_hom.map_add g] instance is_Z_bilin.comp_swap : is_Z_bilin (f ∘ prod.swap) := ⟨λ a a' b, is_Z_bilin.add_right f b a a', λ a b b', is_Z_bilin.add_left f b b' a⟩ lemma is_Z_bilin.zero_left : ∀ b, f (0, b) = 0 := begin intro b, apply add_self_iff_eq_zero.1, rw ←is_Z_bilin.add_left f, simp end lemma is_Z_bilin.zero_right : ∀ a, f (a, 0) = 0 := is_Z_bilin.zero_left (f ∘ prod.swap) lemma is_Z_bilin.zero : f (0, 0) = 0 := is_Z_bilin.zero_left f 0 lemma is_Z_bilin.neg_left : ∀ a b, f (-a, b) = -f (a, b) := begin intros a b, apply eq_of_sub_eq_zero, rw [sub_eq_add_neg, neg_neg, ←is_Z_bilin.add_left f, neg_add_self, is_Z_bilin.zero_left f] end lemma is_Z_bilin.neg_right : ∀ a b, f (a, -b) = -f (a, b) := assume a b, is_Z_bilin.neg_left (f ∘ prod.swap) b a lemma is_Z_bilin.sub_left : ∀ a a' b, f (a - a', b) = f (a, b) - f (a', b) := begin intros, dsimp [algebra.sub], rw [is_Z_bilin.add_left f, is_Z_bilin.neg_left f] end lemma is_Z_bilin.sub_right : ∀ a b b', f (a, b - b') = f (a, b) - f (a,b') := assume a b b', is_Z_bilin.sub_left (f ∘ prod.swap) b b' a end Z_bilin end add_comm_group open add_comm_group filter set function section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} -- α, β and G are abelian topological groups, G is complete Hausdorff variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables {G : Type*} [uniform_space G] [add_comm_group G] [uniform_add_group G] [complete_space G] [separated G] variables {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : is_Z_bilin ψ] include hψ ψbilin lemma is_Z_bilin.tendsto_zero_left (x₁ : α) : tendsto ψ (nhds (x₁, 0)) (nhds 0) := begin have := continuous.tendsto hψ (x₁, 0), rwa [is_Z_bilin.zero_right ψ] at this end lemma is_Z_bilin.tendsto_zero_right (y₁ : β) : tendsto ψ (nhds (0, y₁)) (nhds 0) := begin have := continuous.tendsto hψ (0, y₁), rwa [is_Z_bilin.zero_left ψ] at this end end section variables {α : Type*} {β : Type*} variables [topological_space α] [add_comm_group α] [topological_add_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [add_comm_group β] [topological_add_group β] variables {e : β → α} [is_add_group_hom e] (de : dense_embedding e) include de lemma tendsto_sub_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ nhds (x₀, x₀)) (nhds 0) := begin have comm : (λx:α×α, x.2-x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 - t.1), { ext t, change e t.2 - e t.1 = e (t.2 - t.1), rwa ← is_add_group_hom.map_sub e t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2-x.1) (nhds (x₀, x₀)) (nhds (e 0)), { have := continuous.tendsto (continuous.comp continuous_swap continuous_sub') (x₀, x₀), simpa [-sub_eq_add_neg, sub_self, eq.symm (is_add_group_hom.map_zero e)] using this }, have := de.tendsto_comap_nhds_nhds lim comm, simp [-sub_eq_add_neg, this] end end namespace dense_embedding open filter variables {α : Type*} [topological_space α] variables {β : Type*} [topological_space β] variables {γ : Type*} [uniform_space γ] [complete_space γ] [separated γ] lemma continuous_extend_of_cauchy {e : α → β} {f : α → γ} (de : dense_embedding e) (h : ∀ b : β, cauchy (map f (comap e $ nhds b))) : continuous (de.extend f) := continuous_extend de $ λ b, complete_space.complete (h b) end dense_embedding namespace dense_embedding variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated G] [complete_space G] variables {e : β → α} [is_add_group_hom e] (de : dense_embedding e) variables {f : δ → γ} [is_add_group_hom f] (df : dense_embedding f) variables {φ : β × δ → G} (hφ : continuous φ) [bilin : is_Z_bilin φ] include de df hφ bilin variables {W' : set G} (W'_nhd : W' ∈ nhds (0 : G)) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ comap e (nhds x₀), ∀ x x' ∈ U₂, φ (x' - x, y₁) ∈ W' := begin let Nx := nhds x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (filter.prod (comap e Nx) (comap e Nx)) (nhds (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ nhds (x₀, x₀)) (nhds y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim := tendsto.comp lim1 (is_Z_bilin.tendsto_zero_right hφ y₁), rw tendsto_prod_self_iff at lim, exact lim W' W'_nhd, end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ comap e (nhds x₀), ∃ V ∈ comap f (nhds y₀), ∀ x x' ∈ U, ∀ y y' ∈ V, φ (x', y') - φ (x, y) ∈ W' := begin let Nx := nhds x₀, let Ny := nhds y₀, let dp := dense_embedding.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto φ (nhds (0, 0)) (nhds 0), { have := continuous.tendsto hφ (0, 0), rwa [is_Z_bilin.zero φ] at this }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee $ nhds (x₀, x₀)) (comap ff $ nhds (y₀, y₀))) (nhds 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee (nhds (x₀, x₀))) (comap ff (nhds (y₀, y₀)))) (filter.prod (nhds 0) (nhds 0)), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_sub_sub lim_φ }, rcases exists_nhds_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ comap e (nhds x₀), ∃ V₁ ∈ comap f (nhds y₀), ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x' x_in x'_in y y' y_in y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, have : ∃ x₁, x₁ ∈ U₁ := exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 de.comap_nhds_neq_bot U₁ U₁_nhd), rcases this with ⟨x₁, x₁_in⟩, have : ∃ y₁, y₁ ∈ V₁ := exists_mem_of_ne_empty (forall_sets_neq_empty_iff_neq_bot.2 df.comap_nhds_neq_bot V₁ V₁_nhd), rcases this with ⟨y₁, y₁_in⟩, rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de (continuous.comp continuous_swap hφ) W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem_sets U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem_sets V₁_nhd V₂_nhd], rintros x x' ⟨xU₁, xU₂⟩ ⟨x'U₁, x'U₂⟩ y y' ⟨yV₁, yV₂⟩ ⟨y'V₁, y'V₂⟩, have key_formula : φ(x', y') - φ(x, y) = φ(x' - x, y₁) + φ(x' - x, y' - y₁) + φ(x₁, y' - y) + φ(x - x₁, y' - y), { repeat { rw is_Z_bilin.sub_left φ }, repeat { rw is_Z_bilin.sub_right φ }, apply eq_of_sub_eq_zero, simp }, rw key_formula, have h₁ := HU x x' xU₂ x'U₂, have h₂ := H x x' xU₁ x'U₁ y₁ y' y₁_in y'V₁, have h₃ := HV y y' yV₂ y'V₂, have h₄ := H x₁ x x₁_in xU₁ y y' yV₁ y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense sub-groups into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (dense_embedding.prod de df) φ) := begin let dp := dense_embedding.prod de df, refine dense_embedding.continuous_extend_of_cauchy (dense_embedding.prod de df) _, rintro ⟨x₀, y₀⟩, split, { apply map_ne_bot, apply comap_neq_bot, intros U h, rcases exists_mem_of_ne_empty (mem_closure_iff_nhds.1 (dp.dense (x₀, y₀)) U h) with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), φ p.2 - φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (filter.prod (nhds (x₀, y₀)) (nhds (x₀, y₀)))) ≤ nhds 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap_sets at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap_sets at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap_sets, nhds_prod_eq], existsi set.prod (set.prod U' V') (set.prod U' V'), rw mem_prod_same_iff, simp only [exists_prop], split, { change U' ∈ nhds x₀ at U'_nhd, change V' ∈ nhds y₀ at V'_nhd, have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage_eq, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_embedding
9e6710d31871c3d7a33f2a5a40134f3e95b7ef6f
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/smt/array.lean
e324f1bc0aa202a4038b2a04a87c6f807ccc802c
[ "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
951
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ namespace smt universes u v def array (α : Type u) (β : Type v) := α → β variables {α : Type u} {β : Type v} open tactic def select (a : array α β) (i : α) : β := a i lemma arrayext (a₁ a₂ : array α β) : (∀ i, select a₁ i = select a₂ i) → a₁ = a₂ := funext variable [decidable_eq α] def store (a : array α β) (i : α) (v : β) : array α β := λ j, if j = i then v else select a j @[simp] lemma select_store (a : array α β) (i : α) (v : β) : select (store a i v) i = v := by unfold smt.store smt.select; dsimp; rewrite if_pos; reflexivity @[simp] lemma select_store_ne (a : array α β) (i j : α) (v : β) : j ≠ i → select (store a i v) j = select a j := by intros; unfold smt.store smt.select; dsimp; rewrite if_neg; assumption end smt
a2a108317f322d6ba411a374813d4147708dc8d9
b147e1312077cdcfea8e6756207b3fa538982e12
/tests/examples.lean
5a5ba18c47bfa3e152bfe9bce5add46d9fe7389e
[ "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
2,936
lean
import tactic data.stream.basic data.set.basic data.finset data.multiset open tactic universe u variable {α : Type} example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true := begin dunfold has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (s t u : set ℕ) (h : s ⊆ t ∩ u) (h' : u ⊆ s) : u ⊆ s → true := begin delta has_subset.subset has_inter.inter at *, -- trace_state, intro1, triv end example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, -- trace_state, rw [←h, ←h'] end example (x y z : ℕ) (h'' : true) (h : 0 + y = x) (h' : 0 + y = z) : x = z + 0 := begin simp at *, simp [h] at h', simp [*] end def my_id (x : α) := x def my_id_def (x : α) : my_id x = x := rfl example (x y z : ℕ) (h'' : true) (h : 0 + my_id y = x) (h' : 0 + y = z) : x = z + 0 := begin simp [my_id_def] at *, simp [h] at h', simp [*] end @[simp] theorem mem_set_of {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl -- TODO: write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := begin dsimp [subset_def, union_def] at *, intros x h, cases h; back_chaining_using_hs end theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := begin dsimp [subset_def, inter_def] at *, intros x h, split; back_chaining_using_hs end /- extensionality -/ example : true := begin have : ∀ (s₀ s₁ : set ℕ), s₀ = s₁, { intros, ext1, guard_target x ∈ s₀ ↔ x ∈ s₁, admit }, have : ∀ (s₀ s₁ : finset ℕ), s₀ = s₁, { intros, ext1, guard_target a ∈ s₀ ↔ a ∈ s₁, admit }, have : ∀ (s₀ s₁ : multiset ℕ), s₀ = s₁, { intros, ext1, guard_target multiset.count a s₀ = multiset.count a s₁, admit }, have : ∀ (s₀ s₁ : list ℕ), s₀ = s₁, { intros, ext1, guard_target list.nth s₀ n = list.nth s₁ n, admit }, have : ∀ (s₀ s₁ : stream ℕ), s₀ = s₁, { intros, ext1, guard_target stream.nth n s₀ = stream.nth n s₁, admit }, have : ∀ n (s₀ s₁ : array n ℕ), s₀ = s₁, { intros, ext1, guard_target array.read s₀ i = array.read s₁ i, admit }, trivial end /- refine_struct -/ section refine_struct variables {α} [_inst : monoid α] include _inst example : true := begin have : group α, { refine_struct { .._inst }, guard_tags _field inv group, admit, guard_tags _field mul_left_inv group, admit, }, trivial end end refine_struct
7d24d6e5e997a22c6123a58b850087e904ef31e2
0f5090f82d527e0df5bf3adac9f9e2e1d81d71e2
/src/kenji/polished.lean
e644a06710817acb6896792dbf99485b1e94726f
[]
no_license
apurvanakade/mc2020-lean-projects
36eb42c4baccc37183635c36f8e1b3afa4ec1230
02466225aa629ab1232043bcc0a053a099fdb939
refs/heads/master
1,688,791,717,534
1,597,874,092,000
1,597,874,092,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,803
lean
import ring_theory.fractional_ideal import ring_theory.discrete_valuation_ring import linear_algebra.basic universes u open_locale classical variables (R : Type u) [integral_domain R] (R' : Type u) [comm_ring R'] /- `local_id_is_id` and the other lemmas probably belong in `ring_theory/integral_domains` or whatever For integral domains… `local_id_is_id` asserts that for any submodule `S` that does not contain `0` induces an `integral_domain` on an `integral_domain`. `local_at_prime_of_id_is_id` is the same, with the localization being at a prime `lt_add_nonmem` proves that whenever a ∉ I, I < I+(a) `zero_prime` is a proof that (0) is a prime ideal `nonzero_mem_of_gt_bot` is whenever I ≠ ⊥, there exists a nonzero element of I `ideal_mul_eq_zero` is that whenever I * J = ⊥, either I = ⊥ or J = ⊥. -/ theorem local_id_is_id (S : submonoid R) (zero_non_mem : ((0 : R) ∉ S)) {f : localization_map S (localization S)} : is_integral_domain (localization S) := begin split, {--nontrivial localization (pair ne) use f.to_fun 1, use f.to_fun 0, intro one_eq_zero, have h2 := (localization_map.eq_iff_exists f).1 one_eq_zero, cases h2 with c h2, rw [zero_mul, one_mul] at h2, rw ← h2 at zero_non_mem, exact zero_non_mem c.property }, { exact mul_comm }, {--bulk intros x y mul_eq_zero, cases f.surj' x with a akey, cases f.surj' y with b bkey, have h1 : x * (f.to_fun( a.snd)) * y * (f.to_fun(b.snd))= 0, { rw [mul_assoc x, ← mul_comm y, ← mul_assoc, mul_eq_zero], simp }, rw [akey, mul_assoc, bkey, ← f.map_mul', ← f.map_zero'] at h1, rw f.eq_iff_exists' at h1, cases h1 with c h1, rw [zero_mul, mul_comm] at h1, have h2 := eq_zero_or_eq_zero_of_mul_eq_zero h1, cases h2 with c_eq_zero h2, { exfalso, rw ← c_eq_zero at zero_non_mem, exact zero_non_mem c.property }, replace h2 := eq_zero_or_eq_zero_of_mul_eq_zero h2, cases h2 with a_eq_zero b_eq_zero, { left, rw a_eq_zero at akey, exact localization_map.eq_zero_of_fst_eq_zero f akey rfl }, { right, rw b_eq_zero at bkey, exact localization_map.eq_zero_of_fst_eq_zero f bkey rfl }, }, end instance local_at_prime_of_id_is_id (P : ideal R) (hp_prime : P.is_prime) : integral_domain (localization.at_prime P) := begin have zero_non_mem : (0 : R) ∉ P.prime_compl, { have := ideal.zero_mem P, simpa }, have h1 := local_id_is_id R P.prime_compl zero_non_mem, exact is_integral_domain.to_integral_domain (localization.at_prime P) h1, exact localization.of (ideal.prime_compl P), end lemma lt_add_nonmem (I : ideal R') (a ∉ I) : I < I+ideal.span{a} := begin have blah : ∀ (x y : ideal R'), x ≤ x ⊔ y, { intros x y, simp only [le_sup_left],}, split, exact blah I (ideal.span{a}), have blah2 : ∀ (x y z : ideal R'), x ⊔ y ≤ z → x ≤ z → y ≤ z, { intros x y z, simp only [sup_le_iff], tauto,}, have h : I ≤ I, exact le_refl I, rw ideal.add_eq_sup, intro bad, have h1 := blah2 I (ideal.span{a}) I bad h, have h2 : a ∈ ideal.span{a}, { rw ideal.mem_span_singleton', use 1, rw one_mul,}, have : ∀ (x ∈ ideal.span{a}), x ∈ I, simpa only [], exact H (this a h2), end -- lemma zero_prime : (⊥ : ideal R).is_prime := begin split, { intro, have h1 := (ideal.eq_top_iff_one) (⊥ : ideal R) , rw h1 at a, have : 1 = (0 : R), tauto, simpa, }, { intros, have h1 : x * y = 0, tauto, have x_or_y0 : x = 0 ∨ y = 0, exact zero_eq_mul.mp (eq.symm h1), tauto, }, end lemma nonzero_mem_of_neq_bot (I : ideal R') (gt_bot : ⊥ < I) : ∃ a : I, a ≠ 0 := begin have h := (submodule.lt_iff_le_and_exists.1 gt_bot).2, clear gt_bot, rcases h with ⟨ x, hx, key ⟩, use [x, hx], simp only [submodule.mem_bot] at key, simpa only [ne.def, submodule.mk_eq_zero], end lemma ideal_mul_eq_zero {I J : ideal R} : (I * J = ⊥) ↔ I = ⊥ ∨ J = ⊥ := begin have hJ : inhabited J, by exact submodule.inhabited J, have j := inhabited.default J, clear hJ, split, swap, { intros, cases a, {rw [← ideal.mul_bot J, a, ideal.mul_comm],}, {rw [← ideal.mul_bot I, a, ideal.mul_comm],}, }, intro hij, by_cases J = ⊥, right, exact h, left, rw submodule.eq_bot_iff, intros i hi, rcases J.ne_bot_iff.1 h with ⟨ j', hj, ne0⟩, rw submodule.eq_bot_iff at hij, specialize hij (i * j'), have := eq_zero_or_eq_zero_of_mul_eq_zero ( hij (ideal.mul_mem_mul hi hj)), cases this, assumption, exfalso, exact ne0 this, end theorem set_has_maximal_iff_noetherian {X : Type u} [add_comm_group X] [module R' X] : (∀(a : set $ submodule R' X), a.nonempty → ∃ (M ∈ a), ∀ (I ∈ a), M ≤ I → I=M) ↔ is_noetherian R' X := begin split; intro h, { split, intro I, let S := {J | J ≤ I ∧ J.fg}, have h2 : S.nonempty, { use (⊥ : submodule R' X), convert submodule.fg_bot, simp }, rcases h S h2 with ⟨ M, ⟨hMI, ⟨Mgen, hMgen⟩⟩, max⟩, rw submodule.fg_def, contrapose! max, have : ∃ x ∈ I, x ∉ M, { have := max ↑Mgen (finset.finite_to_set Mgen), contrapose! this, rw hMgen, ext, tauto }, rcases this with ⟨x, hxI, hxM⟩, use submodule.span R' (↑Mgen ∪ {x}), split, { split, { suffices : (↑Mgen : set X) ∪ {x} ⊆ I, { convert submodule.span_mono this, simp }, have : (↑Mgen : set X) ⊆ M, { convert submodule.subset_span, cc }, apply set.union_subset, { exact set.subset.trans this hMI }, { simp [hxI] } }, { rw submodule.fg_def, use (↑Mgen ∪ {x}), split, { split, apply_instance,}, refl } }, split, { rw ← hMgen, convert submodule.span_mono _, simp }, { contrapose! hxM, rw ← hxM, apply submodule.subset_span, exact (↑Mgen : set X).mem_union_right rfl,} }, { rintros A ⟨a, ha⟩, rw is_noetherian_iff_well_founded at h, rw rel_embedding.well_founded_iff_no_descending_seq at h, by_contra hyp, push_neg at hyp, apply h, constructor, have h' : ∀ (M : submodule R' X), M ∈ A → (∃ (I : submodule R' X), I ∈ A ∧ M < I), { intros m mina, rcases hyp m mina with ⟨I, iina, mlei, mneqi⟩, use I, split, exact iina, split, exact mlei, intro ilem, apply mneqi, exact le_antisymm ilem mlei, }, have h'' : ∀ M : A, ∃ I : A, (M : submodule R' X) < I, { rintros ⟨M, M_in⟩, rcases h' M M_in with ⟨I, I_in, hMI⟩, exact ⟨⟨I, I_in⟩, hMI⟩ }, let f : ℕ → A := λ n, nat.rec_on n ⟨a, ha⟩ (λ n M, classical.some (h'' M)), exact rel_embedding.nat_gt (coe ∘ f) (λ n, classical.some_spec (h'' $ f n)), }, end
d61b49380382f1b615031a8adf89cb6841112288
1dd482be3f611941db7801003235dc84147ec60a
/src/data/nat/enat.lean
217ea571316087f598b5435e767eb773e26a07f9
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
7,759
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Natural numbers with infinity, represented as roption ℕ. -/ import data.pfun algebra.ordered_group open roption lattice def enat : Type := roption ℕ namespace enat instance : has_zero enat := ⟨some 0⟩ instance : has_one enat := ⟨some 1⟩ instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance : has_coe ℕ enat := ⟨some⟩ instance (n : ℕ) : decidable (n : enat).dom := is_true trivial @[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := roption.some_inj instance : add_comm_monoid enat := { add := (+), zero := (0), add_comm := λ x y, roption.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, roption.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, roption.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, roption.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top enat := ⟨none⟩ instance : has_bot enat := ⟨0⟩ instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ @[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P n) → P a := roption.induction_on @[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ := roption.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp] lemma coe_zero : ((0 : ℕ) : enat) = 0 := rfl @[simp] lemma coe_one : ((1 : ℕ) : enat) = 1 := rfl @[simp] lemma coe_add (x y : ℕ) : ((x + y : ℕ) : enat) = x + y := roption.ext' (and_true _).symm (λ _ _, rfl) @[simp] lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) : get ((x : enat) + y) h = x + get y h.2 := rfl @[simp] lemma get_add {x y : enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x := roption.ext' (iff_of_true trivial h) (λ _ _, rfl) @[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl lemma dom_of_le_some {x : enat} {y : ℕ} : x ≤ y → x.dom := λ ⟨h, _⟩, h trivial instance : partial_order enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_refl _⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, roption.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } @[simp] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y := ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ @[simp] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} instance semilattice_sup_bot : semilattice_sup_bot enat := { sup := (⊔), bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩, le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..enat.partial_order } instance order_top : order_top enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩, ..enat.semilattice_sup_bot } lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ := lt_of_le_of_ne le_top (λ h, absurd (congr_arg dom h) true_ne_false) @[simp] lemma coe_ne_bot (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := enat.cases_on x ⟨λ _, le_top, λ _, coe_lt_top _⟩ (λ n, ⟨λ h, enat.coe_le_coe.2 (enat.coe_lt_coe.1 h), λ h, enat.coe_lt_coe.2 (enat.coe_le_coe.1 h)⟩) noncomputable instance : decidable_linear_order enat := { le_total := λ x y, enat.cases_on x (or.inr le_top) (enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))), decidable_le := classical.dec_rel _, ..enat.partial_order } noncomputable instance : bounded_lattice enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..enat.order_top, ..enat.semilattice_sup_bot } lemma sup_eq_max {a b : enat} : a ⊔ b = max a b := le_antisymm (sup_le (le_max_left _ _) (le_max_right _ _)) (max_le le_sup_left le_sup_right) lemma inf_eq_min {a b : enat} : a ⊓ b = min a b := rfl instance : ordered_comm_monoid enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro trivial (h₁ h.2), λ _, add_le_add_left (h₂ _) c⟩), lt_of_add_lt_add_left := λ a b c, enat.cases_on a (λ h, by simpa [lt_irrefl] using h) (λ a, enat.cases_on b (λ h, absurd h (not_lt_of_ge (by rw add_top; exact le_top))) (λ b, enat.cases_on c (λ _, coe_lt_top _) (λ c h, coe_lt_coe.2 (by rw [← coe_add, ← coe_add, coe_lt_coe] at h; exact lt_of_add_lt_add_left h)))), ..enat.decidable_linear_order, ..enat.add_comm_monoid } instance : canonically_ordered_monoid enat := { le_iff_exists_add := λ a b, enat.cases_on b (iff_of_true le_top ⟨⊤, (add_top _).symm⟩) (λ b, enat.cases_on a (iff_of_false (not_le_of_gt (coe_lt_top _)) (not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _)))) (λ a, ⟨λ h, ⟨(b - a : ℕ), by rw [← coe_add, coe_inj, add_comm, nat.sub_add_cancel (coe_le_coe.1 h)]⟩, (λ ⟨c, hc⟩, enat.cases_on c (λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top) (λ c (hc : (b : enat) = a + c), coe_le_coe.2 (by rw [← coe_add, coe_inj] at hc; rw hc; exact nat.le_add_right _ _)) hc)⟩)) ..enat.ordered_comm_monoid } section with_top def to_with_top (x : enat) [decidable x.dom]: with_top ℕ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' [decidable (⊤ : enat).dom] : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' [decidable (0 : enat).dom]: to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_coe (n : ℕ) : to_with_top n = n := rfl @[simp] lemma to_with_top_coe' (n : ℕ) [decidable (n : enat).dom] : to_with_top (n : enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := by simp only [lt_iff_le_not_le, to_with_top_le] end with_top lemma lt_wf : well_founded ((<) : enat → enat → Prop) := show well_founded (λ a b : enat, a < b), by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff}; exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) instance : has_well_founded enat := ⟨(<), lt_wf⟩ end enat
40704a1fa28323336606e42f6deeb93c3c8f1421
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/converter.lean
8a1a7af1e95812891bca0b9dea58699e286950b1
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
1,706
lean
open tactic conv open tactic run_cmd mk_simp_attr `foo run_cmd mk_simp_attr `bla constant f : nat → nat → nat @[foo] lemma f_lemma : ∀ x, f x x = 0 := sorry constant g : nat → nat @[bla] lemma g_lemma : ∀ x, g x = x := sorry example (a b c : nat) : (λ x, g (f (a + 0) (sizeof x))) a = 0 := by conversion $ whnf >> trace_lhs >> apply_simp_set `bla >> dsimp >> trace "after defeq simplifier" >> trace_lhs >> change `(f a a) >> trace_lhs >> apply_simp_set `foo >> trace_lhs set_option trace.app_builder true @[simp] lemma sizeof_nat_eq (n : ℕ) : sizeof n = n := rfl example (a b c : nat) : (λ x, g (f x (sizeof x))) = (λ x, 0) := by conversion $ funext $ do trace_lhs, apply_simp_set `bla, dsimp, apply_simp_set `foo constant h : nat → nat → nat lemma ex (a : nat) : (λ a, h (f a (sizeof a)) (g a)) = (λ a, h 0 a) := by conversion $ bottom_up $ (apply_simp_set `foo <|> apply_simp_set `bla <|> dsimp) lemma ex2 {A : Type} [comm_group A] (a b : A) : b * 1 * a = a * b := by conversion $ bottom_up (apply_simp_set `default) lemma ex3 (p q r : Prop) : (p ∧ true ∧ p) = p := by conversion $ bottom_up (apply_propext_simp_set `default) #print "---------" lemma ex4 (a b c : nat) : g (g (g (f (f (g (g a)) (g (g a))) a))) = g (g (g (f (f a a) a))) := by conversion $ findp `(λ x, f (g x) (g x)) $ trace "found pattern" >> trace_lhs >> bottom_up (apply_simp_set `bla) lemma ex5 (a b c : nat) : g (g (g (f (f (g (g a)) (g (g a))) a))) = g (g (g (f (f a a) a))) := by conversion $ find $ match_expr `(λ x, f (g x) (g x)) >> trace "found pattern" >> trace_lhs >> bottom_up (apply_simp_set `bla)
0b0c66ad2d1b978ade5bd3a6aa8e9b2991b98664
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/omega/find_ees.lean
b5be8c3a58484badae1f6bead9e985b4f3aa27ab
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,566
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ /- A tactic for finding a sequence of equality elimination rules for a given set of constraints. -/ import tactic.omega.eq_elim variables {α β : Type} open tactic namespace omega /-- The state of equality elimination proof search. `eqs` is the list of equality constraints, and each `t ∈ eqs` represents the constraint `0 = t`. Similarly, `les` is the list of inequality constraints, and each `t ∈ eqs` represents the constraint `0 < t`. `ees` is the sequence of equality elimination steps that have been used so far to obtain the current set of constraints. The list `ees` grows over time until `eqs` becomes empty. -/ @[derive inhabited] structure ee_state := (eqs : list term) (les : list term) (ees : list ee) @[reducible] meta def eqelim := state_t ee_state tactic meta def abort {α : Type} : eqelim α := ⟨λ x, failed⟩ private meta def mk_eqelim_state (eqs les : list term) : tactic ee_state := return (ee_state.mk eqs les []) /-- Get the current list of equality constraints. -/ meta def get_eqs : eqelim (list term) := ee_state.eqs <$> get /-- Get the current list of inequality constraints. -/ meta def get_les : eqelim (list term) := ee_state.les <$> get /-- Get the current sequence of equality elimiation steps. -/ meta def get_ees : eqelim (list ee) := ee_state.ees <$> get /-- Update the list of equality constraints. -/ meta def set_eqs (eqs : list term) : eqelim unit := modify $ λ s, {eqs := eqs, ..s} /-- Update the list of inequality constraints. -/ meta def set_les (les : list term) : eqelim unit := modify $ λ s, {les := les, ..s} /-- Update the sequence of equality elimiation steps. -/ meta def set_ees (es : list ee) : eqelim unit := modify $ λ s, {ees := es, ..s} /-- Add a new step to the sequence of equality elimination steps. -/ meta def add_ee (e : ee) : eqelim unit := do es ← get_ees, set_ees (es ++ [e]) /-- Return the first equality constraint in the current list of equality constraints. The returned constraint is 'popped' and no longer available in the state. -/ meta def head_eq : eqelim term := do eqs ← get_eqs, match eqs with | [] := abort | (eq::eqs') := set_eqs eqs' >> pure eq end meta def run {α : Type} (eqs les : list term) (r : eqelim α) : tactic α := prod.fst <$> (mk_eqelim_state eqs les >>= r.run) /-- If `t1` succeeds and returns a value, 'commit' to that choice and run `t3` with the returned value as argument. Do not backtrack to try `t2` even if `t3` fails. If `t1` fails outright, run `t2`. -/ meta def ee_commit (t1 : eqelim α) (t2 : eqelim β) (t3 : α → eqelim β) : eqelim β := do x ← ((t1 >>= return ∘ some) <|> return none), match x with | none := t2 | (some a) := t3 a end local notation t1 `!>>=` t2 `;` t3 := ee_commit t1 t2 t3 private meta def of_tactic {α : Type} : tactic α → eqelim α := state_t.lift /-- GCD of all elements of the list. -/ def gcd : list int → nat | [] := 0 | (i::is) := nat.gcd i.nat_abs (gcd is) /-- GCD of all coefficients in a term. -/ meta def get_gcd (t : term) : eqelim int := pure ↑(gcd t.snd) /-- Divide a term by an integer if the integer divides the constant component of the term. It is assumed that the integer also divides all coefficients of the term. -/ meta def factor (i : int) (t : term) : eqelim term := if i ∣ t.fst then add_ee (ee.factor i) >> pure (t.div i) else abort /-- If list has a nonzero element, return the minimum element (by absolute value) with its index. Otherwise, return none. -/ meta def find_min_coeff_core : list int → eqelim (int × nat) | [] := abort | (i::is) := (do (j,n) ← find_min_coeff_core is, if i ≠ 0 ∧ i.nat_abs ≤ j.nat_abs then pure (i,0) else pure (j,n+1)) <|> (if i = (0 : int) then abort else pure (i,0)) /-- Find and return the smallest coefficient (by absolute value) in a term, along with the coefficient's variable index and the term itself. If the coefficient is negative, negate both the coefficient and the term before returning them. -/ meta def find_min_coeff (t : term) : eqelim (int × nat × term) := do (i,n) ← find_min_coeff_core t.snd, if 0 < i then pure (i,n,t) else add_ee (ee.neg) >> pure (-i,n,t.neg) /-- Find an appropriate equality elimination step for the current state and apply it. -/ meta def elim_eq : eqelim unit := do t ← head_eq, i ← get_gcd t, factor i t !>>= (set_eqs [] >> add_ee (ee.nondiv i)) ; λ s, find_min_coeff s !>>= add_ee ee.drop ; λ ⟨i, n, u⟩, if i = 1 then do eqs ← get_eqs, les ← get_les, set_eqs (eqs.map (cancel n u)), set_les (les.map (cancel n u)), add_ee (ee.cancel n) else let v : term := coeffs_reduce n u.fst u.snd in let r : term := rhs n u.fst u.snd in do eqs ← get_eqs, les ← get_les, set_eqs (v::eqs.map (subst n r)), set_les (les.map (subst n r)), add_ee (ee.reduce n), elim_eq /-- Find and return the sequence of steps for eliminating all equality constraints in the current state. -/ meta def elim_eqs : eqelim (list ee) := elim_eq !>>= get_ees ; λ _, elim_eqs /-- Given a linear constrain clause, return a list of steps for eliminating its equality constraints. -/ meta def find_ees : clause → tactic (list ee) | (eqs,les) := run eqs les elim_eqs end omega
dfccdac6be1d9d66d28d07dc5f686c0da011af54
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/fintype/sort.lean
81e53c957ecd5dc8453aa920cc83b2bda8140b51
[ "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
848
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.fintype.basic import data.finset.sort variables {α : Type*} open finset /-- Given a linearly ordered fintype `α` of cardinal `k`, the equiv `mono_equiv_of_fin α h` is the increasing bijection between `fin k` and `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ noncomputable def mono_equiv_of_fin (α) [fintype α] [linear_order α] {k : ℕ} (h : fintype.card α = k) : fin k ≃ α := equiv.of_bijective (mono_of_fin univ h) begin apply set.bijective_iff_bij_on_univ.2, rw ← @coe_univ α _, exact mono_of_fin_bij_on (univ : finset α) h end
228ea3dbba650402ddacaa8cbfff6300d08caa72
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/rbtree/basic_auto.lean
e0f42ca4e0802bd7b583969d88e1b513c2ab10f9
[]
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
5,669
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.ordering.default universes u l v namespace Mathlib inductive rbnode (α : Type u) where | leaf : rbnode α | red_node : rbnode α → α → rbnode α → rbnode α | black_node : rbnode α → α → rbnode α → rbnode α namespace rbnode inductive color where | red : color | black : color protected instance color.decidable_eq : DecidableEq color := fun (a b : color) => color.cases_on a (color.cases_on b (is_true rfl) (isFalse sorry)) (color.cases_on b (isFalse sorry) (is_true rfl)) def depth {α : Type u} (f : ℕ → ℕ → ℕ) : rbnode α → ℕ := sorry protected def min {α : Type u} : rbnode α → Option α := sorry protected def max {α : Type u} : rbnode α → Option α := sorry def fold {α : Type u} {β : Type v} (f : α → β → β) : rbnode α → β → β := sorry def rev_fold {α : Type u} {β : Type v} (f : α → β → β) : rbnode α → β → β := sorry def balance1 {α : Type u} : rbnode α → α → rbnode α → α → rbnode α → rbnode α := sorry def balance1_node {α : Type u} : rbnode α → α → rbnode α → rbnode α := sorry def balance2 {α : Type u} : rbnode α → α → rbnode α → α → rbnode α → rbnode α := sorry def balance2_node {α : Type u} : rbnode α → α → rbnode α → rbnode α := sorry def get_color {α : Type u} : rbnode α → color := sorry def ins {α : Type u} (lt : α → α → Prop) [DecidableRel lt] : rbnode α → α → rbnode α := sorry def mk_insert_result {α : Type u} : color → rbnode α → rbnode α := sorry def insert {α : Type u} (lt : α → α → Prop) [DecidableRel lt] (t : rbnode α) (x : α) : rbnode α := mk_insert_result (get_color t) (ins lt t x) def mem {α : Type u} (lt : α → α → Prop) : α → rbnode α → Prop := sorry def mem_exact {α : Type u} : α → rbnode α → Prop := sorry def find {α : Type u} (lt : α → α → Prop) [DecidableRel lt] : rbnode α → α → Option α := sorry inductive well_formed {α : Type u} (lt : α → α → Prop) : rbnode α → Prop where | leaf_wff : well_formed lt leaf | insert_wff : ∀ {n n' : rbnode α} {x : α} [_inst_1 : DecidableRel lt], well_formed lt n → n' = insert lt n x → well_formed lt n' end rbnode def rbtree (α : Type u) (lt : autoParam (α → α → Prop) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbtree.default_lt") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbtree") "default_lt") [])) := Subtype fun (t : rbnode α) => rbnode.well_formed lt t def mk_rbtree (α : Type u) (lt : autoParam (α → α → Prop) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbtree.default_lt") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbtree") "default_lt") [])) : rbtree α := { val := rbnode.leaf, property := rbnode.well_formed.leaf_wff } namespace rbtree protected def mem {α : Type u} {lt : α → α → Prop} (a : α) (t : rbtree α) := rbnode.mem lt a (subtype.val t) protected instance has_mem {α : Type u} {lt : α → α → Prop} : has_mem α (rbtree α) := has_mem.mk rbtree.mem def mem_exact {α : Type u} {lt : α → α → Prop} (a : α) (t : rbtree α) := rbnode.mem_exact a (subtype.val t) def depth {α : Type u} {lt : α → α → Prop} (f : ℕ → ℕ → ℕ) (t : rbtree α) : ℕ := rbnode.depth f (subtype.val t) def fold {α : Type u} {β : Type v} {lt : α → α → Prop} (f : α → β → β) : rbtree α → β → β := sorry def rev_fold {α : Type u} {β : Type v} {lt : α → α → Prop} (f : α → β → β) : rbtree α → β → β := sorry def empty {α : Type u} {lt : α → α → Prop} : rbtree α → Bool := sorry def to_list {α : Type u} {lt : α → α → Prop} : rbtree α → List α := sorry protected def min {α : Type u} {lt : α → α → Prop} : rbtree α → Option α := sorry protected def max {α : Type u} {lt : α → α → Prop} : rbtree α → Option α := sorry protected instance has_repr {α : Type u} {lt : α → α → Prop} [has_repr α] : has_repr (rbtree α) := sorry def insert {α : Type u} {lt : α → α → Prop} [DecidableRel lt] : rbtree α → α → rbtree α := sorry def find {α : Type u} {lt : α → α → Prop} [DecidableRel lt] : rbtree α → α → Option α := sorry def contains {α : Type u} {lt : α → α → Prop} [DecidableRel lt] (t : rbtree α) (a : α) : Bool := option.is_some (find t a) def from_list {α : Type u} (l : List α) (lt : autoParam (α → α → Prop) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbtree.default_lt") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbtree") "default_lt") [])) [DecidableRel lt] : rbtree α := list.foldl insert (mk_rbtree α) l end rbtree def rbtree_of {α : Type u} (l : List α) (lt : autoParam (α → α → Prop) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.rbtree.default_lt") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "rbtree") "default_lt") [])) [DecidableRel lt] : rbtree α := rbtree.from_list l end Mathlib