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
94a990762beccc7af4c4de5f433f734955c3822a
63abd62053d479eae5abf4951554e1064a4c45b4
/src/ring_theory/free_comm_ring.lean
6cc0518e9eeec24f0d0c20d495871e4af1b4ffb0
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
16,559
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import data.equiv.functor import data.mv_polynomial.equiv import data.mv_polynomial.comm_ring import ring_theory.free_ring /-! # Free commutative rings The theory of the free commutative ring generated by a type `α`. It is isomorphic to the polynomial ring over ℤ with variables in `α` ## Main definitions * `free_comm_ring α` : the free commutative ring on a type α * `lift_hom (f : α → R)` : the ring hom `free_comm_ring α →+* R` induced by functoriality from `f`. * `map (f : α → β)` : the ring hom `free_comm_ring α →*+ free_comm_ring β` induced by functoriality from f. ## Main results `free_comm_ring` has functorial properties (it is an adjoint to the forgetful functor). In this file we have: * `of : α → free_comm_ring α` * `lift_hom (f : α → R) : free_comm_ring α →+* R` * `map (f : α → β) : free_comm_ring α →+* free_comm_ring β` * `free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ` : `free_comm_ring α` is isomorphic to a polynomial ring. ## Implementation notes `free_comm_ring α` is implemented not using `mv_polynomial` but directly as the free abelian group on `multiset α`, the type of monomials in this free commutative ring. ## Tags free commutative ring, free ring -/ noncomputable theory open_locale classical universes u v variables (α : Type u) /-- `free_comm_ring α` is the free commutative ring on the type `α`. -/ def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring /-- The structure of a commutative ring on `free_comm_ring α`. -/ instance : comm_ring (free_comm_ring α) := free_abelian_group.comm_ring _ instance : inhabited (free_comm_ring α) := ⟨0⟩ variables {α} /-- The canonical map from `α` to the free commutative ring on `α`. -/ def of (x : α) : free_comm_ring α := free_abelian_group.of ([x] : multiset α) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {R : Type v} [comm_ring R] (f : α → R) /-- Lift a map `α → R` to a additive group homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : free_comm_ring α →+* R := { map_one' := free_abelian_group.lift.of _ _, map_mul' := λ x y, begin refine free_abelian_group.induction_on y (mul_zero _).symm _ _ _, { intros s2, conv_lhs { dsimp only [free_abelian_group.mul_def] }, simp only [free_abelian_group.lift.of, add_monoid_hom.to_fun_eq_coe], refine free_abelian_group.induction_on x (zero_mul _).symm _ _ _, { intros s1, iterate 3 { rw free_abelian_group.lift.of }, calc _ = multiset.prod ((multiset.map f s1) + (multiset.map f s2)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _ }, { intros s1 ih, iterate 3 { rw free_abelian_group.lift.neg }, rw [ih, neg_mul_eq_neg_mul] }, { intros x1 x2 ih1 ih2, iterate 3 { rw free_abelian_group.lift.add }, rw [ih1, ih2, add_mul] } }, { intros s2 ih, simp only [add_monoid_hom.to_fun_eq_coe] at ih ⊢, rw [mul_neg_eq_neg_mul_symm, add_monoid_hom.map_neg, add_monoid_hom.map_neg, mul_neg_eq_neg_mul_symm, ih] }, { intros y1 y2 ih1 ih2, simp only [add_monoid_hom.to_fun_eq_coe] at ih1 ih2 ⊢, rw [mul_add, add_monoid_hom.map_add, add_monoid_hom.map_add, mul_add, ih1, ih2] }, end, ..free_abelian_group.lift $ λ s : multiplicative (multiset α), (s.to_add.map f).prod } @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_comp_of (f : free_comm_ring α →+* R) : lift (f ∘ of) = f := ring_hom.ext $ λ x, free_comm_ring.induction_on x (by rw [ring_hom.map_neg, ring_hom.map_one, f.map_neg, f.map_one]) (lift_of _) (λ x y ihx ihy, by rw [ring_hom.map_add, f.map_add, ihx, ihy]) (λ x y ihx ihy, by rw [ring_hom.map_mul, f.map_mul, ihx, ihy]) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α →+* free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift $ of ∘ f @[simp] lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ /-- `is_supported x s` means that all monomials showing up in `x` have variables in `s`. -/ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ ring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := ring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := is_add_submonoid.add_mem hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := is_add_subgroup.neg_mem hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := is_add_subgroup.sub_mem _ _ _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := is_submonoid.mul_mem hxs hys theorem is_supported_zero : is_supported 0 s := is_add_submonoid.zero_mem theorem is_supported_one : is_supported 1 s := is_submonoid.one_mem theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported /-- The restriction map from `free_comm_ring α` to `free_comm_ring s` where `s : set α`, defined by sending all variables not in `s` to zero. -/ def restriction (s : set α) [decidable_pred s] : free_comm_ring α →+* free_comm_ring s := lift (λ p, if H : p ∈ s then of ⟨p, H⟩ else 0) section restriction variables (s : set α) [decidable_pred s] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, ring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin haveI := classical.dec_pred s, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : polynomial ℤ) else polynomial.X) x = n, { intros x hx, refine ring.in_closure.rec_on hx _ _ _ _, { use 1, rw [ring_hom.map_one], norm_cast }, { use -1, rw [ring_hom.map_neg, ring_hom.map_one], norm_cast }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [ring_hom.map_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [ring_hom.map_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw ←polynomial.C_eq_int_cast at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg (one_ne_zero : 1 ≠ 0), polynomial.coeff_X, if_pos rfl] at this end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred s] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine ring.in_closure.rec_on hxs _ _ _ _, { rw ring_hom.map_one, refl }, { rw [ring_hom.map_neg, ring_hom.map_neg, ring_hom.map_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [ring_hom.map_mul, restriction_of, dif_pos hps, ring_hom.map_mul, map_of, ih] }, { intros x y ihx ihy, rw [ring_hom.map_add, ring_hom.map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) /-- The canonical ring homomorphism from the free ring generated by `α` to the free commutative ring generated by `α`. -/ def to_free_comm_ring {α} : free_ring α →+* free_comm_ring α := free_ring.lift free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ instance coe.is_ring_hom : is_ring_hom (coe : free_ring α → free_comm_ring α) := free_ring.to_free_comm_ring.is_ring_hom @[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := (free_ring.lift _).map_neg _ @[simp, norm_cast] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := (free_ring.lift _).map_add _ _ @[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := (free_ring.lift _).map_sub _ _ @[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := (free_ring.lift _).map_mul _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact (free_ring.lift _).map_add _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact (free_ring.lift _).map_mul _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := funext $ λ x, free_abelian_group.lift.unique _ _ $ λ L, by { simp_rw [free_abelian_group.lift.of, (∘)], exact list.rec_on L rfl (λ hd tl ih, by { rw [list.map_cons, list.prod_cons, ih], refl }) } -- FIXME This was in `deprecated.ring`, but only used here. -- It would be good to inline it into the next construction. /-- Interpret an equivalence `f : R ≃ S` as a ring equivalence `R ≃+* S`. -/ def of' {R S : Type*} [ring R] [ring S] (e : R ≃ S) [is_ring_hom e] : R ≃+* S := { .. e, .. monoid_hom.of e, .. add_monoid_hom.of e } /-- If α has size at most 1 then the natural map from the free ring on `α` to the free commutative ring on `α` is an isomorphism of rings. -/ def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := @of' (free_ring α) (free_comm_ring α) _ _ (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) $ begin delta functor.map_equiv, rw congr_arg is_ring_hom _, work_on_goal 2 { symmetry, exact coe_eq α }, apply_instance end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by { rw [← (subsingleton_equiv_free_comm_ring α).symm_apply_apply (y * x), ((subsingleton_equiv_free_comm_ring α)).map_mul, mul_comm, ← ((subsingleton_equiv_free_comm_ring α)).map_mul, (subsingleton_equiv_free_comm_ring α).symm_apply_apply], }, .. free_ring.ring α } end free_ring /-- The free commutative ring on `α` is isomorphic to the polynomial ring over ℤ with variables in `α` -/ def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := { to_fun := free_comm_ring.lift $ λ a, mv_polynomial.X a, inv_fun := mv_polynomial.eval₂ (int.cast_ring_hom (free_comm_ring α)) free_comm_ring.of, left_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, refine free_abelian_group.induction_on x rfl _ _ _, { intro s, refine multiset.induction_on s _ _, { unfold free_comm_ring.lift, simp only [free_abelian_group.lift.of, ring_hom.coe_mk, add_monoid_hom.to_fun_eq_coe], exact mv_polynomial.eval₂_one _ _ }, { intros hd tl ih, show mv_polynomial.eval₂ (int.cast_ring_hom (free_comm_ring α)) free_comm_ring.of (free_comm_ring.lift (λ a, mv_polynomial.X a) (free_comm_ring.of hd * free_abelian_group.of tl)) = free_comm_ring.of hd * free_abelian_group.of tl, rw [ring_hom.map_mul, free_comm_ring.lift_of, mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, ih] } }, { intros s ih, rw [ring_hom.map_neg, ← neg_one_mul, mv_polynomial.eval₂_mul, ← mv_polynomial.C_1, ← mv_polynomial.C_neg, mv_polynomial.eval₂_C, ring_hom.map_neg, ring_hom.map_one, neg_one_mul, ih] }, { intros x₁ x₂ ih₁ ih₂, rw [ring_hom.map_add, mv_polynomial.eval₂_add, ih₁, ih₂] } end, right_inv := begin intro x, haveI : is_semiring_hom (coe : int → free_comm_ring α) := (int.cast_ring_hom _).is_semiring_hom, have : ∀ i : ℤ, free_comm_ring.lift (λ (a : α), mv_polynomial.X a) (int.cast_ring_hom _ i) = mv_polynomial.C i, { exact λ i, int.induction_on i (by rw [ring_hom.map_zero, ring_hom.map_zero, mv_polynomial.C_0]) (λ i ih, by rw [ring_hom.map_add, ring_hom.map_one, ring_hom.map_add, ring_hom.map_one, ih, mv_polynomial.C_add, mv_polynomial.C_1]) (λ i ih, by rw [ring_hom.map_sub, ring_hom.map_one, ring_hom.map_sub, ring_hom.map_one, ih, mv_polynomial.C_sub, mv_polynomial.C_1]) }, apply mv_polynomial.induction_on x, { intro i, rw [mv_polynomial.eval₂_C, this] }, { intros p q ihp ihq, rw [mv_polynomial.eval₂_add, ring_hom.map_add, ihp, ihq] }, { intros p a ih, rw [mv_polynomial.eval₂_mul, mv_polynomial.eval₂_X, ring_hom.map_mul, free_comm_ring.lift_of, ih] } end, .. free_comm_ring.lift $ λ a, mv_polynomial.X a } /-- The free commutative ring on the empty type is isomorphic to `ℤ`. -/ def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.pempty_ring_equiv _) /-- The free commutative ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.punit_ring_equiv _) open free_ring /-- The free ring on the empty type is isomorphic to `ℤ`. -/ def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int /-- The free ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* polynomial ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
c6e96c250bc8f7ecd522aea98337f99e76fda5ac
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/category_theory/limits/shapes/images.lean
753eb6e0293763de89ce237c991c2a3f4d87542d
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
21,453
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel -/ import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.strong_epi /-! # Categorical images We define the categorical image of `f` as a factorisation `f = e ≫ m` through a monomorphism `m`, so that `m` factors through the `m'` in any other such factorisation. ## Main definitions * A `mono_factorisation` is a factorisation `f = e ≫ m`, where `m` is a monomorphism * `is_image F` means that a given mono factorisation `F` has the universal property of the image. * `has_image f` means that we have chosen an image for the morphism `f : X ⟶ Y`. * In this case, `image f` is the image object, `image.ι f : image f ⟶ Y` is the monomorphism `m` of the factorisation and `factor_thru_image f : X ⟶ image f` is the morphism `e`. * `has_images C` means that every morphism in `C` has an image. * Let `f : X ⟶ Y` and `g : P ⟶ Q` be morphisms in `C`, which we will represent as objects of the arrow category `arrow C`. Then `sq : f ⟶ g` is a commutative square in `C`. If `f` and `g` have images, then `has_image_map sq` represents the fact that there is a morphism `i : image f ⟶ image g` making the diagram X ----→ image f ----→ Y | | | | | | ↓ ↓ ↓ P ----→ image g ----→ Q commute, where the top row is the image factorisation of `f`, the bottom row is the image factorisation of `g`, and the outer rectangle is the commutative square `sq`. * If a category `has_images`, then `has_image_maps` means that every commutative square admits an image map. * If a category `has_images`, then `has_strong_epi_images` means that the morphism to the image is always a strong epimorphism. ## Main statements * When `C` has equalizers, the morphism `e` appearing in an image factorisation is an epimorphism. * When `C` has strong epi images, then these images admit image maps. ## Future work * TODO: coimages, and abelian categories. * TODO: connect this with existing working in the group theory and ring theory libraries. -/ universes v u open category_theory open category_theory.limits.walking_parallel_pair namespace category_theory.limits variables {C : Type u} [category.{v} C] variables {X Y : C} (f : X ⟶ Y) /-- A factorisation of a morphism `f = e ≫ m`, with `m` monic. -/ structure mono_factorisation (f : X ⟶ Y) := (I : C) (m : I ⟶ Y) [m_mono : mono m] (e : X ⟶ I) (fac' : e ≫ m = f . obviously) restate_axiom mono_factorisation.fac' attribute [simp, reassoc] mono_factorisation.fac attribute [instance] mono_factorisation.m_mono attribute [instance] mono_factorisation.m_mono namespace mono_factorisation /-- The obvious factorisation of a monomorphism through itself. -/ def self [mono f] : mono_factorisation f := { I := X, m := f, e := 𝟙 X } -- I'm not sure we really need this, but the linter says that an inhabited instance ought to exist... instance [mono f] : inhabited (mono_factorisation f) := ⟨self f⟩ /-- The morphism `m` in a factorisation `f = e ≫ m` through a monomorphism is uniquely determined. -/ @[ext] lemma ext {F F' : mono_factorisation f} (hI : F.I = F'.I) (hm : F.m = (eq_to_hom hI) ≫ F'.m) : F = F' := begin cases F, cases F', cases hI, simp at hm, dsimp at F_fac' F'_fac', congr, { assumption }, { resetI, apply (cancel_mono F_m).1, rw [F_fac', hm, F'_fac'], } end end mono_factorisation variable {f} /-- Data exhibiting that a given factorisation through a mono is initial. -/ structure is_image (F : mono_factorisation f) := (lift : Π (F' : mono_factorisation f), F.I ⟶ F'.I) (lift_fac' : Π (F' : mono_factorisation f), lift F' ≫ F'.m = F.m . obviously) restate_axiom is_image.lift_fac' attribute [simp, reassoc] is_image.lift_fac @[simp, reassoc] lemma is_image.fac_lift {F : mono_factorisation f} (hF : is_image F) (F' : mono_factorisation f) : F.e ≫ hF.lift F' = F'.e := (cancel_mono F'.m).1 $ by simp variable (f) namespace is_image /-- The trivial factorisation of a monomorphism satisfies the universal property. -/ @[simps] def self [mono f] : is_image (mono_factorisation.self f) := { lift := λ F', F'.e } instance [mono f] : inhabited (is_image (mono_factorisation.self f)) := ⟨self f⟩ variable {f} /-- Two factorisations through monomorphisms satisfying the universal property must factor through isomorphic objects. -/ -- TODO this is another good candidate for a future `unique_up_to_canonical_iso`. @[simps] def iso_ext {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') : F.I ≅ F'.I := { hom := hF.lift F', inv := hF'.lift F, hom_inv_id' := (cancel_mono F.m).1 (by simp), inv_hom_id' := (cancel_mono F'.m).1 (by simp) } end is_image /-- Data exhibiting that a morphism `f` has an image. -/ class has_image (f : X ⟶ Y) := (F : mono_factorisation f) (is_image : is_image F) section variable [has_image f] /-- The chosen factorisation of `f` through a monomorphism. -/ def image.mono_factorisation : mono_factorisation f := has_image.F /-- The witness of the universal property for the chosen factorisation of `f` through a monomorphism. -/ def image.is_image : is_image (image.mono_factorisation f) := has_image.is_image /-- The categorical image of a morphism. -/ def image : C := (image.mono_factorisation f).I /-- The inclusion of the image of a morphism into the target. -/ def image.ι : image f ⟶ Y := (image.mono_factorisation f).m @[simp] lemma image.as_ι : (image.mono_factorisation f).m = image.ι f := rfl instance : mono (image.ι f) := (image.mono_factorisation f).m_mono /-- The map from the source to the image of a morphism. -/ def factor_thru_image : X ⟶ image f := (image.mono_factorisation f).e /-- Rewrite in terms of the `factor_thru_image` interface. -/ @[simp] lemma as_factor_thru_image : (image.mono_factorisation f).e = factor_thru_image f := rfl @[simp, reassoc] lemma image.fac : factor_thru_image f ≫ image.ι f = f := (image.mono_factorisation f).fac' variable {f} /-- Any other factorisation of the morphism `f` through a monomorphism receives a map from the image. -/ def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (image.is_image f).lift F' @[simp, reassoc] lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := (image.is_image f).lift_fac' F' @[simp, reassoc] lemma image.fac_lift (F' : mono_factorisation f) : factor_thru_image f ≫ image.lift F' = F'.e := (image.is_image f).fac_lift F' -- TODO we could put a category structure on `mono_factorisation f`, -- with the morphisms being `g : I ⟶ I'` commuting with the `m`s -- (they then automatically commute with the `e`s) -- and show that an `image_of f` gives an initial object there -- (uniqueness of the lift comes for free). instance lift_mono (F' : mono_factorisation f) : mono (image.lift F') := begin split, intros Z a b w, have w' : a ≫ image.ι f = b ≫ image.ι f := calc a ≫ image.ι f = a ≫ (image.lift F' ≫ F'.m) : by simp ... = (a ≫ image.lift F') ≫ F'.m : by rw [category.assoc] ... = (b ≫ image.lift F') ≫ F'.m : by rw w ... = b ≫ (image.lift F' ≫ F'.m) : by rw [←category.assoc] ... = b ≫ image.ι f : by simp, exact (cancel_mono (image.ι f)).1 w', end lemma has_image.uniq (F' : mono_factorisation f) (l : image f ⟶ F'.I) (w : l ≫ F'.m = image.ι f) : l = image.lift F' := (cancel_mono F'.m).1 (by simp [w]) end section variables (C) /-- `has_images` represents a choice of image for every morphism -/ class has_images := (has_image : Π {X Y : C} (f : X ⟶ Y), has_image f) attribute [instance, priority 100] has_images.has_image end section variables (f) [has_image f] /-- The image of a monomorphism is isomorphic to the source. -/ def image_mono_iso_source [mono f] : image f ≅ X := is_image.iso_ext (image.is_image f) (is_image.self f) @[simp, reassoc] lemma image_mono_iso_source_inv_ι [mono f] : (image_mono_iso_source f).inv ≫ image.ι f = f := by simp [image_mono_iso_source] @[simp, reassoc] lemma image_mono_iso_source_hom_self [mono f] : (image_mono_iso_source f).hom ≫ f = image.ι f := begin conv { to_lhs, congr, skip, rw ←image_mono_iso_source_inv_ι f, }, rw [←category.assoc, iso.hom_inv_id, category.id_comp], end -- This is the proof that `factor_thru_image f` is an epimorphism -- from https://en.wikipedia.org/wiki/Image_(category_theory), which is in turn taken from: -- Mitchell, Barry (1965), Theory of categories, MR 0202787, p.12, Proposition 10.1 @[ext] lemma image.ext {W : C} {g h : image f ⟶ W} [has_limit (parallel_pair g h)] (w : factor_thru_image f ≫ g = factor_thru_image f ≫ h) : g = h := begin let q := equalizer.ι g h, let e' := equalizer.lift _ w, let F' : mono_factorisation f := { I := equalizer g h, m := q ≫ image.ι f, m_mono := by apply mono_comp, e := e' }, let v := image.lift F', have t₀ : v ≫ q ≫ image.ι f = image.ι f := image.lift_fac F', have t : v ≫ q = 𝟙 (image f) := (cancel_mono_id (image.ι f)).1 (by { convert t₀ using 1, rw category.assoc }), -- The proof from wikipedia next proves `q ≫ v = 𝟙 _`, -- and concludes that `equalizer g h ≅ image f`, -- but this isn't necessary. calc g = 𝟙 (image f) ≫ g : by rw [category.id_comp] ... = v ≫ q ≫ g : by rw [←t, category.assoc] ... = v ≫ q ≫ h : by rw [equalizer.condition g h] ... = 𝟙 (image f) ≫ h : by rw [←category.assoc, t] ... = h : by rw [category.id_comp] end instance [Π {Z : C} (g h : image f ⟶ Z), has_limit (parallel_pair g h)] : epi (factor_thru_image f) := ⟨λ Z g h w, image.ext f w⟩ lemma epi_image_of_epi {X Y : C} (f : X ⟶ Y) [has_image f] [E : epi f] : epi (image.ι f) := begin rw ←image.fac f at E, resetI, exact epi_of_epi (factor_thru_image f) (image.ι f), end lemma epi_of_epi_image {X Y : C} (f : X ⟶ Y) [has_image f] [epi (image.ι f)] [epi (factor_thru_image f)] : epi f := by { rw [←image.fac f], apply epi_comp, } end section variables {f} {f' : X ⟶ Y} [has_image f] [has_image f'] /-- An equation between morphisms gives a comparison map between the images (which momentarily we prove is an iso). -/ def image.eq_to_hom (h : f = f') : image f ⟶ image f' := image.lift { I := image f', m := image.ι f', e := factor_thru_image f', }. instance (h : f = f') : is_iso (image.eq_to_hom h) := { inv := image.eq_to_hom h.symm, hom_inv_id' := (cancel_mono (image.ι f)).1 (by simp [image.eq_to_hom]), inv_hom_id' := (cancel_mono (image.ι f')).1 (by simp [image.eq_to_hom]), } /-- An equation between morphisms gives an isomorphism between the images. -/ def image.eq_to_iso (h : f = f') : image f ≅ image f' := as_iso (image.eq_to_hom h) /-- As long as the category has equalizers, the image inclusion maps commute with `image.eq_to_iso`. -/ lemma image.eq_fac [has_equalizers C] (h : f = f') : image.ι f = (image.eq_to_iso h).hom ≫ image.ι f' := by { ext, simp [image.eq_to_iso, image.eq_to_hom], } end section variables {Z : C} (g : Y ⟶ Z) /-- The comparison map `image (f ≫ g) ⟶ image g`. -/ def image.pre_comp [has_image g] [has_image (f ≫ g)] : image (f ≫ g) ⟶ image g := image.lift { I := image g, m := image.ι g, e := f ≫ factor_thru_image g } @[simp, reassoc] lemma image.factor_thru_image_pre_comp [has_image g] [has_image (f ≫ g)] : factor_thru_image (f ≫ g) ≫ image.pre_comp f g = f ≫ factor_thru_image g := by simp [image.pre_comp] /-- The two step comparison map `image (f ≫ (g ≫ h)) ⟶ image (g ≫ h) ⟶ image h` agrees with the one step comparison map `image (f ≫ (g ≫ h)) ≅ image ((f ≫ g) ≫ h) ⟶ image h`. -/ lemma image.pre_comp_comp {W : C} (h : Z ⟶ W) [has_image (g ≫ h)] [has_image (f ≫ g ≫ h)] [has_image h] [has_image ((f ≫ g) ≫ h)] : image.pre_comp f (g ≫ h) ≫ image.pre_comp g h = image.eq_to_hom (category.assoc f g h).symm ≫ (image.pre_comp (f ≫ g) h) := begin apply (cancel_mono (image.ι h)).1, simp [image.pre_comp, image.eq_to_hom], end variables [has_equalizers C] /-- `image.pre_comp f g` is an isomorphism when `f` is an isomorphism (we need `C` to have equalizers to prove this). -/ instance image.is_iso_precomp_iso (f : X ≅ Y) [has_image g] [has_image (f.hom ≫ g)] : is_iso (image.pre_comp f.hom g) := { inv := image.lift { I := image (f.hom ≫ g), m := image.ι (f.hom ≫ g), e := f.inv ≫ factor_thru_image (f.hom ≫ g) }, hom_inv_id' := by { ext, simp [image.pre_comp], }, inv_hom_id' := by { ext, simp [image.pre_comp], }, } -- Note that in general we don't have the other comparison map you might expect -- `image f ⟶ image (f ≫ g)`. end end category_theory.limits namespace category_theory.limits variables {C : Type u} [category.{v} C] section instance {X Y : C} (f : X ⟶ Y) [has_image f] : has_image (arrow.mk f).hom := show has_image f, by apply_instance end section has_image_map /-- An image map is a morphism `image f → image g` fitting into a commutative square and satisfying the obvious commutativity conditions. -/ class has_image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) := (map : image f.hom ⟶ image g.hom) (map_ι' : map ≫ image.ι g.hom = image.ι f.hom ≫ sq.right . obviously) restate_axiom has_image_map.map_ι' attribute [simp, reassoc] has_image_map.map_ι @[simp, reassoc] lemma has_image_map.factor_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) [has_image_map sq] : factor_thru_image f.hom ≫ has_image_map.map sq = sq.left ≫ factor_thru_image g.hom := (cancel_mono (image.ι g.hom)).1 $ by simp [arrow.w] variables {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f ⟶ g) section local attribute [ext] has_image_map instance : subsingleton (has_image_map sq) := subsingleton.intro $ λ a b, has_image_map.ext a b $ (cancel_mono (image.ι g.hom)).1 $ by simp only [has_image_map.map_ι] end variable [has_image_map sq] /-- The map on images induced by a commutative square. -/ abbreviation image.map : image f.hom ⟶ image g.hom := has_image_map.map sq lemma image.factor_map : factor_thru_image f.hom ≫ image.map sq = sq.left ≫ factor_thru_image g.hom := by simp lemma image.map_ι : image.map sq ≫ image.ι g.hom = image.ι f.hom ≫ sq.right := by simp lemma image.map_hom_mk'_ι {X Y P Q : C} {k : X ⟶ Y} [has_image k] {l : P ⟶ Q} [has_image l] {m : X ⟶ P} {n : Y ⟶ Q} (w : m ≫ l = k ≫ n) [has_image_map (arrow.hom_mk' w)] : image.map (arrow.hom_mk' w) ≫ image.ι l = image.ι k ≫ n := image.map_ι _ section variables {h : arrow C} [has_image h.hom] (sq' : g ⟶ h) variables [has_image_map sq'] /-- Image maps for composable commutative squares induce an image map in the composite square. -/ def has_image_map_comp : has_image_map (sq ≫ sq') := { map := image.map sq ≫ image.map sq' } @[simp] lemma image.map_comp [has_image_map (sq ≫ sq')] : image.map (sq ≫ sq') = image.map sq ≫ image.map sq' := show (has_image_map.map (sq ≫ sq')) = (has_image_map_comp sq sq').map, by congr end section variables (f) /-- The identity `image f ⟶ image f` fits into the commutative square represented by the identity morphism `𝟙 f` in the arrow category. -/ def has_image_map_id : has_image_map (𝟙 f) := { map := 𝟙 (image f.hom) } @[simp] lemma image.map_id [has_image_map (𝟙 f)] : image.map (𝟙 f) = 𝟙 (image f.hom) := show (image.map (𝟙 f)) = (has_image_map_id f).map, by congr end end has_image_map section variables (C) [has_images C] /-- If a category `has_image_maps`, then all commutative squares induce morphisms on images. -/ class has_image_maps := (has_image_map : Π {f g : arrow C} (st : f ⟶ g), has_image_map st) attribute [instance, priority 100] has_image_maps.has_image_map end section has_image_maps variables [has_images C] [has_image_maps C] /-- The functor from the arrow category of `C` to `C` itself that maps a morphism to its image and a commutative square to the induced morphism on images. -/ @[simps] def im : arrow C ⥤ C := { obj := λ f, image f.hom, map := λ _ _ st, image.map st } end has_image_maps section strong_epi_mono_factorisation /-- A strong epi-mono factorisation is a decomposition `f = e ≫ m` with `e` a strong epimorphism and `m` a monomorphism. -/ structure strong_epi_mono_factorisation {X Y : C} (f : X ⟶ Y) extends mono_factorisation f := [e_strong_epi : strong_epi e] attribute [instance] strong_epi_mono_factorisation.e_strong_epi /-- Satisfying the inhabited linter -/ instance strong_epi_mono_factorisation_inhabited {X Y : C} (f : X ⟶ Y) [strong_epi f] : inhabited (strong_epi_mono_factorisation f) := ⟨⟨⟨Y, 𝟙 Y, f, by simp⟩⟩⟩ /-- A mono factorisation coming from a strong epi-mono factorisation always has the universal property of the image. -/ def strong_epi_mono_factorisation.to_mono_is_image {X Y : C} {f : X ⟶ Y} (F : strong_epi_mono_factorisation f) : is_image F.to_mono_factorisation := { lift := λ G, arrow.lift $ arrow.hom_mk' $ show G.e ≫ G.m = F.e ≫ F.m, by rw [F.to_mono_factorisation.fac, G.fac] } variable (C) /-- A category has strong epi-mono factorisations if every morphism admits a strong epi-mono factorisation. -/ class has_strong_epi_mono_factorisations := (has_fac : Π {X Y : C} (f : X ⟶ Y), strong_epi_mono_factorisation f) @[priority 100] instance has_images_of_has_strong_epi_mono_factorisations [has_strong_epi_mono_factorisations C] : has_images C := { has_image := λ X Y f, let F' := has_strong_epi_mono_factorisations.has_fac f in { F := F'.to_mono_factorisation, is_image := F'.to_mono_is_image } } end strong_epi_mono_factorisation section has_strong_epi_images variables (C) [has_images C] /-- A category has strong epi images if it has all images and `factor_thru_image f` is a strong epimorphism for all `f`. -/ class has_strong_epi_images := (strong_factor_thru_image : Π {X Y : C} (f : X ⟶ Y), strong_epi (factor_thru_image f)) attribute [instance] has_strong_epi_images.strong_factor_thru_image end has_strong_epi_images section has_strong_epi_images /-- If we constructed our images from strong epi-mono factorisations, then these images are strong epi images. -/ @[priority 100] instance has_strong_epi_images_of_has_strong_epi_mono_factorisations [has_strong_epi_mono_factorisations C] : has_strong_epi_images C := { strong_factor_thru_image := λ X Y f, (has_strong_epi_mono_factorisations.has_fac f).e_strong_epi } end has_strong_epi_images section has_strong_epi_images variables [has_images C] /-- A category with strong epi images has image maps. The construction is taken from Borceux, Handbook of Categorical Algebra 1, Proposition 4.4.5. -/ @[priority 100] instance has_image_maps_of_has_strong_epi_images [has_strong_epi_images C] : has_image_maps C := { has_image_map := λ f g st, let I := image (image.ι f.hom ≫ st.right) in let I' := image (st.left ≫ factor_thru_image g.hom) in let upper : strong_epi_mono_factorisation (f.hom ≫ st.right) := { I := I, e := factor_thru_image f.hom ≫ factor_thru_image (image.ι f.hom ≫ st.right), m := image.ι (image.ι f.hom ≫ st.right), e_strong_epi := strong_epi_comp _ _, m_mono := by apply_instance } in let lower : strong_epi_mono_factorisation (f.hom ≫ st.right) := { I := I', e := factor_thru_image (st.left ≫ factor_thru_image g.hom), m := image.ι (st.left ≫ factor_thru_image g.hom) ≫ image.ι g.hom, fac' := by simp [arrow.w], e_strong_epi := by apply_instance, m_mono := mono_comp _ _ } in let s : I ⟶ I' := is_image.lift upper.to_mono_is_image lower.to_mono_factorisation in { map := factor_thru_image (image.ι f.hom ≫ st.right) ≫ s ≫ image.ι (st.left ≫ factor_thru_image g.hom), map_ι' := by rw [category.assoc, category.assoc, is_image.lift_fac upper.to_mono_is_image lower.to_mono_factorisation, image.fac] } } end has_strong_epi_images variables [has_strong_epi_mono_factorisations.{v} C] variables {X Y : C} {f : X ⟶ Y} /-- If `C` has strong epi mono factorisations, then the image is unique up to isomorphism, in that if `f` factors as a strong epi followed by a mono, this factorisation is essentially the image factorisation. -/ def image.iso_strong_epi_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : I' ≅ image f := is_image.iso_ext {strong_epi_mono_factorisation . I := I', m := m, e := e}.to_mono_is_image (image.is_image f) @[simp] lemma image.iso_strong_epi_mono_hom_comp_ι {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : (image.iso_strong_epi_mono e m comm).hom ≫ image.ι f = m := is_image.lift_fac _ _ @[simp] lemma image.iso_strong_epi_mono_inv_comp_mono {I' : C} (e : X ⟶ I') (m : I' ⟶ Y) (comm : e ≫ m = f) [strong_epi e] [mono m] : (image.iso_strong_epi_mono e m comm).inv ≫ m = image.ι f := image.lift_fac _ end category_theory.limits
6d2bc49d57d316fd07678fc094d3d87d205a2c02
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/RightMonoid.lean
d2285db2bdde2a001c83e78bc37a82c24cfb91fa
[]
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
6,850
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 RightMonoid structure RightMonoid (A : Type) : Type := (op : (A → (A → A))) (e : A) (runit_e : (∀ {x : A} , (op x e) = x)) (associative_op : (∀ {x y z : A} , (op (op x y) z) = (op x (op y z)))) open RightMonoid structure Sig (AS : Type) : Type := (opS : (AS → (AS → AS))) (eS : AS) structure Product (A : Type) : Type := (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (eP : (Prod A A)) (runit_eP : (∀ {xP : (Prod A A)} , (opP xP eP) = xP)) (associative_opP : (∀ {xP yP zP : (Prod A A)} , (opP (opP xP yP) zP) = (opP xP (opP yP zP)))) structure Hom {A1 : Type} {A2 : Type} (Ri1 : (RightMonoid A1)) (Ri2 : (RightMonoid A2)) : Type := (hom : (A1 → A2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Ri1) x1 x2)) = ((op Ri2) (hom x1) (hom x2)))) (pres_e : (hom (e Ri1)) = (e Ri2)) structure RelInterp {A1 : Type} {A2 : Type} (Ri1 : (RightMonoid A1)) (Ri2 : (RightMonoid A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Ri1) x1 x2) ((op Ri2) y1 y2)))))) (interp_e : (interp (e Ri1) (e Ri2))) inductive RightMonoidTerm : Type | opL : (RightMonoidTerm → (RightMonoidTerm → RightMonoidTerm)) | eL : RightMonoidTerm open RightMonoidTerm inductive ClRightMonoidTerm (A : Type) : Type | sing : (A → ClRightMonoidTerm) | opCl : (ClRightMonoidTerm → (ClRightMonoidTerm → ClRightMonoidTerm)) | eCl : ClRightMonoidTerm open ClRightMonoidTerm inductive OpRightMonoidTerm (n : ℕ) : Type | v : ((fin n) → OpRightMonoidTerm) | opOL : (OpRightMonoidTerm → (OpRightMonoidTerm → OpRightMonoidTerm)) | eOL : OpRightMonoidTerm open OpRightMonoidTerm inductive OpRightMonoidTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpRightMonoidTerm2) | sing2 : (A → OpRightMonoidTerm2) | opOL2 : (OpRightMonoidTerm2 → (OpRightMonoidTerm2 → OpRightMonoidTerm2)) | eOL2 : OpRightMonoidTerm2 open OpRightMonoidTerm2 def simplifyCl {A : Type} : ((ClRightMonoidTerm A) → (ClRightMonoidTerm A)) | (opCl x eCl) := x | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | eCl := eCl | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpRightMonoidTerm n) → (OpRightMonoidTerm n)) | (opOL x eOL) := x | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | eOL := eOL | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpRightMonoidTerm2 n A) → (OpRightMonoidTerm2 n A)) | (opOL2 x eOL2) := x | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | eOL2 := eOL2 | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((RightMonoid A) → (RightMonoidTerm → A)) | Ri (opL x1 x2) := ((op Ri) (evalB Ri x1) (evalB Ri x2)) | Ri eL := (e Ri) def evalCl {A : Type} : ((RightMonoid A) → ((ClRightMonoidTerm A) → A)) | Ri (sing x1) := x1 | Ri (opCl x1 x2) := ((op Ri) (evalCl Ri x1) (evalCl Ri x2)) | Ri eCl := (e Ri) def evalOpB {A : Type} {n : ℕ} : ((RightMonoid A) → ((vector A n) → ((OpRightMonoidTerm n) → A))) | Ri vars (v x1) := (nth vars x1) | Ri vars (opOL x1 x2) := ((op Ri) (evalOpB Ri vars x1) (evalOpB Ri vars x2)) | Ri vars eOL := (e Ri) def evalOp {A : Type} {n : ℕ} : ((RightMonoid A) → ((vector A n) → ((OpRightMonoidTerm2 n A) → A))) | Ri vars (v2 x1) := (nth vars x1) | Ri vars (sing2 x1) := x1 | Ri vars (opOL2 x1 x2) := ((op Ri) (evalOp Ri vars x1) (evalOp Ri vars x2)) | Ri vars eOL2 := (e Ri) def inductionB {P : (RightMonoidTerm → Type)} : ((∀ (x1 x2 : RightMonoidTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → ((P eL) → (∀ (x : RightMonoidTerm) , (P x)))) | popl pel (opL x1 x2) := (popl _ _ (inductionB popl pel x1) (inductionB popl pel x2)) | popl pel eL := pel def inductionCl {A : Type} {P : ((ClRightMonoidTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClRightMonoidTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → ((P eCl) → (∀ (x : (ClRightMonoidTerm A)) , (P x))))) | psing popcl pecl (sing x1) := (psing x1) | psing popcl pecl (opCl x1 x2) := (popcl _ _ (inductionCl psing popcl pecl x1) (inductionCl psing popcl pecl x2)) | psing popcl pecl eCl := pecl def inductionOpB {n : ℕ} {P : ((OpRightMonoidTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpRightMonoidTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → ((P eOL) → (∀ (x : (OpRightMonoidTerm n)) , (P x))))) | pv popol peol (v x1) := (pv x1) | pv popol peol (opOL x1 x2) := (popol _ _ (inductionOpB pv popol peol x1) (inductionOpB pv popol peol x2)) | pv popol peol eOL := peol def inductionOp {n : ℕ} {A : Type} {P : ((OpRightMonoidTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpRightMonoidTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → ((P eOL2) → (∀ (x : (OpRightMonoidTerm2 n A)) , (P x)))))) | pv2 psing2 popol2 peol2 (v2 x1) := (pv2 x1) | pv2 psing2 popol2 peol2 (sing2 x1) := (psing2 x1) | pv2 psing2 popol2 peol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 popol2 peol2 x1) (inductionOp pv2 psing2 popol2 peol2 x2)) | pv2 psing2 popol2 peol2 eOL2 := peol2 def stageB : (RightMonoidTerm → (Staged RightMonoidTerm)) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) | eL := (Now eL) def stageCl {A : Type} : ((ClRightMonoidTerm A) → (Staged (ClRightMonoidTerm A))) | (sing x1) := (Now (sing x1)) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) | eCl := (Now eCl) def stageOpB {n : ℕ} : ((OpRightMonoidTerm n) → (Staged (OpRightMonoidTerm n))) | (v x1) := (const (code (v x1))) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) | eOL := (Now eOL) def stageOp {n : ℕ} {A : Type} : ((OpRightMonoidTerm2 n A) → (Staged (OpRightMonoidTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) | eOL2 := (Now eOL2) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (opT : ((Repr A) → ((Repr A) → (Repr A)))) (eT : (Repr A)) end RightMonoid
29c7fa20f66153485000f0978b49ece8e572fbcd
c3de33d4701e6113627153fe1103b255e752ed7d
/algebra/lattice/basic.lean
f32d0a4eb750534efa19ece3956919a75bd01847
[]
no_license
jroesch/library_dev
77d2b246ff47ab05d55cb9706a37d3de97038388
4faa0a45c6aa7eee6e661113c2072b8840bff79b
refs/heads/master
1,611,281,606,352
1,495,661,644,000
1,495,661,644,000
92,340,430
0
0
null
1,495,663,344,000
1,495,663,344,000
null
UTF-8
Lean
false
false
8,872
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Defines the inf/sup (semi)-lattice with optionally top/bot type class hierarchy. -/ import ..order set_option old_structure_cmd true universes u v w /- TODO: automatic construction of dual definitions / theorems -/ namespace lattice reserve infixl ` ⊓ `:70 reserve infixl ` ⊔ `:65 class has_top (α : Type u) := (top : α) class has_bot (α : Type u) := (bot : α) class has_sup (α : Type u) := (sup : α → α → α) class has_inf (α : Type u) := (inf : α → α → α) class has_imp (α : Type u) := (imp : α → α → α) /- Better name -/ def top {α : Type u} [has_top α] : α := has_top.top α def bot {α : Type u} [has_bot α] : α := has_bot.bot α def sup {α : Type u} [has_sup α] : α → α → α := has_sup.sup def inf {α : Type u} [has_inf α] : α → α → α := has_inf.inf def imp {α : Type u} [has_imp α] : α → α → α := has_imp.imp infix ⊔ := sup infix ⊓ := inf notation `⊤` := top notation `⊥` := bot class order_top (α : Type u) extends has_top α, weak_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables {α : Type u} [order_top α] {a : α} lemma le_top : a ≤ top := order_top.le_top a lemma top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h lemma eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨take eq, eq^.symm ▸ le_refl ⊤, top_unique⟩ end order_top class order_bot (α : Type u) extends has_bot α, weak_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables {α : Type u} [order_bot α] {a : α} lemma bot_le : ⊥ ≤ a := order_bot.bot_le a lemma bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le lemma eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨take eq, eq^.symm ▸ le_refl ⊥, bot_unique⟩ lemma neq_bot_of_le_neq_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := take ha, hb $ bot_unique $ ha ▸ hab end order_bot class semilattice_sup (α : Type u) extends has_sup α, weak_order α := (le_sup_left : ∀ a b : α, a ≤ a ⊔ b) (le_sup_right : ∀ a b : α, b ≤ a ⊔ b) (sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c) section semilattice_sup variables {α : Type u} [semilattice_sup α] {a b c d : α} lemma le_sup_left : a ≤ a ⊔ b := semilattice_sup.le_sup_left a b lemma le_sup_right : b ≤ a ⊔ b := semilattice_sup.le_sup_right a b lemma sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c := semilattice_sup.sup_le a b c lemma le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b := le_trans h le_sup_left lemma le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b := le_trans h le_sup_right lemma sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c := ⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩, take ⟨h₁, h₂⟩, sup_le h₁ h₂⟩ lemma sup_of_le_left (h : b ≤ a) : a ⊔ b = a := le_antisymm (sup_le (le_refl _) h) le_sup_left lemma sup_of_le_right (h : a ≤ b) : a ⊔ b = b := le_antisymm (sup_le h (le_refl _)) le_sup_right lemma sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d := sup_le (le_sup_left_of_le h₁) (le_sup_right_of_le h₂) lemma le_of_sup_eq (h : a ⊔ b = b) : a ≤ b := h ▸ le_sup_left @[simp] lemma sup_idem : a ⊔ a = a := sup_of_le_left (le_refl _) lemma sup_comm : a ⊔ b = b ⊔ a := have ∀{a b : α}, a ⊔ b ≤ b ⊔ a, from take a b, sup_le le_sup_right le_sup_left, le_antisymm this this instance semilattice_sup_to_is_commutative [semilattice_sup α] : is_commutative α sup := ⟨@sup_comm _ _⟩ lemma sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) := le_antisymm (sup_le (sup_le le_sup_left (le_sup_right_of_le le_sup_left)) (le_sup_right_of_le le_sup_right)) (sup_le (le_sup_left_of_le le_sup_left) (sup_le (le_sup_left_of_le le_sup_right) le_sup_right)) instance semilattice_sup_to_is_associative [semilattice_sup α] : is_associative α sup := ⟨@sup_assoc _ _⟩ end semilattice_sup class semilattice_inf (α : Type u) extends has_inf α, weak_order α := (inf_le_left : ∀ a b : α, a ⊓ b ≤ a) (inf_le_right : ∀ a b : α, a ⊓ b ≤ b) (le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c) section semilattice_inf variables {α : Type u} [semilattice_inf α] {a b c d : α} lemma inf_le_left : a ⊓ b ≤ a := semilattice_inf.inf_le_left a b lemma inf_le_right : a ⊓ b ≤ b := semilattice_inf.inf_le_right a b lemma le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c := semilattice_inf.le_inf a b c lemma inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c := le_trans inf_le_left h lemma inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c := le_trans inf_le_right h lemma le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c := ⟨assume h : a ≤ b ⊓ c, ⟨le_trans h inf_le_left, le_trans h inf_le_right⟩, take ⟨h₁, h₂⟩, le_inf h₁ h₂⟩ lemma inf_of_le_left (h : a ≤ b) : a ⊓ b = a := le_antisymm inf_le_left (le_inf (le_refl _) h) lemma inf_of_le_right (h : b ≤ a) : a ⊓ b = b := le_antisymm inf_le_right (le_inf h (le_refl _)) lemma inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d := le_inf (inf_le_left_of_le h₁) (inf_le_right_of_le h₂) lemma le_of_inf_eq (h : a ⊓ b = a) : a ≤ b := h ▸ inf_le_right @[simp] lemma inf_idem : a ⊓ a = a := inf_of_le_left (le_refl _) lemma inf_comm : a ⊓ b = b ⊓ a := have ∀{a b : α}, a ⊓ b ≤ b ⊓ a, from take a b, le_inf inf_le_right inf_le_left, le_antisymm this this instance semilattice_inf_to_is_commutative [semilattice_inf α] : is_commutative α inf := ⟨@inf_comm _ _⟩ lemma inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := le_antisymm (le_inf (inf_le_left_of_le inf_le_left) (le_inf (inf_le_left_of_le inf_le_right) inf_le_right)) (le_inf (le_inf inf_le_left (inf_le_right_of_le inf_le_left)) (inf_le_right_of_le inf_le_right)) instance semilattice_inf_to_is_associative [semilattice_inf α] : is_associative α inf := ⟨@inf_assoc _ _⟩ end semilattice_inf class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables {α : Type u} [semilattice_sup_top α] {a : α} @[simp] lemma top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] lemma sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables {α : Type u} [semilattice_sup_bot α] {a b : α} @[simp] lemma bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] lemma sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] lemma sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by simp [eq_bot_iff, sup_le_iff] end semilattice_sup_bot class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables {α : Type u} [semilattice_inf_top α] {a b : α} @[simp] lemma top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] lemma inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] lemma inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by simp [eq_top_iff, le_inf_iff] end semilattice_inf_top class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables {α : Type u} [semilattice_inf_bot α] {a : α} @[simp] lemma bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] lemma inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Lattices -/ class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α section lattice variables {α : Type u} [lattice α] {a b c d : α} /- Distributivity laws -/ /- TODO: better names? -/ lemma sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) := sup_le (le_inf le_sup_left le_sup_left) $ le_inf (inf_le_left_of_le le_sup_right) (inf_le_right_of_le le_sup_right) lemma le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) := le_inf (sup_le inf_le_left inf_le_left) $ sup_le (le_sup_left_of_le inf_le_right) (le_sup_right_of_le inf_le_right) lemma inf_sup_self : a ⊓ (a ⊔ b) = a := le_antisymm inf_le_left (le_inf (le_refl a) le_sup_left) lemma sup_inf_self : a ⊔ (a ⊓ b) = a := le_antisymm (sup_le (le_refl a) inf_le_left) le_sup_left end lattice /- Lattices derived from linear orders -/ instance lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : lattice α := { o with sup := max, le_sup_left := le_max_left, le_sup_right := le_max_right, sup_le := take a b c, max_le, inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := take a b c, le_min } end lattice
d7648978217f4696d185440b4e4f1c88ab6beb7b
5883d9218e6f144e20eee6ca1dab8529fa1a97c0
/src/data/list/set.lean
9b369e7dca195148fca28987f167246813aedf44
[]
no_license
spl/alpha-conversion-is-easy
0d035bc570e52a6345d4890e4d0c9e3f9b8126c1
ed937fe85d8495daffd9412a5524c77b9fcda094
refs/heads/master
1,607,649,280,020
1,517,380,240,000
1,517,380,240,000
52,174,747
4
0
null
1,456,052,226,000
1,456,001,163,000
Lean
UTF-8
Lean
false
false
495
lean
/- This file is a port of part of data.list.set from the Lean 2 standard library to Lean 3. -/ namespace list ----------------------------------------------------------------- variables {A : Type} [decidable_eq A] theorem insert_eq_of_mem {a : A} {l : list A} : a ∈ l → insert a l = l := λ c, if_pos c theorem insert_eq_of_not_mem {a : A} {l : list A} : a ∉ l → insert a l = a::l := λ c, if_neg c end /- namespace -/ list -------------------------------------------------------
432103f960d1d17d8d8ede7b04a002b18385ae9b
43390109ab88557e6090f3245c47479c123ee500
/src/M2PM2/isomorphism.lean
b78afb46080eba0cd79f7a13ccd9768fa499bf94
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,180
lean
import algebra.group data.set.basic group_theory.subgroup group_theory.quotient_group open function quotient_group is_subgroup is_group_hom universe u --Todo: prove the first isomorphism theorem variables {G : Type*} {H : Type*} [group G] [group H] variables (N K : set G) variables [is_subgroup N] [is_subgroup K] -- introducing the group isomorphism class is_group_isom (f : G → H) extends is_group_hom f : Prop := (group_bij : bijective f) namespace is_group_isom variables (f : G → H) [is_group_isom f] def automorphism (f₁ : G → G) := is_group_isom f₁ --lemma quot_is_isom (f :) theorem isomorphism_thm_one (φ : G → H) [is_group_hom φ] : surjective φ → ∃ (f₂ : (quotient (ker φ)) → H), is_group_isom f₂ := begin intros, existsi _, swap, sorry, end end is_group_isom class is_ring_isom {α : Type*} {β : Type*} [ring α] [ring β] (f : α → β) extends is_ring_hom f : Prop := (ring_bij : bijective f) #print notation $ -- s $ t means s(t) where s is a function, and t is the input. the reason this exists is because it has very low binding power, so you can evaluate t first, then s $ t, making it a better alternative to s(t)
2ceaa4dae6bd83543a58a4d203c33fb0f253f500
c777c32c8e484e195053731103c5e52af26a25d1
/src/linear_algebra/contraction.lean
13f941f92f2f8c22768c229e1e9f44d7ec9ab834
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
12,210
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash, Antoine Labelle -/ import linear_algebra.dual import linear_algebra.matrix.to_lin /-! # Contractions Given modules $M, N$ over a commutative ring $R$, this file defines the natural linear maps: $M^* \otimes M \to R$, $M \otimes M^* \to R$, and $M^* \otimes N → Hom(M, N)$, as well as proving some basic properties of these maps. ## Tags contraction, dual module, tensor product -/ variables {ι : Type*} (R M N P Q : Type*) local attribute [ext] tensor_product.ext section contraction open tensor_product linear_map matrix module open_locale tensor_product big_operators section comm_semiring variables [comm_semiring R] variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] variables [module R M] [module R N] [module R P] [module R Q] variables [decidable_eq ι] [fintype ι] (b : basis ι R M) /-- The natural left-handed pairing between a module and its dual. -/ def contract_left : (module.dual R M) ⊗ M →ₗ[R] R := (uncurry _ _ _ _).to_fun linear_map.id /-- The natural right-handed pairing between a module and its dual. -/ def contract_right : M ⊗ (module.dual R M) →ₗ[R] R := (uncurry _ _ _ _).to_fun (linear_map.flip linear_map.id) /-- The natural map associating a linear map to the tensor product of two modules. -/ def dual_tensor_hom : (module.dual R M) ⊗ N →ₗ[R] M →ₗ[R] N := let M' := module.dual R M in (uncurry R M' N (M →ₗ[R] N) : _ → M' ⊗ N →ₗ[R] M →ₗ[R] N) linear_map.smul_rightₗ variables {R M N P Q} @[simp] lemma contract_left_apply (f : module.dual R M) (m : M) : contract_left R M (f ⊗ₜ m) = f m := rfl @[simp] lemma contract_right_apply (f : module.dual R M) (m : M) : contract_right R M (m ⊗ₜ f) = f m := rfl @[simp] lemma dual_tensor_hom_apply (f : module.dual R M) (m : M) (n : N) : dual_tensor_hom R M N (f ⊗ₜ n) m = (f m) • n := rfl @[simp] lemma transpose_dual_tensor_hom (f : module.dual R M) (m : M) : dual.transpose (dual_tensor_hom R M M (f ⊗ₜ m)) = dual_tensor_hom R _ _ (dual.eval R M m ⊗ₜ f) := by { ext f' m', simp only [dual.transpose_apply, coe_comp, function.comp_app, dual_tensor_hom_apply, linear_map.map_smulₛₗ, ring_hom.id_apply, algebra.id.smul_eq_mul, dual.eval_apply, smul_apply], exact mul_comm _ _ } @[simp] lemma dual_tensor_hom_prod_map_zero (f : module.dual R M) (p : P) : ((dual_tensor_hom R M P) (f ⊗ₜ[R] p)).prod_map (0 : N →ₗ[R] Q) = dual_tensor_hom R (M × N) (P × Q) ((f ∘ₗ fst R M N) ⊗ₜ inl R P Q p) := by {ext; simp only [coe_comp, coe_inl, function.comp_app, prod_map_apply, dual_tensor_hom_apply, fst_apply, prod.smul_mk, zero_apply, smul_zero]} @[simp] lemma zero_prod_map_dual_tensor_hom (g : module.dual R N) (q : Q) : (0 : M →ₗ[R] P).prod_map ((dual_tensor_hom R N Q) (g ⊗ₜ[R] q)) = dual_tensor_hom R (M × N) (P × Q) ((g ∘ₗ snd R M N) ⊗ₜ inr R P Q q) := by {ext; simp only [coe_comp, coe_inr, function.comp_app, prod_map_apply, dual_tensor_hom_apply, snd_apply, prod.smul_mk, zero_apply, smul_zero]} lemma map_dual_tensor_hom (f : module.dual R M) (p : P) (g : module.dual R N) (q : Q) : tensor_product.map (dual_tensor_hom R M P (f ⊗ₜ[R] p)) (dual_tensor_hom R N Q (g ⊗ₜ[R] q)) = dual_tensor_hom R (M ⊗[R] N) (P ⊗[R] Q) (dual_distrib R M N (f ⊗ₜ g) ⊗ₜ[R] (p ⊗ₜ[R] q)) := begin ext m n, simp only [compr₂_apply, mk_apply, map_tmul, dual_tensor_hom_apply, dual_distrib_apply, ←smul_tmul_smul], end @[simp] lemma comp_dual_tensor_hom (f : module.dual R M) (n : N) (g : module.dual R N) (p : P) : (dual_tensor_hom R N P (g ⊗ₜ[R] p)) ∘ₗ (dual_tensor_hom R M N (f ⊗ₜ[R] n)) = g n • dual_tensor_hom R M P (f ⊗ₜ p) := begin ext m, simp only [coe_comp, function.comp_app, dual_tensor_hom_apply, linear_map.map_smul, ring_hom.id_apply, smul_apply], rw smul_comm, end /-- As a matrix, `dual_tensor_hom` evaluated on a basis element of `M* ⊗ N` is a matrix with a single one and zeros elsewhere -/ theorem to_matrix_dual_tensor_hom {m : Type*} {n : Type*} [fintype m] [fintype n] [decidable_eq m] [decidable_eq n] (bM : basis m R M) (bN : basis n R N) (j : m) (i : n) : to_matrix bM bN (dual_tensor_hom R M N (bM.coord j ⊗ₜ bN i)) = std_basis_matrix i j 1 := begin ext i' j', by_cases hij : (i = i' ∧ j = j'); simp [linear_map.to_matrix_apply, finsupp.single_eq_pi_single, hij], rw [and_iff_not_or_not, not_not] at hij, cases hij; simp [hij], end end comm_semiring section comm_ring variables [comm_ring R] 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] variables [decidable_eq ι] [fintype ι] (b : basis ι R M) variables {R M N P Q} /-- If `M` is free, the natural linear map $M^* ⊗ N → Hom(M, N)$ is an equivalence. This function provides this equivalence in return for a basis of `M`. -/ @[simps apply] noncomputable def dual_tensor_hom_equiv_of_basis : (module.dual R M) ⊗[R] N ≃ₗ[R] M →ₗ[R] N := linear_equiv.of_linear (dual_tensor_hom R M N) (∑ i, (tensor_product.mk R _ N (b.dual_basis i)) ∘ₗ linear_map.applyₗ (b i)) (begin ext f m, simp only [applyₗ_apply_apply, coe_fn_sum, dual_tensor_hom_apply, mk_apply, id_coe, id.def, fintype.sum_apply, function.comp_app, basis.coe_dual_basis, coe_comp, basis.coord_apply, ← f.map_smul, (dual_tensor_hom R M N).map_sum, ← f.map_sum, b.sum_repr], end) (begin ext f m, simp only [applyₗ_apply_apply, coe_fn_sum, dual_tensor_hom_apply, mk_apply, id_coe, id.def, fintype.sum_apply, function.comp_app, basis.coe_dual_basis, coe_comp, compr₂_apply, tmul_smul, smul_tmul', ← sum_tmul, basis.sum_dual_apply_smul_coord], end) @[simp] lemma dual_tensor_hom_equiv_of_basis_to_linear_map : (dual_tensor_hom_equiv_of_basis b : (module.dual R M) ⊗[R] N ≃ₗ[R] M →ₗ[R] N).to_linear_map = dual_tensor_hom R M N := rfl @[simp] lemma dual_tensor_hom_equiv_of_basis_symm_cancel_left (x : (module.dual R M) ⊗[R] N) : (dual_tensor_hom_equiv_of_basis b).symm (dual_tensor_hom R M N x) = x := by rw [←dual_tensor_hom_equiv_of_basis_apply b, linear_equiv.symm_apply_apply] @[simp] lemma dual_tensor_hom_equiv_of_basis_symm_cancel_right (x : M →ₗ[R] N) : dual_tensor_hom R M N ((dual_tensor_hom_equiv_of_basis b).symm x) = x := by rw [←dual_tensor_hom_equiv_of_basis_apply b, linear_equiv.apply_symm_apply] variables (R M N P Q) variables [module.free R M] [module.finite R M] [nontrivial R] open_locale classical /-- If `M` is finite free, the natural map $M^* ⊗ N → Hom(M, N)$ is an equivalence. -/ @[simp] noncomputable def dual_tensor_hom_equiv : (module.dual R M) ⊗[R] N ≃ₗ[R] M →ₗ[R] N := dual_tensor_hom_equiv_of_basis (module.free.choose_basis R M) end comm_ring end contraction section hom_tensor_hom open_locale tensor_product open module tensor_product linear_map section comm_ring variables [comm_ring R] 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] variables [free R M] [finite R M] [free R N] [finite R N] [nontrivial R] /-- When `M` is a finite free module, the map `ltensor_hom_to_hom_ltensor` is an equivalence. Note that `ltensor_hom_equiv_hom_ltensor` is not defined directly in terms of `ltensor_hom_to_hom_ltensor`, but the equivalence between the two is given by `ltensor_hom_equiv_hom_ltensor_to_linear_map` and `ltensor_hom_equiv_hom_ltensor_apply`. -/ noncomputable def ltensor_hom_equiv_hom_ltensor : P ⊗[R] (M →ₗ[R] Q) ≃ₗ[R] (M →ₗ[R] P ⊗[R] Q) := congr (linear_equiv.refl R P) (dual_tensor_hom_equiv R M Q).symm ≪≫ₗ tensor_product.left_comm R P _ Q ≪≫ₗ dual_tensor_hom_equiv R M _ /-- When `M` is a finite free module, the map `rtensor_hom_to_hom_rtensor` is an equivalence. Note that `rtensor_hom_equiv_hom_rtensor` is not defined directly in terms of `rtensor_hom_to_hom_rtensor`, but the equivalence between the two is given by `rtensor_hom_equiv_hom_rtensor_to_linear_map` and `rtensor_hom_equiv_hom_rtensor_apply`. -/ noncomputable def rtensor_hom_equiv_hom_rtensor : (M →ₗ[R] P) ⊗[R] Q ≃ₗ[R] (M →ₗ[R] P ⊗[R] Q) := congr (dual_tensor_hom_equiv R M P).symm (linear_equiv.refl R Q) ≪≫ₗ tensor_product.assoc R _ P Q ≪≫ₗ dual_tensor_hom_equiv R M _ @[simp] lemma ltensor_hom_equiv_hom_ltensor_to_linear_map : (ltensor_hom_equiv_hom_ltensor R M P Q).to_linear_map = ltensor_hom_to_hom_ltensor R M P Q := begin let e := congr (linear_equiv.refl R P) (dual_tensor_hom_equiv R M Q), have h : function.surjective e.to_linear_map := e.surjective, refine (cancel_right h).1 _, ext p f q m, dsimp [ltensor_hom_equiv_hom_ltensor], simp only [ltensor_hom_equiv_hom_ltensor, dual_tensor_hom_equiv, compr₂_apply, mk_apply, coe_comp, linear_equiv.coe_to_linear_map, function.comp_app, map_tmul, linear_equiv.coe_coe, dual_tensor_hom_equiv_of_basis_apply, linear_equiv.trans_apply, congr_tmul, linear_equiv.refl_apply, dual_tensor_hom_equiv_of_basis_symm_cancel_left, left_comm_tmul, dual_tensor_hom_apply, ltensor_hom_to_hom_ltensor_apply, tmul_smul], end @[simp] lemma rtensor_hom_equiv_hom_rtensor_to_linear_map : (rtensor_hom_equiv_hom_rtensor R M P Q).to_linear_map = rtensor_hom_to_hom_rtensor R M P Q := begin let e := congr (dual_tensor_hom_equiv R M P) (linear_equiv.refl R Q), have h : function.surjective e.to_linear_map := e.surjective, refine (cancel_right h).1 _, ext f p q m, simp only [rtensor_hom_equiv_hom_rtensor, dual_tensor_hom_equiv, compr₂_apply, mk_apply, coe_comp, linear_equiv.coe_to_linear_map, function.comp_app, map_tmul, linear_equiv.coe_coe, dual_tensor_hom_equiv_of_basis_apply, linear_equiv.trans_apply, congr_tmul, dual_tensor_hom_equiv_of_basis_symm_cancel_left, linear_equiv.refl_apply, assoc_tmul, dual_tensor_hom_apply, rtensor_hom_to_hom_rtensor_apply, smul_tmul'], end variables {R M N P Q} @[simp] lemma ltensor_hom_equiv_hom_ltensor_apply (x : P ⊗[R] (M →ₗ[R] Q)) : ltensor_hom_equiv_hom_ltensor R M P Q x = ltensor_hom_to_hom_ltensor R M P Q x := by rw [←linear_equiv.coe_to_linear_map, ltensor_hom_equiv_hom_ltensor_to_linear_map] @[simp] lemma rtensor_hom_equiv_hom_rtensor_apply (x : (M →ₗ[R] P) ⊗[R] Q) : rtensor_hom_equiv_hom_rtensor R M P Q x = rtensor_hom_to_hom_rtensor R M P Q x := by rw [←linear_equiv.coe_to_linear_map, rtensor_hom_equiv_hom_rtensor_to_linear_map] variables (R M N P Q) /-- When `M` and `N` are free `R` modules, the map `hom_tensor_hom_map` is an equivalence. Note that `hom_tensor_hom_equiv` is not defined directly in terms of `hom_tensor_hom_map`, but the equivalence between the two is given by `hom_tensor_hom_equiv_to_linear_map` and `hom_tensor_hom_equiv_apply`. -/ noncomputable def hom_tensor_hom_equiv : (M →ₗ[R] P) ⊗[R] (N →ₗ[R] Q) ≃ₗ[R] (M ⊗[R] N →ₗ[R] P ⊗[R] Q) := rtensor_hom_equiv_hom_rtensor R M P _ ≪≫ₗ (linear_equiv.refl R M).arrow_congr (ltensor_hom_equiv_hom_ltensor R N _ Q) ≪≫ₗ lift.equiv R M N _ @[simp] lemma hom_tensor_hom_equiv_to_linear_map : (hom_tensor_hom_equiv R M N P Q).to_linear_map = hom_tensor_hom_map R M N P Q := begin ext f g m n, simp only [hom_tensor_hom_equiv, compr₂_apply, mk_apply, linear_equiv.coe_to_linear_map, linear_equiv.trans_apply, lift.equiv_apply, linear_equiv.arrow_congr_apply, linear_equiv.refl_symm, linear_equiv.refl_apply, rtensor_hom_equiv_hom_rtensor_apply, ltensor_hom_equiv_hom_ltensor_apply, ltensor_hom_to_hom_ltensor_apply, rtensor_hom_to_hom_rtensor_apply, hom_tensor_hom_map_apply, map_tmul], end variables {R M N P Q} @[simp] lemma hom_tensor_hom_equiv_apply (x : (M →ₗ[R] P) ⊗[R] (N →ₗ[R] Q)) : hom_tensor_hom_equiv R M N P Q x = hom_tensor_hom_map R M N P Q x := by rw [←linear_equiv.coe_to_linear_map, hom_tensor_hom_equiv_to_linear_map] end comm_ring end hom_tensor_hom
f6a0c30ebb71feb3cf99156f584c0dfaedf56115
ec62863c729b7eedee77b86d974f2c529fa79d25
/8/b.lean
e7576c13f70efeb993570c23c0cb1db14eea3498
[]
no_license
rwbarton/advent-of-lean-4
2ac9b17ba708f66051e3d8cd694b0249bc433b65
417c7e2718253ba7148c0279fcb251b6fc291477
refs/heads/main
1,675,917,092,057
1,609,864,581,000
1,609,864,581,000
317,700,289
24
0
null
null
null
null
UTF-8
Lean
false
false
1,567
lean
inductive Instr : Type | NOP : Int → Instr | ACC : Int → Instr | JMP : Int → Instr open Instr instance : Inhabited Instr := ⟨NOP 0⟩ def execute (prog : Array Instr) : Option Int := do let mut seen : Array Bool := Array.mkArray prog.size false let mut ip : Nat := 0 let mut acc : Int := 0 -- program cannot execute more than prog.size+1 steps for _ in [0:prog.size+1] do if ip == prog.size then return acc if seen.get! ip then Option.none seen := seen.set! ip True match prog.get! ip with | NOP _ => ip := ip + 1 | ACC z => do acc := acc + z ip := ip + 1 | JMP z => ip := (ip + z : Int).toNat panic! "unreachable" def tweakAt (prog : Array Instr) (i : Nat) : Option Int := do let instr' ← match prog.get! i with | NOP n => pure (JMP n) | JMP n => pure (NOP n) | ACC n => Option.none execute (prog.set! i instr') def tweak (prog : Array Instr) : Int := do for i in [0:prog.size] do match tweakAt prog i with | Option.some a => return a | _ => () panic! "no solution found" def readSignedInt (str : String) : Int := match str.toList with | '+' :: rest => rest.asString.toInt! | '-' :: rest => - rest.asString.toInt! | _ => panic! "bad signed int" def parseProgram : Array String → Array Instr := Array.map $ λ str => match str.splitOn " " with | ["nop", n] => NOP (readSignedInt n) | ["acc", n] => ACC (readSignedInt n) | ["jmp", n] => JMP (readSignedInt n) | _ => panic! "bad instruction" def main : IO Unit := do let input ← IO.FS.lines "a.in" let prog := parseProgram input IO.print s!"{tweak prog}\n"
2e0fca5b543cf57cae16a3e7cbecc07531e94c13
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/meta/expr.lean
e105fe2d51352115fd66e97060c23b38ff28fb1e
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,059
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.level init.category.monad structure pos := (line : nat) (column : nat) instance : decidable_eq pos | ⟨l₁, c₁⟩ ⟨l₂, c₂⟩ := if h₁ : l₁ = l₂ then if h₂ : c₁ = c₂ then is_true (eq.rec_on h₁ (eq.rec_on h₂ rfl)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₂ h₂)) else is_false (λ contra, pos.no_confusion contra (λ e₁ e₂, absurd e₁ h₁)) meta instance : has_to_format pos := ⟨λ ⟨l, c⟩, "⟨" ++ l ++ ", " ++ c ++ "⟩"⟩ inductive binder_info | default | implicit | strict_implicit | inst_implicit | other instance : has_to_string binder_info := ⟨λ bi, match bi with | binder_info.default := "default" | binder_info.implicit := "implicit" | binder_info.strict_implicit := "strict_implicit" | binder_info.inst_implicit := "inst_implicit" | binder_info.other := "other" end⟩ meta constant macro_def : Type /- Reflect a C++ expr object. The VM replaces it with the C++ implementation. -/ meta inductive expr (elaborated : bool := tt) | var {} : nat → expr | sort {} : level → expr | const {} : name → list level → expr | mvar : name → expr → expr | local_const : name → name → binder_info → expr → expr | app : expr → expr → expr | lam : name → binder_info → expr → expr → expr | pi : name → binder_info → expr → expr → expr | elet : name → expr → expr → expr → expr | macro : macro_def → list expr → expr variable {elab : bool} universes u v /-- (reflected a) is a special opaque container for a closed `expr` representing `a`. It can only be obtained via type class inference, which will use the representation of `a` in the calling context. Local constants in the representation are replaced by nested inference of `reflected` instances. The quotation expression `(a) (outside of patterns) is equivalent to `reflect a` and thus can be used as an explicit way of inferring an instance of `reflected a`. -/ meta constant reflected {α : Sort u} : α → Sort (max 1 u) meta constant reflected.to_expr {α : Sort u} {a : α} : reflected a → expr meta constant reflected.subst {α : Sort u} {β : α → Sort v} {f : Π a : α, β a} {a : α} : reflected f → reflected a → reflected (f a) meta constant expr.reflect (e : expr elab) : reflected e meta constant string.reflect (s : string) : reflected s attribute [class] reflected attribute [instance] expr.reflect string.reflect meta instance {α : Type u} (a : α) : has_coe (reflected a) expr := ⟨reflected.to_expr⟩ meta def reflect {α : Type u} (a : α) [h : reflected a] : reflected a := h meta instance : inhabited expr := ⟨expr.sort level.zero⟩ meta constant expr.macro_def_name (d : macro_def) : name meta def expr.mk_var (n : nat) : expr := expr.var n /- Expressions can be annotated using the annotation macro. -/ meta constant expr.is_annotation : expr elab → option (name × expr elab) meta def expr.erase_annotations : expr elab → expr elab | e := match e.is_annotation with | some (_, a) := expr.erase_annotations a | none := e end -- Compares expressions, including binder names. meta constant expr.has_decidable_eq : decidable_eq expr attribute [instance] expr.has_decidable_eq -- Compares expressions while ignoring binder names. meta constant expr.alpha_eqv : expr → expr → bool notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt protected meta constant expr.to_string : expr elab → string meta instance : has_to_string (expr elab) := ⟨expr.to_string⟩ meta instance : has_to_format (expr elab) := ⟨λ e, e.to_string⟩ /- Coercion for letting users write (f a) instead of (expr.app f a) -/ meta instance : has_coe_to_fun (expr elab) := { F := λ e, expr elab → expr elab, coe := λ e, expr.app e } meta constant expr.hash : expr → nat -- Compares expressions, ignoring binder names, and sorting by hash. meta constant expr.lt : expr → expr → bool -- Compares expressions, ignoring binder names. meta constant expr.lex_lt : expr → expr → bool -- Compares expressions, ignoring binder names, and sorting by hash. meta def expr.cmp (a b : expr) : ordering := if expr.lt a b then ordering.lt else if a =ₐ b then ordering.eq else ordering.gt meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α meta constant expr.replace : expr → (expr → nat → option expr) → expr meta constant expr.abstract_local : expr → name → expr meta constant expr.abstract_locals : expr → list name → expr meta def expr.abstract : expr → expr → expr | e (expr.local_const n m bi t) := e.abstract_local n | e _ := e meta constant expr.instantiate_univ_params : expr → list (name × level) → expr meta constant expr.instantiate_var : expr → expr → expr meta constant expr.instantiate_vars : expr → list expr → expr protected meta constant expr.subst : expr elab → expr elab → expr elab meta constant expr.has_var : expr → bool meta constant expr.has_var_idx : expr → nat → bool meta constant expr.has_local : expr → bool meta constant expr.has_meta_var : expr → bool meta constant expr.lift_vars : expr → nat → nat → expr meta constant expr.lower_vars : expr → nat → nat → expr protected meta constant expr.pos : expr elab → option pos /- (copy_pos_info src tgt) copy position information from src to tgt. -/ meta constant expr.copy_pos_info : expr → expr → expr meta constant expr.is_internal_cnstr : expr → option unsigned meta constant expr.get_nat_value : expr → option nat meta constant expr.collect_univ_params : expr → list name /-- `occurs e t` returns `tt` iff `e` occurs in `t` -/ meta constant expr.occurs : expr → expr → bool namespace expr open decidable -- Compares expressions, ignoring binder names, and sorting by hash. meta instance : has_ordering expr := ⟨ expr.cmp ⟩ meta def mk_true : expr := const `true [] meta def mk_false : expr := const `false [] /-- Returns the sorry macro with the given type. -/ meta constant mk_sorry (type : expr) : expr /-- Checks whether e is sorry, and returns its type. -/ meta constant is_sorry (e : expr) : option expr meta def instantiate_local (n : name) (s : expr) (e : expr) : expr := instantiate_var (abstract_local e n) s meta def instantiate_locals (s : list (name × expr)) (e : expr) : expr := instantiate_vars (abstract_locals e (list.reverse (list.map prod.fst s))) (list.map prod.snd s) meta def is_var : expr → bool | (var _) := tt | _ := ff meta def app_of_list : expr → list expr → expr | f [] := f | f (p::ps) := app_of_list (f p) ps meta def is_app : expr → bool | (app f a) := tt | e := ff meta def app_fn : expr → expr | (app f a) := f | a := a meta def app_arg : expr → expr | (app f a) := a | a := a meta def get_app_fn : expr elab → expr elab | (app f a) := get_app_fn f | a := a meta def get_app_num_args : expr → nat | (app f a) := get_app_num_args f + 1 | e := 0 meta def get_app_args_aux : list expr → expr → list expr | r (app f a) := get_app_args_aux (a::r) f | r e := r meta def get_app_args : expr → list expr := get_app_args_aux [] meta def mk_app : expr → list expr → expr | e [] := e | e (x::xs) := mk_app (e x) xs meta def ith_arg_aux : expr → nat → expr | (app f a) 0 := a | (app f a) (n+1) := ith_arg_aux f n | e _ := e meta def ith_arg (e : expr) (i : nat) : expr := ith_arg_aux e (get_app_num_args e - i - 1) meta def const_name : expr → name | (const n ls) := n | e := name.anonymous meta def is_constant : expr → bool | (const n ls) := tt | e := ff meta def is_local_constant : expr → bool | (local_const n m bi t) := tt | e := ff meta def local_uniq_name : expr → name | (local_const n m bi t) := n | e := name.anonymous meta def local_pp_name : expr → name | (local_const x n bi t) := n | e := name.anonymous meta def local_type : expr → expr | (local_const _ _ _ t) := t | e := e meta def is_constant_of : expr → name → bool | (const n₁ ls) n₂ := n₁ = n₂ | e n := ff meta def is_app_of (e : expr) (n : name) : bool := is_constant_of (get_app_fn e) n meta def is_napp_of (e : expr) (c : name) (n : nat) : bool := is_app_of e c ∧ get_app_num_args e = n meta def is_false : expr → bool | `(false) := tt | _ := ff meta def is_not : expr → option expr | `(not %%a) := some a | `(%%a → false) := some a | e := none meta def is_and : expr → option (expr × expr) | `(and %%α %%β) := some (α, β) | _ := none meta def is_or : expr → option (expr × expr) | `(or %%α %%β) := some (α, β) | _ := none meta def is_eq : expr → option (expr × expr) | `((%%a : %%_) = %%b) := some (a, b) | _ := none meta def is_ne : expr → option (expr × expr) | `((%%a : %%_) ≠ %%b) := some (a, b) | _ := none meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) := if is_napp_of e op 4 then some (app_arg (app_fn e), app_arg e) else none meta def is_lt (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_lt.lt meta def is_gt (e : expr) : option (expr × expr) := is_bin_arith_app e ``gt meta def is_le (e : expr) : option (expr × expr) := is_bin_arith_app e ``has_le.le meta def is_ge (e : expr) : option (expr × expr) := is_bin_arith_app e ``ge meta def is_heq : expr → option (expr × expr × expr × expr) | `(@heq %%α %%a %%β %%b) := some (α, a, β, b) | _ := none meta def is_pi : expr → bool | (pi _ _ _ _) := tt | e := ff meta def is_arrow : expr → bool | (pi _ _ _ b) := bnot (has_var b) | e := ff meta def is_let : expr → bool | (elet _ _ _ _) := tt | e := ff meta def binding_name : expr → name | (pi n _ _ _) := n | (lam n _ _ _) := n | e := name.anonymous meta def binding_info : expr → binder_info | (pi _ bi _ _) := bi | (lam _ bi _ _) := bi | e := binder_info.default meta def binding_domain : expr → expr | (pi _ _ d _) := d | (lam _ _ d _) := d | e := e meta def binding_body : expr → expr | (pi _ _ _ b) := b | (lam _ _ _ b) := b | e := e meta def imp (a b : expr) : expr := pi `_ binder_info.default a b meta def lambdas : list expr → expr → expr | (local_const uniq pp info t :: es) f := lam pp info t (abstract_local (lambdas es f) uniq) | _ f := f meta def pis : list expr → expr → expr | (local_const uniq pp info t :: es) f := pi pp info t (abstract_local (pis es f) uniq) | _ f := f open format private meta def p := λ xs, paren (format.join (list.intersperse " " xs)) meta def to_raw_fmt : expr elab → format | (var n) := p ["var", to_fmt n] | (sort l) := p ["sort", to_fmt l] | (const n ls) := p ["const", to_fmt n, to_fmt ls] | (mvar n t) := p ["mvar", to_fmt n, to_raw_fmt t] | (local_const n m bi t) := p ["local_const", to_fmt n, to_fmt m, to_raw_fmt t] | (app e f) := p ["app", to_raw_fmt e, to_raw_fmt f] | (lam n bi e t) := p ["lam", to_fmt n, to_string bi, to_raw_fmt e, to_raw_fmt t] | (pi n bi e t) := p ["pi", to_fmt n, to_string bi, to_raw_fmt e, to_raw_fmt t] | (elet n g e f) := p ["elet", to_fmt n, to_raw_fmt g, to_raw_fmt e, to_raw_fmt f] | (macro d args) := sbracket (format.join (list.intersperse " " ("macro" :: to_fmt (macro_def_name d) :: args.map to_raw_fmt))) meta def mfold {α : Type} {m : Type → Type} [monad m] (e : expr) (a : α) (fn : expr → nat → α → m α) : m α := fold e (return a) (λ e n a, a >>= fn e n) end expr
c2cc3635a1a2f53bc04669ea344cc7706f3305e2
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0701.lean
96d7e46529e7b6b9368bb1800778077e1a9cf27d
[]
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
2,896
lean
variables p q r : Prop -- commutativity of ∧ and ∨ example : p ∧ q ↔ q ∧ p := ⟨λ h, ⟨h.right, h.left⟩, λ h, ⟨h.right, h.left⟩⟩ example : p ∨ q ↔ q ∨ p := ⟨λ h, h.elim (λ hp, or.inr hp) (λ hq, or.inl hq), λ h, h.elim (λ hp, or.inr hp) (λ hq, or.inl hq)⟩ -- associativity of ∧ and ∨ example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := ⟨λ h, ⟨h.left.left, h.left.right, h.right⟩, λ h, ⟨⟨h.left, h.right.left⟩, h.right.right⟩⟩ example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := ⟨λ h, h.elim (assume hpq, hpq.elim (assume hp, or.inl hp) (assume hq, or.inr (or.inl hq))) (assume hr, or.inr (or.inr hr)), λ h, h.elim (assume hp, or.inl (or.inl hp)) (assume hqr, hqr.elim (assume hq, or.inl (or.inr hq)) (assume hr, or.inr hr))⟩ -- distributivity example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := ⟨λ h, h.right.elim (assume hq, or.inl ⟨h.left, hq⟩) (assume hr, or.inr ⟨h.left, hr⟩), λ h, h.elim (assume hpq, ⟨hpq.left, or.inl hpq.right⟩) (assume hpr, ⟨hpr.left, or.inr hpr.right⟩)⟩ example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := ⟨λ h, h.elim (assume hp, ⟨or.inl hp, or.inl hp⟩) (assume hqr, ⟨or.inr hqr.left, or.inr hqr.right⟩), λ h, h.left.elim (assume hp, or.inl hp) (assume hq, h.right.elim (assume hp, or.inl hp) (assume hr, or.inr ⟨hq, hr⟩))⟩ -- other properties example : (p → (q → r)) ↔ (p ∧ q → r) := ⟨λ h hpq, h hpq.left hpq.right, λ h hp hq, h ⟨hp, hq⟩⟩ example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := ⟨λ h, ⟨λ hp, h (or.inl hp), λ hq, h (or.inr hq)⟩, λ h hpq, hpq.elim (assume hp, h.left hp) (assume hq, h.right hq)⟩ example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := ⟨λ h, ⟨λ hp, h (or.inl hp), λ hq, h (or.inr hq)⟩, λ h hpq, hpq.elim h.left h.right⟩ example : ¬p ∨ ¬q → ¬(p ∧ q) := assume h hpq, h.elim (assume hnp, hnp hpq.left) (assume hnq, hnq hpq.right) example : ¬(p ∧ ¬p) := λ h, h.right h.left example : p ∧ ¬q → ¬(p → q) := assume hpnq hp2q, suffices hq : q, from hpnq.right hq, show q, from hp2q hpnq.left example : ¬p → (p → q) := λ hnp hp, absurd hp hnp example : (¬p ∨ q) → (p → q) := assume hnpq hp, hnpq.elim (assume hnp, absurd hp hnp) (assume hq, hq) example : p ∨ false ↔ p := ⟨λ h, h.elim id false.elim, λ h, or.inl h⟩ example : p ∧ false ↔ false := ⟨λ h, h.right, λ h, false.elim h⟩ example : ¬(p ↔ ¬p) := assume h, suffices hnp : ¬p, from hnp (h.mpr hnp), assume hp, h.mp hp hp example : (p → q) → (¬q → ¬p) := assume hp2q hnq hp, hnq (hp2q hp)
c9fb937bb425f4d74eac1d5889a73602c13ebc35
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Meta.lean
75e15b42362ca8d4d7155173e4681ef3e50712a1
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
678
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Meta.Basic import Init.Lean.Meta.LevelDefEq import Init.Lean.Meta.WHNF import Init.Lean.Meta.InferType import Init.Lean.Meta.FunInfo import Init.Lean.Meta.ExprDefEq import Init.Lean.Meta.DiscrTree import Init.Lean.Meta.Reduce import Init.Lean.Meta.Instances import Init.Lean.Meta.AbstractMVars import Init.Lean.Meta.SynthInstance import Init.Lean.Meta.AppBuilder import Init.Lean.Meta.Tactic import Init.Lean.Meta.Message import Init.Lean.Meta.KAbstract import Init.Lean.Meta.RecursorInfo
67bba1bc813a25dfa18e3e3cab031c440696f02d
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/rewriter12.lean
82d0c807e4ec2cb7dc4be47f4e1c38995e2fc0bd
[ "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
303
lean
import data.nat open nat constant f : nat → nat example (x y : nat) (H1 : (λ z, z + 0) x = y) : f x = f y := by rewrite [▸* at H1, ^ [add, nat.rec_on, of_num] at H1, H1] example (x y : nat) (H1 : (λ z, z + 0) x = y) : f x = f y := by rewrite [▸* at H1, ↑[add, nat.rec_on, of_num] at H1, H1]
cb5b74d354023c148894990ef24ed757419e9fe6
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Meta/Tactic/Rewrite.lean
dd9b2d68aa7efeb00040de8296444928bfedd41c
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,672
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.MatchUtil import Lean.Meta.KAbstract import Lean.Meta.Check import Lean.Meta.Tactic.Apply namespace Lean.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 let heqType ← inferType heq let (newMVars, binderInfos, heqType) ← forallMetaTelescopeReducing heqType let heq := mkAppN heq newMVars let cont (heq heqType : Expr) : MetaM RewriteResult := do match (← matchEq? heqType) with | none => throwTacticEx `rewrite mvarId msg!"equality or iff proof expected{indentExpr heqType}" | some (α, lhs, rhs) => let cont (heq heqType lhs rhs : Expr) : MetaM RewriteResult := do if lhs.getAppFn.isMVar then throwTacticEx `rewrite mvarId msg!"pattern is a metavariable{indentExpr lhs}\nfrom equation{indentExpr heqType}" let e ← instantiateMVars e let eAbst ← kabstract e lhs occs unless eAbst.hasLooseBVars do throwTacticEx `rewrite mvarId msg!"did not find instance of the pattern in the target expression{indentExpr lhs}" -- construct rewrite proof let eNew := eAbst.instantiate1 rhs let eNew ← instantiateMVars eNew let eEqE ← mkEq e e let eEqEAbst := mkApp eEqE.appFn! eAbst let motive := Lean.mkLambda `_a BinderInfo.default α eEqEAbst unless (← isTypeCorrect motive) do throwTacticEx `rewrite mvarId "motive is not type correct" let eqRefl ← mkEqRefl e let eqPrf ← mkEqNDRec motive eqRefl heq postprocessAppMVars `rewrite mvarId newMVars binderInfos let newMVars ← newMVars.filterM fun mvar => not <$> isExprMVarAssigned mvar.mvarId! pure { eNew := eNew, eqProof := eqPrf, mvarIds := newMVars.toList.map Expr.mvarId! } match symm with | false => cont heq heqType lhs rhs | true => do let heq ← mkEqSymm heq let heqType ← mkEq rhs lhs cont heq heqType rhs lhs match heqType.iff? with | some (lhs, rhs) => let heqType ← mkEq lhs rhs let heq := mkApp3 (mkConst `propext) lhs rhs heq cont heq heqType | none => cont heq heqType end Lean.Meta
ead63ee14acea86011cdca27cb4c2ee24cc7a2c2
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/hex_numeral.lean
8a07c476b5fcfbde7386e03cdac74e7271719a9a
[ "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
100
lean
#eval (0xff : nat) #eval (0xffff : nat) #eval (0xaa : nat) #eval (0x10 : nat) #eval (0x10000 : nat)
c812502f26a3232b6f40cc8241574b5fbb7de49c
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/equiv/ring.lean
a1debe137c044c87500b65a7da0e8fb29bbbe60a
[ "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
13,995
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, Callum Sutton, Yury Kudryashov -/ import data.equiv.mul_add import algebra.field import algebra.opposites /-! # (Semi)ring equivs In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the corresponding group of automorphisms `ring_aut`. ## Notations * ``infix ` ≃+* `:25 := ring_equiv`` The extended equiv have coercions to functions, and the coercion is the canonical notation when treating the isomorphism as maps. ## Implementation notes The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. Definition of multiplication in the groups of automorphisms agrees with function composition, multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with `category_theory.comp`. ## Tags equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut -/ variables {R : Type*} {S : Type*} {S' : Type*} set_option old_structure_cmd true /-- An equivalence between two (semi)rings that preserves the algebraic structure. -/ structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S] extends R ≃ S, R ≃* S, R ≃+ S infix ` ≃+* `:25 := ring_equiv /-- The "plain" equivalence of types underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_equiv /-- The equivalence of additive monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_add_equiv /-- The equivalence of multiplicative monoids underlying an equivalence of (semi)rings. -/ add_decl_doc ring_equiv.to_mul_equiv namespace ring_equiv section basic variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S'] instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : R ≃+* S) : f.to_fun = f := rfl /-- A ring isomorphism preserves multiplication. -/ @[simp] lemma map_mul (e : R ≃+* S) (x y : R) : e (x * y) = e x * e y := e.map_mul' x y /-- A ring isomorphism preserves addition. -/ @[simp] lemma map_add (e : R ≃+* S) (x y : R) : e (x + y) = e x + e y := e.map_add' x y /-- Two ring isomorphisms agree if they are defined by the same underlying function. -/ @[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end @[simp] theorem coe_mk (e e' h₁ h₂ h₃ h₄) : ⇑(⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := rfl @[simp] theorem mk_coe (e : R ≃+* S) (e' h₁ h₂ h₃ h₄) : (⟨e, e', h₁, h₂, h₃, h₄⟩ : R ≃+* S) = e := ext $ λ _, rfl protected lemma congr_arg {f : R ≃+* S} : Π {x x' : R}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : R ≃+* S} (h : f = g) (x : R) : f x = g x := h ▸ rfl lemma ext_iff {f g : R ≃+* S} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩ instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩ lemma to_add_equiv_eq_coe (f : R ≃+* S) : f.to_add_equiv = ↑f := rfl lemma to_mul_equiv_eq_coe (f : R ≃+* S) : f.to_mul_equiv = ↑f := rfl @[simp, norm_cast] lemma coe_to_mul_equiv (f : R ≃+* S) : ⇑(f : R ≃* S) = f := rfl @[simp, norm_cast] lemma coe_to_add_equiv (f : R ≃+* S) : ⇑(f : R ≃+ S) = f := rfl /-- The `ring_equiv` between two semirings with a unique element. -/ def ring_equiv_of_unique_of_unique {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : M ≃+* N := { ..add_equiv.add_equiv_of_unique_of_unique, ..mul_equiv.mul_equiv_of_unique_of_unique} instance {M N} [unique M] [unique N] [has_add M] [has_mul M] [has_add N] [has_mul N] : unique (M ≃+* N) := { default := ring_equiv_of_unique_of_unique, uniq := λ _, ext $ λ x, subsingleton.elim _ _ } variable (R) /-- The identity map is a ring isomorphism. -/ @[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R } @[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl @[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl @[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl instance : inhabited (R ≃+* R) := ⟨ring_equiv.refl R⟩ variables {R} /-- The inverse of a ring isomorphism is a ring isomorphism. -/ @[symm] protected def symm (e : R ≃+* S) : S ≃+* R := { .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm } /-- See Note [custom simps projection] -/ def simps.inv_fun (e : R ≃+* S) : S → R := e.symm initialize_simps_projections ring_equiv (to_fun → apply, inv_fun → symm_apply) @[simp] lemma symm_symm (e : R ≃+* S) : e.symm.symm = e := ext $ λ x, rfl lemma symm_bijective : function.bijective (ring_equiv.symm : (R ≃+* S) → (S ≃+* R)) := equiv.bijective ⟨ring_equiv.symm, ring_equiv.symm, symm_symm, symm_symm⟩ @[simp] lemma mk_coe' (e : R ≃+* S) (f h₁ h₂ h₃ h₄) : (ring_equiv.mk f ⇑e h₁ h₂ h₃ h₄ : S ≃+* R) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[simp] lemma symm_mk (f : R → S) (g h₁ h₂ h₃ h₄) : (mk f g h₁ h₂ h₃ h₄).symm = { to_fun := g, inv_fun := f, ..(mk f g h₁ h₂ h₃ h₄).symm} := rfl /-- Transitivity of `ring_equiv`. -/ @[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' := { .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) } @[simp] lemma trans_apply {A B C : Type*} [semiring A] [semiring B] [semiring C] (e : A ≃+* B) (f : B ≃+* C) (a : A) : e.trans f a = f (e a) := rfl protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective @[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s end basic section comm_semiring open opposite variables (R) [comm_semiring R] /-- A commutative ring is isomorphic to its opposite. -/ def to_opposite : R ≃+* Rᵒᵖ := { map_add' := λ x y, rfl, map_mul' := λ x y, mul_comm (op y) (op x), ..equiv_to_opposite } @[simp] lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl @[simp] lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl end comm_semiring section semiring variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R) /-- A ring isomorphism sends one to one. -/ @[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one /-- A ring isomorphism sends zero to zero. -/ @[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero variable {x} @[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff @[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff /-- Produce a ring isomorphism from a bijective ring homomorphism. -/ noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S := { .. equiv.of_bijective f hf, .. f } end semiring section variables [ring R] [ring S] (f : R ≃+* S) (x y : R) @[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x @[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y @[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1 end section semiring_hom variables [semiring R] [semiring S] [semiring S'] /-- Reinterpret a ring equivalence as a ring homomorphism. -/ def to_ring_hom (e : R ≃+* S) : R →+* S := { .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom } lemma to_ring_hom_injective : function.injective (to_ring_hom : (R ≃+* S) → R →+* S) := λ f g h, ring_equiv.ext (ring_hom.ext_iff.1 h) instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩ lemma to_ring_hom_eq_coe (f : R ≃+* S) : f.to_ring_hom = ↑f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : R ≃+* S) : ⇑(f : R →+* S) = f := rfl lemma coe_ring_hom_inj_iff {R S : Type*} [semiring R] [semiring S] (f g : R ≃+* S) : f = g ↔ (f : R →+* S) = g := ⟨congr_arg _, λ h, ext $ ring_hom.ext_iff.mp h⟩ /-- Reinterpret a ring equivalence as a monoid homomorphism. -/ abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom /-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/ abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom /-- The two paths coercion can take to an `add_monoid_hom` are equivalent -/ lemma to_add_monoid_hom_commutes (f : R ≃+* S) : (f : R →+* S).to_add_monoid_hom = (f : R ≃+ S).to_add_monoid_hom := rfl /-- The two paths coercion can take to an `monoid_hom` are equivalent -/ lemma to_monoid_hom_commutes (f : R ≃+* S) : (f : R →+* S).to_monoid_hom = (f : R ≃* S).to_monoid_hom := rfl /-- The two paths coercion can take to an `equiv` are equivalent -/ lemma to_equiv_commutes (f : R ≃+* S) : (f : R ≃+ S).to_equiv = (f : R ≃* S).to_equiv := rfl @[simp] lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl @[simp] lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl @[simp] lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl @[simp] lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) : ∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y := e.to_equiv.apply_symm_apply @[simp] lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) : ∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x := equiv.symm_apply_apply (e.to_equiv) @[simp] lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : (e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl @[simp] lemma to_ring_hom_comp_symm_to_ring_hom (e : R ≃+* S) : e.to_ring_hom.comp e.symm.to_ring_hom = ring_hom.id _ := by { ext, simp } @[simp] lemma symm_to_ring_hom_comp_to_ring_hom (e : R ≃+* S) : e.symm.to_ring_hom.comp e.to_ring_hom = ring_hom.id _ := by { ext, simp } /-- Construct an equivalence of rings from homomorphisms in both directions, which are inverses. -/ def of_hom_inv (hom : R →+* S) (inv : S →+* R) (hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) : R ≃+* S := { inv_fun := inv, left_inv := λ x, ring_hom.congr_fun hom_inv_id x, right_inv := λ x, ring_hom.congr_fun inv_hom_id x, ..hom } @[simp] lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) : (of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl @[simp] lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) : (of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl end semiring_hom end ring_equiv namespace mul_equiv /-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/ def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S] (h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S := {..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H } end mul_equiv namespace ring_equiv variables [has_add R] [has_add S] [has_mul R] [has_mul S] @[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3 @[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4 /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B] (hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A := { mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa, eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy, have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero], (hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx) (λ hy, by simpa using congr_arg e.symm hy), exists_pair_ne := ⟨e.symm 0, e.symm 1, by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ } /-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/ protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B] (e : A ≃+* B) : integral_domain A := { .. (‹_› : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) } end ring_equiv namespace equiv variables (K : Type*) [division_ring K] /-- In a division ring `K`, the unit group `units K` is equivalent to the subtype of nonzero elements. -/ -- TODO: this might already exist elsewhere for `group_with_zero` -- deduplicate or generalize def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} := ⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩ variable {K} @[simp] lemma coe_units_equiv_ne_zero (a : units K) : ((units_equiv_ne_zero K a) : K) = a := rfl end equiv
463b431500222e7fd30c62e312475d2d22b4f716
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/data/nat/prime.lean
3a4a0094622ab57e52a61b2897e5d820b5879134
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,717
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro Prime numbers. -/ import data.nat.sqrt data.nat.gcd open bool subtype namespace nat open decidable def prime (p : ℕ) := p ≥ 2 ∧ ∀ m ∣ p, m = 1 ∨ m = p theorem prime.ge_two {p : ℕ} : prime p → p ≥ 2 := and.left theorem prime.gt_one {p : ℕ} : prime p → p > 1 := prime.ge_two theorem prime_def_lt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m < p, m ∣ p → m = 1 := and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h l d, (h d).resolve_right (ne_of_lt l), λ h d, (lt_or_eq_of_le $ le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩ theorem prime_def_lt' {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p := prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m, ⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial), λ h l d, begin rcases m with _|_|m, { rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial }, { refl }, { exact (h dec_trivial l).elim d } end⟩ theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p := prime_def_lt'.trans $ and_congr_right $ λ p2, ⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2, λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from λ m k mk m1 e, a m m1 (le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩, λ m m2 l ⟨k, e⟩, begin cases (le_total m k) with mk km, { exact this mk m2 e }, { rw [mul_comm] at e, refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e, rwa [one_mul, ← e] } end⟩ def decidable_prime_1 (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_lt' local attribute [instance] decidable_prime_1 theorem prime.pos {p : ℕ} (pp : prime p) : p > 0 := lt_of_succ_lt pp.gt_one theorem not_prime_zero : ¬ prime 0 := dec_trivial theorem not_prime_one : ¬ prime 1 := dec_trivial theorem prime_two : prime 2 := dec_trivial theorem prime_three : prime 3 := dec_trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : pred p > 0 := lt_pred_of_succ_lt pp.gt_one theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p := succ_pred_eq_of_pos pp.pos theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := ⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩ theorem dvd_prime_ge_two {p m : ℕ} (pp : prime p) (H : m ≥ 2) : m ∣ p ↔ m = p := (dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1 | d := (not_le_of_gt pp.gt_one) $ le_of_dvd dec_trivial d section min_fac private lemma min_fac_lemma (n k : ℕ) (h : ¬ k * k > n) : sqrt n - k < sqrt n + 2 - k := (nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $ nat.lt_add_of_pos_right dec_trivial def min_fac_aux (n : ℕ) : ℕ → ℕ | k := if h : n < k * k then n else if k ∣ n then k else have _, from min_fac_lemma n k h, min_fac_aux (k + 2) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} -- returns the smallest prime factor of n ≠ 1 def min_fac : ℕ → ℕ | 0 := 2 | 1 := 1 | (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3 @[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq : ∀ {n : ℕ} (n2 : n ≥ 2), min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3 | 1 h := (dec_trivial : ¬ _).elim h | (n+2) h := by by_cases 2 ∣ n; simp [min_fac, (nat.dvd_add_iff_left (dvd_refl 2)).symm, h] private def min_fac_prop (n k : ℕ) := k ≥ 2 ∧ k ∣ n ∧ ∀ m ≥ 2, m ∣ n → k ≤ m theorem min_fac_aux_has_prop {n : ℕ} (n2 : n ≥ 2) (nd2 : ¬ 2 ∣ n) : ∀ k i, k = 2*i+3 → (∀ m ≥ 2, m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) | k := λ i e a, begin rw min_fac_aux, by_cases n < k*k with h; simp [h], { have pp : prime n := prime_def_le_sqrt.2 ⟨n2, λ m m2 l d, not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩, from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq ((dvd_prime_ge_two pp m2).1 d).symm⟩ }, have k2 : 2 ≤ k, { subst e, exact dec_trivial }, by_cases k ∣ n with dk; simp [dk], { exact ⟨k2, dk, a⟩ }, { refine have _, from min_fac_lemma n k h, min_fac_aux_has_prop (k+2) (i+1) (by simp [e, left_distrib]) (λ m m2 d, _), cases nat.eq_or_lt_of_le (a m m2 d) with me ml, { subst me, contradiction }, apply (nat.eq_or_lt_of_le ml).resolve_left, intro me, rw [← me, e] at d, change 2 * (i + 2) ∣ n at d, have := dvd_of_mul_right_dvd d, contradiction } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]} theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := begin by_cases n = 0 with n0, {simp [n0, min_fac_prop, ge]}, have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial }, simp [min_fac_eq n2], by_cases 2 ∣ n with d2; simp [d2], { exact ⟨le_refl _, d2, λ k k2 d, k2⟩ }, { refine min_fac_aux_has_prop n2 d2 3 0 rfl (λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)), exact λ e, e.symm ▸ d } end theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := by by_cases n = 1 with n1; [exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1] theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩ theorem min_fac_le_of_dvd (n : ℕ) : ∀ (m : ℕ), m ≥ 2 → m ∣ n → min_fac n ≤ m := by by_cases n = 1 with n1; [exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2, exact (min_fac_has_prop n1).2.2] theorem min_fac_pos (n : ℕ) : min_fac n > 0 := by by_cases n = 1 with n1; [exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos] theorem min_fac_le {n : ℕ} (H : n > 0) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ p ≥ 2 ∧ min_fac p = p := ⟨λ pp, ⟨pp.ge_two, let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.gt_one in ((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩, λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩ instance decidable_prime (p : ℕ) : decidable (prime p) := decidable_of_iff' _ prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : n ≥ 2) : ¬ prime n ↔ min_fac n < n := (not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $ (lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm end min_fac theorem exists_dvd_of_not_prime {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n := ⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).gt_one, ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) : ∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n := ⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).ge_two, (not_prime_iff_min_fac_lt n2).1 np⟩ theorem exists_prime_and_dvd {n : ℕ} (n2 : n ≥ 2) : ∃ p, prime p ∧ p ∣ n := ⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩ theorem exists_infinite_primes : ∀ n : ℕ, ∃ p, p ≥ n ∧ prime p := suffices ∀ {n}, n ≥ 2 → ∃ p, p ≥ n ∧ prime p, from λ n, let ⟨p, h, pp⟩ := this (nat.le_add_left 2 n) in ⟨p, le_trans (nat.le_add_right n 2) h, pp⟩, λ n n2, let p := min_fac (fact n + 1) in have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _, have pp : prime p, from min_fac_prime f1, have n ≤ p, from le_of_not_ge $ λ h, have p ∣ fact n, from dvd_fact (min_fac_pos _) h, have p ∣ 1, from (nat.dvd_add_iff_right this).2 (min_fac_dvd _), pp.not_dvd_one this, ⟨p, this, pp⟩ theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n := ⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]), λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_ge_two pp m2).1 mp).symm ▸ nd⟩ theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n := iff_not_comm.2 pp.coprime_iff_not_dvd theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := ⟨λ H, or_iff_not_imp_left.2 $ λ h, (pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H, or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩ theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n := mt pp.dvd_mul.1 $ by simp [Hm, Hn] theorem dvd_of_prime_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m := by induction n with n IH; [exact pp.not_dvd_one.elim h, exact (pp.dvd_mul.1 h).elim IH id] theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) := (pp.coprime_iff_not_dvd.2 h).symm.pow_right _ theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_ge_two pq pp.ge_two theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p^n) (q^m) := ((coprime_primes pp pq).2 h).pow _ _ theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := by rw [pp.dvd_iff_not_coprime]; apply em theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k := begin induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *}, by_cases p ∣ i, { cases h with a e, subst e, rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH], split; intro h; rcases h with ⟨k, h, e⟩, { exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ }, cases k with k, { apply pp.not_dvd_one.elim, simp at e, rw ← e, apply dvd_mul_right }, { refine ⟨k, le_of_succ_le_succ h, _⟩, rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } }, { split; intro d, { rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d, exact ⟨0, zero_le _, rfl⟩ }, { rcases d with ⟨k, l, e⟩, rw e, exact pow_dvd_pow _ l } } end end nat
2056724991749c10240d1e0e3cb040bbad11824d
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/analysis/convex/topology.lean
18c980ac5378ecfc8cd3fefdd92de5d8d02a6d99
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
7,617
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import analysis.convex.basic import analysis.normed_space.finite_dimension /-! # Topological and metric properties of convex sets We prove the following facts: * `convex.interior` : interior of a convex set is convex; * `convex.closure` : closure of a convex set is convex; * `set.finite.compact_convex_hull` : convex hull of a finite set is compact; * `set.finite.is_closed_convex_hull` : convex hull of a finite set is closed; * `convex_on_dist` : distance to a fixed point is convex on any convex set; * `convex_hull_ediam`, `convex_hull_diam` : convex hull of a set has the same (e)metric diameter as the original set; * `bounded_convex_hull` : convex hull of a set is bounded if and only if the original set is bounded. * `bounded_std_simplex`, `is_closed_std_simplex`, `compact_std_simplex`: topological properties of the standard simplex; -/ variables {ι : Type*} {E : Type*} open set /-! ### Standard simplex -/ section std_simplex variables [fintype ι] /-- Every vector in `std_simplex ι` has `max`-norm at most `1`. -/ lemma std_simplex_subset_closed_ball : std_simplex ι ⊆ metric.closed_ball 0 1 := begin assume f hf, rw [metric.mem_closed_ball, dist_zero_right], refine (nnreal.coe_one ▸ nnreal.coe_le_coe.2 $ finset.sup_le $ λ x hx, _), change abs (f x) ≤ 1, rw [abs_of_nonneg $ hf.1 x], exact (mem_Icc_of_mem_std_simplex hf x).2 end variable (ι) /-- `std_simplex ι` is bounded. -/ lemma bounded_std_simplex : metric.bounded (std_simplex ι) := (metric.bounded_iff_subset_ball 0).2 ⟨1, std_simplex_subset_closed_ball⟩ /-- `std_simplex ι` is closed. -/ lemma is_closed_std_simplex : is_closed (std_simplex ι) := (std_simplex_eq_inter ι).symm ▸ is_closed_inter (is_closed_Inter $ λ i, is_closed_le continuous_const (continuous_apply i)) (is_closed_eq (continuous_finset_sum _ $ λ x _, continuous_apply x) continuous_const) /-- `std_simplex ι` is compact. -/ lemma compact_std_simplex : compact (std_simplex ι) := metric.compact_iff_closed_bounded.2 ⟨is_closed_std_simplex ι, bounded_std_simplex ι⟩ end std_simplex /-! ### Topological vector space -/ section topological_vector_space variables [add_comm_group E] [vector_space ℝ E] [topological_space E] [topological_add_group E] [topological_vector_space ℝ E] local attribute [instance] set.pointwise_add set.smul_set /-- In a topological vector space, the interior of a convex set is convex. -/ lemma convex.interior {s : set E} (hs : convex s) : convex (interior s) := convex_iff_pointwise_add_subset.mpr $ λ a b ha hb hab, have h : is_open (a • interior s + b • interior s), from or.elim (classical.em (a = 0)) (λ heq, have hne : b ≠ 0, by { rw [heq, zero_add] at hab, rw hab, exact one_ne_zero }, (smul_set_eq_image b (interior s)).symm ▸ (is_open_pointwise_add_left ((is_open_map_smul_of_ne_zero hne _) is_open_interior))) (λ hne, (smul_set_eq_image a (interior s)).symm ▸ (is_open_pointwise_add_right ((is_open_map_smul_of_ne_zero hne _) is_open_interior))), (subset_interior_iff_subset_of_open h).mpr $ subset.trans begin apply pointwise_add_subset_add; rw [smul_set_eq_image, smul_set_eq_image]; exact image_subset _ interior_subset end (convex_iff_pointwise_add_subset.mp hs ha hb hab) /-- In a topological vector space, the closure of a convex set is convex. -/ lemma convex.closure {s : set E} (hs : convex s) : convex (closure s) := λ x y hx hy a b ha hb hab, let f : E → E → E := λ x' y', a • x' + b • y' in have hf : continuous (λ p : E × E, f p.1 p.2), from (continuous_const.smul continuous_fst).add (continuous_const.smul continuous_snd), show f x y ∈ closure s, from mem_closure_of_continuous2 hf hx hy (λ x' hx' y' hy', subset_closure (hs hx' hy' ha hb hab)) /-- Convex hull of a finite set is compact. -/ lemma set.finite.compact_convex_hull {s : set E} (hs : finite s) : compact (convex_hull s) := begin rw [hs.convex_hull_eq_image], apply (compact_std_simplex _).image, haveI := hs.fintype, apply linear_map.continuous_on_pi end /-- Convex hull of a finite set is closed. -/ lemma set.finite.is_closed_convex_hull [t2_space E] {s : set E} (hs : finite s) : is_closed (convex_hull s) := hs.compact_convex_hull.is_closed end topological_vector_space /-! ### Normed vector space -/ section normed_space variables [normed_group E] [normed_space ℝ E] lemma convex_on_dist (z : E) (s : set E) (hs : convex s) : convex_on s (λz', dist z' z) := and.intro hs $ assume x y hx hy a b ha hb hab, calc dist (a • x + b • y) z = ∥ (a • x + b • y) - (a + b) • z ∥ : by rw [hab, one_smul, normed_group.dist_eq] ... = ∥a • (x - z) + b • (y - z)∥ : by rw [add_smul, smul_sub, smul_sub, sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg, neg_add, ←add_assoc, add_assoc (a • x), add_comm (b • y)]; simp only [add_assoc] ... ≤ ∥a • (x - z)∥ + ∥b • (y - z)∥ : norm_add_le (a • (x - z)) (b • (y - z)) ... = a * dist x z + b * dist y z : by simp [norm_smul, normed_group.dist_eq, real.norm_eq_abs, abs_of_nonneg ha, abs_of_nonneg hb] lemma convex_ball (a : E) (r : ℝ) : convex (metric.ball a r) := by simpa only [metric.ball, sep_univ] using (convex_on_dist a _ convex_univ).convex_lt r lemma convex_closed_ball (a : E) (r : ℝ) : convex (metric.closed_ball a r) := by simpa only [metric.closed_ball, sep_univ] using (convex_on_dist a _ convex_univ).convex_le r /-- Given a point `x` in the convex hull of `s` and a point `y`, there exists a point of `s` at distance at least `dist x y` from `y`. -/ lemma convex_hull_exists_dist_ge {s : set E} {x : E} (hx : x ∈ convex_hull s) (y : E) : ∃ x' ∈ s, dist x y ≤ dist x' y := (convex_on_dist y _ (convex_convex_hull _)).exists_ge_of_mem_convex_hull hx /-- Given a point `x` in the convex hull of `s` and a point `y` in the convex hull of `t`, there exist points `x' ∈ s` and `y' ∈ t` at distance at least `dist x y`. -/ lemma convex_hull_exists_dist_ge2 {s t : set E} {x y : E} (hx : x ∈ convex_hull s) (hy : y ∈ convex_hull t) : ∃ (x' ∈ s) (y' ∈ t), dist x y ≤ dist x' y' := begin rcases convex_hull_exists_dist_ge hx y with ⟨x', hx', Hx'⟩, rcases convex_hull_exists_dist_ge hy x' with ⟨y', hy', Hy'⟩, use [x', hx', y', hy'], exact le_trans Hx' (dist_comm y x' ▸ dist_comm y' x' ▸ Hy') end /-- Emetric diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/ @[simp] lemma convex_hull_ediam (s : set E) : emetric.diam (convex_hull s) = emetric.diam s := begin refine le_antisymm (emetric.diam_le_of_forall_edist_le $ λ x hx y hy, _) (emetric.diam_mono $ subset_convex_hull s), rcases convex_hull_exists_dist_ge2 hx hy with ⟨x', hx', y', hy', H⟩, rw edist_dist, apply le_trans (ennreal.of_real_le_of_real H), rw ← edist_dist, exact emetric.edist_le_diam_of_mem hx' hy' end /-- Diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/ @[simp] lemma convex_hull_diam (s : set E) : metric.diam (convex_hull s) = metric.diam s := by simp only [metric.diam, convex_hull_ediam] /-- Convex hull of `s` is bounded if and only if `s` is bounded. -/ @[simp] lemma bounded_convex_hull {s : set E} : metric.bounded (convex_hull s) ↔ metric.bounded s := by simp only [metric.bounded_iff_ediam_ne_top, convex_hull_ediam] end normed_space
3586b00d8c37c66c566eaa9b01ba8e23feaf223a
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/newfrontend1.lean
2246eb28291f82fa751ad68845c739decad4e527
[ "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
8,776
lean
def x := 1 #check x variable {α : Type} def f (a : α) : α := a def tst (xs : List Nat) : Nat := xs.foldl (init := 10) (· + ·) #check tst [1, 2, 3] #check fun x y : Nat => x + y #check tst #check (fun stx => if True then let e := stx; Pure.pure e else Pure.pure stx : Nat → Id Nat) #check let x : Nat := 1; x def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat := a + b set_option pp.all true #check foo 1 #check foo 3 (c := false) def Nat.boo (a : Nat) := succ a -- succ here is resolved as `Nat.succ`. #check Nat.boo #check true -- apply is still a valid identifier name def apply := "hello" #check apply theorem simple1 (x y : Nat) (h : x = y) : x = y := by { assumption } theorem simple2 (x y : Nat) : x = y → x = y := by { intro h; assumption } syntax "intro2" : tactic macro_rules | `(tactic| intro2) => `(tactic| intro; intro ) theorem simple3 (x y : Nat) : x = x → x = y → x = y := by { intro2; assumption } macro "intro3" : tactic => `(intro; intro; intro) macro "check2" x:term : command => `(#check $x #check $x) macro "foo" x:term "," y:term : term => `($x + $y + $x) set_option pp.all false check2 0+1 check2 foo 0,1 theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y := by { intro3; assumption } theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; exact Eq.trans h3 h1 } theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine Eq.trans ?_ h1; assumption } theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine' Eq.trans ?pre ?post; exact y; { exact h3 } { exact h1 } } theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := by intro h1; intro _; intro h3 refine' Eq.trans ?pre ?post case post => exact h1 case pre => exact h3 theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 traceState focus refine' Eq.trans ?pre ?post first | exact h1 assumption | exact y exact h3 assumption theorem simple9b (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 traceState focus refine' Eq.trans ?pre ?post first | exact h1 | exact y; exact h3 assumption theorem simple9c (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 solve | exact h1 | refine' Eq.trans ?pre ?post; exact y; exact h3; assumption | exact h3 theorem simple9d (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 refine' Eq.trans ?pre ?post solve | exact h1 | exact y | exact h3 solve | exact h1 | exact h3 solve | exact h1 | assumption namespace Foo def Prod.mk := 1 #check (⟨2, 3⟩ : Prod _ _) end Foo theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; skip; apply Eq.trans; exact h3; assumption } theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; traceState; exact h3; assumption } theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails traceState; try exact h3; traceState; try exact h1; } theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3 traceState apply @Eq.trans case b => exact y traceState repeat assumption theorem simple13b (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; traceState; apply @Eq.trans; case b => exact y; traceState; repeat assumption } theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros apply @Eq.trans case b => exact y repeat assumption theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; revert y; intros y h1 h3; apply Eq.trans; exact h3; exact h1 } theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; try clear x; -- should fail clear h2; traceState; apply Eq.trans; exact h3; exact h1 } macro "blabla" : tactic => `(assumption) -- Tactic head symbols do not become reserved words def blabla := 100 #check blabla theorem simple17 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple18 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 := by subst x; subst y; exact rfl theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) := rfl theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x := rfl set_option pp.all true #check fun {α} (a : α) => a #check @(fun α (a : α) => a) #check let myid := fun {α} (a : α) => a; myid [myid 1] -- In the following example, we need `@` otherwise we will try to insert mvars for α and [Add α], -- and will fail to generate instance for [Add α] #check @(fun α (s : Add α) (a : α) => a + a) def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β := (a₁, a₂, b) def id1 : {α : Type} → α → α := fun x => x def listId : List ({α : Type} → α → α) := (fun x => x) :: [] def id2 : {α : Type} → α → α := @(fun α (x : α) => id1 x) def id3 : {α : Type} → α → α := @(fun α x => id1 x) def id4 : {α : Type} → α → α := fun x => id1 x def id5 : {α : Type} → α → α := fun {α} x => id1 x def id6 : {α : Type} → α → α := @(fun {α} x => id1 x) def id7 : {α : Type} → α → α := fun {α} x => @id α x def id8 : {α : Type} → α → α := fun {α} x => id (@id α x) def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨StateT.failure, StateT.orElse⟩ def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@(fun α => StateT.failure), @(fun α => StateT.orElse)⟩ def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨fun {α} => StateT.failure, fun {α} => StateT.orElse⟩ #check_failure 1 + true /- universes u v /- MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n' -/ set_option pp.raw.maxDepth 100 set_option trace.Elab true def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' := ⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩ -/ syntax "fn" (term:max)+ "=>" term : term macro_rules | `(fn $xs* => $b) => `(fun $xs* => $b) set_option pp.all false #check fn x => x+1 #check fn α (a : α) => a def tst1 : {α : Type} → α → α := @(fn α a => a) #check @tst1 syntax ident "==>" term : term syntax "{" ident "}" "==>" term : term macro_rules | `($x:ident ==> $b) => `(fn $x => $b) | `({$x:ident} ==> $b) => `(fun {$x:ident} => $b) #check x ==> x+1 def tst2a : {α : Type} → α → α := @(α ==> a ==> a) def tst2b : {α : Type} → α → α := {α} ==> a ==> a #check @tst2a #check @tst2b def tst3a : {α : Type} → {β : Type} → α → β → α × β := @(α ==> @(β ==> a ==> b ==> (a, b))) def tst3b : {α : Type} → {β : Type} → α → β → α × β := {α} ==> {β} ==> a ==> b ==> (a, b) syntax "function" (term:max)+ "=>" term : term macro_rules | `(function $xs* => $b) => `(@(fun $xs* => $b)) def tst4 : {α : Type} → {β : Type} → α → β → α × β := function α β a b => (a, b) theorem simple20 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3; try clear x; -- should fail clear h2; traceState; apply Eq.trans; exact h3; exact h1 theorem simple21 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have x = y from by { apply Eq.symm; assumption }; Eq.trans this (by assumption) theorem simple22 (x y z : Nat) : y = z → y = x → id (x = z + 0) := fun h1 h2 => show x = z + 0 by apply Eq.trans exact h2.symm assumption skip theorem simple23 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have x = y by apply Eq.symm; assumption Eq.trans this (by assumption) theorem simple24 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have h : x = y by apply Eq.symm; assumption Eq.trans h (by assumption) def f1 (x : Nat) : Nat := let double x := x + x let rec loop x := match x with | 0 => 0 | x+1 => loop x + double x loop x #eval f1 5 def f2 (x : Nat) : String := let bad x : String := toString x bad x def f3 x y := x + y + 1 theorem f3eq x y : f3 x y = x + y + 1 := rfl def f4 (x y : Nat) : String := if x > y + 1 then "hello" else "world"
a264904c781e698abc4fdfcd1c14e2b80813fdef
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/interactive1.lean
e0f42688e52cfd87c7b2c53c6320b4dd0308dbd9
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
901
lean
def f : nat → nat := λ a, a @[simp] lemma f_def (a : nat) : f a = a := rfl def g : nat → nat := λ a, 1 + a lemma g_def (a : nat) : g a = 1 + a := rfl example (a b c : nat) : b = 0 → c = 1 → a + b + f c = g (f a) := begin intros h1 h2, simp [h1, h2, g_def, nat.add_comm 1 a] end example (b c : nat) : b = 0 → c = b + 1 → c = 1 := begin intros h1 h2, simp [h1] at h2, assumption end open nat example (b c : nat) : succ b = succ c → b + 2 = c + 2 := begin intro h, injection h with h', clear h, trace_state, subst h' end constant h : nat → nat → nat axiom bla : ∀ a b : nat, h a b = h b a axiom boo : ∀ a : nat, h 0 a = a attribute [simp] boo bla example (a b : nat) : a = b → h 0 a = b := begin intro h, simp [h, -bla] -- should fail if bla is used end open tactic example (a b : nat) : a = b → h 0 a = b := by simp [-bla] {contextual := tt}
a2148b17b882b23e47675a672b0b9e68affbae26
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/measure_theory/measure/haar_quotient.lean
67370553b3eda073c727eb18e098dbc0e63d36ac
[ "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
8,608
lean
/- Copyright (c) 2022 Alex Kontorovich and Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Kontorovich, Heather Macbeth -/ import measure_theory.measure.haar import measure_theory.group.fundamental_domain import algebra.group.opposite /-! # Haar quotient measure In this file, we consider properties of fundamental domains and measures for the action of a subgroup of a group `G` on `G` itself. ## Main results * `measure_theory.is_fundamental_domain.smul_invariant_measure_map `: given a subgroup `Γ` of a topological group `G`, the pushforward to the coset space `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a `G`-invariant measure on `G ⧸ Γ`. * `measure_theory.is_fundamental_domain.is_mul_left_invariant_map `: given a normal subgroup `Γ` of a topological group `G`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a left-invariant measure on `G ⧸ Γ`. Note that a group `G` with Haar measure that is both left and right invariant is called **unimodular**. -/ open set measure_theory topological_space measure_theory.measure open_locale pointwise nnreal variables {G : Type*} [group G] [measurable_space G] [topological_space G] [topological_group G] [borel_space G] {μ : measure G} {Γ : subgroup G} /-- Measurability of the action of the topological group `G` on the left-coset space `G/Γ`. -/ @[to_additive "Measurability of the action of the additive topological group `G` on the left-coset space `G/Γ`."] instance quotient_group.has_measurable_smul [measurable_space (G ⧸ Γ)] [borel_space (G ⧸ Γ)] : has_measurable_smul G (G ⧸ Γ) := { measurable_const_smul := λ g, (continuous_const_smul g).measurable, measurable_smul_const := λ x, (quotient_group.continuous_smul₁ x).measurable } variables {𝓕 : set G} (h𝓕 : is_fundamental_domain Γ.opposite 𝓕 μ) include h𝓕 variables [countable Γ] [measurable_space (G ⧸ Γ)] [borel_space (G ⧸ Γ)] /-- The pushforward to the coset space `G ⧸ Γ` of the restriction of a both left- and right- invariant measure on `G` to a fundamental domain `𝓕` is a `G`-invariant measure on `G ⧸ Γ`. -/ @[to_additive "The pushforward to the coset space `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on an additive topological group `G` to a fundamental domain `𝓕` is a `G`-invariant measure on `G ⧸ Γ`."] lemma measure_theory.is_fundamental_domain.smul_invariant_measure_map [μ.is_mul_left_invariant] [μ.is_mul_right_invariant] : smul_invariant_measure G (G ⧸ Γ) (measure.map quotient_group.mk (μ.restrict 𝓕)) := { measure_preimage_smul := begin let π : G → G ⧸ Γ := quotient_group.mk, have meas_π : measurable π := continuous_quotient_mk.measurable, have 𝓕meas : null_measurable_set 𝓕 μ := h𝓕.null_measurable_set, intros g A hA, have meas_πA : measurable_set (π ⁻¹' A) := measurable_set_preimage meas_π hA, rw [measure.map_apply meas_π hA, measure.map_apply meas_π (measurable_set_preimage (measurable_const_smul g) hA), measure.restrict_apply₀' 𝓕meas, measure.restrict_apply₀' 𝓕meas], set π_preA := π ⁻¹' A, have : (quotient_group.mk ⁻¹' ((λ (x : G ⧸ Γ), g • x) ⁻¹' A)) = has_mul.mul g ⁻¹' π_preA, { ext1, simp }, rw this, have : μ (has_mul.mul g ⁻¹' π_preA ∩ 𝓕) = μ (π_preA ∩ has_mul.mul (g⁻¹) ⁻¹' 𝓕), { transitivity μ (has_mul.mul g ⁻¹' (π_preA ∩ has_mul.mul g⁻¹ ⁻¹' 𝓕)), { rw preimage_inter, congr, rw [← preimage_comp, comp_mul_left, mul_left_inv], ext, simp, }, rw measure_preimage_mul, }, rw this, have h𝓕_translate_fundom : is_fundamental_domain Γ.opposite (g • 𝓕) μ := h𝓕.smul_of_comm g, rw [h𝓕.measure_set_eq h𝓕_translate_fundom meas_πA, ← preimage_smul_inv], refl, rintros ⟨γ, γ_in_Γ⟩, ext, have : π (x * (mul_opposite.unop γ)) = π (x) := by simpa [quotient_group.eq'] using γ_in_Γ, simp [(•), this], end } /-- Assuming `Γ` is a normal subgroup of a topological group `G`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a left-invariant measure on `G ⧸ Γ`. -/ @[to_additive "Assuming `Γ` is a normal subgroup of an additive topological group `G`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of a both left- and right-invariant measure on `G` to a fundamental domain `𝓕` is a left-invariant measure on `G ⧸ Γ`."] lemma measure_theory.is_fundamental_domain.is_mul_left_invariant_map [subgroup.normal Γ] [μ.is_mul_left_invariant] [μ.is_mul_right_invariant] : (measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)).is_mul_left_invariant := { map_mul_left_eq_self := begin intros x, apply measure.ext, intros A hA, obtain ⟨x₁, _⟩ := @quotient.exists_rep _ (quotient_group.left_rel Γ) x, haveI := h𝓕.smul_invariant_measure_map, convert measure_preimage_smul x₁ ((measure.map quotient_group.mk) (μ.restrict 𝓕)) A using 1, rw [← h, measure.map_apply], { refl, }, { exact measurable_const_mul _, }, { exact hA, }, end } variables [t2_space (G ⧸ Γ)] [second_countable_topology (G ⧸ Γ)] (K : positive_compacts (G ⧸ Γ)) /-- Given a normal subgroup `Γ` of a topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of `μ` to `𝓕` is a multiple of Haar measure on `G ⧸ Γ`. -/ @[to_additive "Given a normal subgroup `Γ` of an additive topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the pushforward to the quotient group `G ⧸ Γ` of the restriction of `μ` to `𝓕` is a multiple of Haar measure on `G ⧸ Γ`."] lemma measure_theory.is_fundamental_domain.map_restrict_quotient [subgroup.normal Γ] [measure_theory.measure.is_haar_measure μ] [μ.is_mul_right_invariant] (h𝓕_finite : μ 𝓕 < ⊤) : measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕) = (μ (𝓕 ∩ (quotient_group.mk' Γ) ⁻¹' K)) • (measure_theory.measure.haar_measure K) := begin let π : G →* G ⧸ Γ := quotient_group.mk' Γ, have meas_π : measurable π := continuous_quotient_mk.measurable, have 𝓕meas : null_measurable_set 𝓕 μ := h𝓕.null_measurable_set, haveI : is_finite_measure (μ.restrict 𝓕) := ⟨by { rw [measure.restrict_apply₀' 𝓕meas, univ_inter], exact h𝓕_finite }⟩, -- the measure is left-invariant, so by the uniqueness of Haar measure it's enough to show that -- it has the stated size on the reference compact set `K`. haveI : (measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)).is_mul_left_invariant := h𝓕.is_mul_left_invariant_map, rw [measure.haar_measure_unique (measure.map (quotient_group.mk' Γ) (μ.restrict 𝓕)) K, measure.map_apply meas_π, measure.restrict_apply₀' 𝓕meas, inter_comm], exact K.is_compact.measurable_set, end /-- Given a normal subgroup `Γ` of a topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the quotient map to `G ⧸ Γ` is measure-preserving between appropriate multiples of Haar measure on `G` and `G ⧸ Γ`. -/ @[to_additive measure_preserving_quotient_add_group.mk' "Given a normal subgroup `Γ` of an additive topological group `G` with Haar measure `μ`, which is also right-invariant, and a finite volume fundamental domain `𝓕`, the quotient map to `G ⧸ Γ` is measure-preserving between appropriate multiples of Haar measure on `G` and `G ⧸ Γ`."] lemma measure_preserving_quotient_group.mk' [subgroup.normal Γ] [measure_theory.measure.is_haar_measure μ] [μ.is_mul_right_invariant] (h𝓕_finite : μ 𝓕 < ⊤) (c : ℝ≥0) (h : μ (𝓕 ∩ (quotient_group.mk' Γ) ⁻¹' K) = c) : measure_preserving (quotient_group.mk' Γ) (μ.restrict 𝓕) (c • (measure_theory.measure.haar_measure K)) := { measurable := continuous_quotient_mk.measurable, map_eq := by rw [h𝓕.map_restrict_quotient K h𝓕_finite, h]; refl }
a266d51c5870ac855b62b9722bc154ccbc3a886c
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/algebra/star/module.lean
4edc0e2545e0e2be34bb6a46fa081357e4340e98
[ "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
5,528
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Frédéric Dupuis -/ import algebra.star.self_adjoint import algebra.module.equiv import linear_algebra.prod /-! # The star operation, bundled as a star-linear equiv We define `star_linear_equiv`, which is the star operation bundled as a star-linear map. It is defined on a star algebra `A` over the base ring `R`. This file also provides some lemmas that need `algebra.module.basic` imported to prove. ## TODO - Define `star_linear_equiv` for noncommutative `R`. We only the commutative case for now since, in the noncommutative case, the ring hom needs to reverse the order of multiplication. This requires a ring hom of type `R →+* Rᵐᵒᵖ`, which is very undesirable in the commutative case. One way out would be to define a new typeclass `is_op R S` and have an instance `is_op R R` for commutative `R`. - Also note that such a definition involving `Rᵐᵒᵖ` or `is_op R S` would require adding the appropriate `ring_hom_inv_pair` instances to be able to define the semilinear equivalence. -/ section smul_lemmas variables {R M : Type*} @[simp] lemma star_int_cast_smul [ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℤ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_int_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_nat_cast_smul [semiring R] [add_comm_monoid M] [module R M] [star_add_monoid M] (n : ℕ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_nat_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_inv_int_cast_smul [division_ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℤ) (x : M) : star ((n⁻¹ : R) • x) = (n⁻¹ : R) • star x := map_inv_int_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_inv_nat_cast_smul [division_ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℕ) (x : M) : star ((n⁻¹ : R) • x) = (n⁻¹ : R) • star x := map_inv_nat_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_rat_cast_smul [division_ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℚ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_rat_cast_smul (star_add_equiv : M ≃+ M) _ _ _ x @[simp] lemma star_rat_smul {R : Type*} [add_comm_group R] [star_add_monoid R] [module ℚ R] (x : R) (n : ℚ) : star (n • x) = n • star x := map_rat_smul (star_add_equiv : R ≃+ R) _ _ end smul_lemmas /-- If `A` is a module over a commutative `R` with compatible actions, then `star` is a semilinear equivalence. -/ @[simps] def star_linear_equiv (R : Type*) {A : Type*} [comm_ring R] [star_ring R] [semiring A] [star_ring A] [module R A] [star_module R A] : A ≃ₗ⋆[R] A := { to_fun := star, map_smul' := star_smul, .. star_add_equiv } variables (R : Type*) (A : Type*) [semiring R] [star_semigroup R] [has_trivial_star R] [add_comm_group A] [module R A] [star_add_monoid A] [star_module R A] /-- The self-adjoint elements of a star module, as a submodule. -/ def self_adjoint.submodule : submodule R A := { smul_mem' := is_self_adjoint.smul, ..self_adjoint A } /-- The skew-adjoint elements of a star module, as a submodule. -/ def skew_adjoint.submodule : submodule R A := { smul_mem' := skew_adjoint.smul_mem, ..skew_adjoint A } variables {A} [invertible (2 : R)] /-- The self-adjoint part of an element of a star module, as a linear map. -/ @[simps] def self_adjoint_part : A →ₗ[R] self_adjoint A := { to_fun := λ x, ⟨(⅟2 : R) • (x + star x), by simp only [self_adjoint.mem_iff, star_smul, add_comm, star_add_monoid.star_add, star_inv', star_bit0, star_one, star_star, star_inv_of (2 : R), star_trivial]⟩, map_add' := λ x y, by { ext, simp [add_add_add_comm] }, map_smul' := λ r x, by { ext, simp [←mul_smul, show ⅟ 2 * r = r * ⅟ 2, from commute.inv_of_left (commute.one_left r).bit0_left] } } /-- The skew-adjoint part of an element of a star module, as a linear map. -/ @[simps] def skew_adjoint_part : A →ₗ[R] skew_adjoint A := { to_fun := λ x, ⟨(⅟2 : R) • (x - star x), by simp only [skew_adjoint.mem_iff, star_smul, star_sub, star_star, star_trivial, ←smul_neg, neg_sub]⟩, map_add' := λ x y, by { ext, simp only [sub_add, ←smul_add, sub_sub_eq_add_sub, star_add, add_subgroup.coe_mk, add_subgroup.coe_add] }, map_smul' := λ r x, by { ext, simp [←mul_smul, ←smul_sub, show r * ⅟ 2 = ⅟ 2 * r, from commute.inv_of_right (commute.one_right r).bit0_right] } } lemma star_module.self_adjoint_part_add_skew_adjoint_part (x : A) : (self_adjoint_part R x : A) + skew_adjoint_part R x = x := by simp only [smul_sub, self_adjoint_part_apply_coe, smul_add, skew_adjoint_part_apply_coe, add_add_sub_cancel, inv_of_two_smul_add_inv_of_two_smul] variables (A) /-- The decomposition of elements of a star module into their self- and skew-adjoint parts, as a linear equivalence. -/ @[simps] def star_module.decompose_prod_adjoint : A ≃ₗ[R] self_adjoint A × skew_adjoint A := linear_equiv.of_linear ((self_adjoint_part R).prod (skew_adjoint_part R)) ((self_adjoint.submodule R A).subtype.coprod (skew_adjoint.submodule R A).subtype) (by ext; simp) (linear_map.ext $ star_module.self_adjoint_part_add_skew_adjoint_part R)
b7b72fe7039ed642b8fb8161689b7399c70b9d99
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/data/complex/basic.lean
0233c63d7a7e57a09b08cfa444362cc081978f24
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
18,298
lean
/- Copyright (c) 2017 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Mario Carneiro The complex numbers, modelled as R^2 in the obvious way. -/ import data.real.basic tactic.ring algebra.field_power structure complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex @[simp] theorem eta : ∀ z : ℂ, complex.mk z.re z.im = z | ⟨a, b⟩ := rfl theorem ext : ∀ {z w : ℂ}, z.re = w.re → z.im = w.im → z = w | ⟨zr, zi⟩ ⟨_, _⟩ rfl rfl := rfl theorem ext_iff {z w : ℂ} : z = w ↔ z.re = w.re ∧ z.im = w.im := ⟨λ H, by simp [H], and.rec ext⟩ def of_real (r : ℝ) : ℂ := ⟨r, 0⟩ instance : has_coe ℝ ℂ := ⟨of_real⟩ @[simp] lemma of_real_eq_coe (r : ℝ) : of_real r = r := rfl @[simp] lemma of_real_re (r : ℝ) : (r : ℂ).re = r := rfl @[simp] lemma of_real_im (r : ℝ) : (r : ℂ).im = 0 := rfl @[simp] theorem of_real_inj {z w : ℝ} : (z : ℂ) = w ↔ z = w := ⟨congr_arg re, congr_arg _⟩ instance : has_zero ℂ := ⟨(0 : ℝ)⟩ instance : inhabited ℂ := ⟨0⟩ @[simp] lemma zero_re : (0 : ℂ).re = 0 := rfl @[simp] lemma zero_im : (0 : ℂ).im = 0 := rfl @[simp] lemma of_real_zero : ((0 : ℝ) : ℂ) = 0 := rfl @[simp] theorem of_real_eq_zero {z : ℝ} : (z : ℂ) = 0 ↔ z = 0 := of_real_inj @[simp] theorem of_real_ne_zero {z : ℝ} : (z : ℂ) ≠ 0 ↔ z ≠ 0 := not_congr of_real_eq_zero instance : has_one ℂ := ⟨(1 : ℝ)⟩ @[simp] lemma one_re : (1 : ℂ).re = 1 := rfl @[simp] lemma one_im : (1 : ℂ).im = 0 := rfl @[simp] lemma of_real_one : ((1 : ℝ) : ℂ) = 1 := rfl def I : ℂ := ⟨0, 1⟩ @[simp] lemma I_re : I.re = 0 := rfl @[simp] lemma I_im : I.im = 1 := rfl instance : has_add ℂ := ⟨λ z w, ⟨z.re + w.re, z.im + w.im⟩⟩ @[simp] lemma add_re (z w : ℂ) : (z + w).re = z.re + w.re := rfl @[simp] lemma add_im (z w : ℂ) : (z + w).im = z.im + w.im := rfl @[simp] lemma of_real_add (r s : ℝ) : ((r + s : ℝ) : ℂ) = r + s := ext_iff.2 $ by simp @[simp] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : ℂ) = bit0 r := ext_iff.2 $ by simp [bit0] @[simp] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : ℂ) = bit1 r := ext_iff.2 $ by simp [bit1] instance : has_neg ℂ := ⟨λ z, ⟨-z.re, -z.im⟩⟩ @[simp] lemma neg_re (z : ℂ) : (-z).re = -z.re := rfl @[simp] lemma neg_im (z : ℂ) : (-z).im = -z.im := rfl @[simp] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : ℂ) = -r := ext_iff.2 $ by simp instance : has_mul ℂ := ⟨λ z w, ⟨z.re * w.re - z.im * w.im, z.re * w.im + z.im * w.re⟩⟩ @[simp] lemma mul_re (z w : ℂ) : (z * w).re = z.re * w.re - z.im * w.im := rfl @[simp] lemma mul_im (z w : ℂ) : (z * w).im = z.re * w.im + z.im * w.re := rfl @[simp] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : ℂ) = r * s := ext_iff.2 $ by simp @[simp] lemma I_mul_I : I * I = -1 := ext_iff.2 $ by simp lemma I_ne_zero : (I : ℂ) ≠ 0 := mt (congr_arg im) zero_ne_one.symm lemma mk_eq_add_mul_I (a b : ℝ) : complex.mk a b = a + b * I := ext_iff.2 $ by simp @[simp] lemma re_add_im (z : ℂ) : (z.re : ℂ) + z.im * I = z := ext_iff.2 $ by simp def real_prod_equiv : ℂ ≃ (ℝ × ℝ) := { to_fun := λ z, ⟨z.re, z.im⟩, inv_fun := λ p, ⟨p.1, p.2⟩, left_inv := λ ⟨x, y⟩, rfl, right_inv := λ ⟨x, y⟩, rfl } @[simp] theorem real_prod_equiv_apply (z : ℂ) : real_prod_equiv z = (z.re, z.im) := rfl theorem real_prod_equiv_symm_re (x y : ℝ) : (real_prod_equiv.symm (x, y)).re = x := rfl theorem real_prod_equiv_symm_im (x y : ℝ) : (real_prod_equiv.symm (x, y)).im = y := rfl def conj (z : ℂ) : ℂ := ⟨z.re, -z.im⟩ @[simp] lemma conj_re (z : ℂ) : (conj z).re = z.re := rfl @[simp] lemma conj_im (z : ℂ) : (conj z).im = -z.im := rfl @[simp] lemma conj_of_real (r : ℝ) : conj r = r := ext_iff.2 $ by simp [conj] @[simp] lemma conj_zero : conj 0 = 0 := ext_iff.2 $ by simp [conj] @[simp] lemma conj_one : conj 1 = 1 := ext_iff.2 $ by simp @[simp] lemma conj_I : conj I = -I := ext_iff.2 $ by simp @[simp] lemma conj_neg_I : conj (-I) = I := ext_iff.2 $ by simp @[simp] lemma conj_add (z w : ℂ) : conj (z + w) = conj z + conj w := ext_iff.2 $ by simp @[simp] lemma conj_neg (z : ℂ) : conj (-z) = -conj z := rfl @[simp] lemma conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w := ext_iff.2 $ by simp @[simp] lemma conj_conj (z : ℂ) : conj (conj z) = z := ext_iff.2 $ by simp lemma conj_bijective : function.bijective conj := ⟨function.injective_of_has_left_inverse ⟨conj, conj_conj⟩, function.surjective_of_has_right_inverse ⟨conj, conj_conj⟩⟩ lemma conj_inj {z w : ℂ} : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff @[simp] lemma conj_eq_zero {z : ℂ} : conj z = 0 ↔ z = 0 := by simpa using @conj_inj z 0 @[simp] lemma eq_conj_iff_real (z : ℂ) : conj z = z ↔ ∃ r : ℝ, z = r := ⟨λ h, ⟨z.re, ext rfl $ eq_zero_of_neg_eq (congr_arg im h)⟩, λ ⟨h, e⟩, e.symm ▸ rfl⟩ def norm_sq (z : ℂ) : ℝ := z.re * z.re + z.im * z.im @[simp] lemma norm_sq_of_real (r : ℝ) : norm_sq r = r * r := by simp [norm_sq] @[simp] lemma norm_sq_zero : norm_sq 0 = 0 := by simp [norm_sq] @[simp] lemma norm_sq_one : norm_sq 1 = 1 := by simp [norm_sq] @[simp] lemma norm_sq_I : norm_sq I = 1 := by simp [norm_sq] lemma norm_sq_nonneg (z : ℂ) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : ℂ} : norm_sq z = 0 ↔ z = 0 := ⟨λ h, ext (eq_zero_of_mul_self_add_mul_self_eq_zero h) (eq_zero_of_mul_self_add_mul_self_eq_zero $ (add_comm _ _).trans h), λ h, h.symm ▸ norm_sq_zero⟩ @[simp] lemma norm_sq_pos {z : ℂ} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : ℂ) : norm_sq (-z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_conj (z : ℂ) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : ℂ) : norm_sq (z * w) = norm_sq z * norm_sq w := by dsimp [norm_sq]; ring lemma norm_sq_add (z w : ℂ) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (z * conj w).re := by dsimp [norm_sq]; ring lemma re_sq_le_norm_sq (z : ℂ) : z.re * z.re ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : ℂ) : z.im * z.im ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : ℂ) : z * conj z = norm_sq z := ext_iff.2 $ by simp [norm_sq, mul_comm] theorem add_conj (z : ℂ) : z + conj z = (2 * z.re : ℝ) := ext_iff.2 $ by simp [two_mul] instance : comm_ring ℂ := by refine { zero := 0, add := (+), neg := has_neg.neg, one := 1, mul := (*), ..}; { intros, apply ext_iff.2; split; simp; ring } @[simp] lemma bit0_re (z : ℂ) : (bit0 z).re = bit0 z.re := rfl @[simp] lemma bit1_re (z : ℂ) : (bit1 z).re = bit1 z.re := rfl @[simp] lemma bit0_im (z : ℂ) : (bit0 z).im = bit0 z.im := eq.refl _ @[simp] lemma bit1_im (z : ℂ) : (bit1 z).im = bit0 z.im := add_zero _ @[simp] lemma sub_re (z w : ℂ) : (z - w).re = z.re - w.re := rfl @[simp] lemma sub_im (z w : ℂ) : (z - w).im = z.im - w.im := rfl @[simp] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : ℂ) = r - s := ext_iff.2 $ by simp @[simp] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : ℂ) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : ℂ) : z - conj z = (2 * z.im : ℝ) * I := ext_iff.2 $ by simp [two_mul] lemma conj_pow (z : ℂ) (n : ℕ) : conj (z ^ n) = conj z ^ n := by induction n; simp [*, conj_mul, pow_succ] @[simp] lemma conj_two : conj (2 : ℂ) = 2 := by apply complex.ext; simp lemma norm_sq_sub (z w : ℂ) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * (z * conj w).re := by rw [sub_eq_add_neg, norm_sq_add]; simp [-mul_re] noncomputable instance : has_inv ℂ := ⟨λ z, conj z * ((norm_sq z)⁻¹:ℝ)⟩ theorem inv_def (z : ℂ) : z⁻¹ = conj z * ((norm_sq z)⁻¹:ℝ) := rfl @[simp] lemma inv_re (z : ℂ) : (z⁻¹).re = z.re / norm_sq z := by simp [inv_def, division_def] @[simp] lemma inv_im (z : ℂ) : (z⁻¹).im = -z.im / norm_sq z := by simp [inv_def, division_def] @[simp] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : ℂ) = r⁻¹ := ext_iff.2 $ begin simp, by_cases r = 0, {simp [h]}, rw [← div_div_eq_div_mul, div_self h, one_div_eq_inv] end protected lemma inv_zero : (0⁻¹ : ℂ) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : ℂ} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ← mul_assoc, mul_conj, ← of_real_mul, mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] noncomputable instance : discrete_field ℂ := { inv := has_inv.inv, zero_ne_one := mt (congr_arg re) zero_ne_one, mul_inv_cancel := @complex.mul_inv_cancel, inv_mul_cancel := λ z h, by rw [mul_comm, complex.mul_inv_cancel h], inv_zero := complex.inv_zero, has_decidable_eq := classical.dec_eq _, ..complex.comm_ring } instance re.is_add_group_hom : is_add_group_hom complex.re := by refine_struct {..}; simp instance im.is_add_group_hom : is_add_group_hom complex.im := by refine_struct {..}; simp instance : is_ring_hom conj := by refine_struct {..}; simp instance of_real.is_ring_hom : is_ring_hom (coe : ℝ → ℂ) := by refine_struct {..}; simp @[simp] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : ℂ) = r / s := is_field_hom.map_div coe @[simp] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : ℂ) = (r : ℂ) ^ n := is_field_hom.map_fpow of_real r n @[simp] theorem of_real_int_cast : ∀ n : ℤ, ((n : ℝ) : ℂ) = n := int.eq_cast (λ n, ((n : ℝ) : ℂ)) (by rw [int.cast_one, of_real_one]) (λ _ _, by rw [int.cast_add, of_real_add]) @[simp] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : ℂ) = n := by rw [← int.cast_coe_nat, of_real_int_cast]; refl @[simp] lemma conj_inv (z : ℂ) : conj z⁻¹ = (conj z)⁻¹ := if h : z = 0 then by simp [h] else (domain.mul_left_inj (mt conj_eq_zero.1 h)).1 $ by rw [← conj_mul]; simp [h, -conj_mul] @[simp] lemma conj_sub (z w : ℂ) : conj (z - w) = conj z - conj w := by simp @[simp] lemma conj_div (z w : ℂ) : conj (z / w) = conj z / conj w := by rw [division_def, conj_mul, conj_inv]; refl @[simp] lemma norm_sq_inv (z : ℂ) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := if h : z = 0 then by simp [h] else (domain.mul_left_inj (mt norm_sq_eq_zero.1 h)).1 $ by rw [← norm_sq_mul]; simp [h, -norm_sq_mul] @[simp] lemma norm_sq_div (z w : ℂ) : norm_sq (z / w) = norm_sq z / norm_sq w := by rw [division_def, norm_sq_mul, norm_sq_inv]; refl instance char_zero_complex : char_zero ℂ := add_group.char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h @[simp] theorem of_real_rat_cast : ∀ n : ℚ, ((n : ℝ) : ℂ) = n := by apply rat.eq_cast (λ n, ((n : ℝ) : ℂ)); simp theorem re_eq_add_conj (z : ℂ) : (z.re : ℂ) = (z + conj z) / 2 := by rw [add_conj]; simp; rw [mul_div_cancel_left (z.re:ℂ) two_ne_zero'] @[simp] lemma nat_cast_re (n : ℕ) : (n : ℂ).re = n := by rw [← of_real_nat_cast, of_real_re] @[simp] lemma nat_cast_im (n : ℕ) : (n : ℂ).im = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp] lemma int_cast_re (n : ℤ) : (n : ℂ).re = n := by rw [← of_real_int_cast, of_real_re] @[simp] lemma int_cast_im (n : ℤ) : (n : ℂ).im = 0 := by rw [← of_real_int_cast, of_real_im] @[simp] lemma rat_cast_re (q : ℚ) : (q : ℂ).re = q := by rw [← of_real_rat_cast, of_real_re] @[simp] lemma rat_cast_im (q : ℚ) : (q : ℂ).im = 0 := by rw [← of_real_rat_cast, of_real_im] noncomputable def abs (z : ℂ) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs @[simp] lemma abs_of_real (r : ℝ) : abs r = abs' r := by simp [abs, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : abs r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma mul_self_abs (z : ℂ) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : abs 0 = 0 := by simp [abs] @[simp] lemma abs_one : abs 1 = 1 := by simp [abs] @[simp] lemma abs_I : abs I = 1 := by simp [abs] @[simp] lemma abs_two : abs 2 = 2 := calc abs 2 = abs (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : ℂ) : 0 ≤ abs z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : ℂ} : abs z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero @[simp] lemma abs_conj (z : ℂ) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : ℂ) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : ℂ) : abs' z.re ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.re) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : ℂ) : abs' z.im ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg z.im) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : ℂ) : z.re ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : ℂ) : z.im ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma abs_add (z w : ℂ) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@two_pos ℝ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : 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 @[simp] lemma abs_abs (z : ℂ) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : ℂ} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_le_abs_re_add_abs_im (z : ℂ) : abs z ≤ abs' z.re + abs' z.im := by simpa [re_add_im] using abs_add z.re (z.im * I) lemma abs_re_div_abs_le_one (z : ℂ) : abs' (z.re / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_re_le_abs _) lemma abs_im_div_abs_le_one (z : ℂ) : abs' (z.im / z.abs) ≤ 1 := if hz : z = 0 then by simp [hz, zero_le_one] else by rw [_root_.abs_div, abs_abs]; exact div_le_of_le_mul (abs_pos.2 hz) (by rw mul_one; exact abs_im_le_abs _) @[simp] lemma abs_cast_nat (n : ℕ) : abs (n : ℂ) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : ℂ) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] theorem is_cau_seq_re (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).re) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq ℂ abs) : is_cau_seq abs' (λ n, (f n).im) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) noncomputable def cau_seq_re (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ noncomputable def cau_seq_im (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → ℂ} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ noncomputable def lim_aux (f : cau_seq ℂ abs) : ℂ := ⟨cau_seq.lim (cau_seq_re f), cau_seq.lim (cau_seq_im f)⟩ theorem equiv_lim_aux (f : cau_seq ℂ abs) : f ≈ cau_seq.const abs (lim_aux f) := λ ε ε0, (exists_forall_ge_and (cau_seq.equiv_lim ⟨_, is_cau_seq_re f⟩ _ (half_pos ε0)) (cau_seq.equiv_lim ⟨_, is_cau_seq_im f⟩ _ (half_pos ε0))).imp $ λ i H j ij, begin cases H _ ij with H₁ H₂, apply lt_of_le_of_lt (abs_le_abs_re_add_abs_im _), dsimp [lim_aux] at *, have := add_lt_add H₁ H₂, rwa add_halves at this, end noncomputable instance : cau_seq.is_complete ℂ abs := ⟨λ f, ⟨lim_aux f, equiv_lim_aux f⟩⟩ open cau_seq lemma lim_eq_lim_im_add_lim_re (f : cau_seq ℂ abs) : lim f = ↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I := lim_eq_of_equiv_const $ calc f ≈ _ : equiv_lim_aux f ... = cau_seq.const abs (↑(lim (cau_seq_re f)) + ↑(lim (cau_seq_im f)) * I) : cau_seq.ext (λ _, complex.ext (by simp [lim_aux, cau_seq_re]) (by simp [lim_aux, cau_seq_im])) lemma lim_re (f : cau_seq ℂ abs) : lim (cau_seq_re f) = (lim f).re := by rw [lim_eq_lim_im_add_lim_re]; simp lemma lim_im (f : cau_seq ℂ abs) : lim (cau_seq_im f) = (lim f).im := by rw [lim_eq_lim_im_add_lim_re]; simp lemma is_cau_seq_conj (f : cau_seq ℂ abs) : is_cau_seq abs (λ n, conj (f n)) := λ ε ε0, let ⟨i, hi⟩ := f.2 ε ε0 in ⟨i, λ j hj, by rw [← conj_sub, abs_conj]; exact hi j hj⟩ noncomputable def cau_seq_conj (f : cau_seq ℂ abs) : cau_seq ℂ abs := ⟨_, is_cau_seq_conj f⟩ lemma lim_conj (f : cau_seq ℂ abs) : lim (cau_seq_conj f) = conj (lim f) := complex.ext (by simp [cau_seq_conj, (lim_re _).symm, cau_seq_re]) (by simp [cau_seq_conj, (lim_im _).symm, cau_seq_im, (lim_neg _).symm]; refl) noncomputable def cau_seq_abs (f : cau_seq ℂ abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_abs f.2⟩ lemma lim_abs (f : cau_seq ℂ abs) : lim (cau_seq_abs f) = abs (lim f) := lim_eq_of_equiv_const (λ ε ε0, let ⟨i, hi⟩ := equiv_lim f ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩) end complex
fe551a6ed412d0d17641d403353747215385ff9a
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/src/Lean/Util/Path.lean
7be0af525704504c4de2c60049427556d97d1e0c
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
3,956
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich Management of the Lean search path (`LEAN_PATH`), which is a list of paths containing package roots: an import `A.B.C` resolves to `path/A/B/C.olean` for the first entry `path` in `LEAN_PATH` with a directory `A/`. `import A` resolves to `path/A.olean`. -/ import Lean.Data.Name namespace Lean open System def realPathNormalized (p : FilePath) : IO FilePath := do (← IO.realPath p).normalize def modToFilePath (base : FilePath) (mod : Name) (ext : String) : FilePath := go mod |>.withExtension ext where go : Name → FilePath | Name.str p h _ => go p / h | Name.anonymous => base | Name.num p _ _ => panic! "ill-formed import" /-- A `.olean' search path. -/ abbrev SearchPath := System.SearchPath namespace SearchPath /-- If the package of `mod` can be found in `sp`, return the path with extension `ext` (`lean` or `olean`) corresponding to `mod`. Otherwise, return `none.` -/ def findWithExt (sp : SearchPath) (ext : String) (mod : Name) : IO (Option FilePath) := do let pkg := mod.getRoot.toString let root? ← sp.findM? fun p => (p / pkg).isDir <||> ((p / pkg).withExtension ext).pathExists return root?.map (modToFilePath · mod ext) end SearchPath builtin_initialize searchPathRef : IO.Ref SearchPath ← IO.mkRef {} @[extern c inline "LEAN_IS_STAGE0"] private constant isStage0 (u : Unit) : Bool def getBuiltinSearchPath : IO SearchPath := do let appDir ← IO.appDir let mut buildDir := appDir / ".." -- use stage1 stdlib with stage0 executable (which should never be distributed outside of the build directory) if isStage0 () then buildDir := buildDir / ".." / "stage1" [buildDir / "lib" / "lean"] def addSearchPathFromEnv (sp : SearchPath) : IO SearchPath := do let val ← IO.getEnv "LEAN_PATH" match val with | none => pure sp | some val => pure <| SearchPath.parse val ++ sp @[export lean_init_search_path] def initSearchPath (path : Option String := none) : IO Unit := match path with | some path => searchPathRef.set <| SearchPath.parse path | none => do let sp ← getBuiltinSearchPath let sp ← addSearchPathFromEnv sp searchPathRef.set sp partial def findOLean (mod : Name) : IO FilePath := do let sp ← searchPathRef.get if let some fname ← sp.findWithExt "olean" mod then return fname else let pkg := FilePath.mk mod.getRoot.toString let mut msg := s!"unknown package '{pkg}'" let rec maybeThisOne dir := do if ← (pkg / dir).isDir then return some s!"\nYou might need to open '{dir}' as a workspace in your editor" if let some dir ← dir.parent then maybeThisOne dir else return none if let some msg' ← maybeThisOne (← IO.currentDir) then msg := msg ++ msg' throw <| IO.userError msg /-- Infer module name of source file name. -/ @[export lean_module_name_of_file] def moduleNameOfFileName (fname : FilePath) (rootDir : Option FilePath) : IO Name := do let fname ← IO.realPath fname let rootDir ← match rootDir with | some rootDir => pure rootDir | none => IO.currentDir let mut rootDir ← realPathNormalized rootDir if !rootDir.toString.endsWith System.FilePath.pathSeparator.toString then rootDir := ⟨rootDir.toString ++ System.FilePath.pathSeparator.toString⟩ if !rootDir.toString.isPrefixOf fname.normalize.toString then throw $ IO.userError s!"input file '{fname}' must be contained in root directory ({rootDir})" -- NOTE: use `fname` instead of `fname.normalize` to preserve casing on all platforms let fnameSuffix := fname.toString.drop rootDir.toString.length let modNameStr := FilePath.mk fnameSuffix |>.withExtension "" let modName := modNameStr.components.foldl Name.mkStr Name.anonymous pure modName end Lean
4b43a2e9eb900025bc0b749bc060e1a40e9e742e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/basic.lean
5c66632b5e4b58eaa110821536e6e19bbdf6eb91
[ "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
58,556
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov, Hunter Monroe -/ import data.rel import data.set.finite import data.sym.sym2 /-! # Simple graphs > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `simple_graph.neighbor_set` is the `set` of vertices adjacent to a given vertex * `simple_graph.common_neighbors` is the intersection of the neighbor sets of two given vertices * `simple_graph.neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite * `simple_graph.incidence_set` is the `set` of edges containing a given vertex * `simple_graph.incidence_finset` is the `finset` of edges containing a given vertex, if `incidence_set` is finite * `simple_graph.dart` is an ordered pair of adjacent vertices, thought of as being an orientated edge. These are also known as "half-edges" or "bonds." * `simple_graph.hom`, `simple_graph.embedding`, and `simple_graph.iso` for graph homomorphisms, graph embeddings, and graph isomorphisms. Note that a graph embedding is a stronger notion than an injective graph homomorphism, since its image is an induced subgraph. * `complete_boolean_algebra` instance: Under the subgraph relation, `simple_graph` forms a `complete_boolean_algebra`. In other words, this is the complete lattice of spanning subgraphs of the complete graph. ## Notations * `→g`, `↪g`, and `≃g` for graph homomorphisms, graph embeddings, and graph isomorphisms, respectively. ## Implementation notes * A locally finite graph is one with instances `Π v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. * Morphisms of graphs are abbreviations for `rel_hom`, `rel_embedding`, and `rel_iso`. To make use of pre-existing simp lemmas, definitions involving morphisms are abbreviations as well. ## Naming Conventions * If the vertex type of a graph is finite, we refer to its cardinality as `card_verts`. ## Todo * This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. -/ open finset function universes u v w /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent vertices; see `simple_graph.edge_set` for the corresponding edge set. -/ @[ext] structure simple_graph (V : Type u) := (adj : V → V → Prop) (symm : symmetric adj . obviously) (loopless : irreflexive adj . obviously) noncomputable instance {V : Type u} [fintype V] : fintype (simple_graph V) := by { classical, exact fintype.of_injective simple_graph.adj simple_graph.ext } /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V := { adj := λ a b, (a ≠ b) ∧ (r a b ∨ r b a), symm := λ a b ⟨hn, hr⟩, ⟨hn.symm, hr.symm⟩, loopless := λ a ⟨hn, _⟩, hn rfl } @[simp] lemma simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v w : V) : (simple_graph.from_rel r).adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) := iff.rfl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. In `mathlib`, this is usually referred to as `⊤`. -/ def complete_graph (V : Type u) : simple_graph V := { adj := ne } /-- The graph with no edges on a given vertex type `V`. `mathlib` prefers the notation `⊥`. -/ def empty_graph (V : Type u) : simple_graph V := { adj := λ i j, false } /-- Two vertices are adjacent in the complete bipartite graph on two vertex types if and only if they are not from the same side. Bipartite graphs in general may be regarded as being subgraphs of one of these. TODO also introduce complete multi-partite graphs, where the vertex type is a sigma type of an indexed family of vertex types -/ @[simps] def complete_bipartite_graph (V W : Type*) : simple_graph (V ⊕ W) := { adj := λ v w, (v.is_left ∧ w.is_right) ∨ (v.is_right ∧ w.is_left), symm := begin intros v w, cases v; cases w; simp, end, loopless := begin intro v, cases v; simp, end } namespace simple_graph variables {ι : Sort*} {𝕜 : Type*} {V : Type u} {W : Type v} {X : Type w} (G : simple_graph V) (G' : simple_graph W) {a b c u v w : V} {e : sym2 V} @[simp] protected lemma irrefl {v : V} : ¬G.adj v v := G.loopless v lemma adj_comm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.symm x, λ x, G.symm x⟩ @[symm] lemma adj_symm (h : G.adj u v) : G.adj v u := G.symm h lemma adj.symm {G : simple_graph V} {u v : V} (h : G.adj u v) : G.adj v u := G.symm h lemma ne_of_adj (h : G.adj a b) : a ≠ b := by { rintro rfl, exact G.irrefl h } protected lemma adj.ne {G : simple_graph V} {a b : V} (h : G.adj a b) : a ≠ b := G.ne_of_adj h protected lemma adj.ne' {G : simple_graph V} {a b : V} (h : G.adj a b) : b ≠ a := h.ne.symm lemma ne_of_adj_of_not_adj {v w x : V} (h : G.adj v x) (hn : ¬ G.adj w x) : v ≠ w := λ h', hn (h' ▸ h) lemma adj_injective : injective (adj : simple_graph V → V → V → Prop) := λ G H h, by { cases G, cases H, congr' } @[simp] lemma adj_inj {G H : simple_graph V} : G.adj = H.adj ↔ G = H := adj_injective.eq_iff section order /-- The relation that one `simple_graph` is a subgraph of another. Note that this should be spelled `≤`. -/ def is_subgraph (x y : simple_graph V) : Prop := ∀ ⦃v w : V⦄, x.adj v w → y.adj v w instance : has_le (simple_graph V) := ⟨is_subgraph⟩ @[simp] lemma is_subgraph_eq_le : (is_subgraph : simple_graph V → simple_graph V → Prop) = (≤) := rfl /-- The supremum of two graphs `x ⊔ y` has edges where either `x` or `y` have edges. -/ instance : has_sup (simple_graph V) := ⟨λ x y, { adj := x.adj ⊔ y.adj, symm := λ v w h, by rwa [pi.sup_apply, pi.sup_apply, x.adj_comm, y.adj_comm] }⟩ @[simp] lemma sup_adj (x y : simple_graph V) (v w : V) : (x ⊔ y).adj v w ↔ x.adj v w ∨ y.adj v w := iff.rfl /-- The infimum of two graphs `x ⊓ y` has edges where both `x` and `y` have edges. -/ instance : has_inf (simple_graph V) := ⟨λ x y, { adj := x.adj ⊓ y.adj, symm := λ v w h, by rwa [pi.inf_apply, pi.inf_apply, x.adj_comm, y.adj_comm] }⟩ @[simp] lemma inf_adj (x y : simple_graph V) (v w : V) : (x ⊓ y).adj v w ↔ x.adj v w ∧ y.adj v w := iff.rfl /-- We define `Gᶜ` to be the `simple_graph V` such that no two adjacent vertices in `G` are adjacent in the complement, and every nonadjacent pair of vertices is adjacent (still ensuring that vertices are not adjacent to themselves). -/ instance : has_compl (simple_graph V) := ⟨λ G, { adj := λ v w, v ≠ w ∧ ¬G.adj v w, symm := λ v w ⟨hne, _⟩, ⟨hne.symm, by rwa adj_comm⟩, loopless := λ v ⟨hne, _⟩, (hne rfl).elim }⟩ @[simp] lemma compl_adj (G : simple_graph V) (v w : V) : Gᶜ.adj v w ↔ v ≠ w ∧ ¬G.adj v w := iff.rfl /-- The difference of two graphs `x \ y` has the edges of `x` with the edges of `y` removed. -/ instance : has_sdiff (simple_graph V) := ⟨λ x y, { adj := x.adj \ y.adj, symm := λ v w h, by change x.adj w v ∧ ¬ y.adj w v; rwa [x.adj_comm, y.adj_comm] }⟩ @[simp] lemma sdiff_adj (x y : simple_graph V) (v w : V) : (x \ y).adj v w ↔ (x.adj v w ∧ ¬ y.adj v w) := iff.rfl instance : has_Sup (simple_graph V) := ⟨λ s, { adj := λ a b, ∃ G ∈ s, adj G a b, symm := λ a b, Exists₂.imp $ λ _ _, adj.symm, loopless := by { rintro a ⟨G, hG, ha⟩, exact ha.ne rfl } }⟩ instance : has_Inf (simple_graph V) := ⟨λ s, { adj := λ a b, (∀ ⦃G⦄, G ∈ s → adj G a b) ∧ a ≠ b, symm := λ _ _, and.imp (forall₂_imp $ λ _ _, adj.symm) ne.symm, loopless := λ a h, h.2 rfl }⟩ @[simp] lemma Sup_adj {s : set (simple_graph V)} {a b : V} : (Sup s).adj a b ↔ ∃ G ∈ s, adj G a b := iff.rfl @[simp] lemma Inf_adj {s : set (simple_graph V)} : (Inf s).adj a b ↔ (∀ G ∈ s, adj G a b) ∧ a ≠ b := iff.rfl @[simp] lemma supr_adj {f : ι → simple_graph V} : (⨆ i, f i).adj a b ↔ ∃ i, (f i).adj a b := by simp [supr] @[simp] lemma infi_adj {f : ι → simple_graph V} : (⨅ i, f i).adj a b ↔ (∀ i, (f i).adj a b) ∧ a ≠ b := by simp [infi] lemma Inf_adj_of_nonempty {s : set (simple_graph V)} (hs : s.nonempty) : (Inf s).adj a b ↔ ∀ G ∈ s, adj G a b := Inf_adj.trans $ and_iff_left_of_imp $ by { obtain ⟨G, hG⟩ := hs, exact λ h, (h _ hG).ne } lemma infi_adj_of_nonempty [nonempty ι] {f : ι → simple_graph V} : (⨅ i, f i).adj a b ↔ ∀ i, (f i).adj a b := by simp [infi, Inf_adj_of_nonempty (set.range_nonempty _)] /-- For graphs `G`, `H`, `G ≤ H` iff `∀ a b, G.adj a b → H.adj a b`. -/ instance : distrib_lattice (simple_graph V) := { le := λ G H, ∀ ⦃a b⦄, G.adj a b → H.adj a b, ..show distrib_lattice (simple_graph V), from adj_injective.distrib_lattice _ (λ _ _, rfl) (λ _ _, rfl) } instance : complete_boolean_algebra (simple_graph V) := { le := (≤), sup := (⊔), inf := (⊓), compl := has_compl.compl, sdiff := (\), top := complete_graph V, bot := empty_graph V, le_top := λ x v w h, x.ne_of_adj h, bot_le := λ x v w h, h.elim, sdiff_eq := λ x y, by { ext v w, refine ⟨λ h, ⟨h.1, ⟨_, h.2⟩⟩, λ h, ⟨h.1, h.2.2⟩⟩, rintro rfl, exact x.irrefl h.1 }, inf_compl_le_bot := λ a v w h, false.elim $ h.2.2 h.1, top_le_sup_compl := λ a v w ne, by { by_cases a.adj v w, exact or.inl h, exact or.inr ⟨ne, h⟩ }, Sup := Sup, le_Sup := λ s G hG a b hab, ⟨G, hG, hab⟩, Sup_le := λ s G hG a b, by { rintro ⟨H, hH, hab⟩, exact hG _ hH hab }, Inf := Inf, Inf_le := λ s G hG a b hab, hab.1 hG, le_Inf := λ s G hG a b hab, ⟨λ H hH, hG _ hH hab, hab.ne⟩, inf_Sup_le_supr_inf := λ G s a b hab, by simpa only [exists_prop, Sup_adj, and_imp, forall_exists_index, Inf_adj, supr_adj, inf_adj, ←exists_and_distrib_right, exists_and_distrib_left, and_assoc, and_self_right] using hab, infi_sup_le_sup_Inf := λ G s a b hab, begin simp only [sup_adj, Inf_adj, infi_adj] at ⊢ hab, have : (∀ G' ∈ s, adj G a b ∨ adj G' a b) ∧ a ≠ b := (and_congr_left $ λ h, forall_congr $ λ H, _).1 hab, simpa [forall_or_distrib_left, or_and_distrib_right, and_iff_left_of_imp adj.ne] using this, exact and_iff_left h, end, ..simple_graph.distrib_lattice } @[simp] lemma top_adj (v w : V) : (⊤ : simple_graph V).adj v w ↔ v ≠ w := iff.rfl @[simp] lemma bot_adj (v w : V) : (⊥ : simple_graph V).adj v w ↔ false := iff.rfl @[simp] lemma complete_graph_eq_top (V : Type u) : complete_graph V = ⊤ := rfl @[simp] lemma empty_graph_eq_bot (V : Type u) : empty_graph V = ⊥ := rfl @[simps] instance (V : Type u) : inhabited (simple_graph V) := ⟨⊥⟩ section decidable variables (V) (H : simple_graph V) [decidable_rel G.adj] [decidable_rel H.adj] instance bot.adj_decidable : decidable_rel (⊥ : simple_graph V).adj := λ v w, decidable.false instance sup.adj_decidable : decidable_rel (G ⊔ H).adj := λ v w, or.decidable instance inf.adj_decidable : decidable_rel (G ⊓ H).adj := λ v w, and.decidable instance sdiff.adj_decidable : decidable_rel (G \ H).adj := λ v w, and.decidable variable [decidable_eq V] instance top.adj_decidable : decidable_rel (⊤ : simple_graph V).adj := λ v w, not.decidable instance compl.adj_decidable : decidable_rel Gᶜ.adj := λ v w, and.decidable end decidable end order /-- `G.support` is the set of vertices that form edges in `G`. -/ def support : set V := rel.dom G.adj lemma mem_support {v : V} : v ∈ G.support ↔ ∃ w, G.adj v w := iff.rfl lemma support_mono {G G' : simple_graph V} (h : G ≤ G') : G.support ⊆ G'.support := rel.dom_mono h /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set (v : V) : set V := set_of (G.adj v) instance neighbor_set.mem_decidable (v : V) [decidable_rel G.adj] : decidable_pred (∈ G.neighbor_set v) := by { unfold neighbor_set, apply_instance } section edge_set variables {G₁ G₂ : simple_graph V} /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. The way `edge_set` is defined is such that `mem_edge_set` is proved by `refl`. (That is, `⟦(v, w)⟧ ∈ G.edge_set` is definitionally equal to `G.adj v w`.) -/ def edge_set : simple_graph V ↪o set (sym2 V) := order_embedding.of_map_le_iff (λ G, sym2.from_rel G.symm) $ λ G G', ⟨λ h a b, @h ⟦(a, b)⟧, λ h e, sym2.ind @h e⟩ @[simp] lemma mem_edge_set : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w := iff.rfl lemma not_is_diag_of_mem_edge_set : e ∈ G.edge_set → ¬ e.is_diag := sym2.ind (λ v w, adj.ne) e @[simp] lemma edge_set_inj : G₁.edge_set = G₂.edge_set ↔ G₁ = G₂ := (edge_set : simple_graph V ↪o set (sym2 V)).eq_iff_eq @[simp] lemma edge_set_subset_edge_set : G₁.edge_set ⊆ G₂.edge_set ↔ G₁ ≤ G₂ := (edge_set : simple_graph V ↪o set (sym2 V)).le_iff_le @[simp] lemma edge_set_ssubset_edge_set : G₁.edge_set ⊂ G₂.edge_set ↔ G₁ < G₂ := (edge_set : simple_graph V ↪o set (sym2 V)).lt_iff_lt lemma edge_set_injective : injective (edge_set : simple_graph V → set (sym2 V)) := edge_set.injective alias edge_set_subset_edge_set ↔ _ edge_set_mono alias edge_set_ssubset_edge_set ↔ _ edge_set_strict_mono attribute [mono] edge_set_mono edge_set_strict_mono variables (G₁ G₂) @[simp] lemma edge_set_bot : (⊥ : simple_graph V).edge_set = ∅ := sym2.from_rel_bot @[simp] lemma edge_set_sup : (G₁ ⊔ G₂).edge_set = G₁.edge_set ∪ G₂.edge_set := by { ext ⟨x, y⟩, refl } @[simp] lemma edge_set_inf : (G₁ ⊓ G₂).edge_set = G₁.edge_set ∩ G₂.edge_set := by { ext ⟨x, y⟩, refl } @[simp] lemma edge_set_sdiff : (G₁ \ G₂).edge_set = G₁.edge_set \ G₂.edge_set := by { ext ⟨x, y⟩, refl } /-- This lemma, combined with `edge_set_sdiff` and `edge_set_from_edge_set`, allows proving `(G \ from_edge_set s).edge_set = G.edge_set \ s` by `simp`. -/ @[simp] lemma edge_set_sdiff_sdiff_is_diag (G : simple_graph V) (s : set (sym2 V)) : G.edge_set \ (s \ {e | e.is_diag}) = G.edge_set \ s := begin ext e, simp only [set.mem_diff, set.mem_set_of_eq, not_and, not_not, and.congr_right_iff], intro h, simp only [G.not_is_diag_of_mem_edge_set h, imp_false], end /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ lemma adj_iff_exists_edge {v w : V} : G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e := begin refine ⟨λ _, ⟨G.ne_of_adj ‹_›, ⟦(v,w)⟧, _⟩, _⟩, { simpa }, { rintro ⟨hne, e, he, hv⟩, rw sym2.mem_and_mem_iff hne at hv, subst e, rwa mem_edge_set at he } end lemma adj_iff_exists_edge_coe : G.adj a b ↔ ∃ (e : G.edge_set), ↑e = ⟦(a, b)⟧ := by simp only [mem_edge_set, exists_prop, set_coe.exists, exists_eq_right, subtype.coe_mk] lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v := begin erw [← sym2.other_spec h, sym2.eq_swap] at he, exact G.ne_of_adj he, end instance decidable_mem_edge_set [decidable_rel G.adj] : decidable_pred (∈ G.edge_set) := sym2.from_rel.decidable_pred _ instance fintype_edge_set [decidable_eq V] [fintype V] [decidable_rel G.adj] : fintype G.edge_set := subtype.fintype _ instance fintype_edge_set_bot : fintype (⊥ : simple_graph V).edge_set := by { rw edge_set_bot, apply_instance } instance fintype_edge_set_sup [decidable_eq V] [fintype G₁.edge_set] [fintype G₂.edge_set] : fintype (G₁ ⊔ G₂).edge_set := by { rw edge_set_sup, apply_instance } instance fintype_edge_set_inf [decidable_eq V] [fintype G₁.edge_set] [fintype G₂.edge_set] : fintype (G₁ ⊓ G₂).edge_set := by { rw edge_set_inf, exact set.fintype_inter _ _ } instance fintype_edge_set_sdiff [decidable_eq V] [fintype G₁.edge_set] [fintype G₂.edge_set] : fintype (G₁ \ G₂).edge_set := by { rw edge_set_sdiff, exact set.fintype_diff _ _ } end edge_set section from_edge_set variable (s : set (sym2 V)) /-- `from_edge_set` constructs a `simple_graph` from a set of edges, without loops. -/ def from_edge_set : simple_graph V := { adj := sym2.to_rel s ⊓ ne, symm := λ v w h, ⟨sym2.to_rel_symmetric s h.1, h.2.symm⟩} @[simp] lemma from_edge_set_adj : (from_edge_set s).adj v w ↔ ⟦(v, w)⟧ ∈ s ∧ v ≠ w := iff.rfl -- Note: we need to make sure `from_edge_set_adj` and this lemma are confluent. -- In particular, both yield `⟦(u, v)⟧ ∈ (from_edge_set s).edge_set` ==> `⟦(v, w)⟧ ∈ s ∧ v ≠ w`. @[simp] lemma edge_set_from_edge_set : (from_edge_set s).edge_set = s \ {e | e.is_diag} := by { ext e, exact sym2.ind (by simp) e } @[simp] lemma from_edge_set_edge_set : from_edge_set G.edge_set = G := by { ext v w, exact ⟨λ h, h.1, λ h, ⟨h, G.ne_of_adj h⟩⟩ } @[simp] lemma from_edge_set_empty : from_edge_set (∅ : set (sym2 V)) = ⊥ := by { ext v w, simp only [from_edge_set_adj, set.mem_empty_iff_false, false_and, bot_adj] } @[simp] lemma from_edge_set_univ : from_edge_set (set.univ : set (sym2 V)) = ⊤ := by { ext v w, simp only [from_edge_set_adj, set.mem_univ, true_and, top_adj] } @[simp] lemma from_edge_set_inf (s t : set (sym2 V)) : from_edge_set s ⊓ from_edge_set t = from_edge_set (s ∩ t) := by { ext v w, simp only [from_edge_set_adj, set.mem_inter_iff, ne.def, inf_adj], tauto, } @[simp] lemma from_edge_set_sup (s t : set (sym2 V)) : from_edge_set s ⊔ from_edge_set t = from_edge_set (s ∪ t) := by { ext v w, simp [set.mem_union, or_and_distrib_right], } @[simp] lemma from_edge_set_sdiff (s t : set (sym2 V)) : from_edge_set s \ from_edge_set t = from_edge_set (s \ t) := by { ext v w, split; simp { contextual := tt }, } @[mono] lemma from_edge_set_mono {s t : set (sym2 V)} (h : s ⊆ t) : from_edge_set s ≤ from_edge_set t := begin rintro v w, simp only [from_edge_set_adj, ne.def, not_false_iff, and_true, and_imp] {contextual := tt}, exact λ vws _, h vws, end instance [decidable_eq V] [fintype s] : fintype (from_edge_set s).edge_set := by { rw edge_set_from_edge_set s, apply_instance } end from_edge_set /-! ## Darts -/ /-- A `dart` is an oriented edge, implemented as an ordered pair of adjacent vertices. This terminology comes from combinatorial maps, and they are also known as "half-edges" or "bonds." -/ @[ext, derive decidable_eq] structure dart extends V × V := (is_adj : G.adj fst snd) section darts variables {G} /-- The first vertex for the dart. -/ abbreviation dart.fst (d : G.dart) : V := d.fst /-- The second vertex for the dart. -/ abbreviation dart.snd (d : G.dart) : V := d.snd lemma dart.to_prod_injective : function.injective (dart.to_prod : G.dart → V × V) := dart.ext instance dart.fintype [fintype V] [decidable_rel G.adj] : fintype G.dart := fintype.of_equiv (Σ v, G.neighbor_set v) { to_fun := λ s, ⟨(s.fst, s.snd), s.snd.property⟩, inv_fun := λ d, ⟨d.fst, d.snd, d.is_adj⟩, left_inv := λ s, by ext; simp, right_inv := λ d, by ext; simp } /-- The edge associated to the dart. -/ def dart.edge (d : G.dart) : sym2 V := ⟦d.to_prod⟧ @[simp] lemma dart.edge_mk {p : V × V} (h : G.adj p.1 p.2) : (dart.mk p h).edge = ⟦p⟧ := rfl @[simp] lemma dart.edge_mem (d : G.dart) : d.edge ∈ G.edge_set := d.is_adj /-- The dart with reversed orientation from a given dart. -/ @[simps] def dart.symm (d : G.dart) : G.dart := ⟨d.to_prod.swap, G.symm d.is_adj⟩ @[simp] lemma dart.symm_mk {p : V × V} (h : G.adj p.1 p.2) : (dart.mk p h).symm = dart.mk p.swap h.symm := rfl @[simp] lemma dart.edge_symm (d : G.dart) : d.symm.edge = d.edge := sym2.mk_prod_swap_eq @[simp] lemma dart.edge_comp_symm : dart.edge ∘ dart.symm = (dart.edge : G.dart → sym2 V) := funext dart.edge_symm @[simp] lemma dart.symm_symm (d : G.dart) : d.symm.symm = d := dart.ext _ _ $ prod.swap_swap _ @[simp] lemma dart.symm_involutive : function.involutive (dart.symm : G.dart → G.dart) := dart.symm_symm lemma dart.symm_ne (d : G.dart) : d.symm ≠ d := ne_of_apply_ne (prod.snd ∘ dart.to_prod) d.is_adj.ne lemma dart_edge_eq_iff : Π (d₁ d₂ : G.dart), d₁.edge = d₂.edge ↔ d₁ = d₂ ∨ d₁ = d₂.symm := by { rintros ⟨p, hp⟩ ⟨q, hq⟩, simp [sym2.mk_eq_mk_iff] } lemma dart_edge_eq_mk_iff : Π {d : G.dart} {p : V × V}, d.edge = ⟦p⟧ ↔ d.to_prod = p ∨ d.to_prod = p.swap := by { rintro ⟨p, h⟩, apply sym2.mk_eq_mk_iff } lemma dart_edge_eq_mk_iff' : Π {d : G.dart} {u v : V}, d.edge = ⟦(u, v)⟧ ↔ d.fst = u ∧ d.snd = v ∨ d.fst = v ∧ d.snd = u := by { rintro ⟨⟨a, b⟩, h⟩ u v, rw dart_edge_eq_mk_iff, simp } variables (G) /-- Two darts are said to be adjacent if they could be consecutive darts in a walk -- that is, the first dart's second vertex is equal to the second dart's first vertex. -/ def dart_adj (d d' : G.dart) : Prop := d.snd = d'.fst /-- For a given vertex `v`, this is the bijective map from the neighbor set at `v` to the darts `d` with `d.fst = v`. -/ @[simps] def dart_of_neighbor_set (v : V) (w : G.neighbor_set v) : G.dart := ⟨(v, w), w.property⟩ lemma dart_of_neighbor_set_injective (v : V) : function.injective (G.dart_of_neighbor_set v) := λ e₁ e₂ h, subtype.ext $ by { injection h with h', convert congr_arg prod.snd h' } instance nonempty_dart_top [nontrivial V] : nonempty (⊤ : simple_graph V).dart := by { obtain ⟨v, w, h⟩ := exists_pair_ne V, exact ⟨⟨(v, w), h⟩⟩ } end darts /-! ### Incidence set -/ /-- Set of edges incident to a given vertex, aka incidence set. -/ def incidence_set (v : V) : set (sym2 V) := {e ∈ G.edge_set | v ∈ e} lemma incidence_set_subset (v : V) : G.incidence_set v ⊆ G.edge_set := λ _ h, h.1 lemma mk_mem_incidence_set_iff : ⟦(b, c)⟧ ∈ G.incidence_set a ↔ G.adj b c ∧ (a = b ∨ a = c) := and_congr_right' sym2.mem_iff lemma mk_mem_incidence_set_left_iff : ⟦(a, b)⟧ ∈ G.incidence_set a ↔ G.adj a b := and_iff_left $ sym2.mem_mk_left _ _ lemma mk_mem_incidence_set_right_iff : ⟦(a, b)⟧ ∈ G.incidence_set b ↔ G.adj a b := and_iff_left $ sym2.mem_mk_right _ _ lemma edge_mem_incidence_set_iff {e : G.edge_set} : ↑e ∈ G.incidence_set a ↔ a ∈ (e : sym2 V) := and_iff_right e.2 lemma incidence_set_inter_incidence_set_subset (h : a ≠ b) : G.incidence_set a ∩ G.incidence_set b ⊆ {⟦(a, b)⟧} := λ e he, (sym2.mem_and_mem_iff h).1 ⟨he.1.2, he.2.2⟩ lemma incidence_set_inter_incidence_set_of_adj (h : G.adj a b) : G.incidence_set a ∩ G.incidence_set b = {⟦(a, b)⟧} := begin refine (G.incidence_set_inter_incidence_set_subset $ h.ne).antisymm _, rintro _ (rfl : _ = ⟦(a, b)⟧), exact ⟨G.mk_mem_incidence_set_left_iff.2 h, G.mk_mem_incidence_set_right_iff.2 h⟩, end lemma adj_of_mem_incidence_set (h : a ≠ b) (ha : e ∈ G.incidence_set a) (hb : e ∈ G.incidence_set b) : G.adj a b := by rwa [←mk_mem_incidence_set_left_iff, ←set.mem_singleton_iff.1 $ G.incidence_set_inter_incidence_set_subset h ⟨ha, hb⟩] lemma incidence_set_inter_incidence_set_of_not_adj (h : ¬ G.adj a b) (hn : a ≠ b) : G.incidence_set a ∩ G.incidence_set b = ∅ := begin simp_rw [set.eq_empty_iff_forall_not_mem, set.mem_inter_iff, not_and], intros u ha hb, exact h (G.adj_of_mem_incidence_set hn ha hb), end instance decidable_mem_incidence_set [decidable_eq V] [decidable_rel G.adj] (v : V) : decidable_pred (∈ G.incidence_set v) := λ e, and.decidable section edge_finset variables {G₁ G₂ : simple_graph V} [fintype G.edge_set] [fintype G₁.edge_set] [fintype G₂.edge_set] /-- The `edge_set` of the graph as a `finset`. -/ @[reducible] def edge_finset : finset (sym2 V) := set.to_finset G.edge_set @[simp, norm_cast] lemma coe_edge_finset : (G.edge_finset : set (sym2 V)) = G.edge_set := set.coe_to_finset _ variables {G} @[simp] lemma mem_edge_finset : e ∈ G.edge_finset ↔ e ∈ G.edge_set := set.mem_to_finset lemma not_is_diag_of_mem_edge_finset : e ∈ G.edge_finset → ¬ e.is_diag := not_is_diag_of_mem_edge_set _ ∘ mem_edge_finset.1 @[simp] lemma edge_finset_inj : G₁.edge_finset = G₂.edge_finset ↔ G₁ = G₂ := by simp [edge_finset] @[simp] lemma edge_finset_subset_edge_finset : G₁.edge_finset ⊆ G₂.edge_finset ↔ G₁ ≤ G₂ := by simp [edge_finset] @[simp] lemma edge_finset_ssubset_edge_finset : G₁.edge_finset ⊂ G₂.edge_finset ↔ G₁ < G₂ := by simp [edge_finset] alias edge_finset_subset_edge_finset ↔ _ edge_finset_mono alias edge_finset_ssubset_edge_finset ↔ _ edge_finset_strict_mono attribute [mono] edge_finset_mono edge_finset_strict_mono @[simp] lemma edge_finset_bot : (⊥ : simple_graph V).edge_finset = ∅ := by simp [edge_finset] @[simp] lemma edge_finset_sup [decidable_eq V] : (G₁ ⊔ G₂).edge_finset = G₁.edge_finset ∪ G₂.edge_finset := by simp [edge_finset] @[simp] lemma edge_finset_inf [decidable_eq V] : (G₁ ⊓ G₂).edge_finset = G₁.edge_finset ∩ G₂.edge_finset := by simp [edge_finset] @[simp] lemma edge_finset_sdiff [decidable_eq V] : (G₁ \ G₂).edge_finset = G₁.edge_finset \ G₂.edge_finset := by simp [edge_finset] lemma edge_finset_card : G.edge_finset.card = fintype.card G.edge_set := set.to_finset_card _ @[simp] lemma edge_set_univ_card : (univ : finset G.edge_set).card = G.edge_finset.card := fintype.card_of_subtype G.edge_finset $ λ _, mem_edge_finset end edge_finset @[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := iff.rfl @[simp] lemma mem_incidence_set (v w : V) : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ G.adj v w := by simp [incidence_set] lemma mem_incidence_iff_neighbor {v w : V} : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ w ∈ G.neighbor_set v := by simp only [mem_incidence_set, mem_neighbor_set] lemma adj_incidence_set_inter {v : V} {e : sym2 V} (he : e ∈ G.edge_set) (h : v ∈ e) : G.incidence_set v ∩ G.incidence_set h.other = {e} := begin ext e', simp only [incidence_set, set.mem_sep_iff, set.mem_inter_iff, set.mem_singleton_iff], refine ⟨λ h', _, _⟩, { rw ←sym2.other_spec h, exact (sym2.mem_and_mem_iff (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩ }, { rintro rfl, exact ⟨⟨he, h⟩, he, sym2.other_mem _⟩ } end lemma compl_neighbor_set_disjoint (G : simple_graph V) (v : V) : disjoint (G.neighbor_set v) (Gᶜ.neighbor_set v) := begin rw set.disjoint_iff, rintro w ⟨h, h'⟩, rw [mem_neighbor_set, compl_adj] at h', exact h'.2 h, end lemma neighbor_set_union_compl_neighbor_set_eq (G : simple_graph V) (v : V) : G.neighbor_set v ∪ Gᶜ.neighbor_set v = {v}ᶜ := begin ext w, have h := @ne_of_adj _ G, simp_rw [set.mem_union, mem_neighbor_set, compl_adj, set.mem_compl_iff, set.mem_singleton_iff], tauto, end -- TODO find out why TC inference has `h` failing a defeq check for `to_finset` lemma card_neighbor_set_union_compl_neighbor_set [fintype V] (G : simple_graph V) (v : V) [h : fintype (G.neighbor_set v ∪ Gᶜ.neighbor_set v : set V)] : (@set.to_finset _ (G.neighbor_set v ∪ Gᶜ.neighbor_set v) h).card = fintype.card V - 1 := begin classical, simp_rw [neighbor_set_union_compl_neighbor_set_eq, set.to_finset_compl, finset.card_compl, set.to_finset_card, set.card_singleton], end lemma neighbor_set_compl (G : simple_graph V) (v : V) : Gᶜ.neighbor_set v = (G.neighbor_set v)ᶜ \ {v} := by { ext w, simp [and_comm, eq_comm] } /-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the intersection of the neighbor sets of `v` and `w`. -/ def common_neighbors (v w : V) : set V := G.neighbor_set v ∩ G.neighbor_set w lemma common_neighbors_eq (v w : V) : G.common_neighbors v w = G.neighbor_set v ∩ G.neighbor_set w := rfl lemma mem_common_neighbors {u v w : V} : u ∈ G.common_neighbors v w ↔ G.adj v u ∧ G.adj w u := iff.rfl lemma common_neighbors_symm (v w : V) : G.common_neighbors v w = G.common_neighbors w v := set.inter_comm _ _ lemma not_mem_common_neighbors_left (v w : V) : v ∉ G.common_neighbors v w := λ h, ne_of_adj G h.1 rfl lemma not_mem_common_neighbors_right (v w : V) : w ∉ G.common_neighbors v w := λ h, ne_of_adj G h.2 rfl lemma common_neighbors_subset_neighbor_set_left (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set v := set.inter_subset_left _ _ lemma common_neighbors_subset_neighbor_set_right (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set w := set.inter_subset_right _ _ instance decidable_mem_common_neighbors [decidable_rel G.adj] (v w : V) : decidable_pred (∈ G.common_neighbors v w) := λ a, and.decidable lemma common_neighbors_top_eq {v w : V} : (⊤ : simple_graph V).common_neighbors v w = set.univ \ {v, w} := by { ext u, simp [common_neighbors, eq_comm, not_or_distrib.symm] } section incidence variable [decidable_eq V] /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def other_vertex_of_incident {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : V := h.2.other' lemma edge_other_incident_set {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : e ∈ G.incidence_set (G.other_vertex_of_incident h) := by { use h.1, simp [other_vertex_of_incident, sym2.other_mem'] } lemma incidence_other_prop {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : G.other_vertex_of_incident h ∈ G.neighbor_set v := by { cases h with he hv, rwa [←sym2.other_spec' hv, mem_edge_set] at he } @[simp] lemma incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighbor_set v) : G.other_vertex_of_incident (G.mem_incidence_iff_neighbor.mpr h) = w := sym2.congr_right.mp (sym2.other_spec' (G.mem_incidence_iff_neighbor.mpr h).right) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ @[simps] def incidence_set_equiv_neighbor_set (v : V) : G.incidence_set v ≃ G.neighbor_set v := { to_fun := λ e, ⟨G.other_vertex_of_incident e.2, G.incidence_other_prop e.2⟩, inv_fun := λ w, ⟨⟦(v, w.1)⟧, G.mem_incidence_iff_neighbor.mpr w.2⟩, left_inv := λ x, by simp [other_vertex_of_incident], right_inv := λ ⟨w, hw⟩, by simp } end incidence /-! ## Edge deletion -/ /-- Given a set of vertex pairs, remove all of the corresponding edges from the graph's edge set, if present. See also: `simple_graph.subgraph.delete_edges`. -/ def delete_edges (s : set (sym2 V)) : simple_graph V := { adj := G.adj \ sym2.to_rel s, symm := λ a b, by simp [adj_comm, sym2.eq_swap] } @[simp] lemma delete_edges_adj (s : set (sym2 V)) (v w : V) : (G.delete_edges s).adj v w ↔ G.adj v w ∧ ¬ ⟦(v, w)⟧ ∈ s := iff.rfl lemma sdiff_eq_delete_edges (G G' : simple_graph V) : G \ G' = G.delete_edges G'.edge_set := by { ext, simp } lemma delete_edges_eq_sdiff_from_edge_set (s : set (sym2 V)) : G.delete_edges s = G \ from_edge_set s := by { ext, exact ⟨λ h, ⟨h.1, not_and_of_not_left _ h.2⟩, λ h, ⟨h.1, not_and'.mp h.2 h.ne⟩⟩ } lemma compl_eq_delete_edges : Gᶜ = (⊤ : simple_graph V).delete_edges G.edge_set := by { ext, simp } @[simp] lemma delete_edges_delete_edges (s s' : set (sym2 V)) : (G.delete_edges s).delete_edges s' = G.delete_edges (s ∪ s') := by { ext, simp [and_assoc, not_or_distrib] } @[simp] lemma delete_edges_empty_eq : G.delete_edges ∅ = G := by { ext, simp } @[simp] lemma delete_edges_univ_eq : G.delete_edges set.univ = ⊥ := by { ext, simp } lemma delete_edges_le (s : set (sym2 V)) : G.delete_edges s ≤ G := by { intro, simp { contextual := tt } } lemma delete_edges_le_of_le {s s' : set (sym2 V)} (h : s ⊆ s') : G.delete_edges s' ≤ G.delete_edges s := λ v w, begin simp only [delete_edges_adj, and_imp, true_and] { contextual := tt }, exact λ ha hn hs, hn (h hs), end lemma delete_edges_eq_inter_edge_set (s : set (sym2 V)) : G.delete_edges s = G.delete_edges (s ∩ G.edge_set) := by { ext, simp [imp_false] { contextual := tt } } lemma delete_edges_sdiff_eq_of_le {H : simple_graph V} (h : H ≤ G) : G.delete_edges (G.edge_set \ H.edge_set) = H := by { ext v w, split; simp [@h v w] { contextual := tt } } lemma edge_set_delete_edges (s : set (sym2 V)) : (G.delete_edges s).edge_set = G.edge_set \ s := by { ext e, refine sym2.ind _ e, simp } lemma edge_finset_delete_edges [fintype V] [decidable_eq V] [decidable_rel G.adj] (s : finset (sym2 V)) [decidable_rel (G.delete_edges s).adj] : (G.delete_edges s).edge_finset = G.edge_finset \ s := by { ext e, simp [edge_set_delete_edges] } section delete_far variables (G) [ordered_ring 𝕜] [fintype V] [decidable_eq V] [decidable_rel G.adj] {p : simple_graph V → Prop} {r r₁ r₂ : 𝕜} /-- A graph is `r`-*delete-far* from a property `p` if we must delete at least `r` edges from it to get a graph with the property `p`. -/ def delete_far (p : simple_graph V → Prop) (r : 𝕜) : Prop := ∀ ⦃s⦄, s ⊆ G.edge_finset → p (G.delete_edges s) → r ≤ s.card open_locale classical variables {G} lemma delete_far_iff : G.delete_far p r ↔ ∀ ⦃H⦄, H ≤ G → p H → r ≤ G.edge_finset.card - H.edge_finset.card := begin refine ⟨λ h H hHG hH, _, λ h s hs hG, _⟩, { have := h (sdiff_subset G.edge_finset H.edge_finset), simp only [delete_edges_sdiff_eq_of_le _ hHG, edge_finset_mono hHG, card_sdiff, card_le_of_subset, coe_sdiff, coe_edge_finset, nat.cast_sub] at this, exact this hH }, { simpa [card_sdiff hs, edge_finset_delete_edges, -set.to_finset_card, nat.cast_sub, card_le_of_subset hs] using h (G.delete_edges_le s) hG } end alias delete_far_iff ↔ delete_far.le_card_sub_card _ lemma delete_far.mono (h : G.delete_far p r₂) (hr : r₁ ≤ r₂) : G.delete_far p r₁ := λ s hs hG, hr.trans $ h hs hG end delete_far /-! ## Map and comap -/ /-- Given an injective function, there is an covariant induced map on graphs by pushing forward the adjacency relation. This is injective (see `simple_graph.map_injective`). -/ protected def map (f : V ↪ W) (G : simple_graph V) : simple_graph W := { adj := relation.map G.adj f f } @[simp] lemma map_adj (f : V ↪ W) (G : simple_graph V) (u v : W) : (G.map f).adj u v ↔ ∃ (u' v' : V), G.adj u' v' ∧ f u' = u ∧ f v' = v := iff.rfl lemma map_monotone (f : V ↪ W) : monotone (simple_graph.map f) := by { rintros G G' h _ _ ⟨u, v, ha, rfl, rfl⟩, exact ⟨_, _, h ha, rfl, rfl⟩ } /-- Given a function, there is a contravariant induced map on graphs by pulling back the adjacency relation. This is one of the ways of creating induced graphs. See `simple_graph.induce` for a wrapper. This is surjective when `f` is injective (see `simple_graph.comap_surjective`).-/ @[simps] protected def comap (f : V → W) (G : simple_graph W) : simple_graph V := { adj := λ u v, G.adj (f u) (f v) } lemma comap_monotone (f : V ↪ W) : monotone (simple_graph.comap f) := by { intros G G' h _ _ ha, exact h ha } @[simp] lemma comap_map_eq (f : V ↪ W) (G : simple_graph V) : (G.map f).comap f = G := by { ext, simp } lemma left_inverse_comap_map (f : V ↪ W) : function.left_inverse (simple_graph.comap f) (simple_graph.map f) := comap_map_eq f lemma map_injective (f : V ↪ W) : function.injective (simple_graph.map f) := (left_inverse_comap_map f).injective lemma comap_surjective (f : V ↪ W) : function.surjective (simple_graph.comap f) := (left_inverse_comap_map f).surjective lemma map_le_iff_le_comap (f : V ↪ W) (G : simple_graph V) (G' : simple_graph W) : G.map f ≤ G' ↔ G ≤ G'.comap f := ⟨λ h u v ha, h ⟨_, _, ha, rfl, rfl⟩, by { rintros h _ _ ⟨u, v, ha, rfl, rfl⟩, exact h ha, }⟩ lemma map_comap_le (f : V ↪ W) (G : simple_graph W) : (G.comap f).map f ≤ G := by { rw map_le_iff_le_comap, exact le_refl _ } /-! ## Induced graphs -/ /- Given a set `s` of vertices, we can restrict a graph to those vertices by restricting its adjacency relation. This gives a map between `simple_graph V` and `simple_graph s`. There is also a notion of induced subgraphs (see `simple_graph.subgraph.induce`). -/ /-- Restrict a graph to the vertices in the set `s`, deleting all edges incident to vertices outside the set. This is a wrapper around `simple_graph.comap`. -/ @[reducible] def induce (s : set V) (G : simple_graph V) : simple_graph s := G.comap (function.embedding.subtype _) /-- Given a graph on a set of vertices, we can make it be a `simple_graph V` by adding in the remaining vertices without adding in any additional edges. This is a wrapper around `simple_graph.map`. -/ @[reducible] def spanning_coe {s : set V} (G : simple_graph s) : simple_graph V := G.map (function.embedding.subtype _) lemma induce_spanning_coe {s : set V} {G : simple_graph s} : G.spanning_coe.induce s = G := comap_map_eq _ _ lemma spanning_coe_induce_le (s : set V) : (G.induce s).spanning_coe ≤ G := map_comap_le _ _ section finite_at /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ variables (v) [fintype (G.neighbor_set v)] /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset : finset V := (G.neighbor_set v).to_finset lemma neighbor_finset_def : G.neighbor_finset v = (G.neighbor_set v).to_finset := rfl @[simp] lemma mem_neighbor_finset (w : V) : w ∈ G.neighbor_finset v ↔ G.adj v w := set.mem_to_finset @[simp] lemma not_mem_neighbor_finset_self : v ∉ G.neighbor_finset v := (mem_neighbor_finset _ _ _).not.mpr $ G.loopless _ lemma neighbor_finset_disjoint_singleton : disjoint (G.neighbor_finset v) {v} := finset.disjoint_singleton_right.mpr $ not_mem_neighbor_finset_self _ _ lemma singleton_disjoint_neighbor_finset : disjoint {v} (G.neighbor_finset v) := finset.disjoint_singleton_left.mpr $ not_mem_neighbor_finset_self _ _ /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighbor_finset v).card @[simp] lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v := (set.to_finset_card _).symm lemma degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.adj v w := by simp only [degree, card_pos, finset.nonempty, mem_neighbor_finset] lemma degree_compl [fintype (Gᶜ.neighbor_set v)] [fintype V] : Gᶜ.degree v = fintype.card V - 1 - G.degree v := begin classical, rw [← card_neighbor_set_union_compl_neighbor_set G v, set.to_finset_union], simp [card_disjoint_union (set.disjoint_to_finset.mpr (compl_neighbor_set_disjoint G v))], end instance incidence_set_fintype [decidable_eq V] : fintype (G.incidence_set v) := fintype.of_equiv (G.neighbor_set v) (G.incidence_set_equiv_neighbor_set v).symm /-- This is the `finset` version of `incidence_set`. -/ def incidence_finset [decidable_eq V] : finset (sym2 V) := (G.incidence_set v).to_finset @[simp] lemma card_incidence_set_eq_degree [decidable_eq V] : fintype.card (G.incidence_set v) = G.degree v := by { rw fintype.card_congr (G.incidence_set_equiv_neighbor_set v), simp } @[simp] lemma card_incidence_finset_eq_degree [decidable_eq V] : (G.incidence_finset v).card = G.degree v := by { rw ← G.card_incidence_set_eq_degree, apply set.to_finset_card } @[simp] lemma mem_incidence_finset [decidable_eq V] (e : sym2 V) : e ∈ G.incidence_finset v ↔ e ∈ G.incidence_set v := set.mem_to_finset lemma incidence_finset_eq_filter [decidable_eq V] [fintype G.edge_set] : G.incidence_finset v = G.edge_finset.filter (has_mem.mem v) := begin ext e, refine sym2.ind (λ x y, _) e, simp [mk_mem_incidence_set_iff], end end finite_at section locally_finite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ @[reducible] def locally_finite := Π (v : V), fintype (G.neighbor_set v) variable [locally_finite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d variables {G} lemma is_regular_of_degree.degree_eq {d : ℕ} (h : G.is_regular_of_degree d) (v : V) : G.degree v = d := h v lemma is_regular_of_degree.compl [fintype V] [decidable_eq V] {G : simple_graph V} [decidable_rel G.adj] {k : ℕ} (h : G.is_regular_of_degree k) : Gᶜ.is_regular_of_degree (fintype.card V - 1 - k) := by { intro v, rw [degree_compl, h v] } end locally_finite section finite variable [fintype V] instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) := @subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _ lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] : G.neighbor_finset v = finset.univ.filter (G.adj v) := by { ext, simp } lemma neighbor_finset_compl [decidable_eq V] [decidable_rel G.adj] (v : V) : Gᶜ.neighbor_finset v = (G.neighbor_finset v)ᶜ \ {v} := by simp only [neighbor_finset, neighbor_set_compl, set.to_finset_diff, set.to_finset_compl, set.to_finset_singleton] @[simp] lemma complete_graph_degree [decidable_eq V] (v : V) : (⊤ : simple_graph V).degree v = fintype.card V - 1 := by erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v), card_univ] lemma bot_degree (v : V) : (⊥ : simple_graph V).degree v = 0 := begin erw [degree, neighbor_finset_eq_filter, filter_false], exact finset.card_empty, end lemma is_regular_of_degree.top [decidable_eq V] : (⊤ : simple_graph V).is_regular_of_degree (fintype.card V - 1) := by { intro v, simp } /-- The minimum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_minimal_degree_vertex`, `min_degree_le_degree` and `le_min_degree_of_forall_le_degree`. -/ def min_degree [decidable_rel G.adj] : ℕ := with_top.untop' 0 (univ.image (λ v, G.degree v)).min /-- There exists a vertex of minimal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_minimal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.min_degree = G.degree v := begin obtain ⟨t, ht : _ = _⟩ := min_of_nonempty (univ_nonempty.image (λ v, G.degree v)), obtain ⟨v, _, rfl⟩ := mem_image.mp (mem_of_min ht), refine ⟨v, by simp [min_degree, ht]⟩, end /-- The minimum degree in the graph is at most the degree of any particular vertex. -/ lemma min_degree_le_degree [decidable_rel G.adj] (v : V) : G.min_degree ≤ G.degree v := begin obtain ⟨t, ht⟩ := finset.min_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.min_le_of_eq (mem_image_of_mem _ (mem_univ v)) ht, rwa [min_degree, ht] end /-- In a nonempty graph, if `k` is at most the degree of every vertex, it is at most the minimum degree. Note the assumption that the graph is nonempty is necessary as long as `G.min_degree` is defined to be a natural. -/ lemma le_min_degree_of_forall_le_degree [decidable_rel G.adj] [nonempty V] (k : ℕ) (h : ∀ v, k ≤ G.degree v) : k ≤ G.min_degree := by { rcases G.exists_minimal_degree_vertex with ⟨v, hv⟩, rw hv, apply h } /-- The maximum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_maximal_degree_vertex`, `degree_le_max_degree` and `max_degree_le_of_forall_degree_le`. -/ def max_degree [decidable_rel G.adj] : ℕ := option.get_or_else (univ.image (λ v, G.degree v)).max 0 /-- There exists a vertex of maximal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_maximal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.max_degree = G.degree v := begin obtain ⟨t, ht⟩ := max_of_nonempty (univ_nonempty.image (λ v, G.degree v)), have ht₂ := mem_of_max ht, simp only [mem_image, mem_univ, exists_prop_of_true] at ht₂, rcases ht₂ with ⟨v, rfl⟩, refine ⟨v, _⟩, rw [max_degree, ht], refl end /-- The maximum degree in the graph is at least the degree of any particular vertex. -/ lemma degree_le_max_degree [decidable_rel G.adj] (v : V) : G.degree v ≤ G.max_degree := begin obtain ⟨t, ht : _ = _⟩ := finset.max_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.le_max_of_eq (mem_image_of_mem _ (mem_univ v)) ht, rwa [max_degree, ht], end /-- In a graph, if `k` is at least the degree of every vertex, then it is at least the maximum degree. -/ lemma max_degree_le_of_forall_degree_le [decidable_rel G.adj] (k : ℕ) (h : ∀ v, G.degree v ≤ k) : G.max_degree ≤ k := begin by_cases hV : (univ : finset V).nonempty, { haveI : nonempty V := univ_nonempty_iff.mp hV, obtain ⟨v, hv⟩ := G.exists_maximal_degree_vertex, rw hv, apply h }, { rw not_nonempty_iff_eq_empty at hV, rw [max_degree, hV, image_empty], exact zero_le k }, end lemma degree_lt_card_verts [decidable_rel G.adj] (v : V) : G.degree v < fintype.card V := begin classical, apply finset.card_lt_card, rw finset.ssubset_iff, exact ⟨v, by simp, finset.subset_univ _⟩, end /-- The maximum degree of a nonempty graph is less than the number of vertices. Note that the assumption that `V` is nonempty is necessary, as otherwise this would assert the existence of a natural number less than zero. -/ lemma max_degree_lt_card_verts [decidable_rel G.adj] [nonempty V] : G.max_degree < fintype.card V := begin cases G.exists_maximal_degree_vertex with v hv, rw hv, apply G.degree_lt_card_verts v, end lemma card_common_neighbors_le_degree_left [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree v := begin rw [←card_neighbor_set_eq_degree], exact set.card_le_of_subset (set.inter_subset_left _ _), end lemma card_common_neighbors_le_degree_right [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree w := by simp_rw [common_neighbors_symm _ v w, card_common_neighbors_le_degree_left] lemma card_common_neighbors_lt_card_verts [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) < fintype.card V := nat.lt_of_le_of_lt (G.card_common_neighbors_le_degree_left _ _) (G.degree_lt_card_verts v) /-- If the condition `G.adj v w` fails, then `card_common_neighbors_le_degree` is the best we can do in general. -/ lemma adj.card_common_neighbors_lt_degree {G : simple_graph V} [decidable_rel G.adj] {v w : V} (h : G.adj v w) : fintype.card (G.common_neighbors v w) < G.degree v := begin classical, erw [←set.to_finset_card], apply finset.card_lt_card, rw finset.ssubset_iff, use w, split, { rw set.mem_to_finset, apply not_mem_common_neighbors_right }, { rw finset.insert_subset, split, { simpa, }, { rw [neighbor_finset, set.to_finset_subset_to_finset], exact G.common_neighbors_subset_neighbor_set_left _ _ } } end lemma card_common_neighbors_top [decidable_eq V] {v w : V} (h : v ≠ w) : fintype.card ((⊤ : simple_graph V).common_neighbors v w) = fintype.card V - 2 := begin simp only [common_neighbors_top_eq, ← set.to_finset_card, set.to_finset_diff], rw finset.card_sdiff, { simp [finset.card_univ, h], }, { simp only [set.to_finset_subset_to_finset, set.subset_univ] }, end end finite section maps /-- A graph homomorphism is a map on vertex sets that respects adjacency relations. The notation `G →g G'` represents the type of graph homomorphisms. -/ abbreviation hom := rel_hom G.adj G'.adj /-- A graph embedding is an embedding `f` such that for vertices `v w : V`, `G.adj f(v) f(w) ↔ G.adj v w `. Its image is an induced subgraph of G'. The notation `G ↪g G'` represents the type of graph embeddings. -/ abbreviation embedding := rel_embedding G.adj G'.adj /-- A graph isomorphism is an bijective map on vertex sets that respects adjacency relations. The notation `G ≃g G'` represents the type of graph isomorphisms. -/ abbreviation iso := rel_iso G.adj G'.adj infix ` →g ` : 50 := hom infix ` ↪g ` : 50 := embedding infix ` ≃g ` : 50 := iso namespace hom variables {G G'} (f : G →g G') /-- The identity homomorphism from a graph to itself. -/ abbreviation id : G →g G := rel_hom.id _ lemma map_adj {v w : V} (h : G.adj v w) : G'.adj (f v) (f w) := f.map_rel' h lemma map_mem_edge_set {e : sym2 V} (h : e ∈ G.edge_set) : e.map f ∈ G'.edge_set := quotient.ind (λ e h, sym2.from_rel_prop.mpr (f.map_rel' h)) e h lemma apply_mem_neighbor_set {v w : V} (h : w ∈ G.neighbor_set v) : f w ∈ G'.neighbor_set (f v) := map_adj f h /-- The map between edge sets induced by a homomorphism. The underlying map on edges is given by `sym2.map`. -/ @[simps] def map_edge_set (e : G.edge_set) : G'.edge_set := ⟨sym2.map f e, f.map_mem_edge_set e.property⟩ /-- The map between neighbor sets induced by a homomorphism. -/ @[simps] def map_neighbor_set (v : V) (w : G.neighbor_set v) : G'.neighbor_set (f v) := ⟨f w, f.apply_mem_neighbor_set w.property⟩ /-- The map between darts induced by a homomorphism. -/ def map_dart (d : G.dart) : G'.dart := ⟨d.1.map f f, f.map_adj d.2⟩ @[simp] lemma map_dart_apply (d : G.dart) : f.map_dart d = ⟨d.1.map f f, f.map_adj d.2⟩ := rfl /-- The induced map for spanning subgraphs, which is the identity on vertices. -/ @[simps] def map_spanning_subgraphs {G G' : simple_graph V} (h : G ≤ G') : G →g G' := { to_fun := λ x, x, map_rel' := h } lemma map_edge_set.injective (hinj : function.injective f) : function.injective f.map_edge_set := begin rintros ⟨e₁, h₁⟩ ⟨e₂, h₂⟩, dsimp [hom.map_edge_set], repeat { rw subtype.mk_eq_mk }, apply sym2.map.injective hinj, end /-- Every graph homomomorphism from a complete graph is injective. -/ lemma injective_of_top_hom (f : (⊤ : simple_graph V) →g G') : function.injective f := begin intros v w h, contrapose! h, exact G'.ne_of_adj (map_adj _ ((top_adj _ _).mpr h)), end /-- There is a homomorphism to a graph from a comapped graph. When the function is injective, this is an embedding (see `simple_graph.embedding.comap`). -/ @[simps] protected def comap (f : V → W) (G : simple_graph W) : G.comap f →g G := { to_fun := f, map_rel' := by simp } variable {G'' : simple_graph X} /-- Composition of graph homomorphisms. -/ abbreviation comp (f' : G' →g G'') (f : G →g G') : G →g G'' := f'.comp f @[simp] lemma coe_comp (f' : G' →g G'') (f : G →g G') : ⇑(f'.comp f) = f' ∘ f := rfl end hom namespace embedding variables {G G'} (f : G ↪g G') /-- The identity embedding from a graph to itself. -/ abbreviation refl : G ↪g G := rel_embedding.refl _ /-- An embedding of graphs gives rise to a homomorphism of graphs. -/ abbreviation to_hom : G →g G' := f.to_rel_hom lemma map_adj_iff {v w : V} : G'.adj (f v) (f w) ↔ G.adj v w := f.map_rel_iff lemma map_mem_edge_set_iff {e : sym2 V} : e.map f ∈ G'.edge_set ↔ e ∈ G.edge_set := quotient.ind (λ ⟨v, w⟩, f.map_adj_iff) e lemma apply_mem_neighbor_set_iff {v w : V} : f w ∈ G'.neighbor_set (f v) ↔ w ∈ G.neighbor_set v := map_adj_iff f /-- A graph embedding induces an embedding of edge sets. -/ @[simps] def map_edge_set : G.edge_set ↪ G'.edge_set := { to_fun := hom.map_edge_set f, inj' := hom.map_edge_set.injective f f.inj' } /-- A graph embedding induces an embedding of neighbor sets. -/ @[simps] def map_neighbor_set (v : V) : G.neighbor_set v ↪ G'.neighbor_set (f v) := { to_fun := λ w, ⟨f w, f.apply_mem_neighbor_set_iff.mpr w.2⟩, inj' := begin rintros ⟨w₁, h₁⟩ ⟨w₂, h₂⟩ h, rw subtype.mk_eq_mk at h ⊢, exact f.inj' h, end } /-- Given an injective function, there is an embedding from the comapped graph into the original graph. -/ @[simps] protected def comap (f : V ↪ W) (G : simple_graph W) : G.comap f ↪g G := { map_rel_iff' := by simp, ..f } /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ @[simps] protected def map (f : V ↪ W) (G : simple_graph V) : G ↪g G.map f := { map_rel_iff' := by simp, ..f } /-- Induced graphs embed in the original graph. Note that if `G.induce s = ⊤` (i.e., if `s` is a clique) then this gives the embedding of a complete graph. -/ @[reducible] protected def induce (s : set V) : G.induce s ↪g G := simple_graph.embedding.comap (function.embedding.subtype _) G /-- Graphs on a set of vertices embed in their `spanning_coe`. -/ @[reducible] protected def spanning_coe {s : set V} (G : simple_graph s) : G ↪g G.spanning_coe := simple_graph.embedding.map (function.embedding.subtype _) G /-- Embeddings of types induce embeddings of complete graphs on those types. -/ protected def complete_graph {α β : Type*} (f : α ↪ β) : (⊤ : simple_graph α) ↪g (⊤ : simple_graph β) := { map_rel_iff' := by simp, ..f } variables {G'' : simple_graph X} /-- Composition of graph embeddings. -/ abbreviation comp (f' : G' ↪g G'') (f : G ↪g G') : G ↪g G'' := f.trans f' @[simp] lemma coe_comp (f' : G' ↪g G'') (f : G ↪g G') : ⇑(f'.comp f) = f' ∘ f := rfl end embedding section induce_hom variables {G G'} {G'' : simple_graph X} {s : set V} {t : set W} {r : set X} (φ : G →g G') (φst : set.maps_to φ s t) (ψ : G' →g G'') (ψtr : set.maps_to ψ t r) /-- The restriction of a morphism of graphs to induced subgraphs. -/ def induce_hom : G.induce s →g G'.induce t := { to_fun := set.maps_to.restrict φ s t φst, map_rel' := λ _ _, φ.map_rel', } @[simp, norm_cast] lemma coe_induce_hom : ⇑(induce_hom φ φst) = set.maps_to.restrict φ s t φst := rfl @[simp] lemma induce_hom_id (G : simple_graph V) (s) : induce_hom (hom.id : G →g G) (set.maps_to_id s) = hom.id := by { ext x, refl } @[simp] lemma induce_hom_comp : (induce_hom ψ ψtr).comp (induce_hom φ φst) = induce_hom (ψ.comp φ) (ψtr.comp φst) := by { ext x, refl } end induce_hom namespace iso variables {G G'} (f : G ≃g G') /-- The identity isomorphism of a graph with itself. -/ abbreviation refl : G ≃g G := rel_iso.refl _ /-- An isomorphism of graphs gives rise to an embedding of graphs. -/ abbreviation to_embedding : G ↪g G' := f.to_rel_embedding /-- An isomorphism of graphs gives rise to a homomorphism of graphs. -/ abbreviation to_hom : G →g G' := f.to_embedding.to_hom /-- The inverse of a graph isomorphism. -/ abbreviation symm : G' ≃g G := f.symm lemma map_adj_iff {v w : V} : G'.adj (f v) (f w) ↔ G.adj v w := f.map_rel_iff lemma map_mem_edge_set_iff {e : sym2 V} : e.map f ∈ G'.edge_set ↔ e ∈ G.edge_set := quotient.ind (λ ⟨v, w⟩, f.map_adj_iff) e lemma apply_mem_neighbor_set_iff {v w : V} : f w ∈ G'.neighbor_set (f v) ↔ w ∈ G.neighbor_set v := map_adj_iff f /-- An isomorphism of graphs induces an equivalence of edge sets. -/ @[simps] def map_edge_set : G.edge_set ≃ G'.edge_set := { to_fun := hom.map_edge_set f, inv_fun := hom.map_edge_set f.symm, left_inv := begin rintro ⟨e, h⟩, simp only [hom.map_edge_set, sym2.map_map, rel_iso.coe_coe_fn, rel_embedding.coe_coe_fn, subtype.mk_eq_mk, subtype.coe_mk, coe_coe], apply congr_fun, convert sym2.map_id, exact funext (λ _, rel_iso.symm_apply_apply _ _), end, right_inv := begin rintro ⟨e, h⟩, simp only [hom.map_edge_set, sym2.map_map, rel_iso.coe_coe_fn, rel_embedding.coe_coe_fn, subtype.mk_eq_mk, subtype.coe_mk, coe_coe], apply congr_fun, convert sym2.map_id, exact funext (λ _, rel_iso.apply_symm_apply _ _), end } /-- A graph isomorphism induces an equivalence of neighbor sets. -/ @[simps] def map_neighbor_set (v : V) : G.neighbor_set v ≃ G'.neighbor_set (f v) := { to_fun := λ w, ⟨f w, f.apply_mem_neighbor_set_iff.mpr w.2⟩, inv_fun := λ w, ⟨f.symm w, begin convert f.symm.apply_mem_neighbor_set_iff.mpr w.2, simp only [rel_iso.symm_apply_apply], end⟩, left_inv := λ w, by simp, right_inv := λ w, by simp } lemma card_eq_of_iso [fintype V] [fintype W] (f : G ≃g G') : fintype.card V = fintype.card W := by convert (fintype.of_equiv_card f.to_equiv).symm /-- Given a bijection, there is an embedding from the comapped graph into the original graph. -/ @[simps] protected def comap (f : V ≃ W) (G : simple_graph W) : G.comap f.to_embedding ≃g G := { map_rel_iff' := by simp, ..f } /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ @[simps] protected def map (f : V ≃ W) (G : simple_graph V) : G ≃g G.map f.to_embedding := { map_rel_iff' := by simp, ..f } /-- Equivalences of types induce isomorphisms of complete graphs on those types. -/ protected def complete_graph {α β : Type*} (f : α ≃ β) : (⊤ : simple_graph α) ≃g (⊤ : simple_graph β) := { map_rel_iff' := by simp, ..f } lemma to_embedding_complete_graph {α β : Type*} (f : α ≃ β) : (iso.complete_graph f).to_embedding = embedding.complete_graph f.to_embedding := rfl variables {G'' : simple_graph X} /-- Composition of graph isomorphisms. -/ abbreviation comp (f' : G' ≃g G'') (f : G ≃g G') : G ≃g G'' := f.trans f' @[simp] lemma coe_comp (f' : G' ≃g G'') (f : G ≃g G') : ⇑(f'.comp f) = f' ∘ f := rfl end iso end maps end simple_graph
108339130874b2148e2495f94d20bde21da9995d
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/higher_order_funcs/higher_order_intro.lean
997d62afc7eebc441c65a4bb0d80b400bb909b62
[]
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
1,996
lean
/- Take funtion as argument and use it in implementation. -/ def apply_nat_to_nat (f : ℕ → ℕ) (n : ℕ) : ℕ := f n #eval apply_nat_to_nat nat.succ 1 #eval apply_nat_to_nat nat.pred 1 /- Make idea completely general using polymorphism -/ def apply {α β : Type} (f : α → β) (a : α) : β := f a #eval apply nat.succ 1 #eval apply nat.pred 1 #eval apply string.length "I love logic!" /- Return function as a result -/ def apply_twice {α : Type} (f : α → α ) : α → α := λ a, f (f a) #reduce (apply_twice nat.succ) #reduce apply_twice nat.pred def double (n : ℕ) := 2 * n def square (n : ℕ) := n ^ 2 #eval apply_twice nat.succ 3 -- application is left associative #eval apply_twice nat.pred 3 #eval (apply_twice double) 3 def square_twice := apply_twice square def double_twice := apply_twice double #eval square_twice 5 /- That's composition of a function with itself, but we can also compose different functions. Here's a special case. -/ def compose_1 {α : Type} (g : α → α ) (f : α → α ): α → α := λ a, g (f a) def double_inc := compose_1 double nat.succ #reduce double_inc #eval double_inc 3 -- Define and try out inc_double (first double then increment) def is_even (n : ℕ) : bool := n % 2 = 0 #eval is_even 6 def compose {α β γ : Type} (g : β → γ) (f : α → β) : α → γ := λ (a : α), g (f a) def even_length := compose is_even string.length #eval even_length "I love logic!!!!!!!" def even_length' := is_even ∘ string.length -- math notation /- Functions are objects, too, and there are associated operations that apply to functions. Composition is one such operation. Differentiation is another example of a function of functions. -/ /- Exercise: apply_n -/ /- List map. -/ def list_map {α β : Type} : (α → β) → list α → list β | f [] := [] | f (h :: t) := list.cons (f h) (list_map f t) -- exercise box_map -- exercise option_map -- exercise tree_map
bfda15caba8f326b09d2a7799f8a40a62404de86
d406927ab5617694ec9ea7001f101b7c9e3d9702
/test/linear_combination.lean
e318dc1a394eacbdac67661e82be37e18e3de015
[ "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
7,651
lean
import tactic.linear_combination import data.real.basic /-! ### Simple Cases with ℤ and two or less equations -/ example (x y : ℤ) (h1 : 3*x + 2*y = 10): 3*x + 2*y = 10 := by linear_combination 1*h1 example (x y : ℤ) (h1 : 3*x + 2*y = 10): 3*x + 2*y = 10 := by linear_combination (h1) example (x y : ℤ) (h1 : x + 2 = -3) (h2 : y = 10) : 2*x + 4 = -6 := by linear_combination 2*h1 example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by linear_combination 1*h1 - 2*h2 example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by linear_combination -2*h2 + h1 example (x y : ℤ) (h1 : x + 2 = -3) (h2 : y = 10) : 2*x + 4 - y = -16 := by linear_combination 2*h1 + -1*h2 example (x y : ℤ) (h1 : x + 2 = -3) (h2 : y = 10) : -y + 2*x + 4 = -16 := by linear_combination -h2 + 2*h1 example (x y : ℤ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : 11*y = -11 := by linear_combination -2*h1 + 3*h2 example (x y : ℤ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y = 11 := by linear_combination 2*h1 - 3*h2 example (x y : ℤ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y = 11 + 1 - 1 := by linear_combination 2*h1 + -3*h2 example (x y : ℤ) (h1 : 10 = 3*x + 2*y) (h2 : 3 = 2*x + 5*y) : 11 + 1 - 1 = -11*y := by linear_combination 2*h1 - 3*h2 /-! ### More complicated cases with two equations -/ example (x y : ℤ) (h1 : x + 2 = -3) (h2 : y = 10) : -y + 2*x + 4 = -16 := by linear_combination 2*h1 - h2 example (x y : ℚ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y + 1 = 11 + 1 := by linear_combination 2*h1 - 3*h2 example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) : b = 2 / 3 := by linear_combination ha/6 + hab/3 /-! ### Cases with more than 2 equations -/ example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) (hignore : 3 = a + b) : b = 2 / 3 := by linear_combination 1/6 * ha + 1/3 * hab + 0 * hignore example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : -3*x - 3*y - 4*z = 2 := by linear_combination ha - hb - 2*hc example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : 6*x = -10 := by linear_combination 1*ha + 4*hb - 3*hc example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : 10 = 6*-x := by linear_combination ha + 4*hb - 3*hc example (w x y z : ℝ) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5) (h3 : x + y + 5*z + 5*w = 3) : x + 2.2*y + 2*z - 5*w = -8.5 := by linear_combination 2*h1 + 1*h2 - 2*h3 example (w x y z : ℝ) (h1 : x + 2.1*y + 2*z = 2) (h2 : x + 8*z + 5*w = -6.5) (h3 : x + y + 5*z + 5*w = 3) : x + 2.2*y + 2*z - 5*w = -8.5 := by linear_combination 2*h1 + h2 - 2*h3 example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : 2*a - 3 + 9*c + 3*d = 8 - b + 3*d - 3*a := by linear_combination 2*h1 -1*h2 +3*h3 -3*h4 example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : 6 - 3*c + 3*a + 3*d = 2*b - d + 12 - 3*a := by linear_combination 2*h2 -h3 +3*h1 -3*h4 /-! ### Cases with non-hypothesis inputs -/ constants (qc : ℚ) (hqc : qc = 2*qc) example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by linear_combination 3 * h a b + hqc constant bad (q : ℚ) : q = 0 example (a b : ℚ) : a + b^3 = 0 := by linear_combination bad a + b * bad (b*b) /-! ### Cases with arbitrary coefficients -/ example (a b : ℤ) (h : a = b) : a * a = a * b := by linear_combination a*h example (a b c : ℤ) (h : a = b) : a * c = b * c := by linear_combination c*h example (a b c : ℤ) (h1 : a = b) (h2 : b = 1) : c * a + b = c * b + 1 := by linear_combination c*h1 + h2 example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : x*x*y + y*x*y + 6*x = 3*x*y + 14 := by linear_combination x*y*h1 + 2*h2 example {α} [h : comm_ring α] {a b c d e f : α} (h1 : a*d = b*c) (h2 : c*f = e*d) : c * (a*f - b*e) = 0 := by linear_combination e*h1 + a*h2 example (x y z w : ℚ) (hzw : z = w) : x*z + 2*y*z = x*w + 2*y*w := by linear_combination (x + 2*y)*hzw /-! ### Cases that explicitly use a linear_combination_config -/ example (x y : ℚ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y + 1 = 11 + 1 := by linear_combination 2*h1 -3*h2 with {normalization_tactic := `[ring]} example (x y : ℚ) (h1 : 3*x + 2*y = 10) (h2 : 2*x + 5*y = 3) : -11*y + 1 = 11 + 1 := by linear_combination 2*h1 + -3*h2 with {normalization_tactic := `[ring1]} example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) : b = 2 / 3 := by linear_combination 1/6*ha + 1/3*hab with {normalization_tactic := `[ring_nf]} example (x y : ℤ) (h1 : 3*x + 2*y = 10): 3*x + 2*y = 10 := by linear_combination h1 with {normalization_tactic := `[simp]} /-! ### Cases that have linear_combination skip normalization -/ example (a b : ℝ) (ha : 2*a = 4) (hab : 2*b = a - b) : b = 2 / 3 := begin linear_combination 1/6*ha + 1/3*hab with {normalize := ff}, linarith end example (x y : ℤ) (h1 : x = -3) (h2 : y = 10) : 2*x = -6 := begin linear_combination 2*h1 with {normalize := ff}, simp, norm_cast end /-! ### Cases without any arguments provided -/ -- the corner case is "just apply the normalization procedure". -- an empty `linear_combination` at the end of a declaration is a bad edge case for the parser. example {x y z w : ℤ} (h₁ : 3 * x = 4 + y) (h₂ : x + 2 * y = 1) : z + w = w + z := by linear_combination . -- this interacts as expected with options example {x y z w : ℤ} (h₁ : 3 * x = 4 + y) (h₂ : x + 2 * y = 1) : z + w = w + z := begin linear_combination with {normalize := ff}, guard_target' z + w - (w + z) - (0 - 0) = 0, simp [add_comm] end example {x y z w : ℤ} (h₁ : 3 * x = 4 + y) (h₂ : x + 2 * y = 1) : z + w = w + z := by linear_combination with {normalization_tactic := `[simp [add_comm]]} /-! ### Cases where the goal is not closed -/ example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : x*x*y + y*x*y + 6*x = 3*x*y + 14 := begin linear_combination x*y*h1 + h2, guard_target' (x * 3 - 7 = 0), linear_combination h2 end example (a b c d : ℚ) (h1 : a = 4) (h2 : 3 = b) (h3 : c*3 = d) (h4 : -d = a) : 6 - 3*c + 3*a + 3*d = 2*b - d + 12 - 3*a := begin linear_combination 2*h2, linear_combination -h3, linear_combination 3*h1, linear_combination -3*h4, end example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := begin linear_combination, linear_combination h1 - 2 * h2, end /-! ### Cases that should fail -/ -- This should fail because the second coefficient has a different type than -- the equations it is being combined with. This was a design choice for the -- sake of simplicity, but the tactic could potentially be modified to allow -- this behavior. example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y + 2*x = 1 := begin success_if_fail_with_msg {linear_combination h1 + (0 : ℝ) * h2} "invalid type ascription, term has type ℝ but is expected to have type ℤ", linear_combination h1 end -- This fails because the linear_combination tactic requires the equations -- and coefficients to use a type that fulfills the add_group condition, -- and ℕ does not. example (a b : ℕ) (h1 : a = 3) : a = 3 := begin success_if_fail {linear_combination h1}, exact h1 end example (a b : ℤ) (x y : ℝ) (hab : a = b) (hxy : x = y) : 2*x = 2*y := begin success_if_fail_with_msg {linear_combination 2*hab} "hab is an equality between terms of type ℤ, but is expected to be between terms of type ℝ", linear_combination 2*hxy end
339cdb9708fc06168c59ced478ad51b446cebc4d
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_lean_summary/unnamed_339.lean
104ed8f909f86bbbe58e55002cad9fe72066b7f7
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
75
lean
variables p q : Prop -- BEGIN example (h : p) : p ∨ q := or.inl h -- END
6494984815f3551a831ea2d22766611da36764bd
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/group_theory/coset.lean
4d0c85fd7aee2587cd06c7b6878998f03fd9b424
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,735
lean
/- Copyright (c) 2018 Mitchell Rowett. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mitchell Rowett, Scott Morrison -/ import group_theory.subgroup /-! # Cosets This file develops the basic theory of left and right cosets. ## Main definitions * `left_coset a s`: the left coset `a * s` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `left_add_coset a s`. * `right_coset s a`: the right coset `s * a` for an element `a : α` and a subset `s ⊆ α`, for an `add_group` this is `right_add_coset s a`. * `quotient_group.quotient s`: the quotient type representing the left cosets with respect to a subgroup `s`, for an `add_group` this is `quotient_add_group.quotient s`. * `quotient_group.mk`: the canonical map from `α` to `α/s` for a subgroup `s` of `α`, for an `add_group` this is `quotient_add_group.mk`. * `subgroup.left_coset_equiv_subgroup`: the natural bijection between a left coset and the subgroup, for an `add_group` this is `add_subgroup.left_coset_equiv_add_subgroup`. ## Notation * `a *l s`: for `left_coset a s`. * `a +l s`: for `left_add_coset a s`. * `s *r a`: for `right_coset s a`. * `s +r a`: for `right_add_coset s a`. ## TODO Add `to_additive` to `preimage_mk_equiv_subgroup_times_set`. -/ open set function variable {α : Type*} /-- The left coset `a * s` for an element `a : α` and a subset `s : set α` -/ @[to_additive left_add_coset "The left coset `a+s` for an element `a : α` and a subset `s : set α`"] def left_coset [has_mul α] (a : α) (s : set α) : set α := (λ x, a * x) '' s /-- The right coset `s * a` for an element `a : α` and a subset `s : set α` -/ @[to_additive right_add_coset "The right coset `s+a` for an element `a : α` and a subset `s : set α`"] def right_coset [has_mul α] (s : set α) (a : α) : set α := (λ x, x * a) '' s localized "infix ` *l `:70 := left_coset" in coset localized "infix ` +l `:70 := left_add_coset" in coset localized "infix ` *r `:70 := right_coset" in coset localized "infix ` +r `:70 := right_add_coset" in coset section coset_mul variable [has_mul α] @[to_additive mem_left_add_coset] lemma mem_left_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : a * x ∈ a *l s := mem_image_of_mem (λ b : α, a * b) hxS @[to_additive mem_right_add_coset] lemma mem_right_coset {s : set α} {x : α} (a : α) (hxS : x ∈ s) : x * a ∈ s *r a := mem_image_of_mem (λ b : α, b * a) hxS /-- Equality of two left cosets `a * s` and `b * s`. -/ @[to_additive left_add_coset_equivalence "Equality of two left cosets `a + s` and `b + s`."] def left_coset_equivalence (s : set α) (a b : α) := a *l s = b *l s @[to_additive left_add_coset_equivalence_rel] lemma left_coset_equivalence_rel (s : set α) : equivalence (left_coset_equivalence s) := mk_equivalence (left_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) /-- Equality of two right cosets `s * a` and `s * b`. -/ @[to_additive right_add_coset_equivalence "Equality of two right cosets `s + a` and `s + b`."] def right_coset_equivalence (s : set α) (a b : α) := s *r a = s *r b @[to_additive right_add_coset_equivalence_rel] lemma right_coset_equivalence_rel (s : set α) : equivalence (right_coset_equivalence s) := mk_equivalence (right_coset_equivalence s) (λ a, rfl) (λ a b, eq.symm) (λ a b c, eq.trans) end coset_mul section coset_semigroup variable [semigroup α] @[simp] lemma left_coset_assoc (s : set α) (a b : α) : a *l (b *l s) = (a * b) *l s := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive left_add_coset_assoc] left_coset_assoc @[simp] lemma right_coset_assoc (s : set α) (a b : α) : s *r a *r b = s *r (a * b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] attribute [to_additive right_add_coset_assoc] right_coset_assoc @[to_additive left_add_coset_right_add_coset] lemma left_coset_right_coset (s : set α) (a b : α) : a *l s *r b = a *l (s *r b) := by simp [left_coset, right_coset, (image_comp _ _ _).symm, function.comp, mul_assoc] end coset_semigroup section coset_monoid variables [monoid α] (s : set α) @[simp] lemma one_left_coset : 1 *l s = s := set.ext $ by simp [left_coset] attribute [to_additive zero_left_add_coset] one_left_coset @[simp] lemma right_coset_one : s *r 1 = s := set.ext $ by simp [right_coset] attribute [to_additive right_add_coset_zero] right_coset_one end coset_monoid section coset_submonoid open submonoid variables [monoid α] (s : submonoid α) @[to_additive mem_own_left_add_coset] lemma mem_own_left_coset (a : α) : a ∈ a *l s := suffices a * 1 ∈ a *l s, by simpa, mem_left_coset a (one_mem s) @[to_additive mem_own_right_add_coset] lemma mem_own_right_coset (a : α) : a ∈ (s : set α) *r a := suffices 1 * a ∈ (s : set α) *r a, by simpa, mem_right_coset a (one_mem s) @[to_additive mem_left_add_coset_left_add_coset] lemma mem_left_coset_left_coset {a : α} (ha : a *l s = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_left_coset s a @[to_additive mem_right_add_coset_right_add_coset] lemma mem_right_coset_right_coset {a : α} (ha : (s : set α) *r a = s) : a ∈ s := by rw [←set_like.mem_coe, ←ha]; exact mem_own_right_coset s a end coset_submonoid section coset_group variables [group α] {s : set α} {x : α} @[to_additive mem_left_add_coset_iff] lemma mem_left_coset_iff (a : α) : x ∈ a *l s ↔ a⁻¹ * x ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨a⁻¹ * x, h, by simp⟩) @[to_additive mem_right_add_coset_iff] lemma mem_right_coset_iff (a : α) : x ∈ s *r a ↔ x * a⁻¹ ∈ s := iff.intro (assume ⟨b, hb, eq⟩, by simp [eq.symm, hb]) (assume h, ⟨x * a⁻¹, h, by simp⟩) end coset_group section coset_subgroup open subgroup variables [group α] (s : subgroup α) @[to_additive left_add_coset_mem_left_add_coset] lemma left_coset_mem_left_coset {a : α} (ha : a ∈ s) : a *l s = s := set.ext $ by simp [mem_left_coset_iff, mul_mem_cancel_left s (s.inv_mem ha)] @[to_additive right_add_coset_mem_right_add_coset] lemma right_coset_mem_right_coset {a : α} (ha : a ∈ s) : (s : set α) *r a = s := set.ext $ assume b, by simp [mem_right_coset_iff, mul_mem_cancel_right s (s.inv_mem ha)] @[to_additive eq_add_cosets_of_normal] theorem eq_cosets_of_normal (N : s.normal) (g : α) : g *l s = s *r g := set.ext $ assume a, by simp [mem_left_coset_iff, mem_right_coset_iff]; rw [N.mem_comm_iff] @[to_additive normal_of_eq_add_cosets] theorem normal_of_eq_cosets (h : ∀ g : α, g *l s = s *r g) : s.normal := ⟨assume a ha g, show g * a * g⁻¹ ∈ (s : set α), by rw [← mem_right_coset_iff, ← h]; exact mem_left_coset g ha⟩ @[to_additive normal_iff_eq_add_cosets] theorem normal_iff_eq_cosets : s.normal ↔ ∀ g : α, g *l s = s *r g := ⟨@eq_cosets_of_normal _ _ s, normal_of_eq_cosets s⟩ @[to_additive left_add_coset_eq_iff] lemma left_coset_eq_iff {x y : α} : left_coset x s = left_coset y s ↔ x⁻¹ * y ∈ s := begin rw set.ext_iff, simp_rw [mem_left_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_left_inv, exact s.one_mem }, { intros h z, rw ←mul_inv_cancel_right x⁻¹ y, rw mul_assoc, exact s.mul_mem_cancel_left h }, end @[to_additive right_add_coset_eq_iff] lemma right_coset_eq_iff {x y : α} : right_coset ↑s x = right_coset s y ↔ y * x⁻¹ ∈ s := begin rw set.ext_iff, simp_rw [mem_right_coset_iff, set_like.mem_coe], split, { intro h, apply (h y).mpr, rw mul_right_inv, exact s.one_mem }, { intros h z, rw ←inv_mul_cancel_left y x⁻¹, rw ←mul_assoc, exact s.mul_mem_cancel_right h }, end end coset_subgroup run_cmd to_additive.map_namespace `quotient_group `quotient_add_group namespace quotient_group variables [group α] (s : subgroup α) /-- The equivalence relation corresponding to the partition of a group by left cosets of a subgroup.-/ @[to_additive "The equivalence relation corresponding to the partition of a group by left cosets of a subgroup."] def left_rel : setoid α := ⟨λ x y, x⁻¹ * y ∈ s, by { simp_rw ←left_coset_eq_iff, exact left_coset_equivalence_rel s }⟩ lemma left_rel_r_eq_left_coset_equivalence : @setoid.r _ (quotient_group.left_rel s) = left_coset_equivalence s := by { ext, exact (left_coset_eq_iff s).symm } @[to_additive] instance left_rel_decidable [decidable_pred (∈ s)] : decidable_rel (left_rel s).r := λ x y, ‹decidable_pred (∈ s)› _ /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient : Type* := quotient (left_rel s) /-- The equivalence relation corresponding to the partition of a group by right cosets of a subgroup. -/ @[to_additive "The equivalence relation corresponding to the partition of a group by right cosets of a subgroup."] def right_rel : setoid α := ⟨λ x y, y * x⁻¹ ∈ s, by { simp_rw ←right_coset_eq_iff, exact right_coset_equivalence_rel s }⟩ lemma right_rel_r_eq_right_coset_equivalence : @setoid.r _ (quotient_group.right_rel s) = right_coset_equivalence s := by { ext, exact (right_coset_eq_iff s).symm } @[to_additive] instance right_rel_decidable [decidable_pred (∈ s)] : decidable_rel (right_rel s).r := λ x y, ‹decidable_pred (∈ s)› _ end quotient_group namespace quotient_add_group /-- `quotient s` is the quotient type representing the left cosets of `s`. If `s` is a normal subgroup, `quotient s` is a group -/ def quotient [add_group α] (s : add_subgroup α) : Type* := quotient (left_rel s) end quotient_add_group attribute [to_additive quotient_add_group.quotient] quotient_group.quotient namespace quotient_group variables [group α] {s : subgroup α} @[to_additive] instance fintype [fintype α] (s : subgroup α) [decidable_rel (left_rel s).r] : fintype (quotient_group.quotient s) := quotient.fintype (left_rel s) /-- The canonical map from a group `α` to the quotient `α/s`. -/ @[to_additive "The canonical map from an `add_group` `α` to the quotient `α/s`."] abbreviation mk (a : α) : quotient s := quotient.mk' a @[elab_as_eliminator, to_additive] lemma induction_on {C : quotient s → Prop} (x : quotient s) (H : ∀ z, C (quotient_group.mk z)) : C x := quotient.induction_on' x H @[to_additive] instance : has_coe_t α (quotient s) := ⟨mk⟩ -- note [use has_coe_t] @[elab_as_eliminator, to_additive] lemma induction_on' {C : quotient s → Prop} (x : quotient s) (H : ∀ z : α, C z) : C x := quotient.induction_on' x H @[to_additive] instance (s : subgroup α) : inhabited (quotient s) := ⟨((1 : α) : quotient s)⟩ @[to_additive quotient_add_group.eq] protected lemma eq {a b : α} : (a : quotient s) = b ↔ a⁻¹ * b ∈ s := quotient.eq' @[to_additive] lemma eq_class_eq_left_coset (s : subgroup α) (g : α) : {x : α | (x : quotient s) = g} = left_coset g s := set.ext $ λ z, by rw [mem_left_coset_iff, set.mem_set_of_eq, eq_comm, quotient_group.eq, set_like.mem_coe] @[to_additive] lemma preimage_image_coe (N : subgroup α) (s : set α) : coe ⁻¹' ((coe : α → quotient N) '' s) = ⋃ x : N, (λ y : α, y * x) ⁻¹' s := begin ext x, simp only [quotient_group.eq, set_like.exists, exists_prop, set.mem_preimage, set.mem_Union, set.mem_image, subgroup.coe_mk, ← eq_inv_mul_iff_mul_eq], exact ⟨λ ⟨y, hs, hN⟩, ⟨_, N.inv_mem hN, by simpa using hs⟩, λ ⟨z, hz, hxz⟩, ⟨x*z, hxz, by simpa using hz⟩⟩, end end quotient_group namespace subgroup open quotient_group variables [group α] {s : subgroup α} /-- The natural bijection between a left coset `g * s` and `s`. -/ @[to_additive "The natural bijection between the cosets `g + s` and `s`."] def left_coset_equiv_subgroup (g : α) : left_coset g s ≃ s := ⟨λ x, ⟨g⁻¹ * x.1, (mem_left_coset_iff _).1 x.2⟩, λ x, ⟨g * x.1, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- The natural bijection between a right coset `s * g` and `s`. -/ @[to_additive "The natural bijection between the cosets `s + g` and `s`."] def right_coset_equiv_subgroup (g : α) : right_coset ↑s g ≃ s := ⟨λ x, ⟨x.1 * g⁻¹, (mem_right_coset_iff _).1 x.2⟩, λ x, ⟨x.1 * g, x.1, x.2, rfl⟩, λ ⟨x, hx⟩, subtype.eq $ by simp, λ ⟨g, hg⟩, subtype.eq $ by simp⟩ /-- A (non-canonical) bijection between a group `α` and the product `(α/s) × s` -/ @[to_additive "A (non-canonical) bijection between an add_group `α` and the product `(α/s) × s`"] noncomputable def group_equiv_quotient_times_subgroup : α ≃ quotient s × s := calc α ≃ Σ L : quotient s, {x : α // (x : quotient s) = L} : (equiv.sigma_preimage_equiv quotient_group.mk).symm ... ≃ Σ L : quotient s, left_coset (quotient.out' L) s : equiv.sigma_congr_right (λ L, begin rw ← eq_class_eq_left_coset, show _root_.subtype (λ x : α, quotient.mk' x = L) ≃ _root_.subtype (λ x : α, quotient.mk' x = quotient.mk' _), simp [-quotient.eq'], end) ... ≃ Σ L : quotient s, s : equiv.sigma_congr_right (λ L, left_coset_equiv_subgroup _) ... ≃ quotient s × s : equiv.sigma_equiv_prod _ _ lemma card_eq_card_quotient_mul_card_subgroup [fintype α] (s : subgroup α) [fintype s] [decidable_pred (λ a, a ∈ s)] : fintype.card α = fintype.card (quotient s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (subgroup.group_equiv_quotient_times_subgroup) /-- **Order of a Subgroup** -/ lemma card_subgroup_dvd_card [fintype α] (s : subgroup α) [fintype s] : fintype.card s ∣ fintype.card α := by haveI := classical.prop_decidable; simp [card_eq_card_quotient_mul_card_subgroup s] lemma card_quotient_dvd_card [fintype α] (s : subgroup α) [decidable_pred (λ a, a ∈ s)] [fintype s] : fintype.card (quotient s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s] end subgroup namespace quotient_group variables [group α] -- FIXME -- why is there no `to_additive`? /-- If `s` is a subgroup of the group `α`, and `t` is a subset of `α/s`, then there is a (typically non-canonical) bijection between the preimage of `t` in `α` and the product `s × t`. -/ noncomputable def preimage_mk_equiv_subgroup_times_set (s : subgroup α) (t : set (quotient s)) : quotient_group.mk ⁻¹' t ≃ s × t := have h : ∀ {x : quotient s} {a : α}, x ∈ t → a ∈ s → (quotient.mk' (quotient.out' x * a) : quotient s) = quotient.mk' (quotient.out' x) := λ x a hx ha, quotient.sound' (show (quotient.out' x * a)⁻¹ * quotient.out' x ∈ s, from (s.inv_mem_iff).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out' (quotient.mk' a))⁻¹ * a, @quotient.exact' _ (left_rel s) _ _ $ (quotient.out_eq' _)⟩, ⟨quotient.mk' a, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨quotient.out' x * a, show quotient.mk' _ ∈ t, by simp [h hx ha, hx]⟩, left_inv := λ ⟨a, ha⟩, subtype.eq $ show _ * _ = a, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, show (_, _) = _, by simp [h hx ha] } end quotient_group /-- We use the class `has_coe_t` instead of `has_coe` if the first argument is a variable, or if the second argument is a variable not occurring in the first. Using `has_coe` would cause looping of type-class inference. See <https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/remove.20all.20instances.20with.20variable.20domain> -/ library_note "use has_coe_t"
1a1f671a1661da9f83c9dd472dbe466bdaf32780
137c667471a40116a7afd7261f030b30180468c2
/archive/100-theorems-list/82_cubing_a_cube.lean
7ba962329e64ffed679be3a59df89468058ed8e8
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,634
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import data.real.basic import data.set.disjointed import data.set.intervals import set_theory.cardinal /-! Proof that a cube (in dimension n ≥ 3) cannot be cubed: There does not exist a partition of a cube into finitely many smaller cubes (at least two) of different sizes. We follow the proof described here: http://www.alaricstephen.com/main-featured/2017/9/28/cubing-a-cube-proof -/ open real set function fin noncomputable theory variable {n : ℕ} /-- Given three intervals `I, J, K` such that `J ⊂ I`, neither endpoint of `J` coincides with an endpoint of `I`, `¬ (K ⊆ J)` and `K` does not lie completely to the left nor completely to the right of `J`. Then `I ∩ K \ J` is nonempty. -/ lemma Ico_lemma {α} [linear_order α] {x₁ x₂ y₁ y₂ z₁ z₂ w : α} (h₁ : x₁ < y₁) (hy : y₁ < y₂) (h₂ : y₂ < x₂) (hz₁ : z₁ ≤ y₂) (hz₂ : y₁ ≤ z₂) (hw : w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂) : ∃w, w ∈ Ico x₁ x₂ ∧ w ∉ Ico y₁ y₂ ∧ w ∈ Ico z₁ z₂ := begin simp only [not_and, not_lt, mem_Ico] at hw, refine ⟨max x₁ (min w y₂), _, _, _⟩, { simp [le_refl, lt_trans h₁ (lt_trans hy h₂), h₂] }, { simp [hw, lt_irrefl, not_le_of_lt h₁] {contextual := tt} }, { simp [hw.2.1, hw.2.2, hz₁, lt_of_lt_of_le h₁ hz₂] at ⊢ } end /-- A (hyper)-cube (in standard orientation) is a vector `b` consisting of the bottom-left point of the cube, a width `w` and a proof that `w > 0`. We use functions from `fin n` to denote vectors. -/ structure cube (n : ℕ) : Type := (b : fin n → ℝ) -- bottom-left coordinate (w : ℝ) -- width (hw : 0 < w) namespace cube lemma hw' (c : cube n) : 0 ≤ c.w := le_of_lt c.hw /-- The j-th side of a cube is the half-open interval `[b j, b j + w)` -/ def side (c : cube n) (j : fin n) : set ℝ := Ico (c.b j) (c.b j + c.w) @[simp] lemma b_mem_side (c : cube n) (j : fin n) : c.b j ∈ c.side j := by simp [side, cube.hw, le_refl] def to_set (c : cube n) : set (fin n → ℝ) := { x | ∀j, x j ∈ side c j } def to_set_subset {c c' : cube n} : c.to_set ⊆ c'.to_set ↔ ∀j, c.side j ⊆ c'.side j := begin split, intros h j x hx, let f : fin n → ℝ := λ j', if j' = j then x else c.b j', have : f ∈ c.to_set, { intro j', by_cases hj' : j' = j; simp [f, hj', if_pos, if_neg, hx] }, convert h this j, { simp [f, if_pos] }, intros h f hf j, exact h j (hf j) end def to_set_disjoint {c c' : cube n} : disjoint c.to_set c'.to_set ↔ ∃j, disjoint (c.side j) (c'.side j) := begin split, intros h, classical, by_contra h', simp only [not_disjoint_iff, classical.skolem, not_exists] at h', cases h' with f hf, apply not_disjoint_iff.mpr ⟨f, _, _⟩ h; intro j, exact (hf j).1, exact (hf j).2, rintro ⟨j, hj⟩, rw [set.disjoint_iff], rintros f ⟨h1f, h2f⟩, apply not_disjoint_iff.mpr ⟨f j, h1f j, h2f j⟩ hj end lemma b_mem_to_set (c : cube n) : c.b ∈ c.to_set := by simp [to_set] protected def tail (c : cube (n+1)) : cube n := ⟨tail c.b, c.w, c.hw⟩ lemma side_tail (c : cube (n+1)) (j : fin n) : c.tail.side j = c.side j.succ := rfl def bottom (c : cube (n+1)) : set (fin (n+1) → ℝ) := { x | x 0 = c.b 0 ∧ tail x ∈ c.tail.to_set } lemma b_mem_bottom (c : cube (n+1)) : c.b ∈ c.bottom := by simp [bottom, to_set, side, cube.hw, le_refl, cube.tail] def xm (c : cube (n+1)) : ℝ := c.b 0 + c.w lemma b_lt_xm (c : cube (n+1)) : c.b 0 < c.xm := by simp [xm, hw] lemma b_ne_xm (c : cube (n+1)) : c.b 0 ≠ c.xm := ne_of_lt c.b_lt_xm def shift_up (c : cube (n+1)) : cube (n+1) := ⟨cons c.xm $ tail c.b, c.w, c.hw⟩ @[simp] lemma tail_shift_up (c : cube (n+1)) : c.shift_up.tail = c.tail := by simp [shift_up, cube.tail] @[simp] lemma head_shift_up (c : cube (n+1)) : c.shift_up.b 0 = c.xm := rfl def unit_cube : cube n := ⟨λ _, 0, 1, by norm_num⟩ @[simp] lemma side_unit_cube {j : fin n} : unit_cube.side j = Ico 0 1 := by norm_num [unit_cube, side] end cube open cube variables {ι : Type} [fintype ι] {cs : ι → cube (n+1)} {i i' : ι} /-- A finite family of (at least 2) cubes partitioning the unit cube with different sizes -/ def correct (cs : ι → cube n) : Prop := pairwise (disjoint on (cube.to_set ∘ cs)) ∧ (⋃(i : ι), (cs i).to_set) = unit_cube.to_set ∧ injective (cube.w ∘ cs) ∧ 2 ≤ cardinal.mk ι ∧ 3 ≤ n variable (h : correct cs) include h lemma to_set_subset_unit_cube {i} : (cs i).to_set ⊆ unit_cube.to_set := by { rw [←h.2.1], exact subset_Union _ i } lemma side_subset {i j} : (cs i).side j ⊆ Ico 0 1 := by { have := to_set_subset_unit_cube h, rw [to_set_subset] at this, convert this j, norm_num [unit_cube] } lemma zero_le_of_mem_side {i j x} (hx : x ∈ (cs i).side j) : 0 ≤ x := (side_subset h hx).1 lemma zero_le_of_mem {i p} (hp : p ∈ (cs i).to_set) (j) : 0 ≤ p j := zero_le_of_mem_side h (hp j) lemma zero_le_b {i j} : 0 ≤ (cs i).b j := zero_le_of_mem h (cs i).b_mem_to_set j lemma b_add_w_le_one {j} : (cs i).b j + (cs i).w ≤ 1 := by { have := side_subset h, rw [side, Ico_subset_Ico_iff] at this, convert this.2, simp [hw] } /-- The width of any cube in the partition cannot be 1. -/ lemma w_ne_one (i : ι) : (cs i).w ≠ 1 := begin intro hi, have := h.2.2.2.1, rw [cardinal.two_le_iff' i] at this, cases this with i' hi', let p := (cs i').b, have hp : p ∈ (cs i').to_set := (cs i').b_mem_to_set, have h2p : p ∈ (cs i).to_set, { intro j, split, transitivity (0 : ℝ), { rw [←add_le_add_iff_right (1 : ℝ)], convert b_add_w_le_one h, rw hi, rw zero_add }, apply zero_le_b h, apply lt_of_lt_of_le (side_subset h $ (cs i').b_mem_side j).2, simp [hi, zero_le_b h] }, apply not_disjoint_iff.mpr ⟨p, hp, h2p⟩, apply h.1, exact hi'.symm end /-- The top of a cube (which is the bottom of the cube shifted up by its width) must be covered by bottoms of (other) cubes in the family. -/ lemma shift_up_bottom_subset_bottoms (hc : (cs i).xm ≠ 1) : (cs i).shift_up.bottom ⊆ ⋃(i : ι), (cs i).bottom := begin intros p hp, cases hp with hp0 hps, rw [tail_shift_up] at hps, have : p ∈ (unit_cube : cube (n+1)).to_set, { simp only [to_set, forall_fin_succ, hp0, side_unit_cube, mem_set_of_eq, mem_Ico, head_shift_up], refine ⟨⟨_, _⟩, _⟩, { rw [←zero_add (0 : ℝ)], apply add_le_add, apply zero_le_b h, apply (cs i).hw' }, { exact lt_of_le_of_ne (b_add_w_le_one h) hc }, intro j, exact side_subset h (hps j) }, rw [←h.2.1] at this, rcases this with ⟨_, ⟨i', rfl⟩, hi'⟩, rw [mem_Union], use i', refine ⟨_, λ j, hi' j.succ⟩, have : i ≠ i', { rintro rfl, apply not_le_of_lt (hi' 0).2, rw [hp0], refl }, have := h.1 i i' this, rw [on_fun, to_set_disjoint, exists_fin_succ] at this, rcases this with h0|⟨j, hj⟩, rw [hp0], symmetry, apply eq_of_Ico_disjoint h0 (by simp [hw]) _, convert hi' 0, rw [hp0], refl, exfalso, apply not_disjoint_iff.mpr ⟨tail p j, hps j, hi' j.succ⟩ hj end omit h /-- A valley is a square on which cubes in the family of cubes are placed, so that the cubes completely cover the valley and none of those cubes is partially outside the square. We also require that no cube on it has the same size as the valley (so that there are at least two cubes on the valley). This is the main concept in the formalization. We prove that the smallest cube on a valley has another valley on the top of it, which gives an infinite sequence of cubes in the partition, which contradicts the finiteness. A valley is characterized by a cube `c` (which is not a cube in the family cs) by considering the bottom face of `c`. -/ def valley (cs : ι → cube (n+1)) (c : cube (n+1)) : Prop := c.bottom ⊆ (⋃(i : ι), (cs i).bottom) ∧ (∀i, (cs i).b 0 = c.b 0 → (∃x, x ∈ (cs i).tail.to_set ∩ c.tail.to_set) → (cs i).tail.to_set ⊆ c.tail.to_set) ∧ ∀(i : ι), (cs i).b 0 = c.b 0 → (cs i).w ≠ c.w variables {c : cube (n+1)} (v : valley cs c) /-- The bottom of the unit cube is a valley -/ lemma valley_unit_cube (h : correct cs) : valley cs unit_cube := begin refine ⟨_, _, _⟩, { intro v, simp only [bottom, and_imp, mem_Union, mem_set_of_eq], intros h0 hv, have : v ∈ (unit_cube : cube (n+1)).to_set, { dsimp only [to_set, unit_cube, mem_set_of_eq], rw [forall_fin_succ, h0], split, norm_num [side, unit_cube], exact hv }, rw [←h.2.1] at this, rcases this with ⟨_, ⟨i, rfl⟩, hi⟩, use i, split, { apply le_antisymm, rw h0, exact zero_le_b h, exact (hi 0).1 }, intro j, exact hi _ }, { intros i hi h', rw to_set_subset, intro j, convert side_subset h using 1, simp [side_tail] }, { intros i hi, exact w_ne_one h i } end /-- the cubes which lie in the valley `c` -/ def bcubes (cs : ι → cube (n+1)) (c : cube (n+1)) : set ι := { i : ι | (cs i).b 0 = c.b 0 ∧ (cs i).tail.to_set ⊆ c.tail.to_set } /-- A cube which lies on the boundary of a valley in dimension `j` -/ def on_boundary (hi : i ∈ bcubes cs c) (j : fin n) : Prop := c.b j.succ = (cs i).b j.succ ∨ (cs i).b j.succ + (cs i).w = c.b j.succ + c.w lemma tail_sub (hi : i ∈ bcubes cs c) : ∀j, (cs i).tail.side j ⊆ c.tail.side j := by { rw [←to_set_subset], exact hi.2 } lemma bottom_mem_side (hi : i ∈ bcubes cs c) : c.b 0 ∈ (cs i).side 0 := by { convert b_mem_side (cs i) _ using 1, rw hi.1 } lemma b_le_b (hi : i ∈ bcubes cs c) (j : fin n) : c.b j.succ ≤ (cs i).b j.succ := (tail_sub hi j $ b_mem_side _ _).1 lemma t_le_t (hi : i ∈ bcubes cs c) (j : fin n) : (cs i).b j.succ + (cs i).w ≤ c.b j.succ + c.w := begin have h' := tail_sub hi j, dsimp only [side] at h', rw [Ico_subset_Ico_iff] at h', exact h'.2, simp [hw] end include h v /-- Every cube in the valley must be smaller than it -/ lemma w_lt_w (hi : i ∈ bcubes cs c) : (cs i).w < c.w := begin apply lt_of_le_of_ne _ (v.2.2 i hi.1), have j : fin n := ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩, rw [←add_le_add_iff_left ((cs i).b j.succ)], apply le_trans (t_le_t hi j), rw [add_le_add_iff_right], apply b_le_b hi, end open cardinal /-- There are at least two cubes in a valley -/ lemma two_le_mk_bcubes : 2 ≤ cardinal.mk (bcubes cs c) := begin rw [two_le_iff], rcases v.1 c.b_mem_bottom with ⟨_, ⟨i, rfl⟩, hi⟩, have h2i : i ∈ bcubes cs c := ⟨hi.1.symm, v.2.1 i hi.1.symm ⟨tail c.b, hi.2, λ j, c.b_mem_side j.succ⟩⟩, let j : fin (n+1) := ⟨2, h.2.2.2.2⟩, have hj : 0 ≠ j := by { simp only [fin.ext_iff, ne.def], contradiction }, let p : fin (n+1) → ℝ := λ j', if j' = j then c.b j + (cs i).w else c.b j', have hp : p ∈ c.bottom, { split, { simp only [bottom, p, if_neg hj] }, intro j', simp only [tail, side_tail], by_cases hj' : j'.succ = j, { simp [p, -add_comm, if_pos, side, hj', hw', w_lt_w h v h2i] }, { simp [p, -add_comm, if_neg hj'] }}, rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩, have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩, refine ⟨⟨i, h2i⟩, ⟨i', h2i'⟩, _⟩, intro hii', cases congr_arg subtype.val hii', apply not_le_of_lt (hi'.2 ⟨1, nat.le_of_succ_le_succ h.2.2.2.2⟩).2, simp only [-add_comm, tail, cube.tail, p], rw [if_pos, add_le_add_iff_right], { exact (hi.2 _).1 }, refl end /-- There is a cube in the valley -/ lemma nonempty_bcubes : (bcubes cs c).nonempty := begin rw [←set.ne_empty_iff_nonempty], intro h', have := two_le_mk_bcubes h v, rw h' at this, apply not_lt_of_le this, rw mk_emptyc, norm_cast, norm_num end /-- There is a smallest cube in the valley -/ lemma exists_mi : ∃(i : ι), i ∈ bcubes cs c ∧ ∀(i' ∈ bcubes cs c), (cs i).w ≤ (cs i').w := by simpa using (bcubes cs c).exists_min_image (λ i, (cs i).w) (finite.of_fintype _) (nonempty_bcubes h v) /-- We let `mi` be the (index for the) smallest cube in the valley `c` -/ def mi : ι := classical.some $ exists_mi h v variables {h v} lemma mi_mem_bcubes : mi h v ∈ bcubes cs c := (classical.some_spec $ exists_mi h v).1 lemma mi_minimal (hi : i ∈ bcubes cs c) : (cs $ mi h v).w ≤ (cs i).w := (classical.some_spec $ exists_mi h v).2 i hi lemma mi_strict_minimal (hii' : mi h v ≠ i) (hi : i ∈ bcubes cs c) : (cs $ mi h v).w < (cs i).w := by { apply lt_of_le_of_ne (mi_minimal hi), apply h.2.2.1.ne, apply hii' } /-- The top of `mi` cannot be 1, since there is a larger cube in the valley -/ lemma mi_xm_ne_one : (cs $ mi h v).xm ≠ 1 := begin apply ne_of_lt, rcases (two_le_iff' _).mp (two_le_mk_bcubes h v) with ⟨⟨i, hi⟩, h2i⟩, swap, exact ⟨mi h v, mi_mem_bcubes⟩, apply lt_of_lt_of_le _ (b_add_w_le_one h), exact i, exact 0, rw [xm, mi_mem_bcubes.1, hi.1, _root_.add_lt_add_iff_left], apply mi_strict_minimal _ hi, intro h', apply h2i, rw subtype.ext_iff_val, exact h' end /-- If `mi` lies on the boundary of the valley in dimension j, then this lemma expresses that all other cubes on the same boundary extend further from the boundary. More precisely, there is a j-th coordinate `x : ℝ` in the valley, but not in `mi`, such that every cube that shares a (particular) j-th coordinate with `mi` also contains j-th coordinate `x` -/ lemma smallest_on_boundary {j} (bi : on_boundary (mi_mem_bcubes : mi h v ∈ _) j) : ∃(x : ℝ), x ∈ c.side j.succ \ (cs $ mi h v).side j.succ ∧ ∀{{i'}} (hi' : i' ∈ bcubes cs c), i' ≠ mi h v → (cs $ mi h v).b j.succ ∈ (cs i').side j.succ → x ∈ (cs i').side j.succ := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, cases bi, { refine ⟨(cs i).b j.succ + (cs i).w, ⟨_, _⟩, _⟩, { simp [side, bi, hw', w_lt_w h v hi] }, { intro h', simpa [i, lt_irrefl] using h'.2 }, intros i' hi' i'_i h2i', split, apply le_trans h2i'.1, { simp [hw'] }, apply lt_of_lt_of_le (add_lt_add_left (mi_strict_minimal i'_i.symm hi') _), simp [bi.symm, b_le_b hi'] }, let s := bcubes cs c \ { i }, have hs : s.nonempty, { rcases (two_le_iff' (⟨i, hi⟩ : bcubes cs c)).mp (two_le_mk_bcubes h v) with ⟨⟨i', hi'⟩, h2i'⟩, refine ⟨i', hi', _⟩, simp only [mem_singleton_iff], intro h, apply h2i', simp [h] }, rcases set.exists_min_image s (w ∘ cs) (finite.of_fintype _) hs with ⟨i', ⟨hi', h2i'⟩, h3i'⟩, rw [mem_singleton_iff] at h2i', let x := c.b j.succ + c.w - (cs i').w, have hx : x < (cs i).b j.succ, { dsimp only [x], rw [←bi, add_sub_assoc, add_lt_iff_neg_left, sub_lt_zero], apply mi_strict_minimal (ne.symm h2i') hi' }, refine ⟨x, ⟨_, _⟩, _⟩, { simp only [side, x, -add_comm, -add_assoc, neg_lt_zero, hw, add_lt_iff_neg_left, and_true, mem_Ico, sub_eq_add_neg], rw [add_assoc, le_add_iff_nonneg_right, ←sub_eq_add_neg, sub_nonneg], apply le_of_lt (w_lt_w h v hi') }, { simp only [side, not_and_distrib, not_lt, add_comm, not_le, mem_Ico], left, exact hx }, intros i'' hi'' h2i'' h3i'', split, swap, apply lt_trans hx h3i''.2, simp only [x], rw [le_sub_iff_add_le], refine le_trans _ (t_le_t hi'' j), rw [add_le_add_iff_left], apply h3i' i'' ⟨hi'', _⟩, simp [mem_singleton, h2i''] end variables (h v) /-- `mi` cannot lie on the boundary of the valley. Otherwise, the cube adjacent to it in the `j`-th direction will intersect one of the neighbouring cubes on the same boundary as `mi`. -/ lemma mi_not_on_boundary (j : fin n) : ¬on_boundary (mi_mem_bcubes : mi h v ∈ _) j := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, rcases (two_le_iff' j).mp _ with ⟨j', hj'⟩, swap, { rw [mk_fin, ←nat.cast_two, nat_cast_le], apply nat.le_of_succ_le_succ h.2.2.2.2 }, intro hj, rcases smallest_on_boundary hj with ⟨x, ⟨hx, h2x⟩, h3x⟩, let p : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j then x else (cs i).b j₂.succ), have hp : p ∈ c.bottom, { suffices : ∀ (j' : fin n), ite (j' = j) x ((cs i).b j'.succ) ∈ c.side j'.succ, { simpa [bottom, p, to_set, tail, side_tail] }, intro j₂, by_cases hj₂ : j₂ = j, { simp [hj₂, hx] }, simp only [hj₂, if_false], apply tail_sub hi, apply b_mem_side }, rcases v.1 hp with ⟨_, ⟨i', rfl⟩, hi'⟩, have h2i' : i' ∈ bcubes cs c := ⟨hi'.1.symm, v.2.1 i' hi'.1.symm ⟨tail p, hi'.2, hp.2⟩⟩, have i_i' : i ≠ i', { rintro rfl, simpa [p, side_tail, i, h2x] using hi'.2 j }, have : nonempty ↥((cs i').tail.side j' \ (cs i).tail.side j'), { apply nonempty_Ico_sdiff, apply mi_strict_minimal i_i' h2i', apply hw }, rcases this with ⟨⟨x', hx'⟩⟩, let p' : fin (n+1) → ℝ := cons (c.b 0) (λ j₂, if j₂ = j' then x' else (cs i).b j₂.succ), have hp' : p' ∈ c.bottom, { suffices : ∀ (j : fin n), ite (j = j') x' ((cs i).b j.succ) ∈ c.side j.succ, { simpa [bottom, p', to_set, tail, side_tail] }, intro j₂, by_cases hj₂ : j₂ = j', simp [hj₂], apply tail_sub h2i', apply hx'.1, simp only [if_congr, if_false, hj₂], apply tail_sub hi, apply b_mem_side }, rcases v.1 hp' with ⟨_, ⟨i'', rfl⟩, hi''⟩, have h2i'' : i'' ∈ bcubes cs c := ⟨hi''.1.symm, v.2.1 i'' hi''.1.symm ⟨tail p', hi''.2, hp'.2⟩⟩, have i'_i'' : i' ≠ i'', { rintro ⟨⟩, have : (cs i).b ∈ (cs i').to_set, { simp only [to_set, forall_fin_succ, hi.1, bottom_mem_side h2i', true_and, mem_set_of_eq], intro j₂, by_cases hj₂ : j₂ = j, { simpa [side_tail, p', hj', hj₂] using hi''.2 j }, { simpa [hj₂] using hi'.2 j₂ } }, apply not_disjoint_iff.mpr ⟨(cs i).b, (cs i).b_mem_to_set, this⟩ (h.1 i i' i_i') }, have i_i'' : i ≠ i'', { intro h, induction h, simpa [hx'.2] using hi''.2 j' }, apply not.elim _ (h.1 i' i'' i'_i''), simp only [on_fun, to_set_disjoint, not_disjoint_iff, forall_fin_succ, not_exists, comp_app], refine ⟨⟨c.b 0, bottom_mem_side h2i', bottom_mem_side h2i''⟩, _⟩, intro j₂, by_cases hj₂ : j₂ = j, { cases hj₂, refine ⟨x, _, _⟩, { convert hi'.2 j, simp [p] }, apply h3x h2i'' i_i''.symm, convert hi''.2 j, simp [p', hj'] }, by_cases h2j₂ : j₂ = j', { cases h2j₂, refine ⟨x', hx'.1, _⟩, convert hi''.2 j', simp }, refine ⟨(cs i).b j₂.succ, _, _⟩, { convert hi'.2 j₂, simp [hj₂] }, { convert hi''.2 j₂, simp [h2j₂] } end variables {h v} /-- The same result that `mi` cannot lie on the boundary of the valley written as inequalities. -/ lemma mi_not_on_boundary' (j : fin n) : c.tail.b j < (cs (mi h v)).tail.b j ∧ (cs (mi h v)).tail.b j + (cs (mi h v)).w < c.tail.b j + c.w := begin have := mi_not_on_boundary h v j, simp only [on_boundary, not_or_distrib] at this, cases this with h1 h2, split, apply lt_of_le_of_ne (b_le_b mi_mem_bcubes _) h1, apply lt_of_le_of_ne _ h2, apply ((Ico_subset_Ico_iff _).mp (tail_sub mi_mem_bcubes j)).2, simp [hw] end /-- The top of `mi` gives rise to a new valley, since the neighbouring cubes extend further upward than `mi`. -/ def valley_mi : valley cs ((cs (mi h v)).shift_up) := begin let i := mi h v, have hi : i ∈ bcubes cs c := mi_mem_bcubes, refine ⟨_, _, _⟩, { intro p, apply shift_up_bottom_subset_bottoms h mi_xm_ne_one }, { rintros i' hi' ⟨p2, hp2, h2p2⟩, simp only [head_shift_up] at hi', classical, by_contra h2i', rw [tail_shift_up] at h2p2, simp only [not_subset, tail_shift_up] at h2i', rcases h2i' with ⟨p1, hp1, h2p1⟩, have : ∃p3, p3 ∈ (cs i').tail.to_set ∧ p3 ∉ (cs i).tail.to_set ∧ p3 ∈ c.tail.to_set, { simp only [to_set, not_forall, mem_set_of_eq] at h2p1, cases h2p1 with j hj, rcases Ico_lemma (mi_not_on_boundary' j).1 (by simp [hw]) (mi_not_on_boundary' j).2 (le_trans (hp2 j).1 $ le_of_lt (h2p2 j).2) (le_trans (h2p2 j).1 $ le_of_lt (hp2 j).2) ⟨hj, hp1 j⟩ with ⟨w, hw, h2w, h3w⟩, refine ⟨λ j', if j' = j then w else p2 j', _, _, _⟩, { intro j', by_cases h : j' = j, { simp only [if_pos h], convert h3w }, { simp only [if_neg h], exact hp2 j' } }, { simp only [to_set, not_forall, mem_set_of_eq], use j, rw [if_pos rfl], convert h2w }, { intro j', by_cases h : j' = j, { simp only [if_pos h, side_tail], convert hw }, { simp only [if_neg h], apply hi.2, apply h2p2 } } }, rcases this with ⟨p3, h1p3, h2p3, h3p3⟩, let p := @cons n (λ_, ℝ) (c.b 0) p3, have hp : p ∈ c.bottom, { refine ⟨rfl, _⟩, rwa [tail_cons] }, rcases v.1 hp with ⟨_, ⟨i'', rfl⟩, hi''⟩, have h2i'' : i'' ∈ bcubes cs c, { use hi''.1.symm, apply v.2.1 i'' hi''.1.symm, use tail p, split, exact hi''.2, rw [tail_cons], exact h3p3 }, have h3i'' : (cs i).w < (cs i'').w, { apply mi_strict_minimal _ h2i'', rintro rfl, apply h2p3, convert hi''.2, rw [tail_cons] }, let p' := @cons n (λ_, ℝ) (cs i).xm p3, have hp' : p' ∈ (cs i').to_set, { simpa [to_set, forall_fin_succ, p', hi'.symm] using h1p3 }, have h2p' : p' ∈ (cs i'').to_set, { simp only [to_set, forall_fin_succ, p', cons_succ, cons_zero, mem_set_of_eq], refine ⟨_, by simpa [to_set, p] using hi''.2⟩, have : (cs i).b 0 = (cs i'').b 0, { by rw [hi.1, h2i''.1] }, simp [side, hw', xm, this, h3i''] }, apply not_disjoint_iff.mpr ⟨p', hp', h2p'⟩, apply h.1, rintro rfl, apply (cs i).b_ne_xm, rw [←hi', ←hi''.1, hi.1], refl }, { intros i' hi' h2i', dsimp only [shift_up] at h2i', replace h2i' := h.2.2.1 h2i'.symm, induction h2i', exact b_ne_xm (cs i) hi' } end variables (h) omit v /-- We get a sequence of cubes whose size is decreasing -/ noncomputable def sequence_of_cubes : ℕ → { i : ι // valley cs ((cs i).shift_up) } | 0 := let v := valley_unit_cube h in ⟨mi h v, valley_mi⟩ | (k+1) := let v := (sequence_of_cubes k).2 in ⟨mi h v, valley_mi⟩ def decreasing_sequence (k : ℕ) : order_dual ℝ := (cs (sequence_of_cubes h k).1).w lemma strict_mono_sequence_of_cubes : strict_mono $ decreasing_sequence h := strict_mono.nat $ begin intro k, let v := (sequence_of_cubes h k).2, dsimp only [decreasing_sequence, sequence_of_cubes], apply w_lt_w h v (mi_mem_bcubes : mi h v ∈ _), end omit h /-- The infinite sequence of cubes contradicts the finiteness of the family. -/ theorem not_correct : ¬correct cs := begin intro h, apply not_le_of_lt (lt_omega_iff_fintype.mpr ⟨_inst_1⟩), rw [omega, lift_id], fapply mk_le_of_injective, exact λ n, (sequence_of_cubes h n).1, intros n m hnm, apply strict_mono.injective (strict_mono_sequence_of_cubes h), dsimp only [decreasing_sequence], rw hnm end /-- **Dissection of Cubes**: A cube cannot be cubed. -/ theorem cannot_cube_a_cube : ∀{n : ℕ}, n ≥ 3 → -- In ℝ^n for n ≥ 3 ∀{ι : Type} [fintype ι] {cs : ι → cube n}, -- given a finite collection of (hyper)cubes 2 ≤ cardinal.mk ι → -- containing at least two elements pairwise (disjoint on (cube.to_set ∘ cs)) → -- which is pairwise disjoint (⋃(i : ι), (cs i).to_set) = unit_cube.to_set → -- whose union is the unit cube injective (cube.w ∘ cs) → -- such that the widths of all cubes are different false := -- then we can derive a contradiction begin intros n hn ι hι cs h1 h2 h3 h4, resetI, rcases n, cases hn, exact not_correct ⟨h2, h3, h4, h1, hn⟩ end
ea1611581f19e92be967708d882f92dd12f409e3
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/assert_tac3.lean
4d0207366c1201372f57dfa5eeeaf3c3c03737d0
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
813
lean
open tactic definition tst2 (a : nat) : a = a := by do assert `x (expr.const `nat []), rotate 1, trace_state, a ← get_local `a, mk_app `eq.refl [a] >>= exact, a ← get_local `a, exact a, return () print tst2 definition tst3 (a b : nat) : a = a := by do define `x (expr.const `nat []), rotate 1, trace_state, x ← get_local `x, mk_app `eq.refl [x] >>= exact, trace "-- second goal was indirectly solved by the previous tactic", trace_state, return () definition tst4 (a : nat) : a = a := begin assert x : nat, rotate 1, exact eq.refl a, exact a end definition tst5 (a : nat) : a = a := begin definev x : nat := a, trace_state, exact eq.refl x end definition tst6 (a : nat) : a = a := begin pose x := a, trace_state, exact eq.refl x end
cd3d01aee1dfb084a1056fe7051469e9d30e116f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/tactic_error_msg.lean
6ed2b700d7b153c82c69e6b773433665cefc1450
[ "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
75
lean
example (a b : Prop) : a → b → a ∧ b := begin intros, splits end
ef8f394ccf62549ec4d04ae97e51b247044b3768
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/measure_theory/decomposition/unsigned_hahn.lean
16680fd9745074b3e9c13310eb6a5c05437e366e
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,867
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import measure_theory.measure.measure_space /-! # Unsigned Hahn decomposition theorem This file proves the unsigned version of the Hahn decomposition theorem. ## Main statements * `hahn_decomposition` : Given two finite measures `μ` and `ν`, there exists a measurable set `s` such that any measurable set `t` included in `s` satisfies `ν t ≤ μ t`, and any measurable set `u` included in the complement of `s` satisfies `μ u ≤ ν u`. ## Tags Hahn decomposition -/ open set filter open_locale classical topological_space ennreal namespace measure_theory variables {α : Type*} [measurable_space α] {μ ν : measure α} -- suddenly this is necessary?! private lemma aux {m : ℕ} {γ d : ℝ} (h : γ - (1 / 2) ^ m < d) : γ - 2 * (1 / 2) ^ m + (1 / 2) ^ m ≤ d := by linarith /-- **Hahn decomposition theorem** -/ lemma hahn_decomposition [is_finite_measure μ] [is_finite_measure ν] : ∃s, measurable_set s ∧ (∀t, measurable_set t → t ⊆ s → ν t ≤ μ t) ∧ (∀t, measurable_set t → t ⊆ sᶜ → μ t ≤ ν t) := begin let d : set α → ℝ := λs, ((μ s).to_nnreal : ℝ) - (ν s).to_nnreal, let c : set ℝ := d '' {s | measurable_set s }, let γ : ℝ := Sup c, have hμ : ∀s, μ s < ∞ := measure_lt_top μ, have hν : ∀s, ν s < ∞ := measure_lt_top ν, have to_nnreal_μ : ∀s, ((μ s).to_nnreal : ℝ≥0∞) = μ s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hμ _), have to_nnreal_ν : ∀s, ((ν s).to_nnreal : ℝ≥0∞) = ν s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hν _), have d_empty : d ∅ = 0, { simp [d], rw [measure_empty, measure_empty], simp }, have d_split : ∀s t, measurable_set s → measurable_set t → d s = d (s \ t) + d (s ∩ t), { assume s t hs ht, simp only [d], rw [measure_eq_inter_diff hs ht, measure_eq_inter_diff hs ht, ennreal.to_nnreal_add (hμ _) (hμ _), ennreal.to_nnreal_add (hν _) (hν _), nnreal.coe_add, nnreal.coe_add], simp only [sub_eq_add_neg, neg_add], ac_refl }, have d_Union : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → monotone s → tendsto (λn, d (s n)) at_top (𝓝 (d (⋃n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ∞ _).comp $ tendsto_measure_Union hs hm), exact hμ _, exact hν _ }, have d_Inter : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → (∀n m, n ≤ m → s m ⊆ s n) → tendsto (λn, d (s n)) at_top (𝓝 (d (⋂n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ∞ _).comp $ tendsto_measure_Inter hs hm _), exact hμ _, exact ⟨0, hμ _⟩, exact hν _, exact ⟨0, hν _⟩ }, have bdd_c : bdd_above c, { use (μ univ).to_nnreal, rintros r ⟨s, hs, rfl⟩, refine le_trans (sub_le_self _ $ nnreal.coe_nonneg _) _, rw [nnreal.coe_le_coe, ← ennreal.coe_le_coe, to_nnreal_μ, to_nnreal_μ], exact measure_mono (subset_univ _) }, have c_nonempty : c.nonempty := nonempty.image _ ⟨_, measurable_set.empty⟩, have d_le_γ : ∀s, measurable_set s → d s ≤ γ := assume s hs, le_cSup bdd_c ⟨s, hs, rfl⟩, have : ∀n:ℕ, ∃s : set α, measurable_set s ∧ γ - (1/2)^n < d s, { assume n, have : γ - (1/2)^n < γ := sub_lt_self γ (pow_pos (half_pos zero_lt_one) n), rcases exists_lt_of_lt_cSup c_nonempty this with ⟨r, ⟨s, hs, rfl⟩, hlt⟩, exact ⟨s, hs, hlt⟩ }, rcases classical.axiom_of_choice this with ⟨e, he⟩, change ℕ → set α at e, have he₁ : ∀n, measurable_set (e n) := assume n, (he n).1, have he₂ : ∀n, γ - (1/2)^n < d (e n) := assume n, (he n).2, let f : ℕ → ℕ → set α := λn m, (finset.Ico n (m + 1)).inf e, have hf : ∀n m, measurable_set (f n m), { assume n m, simp only [f, finset.inf_eq_infi], exact measurable_set.bInter (countable_encodable _) (assume i _, he₁ _) }, have f_subset_f : ∀{a b c d}, a ≤ b → c ≤ d → f a d ⊆ f b c, { assume a b c d hab hcd, dsimp only [f], rw [finset.inf_eq_infi, finset.inf_eq_infi], refine bInter_subset_bInter_left _, simp, rintros j ⟨hbj, hjc⟩, exact ⟨le_trans hab hbj, lt_of_lt_of_le hjc $ add_le_add_right hcd 1⟩ }, have f_succ : ∀n m, n ≤ m → f n (m + 1) = f n m ∩ e (m + 1), { assume n m hnm, have : n ≤ m + 1 := le_of_lt (nat.succ_le_succ hnm), simp only [f], rw [finset.Ico.succ_top this, finset.inf_insert, set.inter_comm], refl }, have le_d_f : ∀n m, m ≤ n → γ - 2 * ((1 / 2) ^ m) + (1 / 2) ^ n ≤ d (f m n), { assume n m h, refine nat.le_induction _ _ n h, { have := he₂ m, simp only [f], rw [finset.Ico.succ_singleton, finset.inf_singleton], exact aux this }, { assume n (hmn : m ≤ n) ih, have : γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n + 1)) ≤ γ + d (f m (n + 1)), { calc γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n+1)) ≤ γ + (γ - 2 * (1 / 2)^m + ((1 / 2) ^ n - (1/2)^(n+1))) : begin refine add_le_add_left (add_le_add_left _ _) γ, simp only [pow_add, pow_one, le_sub_iff_add_le], linarith end ... = (γ - (1 / 2)^(n+1)) + (γ - 2 * (1 / 2)^m + (1 / 2)^n) : by simp only [sub_eq_add_neg]; ac_refl ... ≤ d (e (n + 1)) + d (f m n) : add_le_add (le_of_lt $ he₂ _) ih ... ≤ d (e (n + 1)) + d (f m n \ e (n + 1)) + d (f m (n + 1)) : by rw [f_succ _ _ hmn, d_split (f m n) (e (n + 1)) (hf _ _) (he₁ _), add_assoc] ... = d (e (n + 1) ∪ f m n) + d (f m (n + 1)) : begin rw [d_split (e (n + 1) ∪ f m n) (e (n + 1)), union_diff_left, union_inter_cancel_left], ac_refl, exact (he₁ _).union (hf _ _), exact (he₁ _) end ... ≤ γ + d (f m (n + 1)) : add_le_add_right (d_le_γ _ $ (he₁ _).union (hf _ _)) _ }, exact (add_le_add_iff_left γ).1 this } }, let s := ⋃ m, ⋂n, f m n, have γ_le_d_s : γ ≤ d s, { have hγ : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 γ), { suffices : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 (γ - 2 * 0)), { simpa }, exact (tendsto_const_nhds.sub $ tendsto_const_nhds.mul $ tendsto_pow_at_top_nhds_0_of_lt_1 (le_of_lt $ half_pos $ zero_lt_one) (half_lt_self zero_lt_one)) }, have hd : tendsto (λm, d (⋂n, f m n)) at_top (𝓝 (d (⋃ m, ⋂ n, f m n))), { refine d_Union _ _ _, { assume n, exact measurable_set.Inter (assume m, hf _ _) }, { exact assume n m hnm, subset_Inter (assume i, subset.trans (Inter_subset (f n) i) $ f_subset_f hnm $ le_refl _) } }, refine le_of_tendsto_of_tendsto' hγ hd (assume m, _), have : tendsto (λn, d (f m n)) at_top (𝓝 (d (⋂ n, f m n))), { refine d_Inter _ _ _, { assume n, exact hf _ _ }, { assume n m hnm, exact f_subset_f (le_refl _) hnm } }, refine ge_of_tendsto this (eventually_at_top.2 ⟨m, assume n hmn, _⟩), change γ - 2 * (1 / 2) ^ m ≤ d (f m n), refine le_trans _ (le_d_f _ _ hmn), exact le_add_of_le_of_nonneg (le_refl _) (pow_nonneg (le_of_lt $ half_pos $ zero_lt_one) _) }, have hs : measurable_set s := measurable_set.Union (assume n, measurable_set.Inter (assume m, hf _ _)), refine ⟨s, hs, _, _⟩, { assume t ht hts, have : 0 ≤ d t := ((add_le_add_iff_left γ).1 $ calc γ + 0 ≤ d s : by rw [add_zero]; exact γ_le_d_s ... = d (s \ t) + d t : by rw [d_split _ _ hs ht, inter_eq_self_of_subset_right hts] ... ≤ γ + d t : add_le_add (d_le_γ _ (hs.diff ht)) (le_refl _)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe], simpa only [d, le_sub_iff_add_le, zero_add] using this }, { assume t ht hts, have : d t ≤ 0, exact ((add_le_add_iff_left γ).1 $ calc γ + d t ≤ d s + d t : add_le_add γ_le_d_s (le_refl _) ... = d (s ∪ t) : begin rw [d_split _ _ (hs.union ht) ht, union_diff_right, union_inter_cancel_right, diff_eq_self.2], exact assume a ⟨hat, has⟩, hts hat has end ... ≤ γ + 0 : by rw [add_zero]; exact d_le_γ _ (hs.union ht)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe], simpa only [d, sub_le_iff_le_add, zero_add] using this } end end measure_theory
eb4ae32777228410b9092ddd689b6fb472a705fb
35b83be3126daae10419b573c55e1fed009d3ae8
/_target/deps/mathlib/data/finsupp.lean
901bcba38ee1609cd5efa0d77d4e6690085f63d3
[]
no_license
AHassan1024/Lean_Playground
ccb25b72029d199c0d23d002db2d32a9f2689ebc
a00b004c3a2eb9e3e863c361aa2b115260472414
refs/heads/master
1,586,221,905,125
1,544,951,310,000
1,544,951,310,000
157,934,290
0
0
null
null
null
null
UTF-8
Lean
false
false
37,949
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 Type of functions with finite support. Functions with finite support provide the basis for the following concrete instances: * ℕ →₀ α: Polynomials (where α is a ring) * (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names) * α →₀ ℕ: Multisets * α →₀ ℤ: Abelian groups freely generated by α * β →₀ α: Linear combinations over β where α is the scalar ring Most of the theory assumes that the range is a commutative monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. A general advice is to not use α →₀ β directly, as the type class setup might not be fitting. The best is to define a copy and select the instances best suited. -/ import data.finset data.set.finite algebra.big_operators algebra.module open finset variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*} {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} reserve infix ` →₀ `:25 /-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type*) (β : Type*) [has_zero β] := (support : finset α) (to_fun : α → β) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infix →₀ := finsupp namespace finsupp section basic variable [has_zero β] instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩ instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩ @[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl instance : inhabited (α →₀ β) := ⟨0⟩ @[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 := by haveI := classical.dec; exact not_iff_comm.1 mem_support_iff.symm @[extensionality] lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin have : f = g, { funext a, exact h a }, subst this, have : s = t, { ext a, exact (hf a).trans (hg a).symm }, subst this end @[simp] lemma support_eq_empty [decidable_eq β] {f : α →₀ β} : f.support = ∅ ↔ f = 0 := ⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $ mem_support_iff.2 H, by rintro rfl; refl⟩ instance [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ⟨assume ⟨h₁, h₂⟩, ext $ assume a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, by rwa [mem_support_iff, not_not] at h, have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h, by rw [hf, hg], by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩ lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} := ⟨set.fintype_of_finset f.support (λ _, mem_support_iff)⟩ lemma support_subset_iff {s : set α} {f : α →₀ β} [decidable_eq α] : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp only [set.subset_def, mem_coe, mem_support_iff]; exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) end basic section single variables [decidable_eq α] [decidable_eq β] [has_zero β] {a a' : α} {b : β} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : β) : α →₀ β := ⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin by_cases hb : b = 0; by_cases a = a'; simp only [hb, h, if_pos, if_false, mem_singleton], { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨false.elim, λ H, H rfl⟩ }, { exact ⟨λ _, hb, λ _, rfl⟩ }, { exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ } end⟩ lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl @[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h @[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 := ext $ assume a', begin by_cases h : a = a', { rw [h, single_eq_same, zero_apply] }, { rw [single_eq_of_ne h, zero_apply] } end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _] end single section on_finset variables [decidable_eq β] [has_zero β] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`. The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise often better set representation is available. -/ def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β := ⟨s.filter (λa, f a ≠ 0), f, assume a, classical.by_cases (assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩) (assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} : (on_finset s f hf : α →₀ β) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} : (on_finset s f hf).support ⊆ s := filter_subset _ end on_finset section map_range variables [has_zero β₁] [has_zero β₂] [decidable_eq β₂] /-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is `map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/ def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf @[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} : map_range f hf g a = f (g a) := rfl lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset variables [decidable_eq α] [decidable_eq β₁] @[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} : map_range f hf (single a b) = single a (f b) := finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf] end map_range section zip_with variables [has_zero β] [has_zero β₁] [has_zero β₂] [decidable_eq α] [decidable_eq β] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/ def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin haveI := classical.dec_eq β₁, simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib], rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf end @[simp] lemma zip_with_apply {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := support_on_finset_subset end zip_with section erase variables [decidable_eq α] [decidable_eq β] def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by rw [mem_erase, mem_support_iff]; split_ifs; [exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩, exact and_iff_right h]⟩ @[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h end erase -- [to_additive finsupp.sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.sum (λa, g a (f a)) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive finsupp.sum] def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.prod (λa, g a (f a)) attribute [to_additive finsupp.sum.equations._eqn_1] finsupp.prod.equations._eqn_1 @[to_additive finsupp.sum_map_range_index] lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] [decidable_eq β₂] {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[to_additive finsupp.sum_zero_index] lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} : (0 : α →₀ β).prod h = 1 := rfl section decidable variables [decidable_eq α] [decidable_eq β] section add_monoid variables [add_monoid β] @[to_additive finsupp.sum_single_index] lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := begin by_cases h : b = 0, { simp only [h, h_zero, single_zero]; refl }, { simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton, prod_singleton, single_eq_same] } end instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support): (g₁ + g₂).support = g₁.support ∪ g₂.support := le_antisymm support_zip_with $ assume a ha, (finset.mem_union.1 ha).elim (assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, add_zero]) (assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha, by simp only [mem_support_iff, not_not] at *; simpa only [add_apply, this, zero_add]) @[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (α →₀ β) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero] else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)] lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add] else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)] @[elab_as_eliminator] protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { rw [support_erase, mem_erase], exact λ H, H.1 rfl }, { rw [← mem_support_iff, hf], exact mem_insert_self _ _ }, { apply ih _ _, rw [support_erase, hf, finset.erase_insert has] } end end add_monoid instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group β] : add_group (α →₀ β) := { neg := map_range (has_neg.neg) neg_zero, add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } lemma single_multiset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β] (s : multiset β) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s single_zero $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β] (s : finset γ) (f : γ → β) (a : α) : single a (s.sum f) = s.sum (λb, single a (f b)) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero γ] [add_comm_monoid β] [decidable_eq α] [decidable_eq β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive finsupp.sum_neg_index] lemma prod_neg_index [add_group β] [comm_monoid γ] {g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl @[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm ... ⊆ support (- f) : support_map_range) instance [add_comm_group β] : add_comm_group (α →₀ β) := { add_comm := add_comm, ..finsupp.add_group } @[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (finset.sum_hom (λf : α →₀ β, f a₂) rfl (assume a b, rfl)).symm lemma support_sum [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} : (f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) := have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 → (∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this @[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} : f.sum (λa b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h := finset.sum_hom (@has_neg.neg γ _) neg_zero (assume a b, neg_add _ _) @[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl @[simp] lemma sum_single [add_comm_monoid β] {f : α →₀ β} : f.sum single = f := have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) = ({a} : finset α).sum (λa', ite (a' = a) (f a') 0), begin intro a, by_cases h : a ∈ f.support, { have : (finset.singleton a : finset α) ⊆ f.support, { simpa only [finset.subset_iff, mem_singleton, forall_eq] }, refine (finset.sum_subset this (λ _ _ H, _)).symm, exact if_neg (mt mem_singleton.2 H) }, { transitivity (f.support.sum (λa, (0 : β))), { refine (finset.sum_congr rfl $ λ a' ha', if_neg _), rintro rfl, exact h ha' }, { rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton, if_pos rfl, not_mem_support_iff.1 h] } } end, ext $ assume a, by simp only [sum_apply, single_apply, this, insert_empty_eq_singleton, sum_singleton, if_pos] @[to_additive finsupp.sum_add_index] lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h, from (finset.prod_subset (finset.subset_union_left _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h, from (finset.prod_subset (finset.subset_union_right _ _) $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm, calc (f + g).support.prod (λa, h a ((f + g) a)) = (f.support ∪ g.support).prod (λa, h a ((f + g) a)) : finset.prod_subset support_add $ by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero] ... = (f.support ∪ g.support).prod (λa, h a (f a)) * (f.support ∪ g.support).prod (λa, h a (g a)) : by simp only [add_apply, h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀a, h a 0 = 0, from assume a, have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0, by simpa only [sub_self] using this, have h_neg : ∀a b, h a (- b) = - h a b, from assume a b, have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b, by simpa only [h_zero, zero_sub] using this, have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂, from assume a b₁ b₂, have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂), by simpa only [h_neg, sub_neg_eq_add] using this, calc (f - g).sum h = (f + - g).sum h : rfl ... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg] ... = f.sum h - g.sum h : rfl @[to_additive finsupp.sum_finset_sum_index] lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ] [decidable_eq ι] {s : finset ι} {g : ι → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂): s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add] @[to_additive finsupp.sum_sum_index] lemma prod_sum_index [decidable_eq α₁] [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂): (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [decidable_eq α] [decidable_eq β] [add_comm_monoid β] [add_comm_monoid γ] (f : multiset (α →₀ β)) (h : α → β → γ) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih] lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (finset.sum_hom _ (multiset.map_zero m) (multiset.map_add m)).symm lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := begin refine (finset.sum_hom multiset.sum _ _).symm, exact multiset.sum_zero, exact multiset.sum_add end section map_domain variables [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] {v v₁ v₂ : α →₀ β} /-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β` is the finitely supported function whose value at `a : α₂` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β := v.sum $ λa, single (f a) lemma map_domain_id : map_domain id v = v := sum_single lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := begin refine ((sum_sum_index _ _).trans _).symm, { intros, exact single_zero }, { intros, exact single_add }, refine sum_congr rfl (λ _ _, sum_single_index _), { exact single_zero } end lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b := sum_single_index single_zero lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) := sum_zero_index lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ λ _ H, by simp only [h _ H] lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_finset_sum [decidable_eq ι] {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} : map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add) lemma map_domain_support {f : α → α₂} {s : α →₀ β} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $ by rw [finset.bind_singleton]; exact subset.refl _ @[to_additive finsupp.sum_map_domain_index] lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β} {h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := (prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _) end map_domain /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the monoid of monomial exponents.) -/ instance [has_add α] [semiring β] : has_mul (α →₀ β) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl /-- The unit of the multiplication is `single 0 1`, i.e. the function that is 1 at 0 and zero elsewhere. -/ instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) := ⟨single 0 1⟩ lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl section filter -- TODO: remove filter? build upon subtype_domain? section has_zero variables [has_zero β] {p : α → Prop} [decidable_pred p] {f : α →₀ β} /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) [decidable_pred p] (f : α →₀ β) : α →₀ β := on_finset f.support (λa, if p a then f a else 0) $ λ a H, mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := finset.ext.mpr $ assume a, if H : p a then by simp only [mem_support_iff, filter_apply_pos H, mem_filter, H, and_true] else by simp only [mem_support_iff, filter_apply_neg H, mem_filter, H, and_false, ne.def, ne_self_iff_false] end has_zero lemma filter_pos_add_filter_neg [add_monoid β] {f : α →₀ β} {p : α → Prop} [decidable_pred p] [decidable_pred (λa, ¬ p a)] : f.filter p + f.filter (λa, ¬ p a) = f := finsupp.ext $ assume a, if H : p a then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero] else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add] end filter section subtype_domain variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p] section zero variables [has_zero β] {v v' : α' →₀ β} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) [decidable_pred p] (f : α →₀ β) : (subtype p →₀ β) := ⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩ @[simp] lemma support_subtype_domain {f : α →₀ β} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 := rfl @[to_additive finsupp.sum_subtype_domain_index] lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β} {h : α → β → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h := prod_bij (λp _, p.val) (λ _, mem_subtype.1) (λ _ _, rfl) (λ _ _ _ _, subtype.eq) (λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩) end zero section monoid variables [add_monoid β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_add {v v' : α →₀ β} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ λ _, rfl end monoid section comm_monoid variables [add_comm_monoid β] lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (finset.sum_hom _ subtype_domain_zero $ assume v v', subtype_domain_add) lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end comm_monoid section group variables [add_group β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_neg {v : α →₀ β} : (- v).subtype_domain p = - v.subtype_domain p := ext $ λ _, rfl @[simp] lemma subtype_domain_sub {v v' : α →₀ β} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ λ _, rfl end group end subtype_domain section multiset def to_multiset (f : α →₀ ℕ) : multiset α := f.sum (λa n, add_monoid.smul n {a}) @[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) : f.to_multiset.count a = f a := calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) : (finset.sum_hom _ (multiset.count_zero a) (multiset.count_add a)).symm ... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul] ... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl ... = f a * (a :: 0 : multiset α).count a : sum_eq_single _ (λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero]) (λ H, by simp only [not_mem_support_iff.1 H, zero_mul]) ... = f a : by simp only [multiset.count_singleton, mul_one] def of_multiset [decidable_eq α] (m : multiset α) : α →₀ ℕ := on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $ by_contradiction (mt multiset.count_eq_zero.2 H) @[simp] lemma of_multiset_apply [decidable_eq α] (m : multiset α) (a : α) : of_multiset m a = m.count a := rfl def equiv_multiset [decidable_eq α] : (α →₀ ℕ) ≃ (multiset α) := ⟨ to_multiset, of_multiset, assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset], assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩ lemma mem_support_multiset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β] {s : multiset (α →₀ β)} (a : α) : a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support := multiset.induction_on s false.elim begin assume f s ih ha, by_cases a ∈ f.support, { exact ⟨f, multiset.mem_cons_self _ _, h⟩ }, { simp only [multiset.sum_cons, mem_support_iff, add_apply, not_mem_support_iff.1 h, zero_add] at ha, rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩, exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ } end lemma mem_support_finset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β] {s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support := let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in ⟨c, hc, eq.symm ▸ hfa⟩ lemma mem_support_single [decidable_eq α] [decidable_eq β] [has_zero β] (a a' : α) (b : β) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := ⟨λ H : (a ∈ ite _ _ _), if h : b = 0 then by rw if_pos h at H; exact H.elim else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩, λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩ end multiset section curry_uncurry protected def curry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] (f : (α × β) →₀ γ) : α →₀ (β →₀ γ) := f.sum $ λp c, single p.1 (single p.2 c) lemma sum_curry_index [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] [add_comm_monoid δ] (f : (α × β) →₀ γ) (g : α → β → γ → δ) (hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) : f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) := begin rw [finsupp.curry], transitivity, { exact sum_sum_index (assume a, sum_zero_index) (assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) }, congr, funext p c, transitivity, { exact sum_single_index sum_zero_index }, exact sum_single_index (hg₀ _ _) end protected def uncurry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ := f.sum $ λa g, g.sum $ λb c, single (a, b) c def finsupp_prod_equiv [add_comm_monoid γ] [decidable_eq α] [decidable_eq β] [decidable_eq γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) := by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [ finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single] end curry_uncurry section variables [add_monoid α] [semiring β] -- TODO: the simplifier unfolds 0 in the instance proof! private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index] private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero] private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c := by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add] private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c := by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add] def to_semiring : semiring (α →₀ β) := { one := 1, mul := (*), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero, zero_add, one_mul, sum_single], mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := zero_mul, mul_zero := mul_zero, mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } end local attribute [instance] to_semiring def to_comm_semiring [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [add_comm] end, .. finsupp.to_semiring } local attribute [instance] to_comm_semiring def to_ring [add_monoid α] [ring β] : ring (α →₀ β) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. finsupp.to_semiring } def to_comm_ring [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) := { mul_comm := mul_comm, .. finsupp.to_ring} lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}: single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := (sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [_root_.mul_zero, single_zero])) lemma prod_single [decidable_eq ι] [add_comm_monoid α] [comm_semiring β] {s : finset ι} {a : ι → α} {b : ι → β} : s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] section variable (β) def to_has_scalar' [ring γ] [module γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero)⟩ local attribute [instance] to_has_scalar' @[simp] lemma smul_apply' [ring γ] [module γ β] {a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) := rfl def to_module [ring γ] [module γ β] : module γ (α →₀ β) := { smul := (•), smul_add := assume a x y, finsupp.ext $ λ _, smul_add, add_smul := assume a x y, finsupp.ext $ λ _, add_smul, one_smul := assume x, finsupp.ext $ λ _, one_smul, mul_smul := assume r s x, finsupp.ext $ λ _, mul_smul, .. finsupp.add_comm_group } end def to_has_scalar [ring β] : has_scalar β (α →₀ β) := to_has_scalar' β local attribute [instance] to_has_scalar @[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} : (b • v) a = b • (v a) := rfl lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 end decidable section variables [semiring β] [semiring γ] lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} : (s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma mul_sum [semiring β] [semiring γ] (b : γ) (s : α →₀ β) {f : α → β → γ} : b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) := by simp only [finsupp.sum, finset.mul_sum] end end finsupp
52d5315e8c86e6a04b62a479fdedfdf8e73f391b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/opposites.lean
863416ac213563ec95a651123c99318fd02c64c0
[]
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
9,710
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.opposite import Mathlib.algebra.field import Mathlib.group_theory.group_action.defs import Mathlib.data.equiv.mul_add import Mathlib.PostPort universes u u_1 u_2 namespace Mathlib /-! # Algebraic operations on `αᵒᵖ` -/ namespace opposite protected instance has_add (α : Type u) [Add α] : Add (αᵒᵖ) := { add := fun (x y : αᵒᵖ) => op (unop x + unop y) } protected instance has_sub (α : Type u) [Sub α] : Sub (αᵒᵖ) := { sub := fun (x y : αᵒᵖ) => op (unop x - unop y) } protected instance add_semigroup (α : Type u) [add_semigroup α] : add_semigroup (αᵒᵖ) := add_semigroup.mk Add.add sorry protected instance add_left_cancel_semigroup (α : Type u) [add_left_cancel_semigroup α] : add_left_cancel_semigroup (αᵒᵖ) := add_left_cancel_semigroup.mk add_semigroup.add sorry sorry protected instance add_right_cancel_semigroup (α : Type u) [add_right_cancel_semigroup α] : add_right_cancel_semigroup (αᵒᵖ) := add_right_cancel_semigroup.mk add_semigroup.add sorry sorry protected instance add_comm_semigroup (α : Type u) [add_comm_semigroup α] : add_comm_semigroup (αᵒᵖ) := add_comm_semigroup.mk add_semigroup.add sorry sorry protected instance has_zero (α : Type u) [HasZero α] : HasZero (αᵒᵖ) := { zero := op 0 } protected instance nontrivial (α : Type u) [nontrivial α] : nontrivial (αᵒᵖ) := sorry @[simp] theorem unop_eq_zero_iff (α : Type u) [HasZero α] (a : αᵒᵖ) : unop a = 0 ↔ a = 0 := iff.refl (unop a = 0) @[simp] theorem op_eq_zero_iff (α : Type u) [HasZero α] (a : α) : op a = 0 ↔ a = 0 := iff.refl (op a = 0) protected instance add_monoid (α : Type u) [add_monoid α] : add_monoid (αᵒᵖ) := add_monoid.mk add_semigroup.add sorry 0 sorry sorry protected instance add_comm_monoid (α : Type u) [add_comm_monoid α] : add_comm_monoid (αᵒᵖ) := add_comm_monoid.mk add_monoid.add sorry add_monoid.zero sorry sorry sorry protected instance has_neg (α : Type u) [Neg α] : Neg (αᵒᵖ) := { neg := fun (x : αᵒᵖ) => op (-unop x) } protected instance add_group (α : Type u) [add_group α] : add_group (αᵒᵖ) := add_group.mk add_monoid.add sorry add_monoid.zero sorry sorry Neg.neg Sub.sub sorry protected instance add_comm_group (α : Type u) [add_comm_group α] : add_comm_group (αᵒᵖ) := add_comm_group.mk add_group.add sorry add_group.zero sorry sorry add_group.neg add_group.sub sorry sorry protected instance has_mul (α : Type u) [Mul α] : Mul (αᵒᵖ) := { mul := fun (x y : αᵒᵖ) => op (unop y * unop x) } protected instance semigroup (α : Type u) [semigroup α] : semigroup (αᵒᵖ) := semigroup.mk Mul.mul sorry protected instance left_cancel_semigroup (α : Type u) [right_cancel_semigroup α] : left_cancel_semigroup (αᵒᵖ) := left_cancel_semigroup.mk semigroup.mul sorry sorry protected instance right_cancel_semigroup (α : Type u) [left_cancel_semigroup α] : right_cancel_semigroup (αᵒᵖ) := right_cancel_semigroup.mk semigroup.mul sorry sorry protected instance comm_semigroup (α : Type u) [comm_semigroup α] : comm_semigroup (αᵒᵖ) := comm_semigroup.mk semigroup.mul sorry sorry protected instance has_one (α : Type u) [HasOne α] : HasOne (αᵒᵖ) := { one := op 1 } @[simp] theorem unop_eq_one_iff (α : Type u) [HasOne α] (a : αᵒᵖ) : unop a = 1 ↔ a = 1 := iff.refl (unop a = 1) @[simp] theorem op_eq_one_iff (α : Type u) [HasOne α] (a : α) : op a = 1 ↔ a = 1 := iff.refl (op a = 1) protected instance monoid (α : Type u) [monoid α] : monoid (αᵒᵖ) := monoid.mk semigroup.mul sorry 1 sorry sorry protected instance comm_monoid (α : Type u) [comm_monoid α] : comm_monoid (αᵒᵖ) := comm_monoid.mk monoid.mul sorry monoid.one sorry sorry sorry protected instance has_inv (α : Type u) [has_inv α] : has_inv (αᵒᵖ) := has_inv.mk fun (x : αᵒᵖ) => op (unop x⁻¹) protected instance group (α : Type u) [group α] : group (αᵒᵖ) := group.mk monoid.mul sorry monoid.one sorry sorry has_inv.inv (div_inv_monoid.div._default monoid.mul sorry monoid.one sorry sorry has_inv.inv) sorry protected instance comm_group (α : Type u) [comm_group α] : comm_group (αᵒᵖ) := comm_group.mk group.mul sorry group.one sorry sorry group.inv group.div sorry sorry protected instance distrib (α : Type u) [distrib α] : distrib (αᵒᵖ) := distrib.mk Mul.mul Add.add sorry sorry protected instance semiring (α : Type u) [semiring α] : semiring (αᵒᵖ) := semiring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry sorry monoid.mul sorry monoid.one sorry sorry sorry sorry sorry sorry protected instance ring (α : Type u) [ring α] : ring (αᵒᵖ) := ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry monoid.mul sorry monoid.one sorry sorry sorry sorry protected instance comm_ring (α : Type u) [comm_ring α] : comm_ring (αᵒᵖ) := comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry sorry protected instance no_zero_divisors (α : Type u) [HasZero α] [Mul α] [no_zero_divisors α] : no_zero_divisors (αᵒᵖ) := no_zero_divisors.mk fun (x y : αᵒᵖ) (H : op (unop y * unop x) = op 0) => or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero (op_injective H)) (fun (hy : unop y = 0) => Or.inr (unop_injective hy)) fun (hx : unop x = 0) => Or.inl (unop_injective hx) protected instance integral_domain (α : Type u) [integral_domain α] : integral_domain (αᵒᵖ) := integral_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry sorry sorry protected instance field (α : Type u) [field α] : field (αᵒᵖ) := field.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry has_inv.inv sorry sorry sorry protected instance has_scalar (α : Type u) (R : Type u_1) [has_scalar R α] : has_scalar R (αᵒᵖ) := has_scalar.mk fun (c : R) (x : αᵒᵖ) => op (c • unop x) protected instance mul_action (α : Type u) (R : Type u_1) [monoid R] [mul_action R α] : mul_action R (αᵒᵖ) := mul_action.mk sorry sorry protected instance distrib_mul_action (α : Type u) (R : Type u_1) [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R (αᵒᵖ) := distrib_mul_action.mk sorry sorry @[simp] theorem op_zero (α : Type u) [HasZero α] : op 0 = 0 := rfl @[simp] theorem unop_zero (α : Type u) [HasZero α] : unop 0 = 0 := rfl @[simp] theorem op_one (α : Type u) [HasOne α] : op 1 = 1 := rfl @[simp] theorem unop_one (α : Type u) [HasOne α] : unop 1 = 1 := rfl @[simp] theorem op_add {α : Type u} [Add α] (x : α) (y : α) : op (x + y) = op x + op y := rfl @[simp] theorem unop_add {α : Type u} [Add α] (x : αᵒᵖ) (y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl @[simp] theorem op_neg {α : Type u} [Neg α] (x : α) : op (-x) = -op x := rfl @[simp] theorem unop_neg {α : Type u} [Neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl @[simp] theorem op_mul {α : Type u} [Mul α] (x : α) (y : α) : op (x * y) = op y * op x := rfl @[simp] theorem unop_mul {α : Type u} [Mul α] (x : αᵒᵖ) (y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl @[simp] theorem op_inv {α : Type u} [has_inv α] (x : α) : op (x⁻¹) = (op x⁻¹) := rfl @[simp] theorem unop_inv {α : Type u} [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x⁻¹) := rfl @[simp] theorem op_sub {α : Type u} [add_group α] (x : α) (y : α) : op (x - y) = op x - op y := rfl @[simp] theorem unop_sub {α : Type u} [add_group α] (x : αᵒᵖ) (y : αᵒᵖ) : unop (x - y) = unop x - unop y := rfl @[simp] theorem op_smul {α : Type u} {R : Type u_1} [has_scalar R α] (c : R) (a : α) : op (c • a) = c • op a := rfl @[simp] theorem unop_smul {α : Type u} {R : Type u_1} [has_scalar R α] (c : R) (a : αᵒᵖ) : unop (c • a) = c • unop a := rfl /-- The function `op` is an additive equivalence. -/ def op_add_equiv {α : Type u} [Add α] : α ≃+ (αᵒᵖ) := add_equiv.mk (equiv.to_fun equiv_to_opposite) (equiv.inv_fun equiv_to_opposite) sorry sorry sorry @[simp] theorem coe_op_add_equiv {α : Type u} [Add α] : ⇑op_add_equiv = op := rfl @[simp] theorem coe_op_add_equiv_symm {α : Type u} [Add α] : ⇑(add_equiv.symm op_add_equiv) = unop := rfl @[simp] theorem op_add_equiv_to_equiv {α : Type u} [Add α] : add_equiv.to_equiv op_add_equiv = equiv_to_opposite := rfl end opposite /-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines a ring homomorphism to `Sᵒᵖ`. -/ def ring_hom.to_opposite {R : Type u_1} {S : Type u_2} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ (x y : R), commute (coe_fn f x) (coe_fn f y)) : R →+* (Sᵒᵖ) := ring_hom.mk (add_monoid_hom.to_fun (add_monoid_hom.comp (add_equiv.to_add_monoid_hom opposite.op_add_equiv) ↑f)) sorry sorry sorry sorry @[simp] theorem ring_hom.coe_to_opposite {R : Type u_1} {S : Type u_2} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ (x y : R), commute (coe_fn f x) (coe_fn f y)) : ⇑(ring_hom.to_opposite f hf) = opposite.op ∘ ⇑f := rfl
82888eea89e53ec9ac0d07b7f15003a00bdd8645
d406927ab5617694ec9ea7001f101b7c9e3d9702
/counterexamples/canonically_ordered_comm_semiring_two_mul.lean
fd6ca5897584d760e03a4c985525c82a5c7b75fa
[ "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
8,943
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.zmod.basic import ring_theory.subsemiring.basic import algebra.order.monoid.basic /-! A `canonically_ordered_comm_semiring` with two different elements `a` and `b` such that `a ≠ b` and `2 * a = 2 * b`. Thus, multiplication by a fixed non-zero element of a canonically ordered semiring need not be injective. In particular, multiplying by a strictly positive element need not be strictly monotone. Recall that a `canonically_ordered_comm_semiring` is a commutative semiring with a partial ordering that is "canonical" in the sense that the inequality `a ≤ b` holds if and only if there is a `c` such that `a + c = b`. There are several compatibility conditions among addition/multiplication and the order relation. The point of the counterexample is to show that monotonicity of multiplication cannot be strengthened to **strict** monotonicity. Reference: https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/canonically_ordered.20pathology -/ namespace from_Bhavik /-- Bhavik Mehta's example. There are only the initial definitions, but no proofs. The Type `K` is a canonically ordered commutative semiring with the property that `2 * (1/2) ≤ 2 * 1`, even though it is not true that `1/2 ≤ 1`, since `1/2` and `1` are not comparable. -/ @[derive [comm_semiring]] def K : Type := subsemiring.closure ({1.5} : set ℚ) instance : has_coe K ℚ := ⟨λ x, x.1⟩ instance inhabited_K : inhabited K := ⟨0⟩ instance : preorder K := { le := λ x y, x = y ∨ (x : ℚ) + 1 ≤ (y : ℚ), le_refl := λ x, or.inl rfl, le_trans := λ x y z xy yz, begin rcases xy with (rfl | _), { apply yz }, rcases yz with (rfl | _), { right, apply xy }, right, exact xy.trans (le_trans ((le_add_iff_nonneg_right _).mpr zero_le_one) yz) end } end from_Bhavik lemma mem_zmod_2 (a : zmod 2) : a = 0 ∨ a = 1 := begin rcases a with ⟨_|_, _|_|_|_⟩, { exact or.inl rfl }, { exact or.inr rfl }, end lemma add_self_zmod_2 (a : zmod 2) : a + a = 0 := begin rcases mem_zmod_2 a with rfl | rfl; refl, end namespace Nxzmod_2 variables {a b : ℕ × zmod 2} /-- The preorder relation on `ℕ × ℤ/2ℤ` where we only compare the first coordinate, except that we leave incomparable each pair of elements with the same first component. For instance, `∀ α, β ∈ ℤ/2ℤ`, the inequality `(1,α) ≤ (2,β)` holds, whereas, `∀ n ∈ ℤ`, the elements `(n,0)` and `(n,1)` are incomparable. -/ instance preN2 : partial_order (ℕ × zmod 2) := { le := λ x y, x = y ∨ x.1 < y.1, le_refl := λ a, or.inl rfl, le_trans := λ x y z xy yz, begin rcases xy with (rfl | _), { exact yz }, { rcases yz with (rfl | _), { exact or.inr xy}, { exact or.inr (xy.trans yz) } } end, le_antisymm := begin intros a b ab ba, cases ab with ab ab, { exact ab }, { cases ba with ba ba, { exact ba.symm }, { exact (nat.lt_asymm ab ba).elim } } end } instance csrN2 : comm_semiring (ℕ × zmod 2) := by apply_instance instance csrN2_1 : add_cancel_comm_monoid (ℕ × zmod 2) := { add_left_cancel := λ a b c h, (add_right_inj a).mp h, ..Nxzmod_2.csrN2 } /-- A strict inequality forces the first components to be different. -/ @[simp] lemma lt_def : a < b ↔ a.1 < b.1 := begin refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨(rfl | a1), h1⟩, { exact ((not_or_distrib.mp h1).1).elim rfl }, { exact a1 } }, refine ⟨or.inr h, not_or_distrib.mpr ⟨λ k, _, not_lt.mpr h.le⟩⟩, rw k at h, exact nat.lt_asymm h h end lemma add_left_cancel : ∀ (a b c : ℕ × zmod 2), a + b = a + c → b = c := λ a b c h, (add_right_inj a).mp h lemma add_le_add_left : ∀ (a b : ℕ × zmod 2), a ≤ b → ∀ (c : ℕ × zmod 2), c + a ≤ c + b := begin rintros a b (rfl | ab) c, { refl }, { exact or.inr (by simpa) } end lemma le_of_add_le_add_left : ∀ (a b c : ℕ × zmod 2), a + b ≤ a + c → b ≤ c := begin rintros a b c (bc | bc), { exact le_of_eq ((add_right_inj a).mp bc) }, { exact or.inr (by simpa using bc) } end instance : zero_le_one_class (ℕ × zmod 2) := ⟨dec_trivial⟩ lemma mul_lt_mul_of_pos_left : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → c * a < c * b := λ a b c ab c0, lt_def.mpr ((mul_lt_mul_left (lt_def.mp c0)).mpr (lt_def.mp ab)) lemma mul_lt_mul_of_pos_right : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → a * c < b * c := λ a b c ab c0, lt_def.mpr ((mul_lt_mul_right (lt_def.mp c0)).mpr (lt_def.mp ab)) instance socsN2 : strict_ordered_comm_semiring (ℕ × zmod 2) := { add_le_add_left := add_le_add_left, le_of_add_le_add_left := le_of_add_le_add_left, zero_le_one := zero_le_one, mul_lt_mul_of_pos_left := mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := mul_lt_mul_of_pos_right, ..Nxzmod_2.csrN2_1, ..(infer_instance : partial_order (ℕ × zmod 2)), ..(infer_instance : comm_semiring (ℕ × zmod 2)), ..pullback_nonzero prod.fst prod.fst_zero prod.fst_one } end Nxzmod_2 namespace ex_L open Nxzmod_2 subtype /-- Initially, `L` was defined as the subsemiring closure of `(1,0)`. -/ def L : Type := { l : (ℕ × zmod 2) // l ≠ (0, 1) } lemma add_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) : a + b ≠ (0, 1) := begin rcases a with ⟨a, a2⟩, rcases b with ⟨b, b2⟩, cases b, { rcases mem_zmod_2 b2 with rfl | rfl, { simp [ha] }, { simpa only } }, { simp [(a + b).succ_ne_zero] } end lemma mul_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) : a * b ≠ (0, 1) := begin rcases a with ⟨a, a2⟩, rcases b with ⟨b, b2⟩, cases b, { rcases mem_zmod_2 b2 with rfl | rfl; rcases mem_zmod_2 a2 with rfl | rfl; -- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where -- it does not finish the proof and on that goal it asks to prove `false` simp, exact hb rfl }, cases a, { rcases mem_zmod_2 b2 with rfl | rfl; rcases mem_zmod_2 a2 with rfl | rfl; -- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where -- it does not finish the proof and on that goal it asks to prove `false` simp, exact ha rfl }, { simp [mul_ne_zero _ _, nat.succ_ne_zero _] } end /-- The subsemiring corresponding to the elements of `L`, used to transfer instances. -/ def L_subsemiring : subsemiring (ℕ × zmod 2) := { carrier := { l | l ≠ (0, 1) }, zero_mem' := dec_trivial, one_mem' := dec_trivial, add_mem' := λ _ _, add_L, mul_mem' := λ _ _, mul_L } instance : ordered_comm_semiring L := L_subsemiring.to_ordered_comm_semiring instance inhabited : inhabited L := ⟨1⟩ lemma bot_le : ∀ (a : L), 0 ≤ a := begin rintros ⟨⟨an, a2⟩, ha⟩, cases an, { rcases mem_zmod_2 a2 with (rfl | rfl), { refl, }, { exact (ha rfl).elim } }, { refine or.inr _, exact nat.succ_pos _ } end instance order_bot : order_bot L := ⟨0, bot_le⟩ lemma exists_add_of_le : ∀ a b : L, a ≤ b → ∃ c, b = a + c := begin rintro a ⟨b, _⟩ (⟨rfl, rfl⟩ | h), { exact ⟨0, (add_zero _).symm⟩ }, { exact ⟨⟨b - a.1, λ H, (tsub_pos_of_lt h).ne' (prod.mk.inj_iff.1 H).1⟩, subtype.ext $ prod.ext (add_tsub_cancel_of_le h.le).symm (add_sub_cancel'_right _ _).symm⟩ } end lemma le_self_add : ∀ a b : L, a ≤ a + b := begin rintro a ⟨⟨bn, b2⟩, hb⟩, obtain rfl | h := nat.eq_zero_or_pos bn, { obtain rfl | rfl := mem_zmod_2 b2, { exact or.inl (prod.ext (add_zero _).symm (add_zero _).symm) }, { exact (hb rfl).elim } }, { exact or.inr ((lt_add_iff_pos_right _).mpr h) } end lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : L), a * b = 0 → a = 0 ∨ b = 0 := begin rintros ⟨⟨a, a2⟩, ha⟩ ⟨⟨b, b2⟩, hb⟩ ab1, injection ab1 with ab, injection ab with abn ab2, rw mul_eq_zero at abn, rcases abn with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine or.inl _, rcases mem_zmod_2 a2 with rfl | rfl, { refl }, { exact (ha rfl).elim } }, { refine or.inr _, rcases mem_zmod_2 b2 with rfl | rfl, { refl }, { exact (hb rfl).elim } } end instance can : canonically_ordered_comm_semiring L := { exists_add_of_le := exists_add_of_le, le_self_add := le_self_add, eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, ..(infer_instance : order_bot L), ..(infer_instance : ordered_comm_semiring L) } /-- The elements `(1,0)` and `(1,1)` of `L` are different, but their doubles coincide. -/ example : ∃ a b : L, a ≠ b ∧ 2 * a = 2 * b := begin refine ⟨⟨(1,0), by simp⟩, 1, λ (h : (⟨(1, 0), _⟩ : L) = ⟨⟨1, 1⟩, _⟩), _, rfl⟩, obtain (F : (0 : zmod 2) = 1) := congr_arg (λ j : L, j.1.2) h, cases F, end end ex_L
387e527c0e796a64738d5d8807bc11d2c2d3852e
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/algebraic.lean
3c25db81256afdaf871cfb0321289ea6bfbffa3d
[ "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
14,444
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import linear_algebra.finite_dimensional import ring_theory.integral_closure import data.polynomial.integral_normalization /-! # Algebraic elements and algebraic extensions An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. An R-algebra is algebraic over R if and only if all its elements are algebraic over R. The main result in this file proves transitivity of algebraicity: a tower of algebraic field extensions is algebraic. -/ universes u v w open_locale classical polynomial open polynomial section variables (R : Type u) {A : Type v} [comm_ring R] [ring A] [algebra R A] /-- An element of an R-algebra is algebraic over R if it is a root of a nonzero polynomial with coefficients in R. -/ def is_algebraic (x : A) : Prop := ∃ p : R[X], p ≠ 0 ∧ aeval x p = 0 /-- An element of an R-algebra is transcendental over R if it is not algebraic over R. -/ def transcendental (x : A) : Prop := ¬ is_algebraic R x lemma is_transcendental_of_subsingleton [subsingleton R] (x : A) : transcendental R x := λ ⟨p, h, _⟩, h $ subsingleton.elim p 0 variables {R} /-- A subalgebra is algebraic if all its elements are algebraic. -/ def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x variables (R A) /-- An algebra is algebraic if all its elements are algebraic. -/ def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x variables {R A} /-- A subalgebra is algebraic if and only if it is algebraic as an algebra. -/ lemma subalgebra.is_algebraic_iff (S : subalgebra R A) : S.is_algebraic ↔ @algebra.is_algebraic R S _ _ S.algebra := begin delta algebra.is_algebraic subalgebra.is_algebraic, rw subtype.forall', refine forall_congr (λ x, exists_congr (λ p, and_congr iff.rfl _)), have h : function.injective S.val := subtype.val_injective, conv_rhs { rw [← h.eq_iff, alg_hom.map_zero] }, rw [← aeval_alg_hom_apply, S.val_apply] end /-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/ lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic := begin delta algebra.is_algebraic subalgebra.is_algebraic, simp only [algebra.mem_top, forall_prop_of_true, iff_self], end lemma is_algebraic_iff_not_injective {x : A} : is_algebraic R x ↔ ¬ function.injective (polynomial.aeval x : R[X] →ₐ[R] A) := by simp only [is_algebraic, injective_iff_map_eq_zero, not_forall, and.comm, exists_prop] end section zero_ne_one variables (R : Type u) {S : Type*} {A : Type v} [comm_ring R] variables [comm_ring S] [ring A] [algebra R A] [algebra R S] [algebra S A] variables [is_scalar_tower R S A] /-- An integral element of an algebra is algebraic.-/ lemma is_integral.is_algebraic [nontrivial R] {x : A} : is_integral R x → is_algebraic R x := λ ⟨p, hp, hpx⟩, ⟨p, hp.ne_zero, hpx⟩ variables {R} lemma is_algebraic_zero [nontrivial R] : is_algebraic R (0 : A) := ⟨_, X_ne_zero, aeval_X 0⟩ /-- An element of `R` is algebraic, when viewed as an element of the `R`-algebra `A`. -/ lemma is_algebraic_algebra_map [nontrivial R] (x : R) : is_algebraic R (algebra_map R A x) := ⟨_, X_sub_C_ne_zero x, by rw [_root_.map_sub, aeval_X, aeval_C, sub_self]⟩ lemma is_algebraic_one [nontrivial R] : is_algebraic R (1 : A) := by { rw ←_root_.map_one _, exact is_algebraic_algebra_map 1 } lemma is_algebraic_nat [nontrivial R] (n : ℕ) : is_algebraic R (n : A) := by { rw ←map_nat_cast _, exact is_algebraic_algebra_map n } lemma is_algebraic_int [nontrivial R] (n : ℤ) : is_algebraic R (n : A) := by { rw ←ring_hom.map_int_cast (algebra_map R A), exact is_algebraic_algebra_map n } lemma is_algebraic_rat (R : Type u) {A : Type v} [division_ring A] [field R] [char_zero R] [algebra R A] (n : ℚ) : is_algebraic R (n : A) := by { rw ←map_rat_cast (algebra_map R A), exact is_algebraic_algebra_map n } lemma is_algebraic_algebra_map_of_is_algebraic {a : S} : is_algebraic R a → is_algebraic R (algebra_map S A a) := λ ⟨f, hf₁, hf₂⟩, ⟨f, hf₁, by rw [← is_scalar_tower.algebra_map_aeval R S A, hf₂, ring_hom.map_zero]⟩ end zero_ne_one section field variables {K : Type u} {A : Type v} [field K] [ring A] [algebra K A] /-- An element of an algebra over a field is algebraic if and only if it is integral.-/ lemma is_algebraic_iff_is_integral {x : A} : is_algebraic K x ↔ is_integral K x := begin refine ⟨_, is_integral.is_algebraic K⟩, rintro ⟨p, hp, hpx⟩, refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩, rw [← aeval_def, alg_hom.map_mul, hpx, zero_mul], end protected lemma algebra.is_algebraic_iff_is_integral : algebra.is_algebraic K A ↔ algebra.is_integral K A := ⟨λ h x, is_algebraic_iff_is_integral.mp (h x), λ h x, is_algebraic_iff_is_integral.mpr (h x)⟩ end field namespace algebra variables {K : Type*} {L : Type*} {R : Type*} {S : Type*} {A : Type*} variables [field K] [field L] [comm_ring R] [comm_ring S] [comm_ring A] variables [algebra K L] [algebra L A] [algebra K A] [is_scalar_tower K L A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] /-- If L is an algebraic field extension of K and A is an algebraic algebra over L, then A is algebraic over K. -/ lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) : is_algebraic K A := begin simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢, exact is_integral_trans L_alg A_alg, end variables (K L) /-- If x is algebraic over R, then x is algebraic over S when S is an extension of R, and the map from `R` to `S` is injective. -/ lemma _root_.is_algebraic_of_larger_base_of_injective (hinj : function.injective (algebra_map R S)) {x : A} (A_alg : _root_.is_algebraic R x) : _root_.is_algebraic S x := let ⟨p, hp₁, hp₂⟩ := A_alg in ⟨p.map (algebra_map _ _), by rwa [ne.def, ← degree_eq_bot, degree_map_eq_of_injective hinj, degree_eq_bot], by simpa⟩ /-- If A is an algebraic algebra over R, then A is algebraic over S when S is an extension of R, and the map from `R` to `S` is injective. -/ lemma is_algebraic_of_larger_base_of_injective (hinj : function.injective (algebra_map R S)) (A_alg : is_algebraic R A) : is_algebraic S A := λ x, is_algebraic_of_larger_base_of_injective hinj (A_alg x) /-- If x is a algebraic over K, then x is algebraic over L when L is an extension of K -/ lemma _root_.is_algebraic_of_larger_base {x : A} (A_alg : _root_.is_algebraic K x) : _root_.is_algebraic L x := _root_.is_algebraic_of_larger_base_of_injective (algebra_map K L).injective A_alg /-- If A is an algebraic algebra over K, then A is algebraic over L when L is an extension of K -/ lemma is_algebraic_of_larger_base (A_alg : is_algebraic K A) : is_algebraic L A := is_algebraic_of_larger_base_of_injective (algebra_map K L).injective A_alg variables {R S} (K L) /-- A field extension is integral if it is finite. -/ lemma is_integral_of_finite [finite_dimensional K L] : algebra.is_integral K L := λ x, is_integral_of_submodule_noetherian ⊤ (is_noetherian.iff_fg.2 infer_instance) x algebra.mem_top /-- A field extension is algebraic if it is finite. -/ lemma is_algebraic_of_finite [finite : finite_dimensional K L] : is_algebraic K L := algebra.is_algebraic_iff_is_integral.mpr (is_integral_of_finite K L) end algebra variables {R S : Type*} [comm_ring R] [is_domain R] [comm_ring S] lemma exists_integral_multiple [algebra R S] {z : S} (hz : is_algebraic R z) (inj : ∀ x, algebra_map R S x = 0 → x = 0) : ∃ (x : integral_closure R S) (y ≠ (0 : R)), z * algebra_map R S y = x := begin rcases hz with ⟨p, p_ne_zero, px⟩, set a := p.leading_coeff with a_def, have a_ne_zero : a ≠ 0 := mt polynomial.leading_coeff_eq_zero.mp p_ne_zero, have y_integral : is_integral R (algebra_map R S a) := is_integral_algebra_map, have x_integral : is_integral R (z * algebra_map R S a) := ⟨p.integral_normalization, monic_integral_normalization p_ne_zero, integral_normalization_aeval_eq_zero px inj⟩, exact ⟨⟨_, x_integral⟩, a, a_ne_zero, rfl⟩ end /-- A fraction `(a : S) / (b : S)` can be reduced to `(c : S) / (d : R)`, if `S` is the integral closure of `R` in an algebraic extension `L` of `R`. -/ lemma is_integral_closure.exists_smul_eq_mul {L : Type*} [field L] [algebra R S] [algebra S L] [algebra R L] [is_scalar_tower R S L] [is_integral_closure S R L] (h : algebra.is_algebraic R L) (inj : function.injective (algebra_map R L)) (a : S) {b : S} (hb : b ≠ 0) : ∃ (c : S) (d ≠ (0 : R)), d • a = b * c := begin obtain ⟨c, d, d_ne, hx⟩ := exists_integral_multiple (h (algebra_map _ L a / algebra_map _ L b)) ((injective_iff_map_eq_zero _).mp inj), refine ⟨is_integral_closure.mk' S (c : L) c.2, d, d_ne, is_integral_closure.algebra_map_injective S R L _⟩, simp only [algebra.smul_def, ring_hom.map_mul, is_integral_closure.algebra_map_mk', ← hx, ← is_scalar_tower.algebra_map_apply], rw [← mul_assoc _ (_ / _), mul_div_cancel' (algebra_map S L a), mul_comm], exact mt ((injective_iff_map_eq_zero _).mp (is_integral_closure.algebra_map_injective S R L) _) hb end section field variables {K L : Type*} [field K] [field L] [algebra K L] (A : subalgebra K L) lemma inv_eq_of_aeval_div_X_ne_zero {x : L} {p : K[X]} (aeval_ne : aeval x (div_X p) ≠ 0) : x⁻¹ = aeval x (div_X p) / (aeval x p - algebra_map _ _ (p.coeff 0)) := begin rw [inv_eq_iff_inv_eq, inv_div, div_eq_iff, sub_eq_iff_eq_add, mul_comm], conv_lhs { rw ← div_X_mul_X_add p }, rw [alg_hom.map_add, alg_hom.map_mul, aeval_X, aeval_C], exact aeval_ne end lemma inv_eq_of_root_of_coeff_zero_ne_zero {x : L} {p : K[X]} (aeval_eq : aeval x p = 0) (coeff_zero_ne : p.coeff 0 ≠ 0) : x⁻¹ = - (aeval x (div_X p) / algebra_map _ _ (p.coeff 0)) := begin convert inv_eq_of_aeval_div_X_ne_zero (mt (λ h, (algebra_map K L).injective _) coeff_zero_ne), { rw [aeval_eq, zero_sub, div_neg] }, rw ring_hom.map_zero, convert aeval_eq, conv_rhs { rw ← div_X_mul_X_add p }, rw [alg_hom.map_add, alg_hom.map_mul, h, zero_mul, zero_add, aeval_C] end lemma subalgebra.inv_mem_of_root_of_coeff_zero_ne_zero {x : A} {p : K[X]} (aeval_eq : aeval x p = 0) (coeff_zero_ne : p.coeff 0 ≠ 0) : (x⁻¹ : L) ∈ A := begin have : (x⁻¹ : L) = aeval x (div_X p) / (aeval x p - algebra_map _ _ (p.coeff 0)), { rw [aeval_eq, subalgebra.coe_zero, zero_sub, div_neg], convert inv_eq_of_root_of_coeff_zero_ne_zero _ coeff_zero_ne, { rw subalgebra.aeval_coe }, { simpa using aeval_eq } }, rw [this, div_eq_mul_inv, aeval_eq, subalgebra.coe_zero, zero_sub, ← ring_hom.map_neg, ← ring_hom.map_inv], exact A.mul_mem (aeval x p.div_X).2 (A.algebra_map_mem _), end lemma subalgebra.inv_mem_of_algebraic {x : A} (hx : is_algebraic K (x : L)) : (x⁻¹ : L) ∈ A := begin obtain ⟨p, ne_zero, aeval_eq⟩ := hx, rw [subalgebra.aeval_coe, subalgebra.coe_eq_zero] at aeval_eq, revert ne_zero aeval_eq, refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a hp ha ih ne_zero aeval_eq, refine A.inv_mem_of_root_of_coeff_zero_ne_zero aeval_eq _, rwa [coeff_add, hp, zero_add, coeff_C, if_pos rfl] }, { intros p hp ih ne_zero aeval_eq, rw [alg_hom.map_mul, aeval_X, mul_eq_zero] at aeval_eq, cases aeval_eq with aeval_eq x_eq, { exact ih hp aeval_eq }, { rw [x_eq, subalgebra.coe_zero, inv_zero], exact A.zero_mem } } end /-- In an algebraic extension L/K, an intermediate subalgebra is a field. -/ lemma subalgebra.is_field_of_algebraic (hKL : algebra.is_algebraic K L) : is_field A := { mul_inv_cancel := λ a ha, ⟨ ⟨a⁻¹, A.inv_mem_of_algebraic (hKL a)⟩, subtype.ext (mul_inv_cancel (mt (subalgebra.coe_eq_zero _).mp ha))⟩, .. show nontrivial A, by apply_instance, .. subalgebra.to_comm_ring A } end field section pi variables (R' : Type u) (S' : Type v) (T' : Type w) /-- This is not an instance as it forms a diamond with `pi.has_smul`. See the `instance_diamonds` test for details. -/ def polynomial.has_smul_pi [semiring R'] [has_smul R' S'] : has_smul (R'[X]) (R' → S') := ⟨λ p f x, eval x p • f x⟩ /-- This is not an instance as it forms a diamond with `pi.has_smul`. See the `instance_diamonds` test for details. -/ noncomputable def polynomial.has_smul_pi' [comm_semiring R'] [semiring S'] [algebra R' S'] [has_smul S' T'] : has_smul (R'[X]) (S' → T') := ⟨λ p f x, aeval x p • f x⟩ variables {R} {S} local attribute [instance] polynomial.has_smul_pi polynomial.has_smul_pi' @[simp] lemma polynomial_smul_apply [semiring R'] [has_smul R' S'] (p : R'[X]) (f : R' → S') (x : R') : (p • f) x = eval x p • f x := rfl @[simp] lemma polynomial_smul_apply' [comm_semiring R'] [semiring S'] [algebra R' S'] [has_smul S' T'] (p : R'[X]) (f : S' → T') (x : S') : (p • f) x = aeval x p • f x := rfl variables [comm_semiring R'] [comm_semiring S'] [comm_semiring T'] [algebra R' S'] [algebra S' T'] /-- This is not an instance for the same reasons as `polynomial.has_smul_pi'`. -/ noncomputable def polynomial.algebra_pi : algebra (R'[X]) (S' → T') := { to_fun := λ p z, algebra_map S' T' (aeval z p), map_one' := funext $ λ z, by simp only [polynomial.aeval_one, pi.one_apply, map_one], map_mul' := λ f g, funext $ λ z, by simp only [pi.mul_apply, map_mul], map_zero' := funext $ λ z, by simp only [polynomial.aeval_zero, pi.zero_apply, map_zero], map_add' := λ f g, funext $ λ z, by simp only [polynomial.aeval_add, pi.add_apply, map_add], commutes' := λ p f, funext $ λ z, mul_comm _ _, smul_def' := λ p f, funext $ λ z, by simp only [algebra.algebra_map_eq_smul_one, polynomial_smul_apply', one_mul, pi.mul_apply, algebra.smul_mul_assoc], ..polynomial.has_smul_pi' R' S' T' } local attribute [instance] polynomial.algebra_pi @[simp] lemma polynomial.algebra_map_pi_eq_aeval : (algebra_map (R'[X]) (S' → T') : R'[X] → (S' → T')) = λ p z, algebra_map _ _ (aeval z p) := rfl @[simp] lemma polynomial.algebra_map_pi_self_eq_eval : (algebra_map (R'[X]) (R' → R') : R'[X] → (R' → R')) = λ p z, eval z p := rfl end pi
4265bf19c136541bed4f75278d0d933fe4372f16
1fd908b06e3f9c1252cb2285ada1102623a67f72
/cubical/square.lean
496b8ab3d339475f39aaca6a0d25ab42c3874270
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
36,223
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jakob von Raumer Squares in a type -/ import types.eq universes u v w hott_theory namespace hott open eq hott.equiv hott.is_equiv namespace eq variables {A : Type _} {B : Type _} {C : Type _} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ a₁ a₂ a₃ a₄ : A} /-a₀₀-/ {p₁₀ p₁₀' : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ p₀₁' : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ p₂₁' : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ p₁₂' : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ {b : B} {c : C} inductive square {A : Type u} {a₀₀ : A} : Π{a₂₀ a₀₂ a₂₂ : A}, a₀₀ = a₂₀ → a₀₂ = a₂₂ → a₀₀ = a₀₂ → a₂₀ = a₂₂ → Type u | ids : square idp idp idp idp /- square top bottom left right -/ variables {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} @[hott, reducible] def ids := @square.ids @[hott, reducible] def idsquare (a : A) := @square.ids A a @[hott] def hrefl (p : a = a') : square idp idp p p := by induction p; exact ids @[hott] def vrefl (p : a = a') : square p p idp idp := by induction p; exact ids @[hott, reducible] def hrfl {p : a = a'} : square idp idp p p := hrefl _ @[hott, reducible] def vrfl {p : a = a'} : square p p idp idp := vrefl _ @[hott] def hdeg_square {p q : a = a'} (r : p = q) : square idp idp p q := by induction r;apply hrefl @[hott] def vdeg_square {p q : a = a'} (r : p = q) : square p q idp idp := by induction r;apply vrefl @[hott, hsimp] def hdeg_square_idp (p : a = a') : hdeg_square (refl p) = hrfl := idp @[hott, hsimp] def vdeg_square_idp (p : a = a') : vdeg_square (refl p) = vrfl := idp @[hott] def hconcat (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁) : square (p₁₀ ⬝ p₃₀) (p₁₂ ⬝ p₃₂) p₀₁ p₄₁ := by induction s₃₁; exact s₁₁ @[hott] def vconcat (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃) : square p₁₀ p₁₄ (p₀₁ ⬝ p₀₃) (p₂₁ ⬝ p₂₃) := by induction s₁₃; exact s₁₁ @[hott] def dconcat {p₀₀ : a₀₀ = a} {p₂₂ : a = a₂₂} (s₂₁ : square p₀₀ p₁₂ p₀₁ p₂₂) (s₁₂ : square p₁₀ p₂₂ p₀₀ p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction s₁₂; exact s₂₁ @[hott] def hinverse (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀⁻¹ p₁₂⁻¹ p₂₁ p₀₁ := by induction s₁₁;exact ids @[hott] def vinverse (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₂ p₁₀ p₀₁⁻¹ p₂₁⁻¹ := by induction s₁₁;exact ids @[hott] def eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ p₂₁ := by induction r; exact s₁₁ @[hott] def vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : square p₁₀ p p₀₁ p₂₁ := by induction r; exact s₁₁ @[hott] def eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := by induction r; exact s₁₁ @[hott] def hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := by induction r; exact s₁₁ infix ` ⬝h `:69 := hconcat --type using \tr infix ` ⬝v `:70 := vconcat --type using \tr infixl ` ⬝hp `:71 := hconcat_eq --type using \tr infixl ` ⬝vp `:73 := vconcat_eq --type using \tr infixr ` ⬝ph `:72 := eq_hconcat --type using \tr infixr ` ⬝pv `:74 := eq_vconcat --type using \tr postfix `⁻¹ʰ`:(max+1) := hinverse --type using \-1h postfix `⁻¹ᵛ`:(max+1) := vinverse --type using \-1v @[hott] def transpose (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₀₁ p₂₁ p₁₀ p₁₂ := by induction s₁₁;exact ids @[hott] def aps (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (ap f p₁₀) (ap f p₁₂) (ap f p₀₁) (ap f p₂₁) := by induction s₁₁;exact ids /- canceling, whiskering and moving thinks along the sides of the square -/ @[hott] def whisker_tl (p : a = a₀₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def whisker_br (p : a₂₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p) := by induction p;exact s₁₁ @[hott] def whisker_rt (p : a = a₂₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁) := by induction s₁₁;induction p;constructor @[hott] def whisker_tr (p : a₂₀ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁) := by induction s₁₁;induction p;constructor @[hott] def whisker_bl (p : a = a₀₂) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def whisker_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁ := by induction s₁₁;induction p;constructor @[hott] def cancel_tl (p : a = a₀₀) (s₁₁ : square (p ⬝ p₁₀) p₁₂ (p ⬝ p₀₁) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_br (p : a₂₂ = a) (s₁₁ : square p₁₀ (p₁₂ ⬝ p) p₀₁ (p₂₁ ⬝ p)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p;exact s₁₁ @[hott] def cancel_rt (p : a = a₂₀) (s₁₁ : square (p₁₀ ⬝ p⁻¹) p₁₂ p₀₁ (p ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_tr (p : a₂₀ = a) (s₁₁ : square (p₁₀ ⬝ p) p₁₂ p₀₁ (p⁻¹ ⬝ p₂₁)) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_bl (p : a = a₀₂) (s₁₁ : square p₁₀ (p ⬝ p₁₂) (p₀₁ ⬝ p⁻¹) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def cancel_lb (p : a₀₂ = a) (s₁₁ : square p₁₀ (p⁻¹ ⬝ p₁₂) (p₀₁ ⬝ p) p₂₁) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p; hsimp at s₁₁; exact s₁₁ @[hott] def move_top_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁) : square (p⁻¹ ⬝ p₁₀) p₁₂ q p₂₁ := by apply cancel_tl p; hsimp; exact s @[hott] def move_top_of_left' {p : a = a₀₀} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p⁻¹ ⬝ q) p₂₁) : square (p ⬝ p₁₀) p₁₂ q p₂₁ := by apply cancel_tl p⁻¹; hsimp; exact s @[hott] def move_left_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁) : square q p₁₂ (p⁻¹ ⬝ p₀₁) p₂₁ := by apply cancel_tl p; hsimp; exact s @[hott] def move_left_of_top' {p : a = a₀₀} {q : a = a₂₀} (s : square (p⁻¹ ⬝ q) p₁₂ p₀₁ p₂₁) : square q p₁₂ (p ⬝ p₀₁) p₂₁ := by apply cancel_tl p⁻¹; hsimp; exact s @[hott] def move_bot_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q)) : square p₁₀ (p₁₂ ⬝ q⁻¹) p₀₁ p := by apply cancel_br q; hsimp; exact s @[hott] def move_bot_of_right' {p : a₂₀ = a} {q : a₂₂ = a} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q⁻¹)) : square p₁₀ (p₁₂ ⬝ q) p₀₁ p := by apply cancel_br q⁻¹; hsimp; exact s @[hott] def move_right_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁) : square p₁₀ p p₀₁ (p₂₁ ⬝ q⁻¹) := by apply cancel_br q; hsimp; exact s @[hott] def move_right_of_bot' {p : a₀₂ = a} {q : a₂₂ = a} (s : square p₁₀ (p ⬝ q⁻¹) p₀₁ p₂₁) : square p₁₀ p p₀₁ (p₂₁ ⬝ q) := by apply cancel_br q⁻¹; hsimp; exact s @[hott] def move_top_of_right {p : a₂₀ = a} {q : a = a₂₂} (s : square p₁₀ p₁₂ p₀₁ (p ⬝ q)) : square (p₁₀ ⬝ p) p₁₂ p₀₁ q := by apply cancel_rt p; hsimp; exact s @[hott] def move_right_of_top {p : a₀₀ = a} {q : a = a₂₀} (s : square (p ⬝ q) p₁₂ p₀₁ p₂₁) : square p p₁₂ p₀₁ (q ⬝ p₂₁) := by apply cancel_tr q; hsimp; exact s @[hott] def move_bot_of_left {p : a₀₀ = a} {q : a = a₀₂} (s : square p₁₀ p₁₂ (p ⬝ q) p₂₁) : square p₁₀ (q ⬝ p₁₂) p p₂₁ := by apply cancel_lb q; hsimp; exact s @[hott] def move_left_of_bot {p : a₀₂ = a} {q : a = a₂₂} (s : square p₁₀ (p ⬝ q) p₀₁ p₂₁) : square p₁₀ q (p₀₁ ⬝ p) p₂₁ := by apply cancel_bl p; hsimp; exact s /- some higher ∞-groupoid operations -/ @[hott] def vconcat_vrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝v vrefl p₁₂ = s₁₁ := by induction s₁₁; reflexivity @[hott] def hconcat_hrfl (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : s₁₁ ⬝h hrefl p₂₁ = s₁₁ := by induction s₁₁; reflexivity /- equivalences -/ @[hott] def eq_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂ := by induction s₁₁; apply idp @[hott] def square_of_eq (r : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₁₂; dsimp at r; induction r; induction p₂₁; induction p₁₀; exact ids @[hott] def eq_top_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹ := by induction s₁₁; apply idp @[hott] def square_of_eq_top (r : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₂; dsimp at r;induction r;induction p₁₀;exact ids @[hott] def eq_bot_of_square (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : p₁₂ = p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ := by induction s₁₁; apply idp @[hott] def square_of_eq_bot (r : p₀₁⁻¹ ⬝ p₁₀ ⬝ p₂₁ = p₁₂) : square p₁₀ p₁₂ p₀₁ p₂₁ := by induction p₂₁; induction p₁₀; dsimp at r; induction r; induction p₀₁; exact ids @[hott] def square_equiv_eq (t : a₀₀ = a₀₂) (b : a₂₀ = a₂₂) (l : a₀₀ = a₂₀) (r : a₀₂ = a₂₂) : square t b l r ≃ t ⬝ r = l ⬝ b := begin fapply equiv.MK, { exact eq_of_square}, { exact square_of_eq}, { intro s, induction b, dsimp [concat] at s, induction s, induction r, induction t, apply idp}, { intro s, induction s, apply idp}, end @[hott] def hdeg_square_equiv' (p q : a = a') : square idp idp p q ≃ p = q := begin transitivity, {apply square_equiv_eq}, transitivity, {apply eq_equiv_eq_symm}, {apply equiv_eq_closed_right, apply idp_con}, end @[hott] def vdeg_square_equiv' (p q : a = a') : square p q idp idp ≃ p = q := begin transitivity, {apply square_equiv_eq}, {apply equiv_eq_closed_right, apply idp_con}, end @[hott] def eq_of_hdeg_square {p q : a = a'} (s : square idp idp p q) : p = q := to_fun (hdeg_square_equiv' _ _) s @[hott] def eq_of_vdeg_square {p q : a = a'} (s : square p q idp idp) : p = q := to_fun (vdeg_square_equiv' _ _) s @[hott] def top_deg_square (l : a₁ = a₂) (b : a₂ = a₃) (r : a₄ = a₃) : square (l ⬝ b ⬝ r⁻¹) b l r := by induction r;induction b;induction l;constructor @[hott] def bot_deg_square (l : a₁ = a₂) (t : a₁ = a₃) (r : a₃ = a₄) : square t (l⁻¹ ⬝ t ⬝ r) l r := by induction r;induction t;induction l;constructor /- the following two equivalences have as underlying inverse function the functions hdeg_square and vdeg_square, respectively. See example below the @[hott] def -/ @[hott] def hdeg_square_equiv (p q : a = a') : square idp idp p q ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply hdeg_square_equiv', exact hdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_hdeg_square}, { reflexivity} end @[hott] def vdeg_square_equiv (p q : a = a') : square p q idp idp ≃ p = q := begin fapply equiv_change_fun, { fapply equiv_change_inv, apply vdeg_square_equiv',exact vdeg_square, intro s, induction s, induction p, reflexivity}, { exact eq_of_vdeg_square}, { reflexivity} end example (p q : a = a') : (hdeg_square_equiv p q)⁻¹ᶠ = hdeg_square := idp /- characterization of pathovers in a equality type. The type B of the equality is fixed here. A version where B may also varies over the path p is given in the file squareover -/ @[hott] def eq_pathover {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : square q r (ap f p) (ap g p)) : q =[p; λ a, f a = g a] r := begin induction p, apply pathover_idp_of_eq, exact eq_of_vdeg_square s end @[hott] def eq_pathover_constant_left {g : A → B} {p : a = a'} {b : B} {q : b = g a} {r : b = g a'} (s : square q r idp (ap g p)) : q =[p; λ a, b = g a] r := eq_pathover (ap_constant p b ⬝ph s) @[hott] def eq_pathover_id_left {g : A → A} {p : a = a'} {q : a = g a} {r : a' = g a'} (s : square q r p (ap g p)) : q =[p; λ a, a = g a] r := eq_pathover (ap_id p ⬝ph s) @[hott] def eq_pathover_constant_right {f : A → B} {p : a = a'} {b : B} {q : f a = b} {r : f a' = b} (s : square q r (ap f p) idp) : q =[p; λ a, f a = b] r := eq_pathover (s ⬝hp (ap_constant p b)⁻¹) @[hott] def eq_pathover_id_right {f : A → A} {p : a = a'} {q : f a = a} {r : f a' = a'} (s : square q r (ap f p) p) : q =[p; λ a, f a = a] r := eq_pathover (s ⬝hp (ap_id p)⁻¹) @[hott] def square_of_pathover {f g : A → B} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : q =[p; λ a, f a = g a] r) : square q r (ap f p) (ap g p) := by induction p;apply vdeg_square;exact (eq_of_pathover_idp s) @[hott] def eq_pathover_constant_left_id_right {p : a = a'} {a₀ : A} {q : a₀ = a} {r : a₀ = a'} (s : square q r idp p) : q =[p] r := eq_pathover (ap_constant p a₀ ⬝ph s ⬝hp (ap_id p)⁻¹) @[hott] def eq_pathover_id_left_constant_right {p : a = a'} {a₀ : A} {q : a = a₀} {r : a' = a₀} (s : square q r p idp) : q =[p; λ a, a = a₀] r := eq_pathover (ap_id p ⬝ph s ⬝hp (ap_constant p a₀)⁻¹) @[hott] def loop_pathover {p : a = a'} {q : a = a} {r : a' = a'} (s : square q r p p) : q =[p; λ a, a = a] r := eq_pathover (ap_id p ⬝ph s ⬝hp (ap_id p)⁻¹) /- interaction of equivalences with operations on squares -/ @[hott] def eq_pathover_equiv_square {f g : A → B} (p : a = a') (q : f a = g a) (r : f a' = g a') : q =[p; λ a, f a = g a] r ≃ square q r (ap f p) (ap g p) := equiv.MK square_of_pathover eq_pathover begin intro s, induction p, dsimp [square_of_pathover,eq_pathover], transitivity, {apply ap vdeg_square, apply to_right_inv (pathover_idp _ _ _)}, {apply to_left_inv (vdeg_square_equiv _ _)} end begin intro s, induction p, dsimp [square_of_pathover,eq_pathover], transitivity, {apply ap (pathover_idp_of_eq _), apply to_right_inv (vdeg_square_equiv _ _)}, {apply to_left_inv (pathover_idp _ _ _)}, end @[hott] def square_of_pathover_eq_concato {f g : A → B} {p : a = a'} {q q' : f a = g a} {r : f a' = g a'} (s' : q = q') (s : q' =[p; λ a, f a = g a] r) : square_of_pathover (s' ⬝po s) = s' ⬝pv square_of_pathover s := by induction s;induction s';reflexivity @[hott] def square_of_pathover_concato_eq {f g : A → B} {p : a = a'} {q : f a = g a} {r r' : f a' = g a'} (s' : r = r') (s : q =[p; λ a, f a = g a] r) : square_of_pathover (s ⬝op s') = square_of_pathover s ⬝vp s' := by induction s;induction s';reflexivity @[hott] def square_of_pathover_concato {f g : A → B} {p : a = a'} {p' : a' = a''} {q : f a = g a} {q' : f a' = g a'} {q'' : f a'' = g a''} (s : q =[p; λ a, f a = g a] q') (s' : q' =[p'; λ a, f a = g a] q'') : square_of_pathover (s ⬝o s') = ap_con f p p' ⬝ph (square_of_pathover s ⬝v square_of_pathover s') ⬝hp (ap_con g p p')⁻¹ := by induction s'; induction s; symmetry; apply vconcat_vrfl @[hott] def eq_of_square_hrfl (p : a = a') : eq_of_square hrfl = idp_con p := by induction p;reflexivity @[hott] def eq_of_square_vrfl (p : a = a') : eq_of_square vrfl = (idp_con p)⁻¹ := by induction p;reflexivity @[hott] def eq_of_square_hdeg_square {p q : a = a'} (r : p = q) : eq_of_square (hdeg_square r) = !idp_con ⬝ r⁻¹ := by induction r;induction p;reflexivity @[hott] def eq_of_square_vdeg_square {p q : a = a'} (r : p = q) : eq_of_square (vdeg_square r) = r ⬝ !idp_con⁻¹ := by induction r;induction p;reflexivity @[hott] def eq_of_square_eq_vconcat {p : a₀₀ = a₂₀} (r : p = p₁₀) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝pv s₁₁) = whisker_right p₂₁ r ⬝ eq_of_square s₁₁ := by induction s₁₁; eq_cases r;reflexivity @[hott] def eq_of_square_eq_hconcat {p : a₀₀ = a₀₂} (r : p = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : eq_of_square (r ⬝ph s₁₁) = eq_of_square s₁₁ ⬝ (whisker_right p₁₂ r)⁻¹ := by induction r;reflexivity @[hott] def eq_of_square_vconcat_eq {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : eq_of_square (s₁₁ ⬝vp r) = eq_of_square s₁₁ ⬝ whisker_left p₀₁ r := by induction r;reflexivity @[hott] def eq_of_square_hconcat_eq {p : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : eq_of_square (s₁₁ ⬝hp r) = (whisker_left p₁₀ r)⁻¹ ⬝ eq_of_square s₁₁ := by induction s₁₁; induction r;reflexivity @[hott] def change_path_eq_pathover {A B : Type _} {a a' : A} {f g : A → B} {p p' : a = a'} (r : p = p') {q : f a = g a} {q' : f a' = g a'} (s : square q q' (ap f p) (ap g p)) : change_path r (eq_pathover s) = eq_pathover ((ap02 f r)⁻¹ ⬝ph s ⬝hp (ap02 g r)) := by induction r; reflexivity @[hott] def eq_hconcat_hdeg_square {A : Type _} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) : q₁ ⬝ph hdeg_square q₂ = hdeg_square (q₁ ⬝ q₂) := by induction q₁; induction q₂; reflexivity @[hott] def hdeg_square_hconcat_eq {A : Type _} {a a' : A} {p₁ p₂ p₃ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) : hdeg_square q₁ ⬝hp q₂ = hdeg_square (q₁ ⬝ q₂) := by induction q₁; induction q₂; reflexivity @[hott] def eq_hconcat_eq_hdeg_square {A : Type _} {a a' : A} {p₁ p₂ p₃ p₄ : a = a'} (q₁ : p₁ = p₂) (q₂ : p₂ = p₃) (q₃ : p₃ = p₄) : q₁ ⬝ph hdeg_square q₂ ⬝hp q₃ = hdeg_square (q₁ ⬝ q₂ ⬝ q₃) := by induction q₃; apply eq_hconcat_hdeg_square -- @[hott] def vconcat_eq [unfold 11] {p : a₀₂ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₁₂ = p) : -- square p₁₀ p p₀₁ p₂₁ := -- by induction r; exact s₁₁ -- @[hott] def eq_hconcat [unfold 11] {p : a₀₀ = a₀₂} (r : p = p₀₁) -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀ p₁₂ p p₂₁ := -- by induction r; exact s₁₁ -- @[hott] def hconcat_eq [unfold 11] {p : a₂₀ = a₂₂} -- (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p) : square p₁₀ p₁₂ p₀₁ p := -- by induction r; exact s₁₁ /- recursors for squares where some sides are reflexivity -/ @[hott,elab_as_eliminator] def rec_on_b {a₀₀ : A} {P : Π{a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂}, square t idp l r → Type _} {a₂₀ a₁₂ : A} {t : a₀₀ = a₂₀} {l : a₀₀ = a₁₂} {r : a₂₀ = a₁₂} (s : square t idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), begin induction r, induction t, hgeneralize: eq_of_square s = es, dsimp at es, induction es, apply H end, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H2 @[hott, elab_as_eliminator] def rec_on_r {a₀₀ : A} {P : Π{a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂}, square t b l idp → Type _} {a₀₂ a₂₁ : A} {t : a₀₀ = a₂₁} {b : a₀₂ = a₂₁} {l : a₀₀ = a₀₂} (s : square t b l idp) (H : P ids) : P s := let p : l ⬝ b = t := (eq_of_square s)⁻¹ in have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx p, P (square_of_eq p⁻¹)) _ p (by induction b; induction l; exact H), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [inv_inv, H3] at H2 @[hott, elab_as_eliminator] def rec_on_l {a₀₁ : A} {P : Π {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂}, square t b idp r → Type _} {a₂₀ a₂₂ : A} {t : a₀₁ = a₂₀} {b : a₀₁ = a₂₂} {r : a₂₀ = a₂₂} (s : square t b idp r) (H : P ids) : P s := let p : t ⬝ r = b := eq_of_square s ⬝ !idp_con in have H2 : P (square_of_eq (p ⬝ !idp_con⁻¹)), from eq.rec_on p (by induction r; induction t; exact H), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [con_inv_cancel_right, H3] at H2 @[hott, elab_as_eliminator] def rec_on_t {a₁₀ : A} {P : Π {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂}, square idp b l r → Type _} {a₀₂ a₂₂ : A} {b : a₀₂ = a₂₂} {l : a₁₀ = a₀₂} {r : a₁₀ = a₂₂} (s : square idp b l r) (H : P ids) : P s := let p : l ⬝ b = r := (eq_of_square s)⁻¹ ⬝ !idp_con in have H2 : P (square_of_eq ((p ⬝ !idp_con⁻¹)⁻¹)), from eq.rec_on p (by induction b; induction l; exact H), have H3 : P (square_of_eq ((eq_of_square s)⁻¹⁻¹)), by rwra con_inv_cancel_right at H2, have H4 : P (square_of_eq (eq_of_square s)), by hsimp at H3; apply H3, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H4 @[hott, elab_as_eliminator] def rec_on_tb {a : A} {P : Π{b : A} {l : a = b} {r : a = b}, square idp idp l r → Type _} {b : A} {l : a = b} {r : a = b} (s : square idp idp l r) (H : P ids) : P s := have H2 : P (square_of_eq (eq_of_square s)), begin induction r, hgeneralize: eq_of_square s = es, dsimp at es, induction es, apply H, end, left_inv (square_equiv_eq _ _ _ _).to_fun s ▸ H2 @[hott, elab_as_eliminator] def rec_on_lr {a : A} {P : Π{a' : A} {t : a = a'} {b : a = a'}, square t b idp idp → Type _} {a' : A} {t : a = a'} {b : a = a'} (s : square t b idp idp) (H : P ids) : P s := let p : idp ⬝ b = t := (eq_of_square s)⁻¹ in have H2 : P (square_of_eq (eq_of_square s)⁻¹⁻¹), from @eq.rec_on _ _ (λx q, P (square_of_eq q⁻¹)) _ p (by induction b; exact H), have H3 : square_of_eq (eq_of_square s) = s, from left_inv (square_equiv_eq _ _ _ _).to_fun s, by rwra [inv_inv, H3] at H2 --we can also do the other recursors (tl, tr, bl, br, tbl, tbr, tlr, blr), but let's postpone this until they are needed @[hott] def whisker_square (r₁₀ : p₁₀ = p₁₀') (r₁₂ : p₁₂ = p₁₂') (r₀₁ : p₀₁ = p₀₁') (r₂₁ : p₂₁ = p₂₁') (s : square p₁₀ p₁₂ p₀₁ p₂₁) : square p₁₀' p₁₂' p₀₁' p₂₁' := by induction r₁₀; induction r₁₂; induction r₀₁; induction r₂₁; exact s /- squares commute with some operations on 2-paths -/ @[hott] def square_inv2 {p₁ p₂ p₃ p₄ : a = a'} {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} (s : square t b l r) : square (inverse2 t) (inverse2 b) (inverse2 l) (inverse2 r) := by induction s;constructor @[hott] def square_con2 {p₁ p₂ p₃ p₄ : a₁ = a₂} {q₁ q₂ q₃ q₄ : a₂ = a₃} {t₁ : p₁ = p₂} {b₁ : p₃ = p₄} {l₁ : p₁ = p₃} {r₁ : p₂ = p₄} {t₂ : q₁ = q₂} {b₂ : q₃ = q₄} {l₂ : q₁ = q₃} {r₂ : q₂ = q₄} (s₁ : square t₁ b₁ l₁ r₁) (s₂ : square t₂ b₂ l₂ r₂) : square (t₁ ◾ t₂) (b₁ ◾ b₂) (l₁ ◾ l₂) (r₁ ◾ r₂) := by induction s₂;induction s₁;constructor open is_trunc @[hott] def is_set.elims [H : is_set A] : square p₁₀ p₁₂ p₀₁ p₂₁ := square_of_eq (is_set.elim _ _) @[hott, instance] def is_trunc_square (n : trunc_index) [H : is_trunc n .+2 A] : is_trunc n (square p₁₀ p₁₂ p₀₁ p₂₁) := is_trunc_equiv_closed_rev n (square_equiv_eq _ _ _ _) (by apply_instance) -- @[hott] def square_of_con_inv_hsquare {p₁ p₂ p₃ p₄ : a₁ = a₂} -- {t : p₁ = p₂} {b : p₃ = p₄} {l : p₁ = p₃} {r : p₂ = p₄} -- (s : square (con_inv_eq_idp t) (con_inv_eq_idp b) (l ◾ r⁻²) idp) -- : square t b l r := -- sorry --by induction s /- Square fillers -/ -- TODO replace by "more algebraic" fillers? variables (p₁₀ p₁₂ p₀₁ p₂₁) @[hott] def square_fill_t : Σ (p : a₀₀ = a₂₀), square p p₁₂ p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, vrefl _⟩ @[hott] def square_fill_b : Σ (p : a₀₂ = a₂₂), square p₁₀ p p₀₁ p₂₁ := by induction p₀₁; induction p₂₁; exact ⟨_, vrefl _⟩ @[hott] def square_fill_l : Σ (p : a₀₀ = a₀₂), square p₁₀ p₁₂ p p₂₁ := by induction p₁₀; induction p₁₂; exact ⟨_, hrefl _⟩ @[hott] def square_fill_r : Σ (p : a₂₀ = a₂₂) , square p₁₀ p₁₂ p₀₁ p := by induction p₁₀; induction p₁₂; exact ⟨_, hrefl _⟩ /- Squares having an 'ap' term on one face -/ --TODO find better names @[hott] def square_Flr_ap_idp {c : B} {f : A → B} (p : Π a, f a = c) {a b : A} (q : a = b) : square (p a) (p b) (ap f q) idp := by induction q; apply vrfl @[hott] def square_Flr_idp_ap {c : B} {f : A → B} (p : Π a, c = f a) {a b : A} (q : a = b) : square (p a) (p b) idp (ap f q) := by induction q; apply vrfl @[hott] def square_ap_idp_Flr {b : B} {f : A → B} (p : Π a, f a = b) {a b : A} (q : a = b) : square (ap f q) idp (p a) (p b) := by induction q; apply hrfl /- Matching eq_hconcat with hconcat etc. -/ -- TODO maybe rename hconcat_eq and the like? variable (s₁₁) @[hott] def ph_eq_pv_h_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) : r ⬝ph s₁₁ = !idp_con⁻¹ ⬝pv ((hdeg_square r) ⬝h s₁₁) ⬝vp !idp_con := by induction r; induction s₁₁; refl @[hott] def hdeg_h_eq_pv_ph_vp {p : a₀₀ = a₀₂} (r : p = p₀₁) : hdeg_square r ⬝h s₁₁ = !idp_con ⬝pv (r ⬝ph s₁₁) ⬝vp !idp_con⁻¹ := by induction r; induction s₁₁; refl @[hott] def hp_eq_h {p : a₂₀ = a₂₂} (r : p₂₁ = p) : s₁₁ ⬝hp r = s₁₁ ⬝h hdeg_square r := by induction r; induction s₁₁; refl @[hott] def pv_eq_ph_vdeg_v_vh {p : a₀₀ = a₂₀} (r : p = p₁₀) : r ⬝pv s₁₁ = !idp_con⁻¹ ⬝ph ((vdeg_square r) ⬝v s₁₁) ⬝hp !idp_con := by induction r; induction s₁₁; refl @[hott] def vdeg_v_eq_ph_pv_hp {p : a₀₀ = a₂₀} (r : p = p₁₀) : vdeg_square r ⬝v s₁₁ = !idp_con ⬝ph (r ⬝pv s₁₁) ⬝hp !idp_con⁻¹ := by induction r; induction s₁₁; refl @[hott] def vp_eq_v {p : a₀₂ = a₂₂} (r : p₁₂ = p) : s₁₁ ⬝vp r = s₁₁ ⬝v vdeg_square r := by induction r; induction s₁₁; refl @[hott] def natural_square {f g : A → B} (p : f ~ g) (q : a = a') : square (p a) (p a') (ap f q) (ap g q) := square_of_pathover (apd p q) @[hott] def natural_square_tr {f g : A → B} (p : f ~ g) (q : a = a') : square (ap f q) (ap g q) (p a) (p a') := transpose (natural_square p q) @[hott] def natural_square011 {A A' : Type _} {B : A → Type _} {a a' : A} {p : a = a'} {b : B a} {b' : B a'} (q : b =[p] b') {l r : Π⦃a⦄, B a → A'} (g : Π⦃a⦄ (b : B a), l b = r b) : square (apd011 l p q) (apd011 r p q) (g b) (g b') := begin induction q, exact hrfl end @[hott] def natural_square0111' {A A' : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'} {c : C b} {c' : C b'} (s : c =[apd011 C p q; id] c') {l r : Π⦃a⦄ {b : B a}, C b → A'} (g : Π⦃a⦄ {b : B a} (c : C b), l c = r c) : square (apd0111 l p q s) (apd0111 r p q s) (g c) (g c') := begin induction q, dsimp at s, apply idp_rec_on s, exact hrfl end -- this can be generalized a bit, by making the domain and codomain of k different, and also have -- a function at the RHS of s (similar to m) @[hott] def natural_square0111 {A A' : Type _} {B : A → Type _} (C : Π⦃a⦄, B a → Type _) {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {q : b =[p] b'} {c : C b} {c' : C b'} (r : c =[apd011 C p q; id] c') {k : A → A} {l : Π⦃a⦄, B a → B (k a)} (m : Π⦃a⦄ {b : B a}, C b → C (l b)) {f : Π⦃a⦄ {b : B a}, C b → A'} (s : Π⦃a⦄ {b : B a} (c : C b), f (m c) = f c) : square (apd0111 (λa b (c : C b), f (m c)) p q r) (apd0111 f p q r) (s c) (s c') := begin induction q, dsimp at r, apply idp_rec_on r, exact hrfl end /- some higher coherence conditions -/ @[hott] theorem whisker_bl_whisker_tl_eq (p : a = a') : whisker_bl p (whisker_tl p ids) = con.right_inv p ⬝ph vrfl := by induction p; reflexivity @[hott] theorem ap_is_constant_natural_square {g : B → C} {f : A → B} (H : Πa, g (f a) = c) (p : a = a') : (ap_is_constant H p)⁻¹ ⬝ph natural_square H p ⬝hp ap_constant p c = whisker_bl (H a') (whisker_tl (H a) ids) := begin induction p, dsimp [ap_is_constant], rwr [inv_inv, whisker_bl_whisker_tl_eq] end @[hott] def inv_ph_eq_of_eq_ph {p : a₀₀ = a₀₂} {r : p₀₁ = p} {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₁₁' : square p₁₀ p₁₂ p p₂₁} (t : s₁₁ = r ⬝ph s₁₁') : r⁻¹ ⬝ph s₁₁ = s₁₁' := by induction r; exact t -- the following is used for torus.elim_surf @[hott] theorem whisker_square_aps_eq {f : A → B} {q₁₀ : f a₀₀ = f a₂₀} {q₀₁ : f a₀₀ = f a₀₂} {q₂₁ : f a₂₀ = f a₂₂} {q₁₂ : f a₀₂ = f a₂₂} {r₁₀ : ap f p₁₀ = q₁₀} {r₀₁ : ap f p₀₁ = q₀₁} {r₂₁ : ap f p₂₁ = q₂₁} {r₁₂ : ap f p₁₂ = q₁₂} {s₁₁ : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} {t₁₁ : square q₁₀ q₁₂ q₀₁ q₂₁} (u : square (ap02 f s₁₁) (eq_of_square t₁₁) (ap_con f p₁₀ p₂₁ ⬝ (r₁₀ ◾ r₂₁)) (ap_con f p₀₁ p₁₂ ⬝ (r₀₁ ◾ r₁₂))) : whisker_square r₁₀ r₁₂ r₀₁ r₂₁ (aps f (square_of_eq s₁₁)) = t₁₁ := begin induction r₁₀, induction r₀₁, induction r₁₂, induction r₂₁, induction p₁₂, induction p₁₀, induction p₂₁, dsimp at *, induction s₁₁, dsimp at *, dsimp [square_of_eq], apply eq_of_fn_eq_fn (square_equiv_eq _ _ _ _), dsimp, exact (eq_bot_of_square u)⁻¹ end @[hott] def natural_square_eq {A B : Type _} {a a' : A} {f g : A → B} (p : f ~ g) (q : a = a') : natural_square p q = square_of_pathover (apd p q) := idp @[hott] def eq_of_square_hrfl_hconcat_eq {A : Type _} {a a' : A} {p p' : a = a'} (q : p = p') : eq_of_square (hrfl ⬝hp q⁻¹) = !idp_con ⬝ q := by induction q; induction p; reflexivity @[hott, hsimp] def aps_vrfl {A B : Type _} {a a' : A} (f : A → B) (p : a = a') : aps f (vrefl p) = vrefl (ap f p) := by induction p; reflexivity @[hott, hsimp] def aps_hrfl {A B : Type _} {a a' : A} (f : A → B) (p : a = a') : aps f (hrefl p) = hrefl (ap f p) := by induction p; reflexivity -- should the following two equalities be cubes? @[hott] def natural_square_ap_fn {A B C : Type _} {a a' : A} {g h : A → B} (f : B → C) (p : g ~ h) (q : a = a') : natural_square (λa, ap f (p a)) q = ap_compose f g q ⬝ph (aps f (natural_square p q) ⬝hp (ap_compose f h q)⁻¹) := begin induction q, exact (aps_vrfl _ _).inverse end @[hott] def natural_square_compose {A B C : Type _} {a a' : A} {g g' : B → C} (p : g ~ g') (f : A → B) (q : a = a') : natural_square (λa, p (f a)) q = ap_compose g f q ⬝ph (natural_square p (ap f q) ⬝hp (ap_compose g' f q)⁻¹) := by induction q; reflexivity @[hott] def natural_square_eq2 {A B : Type _} {a a' : A} {f f' : A → B} (p : f ~ f') {q q' : a = a'} (r : q = q') : natural_square p q = ap02 f r ⬝ph (natural_square p q' ⬝hp (ap02 f' r)⁻¹) := by induction r; reflexivity @[hott, hsimp] def natural_square_refl {A B : Type _} {a a' : A} (f : A → B) (q : a = a') : natural_square (homotopy.refl f) q = hrfl := by induction q; reflexivity @[hott] def aps_eq_hconcat {p₀₁'} (f : A → B) (q : p₀₁' = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) : aps f (q ⬝ph s₁₁) = ap02 f q ⬝ph aps f s₁₁ := by induction q; reflexivity @[hott] def aps_hconcat_eq {p₂₁'} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁' = p₂₁) : aps f (s₁₁ ⬝hp r⁻¹) = aps f s₁₁ ⬝hp (ap02 f r)⁻¹ := by induction r; reflexivity @[hott] def aps_hconcat_eq' {p₂₁'} (f : A → B) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁ = p₂₁') : aps f (s₁₁ ⬝hp r) = aps f s₁₁ ⬝hp ap02 f r := by induction r; reflexivity @[hott] def aps_square_of_eq (f : A → B) (s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂) : aps f (square_of_eq s) = square_of_eq ((ap_con f p₁₀ p₂₁)⁻¹ ⬝ ap02 f s ⬝ ap_con f p₀₁ p₁₂) := by induction p₁₂; dsimp at *; induction s; induction p₂₁; induction p₁₀; reflexivity @[hott] def aps_eq_hconcat_eq {p₀₁' p₂₁'} (f : A → B) (q : p₀₁' = p₀₁) (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) (r : p₂₁' = p₂₁) : aps f (q ⬝ph s₁₁ ⬝hp r⁻¹) = ap02 f q ⬝ph aps f s₁₁ ⬝hp (ap02 f r)⁻¹ := by induction q; induction r; reflexivity end eq end hott
f04b1685e8e8d25920f1482d06836ede86a1d94d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/set_auto.lean
d390519c93d2b33f7214852ea4ef1bd8184d721c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,615
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.interactive import Mathlib.Lean3Lib.init.control.lawful universes u v u_1 namespace Mathlib def set (α : Type u) := α → Prop def set_of {α : Type u} (p : α → Prop) : set α := p namespace set protected def mem {α : Type u} (a : α) (s : set α) := s a protected instance has_mem {α : Type u} : has_mem α (set α) := has_mem.mk set.mem protected def subset {α : Type u} (s₁ : set α) (s₂ : set α) := ∀ {a : α}, a ∈ s₁ → a ∈ s₂ protected instance has_subset {α : Type u} : has_subset (set α) := has_subset.mk set.subset protected def sep {α : Type u} (p : α → Prop) (s : set α) : set α := set_of fun (a : α) => a ∈ s ∧ p a protected instance has_sep {α : Type u} : has_sep α (set α) := has_sep.mk set.sep protected instance has_emptyc {α : Type u} : has_emptyc (set α) := has_emptyc.mk fun (a : α) => False def univ {α : Type u} : set α := fun (a : α) => True protected def insert {α : Type u} (a : α) (s : set α) : set α := set_of fun (b : α) => b = a ∨ b ∈ s protected instance has_insert {α : Type u} : has_insert α (set α) := has_insert.mk set.insert protected instance has_singleton {α : Type u} : has_singleton α (set α) := has_singleton.mk fun (a : α) => set_of fun (b : α) => b = a protected instance is_lawful_singleton {α : Type u} : is_lawful_singleton α (set α) := is_lawful_singleton.mk fun (a : α) => funext fun (b : α) => propext (or_false (b = a)) protected def union {α : Type u} (s₁ : set α) (s₂ : set α) : set α := set_of fun (a : α) => a ∈ s₁ ∨ a ∈ s₂ protected instance has_union {α : Type u} : has_union (set α) := has_union.mk set.union protected def inter {α : Type u} (s₁ : set α) (s₂ : set α) : set α := set_of fun (a : α) => a ∈ s₁ ∧ a ∈ s₂ protected instance has_inter {α : Type u} : has_inter (set α) := has_inter.mk set.inter def compl {α : Type u} (s : set α) : set α := set_of fun (a : α) => ¬a ∈ s protected def diff {α : Type u} (s : set α) (t : set α) : set α := has_sep.sep (fun (a : α) => ¬a ∈ t) s protected instance has_sdiff {α : Type u} : has_sdiff (set α) := has_sdiff.mk set.diff def powerset {α : Type u} (s : set α) : set (set α) := set_of fun (t : set α) => t ⊆ s prefix:100 "𝒫" => Mathlib.set.powerset def sUnion {α : Type u} (s : set (set α)) : set α := set_of fun (t : α) => ∃ (a : set α), ∃ (H : a ∈ s), t ∈ a prefix:110 "⋃₀" => Mathlib.set.sUnion def image {α : Type u} {β : Type v} (f : α → β) (s : set α) : set β := set_of fun (b : β) => ∃ (a : α), a ∈ s ∧ f a = b protected instance functor : Functor set := { map := image, mapConst := fun (α β : Type u_1) => image ∘ function.const β } protected instance is_lawful_functor : is_lawful_functor set := is_lawful_functor.mk (fun (_x : Type u_1) (s : set _x) => funext fun (b : _x) => propext { mp := fun (_x : Functor.map id s b) => sorry, mpr := fun (sb : s b) => Exists.intro b { left := sb, right := rfl } }) fun (_x _x_1 _x_2 : Type u_1) (g : _x → _x_1) (h : _x_1 → _x_2) (s : set _x) => funext fun (c : _x_2) => propext { mp := fun (_x : Functor.map (h ∘ g) s c) => sorry, mpr := fun (_x : Functor.map h (g <$> s) c) => sorry } end Mathlib
b0a83f4deadf78be5fc692455f84d58b068bd3e1
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/tactic/interactive.lean
549b3fc593ebd5d0f91dde847731272e174dffc4
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,291
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.dlist tactic.rcases open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr meta def rcases_parse : parser (list rcases_patt) := with_desc "patt" $ let p := (rcases_patt.one <$> ident_) <|> (rcases_patt.many <$> brackets "⟨" "⟩" (sep_by (tk ",") rcases_parse)) in list.cons <$> p <*> (tk "|" *> p)* meta def rcases_parse.invert : list rcases_patt → list (list rcases_patt) := let invert' (l : list rcases_patt) : rcases_patt := match l with | [k] := k | _ := rcases_patt.many (rcases_parse.invert l) end in list.map $ λ p, match p with | rcases_patt.one n := [rcases_patt.one n] | rcases_patt.many l := invert' <$> l end /-- The `rcases` tactic is the same as `cases`, but with more flexibility in the `with` pattern syntax to allow for recursive case splitting. The pattern syntax uses the following recursive grammar: ``` patt ::= (patt_list "|")* patt_list patt_list ::= id | "_" | "⟨" (patt ",")* patt "⟩" ``` A pattern like `⟨a, b, c⟩ | ⟨d, e⟩` will do a split over the inductive datatype, naming the first three parameters of the first constructor as `a,b,c` and the first two of the second constructor `d,e`. If the list is not as long as the number of arguments to the constructor or the number of constructors, the remaining variables will be automatically named. If there are nested brackets such as `⟨⟨a⟩, b | c⟩ | d` then these will cause more case splits as necessary. If there are too many arguments, such as `⟨a, b, c⟩` for splitting on `∃ x, ∃ y, p x`, then it will be treated as `⟨a, ⟨b, c⟩⟩`, splitting the last parameter as necessary. -/ meta def rcases (p : parse texpr) (ids : parse (tk "with" *> rcases_parse)?) : tactic unit := tactic.rcases p $ rcases_parse.invert $ ids.get_or_else [default _] /-- This is a "finishing" tactic modification of `simp`. The tactic `simpa [rules, ...] using e` will simplify the hypothesis `e` using `rules`, then simplify the goal using `rules`, and try to close the goal using `assumption`. If `e` is a term instead of a local constant, it is first added to the local context using `have`. -/ meta def simpa (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit := do lc ← match tgt with | none := get_local `this >> pure [some `this, none] <|> pure [none] | some e := do e ← i_to_expr e, match e with | local_const _ lc _ _ := pure [some lc, none] | e := do t ← infer_type e, assertv `this t e >> pure [some `this, none] end end, simp no_dflt hs attr_names (loc.ns lc) cfg >> (assumption <|> trivial) meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, tactic.try_for max tac <|> (tactic.trace "try_for timeout, using sorry" >> admit) meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) end interactive end tactic
7b23f1b2c7165fd62e3e827984aeb75eb4058b5e
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/monoidal/of_chosen_finite_products.lean
5c8057bd821a43bbe925ec567f8d204a66997388
[ "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
15,917
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Simon Hudon -/ import category_theory.monoidal.braided import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal import category_theory.pempty /-! # The monoidal structure on a category with chosen finite products. This is a variant of the development in `category_theory.monoidal.of_has_finite_products`, which uses specified choices of the terminal object and binary product, enabling the construction of a cartesian category with specific definitions of the tensor unit and tensor product. (Because the construction in `category_theory.monoidal.of_has_finite_products` uses `has_limit` classes, the actual definitions there are opaque behind `classical.choice`.) We use this in `category_theory.monoidal.types` to construct the monoidal category of types so that the tensor product is the usual cartesian product of types. For now we only do the construction from products, and not from coproducts, which seems less often useful. -/ universes v u noncomputable theory namespace category_theory variables (C : Type u) [category.{v} C] {X Y : C} namespace limits section variables {C} /-- Swap the two sides of a `binary_fan`. -/ def binary_fan.swap {P Q : C} (t : binary_fan P Q) : binary_fan Q P := binary_fan.mk t.snd t.fst @[simp] lemma binary_fan.swap_fst {P Q : C} (t : binary_fan P Q) : t.swap.fst = t.snd := rfl @[simp] lemma binary_fan.swap_snd {P Q : C} (t : binary_fan P Q) : t.swap.snd = t.fst := rfl /-- If a cone `t` over `P Q` is a limit cone, then `t.swap` is a limit cone over `Q P`. -/ @[simps] def is_limit.swap_binary_fan {P Q : C} {t : binary_fan P Q} (I : is_limit t) : is_limit t.swap := { lift := λ s, I.lift (binary_fan.swap s), fac' := λ s, by { rintro ⟨⟩; simp, }, uniq' := λ s m w, begin have h := I.uniq (binary_fan.swap s) m, rw h, intro j, specialize w j.swap, cases j; exact w, end } /-- Construct `has_binary_product Q P` from `has_binary_product P Q`. This can't be an instance, as it would cause a loop in typeclass search. -/ lemma has_binary_product.swap (P Q : C) [has_binary_product P Q] : has_binary_product Q P := has_limit.mk ⟨binary_fan.swap (limit.cone (pair P Q)), (limit.is_limit (pair P Q)).swap_binary_fan⟩ /-- Given a limit cone over `X` and `Y`, and another limit cone over `Y` and `X`, we can construct an isomorphism between the cone points. Relative to some fixed choice of limits cones for every pair, these isomorphisms constitute a braiding. -/ def binary_fan.braiding {X Y : C} {s : binary_fan X Y} (P : is_limit s) {t : binary_fan Y X} (Q : is_limit t) : s.X ≅ t.X := is_limit.cone_point_unique_up_to_iso P Q.swap_binary_fan /-- Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `sXY.X Z`, if `sYZ` is a limit cone we can construct a binary fan over `X sYZ.X`. This is an ingredient of building the associator for a cartesian category. -/ def binary_fan.assoc {X Y Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) : binary_fan X sYZ.X := binary_fan.mk (s.fst ≫ sXY.fst) (Q.lift (binary_fan.mk (s.fst ≫ sXY.snd) s.snd)) @[simp] lemma binary_fan.assoc_fst {X Y Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) : (s.assoc Q).fst = s.fst ≫ sXY.fst := rfl @[simp] lemma binary_fan.assoc_snd {X Y Z : C} {sXY : binary_fan X Y} {sYZ : binary_fan Y Z} (Q : is_limit sYZ) (s : binary_fan sXY.X Z) : (s.assoc Q).snd = Q.lift (binary_fan.mk (s.fst ≫ sXY.snd) s.snd) := rfl /-- Given binary fans `sXY` over `X Y`, and `sYZ` over `Y Z`, and `s` over `X sYZ.X`, if `sYZ` is a limit cone we can construct a binary fan over `sXY.X Z`. This is an ingredient of building the associator for a cartesian category. -/ def binary_fan.assoc_inv {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) : binary_fan sXY.X Z := binary_fan.mk (P.lift (binary_fan.mk s.fst (s.snd ≫ sYZ.fst))) (s.snd ≫ sYZ.snd) @[simp] lemma binary_fan.assoc_inv_fst {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) : (s.assoc_inv P).fst = P.lift (binary_fan.mk s.fst (s.snd ≫ sYZ.fst)) := rfl @[simp] lemma binary_fan.assoc_inv_snd {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (s : binary_fan X sYZ.X) : (s.assoc_inv P).snd = s.snd ≫ sYZ.snd := rfl /-- If all the binary fans involved a limit cones, `binary_fan.assoc` produces another limit cone. -/ @[simps] def is_limit.assoc {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ) {s : binary_fan sXY.X Z} (R : is_limit s) : is_limit (s.assoc Q) := { lift := λ t, R.lift (binary_fan.assoc_inv P t), fac' := λ t, begin rintro ⟨⟩; simp, apply Q.hom_ext, rintro ⟨⟩; simp, end, uniq' := λ t m w, begin have h := R.uniq (binary_fan.assoc_inv P t) m, rw h, rintro ⟨⟩; simp, apply P.hom_ext, rintro ⟨⟩; simp, { exact w walking_pair.left, }, { specialize w walking_pair.right, simp at w, rw [←w], simp, }, { specialize w walking_pair.right, simp at w, rw [←w], simp, }, end, } /-- Given two pairs of limit cones corresponding to the parenthesisations of `X × Y × Z`, we obtain an isomorphism between the cone points. -/ @[reducible] def binary_fan.associator {X Y Z : C} {sXY : binary_fan X Y} (P : is_limit sXY) {sYZ : binary_fan Y Z} (Q : is_limit sYZ) {s : binary_fan sXY.X Z} (R : is_limit s) {t : binary_fan X sYZ.X} (S : is_limit t) : s.X ≅ t.X := is_limit.cone_point_unique_up_to_iso (is_limit.assoc P Q R) S /-- Given a fixed family of limit data for every pair `X Y`, we obtain an associator. -/ @[reducible] def binary_fan.associator_of_limit_cone (L : Π X Y : C, limit_cone (pair X Y)) (X Y Z : C) : (L (L X Y).cone.X Z).cone.X ≅ (L X (L Y Z).cone.X).cone.X := binary_fan.associator (L X Y).is_limit (L Y Z).is_limit (L (L X Y).cone.X Z).is_limit (L X (L Y Z).cone.X).is_limit /-- Construct a left unitor from specified limit cones. -/ @[simps] def binary_fan.left_unitor {X : C} {s : cone (functor.empty.{v} C)} (P : is_limit s) {t : binary_fan s.X X} (Q : is_limit t) : t.X ≅ X := { hom := t.snd, inv := Q.lift (binary_fan.mk (P.lift { X := X, π := { app := pempty.rec _ } }) (𝟙 X) ), hom_inv_id' := by { apply Q.hom_ext, rintro ⟨⟩, { apply P.hom_ext, rintro ⟨⟩, }, { simp, }, }, } /-- Construct a right unitor from specified limit cones. -/ @[simps] def binary_fan.right_unitor {X : C} {s : cone (functor.empty.{v} C)} (P : is_limit s) {t : binary_fan X s.X} (Q : is_limit t) : t.X ≅ X := { hom := t.fst, inv := Q.lift (binary_fan.mk (𝟙 X) (P.lift { X := X, π := { app := pempty.rec _ } })), hom_inv_id' := by { apply Q.hom_ext, rintro ⟨⟩, { simp, }, { apply P.hom_ext, rintro ⟨⟩, }, }, } end end limits open category_theory.limits section local attribute [tidy] tactic.case_bash variables {C} variables (𝒯 : limit_cone (functor.empty.{v} C)) variables (ℬ : Π (X Y : C), limit_cone (pair X Y)) namespace monoidal_of_chosen_finite_products /-- Implementation of the tensor product for `monoidal_of_chosen_finite_products`. -/ @[reducible] def tensor_obj (X Y : C) : C := (ℬ X Y).cone.X /-- Implementation of the tensor product of morphisms for `monoidal_of_chosen_finite_products`. -/ @[reducible] def tensor_hom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : tensor_obj ℬ W Y ⟶ tensor_obj ℬ X Z := (binary_fan.is_limit.lift' (ℬ X Z).is_limit ((ℬ W Y).cone.π.app walking_pair.left ≫ f) (((ℬ W Y).cone.π.app walking_pair.right : (ℬ W Y).cone.X ⟶ Y) ≫ g)).val lemma tensor_id (X₁ X₂ : C) : tensor_hom ℬ (𝟙 X₁) (𝟙 X₂) = 𝟙 (tensor_obj ℬ X₁ X₂) := begin apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩; { dsimp [tensor_hom], simp, }, end lemma tensor_comp {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom ℬ (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom ℬ f₁ f₂ ≫ tensor_hom ℬ g₁ g₂ := begin apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩; { dsimp [tensor_hom], simp, }, end lemma pentagon (W X Y Z : C) : tensor_hom ℬ (binary_fan.associator_of_limit_cone ℬ W X Y).hom (𝟙 Z) ≫ (binary_fan.associator_of_limit_cone ℬ W (tensor_obj ℬ X Y) Z).hom ≫ tensor_hom ℬ (𝟙 W) (binary_fan.associator_of_limit_cone ℬ X Y Z).hom = (binary_fan.associator_of_limit_cone ℬ (tensor_obj ℬ W X) Y Z).hom ≫ (binary_fan.associator_of_limit_cone ℬ W X (tensor_obj ℬ Y Z)).hom := begin dsimp [tensor_hom], apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩, { simp, }, { apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩, { simp, }, apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩, { simp, }, { simp, }, } end lemma triangle (X Y : C) : (binary_fan.associator_of_limit_cone ℬ X 𝒯.cone.X Y).hom ≫ tensor_hom ℬ (𝟙 X) (binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X Y).is_limit).hom = tensor_hom ℬ (binary_fan.right_unitor 𝒯.is_limit (ℬ X 𝒯.cone.X).is_limit).hom (𝟙 Y) := begin dsimp [tensor_hom], apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩; simp, end lemma left_unitor_naturality {X₁ X₂ : C} (f : X₁ ⟶ X₂) : tensor_hom ℬ (𝟙 𝒯.cone.X) f ≫ (binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X X₂).is_limit).hom = (binary_fan.left_unitor 𝒯.is_limit (ℬ 𝒯.cone.X X₁).is_limit).hom ≫ f := begin dsimp [tensor_hom], simp, end lemma right_unitor_naturality {X₁ X₂ : C} (f : X₁ ⟶ X₂) : tensor_hom ℬ f (𝟙 𝒯.cone.X) ≫ (binary_fan.right_unitor 𝒯.is_limit (ℬ X₂ 𝒯.cone.X).is_limit).hom = (binary_fan.right_unitor 𝒯.is_limit (ℬ X₁ 𝒯.cone.X).is_limit).hom ≫ f := begin dsimp [tensor_hom], simp, end lemma associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom ℬ (tensor_hom ℬ f₁ f₂) f₃ ≫ (binary_fan.associator_of_limit_cone ℬ Y₁ Y₂ Y₃).hom = (binary_fan.associator_of_limit_cone ℬ X₁ X₂ X₃).hom ≫ tensor_hom ℬ f₁ (tensor_hom ℬ f₂ f₃) := begin dsimp [tensor_hom], apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩, { simp, }, { apply is_limit.hom_ext (ℬ _ _).is_limit, rintro ⟨⟩, { simp, }, { simp, }, }, end end monoidal_of_chosen_finite_products open monoidal_of_chosen_finite_products /-- A category with a terminal object and binary products has a natural monoidal structure. -/ def monoidal_of_chosen_finite_products : monoidal_category C := { tensor_unit := 𝒯.cone.X, tensor_obj := λ X Y, tensor_obj ℬ X Y, tensor_hom := λ _ _ _ _ f g, tensor_hom ℬ f g, tensor_id' := tensor_id ℬ, tensor_comp' := λ _ _ _ _ _ _ f₁ f₂ g₁ g₂, tensor_comp ℬ f₁ f₂ g₁ g₂, associator := λ X Y Z, binary_fan.associator_of_limit_cone ℬ X Y Z, left_unitor := λ X, binary_fan.left_unitor (𝒯.is_limit) (ℬ 𝒯.cone.X X).is_limit, right_unitor := λ X, binary_fan.right_unitor (𝒯.is_limit) (ℬ X 𝒯.cone.X).is_limit, pentagon' := pentagon ℬ, triangle' := triangle 𝒯 ℬ, left_unitor_naturality' := λ _ _ f, left_unitor_naturality 𝒯 ℬ f, right_unitor_naturality' := λ _ _ f, right_unitor_naturality 𝒯 ℬ f, associator_naturality' := λ _ _ _ _ _ _ f₁ f₂ f₃, associator_naturality ℬ f₁ f₂ f₃, } namespace monoidal_of_chosen_finite_products open monoidal_category /-- A type synonym for `C` carrying a monoidal category structure corresponding to a fixed choice of limit data for the empty functor, and for `pair X Y` for every `X Y : C`. This is an implementation detail for `symmetric_of_chosen_finite_products`. -/ @[derive category, nolint unused_arguments has_inhabited_instance] def monoidal_of_chosen_finite_products_synonym (𝒯 : limit_cone (functor.empty.{v} C)) (ℬ : Π (X Y : C), limit_cone (pair X Y)):= C instance : monoidal_category (monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) := monoidal_of_chosen_finite_products 𝒯 ℬ lemma braiding_naturality {X X' Y Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y') : (tensor_hom ℬ f g) ≫ (limits.binary_fan.braiding (ℬ Y Y').is_limit (ℬ Y' Y).is_limit).hom = (limits.binary_fan.braiding (ℬ X X').is_limit (ℬ X' X).is_limit).hom ≫ (tensor_hom ℬ g f) := begin dsimp [tensor_hom, limits.binary_fan.braiding], apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩; { dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, end lemma hexagon_forward (X Y Z : C) : (binary_fan.associator_of_limit_cone ℬ X Y Z).hom ≫ (limits.binary_fan.braiding (ℬ X (tensor_obj ℬ Y Z)).is_limit (ℬ (tensor_obj ℬ Y Z) X).is_limit).hom ≫ (binary_fan.associator_of_limit_cone ℬ Y Z X).hom = (tensor_hom ℬ (limits.binary_fan.braiding (ℬ X Y).is_limit (ℬ Y X).is_limit).hom (𝟙 Z)) ≫ (binary_fan.associator_of_limit_cone ℬ Y X Z).hom ≫ (tensor_hom ℬ (𝟙 Y) (limits.binary_fan.braiding (ℬ X Z).is_limit (ℬ Z X).is_limit).hom) := begin dsimp [tensor_hom, limits.binary_fan.braiding], apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩, { dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, { apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩; { dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, } end lemma hexagon_reverse (X Y Z : C) : (binary_fan.associator_of_limit_cone ℬ X Y Z).inv ≫ (limits.binary_fan.braiding (ℬ (tensor_obj ℬ X Y) Z).is_limit (ℬ Z (tensor_obj ℬ X Y)).is_limit).hom ≫ (binary_fan.associator_of_limit_cone ℬ Z X Y).inv = (tensor_hom ℬ (𝟙 X) (limits.binary_fan.braiding (ℬ Y Z).is_limit (ℬ Z Y).is_limit).hom) ≫ (binary_fan.associator_of_limit_cone ℬ X Z Y).inv ≫ (tensor_hom ℬ (limits.binary_fan.braiding (ℬ X Z).is_limit (ℬ Z X).is_limit).hom (𝟙 Y)) := begin dsimp [tensor_hom, limits.binary_fan.braiding], apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩, { apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩; { dsimp [binary_fan.associator_of_limit_cone, binary_fan.associator, limits.is_limit.cone_point_unique_up_to_iso], simp, }, }, { dsimp [binary_fan.associator_of_limit_cone, binary_fan.associator, limits.is_limit.cone_point_unique_up_to_iso], simp, }, end lemma symmetry (X Y : C) : (limits.binary_fan.braiding (ℬ X Y).is_limit (ℬ Y X).is_limit).hom ≫ (limits.binary_fan.braiding (ℬ Y X).is_limit (ℬ X Y).is_limit).hom = 𝟙 (tensor_obj ℬ X Y) := begin dsimp [tensor_hom, limits.binary_fan.braiding], apply (ℬ _ _).is_limit.hom_ext, rintro ⟨⟩; { dsimp [limits.is_limit.cone_point_unique_up_to_iso], simp, }, end end monoidal_of_chosen_finite_products open monoidal_of_chosen_finite_products /-- The monoidal structure coming from finite products is symmetric. -/ def symmetric_of_chosen_finite_products : symmetric_category (monoidal_of_chosen_finite_products_synonym 𝒯 ℬ) := { braiding := λ X Y, limits.binary_fan.braiding (ℬ _ _).is_limit (ℬ _ _).is_limit, braiding_naturality' := λ X X' Y Y' f g, braiding_naturality ℬ f g, hexagon_forward' := λ X Y Z, hexagon_forward ℬ X Y Z, hexagon_reverse' := λ X Y Z, hexagon_reverse ℬ X Y Z, symmetry' := λ X Y, symmetry ℬ X Y, } end end category_theory
859f55c7ce9eed738d483725fe81c91be8dd7f38
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/field_theory/algebraic_closure_auto.lean
e3337c51afd98fc107541b64443c2c576765ba50
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
12,686
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.direct_limit import Mathlib.field_theory.splitting_field import Mathlib.analysis.complex.polynomial import Mathlib.PostPort universes u l u_1 u_2 v namespace Mathlib /-! # Algebraic Closure In this file we define the typeclass for algebraically closed fields and algebraic closures. We also construct an algebraic closure for any field. ## Main Definitions - `is_alg_closed k` is the typeclass saying `k` is an algebraically closed field, i.e. every polynomial in `k` splits. - `is_alg_closure k K` is the typeclass saying `K` is an algebraic closure of `k`. - `algebraic_closure k` is an algebraic closure of `k` (in the same universe). It is constructed by taking the polynomial ring generated by indeterminates `x_f` corresponding to monic irreducible polynomials `f` with coefficients in `k`, and quotienting out by a maximal ideal containing every `f(x_f)`, and then repeating this step countably many times. See Exercise 1.13 in Atiyah--Macdonald. ## TODO Show that any algebraic extension embeds into any algebraically closed extension (via Zorn's lemma). ## Tags algebraic closure, algebraically closed -/ /-- Typeclass for algebraically closed fields. -/ class is_alg_closed (k : Type u) [field k] where splits : ∀ (p : polynomial k), polynomial.splits (ring_hom.id k) p theorem polynomial.splits' {k : Type u_1} {K : Type u_2} [field k] [is_alg_closed k] [field K] {f : k →+* K} (p : polynomial k) : polynomial.splits f p := polynomial.splits_of_splits_id f (is_alg_closed.splits p) namespace is_alg_closed theorem of_exists_root (k : Type u) [field k] (H : ∀ (p : polynomial k), polynomial.monic p → irreducible p → ∃ (x : k), polynomial.eval x p = 0) : is_alg_closed k := sorry theorem degree_eq_one_of_irreducible (k : Type u) [field k] [is_alg_closed k] {p : polynomial k} (h_nz : p ≠ 0) (hp : irreducible p) : polynomial.degree p = 1 := polynomial.degree_eq_one_of_irreducible_of_splits h_nz hp (polynomial.splits' p) theorem algebra_map_surjective_of_is_integral {k : Type u_1} {K : Type u_2} [field k] [domain K] [hk : is_alg_closed k] [algebra k K] (hf : algebra.is_integral k K) : function.surjective ⇑(algebra_map k K) := sorry theorem algebra_map_surjective_of_is_integral' {k : Type u_1} {K : Type u_2} [field k] [integral_domain K] [hk : is_alg_closed k] (f : k →+* K) (hf : ring_hom.is_integral f) : function.surjective ⇑f := algebra_map_surjective_of_is_integral hf theorem algebra_map_surjective_of_is_algebraic {k : Type u_1} {K : Type u_2} [field k] [domain K] [hk : is_alg_closed k] [algebra k K] (hf : algebra.is_algebraic k K) : function.surjective ⇑(algebra_map k K) := algebra_map_surjective_of_is_integral (iff.mp (is_algebraic_iff_is_integral' k) hf) end is_alg_closed protected instance complex.is_alg_closed : is_alg_closed ℂ := is_alg_closed.of_exists_root ℂ fun (p : polynomial ℂ) (_x : polynomial.monic p) (hp : irreducible p) => complex.exists_root (polynomial.degree_pos_of_irreducible hp) /-- Typeclass for an extension being an algebraic closure. -/ def is_alg_closure (k : Type u) [field k] (K : Type v) [field K] [algebra k K] := is_alg_closed K ∧ algebra.is_algebraic k K namespace algebraic_closure /-- The subtype of monic irreducible polynomials -/ def monic_irreducible (k : Type u) [field k] := Subtype fun (f : polynomial k) => polynomial.monic f ∧ irreducible f /-- Sends a monic irreducible polynomial `f` to `f(x_f)` where `x_f` is a formal indeterminate. -/ def eval_X_self (k : Type u) [field k] (f : monic_irreducible k) : mv_polynomial (monic_irreducible k) k := polynomial.eval₂ mv_polynomial.C (mv_polynomial.X f) ↑f /-- The span of `f(x_f)` across monic irreducible polynomials `f` where `x_f` is an indeterminate. -/ def span_eval (k : Type u) [field k] : ideal (mv_polynomial (monic_irreducible k) k) := ideal.span (set.range (eval_X_self k)) /-- Given a finset of monic irreducible polynomials, construct an algebra homomorphism to the splitting field of the product of the polynomials sending each indeterminate `x_f` represented by the polynomial `f` in the finset to a root of `f`. -/ def to_splitting_field (k : Type u) [field k] (s : finset (monic_irreducible k)) : alg_hom k (mv_polynomial (monic_irreducible k) k) (polynomial.splitting_field (finset.prod s fun (x : monic_irreducible k) => ↑x)) := mv_polynomial.aeval fun (f : monic_irreducible k) => dite (f ∈ s) (fun (hf : f ∈ s) => polynomial.root_of_splits (algebra_map k (polynomial.splitting_field (finset.prod s fun (x : monic_irreducible k) => ↑x))) sorry sorry) fun (hf : ¬f ∈ s) => bit1 (bit0 (bit1 (bit0 (bit0 1)))) theorem to_splitting_field_eval_X_self (k : Type u) [field k] {s : finset (monic_irreducible k)} {f : monic_irreducible k} (hf : f ∈ s) : coe_fn (to_splitting_field k s) (eval_X_self k f) = 0 := sorry theorem span_eval_ne_top (k : Type u) [field k] : span_eval k ≠ ⊤ := sorry /-- A random maximal ideal that contains `span_eval k` -/ def max_ideal (k : Type u) [field k] : ideal (mv_polynomial (monic_irreducible k) k) := classical.some sorry protected instance max_ideal.is_maximal (k : Type u) [field k] : ideal.is_maximal (max_ideal k) := and.left (classical.some_spec (ideal.exists_le_maximal (span_eval k) (span_eval_ne_top k))) theorem le_max_ideal (k : Type u) [field k] : span_eval k ≤ max_ideal k := and.right (classical.some_spec (ideal.exists_le_maximal (span_eval k) (span_eval_ne_top k))) /-- The first step of constructing `algebraic_closure`: adjoin a root of all monic polynomials -/ def adjoin_monic (k : Type u) [field k] := ideal.quotient (max_ideal k) protected instance adjoin_monic.field (k : Type u) [field k] : field (adjoin_monic k) := ideal.quotient.field (max_ideal k) protected instance adjoin_monic.inhabited (k : Type u) [field k] : Inhabited (adjoin_monic k) := { default := bit1 (bit0 (bit1 (bit0 (bit0 1)))) } /-- The canonical ring homomorphism to `adjoin_monic k`. -/ def to_adjoin_monic (k : Type u) [field k] : k →+* adjoin_monic k := ring_hom.comp (ideal.quotient.mk (max_ideal k)) mv_polynomial.C protected instance adjoin_monic.algebra (k : Type u) [field k] : algebra k (adjoin_monic k) := ring_hom.to_algebra (to_adjoin_monic k) theorem adjoin_monic.algebra_map (k : Type u) [field k] : algebra_map k (adjoin_monic k) = ring_hom.comp (ideal.quotient.mk (max_ideal k)) mv_polynomial.C := rfl theorem adjoin_monic.is_integral (k : Type u) [field k] (z : adjoin_monic k) : is_integral k z := sorry theorem adjoin_monic.exists_root (k : Type u) [field k] {f : polynomial k} (hfm : polynomial.monic f) (hfi : irreducible f) : ∃ (x : adjoin_monic k), polynomial.eval₂ (to_adjoin_monic k) x f = 0 := sorry /-- The `n`th step of constructing `algebraic_closure`, together with its `field` instance. -/ def step_aux (k : Type u) [field k] (n : ℕ) : sigma fun (α : Type u) => field α := nat.rec_on n (sigma.mk k infer_instance) fun (n : ℕ) (ih : sigma fun (α : Type u) => field α) => sigma.mk (adjoin_monic (sigma.fst ih)) (adjoin_monic.field (sigma.fst ih)) /-- The `n`th step of constructing `algebraic_closure`. -/ def step (k : Type u) [field k] (n : ℕ) := sigma.fst (step_aux k n) protected instance step.field (k : Type u) [field k] (n : ℕ) : field (step k n) := sigma.snd (step_aux k n) protected instance step.inhabited (k : Type u) [field k] (n : ℕ) : Inhabited (step k n) := { default := bit1 (bit0 (bit1 (bit0 (bit0 1)))) } /-- The canonical inclusion to the `0`th step. -/ def to_step_zero (k : Type u) [field k] : k →+* step k 0 := ring_hom.id k /-- The canonical ring homomorphism to the next step. -/ def to_step_succ (k : Type u) [field k] (n : ℕ) : step k n →+* step k (n + 1) := to_adjoin_monic (step k n) protected instance step.algebra_succ (k : Type u) [field k] (n : ℕ) : algebra (step k n) (step k (n + 1)) := ring_hom.to_algebra (to_step_succ k n) theorem to_step_succ.exists_root (k : Type u) [field k] {n : ℕ} {f : polynomial (step k n)} (hfm : polynomial.monic f) (hfi : irreducible f) : ∃ (x : step k (n + 1)), polynomial.eval₂ (to_step_succ k n) x f = 0 := adjoin_monic.exists_root (step k n) hfm hfi /-- The canonical ring homomorphism to a step with a greater index. -/ def to_step_of_le (k : Type u) [field k] (m : ℕ) (n : ℕ) (h : m ≤ n) : step k m →+* step k n := ring_hom.mk (nat.le_rec_on h fun (n : ℕ) => ⇑(to_step_succ k n)) sorry sorry sorry sorry @[simp] theorem coe_to_step_of_le (k : Type u) [field k] (m : ℕ) (n : ℕ) (h : m ≤ n) : ⇑(to_step_of_le k m n h) = nat.le_rec_on h fun (n : ℕ) => ⇑(to_step_succ k n) := rfl protected instance step.algebra (k : Type u) [field k] (n : ℕ) : algebra k (step k n) := ring_hom.to_algebra (to_step_of_le k 0 n (nat.zero_le n)) protected instance step.scalar_tower (k : Type u) [field k] (n : ℕ) : is_scalar_tower k (step k n) (step k (n + 1)) := is_scalar_tower.of_algebra_map_eq fun (z : k) => nat.le_rec_on_succ (nat.zero_le n) z theorem step.is_integral (k : Type u) [field k] (n : ℕ) (z : step k n) : is_integral k z := nat.rec_on n (fun (z : step k 0) => is_integral_algebra_map) fun (n : ℕ) (ih : ∀ (z : step k n), is_integral k z) (z : step k (Nat.succ n)) => is_integral_trans ih z (adjoin_monic.is_integral (step k n) z) protected instance to_step_of_le.directed_system (k : Type u) [field k] : directed_system (step k) fun (i j : ℕ) (h : i ≤ j) => ⇑(to_step_of_le k i j h) := directed_system.mk (fun (i : ℕ) (x : step k i) (h : i ≤ i) => nat.le_rec_on_self x) fun (i₁ i₂ i₃ : ℕ) (h₁₂ : i₁ ≤ i₂) (h₂₃ : i₂ ≤ i₃) (x : step k i₁) => Eq.symm (nat.le_rec_on_trans h₁₂ h₂₃ x) end algebraic_closure /-- The canonical algebraic closure of a field, the direct limit of adding roots to the field for each polynomial over the field. -/ def algebraic_closure (k : Type u) [field k] := ring.direct_limit sorry fun (i j : ℕ) (h : i ≤ j) => ⇑sorry namespace algebraic_closure protected instance field (k : Type u) [field k] : field (algebraic_closure k) := field.direct_limit.field (step k) fun (i j : ℕ) (h : i ≤ j) => to_step_of_le k i j h protected instance inhabited (k : Type u) [field k] : Inhabited (algebraic_closure k) := { default := bit1 (bit0 (bit1 (bit0 (bit0 1)))) } /-- The canonical ring embedding from the `n`th step to the algebraic closure. -/ def of_step (k : Type u) [field k] (n : ℕ) : step k n →+* algebraic_closure k := ring_hom.of ⇑(ring.direct_limit.of (step k) (fun (i j : ℕ) (h : i ≤ j) => ⇑(to_step_of_le k i j h)) n) protected instance algebra_of_step (k : Type u) [field k] (n : ℕ) : algebra (step k n) (algebraic_closure k) := ring_hom.to_algebra (of_step k n) theorem of_step_succ (k : Type u) [field k] (n : ℕ) : ring_hom.comp (of_step k (n + 1)) (to_step_succ k n) = of_step k n := sorry theorem exists_of_step (k : Type u) [field k] (z : algebraic_closure k) : ∃ (n : ℕ), ∃ (x : step k n), coe_fn (of_step k n) x = z := ring.direct_limit.exists_of z -- slow theorem exists_root (k : Type u) [field k] {f : polynomial (algebraic_closure k)} (hfm : polynomial.monic f) (hfi : irreducible f) : ∃ (x : algebraic_closure k), polynomial.eval x f = 0 := sorry protected instance is_alg_closed (k : Type u) [field k] : is_alg_closed (algebraic_closure k) := is_alg_closed.of_exists_root (algebraic_closure k) fun (f : polynomial (algebraic_closure k)) => exists_root k protected instance algebra (k : Type u) [field k] : algebra k (algebraic_closure k) := ring_hom.to_algebra (of_step k 0) /-- Canonical algebra embedding from the `n`th step to the algebraic closure. -/ def of_step_hom (k : Type u) [field k] (n : ℕ) : alg_hom k (step k n) (algebraic_closure k) := alg_hom.mk (ring_hom.to_fun (of_step k n)) sorry sorry sorry sorry sorry theorem is_algebraic (k : Type u) [field k] : algebra.is_algebraic k (algebraic_closure k) := sorry protected instance is_alg_closure (k : Type u) [field k] : is_alg_closure k (algebraic_closure k) := { left := algebraic_closure.is_alg_closed k, right := is_algebraic k } end Mathlib
b9603ae54f565ba97a8536d3ffb8a6fab401332a
a30803705b058bf4d3fe292d2e2b73b6d0189758
/src/muri.lean
f898d370a3135f8f40432f07a339841df8413172
[ "MIT" ]
permissive
jroesch/muri
2ff3630899261cb4ecacba2708e0bc25837e4dd2
4700936f4928ad371ed1e8ed999f54b377b87b1d
refs/heads/master
1,609,206,122,077
1,473,129,664,000
1,473,129,664,000
64,623,415
1
0
null
null
null
null
UTF-8
Lean
false
false
2,182
lean
import system.IO import system.ffi -- import config set_option native.library_path "/Users/jroesch/Git/lean/build/debug" set_option native.include_path "/Users/jroesch/Git/lean/src" -- This flag controls whether lean will automatically invoke C++ -- set_option native.compile false set_option native.emit_dwarf true -- set_option trace.compiler true open ffi open ffi.type open ffi.base_type constant put_int : extern void "put_int" [int] attribute [extern "put_int" "/Users/jroesch/Git/muri/target/libfs.so"] put_int constant putstr : extern void "puts" [cstring] attribute [extern "putstr" "/Users/jroesch/Git/muri/target/libfs.so"] putstr inductive file | mk : ptr int -> file constant read_file : extern void "puts" [int, cstring, int] attribute [extern "read_file" "/Users/jroesch/Git/muri/target/libfs.so"] read_file constant open_file : extern int "puts" [cstring] attribute [extern "open_file" "/Users/jroesch/Git/muri/target/libfs.so"] open_file -- local attribute [semireducible] extern local attribute [reducible] cstring local attribute [reducible] extern definition open_file' : ptr cstring -> IO (ptr (base int)) := open_file definition read_file' : ptr (base int) -> ptr cstring -> ptr (base int) -> IO unit := read_file definition openf (file_name : string) : IO file := to_cstring file_name >>= open_file' >>= (fun cfd, return (file.mk cfd)) -- definition select {T : type} (i : nat) (array : ptr (array T)) : ptr T := -- index_array array i definition update {U} {T : type} [sto : storable U T] (i : nat) (value : U) (array : ptr (array T)) : IO unit := do iv <- index_array array i, storable.write value iv definition readf_to_string : file → ptr cstring → IO unit | readf_to_string (file.mk fd) buffer := do (array_capacity buffer >>= (fun (cap : ptr (base int)), read_file' fd buffer cap)), cap_n <- capacity buffer, update (cap_n + 1) (char.of_nat 0) buffer definition readf (f : file) : IO (ptr cstring) := do buf <- new cstring, readf_to_string f buf, return buf definition foo : ptr cstring -> IO unit := putstr definition main : IO unit := do f <- openf "hello.txt", str <- readf f, foo str vm_eval main
ff285c5e8374b4e0e2c0e1bed24b2af889e122a8
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/order/bounded_lattice.lean
81f806de722a579064891cdfd3a284a4e901e77f
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,457
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import order.lattice import data.option.basic import tactic.pi_instances set_option old_structure_cmd true universes u v variables {α : Type u} {β : Type v} /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top notation `⊥` := has_bot.bot attribute [pattern] has_bot.bot has_top.top /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := assume h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := begin haveI := classical.dec_eq α, haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff, by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)] end lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := assume ha, hb $ top_unique $ ha ▸ hab end order_top lemma strict_mono.top_preimage_top' [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) : x ≤ a := H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_top.ext_top H, casesI A, casesI B, injection this; congr' end /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := assume h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)] end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h end order_bot lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) : a ≤ x := H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have := partial_order.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection this; congr' end /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Bounded lattices -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin have H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, have H2 := order_bot.ext H, have H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, casesI A, casesI B, injection H1; injection H2; injection H3; congr' end /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨assume : a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], assume : a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this } ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop := { le := λa b, a → b, le_refl := assume _, id, le_trans := assume a b c f g, g ∘ f, le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := assume a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), le_sup_inf := assume a b c H, or_iff_not_imp_left.2 $ λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩, top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } noncomputable instance Prop.linear_order : linear_order Prop := { le_total := by intros p q; change (p → q) ∨ (q → p); tauto!, decidable_le := classical.dec_rel _, .. (_ : partial_order Prop) } @[simp] lemma le_iff_imp {p q : Prop} : p ≤ q ↔ (p → q) := iff.rfl section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := assume a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := assume a b h, or.imp (m_p h) (m_q h) end logic instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) := { bot := λ _, ⊥, bot_le := λ x a, bot_le, .. pi.partial_order } /- Function lattices -/ instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) := ⟨λ f g i, f i ⊔ g i⟩ @[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i := rfl instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) := ⟨λ f g i, f i ⊓ g i⟩ @[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i := rfl instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) := ⟨λ i, ⊥⟩ @[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) : (⊥ : Π i, α i) i = ⊥ := rfl instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) := ⟨λ i, ⊤⟩ @[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) : (⊤ : Π i, α i) i = ⊤ := rfl instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] : semilattice_sup (Π i, α i) := by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] : semilattice_inf (Π i, α i) := by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] : semilattice_inf_bot (Π i, α i) := by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] : semilattice_inf_top (Π i, α i) := by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] : semilattice_sup_bot (Π i, α i) := by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] : semilattice_sup_top (Π i, α i) := by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) := { .. pi.semilattice_sup, .. pi.semilattice_inf } instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] : bounded_lattice (Π i, α i) := { .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot } lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊥ : α) := eq_bot_mono le_top (eq.symm hα) lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) : x = (⊤ : α) := eq_top_mono bot_le hα lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) : subsingleton α := ⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩ lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) : subsingleton α := subsingleton_of_top_le_bot (ge_of_eq hα) /-- Attach `⊥` to a type. -/ def with_bot (α : Type*) := option α namespace with_bot meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ @[elab_as_eliminator] def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) : Π (n : with_bot α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a := ⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩ lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [preorder α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b | (some a) b := le_refl a | none b := λ _ h, option.no_confusion h @[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} : a.get_or_else ⊥ ≤ b ↔ a ≤ b := by cases a; simp [none_eq_bot, some_eq_coe] instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤) | none x := is_true $ λ a h, option.no_confusion h | (some x) (some y) := if h : x ≤ y then is_true (some_le_some.2 h) else is_false $ by simp * | (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩ instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, decidable_le := with_bot.decidable_le, decidable_lt := with_bot.decidable_lt, ..with_bot.partial_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ assume a b, match a, b with | a, none := assume h : a < ⊥, (not_lt_bot h).elim | none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type*) := option α namespace with_top meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ @[elab_as_eliminator] def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) : Π (n : with_top α), C n := option.rec h₁ h₂ @[norm_cast] theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem le_none [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem some_lt_none [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] @[norm_cast] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none theorem coe_lt_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b) | (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe] | none := by simp [none_eq_top, coe_lt_top] lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) := λ x y, @with_bot.decidable_le (order_dual α) _ _ y x instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) := λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, decidable_le := with_top.decidable_le, decidable_lt := with_top.decidable_lt, ..with_top.partial_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [linear_order α] : lattice_of_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ assume a b, match a, b with | none, a := assume h : ⊤ < a, (not_top_lt h).elim | some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} : (a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) := ⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩, λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩ end with_top namespace subtype /-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/ protected def semilattice_sup [semilattice_sup α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} := { sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩, le_sup_left := λ x y, @le_sup_left _ _ (x : α) y, le_sup_right := λ x y, @le_sup_right _ _ (x : α) y, sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/ protected def semilattice_inf [semilattice_inf α] {P : α → Prop} (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} := { inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩, inf_le_left := λ x y, @inf_le_left _ _ (x : α) y, inf_le_right := λ x y, @inf_le_right _ _ (x : α) y, le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2, ..subtype.partial_order P } /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/ protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_sup Psup } /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/ protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} := { bot := ⟨⊥, Pbot⟩, bot_le := λ x, @bot_le α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/ protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} := { top := ⟨⊤, Ptop⟩, le_top := λ x, @le_top α _ x, ..subtype.semilattice_inf Pinf } /-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/ protected def lattice [lattice α] {P : α → Prop} (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : lattice {x : α // P x} := { ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup } end subtype namespace order_dual variable (α) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.semilattice_sup α, .. order_dual.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.semilattice_inf α, .. order_dual.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α } instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α } end order_dual namespace prod variables (α β) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := assume a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := assume a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.semilattice_sup α β, .. prod.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.semilattice_inf α β, .. prod.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.semilattice_sup α β, .. prod.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.semilattice_inf α β, .. prod.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.bounded_lattice α β, .. prod.distrib_lattice α β } end prod section disjoint section semilattice_inf_bot variable [semilattice_inf_bot α] /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ := eq_bot_iff.2 h theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ := eq_bot_iff.symm theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a := by rw [disjoint, disjoint, inf_comm] @[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a := disjoint.comm.1 @[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := disjoint_iff.2 bot_inf_eq @[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := disjoint_iff.2 inf_bot_eq theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl _) theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl _) h @[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ := by simp [disjoint] lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := by { intro h, rw [←h, disjoint_self] at hab, exact ha hab } end semilattice_inf_bot section bounded_distrib_lattice variables [bounded_distrib_lattice α] {a b c : α} @[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff] @[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff] lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := disjoint_sup_left.2 ⟨ha, hb⟩ lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := disjoint_sup_right.2 ⟨hb, hc⟩ end bounded_distrib_lattice end disjoint /-! ### `is_compl` predicate -/ /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl [bounded_lattice α] (x y : α) : Prop := (inf_le_bot : x ⊓ y ≤ ⊥) (top_le_sup : ⊤ ≤ x ⊔ y) namespace is_compl section bounded_lattice variables [bounded_lattice α] {x y z : α} protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1 @[symm] protected lemma symm (h : is_compl x y) : is_compl y x := ⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩ lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := ⟨le_of_eq h₁, le_of_eq h₂.symm⟩ lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩ end bounded_lattice variables [bounded_distrib_lattice α] {x y z : α} lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y := ⟨λ hz, h.disjoint.mono_left hz, λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩ lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x := h.symm.le_left_iff lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := h.to_order_dual.le_left_iff lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := h.symm.left_le_iff lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _) lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x) lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) : x = y := hxz.symm.right_unique hyz.symm lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := of_eq (by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm, h'.inf_eq_bot, inf_bot_eq]) (by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq, sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq]) lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := (h.symm.sup_inf h'.symm).symm lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := h.symm.inf_left_eq_bot_iff lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z := disjoint_iff.trans h.inf_left_eq_bot_iff lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y := h.symm.disjoint_left_iff end is_compl lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq
1f8cd712bad5b4c4090efd4a1b278ab39ad50187
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/ordmap/ordset.lean
a6656f1f22a7fcbf606e513b79ce7c63ef732593
[ "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
69,866
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.ordmap.ordnode import algebra.ordered_ring import data.nat.dist import tactic.linarith /-! # Verification of the `ordnode α` datatype This file proves the correctness of the operations in `data.ordmap.ordnode`. The public facing version is the type `ordset α`, which is a wrapper around `ordnode α` which includes the correctness invariant of the type, and it exposes parallel operations like `insert` as functions on `ordset` that do the same thing but bundle the correctness proofs. The advantage is that it is possible to, for example, prove that the result of `find` on `insert` will actually find the element, while `ordnode` cannot guarantee this if the input tree did not satisfy the type invariants. ## Main definitions * `ordset α`: A well formed set of values of type `α` ## Implementation notes The majority of this file is actually in the `ordnode` namespace, because we first have to prove the correctness of all the operations (and defining what correctness means here is actually somewhat subtle). So all the actual `ordset` operations are at the very end, once we have all the theorems. An `ordnode α` is an inductive type which describes a tree which stores the `size` at internal nodes. The correctness invariant of an `ordnode α` is: * `ordnode.sized t`: All internal `size` fields must match the actual measured size of the tree. (This is not hard to satisfy.) * `ordnode.balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))` (that is, nil or a single singleton subtree), the two subtrees must satisfy `size l ≤ δ * size r` and `size r ≤ δ * size l`, where `δ := 3` is a global parameter of the data structure (and this property must hold recursively at subtrees). This is why we say this is a "size balanced tree" data structure. * `ordnode.bounded lo hi t`: The members of the tree must be in strictly increasing order, meaning that if `a` is in the left subtree and `b` is the root, then `a ≤ b` and `¬ (b ≤ a)`. We enforce this using `ordnode.bounded` which includes also a global upper and lower bound. Because the `ordnode` file was ported from Haskell, the correctness invariants of some of the functions have not been spelled out, and some theorems like `ordnode.valid'.balance_l_aux` show very intricate assumptions on the sizes, which may need to be revised if it turns out some operations violate these assumptions, because there is a decent amount of slop in the actual data structure invariants, so the theorem will go through with multiple choices of assumption. **Note:** This file is incomplete, in the sense that the intent is to have verified versions and lemmas about all the definitions in `ordnode.lean`, but at the moment only a few operations are verified (the hard part should be out of the way, but still). Contributors are encouraged to pick this up and finish the job, if it appeals to you. ## Tags ordered map, ordered set, data structure, verified programming -/ variable {α : Type*} namespace ordnode /-! ### delta and ratio -/ theorem not_le_delta {s} (H : 1 ≤ s) : ¬ s ≤ delta * 0 := not_le_of_gt H theorem delta_lt_false {a b : ℕ} (h₁ : delta * a < b) (h₂ : delta * b < a) : false := not_le_of_lt (lt_trans ((mul_lt_mul_left dec_trivial).2 h₁) h₂) $ by simpa [mul_assoc] using nat.mul_le_mul_right a (dec_trivial : 1 ≤ delta * delta) /-! ### `singleton` -/ /-! ### `size` and `empty` -/ /-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/ def real_size : ordnode α → ℕ | nil := 0 | (node _ l _ r) := real_size l + real_size r + 1 /-! ### `sized` -/ /-- The `sized` property asserts that all the `size` fields in nodes match the actual size of the respective subtrees. -/ def sized : ordnode α → Prop | nil := true | (node s l _ r) := s = size l + size r + 1 ∧ sized l ∧ sized r theorem sized.node' {l x r} (hl : @sized α l) (hr : sized r) : sized (node' l x r) := ⟨rfl, hl, hr⟩ theorem sized.eq_node' {s l x r} (h : @sized α (node s l x r)) : node s l x r = node' l x r := by rw h.1; refl theorem sized.size_eq {s l x r} (H : sized (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.1 @[elab_as_eliminator] theorem sized.induction {t} (hl : @sized α t) {C : ordnode α → Prop} (H0 : C nil) (H1 : ∀ l x r, C l → C r → C (node' l x r)) : C t := begin induction t, {exact H0}, rw hl.eq_node', exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2) end theorem size_eq_real_size : ∀ {t : ordnode α}, sized t → size t = real_size t | nil _ := rfl | (node s l x r) ⟨h₁, h₂, h₃⟩ := by rw [size, h₁, size_eq_real_size h₂, size_eq_real_size h₃]; refl @[simp] theorem sized.size_eq_zero {t : ordnode α} (ht : sized t) : size t = 0 ↔ t = nil := by cases t; [simp, simp [ht.1]] theorem sized.pos {s l x r} (h : sized (@node α s l x r)) : 0 < s := by rw h.1; apply nat.le_add_left /-! `dual` -/ theorem dual_dual : ∀ (t : ordnode α), dual (dual t) = t | nil := rfl | (node s l x r) := by rw [dual, dual, dual_dual, dual_dual] @[simp] theorem size_dual (t : ordnode α) : size (dual t) = size t := by cases t; refl /-! `balanced` -/ /-- The `balanced_sz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is balanced: either `l ≤ δ * r` and `r ≤ δ * r`, or the tree is trivial with a singleton on one side and nothing on the other. -/ def balanced_sz (l r : ℕ) : Prop := l + r ≤ 1 ∨ (l ≤ delta * r ∧ r ≤ delta * l) instance balanced_sz.dec : decidable_rel balanced_sz := λ l r, or.decidable /-- The `balanced t` asserts that the tree `t` satisfies the balance invariants (at every level). -/ def balanced : ordnode α → Prop | nil := true | (node _ l _ r) := balanced_sz (size l) (size r) ∧ balanced l ∧ balanced r instance balanced.dec : decidable_pred (@balanced α) | t := by induction t; unfold balanced; resetI; apply_instance theorem balanced_sz.symm {l r : ℕ} : balanced_sz l r → balanced_sz r l := or.imp (by rw add_comm; exact id) and.symm theorem balanced_sz_zero {l : ℕ} : balanced_sz l 0 ↔ l ≤ 1 := by simp [balanced_sz] { contextual := tt } theorem balanced_sz_up {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ r₂ ≤ delta * l) (H : balanced_sz l r₁) : balanced_sz l r₂ := begin refine or_iff_not_imp_left.2 (λ h, _), refine ⟨_, h₂.resolve_left h⟩, cases H, { cases r₂, { cases h (le_trans (nat.add_le_add_left (nat.zero_le _) _) H) }, { exact le_trans (le_trans (nat.le_add_right _ _) H) (nat.le_add_left 1 _) } }, { exact le_trans H.1 (nat.mul_le_mul_left _ h₁) } end theorem balanced_sz_down {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ l ≤ delta * r₁) (H : balanced_sz l r₂) : balanced_sz l r₁ := have l + r₂ ≤ 1 → balanced_sz l r₁, from λ H, or.inl (le_trans (nat.add_le_add_left h₁ _) H), or.cases_on H this (λ H, or.cases_on h₂ this (λ h₂, or.inr ⟨h₂, le_trans h₁ H.2⟩)) theorem balanced.dual : ∀ {t : ordnode α}, balanced t → balanced (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨b, bl, br⟩ := ⟨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dual⟩ /-! ### `rotate` and `balance` -/ /-- Build a tree from three nodes, left associated (ignores the invariants). -/ def node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' (node' l x m) y r /-- Build a tree from three nodes, right associated (ignores the invariants). -/ def node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : ordnode α := node' l x (node' m y r) /-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/ def node4_l : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_l l x nil z r -- should not happen /-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/ def node4_r : ordnode α → α → ordnode α → α → ordnode α → ordnode α | l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r) | l x nil z r := node3_r l x nil z r -- should not happen /-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)` if balance is upset. -/ def rotate_l : ordnode α → α → ordnode α → ordnode α | l x (node _ m y r) := if size m < ratio * size r then node3_l l x m y r else node4_l l x m y r | l x nil := node' l x nil -- should not happen /-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))` if balance is upset. -/ def rotate_r : ordnode α → α → ordnode α → ordnode α | (node _ l x m) y r := if size m < ratio * size l then node3_r l x m y r else node4_r l x m y r | nil y r := node' nil y r -- should not happen /-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_l' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size l > delta * size r then rotate_r l x r else node' l x r /-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are not too far from balanced. -/ def balance_r' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else node' l x r /-- The full balance operation. This is the same as `balance`, but with less manual inlining. It is somewhat easier to work with this version in proofs. -/ def balance' (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := if size l + size r ≤ 1 then node' l x r else if size r > delta * size l then rotate_l l x r else if size l > delta * size r then rotate_r l x r else node' l x r theorem dual_node' (l : ordnode α) (x : α) (r : ordnode α) : dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm] theorem dual_node3_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_l l x m y r) = node3_r (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node3_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node3_r l x m y r) = node3_l (dual r) y (dual m) x (dual l) := by simp [node3_l, node3_r, dual_node'] theorem dual_node4_l (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_l l x m y r) = node4_r (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_l, dual_node'] theorem dual_node4_r (l : ordnode α) (x : α) (m : ordnode α) (y : α) (r : ordnode α) : dual (node4_r l x m y r) = node4_l (dual r) y (dual m) x (dual l) := by cases m; simp [node4_l, node4_r, dual_node3_r, dual_node'] theorem dual_rotate_l (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_l l x r) = rotate_r (dual r) x (dual l) := by cases r; simp [rotate_l, rotate_r, dual_node']; split_ifs; simp [dual_node3_l, dual_node4_l] theorem dual_rotate_r (l : ordnode α) (x : α) (r : ordnode α) : dual (rotate_r l x r) = rotate_l (dual r) x (dual l) := by rw [← dual_dual (rotate_l _ _ _), dual_rotate_l, dual_dual, dual_dual] theorem dual_balance' (l : ordnode α) (x : α) (r : ordnode α) : dual (balance' l x r) = balance' (dual r) x (dual l) := begin simp [balance', add_comm], split_ifs; simp [dual_node', dual_rotate_l, dual_rotate_r], cases delta_lt_false h_1 h_2 end theorem dual_balance_l (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_l l x r) = balance_r (dual r) x (dual l) := begin unfold balance_l balance_r, cases r with rs rl rx rr, { cases l with ls ll lx lr, {refl}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp only [dual]; try {refl}, split_ifs; repeat {simp [h, add_comm]} }, { cases l with ls ll lx lr, {refl}, dsimp only [dual], split_ifs, swap, {simp [add_comm]}, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; try {refl}, dsimp only [dual], split_ifs; simp [h, add_comm] }, end theorem dual_balance_r (l : ordnode α) (x : α) (r : ordnode α) : dual (balance_r l x r) = balance_l (dual r) x (dual l) := by rw [← dual_dual (balance_l _ _ _), dual_balance_l, dual_dual, dual_dual] theorem sized.node3_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_l l x m y r) := (hl.node' hm).node' hr theorem sized.node3_r {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node3_r l x m y r) := hl.node' (hm.node' hr) theorem sized.node4_l {l x m y r} (hl : @sized α l) (hm : sized m) (hr : sized r) : sized (node4_l l x m y r) := by cases m; [exact (hl.node' hm).node' hr, exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)] theorem node3_l_size {l x m y r} : size (@node3_l α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_l, node', size]; rw add_right_comm _ 1 theorem node3_r_size {l x m y r} : size (@node3_r α l x m y r) = size l + size m + size r + 2 := by dsimp [node3_r, node', size]; rw [← add_assoc, ← add_assoc] theorem node4_l_size {l x m y r} (hm : sized m) : size (@node4_l α l x m y r) = size l + size m + size r + 2 := by cases m; simp [node4_l, node3_l, node', add_comm, add_left_comm]; [skip, simp [size, hm.1]]; rw [← add_assoc, ← bit0]; simp [add_comm, add_left_comm] theorem sized.dual : ∀ {t : ordnode α} (h : sized t), sized (dual t) | nil h := ⟨⟩ | (node s l x r) ⟨rfl, sl, sr⟩ := ⟨by simp [size_dual, add_comm], sized.dual sr, sized.dual sl⟩ theorem sized.dual_iff {t : ordnode α} : sized (dual t) ↔ sized t := ⟨λ h, by rw ← dual_dual t; exact h.dual, sized.dual⟩ theorem sized.rotate_l {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_l l x r) := begin cases r, {exact hl.node' hr}, rw rotate_l, split_ifs, { exact hl.node3_l hr.2.1 hr.2.2 }, { exact hl.node4_l hr.2.1 hr.2.2 } end theorem sized.rotate_r {l x r} (hl : @sized α l) (hr : sized r) : sized (rotate_r l x r) := sized.dual_iff.1 $ by rw dual_rotate_r; exact hr.dual.rotate_l hl.dual theorem sized.rotate_l_size {l x r} (hm : sized r) : size (@rotate_l α l x r) = size l + size r + 1 := begin cases r; simp [rotate_l], simp [size, hm.1, add_comm, add_left_comm], rw [← add_assoc, ← bit0], simp, split_ifs; simp [node3_l_size, node4_l_size hm.2.1, add_comm, add_left_comm] end theorem sized.rotate_r_size {l x r} (hl : sized l) : size (@rotate_r α l x r) = size l + size r + 1 := by rw [← size_dual, dual_rotate_r, hl.dual.rotate_l_size, size_dual, size_dual, add_comm (size l)] theorem sized.balance' {l x r} (hl : @sized α l) (hr : sized r) : sized (balance' l x r) := begin unfold balance', split_ifs, { exact hl.node' hr }, { exact hl.rotate_l hr }, { exact hl.rotate_r hr }, { exact hl.node' hr } end theorem size_balance' {l x r} (hl : @sized α l) (hr : sized r) : size (@balance' α l x r) = size l + size r + 1 := begin unfold balance', split_ifs, { refl }, { exact hr.rotate_l_size }, { exact hl.rotate_r_size }, { refl } end /-! ## `all`, `any`, `emem`, `amem` -/ theorem all.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, all P t → all Q t | nil h := ⟨⟩ | (node _ l x r) ⟨h₁, h₂, h₃⟩ := ⟨h₁.imp, H _ h₂, h₃.imp⟩ theorem any.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, any P t → any Q t | nil := id | (node _ l x r) := or.imp any.imp $ or.imp (H _) any.imp theorem all_singleton {P : α → Prop} {x : α} : all P (singleton x) ↔ P x := ⟨λ h, h.2.1, λ h, ⟨⟨⟩, h, ⟨⟩⟩⟩ theorem any_singleton {P : α → Prop} {x : α} : any P (singleton x) ↔ P x := ⟨by rintro (⟨⟨⟩⟩ | h | ⟨⟨⟩⟩); exact h, λ h, or.inr (or.inl h)⟩ theorem all_dual {P : α → Prop} : ∀ {t : ordnode α}, all P (dual t) ↔ all P t | nil := iff.rfl | (node s l x r) := ⟨λ ⟨hr, hx, hl⟩, ⟨all_dual.1 hl, hx, all_dual.1 hr⟩, λ ⟨hl, hx, hr⟩, ⟨all_dual.2 hr, hx, all_dual.2 hl⟩⟩ theorem all_iff_forall {P : α → Prop} : ∀ {t}, all P t ↔ ∀ x, emem x t → P x | nil := (iff_true_intro $ by rintro _ ⟨⟩).symm | (node _ l x r) := by simp [all, emem, all_iff_forall, any, or_imp_distrib, forall_and_distrib] theorem any_iff_exists {P : α → Prop} : ∀ {t}, any P t ↔ ∃ x, emem x t ∧ P x | nil := ⟨by rintro ⟨⟩, by rintro ⟨_, ⟨⟩, _⟩⟩ | (node _ l x r) := by simp [any, emem, any_iff_exists, or_and_distrib_right, exists_or_distrib] theorem emem_iff_all {x : α} {t} : emem x t ↔ ∀ P, all P t → P x := ⟨λ h P al, all_iff_forall.1 al _ h, λ H, H _ $ all_iff_forall.2 $ λ _, id⟩ theorem all_node' {P l x r} : @all α P (node' l x r) ↔ all P l ∧ P x ∧ all P r := iff.rfl theorem all_node3_l {P l x m y r} : @all α P (node3_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by simp [node3_l, all_node', and_assoc] theorem all_node3_r {P l x m y r} : @all α P (node3_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := iff.rfl theorem all_node4_l {P l x m y r} : @all α P (node4_l l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_l, all_node', all, all_node3_l, and_assoc] theorem all_node4_r {P l x m y r} : @all α P (node4_r l x m y r) ↔ all P l ∧ P x ∧ all P m ∧ P y ∧ all P r := by cases m; simp [node4_r, all_node', all, all_node3_r, and_assoc] theorem all_rotate_l {P l x r} : @all α P (rotate_l l x r) ↔ all P l ∧ P x ∧ all P r := by cases r; simp [rotate_l, all_node']; split_ifs; simp [all_node3_l, all_node4_l, all] theorem all_rotate_r {P l x r} : @all α P (rotate_r l x r) ↔ all P l ∧ P x ∧ all P r := by rw [← all_dual, dual_rotate_r, all_rotate_l]; simp [all_dual, and_comm, and.left_comm] theorem all_balance' {P l x r} : @all α P (balance' l x r) ↔ all P l ∧ P x ∧ all P r := by rw balance'; split_ifs; simp [all_node', all_rotate_l, all_rotate_r] /-! ### `to_list` -/ theorem foldr_cons_eq_to_list : ∀ (t : ordnode α) (r : list α), t.foldr list.cons r = to_list t ++ r | nil r := rfl | (node _ l x r) r' := by rw [foldr, foldr_cons_eq_to_list, foldr_cons_eq_to_list, ← list.cons_append, ← list.append_assoc, ← foldr_cons_eq_to_list]; refl @[simp] theorem to_list_nil : to_list (@nil α) = [] := rfl @[simp] theorem to_list_node (s l x r) : to_list (@node α s l x r) = to_list l ++ x :: to_list r := by rw [to_list, foldr, foldr_cons_eq_to_list]; refl theorem emem_iff_mem_to_list {x : α} {t} : emem x t ↔ x ∈ to_list t := by unfold emem; induction t; simp [any, *, or_assoc] theorem length_to_list' : ∀ t : ordnode α, (to_list t).length = t.real_size | nil := rfl | (node _ l _ r) := by rw [to_list_node, list.length_append, list.length_cons, length_to_list', length_to_list']; refl theorem length_to_list {t : ordnode α} (h : sized t) : (to_list t).length = t.size := by rw [length_to_list', size_eq_real_size h] theorem equiv_iff {t₁ t₂ : ordnode α} (h₁ : sized t₁) (h₂ : sized t₂) : equiv t₁ t₂ ↔ to_list t₁ = to_list t₂ := and_iff_right_of_imp $ λ h, by rw [← length_to_list h₁, h, length_to_list h₂] /-! ### `mem` -/ theorem pos_size_of_mem [has_le α] [@decidable_rel α (≤)] {x : α} {t : ordnode α} (h : sized t) (h_mem : x ∈ t) : 0 < size t := by { cases t, { contradiction }, { simp [h.1] } } /-! ### `(find/erase/split)_(min/max)` -/ theorem find_min'_dual : ∀ t (x : α), find_min' (dual t) x = find_max' x t | nil x := rfl | (node _ l x r) _ := find_min'_dual r x theorem find_max'_dual (t) (x : α) : find_max' x (dual t) = find_min' t x := by rw [← find_min'_dual, dual_dual] theorem find_min_dual : ∀ t : ordnode α, find_min (dual t) = find_max t | nil := rfl | (node _ l x r) := congr_arg some $ find_min'_dual _ _ theorem find_max_dual (t : ordnode α) : find_max (dual t) = find_min t := by rw [← find_min_dual, dual_dual] theorem dual_erase_min : ∀ t : ordnode α, dual (erase_min t) = erase_max (dual t) | nil := rfl | (node _ nil x r) := rfl | (node _ l@(node _ _ _ _) x r) := by rw [erase_min, dual_balance_r, dual_erase_min, dual, dual, dual, erase_max] theorem dual_erase_max (t : ordnode α) : dual (erase_max t) = erase_min (dual t) := by rw [← dual_dual (erase_min _), dual_erase_min, dual_dual] theorem split_min_eq : ∀ s l (x : α) r, split_min' l x r = (find_min' l x, erase_min (node s l x r)) | _ nil x r := rfl | _ (node ls ll lx lr) x r := by rw [split_min', split_min_eq, split_min', find_min', erase_min] theorem split_max_eq : ∀ s l (x : α) r, split_max' l x r = (erase_max (node s l x r), find_max' x r) | _ l x nil := rfl | _ l x (node ls ll lx lr) := by rw [split_max', split_max_eq, split_max', find_max', erase_max] @[elab_as_eliminator] theorem find_min'_all {P : α → Prop} : ∀ t (x : α), all P t → P x → P (find_min' t x) | nil x h hx := hx | (node _ ll lx lr) x ⟨h₁, h₂, h₃⟩ hx := find_min'_all _ _ h₁ h₂ @[elab_as_eliminator] theorem find_max'_all {P : α → Prop} : ∀ (x : α) t, P x → all P t → P (find_max' x t) | x nil hx h := hx | x (node _ ll lx lr) hx ⟨h₁, h₂, h₃⟩ := find_max'_all _ _ h₂ h₃ /-! ### `glue` -/ /-! ### `merge` -/ @[simp] theorem merge_nil_left (t : ordnode α) : merge t nil = t := by cases t; refl @[simp] theorem merge_nil_right (t : ordnode α) : merge nil t = t := rfl @[simp] theorem merge_node {ls ll lx lr rs rl rx rr} : merge (@node α ls ll lx lr) (node rs rl rx rr) = if delta * ls < rs then balance_l (merge (node ls ll lx lr) rl) rx rr else if delta * rs < ls then balance_r ll lx (merge lr (node rs rl rx rr)) else glue (node ls ll lx lr) (node rs rl rx rr) := rfl /-! ### `insert` -/ theorem dual_insert [preorder α] [is_total α (≤)] [@decidable_rel α (≤)] (x : α) : ∀ t : ordnode α, dual (ordnode.insert x t) = @ordnode.insert (order_dual α) _ _ x (dual t) | nil := rfl | (node _ l y r) := begin rw [ordnode.insert, dual, ordnode.insert, order_dual.cmp_le_flip, ← cmp_le_swap x y], cases cmp_le x y; simp [ordering.swap, ordnode.insert, dual_balance_l, dual_balance_r, dual_insert] end /-! ### `balance` properties -/ theorem balance_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) : @balance α l x r = balance' l x r := begin cases l with ls ll lx lr, { cases r with rs rl rx rr, { refl }, { rw sr.eq_node' at hr ⊢, cases rl with rls rll rlx rlr; cases rr with rrs rrl rrx rrr; dsimp [balance, balance'], { refl }, { have : size rrl = 0 ∧ size rrr = 0, { have := balanced_sz_zero.1 hr.1.symm, rwa [size, sr.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.2.2.1.size_eq_zero.1 this.1, cases sr.2.2.2.2.size_eq_zero.1 this.2, have : rrs = 1 := sr.2.2.1, subst rrs, rw [if_neg, if_pos, rotate_l, if_pos], {refl}, all_goals {exact dec_trivial} }, { have : size rll = 0 ∧ size rlr = 0, { have := balanced_sz_zero.1 hr.1, rwa [size, sr.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.2.1.size_eq_zero.1 this.1, cases sr.2.1.2.2.size_eq_zero.1 this.2, have : rls = 1 := sr.2.1.1, subst rls, rw [if_neg, if_pos, rotate_l, if_neg], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [zero_add, if_neg, if_pos, rotate_l], { split_ifs, { simp [node3_l, node', add_comm, add_left_comm] }, { simp [node4_l, node', sr.2.1.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sr.2.1.pos sr.2.2.pos)) } } } }, { cases r with rs rl rx rr, { rw sl.eq_node' at hl ⊢, cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; dsimp [balance, balance'], { refl }, { have : size lrl = 0 ∧ size lrr = 0, { have := balanced_sz_zero.1 hl.1.symm, rwa [size, sl.2.2.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.2.2.1.size_eq_zero.1 this.1, cases sl.2.2.2.2.size_eq_zero.1 this.2, have : lrs = 1 := sl.2.2.1, subst lrs, rw [if_neg, if_neg, if_pos, rotate_r, if_neg], {refl}, all_goals {exact dec_trivial} }, { have : size lll = 0 ∧ size llr = 0, { have := balanced_sz_zero.1 hl.1, rwa [size, sl.2.1.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sl.2.1.2.1.size_eq_zero.1 this.1, cases sl.2.1.2.2.size_eq_zero.1 this.2, have : lls = 1 := sl.2.1.1, subst lls, rw [if_neg, if_neg, if_pos, rotate_r, if_pos], {refl}, all_goals {exact dec_trivial} }, { symmetry, rw [if_neg, if_neg, if_pos, rotate_r], { split_ifs, { simp [node3_r, node', add_comm, add_left_comm] }, { simp [node4_r, node', sl.2.2.1, add_comm, add_left_comm] } }, { exact dec_trivial }, { exact dec_trivial }, { exact not_le_of_gt (nat.succ_lt_succ (add_pos sl.2.1.pos sl.2.2.pos)) } } }, { simp [balance, balance'], symmetry, rw [if_neg], { split_ifs, { have rd : delta ≤ size rl + size rr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sl.pos) h, rwa [sr.1, nat.lt_succ_iff] at this }, cases rl with rls rll rlx rlr, { rw [size, zero_add] at rd, exact absurd (le_trans rd (balanced_sz_zero.1 hr.1.symm)) dec_trivial }, cases rr with rrs rrl rrx rrr, { exact absurd (le_trans rd (balanced_sz_zero.1 hr.1)) dec_trivial }, dsimp [rotate_l], split_ifs, { simp [node3_l, node', sr.1, add_comm, add_left_comm] }, { simp [node4_l, node', sr.1, sr.2.1.1, add_comm, add_left_comm] } }, { have ld : delta ≤ size ll + size lr, { have := lt_of_le_of_lt (nat.mul_le_mul_left _ sr.pos) h_1, rwa [sl.1, nat.lt_succ_iff] at this }, cases ll with lls lll llx llr, { rw [size, zero_add] at ld, exact absurd (le_trans ld (balanced_sz_zero.1 hl.1.symm)) dec_trivial }, cases lr with lrs lrl lrx lrr, { exact absurd (le_trans ld (balanced_sz_zero.1 hl.1)) dec_trivial }, dsimp [rotate_r], split_ifs, { simp [node3_r, node', sl.1, add_comm, add_left_comm] }, { simp [node4_r, node', sl.1, sl.2.2.1, add_comm, add_left_comm] } }, { simp [node'] } }, { exact not_le_of_gt (add_le_add sl.pos sr.pos : 2 ≤ ls + rs) } } } end theorem balance_l_eq_balance {l x r} (sl : sized l) (sr : sized r) (H1 : size l = 0 → size r ≤ 1) (H2 : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) : @balance_l α l x r = balance l x r := begin cases r with rs rl rx rr, { refl }, { cases l with ls ll lx lr, { have : size rl = 0 ∧ size rr = 0, { have := H1 rfl, rwa [size, sr.1, nat.succ_le_succ_iff, nat.le_zero_iff, add_eq_zero_iff] at this }, cases sr.2.1.size_eq_zero.1 this.1, cases sr.2.2.size_eq_zero.1 this.2, rw sr.eq_node', refl }, { replace H2 : ¬ rs > delta * ls := not_lt_of_le (H2 sl.pos sr.pos), simp [balance_l, balance, H2]; split_ifs; simp [add_comm] } } end /-- `raised n m` means `m` is either equal or one up from `n`. -/ def raised (n m : ℕ) : Prop := m = n ∨ m = n + 1 theorem raised_iff {n m} : raised n m ↔ n ≤ m ∧ m ≤ n + 1 := begin split, rintro (rfl | rfl), { exact ⟨le_refl _, nat.le_succ _⟩ }, { exact ⟨nat.le_succ _, le_refl _⟩ }, { rintro ⟨h₁, h₂⟩, rcases eq_or_lt_of_le h₁ with rfl | h₁, { exact or.inl rfl }, { exact or.inr (le_antisymm h₂ h₁) } } end theorem raised.dist_le {n m} (H : raised n m) : nat.dist n m ≤ 1 := by cases raised_iff.1 H with H1 H2; rwa [nat.dist_eq_sub_of_le H1, nat.sub_le_left_iff_le_add] theorem raised.dist_le' {n m} (H : raised n m) : nat.dist m n ≤ 1 := by rw nat.dist_comm; exact H.dist_le theorem raised.add_left (k) {n m} (H : raised n m) : raised (k + n) (k + m) := begin rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem raised.add_right (k) {n m} (H : raised n m) : raised (n + k) (m + k) := by rw [add_comm, add_comm m]; exact H.add_left _ theorem raised.right {l x₁ x₂ r₁ r₂} (H : raised (size r₁) (size r₂)) : raised (size (@node' α l x₁ r₁)) (size (@node' α l x₂ r₂)) := begin dsimp [node', size], generalize_hyp : size r₂ = m at H ⊢, rcases H with rfl | rfl, { exact or.inl rfl }, { exact or.inr rfl } end theorem balance_l_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : @balance_l α l x r = balance' l x r := begin rw [← balance_eq_balance' hl hr sl sr, balance_l_eq_balance sl sr], { intro l0, rw l0 at H, rcases H with ⟨_, ⟨⟨⟩⟩|⟨⟨⟩⟩, H⟩ | ⟨r', e, H⟩, { exact balanced_sz_zero.1 H.symm }, exact le_trans (raised_iff.1 e).1 (balanced_sz_zero.1 H.symm) }, { intros l1 r1, rcases H with ⟨l', e, H | ⟨H₁, H₂⟩⟩ | ⟨r', e, H | ⟨H₁, H₂⟩⟩, { exact le_trans (le_trans (nat.le_add_left _ _) H) (mul_pos dec_trivial l1 : (0:ℕ)<_) }, { exact le_trans H₂ (nat.mul_le_mul_left _ (raised_iff.1 e).1) }, { cases raised_iff.1 e, unfold delta, linarith }, { exact le_trans (raised_iff.1 e).1 H₂ } } end theorem balance_sz_dual {l r} (H : (∃ l', raised (@size α l) l' ∧ balanced_sz l' (@size α r)) ∨ ∃ r', raised r' (size r) ∧ balanced_sz (size l) r') : (∃ l', raised l' (size (dual r)) ∧ balanced_sz l' (size (dual l))) ∨ ∃ r', raised (size (dual l)) r' ∧ balanced_sz (size (dual r)) r' := begin rw [size_dual, size_dual], exact H.symm.imp (Exists.imp $ λ _, and.imp_right balanced_sz.symm) (Exists.imp $ λ _, and.imp_right balanced_sz.symm) end theorem size_balance_l {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : size (@balance_l α l x r) = size l + size r + 1 := by rw [balance_l_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_l {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : all P (@balance_l α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_l_eq_balance' hl hr sl sr H, all_balance'] theorem balance_r_eq_balance' {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : @balance_r α l x r = balance' l x r := by rw [← dual_dual (balance_r l x r), dual_balance_r, balance_l_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H), ← dual_balance', dual_dual] theorem size_balance_r {l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : size (@balance_r α l x r) = size l + size r + 1 := by rw [balance_r_eq_balance' hl hr sl sr H, size_balance' sl sr] theorem all_balance_r {P l x r} (hl : balanced l) (hr : balanced r) (sl : sized l) (sr : sized r) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : all P (@balance_r α l x r) ↔ all P l ∧ P x ∧ all P r := by rw [balance_r_eq_balance' hl hr sl sr H, all_balance'] /-! ### `bounded` -/ section variable [preorder α] /-- `bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this property holds recursively in subtrees, making the full tree a BST. The bounds can be set to `lo = ⊥` and `hi = ⊤` if we care only about the internal ordering constraints. -/ def bounded : ordnode α → with_bot α → with_top α → Prop | nil (some a) (some b) := a < b | nil _ _ := true | (node _ l x r) o₁ o₂ := bounded l o₁ ↑x ∧ bounded r ↑x o₂ theorem bounded.dual : ∀ {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂), @bounded (order_dual α) _ (dual t) o₂ o₁ | nil o₁ o₂ h := by cases o₁; cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨or.dual, ol.dual⟩ theorem bounded.dual_iff {t : ordnode α} {o₁ o₂} : bounded t o₁ o₂ ↔ @bounded (order_dual α) _ (dual t) o₂ o₁ := ⟨bounded.dual, λ h, by have := bounded.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem bounded.weak_left : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t ⊥ o₂ | nil o₁ o₂ h := by cases o₂; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol.weak_left, or⟩ theorem bounded.weak_right : ∀ {t : ordnode α} {o₁ o₂}, bounded t o₁ o₂ → bounded t o₁ ⊤ | nil o₁ o₂ h := by cases o₁; try {trivial}; exact h | (node s l x r) _ _ ⟨ol, or⟩ := ⟨ol, or.weak_right⟩ theorem bounded.weak {t : ordnode α} {o₁ o₂} (h : bounded t o₁ o₂) : bounded t ⊥ ⊤ := h.weak_left.weak_right theorem bounded.mono_left {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t ↑y o → bounded t ↑x o | nil none h := ⟨⟩ | nil (some z) h := lt_of_le_of_lt xy h | (node s l z r) o ⟨ol, or⟩ := ⟨ol.mono_left, or⟩ theorem bounded.mono_right {x y : α} (xy : x ≤ y) : ∀ {t : ordnode α} {o}, bounded t o ↑x → bounded t o ↑y | nil none h := ⟨⟩ | nil (some z) h := lt_of_lt_of_le h xy | (node s l z r) o ⟨ol, or⟩ := ⟨ol, or.mono_right⟩ theorem bounded.to_lt : ∀ {t : ordnode α} {x y : α}, bounded t x y → x < y | nil x y h := h | (node _ l y r) x z ⟨h₁, h₂⟩ := lt_trans h₁.to_lt h₂.to_lt theorem bounded.to_nil {t : ordnode α} : ∀ {o₁ o₂}, bounded t o₁ o₂ → bounded nil o₁ o₂ | none _ h := ⟨⟩ | (some _) none h := ⟨⟩ | (some x) (some y) h := h.to_lt theorem bounded.trans_left {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₂ o₁ o₂ | none o₂ h₁ h₂ := h₂.weak_left | (some y) o₂ h₁ h₂ := h₂.mono_left (le_of_lt h₁.to_lt) theorem bounded.trans_right {t₁ t₂ : ordnode α} {x : α} : ∀ {o₁ o₂}, bounded t₁ o₁ ↑x → bounded t₂ ↑x o₂ → bounded t₁ o₁ o₂ | o₁ none h₁ h₂ := h₁.weak_right | o₁ (some y) h₁ h₂ := h₁.mono_right (le_of_lt h₂.to_lt) theorem bounded.mem_lt : ∀ {t o} {x : α}, bounded t o ↑x → all (< x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_lt.imp (λ z h, lt_trans h h₂.to_lt), h₂.to_lt, h₂.mem_lt⟩ theorem bounded.mem_gt : ∀ {t o} {x : α}, bounded t ↑x o → all (> x) t | nil o x _ := ⟨⟩ | (node _ l y r) o x ⟨h₁, h₂⟩ := ⟨h₁.mem_gt, h₁.to_lt, h₂.mem_gt.imp (λ z, lt_trans h₁.to_lt)⟩ theorem bounded.of_lt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil o₁ ↑x → all (< x) t → bounded t o₁ ↑x | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁, h₂.of_lt al₂ al₃⟩ theorem bounded.of_gt : ∀ {t o₁ o₂} {x : α}, bounded t o₁ o₂ → bounded nil ↑x o₂ → all (> x) t → bounded t ↑x o₂ | nil o₁ o₂ x _ hn _ := hn | (node _ l y r) o₁ o₂ x ⟨h₁, h₂⟩ hn ⟨al₁, al₂, al₃⟩ := ⟨h₁.of_gt al₂ al₁, h₂⟩ theorem bounded.to_sep {t₁ t₂ o₁ o₂} {x : α} (h₁ : bounded t₁ o₁ ↑x) (h₂ : bounded t₂ ↑x o₂) : t₁.all (λ y, t₂.all (λ z : α, y < z)) := h₁.mem_lt.imp $ λ y yx, h₂.mem_gt.imp $ λ z xz, lt_trans yx xz end /-! ### `valid` -/ section variable [preorder α] /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. This version of `valid` also puts all elements in the tree in the interval `(lo, hi)`. -/ structure valid' (lo : with_bot α) (t : ordnode α) (hi : with_top α) : Prop := (ord : t.bounded lo hi) (sz : t.sized) (bal : t.balanced) /-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are correct, the tree is balanced, and the elements of the tree are organized according to the ordering. -/ def valid (t : ordnode α) : Prop := valid' ⊥ t ⊤ theorem valid'.mono_left {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' ↑y t o) : valid' ↑x t o := ⟨h.1.mono_left xy, h.2, h.3⟩ theorem valid'.mono_right {x y : α} (xy : x ≤ y) {t : ordnode α} {o} (h : valid' o t ↑x) : valid' o t ↑y := ⟨h.1.mono_right xy, h.2, h.3⟩ theorem valid'.trans_left {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (h : bounded t₁ o₁ ↑x) (H : valid' ↑x t₂ o₂) : valid' o₁ t₂ o₂ := ⟨h.trans_left H.1, H.2, H.3⟩ theorem valid'.trans_right {t₁ t₂ : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t₁ ↑x) (h : bounded t₂ ↑x o₂) : valid' o₁ t₁ o₂ := ⟨H.1.trans_right h, H.2, H.3⟩ theorem valid'.of_lt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil o₁ ↑x) (h₂ : all (< x) t) : valid' o₁ t ↑x := ⟨H.1.of_lt h₁ h₂, H.2, H.3⟩ theorem valid'.of_gt {t : ordnode α} {x : α} {o₁ o₂} (H : valid' o₁ t o₂) (h₁ : bounded nil ↑x o₂) (h₂ : all (> x) t) : valid' ↑x t o₂ := ⟨H.1.of_gt h₁ h₂, H.2, H.3⟩ theorem valid'.valid {t o₁ o₂} (h : @valid' α _ o₁ t o₂) : valid t := ⟨h.1.weak, h.2, h.3⟩ theorem valid'_nil {o₁ o₂} (h : bounded nil o₁ o₂) : valid' o₁ (@nil α) o₂ := ⟨h, ⟨⟩, ⟨⟩⟩ theorem valid_nil : valid (@nil α) := valid'_nil ⟨⟩ theorem valid'.node {s l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) (hs : s = size l + size r + 1) : valid' o₁ (@node α s l x r) o₂ := ⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩ theorem valid'.dual : ∀ {t : ordnode α} {o₁ o₂} (h : valid' o₁ t o₂), @valid' (order_dual α) _ o₂ (dual t) o₁ | nil o₁ o₂ h := valid'_nil h.1.dual | (node s l x r) o₁ o₂ ⟨⟨ol, or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ := let ⟨ol', sl', bl'⟩ := valid'.dual ⟨ol, sl, bl⟩, ⟨or', sr', br'⟩ := valid'.dual ⟨or, sr, br⟩ in ⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩, ⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩ theorem valid'.dual_iff {t : ordnode α} {o₁ o₂} : valid' o₁ t o₂ ↔ @valid' (order_dual α) _ o₂ (dual t) o₁ := ⟨valid'.dual, λ h, by have := valid'.dual h; rwa [dual_dual, order_dual.preorder.dual_dual] at this⟩ theorem valid.dual {t : ordnode α} : valid t → @valid (order_dual α) _ (dual t) := valid'.dual theorem valid.dual_iff {t : ordnode α} : valid t ↔ @valid (order_dual α) _ (dual t) := valid'.dual_iff theorem valid'.left {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' o₁ l x := ⟨H.1.1, H.2.2.1, H.3.2.1⟩ theorem valid'.right {s l x r o₁ o₂} (H : valid' o₁ (@node α s l x r) o₂) : valid' ↑x r o₂ := ⟨H.1.2, H.2.2.2, H.3.2.2⟩ theorem valid.left {s l x r} (H : valid (@node α s l x r)) : valid l := H.left.valid theorem valid.right {s l x r} (H : valid (@node α s l x r)) : valid r := H.right.valid theorem valid.size_eq {s l x r} (H : valid (@node α s l x r)) : size (@node α s l x r) = size l + size r + 1 := H.2.1 theorem valid'.node' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : balanced_sz (size l) (size r)) : valid' o₁ (@node' α l x r) o₂ := hl.node hr H rfl theorem valid'_singleton {x : α} {o₁ o₂} (h₁ : bounded nil o₁ ↑x) (h₂ : bounded nil ↑x o₂) : valid' o₁ (singleton x : ordnode α) o₂ := (valid'_nil h₁).node (valid'_nil h₂) (or.inl zero_le_one) rfl theorem valid_singleton {x : α} : valid (singleton x : ordnode α) := valid'_singleton ⟨⟩ ⟨⟩ theorem valid'.node3_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m)) (H2 : balanced_sz (size l + size m + 1) (size r)) : valid' o₁ (@node3_l α l x m y r) o₂ := (hl.node' hm H1).node' hr H2 theorem valid'.node3_r {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (H1 : balanced_sz (size l) (size m + size r + 1)) (H2 : balanced_sz (size m) (size r)) : valid' o₁ (@node3_r α l x m y r) o₂ := hl.node' (hm.node' hr H2) H1 theorem valid'.node4_l_lemma₁ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : b < 3 * a + 1 := by linarith theorem valid'.node4_l_lemma₂ {b c d : ℕ} (mr₂ : b + c + 1 ≤ 3 * d) : c ≤ 3 * d := by linarith theorem valid'.node4_l_lemma₃ {b c d : ℕ} (mr₁ : 2 * d ≤ b + c + 1) (mm₁ : b ≤ 3 * c) : d ≤ 3 * c := by linarith theorem valid'.node4_l_lemma₄ {a b c d : ℕ} (lr₁ : 3 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : a + b + 1 ≤ 3 * (c + d + 1) := by linarith theorem valid'.node4_l_lemma₅ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9) (mr₁ : 2 * d ≤ b + c + 1) (mm₂ : c ≤ 3 * b) : c + d + 1 ≤ 3 * (a + b + 1) := by linarith theorem valid'.node4_l {l x m y r o₁ o₂} (hl : valid' o₁ l ↑x) (hm : valid' ↑x m ↑y) (hr : valid' ↑y r o₂) (Hm : 0 < size m) (H : (size l = 0 ∧ size m = 1 ∧ size r ≤ 1) ∨ (0 < size l ∧ ratio * size r ≤ size m ∧ delta * size l ≤ size m + size r ∧ 3 * (size m + size r) ≤ 16 * size l + 9 ∧ size m ≤ delta * size r)) : valid' o₁ (@node4_l α l x m y r) o₂ := begin cases m with s ml z mr, {cases Hm}, suffices : balanced_sz (size l) (size ml) ∧ balanced_sz (size mr) (size r) ∧ balanced_sz (size l + size ml + 1) (size mr + size r + 1), from (valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2), rcases H with ⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lr₂, mr₂⟩, { rw [hm.2.size_eq, nat.succ_inj', add_eq_zero_iff] at m1, rw [l0, m1.1, m1.2], rcases size r with _|_|_; exact dec_trivial }, { cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0 at mr₂, cases not_le_of_lt Hm mr₂ }, rw [hm.2.size_eq] at lr₁ lr₂ mr₁ mr₂, by_cases mm : size ml + size mr ≤ 1, { have r1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans mr₁ (nat.succ_le_succ mm) : _ ≤ ratio * 1)) r0, rw [r1, add_assoc] at lr₁, have l1 := le_antisymm ((mul_le_mul_left dec_trivial).1 (le_trans lr₁ (add_le_add_right mm 2) : _ ≤ delta * 1)) l0, rw [l1, r1], cases size ml; cases size mr, { exact dec_trivial }, { rw zero_add at mm, rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rcases mm with _|⟨_,⟨⟩⟩, exact dec_trivial }, { rw nat.succ_add at mm, rcases mm with _|⟨_,⟨⟩⟩ } }, rcases hm.3.1.resolve_left mm with ⟨mm₁, mm₂⟩, cases nat.eq_zero_or_pos (size ml) with ml0 ml0, { rw [ml0, mul_zero, nat.le_zero_iff] at mm₂, rw [ml0, mm₂] at mm, cases mm dec_trivial }, cases nat.eq_zero_or_pos (size mr) with mr0 mr0, { rw [mr0, mul_zero, nat.le_zero_iff] at mm₁, rw [mr0, mm₁] at mm, cases mm dec_trivial }, have : 2 * size l ≤ size ml + size mr + 1, { have := nat.mul_le_mul_left _ lr₁, rw [mul_left_comm, mul_add] at this, have := le_trans this (add_le_add_left mr₁ _), rw [← nat.succ_mul] at this, exact (mul_le_mul_left dec_trivial).1 this }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { refine (mul_le_mul_left dec_trivial).1 (le_trans this _), rw [two_mul, nat.succ_le_iff], refine add_lt_add_of_lt_of_le _ mm₂, simpa using (mul_lt_mul_right ml0).2 (dec_trivial:1<3) }, { exact nat.le_of_lt_succ (valid'.node4_l_lemma₁ lr₂ mr₂ mm₁) }, { exact valid'.node4_l_lemma₂ mr₂ }, { exact valid'.node4_l_lemma₃ mr₁ mm₁ }, { exact valid'.node4_l_lemma₄ lr₁ mr₂ mm₁ }, { exact valid'.node4_l_lemma₅ lr₂ mr₁ mm₂ } } end theorem valid'.rotate_l_lemma₁ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (hb₂ : c ≤ 3 * b) : a ≤ 3 * b := by linarith theorem valid'.rotate_l_lemma₂ {a b c : ℕ} (H3 : 2 * (b + c) ≤ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by linarith theorem valid'.rotate_l_lemma₃ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (h : b < 2 * c) : a + b < 3 * c := by linarith theorem valid'.rotate_l_lemma₄ {a b : ℕ} (H3 : 2 * b ≤ 9 * a + 3) : 3 * b ≤ 16 * a + 9 := by linarith theorem valid'.rotate_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size l < size r) (H3 : 2 * size r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@rotate_l α l x r) o₂ := begin cases r with rs rl rx rr, {cases H2}, rw [hr.2.size_eq, nat.lt_succ_iff] at H2, rw [hr.2.size_eq] at H3, replace H3 : 2 * (size rl + size rr) ≤ 9 * size l + 3 ∨ size rl + size rr ≤ 2 := H3.imp (@nat.le_of_add_le_add_right 2 _ _) nat.le_of_succ_le_succ, have H3_0 : size l = 0 → size rl + size rr ≤ 2, { intro l0, rw l0 at H3, exact (or_iff_right_of_imp $ by exact λ h, (mul_le_mul_left dec_trivial).1 (le_trans h dec_trivial)).1 H3 }, have H3p : size l > 0 → 2 * (size rl + size rr) ≤ 9 * size l + 3 := λ l0 : 1 ≤ size l, (or_iff_left_of_imp $ by intro; linarith).1 H3, have ablem : ∀ {a b : ℕ}, 1 ≤ a → a + b ≤ 2 → b ≤ 1, {intros, linarith}, have hlp : size l > 0 → ¬ size rl + size rr ≤ 1 := λ l0 hb, absurd (le_trans (le_trans (nat.mul_le_mul_left _ l0) H2) hb) dec_trivial, rw rotate_l, split_ifs, { have rr0 : size rr > 0 := (mul_lt_mul_left dec_trivial).1 (lt_of_le_of_lt (nat.zero_le _) h : ratio * 0 < _), suffices : balanced_sz (size l) (size rl) ∧ balanced_sz (size l + size rl + 1) (size rr), { exact hl.node3_l hr.left hr.right this.1 this.2 }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, replace H3 := H3_0 l0, have := hr.3.1, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at this ⊢, rw le_antisymm (balanced_sz_zero.1 this.symm) rr0, exact dec_trivial }, have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0, rw add_comm at H3, rw [rr1, show size rl = 1, from le_antisymm (ablem rr0 H3) rl0], exact dec_trivial }, replace H3 := H3p l0, rcases hr.3.1.resolve_left (hlp l0) with ⟨hb₁, hb₂⟩, cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw rl0 at hb₂, cases not_le_of_gt rr0 hb₂ }, cases eq_or_lt_of_le (show 1 ≤ size rr, from rr0) with rr1 rr1, { rw [← rr1] at h H2 ⊢, have : size rl = 1 := le_antisymm (nat.lt_succ_iff.1 h) rl0, rw this at H2, exact absurd (le_trans (nat.mul_le_mul_left _ l0) H2) dec_trivial }, refine ⟨or.inr ⟨_, _⟩, or.inr ⟨_, _⟩⟩, { exact valid'.rotate_l_lemma₁ H2 hb₂ }, { exact nat.le_of_lt_succ (valid'.rotate_l_lemma₂ H3 h) }, { exact valid'.rotate_l_lemma₃ H2 h }, { exact le_trans hb₂ (nat.mul_le_mul_left _ $ le_trans (nat.le_add_left _ _) (nat.le_add_right _ _)) } }, { cases nat.eq_zero_or_pos (size rl) with rl0 rl0, { rw [rl0, not_lt, nat.le_zero_iff, nat.mul_eq_zero] at h, replace h := h.resolve_left dec_trivial, rw [rl0, h, nat.le_zero_iff, nat.mul_eq_zero] at H2, rw [hr.2.size_eq, rl0, h, H2.resolve_left dec_trivial] at H1, cases H1 dec_trivial }, refine hl.node4_l hr.left hr.right rl0 _, cases nat.eq_zero_or_pos (size l) with l0 l0, { replace H3 := H3_0 l0, cases nat.eq_zero_or_pos (size rr) with rr0 rr0, { have := hr.3.1, rw rr0 at this, exact or.inl ⟨l0, le_antisymm (balanced_sz_zero.1 this) rl0, rr0.symm ▸ zero_le_one⟩ }, exact or.inl ⟨l0, le_antisymm (ablem rr0 $ by rwa add_comm) rl0, ablem rl0 H3⟩ }, exact or.inr ⟨l0, not_lt.1 h, H2, valid'.rotate_l_lemma₄ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩ } end theorem valid'.rotate_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H1 : ¬ size l + size r ≤ 1) (H2 : delta * size r < size l) (H3 : 2 * size l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@rotate_r α l x r) o₂ := begin refine valid'.dual_iff.2 _, rw dual_rotate_r, refine hr.dual.rotate_l hl.dual _ _ _, { rwa [size_dual, size_dual, add_comm] }, { rwa [size_dual, size_dual] }, { rwa [size_dual, size_dual] } end theorem valid'.balance'_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) (H₂ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance' α l x r) o₂ := begin rw balance', split_ifs, { exact hl.node' hr (or.inl h) }, { exact hl.rotate_l hr h h_1 H₁ }, { exact hl.rotate_r hr h h_2 H₂ }, { exact hl.node' hr (or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩) } end theorem valid'.balance'_lemma {α l l' r r'} (H1 : balanced_sz l' r') (H2 : nat.dist (@size α l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l') : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3 := begin suffices : @size α r ≤ 3 * (size l + 1), { cases nat.eq_zero_or_pos (size l) with l0 l0, { apply or.inr, rwa l0 at this }, change 1 ≤ _ at l0, apply or.inl, linarith }, rcases H2 with ⟨hl, rfl⟩ | ⟨hr, rfl⟩; rcases H1 with h | ⟨h₁, h₂⟩, { exact le_trans (nat.le_add_left _ _) (le_trans h (nat.le_add_left _ _)) }, { exact le_trans h₂ (nat.mul_le_mul_left _ $ le_trans (nat.dist_tri_right _ _) (nat.add_le_add_left hl _)) }, { exact le_trans (nat.dist_tri_left' _ _) (le_trans (add_le_add hr (le_trans (nat.le_add_left _ _) h)) dec_trivial) }, { rw nat.mul_succ, exact le_trans (nat.dist_tri_right' _ _) (add_le_add h₂ (le_trans hr dec_trivial)) }, end theorem valid'.balance' {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance' α l x r) o₂ := let ⟨l', r', H1, H2⟩ := H in valid'.balance'_aux hl hr (valid'.balance'_lemma H1 H2) (valid'.balance'_lemma H1.symm H2.symm) theorem valid'.balance {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : ∃ l' r', balanced_sz l' r' ∧ (nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ nat.dist (size r) r' ≤ 1 ∧ size l = l')) : valid' o₁ (@balance α l x r) o₂ := by rw balance_eq_balance' hl.3 hr.3 hl.2 hr.2; exact hl.balance' hr H theorem valid'.balance_l_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size l = 0 → size r ≤ 1) (H₂ : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) (H₃ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : valid' o₁ (@balance_l α l x r) o₂ := begin rw [balance_l_eq_balance hl.2 hr.2 H₁ H₂, balance_eq_balance' hl.3 hr.3 hl.2 hr.2], refine hl.balance'_aux hr (or.inl _) H₃, cases nat.eq_zero_or_pos (size r) with r0 r0, { rw r0, exact nat.zero_le _ }, cases nat.eq_zero_or_pos (size l) with l0 l0, { rw l0, exact le_trans (nat.mul_le_mul_left _ (H₁ l0)) dec_trivial }, replace H₂ : _ ≤ 3 * _ := H₂ l0 r0, linarith end theorem valid'.balance_l {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised l' (size l) ∧ balanced_sz l' (size r)) ∨ (∃ r', raised (size r) r' ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_l α l x r) o₂ := begin rw balance_l_eq_balance' hl.3 hr.3 hl.2 hr.2 H, refine hl.balance' hr _, rcases H with ⟨l', e, H⟩ | ⟨r', e, H⟩, { exact ⟨_, _, H, or.inl ⟨e.dist_le', rfl⟩⟩ }, { exact ⟨_, _, H, or.inr ⟨e.dist_le, rfl⟩⟩ }, end theorem valid'.balance_r_aux {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H₁ : size r = 0 → size l ≤ 1) (H₂ : 1 ≤ size r → 1 ≤ size l → size l ≤ delta * size r) (H₃ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) : valid' o₁ (@balance_r α l x r) o₂ := begin rw [valid'.dual_iff, dual_balance_r], have := hr.dual.balance_l_aux hl.dual, rw [size_dual, size_dual] at this, exact this H₁ H₂ H₃ end theorem valid'.balance_r {l x r o₁ o₂} (hl : valid' o₁ l ↑x) (hr : valid' ↑x r o₂) (H : (∃ l', raised (size l) l' ∧ balanced_sz l' (size r)) ∨ (∃ r', raised r' (size r) ∧ balanced_sz (size l) r')) : valid' o₁ (@balance_r α l x r) o₂ := by rw [valid'.dual_iff, dual_balance_r]; exact hr.dual.balance_l hl.dual (balance_sz_dual H) theorem valid'.erase_max_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' o₁ (@erase_max α (node' l x r)) ↑(find_max' x r) ∧ size (node' l x r) = size (erase_max (node' l x r)) + 1 := begin have := H.2.eq_node', rw this at H, clear this, induction r with rs rl rx rr IHrl IHrr generalizing l x o₁, { exact ⟨H.left, rfl⟩ }, have := H.2.2.2.eq_node', rw this at H ⊢, rcases IHrr H.right with ⟨h, e⟩, refine ⟨valid'.balance_l H.left h (or.inr ⟨_, or.inr e, H.3.1⟩), _⟩, rw [erase_max, size_balance_l H.3.2.1 h.3 H.2.2.1 h.2 (or.inr ⟨_, or.inr e, H.3.1⟩)], rw [size, e], refl end theorem valid'.erase_min_aux {s l x r o₁ o₂} (H : valid' o₁ (node s l x r) o₂) : valid' ↑(find_min' l x) (@erase_min α (node' l x r)) o₂ ∧ size (node' l x r) = size (erase_min (node' l x r)) + 1 := by have := H.dual.erase_max_aux; rwa [← dual_node', size_dual, ← dual_erase_min, size_dual, ← valid'.dual_iff, find_max'_dual] at this theorem erase_min.valid : ∀ {t} (h : @valid α _ t), valid (erase_min t) | nil _ := valid_nil | (node _ l x r) h := by rw h.2.eq_node'; exact h.erase_min_aux.1.valid theorem erase_max.valid {t} (h : @valid α _ t) : valid (erase_max t) := by rw [valid.dual_iff, dual_erase_max]; exact erase_min.valid h.dual theorem valid'.glue_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) (bal : balanced_sz (size l) (size r)) : valid' o₁ (@glue α l r) o₂ ∧ size (glue l r) = size l + size r := begin cases l with ls ll lx lr, {exact ⟨hr, (zero_add _).symm⟩ }, cases r with rs rl rx rr, {exact ⟨hl, rfl⟩ }, dsimp [glue], split_ifs, { rw [split_max_eq, glue], cases valid'.erase_max_aux hl with v e, suffices H, refine ⟨valid'.balance_r v (hr.of_gt _ _) H, _⟩, { refine find_max'_all lx lr hl.1.2.to_nil (sep.2.2.imp _), exact λ x h, hr.1.2.to_nil.mono_left (le_of_lt h.2.1) }, { exact @find_max'_all _ (λ a, all (> a) (node rs rl rx rr)) lx lr sep.2.1 sep.2.2 }, { rw [size_balance_r v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1], refl }, { refine or.inl ⟨_, or.inr e, _⟩, rwa hl.2.eq_node' at bal } }, { rw [split_min_eq, glue], cases valid'.erase_min_aux hr with v e, suffices H, refine ⟨valid'.balance_l (hl.of_lt _ _) v H, _⟩, { refine @find_min'_all _ (λ a, bounded nil o₁ ↑a) rl rx (sep.2.1.1.imp _) hr.1.1.to_nil, exact λ y h, hl.1.1.to_nil.mono_right (le_of_lt h) }, { exact @find_min'_all _ (λ a, all (< a) (node ls ll lx lr)) rl rx (all_iff_forall.2 $ λ x hx, sep.imp $ λ y hy, all_iff_forall.1 hy.1 _ hx) (sep.imp $ λ y hy, hy.2.1) }, { rw [size_balance_l hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1], refl }, { refine or.inr ⟨_, or.inr e, _⟩, rwa hr.2.eq_node' at bal } }, end theorem valid'.glue {l x r o₁ o₂} (hl : valid' o₁ l ↑(x:α)) (hr : valid' ↑x r o₂) : balanced_sz (size l) (size r) → valid' o₁ (@glue α l r) o₂ ∧ size (@glue α l r) = size l + size r := valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1) theorem valid'.merge_lemma {a b c : ℕ} (h₁ : 3 * a < b + c + 1) (h₂ : b ≤ 3 * c) : 2 * (a + b) ≤ 9 * c + 5 := by linarith theorem valid'.merge_aux₁ {o₁ o₂ ls ll lx lr rs rl rx rr t} (hl : valid' o₁ (@node α ls ll lx lr) o₂) (hr : valid' o₁ (node rs rl rx rr) o₂) (h : delta * ls < rs) (v : valid' o₁ t ↑rx) (e : size t = ls + size rl) : valid' o₁ (balance_l t rx rr) o₂ ∧ size (balance_l t rx rr) = ls + rs := begin rw hl.2.1 at e, rw [hl.2.1, hr.2.1, delta] at h, rcases hr.3.1 with H|⟨hr₁, hr₂⟩, {linarith}, suffices H₂, suffices H₁, refine ⟨valid'.balance_l_aux v hr.right H₁ H₂ _, _⟩, { rw e, exact or.inl (valid'.merge_lemma h hr₁) }, { rw [balance_l_eq_balance v.2 hr.2.2.2 H₁ H₂, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2, size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1], simp [add_comm, add_left_comm] }, { rw [e, add_right_comm], rintro ⟨⟩ }, { intros _ h₁, rw e, unfold delta at hr₂ ⊢, linarith } end theorem valid'.merge_aux {l r o₁ o₂} (hl : valid' o₁ l o₂) (hr : valid' o₁ r o₂) (sep : l.all (λ x, r.all (λ y, x < y))) : valid' o₁ (@merge α l r) o₂ ∧ size (merge l r) = size l + size r := begin induction l with ls ll lx lr IHll IHlr generalizing o₁ o₂ r, { exact ⟨hr, (zero_add _).symm⟩ }, induction r with rs rl rx rr IHrl IHrr generalizing o₁ o₂, { exact ⟨hl, rfl⟩ }, rw [merge_node], split_ifs, { cases IHrl (sep.imp $ λ x h, h.1) (hl.of_lt hr.1.1.to_nil $ sep.imp $ λ x h, h.2.1) hr.left with v e, exact valid'.merge_aux₁ hl hr h v e }, { cases IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 with v e, have := valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual, rw [size_dual, add_comm, size_dual, ← dual_balance_r, ← valid'.dual_iff, size_dual, add_comm rs] at this, exact this e }, { refine valid'.glue_aux hl hr sep (or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩) } end theorem valid.merge {l r} (hl : valid l) (hr : valid r) (sep : l.all (λ x, r.all (λ y, x < y))) : valid (@merge α l r) := (valid'.merge_aux hl hr sep).1 theorem insert_with.valid_aux [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) : ∀ {t o₁ o₂}, valid' o₁ t o₂ → bounded nil o₁ ↑x → bounded nil ↑x o₂ → valid' o₁ (insert_with f x t) o₂ ∧ raised (size t) (size (insert_with f x t)) | nil o₁ o₂ _ bl br := ⟨valid'_singleton bl br, or.inr rfl⟩ | (node sz l y r) o₁ o₂ h bl br := begin rw [insert_with, cmp_le], split_ifs; rw [insert_with], { rcases h with ⟨⟨lx, xr⟩, hs, hb⟩, rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩, refine ⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, or.inl rfl⟩ }, { rcases insert_with.valid_aux h.left bl (lt_of_le_not_le h_1 h_2) with ⟨vl, e⟩, suffices H, { refine ⟨vl.balance_l h.right H, _⟩, rw [size_balance_l vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq], refine (e.add_right _).add_right _ }, { exact or.inl ⟨_, e, h.3.1⟩ } }, { have : y < x := lt_of_le_not_le ((total_of (≤) _ _).resolve_left h_1) h_1, rcases insert_with.valid_aux h.right this br with ⟨vr, e⟩, suffices H, { refine ⟨h.left.balance_r vr H, _⟩, rw [size_balance_r h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq], refine (e.add_left _).add_right _ }, { exact or.inr ⟨_, e, h.3.1⟩ } }, end theorem insert_with.valid [is_total α (≤)] [@decidable_rel α (≤)] (f : α → α) (x : α) (hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t} (h : valid t) : valid (insert_with f x t) := (insert_with.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1 theorem insert_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, ordnode.insert x t = insert_with (λ _, x) x t | nil := rfl | (node _ l y r) := by unfold ordnode.insert insert_with; cases cmp_le x y; unfold ordnode.insert insert_with; simp [insert_eq_insert_with] theorem insert.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (ordnode.insert x t) := by rw insert_eq_insert_with; exact insert_with.valid _ _ (λ _ _, ⟨le_refl _, le_refl _⟩) h theorem insert'_eq_insert_with [@decidable_rel α (≤)] (x : α) : ∀ t, insert' x t = insert_with id x t | nil := rfl | (node _ l y r) := by unfold insert' insert_with; cases cmp_le x y; unfold insert' insert_with; simp [insert'_eq_insert_with] theorem insert'.valid [is_total α (≤)] [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (insert' x t) := by rw insert'_eq_insert_with; exact insert_with.valid _ _ (λ _, id) h theorem valid'.map_aux {β} [preorder β] {f : α → β} (f_strict_mono : strict_mono f) {t a₁ a₂} (h : valid' a₁ t a₂) : valid' (option.map f a₁) (map f t) (option.map f a₂) ∧ (map f t).size = t.size := begin induction t generalizing a₁ a₂, { simp [map], apply valid'_nil, cases a₁, { trivial }, cases a₂, { trivial }, simp [bounded], exact f_strict_mono h.ord }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, simp [map], split, { exact and.intro t_l_valid.ord t_r_valid.ord }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.sz.1 }, { exact t_l_valid.sz }, { exact t_r_valid.sz } }, { repeat { split }, { rw [t_l_size, t_r_size], exact h.bal.1 }, { exact t_l_valid.bal }, { exact t_r_valid.bal } } }, end theorem map.valid {β} [preorder β] {f : α → β} (f_strict_mono : strict_mono f) {t} (h : valid t) : valid (map f t) := (valid'.map_aux f_strict_mono h).1 theorem valid'.erase_aux [@decidable_rel α (≤)] (x : α) {t a₁ a₂} (h : valid' a₁ t a₂) : valid' a₁ (erase x t) a₂ ∧ raised (erase x t).size t.size := begin induction t generalizing a₁ a₂, { simp [erase, raised], exact h }, { simp [erase], have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, cases t_ih_l' with t_l_valid t_l_size, cases t_ih_r' with t_r_valid t_r_size, cases (cmp_le x t_x); simp [erase._match_1]; rw h.sz.1, { suffices h_balanceable, split, { exact valid'.balance_r t_l_valid h.right h_balanceable }, { rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable, repeat { apply raised.add_right }, exact t_l_size }, { left, existsi t_l.size, exact (and.intro t_l_size h.bal.1) } }, { have h_glue := valid'.glue h.left h.right h.bal.1, cases h_glue with h_glue_valid h_glue_sized, split, { exact h_glue_valid }, { right, rw h_glue_sized } }, { suffices h_balanceable, split, { exact valid'.balance_l h.left t_r_valid h_balanceable }, { rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable, apply raised.add_right, apply raised.add_left, exact t_r_size }, { right, existsi t_r.size, exact (and.intro t_r_size h.bal.1) } } }, end theorem erase.valid [@decidable_rel α (≤)] (x : α) {t} (h : valid t) : valid (erase x t) := (valid'.erase_aux x h).1 theorem size_erase_of_mem [@decidable_rel α (≤)] {x : α} {t a₁ a₂} (h : valid' a₁ t a₂) (h_mem : x ∈ t) : size (erase x t) = size t - 1 := begin induction t generalizing a₁ a₂ h h_mem, { contradiction }, { have t_ih_l' := t_ih_l h.left, have t_ih_r' := t_ih_r h.right, clear t_ih_l t_ih_r, unfold has_mem.mem mem at h_mem, unfold erase, cases (cmp_le x t_x); simp [mem._match_1] at h_mem; simp [erase._match_1], { have t_ih_l := t_ih_l' h_mem, clear t_ih_l' t_ih_r', have t_l_h := valid'.erase_aux x h.left, cases t_l_h with t_l_valid t_l_size, rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz (or.inl (exists.intro t_l.size (and.intro t_l_size h.bal.1))), rw [t_ih_l, h.sz.1], have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem, cases t_l.size with t_l_size, { cases h_pos_t_l_size }, simp [nat.succ_add] }, { rw [(valid'.glue h.left h.right h.bal.1).2, h.sz.1], refl }, { have t_ih_r := t_ih_r' h_mem, clear t_ih_l' t_ih_r', have t_r_h := valid'.erase_aux x h.right, cases t_r_h with t_r_valid t_r_size, rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz (or.inr (exists.intro t_r.size (and.intro t_r_size h.bal.1))), rw [t_ih_r, h.sz.1], have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem, cases t_r.size with t_r_size, { cases h_pos_t_r_size }, simp [nat.succ_add] } }, end end end ordnode /-- An `ordset α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. The correctness property of the tree is baked into the type, so all operations on this type are correct by construction. -/ def ordset (α : Type*) [preorder α] := {t : ordnode α // t.valid} namespace ordset open ordnode variable [preorder α] /-- O(1). The empty set. -/ def nil : ordset α := ⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩ /-- O(1). Get the size of the set. -/ def size (s : ordset α) : ℕ := s.1.size /-- O(1). Construct a singleton set containing value `a`. -/ protected def singleton (a : α) : ordset α := ⟨singleton a, valid_singleton⟩ instance : has_emptyc (ordset α) := ⟨nil⟩ instance : inhabited (ordset α) := ⟨nil⟩ instance : has_singleton α (ordset α) := ⟨ordset.singleton⟩ /-- O(1). Is the set empty? -/ def empty (s : ordset α) : Prop := s = ∅ theorem empty_iff {s : ordset α} : s = ∅ ↔ s.1.empty := ⟨λ h, by cases h; exact rfl, λ h, by cases s; cases s_val; [exact rfl, cases h]⟩ instance : decidable_pred (@empty α _) := λ s, decidable_of_iff' _ empty_iff /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. -/ protected def insert [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.insert x s.1, insert.valid _ s.2⟩ instance [is_total α (≤)] [@decidable_rel α (≤)] : has_insert α (ordset α) := ⟨ordset.insert⟩ /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. -/ def insert' [is_total α (≤)] [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨insert' x s.1, insert'.valid _ s.2⟩ section variables [@decidable_rel α (≤)] /-- O(log n). Does the set contain the element `x`? That is, is there an element that is equivalent to `x` in the order? -/ def mem (x : α) (s : ordset α) : bool := x ∈ s.val /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. -/ def find (x : α) (s : ordset α) : option α := ordnode.find x s.val instance : has_mem α (ordset α) := ⟨λ x s, mem x s⟩ instance mem.decidable (x : α) (s : ordset α) : decidable (x ∈ s) := bool.decidable_eq _ _ theorem pos_size_of_mem {x : α} {t : ordset α} (h_mem : x ∈ t) : 0 < size t := begin simp [has_mem.mem, mem] at h_mem, apply ordnode.pos_size_of_mem t.property.sz h_mem, end end /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. -/ def erase [@decidable_rel α (≤)] (x : α) (s : ordset α) : ordset α := ⟨ordnode.erase x s.val, ordnode.erase.valid x s.property⟩ /-- O(n). Map a function across a tree, without changing the structure. -/ def map {β} [preorder β] (f : α → β) (f_strict_mono : strict_mono f) (s : ordset α) : ordset β := ⟨ordnode.map f s.val, ordnode.map.valid f_strict_mono s.property⟩ end ordset
7f4ce6af3492980531aae3bbe20b6c16c35315ad
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/mllist.lean
cbe5bbeb4e2c03d3bd0ead9b6062ad3550246d42
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
5,424
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carnerio, Keeley Hoek, Simon Hudon, Scott Morrison Monadic lazy lists. The inductive construction is not allowed outside of meta (indeed, we can build infinite objects). This isn't so bad, as the typical use is with the tactic monad, in any case. As we're in meta anyway, we don't bother with proofs about these constructions. -/ import data.option.basic universes u v namespace tactic -- We hide this away in the tactic namespace, just because it's all meta. meta inductive mllist (m : Type u → Type u) (α : Type u) : Type u | nil {} : mllist | cons : m (option α × mllist) → mllist namespace mllist variables {α β : Type u} {m : Type u → Type u} [alternative m] meta def fix (f : α → m α) : α → mllist m α | x := cons $ (λ a, (some x, fix a)) <$> f x <|> pure (some x, nil) variables [monad m] meta def fixl_with (f : α → m (α × list β)) : α → list β → mllist m β | s (b :: rest) := cons $ pure (some b, fixl_with s rest) | s [] := cons $ do { (s', l) ← f s, match l with | (b :: rest) := pure (some b, fixl_with s' rest) | [] := pure (none, fixl_with s' []) end } <|> pure (none, nil) meta def fixl (f : α → m (α × list β)) (s : α) : mllist m β := fixl_with f s [] meta def uncons {α : Type u} : mllist m α → m (option (α × mllist m α)) | nil := pure none | (cons l) := do (x, xs) ← l, some x ← return x | uncons xs, return (x, xs) meta def empty {α : Type u} (xs : mllist m α) : m (ulift bool) := (ulift.up ∘ option.is_some) <$> uncons xs meta def of_list {α : Type u} : list α → mllist m α | [] := nil | (h :: t) := cons (pure (h, of_list t)) meta def m_of_list {α : Type u} : list (m α) → mllist m α | [] := nil | (h :: t) := cons ((λ x, (x, m_of_list t)) <$> some <$> h) meta def force {α} : mllist m α → m (list α) | nil := pure [] | (cons l) := do (x, xs) ← l, some x ← pure x | force xs, (::) x <$> (force xs) meta def take {α} : mllist m α → ℕ → m (list α) | nil _ := pure [] | _ 0 := pure [] | (cons l) (n+1) := do (x, xs) ← l, some x ← pure x | take xs (n+1), (::) x <$> (take xs n) meta def map {α β : Type u} (f : α → β) : mllist m α → mllist m β | nil := nil | (cons l) := cons $ do (x, xs) ← l, pure (f <$> x, map xs) meta def mmap {α β : Type u} (f : α → m β) : mllist m α → mllist m β | nil := nil | (cons l) := cons $ do (x, xs) ← l, b ← x.traverse f, return (b, mmap xs) meta def filter {α : Type u} (p : α → Prop) [decidable_pred p] : mllist m α → mllist m α | nil := nil | (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, filter r), return (if p a then some a else none, filter r) meta def mfilter [alternative m] {α β : Type u} (p : α → m β) : mllist m α → mllist m α | nil := nil | (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, mfilter r), (p a >> return (a, mfilter r)) <|> return (none , mfilter r) meta def filter_map {α β : Type u} (f : α → option β) : mllist m α → mllist m β | nil := nil | (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, filter_map r), match f a with | (some b) := return (some b, filter_map r) | none := return (none, filter_map r) end meta def mfilter_map [alternative m] {α β : Type u} (f : α → m β) : mllist m α → mllist m β | nil := nil | (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, mfilter_map r), (f a >>= (λ b, return (some b, mfilter_map r))) <|> return (none, mfilter_map r) meta def append {α : Type u} : mllist m α → mllist m α → mllist m α | nil ys := ys | (cons xs) ys := cons $ do (x, xs) ← xs, return (x, append xs ys) meta def join {α : Type u} : mllist m (mllist m α) → mllist m α | nil := nil | (cons l) := cons $ do (xs,r) ← l, some xs ← return xs | return (none, join r), match xs with | nil := return (none, join r) | cons m := do (a,n) ← m, return (a, join (cons $ return (n, r))) end meta def squash {α} (t : m (mllist m α)) : mllist m α := (mllist.m_of_list [t]).join meta def enum_from {α : Type u} : ℕ → mllist m α → mllist m (ℕ × α) | _ nil := nil | n (cons l) := cons $ do (a, r) ← l, some a ← return a | return (none, enum_from n r), return ((n, a), (enum_from (n + 1) r)) meta def enum {α : Type u} : mllist m α → mllist m (ℕ × α) := enum_from 0 meta def range {m : Type → Type} [alternative m] : mllist m ℕ := mllist.fix (λ n, pure (n + 1)) 0 meta def concat {α : Type u} : mllist m α → α → mllist m α | L a := (mllist.of_list [L, mllist.of_list [a]]).join meta def bind_ {α β : Type u} : mllist m α → (α → mllist m β) → mllist m β | nil f := nil | (cons ll) f := cons $ do (x, xs) ← ll, some x ← return x | return (none, bind_ xs f), return (none, append (f x) (bind_ xs f)) meta def monad_lift {α} (x : m α) : mllist m α := cons $ (flip prod.mk nil ∘ some) <$> x end mllist end tactic
46f3dcf85e0ce2e3b62b6f80a9917bc69879d509
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_compute_slope_soundness.lean
91773fc59108b6b9c78eefc7303737a5c323ba0f
[]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
10,381
lean
/- File: signature_recover_public_key_compute_slope_soundness.lean Autogenerated file. -/ import starkware.cairo.lean.semantics.soundness.hoare import .signature_recover_public_key_code import ..signature_recover_public_key_spec import .signature_recover_public_key_verify_zero_soundness import .signature_recover_public_key_unreduced_mul_soundness import .signature_recover_public_key_nondet_bigint3_soundness open tactic open starkware.cairo.common.cairo_secp.ec open starkware.cairo.common.cairo_secp.bigint open starkware.cairo.common.cairo_secp.field variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F] variable mem : F → F variable σ : register_state F /- starkware.cairo.common.cairo_secp.ec.compute_slope autogenerated soundness theorem -/ theorem auto_sound_compute_slope -- arguments (range_check_ptr : F) (point0 point1 : EcPoint F) -- code is in memory at σ.pc (h_mem : mem_at mem code_compute_slope σ.pc) -- all dependencies are in memory (h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 220)) (h_mem_5 : mem_at mem code_unreduced_mul (σ.pc - 208)) (h_mem_7 : mem_at mem code_verify_zero (σ.pc - 172)) -- input arguments on the stack (hin_range_check_ptr : range_check_ptr = mem (σ.fp - 15)) (hin_point0 : point0 = cast_EcPoint mem (σ.fp - 14)) (hin_point1 : point1 = cast_EcPoint mem (σ.fp - 8)) -- conclusion : ensures_ret mem σ (λ κ τ, τ.ap = σ.ap + 59 ∧ ∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 15)) (mem $ τ.ap - 4) (spec_compute_slope mem κ range_check_ptr point0 point1 (mem (τ.ap - 4)) (cast_BigInt3 mem (τ.ap - 3)))) := begin apply ensures_of_ensuresb, intro νbound, have h_mem_rec := h_mem, unpack_memory code_compute_slope at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23⟩, -- function call step_assert_eq hpc0 with arg0, step_sub hpc1 (auto_sound_nondet_bigint3 mem _ range_check_ptr _ _), { rw hpc2, norm_num2, exact h_mem_4 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [arg0] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, intros κ_call3 ap3 h_call3, rcases h_call3 with ⟨h_call3_ap_offset, h_call3⟩, rcases h_call3 with ⟨rc_m3, rc_mle3, hl_range_check_ptr₁, h_call3⟩, generalize' hr_rev_range_check_ptr₁: mem (ap3 - 4) = range_check_ptr₁, have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁, generalize' hr_rev_slope: cast_BigInt3 mem (ap3 - 3) = slope, simp only [hr_rev_slope] at h_call3, have htv_slope := hr_rev_slope.symm, clear hr_rev_slope, try { simp only [arg0] at hl_range_check_ptr₁ }, rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁, try { simp only [arg0] at h_call3 }, rw [hin_range_check_ptr] at h_call3, clear arg0, -- let generalize' hl_rev_x_diff: ({ d0 := point0.x.d0 - point1.x.d0, d1 := point0.x.d1 - point1.x.d1, d2 := point0.x.d2 - point1.x.d2 } : BigInt3 F) = x_diff, have hl_x_diff := hl_rev_x_diff.symm, clear hl_rev_x_diff, try { dsimp at hl_x_diff }, try { arith_simps at hl_x_diff }, -- function call step_assert_eq hpc3 with arg0, step_assert_eq hpc4 with arg1, step_assert_eq hpc5 with arg2, step_assert_eq hpc6 with arg3, step_assert_eq hpc7 with arg4, step_assert_eq hpc8 with arg5, step_sub hpc9 (auto_sound_unreduced_mul mem _ x_diff slope _ _ _), { rw hpc10, norm_num2, exact h_mem_5 }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, hl_x_diff] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5] }, try { simp only [h_call3_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, hl_x_diff] }, try { dsimp [cast_EcPoint, cast_BigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5] }, try { simp only [h_call3_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call11 ap11 h_call11, rcases h_call11 with ⟨h_call11_ap_offset, h_call11⟩, generalize' hr_rev_x_diff_slope: cast_UnreducedBigInt3 mem (ap11 - 3) = x_diff_slope, simp only [hr_rev_x_diff_slope] at h_call11, have htv_x_diff_slope := hr_rev_x_diff_slope.symm, clear hr_rev_x_diff_slope, clear arg0 arg1 arg2 arg3 arg4 arg5, -- function call step_assert_eq hpc11 with arg0, step_assert_eq hpc12 with arg1, step_assert_eq hpc13 with arg2, step_assert_eq hpc14 with arg3, step_assert_eq hpc15 with arg4, step_assert_eq hpc16 with arg5, step_assert_eq hpc17 with arg6, step_sub hpc18 (auto_sound_verify_zero mem _ range_check_ptr₁ { d0 := x_diff_slope.d0 - point0.y.d0 + point1.y.d0, d1 := x_diff_slope.d1 - point0.y.d1 + point1.y.d1, d2 := x_diff_slope.d2 - point0.y.d2 + point1.y.d2 } _ _ _), { rw hpc19, norm_num2, exact h_mem_7 }, { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, hl_x_diff, htv_x_diff_slope] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5, arg6] }, try { simp only [h_call3_ap_offset, h_call11_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, }, { try { ext } ; { try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, hl_x_diff, htv_x_diff_slope] }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [(eq_sub_of_eq_add arg0), (eq_sub_of_eq_add arg1), (eq_sub_of_eq_add arg2), arg3, arg4, arg5, arg6] }, try { simp only [h_call3_ap_offset, h_call11_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, }, intros κ_call20 ap20 h_call20, rcases h_call20 with ⟨h_call20_ap_offset, h_call20⟩, rcases h_call20 with ⟨rc_m20, rc_mle20, hl_range_check_ptr₂, h_call20⟩, generalize' hr_rev_range_check_ptr₂: mem (ap20 - 1) = range_check_ptr₂, have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at hl_range_check_ptr₂ }, try { rw [h_call11_ap_offset] at hl_range_check_ptr₂ }, try { arith_simps at hl_range_check_ptr₂ }, rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂, try { simp only [arg0 ,arg1 ,arg2 ,arg3 ,arg4 ,arg5 ,arg6] at h_call20 }, try { rw [h_call11_ap_offset] at h_call20 }, try { arith_simps at h_call20 }, rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call20, clear arg0 arg1 arg2 arg3 arg4 arg5 arg6, -- return step_assert_eq hpc20 with hret0, step_assert_eq hpc21 with hret1, step_assert_eq hpc22 with hret2, step_ret hpc23, -- finish step_done, use_only [rfl, rfl], split, { try { simp only [h_call3_ap_offset ,h_call11_ap_offset ,h_call20_ap_offset] }, try { arith_simps }, try { refl } }, -- range check condition use_only (rc_m3+rc_m20+0+0), split, linarith [rc_mle3, rc_mle20], split, { arith_simps, try { simp only [hret0 ,hret1 ,hret2] }, rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], try { arith_simps, refl <|> norm_cast }, try { refl } }, intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr }, have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr, -- Final Proof -- user-provided reduction suffices auto_spec: auto_spec_compute_slope mem _ range_check_ptr point0 point1 _ _, { apply sound_compute_slope, apply auto_spec }, -- prove the auto generated assertion dsimp [auto_spec_compute_slope], try { norm_num1 }, try { arith_simps }, use_only [κ_call3], use_only [range_check_ptr₁], use_only [slope], have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr, have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' }, have spec3 := h_call3 rc_h_range_check_ptr', rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec3, try { dsimp at spec3, arith_simps at spec3 }, use_only [spec3], use_only [x_diff, hl_x_diff], use_only [κ_call11], use_only [x_diff_slope], try { dsimp at h_call11, arith_simps at h_call11 }, try { use_only [h_call11] }, use_only [κ_call20], use_only [range_check_ptr₂], have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁, have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' }, have spec20 := h_call20 rc_h_range_check_ptr₁', rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec20, try { dsimp at spec20, arith_simps at spec20 }, use_only [spec20], try { split, linarith }, try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_point0, hin_point1, htv_range_check_ptr₁, htv_slope, hl_x_diff, htv_x_diff_slope, htv_range_check_ptr₂] }, }, try { dsimp [cast_EcPoint, cast_BigInt3, cast_UnreducedBigInt3] }, try { arith_simps }, try { simp only [hret0, hret1, hret2] }, try { simp only [h_call3_ap_offset, h_call11_ap_offset, h_call20_ap_offset] }, try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, end
b75ccd34c9dcc6f919bce3342f12fc7dc84e5c17
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/preadditive/basic.lean
8bf3044d5c0c560a1619da8dfafa859f637cdbe7
[ "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
13,949
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel, Jakob von Raumer -/ import algebra.big_operators.basic import algebra.hom.group import algebra.module.basic import category_theory.endomorphism import category_theory.limits.shapes.kernels /-! # Preadditive categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A preadditive category is a category in which `X ⟶ Y` is an abelian group in such a way that composition of morphisms is linear in both variables. This file contains a definition of preadditive category that directly encodes the definition given above. The definition could also be phrased as follows: A preadditive category is a category enriched over the category of Abelian groups. Once the general framework to state this in Lean is available, the contents of this file should become obsolete. ## Main results * Definition of preadditive categories and basic properties * In a preadditive category, `f : Q ⟶ R` is mono if and only if `g ≫ f = 0 → g = 0` for all composable `g`. * A preadditive category with kernels has equalizers. ## Implementation notes The simp normal form for negation and composition is to push negations as far as possible to the outside. For example, `f ≫ (-g)` and `(-f) ≫ g` both become `-(f ≫ g)`, and `(-f) ≫ (-g)` is simplified to `f ≫ g`. ## References * [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2] ## Tags additive, preadditive, Hom group, Ab-category, Ab-enriched -/ universes v u open category_theory.limits open_locale big_operators namespace category_theory variables (C : Type u) [category.{v} C] /-- A category is called preadditive if `P ⟶ Q` is an abelian group such that composition is linear in both variables. -/ class preadditive := (hom_group : Π P Q : C, add_comm_group (P ⟶ Q) . tactic.apply_instance) (add_comp' : ∀ (P Q R : C) (f f' : P ⟶ Q) (g : Q ⟶ R), (f + f') ≫ g = f ≫ g + f' ≫ g . obviously) (comp_add' : ∀ (P Q R : C) (f : P ⟶ Q) (g g' : Q ⟶ R), f ≫ (g + g') = f ≫ g + f ≫ g' . obviously) attribute [instance] preadditive.hom_group restate_axiom preadditive.add_comp' restate_axiom preadditive.comp_add' attribute [simp,reassoc] preadditive.add_comp attribute [reassoc] preadditive.comp_add -- (the linter doesn't like `simp` on this lemma) attribute [simp] preadditive.comp_add end category_theory open category_theory namespace category_theory namespace preadditive section preadditive open add_monoid_hom variables {C : Type u} [category.{v} C] [preadditive C] section induced_category universes u' variables {C} {D : Type u'} (F : D → C) instance induced_category : preadditive.{v} (induced_category C F) := { hom_group := λ P Q, @preadditive.hom_group C _ _ (F P) (F Q), add_comp' := λ P Q R f f' g, add_comp' _ _ _ _ _ _, comp_add' := λ P Q R f g g', comp_add' _ _ _ _ _ _, } end induced_category instance full_subcategory (Z : C → Prop) : preadditive.{v} (full_subcategory Z) := { hom_group := λ P Q, @preadditive.hom_group C _ _ P.obj Q.obj, add_comp' := λ P Q R f f' g, add_comp' _ _ _ _ _ _, comp_add' := λ P Q R f g g', comp_add' _ _ _ _ _ _, } instance (X : C) : add_comm_group (End X) := by { dsimp [End], apply_instance, } instance (X : C) : ring (End X) := { left_distrib := λ f g h, preadditive.add_comp X X X g h f, right_distrib := λ f g h, preadditive.comp_add X X X h f g, ..(infer_instance : add_comm_group (End X)), ..(infer_instance : monoid (End X)) } /-- Composition by a fixed left argument as a group homomorphism -/ def left_comp {P Q : C} (R : C) (f : P ⟶ Q) : (Q ⟶ R) →+ (P ⟶ R) := mk' (λ g, f ≫ g) $ λ g g', by simp /-- Composition by a fixed right argument as a group homomorphism -/ def right_comp (P : C) {Q R : C} (g : Q ⟶ R) : (P ⟶ Q) →+ (P ⟶ R) := mk' (λ f, f ≫ g) $ λ f f', by simp variables {P Q R : C} (f f' : P ⟶ Q) (g g' : Q ⟶ R) /-- Composition as a bilinear group homomorphism -/ def comp_hom : (P ⟶ Q) →+ (Q ⟶ R) →+ (P ⟶ R) := add_monoid_hom.mk' (λ f, left_comp _ f) $ λ f₁ f₂, add_monoid_hom.ext $ λ g, (right_comp _ g).map_add f₁ f₂ @[simp, reassoc] lemma sub_comp : (f - f') ≫ g = f ≫ g - f' ≫ g := map_sub (right_comp P g) f f' -- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. @[reassoc, simp] lemma comp_sub : f ≫ (g - g') = f ≫ g - f ≫ g' := map_sub (left_comp R f) g g' @[simp, reassoc] lemma neg_comp : (-f) ≫ g = -(f ≫ g) := map_neg (right_comp P g) f /- The redundant simp lemma linter says that simp can prove the reassoc version of this lemma. -/ @[reassoc, simp] lemma comp_neg : f ≫ (-g) = -(f ≫ g) := map_neg (left_comp R f) g @[reassoc] lemma neg_comp_neg : (-f) ≫ (-g) = f ≫ g := by simp lemma nsmul_comp (n : ℕ) : (n • f) ≫ g = n • (f ≫ g) := map_nsmul (right_comp P g) n f lemma comp_nsmul (n : ℕ) : f ≫ (n • g) = n • (f ≫ g) := map_nsmul (left_comp R f) n g lemma zsmul_comp (n : ℤ) : (n • f) ≫ g = n • (f ≫ g) := map_zsmul (right_comp P g) n f lemma comp_zsmul (n : ℤ) : f ≫ (n • g) = n • (f ≫ g) := map_zsmul (left_comp R f) n g @[reassoc] lemma comp_sum {P Q R : C} {J : Type*} (s : finset J) (f : P ⟶ Q) (g : J → (Q ⟶ R)) : f ≫ ∑ j in s, g j = ∑ j in s, f ≫ g j := map_sum (left_comp R f) _ _ @[reassoc] lemma sum_comp {P Q R : C} {J : Type*} (s : finset J) (f : J → (P ⟶ Q)) (g : Q ⟶ R) : (∑ j in s, f j) ≫ g = ∑ j in s, f j ≫ g := map_sum (right_comp P g) _ _ instance {P Q : C} {f : P ⟶ Q} [epi f] : epi (-f) := ⟨λ R g g' H, by rwa [neg_comp, neg_comp, ←comp_neg, ←comp_neg, cancel_epi, neg_inj] at H⟩ instance {P Q : C} {f : P ⟶ Q} [mono f] : mono (-f) := ⟨λ R g g' H, by rwa [comp_neg, comp_neg, ←neg_comp, ←neg_comp, cancel_mono, neg_inj] at H⟩ @[priority 100] instance preadditive_has_zero_morphisms : has_zero_morphisms C := { has_zero := infer_instance, comp_zero' := λ P Q f R, show left_comp R f 0 = 0, from map_zero _, zero_comp' := λ P Q R f, show right_comp P f 0 = 0, from map_zero _ } instance module_End_right {X Y : C} : module (End Y) (X ⟶ Y) := { smul_add := λ r f g, add_comp _ _ _ _ _ _, smul_zero := λ r, zero_comp, add_smul := λ r s f, comp_add _ _ _ _ _ _, zero_smul := λ r, comp_zero } lemma mono_of_cancel_zero {Q R : C} (f : Q ⟶ R) (h : ∀ {P : C} (g : P ⟶ Q), g ≫ f = 0 → g = 0) : mono f := ⟨λ P g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (right_comp P f) g g').trans $ sub_eq_zero.2 hg⟩ lemma mono_iff_cancel_zero {Q R : C} (f : Q ⟶ R) : mono f ↔ ∀ (P : C) (g : P ⟶ Q), g ≫ f = 0 → g = 0 := ⟨λ m P g, by exactI zero_of_comp_mono _, mono_of_cancel_zero f⟩ lemma mono_of_kernel_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)] (w : kernel.ι f = 0) : mono f := mono_of_cancel_zero f (λ P g h, by rw [←kernel.lift_ι f g h, w, limits.comp_zero]) lemma epi_of_cancel_zero {P Q : C} (f : P ⟶ Q) (h : ∀ {R : C} (g : Q ⟶ R), f ≫ g = 0 → g = 0) : epi f := ⟨λ R g g' hg, sub_eq_zero.1 $ h _ $ (map_sub (left_comp R f) g g').trans $ sub_eq_zero.2 hg⟩ lemma epi_iff_cancel_zero {P Q : C} (f : P ⟶ Q) : epi f ↔ ∀ (R : C) (g : Q ⟶ R), f ≫ g = 0 → g = 0 := ⟨λ e R g, by exactI zero_of_epi_comp _, epi_of_cancel_zero f⟩ lemma epi_of_cokernel_zero {X Y : C} {f : X ⟶ Y} [has_colimit (parallel_pair f 0 )] (w : cokernel.π f = 0) : epi f := epi_of_cancel_zero f (λ P g h, by rw [←cokernel.π_desc f g h, w, limits.zero_comp]) namespace is_iso @[simp] lemma comp_left_eq_zero [is_iso f] : f ≫ g = 0 ↔ g = 0 := by rw [← is_iso.eq_inv_comp, limits.comp_zero] @[simp] lemma comp_right_eq_zero [is_iso g] : f ≫ g = 0 ↔ f = 0 := by rw [← is_iso.eq_comp_inv, limits.zero_comp] end is_iso open_locale zero_object variables [has_zero_object C] lemma mono_of_kernel_iso_zero {X Y : C} {f : X ⟶ Y} [has_limit (parallel_pair f 0)] (w : kernel f ≅ 0) : mono f := mono_of_kernel_zero (zero_of_source_iso_zero _ w) lemma epi_of_cokernel_iso_zero {X Y : C} {f : X ⟶ Y} [has_colimit (parallel_pair f 0)] (w : cokernel f ≅ 0) : epi f := epi_of_cokernel_zero (zero_of_target_iso_zero _ w) end preadditive section equalizers variables {C : Type u} [category.{v} C] [preadditive C] section variables {X Y : C} {f : X ⟶ Y} {g : X ⟶ Y} /-- Map a kernel cone on the difference of two morphisms to the equalizer fork. -/ @[simps X] def fork_of_kernel_fork (c : kernel_fork (f - g)) : fork f g := fork.of_ι c.ι $ by rw [← sub_eq_zero, ← comp_sub, c.condition] @[simp] lemma fork_of_kernel_fork_ι (c : kernel_fork (f - g)) : (fork_of_kernel_fork c).ι = c.ι := rfl /-- Map any equalizer fork to a cone on the difference of the two morphisms. -/ def kernel_fork_of_fork (c : fork f g) : kernel_fork (f - g) := fork.of_ι c.ι $ by rw [comp_sub, comp_zero, sub_eq_zero, c.condition] @[simp] lemma kernel_fork_of_fork_ι (c : fork f g) : (kernel_fork_of_fork c).ι = c.ι := rfl @[simp] lemma kernel_fork_of_fork_of_ι {P : C} (ι : P ⟶ X) (w : ι ≫ f = ι ≫ g) : (kernel_fork_of_fork (fork.of_ι ι w)) = kernel_fork.of_ι ι (by simp [w]) := rfl /-- A kernel of `f - g` is an equalizer of `f` and `g`. -/ def is_limit_fork_of_kernel_fork {c : kernel_fork (f - g)} (i : is_limit c) : is_limit (fork_of_kernel_fork c) := fork.is_limit.mk' _ $ λ s, ⟨i.lift (kernel_fork_of_fork s), i.fac _ _, λ m h, by apply fork.is_limit.hom_ext i; tidy⟩ @[simp] lemma is_limit_fork_of_kernel_fork_lift {c : kernel_fork (f - g)} (i : is_limit c) (s : fork f g) : (is_limit_fork_of_kernel_fork i).lift s = i.lift (kernel_fork_of_fork s) := rfl /-- An equalizer of `f` and `g` is a kernel of `f - g`. -/ def is_limit_kernel_fork_of_fork {c : fork f g} (i : is_limit c) : is_limit (kernel_fork_of_fork c) := fork.is_limit.mk' _ $ λ s, ⟨i.lift (fork_of_kernel_fork s), i.fac _ _, λ m h, by apply fork.is_limit.hom_ext i; tidy⟩ variables (f g) /-- A preadditive category has an equalizer for `f` and `g` if it has a kernel for `f - g`. -/ lemma has_equalizer_of_has_kernel [has_kernel (f - g)] : has_equalizer f g := has_limit.mk { cone := fork_of_kernel_fork _, is_limit := is_limit_fork_of_kernel_fork (equalizer_is_equalizer (f - g) 0) } /-- A preadditive category has a kernel for `f - g` if it has an equalizer for `f` and `g`. -/ lemma has_kernel_of_has_equalizer [has_equalizer f g] : has_kernel (f - g) := has_limit.mk { cone := kernel_fork_of_fork (equalizer.fork f g), is_limit := is_limit_kernel_fork_of_fork (limit.is_limit (parallel_pair f g)) } variables {f g} /-- Map a cokernel cocone on the difference of two morphisms to the coequalizer cofork. -/ @[simps X] def cofork_of_cokernel_cofork (c : cokernel_cofork (f - g)) : cofork f g := cofork.of_π c.π $ by rw [← sub_eq_zero, ← sub_comp, c.condition] @[simp] lemma cofork_of_cokernel_cofork_π (c : cokernel_cofork (f - g)) : (cofork_of_cokernel_cofork c).π = c.π := rfl /-- Map any coequalizer cofork to a cocone on the difference of the two morphisms. -/ def cokernel_cofork_of_cofork (c : cofork f g) : cokernel_cofork (f - g) := cofork.of_π c.π $ by rw [sub_comp, zero_comp, sub_eq_zero, c.condition] @[simp] lemma cokernel_cofork_of_cofork_π (c : cofork f g) : (cokernel_cofork_of_cofork c).π = c.π := rfl @[simp] lemma cokernel_cofork_of_cofork_of_π {P : C} (π : Y ⟶ P) (w : f ≫ π = g ≫ π) : (cokernel_cofork_of_cofork (cofork.of_π π w)) = cokernel_cofork.of_π π (by simp [w]) := rfl /-- A cokernel of `f - g` is a coequalizer of `f` and `g`. -/ def is_colimit_cofork_of_cokernel_cofork {c : cokernel_cofork (f - g)} (i : is_colimit c) : is_colimit (cofork_of_cokernel_cofork c) := cofork.is_colimit.mk' _ $ λ s, ⟨i.desc (cokernel_cofork_of_cofork s), i.fac _ _, λ m h, by apply cofork.is_colimit.hom_ext i; tidy⟩ @[simp] lemma is_colimit_cofork_of_cokernel_cofork_desc {c : cokernel_cofork (f - g)} (i : is_colimit c) (s : cofork f g) : (is_colimit_cofork_of_cokernel_cofork i).desc s = i.desc (cokernel_cofork_of_cofork s) := rfl /-- A coequalizer of `f` and `g` is a cokernel of `f - g`. -/ def is_colimit_cokernel_cofork_of_cofork {c : cofork f g} (i : is_colimit c) : is_colimit (cokernel_cofork_of_cofork c) := cofork.is_colimit.mk' _ $ λ s, ⟨i.desc (cofork_of_cokernel_cofork s), i.fac _ _, λ m h, by apply cofork.is_colimit.hom_ext i; tidy⟩ variables (f g) /-- A preadditive category has a coequalizer for `f` and `g` if it has a cokernel for `f - g`. -/ lemma has_coequalizer_of_has_cokernel [has_cokernel (f - g)] : has_coequalizer f g := has_colimit.mk { cocone := cofork_of_cokernel_cofork _, is_colimit := is_colimit_cofork_of_cokernel_cofork (coequalizer_is_coequalizer (f - g) 0) } /-- A preadditive category has a cokernel for `f - g` if it has a coequalizer for `f` and `g`. -/ lemma has_cokernel_of_has_coequalizer [has_coequalizer f g] : has_cokernel (f - g) := has_colimit.mk { cocone := cokernel_cofork_of_cofork (coequalizer.cofork f g), is_colimit := is_colimit_cokernel_cofork_of_cofork (colimit.is_colimit (parallel_pair f g)) } end /-- If a preadditive category has all kernels, then it also has all equalizers. -/ lemma has_equalizers_of_has_kernels [has_kernels C] : has_equalizers C := @has_equalizers_of_has_limit_parallel_pair _ _ (λ _ _ f g, has_equalizer_of_has_kernel f g) /-- If a preadditive category has all cokernels, then it also has all coequalizers. -/ lemma has_coequalizers_of_has_cokernels [has_cokernels C] : has_coequalizers C := @has_coequalizers_of_has_colimit_parallel_pair _ _ (λ _ _ f g, has_coequalizer_of_has_cokernel f g) end equalizers end preadditive end category_theory
ce36f49acecc1ce75f5c6bc0da965b04ed6b4d18
c062f1c97fdef9ac746f08754e7d766fd6789aa9
/algebra/order.lean
a2968e904dfe67d1c53122e9fcc49138dbc5e423
[]
no_license
emberian/library_dev
00c7a985b21bdebe912f4127a363f2874e1e7555
f3abd7db0238edc18a397540e361a1da2f51503c
refs/heads/master
1,624,153,474,804
1,490,147,180,000
1,490,147,180,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,617
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ open eq function /- TODO: automatic construction of dual definitions / theorems -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section monotone variables [weak_order α] [weak_order β] [weak_order γ] def monotone (f : α → β) := ∀{{a b}}, a ≤ b → f a ≤ f b lemma monotone_id : @monotone α α _ _ id := take x y h, h lemma monotone_const {b : β} : monotone (λ(a:α), b) := take x y h, le_refl b lemma monotone_comp {f : α → β} {g : β → γ} (m_f : monotone f) (m_g : monotone g) : monotone (g ∘ f) := take a b h, m_g (m_f h) end monotone section variable [decidable_linear_order α] variables {a b c d : α} open decidable theorem le_max_left_iff_true (a b : α) : a ≤ max a b ↔ true := iff_true_intro (le_max_left a b) theorem le_max_right_iff_true (a b : α) : b ≤ max a b ↔ true := iff_true_intro (le_max_right a b) theorem min_right_comm (a b c : α) : min (min a b) c = min (min a c) b := right_comm min min_comm min_assoc a b c theorem max.left_comm (a b c : α) : max a (max b c) = max b (max a c) := left_comm max max_comm max_assoc a b c theorem max.right_comm (a b c : α) : max (max a b) c = max (max a c) b := right_comm max max_comm max_assoc a b c end /- order instances -/ instance weak_order_fun [weak_order β] : weak_order (α → β) := { le := λx y, ∀b, x b ≤ y b, le_refl := λf b, le_refl (f b), le_trans := λf g h h1 h2 b, le_trans (h1 b) (h2 b), le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)) } definition weak_order_dual (wo : weak_order α) : weak_order α := { le := λx y, y ≤ x, le_refl := le_refl, le_trans := take a b c h₁ h₂, le_trans h₂ h₁, le_antisymm := take a b h₁ h₂, le_antisymm h₂ h₁ } lemma le_dual_eq_le {α : Type} (wo : weak_order α) (a b : α) : @le _ (@weak_order.to_has_le _ (weak_order_dual wo)) a b = @le _ (@weak_order.to_has_le _ wo) b a := rfl lemma comp_le_comp_left_of_monotone [weak_order α] [weak_order β] [weak_order γ] {f : β → α} {g h : γ → β} (m_f : monotone f) (le : g ≤ h) : f ∘ g ≤ f ∘ h := take x, m_f (le x) section monotone variables [weak_order α] [weak_order γ] lemma monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := take a a' h b, m b h lemma monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := take a a' h, m h b end monotone
a15e7eca29dc4882fde4d8e029de5b27f60bfe92
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/cases.hlean
b60fa15db1c7c9462e1568344562df2e3b84e0c7
[ "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
479
hlean
open nat inductive vec (A : Type) : nat → Type := | nil {} : vec A zero | cons : Π {n}, A → vec A n → vec A (succ n) namespace vec variables {A B C : Type} variables {n m : nat} notation a :: b := cons a b protected definition destruct (v : vec A (succ n)) {P : Π {n : nat}, vec A (succ n) → Type} (H : Π {n : nat} (h : A) (t : vec A n), P (h :: t)) : P v := begin cases v with [n', h', t'], apply (H h' t') end end vec
070ca7e05f639a487ee5c40ab60200f9423a2ffd
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/algebra/uniform_group.lean
0c3b3ee48df90944977c44b9589c45d2d4fdf0b8
[ "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
19,570
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.complete_separated import topology.algebra.group tactic.abel noncomputable theory open_locale classical uniformity topological_space 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 α := ⟨h₁.comp (uniform_continuous_fst.prod_mk (h₂.comp uniform_continuous_snd))⟩ 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) := uniform_continuous_sub.comp (hf.prod_mk hg) 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_const.sub hf, by simp * at * lemma uniform_continuous_neg : uniform_continuous (λx:α, - x) := uniform_continuous_id.neg 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 hf.sub hg.neg, by simp [*, sub_eq_add_neg] at * lemma uniform_continuous_add : uniform_continuous (λp:α×α, p.1 + p.2) := uniform_continuous_fst.add uniform_continuous_snd @[priority 10] 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_fst.comp uniform_continuous_fst).sub (uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk ((uniform_continuous_snd.comp uniform_continuous_fst).sub (uniform_continuous_snd.comp uniform_continuous_snd))⟩ lemma uniformity_translate (a : α) : (𝓤 α).map (λx:α×α, (x.1 + a, x.2 + a)) = 𝓤 α := le_antisymm (uniform_continuous_id.add 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_id.add uniform_continuous_const)) lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) := { comap_uniformity := begin 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, inj := assume x y, eq_of_add_eq_add_right } section variables (α) lemma uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λx:α×α, x.2 - x.1) (𝓝 (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_invariant 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_invariant 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_nonempty, sub_eq_add_neg] end lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : tendsto f (𝓝 0) (𝓝 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 h tendsto_comap 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 (𝓝 0) (𝓝 (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) (𝓝 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) (𝓝 0)) (𝓝 (-0)), { simpa [(∘), tendsto_comap_iff] }, exact tendsto.comp (tendsto.neg tendsto_id) tendsto_comap 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) (𝓝 (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 [sub_eq_add_neg, add_comm, add_left_comm] 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) (𝓝 (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) (𝓝 (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)) ((𝓝 0).prod (𝓝 0))) (𝓝 (0 - 0)) := (tendsto_fst.sub tendsto_snd).comp tendsto_comap, 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 [(∘), sub_eq_add_neg, add_comm, add_left_comm] using this 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] lemma 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_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, simp [sub_eq_add_neg], 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 a uniform space variables [topological_space α] [add_comm_group α] variables [topological_space β] [add_comm_group β] variables {G : Type*} [uniform_space G] [add_comm_group G] variables {ψ : α × β → G} (hψ : continuous ψ) [ψbilin : is_Z_bilin ψ] include hψ ψbilin lemma is_Z_bilin.tendsto_zero_left (x₁ : α) : tendsto ψ (𝓝 (x₁, 0)) (𝓝 0) := begin have := hψ.tendsto (x₁, 0), rwa [is_Z_bilin.zero_right ψ] at this end lemma is_Z_bilin.tendsto_zero_right (y₁ : β) : tendsto ψ (𝓝 (0, y₁)) (𝓝 0) := begin have := hψ.tendsto (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 β] variables {e : β → α} [is_add_group_hom e] (de : dense_inducing e) include de lemma tendsto_sub_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 - t.1) (comap (λp:β×β, (e p.1, e p.2)) $ 𝓝 (x₀, x₀)) (𝓝 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) (𝓝 (x₀, x₀)) (𝓝 (e 0)), { have := (continuous_sub.comp continuous_swap).tendsto (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_inducing 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_inducing e) variables {f : δ → γ} [is_add_group_hom f] (df : dense_inducing f) variables {φ : β × δ → G} (hφ : continuous φ) [bilin : is_Z_bilin φ] include de df hφ bilin variables {W' : set G} (W'_nhd : W' ∈ 𝓝 (0 : G)) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ comap e (𝓝 x₀), ∀ x x' ∈ U₂, φ (x' - x, y₁) ∈ W' := begin let Nx := 𝓝 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)) (𝓝 (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ 𝓝 (x₀, x₀)) (𝓝 y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim := tendsto.comp (is_Z_bilin.tendsto_zero_right hφ y₁) lim1, rw tendsto_prod_self_iff at lim, exact lim W' W'_nhd, end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ comap e (𝓝 x₀), ∃ V ∈ comap f (𝓝 y₀), ∀ x x' ∈ U, ∀ y y' ∈ V, φ (x', y') - φ (x, y) ∈ W' := begin let Nx := 𝓝 x₀, let Ny := 𝓝 y₀, let dp := dense_inducing.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 φ (𝓝 (0, 0)) (𝓝 0), { have := hφ.tendsto (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 $ 𝓝 (x₀, x₀)) (comap ff $ 𝓝 (y₀, y₀))) (𝓝 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) (filter.prod (comap ee (𝓝 (x₀, x₀))) (comap ff (𝓝 (y₀, y₀)))) (filter.prod (𝓝 0) (𝓝 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_φ lim_sub_sub }, rcases exists_nhds_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ comap e (𝓝 x₀), ∃ V₁ ∈ comap f (𝓝 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⟩, obtain ⟨x₁, x₁_in⟩ : U₁.nonempty := (forall_sets_nonempty_iff_ne_bot.2 de.comap_nhds_ne_bot U₁ U₁_nhd), obtain ⟨y₁, y₁_in⟩ : V₁.nonempty := (forall_sets_nonempty_iff_ne_bot.2 df.comap_nhds_ne_bot V₁ V₁_nhd), rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de (hφ.comp continuous_swap) 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 [sub_eq_add_neg], abel }, 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 open dense_inducing /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense images 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 (de.prod df) φ) := begin refine continuous_extend_of_cauchy _ _, rintro ⟨x₀, y₀⟩, split, { apply map_ne_bot, apply comap_ne_bot, intros U h, rcases mem_closure_iff_nhds.1 ((de.prod df).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 (𝓝 (x₀, y₀)) (𝓝 (x₀, y₀)))) ≤ 𝓝 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' ∈ 𝓝 x₀ at U'_nhd, change V' ∈ 𝓝 y₀ at V'_nhd, have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_inducing
5cd3050eb13b397be6fa5ed77755ec57c2d668fc
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/tools/super/splitting.lean
9caa548c5e8b85b7632e8439ef90bf55747e0b05
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,701
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .prover_state open monad expr list tactic namespace super private meta def find_components : list expr → list (list (expr × ℕ)) → list (list (expr × ℕ)) | (e::es) comps := let (contain_e, do_not_contain_e) := partition (λc : list (expr × ℕ), c^.exists_ $ λf, (abstract_local f.1 e^.local_uniq_name)^.has_var) comps in find_components es $ list.join contain_e :: do_not_contain_e | _ comps := comps meta def get_components (hs : list expr) : list (list expr) := (find_components hs (hs^.zip_with_index^.for $ λh, [h]))^.for $ λc, (sort_on (λh : expr × ℕ, h.2) c)^.for $ λh, h.1 meta def extract_assertions : clause → prover (clause × list expr) | c := if c^.num_lits = 0 then return (c, []) else if c^.num_quants ≠ 0 then do qf ← c^.open_constn c^.num_quants, qf_wo_as ← extract_assertions qf.1, return (qf_wo_as.1^.close_constn qf.2, qf_wo_as.2) else do hd ← return $ c^.get_lit 0, hyp_opt ← get_sat_hyp_core hd^.formula hd^.is_neg, match hyp_opt with | some h := do wo_as ← extract_assertions (c^.inst h), return (wo_as.1, h :: wo_as.2) | _ := do op ← c^.open_const, op_wo_as ← extract_assertions op.1, return (op_wo_as.1^.close_const op.2, op_wo_as.2) end meta def mk_splitting_clause' (empty_clause : clause) : list (list expr) → tactic (list expr × expr) | [] := return ([], empty_clause^.proof) | ([p] :: comps) := do p' ← mk_splitting_clause' comps, return (p::p'.1, p'.2) | (comp :: comps) := do (hs, p') ← mk_splitting_clause' comps, hnc ← mk_local_def `hnc (imp (pis comp empty_clause^.local_false) empty_clause^.local_false), p'' ← return $ app hnc (lambdas comp p'), return (hnc::hs, p'') meta def mk_splitting_clause (empty_clause : clause) (comps : list (list expr)) : tactic clause := do (hs, p) ← mk_splitting_clause' empty_clause comps, return $ { empty_clause with proof := p }^.close_constn hs @[super.inf] meta def splitting_inf : inf_decl := inf_decl.mk 30 $ take given, do lf ← flip monad.lift state_t.read $ λst, st^.local_false, op ← given^.c^.open_constn given^.c^.num_binders, if list.bor (given^.c^.get_lits^.for $ λl, (is_local_not lf l^.formula)^.is_some) then return () else let comps := get_components op.2 in if comps^.length < 2 then return () else do splitting_clause ← mk_splitting_clause op.1 comps, ass ← collect_ass_hyps splitting_clause, add_sat_clause (splitting_clause^.close_constn ass) given^.sc^.sched_default, remove_redundant given^.id [] end super
2ccc50ea2d7fef4011bba0a6aa001355e6de675b
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/topology/instances/real.lean
2ba9cc557b0ad1a21beecafb87149ee112e0640e
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,654
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring import topology.algebra.continuous_functions import ring_theory.subring import group_theory.archimedean /-! # Topological properties of ℝ -/ noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ }, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, abs (y - x) < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets ((is_open_lt' (abs r / 2)).preimage real.continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (((is_open_gt' (abs a₁ + 1)).preimage real.continuous_abs).prod ((is_open_gt' (abs a₂ + 1)).preimage real.continuous_abs )) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, (set.finite_lt_nat _).image _, _⟩, rintro x ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, use i, split, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : is_compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) lemma compact_pi_Icc {ι : Type*} {a b : ι → ℝ} : is_compact (Icc a b) := pi_univ_Icc a b ▸ compact_univ_pi $ λ i, compact_Icc instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (compact_Icc.image_of_continuous_on h) end instance reals_semimodule : topological_semimodule ℝ ℝ := ⟨continuous_mul⟩ instance real_maps_algebra {α : Type*} [topological_space α] : algebra ℝ C(α, ℝ) := continuous_map_algebra section subgroups /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, abs (x - g) < ε, by simpa only [real.mem_closure_iff, abs_sub], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'), refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
6a99f70b05d3840997d96874ede3e0dfe11c372b
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/set/function.lean
a2768fe1248149f01a4cf73d05e41d750226a335
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
45,874
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov -/ import data.set.prod import logic.function.conjugate /-! # Functions over sets ## Main definitions ### Predicate * `set.eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`; * `set.maps_to f s t` : `f` sends every point of `s` to a point of `t`; * `set.inj_on f s` : restriction of `f` to `s` is injective; * `set.surj_on f s t` : every point in `s` has a preimage in `s`; * `set.bij_on f s t` : `f` is a bijection between `s` and `t`; * `set.left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`; * `set.right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`; * `set.inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e. we have `set.left_inv_on f' f s` and `set.right_inv_on f' f t`. ### Functions * `set.restrict f s` : restrict the domain of `f` to the set `s`; * `set.cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`; * `set.maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s` and the codomain to `t`. -/ universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open function namespace set /-! ### Restrict -/ /-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version takes an argument `↥s` instead of `subtype s`. -/ def restrict (f : α → β) (s : set α) : s → β := λ x, f x lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl @[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : restrict f s x = f x := rfl @[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (restrict f s) = f '' s := (range_comp _ _).trans $ congr_arg (('') f) subtype.range_coe lemma image_restrict (f : α → β) (s t : set α) : s.restrict f '' (coe ⁻¹' t) = f '' (t ∩ s) := by rw [restrict, image_comp, image_preimage_eq_inter_range, subtype.range_coe] @[simp] lemma restrict_dite {s : set α} [∀ x, decidable (x ∈ s)] (f : Π a ∈ s, β) (g : Π a ∉ s, β) : restrict (λ a, if h : a ∈ s then f a h else g a h) s = λ a, f a a.2 := funext $ λ a, dif_pos a.2 @[simp] lemma restrict_dite_compl {s : set α} [∀ x, decidable (x ∈ s)] (f : Π a ∈ s, β) (g : Π a ∉ s, β) : restrict (λ a, if h : a ∈ s then f a h else g a h) sᶜ = λ a, g a a.2 := funext $ λ a, dif_neg a.2 @[simp] lemma restrict_ite (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] : restrict (λ a, if a ∈ s then f a else g a) s = restrict f s := restrict_dite _ _ @[simp] lemma restrict_ite_compl (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] : restrict (λ a, if a ∈ s then f a else g a) sᶜ = restrict g sᶜ := restrict_dite_compl _ _ @[simp] lemma restrict_piecewise (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] : restrict (piecewise s f g) s = restrict f s := restrict_ite _ _ _ @[simp] lemma restrict_piecewise_compl (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] : restrict (piecewise s f g) sᶜ = restrict g sᶜ := restrict_ite_compl _ _ _ lemma restrict_extend_range (f : α → β) (g : α → γ) (g' : β → γ) : restrict (extend f g g') (range f) = λ x, g x.coe_prop.some := by convert restrict_dite _ _ @[simp] lemma restrict_extend_compl_range (f : α → β) (g : α → γ) (g' : β → γ) : restrict (extend f g g') (range f)ᶜ = g' ∘ coe := by convert restrict_dite_compl _ _ lemma range_extend_subset (f : α → β) (g : α → γ) (g' : β → γ) : range (extend f g g') ⊆ range g ∪ g' '' (range f)ᶜ := begin classical, rintro _ ⟨y, rfl⟩, rw extend_def, split_ifs, exacts [or.inl (mem_range_self _), or.inr (mem_image_of_mem _ h)] end lemma range_extend {f : α → β} (hf : injective f) (g : α → γ) (g' : β → γ) : range (extend f g g') = range g ∪ g' '' (range f)ᶜ := begin refine (range_extend_subset _ _ _).antisymm _, rintro z (⟨x, rfl⟩|⟨y, hy, rfl⟩), exacts [⟨f x, extend_apply hf _ _ _⟩, ⟨y, extend_apply' _ _ _ hy⟩] end /-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version has codomain `↥s` instead of `subtype s`. -/ def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s := λ x, ⟨f x, h x⟩ @[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) : (cod_restrict f s h x : β) = f x := rfl variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g g₁ g₂ : β → γ} {f' f₁' f₂' : β → α} {g' : γ → β} @[simp] lemma injective_cod_restrict (h : ∀ x, f x ∈ t) : injective (cod_restrict f t h) ↔ injective f := by simp only [injective, subtype.ext_iff, coe_cod_restrict_apply] alias injective_cod_restrict ↔ _ function.injective.cod_restrict /-! ### Equality on a set -/ /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ def eq_on (f₁ f₂ : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x @[simp] lemma eq_on_empty (f₁ f₂ : α → β) : eq_on f₁ f₂ ∅ := λ x, false.elim @[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s := λ x hx, (h hx).symm lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s := ⟨eq_on.symm, eq_on.symm⟩ @[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s := λ _ _, rfl @[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s := λ x hx, (h₁ hx).trans (h₂ hx) theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem eq_on.inter_preimage_eq (heq : eq_on f₁ f₂ s) (t : set β) : s ∩ f₁ ⁻¹' t = s ∩ f₂ ⁻¹' t := ext $ λ x, and.congr_right_iff.2 $ λ hx, by rw [mem_preimage, mem_preimage, heq hx] lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ := λ x hx, hf (hs hx) lemma eq_on.comp_left (h : s.eq_on f₁ f₂) : s.eq_on (g ∘ f₁) (g ∘ f₂) := λ a ha, congr_arg _ $ h ha lemma comp_eq_of_eq_on_range {ι : Sort*} {f : ι → α} {g₁ g₂ : α → β} (h : eq_on g₁ g₂ (range f)) : g₁ ∘ f = g₂ ∘ f := funext $ λ x, h $ mem_range_self _ /-! ### Congruence lemmas -/ section order variables [preorder α] [preorder β] lemma _root_.monotone_on.congr (h₁ : monotone_on f₁ s) (h : s.eq_on f₁ f₂) : monotone_on f₂ s := begin intros a ha b hb hab, rw [←h ha, ←h hb], exact h₁ ha hb hab, end lemma _root_.antitone_on.congr (h₁ : antitone_on f₁ s) (h : s.eq_on f₁ f₂) : antitone_on f₂ s := h₁.dual_right.congr h lemma _root_.strict_mono_on.congr (h₁ : strict_mono_on f₁ s) (h : s.eq_on f₁ f₂) : strict_mono_on f₂ s := begin intros a ha b hb hab, rw [←h ha, ←h hb], exact h₁ ha hb hab, end lemma _root_.strict_anti_on.congr (h₁ : strict_anti_on f₁ s) (h : s.eq_on f₁ f₂) : strict_anti_on f₂ s := h₁.dual_right.congr h lemma eq_on.congr_monotone_on (h : s.eq_on f₁ f₂) : monotone_on f₁ s ↔ monotone_on f₂ s := ⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩ lemma eq_on.congr_antitone_on (h : s.eq_on f₁ f₂) : antitone_on f₁ s ↔ antitone_on f₂ s := ⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩ lemma eq_on.congr_strict_mono_on (h : s.eq_on f₁ f₂) : strict_mono_on f₁ s ↔ strict_mono_on f₂ s := ⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩ lemma eq_on.congr_strict_anti_on (h : s.eq_on f₁ f₂) : strict_anti_on f₁ s ↔ strict_anti_on f₂ s := ⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩ end order /-! ### maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ @[reducible] def maps_to (f : α → β) (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ s → f x ∈ t /-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s` and the codomain to `t`. Same as `subtype.map`. -/ def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) : s → t := subtype.map f h @[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) : (h.restrict f s t x : β) = f x := rfl lemma maps_to_iff_exists_map_subtype : maps_to f s t ↔ ∃ g : s → t, ∀ x : s, f x = g x := ⟨λ h, ⟨h.restrict f s t, λ _, rfl⟩, λ ⟨g, hg⟩ x hx, by { erw [hg ⟨x, hx⟩], apply subtype.coe_prop }⟩ theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t := image_subset_iff.symm @[simp] theorem maps_to_singleton {x : α} : maps_to f {x} t ↔ f x ∈ t := singleton_subset_iff theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _ theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t := maps_to'.1 h theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) : maps_to f₂ s t := λ x hx, h hx ▸ h₁ hx lemma eq_on.comp_right (hg : t.eq_on g₁ g₂) (hf : s.maps_to f t) : s.eq_on (g₁ ∘ f) (g₂ ∘ f) := λ a ha, hg $ hf ha theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p := λ x h, h₁ (h₂ h) theorem maps_to_id (s : set α) : maps_to id s s := λ x, id theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) : ∀ n, maps_to (f^[n]) s s | 0 := λ _, id | (n+1) := (maps_to.iterate n).comp h theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) : (h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ := begin funext x, rw [subtype.ext_iff, maps_to.coe_restrict_apply], induction n with n ihn generalizing x, { refl }, { simp [nat.iterate, ihn] } end theorem maps_to.mono (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) (hf : maps_to f s₁ t₁) : maps_to f s₂ t₂ := λ x hx, ht (hf $ hs hx) theorem maps_to.union_union (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) : maps_to f (s₁ ∪ s₂) (t₁ ∪ t₂) := λ x hx, hx.elim (λ hx, or.inl $ h₁ hx) (λ hx, or.inr $ h₂ hx) theorem maps_to.union (h₁ : maps_to f s₁ t) (h₂ : maps_to f s₂ t) : maps_to f (s₁ ∪ s₂) t := union_self t ▸ h₁.union_union h₂ @[simp] theorem maps_to_union : maps_to f (s₁ ∪ s₂) t ↔ maps_to f s₁ t ∧ maps_to f s₂ t := ⟨λ h, ⟨h.mono (subset_union_left s₁ s₂) (subset.refl t), h.mono (subset_union_right s₁ s₂) (subset.refl t)⟩, λ h, h.1.union h.2⟩ theorem maps_to.inter (h₁ : maps_to f s t₁) (h₂ : maps_to f s t₂) : maps_to f s (t₁ ∩ t₂) := λ x hx, ⟨h₁ hx, h₂ hx⟩ theorem maps_to.inter_inter (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) : maps_to f (s₁ ∩ s₂) (t₁ ∩ t₂) := λ x hx, ⟨h₁ hx.1, h₂ hx.2⟩ @[simp] theorem maps_to_inter : maps_to f s (t₁ ∩ t₂) ↔ maps_to f s t₁ ∧ maps_to f s t₂ := ⟨λ h, ⟨h.mono (subset.refl s) (inter_subset_left t₁ t₂), h.mono (subset.refl s) (inter_subset_right t₁ t₂)⟩, λ h, h.1.inter h.2⟩ theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to' theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _ theorem maps_to_range (f : α → β) (s : set α) : maps_to f s (range f) := (maps_to_image f s).mono (subset.refl s) (image_subset_range _ _) @[simp] lemma maps_image_to (f : α → β) (g : γ → α) (s : set γ) (t : set β) : maps_to f (g '' s) t ↔ maps_to (f ∘ g) s t := ⟨λ h c hc, h ⟨c, hc, rfl⟩, λ h d ⟨c, hc⟩, hc.2 ▸ h hc.1⟩ @[simp] lemma maps_univ_to (f : α → β) (s : set β) : maps_to f univ s ↔ ∀ a, f a ∈ s := ⟨λ h a, h (mem_univ _), λ h x _, h x⟩ @[simp] lemma maps_range_to (f : α → β) (g : γ → α) (s : set β) : maps_to f (range g) s ↔ maps_to (f ∘ g) univ s := by rw [←image_univ, maps_image_to] theorem surjective_maps_to_image_restrict (f : α → β) (s : set α) : surjective ((maps_to_image f s).restrict f s (f '' s)) := λ ⟨y, x, hs, hxy⟩, ⟨⟨x, hs⟩, subtype.ext hxy⟩ theorem maps_to.mem_iff (h : maps_to f s t) (hc : maps_to f sᶜ tᶜ) {x} : f x ∈ t ↔ x ∈ s := ⟨λ ht, by_contra $ λ hs, hc hs ht, λ hx, h hx⟩ /-! ### Injectivity on a set -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ @[reducible] def inj_on (f : α → β) (s : set α) : Prop := ∀ ⦃x₁ : α⦄, x₁ ∈ s → ∀ ⦃x₂ : α⦄, x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂ theorem subsingleton.inj_on (hs : s.subsingleton) (f : α → β) : inj_on f s := λ x hx y hy h, hs hx hy @[simp] theorem inj_on_empty (f : α → β) : inj_on f ∅ := subsingleton_empty.inj_on f @[simp] theorem inj_on_singleton (f : α → β) (a : α) : inj_on f {a} := subsingleton_singleton.inj_on f theorem inj_on.eq_iff {x y} (h : inj_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x = f y ↔ x = y := ⟨h hx hy, λ h, h ▸ rfl⟩ theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) : inj_on f₂ s := λ x hx y hy, h hx ▸ h hy ▸ h₁ hx hy theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ := λ x hx y hy H, ht (h hx) (h hy) H theorem inj_on_union (h : disjoint s₁ s₂) : inj_on f (s₁ ∪ s₂) ↔ inj_on f s₁ ∧ inj_on f s₂ ∧ ∀ (x ∈ s₁) (y ∈ s₂), f x ≠ f y := begin refine ⟨λ H, ⟨H.mono $ subset_union_left _ _, H.mono $ subset_union_right _ _, _⟩, _⟩, { intros x hx y hy hxy, obtain rfl : x = y, from H (or.inl hx) (or.inr hy) hxy, exact h ⟨hx, hy⟩ }, { rintro ⟨h₁, h₂, h₁₂⟩, rintro x (hx|hx) y (hy|hy) hxy, exacts [h₁ hx hy hxy, (h₁₂ _ hx _ hy hxy).elim, (h₁₂ _ hy _ hx hxy.symm).elim, h₂ hx hy hxy] } end theorem inj_on_insert {f : α → β} {s : set α} {a : α} (has : a ∉ s) : set.inj_on f (insert a s) ↔ set.inj_on f s ∧ f a ∉ f '' s := have disjoint s {a}, from λ x ⟨hxs, (hxa : x = a)⟩, has (hxa ▸ hxs), by { rw [← union_singleton, inj_on_union this], simp } lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ := ⟨λ h x hx y hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩ lemma inj_on_of_injective (h : injective f) (s : set α) : inj_on f s := λ x hx y hy hxy, h hxy alias inj_on_of_injective ← function.injective.inj_on theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) : inj_on (g ∘ f) s := λ x hx y hy heq, hf hx hy $ hg (h hx) (h hy) heq lemma inj_on_iff_injective : inj_on f s ↔ injective (restrict f s) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a as b bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ alias inj_on_iff_injective ↔ set.inj_on.injective _ lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ 𝒫 (range f)) : inj_on (preimage f) B := λ s hs t ht hst, (preimage_eq_preimage' (hB hs) (hB ht)).1 hst lemma inj_on.mem_of_mem_image {x} (hf : inj_on f s) (hs : s₁ ⊆ s) (h : x ∈ s) (h₁ : f x ∈ f '' s₁) : x ∈ s₁ := let ⟨x', h', eq⟩ := h₁ in hf (hs h') h eq ▸ h' lemma inj_on.mem_image_iff {x} (hf : inj_on f s) (hs : s₁ ⊆ s) (hx : x ∈ s) : f x ∈ f '' s₁ ↔ x ∈ s₁ := ⟨hf.mem_of_mem_image hs hx, mem_image_of_mem f⟩ lemma inj_on.preimage_image_inter (hf : inj_on f s) (hs : s₁ ⊆ s) : f ⁻¹' (f '' s₁) ∩ s = s₁ := ext $ λ x, ⟨λ ⟨h₁, h₂⟩, hf.mem_of_mem_image hs h₂ h₁, λ h, ⟨mem_image_of_mem _ h, hs h⟩⟩ lemma eq_on.cancel_left (h : s.eq_on (g ∘ f₁) (g ∘ f₂)) (hg : t.inj_on g) (hf₁ : s.maps_to f₁ t) (hf₂ : s.maps_to f₂ t) : s.eq_on f₁ f₂ := λ a ha, hg (hf₁ ha) (hf₂ ha) (h ha) lemma inj_on.cancel_left (hg : t.inj_on g) (hf₁ : s.maps_to f₁ t) (hf₂ : s.maps_to f₂ t) : s.eq_on (g ∘ f₁) (g ∘ f₂) ↔ s.eq_on f₁ f₂ := ⟨λ h, h.cancel_left hg hf₁ hf₂, eq_on.comp_left⟩ /-! ### Surjectivity on a set -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ @[reducible] def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s theorem surj_on.subset_range (h : surj_on f s t) : t ⊆ range f := subset.trans h $ image_subset_range f s lemma surj_on_iff_exists_map_subtype : surj_on f s t ↔ ∃ (t' : set β) (g : s → t'), t ⊆ t' ∧ surjective g ∧ ∀ x : s, f x = g x := ⟨λ h, ⟨_, (maps_to_image f s).restrict f s _, h, surjective_maps_to_image_restrict _ _, λ _, rfl⟩, λ ⟨t', g, htt', hg, hfg⟩ y hy, let ⟨x, hx⟩ := hg ⟨y, htt' hy⟩ in ⟨x, x.2, by rw [hfg, hx, subtype.coe_mk]⟩⟩ theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _ theorem surj_on_image (f : α → β) (s : set α) : surj_on f s (f '' s) := subset.rfl theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty := (ht.mono h).of_image theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t := by rwa [surj_on, ← H.image_eq] theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t := ⟨λ H, H.congr h, λ H, H.congr h.symm⟩ theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ := subset.trans ht $ subset.trans hf $ image_subset _ hs theorem surj_on.union (h₁ : surj_on f s t₁) (h₂ : surj_on f s t₂) : surj_on f s (t₁ ∪ t₂) := λ x hx, hx.elim (λ hx, h₁ hx) (λ hx, h₂ hx) theorem surj_on.union_union (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) : surj_on f (s₁ ∪ s₂) (t₁ ∪ t₂) := (h₁.mono (subset_union_left _ _) (subset.refl _)).union (h₂.mono (subset_union_right _ _) (subset.refl _)) theorem surj_on.inter_inter (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : surj_on f (s₁ ∩ s₂) (t₁ ∩ t₂) := begin intros y hy, rcases h₁ hy.1 with ⟨x₁, hx₁, rfl⟩, rcases h₂ hy.2 with ⟨x₂, hx₂, heq⟩, have : x₁ = x₂, from h (or.inl hx₁) (or.inr hx₂) heq.symm, subst x₂, exact mem_image_of_mem f ⟨hx₁, hx₂⟩ end theorem surj_on.inter (h₁ : surj_on f s₁ t) (h₂ : surj_on f s₂ t) (h : inj_on f (s₁ ∪ s₂)) : surj_on f (s₁ ∩ s₂) t := inter_self t ▸ h₁.inter_inter h₂ h theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p := subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _ lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (restrict f s) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) : f '' s = t := eq_of_subset_of_subset h₂.image_subset h₁ lemma image_eq_iff_surj_on_maps_to : f '' s = t ↔ s.surj_on f t ∧ s.maps_to f t := begin refine ⟨_, λ h, h.1.image_eq_of_maps_to h.2⟩, rintro rfl, exact ⟨s.surj_on_image f, s.maps_to_image f⟩, end lemma surj_on.maps_to_compl (h : surj_on f s t) (h' : injective f) : maps_to f sᶜ tᶜ := λ x hs ht, let ⟨x', hx', heq⟩ := h ht in hs $ h' heq ▸ hx' lemma maps_to.surj_on_compl (h : maps_to f s t) (h' : surjective f) : surj_on f sᶜ tᶜ := h'.forall.2 $ λ x ht, mem_image_of_mem _ $ λ hs, ht (h hs) lemma eq_on.cancel_right (hf : s.eq_on (g₁ ∘ f) (g₂ ∘ f)) (hf' : s.surj_on f t) : t.eq_on g₁ g₂ := begin intros b hb, obtain ⟨a, ha, rfl⟩ := hf' hb, exact hf ha, end lemma surj_on.cancel_right (hf : s.surj_on f t) (hf' : s.maps_to f t) : s.eq_on (g₁ ∘ f) (g₂ ∘ f) ↔ t.eq_on g₁ g₂ := ⟨λ h, h.cancel_right hf, λ h, h.comp_right hf'⟩ lemma eq_on_comp_right_iff : s.eq_on (g₁ ∘ f) (g₂ ∘ f) ↔ (f '' s).eq_on g₁ g₂ := (s.surj_on_image f).cancel_right $ s.maps_to_image f /-! ### Bijectivity -/ /-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/ @[reducible] def bij_on (f : α → β) (s : set α) (t : set β) : Prop := maps_to f s t ∧ inj_on f s ∧ surj_on f s t lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) : bij_on f s t := ⟨h₁, h₂, h₃⟩ lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ := ⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩ lemma bij_on.inter (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : bij_on f (s₁ ∩ s₂) (t₁ ∩ t₂) := ⟨h₁.maps_to.inter_inter h₂.maps_to, h₁.inj_on.mono $ inter_subset_left _ _, h₁.surj_on.inter_inter h₂.surj_on h⟩ lemma bij_on.union (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : bij_on f (s₁ ∪ s₂) (t₁ ∪ t₂) := ⟨h₁.maps_to.union_union h₂.maps_to, h, h₁.surj_on.union_union h₂.surj_on⟩ theorem bij_on.subset_range (h : bij_on f s t) : t ⊆ range f := h.surj_on.subset_range lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) := bij_on.mk (maps_to_image f s) h (subset.refl _) theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) : bij_on f₂ s t := bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h) theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ lemma bij_on.image_eq (h : bij_on f s t) : f '' s = t := h.surj_on.image_eq_of_maps_to h.maps_to theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p := bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to) (hg.surj_on.comp hf.surj_on) theorem bij_on.bijective (h : bij_on f s t) : bijective (t.cod_restrict (s.restrict f) $ λ x, h.maps_to x.val_prop) := ⟨λ x y h', subtype.ext $ h.inj_on x.2 y.2 $ subtype.ext_iff.1 h', λ ⟨y, hy⟩, let ⟨x, hx, hxy⟩ := h.surj_on hy in ⟨⟨x, hx⟩, subtype.eq hxy⟩⟩ lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, inj.inj_on _, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) lemma bij_on.compl (hst : bij_on f s t) (hf : bijective f) : bij_on f sᶜ tᶜ := ⟨hst.surj_on.maps_to_compl hf.1, hf.1.inj_on _, hst.maps_to.surj_on_compl hf.2⟩ /-! ### left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ @[reducible] def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f' (f x) = x lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s) {t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s := λ x hx, heq (h₁' hx) ▸ h₁ hx theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) : left_inv_on f₁' f₂ s := λ x hx, heq hx ▸ h₁ hx theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s := λ x₁ h₁ x₂ h₂ heq, calc x₁ = f₁' (f x₁) : eq.symm $ h h₁ ... = f₁' (f x₂) : congr_arg f₁' heq ... = x₂ : h h₂ theorem left_inv_on.surj_on (h : left_inv_on f' f s) (hf : maps_to f s t) : surj_on f' t s := λ x hx, ⟨f x, hf hx, h hx⟩ theorem left_inv_on.maps_to (h : left_inv_on f' f s) (hf : surj_on f s t) : maps_to f' t s := λ y hy, let ⟨x, hs, hx⟩ := hf hy in by rwa [← hx, h hs] theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) : left_inv_on (f' ∘ g') (g ∘ f) s := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h)) ... = x : hf' h theorem left_inv_on.mono (hf : left_inv_on f' f s) (ht : s₁ ⊆ s) : left_inv_on f' f s₁ := λ x hx, hf (ht hx) theorem left_inv_on.image_inter' (hf : left_inv_on f' f s) : f '' (s₁ ∩ s) = f' ⁻¹' s₁ ∩ f '' s := begin apply subset.antisymm, { rintro _ ⟨x, ⟨h₁, h⟩, rfl⟩, exact ⟨by rwa [mem_preimage, hf h], mem_image_of_mem _ h⟩ }, { rintro _ ⟨h₁, ⟨x, h, rfl⟩⟩, exact mem_image_of_mem _ ⟨by rwa ← hf h, h⟩ } end theorem left_inv_on.image_inter (hf : left_inv_on f' f s) : f '' (s₁ ∩ s) = f' ⁻¹' (s₁ ∩ s) ∩ f '' s := begin rw hf.image_inter', refine subset.antisymm _ (inter_subset_inter_left _ (preimage_mono $ inter_subset_left _ _)), rintro _ ⟨h₁, x, hx, rfl⟩, exact ⟨⟨h₁, by rwa hf hx⟩, mem_image_of_mem _ hx⟩ end theorem left_inv_on.image_image (hf : left_inv_on f' f s) : f' '' (f '' s) = s := by rw [image_image, image_congr hf, image_id'] theorem left_inv_on.image_image' (hf : left_inv_on f' f s) (hs : s₁ ⊆ s) : f' '' (f '' s₁) = s₁ := (hf.mono hs).image_image /-! ### Right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop := left_inv_on f f' t lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy lemma left_inv_on.right_inv_on_image (h : left_inv_on f' f s) : right_inv_on f' f (f '' s) := λ y ⟨x, hx, eq⟩, eq ▸ congr_arg f $ h.eq hx theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) : right_inv_on f₂' f t := h₁.congr_right heq theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s) (heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t := left_inv_on.congr_left h₁ hg heq theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) : surj_on f s t := hf.surj_on hf' theorem right_inv_on.maps_to (h : right_inv_on f' f t) (hf : surj_on f' t s) : maps_to f s t := h.maps_to hf theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p) (g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p := hg.comp hf g'pt theorem right_inv_on.mono (hf : right_inv_on f' f t) (ht : t₁ ⊆ t) : right_inv_on f' f t₁ := hf.mono ht theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t) (h₁ : maps_to f s t) (h₂ : maps_to f' t s) : right_inv_on f f' s := λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h)) theorem eq_on_of_left_inv_on_of_right_inv_on (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t) (h : maps_to f₂' t s) : eq_on f₁' f₂' t := λ y hy, calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm ... = f₂' y : h₁ (h hy) theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) : left_inv_on f f' t := λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx] /-! ### Two-side inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ @[reducible] def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop := left_inv_on g f s ∧ right_inv_on g f t lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩ lemma inv_on.mono (h : inv_on f' f s t) (hs : s₁ ⊆ s) (ht : t₁ ⊆ t) : inv_on f' f s₁ t₁ := ⟨h.1.mono hs, h.2.mono ht⟩ /-- If functions `f'` and `f` are inverse on `s` and `t`, `f` maps `s` into `t`, and `f'` maps `t` into `s`, then `f` is a bijection between `s` and `t`. The `maps_to` arguments can be deduced from `surj_on` statements using `left_inv_on.maps_to` and `right_inv_on.maps_to`. -/ theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) : bij_on f s t := ⟨hf, h.left.inj_on, h.right.surj_on hf'⟩ end set /-! ### `inv_fun_on` is a left/right inverse -/ namespace function variables [nonempty α] {s : set α} {f : α → β} {a : α} {b : β} local attribute [instance, priority 10] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. For a computable version, see `function.injective.inv_of_mem_range`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice ‹nonempty α› theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice ‹nonempty α› := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] end function namespace set open function variables {s s₁ s₂ : set α} {t : set β} {f : α → β} theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) : left_inv_on (inv_fun_on f s) f s := λ a ha, have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h (inv_fun_on_mem this) ha (inv_fun_on_eq this) lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) : (inv_fun_on f s₂) '' (f '' s₁) = s₁ := h.left_inv_on_inv_fun_on.image_image' ht theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : right_inv_on (inv_fun_on f s) f t := λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) : inv_on (inv_fun_on f s) f s t := ⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩ theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t := begin refine ⟨_, h.right_inv_on_inv_fun_on⟩, rintros _ ⟨y, hy, rfl⟩, rw [h.right_inv_on_inv_fun_on hy] end theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) : maps_to (inv_fun_on f s) t s := λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) : bij_on f (inv_fun_on f s '' t) t := begin refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _), rintros _ ⟨y, hy, rfl⟩, rwa [h.right_inv_on_inv_fun_on hy] end theorem surj_on_iff_exists_bij_on_subset : surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t := begin split, { rcases eq_empty_or_nonempty t with rfl|ht, { exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ }, { assume h, haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩, exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }}, { rintros ⟨s', hs', hfs'⟩, exact hfs'.surj_on.mono hs' (subset.refl _) } end lemma preimage_inv_fun_of_mem [n : nonempty α] {f : α → β} (hf : injective f) {s : set α} (h : classical.choice n ∈ s) : inv_fun f ⁻¹' s = f '' s ∪ (range f)ᶜ := begin ext x, rcases em (x ∈ range f) with ⟨a, rfl⟩|hx, { simp [left_inverse_inv_fun hf _, hf.mem_set_image] }, { simp [mem_preimage, inv_fun_neg hx, h, hx] } end lemma preimage_inv_fun_of_not_mem [n : nonempty α] {f : α → β} (hf : injective f) {s : set α} (h : classical.choice n ∉ s) : inv_fun f ⁻¹' s = f '' s := begin ext x, rcases em (x ∈ range f) with ⟨a, rfl⟩|hx, { rw [mem_preimage, left_inverse_inv_fun hf, hf.mem_set_image] }, { have : x ∉ f '' s, from λ h', hx (image_subset_range _ _ h'), simp only [mem_preimage, inv_fun_neg hx, h, this] }, end end set /-! ### Monotone -/ namespace monotone variables [preorder α] [preorder β] {f : α → β} protected lemma restrict (h : monotone f) (s : set α) : monotone (s.restrict f) := λ x y hxy, h hxy protected lemma cod_restrict (h : monotone f) {s : set β} (hs : ∀ x, f x ∈ s) : monotone (s.cod_restrict f hs) := h protected lemma range_factorization (h : monotone f) : monotone (set.range_factorization f) := h end monotone /-! ### Piecewise defined function -/ namespace set variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i) @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] : piecewise set.univ f g = f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] variable [∀j, decidable (j ∈ s)] instance compl.decidable_mem (j : α) : decidable (j ∈ sᶜ) := not.decidable lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin simp [piecewise], ext i, by_cases h : i = j, { rw h, simp }, { by_cases h' : i ∈ s; simp [h, h'] } end @[simp, priority 990] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := if_pos hi @[simp, priority 990] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := if_neg hi lemma piecewise_singleton (x : α) [Π y, decidable (y ∈ ({x} : set α))] [decidable_eq α] (f g : α → β) : piecewise {x} f g = function.update g x (f x) := by { ext y, by_cases hy : y = x, { subst y, simp }, { simp [hy] } } lemma piecewise_eq_on (f g : α → β) : eq_on (s.piecewise f g) f s := λ _, piecewise_eq_of_mem _ _ _ lemma piecewise_eq_on_compl (f g : α → β) : eq_on (s.piecewise f g) g sᶜ := λ _, piecewise_eq_of_not_mem _ _ _ lemma piecewise_le {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g : Π i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g i) (h₂ : ∀ i ∉ s, f₂ i ≤ g i) : s.piecewise f₁ f₂ ≤ g := λ i, if h : i ∈ s then by simp * else by simp * lemma le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g : Π i, δ i} (h₁ : ∀ i ∈ s, g i ≤ f₁ i) (h₂ : ∀ i ∉ s, g i ≤ f₂ i) : g ≤ s.piecewise f₁ f₂ := @piecewise_le α (λ i, order_dual (δ i)) _ s _ _ _ _ h₁ h₂ lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g₁ g₂ : Π i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g₁ i) (h₂ : ∀ i ∉ s, f₂ i ≤ g₂ i) : s.piecewise f₁ f₂ ≤ s.piecewise g₁ g₂ := by apply piecewise_le; intros; simp * @[simp, priority 990] lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] @[simp] lemma piecewise_compl [∀ i, decidable (i ∈ sᶜ)] : sᶜ.piecewise f g = s.piecewise g f := funext $ λ x, if hx : x ∈ s then by simp [hx] else by simp [hx] @[simp] lemma piecewise_range_comp {ι : Sort*} (f : ι → α) [Π j, decidable (j ∈ range f)] (g₁ g₂ : α → β) : (range f).piecewise g₁ g₂ ∘ f = g₁ ∘ f := comp_eq_of_eq_on_range $ piecewise_eq_on _ _ _ theorem maps_to.piecewise_ite {s s₁ s₂ : set α} {t t₁ t₂ : set β} {f₁ f₂ : α → β} [∀ i, decidable (i ∈ s)] (h₁ : maps_to f₁ (s₁ ∩ s) (t₁ ∩ t)) (h₂ : maps_to f₂ (s₂ ∩ sᶜ) (t₂ ∩ tᶜ)) : maps_to (s.piecewise f₁ f₂) (s.ite s₁ s₂) (t.ite t₁ t₂) := begin refine (h₁.congr _).union_union (h₂.congr _), exacts [(piecewise_eq_on s f₁ f₂).symm.mono (inter_subset_right _ _), (piecewise_eq_on_compl s f₁ f₂).symm.mono (inter_subset_right _ _)] end theorem eq_on_piecewise {f f' g : α → β} {t} : eq_on (s.piecewise f f') g t ↔ eq_on f g (t ∩ s) ∧ eq_on f' g (t ∩ sᶜ) := begin simp only [eq_on, ← forall_and_distrib], refine forall_congr (λ a, _), by_cases a ∈ s; simp * end theorem eq_on.piecewise_ite' {f f' g : α → β} {t t'} (h : eq_on f g (t ∩ s)) (h' : eq_on f' g (t' ∩ sᶜ)) : eq_on (s.piecewise f f') g (s.ite t t') := by simp [eq_on_piecewise, *] theorem eq_on.piecewise_ite {f f' g : α → β} {t t'} (h : eq_on f g t) (h' : eq_on f' g t') : eq_on (s.piecewise f f') g (s.ite t t') := (h.mono (inter_subset_left _ _)).piecewise_ite' s (h'.mono (inter_subset_left _ _)) lemma piecewise_preimage (f g : α → β) (t) : s.piecewise f g ⁻¹' t = s.ite (f ⁻¹' t) (g ⁻¹' t) := ext $ λ x, by by_cases x ∈ s; simp [*, set.ite] lemma apply_piecewise {δ' : α → Sort*} (h : Π i, δ i → δ' i) {x : α} : h x (s.piecewise f g x) = s.piecewise (λ x, h x (f x)) (λ x, h x (g x)) x := by by_cases hx : x ∈ s; simp [hx] lemma apply_piecewise₂ {δ' δ'' : α → Sort*} (f' g' : Π i, δ' i) (h : Π i, δ i → δ' i → δ'' i) {x : α} : h x (s.piecewise f g x) (s.piecewise f' g' x) = s.piecewise (λ x, h x (f x) (f' x)) (λ x, h x (g x) (g' x)) x := by by_cases hx : x ∈ s; simp [hx] lemma piecewise_op {δ' : α → Sort*} (h : Π i, δ i → δ' i) : s.piecewise (λ x, h x (f x)) (λ x, h x (g x)) = λ x, h x (s.piecewise f g x) := funext $ λ x, (apply_piecewise _ _ _ _).symm lemma piecewise_op₂ {δ' δ'' : α → Sort*} (f' g' : Π i, δ' i) (h : Π i, δ i → δ' i → δ'' i) : s.piecewise (λ x, h x (f x) (f' x)) (λ x, h x (g x) (g' x)) = λ x, h x (s.piecewise f g x) (s.piecewise f' g' x) := funext $ λ x, (apply_piecewise₂ _ _ _ _ _ _).symm @[simp] lemma piecewise_same : s.piecewise f f = f := by { ext x, by_cases hx : x ∈ s; simp [hx] } lemma range_piecewise (f g : α → β) : range (s.piecewise f g) = f '' s ∪ g '' sᶜ := begin ext y, split, { rintro ⟨x, rfl⟩, by_cases h : x ∈ s;[left, right]; use x; simp [h] }, { rintro (⟨x, hx, rfl⟩|⟨x, hx, rfl⟩); use x; simp * at * } end lemma injective_piecewise_iff {f g : α → β} : injective (s.piecewise f g) ↔ inj_on f s ∧ inj_on g sᶜ ∧ (∀ (x ∈ s) (y ∉ s), f x ≠ g y) := begin rw [injective_iff_inj_on_univ, ← union_compl_self s, inj_on_union (@disjoint_compl_right _ s _), (piecewise_eq_on s f g).inj_on_iff, (piecewise_eq_on_compl s f g).inj_on_iff], refine and_congr iff.rfl (and_congr iff.rfl $ forall₄_congr $ λ x hx y hy, _), rw [piecewise_eq_of_mem s f g hx, piecewise_eq_of_not_mem s f g hy] end lemma piecewise_mem_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ pi t t') (hg : g ∈ pi t t') : s.piecewise f g ∈ pi t t' := by { intros i ht, by_cases hs : i ∈ s; simp [hf i ht, hg i ht, hs] } @[simp] lemma pi_piecewise {ι : Type*} {α : ι → Type*} (s s' : set ι) (t t' : Π i, set (α i)) [Π x, decidable (x ∈ s')] : pi s (s'.piecewise t t') = pi (s ∩ s') t ∩ pi (s \ s') t' := begin ext x, simp only [mem_pi, mem_inter_eq, ← forall_and_distrib], refine forall_congr (λ i, _), by_cases hi : i ∈ s'; simp * end lemma univ_pi_piecewise {ι : Type*} {α : ι → Type*} (s : set ι) (t : Π i, set (α i)) [Π x, decidable (x ∈ s)] : pi univ (s.piecewise t (λ _, univ)) = pi s t := by simp end set lemma strict_mono_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α} (H : strict_mono_on f s) : s.inj_on f := λ x hx y hy hxy, show ordering.eq.compares x y, from (H.compares hx hy).1 hxy lemma strict_anti_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α} (H : strict_anti_on f s) : s.inj_on f := @strict_mono_on.inj_on α (order_dual β) _ _ f s H lemma strict_mono_on.comp [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_mono_on g t) (hf : strict_mono_on f s) (hs : set.maps_to f s t) : strict_mono_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hx) (hs hy) $ hf hx hy hxy lemma strict_mono_on.comp_strict_anti_on [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_mono_on g t) (hf : strict_anti_on f s) (hs : set.maps_to f s t) : strict_anti_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hy) (hs hx) $ hf hx hy hxy lemma strict_anti_on.comp [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_anti_on g t) (hf : strict_anti_on f s) (hs : set.maps_to f s t) : strict_mono_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hy) (hs hx) $ hf hx hy hxy lemma strict_anti_on.comp_strict_mono_on [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_anti_on g t) (hf : strict_mono_on f s) (hs : set.maps_to f s t) : strict_anti_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hx) (hs hy) $ hf hx hy hxy lemma strict_mono.cod_restrict [preorder α] [preorder β] {f : α → β} (hf : strict_mono f) {s : set β} (hs : ∀ x, f x ∈ s) : strict_mono (set.cod_restrict f s hs) := hf namespace function open set variables {fa : α → α} {fb : β → β} {f : α → β} {g : β → γ} {s t : set α} lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) := (hg.inj_on univ).comp hf (maps_to_univ _ _) lemma surjective.surj_on (hf : surjective f) (s : set β) : surj_on f univ s := (surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _) lemma left_inverse.left_inv_on {g : β → α} (h : left_inverse f g) (s : set β) : left_inv_on f g s := λ x hx, h x lemma right_inverse.right_inv_on {g : β → α} (h : right_inverse f g) (s : set α) : right_inv_on f g s := λ x hx, h x lemma left_inverse.right_inv_on_range {g : β → α} (h : left_inverse f g) : right_inv_on f g (range g) := forall_range_iff.2 $ λ i, congr_arg g (h i) namespace semiconj lemma maps_to_image (h : semiconj f fa fb) (ha : maps_to fa s t) : maps_to fb (f '' s) (f '' t) := λ y ⟨x, hx, hy⟩, hy ▸ ⟨fa x, ha hx, h x⟩ lemma maps_to_range (h : semiconj f fa fb) : maps_to fb (range f) (range f) := λ y ⟨x, hy⟩, hy ▸ ⟨fa x, h x⟩ lemma surj_on_image (h : semiconj f fa fb) (ha : surj_on fa s t) : surj_on fb (f '' s) (f '' t) := begin rintros y ⟨x, hxt, rfl⟩, rcases ha hxt with ⟨x, hxs, rfl⟩, rw [h x], exact mem_image_of_mem _ (mem_image_of_mem _ hxs) end lemma surj_on_range (h : semiconj f fa fb) (ha : surjective fa) : surj_on fb (range f) (range f) := by { rw ← image_univ, exact h.surj_on_image (ha.surj_on univ) } lemma inj_on_image (h : semiconj f fa fb) (ha : inj_on fa s) (hf : inj_on f (fa '' s)) : inj_on fb (f '' s) := begin rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ H, simp only [← h.eq] at H, exact congr_arg f (ha hx hy $ hf (mem_image_of_mem fa hx) (mem_image_of_mem fa hy) H) end lemma inj_on_range (h : semiconj f fa fb) (ha : injective fa) (hf : inj_on f (range fa)) : inj_on fb (range f) := by { rw ← image_univ at *, exact h.inj_on_image (ha.inj_on univ) hf } lemma bij_on_image (h : semiconj f fa fb) (ha : bij_on fa s t) (hf : inj_on f t) : bij_on fb (f '' s) (f '' t) := ⟨h.maps_to_image ha.maps_to, h.inj_on_image ha.inj_on (ha.image_eq.symm ▸ hf), h.surj_on_image ha.surj_on⟩ lemma bij_on_range (h : semiconj f fa fb) (ha : bijective fa) (hf : injective f) : bij_on fb (range f) (range f) := begin rw [← image_univ], exact h.bij_on_image (bijective_iff_bij_on_univ.1 ha) (hf.inj_on univ) end lemma maps_to_preimage (h : semiconj f fa fb) {s t : set β} (hb : maps_to fb s t) : maps_to fa (f ⁻¹' s) (f ⁻¹' t) := λ x hx, by simp only [mem_preimage, h x, hb hx] lemma inj_on_preimage (h : semiconj f fa fb) {s : set β} (hb : inj_on fb s) (hf : inj_on f (f ⁻¹' s)) : inj_on fa (f ⁻¹' s) := begin intros x hx y hy H, have := congr_arg f H, rw [h.eq, h.eq] at this, exact hf hx hy (hb hx hy this) end end semiconj lemma update_comp_eq_of_not_mem_range' {α β : Sort*} {γ : β → Sort*} [decidable_eq β] (g : Π b, γ b) {f : α → β} {i : β} (a : γ i) (h : i ∉ set.range f) : (λ j, (function.update g i a) (f j)) = (λ j, g (f j)) := update_comp_eq_of_forall_ne' _ _ $ λ x hx, h ⟨x, hx⟩ /-- Non-dependent version of `function.update_comp_eq_of_not_mem_range'` -/ lemma update_comp_eq_of_not_mem_range {α β γ : Sort*} [decidable_eq β] (g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) : (function.update g i a) ∘ f = g ∘ f := update_comp_eq_of_not_mem_range' g a h end function
c6116aaeac16f59dc3fdd10afec411ec8e042937
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/dynamics/circle/rotation_number/translation_number.lean
ca4fa34270ffe3649272c7b6d79afdf5d91ed574
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
39,520
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import algebra.iterate_hom import analysis.specific_limits import topology.algebra.ordered.monotone_continuity import order.iterate import order.semiconj_Sup /-! # Translation number of a monotone real map that commutes with `x ↦ x + 1` Let `f : ℝ → ℝ` be a monotone map such that `f (x + 1) = f x + 1` for all `x`. Then the limit $$ \tau(f)=\lim_{n\to\infty}{f^n(x)-x}{n} $$ exists and does not depend on `x`. This number is called the *translation number* of `f`. Different authors use different notation for this number: `τ`, `ρ`, `rot`, etc In this file we define a structure `circle_deg1_lift` for bundled maps with these properties, define translation number of `f : circle_deg1_lift`, prove some estimates relating `f^n(x)-x` to `τ(f)`. In case of a continuous map `f` we also prove that `f` admits a point `x` such that `f^n(x)=x+m` if and only if `τ(f)=m/n`. Maps of this type naturally appear as lifts of orientation preserving circle homeomorphisms. More precisely, let `f` be an orientation preserving homeomorphism of the circle $S^1=ℝ/ℤ$, and consider a real number `a` such that `⟦a⟧ = f 0`, where `⟦⟧` means the natural projection `ℝ → ℝ/ℤ`. Then there exists a unique continuous function `F : ℝ → ℝ` such that `F 0 = a` and `⟦F x⟧ = f ⟦x⟧` for all `x` (this fact is not formalized yet). This function is strictly monotone, continuous, and satisfies `F (x + 1) = F x + 1`. The number `⟦τ F⟧ : ℝ / ℤ` is called the *rotation number* of `f`. It does not depend on the choice of `a`. ## Main definitions * `circle_deg1_lift`: a monotone map `f : ℝ → ℝ` such that `f (x + 1) = f x + 1` for all `x`; the type `circle_deg1_lift` is equipped with `lattice` and `monoid` structures; the multiplication is given by composition: `(f * g) x = f (g x)`. * `circle_deg1_lift.translation_number`: translation number of `f : circle_deg1_lift`. ## Main statements We prove the following properties of `circle_deg1_lift.translation_number`. * `circle_deg1_lift.translation_number_eq_of_dist_bounded`: if the distance between `(f^n) 0` and `(g^n) 0` is bounded from above uniformly in `n : ℕ`, then `f` and `g` have equal translation numbers. * `circle_deg1_lift.translation_number_eq_of_semiconj_by`: if two `circle_deg1_lift` maps `f`, `g` are semiconjugate by a `circle_deg1_lift` map, then `τ f = τ g`. * `circle_deg1_lift.translation_number_units_inv`: if `f` is an invertible `circle_deg1_lift` map (equivalently, `f` is a lift of an orientation-preserving circle homeomorphism), then the translation number of `f⁻¹` is the negative of the translation number of `f`. * `circle_deg1_lift.translation_number_mul_of_commute`: if `f` and `g` commute, then `τ (f * g) = τ f + τ g`. * `circle_deg1_lift.translation_number_eq_rat_iff`: the translation number of `f` is equal to a rational number `m / n` if and only if `(f^n) x = x + m` for some `x`. * `circle_deg1_lift.semiconj_of_bijective_of_translation_number_eq`: if `f` and `g` are two bijective `circle_deg1_lift` maps and their translation numbers are equal, then these maps are semiconjugate to each other. * `circle_deg1_lift.semiconj_of_group_action_of_forall_translation_number_eq`: let `f₁` and `f₂` be two actions of a group `G` on the circle by degree 1 maps (formally, `f₁` and `f₂` are two homomorphisms from `G →* circle_deg1_lift`). If the translation numbers of `f₁ g` and `f₂ g` are equal to each other for all `g : G`, then these two actions are semiconjugate by some `F : circle_deg1_lift`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. ## Notation We use a local notation `τ` for the translation number of `f : circle_deg1_lift`. ## Implementation notes We define the translation number of `f : circle_deg1_lift` to be the limit of the sequence `(f ^ (2 ^ n)) 0 / (2 ^ n)`, then prove that `((f ^ n) x - x) / n` tends to this number for any `x`. This way it is much easier to prove that the limit exists and basic properties of the limit. We define translation number for a wider class of maps `f : ℝ → ℝ` instead of lifts of orientation preserving circle homeomorphisms for two reasons: * non-strictly monotone circle self-maps with discontinuities naturally appear as Poincaré maps for some flows on the two-torus (e.g., one can take a constant flow and glue in a few Cherry cells); * definition and some basic properties still work for this class. ## References * [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes] ## TODO Here are some short-term goals. * Introduce a structure or a typeclass for lifts of circle homeomorphisms. We use `units circle_deg1_lift` for now, but it's better to have a dedicated type (or a typeclass?). * Prove that the `semiconj_by` relation on circle homeomorphisms is an equivalence relation. * Introduce `conditionally_complete_lattice` structure, use it in the proof of `circle_deg1_lift.semiconj_of_group_action_of_forall_translation_number_eq`. * Prove that the orbits of the irrational rotation are dense in the circle. Deduce that a homeomorphism with an irrational rotation is semiconjugate to the corresponding irrational translation by a continuous `circle_deg1_lift`. ## Tags circle homeomorphism, rotation number -/ open filter set function (hiding commute) int open_locale topological_space classical /-! ### Definition and monoid structure -/ /-- A lift of a monotone degree one map `S¹ → S¹`. -/ structure circle_deg1_lift : Type := (to_fun : ℝ → ℝ) (monotone' : monotone to_fun) (map_add_one' : ∀ x, to_fun (x + 1) = to_fun x + 1) namespace circle_deg1_lift instance : has_coe_to_fun circle_deg1_lift (λ _, ℝ → ℝ) := ⟨circle_deg1_lift.to_fun⟩ @[simp] lemma coe_mk (f h₁ h₂) : ⇑(mk f h₁ h₂) = f := rfl variables (f g : circle_deg1_lift) protected lemma monotone : monotone f := f.monotone' @[mono] lemma mono {x y} (h : x ≤ y) : f x ≤ f y := f.monotone h lemma strict_mono_iff_injective : strict_mono f ↔ injective f := f.monotone.strict_mono_iff_injective @[simp] lemma map_add_one : ∀ x, f (x + 1) = f x + 1 := f.map_add_one' @[simp] lemma map_one_add (x : ℝ) : f (1 + x) = 1 + f x := by rw [add_comm, map_add_one, add_comm] theorem coe_inj : ∀ ⦃f g : circle_deg1_lift ⦄, (f : ℝ → ℝ) = g → f = g := assume ⟨f, fm, fd⟩ ⟨g, gm, gd⟩ h, by congr; exact h @[ext] theorem ext ⦃f g : circle_deg1_lift ⦄ (h : ∀ x, f x = g x) : f = g := coe_inj $ funext h theorem ext_iff {f g : circle_deg1_lift} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : monoid circle_deg1_lift := { mul := λ f g, { to_fun := f ∘ g, monotone' := f.monotone.comp g.monotone, map_add_one' := λ x, by simp [map_add_one] }, one := ⟨id, monotone_id, λ _, rfl⟩, mul_one := λ f, coe_inj $ function.comp.right_id f, one_mul := λ f, coe_inj $ function.comp.left_id f, mul_assoc := λ f₁ f₂ f₃, coe_inj rfl } instance : inhabited circle_deg1_lift := ⟨1⟩ @[simp] lemma coe_mul : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (x) : (f * g) x = f (g x) := rfl @[simp] lemma coe_one : ⇑(1 : circle_deg1_lift) = id := rfl instance units_has_coe_to_fun : has_coe_to_fun (circle_deg1_liftˣ) (λ _, ℝ → ℝ) := ⟨λ f, ⇑(f : circle_deg1_lift)⟩ @[simp, norm_cast] lemma units_coe (f : circle_deg1_liftˣ) : ⇑(f : circle_deg1_lift) = f := rfl @[simp] lemma units_inv_apply_apply (f : circle_deg1_liftˣ) (x : ℝ) : (f⁻¹ : circle_deg1_liftˣ) (f x) = x := by simp only [← units_coe, ← mul_apply, f.inv_mul, coe_one, id] @[simp] lemma units_apply_inv_apply (f : circle_deg1_liftˣ) (x : ℝ) : f ((f⁻¹ : circle_deg1_liftˣ) x) = x := by simp only [← units_coe, ← mul_apply, f.mul_inv, coe_one, id] /-- If a lift of a circle map is bijective, then it is an order automorphism of the line. -/ def to_order_iso : circle_deg1_liftˣ →* ℝ ≃o ℝ := { to_fun := λ f, { to_fun := f, inv_fun := ⇑(f⁻¹), left_inv := units_inv_apply_apply f, right_inv := units_apply_inv_apply f, map_rel_iff' := λ x y, ⟨λ h, by simpa using mono ↑(f⁻¹) h, mono f⟩ }, map_one' := rfl, map_mul' := λ f g, rfl } @[simp] lemma coe_to_order_iso (f : circle_deg1_liftˣ) : ⇑(to_order_iso f) = f := rfl @[simp] lemma coe_to_order_iso_symm (f : circle_deg1_liftˣ) : ⇑(to_order_iso f).symm = (f⁻¹ : circle_deg1_liftˣ) := rfl @[simp] lemma coe_to_order_iso_inv (f : circle_deg1_liftˣ) : ⇑(to_order_iso f)⁻¹ = (f⁻¹ : circle_deg1_liftˣ) := rfl lemma is_unit_iff_bijective {f : circle_deg1_lift} : is_unit f ↔ bijective f := ⟨λ ⟨u, h⟩, h ▸ (to_order_iso u).bijective, λ h, units.is_unit { val := f, inv := { to_fun := (equiv.of_bijective f h).symm, monotone' := λ x y hxy, (f.strict_mono_iff_injective.2 h.1).le_iff_le.1 (by simp only [equiv.of_bijective_apply_symm_apply f h, hxy]), map_add_one' := λ x, h.1 $ by simp only [equiv.of_bijective_apply_symm_apply f, f.map_add_one] }, val_inv := ext $ equiv.of_bijective_apply_symm_apply f h, inv_val := ext $ equiv.of_bijective_symm_apply_apply f h }⟩ lemma coe_pow : ∀ n : ℕ, ⇑(f^n) = (f^[n]) | 0 := rfl | (n+1) := by {ext x, simp [coe_pow n, pow_succ'] } lemma semiconj_by_iff_semiconj {f g₁ g₂ : circle_deg1_lift} : semiconj_by f g₁ g₂ ↔ semiconj f g₁ g₂ := ext_iff lemma commute_iff_commute {f g : circle_deg1_lift} : commute f g ↔ function.commute f g := ext_iff /-! ### Translate by a constant -/ /-- The map `y ↦ x + y` as a `circle_deg1_lift`. More precisely, we define a homomorphism from `multiplicative ℝ` to `circle_deg1_liftˣ`, so the translation by `x` is `translation (multiplicative.of_add x)`. -/ def translate : multiplicative ℝ →* circle_deg1_liftˣ := by refine (units.map _).comp to_units.to_monoid_hom; exact { to_fun := λ x, ⟨λ y, x.to_add + y, λ y₁ y₂ h, add_le_add_left h _, λ y, (add_assoc _ _ _).symm⟩, map_one' := ext $ zero_add, map_mul' := λ x y, ext $ add_assoc _ _ } @[simp] lemma translate_apply (x y : ℝ) : translate (multiplicative.of_add x) y = x + y := rfl @[simp] lemma translate_inv_apply (x y : ℝ) : (translate $ multiplicative.of_add x)⁻¹ y = -x + y := rfl @[simp] lemma translate_zpow (x : ℝ) (n : ℤ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ ↑n * x) := by simp only [← zsmul_eq_mul, of_add_zsmul, monoid_hom.map_zpow] @[simp] lemma translate_pow (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ ↑n * x) := translate_zpow x n @[simp] lemma translate_iterate (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^[n] = translate (multiplicative.of_add $ ↑n * x) := by rw [← units_coe, ← coe_pow, ← units.coe_pow, translate_pow, units_coe] /-! ### Commutativity with integer translations In this section we prove that `f` commutes with translations by an integer number. First we formulate these statements (for a natural or an integer number, addition on the left or on the right, addition or subtraction) using `function.commute`, then reformulate as `simp` lemmas `map_int_add` etc. -/ lemma commute_nat_add (n : ℕ) : function.commute f ((+) n) := by simpa only [nsmul_one, add_left_iterate] using function.commute.iterate_right f.map_one_add n lemma commute_add_nat (n : ℕ) : function.commute f (λ x, x + n) := by simp only [add_comm _ (n:ℝ), f.commute_nat_add n] lemma commute_sub_nat (n : ℕ) : function.commute f (λ x, x - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_nat n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv lemma commute_add_int : ∀ n : ℤ, function.commute f (λ x, x + n) | (n:ℕ) := f.commute_add_nat n | -[1+n] := by simpa only [sub_eq_add_neg] using f.commute_sub_nat (n + 1) lemma commute_int_add (n : ℤ) : function.commute f ((+) n) := by simpa only [add_comm _ (n:ℝ)] using f.commute_add_int n lemma commute_sub_int (n : ℤ) : function.commute f (λ x, x - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_int n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv @[simp] lemma map_int_add (m : ℤ) (x : ℝ) : f (m + x) = m + f x := f.commute_int_add m x @[simp] lemma map_add_int (x : ℝ) (m : ℤ) : f (x + m) = f x + m := f.commute_add_int m x @[simp] lemma map_sub_int (x : ℝ) (n : ℤ) : f (x - n) = f x - n := f.commute_sub_int n x @[simp] lemma map_add_nat (x : ℝ) (n : ℕ) : f (x + n) = f x + n := f.map_add_int x n @[simp] lemma map_nat_add (n : ℕ) (x : ℝ) : f (n + x) = n + f x := f.map_int_add n x @[simp] lemma map_sub_nat (x : ℝ) (n : ℕ) : f (x - n) = f x - n := f.map_sub_int x n lemma map_int_of_map_zero (n : ℤ) : f n = f 0 + n := by rw [← f.map_add_int, zero_add] @[simp] lemma map_fract_sub_fract_eq (x : ℝ) : f (fract x) - fract x = f x - x := by rw [int.fract, f.map_sub_int, sub_sub_sub_cancel_right] /-! ### Pointwise order on circle maps -/ /-- Monotone circle maps form a lattice with respect to the pointwise order -/ noncomputable instance : lattice circle_deg1_lift := { sup := λ f g, { to_fun := λ x, max (f x) (g x), monotone' := λ x y h, max_le_max (f.mono h) (g.mono h), -- TODO: generalize to `monotone.max` map_add_one' := λ x, by simp [max_add_add_right] }, le := λ f g, ∀ x, f x ≤ g x, le_refl := λ f x, le_refl (f x), le_trans := λ f₁ f₂ f₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ f₁ f₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x), le_sup_left := λ f g x, le_max_left (f x) (g x), le_sup_right := λ f g x, le_max_right (f x) (g x), sup_le := λ f₁ f₂ f₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), inf := λ f g, { to_fun := λ x, min (f x) (g x), monotone' := λ x y h, min_le_min (f.mono h) (g.mono h), map_add_one' := λ x, by simp [min_add_add_right] }, inf_le_left := λ f g x, min_le_left (f x) (g x), inf_le_right := λ f g x, min_le_right (f x) (g x), le_inf := λ f₁ f₂ f₃ h₂ h₃ x, le_min (h₂ x) (h₃ x) } @[simp] lemma sup_apply (x : ℝ) : (f ⊔ g) x = max (f x) (g x) := rfl @[simp] lemma inf_apply (x : ℝ) : (f ⊓ g) x = min (f x) (g x) := rfl lemma iterate_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^[n]) := λ f g h, f.monotone.iterate_le_of_le h _ lemma iterate_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := iterate_monotone n h lemma pow_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^n ≤ g^n := λ x, by simp only [coe_pow, iterate_mono h n x] lemma pow_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^n) := λ f g h, pow_mono h n /-! ### Estimates on `(f * g) 0` We prove the estimates `f 0 + ⌊g 0⌋ ≤ f (g 0) ≤ f 0 + ⌈g 0⌉` and some corollaries with added/removed floors and ceils. We also prove that for two semiconjugate maps `g₁`, `g₂`, the distance between `g₁ 0` and `g₂ 0` is less than two. -/ lemma map_le_of_map_zero (x : ℝ) : f x ≤ f 0 + ⌈x⌉ := calc f x ≤ f ⌈x⌉ : f.monotone $ le_ceil _ ... = f 0 + ⌈x⌉ : f.map_int_of_map_zero _ lemma map_map_zero_le : f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_le_of_map_zero (g 0) lemma floor_map_map_zero_le : ⌊f (g 0)⌋ ≤ ⌊f 0⌋ + ⌈g 0⌉ := calc ⌊f (g 0)⌋ ≤ ⌊f 0 + ⌈g 0⌉⌋ : floor_mono $ f.map_map_zero_le g ... = ⌊f 0⌋ + ⌈g 0⌉ : floor_add_int _ _ lemma ceil_map_map_zero_le : ⌈f (g 0)⌉ ≤ ⌈f 0⌉ + ⌈g 0⌉ := calc ⌈f (g 0)⌉ ≤ ⌈f 0 + ⌈g 0⌉⌉ : ceil_mono $ f.map_map_zero_le g ... = ⌈f 0⌉ + ⌈g 0⌉ : ceil_add_int _ _ lemma map_map_zero_lt : f (g 0) < f 0 + g 0 + 1 := calc f (g 0) ≤ f 0 + ⌈g 0⌉ : f.map_map_zero_le g ... < f 0 + (g 0 + 1) : add_lt_add_left (ceil_lt_add_one _) _ ... = f 0 + g 0 + 1 : (add_assoc _ _ _).symm lemma le_map_of_map_zero (x : ℝ) : f 0 + ⌊x⌋ ≤ f x := calc f 0 + ⌊x⌋ = f ⌊x⌋ : (f.map_int_of_map_zero _).symm ... ≤ f x : f.monotone $ floor_le _ lemma le_map_map_zero : f 0 + ⌊g 0⌋ ≤ f (g 0) := f.le_map_of_map_zero (g 0) lemma le_floor_map_map_zero : ⌊f 0⌋ + ⌊g 0⌋ ≤ ⌊f (g 0)⌋ := calc ⌊f 0⌋ + ⌊g 0⌋ = ⌊f 0 + ⌊g 0⌋⌋ : (floor_add_int _ _).symm ... ≤ ⌊f (g 0)⌋ : floor_mono $ f.le_map_map_zero g lemma le_ceil_map_map_zero : ⌈f 0⌉ + ⌊g 0⌋ ≤ ⌈(f * g) 0⌉ := calc ⌈f 0⌉ + ⌊g 0⌋ = ⌈f 0 + ⌊g 0⌋⌉ : (ceil_add_int _ _).symm ... ≤ ⌈f (g 0)⌉ : ceil_mono $ f.le_map_map_zero g lemma lt_map_map_zero : f 0 + g 0 - 1 < f (g 0) := calc f 0 + g 0 - 1 = f 0 + (g 0 - 1) : add_sub_assoc _ _ _ ... < f 0 + ⌊g 0⌋ : add_lt_add_left (sub_one_lt_floor _) _ ... ≤ f (g 0) : f.le_map_map_zero g lemma dist_map_map_zero_lt : dist (f 0 + g 0) (f (g 0)) < 1 := begin rw [dist_comm, real.dist_eq, abs_lt, lt_sub_iff_add_lt', sub_lt_iff_lt_add', ← sub_eq_add_neg], exact ⟨f.lt_map_map_zero g, f.map_map_zero_lt g⟩ end lemma dist_map_zero_lt_of_semiconj {f g₁ g₂ : circle_deg1_lift} (h : function.semiconj f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := calc dist (g₁ 0) (g₂ 0) ≤ dist (g₁ 0) (f (g₁ 0) - f 0) + dist _ (g₂ 0) : dist_triangle _ _ _ ... = dist (f 0 + g₁ 0) (f (g₁ 0)) + dist (g₂ 0 + f 0) (g₂ (f 0)) : by simp only [h.eq, real.dist_eq, sub_sub, add_comm (f 0), sub_sub_assoc_swap, abs_sub_comm (g₂ (f 0))] ... < 2 : add_lt_add (f.dist_map_map_zero_lt g₁) (g₂.dist_map_map_zero_lt f) lemma dist_map_zero_lt_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (h : semiconj_by f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := dist_map_zero_lt_of_semiconj $ semiconj_by_iff_semiconj.1 h /-! ### Limits at infinities and continuity -/ protected lemma tendsto_at_bot : tendsto f at_bot at_bot := tendsto_at_bot_mono f.map_le_of_map_zero $ tendsto_at_bot_add_const_left _ _ $ tendsto_at_bot_mono (λ x, (ceil_lt_add_one x).le) $ tendsto_at_bot_add_const_right _ _ tendsto_id protected lemma tendsto_at_top : tendsto f at_top at_top := tendsto_at_top_mono f.le_map_of_map_zero $ tendsto_at_top_add_const_left _ _ $ tendsto_at_top_mono (λ x, (sub_one_lt_floor x).le) $ by simpa [sub_eq_add_neg] using tendsto_at_top_add_const_right _ _ tendsto_id lemma continuous_iff_surjective : continuous f ↔ function.surjective f := ⟨λ h, h.surjective f.tendsto_at_top f.tendsto_at_bot, f.monotone.continuous_of_surjective⟩ /-! ### Estimates on `(f^n) x` If we know that `f x` is `≤`/`<`/`≥`/`>`/`=` to `x + m`, then we have a similar estimate on `f^[n] x` and `x + n * m`. For `≤`, `≥`, and `=` we formulate both `of` (implication) and `iff` versions because implications work for `n = 0`. For `<` and `>` we formulate only `iff` versions. -/ lemma iterate_le_of_map_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) (n : ℕ) : f^[n] x ≤ x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_le_of_map_le f.monotone (monotone_id.add_const m) h n lemma le_iterate_of_add_int_le_map {x : ℝ} {m : ℤ} (h : x + m ≤ f x) (n : ℕ) : x + n * m ≤ (f^[n]) x := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).symm.iterate_le_of_map_le (monotone_id.add_const m) f.monotone h n lemma iterate_eq_of_map_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) (n : ℕ) : f^[n] x = x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_eq_of_map_eq n h lemma iterate_pos_le_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x ≤ x + n * m ↔ f x ≤ x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_le_iff_map_le f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_lt_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x < x + n * m ↔ f x < x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_lt_iff_map_lt f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_eq_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x = x + n * m ↔ f x = x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_eq_iff_map_eq f.monotone (strict_mono_id.add_const m) hn lemma le_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m ≤ (f^[n]) x ↔ x + m ≤ f x := by simpa only [not_lt] using not_congr (f.iterate_pos_lt_iff hn) lemma lt_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m < (f^[n]) x ↔ x + m < f x := by simpa only [not_le] using not_congr (f.iterate_pos_le_iff hn) lemma mul_floor_map_zero_le_floor_iterate_zero (n : ℕ) : ↑n * ⌊f 0⌋ ≤ ⌊(f^[n] 0)⌋ := begin rw [le_floor, int.cast_mul, int.cast_coe_nat, ← zero_add ((n : ℝ) * _)], apply le_iterate_of_add_int_le_map, simp [floor_le] end /-! ### Definition of translation number -/ noncomputable theory /-- An auxiliary sequence used to define the translation number. -/ def transnum_aux_seq (n : ℕ) : ℝ := (f^(2^n)) 0 / 2^n /-- The translation number of a `circle_deg1_lift`, $τ(f)=\lim_{n→∞}\frac{f^n(x)-x}{n}$. We use an auxiliary sequence `\frac{f^{2^n}(0)}{2^n}` to define `τ(f)` because some proofs are simpler this way. -/ def translation_number : ℝ := lim at_top f.transnum_aux_seq -- TODO: choose two different symbols for `circle_deg1_lift.translation_number` and the future -- `circle_mono_homeo.rotation_number`, then make them `localized notation`s local notation `τ` := translation_number lemma transnum_aux_seq_def : f.transnum_aux_seq = λ n : ℕ, (f^(2^n)) 0 / 2^n := rfl lemma translation_number_eq_of_tendsto_aux {τ' : ℝ} (h : tendsto f.transnum_aux_seq at_top (𝓝 τ')) : τ f = τ' := h.lim_eq lemma translation_number_eq_of_tendsto₀ {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n] 0 / n) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto_aux $ by simpa [(∘), transnum_aux_seq_def, coe_pow] using h.comp (nat.tendsto_pow_at_top_at_top_of_one_lt one_lt_two) lemma translation_number_eq_of_tendsto₀' {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n + 1] 0 / (n + 1)) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto₀ $ (tendsto_add_at_top_iff_nat 1).1 h lemma transnum_aux_seq_zero : f.transnum_aux_seq 0 = f 0 := by simp [transnum_aux_seq] lemma transnum_aux_seq_dist_lt (n : ℕ) : dist (f.transnum_aux_seq n) (f.transnum_aux_seq (n+1)) < (1 / 2) / (2^n) := begin have : 0 < (2^(n+1):ℝ) := pow_pos zero_lt_two _, rw [div_div_eq_div_mul, ← pow_succ, ← abs_of_pos this], replace := abs_pos.2 (ne_of_gt this), convert (div_lt_div_right this).2 ((f^(2^n)).dist_map_map_zero_lt (f^(2^n))), simp_rw [transnum_aux_seq, real.dist_eq], rw [← abs_div, sub_div, pow_succ', pow_succ, ← two_mul, mul_div_mul_left _ _ (@two_ne_zero ℝ _ _), pow_mul, sq, mul_apply] end lemma tendsto_translation_number_aux : tendsto f.transnum_aux_seq at_top (𝓝 $ τ f) := (cauchy_seq_of_le_geometric_two 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n)).tendsto_lim lemma dist_map_zero_translation_number_le : dist (f 0) (τ f) ≤ 1 := f.transnum_aux_seq_zero ▸ dist_le_of_le_geometric_two_of_tendsto₀ 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n) f.tendsto_translation_number_aux lemma tendsto_translation_number_of_dist_bounded_aux (x : ℕ → ℝ) (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) (x n) ≤ C) : tendsto (λ n : ℕ, x (2^n) / (2^n)) at_top (𝓝 $ τ f) := begin refine f.tendsto_translation_number_aux.congr_dist (squeeze_zero (λ _, dist_nonneg) _ _), { exact λ n, C / 2^n }, { intro n, have : 0 < (2^n:ℝ) := pow_pos zero_lt_two _, convert (div_le_div_right this).2 (H (2^n)), rw [transnum_aux_seq, real.dist_eq, ← sub_div, abs_div, abs_of_pos this, real.dist_eq] }, { exact mul_zero C ▸ tendsto_const_nhds.mul (tendsto_inv_at_top_zero.comp $ tendsto_pow_at_top_at_top_of_one_lt one_lt_two) } end lemma translation_number_eq_of_dist_bounded {f g : circle_deg1_lift} (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) ((g^n) 0) ≤ C) : τ f = τ g := eq.symm $ g.translation_number_eq_of_tendsto_aux $ f.tendsto_translation_number_of_dist_bounded_aux _ C H @[simp] lemma translation_number_one : τ 1 = 0 := translation_number_eq_of_tendsto₀ _ $ by simp [tendsto_const_nhds] lemma translation_number_eq_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (H : semiconj_by f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_dist_bounded 2 $ λ n, le_of_lt $ dist_map_zero_lt_of_semiconj_by $ H.pow_right n lemma translation_number_eq_of_semiconj {f g₁ g₂ : circle_deg1_lift} (H : function.semiconj f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_semiconj_by $ semiconj_by_iff_semiconj.2 H lemma translation_number_mul_of_commute {f g : circle_deg1_lift} (h : commute f g) : τ (f * g) = τ f + τ g := begin have : tendsto (λ n : ℕ, ((λ k, (f^k) 0 + (g^k) 0) (2^n)) / (2^n)) at_top (𝓝 $ τ f + τ g) := ((f.tendsto_translation_number_aux.add g.tendsto_translation_number_aux).congr $ λ n, (add_div ((f^(2^n)) 0) ((g^(2^n)) 0) ((2:ℝ)^n)).symm), refine tendsto_nhds_unique ((f * g).tendsto_translation_number_of_dist_bounded_aux _ 1 (λ n, _)) this, rw [h.mul_pow, dist_comm], exact le_of_lt ((f^n).dist_map_map_zero_lt (g^n)) end @[simp] lemma translation_number_units_inv (f : circle_deg1_liftˣ) : τ ↑(f⁻¹) = -τ f := eq_neg_iff_add_eq_zero.2 $ by simp [← translation_number_mul_of_commute (commute.refl _).units_inv_left] @[simp] lemma translation_number_pow : ∀ n : ℕ, τ (f^n) = n * τ f | 0 := by simp | (n+1) := by rw [pow_succ', translation_number_mul_of_commute (commute.pow_self f n), translation_number_pow n, nat.cast_add_one, add_mul, one_mul] @[simp] lemma translation_number_zpow (f : circle_deg1_liftˣ) : ∀ n : ℤ, τ (f ^ n : units _) = n * τ f | (n : ℕ) := by simp [translation_number_pow f n] | -[1+n] := by { simp, ring } @[simp] lemma translation_number_conj_eq (f : circle_deg1_liftˣ) (g : circle_deg1_lift) : τ (↑f * g * ↑(f⁻¹)) = τ g := (translation_number_eq_of_semiconj_by (f.mk_semiconj_by g)).symm @[simp] lemma translation_number_conj_eq' (f : circle_deg1_liftˣ) (g : circle_deg1_lift) : τ (↑(f⁻¹) * g * f) = τ g := translation_number_conj_eq f⁻¹ g lemma dist_pow_map_zero_mul_translation_number_le (n:ℕ) : dist ((f^n) 0) (n * f.translation_number) ≤ 1 := f.translation_number_pow n ▸ (f^n).dist_map_zero_translation_number_le lemma tendsto_translation_number₀' : tendsto (λ n:ℕ, (f^(n+1)) 0 / (n+1)) at_top (𝓝 $ τ f) := begin refine (tendsto_iff_dist_tendsto_zero.2 $ squeeze_zero (λ _, dist_nonneg) (λ n, _) ((tendsto_const_div_at_top_nhds_0_nat 1).comp (tendsto_add_at_top_nat 1))), dsimp, have : (0:ℝ) < n + 1 := n.cast_add_one_pos, rw [real.dist_eq, div_sub' _ _ _ (ne_of_gt this), abs_div, ← real.dist_eq, abs_of_pos this, div_le_div_right this, ← nat.cast_add_one], apply dist_pow_map_zero_mul_translation_number_le end lemma tendsto_translation_number₀ : tendsto (λ n:ℕ, ((f^n) 0) / n) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).1 f.tendsto_translation_number₀' /-- For any `x : ℝ` the sequence $\frac{f^n(x)-x}{n}$ tends to the translation number of `f`. In particular, this limit does not depend on `x`. -/ lemma tendsto_translation_number (x : ℝ) : tendsto (λ n:ℕ, ((f^n) x - x) / n) at_top (𝓝 $ τ f) := begin rw [← translation_number_conj_eq' (translate $ multiplicative.of_add x)], convert tendsto_translation_number₀ _, ext n, simp [sub_eq_neg_add, units.conj_pow'] end lemma tendsto_translation_number' (x : ℝ) : tendsto (λ n:ℕ, ((f^(n+1)) x - x) / (n+1)) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).2 (f.tendsto_translation_number x) lemma translation_number_mono : monotone τ := λ f g h, le_of_tendsto_of_tendsto' f.tendsto_translation_number₀ g.tendsto_translation_number₀ $ λ n, div_le_div_of_le_of_nonneg (pow_mono h n 0) n.cast_nonneg lemma translation_number_translate (x : ℝ) : τ (translate $ multiplicative.of_add x) = x := translation_number_eq_of_tendsto₀' _ $ by simp [nat.cast_add_one_ne_zero, mul_div_cancel_left, tendsto_const_nhds] lemma translation_number_le_of_le_add {z : ℝ} (hz : ∀ x, f x ≤ x + z) : τ f ≤ z := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_left _ (hz x) (add_comm _ _)) lemma le_translation_number_of_add_le {z : ℝ} (hz : ∀ x, x + z ≤ f x) : z ≤ τ f := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_right _ (add_comm _ _) (hz x)) lemma translation_number_le_of_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) : τ f ≤ m := le_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (div_le_iff' (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ sub_le_iff_le_add'.2 $ (coe_pow f (n + 1)).symm ▸ f.iterate_le_of_map_le_add_int h (n + 1) lemma translation_number_le_of_le_add_nat {x : ℝ} {m : ℕ} (h : f x ≤ x + m) : τ f ≤ m := @translation_number_le_of_le_add_int f x m h lemma le_translation_number_of_add_int_le {x : ℝ} {m : ℤ} (h : x + m ≤ f x) : ↑m ≤ τ f := ge_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (le_div_iff (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ le_sub_iff_add_le'.2 $ by simp only [coe_pow, mul_comm (m:ℝ), ← nat.cast_add_one, f.le_iterate_of_add_int_le_map h] lemma le_translation_number_of_add_nat_le {x : ℝ} {m : ℕ} (h : x + m ≤ f x) : ↑m ≤ τ f := @le_translation_number_of_add_int_le f x m h /-- If `f x - x` is an integer number `m` for some point `x`, then `τ f = m`. On the circle this means that a map with a fixed point has rotation number zero. -/ lemma translation_number_of_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) : τ f = m := le_antisymm (translation_number_le_of_le_add_int f $ le_of_eq h) (le_translation_number_of_add_int_le f $ le_of_eq h.symm) lemma floor_sub_le_translation_number (x : ℝ) : ↑⌊f x - x⌋ ≤ τ f := le_translation_number_of_add_int_le f $ le_sub_iff_add_le'.1 (floor_le $ f x - x) lemma translation_number_le_ceil_sub (x : ℝ) : τ f ≤ ⌈f x - x⌉ := translation_number_le_of_le_add_int f $ sub_le_iff_le_add'.1 (le_ceil $ f x - x) lemma map_lt_of_translation_number_lt_int {n : ℤ} (h : τ f < n) (x : ℝ) : f x < x + n := not_le.1 $ mt f.le_translation_number_of_add_int_le $ not_le.2 h lemma map_lt_of_translation_number_lt_nat {n : ℕ} (h : τ f < n) (x : ℝ) : f x < x + n := @map_lt_of_translation_number_lt_int f n h x lemma map_lt_add_floor_translation_number_add_one (x : ℝ) : f x < x + ⌊τ f⌋ + 1 := begin rw [add_assoc], norm_cast, refine map_lt_of_translation_number_lt_int _ _ _, push_cast, exact lt_floor_add_one _ end lemma map_lt_add_translation_number_add_one (x : ℝ) : f x < x + τ f + 1 := calc f x < x + ⌊τ f⌋ + 1 : f.map_lt_add_floor_translation_number_add_one x ... ≤ x + τ f + 1 : by { mono*, exact floor_le (τ f) } lemma lt_map_of_int_lt_translation_number {n : ℤ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := not_le.1 $ mt f.translation_number_le_of_le_add_int $ not_le.2 h lemma lt_map_of_nat_lt_translation_number {n : ℕ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := @lt_map_of_int_lt_translation_number f n h x /-- If `f^n x - x`, `n > 0`, is an integer number `m` for some point `x`, then `τ f = m / n`. On the circle this means that a map with a periodic orbit has a rational rotation number. -/ lemma translation_number_of_map_pow_eq_add_int {x : ℝ} {n : ℕ} {m : ℤ} (h : (f^n) x = x + m) (hn : 0 < n) : τ f = m / n := begin have := (f^n).translation_number_of_eq_add_int h, rwa [translation_number_pow, mul_comm, ← eq_div_iff] at this, exact nat.cast_ne_zero.2 (ne_of_gt hn) end /-- If a predicate depends only on `f x - x` and holds for all `0 ≤ x ≤ 1`, then it holds for all `x`. -/ lemma forall_map_sub_of_Icc (P : ℝ → Prop) (h : ∀ x ∈ Icc (0:ℝ) 1, P (f x - x)) (x : ℝ) : P (f x - x) := f.map_fract_sub_fract_eq x ▸ h _ ⟨fract_nonneg _, le_of_lt (fract_lt_one _)⟩ lemma translation_number_lt_of_forall_lt_add (hf : continuous f) {z : ℝ} (hz : ∀ x, f x < x + z) : τ f < z := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f y - y ≤ f x - x, from is_compact_Icc.exists_forall_ge (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_le_of_lt _ (sub_lt_iff_lt_add'.2 $ hz x), apply translation_number_le_of_le_add, simp only [← sub_le_iff_le_add'], exact f.forall_map_sub_of_Icc (λ a, a ≤ f x - x) hx end lemma lt_translation_number_of_forall_add_lt (hf : continuous f) {z : ℝ} (hz : ∀ x, x + z < f x) : z < τ f := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f x - x ≤ f y - y, from is_compact_Icc.exists_forall_le (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_lt_of_le (lt_sub_iff_add_lt'.2 $ hz x) _, apply le_translation_number_of_add_le, simp only [← le_sub_iff_add_le'], exact f.forall_map_sub_of_Icc _ hx end /-- If `f` is a continuous monotone map `ℝ → ℝ`, `f (x + 1) = f x + 1`, then there exists `x` such that `f x = x + τ f`. -/ lemma exists_eq_add_translation_number (hf : continuous f) : ∃ x, f x = x + τ f := begin obtain ⟨a, ha⟩ : ∃ x, f x ≤ x + f.translation_number, { by_contra' H, exact lt_irrefl _ (f.lt_translation_number_of_forall_add_lt hf H) }, obtain ⟨b, hb⟩ : ∃ x, x + τ f ≤ f x, { by_contra' H, exact lt_irrefl _ (f.translation_number_lt_of_forall_lt_add hf H) }, exact intermediate_value_univ₂ hf (continuous_id.add continuous_const) ha hb end lemma translation_number_eq_int_iff (hf : continuous f) {m : ℤ} : τ f = m ↔ ∃ x, f x = x + m := begin refine ⟨λ h, h ▸ f.exists_eq_add_translation_number hf, _⟩, rintros ⟨x, hx⟩, exact f.translation_number_of_eq_add_int hx end lemma continuous_pow (hf : continuous f) (n : ℕ) : continuous ⇑(f^n : circle_deg1_lift) := by { rw coe_pow, exact hf.iterate n } lemma translation_number_eq_rat_iff (hf : continuous f) {m : ℤ} {n : ℕ} (hn : 0 < n) : τ f = m / n ↔ ∃ x, (f^n) x = x + m := begin rw [eq_div_iff, mul_comm, ← translation_number_pow]; [skip, exact ne_of_gt (nat.cast_pos.2 hn)], exact (f^n).translation_number_eq_int_iff (f.continuous_pow hf n) end /-- Consider two actions `f₁ f₂ : G →* circle_deg1_lift` of a group on the real line by lifts of orientation preserving circle homeomorphisms. Suppose that for each `g : G` the homeomorphisms `f₁ g` and `f₂ g` have equal rotation numbers. Then there exists `F : circle_deg1_lift` such that `F * f₁ g = f₂ g * F` for all `g : G`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ lemma semiconj_of_group_action_of_forall_translation_number_eq {G : Type*} [group G] (f₁ f₂ : G →* circle_deg1_lift) (h : ∀ g, τ (f₁ g) = τ (f₂ g)) : ∃ F : circle_deg1_lift, ∀ g, semiconj F (f₁ g) (f₂ g) := begin -- Equality of translation number guarantees that for each `x` -- the set `{f₂ g⁻¹ (f₁ g x) | g : G}` is bounded above. have : ∀ x, bdd_above (range $ λ g, f₂ g⁻¹ (f₁ g x)), { refine λ x, ⟨x + 2, _⟩, rintro _ ⟨g, rfl⟩, have : τ (f₂ g⁻¹) = -τ (f₂ g), by rw [← monoid_hom.coe_to_hom_units, monoid_hom.map_inv, translation_number_units_inv, monoid_hom.coe_to_hom_units], calc f₂ g⁻¹ (f₁ g x) ≤ f₂ g⁻¹ (x + τ (f₁ g) + 1) : mono _ (map_lt_add_translation_number_add_one _ _).le ... = f₂ g⁻¹ (x + τ (f₂ g)) + 1 : by rw [h, map_add_one] ... ≤ x + τ (f₂ g) + τ (f₂ g⁻¹) + 1 + 1 : by { mono, exact (map_lt_add_translation_number_add_one _ _).le } ... = x + 2 : by simp [this, bit0, add_assoc] }, -- We have a theorem about actions by `order_iso`, so we introduce auxiliary maps -- to `ℝ ≃o ℝ`. set F₁ := to_order_iso.comp f₁.to_hom_units, set F₂ := to_order_iso.comp f₂.to_hom_units, have hF₁ : ∀ g, ⇑(F₁ g) = f₁ g := λ _, rfl, have hF₂ : ∀ g, ⇑(F₂ g) = f₂ g := λ _, rfl, simp only [← hF₁, ← hF₂], -- Now we apply `cSup_div_semiconj` and go back to `f₁` and `f₂`. refine ⟨⟨_, λ x y hxy, _, λ x, _⟩, cSup_div_semiconj F₂ F₁ (λ x, _)⟩; simp only [hF₁, hF₂, ← monoid_hom.map_inv, coe_mk], { refine csupr_le_csupr (this y) (λ g, _), exact mono _ (mono _ hxy) }, { simp only [map_add_one], exact (map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) (monotone_id.add_const (1 : ℝ)) (this x)).symm }, { exact this x } end /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses arguments `f₁ f₂ : circle_deg1_liftˣ` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma units_semiconj_of_translation_number_eq {f₁ f₂ : circle_deg1_liftˣ} (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := begin have : ∀ n : multiplicative ℤ, τ ((units.coe_hom _).comp (zpowers_hom _ f₁) n) = τ ((units.coe_hom _).comp (zpowers_hom _ f₂) n), { intro n, simp [h] }, exact (semiconj_of_group_action_of_forall_translation_number_eq _ _ this).imp (λ F hF, hF (multiplicative.of_add 1)) end /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses assumptions `is_unit f₁` and `is_unit f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma semiconj_of_is_unit_of_translation_number_eq {f₁ f₂ : circle_deg1_lift} (h₁ : is_unit f₁) (h₂ : is_unit f₂) (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := by { rcases ⟨h₁, h₂⟩ with ⟨⟨f₁, rfl⟩, ⟨f₂, rfl⟩⟩, exact units_semiconj_of_translation_number_eq h } /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses assumptions `bijective f₁` and `bijective f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma semiconj_of_bijective_of_translation_number_eq {f₁ f₂ : circle_deg1_lift} (h₁ : bijective f₁) (h₂ : bijective f₂) (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := semiconj_of_is_unit_of_translation_number_eq (is_unit_iff_bijective.2 h₁) (is_unit_iff_bijective.2 h₂) h end circle_deg1_lift
5294220ec2dafe5e1af7ce3aa9949c5a5ee8b4ff
f00cc9c04d77f9621aa57d1406d35c522c3ff82c
/tests/lean/run/check_constants.lean
a04d4b3347b78603028fdcc16a03077b92d8287f
[ "Apache-2.0" ]
permissive
shonfeder/lean
444c66a74676d74fb3ef682d88cd0f5c1bf928a5
24d5a1592d80cefe86552d96410c51bb07e6d411
refs/heads/master
1,619,338,440,905
1,512,842,340,000
1,512,842,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,191
lean
-- DO NOT EDIT, automatically generated file, generator scripts/gen_constants_cpp.py import smt system.io open tactic meta def script_check_id (n : name) : tactic unit := do env ← get_env, (env^.get n >> return ()) <|> (guard $ env^.is_namespace n) <|> (attribute.get_instances n >> return ()) <|> fail ("identifier '" ++ to_string n ++ "' is not a constant, namespace nor attribute") run_cmd script_check_id `abs run_cmd script_check_id `absurd run_cmd script_check_id `acc.cases_on run_cmd script_check_id `acc.rec run_cmd script_check_id `add_comm_group run_cmd script_check_id `add_comm_semigroup run_cmd script_check_id `add_group run_cmd script_check_id `add_monoid run_cmd script_check_id `and run_cmd script_check_id `and.elim_left run_cmd script_check_id `and.elim_right run_cmd script_check_id `and.intro run_cmd script_check_id `and.rec run_cmd script_check_id `and.cases_on run_cmd script_check_id `auto_param run_cmd script_check_id `bit0 run_cmd script_check_id `bit1 run_cmd script_check_id `bin_tree.empty run_cmd script_check_id `bin_tree.leaf run_cmd script_check_id `bin_tree.node run_cmd script_check_id `bool run_cmd script_check_id `bool.ff run_cmd script_check_id `bool.tt run_cmd script_check_id `combinator.K run_cmd script_check_id `cast run_cmd script_check_id `cast_heq run_cmd script_check_id `char run_cmd script_check_id `char.mk run_cmd script_check_id `char.ne_of_vne run_cmd script_check_id `char.of_nat run_cmd script_check_id `char.of_nat_ne_of_ne run_cmd script_check_id `is_valid_char_range_1 run_cmd script_check_id `is_valid_char_range_2 run_cmd script_check_id `classical.prop_decidable run_cmd script_check_id `classical.type_decidable_eq run_cmd script_check_id `coe run_cmd script_check_id `coe_fn run_cmd script_check_id `coe_sort run_cmd script_check_id `coe_to_lift run_cmd script_check_id `congr run_cmd script_check_id `congr_arg run_cmd script_check_id `congr_fun run_cmd script_check_id `decidable run_cmd script_check_id `decidable.to_bool run_cmd script_check_id `distrib run_cmd script_check_id `dite run_cmd script_check_id `empty run_cmd script_check_id `Exists run_cmd script_check_id `eq run_cmd script_check_id `eq.cases_on run_cmd script_check_id `eq.drec run_cmd script_check_id `eq.mp run_cmd script_check_id `eq.mpr run_cmd script_check_id `eq.rec run_cmd script_check_id `eq.refl run_cmd script_check_id `eq.subst run_cmd script_check_id `eq.symm run_cmd script_check_id `eq.trans run_cmd script_check_id `eq_of_heq run_cmd script_check_id `eq_rec_heq run_cmd script_check_id `eq_true_intro run_cmd script_check_id `eq_false_intro run_cmd script_check_id `eq_self_iff_true run_cmd script_check_id `expr run_cmd script_check_id `expr.subst run_cmd script_check_id `format run_cmd script_check_id `false run_cmd script_check_id `false_of_true_iff_false run_cmd script_check_id `false_of_true_eq_false run_cmd script_check_id `true_eq_false_of_false run_cmd script_check_id `false.rec run_cmd script_check_id `field run_cmd script_check_id `fin.mk run_cmd script_check_id `fin.ne_of_vne run_cmd script_check_id `forall_congr run_cmd script_check_id `forall_congr_eq run_cmd script_check_id `forall_not_of_not_exists run_cmd script_check_id `funext run_cmd script_check_id `ge run_cmd script_check_id `gt run_cmd script_check_id `has_add run_cmd script_check_id `has_add.add run_cmd script_check_id `andthen run_cmd script_check_id `has_bind.and_then run_cmd script_check_id `has_bind.bind run_cmd script_check_id `has_bind.seq run_cmd script_check_id `has_div run_cmd script_check_id `has_div.div run_cmd script_check_id `has_emptyc.emptyc run_cmd script_check_id `has_mod.mod run_cmd script_check_id `has_mul run_cmd script_check_id `has_mul.mul run_cmd script_check_id `has_insert.insert run_cmd script_check_id `has_inv run_cmd script_check_id `has_inv.inv run_cmd script_check_id `has_le run_cmd script_check_id `has_le.le run_cmd script_check_id `has_lt run_cmd script_check_id `has_lt.lt run_cmd script_check_id `has_neg run_cmd script_check_id `has_neg.neg run_cmd script_check_id `has_one run_cmd script_check_id `has_one.one run_cmd script_check_id `has_orelse.orelse run_cmd script_check_id `has_sep.sep run_cmd script_check_id `has_sizeof run_cmd script_check_id `has_sizeof.mk run_cmd script_check_id `has_sub run_cmd script_check_id `has_sub.sub run_cmd script_check_id `has_to_format run_cmd script_check_id `has_repr run_cmd script_check_id `has_well_founded run_cmd script_check_id `has_well_founded.r run_cmd script_check_id `has_well_founded.wf run_cmd script_check_id `has_zero run_cmd script_check_id `has_zero.zero run_cmd script_check_id `has_coe_t run_cmd script_check_id `heq run_cmd script_check_id `heq.refl run_cmd script_check_id `heq.symm run_cmd script_check_id `heq.trans run_cmd script_check_id `heq_of_eq run_cmd script_check_id `hole_command run_cmd script_check_id `id run_cmd script_check_id `id_rhs run_cmd script_check_id `id_delta run_cmd script_check_id `if_neg run_cmd script_check_id `if_pos run_cmd script_check_id `iff run_cmd script_check_id `iff_false_intro run_cmd script_check_id `iff.intro run_cmd script_check_id `iff.mp run_cmd script_check_id `iff.mpr run_cmd script_check_id `iff.refl run_cmd script_check_id `iff.symm run_cmd script_check_id `iff.trans run_cmd script_check_id `iff_true_intro run_cmd script_check_id `imp_congr run_cmd script_check_id `imp_congr_eq run_cmd script_check_id `imp_congr_ctx run_cmd script_check_id `imp_congr_ctx_eq run_cmd script_check_id `implies run_cmd script_check_id `implies_of_if_neg run_cmd script_check_id `implies_of_if_pos run_cmd script_check_id `int run_cmd script_check_id `int.has_add run_cmd script_check_id `int.has_mul run_cmd script_check_id `int.has_sub run_cmd script_check_id `int.has_div run_cmd script_check_id `int.has_le run_cmd script_check_id `int.has_lt run_cmd script_check_id `int.has_neg run_cmd script_check_id `int.has_mod run_cmd script_check_id `int.bit0_nonneg run_cmd script_check_id `int.bit1_nonneg run_cmd script_check_id `int.one_nonneg run_cmd script_check_id `int.zero_nonneg run_cmd script_check_id `int.bit0_pos run_cmd script_check_id `int.bit1_pos run_cmd script_check_id `int.one_pos run_cmd script_check_id `int.nat_abs_zero run_cmd script_check_id `int.nat_abs_one run_cmd script_check_id `int.nat_abs_bit0_step run_cmd script_check_id `int.nat_abs_bit1_nonneg_step run_cmd script_check_id `int.ne_of_nat_ne_nonneg_case run_cmd script_check_id `int.ne_neg_of_ne run_cmd script_check_id `int.neg_ne_of_pos run_cmd script_check_id `int.ne_neg_of_pos run_cmd script_check_id `int.neg_ne_zero_of_ne run_cmd script_check_id `int.zero_ne_neg_of_ne run_cmd script_check_id `int.decidable_linear_ordered_comm_group run_cmd script_check_id `interactive.param_desc run_cmd script_check_id `interactive.parse run_cmd script_check_id `io run_cmd script_check_id `io.interface run_cmd script_check_id `is_associative run_cmd script_check_id `is_associative.assoc run_cmd script_check_id `is_commutative run_cmd script_check_id `is_commutative.comm run_cmd script_check_id `ite run_cmd script_check_id `lean.parser run_cmd script_check_id `lean.parser.pexpr run_cmd script_check_id `lean.parser.tk run_cmd script_check_id `left_distrib run_cmd script_check_id `left_comm run_cmd script_check_id `le_refl run_cmd script_check_id `linear_ordered_ring run_cmd script_check_id `linear_ordered_semiring run_cmd script_check_id `list run_cmd script_check_id `list.nil run_cmd script_check_id `list.cons run_cmd script_check_id `match_failed run_cmd script_check_id `monad run_cmd script_check_id `monad_fail run_cmd script_check_id `monoid run_cmd script_check_id `mul_one run_cmd script_check_id `mul_zero run_cmd script_check_id `mul_zero_class run_cmd script_check_id `name.anonymous run_cmd script_check_id `name.mk_numeral run_cmd script_check_id `name.mk_string run_cmd script_check_id `nat run_cmd script_check_id `nat.succ run_cmd script_check_id `nat.zero run_cmd script_check_id `nat.has_zero run_cmd script_check_id `nat.has_one run_cmd script_check_id `nat.has_add run_cmd script_check_id `nat.add run_cmd script_check_id `nat.cases_on run_cmd script_check_id `nat.bit0_ne run_cmd script_check_id `nat.bit0_ne_bit1 run_cmd script_check_id `nat.bit0_ne_zero run_cmd script_check_id `nat.bit0_ne_one run_cmd script_check_id `nat.bit1_ne run_cmd script_check_id `nat.bit1_ne_bit0 run_cmd script_check_id `nat.bit1_ne_zero run_cmd script_check_id `nat.bit1_ne_one run_cmd script_check_id `nat.zero_ne_one run_cmd script_check_id `nat.zero_ne_bit0 run_cmd script_check_id `nat.zero_ne_bit1 run_cmd script_check_id `nat.one_ne_zero run_cmd script_check_id `nat.one_ne_bit0 run_cmd script_check_id `nat.one_ne_bit1 run_cmd script_check_id `nat.bit0_lt run_cmd script_check_id `nat.bit1_lt run_cmd script_check_id `nat.bit0_lt_bit1 run_cmd script_check_id `nat.bit1_lt_bit0 run_cmd script_check_id `nat.zero_lt_one run_cmd script_check_id `nat.zero_lt_bit1 run_cmd script_check_id `nat.zero_lt_bit0 run_cmd script_check_id `nat.one_lt_bit0 run_cmd script_check_id `nat.one_lt_bit1 run_cmd script_check_id `nat.le_of_lt run_cmd script_check_id `nat.le_refl run_cmd script_check_id `ne run_cmd script_check_id `neq_of_not_iff run_cmd script_check_id `norm_num.add1 run_cmd script_check_id `norm_num.add1_bit0 run_cmd script_check_id `norm_num.add1_bit1_helper run_cmd script_check_id `norm_num.add1_one run_cmd script_check_id `norm_num.add1_zero run_cmd script_check_id `norm_num.add_div_helper run_cmd script_check_id `norm_num.bin_add_zero run_cmd script_check_id `norm_num.bin_zero_add run_cmd script_check_id `norm_num.bit0_add_bit0_helper run_cmd script_check_id `norm_num.bit0_add_bit1_helper run_cmd script_check_id `norm_num.bit0_add_one run_cmd script_check_id `norm_num.bit1_add_bit0_helper run_cmd script_check_id `norm_num.bit1_add_bit1_helper run_cmd script_check_id `norm_num.bit1_add_one_helper run_cmd script_check_id `norm_num.div_add_helper run_cmd script_check_id `norm_num.div_eq_div_helper run_cmd script_check_id `norm_num.div_helper run_cmd script_check_id `norm_num.div_mul_helper run_cmd script_check_id `norm_num.mk_cong run_cmd script_check_id `norm_num.mul_bit0_helper run_cmd script_check_id `norm_num.mul_bit1_helper run_cmd script_check_id `norm_num.mul_div_helper run_cmd script_check_id `norm_num.neg_add_neg_helper run_cmd script_check_id `norm_num.neg_add_pos_helper1 run_cmd script_check_id `norm_num.neg_add_pos_helper2 run_cmd script_check_id `norm_num.neg_mul_neg_helper run_cmd script_check_id `norm_num.neg_mul_pos_helper run_cmd script_check_id `norm_num.neg_neg_helper run_cmd script_check_id `norm_num.neg_zero_helper run_cmd script_check_id `norm_num.nonneg_bit0_helper run_cmd script_check_id `norm_num.nonneg_bit1_helper run_cmd script_check_id `norm_num.nonzero_of_div_helper run_cmd script_check_id `norm_num.nonzero_of_neg_helper run_cmd script_check_id `norm_num.nonzero_of_pos_helper run_cmd script_check_id `norm_num.one_add_bit0 run_cmd script_check_id `norm_num.one_add_bit1_helper run_cmd script_check_id `norm_num.one_add_one run_cmd script_check_id `norm_num.pos_add_neg_helper run_cmd script_check_id `norm_num.pos_bit0_helper run_cmd script_check_id `norm_num.pos_bit1_helper run_cmd script_check_id `norm_num.pos_mul_neg_helper run_cmd script_check_id `norm_num.sub_nat_zero_helper run_cmd script_check_id `norm_num.sub_nat_pos_helper run_cmd script_check_id `norm_num.subst_into_div run_cmd script_check_id `norm_num.subst_into_prod run_cmd script_check_id `norm_num.subst_into_subtr run_cmd script_check_id `norm_num.subst_into_sum run_cmd script_check_id `not run_cmd script_check_id `not_of_iff_false run_cmd script_check_id `not_of_eq_false run_cmd script_check_id `of_eq_true run_cmd script_check_id `of_iff_true run_cmd script_check_id `opt_param run_cmd script_check_id `or run_cmd script_check_id `inout_param run_cmd script_check_id `punit run_cmd script_check_id `punit.star run_cmd script_check_id `prod.mk run_cmd script_check_id `pprod run_cmd script_check_id `pprod.mk run_cmd script_check_id `pprod.fst run_cmd script_check_id `pprod.snd run_cmd script_check_id `propext run_cmd script_check_id `to_pexpr run_cmd script_check_id `quot.mk run_cmd script_check_id `quot.lift run_cmd script_check_id `real run_cmd script_check_id `real.of_int run_cmd script_check_id `real.to_int run_cmd script_check_id `real.is_int run_cmd script_check_id `real.has_neg run_cmd script_check_id `real.has_div run_cmd script_check_id `real.has_add run_cmd script_check_id `real.has_mul run_cmd script_check_id `real.has_sub run_cmd script_check_id `real.has_lt run_cmd script_check_id `real.has_le run_cmd script_check_id `reflected run_cmd script_check_id `reflected.subst run_cmd script_check_id `repr run_cmd script_check_id `rfl run_cmd script_check_id `right_distrib run_cmd script_check_id `ring run_cmd script_check_id `scope_trace run_cmd script_check_id `set_of run_cmd script_check_id `semiring run_cmd script_check_id `psigma run_cmd script_check_id `psigma.cases_on run_cmd script_check_id `psigma.mk run_cmd script_check_id `psigma.fst run_cmd script_check_id `psigma.snd run_cmd script_check_id `singleton run_cmd script_check_id `sizeof run_cmd script_check_id `smt.array run_cmd script_check_id `smt.select run_cmd script_check_id `smt.store run_cmd script_check_id `smt.prove run_cmd script_check_id `string run_cmd script_check_id `string.empty run_cmd script_check_id `string.str run_cmd script_check_id `string.empty_ne_str run_cmd script_check_id `string.str_ne_empty run_cmd script_check_id `string.str_ne_str_left run_cmd script_check_id `string.str_ne_str_right run_cmd script_check_id `subsingleton run_cmd script_check_id `subsingleton.elim run_cmd script_check_id `subsingleton.helim run_cmd script_check_id `subtype run_cmd script_check_id `subtype.mk run_cmd script_check_id `subtype.val run_cmd script_check_id `subtype.rec run_cmd script_check_id `psum run_cmd script_check_id `psum.cases_on run_cmd script_check_id `psum.inl run_cmd script_check_id `psum.inr run_cmd script_check_id `tactic run_cmd script_check_id `tactic.try run_cmd script_check_id `tactic.triv run_cmd script_check_id `thunk run_cmd script_check_id `to_fmt run_cmd script_check_id `trans_rel_left run_cmd script_check_id `trans_rel_right run_cmd script_check_id `true run_cmd script_check_id `true.intro run_cmd script_check_id `unification_hint run_cmd script_check_id `unification_hint.mk run_cmd script_check_id `unit run_cmd script_check_id `unit.cases_on run_cmd script_check_id `unit.star run_cmd script_check_id `unsafe_monad_from_pure_bind run_cmd script_check_id `user_attribute run_cmd script_check_id `user_attribute.parse_reflect run_cmd script_check_id `vm_monitor run_cmd script_check_id `partial_order run_cmd script_check_id `well_founded.fix run_cmd script_check_id `well_founded.fix_eq run_cmd script_check_id `well_founded_tactics run_cmd script_check_id `well_founded_tactics.default run_cmd script_check_id `well_founded_tactics.rel_tac run_cmd script_check_id `well_founded_tactics.dec_tac run_cmd script_check_id `xor run_cmd script_check_id `zero_le_one run_cmd script_check_id `zero_lt_one run_cmd script_check_id `zero_mul
1d801c42defd38fec3d1c4061ca194b8c595f9e3
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/id.lean
6ec79681143201cf77480778236e6435f2ffbbac
[ "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
199
lean
import logic definition id {A : Type} (a : A) := a check id id set_option pp.universes true check id id check id Prop check id num check @id.{0} check @id.{1} check id num.zero check @eq check eq eq
9375c8dd7ef88fe72787ad7345decd2bce6ec9e7
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/module/pi.lean
40d470756995d15e7dd60f649a576999a8c596df
[ "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
3,418
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import algebra.module.basic import algebra.regular.smul import algebra.ring.pi import group_theory.group_action.pi /-! # Pi instances for modules This file defines instances for module and related structures on Pi Types -/ universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) namespace pi lemma _root_.is_smul_regular.pi {α : Type*} [Π i, has_smul α $ f i] {k : α} (hk : Π i, is_smul_regular (f i) k) : is_smul_regular (Π i, f i) k := λ _ _ h, funext $ λ i, hk i (congr_fun h i : _) instance smul_with_zero (α) [has_zero α] [Π i, has_zero (f i)] [Π i, smul_with_zero α (f i)] : smul_with_zero α (Π i, f i) := { smul_zero := λ _, funext $ λ _, smul_zero' (f _) _, zero_smul := λ _, funext $ λ _, zero_smul _ _, ..pi.has_smul } instance smul_with_zero' {g : I → Type*} [Π i, has_zero (g i)] [Π i, has_zero (f i)] [Π i, smul_with_zero (g i) (f i)] : smul_with_zero (Π i, g i) (Π i, f i) := { smul_zero := λ _, funext $ λ _, smul_zero' (f _) _, zero_smul := λ _, funext $ λ _, zero_smul _ _, ..pi.has_smul' } instance mul_action_with_zero (α) [monoid_with_zero α] [Π i, has_zero (f i)] [Π i, mul_action_with_zero α (f i)] : mul_action_with_zero α (Π i, f i) := { ..pi.mul_action _, ..pi.smul_with_zero _ } instance mul_action_with_zero' {g : I → Type*} [Π i, monoid_with_zero (g i)] [Π i, has_zero (f i)] [Π i, mul_action_with_zero (g i) (f i)] : mul_action_with_zero (Π i, g i) (Π i, f i) := { ..pi.mul_action', ..pi.smul_with_zero' } variables (I f) instance module (α) {r : semiring α} {m : ∀ i, add_comm_monoid $ f i} [∀ i, module α $ f i] : @module α (Π i : I, f i) r (@pi.add_comm_monoid I f m) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } /- Extra instance to short-circuit type class resolution. For unknown reasons, this is necessary for certain inference problems. E.g., for this to succeed: ```lean example (β X : Type*) [normed_add_comm_group β] [normed_space ℝ β] : module ℝ (X → β) := infer_instance ``` See: https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Typeclass.20resolution.20under.20binders/near/281296989 -/ /-- A special case of `pi.module` for non-dependent types. Lean struggles to elaborate definitions elsewhere in the library without this. -/ instance _root_.function.module (α β : Type*) [semiring α] [add_comm_monoid β] [module α β] : module α (I → β) := pi.module _ _ _ variables {I f} instance module' {g : I → Type*} {r : Π i, semiring (f i)} {m : Π i, add_comm_monoid (g i)} [Π i, module (f i) (g i)] : module (Π i, f i) (Π i, g i) := { add_smul := by { intros, ext1, apply add_smul }, zero_smul := by { intros, ext1, apply zero_smul } } instance (α) {r : semiring α} {m : Π i, add_comm_monoid $ f i} [Π i, module α $ f i] [∀ i, no_zero_smul_divisors α $ f i] : no_zero_smul_divisors α (Π i : I, f i) := ⟨λ c x h, or_iff_not_imp_left.mpr (λ hc, funext (λ i, (smul_eq_zero.mp (congr_fun h i)).resolve_left hc))⟩ end pi
91f7ceaaa5600807b8e7f8c1a9e6c6d379c18a03
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/expr.lean
085fde1bbd1ce842a343b118cb60efe5fb1bddcf
[]
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,546
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.level import Mathlib.Lean3Lib.init.control.monad import Mathlib.Lean3Lib.init.meta.rb_map universes l namespace Mathlib /-- Column and line position in a Lean source file. -/ structure pos where line : ℕ column : ℕ protected instance pos.decidable_eq : DecidableEq pos := sorry /-- Auxiliary annotation for binders (Lambda and Pi). This information is only used for elaboration. The difference between `{}` and `⦃⦄` is how implicit arguments are treated that are *not* followed by explicit arguments. `{}` arguments are applied eagerly, while `⦃⦄` arguments are left partially applied: ```lean def foo {x : ℕ} : ℕ := x def bar ⦃x : ℕ⦄ : ℕ := x #check foo -- foo : ℕ #check bar -- bar : Π ⦃x : ℕ⦄, ℕ ``` -/ /- `(x : α)` -/ inductive binder_info where | default : binder_info | implicit : binder_info | strict_implicit : binder_info | inst_implicit : binder_info | aux_decl : binder_info /- `{x : α}` -/ /- `⦃x:α⦄` -/ /- `[x : α]`. Should be inferred with typeclass resolution. -/ /- Auxiliary internal attribute used to mark local constants representing recursive functions in recursive equations and `match` statements. -/ protected instance binder_info.has_repr : has_repr binder_info := has_repr.mk fun (bi : binder_info) => sorry
6f5d5393f7be6b62200cac23d2659b037c953641
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Elab/Term.lean
ac9390c65d830fb2e901e85dedabcaebc7673c91
[ "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
57,021
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Util.Sorry import Init.Lean.Structure import Init.Lean.Meta.ExprDefEq import Init.Lean.Meta.AppBuilder import Init.Lean.Meta.SynthInstance import Init.Lean.Meta.Tactic.Util import Init.Lean.Hygiene import Init.Lean.Util.RecDepth import Init.Lean.Elab.Log import Init.Lean.Elab.Alias import Init.Lean.Elab.ResolveName import Init.Lean.Elab.Level namespace Lean namespace Elab namespace Term structure Context extends Meta.Context := (fileName : String) (fileMap : FileMap) (cmdPos : String.Pos) (currNamespace : Name) (declName? : Option Name := none) (levelNames : List Name := []) (openDecls : List OpenDecl := []) (macroStack : MacroStack := []) (currMacroScope : MacroScope := firstFrontendMacroScope) /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ (mayPostpone : Bool := true) (errToSorry : Bool := true) /- If `macroStackAtErr == true`, we include it in error messages. -/ (macroStackAtErr : Bool := true) /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind -- typeclass instance search | typeClass -- Similar to typeClass, but error messages are different, -- we use "type mismatch" or "application type mismatch" (when `f?` is some) instead of "failed to synthesize" | coe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (macroStack : MacroStack) -- type defaulting (currently: defaulting numeric literals to `Nat`) | withDefault (defaultVal : Expr) structure SyntheticMVarDecl := (mvarId : MVarId) (ref : Syntax) (kind : SyntheticMVarKind) structure State extends Meta.State := (syntheticMVars : List SyntheticMVarDecl := []) (messages : MessageLog := {}) (instImplicitIdx : Nat := 1) (anonymousIdx : Nat := 1) (nextMacroScope : Nat := firstFrontendMacroScope + 1) instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _ }⟩ /- The Term elaborator monad has a special kind of exception `Exception.postpone` which is used by an elaboration function to notify the main driver that it should be tried later. Remark: `Exception.postpone` is used only when `mayPostpone == true` in the `Context`. -/ inductive Exception | ex : Elab.Exception → Exception | postpone : Exception instance Exception.inhabited : Inhabited Exception := ⟨Exception.postpone⟩ instance Exception.hasToString : HasToString Exception := ⟨fun ex => match ex with | Exception.postpone => "postponed" | Exception.ex ex => toString ex⟩ /- Term elaborator Monad. In principle, we could track statically which methods may postpone or not by having adding a Boolean parameter `mayPostpone` to `TermElabM`. This would be useful to ensure that `Exception.postpone` does not leak to `CommandElabM`, but we abandoned this design because it adds unnecessary complexity. -/ abbrev TermElabM := ReaderT Context (EStateM Exception State) abbrev TermElab := Syntax → Option Expr → TermElabM Expr instance TermElabM.inhabited {α} : Inhabited (TermElabM α) := ⟨throw $ Exception.postpone⟩ abbrev TermElabResult := EStateM.Result Message State Expr instance TermElabResult.inhabited : Inhabited TermElabResult := ⟨EStateM.Result.ok (arbitrary _) (arbitrary _)⟩ /-- Execute `x`, save resulting expression and new state. If `x` fails, then it also stores exception and new state. Remark: we do not capture `Exception.postpone`. -/ @[inline] def observing (x : TermElabM Expr) : TermElabM TermElabResult := fun ctx s => match x ctx s with | EStateM.Result.error (Exception.ex (Elab.Exception.error errMsg)) newS => EStateM.Result.ok (EStateM.Result.error errMsg newS) s | EStateM.Result.error Exception.postpone _ => EStateM.Result.error Exception.postpone s | EStateM.Result.error ex newS => EStateM.Result.error ex newS | EStateM.Result.ok e newS => EStateM.Result.ok (EStateM.Result.ok e newS) s /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult) : TermElabM Expr := match result with | EStateM.Result.ok e s => do set s; pure e | EStateM.Result.error errMsg s => do set s; throw (Exception.ex (Elab.Exception.error errMsg)) def getEnv : TermElabM Environment := do s ← get; pure s.env def getMCtx : TermElabM MetavarContext := do s ← get; pure s.mctx def getLCtx : TermElabM LocalContext := do ctx ← read; pure ctx.lctx def getLocalInsts : TermElabM LocalInstances := do ctx ← read; pure ctx.localInstances def getOptions : TermElabM Options := do ctx ← read; pure ctx.config.opts def setEnv (env : Environment) : TermElabM Unit := modify $ fun s => { s with env := env } def setMCtx (mctx : MetavarContext) : TermElabM Unit := modify $ fun s => { s with mctx := mctx } def addContext (msg : MessageData) : TermElabM MessageData := do env ← getEnv; mctx ← getMCtx; lctx ← getLCtx; opts ← getOptions; pure (MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msg) instance monadLog : MonadLog TermElabM := { getCmdPos := do ctx ← read; pure ctx.cmdPos, getFileMap := do ctx ← read; pure ctx.fileMap, getFileName := do ctx ← read; pure ctx.fileName, addContext := addContext, logMessage := fun msg => modify $ fun s => { s with messages := s.messages.add msg } } /-- Throws an error with the given `msgData` and extracting position information from `ref`. If `ref` does not contain position information, then use `cmdPos` -/ def throwError {α} (ref : Syntax) (msgData : MessageData) : TermElabM α := do ctx ← read; let ref := getBetterRef ref ctx.macroStack; let msgData := if ctx.macroStackAtErr then addMacroStack msgData ctx.macroStack else msgData; msg ← mkMessage msgData MessageSeverity.error ref; throw (Exception.ex (Elab.Exception.error msg)) def throwUnsupportedSyntax {α} : TermElabM α := throw (Exception.ex Elab.Exception.unsupportedSyntax) @[inline] def withIncRecDepth {α} (ref : Syntax) (x : TermElabM α) : TermElabM α := do ctx ← read; when (ctx.currRecDepth == ctx.maxRecDepth) $ throwError ref maxRecDepthErrorMessage; adaptReader (fun (ctx : Context) => { ctx with currRecDepth := ctx.currRecDepth + 1 }) x protected def getCurrMacroScope : TermElabM MacroScope := do ctx ← read; pure ctx.currMacroScope protected def getMainModule : TermElabM Name := do env ← getEnv; pure env.mainModule @[inline] protected def withFreshMacroScope {α} (x : TermElabM α) : TermElabM α := do fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })); adaptReader (fun (ctx : Context) => { ctx with currMacroScope := fresh }) x instance monadQuotation : MonadQuotation TermElabM := { getCurrMacroScope := Term.getCurrMacroScope, getMainModule := Term.getMainModule, withFreshMacroScope := @Term.withFreshMacroScope } unsafe def mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" @[init mkTermElabAttribute] constant termElabAttribute : KeyedDeclsAttribute TermElab := arbitrary _ /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`. Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/ inductive LVal | fieldIdx (i : Nat) | fieldName (name : String) | getOp (idx : Syntax) instance LVal.hasToString : HasToString LVal := ⟨fun p => match p with | LVal.fieldIdx i => toString i | LVal.fieldName n => n | LVal.getOp idx => "[" ++ toString idx ++ "]"⟩ def getDeclName? : TermElabM (Option Name) := do ctx ← read; pure ctx.declName? def getCurrNamespace : TermElabM Name := do ctx ← read; pure ctx.currNamespace def getOpenDecls : TermElabM (List OpenDecl) := do ctx ← read; pure ctx.openDecls def getTraceState : TermElabM TraceState := do s ← get; pure s.traceState def setTraceState (traceState : TraceState) : TermElabM Unit := modify $ fun s => { s with traceState := traceState } def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := do mctx ← getMCtx; pure $ mctx.isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := do mctx ← getMCtx; pure $ mctx.getDecl mvarId def assignExprMVar (mvarId : MVarId) (val : Expr) : TermElabM Unit := modify $ fun s => { s with mctx := s.mctx.assignExpr mvarId val } def logTrace (cls : Name) (ref : Syntax) (msg : MessageData) : TermElabM Unit := do ctx ← read; s ← get; logInfo ref $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } $ MessageData.tagged cls msg @[inline] def trace (cls : Name) (ref : Syntax) (msg : Unit → MessageData) : TermElabM Unit := do opts ← getOptions; when (checkTraceOption opts cls) $ logTrace cls ref (msg ()) def logDbgTrace (msg : MessageData) : TermElabM Unit := do trace `Elab.debug Syntax.missing $ fun _ => msg /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do s ← get; when s.messages.hasErrors $ throwError Syntax.missing "Error(s)" @[inline] def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := trace cls Syntax.missing msg def dbgTrace {α} [HasToString α] (a : α) : TermElabM Unit := _root_.dbgTrace (toString a) $ fun _ => pure () /-- Auxiliary function for `liftMetaM` -/ private def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos.getD ctx.cmdPos) /-- Auxiliary function for `liftMetaM` -/ private def fromMetaException (ctx : Context) (ref : Syntax) (ex : Meta.Exception) : Exception := Exception.ex $ Elab.Exception.error $ mkMessageAux ctx ref ex.toMessageData MessageSeverity.error /-- Auxiliary function for `liftMetaM` -/ private def fromMetaState (ref : Syntax) (ctx : Context) (s : State) (newS : Meta.State) (oldTraceState : TraceState) : State := let traces := newS.traceState.traces; let messages := traces.foldl (fun (messages : MessageLog) trace => messages.add (mkMessageAux ctx ref trace MessageSeverity.information)) s.messages; { s with toState := { newS with traceState := oldTraceState }, messages := messages } @[inline] def liftMetaM {α} (ref : Syntax) (x : MetaM α) : TermElabM α := fun ctx s => let oldTraceState := s.traceState; match x ctx.toContext { s.toState with traceState := {} } with | EStateM.Result.ok a newS => EStateM.Result.ok a (fromMetaState ref ctx s newS oldTraceState) | EStateM.Result.error ex newS => EStateM.Result.error (fromMetaException ctx ref ex) (fromMetaState ref ctx s newS oldTraceState) def ppGoal (ref : Syntax) (mvarId : MVarId) : TermElabM Format := liftMetaM ref $ Meta.ppGoal mvarId def isType (ref : Syntax) (e : Expr) : TermElabM Bool := liftMetaM ref $ Meta.isType e def isTypeFormer (ref : Syntax) (e : Expr) : TermElabM Bool := liftMetaM ref $ Meta.isTypeFormer e def isDefEqNoConstantApprox (ref : Syntax) (t s : Expr) : TermElabM Bool := liftMetaM ref $ Meta.approxDefEq $ Meta.isDefEq t s def isDefEq (ref : Syntax) (t s : Expr) : TermElabM Bool := liftMetaM ref $ Meta.fullApproxDefEq $ Meta.isDefEq t s def inferType (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.inferType e def whnf (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnf e def whnfForall (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnfForall e def whnfCore (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnfCore e def unfoldDefinition? (ref : Syntax) (e : Expr) : TermElabM (Option Expr) := liftMetaM ref $ Meta.unfoldDefinition? e def instantiateMVars (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.instantiateMVars e def isClass (ref : Syntax) (t : Expr) : TermElabM (Option Name) := liftMetaM ref $ Meta.isClass t def mkFreshLevelMVar (ref : Syntax) : TermElabM Level := liftMetaM ref $ Meta.mkFreshLevelMVar def mkFreshExprMVar (ref : Syntax) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName? : Name := Name.anonymous) : TermElabM Expr := match type? with | some type => liftMetaM ref $ Meta.mkFreshExprMVar type userName? kind | none => liftMetaM ref $ do u ← Meta.mkFreshLevelMVar; type ← Meta.mkFreshExprMVar (mkSort u); Meta.mkFreshExprMVar type userName? kind def mkFreshTypeMVar (ref : Syntax) (kind : MetavarKind := MetavarKind.natural) (userName? : Name := Name.anonymous) : TermElabM Expr := liftMetaM ref $ do u ← Meta.mkFreshLevelMVar; Meta.mkFreshExprMVar (mkSort u) userName? kind def getLevel (ref : Syntax) (type : Expr) : TermElabM Level := liftMetaM ref $ Meta.getLevel type def mkForall (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkForall xs e def mkForallUsedOnly (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM (Expr × Nat) := liftMetaM ref $ Meta.mkForallUsedOnly xs e def mkLambda (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkLambda xs e def mkLet (ref : Syntax) (x : Expr) (e : Expr) : TermElabM Expr := mkLambda ref #[x] e def trySynthInstance (ref : Syntax) (type : Expr) : TermElabM (LOption Expr) := liftMetaM ref $ Meta.trySynthInstance type def mkAppM (ref : Syntax) (constName : Name) (args : Array Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkAppM constName args def mkExpectedTypeHint (ref : Syntax) (e : Expr) (expectedType : Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkExpectedTypeHint e expectedType def decLevel? (ref : Syntax) (u : Level) : TermElabM (Option Level) := liftMetaM ref $ Meta.decLevel? u def decLevel (ref : Syntax) (u : Level) : TermElabM Level := do u? ← decLevel? ref u; match u? with | some u => pure u | none => throwError ref ("invalid universe level, " ++ u ++ " is not greater than 0") /- This function is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`. Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level, and then decrement 1 to obtain `u`. -/ def getDecLevel (ref : Syntax) (type : Expr) : TermElabM Level := do u ← getLevel ref type; decLevel ref u @[inline] def savingMCtx {α} (x : TermElabM α) : TermElabM α := do mctx ← getMCtx; finally x (modify $ fun s => { s with mctx := mctx }) def liftLevelM {α} (x : LevelElabM α) : TermElabM α := fun ctx s => let lvlCtx : Level.Context := { fileName := ctx.fileName, fileMap := ctx.fileMap, cmdPos := ctx.cmdPos, levelNames := ctx.levelNames }; match (x lvlCtx).run { ngen := s.ngen, mctx := s.mctx } with | EStateM.Result.ok a newS => EStateM.Result.ok a { s with mctx := newS.mctx, ngen := newS.ngen } | EStateM.Result.error ex newS => EStateM.Result.error (Exception.ex ex) s def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx @[inline] def withConfig {α} (f : Meta.Config → Meta.Config) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { ctx with config := f ctx.config }) x @[inline] def withTransparency {α} (mode : Meta.TransparencyMode) (x : TermElabM α) : TermElabM α := withConfig (fun config => { config with transparency := mode }) x @[inline] def withReducible {α} (x : TermElabM α) : TermElabM α := withTransparency Meta.TransparencyMode.reducible x /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (ref : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := modify $ fun s => { s with syntheticMVars := { mvarId := mvarId, ref := ref, kind := kind } :: s.syntheticMVars } /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ @[inline] def withoutPostponing {α} (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode `Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. -/ def levelMVarToParam (e : Expr) : TermElabM Expr := do ctx ← read; mctx ← getMCtx; let r := mctx.levelMVarToParam (fun n => ctx.levelNames.elem n) e; modify $ fun s => { s with mctx := r.mctx }; pure r.expr /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshAnonymousName : TermElabM Name := do s ← get; let anonymousIdx := s.anonymousIdx; modify $ fun s => { s with anonymousIdx := s.anonymousIdx + 1 }; pure $ (`_a).appendIndexAfter anonymousIdx /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshAnonymousName`. -/ def mkFreshAnonymousIdent (ref : Syntax) : TermElabM Syntax := do n ← mkFreshAnonymousName; pure $ mkIdentFrom ref n /-- Auxiliary method for creating binder names for local instances. Users expect them to be named as `_inst_<idx>`. -/ def mkFreshInstanceName : TermElabM Name := do s ← get; let instIdx := s.instImplicitIdx; modify $ fun s => { s with instImplicitIdx := s.instImplicitIdx + 1 }; pure $ (`_inst).appendIndexAfter instIdx private partial def hasCDot : Syntax → Bool | Syntax.node k args => if k == `Lean.Parser.Term.paren then false else if k == `Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Auxiliary function for expandind the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ private partial def expandCDot : Syntax → StateT (Array Syntax) MacroM Syntax | stx@(Syntax.node k args) => if k == `Lean.Parser.Term.paren then pure stx else if k == `Lean.Parser.Term.cdot then withFreshMacroScope $ do id ← `(a); modify $ fun s => s.push id; pure id else do args ← args.mapM expandCDot; pure $ Syntax.node k args | stx => pure stx /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := if hasCDot stx then do (newStx, binders) ← (expandCDot stx).run #[]; `(fun $binders* => $newStx) else pure none def mkFreshFVarId : TermElabM Name := do s ← get; let id := s.ngen.curr; modify $ fun s => { s with ngen := s.ngen.next }; pure id def withLocalDecl {α} (ref : Syntax) (n : Name) (binderInfo : BinderInfo) (type : Expr) (k : Expr → TermElabM α) : TermElabM α := do fvarId ← mkFreshFVarId; ctx ← read; let lctx := ctx.lctx.mkLocalDecl fvarId n type binderInfo; let localInsts := ctx.localInstances; let fvar := mkFVar fvarId; c? ← isClass ref type; match c? with | some c => adaptReader (fun (ctx : Context) => { ctx with lctx := lctx, localInstances := localInsts.push { className := c, fvar := fvar } }) $ k fvar | none => adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ k fvar def withLetDecl {α} (ref : Syntax) (n : Name) (type : Expr) (val : Expr) (k : Expr → TermElabM α) : TermElabM α := do fvarId ← mkFreshFVarId; ctx ← read; let lctx := ctx.lctx.mkLetDecl fvarId n type val; let localInsts := ctx.localInstances; let fvar := mkFVar fvarId; c? ← isClass ref type; match c? with | some c => adaptReader (fun (ctx : Context) => { ctx with lctx := lctx, localInstances := localInsts.push { className := c, fvar := fvar } }) $ k fvar | none => adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ k fvar def throwTypeMismatchError {α} (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; match f? with | none => let msg : MessageData := "type mismatch" ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType ++ Format.line ++ "but it is expected to have type" ++ indentExpr expectedType ++ extraMsg; throwError ref msg | some f => do env ← getEnv; mctx ← getMCtx; lctx ← getLCtx; opts ← getOptions; throwError ref $ Meta.Exception.mkAppTypeMismatchMessage f e { env := env, mctx := mctx, lctx := lctx, opts := opts } ++ extraMsg @[inline] def withoutMacroStackAtErr {α} (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { ctx with macroStackAtErr := false }) x /- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (ref : Syntax) (instMVar : MVarId) : TermElabM Bool := do instMVarDecl ← getMVarDecl instMVar; let type := instMVarDecl.type; type ← instantiateMVars ref type; result ← trySynthInstance ref type; match result with | LOption.some val => do condM (isExprMVarAssigned instMVar) (do oldVal ← instantiateMVars ref (mkMVar instMVar); unlessM (isDefEq ref oldVal val) $ throwError ref $ "synthesized type class instance is not definitionally equal to expression " ++ "inferred by typing rules, synthesized" ++ indentExpr val ++ Format.line ++ "inferred" ++ indentExpr oldVal) (assignExprMVar instMVar val); pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError ref ("failed to synthesize instance" ++ indentExpr type) /-- Try to apply coercion to make sure `e` has type `expectedType`. Relevant definitions: ``` class CoeT (α : Sort u) (a : α) (β : Sort v) abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β ``` -/ def tryCoe (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := condM (isDefEq ref expectedType eType) (pure e) $ do u ← getLevel ref eType; v ← getLevel ref expectedType; let coeTInstType := mkAppN (mkConst `CoeT [u, v]) #[eType, e, expectedType]; mvar ← mkFreshExprMVar ref coeTInstType MetavarKind.synthetic; let eNew := mkAppN (mkConst `coe [u, v]) #[eType, expectedType, e, mvar]; let mvarId := mvar.mvarId!; catch (withoutMacroStackAtErr $ do unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId (SyntheticMVarKind.coe expectedType eType e f?); pure eNew) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwTypeMismatchError ref expectedType eType e f? errMsg.data | _ => throwTypeMismatchError ref expectedType eType e f?) private def isTypeApp? (ref : Syntax) (type : Expr) : TermElabM (Option (Expr × Expr)) := do type ← withReducible $ whnf ref type; match type with | Expr.app m α _ => pure (some (m, α)) | _ => pure none structure IsMonadResult := (m : Expr) (α : Expr) (inst : Expr) private def isMonad? (ref : Syntax) (type : Expr) : TermElabM (Option IsMonadResult) := do type ← withReducible $ whnf ref type; match type with | Expr.app m α _ => catch (do monadType ← mkAppM ref `Monad #[m]; result ← trySynthInstance ref monadType; match result with | LOption.some inst => pure (some { m := m, α := α, inst := inst }) | _ => pure none) (fun _ => pure none) | _ => pure none def synthesizeInst (ref : Syntax) (type : Expr) : TermElabM Expr := do type ← instantiateMVars ref type; result ← trySynthInstance ref type; match result with | LOption.some val => pure val | LOption.undef => throwError ref ("failed to synthesize instance" ++ indentExpr type) | LOption.none => throwError ref ("failed to synthesize instance" ++ indentExpr type) /-- Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`. The method is only applied if the head of `α` nor ‵β` is not a metavariable. -/ private def tryPureCoe? (ref : Syntax) (m β α a : Expr) : TermElabM (Option Expr) := if β.getAppFn.isMVar || α.getAppFn.isMVar then pure none else catch (do aNew ← tryCoe ref β α a none; aNew ← liftMetaM ref $ Meta.mkPure m aNew; pure $ some aNew) (fun _ => pure none) /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n β` where `n` is a Monad, we try monad lifts and other extensions. Otherwise, we just use the basic `tryCoe`. Extensions for monads. Given an expected type of the form `n β`, if `eType` is of the form `α` 1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`. If `eType` is of the form `m α`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we rely on `tryCoe`, and the instances ``` instance coeMethod {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] : Coe (m α) (m β) instance pureCoeDepProp {m : Type → Type v} [HasPure m] {p : Prop} [Decidable p] : CoeDep (m Prop) (pure p) (m Bool) ``` 2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use ``` liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : HasMonadLiftT m n] {α : Type u_1}, m α → n α ``` 3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use ``` liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [HasMonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β ``` Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`. This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)` using the instance `pureCoeDepProp`. Note that, approach 2 is more powerful than `tryCoe`. Recall that type class resolution never assigns metavariables created by other modules. Now, consider the following scenario ```lean def g (x : Nat) : IO Nat := ... deg h (x : Nat) : StateT Nat IO Nat := do v ← g x; IO.Println v; ... ``` Let's assume there is no other occurrence of `v` in `h`. Thus, we have that the expected of `g x` is `StateT Nat IO ?α`, and the given type is `IO Nat`. So, even if we add a coercion. ``` instance {α m n} [HasLiftT m n] {α} : Coe (m α) (n α) := ... ``` It is not applicable because TC would have to assign `?α := Nat`. On the other hand, TC can easily solve `[HasLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ def tryLiftAndCoe (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do eType ← instantiateMVars ref eType; some ⟨n, β, monadInst⟩ ← isMonad? ref expectedType | tryCoe ref expectedType eType e f?; β ← instantiateMVars ref β; eNew? ← tryPureCoe? ref n β eType e; match eNew? with | some eNew => pure eNew | none => do some (m, α) ← isTypeApp? ref eType | tryCoe ref expectedType eType e f?; condM (isDefEq ref m n) (tryCoe ref expectedType eType e f?) $ catch (do -- Construct lift from `m` to `n` hasMonadLiftType ← mkAppM ref `HasMonadLiftT #[m, n]; hasMonadLiftVal ← synthesizeInst ref hasMonadLiftType; u_1 ← getDecLevel ref α; u_2 ← getDecLevel ref eType; u_3 ← getDecLevel ref expectedType; let eNew := mkAppN (Lean.mkConst `liftM [u_1, u_2, u_3]) #[m, n, hasMonadLiftVal, α, e]; eNewType ← inferType ref eNew; condM (isDefEq ref expectedType eNewType) (pure eNew) -- approach 2 worked (do u ← getLevel ref α; v ← getLevel ref β; let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst `CoeT [u, v]) #[α, mkBVar 0, β]; coeTInstVal ← synthesizeInst ref coeTInstType; let eNew := mkAppN (Lean.mkConst `liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, hasMonadLiftVal, coeTInstVal, monadInst, e]; eNewType ← inferType ref eNew; condM (isDefEq ref expectedType eNewType) (pure eNew) -- approach 3 worked (throwTypeMismatchError ref expectedType eType e f?))) (fun _ => throwTypeMismatchError ref expectedType eType e f?) /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasTypeAux (ref : Syntax) (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) : TermElabM Expr := match expectedType? with | none => pure e | some expectedType => /- Recall that constant approximation is used to solve constraint of the form ``` ?m t =?= s ``` where `t` is an arbitrary term, by assigning `?m := fun _ => s` This approximation when not used carefully produces bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, not first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure 0; f () ``` with expected type `StateT Nat Id Nat`. In this example, the following unification contraint is generated. ``` ?m () (?n ()) =?= StateT Nat Id Nat ``` It is not a higher-order pattern, and first-order approximation fails. However, constant approximation solves it by assigning ``` ?m := fun _ => StateT Nat Id ?n := fun _ => Nat ``` Note that `f`s type is `(x : ?α) -> ?m x (?n x)`. The metavariables `?m` and `?n` may depend on `x`. The `isDefEqNoConstantApprox` fails to unify the expected and inferred types. Then, `tryLiftAndCoe` first tries the monadic extensions, and then falls back to `isDefEq` which enables all approximations. -/ condM (isDefEqNoConstantApprox ref eType expectedType) (pure e) (tryLiftAndCoe ref expectedType eType e f?) /-- If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal. If they are not, then try coercions. -/ def ensureHasType (ref : Syntax) (expectedType? : Option Expr) (e : Expr) : TermElabM Expr := match expectedType? with | none => pure e | _ => do eType ← inferType ref e; ensureHasTypeAux ref expectedType? eType e private def exceptionToSorry (ref : Syntax) (errMsg : Message) (expectedType? : Option Expr) : TermElabM Expr := do expectedType : Expr ← match expectedType? with | none => mkFreshTypeMVar ref | some expectedType => pure expectedType; u ← getLevel ref expectedType; -- TODO: should be `(sorryAx.{$u} $expectedType true) when we support antiquotations at that place let syntheticSorry := mkApp2 (mkConst `sorryAx [u]) expectedType (mkConst `Bool.true); unless errMsg.data.hasSyntheticSorry $ logMessage errMsg; pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do ctx ← read; when ctx.mayPostpone $ throw Exception.postpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do when e.getAppFn.isMVar $ tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace `Elab.postpone stx $ fun _ => stx ++ " : " ++ expectedType?; mvar ← mkFreshExprMVar stx expectedType? MetavarKind.syntheticOpaque; ctx ← read; registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed ctx.macroStack); pure mvar /- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : State) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List TermElab → TermElabM Expr | [] => do let refFmt := stx.prettyPrint; throwError stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ refFmt)) | (elabFn::elabFns) => catch (elabFn stx expectedType?) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => do ctx ← read; if ctx.errToSorry then exceptionToSorry stx errMsg expectedType? else throw ex | Exception.ex Elab.Exception.unsupportedSyntax => do set s; elabUsingElabFnsAux elabFns | Exception.postpone => if catchExPostpone then do /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ set s; postponeElabTerm stx expectedType? else throw ex) def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do s ← get; let table := (termElabAttribute.ext.getState s.env).table; let k := stx.getKind; match table.find? k with | some elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns | none => throwError stx ("elaboration function for '" ++ toString k ++ "' has not been implemented") instance : MonadMacroAdapter TermElabM := { getEnv := getEnv, getCurrMacroScope := getCurrMacroScope, getNextMacroScope := do s ← get; pure s.nextMacroScope, setNextMacroScope := fun next => modify $ fun s => { s with nextMacroScope := next }, throwError := @throwError, throwUnsupportedSyntax := @throwUnsupportedSyntax} private def isExplicit (stx : Syntax) : Bool := match_syntax stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == `Lean.Parser.Term.app && isExplicit (stx.getArg 0) /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {α} (a : α) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match_syntax stx with | `(fun $binders* => $body) => binders.any $ fun b => b.isOfKind `Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false partial def dropTermParens : Syntax → Syntax | stx => match_syntax stx with | `(($stx)) => dropTermParens stx | _ => stx /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx; isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. -/ def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then pure none else match expectedType? with | some expectedType => do expectedType ← whnfForall stx expectedType; match expectedType with | Expr.forallE _ _ _ c => pure $ if c.binderInfo.isExplicit then none else some expectedType | _ => pure $ none | _ => pure $ none def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (fvars : Array Expr) : TermElabM Expr := do body ← elabUsingElabFns stx expectedType catchExPostpone; -- body ← ensureHasType stx expectedType body; r ← mkLambda stx fvars body; trace `Elab.implicitForall stx $ fun _ => r; pure r partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) : Expr → Array Expr → TermElabM Expr | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope $ do n ← MonadQuotation.addMacroScope n; withLocalDecl stx n c.binderInfo d $ fun fvar => do type ← whnfForall stx (b.instantiate1 fvar); elabImplicitLambda type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /- Main loop for `elabTerm` -/ partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | stx => withFreshMacroScope $ withIncRecDepth stx $ do trace `Elab.step stx $ fun _ => expectedType? ++ " " ++ stx; s ← get; stxNew? ← catch (do newStx ← adaptMacro (getMacros s.env) stx; pure (some newStx)) (fun ex => match ex with | Exception.ex Elab.Exception.unsupportedSyntax => pure none | _ => throw ex); match stxNew? with | some stxNew => withMacroExpansion stx stxNew $ elabTermAux stxNew | _ => do implicit? ← if implicitLambda then useImplicitLambda? stx expectedType? else pure none; match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType #[] | none => elabUsingElabFns stx expectedType? catchExPostpone /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) : TermElabM Expr := elabTermAux expectedType? catchExPostpone true stx def elabTermWithoutImplicitLambdas (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) : TermElabM Expr := do elabTermAux expectedType? catchExPostpone false stx /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do stx' ← exp stx; withMacroExpansion stx stx' $ elabTerm stx' expectedType? @[inline] def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { ctx with lctx := lctx, localInstances := localInsts }) x def resetSynthInstanceCache : TermElabM Unit := modify $ fun s => { s with cache := { s.cache with synthInstance := {} } } @[inline] def resettingSynthInstanceCache {α} (x : TermElabM α) : TermElabM α := do s ← get; let savedSythInstance := s.cache.synthInstance; resetSynthInstanceCache; finally x (modify $ fun s => { s with cache := { s.cache with synthInstance := savedSythInstance } }) @[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : TermElabM α) : TermElabM α := if b then resettingSynthInstanceCache x else x /-- Execute `x` using the given metavariable's `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def withMVarContext {α} (mvarId : MVarId) (x : TermElabM α) : TermElabM α := do mvarDecl ← getMVarDecl mvarId; ctx ← read; let needReset := ctx.localInstances == mvarDecl.localInstances; withLCtx mvarDecl.lctx mvarDecl.localInstances $ resettingSynthInstanceCacheWhen needReset x def mkInstMVar (ref : Syntax) (type : Expr) : TermElabM Expr := do mvar ← mkFreshExprMVar ref type MetavarKind.synthetic; let mvarId := mvar.mvarId!; unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId SyntheticMVarKind.typeClass; pure mvar /- Relevant definitions: ``` class CoeSort (α : Sort u) (β : outParam (Sort v)) abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β ``` -/ private def tryCoeSort (ref : Syntax) (α : Expr) (a : Expr) : TermElabM Expr := do β ← mkFreshTypeMVar ref; u ← getLevel ref α; v ← getLevel ref β; let coeSortInstType := mkAppN (Lean.mkConst `CoeSort [u, v]) #[α, β]; mvar ← mkFreshExprMVar ref coeSortInstType MetavarKind.synthetic; let mvarId := mvar.mvarId!; catch (withoutMacroStackAtErr $ condM (synthesizeInstMVarCore ref mvarId) (pure $ mkAppN (Lean.mkConst `coeSort [u, v]) #[α, β, a, mvar]) (throwError ref "type expected")) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwError ref ("type expected" ++ Format.line ++ errMsg.data) | _ => throwError ref "type expected") /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (ref : Syntax) (e : Expr) : TermElabM Expr := condM (isType ref e) (pure e) (do eType ← inferType ref e; u ← mkFreshLevelMVar ref; condM (isDefEq ref eType (mkSort u)) (pure e) (tryCoeSort ref eType e)) /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do u ← mkFreshLevelMVar stx; type ← elabTerm stx (mkSort u); ensureType stx type def addDecl (ref : Syntax) (decl : Declaration) : TermElabM Unit := do env ← getEnv; match env.addDecl decl with | Except.ok env => setEnv env | Except.error kex => do opts ← getOptions; throwError ref (kex.toMessageData opts) def compileDecl (ref : Syntax) (decl : Declaration) : TermElabM Unit := do env ← getEnv; opts ← getOptions; match env.compileDecl opts decl with | Except.ok env => setEnv env | Except.error kex => throwError ref (kex.toMessageData opts) private partial def mkAuxNameAux (env : Environment) (base : Name) : Nat → Name | i => let candidate := base.appendIndexAfter i; if env.contains candidate then mkAuxNameAux (i+1) else candidate def mkAuxName (ref : Syntax) (suffix : Name) : TermElabM Name := do env ← getEnv; ctx ← read; match ctx.declName? with | none => throwError ref "auxiliary declaration cannot be created when declaration name is not available" | some declName => pure $ mkAuxNameAux env (declName ++ suffix) 1 /- ======================================= Builtin elaboration functions ======================================= -/ @[builtinTermElab «prop»] def elabProp : TermElab := fun _ _ => pure $ mkSort levelZero @[builtinTermElab «sort»] def elabSort : TermElab := fun _ _ => pure $ mkSort levelZero @[builtinTermElab «type»] def elabTypeStx : TermElab := fun _ _ => pure $ mkSort levelOne @[builtinTermElab «hole»] def elabHole : TermElab := fun stx expectedType? => mkFreshExprMVar stx expectedType? @[builtinTermElab «namedHole»] def elabNamedHole : TermElab := fun stx expectedType? => let name := stx.getIdAt 1; mkFreshExprMVar stx expectedType? MetavarKind.syntheticOpaque name def mkTacticMVar (ref : Syntax) (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do mvar ← mkFreshExprMVar ref type MetavarKind.syntheticOpaque `main; let mvarId := mvar.mvarId!; registerSyntheticMVar ref mvarId $ SyntheticMVarKind.tactic tacticCode; pure mvar @[builtinTermElab tacticBlock] def elabTacticBlock : TermElab := fun stx expectedType? => match expectedType? with | some expectedType => mkTacticMVar stx expectedType (stx.getArg 1) | none => throwError stx ("invalid tactic block, expected type has not been provided") @[builtinTermElab byTactic] def elabByTactic : TermElab := fun stx expectedType? => match expectedType? with | some expectedType => mkTacticMVar stx expectedType (stx.getArg 1) | none => throwError stx ("invalid 'by' tactic, expected type has not been provided") /-- Main loop for `mkPairs`. -/ private partial def mkPairsAux (elems : Array Syntax) : Nat → Syntax → MacroM Syntax | i, acc => if i > 0 then do let i := i - 1; let elem := elems.get! i; acc ← `(Prod.mk $elem $acc); mkPairsAux i acc else pure acc /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ def mkPairs (elems : Array Syntax) : MacroM Syntax := mkPairsAux elems (elems.size - 1) elems.back /-- Try to expand `·` notation, and if successful elaborate result. This method is used to elaborate the Lean parentheses notation. Recall that in Lean the `·` notation must be surrounded by parentheses. We may change this is the future, but right now, here are valid examples - `(· + 1)` - `(f ⟨·, 1⟩ ·)` - `(· + ·)` - `(f · a b)` -/ private def elabCDot (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do stx? ← liftMacroM $ expandCDot? stx; match stx? with | some stx' => withMacroExpansion stx stx' (elabTerm stx' expectedType?) | none => elabTerm stx expectedType? @[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => let ref := stx; match_syntax ref with | `(()) => pure $ Lean.mkConst `Unit.unit | `(($e : $type)) => do type ← elabType type; e ← elabCDot e type; ensureHasType ref type e | `(($e)) => elabCDot e expectedType? | `(($e, $es*)) => do pairs ← liftMacroM $ mkPairs (#[e] ++ es.getEvenElems); withMacroExpansion stx pairs (elabTerm pairs expectedType?) | _ => throwError stx "unexpected parentheses notation" @[builtinTermElab «listLit»] def elabListLit : TermElab := fun stx expectedType? => do let openBkt := stx.getArg 0; let args := stx.getArg 1; let closeBkt := stx.getArg 2; let consId := mkTermIdFrom openBkt `List.cons; let nilId := mkTermIdFrom closeBkt `List.nil; let newStx := args.foldSepRevArgs (fun arg r => mkAppStx consId #[arg, r]) nilId; withMacroExpansion stx newStx $ elabTerm newStx expectedType? @[builtinTermElab «arrayLit»] def elabArrayLit : TermElab := fun stx expectedType? => do match_syntax stx with | `(#[$args*]) => do newStx ← `(List.toArray [$args*]); withMacroExpansion stx newStx (elabTerm newStx expectedType?) | _ => throwError stx "unexpected array literal syntax" private partial def resolveLocalNameAux (lctx : LocalContext) : Name → List String → Option (Expr × List String) | n, projs => match lctx.findFromUserName? n with | some decl => some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => resolveLocalNameAux pre (s::projs) | _ => none private def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do lctx ← getLCtx; pure $ resolveLocalNameAux lctx n [] /- Return true iff `stx` is a `Term.id`, and it is local variable. -/ def isLocalTermId? (stx : Syntax) (relaxed : Bool := false) : TermElabM (Option Expr) := match stx.isTermId? relaxed with | some (Syntax.ident _ _ val _, _) => do r? ← resolveLocalName val; match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none private def mkFreshLevelMVars (ref : Syntax) (num : Nat) : TermElabM (List Level) := num.foldM (fun _ us => do u ← mkFreshLevelMVar ref; pure $ u::us) [] /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (ref : Syntax) (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do env ← getEnv; match env.find? constName with | none => throwError ref ("unknown constant '" ++ constName ++ "'") | some cinfo => if explicitLevels.length > cinfo.lparams.length then throwError ref ("too many explicit universe levels") else do let numMissingLevels := cinfo.lparams.length - explicitLevels.length; us ← mkFreshLevelMVars ref numMissingLevels; pure $ Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (ref : Syntax) (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do env ← getEnv; candidates.foldlM (fun result ⟨constName, projs⟩ => do -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. const ← mkConst ref constName explicitLevels; pure $ (const, projs) :: result) [] def resolveGlobalName (n : Name) : TermElabM (List (Name × List String)) := do env ← getEnv; currNamespace ← getCurrNamespace; openDecls ← getOpenDecls; pure (Lean.Elab.resolveGlobalName env currNamespace openDecls n) def resolveName (ref : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do result? ← resolveLocalName n; match result? with | some (e, projs) => do unless explicitLevels.isEmpty $ throwError ref ("invalid use of explicit universe parameters, '" ++ toString e.fvarId! ++ "' is a local"); pure [(e, projs)] | none => let process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do { when candidates.isEmpty $ do { mainModule ← getMainModule; let view := extractMacroScopes n; throwError ref ("unknown identifier '" ++ view.format mainModule ++ "'") }; mkConsts ref candidates explicitLevels }; if preresolved.isEmpty then do r ← resolveGlobalName n; process r else process preresolved @[builtinTermElab cdot] def elabBadCDot : TermElab := fun stx _ => throwError stx "invalid occurrence of `·` notation, it must be surrounded by parentheses (e.g. `(· + 1)`)" /- A raw literal is not a valid term, but it is nice to have a handler for them because it allows `macros` to insert them into terms. TODO: check whether we still need wrapper nodes around literals. -/ @[builtinTermElab strLit] def elabRawStrLit : TermElab := fun stx _ => do match stx.isStrLit? with | some val => pure $ mkStrLit val | none => throwError stx "ill-formed syntax" @[builtinTermElab str] def elabStr : TermElab := fun stx expectedType? => elabRawStrLit (stx.getArg 0) expectedType? /- See `elabRawStrLit` -/ @[builtinTermElab numLit] def elabRawNumLit : TermElab := fun stx expectedType? => do let ref := stx; val ← match stx.isNatLit? with | some val => pure (mkNatLit val) | none => throwError stx "ill-formed syntax"; typeMVar ← mkFreshTypeMVar ref MetavarKind.synthetic; registerSyntheticMVar ref typeMVar.mvarId! (SyntheticMVarKind.withDefault (Lean.mkConst `Nat)); match expectedType? with | some expectedType => do _ ← isDefEq ref expectedType typeMVar; pure () | _ => pure (); u ← getLevel ref typeMVar; u ← decLevel ref u; mvar ← mkInstMVar ref (mkApp (Lean.mkConst `HasOfNat [u]) typeMVar); pure $ mkApp3 (Lean.mkConst `HasOfNat.ofNat [u]) typeMVar mvar val @[builtinTermElab num] def elabNum : TermElab := fun stx expectedType? => elabRawNumLit (stx.getArg 0) expectedType? /- See `elabRawStrLit` -/ @[builtinTermElab charLit] def elabRawCharLit : TermElab := fun stx _ => do match stx.isCharLit? with | some val => pure $ mkApp (Lean.mkConst `Char.ofNat) (mkNatLit val.toNat) | none => throwError stx "ill-formed syntax" @[builtinTermElab char] def elabChar : TermElab := fun stx expectedType? => elabRawCharLit (stx.getArg 0) expectedType? @[builtinTermElab quotedName] def elabQuotedName : TermElab := fun stx _ => match (stx.getArg 0).isNameLit? with | some val => pure $ toExpr val | none => throwError stx "ill-formed syntax" instance MetaHasEval {α} [MetaHasEval α] : MetaHasEval (TermElabM α) := ⟨fun env opts x _ => do let ctx : Context := { config := { opts := opts }, fileName := "<TermElabM>", fileMap := arbitrary _, cmdPos := 0, currNamespace := Name.anonymous, currRecDepth := 0, maxRecDepth := getMaxRecDepth opts }; let showMessages (s : State) : IO Unit := do { s.messages.forM $ fun m => IO.println $ format m }; match x ctx { env := env } with | EStateM.Result.ok a s => do showMessages s; MetaHasEval.eval s.env opts a | EStateM.Result.error (Exception.ex (Elab.Exception.error err)) s => do showMessages s; throw (IO.userError (toString (format err))) | EStateM.Result.error (Exception.ex Elab.Exception.unsupportedSyntax) s => do showMessages s; throw (IO.userError "error: unsupported syntax") | EStateM.Result.error Exception.postpone s => do showMessages s; throw (IO.userError "error: elaborator postponed")⟩ end Term @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.postpone; registerTraceClass `Elab.coe; registerTraceClass `Elab.debug; pure () export Term (TermElabM) end Elab end Lean
d21c81e62d0cade93b503805fd858aa0848e80fe
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_2697.lean
78c85385be6695edb491c342e74830a97d6684b2
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
550
lean
import logic.basic variables {p q : Prop} local attribute [instance] classical.prop_decidable -- BEGIN example : ¬(p ∧ q) → ¬p ∨ ¬ q := begin rw ←not_imp_not, -- It suffices to prove the contrapositive, `¬(¬p ∨ ¬q) → ¬¬(p ∧ q)`. rw not_or_distrib, -- By De Morgan's Law `not_or_distrib`, it suffices to prove `¬¬p ∧ ¬¬q → ¬¬(p ∧ q)`. repeat {rw not_not}, -- By repeated double negation, it suffices to prove `p ∧ q → p ∧ q`. exact id, -- This follows by `id`, the reflexivity of implication. end -- END
f392bfde3f11580ad5538bbb6208bc1956f01ce9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/int/sqrt.lean
72aaef66385da09f93c769985a281cc74900420c
[ "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
1,163
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 data.nat.sqrt /-! # Square root of integers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the square root function on integers. `int.sqrt z` is the greatest integer `r` such that `r * r ≤ z`. If `z ≤ 0`, then `int.sqrt z = 0`. -/ namespace int /-- `sqrt z` is the square root of an integer `z`. If `z` is positive, it returns the largest integer `r` such that `r * r ≤ n`. If it is negative, it returns `0`. For example, `sqrt (-1) = 0`, `sqrt 1 = 1`, `sqrt 2 = 1` -/ @[pp_nodot] def sqrt (z : ℤ) : ℤ := nat.sqrt $ int.to_nat z theorem sqrt_eq (n : ℤ) : sqrt (n*n) = n.nat_abs := by rw [sqrt, ← nat_abs_mul_self, to_nat_coe_nat, nat.sqrt_eq] theorem exists_mul_self (x : ℤ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, ← int.coe_nat_mul, nat_abs_mul_self], λ h, ⟨sqrt x, h⟩⟩ theorem sqrt_nonneg (n : ℤ) : 0 ≤ sqrt n := coe_nat_nonneg _ end int
253aaf87417d73d54ac877715cd7be40494b9984
bdd56e6eb0f467437e368d613de75299495d4054
/src/ring_theory/algebra2.lean
604e56eb511766f0ecfc558fd90665f4d712c073
[]
no_license
truong111000/formalabstracts
49a04c268ccee136e48e24e9d5dcb6fedea4b53e
93a89a5c05c6fbc23eb9b914b60dcc353e609cd2
refs/heads/master
1,589,551,767,824
1,555,708,723,000
1,555,708,723,000
182,326,292
0
0
null
1,555,708,332,000
1,555,708,331,000
null
UTF-8
Lean
false
false
7,734
lean
import ..basic ring_theory.algebra linear_algebra.tensor_product ring_theory.ideal_operations category_theory.concrete_category open set universes u v w /- move to ideal-/ namespace ideal namespace quotient variables {α : Type*} {β : Type*} [comm_ring α] [comm_ring β] {S : ideal α} {T : ideal β} {f : α → β} {H : ∀ {{a : α}}, a ∈ S → f a ∈ T} -- replace lift def lift' (S : ideal α) (f : α → β) [is_add_group_hom f] (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S → β := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero (by simpa only [is_add_group_hom.sub f] using H _ h) def map (S : ideal α) (T : ideal β) (f : α → β) [is_add_group_hom f] (H : ∀ {{a : α}}, a ∈ S → f a ∈ T) : quotient S → quotient T := begin haveI : is_add_group_hom ((mk T : β → quotient T) ∘ f) := is_add_group_hom.comp _ _, refine ideal.quotient.lift' S (mk T ∘ f) _, intros x hx, refine ideal.quotient.eq.2 _, rw [sub_zero], exact H hx end @[simp] lemma map_mk' [is_add_group_hom f] (x : α) : map S T f H (mk S x) = mk T (f x) := rfl instance map.is_ring_hom [is_ring_hom f] : is_ring_hom (map S T f H) := by dsimp [map]; exact omitted end quotient end ideal /- move to module -/ section module variables {R : Type u} {S : Type*} [ring R] variables {M : Type*} [add_comm_group M] variables [module R M] instance smul.is_add_group_hom {r : R} : is_add_group_hom (λ x : M, r • x) := by refine_struct {..}; simp [smul_add] def quotient_add_group.quotient.module {s : set M} [normal_add_subgroup s] (h : ∀(r : R) {x : M}, x ∈ s → r • x ∈ s) : module R (quotient_add_group.quotient s) := { smul := λ r, quotient_add_group.map _ _ (λ(x : M), r • x) (λ x h', h r h'), smul_add := omitted, add_smul := omitted, mul_smul := omitted, one_smul := omitted, zero_smul := omitted, smul_zero := omitted } end module variables {R : Type u} {S : Type*} [comm_ring R] [comm_ring S] variables {M : Type*} {N : Type*} {A : Type*} [ring M] [ring N] [comm_ring A] variables [algebra R M] [algebra R N] [algebra R A] local notation M ` ⊗[`:100 R `] ` N:100 := tensor_product R M N namespace algebra /-- A R-module is an R-algebra if scalar multiplication commutes with multiplication -/ def of_module {R : Type u} {A : Type v} [comm_ring R] [ring A] [m : module R A] (h : ∀(r : R) (x y : A), r • x * y = x * r • y) : algebra R A := { to_fun := λ r, r • 1, hom := ⟨one_smul R 1, by { intros, rw [h, one_mul, mul_smul] }, λ x y, add_smul x y 1⟩, commutes' := by { intros, rw [h, one_mul, ←h, mul_one] }, smul_def' := by { intros, rw [h, one_mul] }, ..m } /-- The codomain of a ring homomorphism viewed as an algebra over the domain -/ def induced_algebra (f : R → S) [is_ring_hom f] : Type* := S instance (f : R → S) [is_ring_hom f] : comm_ring (induced_algebra f) := _inst_2 instance (f : R → S) [is_ring_hom f] : algebra R (induced_algebra f) := algebra.of_ring_hom f (by apply_instance) end algebra open algebra namespace alg_hom /-- A ring homomorphism induces an algebra homomorphism -/ protected def of_ring_hom (f : R → S) [is_ring_hom f] : R →ₐ[R] induced_algebra f := { to_fun := f, hom := by apply_instance, commutes' := λ r, rfl } end alg_hom open algebra namespace tensor_product /- short-ciruiting some type class inference -/ protected def add_comm_group' : add_comm_group (M ⊗[R] N) := by apply_instance protected def module' : module R (M ⊗[R] N) := by apply_instance local attribute [instance, priority 2000] tensor_product.add_comm_group' tensor_product.module' protected def lmap_add_comm_group : add_comm_group (M ⊗[R] N →ₗ[R] M ⊗[R] N) := by apply_instance protected def lmap_module : module R (M ⊗[R] N →ₗ[R] M ⊗[R] N) := by apply_instance local attribute [instance, priority 2000] tensor_product.lmap_add_comm_group tensor_product.lmap_module /-- The multiplication on the tensor product of two R-algebras as a bilinear map -/ protected def mul : M ⊗[R] N →ₗ[R] M ⊗[R] N →ₗ[R] M ⊗[R] N := begin refine tensor_product.lift ⟨λ m, ⟨λ n, _, omitted, omitted⟩, omitted, omitted⟩, refine tensor_product.lift ⟨λ m', ⟨λ n', _, omitted, omitted⟩, omitted, omitted⟩, exact tmul R (m * m') (n * n') end /-- The ring structure on the tensor product of two R-algebras -/ instance : ring (M ⊗[R] N) := { mul := λ x y, tensor_product.mul.to_fun x y, mul_assoc := omitted, one := tmul R 1 1, one_mul := omitted, mul_one := omitted, left_distrib := omitted, right_distrib := omitted, ..tensor_product.add_comm_group M N } /-- The algebra structure on the tensor product of two R-algebras -/ instance : algebra R (M ⊗[R] N) := algebra.of_module omitted end tensor_product namespace quotient def smul {I : ideal A} (r : R) : I.quotient → I.quotient := ideal.quotient.map _ _ (λ(x : A), r • x) (λ x h', by rw [smul_def]; exact I.mul_mem_left h') @[simp] lemma smul_mk {I : ideal A} (r : R) (x : A) : quotient.smul r (ideal.quotient.mk I x) = ideal.quotient.mk I (r • x) := by refl end quotient instance quotient.algebra (I : ideal A) : algebra R I.quotient := { smul := quotient.smul, smul_add := λ r x y, quotient.induction_on₂' x y $ λ a b, congr_arg (ideal.quotient.mk _) $ smul_add r a b, add_smul := λ r s x, quotient.induction_on' x $ λ a, congr_arg (ideal.quotient.mk _) $ add_smul r s a, mul_smul := λ r s x, quotient.induction_on' x $ λ a, congr_arg (ideal.quotient.mk _) $ mul_smul r s a, one_smul := λ x, quotient.induction_on' x $ λ a, congr_arg (ideal.quotient.mk _) $ by simp only [one_smul], zero_smul := λ x, quotient.induction_on' x $ λ a, congr_arg (ideal.quotient.mk _) $ by simp only [zero_smul], smul_zero := λ r, congr_arg (ideal.quotient.mk _) $ by simp only [smul_zero], to_fun := ideal.quotient.mk I ∘ algebra_map A, commutes' := λ r x, quotient.induction_on' x $ λ a, congr_arg (ideal.quotient.mk _) $ commutes r a, smul_def' := λ r x, quotient.induction_on' x $ λ a, congr_arg (ideal.quotient.mk _) $ smul_def r a } local attribute [instance, priority 0] classical.prop_decidable /-- An algebra `β` is finitely generated over a ring `α` if there is a finite subset `s` of `β` such that every element of `β` can be expressed as a polynomial in the elements of `s` with coefficients in `α` -/ def is_finitely_generated (α : Type u) [comm_ring α] (β : Type v) [comm_ring β] [algebra α β] : Prop := ∃(s : finset β), ∀(x : β), ∃(p : mv_polynomial {x // x ∈ s} α), p.eval₂ (algebra_map β) subtype.val = x /-- Every quotient algebra is finitely generated -/ lemma is_finitely_generated_quotient {α : Type u} [comm_ring α] {β : Type v} [comm_ring β] [algebra α β] [decidable_eq α] [decidable_eq β] (h : is_finitely_generated α β) (I : ideal β) : is_finitely_generated α (I.quotient) := omitted /-- The type of algebras over a fixed commutative ring. -/ structure Algebra (R : Type u) [comm_ring R] : Type max u (v+1) := (β : Type v) (ring : ring β) (algebra : algebra R β) attribute [instance] Algebra.ring Algebra.algebra instance : has_coe_to_sort (Algebra.{u v} R) := { S := Type v, coe := Algebra.β } -- instance Algebra.ring' (x : Algebra R) : ring x := by apply_instance -- instance Algebra.algebra' (x : Algebra R) : algebra R x := by apply_instance open category_theory /-- The category of algebras over a fixed commutative ring. -/ instance Algebra.category : category (Algebra.{u v} R) := { hom := λ a b, a.β →ₐ[R] b.β, id := λ a, alg_hom.id R a, comp := λ a b c f g, alg_hom.comp g f }
992860aa3915f5f61c354af6786468d593c84bdb
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/src/Lean/Elab/StructInst.lean
bfa99d8ef182c4768b7b91b229cd60f377b651e9
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,820
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.FindExpr import Lean.Elab.App import Lean.Elab.Binders import Lean.Elab.Quotation namespace Lean namespace Elab namespace Term namespace StructInst open Std (HashMap) open Meta /- parser! "{" >> optional (try (termParser >> "with")) >> sepBy structInstField ", " true >> optional ".." >> optional (" : " >> termParser) >> "}" -/ /- If `stx` is of the form `{ s with ... }` and `s` is not a local variable, expand into `let src := s; { src with ... }`. -/ private def expandNonAtomicExplicitSource (stx : Syntax) : TermElabM (Option Syntax) := withFreshMacroScope $ let sourceOpt := stx.getArg 1; if sourceOpt.isNone then pure none else do let source := sourceOpt.getArg 0; fvar? ← isLocalIdent? source; match fvar? with | some _ => pure none | none => do src ← `(src); let sourceOpt := sourceOpt.setArg 0 src; let stxNew := stx.setArg 1 sourceOpt; `(let src := $source; $stxNew) inductive Source | none -- structure instance source has not been provieded | implicit (stx : Syntax) -- `..` | explicit (stx : Syntax) (src : Expr) -- `src with` instance Source.inhabited : Inhabited Source := ⟨Source.none⟩ def Source.isNone : Source → Bool | Source.none => true | _ => false def setStructSourceSyntax (structStx : Syntax) : Source → Syntax | Source.none => (structStx.setArg 1 mkNullNode).setArg 3 mkNullNode | Source.implicit stx => (structStx.setArg 1 mkNullNode).setArg 3 stx | Source.explicit stx _ => (structStx.setArg 1 stx).setArg 3 mkNullNode private def getStructSource (stx : Syntax) : TermElabM Source := withRef stx $ let explicitSource := stx.getArg 1; let implicitSource := stx.getArg 3; if explicitSource.isNone && implicitSource.isNone then pure Source.none else if explicitSource.isNone then pure $ Source.implicit implicitSource else if implicitSource.isNone then do fvar? ← isLocalIdent? (explicitSource.getArg 0); match fvar? with | none => unreachable! -- expandNonAtomicExplicitSource must have been used when we get here | some src => pure $ Source.explicit explicitSource src else throwError "invalid structure instance `with` and `..` cannot be used together" /- We say a `{ ... }` notation is a `modifyOp` if it contains only one ``` def structInstArrayRef := parser! "[" >> termParser >>"]" ``` -/ private def isModifyOp? (stx : Syntax) : TermElabM (Option Syntax) := do let args := (stx.getArg 2).getArgs; s? ← args.foldSepByM (fun arg s? => /- Remark: the syntax for `structInstField` is ``` def structInstLVal := (ident <|> numLit <|> structInstArrayRef) >> many (group ("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstField := parser! structInstLVal >> " := " >> termParser ``` -/ let lval := arg.getArg 0; let k := lval.getKind; if k == `Lean.Parser.Term.structInstArrayRef then match s? with | none => pure (some arg) | some s => if s.getKind == `Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid {...} notation, at most one `[..]` at a given level" else throwErrorAt arg "invalid {...} notation, can't mix field and `[..]` at a given level" else match s? with | none => pure (some arg) | some s => if s.getKind == `Lean.Parser.Term.structInstArrayRef then throwErrorAt arg "invalid {...} notation, can't mix field and `[..]` at a given level" else pure s?) none; match s? with | none => pure none | some s => if (s.getArg 0).getKind == `Lean.Parser.Term.structInstArrayRef then pure s? else pure none private def elabModifyOp (stx modifyOp source : Syntax) (expectedType? : Option Expr) : TermElabM Expr := let continue (val : Syntax) : TermElabM Expr := do { let lval := modifyOp.getArg 0; let idx := lval.getArg 1; let self := source.getArg 0; stxNew ← `($(self).modifyOp (idx := $idx) (fun s => $val)); trace `Elab.struct.modifyOp fun _ => stx ++ "\n===>\n" ++ stxNew; withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? }; do trace `Elab.struct.modifyOp fun _ => modifyOp ++ "\nSource: " ++ source; let rest := modifyOp.getArg 1; if rest.isNone then do continue (modifyOp.getArg 3) else do s ← `(s); let valFirst := rest.getArg 0; let valFirst := if valFirst.getKind == `Lean.Parser.Term.structInstArrayRef then valFirst else valFirst.getArg 1; let restArgs := rest.getArgs; let valRest := mkNullNode (restArgs.extract 1 restArgs.size); let valField := modifyOp.setArg 0 valFirst; let valField := valField.setArg 1 valRest; let valSource := source.modifyArg 0 $ fun _ => s; let val := stx.setArg 1 valSource; let val := val.setArg 2 $ mkNullNode #[valField]; trace `Elab.struct.modifyOp fun _ => stx ++ "\nval: " ++ val; continue val /- Get structure name and elaborate explicit source (if available) -/ private def getStructName (stx : Syntax) (expectedType? : Option Expr) (sourceView : Source) : TermElabM Name := do tryPostponeIfNoneOrMVar expectedType?; let useSource : Unit → TermElabM Name := fun _ => match sourceView with | Source.explicit _ src => do srcType ← inferType src; srcType ← whnf srcType; tryPostponeIfMVar srcType; match srcType.getAppFn with | Expr.const constName _ _ => pure constName | _ => throwError ("invalid {...} notation, source type is not of the form (C ...)" ++ indentExpr srcType) | _ => throwError ("invalid {...} notation, expected type is not of the form (C ...)" ++ indentExpr expectedType?.get!); match expectedType? with | none => useSource () | some expectedType => do expectedType ← whnf expectedType; match expectedType.getAppFn with | Expr.const constName _ _ => pure constName | _ => useSource () inductive FieldLHS | fieldName (ref : Syntax) (name : Name) | fieldIndex (ref : Syntax) (idx : Nat) | modifyOp (ref : Syntax) (index : Syntax) instance FieldLHS.inhabited : Inhabited FieldLHS := ⟨FieldLHS.fieldName (arbitrary _) (arbitrary _)⟩ instance FieldLHS.hasFormat : HasFormat FieldLHS := ⟨fun lhs => match lhs with | FieldLHS.fieldName _ n => fmt n | FieldLHS.fieldIndex _ i => fmt i | FieldLHS.modifyOp _ i => "[" ++ i.prettyPrint ++ "]"⟩ inductive FieldVal (σ : Type) | term (stx : Syntax) : FieldVal | nested (s : σ) : FieldVal | default : FieldVal -- mark that field must be synthesized using default value structure Field (σ : Type) := (ref : Syntax) (lhs : List FieldLHS) (val : FieldVal σ) (expr? : Option Expr := none) instance Field.inhabited {σ} : Inhabited (Field σ) := ⟨⟨arbitrary _, [], FieldVal.term (arbitrary _), arbitrary _⟩⟩ def Field.isSimple {σ} : Field σ → Bool | { lhs := [_], .. } => true | _ => false inductive Struct | mk (ref : Syntax) (structName : Name) (fields : List (Field Struct)) (source : Source) instance Struct.inhabited : Inhabited Struct := ⟨⟨arbitrary _, arbitrary _, [], arbitrary _⟩⟩ abbrev Fields := List (Field Struct) def Struct.ref : Struct → Syntax | ⟨ref, _, _, _⟩ => ref def Struct.structName : Struct → Name | ⟨_, structName, _, _⟩ => structName def Struct.fields : Struct → Fields | ⟨_, _, fields, _⟩ => fields def Struct.source : Struct → Source | ⟨_, _, _, s⟩ => s def formatField (formatStruct : Struct → Format) (field : Field Struct) : Format := Format.joinSep field.lhs " . " ++ " := " ++ match field.val with | FieldVal.term v => v.prettyPrint | FieldVal.nested s => formatStruct s | FieldVal.default => "<default>" partial def formatStruct : Struct → Format | ⟨_, structName, fields, source⟩ => let fieldsFmt := Format.joinSep (fields.map (formatField formatStruct)) ", "; match source with | Source.none => "{" ++ fieldsFmt ++ "}" | Source.implicit _ => "{" ++ fieldsFmt ++ " .. }" | Source.explicit _ src => "{" ++ format src ++ " with " ++ fieldsFmt ++ "}" instance Struct.hasFormat : HasFormat Struct := ⟨formatStruct⟩ instance Struct.hasToString : HasToString Struct := ⟨toString ∘ format⟩ instance Field.hasFormat : HasFormat (Field Struct) := ⟨formatField formatStruct⟩ instance Field.hasToString : HasToString (Field Struct) := ⟨toString ∘ format⟩ /- Recall that `structInstField` elements have the form ``` def structInstField := parser! structInstLVal >> " := " >> termParser def structInstLVal := (ident <|> numLit <|> structInstArrayRef) >> many (("." >> (ident <|> numLit)) <|> structInstArrayRef) def structInstArrayRef := parser! "[" >> termParser >>"]" -/ -- Remark: this code relies on the fact that `expandStruct` only transforms `fieldLHS.fieldName` def FieldLHS.toSyntax (first : Bool) : FieldLHS → Syntax | FieldLHS.modifyOp stx _ => stx | FieldLHS.fieldName stx name => if first then mkIdentFrom stx name else mkNullNode #[mkAtomFrom stx ".", mkIdentFrom stx name] | FieldLHS.fieldIndex stx _ => if first then stx else mkNullNode #[mkAtomFrom stx ".", stx] def FieldVal.toSyntax : FieldVal Struct → Syntax | FieldVal.term stx => stx | _ => unreachable! def Field.toSyntax : Field Struct → Syntax | field => let stx := field.ref; let stx := stx.setArg 3 field.val.toSyntax; match field.lhs with | first::rest => let stx := stx.setArg 0 $ first.toSyntax true; let stx := stx.setArg 1 $ mkNullNode $ rest.toArray.map (FieldLHS.toSyntax false); stx | _ => unreachable! private def toFieldLHS (stx : Syntax) : Except String FieldLHS := if stx.getKind == `Lean.Parser.Term.structInstArrayRef then pure $ FieldLHS.modifyOp stx (stx.getArg 1) else -- Note that the representation of the first field is different. let stx := if stx.getKind == nullKind then stx.getArg 1 else stx; if stx.isIdent then pure $ FieldLHS.fieldName stx stx.getId else match stx.isFieldIdx? with | some idx => pure $ FieldLHS.fieldIndex stx idx | none => throw "unexpected structure syntax" private def mkStructView (stx : Syntax) (structName : Name) (source : Source) : Except String Struct := do let args := (stx.getArg 2).getArgs; let fieldsStx := args.filter $ fun arg => arg.getKind == `Lean.Parser.Term.structInstField; fields ← fieldsStx.toList.mapM $ fun fieldStx => do { let val := fieldStx.getArg 3; first ← toFieldLHS (fieldStx.getArg 0); rest ← (fieldStx.getArg 1).getArgs.toList.mapM toFieldLHS; pure $ ({ref := fieldStx, lhs := first :: rest, val := FieldVal.term val } : Field Struct) }; pure ⟨stx, structName, fields, source⟩ def Struct.modifyFieldsM {m : Type → Type} [Monad m] (s : Struct) (f : Fields → m Fields) : m Struct := match s with | ⟨ref, structName, fields, source⟩ => do fields ← f fields; pure ⟨ref, structName, fields, source⟩ @[inline] def Struct.modifyFields (s : Struct) (f : Fields → Fields) : Struct := Id.run $ s.modifyFieldsM f def Struct.setFields (s : Struct) (fields : Fields) : Struct := s.modifyFields $ fun _ => fields private def expandCompositeFields (s : Struct) : Struct := s.modifyFields $ fun fields => fields.map $ fun field => match field with | { lhs := FieldLHS.fieldName ref (Name.str Name.anonymous _ _) :: rest, .. } => field | { lhs := FieldLHS.fieldName ref n@(Name.str _ _ _) :: rest, .. } => let newEntries := n.components.map $ FieldLHS.fieldName ref; { field with lhs := newEntries ++ rest } | _ => field private def expandNumLitFields (s : Struct) : TermElabM Struct := s.modifyFieldsM $ fun fields => do env ← getEnv; let fieldNames := getStructureFields env s.structName; fields.mapM $ fun field => match field with | { lhs := FieldLHS.fieldIndex ref idx :: rest, .. } => if idx == 0 then throwErrorAt ref "invalid field index, index must be greater than 0" else if idx > fieldNames.size then throwErrorAt ref ("invalid field index, structure has only #" ++ toString fieldNames.size ++ " fields") else pure { field with lhs := FieldLHS.fieldName ref (fieldNames.get! $ idx - 1) :: rest } | _ => pure field /- For example, consider the following structures: ``` structure A := (x : Nat) structure B extends A := (y : Nat) structure C extends B := (z : Bool) ``` This method expands parent structure fields using the path to the parent structure. For example, ``` { x := 0, y := 0, z := true : C } ``` is expanded into ``` { toB.toA.x := 0, toB.y := 0, z := true : C } ``` -/ private def expandParentFields (s : Struct) : TermElabM Struct := do env ← getEnv; s.modifyFieldsM $ fun fields => fields.mapM $ fun field => match field with | { lhs := FieldLHS.fieldName ref fieldName :: rest, .. } => match findField? env s.structName fieldName with | none => throwErrorAt ref ("'" ++ fieldName ++ "' is not a field of structure '" ++ s.structName ++ "'") | some baseStructName => if baseStructName == s.structName then pure field else match getPathToBaseStructure? env baseStructName s.structName with | some path => do let path := path.map $ fun funName => match funName with | Name.str _ s _ => FieldLHS.fieldName ref (mkNameSimple s) | _ => unreachable!; pure { field with lhs := path ++ field.lhs } | _ => throwErrorAt ref ("failed to access field '" ++ fieldName ++ "' in parent structure") | _ => pure field private abbrev FieldMap := HashMap Name Fields private def mkFieldMap (fields : Fields) : TermElabM FieldMap := fields.foldlM (fun fieldMap field => match field.lhs with | FieldLHS.fieldName _ fieldName :: rest => match fieldMap.find? fieldName with | some (prevField::restFields) => if field.isSimple || prevField.isSimple then throwErrorAt field.ref ("field '" ++ fieldName ++ "' has already beed specified") else pure $ fieldMap.insert fieldName (field::prevField::restFields) | _ => pure $ fieldMap.insert fieldName [field] | _ => unreachable!) {} private def isSimpleField? : Fields → Option (Field Struct) | [field] => if field.isSimple then some field else none | _ => none private def getFieldIdx (structName : Name) (fieldNames : Array Name) (fieldName : Name) : TermElabM Nat := do match fieldNames.findIdx? $ fun n => n == fieldName with | some idx => pure idx | none => throwError ("field '" ++ fieldName ++ "' is not a valid field of '" ++ structName ++ "'") private def mkProjStx (s : Syntax) (fieldName : Name) : Syntax := Syntax.node `Lean.Parser.Term.proj #[s, mkAtomFrom s ".", mkIdentFrom s fieldName] private def mkSubstructSource (structName : Name) (fieldNames : Array Name) (fieldName : Name) (src : Source) : TermElabM Source := match src with | Source.explicit stx src => do idx ← getFieldIdx structName fieldNames fieldName; let stx := stx.modifyArg 0 $ fun stx => mkProjStx stx fieldName; pure $ Source.explicit stx (mkProj structName idx src) | s => pure s @[specialize] private def groupFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do env ← getEnv; let fieldNames := getStructureFields env s.structName; withRef s.ref $ s.modifyFieldsM $ fun fields => do fieldMap ← mkFieldMap fields; fieldMap.toList.mapM $ fun ⟨fieldName, fields⟩ => match isSimpleField? fields with | some field => pure field | none => do let substructFields := fields.map $ fun field => { field with lhs := field.lhs.tail! }; substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source; let field := fields.head!; match Lean.isSubobjectField? env s.structName fieldName with | some substructName => do let substruct := Struct.mk s.ref substructName substructFields substructSource; substruct ← expandStruct substruct; pure { field with lhs := [field.lhs.head!], val := FieldVal.nested substruct } | none => do -- It is not a substructure field. Thus, we wrap fields using `Syntax`, and use `elabTerm` to process them. let valStx := s.ref; -- construct substructure syntax using s.ref as template let valStx := valStx.setArg 4 mkNullNode; -- erase optional expected type let args := substructFields.toArray.map $ Field.toSyntax; let valStx := valStx.setArg 2 (mkSepStx args (mkAtomFrom s.ref ",")); let valStx := setStructSourceSyntax valStx substructSource; pure { field with lhs := [field.lhs.head!], val := FieldVal.term valStx } def findField? (fields : Fields) (fieldName : Name) : Option (Field Struct) := fields.find? $ fun field => match field.lhs with | [FieldLHS.fieldName _ n] => n == fieldName | _ => false @[specialize] private def addMissingFields (expandStruct : Struct → TermElabM Struct) (s : Struct) : TermElabM Struct := do env ← getEnv; let fieldNames := getStructureFields env s.structName; let ref := s.ref; withRef ref do fields ← fieldNames.foldlM (fun fields fieldName => do match findField? s.fields fieldName with | some field => pure $ field::fields | none => let addField (val : FieldVal Struct) : TermElabM Fields := do { pure $ { ref := s.ref, lhs := [FieldLHS.fieldName s.ref fieldName], val := val } :: fields }; match Lean.isSubobjectField? env s.structName fieldName with | some substructName => do substructSource ← mkSubstructSource s.structName fieldNames fieldName s.source; let substruct := Struct.mk s.ref substructName [] substructSource; substruct ← expandStruct substruct; addField (FieldVal.nested substruct) | none => match s.source with | Source.none => addField FieldVal.default | Source.implicit _ => addField (FieldVal.term (mkHole s.ref)) | Source.explicit stx _ => -- stx is of the form `optional (try (termParser >> "with"))` let src := stx.getArg 0; let val := mkProjStx src fieldName; addField (FieldVal.term val)) []; pure $ s.setFields fields.reverse private partial def expandStruct : Struct → TermElabM Struct | s => do let s := expandCompositeFields s; s ← expandNumLitFields s; s ← expandParentFields s; s ← groupFields expandStruct s; addMissingFields expandStruct s structure CtorHeaderResult := (ctorFn : Expr) (ctorFnType : Expr) (instMVars : Array MVarId := #[]) private def mkCtorHeaderAux : Nat → Expr → Expr → Array MVarId → TermElabM CtorHeaderResult | 0, type, ctorFn, instMVars => pure { ctorFn := ctorFn, ctorFnType := type, instMVars := instMVars } | n+1, type, ctorFn, instMVars => do type ← whnfForall type; match type with | Expr.forallE _ d b c => match c.binderInfo with | BinderInfo.instImplicit => do a ← mkFreshExprMVar d MetavarKind.synthetic; mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) (instMVars.push a.mvarId!) | _ => do a ← mkFreshExprMVar d; mkCtorHeaderAux n (b.instantiate1 a) (mkApp ctorFn a) instMVars | _ => throwError "unexpected constructor type" private partial def getForallBody : Nat → Expr → Option Expr | i+1, Expr.forallE _ _ b _ => getForallBody i b | i+1, _ => none | 0, type => type private def propagateExpectedType (type : Expr) (numFields : Nat) (expectedType? : Option Expr) : TermElabM Unit := match expectedType? with | none => pure () | some expectedType => match getForallBody numFields type with | none => pure () | some typeBody => unless typeBody.hasLooseBVars $ do _ ← isDefEq expectedType typeBody; pure () private def mkCtorHeader (ctorVal : ConstructorVal) (expectedType? : Option Expr) : TermElabM CtorHeaderResult := do lvls ← ctorVal.lparams.mapM $ fun _ => mkFreshLevelMVar; let val := Lean.mkConst ctorVal.name lvls; let type := (ConstantInfo.ctorInfo ctorVal).instantiateTypeLevelParams lvls; r ← mkCtorHeaderAux ctorVal.nparams type val #[]; propagateExpectedType r.ctorFnType ctorVal.nfields expectedType?; synthesizeAppInstMVars r.instMVars; pure r def markDefaultMissing (e : Expr) : Expr := mkAnnotation `structInstDefault e def defaultMissing? (e : Expr) : Option Expr := annotation? `structInstDefault e def throwFailedToElabField {α} (fieldName : Name) (structName : Name) (msgData : MessageData) : TermElabM α := throwError ("failed to elaborate field '" ++ fieldName ++ "' of '" ++ structName ++ ", " ++ msgData) private partial def elabStruct : Struct → Option Expr → TermElabM (Expr × Struct) | s, expectedType? => withRef s.ref do env ← getEnv; let ctorVal := getStructureCtor env s.structName; { ctorFn := ctorFn, ctorFnType := ctorFnType, .. } ← mkCtorHeader ctorVal expectedType?; (e, _, fields) ← s.fields.foldlM (fun (acc : Expr × Expr × Fields) field => let (e, type, fields) := acc; match field.lhs with | [FieldLHS.fieldName ref fieldName] => do type ← whnfForall type; match type with | Expr.forallE _ d b c => let continue (val : Expr) (field : Field Struct) : TermElabM (Expr × Expr × Fields) := do { let e := mkApp e val; let type := b.instantiate1 val; let field := { field with expr? := some val }; pure (e, type, field::fields) }; match field.val with | FieldVal.term stx => do val ← elabTermEnsuringType stx d; continue val field | FieldVal.nested s => do (val, sNew) ← elabStruct s (some d); val ← ensureHasType d val; continue val { field with val := FieldVal.nested sNew } | FieldVal.default => do val ← withRef field.ref $ mkFreshExprMVar (some d); continue (markDefaultMissing val) field | _ => withRef field.ref $ throwFailedToElabField fieldName s.structName ("unexpected constructor type" ++ indentExpr type) | _ => throwErrorAt field.ref "unexpected unexpanded structure field") (ctorFn, ctorFnType, []); pure (e, s.setFields fields.reverse) namespace DefaultFields structure Context := -- We must search for default values overriden in derived structures (structs : Array Struct := #[]) (allStructNames : Array Name := #[]) /- Consider the following example: ``` structure A := (x : Nat := 1) structure B extends A := (y : Nat := x + 1) (x := y + 1) structure C extends B := (z : Nat := 2*y) (x := z + 3) ``` And we are trying to elaborate a structure instance for `C`. There are default values for `x` at `A`, `B`, and `C`. We say the default value at `C` has distance 0, the one at `B` distance 1, and the one at `A` distance 2. The field `maxDistance` specifies the maximum distance considered in a round of Default field computation. Remark: since `C` does not set a default value of `y`, the default value at `B` is at distance 0. The fixpoint for setting default values works in the following way. - Keep computing default values using `maxDistance == 0`. - We increase `maxDistance` whenever we failed to compute a new default value in a round. - If `maxDistance > 0`, then we interrupt a round as soon as we compute some default value. We use depth-first search. - We sign an error if no progress is made when `maxDistance` == structure hierarchy depth (2 in the example above). -/ (maxDistance : Nat := 0) structure State := (progress : Bool := false) partial def collectStructNames : Struct → Array Name → Array Name | struct, names => let names := names.push struct.structName; struct.fields.foldl (fun names field => match field.val with | FieldVal.nested struct => collectStructNames struct names | _ => names) names partial def getHierarchyDepth : Struct → Nat | struct => struct.fields.foldl (fun max field => match field.val with | FieldVal.nested struct => Nat.max max (getHierarchyDepth struct + 1) | _ => max) 0 partial def findDefaultMissing? (mctx : MetavarContext) : Struct → Option (Field Struct) | struct => struct.fields.findSome? $ fun field => match field.val with | FieldVal.nested struct => findDefaultMissing? struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => if mctx.isExprAssigned mvarId then none else some field | _ => none def getFieldName (field : Field Struct) : Name := match field.lhs with | [FieldLHS.fieldName _ fieldName] => fieldName | _ => unreachable! abbrev M := ReaderT Context (StateRefT State TermElabM) def isRoundDone : M Bool := do ctx ← read; s ← get; pure (s.progress && ctx.maxDistance > 0) def getFieldValue? (struct : Struct) (fieldName : Name) : Option Expr := struct.fields.findSome? $ fun field => if getFieldName field == fieldName then field.expr? else none partial def mkDefaultValueAux? (struct : Struct) : Expr → TermElabM (Option Expr) | Expr.lam n d b c => withRef struct.ref $ if c.binderInfo.isExplicit then let fieldName := n; match getFieldValue? struct fieldName with | none => pure none | some val => do valType ← inferType val; condM (isDefEq valType d) (mkDefaultValueAux? (b.instantiate1 val)) (pure none) else do arg ← mkFreshExprMVar d; mkDefaultValueAux? (b.instantiate1 arg) | e => if e.isAppOfArity `id 2 then pure (some e.appArg!) else pure (some e) def mkDefaultValue? (struct : Struct) (cinfo : ConstantInfo) : TermElabM (Option Expr) := withRef struct.ref do us ← cinfo.lparams.mapM $ fun _ => mkFreshLevelMVar; mkDefaultValueAux? struct (cinfo.instantiateValueLevelParams us) /-- If `e` is a projection function of one of the given structures, then reduce it -/ def reduceProjOf? (structNames : Array Name) (e : Expr) : MetaM (Option Expr) := do if !e.isApp then pure none else match e.getAppFn with | Expr.const name _ _ => do env ← getEnv; match env.getProjectionStructureName? name with | some structName => if structNames.contains structName then Meta.unfoldDefinition? e else pure none | none => pure none | _ => pure none /-- Reduce default value. It performs beta reduction and projections of the given structures. -/ partial def reduce (structNames : Array Name) : Expr → MetaM Expr | e@(Expr.lam _ _ _ _) => lambdaLetTelescope e $ fun xs b => do b ← reduce b; mkLambdaFVars xs b | e@(Expr.forallE _ _ _ _) => forallTelescope e $ fun xs b => do b ← reduce b; mkForallFVars xs b | e@(Expr.letE _ _ _ _ _) => lambdaLetTelescope e $ fun xs b => do b ← reduce b; mkLetFVars xs b | e@(Expr.proj _ i b _) => do r? ← Meta.reduceProj? b i; match r? with | some r => reduce r | none => do b ← reduce b; pure $ e.updateProj! b | e@(Expr.app f _ _) => do r? ← reduceProjOf? structNames e; match r? with | some r => reduce r | none => do let f := f.getAppFn; f' ← reduce f; if f'.isLambda then let revArgs := e.getAppRevArgs; reduce $ f'.betaRev revArgs else do args ← e.getAppArgs.mapM reduce; pure (mkAppN f' args) | e@(Expr.mdata _ b _) => do b ← reduce b; if (defaultMissing? e).isSome && !b.isMVar then pure b else pure $ e.updateMData! b | e@(Expr.mvar mvarId _) => do val? ← getExprMVarAssignment? mvarId; match val? with | some val => if val.isMVar then reduce val else pure val | none => pure e | e => pure e partial def tryToSynthesizeDefaultAux (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : Nat → Nat → TermElabM Bool | i, dist => if dist > maxDistance then pure false else if h : i < structs.size then do let struct := structs.get ⟨i, h⟩; let defaultName := struct.structName ++ fieldName ++ `_default; env ← getEnv; match env.find? defaultName with | some cinfo@(ConstantInfo.defnInfo defVal) => do mctx ← getMCtx; val? ← mkDefaultValue? struct cinfo; match val? with | none => do setMCtx mctx; tryToSynthesizeDefaultAux (i+1) (dist+1) | some val => do val ← liftMetaM $ reduce allStructNames val; match val.find? $ fun e => (defaultMissing? e).isSome with | some _ => do setMCtx mctx; tryToSynthesizeDefaultAux (i+1) (dist+1) | none => do mvarDecl ← getMVarDecl mvarId; val ← ensureHasType mvarDecl.type val; assignExprMVar mvarId val; pure true | _ => tryToSynthesizeDefaultAux (i+1) dist else pure false def tryToSynthesizeDefault (structs : Array Struct) (allStructNames : Array Name) (maxDistance : Nat) (fieldName : Name) (mvarId : MVarId) : TermElabM Bool := tryToSynthesizeDefaultAux structs allStructNames maxDistance fieldName mvarId 0 0 partial def step : Struct → M Unit | struct => unlessM isRoundDone $ adaptReader (fun (ctx : Context) => { ctx with structs := ctx.structs.push struct }) $ do struct.fields.forM $ fun field => match field.val with | FieldVal.nested struct => step struct | _ => match field.expr? with | none => unreachable! | some expr => match defaultMissing? expr with | some (Expr.mvar mvarId _) => unlessM (liftM $ isExprMVarAssigned mvarId) $ do ctx ← read; whenM (liftM $ withRef field.ref $ tryToSynthesizeDefault ctx.structs ctx.allStructNames ctx.maxDistance (getFieldName field) mvarId) $ do modify $ fun s => { s with progress := true } | _ => pure () partial def propagateLoop (hierarchyDepth : Nat) : Nat → Struct → M Unit | d, struct => do mctx ← getMCtx; match findDefaultMissing? mctx struct with | none => pure () -- Done | some field => if d > hierarchyDepth then throwErrorAt field.ref ("field '" ++ getFieldName field ++ "' is missing") else adaptReader (fun (ctx : Context) => { ctx with maxDistance := d }) $ do modify $ fun (s : State) => { s with progress := false }; step struct; s ← get; if s.progress then do propagateLoop 0 struct else propagateLoop (d+1) struct def propagate (struct : Struct) : TermElabM Unit := let hierarchyDepth := getHierarchyDepth struct; let structNames := collectStructNames struct #[]; (propagateLoop hierarchyDepth 0 struct { allStructNames := structNames }).run' {} end DefaultFields private def elabStructInstAux (stx : Syntax) (expectedType? : Option Expr) (source : Source) : TermElabM Expr := do structName ← getStructName stx expectedType? source; env ← getEnv; unless (isStructureLike env structName) $ throwError ("invalid {...} notation, '" ++ structName ++ "' is not a structure"); match mkStructView stx structName source with | Except.error ex => throwError ex | Except.ok struct => do struct ← expandStruct struct; trace `Elab.struct fun _ => toString struct; (r, struct) ← elabStruct struct expectedType?; DefaultFields.propagate struct; pure r private def expandStructInstExpectedType (stx : Syntax) : MacroM (Option Syntax) := let expectedArg := stx.getArg 4; if expectedArg.isNone then pure none else let expected := expectedArg.getArg 1; let stxNew := stx.setArg 4 mkNullNode; `(($stxNew : $expected)) @[builtinTermElab structInst] def elabStructInst : TermElab := fun stx expectedType? => do stxNew? ← liftMacroM $ expandStructInstExpectedType stx; match stxNew? with | some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | none => do stxNew? ← expandNonAtomicExplicitSource stx; match stxNew? with | some stxNew => withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? | none => do sourceView ← getStructSource stx; modifyOp? ← isModifyOp? stx; match modifyOp?, sourceView with | some modifyOp, Source.explicit source _ => elabModifyOp stx modifyOp source expectedType? | some _, _ => throwError ("invalid {...} notation, explicit source is required when using '[<index>] := <value>'") | _, _ => elabStructInstAux stx expectedType? sourceView @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.struct; pure () end StructInst end Term end Elab end Lean
5589d9fc0cde4ad32c0769908c6875611bb827f6
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/974.lean
195fb2bf852661e0d9fedf8a46d8da315d35b920
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
708
lean
inductive Formula : Nat → Type u | bot : Formula n | imp (f₁ f₂ : Formula n ) : Formula n | all (f : Formula (n+1)) : Formula n def Formula.count_quantifiers : {n:Nat} → Formula n → Nat | _, imp f₁ f₂ => f₁.count_quantifiers + f₂.count_quantifiers | _, all f => f.count_quantifiers + 1 | _, _ => 0 attribute [simp] Formula.count_quantifiers #check @Formula.count_quantifiers._eq_1 #check @Formula.count_quantifiers._eq_2 #check @Formula.count_quantifiers._eq_3 @[simp] def Formula.count_quantifiers2 : Formula n → Nat | imp f₁ f₂ => f₁.count_quantifiers2 + f₂.count_quantifiers2 | all f => f.count_quantifiers2 + 1 | _ => 0
2dd325a3af296fa7f08a300ddb0bc61fb7e8530b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/localization/at_prime.lean
62cd3aaab6ebdd92e5503160e5d2b90dc69d570d
[ "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
9,620
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import ring_theory.ideal.local_ring import ring_theory.localization.ideal /-! # Localizations of commutative rings at the complement of a prime ideal ## Main definitions * `is_localization.at_prime (I : ideal R) [is_prime I] (S : Type*)` expresses that `S` is a localization at (the complement of) a prime ideal `I`, as an abbreviation of `is_localization I.prime_compl S` ## Main results * `is_localization.at_prime.local_ring`: a theorem (not an instance) stating a localization at the complement of a prime ideal is a local ring ## Implementation notes See `src/ring_theory/localization/basic.lean` for a design overview. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ variables {R : Type*} [comm_semiring R] (M : submonoid R) (S : Type*) [comm_semiring S] variables [algebra R S] {P : Type*} [comm_semiring P] section at_prime variables (I : ideal R) [hp : I.is_prime] include hp namespace ideal /-- The complement of a prime ideal `I ⊆ R` is a submonoid of `R`. -/ def prime_compl : submonoid R := { carrier := (Iᶜ : set R), one_mem' := by convert I.ne_top_iff_one.1 hp.1; refl, mul_mem' := λ x y hnx hny hxy, or.cases_on (hp.mem_or_mem hxy) hnx hny } lemma prime_compl_le_non_zero_divisors [no_zero_divisors R] : I.prime_compl ≤ non_zero_divisors R := le_non_zero_divisors_of_no_zero_divisors $ not_not_intro I.zero_mem end ideal variables (S) /-- Given a prime ideal `P`, the typeclass `is_localization.at_prime S P` states that `S` is isomorphic to the localization of `R` at the complement of `P`. -/ protected abbreviation is_localization.at_prime := is_localization I.prime_compl S /-- Given a prime ideal `P`, `localization.at_prime S P` is a localization of `R` at the complement of `P`, as a quotient type. -/ protected abbreviation localization.at_prime := localization I.prime_compl namespace is_localization lemma at_prime.nontrivial [is_localization.at_prime S I] : nontrivial S := nontrivial_of_ne (0 : S) 1 $ λ hze, begin rw [←(algebra_map R S).map_one, ←(algebra_map R S).map_zero] at hze, obtain ⟨t, ht⟩ := (eq_iff_exists I.prime_compl S).1 hze, have htz : (t : R) = 0, by simpa using ht.symm, exact t.2 (htz.symm ▸ I.zero_mem : ↑t ∈ I) end local attribute [instance] at_prime.nontrivial theorem at_prime.local_ring [is_localization.at_prime S I] : local_ring S := local_ring.of_nonunits_add begin intros x y hx hy hu, cases is_unit_iff_exists_inv.1 hu with z hxyz, have : ∀ {r : R} {s : I.prime_compl}, mk' S r s ∈ nonunits S → r ∈ I, from λ (r : R) (s : I.prime_compl), not_imp_comm.1 (λ nr, is_unit_iff_exists_inv.2 ⟨mk' S ↑s (⟨r, nr⟩ : I.prime_compl), mk'_mul_mk'_eq_one' _ _ nr⟩), rcases mk'_surjective I.prime_compl x with ⟨rx, sx, hrx⟩, rcases mk'_surjective I.prime_compl y with ⟨ry, sy, hry⟩, rcases mk'_surjective I.prime_compl z with ⟨rz, sz, hrz⟩, rw [←hrx, ←hry, ←hrz, ←mk'_add, ←mk'_mul, ←mk'_self S I.prime_compl.one_mem] at hxyz, rw ←hrx at hx, rw ←hry at hy, obtain ⟨t, ht⟩ := is_localization.eq.1 hxyz, simp only [mul_one, one_mul, submonoid.coe_mul, subtype.coe_mk] at ht, suffices : ↑sx * ↑sy * ↑sz * ↑t ∈ I, from not_or (mt hp.mem_or_mem $ not_or sx.2 sy.2) sz.2 (hp.mem_or_mem $ (hp.mem_or_mem this).resolve_right t.2), rw [←ht, mul_assoc], exact I.mul_mem_right _ (I.add_mem (I.mul_mem_right _ $ this hx) (I.mul_mem_right _ $ this hy)) end end is_localization namespace localization /-- The localization of `R` at the complement of a prime ideal is a local ring. -/ instance at_prime.local_ring : local_ring (localization I.prime_compl) := is_localization.at_prime.local_ring (localization I.prime_compl) I end localization end at_prime namespace is_localization variables {A : Type*} [comm_ring A] [is_domain A] /-- The localization of an integral domain at the complement of a prime ideal is an integral domain. -/ instance is_domain_of_local_at_prime {P : ideal A} (hp : P.is_prime) : is_domain (localization.at_prime P) := is_domain_localization P.prime_compl_le_non_zero_divisors namespace at_prime variables (I : ideal R) [hI : I.is_prime] [is_localization.at_prime S I] include hI lemma is_unit_to_map_iff (x : R) : is_unit ((algebra_map R S) x) ↔ x ∈ I.prime_compl := ⟨λ h hx, (is_prime_of_is_prime_disjoint I.prime_compl S I hI disjoint_compl_left).ne_top $ (ideal.map (algebra_map R S) I).eq_top_of_is_unit_mem (ideal.mem_map_of_mem _ hx) h, λ h, map_units S ⟨x, h⟩⟩ -- Can't use typeclasses to infer the `local_ring` instance, so use an `opt_param` instead -- (since `local_ring` is a `Prop`, there should be no unification issues.) lemma to_map_mem_maximal_iff (x : R) (h : _root_.local_ring S := local_ring S I) : algebra_map R S x ∈ local_ring.maximal_ideal S ↔ x ∈ I := not_iff_not.mp $ by simpa only [local_ring.mem_maximal_ideal, mem_nonunits_iff, not_not] using is_unit_to_map_iff S I x lemma is_unit_mk'_iff (x : R) (y : I.prime_compl) : is_unit (mk' S x y) ↔ x ∈ I.prime_compl := ⟨λ h hx, mk'_mem_iff.mpr ((to_map_mem_maximal_iff S I x).mpr hx) h, λ h, is_unit_iff_exists_inv.mpr ⟨mk' S ↑y ⟨x, h⟩, mk'_mul_mk'_eq_one ⟨x, h⟩ y⟩⟩ lemma mk'_mem_maximal_iff (x : R) (y : I.prime_compl) (h : _root_.local_ring S := local_ring S I) : mk' S x y ∈ local_ring.maximal_ideal S ↔ x ∈ I := not_iff_not.mp $ by simpa only [local_ring.mem_maximal_ideal, mem_nonunits_iff, not_not] using is_unit_mk'_iff S I x y end at_prime end is_localization namespace localization open is_localization local attribute [instance] classical.prop_decidable variables (I : ideal R) [hI : I.is_prime] include hI variables {I} /-- The unique maximal ideal of the localization at `I.prime_compl` lies over the ideal `I`. -/ lemma at_prime.comap_maximal_ideal : ideal.comap (algebra_map R (localization.at_prime I)) (local_ring.maximal_ideal (localization I.prime_compl)) = I := ideal.ext $ λ x, by simpa only [ideal.mem_comap] using at_prime.to_map_mem_maximal_iff _ I x /-- The image of `I` in the localization at `I.prime_compl` is a maximal ideal, and in particular it is the unique maximal ideal given by the local ring structure `at_prime.local_ring` -/ lemma at_prime.map_eq_maximal_ideal : ideal.map (algebra_map R (localization.at_prime I)) I = (local_ring.maximal_ideal (localization I.prime_compl)) := begin convert congr_arg (ideal.map _) at_prime.comap_maximal_ideal.symm, rw map_comap I.prime_compl end lemma le_comap_prime_compl_iff {J : ideal P} [hJ : J.is_prime] {f : R →+* P} : I.prime_compl ≤ J.prime_compl.comap f ↔ J.comap f ≤ I := ⟨λ h x hx, by { contrapose! hx, exact h hx }, λ h x hx hfxJ, hx (h hfxJ)⟩ variables (I) /-- For a ring hom `f : R →+* S` and a prime ideal `J` in `S`, the induced ring hom from the localization of `R` at `J.comap f` to the localization of `S` at `J`. To make this definition more flexible, we allow any ideal `I` of `R` as input, together with a proof that `I = J.comap f`. This can be useful when `I` is not definitionally equal to `J.comap f`. -/ noncomputable def local_ring_hom (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) : localization.at_prime I →+* localization.at_prime J := is_localization.map (localization.at_prime J) f (le_comap_prime_compl_iff.mpr (ge_of_eq hIJ)) lemma local_ring_hom_to_map (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) (x : R) : local_ring_hom I J f hIJ (algebra_map _ _ x) = algebra_map _ _ (f x) := map_eq _ _ lemma local_ring_hom_mk' (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) (x : R) (y : I.prime_compl) : local_ring_hom I J f hIJ (is_localization.mk' _ x y) = is_localization.mk' (localization.at_prime J) (f x) (⟨f y, le_comap_prime_compl_iff.mpr (ge_of_eq hIJ) y.2⟩ : J.prime_compl) := map_mk' _ _ _ instance is_local_ring_hom_local_ring_hom (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) : is_local_ring_hom (local_ring_hom I J f hIJ) := is_local_ring_hom.mk $ λ x hx, begin rcases is_localization.mk'_surjective I.prime_compl x with ⟨r, s, rfl⟩, rw local_ring_hom_mk' at hx, rw at_prime.is_unit_mk'_iff at hx ⊢, exact λ hr, hx ((set_like.ext_iff.mp hIJ r).mp hr), end lemma local_ring_hom_unique (J : ideal P) [hJ : J.is_prime] (f : R →+* P) (hIJ : I = J.comap f) {j : localization.at_prime I →+* localization.at_prime J} (hj : ∀ x : R, j (algebra_map _ _ x) = algebra_map _ _ (f x)) : local_ring_hom I J f hIJ = j := map_unique _ _ hj @[simp] lemma local_ring_hom_id : local_ring_hom I I (ring_hom.id R) (ideal.comap_id I).symm = ring_hom.id _ := local_ring_hom_unique _ _ _ _ (λ x, rfl) @[simp] lemma local_ring_hom_comp {S : Type*} [comm_semiring S] (J : ideal S) [hJ : J.is_prime] (K : ideal P) [hK : K.is_prime] (f : R →+* S) (hIJ : I = J.comap f) (g : S →+* P) (hJK : J = K.comap g) : local_ring_hom I K (g.comp f) (by rw [hIJ, hJK, ideal.comap_comap f g]) = (local_ring_hom J K g hJK).comp (local_ring_hom I J f hIJ) := local_ring_hom_unique _ _ _ _ (λ r, by simp only [function.comp_app, ring_hom.coe_comp, local_ring_hom_to_map]) end localization
c3be754d368fbcbd04adc467024ef3ff7f04ef54
26ac254ecb57ffcb886ff709cf018390161a9225
/src/data/polynomial/algebra_map.lean
495405d4a41b45a65724e5ab1343d63bdba15899
[ "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
9,000
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.induction import data.polynomial.degree /-! # 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 finsupp finset add_monoid_algebra 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 semiring variables [semiring R] {p q r : polynomial R} lemma C_mul' (a : R) (f : polynomial R) : C a * f = a • f := ext $ λ n, coeff_C_mul f lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩ end semiring 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) := add_monoid_algebra.algebra 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 @[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₂, finsupp.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₂, finsupp.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 } section eval variable {x : R} @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval₂_hom [comm_semiring S] (f : R →+* S) (x : R) : p.eval₂ f (f x) = f (p.eval x) := polynomial.induction_on p (by simp) (by simp [f.map_add] {contextual := tt}) (by simp [f.map_mul, eval_pow, f.map_pow, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] end eval section comp lemma eval₂_comp [comm_semiring S] (f : R →+* S) {x : S} : (p.comp q).eval₂ f x = p.eval₂ f (q.eval₂ f x) := by rw [comp, p.as_sum]; simp only [eval₂_mul, eval₂_C, eval₂_pow, eval₂_finset_sum, eval₂_X] lemma eval_comp : (p.comp q).eval a = p.eval (q.eval a) := eval₂_comp _ instance : is_semiring_hom (λ q : polynomial R, q.comp p) := by unfold comp; apply_instance @[simp] lemma mul_comp : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ end comp end comm_semiring section aeval variables [comm_semiring R] {p : polynomial R} variables (R) (A) -- TODO this could be generalized: there's no need for `A` to be commutative, -- we just need that `x` is central. variables [comm_semiring A] [algebra R A] variables {B : Type*} [comm_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 } variables {R A} theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map R A) x p := rfl @[simp] lemma aeval_X : aeval R A x X = x := eval₂_X _ x @[simp] lemma aeval_C (r : R) : aeval R A x (C r) = algebra_map R A r := eval₂_C _ x 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 (algebra_map R A), eval₂_X, ih] } end theorem aeval_alg_hom (f : A →ₐ[R] B) (x : A) : aeval R B (f x) = f.comp (aeval R A x) := alg_hom.ext $ λ p, by rw [eval_unique (f.comp (aeval R A x)), alg_hom.comp_apply, aeval_X, aeval_def] theorem aeval_alg_hom_apply (f : A →ₐ[R] B) (x : A) (p) : aeval R B (f x) p = f (aeval R A x p) := alg_hom.ext_iff.1 (aeval_alg_hom f x) p @[simp] lemma coe_aeval_eq_eval (r : R) : (aeval R R r : polynomial R → R) = eval r := rfl lemma coeff_zero_eq_aeval_zero (p : polynomial R) : p.coeff 0 = aeval R R 0 p := by simp [coeff_zero_eq_eval_zero] lemma pow_comp (p q : polynomial R) (k : ℕ) : (p ^ k).comp q = (p.comp q) ^ k := by { unfold comp, rw ← coe_eval₂_ring_hom, apply ring_hom.map_pow } 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 := show eval₂ (f.comp (ring_hom.id R)) (f r) p = 0 → eval₂ (ring_hom.id R) r p = 0, begin intro h, apply hf, rw [hom_eval₂, 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 R S (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, { unfold polynomial.eval polynomial.eval₂ finsupp.sum id at dvd_eval, rw [←finset.insert_erase hi, finset.sum_insert (finset.not_mem_erase _ _)] at dvd_eval, refine (dvd_add_left (finset.dvd_sum _)).mp dvd_eval, intros j hj, exact dvd_terms j (finset.ne_of_mem_erase hj) }, { convert dvd_zero p, convert _root_.zero_mul _, exact finsupp.not_mem_support_iff.mp 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 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_single], 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 end polynomial
dfffaa18efea65ee442937dd929e763dce0cfb21
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/quandle.lean
b965c39dca412ecf2106c48cc8e073d30b27a25b
[]
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
23,108
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.zmod.basic import Mathlib.data.equiv.mul_add import Mathlib.tactic.group import Mathlib.PostPort universes u l u_1 u_2 u_3 namespace Mathlib /-! # Racks and Quandles This file defines racks and quandles, algebraic structures for sets that bijectively act on themselves with a self-distributivity property. If `R` is a rack and `act : R → (R ≃ R)` is the self-action, then the self-distributivity is, equivalently, that ``` act (act x y) = act x * act y * (act x)⁻¹ ``` where multiplication is composition in `R ≃ R` as a group. Quandles are racks such that `act x x = x` for all `x`. One example of a quandle (not yet in mathlib) is the action of a Lie algebra on itself, defined by `act x y = Ad (exp x) y`. Quandles and racks were independently developed by multiple mathematicians. David Joyce introduced quandles in his thesis [Joyce1982] to define an algebraic invariant of knot and link complements that is analogous to the fundamental group of the exterior, and he showed that the quandle associated to an oriented knot is invariant up to orientation-reversed mirror image. Racks were used by Fenn and Rourke for framed codimension-2 knots and links.[FennRourke1992] The name "rack" came from wordplay by Conway and Wraith for the "wrack and ruin" of forgetting everything but the conjugation operation for a group. ## Main definitions * `shelf` is a type with a self-distributive action * `rack` is a shelf whose action for each element is invertible * `quandle` is a rack whose action for an element fixes that element * `quandle.conj` defines a quandle of a group acting on itself by conjugation. * `shelf_hom` is homomorphisms of shelves, racks, and quandles. * `rack.envel_group` gives the universal group the rack maps to as a conjugation quandle. * `rack.opp` gives the rack with the action replaced by its inverse. ## Main statements * `rack.envel_group` is left adjoint to `quandle.conj` (`to_envel_group.map`). The universality statements are `to_envel_group.univ` and `to_envel_group.univ_uniq`. ## Notation The following notation is localized in `quandles`: * `x ◃ y` is `shelf.act x y` * `x ◃⁻¹ y` is `rack.inv_act x y` * `S →◃ S'` is `shelf_hom S S'` Use `open_locale quandles` to use these. ## Todo * If g is the Lie algebra of a Lie group G, then (x ◃ y) = Ad (exp x) x forms a quandle * If X is a symmetric space, then each point has a corresponding involution that acts on X, forming a quandle. * Alexander quandle with `a ◃ b = t * b + (1 - t) * b`, with `a` and `b` elements of a module over Z[t,t⁻¹]. * If G is a group, H a subgroup, and z in H, then there is a quandle `(G/H;z)` defined by `yH ◃ xH = yzy⁻¹xH`. Every homogeneous quandle (i.e., a quandle Q whose automorphism group acts transitively on Q as a set) is isomorphic to such a quandle. There is a generalization to this arbitrary quandles in [Joyce's paper (Theorem 7.2)][Joyce1982]. ## Tags rack, quandle -/ /-- A *shelf* is a structure with a self-distributive binary operation. The binary operation is regarded as a left action of the type on itself. -/ class shelf (α : Type u) where act : α → α → α self_distrib : ∀ {x y z : α}, act x (act y z) = act (act x y) (act x z) /-- The type of homomorphisms between shelves. This is also the notion of rack and quandle homomorphisms. -/ structure shelf_hom (S₁ : Type u_1) (S₂ : Type u_2) [shelf S₁] [shelf S₂] where to_fun : S₁ → S₂ map_act' : ∀ {x y : S₁}, to_fun (shelf.act x y) = shelf.act (to_fun x) (to_fun y) /-- A *rack* is an automorphic set (a set with an action on itself by bijections) that is self-distributive. It is a shelf such that each element's action is invertible. The notations `x ◃ y` and `x ◃⁻¹ y` denote the action and the inverse action, respectively, and they are right associative. -/ class rack (α : Type u) extends shelf α where inv_act : α → α → α left_inv : ∀ (x : α), function.left_inverse (inv_act x) (shelf.act x) right_inv : ∀ (x : α), function.right_inverse (inv_act x) (shelf.act x) namespace rack theorem self_distrib {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : shelf.act x (shelf.act y z) = shelf.act (shelf.act x y) (shelf.act x z) := shelf.self_distrib /-- A rack acts on itself by equivalences. -/ def act {R : Type u_1} [rack R] (x : R) : R ≃ R := equiv.mk (shelf.act x) (inv_act x) (left_inv x) (right_inv x) @[simp] theorem act_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (act x) y = shelf.act x y := rfl @[simp] theorem act_symm_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (equiv.symm (act x)) y = inv_act x y := rfl @[simp] theorem inv_act_apply {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (act x⁻¹) y = inv_act x y := rfl @[simp] theorem inv_act_act_eq {R : Type u_1} [rack R] (x : R) (y : R) : inv_act x (shelf.act x y) = y := left_inv x y @[simp] theorem act_inv_act_eq {R : Type u_1} [rack R] (x : R) (y : R) : shelf.act x (inv_act x y) = y := right_inv x y theorem left_cancel {R : Type u_1} [rack R] (x : R) {y : R} {y' : R} : shelf.act x y = shelf.act x y' ↔ y = y' := { mp := equiv.injective (act x), mpr := fun (ᾰ : y = y') => Eq._oldrec (Eq.refl (shelf.act x y)) ᾰ } theorem left_cancel_inv {R : Type u_1} [rack R] (x : R) {y : R} {y' : R} : inv_act x y = inv_act x y' ↔ y = y' := { mp := equiv.injective (equiv.symm (act x)), mpr := fun (ᾰ : y = y') => Eq._oldrec (Eq.refl (inv_act x y)) ᾰ } theorem self_distrib_inv {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : inv_act x (inv_act y z) = inv_act (inv_act x y) (inv_act x z) := sorry /-- The *adjoint action* of a rack on itself is `op'`, and the adjoint action of `x ◃ y` is the conjugate of the action of `y` by the action of `x`. It is another way to understand the self-distributivity axiom. This is used in the natural rack homomorphism `to_conj` from `R` to `conj (R ≃ R)` defined by `op'`. -/ theorem ad_conj {R : Type u_1} [rack R] (x : R) (y : R) : act (shelf.act x y) = act x * act y * (act x⁻¹) := sorry /-- The opposite rack, swapping the roles of `◃` and `◃⁻¹`. -/ protected instance opposite_rack {R : Type u_1} [rack R] : rack (Rᵒᵖ) := mk (fun (x y : Rᵒᵖ) => opposite.op (shelf.act (opposite.unop x) (opposite.unop y))) sorry sorry @[simp] theorem op_act_op_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (opposite.op x) (opposite.op y) = opposite.op (inv_act x y) := rfl @[simp] theorem op_inv_act_op_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (opposite.op x) (opposite.op y) = opposite.op (shelf.act x y) := rfl @[simp] theorem self_act_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (shelf.act x x) y = shelf.act x y := sorry @[simp] theorem self_inv_act_inv_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (inv_act x x) y = inv_act x y := sorry @[simp] theorem self_act_inv_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act (shelf.act x x) y = inv_act x y := sorry @[simp] theorem self_inv_act_act_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act (inv_act x x) y = shelf.act x y := sorry theorem self_act_eq_iff_eq {R : Type u_1} [rack R] {x : R} {y : R} : shelf.act x x = shelf.act y y ↔ x = y := sorry theorem self_inv_act_eq_iff_eq {R : Type u_1} [rack R] {x : R} {y : R} : inv_act x x = inv_act y y ↔ x = y := sorry /-- The map `x ↦ x ◃ x` is a bijection. (This has applications for the regular isotopy version of the Reidemeister I move for knot diagrams.) -/ def self_apply_equiv (R : Type u_1) [rack R] : R ≃ R := equiv.mk (fun (x : R) => shelf.act x x) (fun (x : R) => inv_act x x) sorry sorry /-- An involutory rack is one for which `rack.op R x` is an involution for every x. -/ def is_involutory (R : Type u_1) [rack R] := ∀ (x : R), function.involutive (shelf.act x) theorem involutory_inv_act_eq_act {R : Type u_1} [rack R] (h : is_involutory R) (x : R) (y : R) : inv_act x y = shelf.act x y := eq.mpr (id (Eq._oldrec (Eq.refl (inv_act x y = shelf.act x y)) (Eq.symm (propext (left_cancel x))))) (eq.mpr (id (Eq._oldrec (Eq.refl (shelf.act x (inv_act x y) = shelf.act x (shelf.act x y))) (right_inv x y))) (Eq.symm (function.involutive.left_inverse (h x) y))) /-- An abelian rack is one for which the mediality axiom holds. -/ def is_abelian (R : Type u_1) [rack R] := ∀ (x y z w : R), shelf.act (shelf.act x y) (shelf.act z w) = shelf.act (shelf.act x z) (shelf.act y w) /-- Associative racks are uninteresting. -/ theorem assoc_iff_id {R : Type u_1} [rack R] {x : R} {y : R} {z : R} : shelf.act x (shelf.act y z) = shelf.act (shelf.act x y) z ↔ shelf.act x z = z := sorry end rack namespace shelf_hom protected instance has_coe_to_fun {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] : has_coe_to_fun (shelf_hom S₁ S₂) := has_coe_to_fun.mk (fun (x : shelf_hom S₁ S₂) => S₁ → S₂) to_fun @[simp] theorem to_fun_eq_coe {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] (f : shelf_hom S₁ S₂) : to_fun f = ⇑f := rfl @[simp] theorem map_act {S₁ : Type u_1} {S₂ : Type u_2} [shelf S₁] [shelf S₂] (f : shelf_hom S₁ S₂) {x : S₁} {y : S₁} : coe_fn f (shelf.act x y) = shelf.act (coe_fn f x) (coe_fn f y) := map_act' f /-- The identity homomorphism -/ def id (S : Type u_1) [shelf S] : shelf_hom S S := mk id sorry protected instance inhabited (S : Type u_1) [shelf S] : Inhabited (shelf_hom S S) := { default := id S } /-- The composition of shelf homomorphisms -/ def comp {S₁ : Type u_1} {S₂ : Type u_2} {S₃ : Type u_3} [shelf S₁] [shelf S₂] [shelf S₃] (g : shelf_hom S₂ S₃) (f : shelf_hom S₁ S₂) : shelf_hom S₁ S₃ := mk (to_fun g ∘ to_fun f) sorry @[simp] theorem comp_apply {S₁ : Type u_1} {S₂ : Type u_2} {S₃ : Type u_3} [shelf S₁] [shelf S₂] [shelf S₃] (g : shelf_hom S₂ S₃) (f : shelf_hom S₁ S₂) (x : S₁) : coe_fn (comp g f) x = coe_fn g (coe_fn f x) := rfl end shelf_hom /-- A quandle is a rack such that each automorphism fixes its corresponding element. -/ class quandle (α : Type u_1) extends rack α where fix : ∀ {x : α}, shelf.act x x = x namespace quandle @[simp] theorem fix_inv {Q : Type u_1} [quandle Q] {x : Q} : rack.inv_act x x = x := sorry protected instance opposite_quandle {Q : Type u_1} [quandle Q] : quandle (Qᵒᵖ) := mk sorry /-- The conjugation quandle of a group. Each element of the group acts by the corresponding inner automorphism. -/ def conj (G : Type u_1) := G protected instance conj.quandle (G : Type u_1) [group G] : quandle (conj G) := mk sorry @[simp] theorem conj_act_eq_conj {G : Type u_1} [group G] (x : conj G) (y : conj G) : shelf.act x y = x * y * (x⁻¹) := rfl theorem conj_swap {G : Type u_1} [group G] (x : conj G) (y : conj G) : shelf.act x y = y ↔ shelf.act y x = x := sorry /-- `conj` is functorial -/ def conj.map {G : Type u_1} {H : Type u_2} [group G] [group H] (f : G →* H) : shelf_hom (conj G) (conj H) := shelf_hom.mk ⇑f sorry protected instance shelf_hom.has_lift {G : Type u_1} {H : Type u_2} [group G] [group H] : has_lift (G →* H) (shelf_hom (conj G) (conj H)) := has_lift.mk conj.map /-- The dihedral quandle. This is the conjugation quandle of the dihedral group restrict to flips. Used for Fox n-colorings of knots. -/ def dihedral (n : ℕ) := zmod n /-- The operation for the dihedral quandle. It does not need to be an equivalence because it is an involution (see `dihedral_act.inv`). -/ def dihedral_act (n : ℕ) (a : zmod n) : zmod n → zmod n := fun (b : zmod n) => bit0 1 * a - b theorem dihedral_act.inv (n : ℕ) (a : zmod n) : function.involutive (dihedral_act n a) := sorry protected instance dihedral.quandle (n : ℕ) : quandle (dihedral n) := mk sorry end quandle namespace rack /-- This is the natural rack homomorphism to the conjugation quandle of the group `R ≃ R` that acts on the rack. -/ def to_conj (R : Type u_1) [rack R] : shelf_hom R (quandle.conj (R ≃ R)) := shelf_hom.mk act ad_conj /-! ### Universal enveloping group of a rack The universal enveloping group `envel_group R` of a rack `R` is the universal group such that every rack homomorphism `R →◃ conj G` is induced by a unique group homomorphism `envel_group R →* G`. For quandles, Joyce called this group `AdConj R`. The `envel_group` functor is left adjoint to the `conj` forgetful functor, and the way we construct the enveloping group is via a technique that should work for left adjoints of forgetful functors in general. It involves thinking a little about 2-categories, but the payoff is that the map `envel_group R →* G` has a nice description. Let's think of a group as being a one-object category. The first step is to define `pre_envel_group`, which gives formal expressions for all the 1-morphisms and includes the unit element, elements of `R`, multiplication, and inverses. To introduce relations, the second step is to define `pre_envel_group_rel'`, which gives formal expressions for all 2-morphisms between the 1-morphisms. The 2-morphisms include associativity, multiplication by the unit, multiplication by inverses, compatibility with multiplication and inverses (`congr_mul` and `congr_inv`), the axioms for an equivalence relation, and, importantly, the relationship between conjugation and the rack action (see `rack.ad_conj`). None of this forms a 2-category yet, for example due to lack of associativity of `trans`. The `pre_envel_group_rel` relation is a `Prop`-valued version of `pre_envel_group_rel'`, and making it `Prop`-valued essentially introduces enough 3-isomorphisms so that every pair of compatible 2-morphisms is isomorphic. Now, while composition in `pre_envel_group` does not strictly satisfy the category axioms, `pre_envel_group` and `pre_envel_group_rel'` do form a weak 2-category. Since we just want a 1-category, the last step is to quotient `pre_envel_group` by `pre_envel_group_rel'`, and the result is the group `envel_group`. For a homomorphism `f : R →◃ conj G`, how does `envel_group.map f : envel_group R →* G` work? Let's think of `G` as being a 2-category with one object, a 1-morphism per element of `G`, and a single 2-morphism called `eq.refl` for each 1-morphism. We define the map using a "higher `quotient.lift`" -- not only do we evaluate elements of `pre_envel_group` as expressions in `G` (this is `to_envel_group.map_aux`), but we evaluate elements of `pre_envel_group'` as expressions of 2-morphisms of `G` (this is `to_envel_group.map_aux.well_def`). That is to say, `to_envel_group.map_aux.well_def` recursively evaluates formal expressions of 2-morphisms as equality proofs in `G`. Now that all morphisms are accounted for, the map descends to a homomorphism `envel_group R →* G`. Note: `Type`-valued relations are not common. The fact it is `Type`-valued is what makes `to_envel_group.map_aux.well_def` have well-founded recursion. -/ /-- Free generators of the enveloping group. -/ inductive pre_envel_group (R : Type u) where | unit : pre_envel_group R | incl : R → pre_envel_group R | mul : pre_envel_group R → pre_envel_group R → pre_envel_group R | inv : pre_envel_group R → pre_envel_group R protected instance pre_envel_group.inhabited (R : Type u) : Inhabited (pre_envel_group R) := { default := pre_envel_group.unit } /-- Relations for the enveloping group. This is a type-valued relation because `to_envel_group.map_aux.well_def` inducts on it to show `to_envel_group.map` is well-defined. The relation `pre_envel_group_rel` is the `Prop`-valued version, which is used to define `envel_group` itself. -/ inductive pre_envel_group_rel' (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Type u where | refl : {a : pre_envel_group R} → pre_envel_group_rel' R a a | symm : {a b : pre_envel_group R} → pre_envel_group_rel' R a b → pre_envel_group_rel' R b a | trans : {a b c : pre_envel_group R} → pre_envel_group_rel' R a b → pre_envel_group_rel' R b c → pre_envel_group_rel' R a c | congr_mul : {a b a' b' : pre_envel_group R} → pre_envel_group_rel' R a a' → pre_envel_group_rel' R b b' → pre_envel_group_rel' R (pre_envel_group.mul a b) (pre_envel_group.mul a' b') | congr_inv : {a a' : pre_envel_group R} → pre_envel_group_rel' R a a' → pre_envel_group_rel' R (pre_envel_group.inv a) (pre_envel_group.inv a') | assoc : (a b c : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul (pre_envel_group.mul a b) c) (pre_envel_group.mul a (pre_envel_group.mul b c)) | one_mul : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul pre_envel_group.unit a) a | mul_one : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul a pre_envel_group.unit) a | mul_left_inv : (a : pre_envel_group R) → pre_envel_group_rel' R (pre_envel_group.mul (pre_envel_group.inv a) a) pre_envel_group.unit | act_incl : (x y : R) → pre_envel_group_rel' R (pre_envel_group.mul (pre_envel_group.mul (pre_envel_group.incl x) (pre_envel_group.incl y)) (pre_envel_group.inv (pre_envel_group.incl x))) (pre_envel_group.incl (shelf.act x y)) protected instance pre_envel_group_rel'.inhabited (R : Type u) [rack R] : Inhabited (pre_envel_group_rel' R pre_envel_group.unit pre_envel_group.unit) := { default := pre_envel_group_rel'.refl } /-- The `pre_envel_group_rel` relation as a `Prop`. Used as the relation for `pre_envel_group.setoid`. -/ inductive pre_envel_group_rel (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Prop where | rel : ∀ {a b : pre_envel_group R}, pre_envel_group_rel' R a b → pre_envel_group_rel R a b /-- A quick way to convert a `pre_envel_group_rel'` to a `pre_envel_group_rel`. -/ theorem pre_envel_group_rel'.rel {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel' R a b → pre_envel_group_rel R a b := pre_envel_group_rel.rel theorem pre_envel_group_rel.refl {R : Type u} [rack R] {a : pre_envel_group R} : pre_envel_group_rel R a a := pre_envel_group_rel.rel pre_envel_group_rel'.refl theorem pre_envel_group_rel.symm {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b a := sorry theorem pre_envel_group_rel.trans {R : Type u} [rack R] {a : pre_envel_group R} {b : pre_envel_group R} {c : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b c → pre_envel_group_rel R a c := sorry protected instance pre_envel_group.setoid (R : Type u_1) [rack R] : setoid (pre_envel_group R) := setoid.mk (pre_envel_group_rel R) sorry /-- The universal enveloping group for the rack R. -/ def envel_group (R : Type u_1) [rack R] := quotient (pre_envel_group.setoid R) -- Define the `group` instances in two steps so `inv` can be inferred correctly. -- TODO: is there a non-invasive way of defining the instance directly? protected instance envel_group.div_inv_monoid (R : Type u_1) [rack R] : div_inv_monoid (envel_group R) := div_inv_monoid.mk (fun (a b : envel_group R) => quotient.lift_on₂ a b (fun (a b : pre_envel_group R) => quotient.mk (pre_envel_group.mul a b)) sorry) sorry (quotient.mk pre_envel_group.unit) sorry sorry (fun (a : envel_group R) => quotient.lift_on a (fun (a : pre_envel_group R) => quotient.mk (pre_envel_group.inv a)) sorry) fun (a b : envel_group R) => quotient.lift_on₂ a (quotient.lift_on b (fun (a : pre_envel_group R) => quotient.mk (pre_envel_group.inv a)) sorry) (fun (a b : pre_envel_group R) => quotient.mk (pre_envel_group.mul a b)) sorry protected instance envel_group.group (R : Type u_1) [rack R] : group (envel_group R) := group.mk div_inv_monoid.mul sorry div_inv_monoid.one sorry sorry div_inv_monoid.inv div_inv_monoid.div sorry protected instance envel_group.inhabited (R : Type u_1) [rack R] : Inhabited (envel_group R) := { default := 1 } /-- The canonical homomorphism from a rack to its enveloping group. Satisfies universal properties given by `to_envel_group.map` and `to_envel_group.univ`. -/ def to_envel_group (R : Type u_1) [rack R] : shelf_hom R (quandle.conj (envel_group R)) := shelf_hom.mk (fun (x : R) => quotient.mk (pre_envel_group.incl x)) sorry /-- The preliminary definition of the induced map from the enveloping group. See `to_envel_group.map`. -/ def to_envel_group.map_aux {R : Type u_1} [rack R] {G : Type u_2} [group G] (f : shelf_hom R (quandle.conj G)) : pre_envel_group R → G := sorry namespace to_envel_group.map_aux /-- Show that `to_envel_group.map_aux` sends equivalent expressions to equal terms. -/ theorem well_def {R : Type u_1} [rack R] {G : Type u_2} [group G] (f : shelf_hom R (quandle.conj G)) {a : pre_envel_group R} {b : pre_envel_group R} : pre_envel_group_rel' R a b → map_aux f a = map_aux f b := sorry end to_envel_group.map_aux /-- Given a map from a rack to a group, lift it to being a map from the enveloping group. More precisely, the `envel_group` functor is left adjoint to `quandle.conj`. -/ def to_envel_group.map {R : Type u_1} [rack R] {G : Type u_2} [group G] : shelf_hom R (quandle.conj G) ≃ (envel_group R →* G) := equiv.mk (fun (f : shelf_hom R (quandle.conj G)) => monoid_hom.mk (fun (x : envel_group R) => quotient.lift_on x (to_envel_group.map_aux f) sorry) sorry sorry) (fun (F : envel_group R →* G) => shelf_hom.comp (quandle.conj.map F) (to_envel_group R)) sorry sorry /-- Given a homomorphism from a rack to a group, it factors through the enveloping group. -/ theorem to_envel_group.univ (R : Type u_1) [rack R] (G : Type u_2) [group G] (f : shelf_hom R (quandle.conj G)) : shelf_hom.comp (quandle.conj.map (coe_fn to_envel_group.map f)) (to_envel_group R) = f := equiv.symm_apply_apply to_envel_group.map f /-- The homomorphism `to_envel_group.map f` is the unique map that fits into the commutative triangle in `to_envel_group.univ`. -/ theorem to_envel_group.univ_uniq (R : Type u_1) [rack R] (G : Type u_2) [group G] (f : shelf_hom R (quandle.conj G)) (g : envel_group R →* G) (h : f = shelf_hom.comp (quandle.conj.map g) (to_envel_group R)) : g = coe_fn to_envel_group.map f := Eq.symm h ▸ Eq.symm (equiv.apply_symm_apply to_envel_group.map g) /-- The induced group homomorphism from the enveloping group into bijections of the rack, using `rack.to_conj`. Satisfies the property `envel_action_prop`. This gives the rack `R` the structure of an augmented rack over `envel_group R`. -/ def envel_action {R : Type u_1} [rack R] : envel_group R →* R ≃ R := coe_fn to_envel_group.map (to_conj R) @[simp] theorem envel_action_prop {R : Type u_1} [rack R] (x : R) (y : R) : coe_fn (coe_fn envel_action (coe_fn (to_envel_group R) x)) y = shelf.act x y := rfl
dcf109ec739c2b64ac7b15db01efc716daa587c1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/dotNameIssue.lean
5198e509f99bd2363089c59b749802dd9fdf7c46
[ "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
163
lean
example : x ≠ y → x ∉ [y] := fun hne hin => match hin with | .head _ => hne rfl example : x ≠ y → x ∉ [y] := fun hne (.head _) => hne rfl
3dab0f80e4fc998e07b0808f38d06ebb1f948c5a
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebraic_topology/simplex_category.lean
e8c9922574dc3f02b0121b05423d484289b62b48
[ "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
30,369
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import tactic.linarith import category_theory.skeletal import data.fintype.sort import order.category.NonemptyFinLinOrd import category_theory.functor.reflects_isomorphisms /-! # The simplex category We construct a skeletal model of the simplex category, with objects `ℕ` and the morphism `n ⟶ m` being the monotone maps from `fin (n+1)` to `fin (m+1)`. We show that this category is equivalent to `NonemptyFinLinOrd`. ## Remarks The definitions `simplex_category` and `simplex_category.hom` are marked as irreducible. We provide the following functions to work with these objects: 1. `simplex_category.mk` creates an object of `simplex_category` out of a natural number. Use the notation `[n]` in the `simplicial` locale. 2. `simplex_category.len` gives the "length" of an object of `simplex_category`, as a natural. 3. `simplex_category.hom.mk` makes a morphism out of a monotone map between `fin`'s. 4. `simplex_category.hom.to_order_hom` gives the underlying monotone map associated to a term of `simplex_category.hom`. -/ universe v open category_theory category_theory.limits /-- The simplex category: * objects are natural numbers `n : ℕ` * morphisms from `n` to `m` are monotone functions `fin (n+1) → fin (m+1)` -/ @[derive inhabited, irreducible] def simplex_category := ℕ namespace simplex_category section local attribute [semireducible] simplex_category -- TODO: Make `mk` irreducible. /-- Interpet a natural number as an object of the simplex category. -/ def mk (n : ℕ) : simplex_category := n localized "notation (name := simplex_category.mk) `[`n`]` := simplex_category.mk n" in simplicial -- TODO: Make `len` irreducible. /-- The length of an object of `simplex_category`. -/ def len (n : simplex_category) : ℕ := n @[ext] lemma ext (a b : simplex_category) : a.len = b.len → a = b := id @[simp] lemma len_mk (n : ℕ) : [n].len = n := rfl @[simp] lemma mk_len (n : simplex_category) : [n.len] = n := rfl /-- A recursor for `simplex_category`. Use it as `induction Δ using simplex_category.rec`. -/ protected def rec {F : Π (Δ : simplex_category), Sort*} (h : ∀ (n : ℕ), F [n]) : Π X, F X := λ n, h n.len /-- Morphisms in the simplex_category. -/ @[irreducible, nolint has_nonempty_instance] protected def hom (a b : simplex_category) := fin (a.len + 1) →o fin (b.len + 1) namespace hom local attribute [semireducible] simplex_category.hom /-- Make a moprhism in `simplex_category` from a monotone map of fin's. -/ def mk {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) : simplex_category.hom a b := f /-- Recover the monotone map from a morphism in the simplex category. -/ def to_order_hom {a b : simplex_category} (f : simplex_category.hom a b) : fin (a.len + 1) →o fin (b.len + 1) := f @[ext] lemma ext {a b : simplex_category} (f g : simplex_category.hom a b) : f.to_order_hom = g.to_order_hom → f = g := id @[simp] lemma mk_to_order_hom {a b : simplex_category} (f : simplex_category.hom a b) : mk (f.to_order_hom) = f := rfl @[simp] lemma to_order_hom_mk {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) : (mk f).to_order_hom = f := rfl lemma mk_to_order_hom_apply {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) (i : fin (a.len + 1)) : (mk f).to_order_hom i = f i := rfl /-- Identity morphisms of `simplex_category`. -/ @[simp] def id (a : simplex_category) : simplex_category.hom a a := mk order_hom.id /-- Composition of morphisms of `simplex_category`. -/ @[simp] def comp {a b c : simplex_category} (f : simplex_category.hom b c) (g : simplex_category.hom a b) : simplex_category.hom a c := mk $ f.to_order_hom.comp g.to_order_hom end hom @[simps] instance small_category : small_category.{0} simplex_category := { hom := λ n m, simplex_category.hom n m, id := λ m, simplex_category.hom.id _, comp := λ _ _ _ f g, simplex_category.hom.comp g f, } /-- The constant morphism from [0]. -/ def const (x : simplex_category) (i : fin (x.len+1)) : [0] ⟶ x := hom.mk $ ⟨λ _, i, by tauto⟩ @[simp] lemma const_comp (x y : simplex_category) (i : fin (x.len + 1)) (f : x ⟶ y) : const x i ≫ f = const y (f.to_order_hom i) := rfl /-- Make a morphism `[n] ⟶ [m]` from a monotone map between fin's. This is useful for constructing morphisms beetween `[n]` directly without identifying `n` with `[n].len`. -/ @[simp] def mk_hom {n m : ℕ} (f : (fin (n+1)) →o (fin (m+1))) : [n] ⟶ [m] := simplex_category.hom.mk f lemma hom_zero_zero (f : [0] ⟶ [0]) : f = 𝟙 _ := by { ext : 2, dsimp, apply subsingleton.elim } end open_locale simplicial section generators /-! ## Generating maps for the simplex category TODO: prove that the simplex category is equivalent to one given by the following generators and relations. -/ /-- The `i`-th face map from `[n]` to `[n+1]` -/ def δ {n} (i : fin (n+2)) : [n] ⟶ [n+1] := mk_hom (fin.succ_above i).to_order_hom /-- The `i`-th degeneracy map from `[n+1]` to `[n]` -/ def σ {n} (i : fin (n+1)) : [n+1] ⟶ [n] := mk_hom { to_fun := fin.pred_above i, monotone' := fin.pred_above_right_monotone i } /-- The generic case of the first simplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : δ i ≫ δ j.succ = δ j ≫ δ i.cast_succ := begin ext k, dsimp [δ, fin.succ_above], simp only [order_embedding.to_order_hom_coe, order_embedding.coe_of_strict_mono, function.comp_app, simplex_category.hom.to_order_hom_mk, order_hom.comp_coe], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, split_ifs; { simp at *; linarith }, end lemma δ_comp_δ' {n} {i : fin (n+2)} {j : fin (n+3)} (H : i.cast_succ < j) : δ i ≫ δ j = δ (j.pred (λ hj, by simpa only [hj, fin.not_lt_zero] using H)) ≫ δ i.cast_succ := begin rw ← δ_comp_δ, { rw fin.succ_pred, }, { simpa only [fin.le_iff_coe_le_coe, ← nat.lt_succ_iff, nat.succ_eq_add_one, ← fin.coe_succ, j.succ_pred, fin.lt_iff_coe_lt_coe] using H, }, end lemma δ_comp_δ'' {n} {i : fin (n+3)} {j : fin (n+2)} (H : i ≤ j.cast_succ) : δ (i.cast_lt (nat.lt_of_le_of_lt (fin.le_iff_coe_le_coe.mp H) j.is_lt)) ≫ δ j.succ = δ j ≫ δ i := begin rw δ_comp_δ, { refl, }, { exact H, }, end /-- The special case of the first simplicial identity -/ @[reassoc] lemma δ_comp_δ_self {n} {i : fin (n+2)} : δ i ≫ δ i.cast_succ = δ i ≫ δ i.succ := (δ_comp_δ (le_refl i)).symm @[reassoc] lemma δ_comp_δ_self' {n} {i : fin (n+2)} {j : fin (n+3)} (H : j = i.cast_succ) : δ i ≫ δ j = δ i ≫ δ i.succ := by { subst H, rw δ_comp_δ_self, } /-- The second simplicial identity -/ @[reassoc] lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : δ i.cast_succ ≫ σ j.succ = σ j ≫ δ i := begin ext k, suffices : ite (j.succ.cast_succ < ite (k < i) k.cast_succ k.succ) (ite (k < i) (k:ℕ) (k + 1) - 1) (ite (k < i) k (k + 1)) = ite ((if h : (j:ℕ) < k then k.pred (by { rintro rfl, exact nat.not_lt_zero _ h }) else k.cast_lt (by { cases j, cases k, simp only [len_mk], linarith })).cast_succ < i) (ite (j.cast_succ < k) (k - 1) k) (ite (j.cast_succ < k) (k - 1) k + 1), { dsimp [δ, σ, fin.succ_above, fin.pred_above], simp [fin.pred_above] with push_cast, convert rfl }, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [fin.mk_le_mk, fin.cast_succ_mk] at H, dsimp, split_ifs, -- Most of the goals can now be handled by `linarith`, -- but we have to deal with two of them by hand. swap 8, { exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) ‹_›)).symm, }, swap 7, { have : k ≤ i := nat.le_of_pred_lt ‹_›, linarith, }, -- Hope for the best from `linarith`: all_goals { try { refl <|> simp at * }; linarith, }, end /-- The first part of the third simplicial identity -/ @[reassoc] lemma δ_comp_σ_self {n} {i : fin (n+1)} : δ i.cast_succ ≫ σ i = 𝟙 [n] := begin ext j, suffices : ite (fin.cast_succ i < ite (j < i) (fin.cast_succ j) j.succ) (ite (j < i) (j:ℕ) (j + 1) - 1) (ite (j < i) j (j + 1)) = j, { dsimp [δ, σ, fin.succ_above, fin.pred_above], simpa [fin.pred_above] with push_cast }, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, dsimp, split_ifs; { simp at *; linarith, }, end @[reassoc] lemma δ_comp_σ_self' {n} {j : fin (n+2)} {i : fin (n+1)} (H : j = i.cast_succ) : δ j ≫ σ i = 𝟙 [n] := by { subst H, rw δ_comp_σ_self, } /-- The second part of the third simplicial identity -/ @[reassoc] lemma δ_comp_σ_succ {n} {i : fin (n+1)} : δ i.succ ≫ σ i = 𝟙 [n] := begin ext j, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, dsimp [δ, σ, fin.succ_above, fin.pred_above], simp [fin.pred_above] with push_cast, split_ifs; { simp at *; linarith, }, end @[reassoc] lemma δ_comp_σ_succ' {n} (j : fin (n+2)) (i : fin (n+1)) (H : j = i.succ) : δ j ≫ σ i = 𝟙 [n] := by { subst H, rw δ_comp_σ_succ, } /-- The fourth simplicial identity -/ @[reassoc] lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : δ i.succ ≫ σ j.cast_succ = σ j ≫ δ i := begin ext k, dsimp [δ, σ, fin.succ_above, fin.pred_above], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [fin.mk_lt_mk, fin.cast_succ_mk] at H, suffices : ite (_ < ite (k < i + 1) _ _) _ _ = ite _ (ite (j < k) (k - 1) k) (ite (j < k) (k - 1) k + 1), { simpa [apply_dite fin.cast_succ, fin.pred_above] with push_cast, }, split_ifs, -- Most of the goals can now be handled by `linarith`, -- but we have to deal with three of them by hand. swap 2, { simp only [fin.mk_lt_mk] at h_1, simp only [not_lt] at h_2, simp only [self_eq_add_right, one_ne_zero], exact lt_irrefl (k - 1) (lt_of_lt_of_le (nat.pred_lt (ne_of_lt (lt_of_le_of_lt (zero_le _) h_1)).symm) (le_trans (nat.le_of_lt_succ h) h_2)) }, swap 4, { simp only [fin.mk_lt_mk] at h_1, simp only [not_lt] at h, simp only [nat.add_succ_sub_one, add_zero], exfalso, exact lt_irrefl _ (lt_of_le_of_lt (nat.le_pred_of_lt (nat.lt_of_succ_le h)) h_3), }, swap 4, { simp only [fin.mk_lt_mk] at h_1, simp only [not_lt] at h_3, simp only [nat.add_succ_sub_one, add_zero], exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) h_2)).symm, }, -- Hope for the best from `linarith`: all_goals { simp at h_1 h_2 ⊢; linarith, }, end @[reassoc] lemma δ_comp_σ_of_gt' {n} {i : fin (n+3)} {j : fin (n+2)} (H : j.succ < i) : δ i ≫ σ j = σ (j.cast_lt ((add_lt_add_iff_right 1).mp (lt_of_lt_of_le (by simpa only [fin.val_eq_coe, ← fin.coe_succ] using fin.lt_iff_coe_lt_coe.mp H) i.is_le))) ≫ δ (i.pred (λ hi, by simpa only [fin.not_lt_zero, hi] using H)) := begin rw ← δ_comp_σ_of_gt, { simpa only [fin.succ_pred], }, { rw [fin.cast_succ_cast_lt, ← fin.succ_lt_succ_iff, fin.succ_pred], exact H, }, end local attribute [simp] fin.pred_mk /-- The fifth simplicial identity -/ @[reassoc] lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : σ i.cast_succ ≫ σ j = σ j.succ ≫ σ i := begin ext k, dsimp [σ, fin.pred_above], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [fin.mk_le_mk] at H, -- At this point `simp with push_cast` makes good progress, but neither `simp?` nor `squeeze_simp` -- return usable sets of lemmas. -- To avoid using a non-terminal simp, we make a `suffices` statement indicating the shape -- of the goal we're looking for, and then use `simpa with push_cast`. -- I'm not sure this is actually much more robust that a non-terminal simp. suffices : ite (_ < dite (i < k) _ _) _ _ = ite (_ < dite (j + 1 < k) _ _) _ _, { simpa [fin.pred_above] with push_cast, }, split_ifs, -- `split_ifs` created 12 goals. -- Most of them are dealt with `by simp at *; linarith`, -- but we pull out two harder ones to do by hand. swap 3, { simp only [not_lt] at h_2, exact false.elim (lt_irrefl (k - 1) (lt_of_lt_of_le (nat.pred_lt (id (ne_of_lt (lt_of_le_of_lt (zero_le i) h)).symm)) (le_trans h_2 (nat.succ_le_of_lt h_1)))) }, swap 3, { simp only [subtype.mk_lt_mk, not_lt] at h_1, exact false.elim (lt_irrefl j (lt_of_lt_of_le (nat.pred_lt_pred (nat.succ_ne_zero j) h_2) h_1)) }, -- Deal with the rest automatically. all_goals { simp at *; linarith, }, end end generators section skeleton /-- The functor that exhibits `simplex_category` as skeleton of `NonemptyFinLinOrd` -/ @[simps obj map] def skeletal_functor : simplex_category ⥤ NonemptyFinLinOrd.{v} := { obj := λ a, NonemptyFinLinOrd.of $ ulift (fin (a.len + 1)), map := λ a b f, ⟨λ i, ulift.up (f.to_order_hom i.down), λ i j h, f.to_order_hom.monotone h⟩, map_id' := λ a, by { ext, simp, }, map_comp' := λ a b c f g, by { ext, simp, }, } lemma skeletal_functor.coe_map {Δ₁ Δ₂ : simplex_category} (f : Δ₁ ⟶ Δ₂) : coe_fn (skeletal_functor.{v}.map f) = ulift.up ∘ f.to_order_hom ∘ ulift.down := rfl lemma skeletal : skeletal simplex_category := λ X Y ⟨I⟩, begin suffices : fintype.card (fin (X.len+1)) = fintype.card (fin (Y.len+1)), { ext, simpa }, { apply fintype.card_congr, refine equiv.ulift.symm.trans (((skeletal_functor ⋙ forget _).map_iso I).to_equiv.trans _), apply equiv.ulift } end namespace skeletal_functor instance : full skeletal_functor.{v} := { preimage := λ a b f, simplex_category.hom.mk ⟨λ i, (f (ulift.up i)).down, λ i j h, f.monotone h⟩, witness' := by { intros m n f, dsimp at *, ext1 ⟨i⟩, ext1, ext1, cases x, simp, } } instance : faithful skeletal_functor.{v} := { map_injective' := λ m n f g h, begin ext1, ext1, ext1 i, apply ulift.up.inj, change (skeletal_functor.map f) ⟨i⟩ = (skeletal_functor.map g) ⟨i⟩, rw h, end } instance : ess_surj skeletal_functor.{v} := { mem_ess_image := λ X, ⟨mk (fintype.card X - 1 : ℕ), ⟨begin have aux : fintype.card X = fintype.card X - 1 + 1, { exact (nat.succ_pred_eq_of_pos $ fintype.card_pos_iff.mpr ⟨⊥⟩).symm, }, let f := mono_equiv_of_fin X aux, have hf := (finset.univ.order_emb_of_fin aux).strict_mono, refine { hom := ⟨λ i, f i.down, _⟩, inv := ⟨λ i, ⟨f.symm i⟩, _⟩, hom_inv_id' := _, inv_hom_id' := _ }, { rintro ⟨i⟩ ⟨j⟩ h, show f i ≤ f j, exact hf.monotone h, }, { intros i j h, show f.symm i ≤ f.symm j, rw ← hf.le_iff_le, show f (f.symm i) ≤ f (f.symm j), simpa only [order_iso.apply_symm_apply], }, { ext1, ext1 ⟨i⟩, ext1, exact f.symm_apply_apply i }, { ext1, ext1 i, exact f.apply_symm_apply i }, end⟩⟩, } noncomputable instance is_equivalence : is_equivalence (skeletal_functor.{v}) := equivalence.of_fully_faithfully_ess_surj skeletal_functor end skeletal_functor /-- The equivalence that exhibits `simplex_category` as skeleton of `NonemptyFinLinOrd` -/ noncomputable def skeletal_equivalence : simplex_category ≌ NonemptyFinLinOrd.{v} := functor.as_equivalence skeletal_functor end skeleton /-- `simplex_category` is a skeleton of `NonemptyFinLinOrd`. -/ noncomputable def is_skeleton_of : is_skeleton_of NonemptyFinLinOrd simplex_category skeletal_functor.{v} := { skel := skeletal, eqv := skeletal_functor.is_equivalence } /-- The truncated simplex category. -/ @[derive small_category] def truncated (n : ℕ) := full_subcategory (λ a : simplex_category, a.len ≤ n) namespace truncated instance {n} : inhabited (truncated n) := ⟨⟨[0],by simp⟩⟩ /-- The fully faithful inclusion of the truncated simplex category into the usual simplex category. -/ @[derive [full, faithful]] def inclusion {n : ℕ} : simplex_category.truncated n ⥤ simplex_category := full_subcategory_inclusion _ end truncated section concrete instance : concrete_category.{0} simplex_category := { forget := { obj := λ i, fin (i.len + 1), map := λ i j f, f.to_order_hom }, forget_faithful := {} } end concrete section epi_mono /-- A morphism in `simplex_category` is a monomorphism precisely when it is an injective function -/ theorem mono_iff_injective {n m : simplex_category} {f : n ⟶ m} : mono f ↔ function.injective f.to_order_hom := begin rw ← functor.mono_map_iff_mono skeletal_equivalence.functor.{0}, dsimp only [skeletal_equivalence, functor.as_equivalence_functor], rw [NonemptyFinLinOrd.mono_iff_injective, skeletal_functor.coe_map, function.injective.of_comp_iff ulift.up_injective, function.injective.of_comp_iff' _ ulift.down_bijective], end /-- A morphism in `simplex_category` is an epimorphism if and only if it is a surjective function -/ lemma epi_iff_surjective {n m : simplex_category} {f: n ⟶ m} : epi f ↔ function.surjective f.to_order_hom := begin rw ← functor.epi_map_iff_epi skeletal_equivalence.functor.{0}, dsimp only [skeletal_equivalence, functor.as_equivalence_functor], rw [NonemptyFinLinOrd.epi_iff_surjective, skeletal_functor.coe_map, function.surjective.of_comp_iff' ulift.up_bijective, function.surjective.of_comp_iff _ ulift.down_surjective], end /-- A monomorphism in `simplex_category` must increase lengths-/ lemma len_le_of_mono {x y : simplex_category} {f : x ⟶ y} : mono f → (x.len ≤ y.len) := begin intro hyp_f_mono, have f_inj : function.injective f.to_order_hom.to_fun, { exact mono_iff_injective.elim_left (hyp_f_mono) }, simpa using fintype.card_le_of_injective f.to_order_hom.to_fun f_inj, end lemma le_of_mono {n m : ℕ} {f : [n] ⟶ [m]} : (category_theory.mono f) → (n ≤ m) := len_le_of_mono /-- An epimorphism in `simplex_category` must decrease lengths-/ lemma len_le_of_epi {x y : simplex_category} {f : x ⟶ y} : epi f → y.len ≤ x.len := begin intro hyp_f_epi, have f_surj : function.surjective f.to_order_hom.to_fun, { exact epi_iff_surjective.elim_left (hyp_f_epi) }, simpa using fintype.card_le_of_surjective f.to_order_hom.to_fun f_surj, end lemma le_of_epi {n m : ℕ} {f : [n] ⟶ [m]} : epi f → (m ≤ n) := len_le_of_epi instance {n : ℕ} {i : fin (n+2)} : mono (δ i) := begin rw mono_iff_injective, exact fin.succ_above_right_injective, end instance {n : ℕ} {i : fin (n+1)} : epi (σ i) := begin rw epi_iff_surjective, intro b, simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk], by_cases b ≤ i, { use b, rw fin.pred_above_below i b (by simpa only [fin.coe_eq_cast_succ] using h), simp only [fin.coe_eq_cast_succ, fin.cast_pred_cast_succ], }, { use b.succ, rw [fin.pred_above_above i b.succ _, fin.pred_succ], rw not_le at h, rw fin.lt_iff_coe_lt_coe at h ⊢, simpa only [fin.coe_succ, fin.coe_cast_succ] using nat.lt.step h, } end instance : reflects_isomorphisms (forget simplex_category) := ⟨begin intros x y f, introI, exact is_iso.of_iso { hom := f, inv := hom.mk { to_fun := inv ((forget simplex_category).map f), monotone' :=λ y₁ y₂ h, begin by_cases h' : y₁ < y₂, { by_contradiction h'', have eq := λ i, congr_hom (iso.inv_hom_id (as_iso ((forget _).map f))) i, have ineq := f.to_order_hom.monotone' (le_of_not_ge h''), dsimp at ineq, erw [eq, eq] at ineq, exact not_le.mpr h' ineq, }, { rw eq_of_le_of_not_lt h h', } end, }, hom_inv_id' := by { ext1, ext1, exact iso.hom_inv_id (as_iso ((forget _).map f)), }, inv_hom_id' := by { ext1, ext1, exact iso.inv_hom_id (as_iso ((forget _).map f)), }, }, end⟩ lemma is_iso_of_bijective {x y : simplex_category} {f : x ⟶ y} (hf : function.bijective (f.to_order_hom.to_fun)) : is_iso f := begin haveI : is_iso ((forget simplex_category).map f) := (is_iso_iff_bijective _).mpr hf, exact is_iso_of_reflects_iso f (forget simplex_category), end /-- An isomorphism in `simplex_category` induces an `order_iso`. -/ @[simp] def order_iso_of_iso {x y : simplex_category} (e : x ≅ y) : fin (x.len+1) ≃o fin (y.len+1) := equiv.to_order_iso { to_fun := e.hom.to_order_hom, inv_fun := e.inv.to_order_hom, left_inv := λ i, by simpa only using congr_arg (λ φ, (hom.to_order_hom φ) i) e.hom_inv_id', right_inv := λ i, by simpa only using congr_arg (λ φ, (hom.to_order_hom φ) i) e.inv_hom_id', } e.hom.to_order_hom.monotone e.inv.to_order_hom.monotone lemma iso_eq_iso_refl {x : simplex_category} (e : x ≅ x) : e = iso.refl x := begin have h : (finset.univ : finset (fin (x.len+1))).card = x.len+1 := finset.card_fin (x.len+1), have eq₁ := finset.order_emb_of_fin_unique' h (λ i, finset.mem_univ ((order_iso_of_iso e) i)), have eq₂ := finset.order_emb_of_fin_unique' h (λ i, finset.mem_univ ((order_iso_of_iso (iso.refl x)) i)), ext1, ext1, convert congr_arg (λ φ, (order_embedding.to_order_hom φ)) (eq₁.trans eq₂.symm), ext1, ext1 i, refl, end lemma eq_id_of_is_iso {x : simplex_category} (f : x ⟶ x) [hf : is_iso f] : f = 𝟙 _ := congr_arg (λ (φ : _ ≅ _), φ.hom) (iso_eq_iso_refl (as_iso f)) lemma eq_σ_comp_of_not_injective' {n : ℕ} {Δ' : simplex_category} (θ : mk (n+1) ⟶ Δ') (i : fin (n+1)) (hi : θ.to_order_hom i.cast_succ = θ.to_order_hom i.succ): ∃ (θ' : mk n ⟶ Δ'), θ = σ i ≫ θ' := begin use δ i.succ ≫ θ, ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp, σ, mk_hom, order_hom.coe_fun_mk], by_cases h' : x ≤ i.cast_succ, { rw fin.pred_above_below i x h', have eq := fin.cast_succ_cast_pred (gt_of_gt_of_ge (fin.cast_succ_lt_last i) h'), erw fin.succ_above_below i.succ x.cast_pred _, swap, { rwa [eq, ← fin.le_cast_succ_iff], }, rw eq, }, { simp only [not_le] at h', let y := x.pred begin intro h, rw h at h', simpa only [fin.lt_iff_coe_lt_coe, nat.not_lt_zero, fin.coe_zero] using h', end, simp only [show x = y.succ, by rw fin.succ_pred] at h' ⊢, rw [fin.pred_above_above i y.succ h', fin.pred_succ], by_cases h'' : y = i, { rw h'', convert hi.symm, erw fin.succ_above_below i.succ _, exact fin.lt_succ, }, { erw fin.succ_above_above i.succ _, simp only [fin.lt_iff_coe_lt_coe, fin.le_iff_coe_le_coe, fin.coe_succ, fin.coe_cast_succ, nat.lt_succ_iff, fin.ext_iff] at h' h'' ⊢, cases nat.le.dest h' with c hc, cases c, { exfalso, rw [add_zero] at hc, rw [hc] at h'', exact h'' rfl, }, { rw ← hc, simp only [add_le_add_iff_left, nat.succ_eq_add_one, le_add_iff_nonneg_left, zero_le], }, }, } end lemma eq_σ_comp_of_not_injective {n : ℕ} {Δ' : simplex_category} (θ : mk (n+1) ⟶ Δ') (hθ : ¬function.injective θ.to_order_hom) : ∃ (i : fin (n+1)) (θ' : mk n ⟶ Δ'), θ = σ i ≫ θ' := begin simp only [function.injective, exists_prop, not_forall] at hθ, -- as θ is not injective, there exists `x<y` such that `θ x = θ y` -- and then, `θ x = θ (x+1)` have hθ₂ : ∃ (x y : fin (n+2)), (hom.to_order_hom θ) x = (hom.to_order_hom θ) y ∧ x<y, { rcases hθ with ⟨x, y, ⟨h₁, h₂⟩⟩, by_cases x<y, { exact ⟨x, y, ⟨h₁, h⟩⟩, }, { refine ⟨y, x, ⟨h₁.symm, _⟩⟩, cases lt_or_eq_of_le (not_lt.mp h) with h' h', { exact h', }, { exfalso, exact h₂ h'.symm, }, }, }, rcases hθ₂ with ⟨x, y, ⟨h₁, h₂⟩⟩, let z := x.cast_pred, use z, simp only [← (show z.cast_succ = x, by exact fin.cast_succ_cast_pred (lt_of_lt_of_le h₂ (fin.le_last y)))] at h₁ h₂, apply eq_σ_comp_of_not_injective', rw fin.cast_succ_lt_iff_succ_le at h₂, apply le_antisymm, { exact θ.to_order_hom.monotone (le_of_lt (fin.cast_succ_lt_succ z)), }, { rw h₁, exact θ.to_order_hom.monotone h₂, }, end lemma eq_comp_δ_of_not_surjective' {n : ℕ} {Δ : simplex_category} (θ : Δ ⟶ mk (n+1)) (i : fin (n+2)) (hi : ∀ x, θ.to_order_hom x ≠ i) : ∃ (θ' : Δ ⟶ (mk n)), θ = θ' ≫ δ i := begin by_cases i < fin.last (n+1), { use θ ≫ σ (fin.cast_pred i), ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp], by_cases h' : θ.to_order_hom x ≤ i, { simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk], rw fin.pred_above_below (fin.cast_pred i) (θ.to_order_hom x) (by simpa [fin.cast_succ_cast_pred h] using h'), erw fin.succ_above_below i, swap, { simp only [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ], exact lt_of_le_of_lt (fin.coe_cast_pred_le_self _) (fin.lt_iff_coe_lt_coe.mp ((ne.le_iff_lt (hi x)).mp h')), }, rw fin.cast_succ_cast_pred, apply lt_of_le_of_lt h' h, }, { simp only [not_le] at h', simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk, fin.pred_above_above (fin.cast_pred i) (θ.to_order_hom x) (by simpa only [fin.cast_succ_cast_pred h] using h')], erw [fin.succ_above_above i _, fin.succ_pred], simpa only [fin.le_iff_coe_le_coe, fin.coe_cast_succ, fin.coe_pred] using nat.le_pred_of_lt (fin.lt_iff_coe_lt_coe.mp h'), }, }, { obtain rfl := le_antisymm (fin.le_last i) (not_lt.mp h), use θ ≫ σ (fin.last _), ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp, σ, δ, mk_hom, order_hom.coe_fun_mk, order_embedding.to_order_hom_coe, fin.pred_above_last, fin.succ_above_last, fin.cast_succ_cast_pred ((ne.le_iff_lt (hi x)).mp (fin.le_last _))], }, end lemma eq_comp_δ_of_not_surjective {n : ℕ} {Δ : simplex_category} (θ : Δ ⟶ mk (n+1)) (hθ : ¬function.surjective θ.to_order_hom) : ∃ (i : fin (n+2)) (θ' : Δ ⟶ (mk n)), θ = θ' ≫ δ i := begin cases not_forall.mp hθ with i hi, use i, exact eq_comp_δ_of_not_surjective' θ i (not_exists.mp hi), end lemma eq_id_of_mono {x : simplex_category} (i : x ⟶ x) [mono i] : i = 𝟙 _ := begin suffices : is_iso i, { haveI := this, apply eq_id_of_is_iso, }, apply is_iso_of_bijective, dsimp, rw [fintype.bijective_iff_injective_and_card i.to_order_hom, ← mono_iff_injective, eq_self_iff_true, and_true], apply_instance, end lemma eq_id_of_epi {x : simplex_category} (i : x ⟶ x) [epi i] : i = 𝟙 _ := begin suffices : is_iso i, { haveI := this, apply eq_id_of_is_iso, }, apply is_iso_of_bijective, dsimp, rw [fintype.bijective_iff_surjective_and_card i.to_order_hom, ← epi_iff_surjective, eq_self_iff_true, and_true], apply_instance, end lemma eq_σ_of_epi {n : ℕ} (θ : mk (n+1) ⟶ mk n) [epi θ] : ∃ (i : fin (n+1)), θ = σ i := begin rcases eq_σ_comp_of_not_injective θ _ with ⟨i, θ', h⟩, swap, { by_contradiction, simpa only [nat.one_ne_zero, add_le_iff_nonpos_right, nonpos_iff_eq_zero] using le_of_mono (mono_iff_injective.mpr h), }, use i, haveI : epi (σ i ≫ θ') := by { rw ← h, apply_instance, }, haveI := category_theory.epi_of_epi (σ i) θ', rw [h, eq_id_of_epi θ', category.comp_id], end lemma eq_δ_of_mono {n : ℕ} (θ : mk n ⟶ mk (n+1)) [mono θ] : ∃ (i : fin (n+2)), θ = δ i := begin rcases eq_comp_δ_of_not_surjective θ _ with ⟨i, θ', h⟩, swap, { by_contradiction, simpa only [add_le_iff_nonpos_right, nonpos_iff_eq_zero] using le_of_epi (epi_iff_surjective.mpr h), }, use i, haveI : mono (θ' ≫ δ i) := by { rw ← h, apply_instance, }, haveI := category_theory.mono_of_mono θ' (δ i), rw [h, eq_id_of_mono θ', category.id_comp], end lemma len_lt_of_mono {Δ' Δ : simplex_category} (i : Δ' ⟶ Δ) [hi : mono i] (hi' : Δ ≠ Δ') : Δ'.len < Δ.len := begin cases lt_or_eq_of_le (len_le_of_mono hi), { exact h, }, { exfalso, exact hi' (by { ext, exact h.symm,}), }, end noncomputable instance : split_epi_category simplex_category := skeletal_equivalence.{0}.inverse.split_epi_category_imp_of_is_equivalence instance : has_strong_epi_mono_factorisations simplex_category := functor.has_strong_epi_mono_factorisations_imp_of_is_equivalence simplex_category.skeletal_equivalence.{0}.inverse instance : has_strong_epi_images simplex_category := limits.has_strong_epi_images_of_has_strong_epi_mono_factorisations instance (Δ Δ' : simplex_category) (θ : Δ ⟶ Δ') : epi (factor_thru_image θ) := strong_epi.epi lemma image_eq {Δ Δ' Δ'' : simplex_category } {φ : Δ ⟶ Δ''} {e : Δ ⟶ Δ'} [epi e] {i : Δ' ⟶ Δ''} [mono i] (fac : e ≫ i = φ) : image φ = Δ' := begin haveI := strong_epi_of_epi e, let e := image.iso_strong_epi_mono e i fac, ext, exact le_antisymm (len_le_of_epi (infer_instance : epi e.hom)) (len_le_of_mono (infer_instance : mono e.hom)), end lemma image_ι_eq {Δ Δ'' : simplex_category } {φ : Δ ⟶ Δ''} {e : Δ ⟶ image φ} [epi e] {i : image φ ⟶ Δ''} [mono i] (fac : e ≫ i = φ) : image.ι φ = i := begin haveI := strong_epi_of_epi e, rw [← image.iso_strong_epi_mono_hom_comp_ι e i fac, simplex_category.eq_id_of_is_iso (image.iso_strong_epi_mono e i fac).hom, category.id_comp], end lemma factor_thru_image_eq {Δ Δ'' : simplex_category } {φ : Δ ⟶ Δ''} {e : Δ ⟶ image φ} [epi e] {i : image φ ⟶ Δ''} [mono i] (fac : e ≫ i = φ) : factor_thru_image φ = e := by rw [← cancel_mono i, fac, ← image_ι_eq fac, image.fac] end epi_mono /-- This functor `simplex_category ⥤ Cat` sends `[n]` (for `n : ℕ`) to the category attached to the ordered set `{0, 1, ..., n}` -/ @[simps obj map] def to_Cat : simplex_category ⥤ Cat.{0} := simplex_category.skeletal_functor ⋙ forget₂ NonemptyFinLinOrd LinearOrder ⋙ forget₂ LinearOrder Lattice ⋙ forget₂ Lattice PartialOrder ⋙ forget₂ PartialOrder Preorder ⋙ Preorder_to_Cat end simplex_category
b14ddb8e91e9660402642107a032c441a92ac7f2
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/list/defs.lean
a6ac69756dbc64311e81dfea00a2463efa3b9dc2
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
19,025
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 Extra definitions on lists. -/ import data.option.defs logic.basic tactic.cache namespace list open function nat universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 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) def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- 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] def head' : list α → option α | [] := none | (a :: l) := some a /-- 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 /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[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) def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- 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 [] /-- 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' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `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 /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end def map_with_index_core (f : ℕ → α → β) : ℕ → list α → list β | k [] := [] | k (a::as) := f k a::(map_with_index_core (k+1) as) def map_with_index (f : ℕ → α → β) (as : list α) : list β := map_with_index_core f 0 as /-- `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) /-- `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 /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `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 /-- `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) /-- `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 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 [] 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`; cf. `sublists'` for a different ordering. 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 def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} 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₂) attribute [simp] forall₂.nil end forall₂ 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) /-- 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 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 [] end permutations def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `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 /-- `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 {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a 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 _) [] def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : _ then some (f ⟨i, h⟩) else none /-- `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 section pairwise variables (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) variables {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⟩ instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ 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 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) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l 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⟩ instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `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 (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠) /-- `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 def reduce_option {α} : list (option α) → list α := list.filter_map id def map_head {α} (f : α → α) : list α → list α | [] := [] | (x :: xs) := f x :: xs def map_last {α} (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: map_last xs /-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty; it returns `x` otherwise -/ @[simp] def ilast' {α} : α → list α → α | a [] := a | a (b::l) := ilast' b l /-- `last' xs` returns the last element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def last' {α} : list α → option α | [] := none | [a] := some a | (b::l) := last' l /- tfae: The Following (propositions) Are Equivalent -/ def tfae (l : list Prop) : Prop := ∀ x ∈ l, ∀ y ∈ l, x ↔ y /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose namespace func /- Definitions for using lists as finite representations of functions with domain ℕ. -/ variables [inhabited α] [inhabited β] @[simp] def set (a : α) : list α → ℕ → list α | (_::as) 0 := a::as | [] 0 := [a] | (h::as) (k+1) := h::(set as k) | [] (k+1) := (default α)::(set ([] : list α) k) @[simp] def get : ℕ → list α → α | _ [] := default α | 0 (a::as) := a | (n+1) (a::as) := get n as def equiv (as1 as2 : list α) : Prop := ∀ (m : nat), get m as1 = get m as2 def neg [has_neg α] (as : list α) := as.map (λ a, -a) @[simp] def pointwise (f : α → β → γ) : list α → list β → list γ | [] [] := [] | [] (b::bs) := map (f $ default α) (b::bs) | (a::as) [] := map (λ x, f x $ default β) (a::as) | (a::as) (b::bs) := (f a b)::(pointwise as bs) def add {α : Type u} [has_zero α] [has_add α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (+) def sub {α : Type u} [has_zero α] [has_sub α] : list α → list α → list α := @pointwise α α α ⟨0⟩ ⟨0⟩ (@has_sub.sub α _) end func end list
2ea05c24f6aed35574cf26537fd6182c8303696c
43390109ab88557e6090f3245c47479c123ee500
/src/chris_hughes_various/lagrange_four_square.lean
3aacae92dfb2289669d6f984e986272fe2614947
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,324
lean
import tactic.find data.nat.prime algebra.group_power tactic.ring data.set.finite .disjoint_finset data.int.modeq universes u v variables {α : Type u} {β : Type v} open nat finset equiv int.modeq nat int local attribute [instance, priority 0] classical.prop_decidable lemma int.mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show (2 : ℤ) ≥ 0, from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : n % 2 ≥ 0 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end lemma nat.sub_le_self (a b : ℕ) : a - b ≤ a := nat.sub_le_sub_left _ (zero_le _) lemma nat.div_mul_le (a) {b} (hb : 0 < b) : a / b * b ≤ a := have h : 0 + a / b * b ≤ a % b + a / b * b := add_le_add (zero_le _) (le_refl _), by rwa [zero_add, mul_comm, nat.mod_add_div, mul_comm] at h lemma int.coe_nat_nonneg (n : ℕ) : (0 : ℤ) ≤ n := int.coe_nat_le.2 (zero_le _) lemma nat.mul_pow (a b n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm] lemma nat.dvd_of_pow_dvd_pow : ∀ {a b n : ℕ}, 0 < n → a ^ n ∣ b ^ n → a ∣ b | a 0 := λ n hn h, dvd_zero _ | a (b+1) := λ n hn h, let d := nat.gcd a (b + 1) in have hd : nat.gcd a (b + 1) = d := rfl, match d, hd with | 0 := λ hd, (eq_zero_of_gcd_eq_zero_right hd).symm ▸ dvd_zero _ | 1 := λ hd, begin have h₁ : a ^ n = 1 := coprime.eq_one_of_dvd (coprime.pow n n hd) h, have := pow_dvd_pow a hn, rw [nat.pow_one, h₁] at this, exact dvd.trans this (one_dvd _), end | (d+2) := λ hd, have (b+1) / (d+2) < (b+1) := div_lt_self dec_trivial dec_trivial, have ha : a = (d+2) * (a / (d+2)) := by rw [← hd, nat.mul_div_cancel' (gcd_dvd_left _ _)], have hb : (b+1) = (d+2) * ((b+1) / (d+2)) := by rw [← hd, nat.mul_div_cancel' (gcd_dvd_right _ _)], have a / (d+2) ∣ (b+1) / (d+2) := nat.dvd_of_pow_dvd_pow hn $ dvd_of_mul_dvd_mul_left (show (d + 2) ^ n > 0, from pos_pow_of_pos _ dec_trivial) (by rwa [← nat.mul_pow, ← nat.mul_pow, ← ha, ← hb]), by rw [ha, hb]; exact mul_dvd_mul_left _ this end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf psigma.snd⟩]} lemma int.nat_abs_pow (a : ℤ) (n : ℕ) : a.nat_abs ^ n = (a ^ n).nat_abs := by induction n; simp [*, nat.pow_succ, _root_.pow_succ, nat_abs_mul, mul_comm] lemma int.dvd_of_pow_dvd_pow {a b : ℤ} {n : ℕ} (hn : 0 < n) (h : a ^ n ∣ b ^ n) : a ∣ b := begin rw [← nat_abs_dvd, ← dvd_nat_abs, ← int.nat_abs_pow, ← int.nat_abs_pow, int.coe_nat_dvd] at h, rw [← nat_abs_dvd, ← dvd_nat_abs, int.coe_nat_dvd], exact nat.dvd_of_pow_dvd_pow hn h end @[simp] lemma int.mod_mod (a b : ℤ) : a % b % b = a % b := or.cases_on (classical.em (b = 0)) (by simp {contextual := tt}) (λ h, int.mod_abs (a % b) b ▸ int.mod_eq_of_lt (int.mod_nonneg _ h) (int.mod_lt _ h)) lemma nat.pow_two (n : ℕ) : n ^ 2 = n * n := by simp [nat.pow_succ, nat.pow_zero] lemma nat.cast_div [division_ring α] [char_zero α] {n m : ℕ} (h : n ∣ m) (hn : n ≠ 0) : ((m / n : ℕ) : α) = (m : α) / n := eq.symm ((div_eq_iff_mul_eq (by rwa nat.cast_ne_zero)).2 (by rw [← nat.cast_mul, nat.div_mul_cancel h])) lemma nat.cast_div_le [linear_ordered_field α] {n m : ℕ} (hm : 0 < m) : ((n / m : ℕ) : α) ≤ (n / m : α) := le_of_mul_le_mul_right (calc ((n / m : ℕ) : α) * m ≤ n : by rw [← nat.cast_mul, nat.cast_le]; exact nat.div_mul_le _ hm ... = (n / m : α) * m : (div_mul_cancel (n : α) (ne_of_lt (nat.cast_lt.2 hm)).symm).symm) (nat.cast_lt.2 hm) lemma nat.prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 := or.cases_on (nat.mod_two_eq_zero_or_one p) (λ h, or.inl (or.resolve_left (hp.2 _ (nat.dvd_of_mod_eq_zero h)) dec_trivial).symm) or.inr lemma nat.prime.odd_iff_ge_three {p : ℕ} (hp : prime p) : p % 2 = 1 ↔ 3 ≤ p := ⟨λ hpo, succ_le_of_lt (lt_of_le_of_ne hp.1 (λ h, by rw ← h at hpo; exact absurd hpo dec_trivial)), λ hp3, or.cases_on (mod_two_eq_zero_or_one p) (λ h, or.cases_on (hp.2 _ (nat.dvd_of_mod_eq_zero h)) (λ h2, absurd h2 dec_trivial) (λ h1, by rw ← h1 at hp3; exact absurd hp3 dec_trivial)) id⟩ lemma int.cast_div [division_ring α] [char_zero α] {i j : ℤ} (h : j ∣ i) (hj : j ≠ 0) : ((i / j : ℤ) : α) = (i : α) / j := eq.symm ((div_eq_iff_mul_eq (by rwa int.cast_ne_zero)).2 (by rw [← int.cast_mul, int.div_mul_cancel h])) lemma int.add_div {i j : ℤ} (k : ℤ) (h : j ∣ i) (hk : j ≠ 0) : i / j + k / j = (i + k) / j := (domain.mul_left_inj hk).1 (let ⟨m, hm⟩ := exists_eq_mul_left_of_dvd h in by rw [hm, mul_add, add_comm _ k, int.add_mul_div_right _ _ hk, int.mul_div_cancel _ hk, mul_add, add_comm]) private lemma mul_self_mod_injective_of_le_half_prime_aux {p : ℕ} (hp : prime p) (hpo : p % 2 = 1) (a b : fin (succ (p / 2))) (h₁ :a.1 ≤ b.1) (h : (a.1 : ℕ) * a.1 ≡ b.1 * b.1 [MOD p]) : a = b := begin have : ∀ i j : ℤ, i * i - j * j = (i - j) * (i + j) := λ i j, by ring, have h₃ : p ∣ b.val - a.val ∨ p ∣ b.val + a.val := by rwa [nat.modeq.modeq_iff_dvd, int.coe_nat_mul, int.coe_nat_mul, this, ← int.coe_nat_sub h₁, ← int.coe_nat_add, ← int.coe_nat_mul, int.coe_nat_dvd, hp.dvd_mul] at h, by_contra hab, have hab' := fin.vne_of_ne hab, cases h₃ with h₃ h₃, { have : p < p := calc p ≤ b.1 - a.1 : le_of_dvd (nat.pos_of_ne_zero (λ h₂, hab' (le_antisymm h₁ (nat.sub_eq_zero_iff_le.1 h₂)))) h₃ ... ≤ b.1 : nat.sub_le_sub_left _ (zero_le _) ... ≤ p / 2 : le_of_lt_succ b.2 ... < p : nat.div_lt_self hp.pos (lt_succ_self _), exact lt_irrefl _ this }, { have : 0 < b.1 + a.1, { cases a.1, exact nat.pos_of_ne_zero hab'.symm, exact succ_pos _ }, have : p < p := calc p ≤ b.1 + a.1 : le_of_dvd this h₃ ... ≤ p / 2 + p / 2 : add_le_add (le_of_lt_succ b.2) (le_of_lt_succ a.2) ... < p : by conv {to_rhs, rw [← nat.mod_add_div p 2, hpo, add_comm, two_mul]}; exact lt_succ_self _, exact lt_irrefl _ this } end lemma mul_self_mod_injective_of_le_half_prime {p : ℕ} (hp : prime p) (hpo : p % 2 = 1) : function.injective (λ a : fin (succ (p / 2)), (a.1 : ℕ) * a.1 % p) := λ a b h, (le_total a.1 b.1).elim (λ h₁, mul_self_mod_injective_of_le_half_prime_aux hp hpo a b h₁ h) (λ h₁, eq.symm (mul_self_mod_injective_of_le_half_prime_aux hp hpo b a h₁ h.symm)) lemma neg_mul_self_mod_add_one_injective_of_le_half_prime {p : ℕ} (hp : prime p) (hpo : p % 2 = 1) : function.injective (λ a : fin (succ (p / 2)), ((-(((a.1 : ℕ) * a.1) + 1 : ℕ) : ℤ) % p).to_nat) := λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : int.to_nat _ = int.to_nat _), have hp0 : (p : ℤ) ≠ 0 := λ (h : (p : ℤ) = (0 : ℕ)), by have := hp.pos; rw int.coe_nat_inj h at this; exact lt_irrefl _ this, begin rw [← int.coe_nat_eq_coe_nat_iff, int.to_nat_of_nonneg (int.mod_nonneg _ hp0), int.to_nat_of_nonneg (int.mod_nonneg _ hp0)] at hxy, have := int.dvd_of_mod_eq_zero (int.mod_eq_mod_iff_mod_sub_eq_zero.1 hxy), rw [sub_neg_eq_add, add_comm, ← sub_eq_add_neg] at this, exact mul_self_mod_injective_of_le_half_prime hp hpo (nat.modeq.modeq_add_cancel_right rfl (nat.modeq.modeq_iff_dvd.2 this)), end lemma modeq_two_square_self (a : ℤ) : a * a ≡ a [ZMOD 2] := or.cases_on (int.mod_two_eq_zero_or_one a) (λ h, have h' : a ≡ 0 [ZMOD 2] := h, ((show a * a ≡ 0 * 0 [ZMOD 2], from modeq_mul h' h').trans h'.symm)) (λ h, @eq.subst _ (λ b, a * a ≡ b [ZMOD 2]) _ _ (mul_one a) (int.modeq.modeq_mul rfl h)) lemma sum_two_squares_of_sum_two_squares_two_mul {n a b : ℤ} (h : a * a + b * b = 2 * n) : ∃ c d : ℤ, c * c + d * d = n := have hs : a * a + b * b ≡ 0 [ZMOD 2] := int.modeq.modeq_zero_iff.2 (h.symm ▸ dvd_mul_right _ _), have hadd : (2 : ℤ) ∣ a + b := int.modeq.modeq_zero_iff.1 (int.modeq.trans (int.modeq.modeq_add (modeq_two_square_self _).symm (modeq_two_square_self _).symm) hs), have hsub : (2 : ℤ) ∣ a - b := begin have : a - b = (a + b) + 2 * -b := by ring, rw this, exact dvd_add hadd (dvd_mul_right _ _), end, have h2 : (2 : ℤ) ≠ 0 := by norm_num, ⟨(a + b) / 2, (a - b) / 2, (domain.mul_left_inj h2).1 (calc 2 * (((a + b) / 2) * ((a + b) / 2) + (a - b) / 2 * ((a - b) / 2)) = (a + b) * ((a + b) / 2) + (a - b) * ((a - b) / 2) : by rw [mul_add (2 : ℤ), ← mul_assoc, ← mul_assoc, int.mul_div_cancel' hadd, int.mul_div_cancel' hsub] ... = a * a + b * b : (domain.mul_right_inj h2).1 (by simp only [add_mul, mul_assoc _ _ (2 : ℤ), int.div_mul_cancel hadd, int.div_mul_cancel hsub]; ring) ... = 2 * n : h ▸ by simp [nat.pow_succ, int.coe_nat_mul, int.coe_nat_add])⟩ open finset function lemma surjective_of_injective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) (hinj : injective f) : surjective f := by haveI : fintype β := fintype.of_equiv _ e; exact λ x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ show fintype.card β ≤ fintype.card α, from fintype.card_congr e ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂) lemma injective_of_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) (hsurj : surjective f) : injective f := by haveI : fintype β := fintype.of_equiv _ e; exact injective_of_has_left_inverse ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (surjective_of_injective_of_equiv e.symm (injective_surj_inv hsurj)) (right_inverse_surj_inv hsurj)⟩ lemma bla12 {p : ℕ} (hp : prime p) (hpo : p % 2 = 1) : ∃ a b : fin (succ (p / 2)), p ∣ a.1 * a.1 + b.1 * b.1 + 1 := have hp0 : (p : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 hp.pos)).symm, let s := image (λ a : fin (succ (p / 2)), a.val * a.val % p) univ in let t := image (λ a : fin (succ (p / 2)), to_nat (-↑(a.val * a.val + 1) % ↑p)) univ in have hs : card s = fintype.card _ := card_image_of_injective univ (mul_self_mod_injective_of_le_half_prime hp hpo), have ht : card t = fintype.card _:= card_image_of_injective univ (neg_mul_self_mod_add_one_injective_of_le_half_prime hp hpo), have hsp : s ⊆ range p := λ x hx, let ⟨y, hy₁, hy₂⟩ := mem_image.1 hx in hy₂ ▸ mem_range.2 (mod_lt _ hp.pos), have htp : t ⊆ range p := λ x hx, let ⟨y, hy₁, hy₂⟩ := mem_image.1 hx in hy₂ ▸ mem_range.2 (int.coe_nat_lt.1 (by rw int.to_nat_of_nonneg (int.mod_nonneg _ hp0); exact int.mod_lt_of_pos _ (int.coe_nat_lt.2 hp.pos))), have hd : ¬ finset.disjoint s t := λ h, begin have := card_le_of_subset (union_subset hsp htp), rw fintype.card_fin at hs ht, rw [card_disjoint_union h, hs, ht, card_range, ← two_mul, ← one_add, mul_add] at this, conv at this { to_rhs, rw [← nat.mod_add_div p 2] }, exact not_lt_of_ge (le_of_add_le_add_right this) (mod_lt _ (succ_pos _)), end, let ⟨n, hn⟩ := classical.not_forall.1 hd in begin rw [not_imp, not_imp] at hn, rcases (mem_image.1 hn.1 ) with ⟨a, _, ha⟩, rcases (mem_image.1 hn.2.1) with ⟨b, _, hb⟩, existsi [a, b], rw [← int.coe_nat_dvd, add_assoc, int.coe_nat_add, ← sub_neg_eq_add, int.dvd_iff_mod_eq_zero, ← int.mod_eq_mod_iff_mod_sub_eq_zero, ← int.coe_nat_mod, ← int.to_nat_of_nonneg (int.mod_nonneg _ hp0), hb, ha] end private def mod_sub_half (n m : ℤ) : ℤ := if ((n % m : ℤ) : ℚ) ≤ m / 2 then (n : ℤ) % m else n % m - m private lemma mod_sub_half_modeq {n m : ℤ} (hm : 0 < m) : mod_sub_half n m ≡ n [ZMOD m] := or.cases_on (classical.em (((n % m : ℤ) : ℚ) ≤ m / 2)) (λ h, begin rw [mod_sub_half, if_pos h], exact int.mod_mod _ _, end) (λ h, begin rw [mod_sub_half, if_neg h], conv {to_rhs, skip, rw ← sub_zero (n : ℤ)}, exact int.modeq.modeq_sub (int.mod_mod _ _) (int.modeq.modeq_zero_iff.2 (dvd_refl _)), end) private lemma mod_sub_half_square {n m : ℤ} (hm : 0 < m) : mod_sub_half n m * mod_sub_half n m ≡ n * n [ZMOD m] := int.modeq.modeq_mul (mod_sub_half_modeq hm) (mod_sub_half_modeq hm) private lemma mod_sub_half_eq_zero {n m : ℤ} (hm : 0 < m) (h : mod_sub_half n m * mod_sub_half n m = 0) : n * n ≡ 0 [ZMOD (m * m)] := have h : _ := eq_zero_of_mul_self_eq_zero h, modeq_zero_iff.2 (mul_dvd_mul (modeq_zero_iff.1 (h ▸ (mod_sub_half_modeq hm).symm)) (modeq_zero_iff.1 (h ▸ (mod_sub_half_modeq hm).symm))) private lemma mod_sub_half_le {n m : ℤ} (hm : 0 < m) : ((abs (mod_sub_half n m) : ℤ) : ℚ) ≤ m / 2 := have hm0 : (m : ℤ) ≠ 0 := (ne_of_lt hm).symm, begin cases classical.em (((n % m : ℤ) : ℚ) ≤ m / 2) with h h, { rwa [mod_sub_half, if_pos h, abs_of_nonneg (int.mod_nonneg (n : ℤ) hm0)] }, { have hmn : (n : ℤ) % m - m < 0 := sub_neg_of_lt (trans_rel_left _ (int.mod_lt _ hm0) (abs_of_pos hm)), rw [mod_sub_half, if_neg h, abs_of_neg hmn, neg_sub, int.cast_sub, sub_le_iff_le_add, ← sub_le_iff_le_add', sub_half], exact le_of_lt (lt_of_not_ge h) } end private lemma mod_sub_half_square_le {n m : ℤ} (hm : 0 < m) : ((mod_sub_half n m * mod_sub_half n m : ℤ) : ℚ) ≤ ((m * m) / 4) := calc ((mod_sub_half n m * mod_sub_half n m : ℤ) : ℚ) = ((abs (mod_sub_half n m) : ℤ) : ℚ) * ((abs (mod_sub_half n m) : ℤ) : ℚ) : by rw [← int.cast_mul, ← abs_mul, abs_mul_self] ... ≤ (m / 2) * (m / 2) : mul_self_le_mul_self (int.cast_nonneg.2 (abs_nonneg _)) (mod_sub_half_le hm) ... = m * m / 4 : by rw [div_mul_div, (show (2 : ℚ) * 2 = 4, from rfl)] private lemma mod_sub_half_lt_of_odd {n m : ℤ} (hm : 0 < m) (hmo : m % 2 = 1) : ((abs (mod_sub_half n m) : ℤ) : ℚ) < m / 2 := let h := (@int.cast_nonneg ℚ _ _).2 (abs_nonneg (mod_sub_half n m)) in have h2 : (2 : ℚ) ≠ 0 := by norm_num, lt_of_le_of_ne (mod_sub_half_le hm) (λ h, begin rw [← domain.mul_left_inj h2, mul_div_cancel' _ h2, (show (2 : ℚ) = ((2 : ℤ) : ℚ), from rfl), ← int.cast_mul, int.cast_inj] at h, have h2m : 2 ∣ m := h ▸ dvd_mul_right _ _, exact absurd ((int.mod_eq_zero_of_dvd h2m).symm.trans hmo) dec_trivial end) lemma four_squares_mul_four_squares {α : Type*} [comm_ring α] (a b c d w x y z : α) : (a * a + b * b + c * c + d * d) * (w * w + x * x + y * y + z * z) = (a * x - w * b + (d * y - z * c)) * (a * x - w * b + (d * y - z * c)) + (a * y - w * c + (b * z - x * d)) * (a * y - w * c + (b * z - x * d)) + (a * z - w * d + (c * x - y * b)) * (a * z - w * d + (c * x - y * b)) + (a * w + b * x + c * y + d * z) * (a * w + b * x + c * y + d * z) := by ring lemma dvd_mul_sub_add_mul_sub {m a b c d w x y z : ℤ} (haw : w ≡ a [ZMOD m]) (hbx : x ≡ b [ZMOD m]) (hcy : y ≡ c [ZMOD m]) (hdz : z ≡ d [ZMOD m]) : m ∣ (a * x - w * b + (d * y - z * c)) := dvd_add (modeq_iff_dvd.1 (modeq_mul haw hbx.symm)) (modeq_iff_dvd.1 (modeq_mul hdz hcy.symm)) lemma int.even_add_even {a b : ℤ} (ha : a % 2 = 0) (hb : b % 2 = 0) : (a + b) % 2 = 0 := show a + b ≡ 0 + 0 [ZMOD 2], from int.modeq.modeq_add ha hb lemma int.odd_add_odd {a b : ℤ} (ha : a % 2 = 1) (hb : b % 2 = 1) : (a + b) % 2 = 0 := show a + b ≡ 1 + 1 [ZMOD 2], from int.modeq.modeq_add ha hb lemma even_sum_four_squares {n a b c d : ℤ} (H : a * a + b * b + c * c + d * d = 2 * n) : ∃ w x y z, w * w + x * x + y * y + z * z = 2 * n ∧ w * w + x * x ≡ 0 [ZMOD 2] ∧ y * y + z * z ≡ 0 [ZMOD 2] := have h' : a * a + b * b + c * c + d * d ≡ 0 [ZMOD 2] := modeq_zero_iff.2 (H.symm ▸ dvd_mul_right _ _), or.cases_on (int.mod_two_eq_zero_or_one (a * a)) (λ ha, or.cases_on (int.mod_two_eq_zero_or_one (b * b)) (λ hb, ⟨a, b, c, d, H, int.even_add_even ha hb, modeq_add_cancel_left (show a * a + b * b ≡ 0 [ZMOD 2], from int.even_add_even ha hb) (int.modeq.trans (by simp) h')⟩) (λ hb, or.cases_on (int.mod_two_eq_zero_or_one (c * c)) (λ hc, ⟨a, c, b, d, by simp [H.symm], int.even_add_even ha hc, modeq_add_cancel_left (show a * a + c * c ≡ 0 [ZMOD 2], from int.even_add_even ha hc) (int.modeq.trans (by simp) h')⟩) (λ hc, ⟨a, d, b, c, by simp [H.symm], modeq_add_cancel_left (show b * b + c * c ≡ 0 [ZMOD 2], from int.odd_add_odd hb hc) (int.modeq.trans (by simp) h'), int.odd_add_odd hb hc⟩))) (λ ha, or.cases_on (int.mod_two_eq_zero_or_one (b * b)) (λ hb, or.cases_on (int.mod_two_eq_zero_or_one (c * c)) (λ hc, ⟨b, c, a, d, by simp [H.symm], int.even_add_even hb hc, modeq_add_cancel_left (show b * b + c * c ≡ 0 [ZMOD 2], from int.even_add_even hb hc) (int.modeq.trans (by simp) h')⟩) (λ hc, ⟨a, c, b, d, by simp [H.symm], int.odd_add_odd ha hc, modeq_add_cancel_left (show a * a + c * c ≡ 0 [ZMOD 2], from int.odd_add_odd ha hc) (int.modeq.trans (by simp) h')⟩)) (λ hb, ⟨a, b, c, d, by simp [H.symm], int.odd_add_odd ha hb, modeq_add_cancel_left (show a * a + b * b ≡ 0 [ZMOD 2], from int.odd_add_odd ha hb) (int.modeq.trans (by simp) h')⟩)) private lemma sum_four_squares_of_sum_four_squares_two_mul {n a b c d : ℤ} (h : a * a + b * b + c * c + d * d = 2 * n) : ∃ a' b' c' d', a' * a' + b' * b' + c' * c' + d' * d' = n := let ⟨a, b, c, d, h, hab, hcd⟩ := even_sum_four_squares h in let ⟨k, hk⟩ := exists_eq_mul_right_of_dvd (modeq_zero_iff.1 hab) in let ⟨l, hl⟩ := exists_eq_mul_right_of_dvd (modeq_zero_iff.1 hcd) in let ⟨a', b', hab'⟩ := sum_two_squares_of_sum_two_squares_two_mul hk in let ⟨c', d', hcd'⟩ := sum_two_squares_of_sum_two_squares_two_mul hl in ⟨a', b', c', d', (domain.mul_left_inj (show (2 : ℤ) ≠ 0, by norm_num)).1 (h ▸ by rw [add_assoc, hab', hcd', mul_add, ← hk, ← hl, ← add_assoc])⟩ section odd_primes variables {p : ℕ} (hp : prime p) (hpo : p % 2 = 1) include hp hpo lemma bla14 {p : ℕ} (hp : prime p) (hpo : p % 2 = 1) {a b : fin (succ (p / 2))} : a.1 * a.1 + b.1 * b.1 + 1 < p * p := have hf : ∀ {a : fin (succ (p / 2))}, (a.1 : ℚ) ≤ p / 2 := λ a, calc (a.1 : ℚ) ≤ ((p / 2 : ℕ) : ℚ) : nat.cast_le.2 (le_of_lt_succ a.2) ... ≤ (p / 2 : ℚ) : nat.cast_div_le dec_trivial, have hp2 : 0 ≤ (p : ℚ) / 2 := div_nonneg (nat.cast_nonneg _) (by norm_num), have h20 : (2 : ℚ) ≠ 0 := by norm_num, (@nat.cast_lt ℚ _ _ _).1 $ calc ((a.1 * a.1 + b.1 * b.1 + 1 : ℕ) : ℚ) = (a.1 : ℚ) * a.1 + b.1 * b.1 + 1 : by simp [nat.cast_mul, nat.cast_add] ... ≤ (p / 2) * (p / 2) + (p / 2) * (p / 2) + 1 : add_le_add (add_le_add (mul_le_mul hf hf (nat.cast_nonneg _) hp2) (mul_le_mul hf hf (nat.cast_nonneg _) hp2)) (le_refl _) ... = ((p : ℚ) * p) / 2 + 1 : by rw [div_mul_div, div_add_div_same, ← mul_two, mul_div_mul_right _ h20 h20] ... < ((p * p : ℕ) : ℚ) : add_lt_of_lt_sub_left (begin rw [nat.cast_mul, sub_half, one_lt_div_iff_lt (show (0 : ℚ) < 2, by norm_num)], exact calc (2 : ℚ) < 3 * 3 : by norm_num ... ≤ (p : ℚ) * (p : ℚ) : mul_self_le_mul_self (by norm_num) (nat.cast_le.2 (hp.odd_iff_ge_three.1 hpo)), end) private lemma exists_sum_four_squares_dvd_prime : ∃ (m : ℕ) (a b c d : ℤ), a * a + b * b + c * c + d * d = m * p ∧ m < p ∧ 0 < m := let ⟨a, b, hab⟩ := bla12 hp hpo in let ⟨m, hm⟩ := exists_eq_mul_left_of_dvd hab in ⟨m, a.1, b.1, 1, 0, by rw [← int.coe_nat_mul m, ← hm]; simp, lt_of_mul_lt_mul_right (by rw ← hm; exact bla14 hp hpo) (nat.zero_le p), pos_of_mul_pos_right (by rw [← hm, add_assoc]; exact succ_pos _) (nat.zero_le p)⟩ private lemma sum_four_squares_odd_prime : ∃ a b c d : ℤ, a * a + b * b + c * c + d * d = p := let h := exists_sum_four_squares_dvd_prime hp hpo in let m := nat.find h in let ⟨a, b, c, d, (habcd : (_ : ℤ) = (↑m : ℤ) * p), (hmp : m < p), (hm0 : 0 < m)⟩ := nat.find_spec h in have hm0' : (0 : ℤ) < m := int.coe_nat_lt.2 hm0, have h₂ : ∃ r : ℤ, mod_sub_half a m * mod_sub_half a m + mod_sub_half b m * mod_sub_half b m + mod_sub_half c m * mod_sub_half c m + mod_sub_half d m * mod_sub_half d m = m * r := exists_eq_mul_right_of_dvd (modeq_zero_iff.1 $ int.modeq.trans (show _ ≡ m * p [ZMOD m], from by rw ← habcd; exact modeq_add (modeq_add (modeq_add (mod_sub_half_square hm0') (mod_sub_half_square hm0')) (mod_sub_half_square hm0')) (mod_sub_half_square hm0')) (show (m : ℤ) * p ≡ 0 [ZMOD m], from modeq_zero_iff.2 (dvd_mul_right m p))), let ⟨r', hr'⟩ := h₂ in have hr0 : (0 : ℤ) ≤ r' := @nonneg_of_mul_nonneg_left _ _ (↑m : ℤ) r' (hr' ▸ add_nonneg (add_nonneg (add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)) (mul_self_nonneg _)) (mul_self_nonneg _)) hm0', let r := r'.nat_abs in have hr : mod_sub_half a ↑m * mod_sub_half a ↑m + mod_sub_half b ↑m * mod_sub_half b ↑m + mod_sub_half c ↑m * mod_sub_half c ↑m + mod_sub_half d ↑m * mod_sub_half d ↑m = ((m * r : ℕ) : ℤ) := show _ = ((_ * r'.nat_abs : ℕ) : ℤ), by rwa [int.coe_nat_mul, int.nat_abs_of_nonneg hr0], have h₁ : m = 1 := by_contradiction $ λ h₁, or.cases_on (mod_two_eq_zero_or_one m) (λ hm2, let ⟨k, hk⟩ := exists_eq_mul_right_of_dvd (dvd_of_mod_eq_zero hm2) in have hk0 : 0 < k := pos_of_mul_pos_left (show 0 < 2 * k, from hk ▸ hm0) (zero_le _), have hkm : k < m := hk.symm ▸ (lt_mul_iff_one_lt_left hk0).2 (lt_succ_self _), begin rw [hk, int.coe_nat_mul, mul_assoc] at habcd, rcases sum_four_squares_of_sum_four_squares_two_mul habcd with ⟨a', b', c', d', habcd'⟩, exact nat.find_min h hkm ⟨a', b', c', d', habcd', lt_trans hkm hmp, hk0⟩, end) (λ hm2, have hm2' : (m : ℤ) % (2 : ℕ) = 1 := by rw [← int.coe_nat_mod, hm2, int.coe_nat_one], have add_quarters : ∀ q : ℚ, q = q / 4 + q / 4 + q / 4 + q / 4 := λ q, by rw [← (show ((2 : ℚ) * 2 = 4), by norm_num), ← div_div_eq_div_mul, add_halves, add_assoc, add_halves, add_halves], have hrm : r < m := lt_of_mul_lt_mul_left (begin rw [← int.coe_nat_lt, ← hr, ← @int.cast_lt ℚ], simp only [int.cast_add, int.cast_coe_nat, nat.cast_mul, nat.cast_add], rw [add_quarters ((m : ℚ) * m)], refine add_lt_add_of_lt_of_le (add_lt_add_of_lt_of_le (add_lt_add_of_lt_of_le _ (mod_sub_half_square_le hm0')) (mod_sub_half_square_le hm0')) (mod_sub_half_square_le hm0'), rw [← (show (2 : ℚ) * 2 = 4, by norm_num), ← div_mul_div, ← abs_mul_self, abs_mul, int.cast_mul], exact mul_self_lt_mul_self (int.cast_nonneg.2 (abs_nonneg _)) (mod_sub_half_lt_of_odd hm0' hm2'), end) (nat.zero_le m), have hmodeq : mod_sub_half a m * mod_sub_half a m + mod_sub_half b m * mod_sub_half b m + mod_sub_half c m * mod_sub_half c m + mod_sub_half d m * mod_sub_half d m ≡ a * a + b * b + c * c + d * d [ZMOD m] := modeq_add (modeq_add (modeq_add (mod_sub_half_square hm0') (mod_sub_half_square hm0')) (mod_sub_half_square hm0')) (mod_sub_half_square hm0'), have hdvd : (m : ℤ) ∣ a * a + b * b + c * c + d * d := habcd.symm ▸ dvd_mul_right _ _, have hdvd₁ : (m : ℤ) ∣ _ := modeq_zero_iff.1 ((modeq.trans hmodeq) (modeq_zero_iff.2 hdvd)), have hr0 : r ≠ 0 := λ h, begin rw [h, mul_zero, int.coe_nat_zero] at hr, simp only [int.nat_abs_mul_self.symm, (int.coe_nat_add _ _).symm] at hr, have hd := eq_zero_of_add_eq_zero (int.coe_nat_inj hr), have hc := eq_zero_of_add_eq_zero hd.1, have hab := eq_zero_of_add_eq_zero hc.1, simp only [(int.coe_nat_eq_coe_nat_iff _ _).symm, int.nat_abs_mul_self] at hab hc hd, have h : a * a + b * b + c * c + d * d ≡ 0 + 0 + 0 + 0 [ZMOD (m * m)] := modeq_add (modeq_add (modeq_add (mod_sub_half_eq_zero hm0' hab.1) (mod_sub_half_eq_zero hm0' hab.2)) (mod_sub_half_eq_zero hm0' hc.2)) (mod_sub_half_eq_zero hm0' hd.2), have : m ∣ p := dvd_of_mul_dvd_mul_left hm0 (by rw [← int.coe_nat_dvd, int.coe_nat_mul, int.coe_nat_mul, ← habcd]; exact modeq_zero_iff.1 h), cases hp.2 _ this with he he, { contradiction }, { rw he at hmp, exact lt_irrefl _ hmp } end, have hk : _ := four_squares_mul_four_squares a b c d (mod_sub_half a m) (mod_sub_half b m) (mod_sub_half c m) (mod_sub_half d m), have ha : _ := @mod_sub_half_modeq a _ hm0', have hb : _ := @mod_sub_half_modeq b _ hm0', have hc : _ := @mod_sub_half_modeq c _ hm0', have hd : _ := @mod_sub_half_modeq d _ hm0', let ⟨a', ha'⟩ := exists_eq_mul_right_of_dvd (dvd_mul_sub_add_mul_sub ha hb hc hd) in let ⟨b', hb'⟩ := exists_eq_mul_right_of_dvd (dvd_mul_sub_add_mul_sub ha hc hd hb) in let ⟨c', hc'⟩ := exists_eq_mul_right_of_dvd (dvd_mul_sub_add_mul_sub ha hd hb hc) in have hm4 : ∀ i j : ℤ, (m : ℤ) * i * (m * j) = (m * m) * (i * j) := λ i j, by simp [mul_comm, mul_assoc, mul_left_comm], begin rw [hr, habcd, ha', hb', hc', int.coe_nat_mul, hm4, hm4, hm4, hm4, ← mul_add, ← mul_add] at hk, have hk' := sub_eq_iff_eq_add'.2 hk, have hd₁ : (m : ℤ) * m ∣ ((a * mod_sub_half a ↑m + b * mod_sub_half b ↑m + c * mod_sub_half c ↑m + d * mod_sub_half d ↑m).nat_abs * (a * mod_sub_half a ↑m + b * mod_sub_half b ↑m + c * mod_sub_half c ↑m + d * mod_sub_half d ↑m).nat_abs : ℕ) := by rw [int.nat_abs_mul_self, ← hk', ← mul_sub]; exact dvd_mul_right _ _, have hd' : (m : ℤ) ∣ (a * mod_sub_half a ↑m + b * mod_sub_half b ↑m + c * mod_sub_half c ↑m + d * mod_sub_half d ↑m) := dvd_nat_abs.1 (int.coe_nat_dvd.2 begin rw [← int.coe_nat_mul, ← nat.pow_two, ← nat.pow_two, int.coe_nat_dvd] at hd₁, exact nat.dvd_of_pow_dvd_pow dec_trivial hd₁, end), cases exists_eq_mul_right_of_dvd hd' with d' hd', have habcd' : a' * a' + b' * b' + c' * c' + d' * d' = ↑r * ↑p := (domain.mul_left_inj (ne_of_lt (mul_pos hm0' hm0')).symm).1 begin rw [mul_comm (r : ℤ), hk, hd'], ring, end, exact nat.find_min h hrm ⟨a', b', c', d', habcd', lt_trans hrm hmp, nat.pos_of_ne_zero (λ h, by rw h at hr0; contradiction)⟩, end), ⟨a, b, c, d, by rw [habcd, h₁]; simp⟩ end odd_primes lemma sum_four_squares_int : ∀ n : ℕ, ∃ a b c d : ℤ, a * a + b * b + c * c + d * d = n | 0 := ⟨0, 0, 0, 0, rfl⟩ | 1 := ⟨1, 0, 0, 0, rfl⟩ | n@(k+2) := have hm : prime (min_fac n) := min_fac_prime dec_trivial, have n / min_fac n < n := factors_lemma, let ⟨a, b, c, d, h₁⟩ := show ∃ a b c d : ℤ, a * a + b * b + c * c + d * d = min_fac n, from or.cases_on hm.eq_two_or_odd (λ h2, h2.symm ▸ ⟨1, 1, 0, 0, rfl⟩) (sum_four_squares_odd_prime hm) in let ⟨w, x, y, z, h₂⟩ := sum_four_squares_int (n / min_fac n) in ⟨a * x - w * b + (d * y - z * c), a * y - w * c + (b * z - x * d), a * z - w * d + (c * x - y * b), a * w + b * x + c * y + d * z, by rw [← four_squares_mul_four_squares, h₁, h₂, ← int.coe_nat_mul, int.coe_nat_eq_coe_nat_iff, nat.mul_div_cancel' (min_fac_dvd _)]⟩ lemma sum_four_squares (n : ℕ) : ∃ a b c d : ℕ, a * a + b * b + c * c + d * d = n := let ⟨a, b, c, d, h⟩ := sum_four_squares_int n in ⟨a.nat_abs, b.nat_abs, c.nat_abs, d.nat_abs, int.coe_nat_inj (h ▸ by simp only [int.coe_nat_add, int.nat_abs_mul_self])⟩
d9c22b51da10c94e4fc011787419e4ae0f804bd0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Control/EState.lean
030f10b142b376a540e6fec2c09f9304698712e5
[ "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,039
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.State import Init.Control.Except import Init.Data.ToString.Basic universe u v namespace EStateM variable {ε σ α : Type u} instance [ToString ε] [ToString α] : ToString (Result ε σ α) where toString | Result.ok a _ => "ok: " ++ toString a | Result.error e _ => "error: " ++ toString e instance [Repr ε] [Repr α] : Repr (Result ε σ α) where reprPrec | Result.error e _, prec => Repr.addAppParen ("EStateM.Result.error " ++ reprArg e) prec | Result.ok a _, prec => Repr.addAppParen ("EStateM.Result.ok " ++ reprArg a) prec end EStateM namespace EStateM variable {ε σ α β : Type u} /-- Alternative orElse operator that allows to select which exception should be used. The default is to use the first exception since the standard `orElse` uses the second. -/ @[always_inline, inline] protected def orElse' {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) (useFirstEx := true) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error e₁ s₁ => match x₂ (Backtrackable.restore s₁ d) with | Result.error e₂ s₂ => Result.error (if useFirstEx then e₁ else e₂) s₂ | ok => ok | ok => ok @[always_inline] instance : MonadFinally (EStateM ε σ) := { tryFinally' := fun x h s => let r := x s match r with | Result.ok a s => match h (some a) s with | Result.ok b s => Result.ok (a, b) s | Result.error e s => Result.error e s | Result.error e₁ s => match h none s with | Result.ok _ s => Result.error e₁ s | Result.error e₂ s => Result.error e₂ s } @[always_inline, inline] def fromStateM {ε σ α : Type} (x : StateM σ α) : EStateM ε σ α := fun s => match x.run s with | (a, s') => EStateM.Result.ok a s' end EStateM
e5f7bb0ae6bee6f7c4051808556a2089426c6e94
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/bump_function_findim.lean
b46cf1c50c964c50c19dcc04ea64dd2b16912efe
[ "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
24,286
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.series import analysis.convolution import analysis.inner_product_space.euclidean_dist import measure_theory.measure.haar.normed_space import data.set.pointwise.support /-! # Bump functions in finite-dimensional vector spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `E` be a finite-dimensional real normed vector space. We show that any open set `s` in `E` is exactly the support of a smooth function taking values in `[0, 1]`, in `is_open.exists_smooth_support_eq`. Then we use this construction to construct bump functions with nice behavior, by convolving the indicator function of `closed_ball 0 1` with a function as above with `s = ball 0 D`. -/ noncomputable theory open set metric topological_space function asymptotics measure_theory finite_dimensional continuous_linear_map filter measure_theory.measure open_locale pointwise topology nnreal big_operators convolution variables {E : Type*} [normed_add_comm_group E] section variables [normed_space ℝ E] [finite_dimensional ℝ E] /-- If a set `s` is a neighborhood of `x`, then there exists a smooth function `f` taking values in `[0, 1]`, supported in `s` and with `f x = 1`. -/ theorem exists_smooth_tsupport_subset {s : set E} {x : E} (hs : s ∈ 𝓝 x) : ∃ (f : E → ℝ), tsupport f ⊆ s ∧ has_compact_support f ∧ cont_diff ℝ ⊤ f ∧ range f ⊆ Icc 0 1 ∧ f x = 1 := begin obtain ⟨d, d_pos, hd⟩ : ∃ (d : ℝ) (hr : 0 < d), euclidean.closed_ball x d ⊆ s, from euclidean.nhds_basis_closed_ball.mem_iff.1 hs, let c : cont_diff_bump (to_euclidean x) := { r := d/2, R := d, r_pos := half_pos d_pos, r_lt_R := half_lt_self d_pos }, let f : E → ℝ := c ∘ to_euclidean, have f_supp : f.support ⊆ euclidean.ball x d, { assume y hy, have : to_euclidean y ∈ function.support c, by simpa only [f, function.mem_support, function.comp_app, ne.def] using hy, rwa c.support_eq at this }, have f_tsupp : tsupport f ⊆ euclidean.closed_ball x d, { rw [tsupport, ← euclidean.closure_ball _ d_pos.ne'], exact closure_mono f_supp }, refine ⟨f, f_tsupp.trans hd, _, _, _, _⟩, { refine is_compact_of_is_closed_bounded is_closed_closure _, have : bounded (euclidean.closed_ball x d), from euclidean.is_compact_closed_ball.bounded, apply this.mono _, refine (is_closed.closure_subset_iff euclidean.is_closed_closed_ball).2 _, exact f_supp.trans euclidean.ball_subset_closed_ball }, { apply c.cont_diff.comp, exact continuous_linear_equiv.cont_diff _ }, { rintros t ⟨y, rfl⟩, exact ⟨c.nonneg, c.le_one⟩ }, { apply c.one_of_mem_closed_ball, apply mem_closed_ball_self, exact (half_pos d_pos).le } end /-- Given an open set `s` in a finite-dimensional real normed vector space, there exists a smooth function with values in `[0, 1]` whose support is exactly `s`. -/ theorem is_open.exists_smooth_support_eq {s : set E} (hs : is_open s) : ∃ (f : E → ℝ), f.support = s ∧ cont_diff ℝ ⊤ f ∧ set.range f ⊆ set.Icc 0 1 := begin /- For any given point `x` in `s`, one can construct a smooth function with support in `s` and nonzero at `x`. By second-countability, it follows that we may cover `s` with the supports of countably many such functions, say `g i`. Then `∑ i, r i • g i` will be the desired function if `r i` is a sequence of positive numbers tending quickly enough to zero. Indeed, this ensures that, for any `k ≤ i`, the `k`-th derivative of `r i • g i` is bounded by a prescribed (summable) sequence `u i`. From this, the summability of the series and of its successive derivatives follows. -/ rcases eq_empty_or_nonempty s with rfl|h's, { exact ⟨(λ x, 0), function.support_zero, cont_diff_const, by simp only [range_const, singleton_subset_iff, left_mem_Icc, zero_le_one]⟩ }, let ι := {f : E → ℝ // f.support ⊆ s ∧ has_compact_support f ∧ cont_diff ℝ ⊤ f ∧ range f ⊆ Icc 0 1}, obtain ⟨T, T_count, hT⟩ : ∃ T : set ι, T.countable ∧ (⋃ f ∈ T, support (f : E → ℝ)) = s, { have : (⋃ (f : ι), (f : E → ℝ).support) = s, { refine subset.antisymm (Union_subset (λ f, f.2.1)) _, assume x hx, rcases exists_smooth_tsupport_subset (hs.mem_nhds hx) with ⟨f, hf⟩, let g : ι := ⟨f, (subset_tsupport f).trans hf.1, hf.2.1, hf.2.2.1, hf.2.2.2.1⟩, have : x ∈ support (g : E → ℝ), by simp only [hf.2.2.2.2, subtype.coe_mk, mem_support, ne.def, one_ne_zero, not_false_iff], exact mem_Union_of_mem _ this }, simp_rw ← this, apply is_open_Union_countable, rintros ⟨f, hf⟩, exact hf.2.2.1.continuous.is_open_support }, obtain ⟨g0, hg⟩ : ∃ (g0 : ℕ → ι), T = range g0, { apply countable.exists_eq_range T_count, rcases eq_empty_or_nonempty T with rfl|hT, { simp only [Union_false, Union_empty] at hT, simp only [←hT, not_nonempty_empty] at h's, exact h's.elim }, { exact hT } }, let g : ℕ → E → ℝ := λ n, (g0 n).1, have g_s : ∀ n, support (g n) ⊆ s := λ n, (g0 n).2.1, have s_g : ∀ x ∈ s, ∃ n, x ∈ support (g n), { assume x hx, rw ← hT at hx, obtain ⟨i, iT, hi⟩ : ∃ (i : ι) (hi : i ∈ T), x ∈ support (i : E → ℝ), by simpa only [mem_Union] using hx, rw [hg, mem_range] at iT, rcases iT with ⟨n, hn⟩, rw ← hn at hi, exact ⟨n, hi⟩ }, have g_smooth : ∀ n, cont_diff ℝ ⊤ (g n) := λ n, (g0 n).2.2.2.1, have g_comp_supp : ∀ n, has_compact_support (g n) := λ n, (g0 n).2.2.1, have g_nonneg : ∀ n x, 0 ≤ g n x, from λ n x, ((g0 n).2.2.2.2 (mem_range_self x)).1, obtain ⟨δ, δpos, c, δc, c_lt⟩ : ∃ (δ : ℕ → ℝ≥0), (∀ (i : ℕ), 0 < δ i) ∧ ∃ (c : nnreal), has_sum δ c ∧ c < 1, from nnreal.exists_pos_sum_of_countable one_ne_zero ℕ, have : ∀ (n : ℕ), ∃ (r : ℝ), 0 < r ∧ ∀ i ≤ n, ∀ x, ‖iterated_fderiv ℝ i (r • g n) x‖ ≤ δ n, { assume n, have : ∀ i, ∃ R, ∀ x, ‖iterated_fderiv ℝ i (λ x, g n x) x‖ ≤ R, { assume i, have : bdd_above (range (λ x, ‖iterated_fderiv ℝ i (λ (x : E), g n x) x‖)), { apply ((g_smooth n).continuous_iterated_fderiv le_top).norm .bdd_above_range_of_has_compact_support, apply has_compact_support.comp_left _ norm_zero, apply (g_comp_supp n).iterated_fderiv }, rcases this with ⟨R, hR⟩, exact ⟨R, λ x, hR (mem_range_self _)⟩ }, choose R hR using this, let M := max (((finset.range (n+1)).image R).max' (by simp)) 1, have M_pos : 0 < M := zero_lt_one.trans_le (le_max_right _ _), have δnpos : 0 < δ n := δpos n, have IR : ∀ i ≤ n, R i ≤ M, { assume i hi, refine le_trans _ (le_max_left _ _), apply finset.le_max', apply finset.mem_image_of_mem, simp only [finset.mem_range], linarith }, refine ⟨M⁻¹ * δ n, by positivity, λ i hi x, _⟩, calc ‖iterated_fderiv ℝ i ((M⁻¹ * δ n) • g n) x‖ = ‖(M⁻¹ * δ n) • iterated_fderiv ℝ i (g n) x‖ : by { rw iterated_fderiv_const_smul_apply, exact (g_smooth n).of_le le_top } ... = M⁻¹ * δ n * ‖iterated_fderiv ℝ i (g n) x‖ : by { rw [norm_smul, real.norm_of_nonneg], positivity } ... ≤ M⁻¹ * δ n * M : mul_le_mul_of_nonneg_left ((hR i x).trans (IR i hi)) (by positivity) ... = δ n : by field_simp [M_pos.ne'] }, choose r rpos hr using this, have S : ∀ x, summable (λ n, (r n • g n) x), { assume x, refine summable_of_nnnorm_bounded _ δc.summable (λ n, _), rw [← nnreal.coe_le_coe, coe_nnnorm], simpa only [norm_iterated_fderiv_zero] using hr n 0 (zero_le n) x }, refine ⟨λ x, (∑' n, (r n • g n) x), _, _, _⟩, { apply subset.antisymm, { assume x hx, simp only [pi.smul_apply, algebra.id.smul_eq_mul, mem_support, ne.def] at hx, contrapose! hx, have : ∀ n, g n x = 0, { assume n, contrapose! hx, exact g_s n hx }, simp only [this, mul_zero, tsum_zero] }, { assume x hx, obtain ⟨n, hn⟩ : ∃ n, x ∈ support (g n), from s_g x hx, have I : 0 < r n * g n x, from mul_pos (rpos n) (lt_of_le_of_ne (g_nonneg n x) (ne.symm hn)), exact ne_of_gt (tsum_pos (S x) (λ i, mul_nonneg (rpos i).le (g_nonneg i x)) n I) } }, { refine cont_diff_tsum_of_eventually (λ n, (g_smooth n).const_smul _) (λ k hk, (nnreal.has_sum_coe.2 δc).summable) _, assume i hi, simp only [nat.cofinite_eq_at_top, pi.smul_apply, algebra.id.smul_eq_mul, filter.eventually_at_top, ge_iff_le], exact ⟨i, λ n hn x, hr _ _ hn _⟩ }, { rintros - ⟨y, rfl⟩, refine ⟨tsum_nonneg (λ n, mul_nonneg (rpos n).le (g_nonneg n y)), le_trans _ c_lt.le⟩, have A : has_sum (λ n, (δ n : ℝ)) c, from nnreal.has_sum_coe.2 δc, rw ← A.tsum_eq, apply tsum_le_tsum _ (S y) A.summable, assume n, apply (le_abs_self _).trans, simpa only [norm_iterated_fderiv_zero] using hr n 0 (zero_le n) y } end end section namespace exists_cont_diff_bump_base /-- An auxiliary function to construct partitions of unity on finite-dimensional real vector spaces. It is the characteristic function of the closed unit ball. -/ def φ : E → ℝ := (closed_ball (0 : E) 1).indicator (λ y, (1 : ℝ)) variables [normed_space ℝ E] [finite_dimensional ℝ E] section helper_definitions variable (E) lemma u_exists : ∃ u : E → ℝ, cont_diff ℝ ⊤ u ∧ (∀ x, u x ∈ Icc (0 : ℝ) 1) ∧ (support u = ball 0 1) ∧ (∀ x, u (-x) = u x) := begin have A : is_open (ball (0 : E) 1), from is_open_ball, obtain ⟨f, f_support, f_smooth, f_range⟩ : ∃ (f : E → ℝ), f.support = ball (0 : E) 1 ∧ cont_diff ℝ ⊤ f ∧ set.range f ⊆ set.Icc 0 1, from A.exists_smooth_support_eq, have B : ∀ x, f x ∈ Icc (0 : ℝ) 1 := λ x, f_range (mem_range_self x), refine ⟨λ x, (f x + f (-x)) / 2, _, _, _, _⟩, { exact (f_smooth.add (f_smooth.comp cont_diff_neg)).div_const _ }, { assume x, split, { linarith [(B x).1, (B (-x)).1] }, { linarith [(B x).2, (B (-x)).2] } }, { refine support_eq_iff.2 ⟨λ x hx, _, λ x hx, _⟩, { apply ne_of_gt, have : 0 < f x, { apply lt_of_le_of_ne (B x).1 (ne.symm _), rwa ← f_support at hx }, linarith [(B (-x)).1] }, { have I1 : x ∉ support f, by rwa f_support, have I2 : -x ∉ support f, { rw f_support, simp only at hx, simpa using hx }, simp only [mem_support, not_not] at I1 I2, simp only [I1, I2, add_zero, zero_div] } }, { assume x, simp only [add_comm, neg_neg] } end variable {E} /-- An auxiliary function to construct partitions of unity on finite-dimensional real vector spaces, which is smooth, symmetric, and with support equal to the unit ball. -/ def u (x : E) : ℝ := classical.some (u_exists E) x variable (E) lemma u_smooth : cont_diff ℝ ⊤ (u : E → ℝ) := (classical.some_spec (u_exists E)).1 lemma u_continuous : continuous (u : E → ℝ) := (u_smooth E).continuous lemma u_support : support (u : E → ℝ) = ball 0 1 := (classical.some_spec (u_exists E)).2.2.1 lemma u_compact_support : has_compact_support (u : E → ℝ) := begin rw [has_compact_support_def, u_support, closure_ball (0 : E) one_ne_zero], exact is_compact_closed_ball _ _, end variable {E} lemma u_nonneg (x : E) : 0 ≤ u x := ((classical.some_spec (u_exists E)).2.1 x).1 lemma u_le_one (x : E) : u x ≤ 1 := ((classical.some_spec (u_exists E)).2.1 x).2 lemma u_neg (x : E) : u (-x) = u x := (classical.some_spec (u_exists E)).2.2.2 x variables [measurable_space E] [borel_space E] local notation `μ` := measure_theory.measure.add_haar variable (E) lemma u_int_pos : 0 < ∫ (x : E), u x ∂μ := begin refine (integral_pos_iff_support_of_nonneg u_nonneg _).mpr _, { exact (u_continuous E).integrable_of_has_compact_support (u_compact_support E) }, { rw u_support, exact measure_ball_pos _ _ zero_lt_one } end variable {E} /-- An auxiliary function to construct partitions of unity on finite-dimensional real vector spaces, which is smooth, symmetric, with support equal to the ball of radius `D` and integral `1`. -/ def W (D : ℝ) (x : E) : ℝ := ((∫ (x : E), u x ∂μ) * |D|^(finrank ℝ E))⁻¹ • u (D⁻¹ • x) lemma W_def (D : ℝ) : (W D : E → ℝ) = λ x, ((∫ (x : E), u x ∂μ) * |D|^(finrank ℝ E))⁻¹ • u (D⁻¹ • x) := by { ext1 x, refl } lemma W_nonneg (D : ℝ) (x : E) : 0 ≤ W D x := begin apply mul_nonneg _ (u_nonneg _), apply inv_nonneg.2, apply mul_nonneg (u_int_pos E).le, apply pow_nonneg (abs_nonneg D) end lemma W_mul_φ_nonneg (D : ℝ) (x y : E) : 0 ≤ W D y * φ (x - y) := mul_nonneg (W_nonneg D y) (indicator_nonneg (by simp only [zero_le_one, implies_true_iff]) _) variable (E) lemma W_integral {D : ℝ} (Dpos : 0 < D) : ∫ (x : E), W D x ∂μ = 1 := begin simp_rw [W, integral_smul], rw [integral_comp_inv_smul_of_nonneg μ (u : E → ℝ) Dpos.le, abs_of_nonneg Dpos.le, mul_comm], field_simp [Dpos.ne', (u_int_pos E).ne'], end lemma W_support {D : ℝ} (Dpos : 0 < D) : support (W D : E → ℝ) = ball 0 D := begin have B : D • ball (0 : E) 1 = ball 0 D, by rw [smul_unit_ball Dpos.ne', real.norm_of_nonneg Dpos.le], have C : D ^ finrank ℝ E ≠ 0, from pow_ne_zero _ Dpos.ne', simp only [W_def, algebra.id.smul_eq_mul, support_mul, support_inv, univ_inter, support_comp_inv_smul₀ Dpos.ne', u_support, B, support_const (u_int_pos E).ne', support_const C, abs_of_nonneg Dpos.le], end lemma W_compact_support {D : ℝ} (Dpos : 0 < D) : has_compact_support (W D : E → ℝ) := begin rw [has_compact_support_def, W_support E Dpos, closure_ball (0 : E) Dpos.ne'], exact is_compact_closed_ball _ _, end variable {E} /-- An auxiliary function to construct partitions of unity on finite-dimensional real vector spaces. It is the convolution between a smooth function of integral `1` supported in the ball of radius `D`, with the indicator function of the closed unit ball. Therefore, it is smooth, equal to `1` on the ball of radius `1 - D`, with support equal to the ball of radius `1 + D`. -/ def Y (D : ℝ) : E → ℝ := W D ⋆[lsmul ℝ ℝ, μ] φ lemma Y_neg (D : ℝ) (x : E) : Y D (-x) = Y D x := begin apply convolution_neg_of_neg_eq, { apply eventually_of_forall (λ x, _), simp only [W_def, u_neg, smul_neg, algebra.id.smul_eq_mul, mul_eq_mul_left_iff, eq_self_iff_true, true_or], }, { apply eventually_of_forall (λ x, _), simp only [φ, indicator, mem_closed_ball_zero_iff, norm_neg] }, end lemma Y_eq_one_of_mem_closed_ball {D : ℝ} {x : E} (Dpos : 0 < D) (hx : x ∈ closed_ball (0 : E) (1 - D)) : Y D x = 1 := begin change (W D ⋆[lsmul ℝ ℝ, μ] φ) x = 1, have B : ∀ (y : E), y ∈ ball x D → φ y = 1, { have C : ball x D ⊆ ball 0 1, { apply ball_subset_ball', simp only [mem_closed_ball] at hx, linarith only [hx] }, assume y hy, simp only [φ, indicator, mem_closed_ball, ite_eq_left_iff, not_le, zero_ne_one], assume h'y, linarith only [mem_ball.1 (C hy), h'y] }, have Bx : φ x = 1, from B _ (mem_ball_self Dpos), have B' : ∀ y, y ∈ ball x D → φ y = φ x, by { rw Bx, exact B }, rw convolution_eq_right' _ (le_of_eq (W_support E Dpos)) B', simp only [lsmul_apply, algebra.id.smul_eq_mul, integral_mul_right, W_integral E Dpos, Bx, one_mul], end lemma Y_eq_zero_of_not_mem_ball {D : ℝ} {x : E} (Dpos : 0 < D) (hx : x ∉ ball (0 : E) (1 + D)) : Y D x = 0 := begin change (W D ⋆[lsmul ℝ ℝ, μ] φ) x = 0, have B : ∀ y, y ∈ ball x D → φ y = 0, { assume y hy, simp only [φ, indicator, mem_closed_ball_zero_iff, ite_eq_right_iff, one_ne_zero], assume h'y, have C : ball y D ⊆ ball 0 (1+D), { apply ball_subset_ball', rw ← dist_zero_right at h'y, linarith only [h'y] }, exact hx (C (mem_ball_comm.1 hy)) }, have Bx : φ x = 0, from B _ (mem_ball_self Dpos), have B' : ∀ y, y ∈ ball x D → φ y = φ x, by { rw Bx, exact B }, rw convolution_eq_right' _ (le_of_eq (W_support E Dpos)) B', simp only [lsmul_apply, algebra.id.smul_eq_mul, Bx, mul_zero, integral_const] end lemma Y_nonneg (D : ℝ) (x : E) : 0 ≤ Y D x := integral_nonneg (W_mul_φ_nonneg D x) lemma Y_le_one {D : ℝ} (x : E) (Dpos : 0 < D) : Y D x ≤ 1 := begin have A : (W D ⋆[lsmul ℝ ℝ, μ] φ) x ≤ (W D ⋆[lsmul ℝ ℝ, μ] 1) x, { apply convolution_mono_right_of_nonneg _ (W_nonneg D) (indicator_le_self' (λ x hx, zero_le_one)) (λ x, zero_le_one), refine (has_compact_support.convolution_exists_left _ (W_compact_support E Dpos) _ (locally_integrable_const (1 : ℝ)) x).integrable, exact continuous_const.mul ((u_continuous E).comp (continuous_id.const_smul _)) }, have B : (W D ⋆[lsmul ℝ ℝ, μ] (λ y, (1 : ℝ))) x = 1, by simp only [convolution, continuous_linear_map.map_smul, mul_inv_rev, coe_smul', mul_one, lsmul_apply, algebra.id.smul_eq_mul, integral_mul_left, W_integral E Dpos, pi.smul_apply], exact A.trans (le_of_eq B) end lemma Y_pos_of_mem_ball {D : ℝ} {x : E} (Dpos : 0 < D) (D_lt_one : D < 1) (hx : x ∈ ball (0 : E) (1 + D)) : 0 < Y D x := begin simp only [mem_ball_zero_iff] at hx, refine (integral_pos_iff_support_of_nonneg (W_mul_φ_nonneg D x) _).2 _, { have F_comp : has_compact_support (W D), from W_compact_support E Dpos, have B : locally_integrable (φ : E → ℝ) μ, from (locally_integrable_const _).indicator measurable_set_closed_ball, have C : continuous (W D : E → ℝ), from continuous_const.mul ((u_continuous E).comp (continuous_id.const_smul _)), exact (has_compact_support.convolution_exists_left (lsmul ℝ ℝ : ℝ →L[ℝ] ℝ →L[ℝ] ℝ) F_comp C B x).integrable }, { set z := (D / (1 + D)) • x with hz, have B : 0 < 1 + D, by linarith, have C : ball z (D * (1 + D- ‖x‖) / (1 + D)) ⊆ support (λ (y : E), W D y * φ (x - y)), { assume y hy, simp only [support_mul, W_support E Dpos], simp only [φ, mem_inter_iff, mem_support, ne.def, indicator_apply_eq_zero, mem_closed_ball_zero_iff, one_ne_zero, not_forall, not_false_iff, exists_prop, and_true], split, { apply ball_subset_ball' _ hy, simp only [z, norm_smul, abs_of_nonneg Dpos.le, abs_of_nonneg B.le, dist_zero_right, real.norm_eq_abs, abs_div], simp only [div_le_iff B] with field_simps, ring_nf }, { have ID : ‖D / (1 + D) - 1‖ = 1 / (1 + D), { rw real.norm_of_nonpos, { simp only [B.ne', ne.def, not_false_iff, mul_one, neg_sub, add_tsub_cancel_right] with field_simps}, { simp only [B.ne', ne.def, not_false_iff, mul_one] with field_simps, apply div_nonpos_of_nonpos_of_nonneg _ B.le, linarith only, } }, rw ← mem_closed_ball_iff_norm', apply closed_ball_subset_closed_ball' _ (ball_subset_closed_ball hy), rw [← one_smul ℝ x, dist_eq_norm, hz, ← sub_smul, one_smul, norm_smul, ID], simp only [-one_div, -mul_eq_zero, B.ne', div_le_iff B] with field_simps, simp only [mem_ball_zero_iff] at hx, nlinarith only [hx, D_lt_one] } }, apply lt_of_lt_of_le _ (measure_mono C), apply measure_ball_pos, exact div_pos (mul_pos Dpos (by linarith only [hx])) B } end variable (E) lemma Y_smooth : cont_diff_on ℝ ⊤ (uncurry Y) ((Ioo (0 : ℝ) 1) ×ˢ (univ : set E)) := begin have hs : is_open (Ioo (0 : ℝ) (1 : ℝ)), from is_open_Ioo, have hk : is_compact (closed_ball (0 : E) 1), from proper_space.is_compact_closed_ball _ _, refine cont_diff_on_convolution_left_with_param (lsmul ℝ ℝ) hs hk _ _ _, { rintros p x hp hx, simp only [W, mul_inv_rev, algebra.id.smul_eq_mul, mul_eq_zero, inv_eq_zero], right, contrapose! hx, have : p⁻¹ • x ∈ support u, from mem_support.2 hx, simp only [u_support, norm_smul, mem_ball_zero_iff, real.norm_eq_abs, abs_inv, abs_of_nonneg hp.1.le, ← div_eq_inv_mul, div_lt_one hp.1] at this, rw mem_closed_ball_zero_iff, exact this.le.trans hp.2.le }, { exact (locally_integrable_const _).indicator measurable_set_closed_ball }, { apply cont_diff_on.mul, { refine (cont_diff_on_const.mul _).inv (λ x hx, ne_of_gt (mul_pos (u_int_pos E) (pow_pos (abs_pos_of_pos hx.1.1) _))), apply cont_diff_on.pow, simp_rw [← real.norm_eq_abs], apply @cont_diff_on.norm ℝ, { exact cont_diff_on_fst }, { assume x hx, exact ne_of_gt hx.1.1 } }, { apply (u_smooth E).comp_cont_diff_on, exact cont_diff_on.smul (cont_diff_on_fst.inv (λ x hx, ne_of_gt hx.1.1)) cont_diff_on_snd } }, end lemma Y_support {D : ℝ} (Dpos : 0 < D) (D_lt_one : D < 1) : support (Y D : E → ℝ) = ball (0 : E) (1 + D) := support_eq_iff.2 ⟨λ x hx, (Y_pos_of_mem_ball Dpos D_lt_one hx).ne', λ x hx, Y_eq_zero_of_not_mem_ball Dpos hx⟩ variable {E} end helper_definitions @[priority 100] instance {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [finite_dimensional ℝ E] : has_cont_diff_bump E := begin refine ⟨⟨_⟩⟩, borelize E, have IR : ∀ (R : ℝ), 1 < R → 0 < (R - 1) / (R + 1), { assume R hR, apply div_pos; linarith }, exact { to_fun := λ R x, if 1 < R then Y ((R - 1) / (R + 1)) (((R + 1) / 2)⁻¹ • x) else 0, mem_Icc := λ R x, begin split_ifs, { refine ⟨Y_nonneg _ _, Y_le_one _ (IR R h)⟩ }, { simp only [pi.zero_apply, left_mem_Icc, zero_le_one] } end, symmetric := λ R x, begin split_ifs, { simp only [Y_neg, smul_neg] }, { refl }, end, smooth := begin suffices : cont_diff_on ℝ ⊤ ((uncurry Y) ∘ (λ (p : ℝ × E), ((p.1 - 1) / (p.1 + 1), ((p.1 + 1)/2)⁻¹ • p.2))) (Ioi 1 ×ˢ univ), { apply this.congr, rintros ⟨R, x⟩ ⟨(hR : 1 < R), hx⟩, simp only [hR, uncurry_apply_pair, if_true, comp_app], }, apply (Y_smooth E).comp, { apply cont_diff_on.prod, { refine (cont_diff_on_fst.sub cont_diff_on_const).div (cont_diff_on_fst.add cont_diff_on_const) _, rintros ⟨R, x⟩ ⟨(hR : 1 < R), hx⟩, apply ne_of_gt, dsimp only, linarith, }, { apply cont_diff_on.smul _ cont_diff_on_snd, refine ((cont_diff_on_fst.add cont_diff_on_const).div_const _).inv _, rintros ⟨R, x⟩ ⟨(hR : 1 < R), hx⟩, apply ne_of_gt, dsimp only, linarith } }, { rintros ⟨R, x⟩ ⟨(hR : 1 < R), hx⟩, have A : 0 < (R - 1) / (R + 1), by { apply div_pos; linarith }, have B : (R - 1) / (R + 1) < 1, by { apply (div_lt_one _ ).2; linarith }, simp only [mem_preimage, prod_mk_mem_set_prod_eq, mem_Ioo, mem_univ, and_true, A, B] } end, eq_one := λ R hR x hx, begin have A : 0 < R + 1, by linarith, simp only [hR, if_true], apply Y_eq_one_of_mem_closed_ball (IR R hR), simp only [norm_smul, inv_div, mem_closed_ball_zero_iff, real.norm_eq_abs, abs_div, abs_two, abs_of_nonneg A.le], calc 2 / (R + 1) * ‖x‖ ≤ 2 / (R + 1) * 1 : mul_le_mul_of_nonneg_left hx (div_nonneg zero_le_two A.le) ... = 1 - (R - 1) / (R + 1) : by { field_simp [A.ne'], ring } end, support := λ R hR, begin have A : 0 < (R + 1) / 2, by linarith, have A' : 0 < R + 1, by linarith, have C : (R - 1) / (R + 1) < 1, by { apply (div_lt_one _ ).2; linarith }, simp only [hR, if_true, support_comp_inv_smul₀ A.ne', Y_support _ (IR R hR) C, smul_ball A.ne', real.norm_of_nonneg A.le, smul_zero], congr' 1, field_simp [A'.ne'], ring, end }, end end exists_cont_diff_bump_base end
f58d44cceb2a7ea77d3fdff83a7efa749aa279ba
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/logic/instances.lean
f5da26e7ac63f7287e394508591a5c40f8f53585
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,785
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: logic.instances Author: Jeremy Avigad Class instances for iff and eq. -/ import logic.connectives algebra.relation namespace relation /- logical equivalence relations -/ theorem is_equivalence_eq [instance] (T : Type) : relation.is_equivalence (@eq T) := relation.is_equivalence.mk (@eq.refl T) (@eq.symm T) (@eq.trans T) theorem is_equivalence_iff [instance] : relation.is_equivalence iff := relation.is_equivalence.mk @iff.refl @iff.symm @iff.trans /- congruences for logic operations -/ theorem is_congruence_not : is_congruence iff iff not := is_congruence.mk (take a b, assume H : a ↔ b, iff.intro (assume H1 : ¬a, assume H2 : b, H1 (iff.elim_right H H2)) (assume H1 : ¬b, assume H2 : a, H1 (iff.elim_left H H2))) theorem is_congruence_and : is_congruence2 iff iff iff and := is_congruence2.mk (take a1 b1 a2 b2, assume H1 : a1 ↔ b1, assume H2 : a2 ↔ b2, iff.intro (assume H3 : a1 ∧ a2, and_of_and_of_imp_of_imp H3 (iff.elim_left H1) (iff.elim_left H2)) (assume H3 : b1 ∧ b2, and_of_and_of_imp_of_imp H3 (iff.elim_right H1) (iff.elim_right H2))) theorem is_congruence_or : is_congruence2 iff iff iff or := is_congruence2.mk (take a1 b1 a2 b2, assume H1 : a1 ↔ b1, assume H2 : a2 ↔ b2, iff.intro (assume H3 : a1 ∨ a2, or_of_or_of_imp_of_imp H3 (iff.elim_left H1) (iff.elim_left H2)) (assume H3 : b1 ∨ b2, or_of_or_of_imp_of_imp H3 (iff.elim_right H1) (iff.elim_right H2))) theorem is_congruence_imp : is_congruence2 iff iff iff imp := is_congruence2.mk (take a1 b1 a2 b2, assume H1 : a1 ↔ b1, assume H2 : a2 ↔ b2, iff.intro (assume H3 : a1 → a2, assume Hb1 : b1, iff.elim_left H2 (H3 ((iff.elim_right H1) Hb1))) (assume H3 : b1 → b2, assume Ha1 : a1, iff.elim_right H2 (H3 ((iff.elim_left H1) Ha1)))) theorem is_congruence_iff : is_congruence2 iff iff iff iff := is_congruence2.mk (take a1 b1 a2 b2, assume H1 : a1 ↔ b1, assume H2 : a2 ↔ b2, iff.intro (assume H3 : a1 ↔ a2, iff.trans (iff.symm H1) (iff.trans H3 H2)) (assume H3 : b1 ↔ b2, iff.trans H1 (iff.trans H3 (iff.symm H2)))) definition is_congruence_not_compose [instance] := is_congruence.compose is_congruence_not definition is_congruence_and_compose [instance] := is_congruence.compose21 is_congruence_and definition is_congruence_or_compose [instance] := is_congruence.compose21 is_congruence_or definition is_congruence_implies_compose [instance] := is_congruence.compose21 is_congruence_imp definition is_congruence_iff_compose [instance] := is_congruence.compose21 is_congruence_iff /- a general substitution operation with respect to an arbitrary congruence -/ namespace general_subst theorem subst {T : Type} (R : T → T → Prop) ⦃P : T → Prop⦄ [C : is_congruence R iff P] {a b : T} (H : R a b) (H1 : P a) : P b := iff.elim_left (is_congruence.app C H) H1 end general_subst /- iff can be coerced to implication -/ definition mp_like_iff [instance] : relation.mp_like iff := relation.mp_like.mk (λa b (H : a ↔ b), iff.elim_left H) /- support for calculations with iff -/ namespace iff theorem subst {P : Prop → Prop} [C : is_congruence iff iff P] {a b : Prop} (H : a ↔ b) (H1 : P a) : P b := @general_subst.subst Prop iff P C a b H H1 end iff calc_subst iff.subst namespace iff_ops notation H ⁻¹ := iff.symm H notation H1 ⬝ H2 := iff.trans H1 H2 notation H1 ▸ H2 := iff.subst H1 H2 definition refl := iff.refl definition symm := @iff.symm definition trans := @iff.trans definition subst := @iff.subst definition mp := @iff.mp end iff_ops end relation
aa129f75a80aab0641cb08f47a8e559d73e6e145
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/tactic/norm_num.lean
fd3bf7b82b1ab45aaae9fe1dd713d1bee4cd144e
[ "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
62,954
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Mario Carneiro -/ import data.rat.cast import data.rat.meta_defs /-! # `norm_num` Evaluating arithmetic expressions including `*`, `+`, `-`, `^`, `≤`. -/ universes u v w namespace tactic namespace instance_cache /-- Faster version of `mk_app ``bit0 [e]`. -/ meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]) /-- Faster version of `mk_app ``bit1 [e]`. -/ meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) := do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) end instance_cache end tactic open tactic /-! Each lemma in this file is written the way it is to exactly match (with no defeq reduction allowed) the conclusion of some lemma generated by the proof procedure that uses it. That proof procedure should describe the shape of the generated lemma in its docstring. -/ namespace norm_num variable {α : Type u} lemma subst_into_add {α} [has_add α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t := by rw [prl, prr, prt] lemma subst_into_mul {α} [has_mul α] (l r tl tr t) (prl : (l : α) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t := by rw [prl, prr, prt] lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t := by simp [pra, prt] /-- The result type of `match_numeral`, either `0`, `1`, or a top level decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/ meta inductive match_numeral_result | zero | one | bit0 (e : expr) | bit1 (e : expr) | other /-- Unfold the top level constructor of the numeral expression. -/ meta def match_numeral : expr → match_numeral_result | `(bit0 %%e) := match_numeral_result.bit0 e | `(bit1 %%e) := match_numeral_result.bit1 e | `(@has_zero.zero _ _) := match_numeral_result.zero | `(@has_one.one _ _) := match_numeral_result.one | _ := match_numeral_result.other theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _ theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable. (It may prove garbage instead of failing if `a + 1 = b` is false.) -/ meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr) | c e r := match match_numeral e with | zero := c.mk_app ``zero_succ [] | one := c.mk_app ``one_succ [] | bit0 e := c.mk_app ``bit0_succ [e] | bit1 e := do let r := r.app_arg, (c, p) ← prove_succ c e r, c.mk_app ``bit1_succ [e, r, p] | _ := failed end end /-- Given `a` natural numeral, returns `(b, ⊢ a + 1 = b)`. -/ meta def prove_succ' (c : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, (c, b) ← c.of_nat (na + 1), (c, p) ← prove_succ c a b, return (c, b, p) theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_assoc] theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc] theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c := h ▸ by simp [bit0, bit1, add_left_comm, add_comm, add_assoc] theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b := h ▸ by simp [bit0, add_left_comm, add_assoc] theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit0 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit0 a + bit1 b + 1 = bit0 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b + 1 = bit1 c := h ▸ by simp [bit1, bit0, add_left_comm, add_assoc] section open match_numeral_result meta mutual def prove_add_nat, prove_adc_nat with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := c.mk_app ``zero_add [b] | _, zero := c.mk_app ``add_zero [a] | _, one := prove_succ c a r | one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p] | _, _ := failed end with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr) | c a b r := do match match_numeral a, match_numeral b with | zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p] | _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p] | one, one := c.mk_app ``adc_one_one [] | bit0 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p] | one, bit0 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p] | bit1 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p] | one, bit1 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p] | bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p] | bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p] | bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p] | bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p] | _, _ := failed end /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/ add_decl_doc prove_add_nat /-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/ add_decl_doc prove_adc_nat /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/ meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_nat, nb ← b.to_nat, (c, r) ← c.of_nat (na + nb), (c, p) ← prove_add_nat c a b r, return (c, r, p) end theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul] theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) : a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add] theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) : bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h) theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α) (hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) : bit1 a * bit1 b = bit1 e := by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc] section open match_numeral_result /-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/ meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr) | ic a b := match match_numeral a, match_numeral b with | zero, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, zero := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p) | _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p) | bit0 a, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p], (ic, c') ← ic.mk_bit0 c, (ic, c') ← ic.mk_bit0 c', return (ic, c', p) | bit0 a, _ := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | _, bit0 b := do (ic, c, p) ← prove_mul_nat ic a b, (ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p], (ic, c') ← ic.mk_bit0 c, return (ic, c', p) | bit1 a, bit1 b := do (ic, c, pc) ← prove_mul_nat ic a b, (ic, d, pd) ← prove_add_nat' ic a b, (ic, c') ← ic.mk_bit0 c, (ic, e, pe) ← prove_add_nat' ic c' d, (ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe], (ic, e') ← ic.mk_bit1 e, return (ic, e', p) | _, _ := failed end end section open match_numeral_result /-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/ meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr) | e := match match_numeral e with | one := c.mk_app ``zero_lt_one' [] | bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p] | bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p] | _ := failed end end /-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/ meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr) | `(%%e₁ / %%e₂) := do (c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂, c.mk_app ``div_pos [e₁, e₂, p₁, p₂] | e := prove_pos_nat c e /-- `match_neg (- e) = some e`, otherwise `none` -/ meta def match_neg : expr → option expr | `(- %%e) := some e | _ := none /-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/ meta def match_sign : expr → expr ⊕ bool | `(- %%e) := sum.inl e | `(has_zero.zero) := sum.inr ff | _ := sum.inr tt theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1 /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero' (c : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_neg a with | some a := do (c, p) ← prove_ne_zero' a, c.mk_app ``ne_zero_neg [a, p] | none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p] end theorem clear_denom_div {α} [division_ring α] (a b b' c d : α) (h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c := by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀] /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom' (prove_ne_zero : instance_cache → expr → ℚ → tactic (instance_cache × expr)) (c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) : tactic (instance_cache × expr × expr) := if na.denom = 1 then prove_mul_nat c a d else do [_, _, a, b] ← return a.get_app_args, (c, b') ← c.of_nat (nd / na.denom), (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, _, p₁) ← prove_mul_nat c b b', (c, r, p₂) ← prove_mul_nat c a b', (c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂], return (c, r, p) theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a := lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h) theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a := one_lt_bit1.2 h theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b := bit0_lt_bit0.2 theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b := lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _) theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b := lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h) theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b := bit1_lt_bit1.2 theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a := le_of_lt (lt_one_bit0 _ h) -- deliberately strong hypothesis because bit1 0 is not a numeral theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a := le_of_lt (lt_one_bit1 _ h) theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b := bit0_le_bit0.2 theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b := le_of_lt (lt_bit0_bit1 _ _ h) theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b := le_of_lt (lt_bit1_bit0 _ _ h) theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b := bit1_le_bit1.2 theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a := bit0_le_bit0.2 theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a := le_bit0_bit1 _ _ theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b := le_bit1_bit0 _ _ theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b := bit1_le_bit1.2 h theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit0 b := (bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit1 b := (bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h /-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/ meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr) | e@`(has_zero.zero) := ic.mk_app ``le_refl [e] | e := if ic.α = `(ℕ) then return (ic, `(nat.zero_le).mk_app [e]) else do (ic, p) ← prove_pos ic e, ic.mk_app ``nonneg_pos [e, p] section open match_numeral_result /-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/ meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr) | a := match match_numeral a with | one := ic.mk_app ``le_refl [a] | bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p] | bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p] | _ := failed end meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache) with prove_le_nat : expr → expr → tactic (instance_cache × expr) | a b := if a = b then ic.mk_app ``le_refl [a] else match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p] | _, _ := failed end with prove_sle_nat : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_nonneg ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p] | _, _ := failed end /-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/ add_decl_doc prove_le_nat /-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/ add_decl_doc prove_sle_nat /-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/ meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr) | a b := match match_numeral a, match_numeral b with | zero, _ := prove_pos ic b | one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p] | one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p] | bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p] | bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p] | bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p] | bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p] | _, _ := failed end end theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b := lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀) /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_lt_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_lt_nat ic a' b', ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p] lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b := lt_trans (neg_neg_of_pos ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/ meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do -- we have to switch the order of `a` and `b` because `a < b ↔ -b < -a` (ic, p) ← prove_lt_nonneg_rat ic b a (-nb) (-na), ic.mk_app ``neg_lt_neg [b, a, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_pos ic a, ic.mk_app ``neg_neg_of_pos [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_pos ic a, (ic, pb) ← prove_pos ic b, ic.mk_app ``lt_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_pos ic b | sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb end theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α) (h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b := le_of_mul_le_mul_right (by rwa [ha, hb]) h₀ /-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_le_nat ic a b else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_pos ic d, (ic, a', pa) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic a d na nd, (ic, b', pb) ← prove_clear_denom' (λ ic e _, prove_ne_zero' ic e) ic b d nb nd, (ic, p) ← prove_le_nat ic a' b', ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p] lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b := le_trans (neg_nonpos_of_nonneg ha) hb /-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/ meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb), ic.mk_app ``neg_le_neg [a, b, p] | sum.inl a, sum.inr ff := do (ic, p) ← prove_nonneg ic a, ic.mk_app ``neg_nonpos_of_nonneg [a, p] | sum.inl a, sum.inr tt := do (ic, pa) ← prove_nonneg ic a, (ic, pb) ← prove_nonneg ic b, ic.mk_app ``le_neg_pos [a, b, pa, pb] | sum.inr ff, _ := prove_nonneg ic b | sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb end /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version tries to prove `⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/ meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) := if na < nb then do (ic, p) ← prove_lt_rat ic a b na nb, ic.mk_app ``ne_of_lt [a, b, p] else do (ic, p) ← prove_lt_rat ic b a nb na, ic.mk_app ``ne_of_gt [a, b, p] theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ nat.cast_bit0 _ theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ nat.cast_bit1 _ theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ int.cast_bit0 _ theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ int.cast_bit1 _ theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' := h ▸ rat.cast_bit0 _ theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' := h ▸ rat.cast_bit1 _ /-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (nc, e) ← nc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``nat_cast_zero [], return (ic, nc, e, p) | match_numeral_result.one := do (nc, e) ← nc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``nat_cast_one [], return (ic, nc, e, p) | match_numeral_result.bit0 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a0) ← nc.mk_bit0 a, (ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p], return (ic, nc, a0, p) | match_numeral_result.bit1 a' := do (ic, nc, a, p) ← prove_nat_uncast a', (nc, a1) ← nc.mk_bit1 a, (ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p], return (ic, nc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (zc, e) ← zc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``int_cast_zero [], return (ic, zc, e, p) | match_numeral_result.one := do (zc, e) ← zc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``int_cast_one [], return (ic, zc, e, p) | match_numeral_result.bit0 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a0) ← zc.mk_bit0 a, (ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p], return (ic, zc, a0, p) | match_numeral_result.bit1 a' := do (ic, zc, a, p) ← prove_int_uncast_nat a', (zc, a1) ← zc.mk_bit1 a, (ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p], return (ic, zc, a1, p) | _ := failed end /-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr), tactic (instance_cache × instance_cache × expr × expr) | a' := match match_numeral a' with | match_numeral_result.zero := do (qc, e) ← qc.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``rat.cast_zero [], return (ic, qc, e, p) | match_numeral_result.one := do (qc, e) ← qc.mk_app ``has_one.one [], (ic, p) ← ic.mk_app ``rat.cast_one [], return (ic, qc, e, p) | match_numeral_result.bit0 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a0) ← qc.mk_bit0 a, (ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p], return (ic, qc, a0, p) | match_numeral_result.bit1 a' := do (ic, qc, a, p) ← prove_rat_uncast_nat a', (qc, a1) ← qc.mk_bit1 a, (ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p], return (ic, qc, a1, p) | _ := failed end theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' := ha ▸ hb ▸ rat.cast_div _ _ /-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := if na'.denom = 1 then prove_rat_uncast_nat ic qc cz_inst a' else do [_, _, a', b'] ← return a'.get_app_args, (ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a', (ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b', (qc, e) ← qc.mk_app ``has_div.div [a, b], (ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb], return (ic, qc, e, p) theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ int.cast_neg _ theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' := h ▸ rat.cast_neg _ /-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, zc, a, p) ← prove_int_uncast_nat ic zc a', (zc, e) ← zc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``int_cast_neg [a, a', p], return (ic, zc, e, p) | none := prove_int_uncast_nat ic zc a' end /-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`. (Note that the returned value is on the left of the equality.) -/ meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) : tactic (instance_cache × instance_cache × expr × expr) := match match_neg a' with | some a' := do (ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'), (qc, e) ← qc.mk_app ``has_neg.neg [a], (ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p], return (ic, qc, e, p) | none := prove_rat_uncast_nonneg ic qc cz_inst a' na' end theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt nat.cast_inj.1 h theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt int.cast_inj.1 h theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α) (ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' := ha ▸ hb ▸ mt rat.cast_inj.1 h /-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods: * Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order * Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`. This requires that the base type be `char_zero`, and also that it be a `division_ring` so that the coercion from `ℚ` is well defined. We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero` rings and semirings. -/ meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr) | ic a b na nb := prove_ne_rat ic a b na nb <|> do cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance, if na.denom = 1 ∧ nb.denom = 1 then if na ≥ 0 ∧ nb ≥ 0 then do guard (ic.α ≠ `(ℕ)), nc ← mk_instance_cache `(ℕ), (ic, nc, a', pa) ← prove_nat_uncast ic nc a, (ic, nc, b', pb) ← prove_nat_uncast ic nc b, (nc, p) ← prove_ne_rat nc a' b' na nb, ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℤ)), zc ← mk_instance_cache `(ℤ), (ic, zc, a', pa) ← prove_int_uncast ic zc a, (ic, zc, b', pb) ← prove_int_uncast ic zc b, (zc, p) ← prove_ne_rat zc a' b' na nb, ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p] else do guard (ic.α ≠ `(ℚ)), qc ← mk_instance_cache `(ℚ), (ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na, (ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb, (qc, p) ← prove_ne_rat qc a' b' na nb, ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p] /-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/ meta def prove_ne_zero (ic : instance_cache) : expr → ℚ → tactic (instance_cache × expr) | a na := do (ic, z) ← ic.mk_app ``has_zero.zero [], prove_ne ic a z na 0 /-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`. (`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/ meta def prove_clear_denom : instance_cache → expr → expr → ℚ → ℕ → tactic (instance_cache × expr × expr) := prove_clear_denom' prove_ne_zero theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α) (h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c') (h : a' + b' = c') : a + b = c := mul_right_cancel₀ h₀ $ by rwa [add_mul, ha, hb, hc] /-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) : tactic (instance_cache × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_add_nat ic a b c else do let nd := na.denom.lcm nb.denom, (ic, d) ← ic.of_nat nd, (ic, p₀) ← prove_ne_zero ic d (rat.of_int nd), (ic, a', pa) ← prove_clear_denom ic a d na nd, (ic, b', pb) ← prove_clear_denom ic b d nb nd, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, p) ← prove_add_nat ic a' b' c', ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p] theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c := h ▸ by simp theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c := h ▸ by simp theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c := h ▸ by simp theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c := h ▸ by simp theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c := h ▸ by simp /-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/ meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) : tactic (instance_cache × expr) := match match_neg ea, match_neg eb, match_neg ec with | some ea, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c), ic.mk_app ``add_neg_neg [ea, eb, ec, p] | some ea, none, some ec := do (ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a), ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p] | some ea, none, none := do (ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b, ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p] | none, some eb, some ec := do (ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b), ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p] | none, some eb, none := do (ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a, ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p] | _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c end /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/ meta def prove_add_rat' (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do na ← a.to_rat, nb ← b.to_rat, let nc := na + nb, (ic, c) ← ic.of_rat nc, (ic, p) ← prove_add_rat ic a b c na nb nc, return (ic, c, p) theorem clear_denom_simple_nat {α} [division_ring α] (a : α) : (1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩ theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) : b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩ /-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)` where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/ meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) : tactic (instance_cache × expr × expr × expr) := if na.denom = 1 then do (c, d) ← c.mk_app ``has_one.one [], (c, p) ← c.mk_app ``clear_denom_simple_nat [a], return (c, d, a, p) else do [α, _, a, b] ← return a.get_app_args, (c, p₀) ← prove_ne_zero c b (rat.of_int na.denom), (c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀], return (c, b, a, p) theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α) (ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b') (hc : c * d = c') (hd : d₁ * d₂ = d) (h : a' * b' = c') : a * b = c := mul_right_cancel₀ ha.1 $ mul_right_cancel₀ hb.1 $ by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a] /-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := if na.denom = 1 ∧ nb.denom = 1 then prove_mul_nat ic a b else do let nc := na * nb, (ic, c) ← ic.of_rat nc, (ic, d₁, a', pa) ← prove_clear_denom_simple ic a na, (ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb, (ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat, (ic, c', pc) ← prove_clear_denom ic c d nc nd, (ic, _, p) ← prove_mul_nat ic a' b', (ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p], return (ic, c, p) theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/ meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := match match_sign a, match_sign b with | sum.inl a, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb), (ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p], return (ic, c, p) | sum.inr ff, _ := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``zero_mul [b], return (ic, z, p) | _, sum.inr ff := do (ic, z) ← ic.mk_app ``has_zero.zero [], (ic, p) ← ic.mk_app ``mul_zero [a], return (ic, z, p) | sum.inl a, sum.inr tt := do (ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb, (ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inl b := do (ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb), (ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p], (ic, c') ← ic.mk_app ``has_neg.neg [c], return (ic, c', p) | sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb end theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b := h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div] theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := inv_one theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a := by rw [one_div, inv_inv₀] theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a := inv_eq_one_div _ theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a := by simp only [inv_eq_one_div, one_div_div] /-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/ meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr) | ic e n := match match_sign e with | sum.inl e := do (ic, e', p) ← prove_inv ic e (-n), (ic, r) ← ic.mk_app ``has_neg.neg [e'], (ic, p) ← ic.mk_app ``inv_neg [e, e', p], return (ic, r, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``inv_zero [], return (ic, e, p) | sum.inr tt := if n.num = 1 then if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_one [], return (ic, e, p) else do let e := e.app_arg, (ic, p) ← ic.mk_app ``inv_one_div [e], return (ic, e, p) else if n.denom = 1 then do (ic, p) ← ic.mk_app ``inv_div_one [e], e ← infer_type p, return (ic, e.app_arg, p) else do [_, _, a, b] ← return e.get_app_args, (ic, e') ← ic.mk_app ``has_div.div [b, a], (ic, p) ← ic.mk_app ``inv_div [a, b], return (ic, e', p) end theorem div_eq {α} [division_ring α] (a b b' c : α) (hb : b⁻¹ = b') (h : a * b' = c) : a / b = c := by rwa [ ← hb, ← div_eq_mul_inv] at h /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/ meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) := do (ic, b', pb) ← prove_inv ic b nb, (ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹, (ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p], return (ic, c, p) /-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/ meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) := match match_sign a with | sum.inl a := do (ic, p) ← ic.mk_app ``neg_neg [a], return (ic, a, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``neg_zero [], return (ic, a, p) | sum.inr tt := do (ic, a') ← ic.mk_app ``has_neg.neg [a], p ← mk_eq_refl a', return (ic, a', p) end theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c := by rwa [← hb, ← sub_eq_add_neg] at h theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c := by rwa sub_neg_eq_add /-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := match match_sign b with | sum.inl b := do (ic, c, p) ← prove_add_rat' ic a b, (ic, p) ← ic.mk_app ``sub_neg [a, b, c, p], return (ic, c, p) | sum.inr ff := do (ic, p) ← ic.mk_app ``sub_zero [a], return (ic, a, p) | sum.inr tt := do (ic, b', pb) ← prove_neg ic b, (ic, c, p) ← prove_add_rat' ic a b', (ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p], return (ic, c, p) end theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c := h ▸ nat.add_sub_cancel_left _ _ theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 := nat.sub_eq_zero_of_le $ h ▸ nat.le_add_right _ _ /-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/ meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) := do na ← a.to_nat, nb ← b.to_nat, if nb ≤ na then do (ic, c) ← ic.of_nat (na - nb), (ic, p) ← prove_add_nat ic b c a, return (c, `(sub_nat_pos).mk_app [a, b, c, p]) else do (ic, c) ← ic.of_nat (nb - na), (ic, p) ← prove_add_nat ic a c b, return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p]) /-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals. Also handles nat subtraction. Does not do recursive simplification; that is, `1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level `simp` call in `norm_num.derive`. -/ meta def eval_field : expr → tactic (expr × expr) | `(%%e₁ + %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, let n₃ := n₁ + n₂, (c, e₃) ← c.of_rat n₃, (_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃, return (e₃, p) | `(%%e₁ * %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂ | `(- %%e) := do c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_neg c e | `(@has_sub.sub %%α %%inst %%a %%b) := do c ← mk_instance_cache α, if α = `(nat) then prove_sub_nat c a b else prod.snd <$> prove_sub c a b | `(has_inv.inv %%e) := do n ← e.to_rat, c ← infer_type e >>= mk_instance_cache, prod.snd <$> prove_inv c e n | `(%%e₁ / %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_div c e₁ e₂ n₁ n₂ | _ := failed lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ) (h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c := h₂ ▸ by simp [pow_bit0, h] lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ) (h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c := by rw [← h₃, ← h₂]; simp [pow_bit1, h] section open match_numeral_result /-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/ meta def prove_pow (a : expr) (na : ℚ) : instance_cache → expr → tactic (instance_cache × expr × expr) | ic b := match match_numeral b with | zero := do (ic, p) ← ic.mk_app ``pow_zero [a], (ic, o) ← ic.mk_app ``has_one.one [], return (ic, o, p) | one := do (ic, p) ← ic.mk_app ``pow_one [a], return (ic, a, p) | bit0 b := do (ic, c', p) ← prove_pow ic b, nc' ← expr.to_rat c', (ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc', (ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂], return (ic, c, p) | bit1 b := do (ic, c₁, p) ← prove_pow ic b, nc₁ ← expr.to_rat c₁, (ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁, (ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na, (ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃], return (ic, c, p) | _ := failed end end /-- Evaluates expressions of the form `a ^ b`, `monoid.npow a b` or `nat.pow a b`. -/ meta def eval_pow : expr → tactic (expr × expr) | `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, match m with | `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂ | _ := failed end | `(monoid.npow %%e₁ %%e₂) := do n₁ ← e₁.to_rat, c ← infer_type e₁ >>= mk_instance_cache, prod.snd <$> prove_pow e₁ n₁ c e₂ | _ := failed /-- Given `⊢ p`, returns `(true, ⊢ p = true)`. -/ meta def true_intro (p : expr) : tactic (expr × expr) := prod.mk `(true) <$> mk_app ``eq_true_intro [p] /-- Given `⊢ ¬ p`, returns `(false, ⊢ p = false)`. -/ meta def false_intro (p : expr) : tactic (expr × expr) := prod.mk `(false) <$> mk_app ``eq_false_intro [p] theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false := eq_false_intro $ not_not_intro rfl /-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/ meta def eval_ineq : expr → tactic (expr × expr) | `(%%e₁ < %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ < n₂ then do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p else if n₁ = n₂ then do (_, p) ← c.mk_app ``lt_irrefl [e₁], false_intro p else do (c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'], false_intro p | `(%%e₁ ≤ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ ≤ n₂ then do (_, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else prove_le_rat c e₁ e₂ n₁ n₂, true_intro p else do (c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁, (_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p], false_intro p | `(%%e₁ = %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p | `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq | `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq | `(%%e₁ ≠ %%e₂) := do n₁ ← e₁.to_rat, n₂ ← e₂.to_rat, c ← infer_type e₁ >>= mk_instance_cache, if n₁ = n₂ then prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁] else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p | _ := failed theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁ /-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral. (We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure that towers of successors coming from e.g. `induction` are a common case.) -/ meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr) | `(nat.succ %%a) := do (ic, n, b, p₁) ← prove_nat_succ a, let n' := n + 1, (ic, c) ← ic.of_nat n', (ic, p₂) ← prove_add_nat ic b `(1) c, return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂]) | e := do n ← e.to_nat, p ← mk_eq_refl e, return (ic, n, e, p) lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂), nat.div_eq_of_lt h₂, zero_add] lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q := by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)), int.div_eq_zero_of_lt h₁ h₂, zero_add] lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂] lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r := by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂] lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c := h₂ ▸ h ▸ int.div_neg _ _ lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c := (int.mod_neg _ _).trans h /-- Given `a`,`b` numerals in `nat` or `int`, * `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)` * `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)` -/ meta def prove_div_mod (ic : instance_cache) : expr → expr → bool → tactic (instance_cache × expr × expr) | a b mod := match match_neg b with | some b := do (ic, c', p) ← prove_div_mod a b mod, if mod then return (ic, c', `(int_mod_neg).mk_app [a, b, c', p]) else do (ic, c, p₂) ← prove_neg ic c', return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂]) | none := do nb ← b.to_nat, na ← a.to_int, let nq := na / nb, let nr := na % nb, let nm := nq * nr, (ic, q) ← ic.of_int nq, (ic, r) ← ic.of_int nr, (ic, m, pm) ← prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb), (ic, p) ← prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na), (ic, p') ← prove_lt_nat ic r b, if ic.α = `(nat) then if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p']) else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p']) else if ic.α = `(int) then do (ic, p₀) ← prove_nonneg ic r, if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p']) else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p']) else failed end theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂ theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p := (propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂ theorem int_to_nat_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : a.to_nat = b := by rw ← h; simp theorem int_to_nat_neg (a : ℤ) (h : 0 < a) : (-a).to_nat = 0 := by simp only [int.to_nat_of_nonpos, h.le, neg_nonpos] theorem nat_abs_pos (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : a.nat_abs = b := by rw ← h; simp theorem nat_abs_neg (a : ℤ) (b : ℕ) (h : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = a) : (-a).nat_abs = b := by rw ← h; simp theorem neg_succ_of_nat (a b : ℕ) (c : ℤ) (h₁ : a + 1 = b) (h₂ : (by haveI := @nat.cast_coe ℤ; exact b : ℤ) = c) : -[1+ a] = -c := by rw [← h₂, ← h₁, int.nat_cast_eq_coe_nat]; refl /-- Evaluates some extra numeric operations on `nat` and `int`, specifically `nat.succ`, `/` and `%`, and `∣` (divisibility). -/ meta def eval_nat_int_ext : expr → tactic (expr × expr) | e@`(nat.succ _) := do ic ← mk_instance_cache `(ℕ), (_, _, ep) ← prove_nat_succ ic e, return ep | `(%%a / %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b ff | `(%%a % %%b) := do c ← infer_type a >>= mk_instance_cache, prod.snd <$> prove_div_mod c a b tt | `(%%a ∣ %%b) := do α ← infer_type a, ic ← mk_instance_cache α, th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else if α = `(int) then return `(dvd_eq_int) else failed, (ic, c, p₁) ← prove_div_mod ic b a tt, (ic, z) ← ic.mk_app ``has_zero.zero [], (e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq, return (e', th.mk_app [a, b, c, e', p₁, p₂]) | `(int.to_nat %%a) := do n ← a.to_int, ic ← mk_instance_cache `(ℤ), if n ≥ 0 then do nc ← mk_instance_cache `(ℕ), (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(int_to_nat_pos).mk_app [a, b, p]) else do a ← match_neg a, (_, p) ← prove_pos ic a, pure (`(0), `(int_to_nat_neg).mk_app [a, p]) | `(int.nat_abs %%a) := do n ← a.to_int, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), if n ≥ 0 then do (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(nat_abs_pos).mk_app [a, b, p]) else do a ← match_neg a, (_, _, b, p) ← prove_nat_uncast ic nc a, pure (b, `(nat_abs_neg).mk_app [a, b, p]) | `(int.neg_succ_of_nat %%a) := do na ← a.to_nat, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), let nb := na + 1, (nc, b) ← nc.of_nat nb, (nc, p₁) ← prove_add_nat nc a `(1) b, (ic, c) ← ic.of_nat nb, (_, _, _, p₂) ← prove_nat_uncast ic nc c, pure (`(-%%c : ℤ), `(neg_succ_of_nat).mk_app [a, b, c, p₁, p₂]) | _ := failed theorem int_to_nat_cast (a : ℕ) (b : ℤ) (h : (by haveI := @nat.cast_coe ℤ; exact a : ℤ) = b) : ↑a = b := eq.trans (by simp) h /-- Evaluates the `↑n` cast operation from `ℕ`, `ℤ`, `ℚ` to an arbitrary type `α`. -/ meta def eval_cast : expr → tactic (expr × expr) | `(@coe ℕ %%α %%inst %%a) := do if inst.is_app_of ``coe_to_lift then if inst.app_arg.is_app_of ``nat.cast_coe then do n ← a.to_nat, ic ← mk_instance_cache α, nc ← mk_instance_cache `(ℕ), (ic, b) ← ic.of_nat n, (_, _, _, p) ← prove_nat_uncast ic nc b, pure (b, p) else if inst.app_arg.is_app_of ``int.cast_coe then do n ← a.to_int, ic ← mk_instance_cache α, zc ← mk_instance_cache `(ℤ), (ic, b) ← ic.of_int n, (_, _, _, p) ← prove_int_uncast ic zc b, pure (b, p) else if inst.app_arg.is_app_of ``int.cast_coe then do n ← a.to_rat, cz_inst ← mk_mapp ``char_zero [α, none, none] >>= mk_instance, ic ← mk_instance_cache α, qc ← mk_instance_cache `(ℚ), (ic, b) ← ic.of_rat n, (_, _, _, p) ← prove_rat_uncast ic qc cz_inst b n, pure (b, p) else failed else if inst = `(@coe_base nat int int.has_coe) then do n ← a.to_nat, ic ← mk_instance_cache `(ℤ), nc ← mk_instance_cache `(ℕ), (ic, b) ← ic.of_nat n, (_, _, _, p) ← prove_nat_uncast ic nc b, pure (b, `(int_to_nat_cast).mk_app [a, b, p]) else failed | _ := failed /-- This version of `derive` does not fail when the input is already a numeral -/ meta def derive.step (e : expr) : tactic (expr × expr) := eval_field e <|> eval_pow e <|> eval_ineq e <|> eval_cast e <|> eval_nat_int_ext e /-- An attribute for adding additional extensions to `norm_num`. To use this attribute, put `@[norm_num]` on a tactic of type `expr → tactic (expr × expr)`; the tactic will be called on subterms by `norm_num`, and it is responsible for identifying that the expression is a numerical function applied to numerals, for example `nat.fib 17`, and should return the reduced numerical expression (which must be in `norm_num`-normal form: a natural or rational numeral, i.e. `37`, `12 / 7` or `-(2 / 3)`, although this can be an expression in any type), and the proof that the original expression is equal to the rewritten expression. Failure is used to indicate that this tactic does not apply to the term. For performance reasons, it is best to detect non-applicability as soon as possible so that the next tactic can have a go, so generally it will start with a pattern match and then checking that the arguments to the term are numerals or of the appropriate form, followed by proof construction, which should not fail. Propositions are treated like any other term. The normal form for propositions is `true` or `false`, so it should produce a proof of the form `p = true` or `p = false`. `eq_true_intro` can be used to help here. -/ @[user_attribute] protected meta def attr : user_attribute (expr → tactic (expr × expr)) unit := { name := `norm_num, descr := "Add norm_num derivers", cache_cfg := { mk_cache := λ ns, do { t ← ns.mfoldl (λ (t : expr → tactic (expr × expr)) n, do t' ← eval_expr (expr → tactic (expr × expr)) (expr.const n []), pure (λ e, t' e <|> t e)) (λ _, failed), pure (λ e, derive.step e <|> t e) }, dependencies := [] } } add_tactic_doc { name := "norm_num", category := doc_category.attr, decl_names := [`norm_num.attr], tags := ["arithmetic", "decision_procedure"] } /-- Look up the `norm_num` extensions in the cache and return a tactic extending `derive.step` with additional reduction procedures. -/ meta def get_step : tactic (expr → tactic (expr × expr)) := norm_num.attr.get_cache /-- Simplify an expression bottom-up using `step` to simplify the subexpressions. -/ meta def derive' (step : expr → tactic (expr × expr)) : expr → tactic (expr × expr) | e := do e ← instantiate_mvars e, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← step e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, tt)) `eq e, return (e', pr) /-- Simplify an expression bottom-up using the default `norm_num` set to simplify the subexpressions. -/ meta def derive (e : expr) : tactic (expr × expr) := do f ← get_step, derive' f e end norm_num /-- Basic version of `norm_num` that does not call `simp`. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num1 (step : expr → tactic (expr × expr)) (loc : interactive.loc) : tactic unit := do ns ← loc.get_locals, success ← tactic.replace_at (norm_num.derive' step) ns loc.include_goal, when loc.include_goal $ try tactic.triv, when (¬ ns.empty) $ try tactic.contradiction, monad.unlessb success $ done <|> fail "norm_num failed to simplify" /-- Normalize numerical expressions. It uses the provided `step` tactic to simplify the expression; use `get_step` to get the default `norm_num` set and `derive.step` for the basic builtin set of simplifications. -/ meta def tactic.norm_num (step : expr → tactic (expr × expr)) (hs : list simp_arg_type) (l : interactive.loc) : tactic unit := repeat1 $ orelse' (tactic.norm_num1 step l) $ interactive.simp_core {} (tactic.norm_num1 step (interactive.loc.ns [none])) ff (simp_arg_type.except ``one_div :: hs) [] l >> skip namespace tactic.interactive open norm_num interactive interactive.types /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 (loc : parse location) : tactic unit := do f ← get_step, tactic.norm_num1 f loc /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit := do f ← get_step, tactic.norm_num f hs l add_hint_tactic "norm_num" /-- Normalizes a numerical expression and tries to close the goal with the result. -/ meta def apply_normed (x : parse texpr) : tactic unit := do x₁ ← to_expr x, (x₂,_) ← derive x₁, tactic.exact x₂ /-- Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. Add-on tactics marked as `@[norm_num]` can extend the behavior of `norm_num` to include other functions. This is used to support several other functions on `nat` like `prime`, `min_fac` and `factors`. ```lean import data.real.basic example : (2 : ℝ) + 2 = 4 := by norm_num example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num example : (73 : ℝ) < 789/2 := by norm_num example : 123456789 + 987654321 = 1111111110 := by norm_num example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num example : nat.prime (2^13 - 1) := by norm_num example : ¬ nat.prime (2^11 - 1) := by norm_num example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption ``` The variant `norm_num1` does not call `simp`. Both `norm_num` and `norm_num1` can be called inside the `conv` tactic. The tactic `apply_normed` normalises a numerical expression and tries to close the goal with the result. Compare: ```lean def a : ℕ := 2^100 #print a -- 2 ^ 100 def normed_a : ℕ := by apply_normed 2^100 #print normed_a -- 1267650600228229401496703205376 ``` -/ add_tactic_doc { name := "norm_num", category := doc_category.tactic, decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num, `tactic.interactive.apply_normed], tags := ["arithmetic", "decision procedure"] } end tactic.interactive namespace conv.interactive open conv interactive tactic.interactive open norm_num (derive) /-- Basic version of `norm_num` that does not call `simp`. -/ meta def norm_num1 : conv unit := replace_lhs derive /-- Normalize numerical expressions. Supports the operations `+` `-` `*` `/` `^` and `%` over numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types, and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`, where `A` and `B` are numerical expressions. It also has a relatively simple primality prover. -/ meta def norm_num (hs : parse simp_arg_list) : conv unit := repeat1 $ orelse' norm_num1 $ conv.interactive.simp ff (simp_arg_type.except ``one_div :: hs) [] { discharger := tactic.interactive.norm_num1 (loc.ns [none]) } end conv.interactive
b799b19b67d88a10e56ad9dbc27b30e97306ed88
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/star/chsh.lean
f794817618872e1d66d540ce1e82c3d754ff1864
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
10,153
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.char_p.invertible import data.real.sqrt /-! # The Clauser-Horne-Shimony-Holt inequality and Tsirelson's inequality. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We establish a version of the Clauser-Horne-Shimony-Holt (CHSH) inequality (which is a generalization of Bell's inequality). This is a foundational result which implies that quantum mechanics is not a local hidden variable theory. As usually stated the CHSH inequality requires substantial language from physics and probability, but it is possible to give a statement that is purely about ordered `*`-algebras. We do that here, to avoid as many practical and logical dependencies as possible. Since the algebra of observables of any quantum system is an ordered `*`-algebra (in particular a von Neumann algebra) this is a strict generalization of the usual statement. Let `R` be a `*`-ring. A CHSH tuple in `R` consists of * four elements `A₀ A₁ B₀ B₁ : R`, such that * each `Aᵢ` and `Bⱼ` is a self-adjoint involution, and * the `Aᵢ` commute with the `Bⱼ`. The physical interpretation is that the four elements are observables (hence self-adjoint) that take values ±1 (hence involutions), and that the `Aᵢ` are spacelike separated from the `Bⱼ` (and hence commute). The CHSH inequality says that when `R` is an ordered `*`-ring (that is, a `*`-ring which is ordered, and for every `r : R`, `0 ≤ star r * r`), which is moreover *commutative*, we have `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2` On the other hand, Tsirelson's inequality says that for any ordered `*`-ring we have `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2√2` (A caveat: in the commutative case we need 2⁻¹ in the ring, and in the noncommutative case we need √2 and √2⁻¹. To keep things simple we just assume our rings are ℝ-algebras.) The proofs I've seen in the literature either assume a significant framework for quantum mechanics, or assume the ring is a `C^*`-algebra. In the `C^*`-algebra case, the order structure is completely determined by the `*`-algebra structure: `0 ≤ A` iff there exists some `B` so `A = star B * B`. There's a nice proof of both bounds in this setting at https://en.wikipedia.org/wiki/Tsirelson%27s_bound The proof given here is purely algebraic. ## Future work One can show that Tsirelson's inequality is tight. In the `*`-ring of n-by-n complex matrices, if `A ≤ λ I` for some `λ : ℝ`, then every eigenvalue has absolute value at most `λ`. There is a CHSH tuple in 4-by-4 matrices such that `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁` has `2√2` as an eigenvalue. ## References * [Clauser, Horne, Shimony, Holt, *Proposed experiment to test local hidden-variable theories*][zbMATH06785026] * [Bell, *On the Einstein Podolsky Rosen Paradox*][MR3790629] * [Tsirelson, *Quantum generalizations of Bell's inequality*][MR577178] -/ universes u /-- A CHSH tuple in a *-monoid consists of 4 self-adjoint involutions `A₀ A₁ B₀ B₁` such that the `Aᵢ` commute with the `Bⱼ`. The physical interpretation is that `A₀` and `A₁` are a pair of boolean observables which are spacelike separated from another pair `B₀` and `B₁` of boolean observables. -/ @[nolint has_nonempty_instance] structure is_CHSH_tuple {R} [monoid R] [star_semigroup R] (A₀ A₁ B₀ B₁ : R) := (A₀_inv : A₀^2 = 1) (A₁_inv : A₁^2 = 1) (B₀_inv : B₀^2 = 1) (B₁_inv : B₁^2 = 1) (A₀_sa : star A₀ = A₀) (A₁_sa : star A₁ = A₁) (B₀_sa : star B₀ = B₀) (B₁_sa : star B₁ = B₁) (A₀B₀_commutes : A₀ * B₀ = B₀ * A₀) (A₀B₁_commutes : A₀ * B₁ = B₁ * A₀) (A₁B₀_commutes : A₁ * B₀ = B₀ * A₁) (A₁B₁_commutes : A₁ * B₁ = B₁ * A₁) variables {R : Type u} lemma CHSH_id [comm_ring R] {A₀ A₁ B₀ B₁ : R} (A₀_inv : A₀^2 = 1) (A₁_inv : A₁^2 = 1) (B₀_inv : B₀^2 = 1) (B₁_inv : B₁^2 = 1) : (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) * (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) = 4 * (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁) := -- If we had a Gröbner basis algorithm, this would be trivial. -- Without one, it is somewhat tedious! begin rw ← sub_eq_zero, repeat { ring_nf, simp only [A₁_inv, B₁_inv, sub_eq_add_neg, add_mul, mul_add, sub_mul, mul_sub, add_assoc, neg_add, neg_sub, sub_add, sub_sub, neg_mul, ←sq, A₀_inv, B₀_inv, ←sq, ←mul_assoc, one_mul, mul_one, add_right_neg, add_zero, sub_eq_add_neg, A₀_inv, mul_one, add_right_neg, zero_mul] } end /-- Given a CHSH tuple (A₀, A₁, B₀, B₁) in a *commutative* ordered `*`-algebra over ℝ, `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2`. (We could work over ℤ[⅟2] if we wanted to!) -/ lemma CHSH_inequality_of_comm [ordered_comm_ring R] [star_ordered_ring R] [algebra ℝ R] [ordered_smul ℝ R] (A₀ A₁ B₀ B₁ : R) (T : is_CHSH_tuple A₀ A₁ B₀ B₁) : A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2 := begin let P := (2 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁), have i₁ : 0 ≤ P, { have idem : P * P = 4 * P := CHSH_id T.A₀_inv T.A₁_inv T.B₀_inv T.B₁_inv, have idem' : P = (1 / 4 : ℝ) • (P * P), { have h : 4 * P = (4 : ℝ) • P := by simp [algebra.smul_def], rw [idem, h, ←mul_smul], norm_num, }, have sa : star P = P, { dsimp [P], simp only [star_add, star_sub, star_mul, star_bit0, star_one, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa, mul_comm B₀, mul_comm B₁], }, rw idem', conv_rhs { congr, skip, congr, rw ←sa, }, convert smul_le_smul_of_nonneg (star_mul_self_nonneg : 0 ≤ star P * P) _, { simp, }, { apply_instance, }, { norm_num, } }, apply le_of_sub_nonneg, simpa only [sub_add_eq_sub_sub, ←sub_add] using i₁, end /-! We now prove some rather specialized lemmas in preparation for the Tsirelson inequality, which we hide in a namespace as they are unlikely to be useful elsewhere. -/ local notation `√2` := (real.sqrt 2 : ℝ) namespace tsirelson_inequality /-! Before proving Tsirelson's bound, we prepare some easy lemmas about √2. -/ -- This calculation, which we need for Tsirelson's bound, -- defeated me. Thanks for the rescue from Shing Tak Lam! lemma tsirelson_inequality_aux : √2 * √2 ^ 3 = √2 * (2 * √2⁻¹ + 4 * (√2⁻¹ * 2⁻¹)) := begin ring_nf, field_simp [(@real.sqrt_pos 2).2 (by norm_num)], convert congr_arg (^2) (@real.sq_sqrt 2 (by norm_num)) using 1; simp only [← pow_mul]; norm_num, end lemma sqrt_two_inv_mul_self : √2⁻¹ * √2⁻¹ = (2⁻¹ : ℝ) := by { rw ←mul_inv, norm_num } end tsirelson_inequality open tsirelson_inequality /-- In a noncommutative ordered `*`-algebra over ℝ, Tsirelson's bound for a CHSH tuple (A₀, A₁, B₀, B₁) is `A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ 2^(3/2) • 1`. We prove this by providing an explicit sum-of-squares decomposition of the difference. (We could work over `ℤ[2^(1/2), 2^(-1/2)]` if we really wanted to!) -/ lemma tsirelson_inequality [ordered_ring R] [star_ordered_ring R] [algebra ℝ R] [ordered_smul ℝ R] [star_module ℝ R] (A₀ A₁ B₀ B₁ : R) (T : is_CHSH_tuple A₀ A₁ B₀ B₁) : A₀ * B₀ + A₀ * B₁ + A₁ * B₀ - A₁ * B₁ ≤ √2^3 • 1 := begin -- abel will create `ℤ` multiplication. We will `simp` them away to `ℝ` multiplication. have M : ∀ (m : ℤ) (a : ℝ) (x : R), m • a • x = ((m : ℝ) * a) • x := λ m a x, by rw [zsmul_eq_smul_cast ℝ, ← mul_smul], let P := √2⁻¹ • (A₁ + A₀) - B₀, let Q := √2⁻¹ • (A₁ - A₀) + B₁, have w : √2^3 • 1 - A₀ * B₀ - A₀ * B₁ - A₁ * B₀ + A₁ * B₁ = √2⁻¹ • (P^2 + Q^2), { dsimp [P, Q], -- distribute out all the powers and products appearing on the RHS simp only [sq, sub_mul, mul_sub, add_mul, mul_add, smul_add, smul_sub], -- pull all coefficients out to the front, and combine `√2`s where possible simp only [algebra.mul_smul_comm, algebra.smul_mul_assoc, ←mul_smul, sqrt_two_inv_mul_self], -- replace Aᵢ * Aᵢ = 1 and Bᵢ * Bᵢ = 1 simp only [←sq, T.A₀_inv, T.A₁_inv, T.B₀_inv, T.B₁_inv], -- move Aᵢ to the left of Bᵢ simp only [←T.A₀B₀_commutes, ←T.A₀B₁_commutes, ←T.A₁B₀_commutes, ←T.A₁B₁_commutes], -- collect terms, simplify coefficients, and collect terms again: abel, -- all terms coincide, but the last one. Simplify all other terms simp only [M], simp only [neg_mul, int.cast_bit0, one_mul, mul_inv_cancel_of_invertible, int.cast_one, one_smul, int.cast_neg, add_right_inj, neg_smul, ← add_smul], -- just look at the coefficients now: congr, exact mul_left_cancel₀ (by norm_num) tsirelson_inequality_aux, }, have pos : 0 ≤ √2⁻¹ • (P^2 + Q^2), { have P_sa : star P = P, { dsimp [P], simp only [star_smul, star_add, star_sub, star_id_of_comm, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa], }, have Q_sa : star Q = Q, { dsimp [Q], simp only [star_smul, star_add, star_sub, star_id_of_comm, T.A₀_sa, T.A₁_sa, T.B₀_sa, T.B₁_sa], }, have P2_nonneg : 0 ≤ P^2, { rw [sq], conv { congr, skip, congr, rw ←P_sa, }, convert (star_mul_self_nonneg : 0 ≤ star P * P), }, have Q2_nonneg : 0 ≤ Q^2, { rw [sq], conv { congr, skip, congr, rw ←Q_sa, }, convert (star_mul_self_nonneg : 0 ≤ star Q * Q), }, convert smul_le_smul_of_nonneg (add_nonneg P2_nonneg Q2_nonneg) (le_of_lt (show 0 < √2⁻¹, by norm_num)), -- `norm_num` can't directly show `0 ≤ √2⁻¹` simp, }, apply le_of_sub_nonneg, simpa only [sub_add_eq_sub_sub, ←sub_add, w] using pos, end
5bb7bb2594421ca0c91dd0ccc309f095d20e0709
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/category_theory/over.lean
cf1f31ea66c4d98cf241afbca0828cc8083fee8c
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,135
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Bhavik Mehta -/ import category_theory.comma import category_theory.punit import category_theory.reflects_isomorphisms import category_theory.epi_mono /-! # Over and under categories Over (and under) categories are special cases of comma categories. * If `L` is the identity functor and `R` is a constant functor, then `comma L R` is the "slice" or "over" category over the object `R` maps to. * Conversely, if `L` is a constant functor and `R` is the identity functor, then `comma L R` is the "coslice" or "under" category under the object `L` maps to. ## Tags comma, slice, coslice, over, under -/ namespace category_theory universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {T : Type u₁} [category.{v₁} T] /-- The over category has as objects arrows in `T` with codomain `X` and as morphisms commutative triangles. See https://stacks.math.columbia.edu/tag/001G. -/ @[derive category] def over (X : T) := comma.{v₁ v₁ v₁} (𝟭 T) (functor.from_punit X) -- Satisfying the inhabited linter instance over.inhabited [inhabited T] : inhabited (over (default T)) := { default := { left := default T, hom := 𝟙 _ } } namespace over variables {X : T} @[ext] lemma over_morphism.ext {X : T} {U V : over X} {f g : U ⟶ V} (h : f.left = g.left) : f = g := by tidy @[simp] lemma over_right (U : over X) : U.right = punit.star := by tidy @[simp] lemma id_left (U : over X) : comma_morphism.left (𝟙 U) = 𝟙 U.left := rfl @[simp] lemma comp_left (a b c : over X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).left = f.left ≫ g.left := rfl @[simp, reassoc] lemma w {A B : over X} (f : A ⟶ B) : f.left ≫ B.hom = A.hom := by have := f.w; tidy /-- To give an object in the over category, it suffices to give a morphism with codomain `X`. -/ @[simps] def mk {X Y : T} (f : Y ⟶ X) : over X := { left := Y, hom := f } /-- We can set up a coercion from arrows with codomain `X` to `over X`. This most likely should not be a global instance, but it is sometimes useful. -/ def coe_from_hom {X Y : T} : has_coe (Y ⟶ X) (over X) := { coe := mk } section local attribute [instance] coe_from_hom @[simp] lemma coe_hom {X Y : T} (f : Y ⟶ X) : (f : over X).hom = f := rfl end /-- To give a morphism in the over category, it suffices to give an arrow fitting in a commutative triangle. -/ @[simps] def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) : U ⟶ V := { left := f } /-- Construct an isomorphism in the over category given isomorphisms of the objects whose forward direction gives a commutative triangle. -/ @[simps] def iso_mk {f g : over X} (hl : f.left ≅ g.left) (hw : hl.hom ≫ g.hom = f.hom . obviously) : f ≅ g := comma.iso_mk hl (eq_to_iso (subsingleton.elim _ _)) (by simp [hw]) section variable (X) /-- The forgetful functor mapping an arrow to its domain. See https://stacks.math.columbia.edu/tag/001G. -/ def forget : over X ⥤ T := comma.fst _ _ end @[simp] lemma forget_obj {U : over X} : (forget X).obj U = U.left := rfl @[simp] lemma forget_map {U V : over X} {f : U ⟶ V} : (forget X).map f = f.left := rfl /-- A morphism `f : X ⟶ Y` induces a functor `over X ⥤ over Y` in the obvious way. See https://stacks.math.columbia.edu/tag/001G. -/ def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ discrete.nat_trans (λ _, f) section variables {Y : T} {f : X ⟶ Y} {U V : over X} {g : U ⟶ V} @[simp] lemma map_obj_left : ((map f).obj U).left = U.left := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = U.hom ≫ f := rfl @[simp] lemma map_map_left : ((map f).map g).left = g.left := rfl /-- Mapping by the identity morphism is just the identity functor. -/ def map_id : map (𝟙 Y) ≅ 𝟭 _ := nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy) /-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/ def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map f ⋙ map g := nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy) end instance forget_reflects_iso : reflects_isomorphisms (forget X) := { reflects := λ Y Z f t, by exactI { inv := over.hom_mk t.inv ((as_iso ((forget X).map f)).inv_comp_eq.2 (over.w f).symm) } } instance forget_faithful : faithful (forget X) := {}. /-- If `k.left` is an epimorphism, then `k` is an epimorphism. In other words, `over.forget X` reflects epimorphisms. The converse does not hold without additional assumptions on the underlying category. -/ -- TODO: Show the converse holds if `T` has binary products or pushouts. lemma epi_of_epi_left {f g : over X} (k : f ⟶ g) [hk : epi k.left] : epi k := faithful_reflects_epi (forget X) hk /-- If `k.left` is a monomorphism, then `k` is a monomorphism. In other words, `over.forget X` reflects monomorphisms. The converse of `category_theory.over.mono_left_of_mono`. This lemma is not an instance, to avoid loops in type class inference. -/ lemma mono_of_mono_left {f g : over X} (k : f ⟶ g) [hk : mono k.left] : mono k := faithful_reflects_mono (forget X) hk /-- If `k` is a monomorphism, then `k.left` is a monomorphism. In other words, `over.forget X` preserves monomorphisms. The converse of `category_theory.over.mono_of_mono_left`. -/ instance mono_left_of_mono {f g : over X} (k : f ⟶ g) [mono k] : mono k.left := begin refine ⟨λ (Y : T) l m a, _⟩, let l' : mk (m ≫ f.hom) ⟶ f := hom_mk l (by { dsimp, rw [←over.w k, reassoc_of a] }), suffices : l' = hom_mk m, { apply congr_arg comma_morphism.left this }, rw ← cancel_mono k, ext, apply a, end section iterated_slice variables (f : over X) /-- Given f : Y ⟶ X, this is the obvious functor from (T/X)/f to T/Y -/ @[simps] def iterated_slice_forward : over f ⥤ over f.left := { obj := λ α, over.mk α.hom.left, map := λ α β κ, over.hom_mk κ.left.left (by { rw auto_param_eq, rw ← over.w κ, refl }) } /-- Given f : Y ⟶ X, this is the obvious functor from T/Y to (T/X)/f -/ @[simps] def iterated_slice_backward : over f.left ⥤ over f := { obj := λ g, mk (hom_mk g.hom : mk (g.hom ≫ f.hom) ⟶ f), map := λ g h α, hom_mk (hom_mk α.left (w_assoc α f.hom)) (over_morphism.ext (w α)) } /-- Given f : Y ⟶ X, we have an equivalence between (T/X)/f and T/Y -/ @[simps] def iterated_slice_equiv : over f ≌ over f.left := { functor := iterated_slice_forward f, inverse := iterated_slice_backward f, unit_iso := nat_iso.of_components (λ g, over.iso_mk (over.iso_mk (iso.refl _) (by tidy)) (by tidy)) (λ X Y g, by { ext, dsimp, simp }), counit_iso := nat_iso.of_components (λ g, over.iso_mk (iso.refl _) (by tidy)) (λ X Y g, by { ext, dsimp, simp }) } lemma iterated_slice_forward_forget : iterated_slice_forward f ⋙ forget f.left = forget f ⋙ forget X := rfl lemma iterated_slice_backward_forget_forget : iterated_slice_backward f ⋙ forget f ⋙ forget X = forget f.left := rfl end iterated_slice section variables {D : Type u₂} [category.{v₂} D] /-- A functor `F : T ⥤ D` induces a functor `over X ⥤ over (F.obj X)` in the obvious way. -/ @[simps] def post (F : T ⥤ D) : over X ⥤ over (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { left := F.map f.left, w' := by tidy; erw [← F.map_comp, w] } } end end over /-- The under category has as objects arrows with domain `X` and as morphisms commutative triangles. -/ @[derive category] def under (X : T) := comma.{v₁ v₁ v₁} (functor.from_punit X) (𝟭 T) -- Satisfying the inhabited linter instance under.inhabited [inhabited T] : inhabited (under (default T)) := { default := { right := default T, hom := 𝟙 _ } } namespace under variables {X : T} @[ext] lemma under_morphism.ext {X : T} {U V : under X} {f g : U ⟶ V} (h : f.right = g.right) : f = g := by tidy @[simp] lemma under_left (U : under X) : U.left = punit.star := by tidy @[simp] lemma id_right (U : under X) : comma_morphism.right (𝟙 U) = 𝟙 U.right := rfl @[simp] lemma comp_right (a b c : under X) (f : a ⟶ b) (g : b ⟶ c) : (f ≫ g).right = f.right ≫ g.right := rfl @[simp] lemma w {A B : under X} (f : A ⟶ B) : A.hom ≫ f.right = B.hom := by have := f.w; tidy /-- To give an object in the under category, it suffices to give an arrow with domain `X`. -/ @[simps] def mk {X Y : T} (f : X ⟶ Y) : under X := { right := Y, hom := f } /-- To give a morphism in the under category, it suffices to give a morphism fitting in a commutative triangle. -/ @[simps] def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) : U ⟶ V := { right := f } /-- Construct an isomorphism in the over category given isomorphisms of the objects whose forward direction gives a commutative triangle. -/ def iso_mk {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : f ≅ g := comma.iso_mk (eq_to_iso (subsingleton.elim _ _)) hr (by simp [hw]) @[simp] lemma iso_mk_hom_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : (iso_mk hr hw).hom.right = hr.hom := rfl @[simp] lemma iso_mk_inv_right {f g : under X} (hr : f.right ≅ g.right) (hw : f.hom ≫ hr.hom = g.hom) : (iso_mk hr hw).inv.right = hr.inv := rfl section variables (X) /-- The forgetful functor mapping an arrow to its domain. -/ def forget : under X ⥤ T := comma.snd _ _ end @[simp] lemma forget_obj {U : under X} : (forget X).obj U = U.right := rfl @[simp] lemma forget_map {U V : under X} {f : U ⟶ V} : (forget X).map f = f.right := rfl /-- A morphism `X ⟶ Y` induces a functor `under Y ⥤ under X` in the obvious way. -/ def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ discrete.nat_trans (λ _, f) section variables {Y : T} {f : X ⟶ Y} {U V : under Y} {g : U ⟶ V} @[simp] lemma map_obj_right : ((map f).obj U).right = U.right := rfl @[simp] lemma map_obj_hom : ((map f).obj U).hom = f ≫ U.hom := rfl @[simp] lemma map_map_right : ((map f).map g).right = g.right := rfl /-- Mapping by the identity morphism is just the identity functor. -/ def map_id : map (𝟙 Y) ≅ 𝟭 _ := nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy) /-- Mapping by the composite morphism `f ≫ g` is the same as mapping by `f` then by `g`. -/ def map_comp {Y Z : T} (f : X ⟶ Y) (g : Y ⟶ Z) : map (f ≫ g) ≅ map g ⋙ map f := nat_iso.of_components (λ X, iso_mk (iso.refl _) (by tidy)) (by tidy) end section variables {D : Type u₂} [category.{v₂} D] /-- A functor `F : T ⥤ D` induces a functor `under X ⥤ under (F.obj X)` in the obvious way. -/ @[simps] def post {X : T} (F : T ⥤ D) : under X ⥤ under (F.obj X) := { obj := λ Y, mk $ F.map Y.hom, map := λ Y₁ Y₂ f, { right := F.map f.right, w' := by tidy; erw [← F.map_comp, w] } } end end under end category_theory
6dfeabe03d2236e45dacbd01ddb57e6c63f1e239
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/list/rotate.lean
7c9cbb68c0de3424163b56435f0bb4b453341e1b
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,685
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Yakov Pechersky -/ import data.list.perm import data.list.range /-! # List rotation This file proves basic results about `list.rotate`, the list rotation. ## Main declarations * `is_rotated l₁ l₂`: States that `l₁` is a rotated version of `l₂`. * `cyclic_permutations l`: The list of all cyclic permutants of `l`, up to the length of `l`. ## Tags rotated, rotation, permutation, cycle -/ universe u variables {α : Type u} open nat namespace list lemma rotate_mod (l : list α) (n : ℕ) : l.rotate (n % l.length) = l.rotate n := by simp [rotate] @[simp] lemma rotate_nil (n : ℕ) : ([] : list α).rotate n = [] := by cases n; simp [rotate] @[simp] lemma rotate_zero (l : list α) : l.rotate 0 = l := by simp [rotate] @[simp] lemma rotate'_nil (n : ℕ) : ([] : list α).rotate' n = [] := by cases n; refl @[simp] lemma rotate'_zero (l : list α) : l.rotate' 0 = l := by cases l; refl lemma rotate'_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate' n.succ = (l ++ [a]).rotate' n := by simp [rotate'] @[simp] lemma length_rotate' : ∀ (l : list α) (n : ℕ), (l.rotate' n).length = l.length | [] n := rfl | (a::l) 0 := rfl | (a::l) (n+1) := by rw [list.rotate', length_rotate' (l ++ [a]) n]; simp lemma rotate'_eq_drop_append_take : ∀ {l : list α} {n : ℕ}, n ≤ l.length → l.rotate' n = l.drop n ++ l.take n | [] n h := by simp [drop_append_of_le_length h] | l 0 h := by simp [take_append_of_le_length h] | (a::l) (n+1) h := have hnl : n ≤ l.length, from le_of_succ_le_succ h, have hnl' : n ≤ (l ++ [a]).length, by rw [length_append, length_cons, list.length, zero_add]; exact (le_of_succ_le h), by rw [rotate'_cons_succ, rotate'_eq_drop_append_take hnl', drop, take, drop_append_of_le_length hnl, take_append_of_le_length hnl]; simp lemma rotate'_rotate' : ∀ (l : list α) (n m : ℕ), (l.rotate' n).rotate' m = l.rotate' (n + m) | (a::l) 0 m := by simp | [] n m := by simp | (a::l) (n+1) m := by rw [rotate'_cons_succ, rotate'_rotate', add_right_comm, rotate'_cons_succ] @[simp] lemma rotate'_length (l : list α) : rotate' l l.length = l := by rw rotate'_eq_drop_append_take (le_refl _); simp @[simp] lemma rotate'_length_mul (l : list α) : ∀ n : ℕ, l.rotate' (l.length * n) = l | 0 := by simp | (n+1) := calc l.rotate' (l.length * (n + 1)) = (l.rotate' (l.length * n)).rotate' (l.rotate' (l.length * n)).length : by simp [-rotate'_length, nat.mul_succ, rotate'_rotate'] ... = l : by rw [rotate'_length, rotate'_length_mul] lemma rotate'_mod (l : list α) (n : ℕ) : l.rotate' (n % l.length) = l.rotate' n := calc l.rotate' (n % l.length) = (l.rotate' (n % l.length)).rotate' ((l.rotate' (n % l.length)).length * (n / l.length)) : by rw rotate'_length_mul ... = l.rotate' n : by rw [rotate'_rotate', length_rotate', nat.mod_add_div] lemma rotate_eq_rotate' (l : list α) (n : ℕ) : l.rotate n = l.rotate' n := if h : l.length = 0 then by simp [length_eq_zero, *] at * else by rw [← rotate'_mod, rotate'_eq_drop_append_take (le_of_lt (nat.mod_lt _ (nat.pos_of_ne_zero h)))]; simp [rotate] lemma rotate_cons_succ (l : list α) (a : α) (n : ℕ) : (a :: l : list α).rotate n.succ = (l ++ [a]).rotate n := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate'_cons_succ] @[simp] lemma mem_rotate : ∀ {l : list α} {a : α} {n : ℕ}, a ∈ l.rotate n ↔ a ∈ l | [] _ n := by simp | (a::l) _ 0 := by simp | (a::l) _ (n+1) := by simp [rotate_cons_succ, mem_rotate, or.comm] @[simp] lemma length_rotate (l : list α) (n : ℕ) : (l.rotate n).length = l.length := by rw [rotate_eq_rotate', length_rotate'] lemma rotate_eq_drop_append_take {l : list α} {n : ℕ} : n ≤ l.length → l.rotate n = l.drop n ++ l.take n := by rw rotate_eq_rotate'; exact rotate'_eq_drop_append_take lemma rotate_eq_drop_append_take_mod {l : list α} {n : ℕ} : l.rotate n = l.drop (n % l.length) ++ l.take (n % l.length) := begin cases l.length.zero_le.eq_or_lt with hl hl, { simp [eq_nil_of_length_eq_zero hl.symm ] }, rw [←rotate_eq_drop_append_take (n.mod_lt hl).le, rotate_mod] end @[simp] lemma rotate_append_length_eq (l l' : list α) : (l ++ l').rotate l.length = l' ++ l := begin rw rotate_eq_rotate', induction l generalizing l', { simp, }, { simp [rotate', l_ih] }, end lemma rotate_rotate (l : list α) (n m : ℕ) : (l.rotate n).rotate m = l.rotate (n + m) := by rw [rotate_eq_rotate', rotate_eq_rotate', rotate_eq_rotate', rotate'_rotate'] @[simp] lemma rotate_length (l : list α) : rotate l l.length = l := by rw [rotate_eq_rotate', rotate'_length] @[simp] lemma rotate_length_mul (l : list α) (n : ℕ) : l.rotate (l.length * n) = l := by rw [rotate_eq_rotate', rotate'_length_mul] lemma prod_rotate_eq_one_of_prod_eq_one [group α] : ∀ {l : list α} (hl : l.prod = 1) (n : ℕ), (l.rotate n).prod = 1 | [] _ _ := by simp | (a::l) hl n := have n % list.length (a :: l) ≤ list.length (a :: l), from le_of_lt (nat.mod_lt _ dec_trivial), by rw ← list.take_append_drop (n % list.length (a :: l)) (a :: l) at hl; rw [← rotate_mod, rotate_eq_drop_append_take this, list.prod_append, mul_eq_one_iff_inv_eq, ← one_mul (list.prod _)⁻¹, ← hl, list.prod_append, mul_assoc, mul_inv_self, mul_one] lemma rotate_perm (l : list α) (n : ℕ) : l.rotate n ~ l := begin rw rotate_eq_rotate', induction n with n hn generalizing l, { simp }, { cases l with hd tl, { simp }, { rw rotate'_cons_succ, exact (hn _).trans (perm_append_singleton _ _) } } end @[simp] lemma nodup_rotate {l : list α} {n : ℕ} : nodup (l.rotate n) ↔ nodup l := (rotate_perm l n).nodup_iff @[simp] lemma rotate_eq_nil_iff {l : list α} {n : ℕ} : l.rotate n = [] ↔ l = [] := begin induction n with n hn generalizing l, { simp }, { cases l with hd tl, { simp }, { simp [rotate_cons_succ, hn] } } end @[simp] lemma nil_eq_rotate_iff {l : list α} {n : ℕ} : [] = l.rotate n ↔ [] = l := by rw [eq_comm, rotate_eq_nil_iff, eq_comm] @[simp] lemma rotate_singleton (x : α) (n : ℕ) : [x].rotate n = [x] := begin induction n with n hn, { simp }, { rwa [rotate_cons_succ] } end @[simp] lemma rotate_eq_singleton_iff {l : list α} {n : ℕ} {x : α} : l.rotate n = [x] ↔ l = [x] := begin induction n with n hn generalizing l, { simp }, { cases l with hd tl, { simp }, { simp [rotate_cons_succ, hn, append_eq_cons_iff, and_comm] } } end @[simp] lemma singleton_eq_rotate_iff {l : list α} {n : ℕ} {x : α} : [x] = l.rotate n ↔ [x] = l := by rw [eq_comm, rotate_eq_singleton_iff, eq_comm] lemma zip_with_rotate_distrib {α β γ : Type*} (f : α → β → γ) (l : list α) (l' : list β) (n : ℕ) (h : l.length = l'.length) : (zip_with f l l').rotate n = zip_with f (l.rotate n) (l'.rotate n) := begin rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod, h, zip_with_append, ←zip_with_distrib_drop, ←zip_with_distrib_take, list.length_zip_with, h, min_self], rw [length_drop, length_drop, h] end local attribute [simp] rotate_cons_succ @[simp] lemma zip_with_rotate_one {β : Type*} (f : α → α → β) (x y : α) (l : list α) : zip_with f (x :: y :: l) ((x :: y :: l).rotate 1) = f x y :: zip_with f (y :: l) (l ++ [x]) := by simp lemma nth_le_rotate_one (l : list α) (k : ℕ) (hk : k < (l.rotate 1).length) : (l.rotate 1).nth_le k hk = l.nth_le ((k + 1) % l.length) (mod_lt _ (length_rotate l 1 ▸ k.zero_le.trans_lt hk)) := begin cases l with hd tl, { simp }, { have : k ≤ tl.length, { refine nat.le_of_lt_succ _, simpa using hk }, rcases this.eq_or_lt with rfl|hk', { simp [nth_le_append_right (le_refl _)] }, { simpa [nth_le_append _ hk', length_cons, nat.mod_eq_of_lt (nat.succ_lt_succ hk')] } } end lemma nth_le_rotate (l : list α) (n k : ℕ) (hk : k < (l.rotate n).length) : (l.rotate n).nth_le k hk = l.nth_le ((k + n) % l.length) (mod_lt _ (length_rotate l n ▸ k.zero_le.trans_lt hk)) := begin induction n with n hn generalizing l k, { have hk' : k < l.length := by simpa using hk, simp [nat.mod_eq_of_lt hk'] }, { simp [nat.succ_eq_add_one, ←rotate_rotate, nth_le_rotate_one, hn l, add_comm, add_left_comm] } end /-- A variant of `nth_le_rotate` useful for rewrites. -/ lemma nth_le_rotate' (l : list α) (n k : ℕ) (hk : k < l.length) : (l.rotate n).nth_le ((l.length - n % l.length + k) % l.length) ((nat.mod_lt _ (k.zero_le.trans_lt hk)).trans_le (length_rotate _ _).ge) = l.nth_le k hk := begin rw nth_le_rotate, congr, set m := l.length, rw [mod_add_mod, add_assoc, add_left_comm, add_comm, add_mod, add_mod _ n], cases (n % m).zero_le.eq_or_lt with hn hn, { simpa [←hn] using nat.mod_eq_of_lt hk }, { have mpos : 0 < m := k.zero_le.trans_lt hk, have hm : m - n % m < m := nat.sub_lt_self mpos hn, have hn' : n % m < m := nat.mod_lt _ mpos, simpa [mod_eq_of_lt hm, nat.sub_add_cancel hn'.le] using nat.mod_eq_of_lt hk } end lemma rotate_injective (n : ℕ) : function.injective (λ l : list α, l.rotate n) := begin rintros l l' (h : l.rotate n = l'.rotate n), have hle : l.length = l'.length := (l.length_rotate n).symm.trans (h.symm ▸ l'.length_rotate n), rw [rotate_eq_drop_append_take_mod, rotate_eq_drop_append_take_mod] at h, obtain ⟨hd, ht⟩ := append_inj h _, { rw [←take_append_drop _ l, ht, hd, take_append_drop] }, { rw [length_drop, length_drop, hle] } end -- possibly easier to find in doc-gen, otherwise not that useful. lemma rotate_eq_rotate {l l' : list α} {n : ℕ} : l.rotate n = l'.rotate n ↔ l = l' := (rotate_injective n).eq_iff lemma rotate_eq_iff {l l' : list α} {n : ℕ} : l.rotate n = l' ↔ l = l'.rotate (l'.length - n % l'.length) := begin rw [←@rotate_eq_rotate _ l _ n, rotate_rotate, ←rotate_mod l', add_mod], cases l'.length.zero_le.eq_or_lt with hl hl, { rw [eq_nil_of_length_eq_zero hl.symm, rotate_nil, rotate_eq_nil_iff] }, { cases (nat.zero_le (n % l'.length)).eq_or_lt with hn hn, { simp [←hn] }, { rw [mod_eq_of_lt (nat.sub_lt_self hl hn), nat.sub_add_cancel, mod_self, rotate_zero], exact (nat.mod_lt _ hl).le } } end lemma reverse_rotate (l : list α) (n : ℕ) : (l.rotate n).reverse = l.reverse.rotate (l.length - (n % l.length)) := begin rw [←length_reverse l, ←rotate_eq_iff], induction n with n hn generalizing l, { simp }, { cases l with hd tl, { simp }, { rw [rotate_cons_succ, nat.succ_eq_add_one, ←rotate_rotate, hn], simp } } end lemma rotate_reverse (l : list α) (n : ℕ) : l.reverse.rotate n = (l.rotate (l.length - (n % l.length))).reverse := begin rw [←reverse_reverse l], simp_rw [reverse_rotate, reverse_reverse, rotate_eq_iff, rotate_rotate, length_rotate, length_reverse], rw [←length_reverse l], set k := n % l.reverse.length with hk, cases hk' : k with k', { simp [-length_reverse, ←rotate_rotate] }, { cases l with x l, { simp }, { have : k'.succ < (x :: l).length, { simp [←hk', hk, nat.mod_lt] }, rw [nat.mod_eq_of_lt, nat.sub_add_cancel, rotate_length], { exact nat.sub_le_self _ _ }, { exact nat.sub_lt_self (by simp) nat.succ_pos' } } } end lemma map_rotate {β : Type*} (f : α → β) (l : list α) (n : ℕ) : map f (l.rotate n) = (map f l).rotate n := begin induction n with n hn IH generalizing l, { simp }, { cases l with hd tl, { simp }, { simp [hn] } } end theorem nodup.rotate_eq_self_iff {l : list α} (hl : l.nodup) {n : ℕ} : l.rotate n = l ↔ n % l.length = 0 ∨ l = [] := begin split, { intro h, cases l.length.zero_le.eq_or_lt with hl' hl', { simp [←length_eq_zero, ←hl'] }, left, rw nodup_iff_nth_le_inj at hl, refine hl _ _ (mod_lt _ hl') hl' _, rw ←nth_le_rotate' _ n, simp_rw [h, nat.sub_add_cancel (mod_lt _ hl').le, mod_self] }, { rintro (h|h), { rw [←rotate_mod, h], exact rotate_zero l }, { simp [h] } } end lemma nodup.rotate_congr {l : list α} (hl : l.nodup) (hn : l ≠ []) (i j : ℕ) (h : l.rotate i = l.rotate j) : i % l.length = j % l.length := begin have hi : i % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hn), have hj : j % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hn), refine (nodup_iff_nth_le_inj.mp hl) _ _ hi hj _, rw [←nth_le_rotate' l i, ←nth_le_rotate' l j], simp [nat.sub_add_cancel, hi.le, hj.le, h] end section is_rotated variables (l l' : list α) /-- `is_rotated l₁ l₂` or `l₁ ~r l₂` asserts that `l₁` and `l₂` are cyclic permutations of each other. This is defined by claiming that `∃ n, l.rotate n = l'`. -/ def is_rotated : Prop := ∃ n, l.rotate n = l' infixr ` ~r `:1000 := is_rotated variables {l l'} @[refl] lemma is_rotated.refl (l : list α) : l ~r l := ⟨0, by simp⟩ @[symm] lemma is_rotated.symm (h : l ~r l') : l' ~r l := begin obtain ⟨n, rfl⟩ := h, cases l with hd tl, { simp }, { use (hd :: tl).length * n - n, rw [rotate_rotate, nat.add_sub_cancel', rotate_length_mul], exact nat.le_mul_of_pos_left (by simp) } end lemma is_rotated_comm : l ~r l' ↔ l' ~r l := ⟨is_rotated.symm, is_rotated.symm⟩ @[simp] protected lemma is_rotated.forall (l : list α) (n : ℕ) : l.rotate n ~r l := is_rotated.symm ⟨n, rfl⟩ @[trans] lemma is_rotated.trans {l'' : list α} (h : l ~r l') (h' : l' ~r l'') : l ~r l'' := begin obtain ⟨n, rfl⟩ := h, obtain ⟨m, rfl⟩ := h', rw rotate_rotate, use (n + m) end lemma is_rotated.eqv : equivalence (@is_rotated α) := mk_equivalence _ is_rotated.refl (λ _ _, is_rotated.symm) (λ _ _ _, is_rotated.trans) /-- The relation `list.is_rotated l l'` forms a `setoid` of cycles. -/ def is_rotated.setoid (α : Type*) : setoid (list α) := { r := is_rotated, iseqv := is_rotated.eqv } lemma is_rotated.perm (h : l ~r l') : l ~ l' := exists.elim h (λ _ hl, hl ▸ (rotate_perm _ _).symm) lemma is_rotated.nodup_iff (h : l ~r l') : nodup l ↔ nodup l' := h.perm.nodup_iff lemma is_rotated.mem_iff (h : l ~r l') {a : α} : a ∈ l ↔ a ∈ l' := h.perm.mem_iff @[simp] lemma is_rotated_nil_iff : l ~r [] ↔ l = [] := ⟨λ ⟨n, hn⟩, by simpa using hn, λ h, h ▸ by refl⟩ @[simp] lemma is_rotated_nil_iff' : [] ~r l ↔ [] = l := by rw [is_rotated_comm, is_rotated_nil_iff, eq_comm] @[simp] lemma is_rotated_singleton_iff {x : α} : l ~r [x] ↔ l = [x] := ⟨λ ⟨n, hn⟩, by simpa using hn, λ h, h ▸ by refl⟩ @[simp] lemma is_rotated_singleton_iff' {x : α} : [x] ~r l ↔ [x] = l := by rw [is_rotated_comm, is_rotated_singleton_iff, eq_comm] lemma is_rotated_concat (hd : α) (tl : list α) : (tl ++ [hd]) ~r (hd :: tl) := is_rotated.symm ⟨1, by simp⟩ lemma is_rotated_append : (l ++ l') ~r (l' ++ l) := ⟨l.length, by simp⟩ lemma is_rotated.reverse (h : l ~r l') : l.reverse ~r l'.reverse := begin obtain ⟨n, rfl⟩ := h, exact ⟨_, (reverse_rotate _ _).symm⟩ end lemma is_rotated_reverse_comm_iff : l.reverse ~r l' ↔ l ~r l'.reverse := begin split; { intro h, simpa using h.reverse } end @[simp] lemma is_rotated_reverse_iff : l.reverse ~r l'.reverse ↔ l ~r l' := by simp [is_rotated_reverse_comm_iff] lemma is_rotated_iff_mod : l ~r l' ↔ ∃ n ≤ l.length, l.rotate n = l' := begin refine ⟨λ h, _, λ ⟨n, _, h⟩, ⟨n, h⟩⟩, obtain ⟨n, rfl⟩ := h, cases l with hd tl, { simp }, { refine ⟨n % (hd :: tl).length, _, rotate_mod _ _⟩, refine (nat.mod_lt _ _).le, simp } end lemma is_rotated_iff_mem_map_range : l ~r l' ↔ l' ∈ (list.range (l.length + 1)).map l.rotate := begin simp_rw [mem_map, mem_range, is_rotated_iff_mod], exact ⟨λ ⟨n, hn, h⟩, ⟨n, nat.lt_succ_of_le hn, h⟩, λ ⟨n, hn, h⟩, ⟨n, nat.le_of_lt_succ hn, h⟩⟩ end @[congr] theorem is_rotated.map {β : Type*} {l₁ l₂ : list α} (h : l₁ ~r l₂) (f : α → β) : map f l₁ ~r map f l₂ := begin obtain ⟨n, rfl⟩ := h, rw map_rotate, use n end /-- List of all cyclic permutations of `l`. The `cyclic_permutations` of a nonempty list `l` will always contain `list.length l` elements. This implies that under certain conditions, there are duplicates in `list.cyclic_permutations l`. The `n`th entry is equal to `l.rotate n`, proven in `list.nth_le_cyclic_permutations`. The proof that every cyclic permutant of `l` is in the list is `list.mem_cyclic_permutations_iff`. cyclic_permutations [1, 2, 3, 2, 4] = [[1, 2, 3, 2, 4], [2, 3, 2, 4, 1], [3, 2, 4, 1, 2], [2, 4, 1, 2, 3], [4, 1, 2, 3, 2]] -/ def cyclic_permutations : list α → list (list α) | [] := [[]] | l@(_ :: _) := init (zip_with (++) (tails l) (inits l)) @[simp] lemma cyclic_permutations_nil : cyclic_permutations ([] : list α) = [[]] := rfl lemma cyclic_permutations_cons (x : α) (l : list α) : cyclic_permutations (x :: l) = init (zip_with (++) (tails (x :: l)) (inits (x :: l))) := rfl lemma cyclic_permutations_of_ne_nil (l : list α) (h : l ≠ []) : cyclic_permutations l = init (zip_with (++) (tails l) (inits l)) := begin obtain ⟨hd, tl, rfl⟩ := exists_cons_of_ne_nil h, exact cyclic_permutations_cons _ _, end lemma length_cyclic_permutations_cons (x : α) (l : list α) : length (cyclic_permutations (x :: l)) = length l + 1 := by simp [cyclic_permutations_of_ne_nil] @[simp] lemma length_cyclic_permutations_of_ne_nil (l : list α) (h : l ≠ []) : length (cyclic_permutations l) = length l := by simp [cyclic_permutations_of_ne_nil _ h] @[simp] lemma nth_le_cyclic_permutations (l : list α) (n : ℕ) (hn : n < length (cyclic_permutations l)) : nth_le (cyclic_permutations l) n hn = l.rotate n := begin obtain rfl | h := eq_or_ne l [], { simp }, { rw length_cyclic_permutations_of_ne_nil _ h at hn, simp [init_eq_take, cyclic_permutations_of_ne_nil _ h, nth_le_take', rotate_eq_drop_append_take hn.le] } end lemma mem_cyclic_permutations_self (l : list α) : l ∈ cyclic_permutations l := begin cases l with x l, { simp }, { rw mem_iff_nth_le, refine ⟨0, by simp, _⟩, simp } end lemma length_mem_cyclic_permutations (l : list α) (h : l' ∈ cyclic_permutations l) : length l' = length l := begin obtain ⟨k, hk, rfl⟩ := nth_le_of_mem h, simp end @[simp] lemma mem_cyclic_permutations_iff {l l' : list α} : l ∈ cyclic_permutations l' ↔ l ~r l' := begin split, { intro h, obtain ⟨k, hk, rfl⟩ := nth_le_of_mem h, simp }, { intro h, obtain ⟨k, rfl⟩ := h.symm, rw mem_iff_nth_le, simp only [exists_prop, nth_le_cyclic_permutations], cases l' with x l, { simp }, { refine ⟨k % length (x :: l), _, rotate_mod _ _⟩, simpa using nat.mod_lt _ (zero_lt_succ _) } } end @[simp] lemma cyclic_permutations_eq_nil_iff {l : list α} : cyclic_permutations l = [[]] ↔ l = [] := begin refine ⟨λ h, _, λ h, by simp [h]⟩, rw [eq_comm, ←is_rotated_nil_iff', ←mem_cyclic_permutations_iff, h, mem_singleton] end @[simp] lemma cyclic_permutations_eq_singleton_iff {l : list α} {x : α} : cyclic_permutations l = [[x]] ↔ l = [x] := begin refine ⟨λ h, _, λ h, by simp [cyclic_permutations, h, init_eq_take]⟩, rw [eq_comm, ←is_rotated_singleton_iff', ←mem_cyclic_permutations_iff, h, mem_singleton] end /-- If a `l : list α` is `nodup l`, then all of its cyclic permutants are distinct. -/ lemma nodup.cyclic_permutations {l : list α} (hn : nodup l) : nodup (cyclic_permutations l) := begin cases l with x l, { simp }, rw nodup_iff_nth_le_inj, intros i j hi hj h, simp only [length_cyclic_permutations_cons] at hi hj, rw [←mod_eq_of_lt hi, ←mod_eq_of_lt hj, ←length_cons x l], apply hn.rotate_congr, { simp }, { simpa using h } end @[simp] lemma cyclic_permutations_rotate (l : list α) (k : ℕ) : (l.rotate k).cyclic_permutations = l.cyclic_permutations.rotate k := begin have : (l.rotate k).cyclic_permutations.length = length (l.cyclic_permutations.rotate k), { cases l, { simp }, { rw length_cyclic_permutations_of_ne_nil; simp } }, refine ext_le this (λ n hn hn', _), rw [nth_le_cyclic_permutations, nth_le_rotate, nth_le_cyclic_permutations, rotate_rotate, ←rotate_mod, add_comm], cases l; simp end lemma is_rotated.cyclic_permutations {l l' : list α} (h : l ~r l') : l.cyclic_permutations ~r l'.cyclic_permutations := begin obtain ⟨k, rfl⟩ := h, exact ⟨k, by simp⟩ end @[simp] lemma is_rotated_cyclic_permutations_iff {l l' : list α} : l.cyclic_permutations ~r l'.cyclic_permutations ↔ l ~r l' := begin by_cases hl : l = [], { simp [hl, eq_comm] }, have hl' : l.cyclic_permutations.length = l.length := length_cyclic_permutations_of_ne_nil _ hl, refine ⟨λ h, _, is_rotated.cyclic_permutations⟩, obtain ⟨k, hk⟩ := h, refine ⟨k % l.length, _⟩, have hk' : k % l.length < l.length := mod_lt _ (length_pos_of_ne_nil hl), rw [←nth_le_cyclic_permutations _ _ (hk'.trans_le hl'.ge), ←nth_le_rotate' _ k], simp [hk, hl', nat.sub_add_cancel hk'.le] end section decidable variables [decidable_eq α] instance is_rotated_decidable (l l' : list α) : decidable (l ~r l') := decidable_of_iff' _ is_rotated_iff_mem_map_range instance {l l' : list α} : decidable (@setoid.r _ (is_rotated.setoid α) l l') := list.is_rotated_decidable _ _ end decidable end is_rotated end list
814b76068b32b41d5b6985e811dfa6fa855478a7
0ed3609caf1962115b28aeb010d2bda5f67ddc4c
/src/algebra/field.lean
3121236bcc32f60d112036277eb69b121294f3b9
[ "Apache-2.0" ]
permissive
jonaslippert/mathlib
82dba29632969e3ed1c153a6454306f6bc9d9037
1435a196db69a7886a11e310e8923f3dcf249b81
refs/heads/master
1,609,938,673,069
1,582,018,388,000
1,582,018,388,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,770
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 algebra.ring logic.basic open set universe u variables {α : Type u} /-- Core version `division_ring_has_div` erratically requires two instances of `division_ring` -/ -- priority 900 sufficient as core version has custom-set lower priority (100) @[priority 900] -- see Note [lower instance priority] instance division_ring_has_div' [division_ring α] : has_div α := ⟨algebra.div⟩ @[priority 100] -- see Note [lower instance priority] instance division_ring.to_domain [s : division_ring α] : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, classical.by_contradiction $ λ hn, division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h ..s } @[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one] @[simp] theorem inv_inv' [discrete_field α] (x : α) : x⁻¹⁻¹ = x := if h : x = 0 then by rw [h, inv_zero, inv_zero] else division_ring.inv_inv h lemma inv_involutive' [discrete_field α] : function.involutive (has_inv.inv : α → α) := inv_inv' namespace units variables [division_ring α] {a b : α} /-- Embed an element of a division ring into the unit group. By combining this function with the operations on units, or the `/ₚ` operation, it is possible to write a division as a partial function with three arguments. -/ def mk0 (a : α) (ha : a ≠ 0) : units α := ⟨a, a⁻¹, mul_inv_cancel ha, inv_mul_cancel ha⟩ @[simp] theorem inv_eq_inv (u : units α) : (↑u⁻¹ : α) = u⁻¹ := (mul_left_inj u).1 $ by rw [units.mul_inv, mul_inv_cancel]; apply units.ne_zero @[simp] theorem mk0_val (ha : a ≠ 0) : (mk0 a ha : α) = a := rfl @[simp] theorem mk0_inv (ha : a ≠ 0) : ((mk0 a ha)⁻¹ : α) = a⁻¹ := rfl @[simp] lemma mk0_coe (u : units α) (h : (u : α) ≠ 0) : mk0 (u : α) h = u := units.ext rfl @[simp] lemma mk0_inj {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : units.mk0 a ha = units.mk0 b hb ↔ a = b := ⟨λ h, by injection h, λ h, units.ext h⟩ end units section division_ring variables [s : division_ring α] {a b c : α} include s lemma div_eq_mul_inv : a / b = a * b⁻¹ := rfl attribute [simp] div_one zero_div div_self theorem divp_eq_div (a : α) (u : units α) : a /ₚ u = a / u := congr_arg _ $ units.inv_eq_inv _ @[simp] theorem divp_mk0 (a : α) {b : α} (hb : b ≠ 0) : a /ₚ units.mk0 b hb = a / b := divp_eq_div _ _ lemma inv_div (ha : a ≠ 0) (hb : b ≠ 0) : (a / b)⁻¹ = b / a := (mul_inv_eq (inv_ne_zero hb) ha).trans $ by rw division_ring.inv_inv hb; refl lemma inv_div_left (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ / b = (b * a)⁻¹ := (mul_inv_eq ha hb).symm lemma neg_inv (h : a ≠ 0) : - a⁻¹ = (- a)⁻¹ := by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div _ h] lemma division_ring.inv_comm_of_comm (h : a ≠ 0) (H : a * b = b * a) : a⁻¹ * b = b * a⁻¹ := begin have : a⁻¹ * (b * a) * a⁻¹ = a⁻¹ * (a * b) * a⁻¹ := congr_arg (λ x:α, a⁻¹ * x * a⁻¹) H.symm, rwa [mul_assoc, mul_assoc, mul_inv_cancel, mul_one, ← mul_assoc, inv_mul_cancel, one_mul] at this; exact h end lemma div_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a / b ≠ 0 := division_ring.mul_ne_zero ha (inv_ne_zero hb) lemma div_ne_zero_iff (hb : b ≠ 0) : a / b ≠ 0 ↔ a ≠ 0 := ⟨mt (λ h, by rw [h, zero_div]), λ ha, div_ne_zero ha hb⟩ lemma div_eq_zero_iff (hb : b ≠ 0) : a / b = 0 ↔ a = 0 := by haveI := classical.prop_decidable; exact not_iff_not.1 (div_ne_zero_iff hb) lemma add_div (a b c : α) : (a + b) / c = a / c + b / c := (div_add_div_same _ _ _).symm lemma div_right_inj (hc : c ≠ 0) : a / c = b / c ↔ a = b := by rw [← divp_mk0 _ hc, ← divp_mk0 _ hc, divp_right_inj] lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c := (div_sub_div_same _ _ _).symm lemma division_ring.inv_inj (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b⁻¹ ↔ a = b := ⟨λ h, by rw [← division_ring.inv_inv ha, ← division_ring.inv_inv hb, h], congr_arg (λx,x⁻¹)⟩ lemma division_ring.inv_eq_iff (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ = b ↔ b⁻¹ = a := by rw [← division_ring.inv_inj (inv_ne_zero ha) hb, eq_comm, division_ring.inv_inv ha] lemma div_neg (a : α) (hb : b ≠ 0) : a / -b = -(a / b) := by rw [← division_ring.neg_div_neg_eq _ (neg_ne_zero.2 hb), neg_neg, neg_div] lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a := ⟨λ h, by rw [← h, div_mul_cancel _ hb], λ h, by rw [← h, mul_div_cancel _ hb]⟩ end division_ring @[priority 100] -- see Note [lower instance priority] instance field.to_integral_domain [F : field α] : integral_domain α := { ..F, ..division_ring.to_domain } section variables [field α] {a b c d : α} lemma div_eq_inv_mul : a / b = b⁻¹ * a := mul_comm _ _ lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb] lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) := by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one] lemma mul_div_right_comm (a b c : α) : (a * b) / c = (a / c) * b := (div_mul_eq_mul_div _ _ _).symm lemma mul_comm_div (a b c : α) : (a / b) * c = a * (c / b) := by rw [← mul_div_assoc, mul_div_right_comm] lemma div_mul_comm (a b c : α) : (a / b) * c = (c / b) * a := by rw [div_mul_eq_mul_div, mul_comm, mul_div_right_comm] lemma mul_div_comm (a b c : α) : a * (b / c) = b * (a / c) := by rw [← mul_div_assoc, mul_comm, mul_div_assoc] lemma field.div_right_comm (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / b) / c = (a / c) / b := by rw [field.div_div_eq_div_mul _ hb hc, field.div_div_eq_div_mul _ hc hb, mul_comm] lemma field.div_div_div_cancel_right (a : α) (hb : b ≠ 0) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := by rw [field.div_div_eq_mul_div _ hb hc, div_mul_cancel _ hc] lemma div_mul_div_cancel (a : α) (hc : c ≠ 0) : (a / c) * (c / b) = a / b := by rw [← mul_div_assoc, div_mul_cancel _ hc] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b := (domain.mul_right_inj (mul_ne_zero' hb hd)).symm.trans $ by rw [← mul_assoc, div_mul_cancel _ hb, ← mul_assoc, mul_right_comm, div_mul_cancel _ hd] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b := by simpa using @div_eq_div_iff _ _ a b c 1 hb one_ne_zero lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a := by simpa using @div_eq_div_iff _ _ c 1 a b one_ne_zero hb lemma field.div_div_cancel (ha : a ≠ 0) (hb : b ≠ 0) : a / (a / b) = b := by rw [div_eq_mul_inv, inv_div ha hb, mul_div_cancel' _ ha] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by simpa using div_add_div b a one_ne_zero hc end section variables [discrete_field α] {a b c : α} attribute [simp] inv_zero div_zero lemma div_right_comm (a b c : α) : (a / b) / c = (a / c) / b := if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else if c0 : c = 0 then by simp only [c0, div_zero, zero_div] else field.div_right_comm _ b0 c0 lemma div_div_div_cancel_right (a b : α) (hc : c ≠ 0) : (a / c) / (b / c) = a / b := if b0 : b = 0 then by simp only [b0, div_zero, zero_div] else field.div_div_div_cancel_right _ b0 hc lemma div_div_cancel (ha : a ≠ 0) : a / (a / b) = b := if b0 : b = 0 then by simp only [b0, div_zero] else field.div_div_cancel ha b0 @[simp] lemma inv_eq_zero {a : α} : a⁻¹ = 0 ↔ a = 0 := classical.by_cases (assume : a = 0, by simp [*])(assume : a ≠ 0, by simp [*, inv_ne_zero]) lemma neg_inv' (a : α) : (-a)⁻¹ = - a⁻¹ := begin by_cases a = 0, { rw [h, neg_zero, inv_zero, neg_zero] }, { rw [neg_inv h] } end end namespace ring_hom section variables {β : Type*} [division_ring α] [division_ring β] (f : α →+* β) {x y : α} lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := ⟨mt $ λ h, h.symm ▸ f.map_zero, λ x0 h, one_ne_zero $ by rw [← f.map_one, ← mul_inv_cancel x0, f.map_mul, h, zero_mul]⟩ lemma map_eq_zero : f x = 0 ↔ x = 0 := by haveI := classical.dec; exact not_iff_not.1 f.map_ne_zero lemma map_inv' (h : x ≠ 0) : f x⁻¹ = (f x)⁻¹ := (domain.mul_left_inj (f.map_ne_zero.2 h)).1 $ by rw [mul_inv_cancel (f.map_ne_zero.2 h), ← f.map_mul, mul_inv_cancel h, f.map_one] lemma map_div' (h : y ≠ 0) : f (x / y) = f x / f y := (f.map_mul _ _).trans $ congr_arg _ $ f.map_inv' h lemma injective : function.injective f := f.injective_iff.2 (λ a ha, classical.by_contradiction $ λ ha0, by simpa [ha, f.map_mul, f.map_one, zero_ne_one] using congr_arg f (mul_inv_cancel ha0)) end section variables {β : Type*} [discrete_field α] [discrete_field β] (f : α →+* β) {x y : α} lemma map_inv : f x⁻¹ = (f x)⁻¹ := classical.by_cases (by rintro rfl; simp only [map_zero f, inv_zero]) (map_inv' f) lemma map_div : f (x / y) = f x / f y := (f.map_mul _ _).trans $ congr_arg _ $ map_inv f end end ring_hom namespace is_ring_hom open ring_hom (of) section variables {β : Type*} [division_ring α] [division_ring β] variables (f : α → β) [is_ring_hom f] {x y : α} @[simp] lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 := (of f).map_ne_zero @[simp] lemma map_eq_zero : f x = 0 ↔ x = 0 := (of f).map_eq_zero lemma map_inv' (h : x ≠ 0) : f x⁻¹ = (f x)⁻¹ := (of f).map_inv' h lemma map_div' (h : y ≠ 0) : f (x / y) = f x / f y := (of f).map_div' h lemma injective : function.injective f := (of f).injective end section variables {β : Type*} [discrete_field α] [discrete_field β] variables (f : α → β) [is_ring_hom f] {x y : α} @[simp] lemma map_inv : f x⁻¹ = (f x)⁻¹ := (of f).map_inv @[simp] lemma map_div : f (x / y) = f x / f y := (of f).map_div end end is_ring_hom section field_simp mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are division-free." lemma mul_div_assoc' {α : Type*} [division_ring α] (a b c : α) : a * (b / c) = (a * b) / c := by simp [mul_div_assoc] lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a := by simp [neg_div] attribute [field_simps] div_add_div_same inv_eq_one_div div_mul_eq_mul_div div_add' add_div' div_div_eq_div_mul mul_div_assoc' div_eq_div_iff div_eq_iff eq_div_iff mul_ne_zero' div_div_eq_mul_div neg_div' two_ne_zero end field_simp
a8b3cca3c19ebfc2acab5cef97090001d5d9730b
649957717d58c43b5d8d200da34bf374293fe739
/src/linear_algebra/finsupp_vector_space.lean
21defae08bc75b6b1c739ff19b5c56b336e65798
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
5,783
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear structures on function with finite support `α →₀ β`. -/ import data.finsupp data.mv_polynomial linear_algebra.dimension noncomputable theory open lattice set linear_map submodule namespace finsupp section module variables {α : Type*} {β : Type*} {γ : Type*} variables [decidable_eq α] [decidable_eq β] [ring γ] [add_comm_group β] [module γ β] lemma linear_independent_single [decidable_eq γ] {φ : α → Type*} [∀ a, decidable_eq (φ a)] {f : Π α, φ α → β} (hf : ∀a, linear_independent γ (f a)) : linear_independent γ (λ ax : Σ a, φ a, single ax.1 (f ax.1 ax.2)) := begin apply @linear_independent_Union_finite γ _ _ _ _ _ _ α φ _ _ (λ a x, single a (f a x)), { assume a, have h_disjoint : disjoint (span γ (range (f a))) (ker (lsingle a)), { rw ker_lsingle, exact disjoint_bot_right }, apply linear_independent.image (hf a) h_disjoint }, { intros i t ht hit, apply disjoint_mono _ _ (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)), { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr_le_supr (λ i, supr_le_supr _), intros hi, rw span_le, rw range_coe, apply range_comp_subset_range } } end end module section vector_space variables {α : Type*} {β : Type*} {γ : Type*} variables [decidable_eq α] [decidable_eq β] [discrete_field γ] [add_comm_group β] [vector_space γ β] open linear_map submodule lemma is_basis_single {φ : α → Type*} [∀ a, decidable_eq (φ a)] (f : Π α, φ α → β) (hf : ∀a, is_basis γ (f a)) : is_basis γ (λ ax : Σ a, φ a, single ax.1 (f ax.1 ax.2)) := begin split, { apply linear_independent_single, exact λ a, (hf a).1 }, { rw [range_sigma_eq_Union_range, span_Union], simp only [image_univ.symm, λ i, image_comp (single i) (f i), span_single_image], simp only [image_univ, (hf _).2, map_top, supr_lsingle_range] } end end vector_space section dim universes u v variables {α : Type u} {β : Type u} {γ : Type v} variables [decidable_eq α] [decidable_eq β] [discrete_field γ] [add_comm_group β] [vector_space γ β] lemma dim_eq : vector_space.dim γ (α →₀ β) = cardinal.mk α * vector_space.dim γ β := begin rcases exists_is_basis γ β with ⟨bs, hbs⟩, rw [← cardinal.lift_inj, cardinal.lift_mul, ← hbs.mk_eq_dim, ← (is_basis_single _ (λa:α, hbs)).mk_eq_dim, ← cardinal.sum_mk, ← cardinal.lift_mul, cardinal.lift_inj], { simp only [cardinal.mk_image_eq (injective_single.{u u} _), cardinal.sum_const] } end end dim end finsupp section vector_space universes u v variables {α : Type u} {β γ : Type v} variables [discrete_field α] variables [add_comm_group β] [vector_space α β] variables [add_comm_group γ] [vector_space α γ] open vector_space set_option class.instance_max_depth 70 lemma equiv_of_dim_eq_dim [decidable_eq β] [decidable_eq γ] (h : dim α β = dim α γ) : nonempty (β ≃ₗ[α] γ) := begin rcases exists_is_basis α β with ⟨b, hb⟩, rcases exists_is_basis α γ with ⟨c, hc⟩, rw [← cardinal.lift_inj, ← hb.mk_eq_dim, ← hc.mk_eq_dim, cardinal.lift_inj] at h, rcases quotient.exact h with ⟨e⟩, exact ⟨((module_equiv_finsupp hb).trans (finsupp.dom_lcongr e)).trans (module_equiv_finsupp hc).symm⟩, end lemma eq_bot_iff_dim_eq_zero [decidable_eq β] (p : submodule α β) (h : dim α p = 0) : p = ⊥ := begin have : dim α p = dim α (⊥ : submodule α β) := by rwa [dim_bot], rcases equiv_of_dim_eq_dim this with ⟨e⟩, exact e.eq_bot_of_equiv _ end lemma injective_of_surjective [decidable_eq β] [decidable_eq γ] (f : β →ₗ[α] γ) (hβ : dim α β < cardinal.omega) (heq : dim α γ = dim α β) (hf : f.range = ⊤) : f.ker = ⊥ := have hk : dim α f.ker < cardinal.omega := lt_of_le_of_lt (dim_submodule_le _) hβ, begin rcases cardinal.lt_omega.1 hβ with ⟨d₁, eq₁⟩, rcases cardinal.lt_omega.1 hk with ⟨d₂, eq₂⟩, have : 0 = d₂, { have := dim_eq_surjective f (linear_map.range_eq_top.1 hf), rw [heq, eq₁, eq₂, ← nat.cast_add, cardinal.nat_cast_inj] at this, exact nat.add_left_cancel this }, refine eq_bot_iff_dim_eq_zero _ _, rw [eq₂, ← this, nat.cast_zero] end end vector_space section vector_space universes u open vector_space set_option class.instance_max_depth 50 local attribute [instance] submodule.module set_option pp.universes false lemma cardinal_mk_eq_cardinal_mk_field_pow_dim {α β : Type u} [decidable_eq β] [discrete_field α] [add_comm_group β] [vector_space α β] (h : dim α β < cardinal.omega) : cardinal.mk β = cardinal.mk α ^ dim α β := begin rcases exists_is_basis α β with ⟨s, hs⟩, have : nonempty (fintype s), { rwa [← cardinal.lt_omega_iff_fintype, cardinal.lift_inj.1 hs.mk_eq_dim] }, cases this with hsf, letI := hsf, calc cardinal.mk β = cardinal.mk (s →₀ α) : quotient.sound ⟨(module_equiv_finsupp hs).to_equiv⟩ ... = cardinal.mk (s → α) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_dim_lt_omega {α β : Type u} [decidable_eq β] [discrete_field α] [add_comm_group β] [vector_space α β] [fintype α] (h : dim α β < cardinal.omega) : cardinal.mk β < cardinal.omega := begin rw [cardinal_mk_eq_cardinal_mk_field_pow_dim h], exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) h end end vector_space
52a37d27afa6ea5a2bc8400838b68680779978e9
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Compiler/IR/EmitC.lean
3fec035e886a0d0a8dca8a5149ed5781b61e3c6f
[ "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
24,611
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.Conditional import Init.Lean.Runtime import Init.Lean.Compiler.NameMangling import Init.Lean.Compiler.ExportAttr import Init.Lean.Compiler.InitAttr import Init.Lean.Compiler.IR.CompilerM import Init.Lean.Compiler.IR.EmitUtil import Init.Lean.Compiler.IR.NormIds import Init.Lean.Compiler.IR.SimpCase import Init.Lean.Compiler.IR.Boxing namespace Lean namespace IR open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName) namespace EmitC def leanMainFn := "_lean_main" structure Context := (env : Environment) (modName : Name) (jpMap : JPParamsMap := {}) (mainFn : FunId := arbitrary _) (mainParams : Array Param := #[]) abbrev M := ReaderT Context (EStateM String String) def getEnv : M Environment := Context.env <$> read def getModName : M Name := Context.modName <$> read def getDecl (n : Name) : M Decl := do env ← getEnv; match findEnvDecl env n with | some d => pure d | none => throw ("unknown declaration '" ++ toString n ++ "'") @[inline] def emit {α : Type} [HasToString α] (a : α) : M Unit := modify (fun out => out ++ toString a) @[inline] def emitLn {α : Type} [HasToString α] (a : α) : M Unit := emit a *> emit "\n" def emitLns {α : Type} [HasToString α] (as : List α) : M Unit := as.forM $ fun a => emitLn a def argToCString (x : Arg) : String := match x with | Arg.var x => toString x | _ => "lean_box(0)" def emitArg (x : Arg) : M Unit := emit (argToCString x) def toCType : IRType → String | IRType.float => "double" | IRType.uint8 => "uint8_t" | IRType.uint16 => "uint16_t" | IRType.uint32 => "uint32_t" | IRType.uint64 => "uint64_t" | IRType.usize => "size_t" | IRType.object => "lean_object*" | IRType.tobject => "lean_object*" | IRType.irrelevant => "lean_object*" | IRType.struct _ _ => panic! "not implemented yet" | IRType.union _ _ => panic! "not implemented yet" def throwInvalidExportName {α : Type} (n : Name) : M α := throw ("invalid export name '" ++ toString n ++ "'") def toCName (n : Name) : M String := do env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor env n with | some (Name.str Name.anonymous s _) => pure s | some _ => throwInvalidExportName n | none => if n == `main then pure leanMainFn else pure n.mangle def emitCName (n : Name) : M Unit := toCName n >>= emit def toCInitName (n : Name) : M String := do env ← getEnv; -- TODO: we should support simple export names only match getExportNameFor env n with | some (Name.str Name.anonymous s _) => pure $ "_init_" ++ s | some _ => throwInvalidExportName n | none => pure ("_init_" ++ n.mangle) def emitCInitName (n : Name) : M Unit := toCInitName n >>= emit def emitFnDeclAux (decl : Decl) (cppBaseName : String) (addExternForConsts : Bool) : M Unit := do let ps := decl.params; env ← getEnv; when (ps.isEmpty && addExternForConsts) (emit "extern "); emit (toCType decl.resultType ++ " " ++ cppBaseName); unless (ps.isEmpty) $ do { emit "("; -- We omit irrelevant parameters for extern constants let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps; if ps.size > closureMaxArgs && isBoxedName decl.name then emit "lean_object**" else ps.size.forM $ fun i => do { when (i > 0) (emit ", "); emit (toCType (ps.get! i).ty) }; emit ")" }; emitLn ";" def emitFnDecl (decl : Decl) (addExternForConsts : Bool) : M Unit := do cppBaseName ← toCName decl.name; emitFnDeclAux decl cppBaseName addExternForConsts def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do let cName := mkNameSimple cNameStr; env ← getEnv; let extC := isExternC env decl.name; emitFnDeclAux decl cNameStr (!extC) def emitFnDecls : M Unit := do env ← getEnv; let decls := getDecls env; let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {}; let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {}; let usedDecls := usedDecls.toList; usedDecls.forM $ fun n => do decl ← getDecl n; match getExternNameFor env `c decl.name with | some cName => emitExternDeclAux decl cName | none => emitFnDecl decl (!modDecls.contains n) def emitMainFn : M Unit := do d ← getDecl `main; match d with | Decl.fdecl f xs t b => do unless (xs.size == 2 || xs.size == 1) (throw "invalid main function, incorrect arity when generating code"); env ← getEnv; let usesLeanAPI := usesModuleFrom env `Init.Lean; if usesLeanAPI then emitLn "void lean_initialize();" else emitLn "void lean_initialize_runtime_module();"; emitLn " #if defined(WIN32) || defined(_WIN32) #include <windows.h> #endif int main(int argc, char ** argv) { #if defined(WIN32) || defined(_WIN32) SetErrorMode(SEM_FAILCRITICALERRORS); #endif lean_object* in; lean_object* res;"; if usesLeanAPI then emitLn "lean_initialize();" else emitLn "lean_initialize_runtime_module();"; modName ← getModName; emitLn ("res = initialize_" ++ (modName.mangle "") ++ "(lean_io_mk_world());"); emitLns ["lean_io_mark_end_initialization();", "if (lean_io_result_is_ok(res)) {", "lean_dec_ref(res);", "lean_init_task_manager();"]; if xs.size == 2 then do { emitLns ["in = lean_box(0);", "int i = argc;", "while (i > 1) {", " lean_object* n;", " i--;", " n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);", " in = n;", "}"]; emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());") } else do { emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());") }; emitLn "}"; emitLns ["if (lean_io_result_is_ok(res)) {", " int ret = lean_unbox(lean_io_result_get_value(res));", " lean_dec_ref(res);", " return ret;", "} else {", " lean_io_result_show_error(res);", " lean_dec_ref(res);", " return 1;", "}"]; emitLn "}" | other => throw "function declaration expected" def hasMainFn : M Bool := do env ← getEnv; let decls := getDecls env; pure $ decls.any (fun d => d.name == `main) def emitMainFnIfNeeded : M Unit := whenM hasMainFn emitMainFn def emitFileHeader : M Unit := do env ← getEnv; modName ← getModName; emitLn "// Lean compiler output"; emitLn ("// Module: " ++ toString modName); emit "// Imports:"; env.imports.forM $ fun m => emit (" " ++ toString m); emitLn ""; emitLn "#include <lean/lean.h>"; emitLns [ "#if defined(__clang__)", "#pragma clang diagnostic ignored \"-Wunused-parameter\"", "#pragma clang diagnostic ignored \"-Wunused-label\"", "#elif defined(__GNUC__) && !defined(__CLANG__)", "#pragma GCC diagnostic ignored \"-Wunused-parameter\"", "#pragma GCC diagnostic ignored \"-Wunused-label\"", "#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"", "#endif", "#ifdef __cplusplus", "extern \"C\" {", "#endif" ] def emitFileFooter : M Unit := emitLns [ "#ifdef __cplusplus", "}", "#endif" ] def throwUnknownVar {α : Type} (x : VarId) : M α := throw ("unknown variable '" ++ toString x ++ "'") def getJPParams (j : JoinPointId) : M (Array Param) := do ctx ← read; match ctx.jpMap.find? j with | some ps => pure ps | none => throw "unknown join point" def declareVar (x : VarId) (t : IRType) : M Unit := do emit (toCType t); emit " "; emit x; emit "; " def declareParams (ps : Array Param) : M Unit := ps.forM $ fun p => declareVar p.x p.ty partial def declareVars : FnBody → Bool → M Bool | e@(FnBody.vdecl x t _ b), d => do ctx ← read; if isTailCallTo ctx.mainFn e then pure d else declareVar x t *> declareVars b true | FnBody.jdecl j xs _ b, d => declareParams xs *> declareVars b (d || xs.size > 0) | e, d => if e.isTerminal then pure d else declareVars e.body d def emitTag (x : VarId) (xType : IRType) : M Unit := do if xType.isObj then do emit "lean_obj_tag("; emit x; emit ")" else emit x def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) := if alts.size != 2 then none else match alts.get! 0 with | Alt.ctor c b => some (c.cidx, b, (alts.get! 1).body) | _ => none def emitIf (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")"; emitBody t; emitLn "else"; emitBody e def emitCase (emitBody : FnBody → M Unit) (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit := match isIf alts with | some (tag, t, e) => emitIf emitBody x xType tag t e | _ => do emit "switch ("; emitTag x xType; emitLn ") {"; let alts := ensureHasDefault alts; alts.forM $ fun alt => match alt with | Alt.ctor c b => emit "case " *> emit c.cidx *> emitLn ":" *> emitBody b | Alt.default b => emitLn "default: " *> emitBody b; emitLn "}" def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit $ if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n") else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n"); emit "(" *> emit x; when (n != 1) (emit ", " *> emit n); emitLn ");" def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do emit (if checkRef then "lean_dec" else "lean_dec_ref"); emit "("; emit x; when (n != 1) (do emit ", "; emit n); emitLn ");" def emitDel (x : VarId) : M Unit := do emit "lean_free_object("; emit x; emitLn ");" def emitSetTag (x : VarId) (i : Nat) : M Unit := do emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");" def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" def emitOffset (n : Nat) (offset : Nat) : M Unit := if n > 0 then do emit "sizeof(void*)*"; emit n; when (offset > 0) (emit " + " *> emit offset) else emit offset def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");" def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do match t with | IRType.float => emit "lean_ctor_set_float" | IRType.uint8 => emit "lean_ctor_set_uint8" | IRType.uint16 => emit "lean_ctor_set_uint16" | IRType.uint32 => emit "lean_ctor_set_uint32" | IRType.uint64 => emit "lean_ctor_set_uint64" | _ => throw "invalid instruction"; emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");" def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do ps ← getJPParams j; unless (xs.size == ps.size) (throw "invalid goto"); xs.size.forM $ fun i => do { let p := ps.get! i; let x := xs.get! i; emit p.x; emit " = "; emitArg x; emitLn ";" }; emit "goto "; emit j; emitLn ";" def emitLhs (z : VarId) : M Unit := do emit z; emit " = " def emitArgs (ys : Array Arg) : M Unit := ys.size.forM $ fun i => do when (i > 0) (emit ", "); emitArg (ys.get! i) def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit := if usize == 0 then emit ssize else if ssize == 0 then emit "sizeof(size_t)*" *> emit usize else emit "sizeof(size_t)*" *> emit usize *> emit " + " *> emit ssize def emitAllocCtor (c : CtorInfo) : M Unit := do emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", "; emitCtorScalarSize c.usize c.ssize; emitLn ");" def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit := ys.size.forM $ fun i => do emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg (ys.get! i); emitLn ");" def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do emitLhs z; if c.size == 0 && c.usize == 0 && c.ssize == 0 then do emit "lean_box("; emit c.cidx; emitLn ");" else do emitAllocCtor c; emitCtorSetArgs z ys def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do emit "if (lean_is_exclusive("; emit x; emitLn ")) {"; n.forM $ fun i => do { emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");" }; emit " "; emitLhs z; emit x; emitLn ";"; emitLn "} else {"; emit " lean_dec_ref("; emit x; emitLn ");"; emit " "; emitLhs z; emitLn "lean_box(0);"; emitLn "}" def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do emit "if (lean_is_scalar("; emit x; emitLn ")) {"; emit " "; emitLhs z; emitAllocCtor c; emitLn "} else {"; emit " "; emitLhs z; emit x; emitLn ";"; when updtHeader (do emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");"); emitLn "}"; emitCtorSetArgs z ys def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");" def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");" def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.float => emit "lean_ctor_get_float" | IRType.uint8 => emit "lean_ctor_get_uint8" | IRType.uint16 => emit "lean_ctor_get_uint16" | IRType.uint32 => emit "lean_ctor_get_uint32" | IRType.uint64 => emit "lean_ctor_get_uint64" | _ => throw "invalid instruction"; emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");" def toStringArgs (ys : Array Arg) : List String := ys.toList.map argToCString def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do emit f; emit "("; -- We must remove irrelevant arguments to extern calls. _ ← ys.size.foldM (fun i (first : Bool) => if (ps.get! i).ty.isIrrelevant then pure first else do unless first (emit ", "); emitArg (ys.get! i); pure false) true; emitLn ");"; pure () def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit := match getExternEntryFor extData `c with | some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys | some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";" | some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys | _ => throw ("failed to emit extern application '" ++ toString f ++ "'") def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do emitLhs z; decl ← getDecl f; match decl with | Decl.extern _ ps _ extData => emitExternCall f ps extData ys | _ => do emitCName f; when (ys.size > 0) (do emit "("; emitArgs ys; emit ")"); emitLn ";" def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do decl ← getDecl f; let arity := decl.params.size; emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");"; ys.size.forM $ fun i => do { let y := ys.get! i; emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");" } def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit := if ys.size > closureMaxArgs then do emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};"; emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }" else do emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");" def emitBoxFn (xType : IRType) : M Unit := match xType with | IRType.usize => emit "lean_box_usize" | IRType.uint32 => emit "lean_box_uint32" | IRType.uint64 => emit "lean_box_uint64" | IRType.float => emit "lean_box_float" | other => emit "lean_box" def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");" def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do emitLhs z; match t with | IRType.usize => emit "lean_unbox_usize" | IRType.uint32 => emit "lean_unbox_uint32" | IRType.uint64 => emit "lean_unbox_uint64" | IRType.float => emit "lean_unbox_float" | other => emit "lean_unbox"; emit "("; emit x; emitLn ");" def emitIsShared (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");" def emitIsTaggedPtr (z : VarId) (x : VarId) : M Unit := do emitLhs z; emit "!lean_is_scalar("; emit x; emitLn ");" def toHexDigit (c : Nat) : String := String.singleton c.digitChar def quoteString (s : String) : String := let q := "\""; let q := s.foldl (fun q c => q ++ if c == '\n' then "\\n" else if c == '\n' then "\\t" else if c == '\\' then "\\\\" else if c == '\"' then "\\\"" else if c.toNat <= 31 then "\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16) -- TODO(Leo): we should use `\unnnn` for escaping unicode characters. else String.singleton c) q; q ++ "\"" def emitNumLit (t : IRType) (v : Nat) : M Unit := if t.isObj then do if v < uint32Sz then emit "lean_unsigned_to_nat(" *> emit v *> emit "u)" else emit "lean_cstr_to_nat(\"" *> emit v *> emit "\")" else emit v def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit := emitLhs z *> match v with | LitVal.num v => emitNumLit t v *> emitLn ";" | LitVal.str v => do emit "lean_mk_string("; emit (quoteString v); emitLn ");" def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit := match v with | Expr.ctor c ys => emitCtor z c ys | Expr.reset n x => emitReset z n x | Expr.reuse x c u ys => emitReuse z x c u ys | Expr.proj i x => emitProj z i x | Expr.uproj i x => emitUProj z i x | Expr.sproj n o x => emitSProj z t n o x | Expr.fap c ys => emitFullApp z c ys | Expr.pap c ys => emitPartialApp z c ys | Expr.ap x ys => emitApp z x ys | Expr.box t x => emitBox z x t | Expr.unbox x => emitUnbox z t x | Expr.isShared x => emitIsShared z x | Expr.isTaggedPtr x => emitIsTaggedPtr z x | Expr.lit v => emitLit z t v def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do ctx ← read; match v, b with | Expr.fap f _, FnBody.ret (Arg.var y) => pure $ f == ctx.mainFn && x == y | _, _ => pure false def paramEqArg (p : Param) (x : Arg) : Bool := match x with | Arg.var x => p.x == x | _ => false /- Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments ``` p_0 := y_0, ... p_{n-1} := y_{n-1} ``` Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`. That is, we have ``` p_i := y_i, ... p_j := p_i, -- p_i was overwritten above ``` -/ def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool := let n := ps.size; n.any $ fun i => let p := ps.get! i; (i+1, n).anyI $ fun j => paramEqArg p (ys.get! j) def emitTailCall (v : Expr) : M Unit := match v with | Expr.fap _ ys => do ctx ← read; let ps := ctx.mainParams; unless (ps.size == ys.size) (throw "invalid tail call"); if overwriteParam ps ys then do { emitLn "{"; ps.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) $ do { emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";" } }; ps.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) (do emit p.x; emit " = _tmp_"; emit i; emitLn ";") }; emitLn "}" } else do { ys.size.forM $ fun i => do { let p := ps.get! i; let y := ys.get! i; unless (paramEqArg p y) (do emit p.x; emit " = "; emitArg y; emitLn ";") } }; emitLn "goto _start;" | _ => throw "bug at emitTailCall" partial def emitBlock (emitBody : FnBody → M Unit) : FnBody → M Unit | FnBody.jdecl j xs v b => emitBlock b | d@(FnBody.vdecl x t v b) => do ctx ← read; if isTailCallTo ctx.mainFn d then emitTailCall v else emitVDecl x t v *> emitBlock b | FnBody.inc x n c p b => unless p (emitInc x n c) *> emitBlock b | FnBody.dec x n c p b => unless p (emitDec x n c) *> emitBlock b | FnBody.del x b => emitDel x *> emitBlock b | FnBody.setTag x i b => emitSetTag x i *> emitBlock b | FnBody.set x i y b => emitSet x i y *> emitBlock b | FnBody.uset x i y b => emitUSet x i y *> emitBlock b | FnBody.sset x i o y t b => emitSSet x i o y t *> emitBlock b | FnBody.mdata _ b => emitBlock b | FnBody.ret x => emit "return " *> emitArg x *> emitLn ";" | FnBody.case _ x xType alts => emitCase emitBody x xType alts | FnBody.jmp j xs => emitJmp j xs | FnBody.unreachable => emitLn "lean_panic_unreachable();" partial def emitJPs (emitBody : FnBody → M Unit) : FnBody → M Unit | FnBody.jdecl j xs v b => do emit j; emitLn ":"; emitBody v; emitJPs b | e => unless e.isTerminal (emitJPs e.body) partial def emitFnBody : FnBody → M Unit | b => do emitLn "{"; declared ← declareVars b false; when declared (emitLn ""); emitBlock emitFnBody b; emitJPs emitFnBody b; emitLn "}" def emitDeclAux (d : Decl) : M Unit := do env ← getEnv; let (vMap, jpMap) := mkVarJPMaps d; adaptReader (fun (ctx : Context) => { ctx with jpMap := jpMap }) $ do unless (hasInitAttr env d.name) $ match d with | Decl.fdecl f xs t b => do baseName ← toCName f; emit (toCType t); emit " "; if xs.size > 0 then do { emit baseName; emit "("; if xs.size > closureMaxArgs && isBoxedName d.name then emit "lean_object** _args" else xs.size.forM $ fun i => do { when (i > 0) (emit ", "); let x := xs.get! i; emit (toCType x.ty); emit " "; emit x.x }; emit ")" } else do { emit ("_init_" ++ baseName ++ "()") }; emitLn " {"; when (xs.size > closureMaxArgs && isBoxedName d.name) $ xs.size.forM $ fun i => do { let x := xs.get! i; emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];" }; emitLn "_start:"; adaptReader (fun (ctx : Context) => { ctx with mainFn := f, mainParams := xs }) (emitFnBody b); emitLn "}" | _ => pure () def emitDecl (d : Decl) : M Unit := let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices catch (emitDeclAux d) (fun err => throw (err ++ "\ncompiling:\n" ++ toString d)) def emitFns : M Unit := do env ← getEnv; let decls := getDecls env; decls.reverse.forM emitDecl def emitMarkPersistent (d : Decl) (n : Name) : M Unit := when d.resultType.isObj $ do { emit "lean_mark_persistent("; emitCName n; emitLn ");" } def emitDeclInit (d : Decl) : M Unit := do env ← getEnv; let n := d.name; if isIOUnitInitFn env n then do { emit "res = "; emitCName n; emitLn "(lean_io_mk_world());"; emitLn "if (lean_io_result_is_error(res)) return res;"; emitLn "lean_dec_ref(res);" } else when (d.params.size == 0) $ match getInitFnNameFor env d.name with | some initFn => do { emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());"; emitLn "if (lean_io_result_is_error(res)) return res;"; emitCName n; emitLn " = lean_io_result_get_value(res);"; emitMarkPersistent d n; emitLn "lean_dec_ref(res);" } | _ => do { emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n } def emitInitFn : M Unit := do env ← getEnv; modName ← getModName; env.imports.forM $ fun imp => emitLn ("lean_object* initialize_" ++ imp.module.mangle "" ++ "(lean_object*);"); emitLns [ "static bool _G_initialized = false;", "lean_object* initialize_" ++ modName.mangle "" ++ "(lean_object* w) {", "lean_object * res;", "if (_G_initialized) return lean_mk_io_result(lean_box(0));", "_G_initialized = true;" ]; env.imports.forM $ fun imp => emitLns [ "res = initialize_" ++ imp.module.mangle "" ++ "(lean_io_mk_world());", "if (lean_io_result_is_error(res)) return res;", "lean_dec_ref(res);"]; let decls := getDecls env; decls.reverse.forM emitDeclInit; emitLns ["return lean_mk_io_result(lean_box(0));", "}"] def main : M Unit := do emitFileHeader; emitFnDecls; emitFns; emitInitFn; emitMainFnIfNeeded; emitFileFooter end EmitC @[export lean_ir_emit_c] def emitC (env : Environment) (modName : Name) : Except String String := match (EmitC.main { env := env, modName := modName }).run "" with | EStateM.Result.ok _ s => Except.ok s | EStateM.Result.error err _ => Except.error err end IR end Lean
975bfafa0fb185c312ed4f915c5d60ab66b08cb6
957a80ea22c5abb4f4670b250d55534d9db99108
/library/init/meta/async_tactic.lean
88c171a528bff2296fe6ea13905e8a9d38460e11
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
1,845
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ prelude import init.meta.tactic import init.meta.interactive namespace tactic private meta def report {α} (s : tactic_state) : option (unit → format) → α | (some fmt) := undefined_core $ format.to_string $ fmt () ++ format.line ++ to_fmt s | none := undefined_core "silent failure" private meta def run_or_fail {α} (s : tactic_state) (tac : tactic α) : α := match tac s with | (result.success a s) := a | (result.exception fmt _ s') := report s' fmt end meta def run_async {α : Type} (tac : tactic α) : tactic (task α) := do s ← read, return $ task.delay $ λ _, match tac s with | (result.success a s) := a | (result.exception fmt _ s') := report s' fmt end meta def prove_goal_async (tac : tactic unit) : tactic unit := do ctx ← local_context, revert_lst ctx, tgt ← target, tgt ← instantiate_mvars tgt, env ← get_env, tgt ← return $ env.unfold_untrusted_macros tgt, when tgt.has_meta_var (fail "goal contains metavariables"), params ← return tgt.collect_univ_params, lemma_name ← new_aux_decl_name, proof ← run_async (do goal_meta ← mk_meta_var tgt, set_goals [goal_meta], ctx.mmap' (λc, intro c.local_pp_name), tac, proof ← instantiate_mvars goal_meta, proof ← return $ env.unfold_untrusted_macros proof, when proof.has_meta_var $ fail "async proof failed: contains metavariables", return proof), add_decl $ declaration.thm lemma_name params tgt proof, exact (expr.const lemma_name (params.map level.param)) namespace interactive open interactive.types /-- Proves the first goal asynchronously as a separate lemma. -/ meta def async (tac : itactic) : tactic unit := prove_goal_async tac end interactive end tactic
004565831dc5324ee5b8192e38073a035e9617d1
b147e1312077cdcfea8e6756207b3fa538982e12
/data/finsupp.lean
110dc3d7f13f6d491fc3351afaa4401605f3007c
[ "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
28,347
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 Type of functions with finite support. Functions with finite support provide the basis for the following concrete instances: * ℕ →₀ α: Polynomials (where α is a ring) * (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names) * α →₀ ℕ: Multisets * α →₀ ℤ: Abelean groups freely generated by α * β →₀ α: Linear combinations over β where α is the scalar ring Most of the theory assumes that the range is a commutative monoid. This gives us the big sum operator as a powerful way to construct `finsupp` elements. A general advice is to not use α →₀ β directly, as the type class setup might not be fitting. The best is to define a copy and select the instances best suited. -/ import data.finset data.set.finite algebra.big_operators algebra.module open finset reserve infix ` →₀ `:25 universes u u₁ u₂ v v₁ v₂ v₃ w x y namespace finset variables {α : Type u} [decidable_eq α] protected def subtype (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.image $ λ⟨a, ha⟩, ⟨a, (mem_filter.1 ha).2⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] end finset /-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that `f x = 0` for all but finitely many `x`. -/ structure finsupp (α : Type u) (β : Type v) [has_zero β] := (support : finset α) (to_fun : α → β) (mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0) infix →₀ := finsupp namespace finsupp variables {α : Type u} {β : Type v} {γ : Type w} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} section basic variable [has_zero β] instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩ instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), by simp⟩⟩ @[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl @[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl instance : inhabited (α →₀ β) := ⟨0⟩ @[simp] lemma mem_support_iff (f : α →₀ β) : ∀a:α, a ∈ f.support ↔ f a ≠ 0 := f.mem_support_to_fun @[extensionality] lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g | ⟨s, f, hf⟩ ⟨t, g, hg⟩ h := begin have : f = g, { funext a, exact h a }, subst this, have : s = t, { simp [finset.ext, hf, hg] }, subst this end @[simp] lemma support_eq_empty [decidable_eq β] {f : α →₀ β} : f.support = ∅ ↔ f = 0 := ⟨assume h, ext $ assume a, by simp [finset.ext] at h; exact h a, by simp {contextual:=tt}⟩ instance [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) := assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ⟨assume ⟨h₁, h₂⟩, ext $ assume a, if h : a ∈ f.support then h₂ a h else have hf : f a = 0, by rwa [f.mem_support_iff, not_not] at h, have hg : g a = 0, by rwa [h₁, g.mem_support_iff, not_not] at h, by rw [hf, hg], by intro h; subst h; simp⟩ lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} := ⟨set.fintype_of_finset f.support f.mem_support_iff⟩ lemma support_subset_iff {s : set α} {f : α →₀ β} [decidable_eq α] : ↑f.support ⊆ s ↔ (∀a∉s, f a = 0) := by simp [set.subset_def]; exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _)) end basic section single variables [decidable_eq α] [decidable_eq β] [has_zero β] {a a' : α} {b : β} /-- `single a b` is the finitely supported function which has value `b` at `a` and zero otherwise. -/ def single (a : α) (b : β) : α →₀ β := ⟨(if b = 0 then ∅ else {a}), (λa', if a = a' then b else 0), begin intro a', by_cases hb : b = 0; by_cases a = a'; simp [h, hb], simp [ne.symm h, h] end⟩ lemma single_apply : (single a b : α →₀ β) a' = (if a = a' then b else 0) := rfl @[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := by simp [single_apply] @[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := by simp [single_apply, h] @[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 := ext $ assume a', begin by_cases h : a = a', { rw [h, single_eq_same, zero_apply] }, { rw [single_eq_of_ne h, zero_apply] } end lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} := if_neg hb lemma support_single_subset : (single a b).support ⊆ {a} := by by_cases b = 0; simp [support_single_ne_zero, h] end single section on_finset variables [decidable_eq β] [has_zero β] /-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`. The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise often better set representation is available. -/ def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β := ⟨s.filter (λa, f a ≠ 0), f, assume a, classical.by_cases (assume h : f a = 0, by simp [h]) (assume h : f a ≠ 0, by simp [h, hf])⟩ @[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} : (on_finset s f hf : α →₀ β) a = f a := rfl @[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} : (on_finset s f hf).support ⊆ s := by simp [on_finset] end on_finset section map_range variables [has_zero β₁] [has_zero β₂] [decidable_eq β₂] /-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is `map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/ def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ := on_finset g.support (f ∘ g) $ assume a, by rw [mem_support_iff, not_imp_not]; simp [hf] {contextual := tt} @[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} : map_range f hf g a = f (g a) := rfl lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} : (map_range f hf g).support ⊆ g.support := support_on_finset_subset end map_range section zip_with variables [has_zero β] [has_zero β₁] [has_zero β₂] [decidable_eq α] [decidable_eq β] /-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying `zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/ def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) := on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ assume a, classical.by_cases (assume h : g₁ a = 0, by simp [h]; rw [not_imp_not]; simp [hf] {contextual := tt}) (assume h : g₁ a ≠ 0, by simp [h]) @[simp] lemma zip_with_apply {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} : zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} : (zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := support_on_finset_subset end zip_with section erase variables [decidable_eq α] [decidable_eq β] def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β := ⟨f.support.erase a, (λa', if a' = a then 0 else f a'), assume a', by by_cases a' = a; simp [h]⟩ @[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} : (f.erase a).support = f.support.erase a := rfl @[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 := if_pos rfl @[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' := if_neg h end erase -- [to_additive finsupp.sum] for finsupp.prod doesn't work, the equation lemmas are not generated /-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/ def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.sum (λa, g a (f a)) /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive finsupp.sum] def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ := f.support.prod (λa, g a (f a)) attribute [to_additive finsupp.sum.equations._eqn_1] finsupp.prod.equations._eqn_1 @[to_additive finsupp.sum_map_range_index] lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] [decidable_eq β₂] {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ by simp [h0] {contextual := tt} @[to_additive finsupp.sum_zero_index] lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} : (0 : α →₀ β).prod h = 1 := by simp [finsupp.prod] section decidable variables [decidable_eq α] [decidable_eq β] section add_monoid variables [add_monoid β] @[to_additive finsupp.sum_single_index] lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := begin by_cases h : b = 0, { simp [h, prod_zero_index, h_zero], refl }, { simp [finsupp.prod, support_single_ne_zero h] } end instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩ @[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a := rfl lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support := support_zip_with @[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ := ext $ assume a', begin by_cases h : a = a', { rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] }, { rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] } end instance : add_monoid (α →₀ β) := { add_monoid . zero := 0, add := (+), add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _, zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _, add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ } lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f := ext $ λ a', if h : a = a' then by subst h; simp else by simp [ne.symm h, h] lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f := ext $ λ a', if h : a = a' then by subst h; simp else by simp [ne.symm h, h] protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (by simp [h0] {contextual := tt}) $ assume a s has ih f hf, suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this, begin apply ha, { simp }, { rw [← mem_support_iff _ a, hf], simp }, { apply ih _ _, simp [hf, has, finset.erase_insert] } end lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β) (h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) : p f := suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl, assume s, finset.induction_on s (by simp [h0] {contextual := tt}) $ assume a s has ih f hf, suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this, begin apply ha, { simp }, { rw [← mem_support_iff _ a, hf], simp }, { apply ih _ _, simp [hf, has, finset.erase_insert] } end end add_monoid instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) := { add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _, .. finsupp.add_monoid } instance [add_group β] : add_group (α →₀ β) := { neg := map_range (has_neg.neg) neg_zero, add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _, .. finsupp.add_monoid } @[to_additive finsupp.sum_neg_index] lemma prod_neg_index [add_group β] [comm_monoid γ] {g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 @[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl @[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl @[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f := finset.subset.antisymm support_map_range (calc support f = support (- (- f)) : by simp ... ⊆ support (- f) : support_map_range) instance [add_comm_group β] : add_comm_group (α →₀ β) := { add_comm := add_comm, ..finsupp.add_group } @[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := (finset.sum_hom (λf : α →₀ β, f a₂) rfl (assume a b, rfl)).symm lemma support_sum [has_zero β₁] [add_comm_monoid β] {f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} : (f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) := have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 → (∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, (f.mem_support_iff a).mp ha, ne⟩, by simpa [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply] using this @[simp] lemma sum_zero {γ : Type w} [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} : f.sum (λa b, (0 : γ)) = 0 := finset.sum_const_zero @[simp] lemma sum_add {γ : Type w} [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} {h₁ h₂ : α → β → γ} : f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ := finset.sum_add_distrib @[simp] lemma sum_neg {γ : Type w} [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β} {h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h := finset.sum_hom (@has_neg.neg γ _) neg_zero (assume a b, neg_add _ _) @[simp] lemma sum_single [add_comm_monoid β] {f : α →₀ β} : f.sum single = f := have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) = ({a} : finset α).sum (λa', ite (a' = a) (f a') 0), begin intro a, by_cases h : a ∈ f.support, { have : (finset.singleton a : finset α) ⊆ f.support, { simp [finset.subset_iff, *] at * }, refine (finset.sum_subset this _).symm, simp {contextual := tt} }, { transitivity (f.support.sum (λa, (0 : β))), { refine (finset.sum_congr rfl _), intros a' ha', have h: a' ≠ a, { assume eq, simp * at * }, simp * at * }, { simp * at * } } end, ext $ assume a, by simp [single_apply, this] @[to_additive finsupp.sum_add_index] lemma prod_add_index {γ : Type w} [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h, from (finset.prod_subset finset.subset_union_left $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h, from (finset.prod_subset finset.subset_union_right $ by simp [mem_support_iff, h_zero] {contextual := tt}).symm, calc (f + g).support.prod (λa, h a ((f + g) a)) = (f.support ∪ g.support).prod (λa, h a ((f + g) a)) : finset.prod_subset support_add $ by simp [mem_support_iff, h_zero] {contextual := tt} ... = (f.support ∪ g.support).prod (λa, h a (f a)) * (f.support ∪ g.support).prod (λa, h a (g a)) : by simp [h_add, finset.prod_mul_distrib] ... = _ : by rw [f_eq, g_eq] lemma sum_sub_index {γ : Type w} [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := have h_zero : ∀a, h a 0 = 0, from assume a, have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0, by simpa using this, have h_neg : ∀a b, h a (- b) = - h a b, from assume a b, have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b, by simpa [h_zero] using this, have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂, from assume a b₁ b₂, have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂), by simpa [h_neg] using this, calc (f - g).sum h = (f + - g).sum h : by simp ... = f.sum h + - g.sum h : by simp [sum_add_index, sum_neg_index, h_add, h_zero, h_neg] ... = _ : by simp @[to_additive finsupp.sum_finset_sum_index] lemma prod_finset_sum_index {γ : Type w} {ι : Type x} [add_comm_monoid β] [comm_monoid γ] [decidable_eq ι] {s : finset ι} {g : ι → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂): s.prod (λi, (g i).prod h) = (s.sum g).prod h := finset.induction_on s (by simp [prod_zero_index]) (by simp [prod_add_index, h_zero, h_add] {contextual := tt}) @[to_additive finsupp.sum_sum_index] lemma prod_sum_index {γ : Type w} [decidable_eq α₁] [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ] {f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂): (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm section map_domain variables [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] {v v₁ v₂ : α →₀ β} /-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β` is the finitely supported function whose value at `a : α₂` is the sum of `v x` over all `x` such that `f x = a`. -/ def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β := v.sum $ λa, single (f a) lemma map_domain_id : map_domain id v = v := sum_single lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} : map_domain (g ∘ f) v = map_domain g (map_domain f v) := by simp [map_domain, sum_sum_index, sum_single_index] lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b := sum_single_index (by simp) lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) := sum_zero_index lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) : v.map_domain f = v.map_domain g := finset.sum_congr rfl $ by simp [*] at * {contextual := tt} lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ := sum_add_index (by simp) (by simp) lemma map_domain_finset_sum {ι : Type x} [decidable_eq ι] {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} : map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) := by refine (sum_finset_sum_index _ _).symm; simp lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} : map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) := by refine (sum_finset_sum_index _ _).symm; simp lemma map_domain_support {f : α → α₂} {s : α →₀ β} : (s.map_domain f).support ⊆ s.support.image f := finset.subset.trans support_sum $ finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $ by rw [finset.bind_singleton]; exact subset.refl _ @[to_additive finsupp.sum_map_domain_index] lemma prod_map_domain_index {γ : Type w} [comm_monoid γ] {f : α → α₂} {s : α →₀ β} {h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (s.map_domain f).prod h = s.prod (λa b, h (f a) b) := by simp [map_domain, prod_sum_index, h_zero, h_add, prod_single_index] end map_domain /-- The product of `f g : α →₀ β` is the finitely supported function whose value at `a` is the sum of `f x * g y` over all pairs `x, y` such that `x + y = a`. (Think of the product of multivariate polynomials where `α` is the monoid of monomial exponents.) -/ instance [has_add α] [semiring β] : has_mul (α →₀ β) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl /-- The unit of the multiplication is `single 0 1`, i.e. the function that is 1 at 0 and zero elsewhere. -/ instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) := ⟨single 0 1⟩ lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl section filter -- TODO: remove filter? build upon subtype_domain? section has_zero variables [has_zero β] {p : α → Prop} [decidable_pred p] {f : α →₀ β} /-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/ def filter (p : α → Prop) [decidable_pred p] (f : α →₀ β) : α →₀ β := on_finset f.support (λa, if p a then f a else 0) (assume a, by by_cases (p a); simp [h]) @[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h @[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 := if_neg h @[simp] lemma support_filter : (f.filter p).support = f.support.filter p := finset.ext.mpr $ assume a, by by_cases p a; simp * end has_zero lemma filter_pos_add_filter_neg [add_monoid β] {f : α →₀ β} {p : α → Prop} [decidable_pred p] [decidable_pred (λa, ¬ p a)] : f.filter p + f.filter (λa, ¬ p a) = f := finsupp.ext $ assume a, by by_cases p a; simp * end filter section subtype_domain variables {α' : Type u₁} {δ : Type y} [has_zero δ] {p : α → Prop} [decidable_pred p] section zero variables [has_zero β] {v v' : α' →₀ β} /-- `subtype_domain p f` is the restriction of the finitely supported function `f` to the subtype `p`. -/ def subtype_domain (p : α → Prop) [decidable_pred p] (f : α →₀ β) : (subtype p →₀ β) := ⟨f.support.subtype p, f ∘ subtype.val, by simp⟩ @[simp] lemma support_subtype_domain {f : α →₀ β} : (subtype_domain p f).support = f.support.subtype p := rfl @[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} : (subtype_domain p v) a = v (a.val) := rfl @[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 := rfl @[to_additive finsupp.sum_subtype_domain_index] lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β} {h : α → β → γ} (hp : ∀x∈v.support, p x) : (v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h := prod_bij (λp _, p.val) (by simp) (by simp) (assume ⟨a₀, ha₀⟩ ⟨a₁, ha₁⟩, by simp) (begin simp; exact assume b hb, ⟨b, hp _ (by simp [hb]), by simp [hb]⟩ end) end zero section monoid variables [add_monoid β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_add {v v' : α →₀ β} : (v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p := ext $ by simp end monoid section comm_monoid variables [add_comm_monoid β] lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) := eq.symm (finset.sum_hom _ subtype_domain_zero $ assume v v', subtype_domain_add) lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} : (s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) := subtype_domain_sum end comm_monoid section group variables [add_group β] {v v' : α' →₀ β} @[simp] lemma subtype_domain_neg {v : α →₀ β} : (- v).subtype_domain p = - v.subtype_domain p := ext $ by simp @[simp] lemma subtype_domain_sub {v v' : α →₀ β} : (v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p := ext $ by simp end group end subtype_domain section variables [add_monoid α] [semiring β] -- TODO: the simplifier unfolds 0 in the instance proof! private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp [mul_def, sum_zero_index] private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp [mul_def, sum_zero_index] private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c := by simp [mul_def, sum_add_index, mul_add] private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c := by simp [mul_def, sum_add_index, add_mul] def to_semiring : semiring (α →₀ β) := { one := 1, mul := (*), one_mul := assume f, by simp [mul_def, one_def, sum_single_index], mul_one := assume f, by simp [mul_def, one_def, sum_single_index], zero_mul := zero_mul, mul_zero := mul_zero, mul_assoc := assume f g h, by simp [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index, add_mul, mul_add, mul_assoc], left_distrib := left_distrib, right_distrib := right_distrib, .. finsupp.add_comm_monoid } end local attribute [instance] to_semiring def to_comm_semiring [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) := { mul_comm := assume f g, begin simp [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp end, .. finsupp.to_semiring } local attribute [instance] to_comm_semiring def to_ring [add_monoid α] [ring β] : ring (α →₀ β) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. finsupp.to_semiring } def to_comm_ring [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) := { mul_comm := mul_comm, .. finsupp.to_ring} lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}: single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := by simp [mul_def, sum_single_index] lemma prod_single {ι : Type x} [decidable_eq ι] [add_comm_monoid α] [comm_semiring β] {s : finset ι} {a : ι → α} {b : ι → β} : s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) := finset.induction_on s (by simp [one_def]) (by simp [single_mul_single] {contextual := tt}) def to_has_scalar [semiring β] : has_scalar β (α →₀ β) := ⟨λa v, v.map_range ((*) a) (mul_zero a)⟩ local attribute [instance] to_has_scalar @[simp] lemma smul_apply [semiring β] {a : α} {b : β} {v : α →₀ β} : (b • v) a = b * v a := rfl /- should this be stronger? [module γ β] → module γ (α →₀ β) -/ def to_module [ring β] : module β (α →₀ β) := { smul := (•), smul_add := assume a x y, finsupp.ext $ by simp [mul_add], add_smul := assume a x y, finsupp.ext $ by simp [add_mul], one_smul := assume x, finsupp.ext $ by simp, mul_smul := assume r s x, finsupp.ext $ by simp [mul_assoc], .. finsupp.add_comm_group } lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ} (h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) := finsupp.sum_map_range_index h0 end decidable section variables [semiring β] [semiring γ] lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} : (s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) := by simp [finsupp.sum, finset.sum_mul] lemma mul_sum [semiring β] [semiring γ] (b : γ) (s : α →₀ β) {f : α → β → γ} : b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) := by simp [finsupp.sum, finset.mul_sum] end end finsupp
eb6cfd820a73fef1e7ec3e6a736fcdf2f81ad2e4
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/topology/path_connected.lean
080b0418a376398132d60c1e8624c2d10a3abd41
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
34,440
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.instances.real import topology.algebra.ordered.proj_Icc /-! # Path connectedness ## Main definitions In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space. * `path (x y : X)` is the type of paths from `x` to `y`, i.e., continuous maps from `I` to `X` mapping `0` to `x` and `1` to `y`. * `path.map` is the image of a path under a continuous map. * `joined (x y : X)` means there is a path between `x` and `y`. * `joined.some_path (h : joined x y)` selects some path between two points `x` and `y`. * `path_component (x : X)` is the set of points joined to `x`. * `path_connected_space X` is a predicate class asserting that `X` is non-empty and every two points of `X` are joined. Then there are corresponding relative notions for `F : set X`. * `joined_in F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`. * `joined_in.some_path (h : joined_in F x y)` selects a path from `x` to `y` inside `F`. * `path_component_in F (x : X)` is the set of points joined to `x` in `F`. * `is_path_connected F` asserts that `F` is non-empty and every two points of `F` are joined in `F`. * `loc_path_connected_space X` is a predicate class asserting that `X` is locally path-connected: each point has a basis of path-connected neighborhoods (we do *not* ask these to be open). ## Main theorems * `joined` and `joined_in F` are transitive relations. One can link the absolute and relative version in two directions, using `(univ : set X)` or the subtype `↥F`. * `path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X)` * `is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space ↥F` For locally path connected spaces, we have * `path_connected_space_iff_connected_space : path_connected_space X ↔ connected_space X` * `is_connected_iff_is_path_connected (U_op : is_open U) : is_path_connected U ↔ is_connected U` ## Implementation notes By default, all paths have `I` as their source and `X` as their target, but there is an operation `set.Icc_extend` that will extend any continuous map `γ : I → X` into a continuous map `Icc_extend zero_le_one γ : ℝ → X` that is constant before `0` and after `1`. This is used to define `path.extend` that turns `γ : path x y` into a continuous map `γ.extend : ℝ → X` whose restriction to `I` is the original `γ`, and is equal to `x` on `(-∞, 0]` and to `y` on `[1, +∞)`. -/ noncomputable theory open_locale classical topological_space filter open filter set function variables {X : Type*} [topological_space X] {x y z : X} {ι : Type*} /-! ### The unit interval -/ local notation `I` := Icc (0 : ℝ) 1 lemma Icc_zero_one_symm {t : ℝ} : t ∈ I ↔ 1 - t ∈ I := begin rw [mem_Icc, mem_Icc], split ; intro ; split ; linarith end instance I_has_zero : has_zero I := ⟨⟨0, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_zero : ((0 : I) : ℝ) = 0 := rfl instance I_has_one : has_one I := ⟨⟨1, by split ; norm_num⟩⟩ @[simp, norm_cast] lemma coe_I_one : ((1 : I) : ℝ) = 1 := rfl /-- Unit interval central symmetry. -/ def I_symm : I → I := λ t, ⟨1 - t.val, Icc_zero_one_symm.mp t.property⟩ local notation `σ` := I_symm @[simp] lemma I_symm_zero : σ 0 = 1 := subtype.ext $ by simp [I_symm] @[simp] lemma I_symm_one : σ 1 = 0 := subtype.ext $ by simp [I_symm] @[continuity] lemma continuous_I_symm : continuous σ := by continuity! instance : connected_space I := subtype.connected_space ⟨nonempty_Icc.mpr zero_le_one, is_preconnected_Icc⟩ instance : compact_space I := compact_iff_compact_space.1 compact_Icc /-! ### Paths -/ /-- Continuous path connecting two points `x` and `y` in a topological space -/ @[nolint has_inhabited_instance] structure path (x y : X) := (to_fun : I → X) (continuous' : continuous to_fun) (source' : to_fun 0 = x) (target' : to_fun 1 = y) instance : has_coe_to_fun (path x y) := ⟨_, path.to_fun⟩ @[ext] protected lemma path.ext {X : Type*} [topological_space X] {x y : X} : ∀ {γ₁ γ₂ : path x y}, (γ₁ : I → X) = γ₂ → γ₁ = γ₂ | ⟨x, h11, h12, h13⟩ ⟨.(x), h21, h22, h23⟩ rfl := rfl namespace path @[simp] lemma coe_mk (f : I → X) (h₁ h₂ h₃) : ⇑(mk f h₁ h₂ h₃ : path x y) = f := rfl variable (γ : path x y) @[continuity] protected lemma continuous : continuous γ := γ.continuous' @[simp] protected lemma source : γ 0 = x := γ.source' @[simp] protected lemma target : γ 1 = y := γ.target' /-- Any function `φ : Π (a : α), path (x a) (y a)` can be seen as a function `α × I → X`. -/ instance has_uncurry_path {X α : Type*} [topological_space X] {x y : α → X} : has_uncurry (Π (a : α), path (x a) (y a)) (α × I) X := ⟨λ φ p, φ p.1 p.2⟩ /-- The constant path from a point to itself -/ @[refl] def refl (x : X) : path x x := { to_fun := λ t, x, continuous' := continuous_const, source' := rfl, target' := rfl } @[simp] lemma refl_range {X : Type*} [topological_space X] {a : X} : range (path.refl a) = {a} := by simp [path.refl, has_coe_to_fun.coe, coe_fn] /-- The reverse of a path from `x` to `y`, as a path from `y` to `x` -/ @[symm] def symm (γ : path x y) : path y x := { to_fun := γ ∘ σ, continuous' := by continuity, source' := by simpa [-path.target] using γ.target, target' := by simpa [-path.source] using γ.source } @[simp] lemma refl_symm {X : Type*} [topological_space X] {a : X} : (path.refl a).symm = path.refl a := by { ext, refl } @[simp] lemma symm_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.symm = range γ := begin ext x, simp only [ mem_range, path.symm, has_coe_to_fun.coe, coe_fn, I_symm, set_coe.exists, comp_app, subtype.coe_mk, subtype.val_eq_coe ], split; rintros ⟨y, hy, hxy⟩; refine ⟨1-y, Icc_zero_one_symm.mp hy, _⟩; convert hxy, exact sub_sub_cancel _ _ end /-- A continuous map extending a path to `ℝ`, constant before `0` and after `1`. -/ def extend : ℝ → X := Icc_extend zero_le_one γ lemma continuous_extend : continuous γ.extend := γ.continuous.Icc_extend @[simp] lemma extend_zero : γ.extend 0 = x := (Icc_extend_left _ _).trans γ.source @[simp] lemma extend_one : γ.extend 1 = y := (Icc_extend_right _ _).trans γ.target @[simp] lemma extend_extends {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ∈ (Icc 0 1 : set ℝ)) : γ.extend t = γ ⟨t, ht⟩ := Icc_extend_of_mem _ γ ht @[simp] lemma extend_extends' {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : (Icc 0 1 : set ℝ)) : γ.extend t = γ t := Icc_extend_coe _ γ t @[simp] lemma extend_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.extend = range γ := Icc_extend_range _ γ lemma extend_of_le_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ≤ 0) : γ.extend t = a := (Icc_extend_of_le_left _ _ ht).trans γ.source lemma extend_of_one_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : 1 ≤ t) : γ.extend t = b := (Icc_extend_of_right_le _ _ ht).trans γ.target @[simp] lemma refl_extend {X : Type*} [topological_space X] {a : X} : (path.refl a).extend = λ _, a := rfl /-- The path obtained from a map defined on `ℝ` by restriction to the unit interval. -/ def of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : path x y := { to_fun := f ∘ coe, continuous' := hf.comp_continuous continuous_subtype_coe subtype.prop, source' := h₀, target' := h₁ } lemma of_line_mem {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : ∀ t, of_line hf h₀ h₁ t ∈ f '' I := λ ⟨t, t_in⟩, ⟨t, t_in, rfl⟩ local attribute [simp] Iic_def /-- Concatenation of two paths from `x` to `y` and from `y` to `z`, putting the first path on `[0, 1/2]` and the second one on `[1/2, 1]`. -/ @[trans] def trans (γ : path x y) (γ' : path y z) : path x z := { to_fun := (λ t : ℝ, if t ≤ 1/2 then γ.extend (2*t) else γ'.extend (2*t-1)) ∘ coe, continuous' := begin apply (continuous_if _ _ _).comp continuous_subtype_coe, { norm_num }, -- TODO: the following are provable by `continuity` but it is too slow { exact γ.continuous_extend.comp (continuous_const.mul continuous_id) }, { exact γ'.continuous_extend.comp ((continuous_const.mul continuous_id).sub continuous_const) } end, source' := by norm_num, target' := by norm_num } @[simp] lemma refl_trans_refl {X : Type*} [topological_space X] {a : X} : (path.refl a).trans (path.refl a) = path.refl a := begin ext, simp only [path.trans, if_t_t, one_div, path.refl_extend], refl end lemma trans_range {X : Type*} [topological_space X] {a b c : X} (γ₁ : path a b) (γ₂ : path b c) : range (γ₁.trans γ₂) = range γ₁ ∪ range γ₂ := begin rw path.trans, apply eq_of_subset_of_subset, { rintros x ⟨⟨t, ht0, ht1⟩, hxt⟩, by_cases h : t ≤ 1/2, { left, use [2*t, ⟨by linarith, by linarith⟩], rw ← γ₁.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_true] at hxt, exact hxt }, { right, use [2*t-1, ⟨by linarith, by linarith⟩], rw ← γ₂.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_false] at hxt, exact hxt } }, { rintros x (⟨⟨t, ht0, ht1⟩, hxt⟩ | ⟨⟨t, ht0, ht1⟩, hxt⟩), { use ⟨t/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, have : t/2 ≤ 1/2 := by linarith, simp only [this, comp_app, if_true], ring, rwa γ₁.extend_extends }, { by_cases h : t = 0, { use ⟨1/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, simp only [h, comp_app, if_true, le_refl, mul_one_div_cancel (@two_ne_zero ℝ _ _)], rw γ₁.extend_one, rwa [← γ₂.extend_extends, h, γ₂.extend_zero] at hxt }, { use ⟨(t+1)/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, change t ≠ 0 at h, have ht0 := lt_of_le_of_ne ht0 h.symm, have : ¬ (t+1)/2 ≤ 1/2 := by {rw not_le, linarith}, simp only [comp_app, if_false, this], ring, rwa γ₂.extend_extends } } } end /-- Image of a path from `x` to `y` by a continuous map -/ def map (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : path (f x) (f y) := { to_fun := f ∘ γ, continuous' := by continuity, source' := by simp, target' := by simp } @[simp] lemma map_coe (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.map h : I → Y) = f ∘ γ := by { ext t, refl } /-- Casting a path from `x` to `y` to a path from `x'` to `y'` when `x' = x` and `y' = y` -/ def cast (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : path x' y' := { to_fun := γ, continuous' := γ.continuous, source' := by simp [hx], target' := by simp [hy] } @[simp] lemma symm_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ : X} (γ : path a₂ b₂) (ha : a₁ = a₂) (hb : b₁ = b₂) : (γ.cast ha hb).symm = (γ.symm).cast hb ha := rfl @[simp] lemma trans_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ c₁ c₂ : X} (γ : path a₂ b₂) (γ' : path b₂ c₂) (ha : a₁ = a₂) (hb : b₁ = b₂) (hc : c₁ = c₂) : (γ.cast ha hb).trans (γ'.cast hb hc) = (γ.trans γ').cast ha hc := rfl @[simp] lemma cast_coe (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : (γ.cast hx hy : I → X) = γ := rfl lemma symm_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).symm) := h.comp (continuous_id.prod_map continuous_I_symm) lemma continuous_uncurry_extend_of_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).extend) := h.comp (continuous_id.prod_map continuous_proj_Icc) lemma trans_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b c : ι → X} (γ₁ : Π (t : ι), path (a t) (b t)) (h₁ : continuous ↿γ₁) (γ₂ : Π (t : ι), path (b t) (c t)) (h₂ : continuous ↿γ₂) : continuous ↿(λ t, (γ₁ t).trans (γ₂ t)) := begin have h₁' := path.continuous_uncurry_extend_of_continuous_family γ₁ h₁, have h₂' := path.continuous_uncurry_extend_of_continuous_family γ₂ h₂, simp [has_uncurry.uncurry, has_coe_to_fun.coe, coe_fn, path.trans], apply continuous_if _ _ _, { rintros st hst, have := frontier_le_subset_eq (continuous_subtype_coe.comp continuous_snd) continuous_const hst, simp only [mem_set_of_eq, comp_app] at this, simp [this, mul_inv_cancel (@two_ne_zero ℝ _ _)] }, { change continuous ((λ p : ι × ℝ, (γ₁ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x : I → ℝ))), exact h₁'.comp (continuous_id.prod_map $ continuous_const.mul continuous_subtype_coe) }, { change continuous ((λ p : ι × ℝ, (γ₂ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x - 1 : I → ℝ))), exact h₂'.comp (continuous_id.prod_map $ (continuous_const.mul continuous_subtype_coe).sub continuous_const) }, end /-! #### Truncating a path -/ /-- `γ.truncate t₀ t₁` is the path which follows the path `γ` on the time interval `[t₀, t₁]` and stays still otherwise. -/ def truncate {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t₀ t₁ : ℝ) : path (γ.extend $ min t₀ t₁) (γ.extend t₁) := { to_fun := λ s, γ.extend (min (max s t₀) t₁), continuous' := γ.continuous_extend.comp ((continuous_subtype_coe.max continuous_const).min continuous_const), source' := begin unfold min max, norm_cast, split_ifs with h₁ h₂ h₃ h₄, { simp [γ.extend_of_le_zero h₁] }, { congr, linarith }, { have h₄ : t₁ ≤ 0 := le_of_lt (by simpa using h₂), simp [γ.extend_of_le_zero h₄, γ.extend_of_le_zero h₁] }, all_goals { refl } end, target' := begin unfold min max, norm_cast, split_ifs with h₁ h₂ h₃, { simp [γ.extend_of_one_le h₂] }, { refl }, { have h₄ : 1 ≤ t₀ := le_of_lt (by simpa using h₁), simp [γ.extend_of_one_le h₄, γ.extend_of_one_le (h₄.trans h₃)] }, { refl } end } /-- `γ.truncate_of_le t₀ t₁ h`, where `h : t₀ ≤ t₁` is `γ.truncate t₀ t₁` casted as a path from `γ.extend t₀` to `γ.extend t₁`. -/ def truncate_of_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} (h : t₀ ≤ t₁) : path (γ.extend t₀) (γ.extend t₁) := (γ.truncate t₀ t₁).cast (by rw min_eq_left h) rfl lemma truncate_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} : range (γ.truncate t₀ t₁) ⊆ range γ := begin rw ← γ.extend_range, simp only [range_subset_iff, set_coe.exists, set_coe.forall], intros x hx, simp only [has_coe_to_fun.coe, coe_fn, path.truncate, mem_range_self] end /-- For a path `γ`, `γ.truncate` gives a "continuous family of paths", by which we mean the uncurried function which maps `(t₀, t₁, s)` to `γ.truncate t₀ t₁ s` is continuous. -/ lemma truncate_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) : continuous (λ x, γ.truncate x.1 x.2.1 x.2.2 : ℝ × ℝ × I → X) := γ.continuous_extend.comp (((continuous_subtype_coe.comp (continuous_snd.comp continuous_snd)).max continuous_fst).min (continuous_fst.comp continuous_snd)) /- TODO : When `continuity` gets quicker, change the proof back to : `begin` `simp only [has_coe_to_fun.coe, coe_fn, path.truncate],` `continuity,` `exact continuous_subtype_coe` `end` -/ lemma truncate_const_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : continuous ↿(γ.truncate t) := have key : continuous (λ x, (t, x) : ℝ × I → ℝ × ℝ × I) := continuous_const.prod_mk continuous_id, by convert γ.truncate_continuous_family.comp key @[simp] lemma truncate_self {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : γ.truncate t t = (path.refl $ γ.extend t).cast (by rw min_self) rfl := begin ext x, rw cast_coe, simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min, max], split_ifs with h₁ h₂; congr, linarith end @[simp] lemma truncate_zero_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 0 = (path.refl a).cast (by rw [min_self, γ.extend_zero]) γ.extend_zero := by convert γ.truncate_self 0; exact γ.extend_zero.symm @[simp] lemma truncate_one_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 1 1 = (path.refl b).cast (by rw [min_self, γ.extend_one]) γ.extend_one := by convert γ.truncate_self 1; exact γ.extend_one.symm @[simp] lemma truncate_zero_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 1 = γ.cast (by simp [zero_le_one, extend_zero]) (by simp) := begin ext x, rw cast_coe, have : ↑x ∈ (Icc 0 1 : set ℝ) := x.2, rw [truncate, coe_mk, max_eq_left this.1, min_eq_left this.2, extend_extends'] end end path /-! ### Being joined by a path -/ /-- The relation "being joined by a path". This is an equivalence relation. -/ def joined (x y : X) : Prop := nonempty (path x y) @[refl] lemma joined.refl (x : X) : joined x x := ⟨path.refl x⟩ /-- When two points are joined, choose some path from `x` to `y`. -/ def joined.some_path (h : joined x y) : path x y := nonempty.some h @[symm] lemma joined.symm {x y : X} (h : joined x y) : joined y x := ⟨h.some_path.symm⟩ @[trans] lemma joined.trans {x y z : X} (hxy : joined x y) (hyz : joined y z) : joined x z := ⟨hxy.some_path.trans hyz.some_path⟩ variables (X) /-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/ def path_setoid : setoid X := { r := joined, iseqv := mk_equivalence _ joined.refl (λ x y, joined.symm) (λ x y z, joined.trans) } /-- The quotient type of points of a topological space modulo being joined by a continuous path. -/ def zeroth_homotopy := quotient (path_setoid X) instance : inhabited (zeroth_homotopy ℝ) := ⟨@quotient.mk ℝ (path_setoid ℝ) 0⟩ variables {X} /-! ### Being joined by a path inside a set -/ /-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not reflexive for points that do not belong to `F`. -/ def joined_in (F : set X) (x y : X) : Prop := ∃ γ : path x y, ∀ t, γ t ∈ F variables {F : set X} lemma joined_in.mem (h : joined_in F x y) : x ∈ F ∧ y ∈ F := begin rcases h with ⟨γ, γ_in⟩, have : γ 0 ∈ F ∧ γ 1 ∈ F, by { split; apply γ_in }, simpa using this end lemma joined_in.source_mem (h : joined_in F x y) : x ∈ F := h.mem.1 lemma joined_in.target_mem (h : joined_in F x y) : y ∈ F := h.mem.2 /-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/ def joined_in.some_path (h : joined_in F x y) : path x y := classical.some h lemma joined_in.some_path_mem (h : joined_in F x y) (t : I) : h.some_path t ∈ F := classical.some_spec h t /-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/ lemma joined_in.joined_subtype (h : joined_in F x y) : joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) := ⟨{ to_fun := λ t, ⟨h.some_path t, h.some_path_mem t⟩, continuous' := by continuity, source' := by simp, target' := by simp }⟩ lemma joined_in.of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) (hF : f '' I ⊆ F) : joined_in F x y := ⟨path.of_line hf h₀ h₁, λ t, hF $ path.of_line_mem hf h₀ h₁ t⟩ lemma joined_in.joined (h : joined_in F x y) : joined x y := ⟨h.some_path⟩ lemma joined_in_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) : joined_in F x y ↔ joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) := ⟨λ h, h.joined_subtype, λ h, ⟨h.some_path.map continuous_subtype_coe, by simp⟩⟩ @[simp] lemma joined_in_univ : joined_in univ x y ↔ joined x y := by simp [joined_in, joined, exists_true_iff_nonempty] lemma joined_in.mono {U V : set X} (h : joined_in U x y) (hUV : U ⊆ V) : joined_in V x y := ⟨h.some_path, λ t, hUV (h.some_path_mem t)⟩ lemma joined_in.refl (h : x ∈ F) : joined_in F x x := ⟨path.refl x, λ t, h⟩ @[symm] lemma joined_in.symm (h : joined_in F x y) : joined_in F y x := begin cases h.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact h.symm end lemma joined_in.trans (hxy : joined_in F x y) (hyz : joined_in F y z) : joined_in F x z := begin cases hxy.mem with hx hy, cases hyz.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact hxy.trans hyz end /-! ### Path component -/ /-- The path component of `x` is the set of points that can be joined to `x`. -/ def path_component (x : X) := {y | joined x y} @[simp] lemma mem_path_component_self (x : X) : x ∈ path_component x := joined.refl x @[simp] lemma path_component.nonempty (x : X) : (path_component x).nonempty := ⟨x, mem_path_component_self x⟩ lemma mem_path_component_of_mem (h : x ∈ path_component y) : y ∈ path_component x := joined.symm h lemma path_component_symm : x ∈ path_component y ↔ y ∈ path_component x := ⟨λ h, mem_path_component_of_mem h, λ h, mem_path_component_of_mem h⟩ lemma path_component_congr (h : x ∈ path_component y) : path_component x = path_component y := begin ext z, split, { intro h', rw path_component_symm, exact (h.trans h').symm }, { intro h', rw path_component_symm at h' ⊢, exact h'.trans h }, end lemma path_component_subset_component (x : X) : path_component x ⊆ connected_component x := λ y h, subset_connected_component (is_connected_range h.some_path.continuous).2 ⟨0, by simp⟩ ⟨1, by simp⟩ /-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/ def path_component_in (x : X) (F : set X) := {y | joined_in F x y} @[simp] lemma path_component_in_univ (x : X) : path_component_in x univ = path_component x := by simp [path_component_in, path_component, joined_in, joined, exists_true_iff_nonempty] lemma joined.mem_path_component (hyz : joined y z) (hxy : y ∈ path_component x) : z ∈ path_component x := hxy.trans hyz /-! ### Path connected sets -/ /-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/ def is_path_connected (F : set X) : Prop := ∃ x ∈ F, ∀ {y}, y ∈ F → joined_in F x y lemma is_path_connected_iff_eq : is_path_connected F ↔ ∃ x ∈ F, path_component_in x F = F := begin split ; rintros ⟨x, x_in, h⟩ ; use [x, x_in], { ext y, exact ⟨λ hy, hy.mem.2, h⟩ }, { intros y y_in, rwa ← h at y_in }, end lemma is_path_connected.joined_in (h : is_path_connected F) : ∀ x y ∈ F, joined_in F x y := λ x y x_in y_in, let ⟨b, b_in, hb⟩ := h in (hb x_in).symm.trans (hb y_in) lemma is_path_connected_iff : is_path_connected F ↔ F.nonempty ∧ ∀ x y ∈ F, joined_in F x y := ⟨λ h, ⟨let ⟨b, b_in, hb⟩ := h in ⟨b, b_in⟩, h.joined_in⟩, λ ⟨⟨b, b_in⟩, h⟩, ⟨b, b_in, λ x x_in, h b x b_in x_in⟩⟩ lemma is_path_connected.image {Y : Type*} [topological_space Y] (hF : is_path_connected F) {f : X → Y} (hf : continuous f) : is_path_connected (f '' F) := begin rcases hF with ⟨x, x_in, hx⟩, use [f x, mem_image_of_mem f x_in], rintros _ ⟨y, y_in, rfl⟩, exact ⟨(hx y_in).some_path.map hf, λ t, ⟨_, (hx y_in).some_path_mem t, rfl⟩⟩, end lemma is_path_connected.mem_path_component (h : is_path_connected F) (x_in : x ∈ F) (y_in : y ∈ F) : y ∈ path_component x := (h.joined_in x y x_in y_in).joined lemma is_path_connected.subset_path_component (h : is_path_connected F) (x_in : x ∈ F) : F ⊆ path_component x := λ y y_in, h.mem_path_component x_in y_in lemma is_path_connected.union {U V : set X} (hU : is_path_connected U) (hV : is_path_connected V) (hUV : (U ∩ V).nonempty) : is_path_connected (U ∪ V) := begin rcases hUV with ⟨x, xU, xV⟩, use [x, or.inl xU], rintros y (yU | yV), { exact (hU.joined_in x y xU yU).mono (subset_union_left U V) }, { exact (hV.joined_in x y xV yV).mono (subset_union_right U V) }, end /-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller ambient type `U` (when `U` contains `W`). -/ lemma is_path_connected.preimage_coe {U W : set X} (hW : is_path_connected W) (hWU : W ⊆ U) : is_path_connected ((coe : U → X) ⁻¹' W) := begin rcases hW with ⟨x, x_in, hx⟩, use [⟨x, hWU x_in⟩, by simp [x_in]], rintros ⟨y, hyU⟩ hyW, exact ⟨(hx hyW).joined_subtype.some_path.map (continuous_inclusion hWU), by simp⟩ end lemma is_path_connected.exists_path_through_family {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ γ : path (p 0) (p n), (range γ ⊆ s) ∧ (∀ i, p i ∈ range γ) := begin let p' : ℕ → X := λ k, if h : k < n+1 then p ⟨k, h⟩ else p ⟨0, n.zero_lt_succ⟩, obtain ⟨γ, hγ⟩ : ∃ (γ : path (p' 0) (p' n)), (∀ i ≤ n, p' i ∈ range γ) ∧ range γ ⊆ s, { have hp' : ∀ i ≤ n, p' i ∈ s, { intros i hi, simp [p', nat.lt_succ_of_le hi, hp] }, clear_value p', clear hp p, induction n with n hn, { use (λ _, p' 0), { continuity }, { split, { rintros i hi, rw nat.le_zero_iff.mp hi, exact ⟨0, rfl⟩ }, { rw range_subset_iff, rintros x, exact hp' 0 (le_refl _) } } }, { rcases hn (λ i hi, hp' i $ nat.le_succ_of_le hi) with ⟨γ₀, hγ₀⟩, rcases h.joined_in (p' n) (p' $ n+1) (hp' n n.le_succ) (hp' (n+1) $ le_refl _) with ⟨γ₁, hγ₁⟩, let γ : path (p' 0) (p' $ n+1) := γ₀.trans γ₁, use γ, have range_eq : range γ = range γ₀ ∪ range γ₁ := γ₀.trans_range γ₁, split, { rintros i hi, by_cases hi' : i ≤ n, { rw range_eq, left, exact hγ₀.1 i hi' }, { rw [not_le, ← nat.succ_le_iff] at hi', have : i = n.succ := by linarith, rw this, use 1, exact γ.target } }, { rw range_eq, apply union_subset hγ₀.2, rw range_subset_iff, exact hγ₁ } } }, have hpp' : ∀ k < n+1, p k = p' k, { intros k hk, simp only [p', hk, dif_pos], congr, ext, rw fin.coe_coe_of_lt hk, norm_cast }, use γ.cast (hpp' 0 n.zero_lt_succ) (hpp' n n.lt_succ_self), simp only [γ.cast_coe], refine and.intro hγ.2 _, rintros ⟨i, hi⟩, convert hγ.1 i (nat.le_of_lt_succ hi), rw ← hpp' i hi, congr, ext, rw fin.coe_coe_of_lt hi, norm_cast end lemma is_path_connected.exists_path_through_family' {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), (∀ t, γ t ∈ s) ∧ ∀ i, γ (t i) = p i := begin rcases h.exists_path_through_family p hp with ⟨γ, hγ⟩, rcases hγ with ⟨h₁, h₂⟩, simp only [range, mem_set_of_eq] at h₂, rw range_subset_iff at h₁, choose! t ht using h₂, exact ⟨γ, t, h₁, ht⟩ end /-! ### Path connected spaces -/ /-- A topological space is path-connected if it is non-empty and every two points can be joined by a continuous path. -/ class path_connected_space (X : Type*) [topological_space X] : Prop := (nonempty : nonempty X) (joined : ∀ x y : X, joined x y) attribute [instance, priority 50] path_connected_space.nonempty lemma path_connected_space_iff_zeroth_homotopy : path_connected_space X ↔ nonempty (zeroth_homotopy X) ∧ subsingleton (zeroth_homotopy X) := begin letI := path_setoid X, split, { introI h, refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨_⟩⟩, rintros ⟨x⟩ ⟨y⟩, exact quotient.sound (path_connected_space.joined x y) }, { unfold zeroth_homotopy, rintros ⟨h, h'⟩, resetI, exact ⟨(nonempty_quotient_iff _).mp h, λ x y, quotient.exact $ subsingleton.elim ⟦x⟧ ⟦y⟧⟩ }, end namespace path_connected_space variables [path_connected_space X] /-- Use path-connectedness to build a path between two points. -/ def some_path (x y : X) : path x y := nonempty.some (joined x y) end path_connected_space lemma is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space F := begin rw is_path_connected_iff, split, { rintro ⟨⟨x, x_in⟩, h⟩, refine ⟨⟨⟨x, x_in⟩⟩, _⟩, rintros ⟨y, y_in⟩ ⟨z, z_in⟩, have H := h y z y_in z_in, rwa joined_in_iff_joined y_in z_in at H }, { rintros ⟨⟨x, x_in⟩, H⟩, refine ⟨⟨x, x_in⟩, λ y z y_in z_in, _⟩, rw joined_in_iff_joined y_in z_in, apply H } end lemma path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X) := begin split, { introI h, inhabit X, refine ⟨default X, mem_univ _, _⟩, simpa using path_connected_space.joined (default X) }, { intro h, have h' := h.joined_in, cases h with x h, exact ⟨⟨x⟩, by simpa using h'⟩ }, end lemma path_connected_space_iff_eq : path_connected_space X ↔ ∃ x : X, path_component x = univ := by simp [path_connected_space_iff_univ, is_path_connected_iff_eq] @[priority 100] -- see Note [lower instance priority] instance path_connected_space.connected_space [path_connected_space X] : connected_space X := begin rw connected_space_iff_connected_component, rcases is_path_connected_iff_eq.mp (path_connected_space_iff_univ.mp ‹_›) with ⟨x, x_in, hx⟩, use x, rw ← univ_subset_iff, exact (by simpa using hx : path_component x = univ) ▸ path_component_subset_component x end namespace path_connected_space variables [path_connected_space X] lemma exists_path_through_family {n : ℕ} (p : fin (n+1) → X) : ∃ γ : path (p 0) (p n), (∀ i, p i ∈ range γ) := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family p (λ i, true.intro) with ⟨γ, -, h⟩, exact ⟨γ, h⟩ end lemma exists_path_through_family' {n : ℕ} (p : fin (n+1) → X) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), ∀ i, γ (t i) = p i := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family' p (λ i, true.intro) with ⟨γ, t, -, h⟩, exact ⟨γ, t, h⟩ end end path_connected_space /-! ### Locally path connected spaces -/ /-- A topological space is locally path connected, at every point, path connected neighborhoods form a neighborhood basis. -/ class loc_path_connected_space (X : Type*) [topological_space X] : Prop := (path_connected_basis : ∀ x : X, (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s) id) export loc_path_connected_space (path_connected_basis) lemma loc_path_connected_of_bases {p : ι → Prop} {s : X → ι → set X} (h : ∀ x, (𝓝 x).has_basis p (s x)) (h' : ∀ x i, p i → is_path_connected (s x i)) : loc_path_connected_space X := begin constructor, intro x, apply (h x).to_has_basis, { intros i pi, exact ⟨s x i, ⟨(h x).mem_of_mem pi, h' x i pi⟩, by refl⟩ }, { rintros U ⟨U_in, hU⟩, rcases (h x).mem_iff.mp U_in with ⟨i, pi, hi⟩, tauto } end lemma path_connected_space_iff_connected_space [loc_path_connected_space X] : path_connected_space X ↔ connected_space X := begin split, { introI h, apply_instance }, { introI hX, inhabit X, let x₀ := default X, rw path_connected_space_iff_eq, use x₀, refine eq_univ_of_nonempty_clopen (by simp) ⟨_, _⟩, { rw is_open_iff_mem_nhds, intros y y_in, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, apply mem_sets_of_superset U_in, rw ← path_component_congr y_in, exact hU.subset_path_component (mem_of_nhds U_in) }, { rw is_closed_iff_nhds, intros y H, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, rcases H U U_in with ⟨z, hz, hz'⟩, exact ((hU.joined_in z y hz $ mem_of_nhds U_in).joined.mem_path_component hz') } }, end lemma path_connected_subset_basis [loc_path_connected_space X] {U : set X} (h : is_open U) (hx : x ∈ U) : (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s ∧ s ⊆ U) id := (path_connected_basis x).has_basis_self_subset (mem_nhds_sets h hx) lemma loc_path_connected_of_is_open [loc_path_connected_space X] {U : set X} (h : is_open U) : loc_path_connected_space U := ⟨begin rintros ⟨x, x_in⟩, rw nhds_subtype_eq_comap, constructor, intros V, rw (has_basis.comap (coe : U → X) (path_connected_subset_basis h x_in)).mem_iff, split, { rintros ⟨W, ⟨W_in, hW, hWU⟩, hWV⟩, exact ⟨coe ⁻¹' W, ⟨⟨preimage_mem_comap W_in, hW.preimage_coe hWU⟩, hWV⟩⟩ }, { rintros ⟨W, ⟨W_in, hW⟩, hWV⟩, refine ⟨coe '' W, ⟨filter.image_coe_mem_sets (mem_nhds_sets h x_in) W_in, hW.image continuous_subtype_coe, subtype.coe_image_subset U W⟩, _⟩, rintros x ⟨y, ⟨y_in, hy⟩⟩, rw ← subtype.coe_injective hy, tauto }, end⟩ lemma is_open.is_connected_iff_is_path_connected [loc_path_connected_space X] {U : set X} (U_op : is_open U) : is_path_connected U ↔ is_connected U := begin rw [is_connected_iff_connected_space, is_path_connected_iff_path_connected_space], haveI := loc_path_connected_of_is_open U_op, exact path_connected_space_iff_connected_space end
3f5997f622a0ee2150fff8cf8c7165804e56c042
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/category/NonemptyFinLinOrd.lean
fb2ff8992189631ada12e11e16063cc7f90010a1
[ "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,542
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.fintype.order import data.set.finite import order.category.LinearOrder import category_theory.limits.shapes.images import category_theory.limits.shapes.regular_mono /-! # Nonempty finite linear orders This defines `NonemptyFinLinOrd`, the category of nonempty finite linear orders with monotone maps. This is the index category for simplicial objects. -/ universes u v open category_theory category_theory.limits /-- A typeclass for nonempty finite linear orders. -/ class nonempty_fin_lin_ord (α : Type*) extends fintype α, linear_order α := (nonempty : nonempty α . tactic.apply_instance) attribute [instance] nonempty_fin_lin_ord.nonempty @[priority 100] instance nonempty_fin_lin_ord.to_bounded_order (α : Type*) [nonempty_fin_lin_ord α] : bounded_order α := fintype.to_bounded_order α instance punit.nonempty_fin_lin_ord : nonempty_fin_lin_ord punit := { } instance fin.nonempty_fin_lin_ord (n : ℕ) : nonempty_fin_lin_ord (fin (n+1)) := { } instance ulift.nonempty_fin_lin_ord (α : Type u) [nonempty_fin_lin_ord α] : nonempty_fin_lin_ord (ulift.{v} α) := { .. linear_order.lift' equiv.ulift (equiv.injective _) } instance (α : Type*) [nonempty_fin_lin_ord α] : nonempty_fin_lin_ord αᵒᵈ := { ..order_dual.fintype α } /-- The category of nonempty finite linear orders. -/ def NonemptyFinLinOrd := bundled nonempty_fin_lin_ord namespace NonemptyFinLinOrd instance : bundled_hom.parent_projection @nonempty_fin_lin_ord.to_linear_order := ⟨⟩ attribute [derive [large_category, concrete_category]] NonemptyFinLinOrd instance : has_coe_to_sort NonemptyFinLinOrd Type* := bundled.has_coe_to_sort /-- Construct a bundled `NonemptyFinLinOrd` from the underlying type and typeclass. -/ def of (α : Type*) [nonempty_fin_lin_ord α] : NonemptyFinLinOrd := bundled.of α @[simp] lemma coe_of (α : Type*) [nonempty_fin_lin_ord α] : ↥(of α) = α := rfl instance : inhabited NonemptyFinLinOrd := ⟨of punit⟩ instance (α : NonemptyFinLinOrd) : nonempty_fin_lin_ord α := α.str instance has_forget_to_LinearOrder : has_forget₂ NonemptyFinLinOrd LinearOrder := bundled_hom.forget₂ _ _ /-- Constructs an equivalence between nonempty finite linear orders from an order isomorphism between them. -/ @[simps] def iso.mk {α β : NonemptyFinLinOrd.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply x }, inv_hom_id' := by { ext, exact e.apply_symm_apply x } } /-- `order_dual` as a functor. -/ @[simps] def dual : NonemptyFinLinOrd ⥤ NonemptyFinLinOrd := { obj := λ X, of Xᵒᵈ, map := λ X Y, order_hom.dual } /-- The equivalence between `FinPartialOrder` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : NonemptyFinLinOrd ≌ NonemptyFinLinOrd := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) lemma mono_iff_injective {A B : NonemptyFinLinOrd.{u}} (f : A ⟶ B) : mono f ↔ function.injective f := begin refine ⟨_, concrete_category.mono_of_injective f⟩, introI, intros a₁ a₂ h, let X : NonemptyFinLinOrd.{u} := ⟨ulift (fin 1)⟩, let g₁ : X ⟶ A := ⟨λ x, a₁, λ x₁ x₂ h, by refl⟩, let g₂ : X ⟶ A := ⟨λ x, a₂, λ x₁ x₂ h, by refl⟩, change g₁ (ulift.up (0 : fin 1)) = g₂ (ulift.up (0 : fin 1)), have eq : g₁ ≫ f = g₂ ≫ f := by { ext x, exact h, }, rw cancel_mono at eq, rw eq, end lemma epi_iff_surjective {A B : NonemptyFinLinOrd.{u}} (f : A ⟶ B) : epi f ↔ function.surjective f := begin split, { introI, by_contra' hf', rcases hf' with ⟨m, hm⟩, let Y : NonemptyFinLinOrd.{u} := ⟨ulift (fin 2)⟩, let p₁ : B ⟶ Y := ⟨λ b, if b < m then ulift.up 0 else ulift.up 1, λ x₁ x₂ h, begin simp only, split_ifs with h₁ h₂ h₂, any_goals { apply fin.zero_le, }, { exfalso, exact h₁ (lt_of_le_of_lt h h₂), }, { refl, }, end⟩, let p₂ : B ⟶ Y := ⟨λ b, if b ≤ m then ulift.up 0 else ulift.up 1, λ x₁ x₂ h, begin simp only, split_ifs with h₁ h₂ h₂, any_goals { apply fin.zero_le, }, { exfalso, exact h₁ (h.trans h₂), }, { refl, }, end⟩, have h : p₁ m = p₂ m, { congr, rw ← cancel_epi f, ext a : 2, simp only [comp_apply, order_hom.coe_fun_mk], split_ifs with h₁ h₂ h₂, any_goals { refl, }, { exfalso, exact h₂ (le_of_lt h₁), }, { exfalso, exact hm a (eq_of_le_of_not_lt h₂ h₁), }, }, simpa only [order_hom.coe_fun_mk, lt_self_iff_false, if_false, le_refl, if_true, ulift.up_inj, fin.one_eq_zero_iff] using h, }, { intro h, exact concrete_category.epi_of_surjective f h, }, end instance : split_epi_category NonemptyFinLinOrd.{u} := ⟨λ X Y f hf, begin have H : ∀ (y : Y), nonempty (f⁻¹' { y }), { rw epi_iff_surjective at hf, intro y, exact nonempty.intro ⟨(hf y).some, (hf y).some_spec⟩, }, let φ : Y → X := λ y, (H y).some.1, have hφ : ∀ (y : Y), f (φ y) = y := λ y, (H y).some.2, refine is_split_epi.mk' ⟨⟨φ, _⟩, _⟩, swap, { ext b, apply hφ, }, { intros a b, contrapose, intro h, simp only [not_le] at h ⊢, suffices : b ≤ a, { apply lt_of_le_of_ne this, intro h', exfalso, simpa only [h', lt_self_iff_false] using h, }, simpa only [hφ] using f.monotone (le_of_lt h), }, end⟩ instance : has_strong_epi_mono_factorisations NonemptyFinLinOrd.{u} := ⟨λ X Y f, begin let I : NonemptyFinLinOrd.{u} := ⟨set.image (coe_fn f) ⊤, ⟨⟩⟩, let e : X ⟶ I := ⟨λ x, ⟨f x, ⟨x, by tidy⟩⟩, λ x₁ x₂ h, f.monotone h⟩, let m : I ⟶ Y := ⟨λ y, y, by tidy⟩, haveI : epi e := by { rw epi_iff_surjective, tidy, }, haveI : strong_epi e := strong_epi_of_epi e, haveI : mono m := concrete_category.mono_of_injective _ (by tidy), exact nonempty.intro { I := I, m := m, e := e, }, end⟩ end NonemptyFinLinOrd lemma NonemptyFinLinOrd_dual_comp_forget_to_LinearOrder : NonemptyFinLinOrd.dual ⋙ forget₂ NonemptyFinLinOrd LinearOrder = forget₂ NonemptyFinLinOrd LinearOrder ⋙ LinearOrder.dual := rfl
a8960211f0a9e9de55a0d664d2c4657f14e76aad
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/quot.lean
fac3f392436edabec7b64889d0b05b956a1eeabc
[ "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
28,438
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import logic.relator /-! # Quotient types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This module extends the core library's treatment of quotient types (`init.data.quot`). ## Tags quotient -/ variables {α : Sort*} {β : Sort*} open function namespace setoid lemma ext {α : Sort*} : ∀{s t : setoid α}, (∀a b, @setoid.r α s a b ↔ @setoid.r α t a b) → s = t | ⟨r, _⟩ ⟨p, _⟩ eq := have r = p, from funext $ assume a, funext $ assume b, propext $ eq a b, by subst this end setoid namespace quot variables {ra : α → α → Prop} {rb : β → β → Prop} {φ : quot ra → quot rb → Sort*} local notation (name := mk) `⟦`:max a `⟧` := quot.mk _ a instance (r : α → α → Prop) [inhabited α] : inhabited (quot r) := ⟨⟦default⟧⟩ instance [subsingleton α] : subsingleton (quot ra) := ⟨λ x, quot.induction_on x (λ y, quot.ind (λ b, congr_arg _ (subsingleton.elim _ _)))⟩ /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quot ra) (qb : quot rb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (ca : ∀ {b a₁ a₂}, ra a₁ a₂ → f a₁ b == f a₂ b) (cb : ∀ {a b₁ b₂}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb := quot.hrec_on qa (λ a, quot.hrec_on qb (f a) (λ b₁ b₂ pb, cb pb)) $ λ a₁ a₂ pa, quot.induction_on qb $ λ b, calc @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₁) (@cb _) == f a₁ b : by simp [heq_self_iff_true] ... == f a₂ b : ca pa ... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp [heq_self_iff_true] /-- Map a function `f : α → β` such that `ra x y` implies `rb (f x) (f y)` to a map `quot ra → quot rb`. -/ protected def map (f : α → β) (h : (ra ⇒ rb) f f) : quot ra → quot rb := quot.lift (λ x, ⟦f x⟧) $ assume x y (h₁ : ra x y), quot.sound $ h h₁ /-- If `ra` is a subrelation of `ra'`, then we have a natural map `quot ra → quot ra'`. -/ protected def map_right {ra' : α → α → Prop} (h : ∀a₁ a₂, ra a₁ a₂ → ra' a₁ a₂) : quot ra → quot ra' := quot.map id h /-- Weaken the relation of a quotient. This is the same as `quot.map id`. -/ def factor {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : quot r → quot s := quot.lift (quot.mk s) (λ x y rxy, quot.sound (h x y rxy)) lemma factor_mk_eq {α : Type*} (r s : α → α → Prop) (h : ∀ x y, r x y → s x y) : factor r s h ∘ quot.mk _ = quot.mk _ := rfl variables {γ : Sort*} {r : α → α → Prop} {s : β → β → Prop} /-- **Alias** of `quot.lift_beta`. -/ lemma lift_mk (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) (a : α) : quot.lift f h (quot.mk r a) = f a := rfl @[simp] lemma lift_on_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : quot.lift_on (quot.mk r a) f h = f a := rfl @[simp] lemma surjective_lift {f : α → γ} (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : surjective (lift f h) ↔ surjective f := ⟨λ hf, hf.comp quot.exists_rep, λ hf y, let ⟨x, hx⟩ := hf y in ⟨quot.mk _ x, hx⟩⟩ /-- Descends a function `f : α → β → γ` to quotients of `α` and `β`. -/ attribute [reducible, elab_as_eliminator] protected def lift₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (q₁ : quot r) (q₂ : quot s) : γ := quot.lift (λ a, quot.lift (f a) (hr a)) (λ a₁ a₂ ha, funext (λ q, quot.induction_on q (λ b, hs a₁ a₂ b ha))) q₁ q₂ @[simp] lemma lift₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) (a : α) (b : β) : quot.lift₂ f hr hs (quot.mk r a) (quot.mk s b) = f a b := rfl /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` and applies it. -/ attribute [reducible, elab_as_eliminator] protected def lift_on₂ (p : quot r) (q : quot s) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : γ := quot.lift₂ f hr hs p q @[simp] lemma lift_on₂_mk (a : α) (b : β) (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hs : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) : quot.lift_on₂ (quot.mk r a) (quot.mk s b) f hr hs = f a b := rfl variables {t : γ → γ → Prop} /-- Descends a function `f : α → β → γ` to quotients of `α` and `β` wih values in a quotient of `γ`. -/ protected def map₂ (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (q₁ : quot r) (q₂ : quot s) : quot t := quot.lift₂ (λ a b, quot.mk t $ f a b) (λ a b₁ b₂ hb, quot.sound (hr a b₁ b₂ hb)) (λ a₁ a₂ b ha, quot.sound (hs a₁ a₂ b ha)) q₁ q₂ @[simp] lemma map₂_mk (f : α → β → γ) (hr : ∀ a b₁ b₂, s b₁ b₂ → t (f a b₁) (f a b₂)) (hs : ∀ a₁ a₂ b, r a₁ a₂ → t (f a₁ b) (f a₂ b)) (a : α) (b : β) : quot.map₂ f hr hs (quot.mk r a) (quot.mk s b) = quot.mk t (f a b) := rfl /-- A binary version of `quot.rec_on_subsingleton`. -/ @[reducible, elab_as_eliminator] protected def rec_on_subsingleton₂ {φ : quot r → quot s → Sort*} [h : ∀ a b, subsingleton (φ ⟦a⟧ ⟦b⟧)] (q₁ : quot r) (q₂ : quot s) (f : Π a b, φ ⟦a⟧ ⟦b⟧) : φ q₁ q₂ := @quot.rec_on_subsingleton _ r (λ q, φ q q₂) (λ a, quot.ind (h a) q₂) q₁ $ λ a, quot.rec_on_subsingleton q₂ $ λ b, f a b attribute [elab_as_eliminator] protected lemma induction_on₂ {δ : quot r → quot s → Prop} (q₁ : quot r) (q₂ : quot s) (h : ∀ a b, δ (quot.mk r a) (quot.mk s b)) : δ q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, h a₁ a₂) q₂) q₁ attribute [elab_as_eliminator] protected lemma induction_on₃ {δ : quot r → quot s → quot t → Prop} (q₁ : quot r) (q₂ : quot s) (q₃ : quot t) (h : ∀ a b c, δ (quot.mk r a) (quot.mk s b) (quot.mk t c)) : δ q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, h a₁ a₂ a₃) q₃) q₂) q₁ instance (r : α → α → Prop) (f : α → Prop) (h : ∀ a b, r a b → f a = f b) [hf : decidable_pred f] : decidable_pred (quot.lift f h) := λ q, quot.rec_on_subsingleton q hf /-- Note that this provides `decidable_rel (quot.lift₂ f ha hb)` when `α = β`. -/ instance (r : α → α → Prop) (s : β → β → Prop) (f : α → β → Prop) (ha : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hb : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) [hf : Π a, decidable_pred (f a)] (q₁ : quot r) : decidable_pred (quot.lift₂ f ha hb q₁) := λ q₂, quot.rec_on_subsingleton₂ q₁ q₂ hf instance (r : α → α → Prop) (q : quot r) (f : α → Prop) (h : ∀ a b, r a b → f a = f b) [decidable_pred f] : decidable (quot.lift_on q f h) := quot.lift.decidable_pred _ _ _ _ instance (r : α → α → Prop) (s : β → β → Prop) (q₁ : quot r) (q₂ : quot s) (f : α → β → Prop) (ha : ∀ a b₁ b₂, s b₁ b₂ → f a b₁ = f a b₂) (hb : ∀ a₁ a₂ b, r a₁ a₂ → f a₁ b = f a₂ b) [Π a, decidable_pred (f a)] : decidable (quot.lift_on₂ q₁ q₂ f ha hb) := quot.lift₂.decidable_pred _ _ _ _ _ _ _ end quot namespace quotient variables [sa : setoid α] [sb : setoid β] variables {φ : quotient sa → quotient sb → Sort*} instance (s : setoid α) [inhabited α] : inhabited (quotient s) := ⟨⟦default⟧⟩ instance (s : setoid α) [subsingleton α] : subsingleton (quotient s) := quot.subsingleton instance {α : Type*} [setoid α] : is_equiv α (≈) := { refl := setoid.refl, symm := λ a b, setoid.symm, trans := λ a b c, setoid.trans } /-- Induction on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂ (qa : quotient sa) (qb : quotient sb) (f : Π a b, φ ⟦a⟧ ⟦b⟧) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quot.hrec_on₂ qa qb f (λ _ _ _ p, c _ _ _ _ p (setoid.refl _)) (λ _ _ _ p, c _ _ _ _ (setoid.refl _) p) /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map (f : α → β) (h : ((≈) ⇒ (≈)) f f) : quotient sa → quotient sb := quot.map f h @[simp] lemma map_mk (f : α → β) (h : ((≈) ⇒ (≈)) f f) (x : α) : quotient.map f h (⟦x⟧ : quotient sa) = (⟦f x⟧ : quotient sb) := rfl variables {γ : Sort*} [sc : setoid γ] /-- Map a function `f : α → β → γ` that sends equivalent elements to equivalent elements to a function `f : quotient sa → quotient sb → quotient sc`. Useful to define binary operations on quotients. -/ protected def map₂ (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) : quotient sa → quotient sb → quotient sc := quotient.lift₂ (λ x y, ⟦f x y⟧) (λ x₁ y₁ x₂ y₂ h₁ h₂, quot.sound $ h h₁ h₂) @[simp] lemma map₂_mk (f : α → β → γ) (h : ((≈) ⇒ (≈) ⇒ (≈)) f f) (x : α) (y : β) : quotient.map₂ f h (⟦x⟧ : quotient sa) (⟦y⟧ : quotient sb) = (⟦f x y⟧ : quotient sc) := rfl include sa instance (f : α → Prop) (h : ∀ a b, a ≈ b → f a = f b) [decidable_pred f] : decidable_pred (quotient.lift f h) := quot.lift.decidable_pred _ _ _ include sb /-- Note that this provides `decidable_rel (quotient.lift₂ f h)` when `α = β`. -/ instance (f : α → β → Prop) (h : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) [hf : Π a, decidable_pred (f a)] (q₁ : quotient sa) : decidable_pred (quotient.lift₂ f h q₁) := λ q₂, quotient.rec_on_subsingleton₂ q₁ q₂ hf omit sb instance (q : quotient sa) (f : α → Prop) (h : ∀ a b, a ≈ b → f a = f b) [decidable_pred f] : decidable (quotient.lift_on q f h) := quotient.lift.decidable_pred _ _ _ instance (q₁ : quotient sa) (q₂ : quotient sb) (f : α → β → Prop) (h : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) [Π a, decidable_pred (f a)] : decidable (quotient.lift_on₂ q₁ q₂ f h) := quotient.lift₂.decidable_pred _ _ _ _ end quotient lemma quot.eq {α : Type*} {r : α → α → Prop} {x y : α} : quot.mk r x = quot.mk r y ↔ eqv_gen r x y := ⟨quot.exact r, quot.eqv_gen_sound⟩ @[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := ⟨quotient.exact, quotient.sound⟩ theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} : (∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) := ⟨assume h x, h _, assume h a, a.induction_on h⟩ @[simp] lemma quotient.lift_mk [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift f h (quotient.mk x) = f x := rfl @[simp] lemma quotient.lift_comp_mk [setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) : quotient.lift f h ∘ quotient.mk = f := rfl @[simp] lemma quotient.lift₂_mk {α : Sort*} {β : Sort*} {γ : Sort*} [setoid α] [setoid β] (f : α → β → γ) (h : ∀ (a₁ : α) (a₂ : β) (b₁ : α) (b₂ : β), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (a : α) (b : β) : quotient.lift₂ f h (quotient.mk a) (quotient.mk b) = f a b := rfl @[simp] lemma quotient.lift_on_mk [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α) : quotient.lift_on (quotient.mk x) f h = f x := rfl @[simp] theorem quotient.lift_on₂_mk {α : Sort*} {β : Sort*} [setoid α] (f : α → α → β) (h : ∀ (a₁ a₂ b₁ b₂ : α), a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (x y : α) : quotient.lift_on₂ (quotient.mk x) (quotient.mk y) f h = f x y := rfl /-- `quot.mk r` is a surjective function. -/ lemma surjective_quot_mk (r : α → α → Prop) : surjective (quot.mk r) := quot.exists_rep /-- `quotient.mk` is a surjective function. -/ lemma surjective_quotient_mk (α : Sort*) [s : setoid α] : surjective (quotient.mk : α → quotient s) := quot.exists_rep /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α := classical.some (quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast @[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q := classical.some_spec (quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out @[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a := quotient.exact (quotient.out_eq _) lemma quotient.mk_eq_iff_out [s : setoid α] {x : α} {y : quotient s} : ⟦x⟧ = y ↔ x ≈ quotient.out y := begin refine iff.trans _ quotient.eq, rw quotient.out_eq y, end lemma quotient.eq_mk_iff_out [s : setoid α] {x : quotient s} {y : α} : x = ⟦y⟧ ↔ quotient.out x ≈ y := begin refine iff.trans _ quotient.eq, rw quotient.out_eq x, end @[simp] lemma quotient.out_equiv_out {s : setoid α} {x y : quotient s} : x.out ≈ y.out ↔ x = y := by rw [← quotient.eq_mk_iff_out, quotient.out_eq] lemma quotient.out_injective {s : setoid α} : injective (@quotient.out α s) := λ a b h, quotient.out_equiv_out.1 $ h ▸ setoid.refl _ @[simp] lemma quotient.out_inj {s : setoid α} {x y : quotient s} : x.out = y.out ↔ x = y := ⟨λ h, quotient.out_injective h, λ h, h ▸ rfl⟩ section pi instance pi_setoid {ι : Sort*} {α : ι → Sort*} [∀ i, setoid (α i)] : setoid (Π i, α i) := { r := λ a b, ∀ i, a i ≈ b i, iseqv := ⟨ λ a i, setoid.refl _, λ a b h i, setoid.symm (h _), λ a b c h₁ h₂ i, setoid.trans (h₁ _) (h₂ _)⟩ } /-- Given a function `f : Π i, quotient (S i)`, returns the class of functions `Π i, α i` sending each `i` to an element of the class `f i`. -/ noncomputable def quotient.choice {ι : Type*} {α : ι → Type*} [S : Π i, setoid (α i)] (f : Π i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := ⟦λ i, (f i).out⟧ @[simp] theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [Π i, setoid (α i)] (f : Π i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ := quotient.sound $ λ i, quotient.mk_out _ @[elab_as_eliminator] lemma quotient.induction_on_pi {ι : Type*} {α : ι → Sort*} [s : ∀ i, setoid (α i)] {p : (Π i, quotient (s i)) → Prop} (f : Π i, quotient (s i)) (h : ∀ a : Π i, α i, p (λ i, ⟦a i⟧)) : p f := begin rw ← (funext (λ i, quotient.out_eq (f i)) : (λ i, ⟦(f i).out⟧) = f), apply h, end end pi lemma nonempty_quotient_iff (s : setoid α) : nonempty (quotient s) ↔ nonempty α := ⟨assume ⟨a⟩, quotient.induction_on a nonempty.intro, assume ⟨a⟩, ⟨⟦a⟧⟩⟩ /-! ### Truncation -/ theorem true_equivalence : @equivalence α (λ _ _, true) := ⟨λ _, trivial, λ _ _ _, trivial, λ _ _ _ _ _, trivial⟩ /-- Always-true relation as a `setoid`. Note that in later files the preferred spelling is `⊤ : setoid α`. -/ def true_setoid : setoid α := ⟨_, true_equivalence⟩ /-- `trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def {u} trunc (α : Sort u) : Sort u := @quotient α true_setoid namespace trunc /-- Constructor for `trunc α` -/ def mk (a : α) : trunc α := quot.mk _ a instance [inhabited α] : inhabited (trunc α) := ⟨mk default⟩ /-- Any constant function lifts to a function out of the truncation -/ def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β := quot.lift f (λ a b _, c a b) theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind protected theorem lift_mk (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl /-- Lift a constant function on `q : trunc α`. -/ @[reducible, elab_as_eliminator] protected def lift_on (q : trunc α) (f : α → β) (c : ∀ a b : α, f a = f b) : β := lift f c q @[elab_as_eliminator] protected theorem induction_on {β : trunc α → Prop} (q : trunc α) (h : ∀ a, β (mk a)) : β q := ind h q theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q attribute [elab_as_eliminator] protected theorem induction_on₂ {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ := trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁) protected theorem eq (a b : trunc α) : a = b := trunc.induction_on₂ a b (λ x y, quot.sound trivial) instance : subsingleton (trunc α) := ⟨trunc.eq⟩ /-- The `bind` operator for the `trunc` monad. -/ def bind (q : trunc α) (f : α → trunc β) : trunc β := trunc.lift_on q f (λ a b, trunc.eq _ _) /-- A function `f : α → β` defines a function `map f : trunc α → trunc β`. -/ def map (f : α → β) (q : trunc α) : trunc β := bind q (trunc.mk ∘ f) instance : monad trunc := { pure := @trunc.mk, bind := @trunc.bind } instance : is_lawful_monad trunc := { id_map := λ α q, trunc.eq _ _, pure_bind := λ α β q f, rfl, bind_assoc := λ α β γ x f g, trunc.eq _ _ } variable {C : trunc α → Sort*} /-- Recursion/induction principle for `trunc`. -/ @[reducible, elab_as_eliminator] protected def rec (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) (q : trunc α) : C q := quot.rec f (λ a b _, h a b) q /-- A version of `trunc.rec` taking `q : trunc α` as the first argument. -/ @[reducible, elab_as_eliminator] protected def rec_on (q : trunc α) (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q := trunc.rec f h q /-- A version of `trunc.rec_on` assuming the codomain is a `subsingleton`. -/ @[reducible, elab_as_eliminator] protected def rec_on_subsingleton [∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q := trunc.rec f (λ a b, subsingleton.elim _ (f b)) q /-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/ noncomputable def out : trunc α → α := quot.out @[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _ protected theorem nonempty (q : trunc α) : nonempty α := nonempty_of_exists q.exists_rep end trunc /-! ### `quotient` with implicit `setoid` -/ namespace quotient variables {γ : Sort*} {φ : Sort*} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} /-! Versions of quotient definitions and lemmas ending in `'` use unification instead of typeclass inference for inferring the `setoid` argument. This is useful when there are several different quotient relations on a type, for example quotient groups, rings and modules. -/ /-- A version of `quotient.mk` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ protected def mk' (a : α) : quotient s₁ := quot.mk s₁.1 a /-- `quotient.mk'` is a surjective function. -/ lemma surjective_quotient_mk' : surjective (quotient.mk' : α → quotient s₁) := quot.exists_rep /-- A version of `quotient.lift_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator, reducible] protected def lift_on' (q : quotient s₁) (f : α → φ) (h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : φ := quotient.lift_on q f h @[simp] protected lemma lift_on'_mk' (f : α → φ) (h) (x : α) : quotient.lift_on' (@quotient.mk' _ s₁ x) f h = f x := rfl @[simp] lemma surjective_lift_on' {f : α → φ} (h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : surjective (λ x, quotient.lift_on' x f h) ↔ surjective f := quot.surjective_lift _ /-- A version of `quotient.lift_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator, reducible] protected def lift_on₂' (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ) (h : ∀ a₁ a₂ b₁ b₂, @setoid.r α s₁ a₁ b₁ → @setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ := quotient.lift_on₂ q₁ q₂ f h @[simp] protected lemma lift_on₂'_mk' (f : α → β → γ) (h) (a : α) (b : β) : quotient.lift_on₂' (@quotient.mk' _ s₁ a) (@quotient.mk' _ s₂ b) f h = f a b := rfl /-- A version of `quotient.ind` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma ind' {p : quotient s₁ → Prop} (h : ∀ a, p (quotient.mk' a)) (q : quotient s₁) : p q := quotient.ind h q /-- A version of `quotient.ind₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma ind₂' {p : quotient s₁ → quotient s₂ → Prop} (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) (q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ := quotient.ind₂ h q₁ q₂ /-- A version of `quotient.induction_on` taking `{s : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected lemma induction_on' {p : quotient s₁ → Prop} (q : quotient s₁) (h : ∀ a, p (quotient.mk' a)) : p q := quotient.induction_on q h /-- A version of `quotient.induction_on₂` taking `{s₁ : setoid α} {s₂ : setoid β}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₂' {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ := quotient.induction_on₂ q₁ q₂ h /-- A version of `quotient.induction_on₃` taking `{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}` as implicit arguments instead of instance arguments. -/ @[elab_as_eliminator] protected lemma induction_on₃' {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ a₁ a₂ a₃, p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ := quotient.induction_on₃ q₁ q₂ q₃ h /-- A version of `quotient.rec_on_subsingleton` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ @[elab_as_eliminator] protected def rec_on_subsingleton' {φ : quotient s₁ → Sort*} [h : ∀ a, subsingleton (φ ⟦a⟧)] (q : quotient s₁) (f : Π a, φ (quotient.mk' a)) : φ q := quotient.rec_on_subsingleton q f /-- A version of `quotient.rec_on_subsingleton₂` taking `{s₁ : setoid α} {s₂ : setoid α}` as implicit arguments instead of instance arguments. -/ attribute [reducible, elab_as_eliminator] protected def rec_on_subsingleton₂' {φ : quotient s₁ → quotient s₂ → Sort*} [h : ∀ a b, subsingleton (φ ⟦a⟧ ⟦b⟧)] (q₁ : quotient s₁) (q₂ : quotient s₂) (f : Π a₁ a₂, φ (quotient.mk' a₁) (quotient.mk' a₂)) : φ q₁ q₂ := quotient.rec_on_subsingleton₂ q₁ q₂ f /-- Recursion on a `quotient` argument `a`, result type depends on `⟦a⟧`. -/ protected def hrec_on' {φ : quotient s₁ → Sort*} (qa : quotient s₁) (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) : φ qa := quot.hrec_on qa f c @[simp] lemma hrec_on'_mk' {φ : quotient s₁ → Sort*} (f : Π a, φ (quotient.mk' a)) (c : ∀ a₁ a₂, a₁ ≈ a₂ → f a₁ == f a₂) (x : α) : (quotient.mk' x).hrec_on' f c = f x := rfl /-- Recursion on two `quotient` arguments `a` and `b`, result type depends on `⟦a⟧` and `⟦b⟧`. -/ protected def hrec_on₂' {φ : quotient s₁ → quotient s₂ → Sort*} (qa : quotient s₁) (qb : quotient s₂) (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quotient.hrec_on₂ qa qb f c @[simp] lemma hrec_on₂'_mk' {φ : quotient s₁ → quotient s₂ → Sort*} (f : ∀ a b, φ (quotient.mk' a) (quotient.mk' b)) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) (x : α) (qb : quotient s₂) : (quotient.mk' x).hrec_on₂' qb f c = qb.hrec_on' (f x) (λ b₁ b₂, c _ _ _ _ (setoid.refl _)) := rfl /-- Map a function `f : α → β` that sends equivalent elements to equivalent elements to a function `quotient sa → quotient sb`. Useful to define unary operations on quotients. -/ protected def map' (f : α → β) (h : (s₁.r ⇒ s₂.r) f f) : quotient s₁ → quotient s₂ := quot.map f h @[simp] lemma map'_mk' (f : α → β) (h) (x : α) : (quotient.mk' x : quotient s₁).map' f h = (quotient.mk' (f x) : quotient s₂) := rfl /-- A version of `quotient.map₂` using curly braces and unification. -/ protected def map₂' (f : α → β → γ) (h : (s₁.r ⇒ s₂.r ⇒ s₃.r) f f) : quotient s₁ → quotient s₂ → quotient s₃ := quotient.map₂ f h @[simp] lemma map₂'_mk' (f : α → β → γ) (h) (x : α) : (quotient.mk' x : quotient s₁).map₂' f h = (quotient.map' (f x) (h (setoid.refl x)) : quotient s₂ → quotient s₃) := rfl lemma exact' {a b : α} : (quotient.mk' a : quotient s₁) = quotient.mk' b → @setoid.r _ s₁ a b := quotient.exact lemma sound' {a b : α} : @setoid.r _ s₁ a b → @quotient.mk' α s₁ a = quotient.mk' b := quotient.sound @[simp] protected lemma eq' {a b : α} : @quotient.mk' α s₁ a = quotient.mk' b ↔ @setoid.r _ s₁ a b := quotient.eq /-- A version of `quotient.out` taking `{s₁ : setoid α}` as an implicit argument instead of an instance argument. -/ noncomputable def out' (a : quotient s₁) : α := quotient.out a @[simp] theorem out_eq' (q : quotient s₁) : quotient.mk' q.out' = q := q.out_eq theorem mk_out' (a : α) : @setoid.r α s₁ (quotient.mk' a : quotient s₁).out' a := quotient.exact (quotient.out_eq _) section variables [setoid α] protected lemma mk'_eq_mk (x : α) : quotient.mk' x = ⟦x⟧ := rfl @[simp] protected lemma lift_on'_mk (x : α) (f : α → β) (h) : ⟦x⟧.lift_on' f h = f x := rfl @[simp] protected lemma lift_on₂'_mk [setoid β] (f : α → β → γ) (h) (a : α) (b : β) : quotient.lift_on₂' ⟦a⟧ ⟦b⟧ f h = f a b := quotient.lift_on₂'_mk' _ _ _ _ @[simp] lemma map'_mk [setoid β] (f : α → β) (h) (x : α) : ⟦x⟧.map' f h = ⟦f x⟧ := rfl end instance (q : quotient s₁) (f : α → Prop) (h : ∀ a b, @setoid.r α s₁ a b → f a = f b) [decidable_pred f] : decidable (quotient.lift_on' q f h) := quotient.lift.decidable_pred _ _ q instance (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → Prop) (h : ∀ a₁ b₁ a₂ b₂, @setoid.r α s₁ a₁ a₂ → @setoid.r β s₂ b₁ b₂ → f a₁ b₁ = f a₂ b₂) [Π a, decidable_pred (f a)] : decidable (quotient.lift_on₂' q₁ q₂ f h) := quotient.lift₂.decidable_pred _ _ _ _ end quotient
1d54feb760710d5d6928352e4ea067043ba01a7a
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/advanced_addition/11.lean
fc4ffdfdf1964f22fe25309014e7a4adc8f016f0
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
114
lean
lemma add_right_eq_zero (a b : mynat) : a + b = 0 → a = 0 := begin rw add_comm, exact add_left_eq_zero, end
66ed7259712c0ad083d6decbc525e3da69e70f84
c61b91f85121053c627318ad8fcde30dfb8637d2
/Chapter4/4-4.lean
3ba007de6f1ee4c59f8de103c54792725096c6d8
[]
no_license
robkorn/theorem-proving-in-lean-exercises
9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb
9c51da587105ee047a9db55d52709d881a39be7a
refs/heads/master
1,585,403,341,988
1,540,142,619,000
1,540,142,619,000
148,431,678
2
0
null
null
null
null
UTF-8
Lean
false
false
1,987
lean
open nat namespace existential theorem bob : ∃x : ℕ, x > 0 := have h : 1 > 0, from zero_lt_succ 0, exists.intro _ h #check bob example (x : ℕ) (h : x > 0) : ∃y, y < x := exists.intro 0 h example (x y z : ℕ) (hxy : x < y) (hyz : y < z) : ∃w, x < w ∧ w < z := -- exists.intro y (and.intro hxy hyz) -- exists.intro y ⟨hxy, hyz⟩ -- ⟨y, ⟨hxy, hyz⟩⟩ ⟨y, hxy, hyz⟩ #check @exists.intro example : ∃x : ℕ, x > 0 := ⟨1, zero_lt_succ 0⟩ example (x : ℕ) (h : x > 0) : ∃y, y < x := ⟨0, h⟩ example (x y z : ℕ) (hxy : x < y) (hyz : y < z) : ∃w, x < w ∧ w < z := ⟨y, hxy, hyz⟩ variable g : ℕ → ℕ → ℕ variable hg : g 0 0 = 0 theorem gex1 : ∃ x, g x x = x := ⟨0, hg⟩ theorem gex2 : ∃ x, g x 0 = x := ⟨0, hg⟩ theorem gex3 : ∃ x, g 0 0 = x := ⟨0, hg⟩ theorem gex4 : ∃ x, g x x = 0 := ⟨0, hg⟩ set_option pp.implicit true #print gex1 #print gex2 #print gex3 #print gex4 variables (α : Type) (p q : α → Prop) example (h : ∃ r, p r ∧ q r) : ∃ x, q x ∧ p x := exists.elim h (assume w, assume hw : p w ∧ q w, show ∃ x, q x ∧ p x, from ⟨w, hw.right, hw.left⟩) end existential namespace matchh variables (α : Type) (p q : α → Prop) example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x := -- match h with ⟨(w : α),(hw : p w ∧ q w)⟩ := -- match h with ⟨w, hw⟩ := -- ⟨w, hw.right, hw.left⟩ match h with ⟨w, hpw, hqw⟩ := ⟨w, hqw, hpw⟩ end example (h : ∃ x, p x ∧ q x) : ∃ x, q x ∧ p x := let ⟨w, hpw, hqw⟩ := h in ⟨w, hqw, hpw⟩ example : (∃ x, p x ∧ q x) → ∃ x, q x ∧ p x := assume ⟨w, hpw, hqw⟩, ⟨w, hqw, hpw⟩ def is_even (a : nat) := ∃ b, a = 2 * b theorem even_plus_even {a b : nat} (h1 : is_even a) (h2 : is_even b) : is_even (a + b) := match h1, h2 with ⟨w1, hw1⟩, ⟨w2, hw2⟩ := ⟨w1 + w2, by rw [hw1, hw2, mul_add]⟩ end #check even_plus_even end matchh
dded29f598edccdc3051476ae5517c2478c62abc
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/305.lean
bdebaea140952142879cbffc239a2ba4df5ed3d8
[ "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,306
lean
def Unit.longName (f : Unit) : String := "" inductive Cmd | init (name : String) (subCmds : Array Cmd) (flags : Array Unit) open Inhabited in instance : Inhabited Cmd where default := Cmd.init default default default namespace Cmd def name : Cmd → String | init v _ _ => v def subCmds : Cmd → Array Cmd | init _ v _ => v def flags : Cmd → Array Unit | init _ _ v => v def subCmd? (c : Cmd) (name : String) : Option Cmd := c.subCmds.find? (·.name = name) def flag? (c : Cmd) (longName : String) : Option Unit := c.flags.find? (·.longName = longName) def hasFlag (c : Cmd) (longName : String) : Bool := c.flag? longName |>.isSome def subCmdByFullName? (c : Cmd) (fullName : Array String) : Option Cmd := do let mut c := c guard <| c.name = fullName.get? 0 for subName in fullName[1:] do c ← c.subCmd? subName return c end Cmd structure Flag.Parsed where longName : String abbrev FullCmdName := Array String structure Cmd.Parsed where name : FullCmdName flags : Array Flag.Parsed namespace Cmd.Parsed def hasFlag (c : Cmd.Parsed) (longName : String) : Bool := false end Cmd.Parsed def readSubCmds : Id FullCmdName := panic! "" def readArgs : Id (Array Flag.Parsed) := panic! "" def parse (c : Cmd) : Id Cmd.Parsed := do let cmdName ← readSubCmds let flags ← readArgs let cmd := c.subCmdByFullName? cmdName |>.get! let defaultedFlags : Array Flag.Parsed := #[] -- If we uncomment /-: Cmd.Parsed -/ two lines below or comment the line below, the elaborator stops hanging. let flags := defaultedFlags let parsedCmd /- : Cmd.Parsed -/ := { name := cmdName, flags := flags } -- If we remove `∨ cmd.hasFlag "version" ∧ parsedCmd.hasFlag "version"` from the condition below, -- the timeout turns into an error. If we also remove `∧ parsedCmd.hasFlag "help"`, it works fine. -- Error: -- synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized -- instDecidableAnd -- inferred -- ?m.4652 flags✝ positionalArgs variableArgs if cmd.hasFlag "help" ∧ parsedCmd.hasFlag "help" ∨ cmd.hasFlag "version" ∧ parsedCmd.hasFlag "version" then return parsedCmd return parsedCmd
2664db349bcdb39005b5047ec60ae7e4e690fb43
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/dec_trivial_loop.lean
741716a7371c8d73776af2468b70eb2b343ee855
[ "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
37
lean
check @dec_trivial print dec_trivial
1463836101db1101755ef8a5ea1f696952a3e8a6
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/meta/declaration.lean
be2bb4cba0039859a481493dcc9d4c0a90992c94
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,928
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.expr init.meta.name init.meta.task /- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` constructor are: the definitional height and the flag `self_opt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. For definitions marked as regular, we also have a hint for constraints such as (f a) =?= (f b) if self_opt == true, then checker will first try to solve (a =?= b), only if it fails, it unfolds f. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during type checking. Remark: the reducibility_hints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the elaborator. The reducibility_hints are used by the kernel (and elaborator). Moreover, the reducibility_hints cannot be changed after a declaration is added to the kernel. -/ inductive reducibility_hints | opaque : reducibility_hints | abbrev : reducibility_hints | regular : nat → bool → reducibility_hints /- Reflect a C++ declaration object. The VM replaces it with the C++ implementation. -/ meta inductive declaration /- definition: name, list universe parameters, type, value, is_trusted -/ | defn : name → list name → expr → expr → reducibility_hints → bool → declaration /- theorem: name, list universe parameters, type, value (remark: theorems are always trusted) -/ | thm : name → list name → expr → task expr → declaration /- constant assumption: name, list universe parameters, type, is_trusted -/ | cnst : name → list name → expr → bool → declaration /- axiom : name → list universe parameters, type (remark: axioms are always trusted) -/ | ax : name → list name → expr → declaration meta def mk_definition (n : name) (ls : list name) (v : expr) (e : expr) : declaration := declaration.defn n ls v e (reducibility_hints.regular 1 tt) tt meta def declaration.to_name : declaration → name | (declaration.defn n ls t v h tr) := n | (declaration.thm n ls t v) := n | (declaration.cnst n ls t tr) := n | (declaration.ax n ls t) := n meta def declaration.univ_params : declaration → list name | (declaration.defn n ls t v h tr) := ls | (declaration.thm n ls t v) := ls | (declaration.cnst n ls t tr) := ls | (declaration.ax n ls t) := ls meta def declaration.type : declaration → expr | (declaration.defn n ls t v h tr) := t | (declaration.thm n ls t v) := t | (declaration.cnst n ls t tr) := t | (declaration.ax n ls t) := t meta def declaration.value : declaration → expr | (declaration.defn n ls t v h tr) := v | (declaration.thm n ls t v) := v^.get | _ := default expr meta def declaration.value_task : declaration → task expr | (declaration.defn n ls t v h tr) := task.pure v | (declaration.thm n ls t v) := v | _ := task.pure (default expr) meta def declaration.update_type : declaration → expr → declaration | (declaration.defn n ls t v h tr) new_t := declaration.defn n ls new_t v h tr | (declaration.thm n ls t v) new_t := declaration.thm n ls new_t v | (declaration.cnst n ls t tr) new_t := declaration.cnst n ls new_t tr | (declaration.ax n ls t) new_t := declaration.ax n ls new_t meta def declaration.update_name : declaration → name → declaration | (declaration.defn n ls t v h tr) new_n := declaration.defn new_n ls t v h tr | (declaration.thm n ls t v) new_n := declaration.thm new_n ls t v | (declaration.cnst n ls t tr) new_n := declaration.cnst new_n ls t tr | (declaration.ax n ls t) new_n := declaration.ax new_n ls t meta def declaration.update_value : declaration → expr → declaration | (declaration.defn n ls t v h tr) new_v := declaration.defn n ls t new_v h tr | (declaration.thm n ls t v) new_v := declaration.thm n ls t (task.pure new_v) | d new_v := d meta def declaration.update_value_task : declaration → task expr → declaration | (declaration.defn n ls t v h tr) new_v := declaration.defn n ls t new_v^.get h tr | (declaration.thm n ls t v) new_v := declaration.thm n ls t new_v | d new_v := d meta def declaration.map_value : declaration → (expr → expr) → declaration | (declaration.defn n ls t v h tr) f := declaration.defn n ls t (f v) h tr | (declaration.thm n ls t v) f := declaration.thm n ls t (task.map f v) | d f := d meta def declaration.to_definition : declaration → declaration | (declaration.cnst n ls t tr) := declaration.defn n ls t (default expr) reducibility_hints.abbrev tr | (declaration.ax n ls t) := declaration.thm n ls t (task.pure (default expr)) | d := d /- Instantiate a universe polymorphic declaration type with the given universes. -/ meta constant declaration.instantiate_type_univ_params : declaration → list level → option expr /- Instantiate a universe polymorphic declaration value with the given universes. -/ meta constant declaration.instantiate_value_univ_params : declaration → list level → option expr
0789ffc84aca567dcfcc906bd5a9e4f83099b269
9028d228ac200bbefe3a711342514dd4e4458bff
/src/algebra/category/Algebra/basic.lean
657881f6d8dda46770f97ebcc4f34c4bfe5b6d9d
[ "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
3,731
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.algebra.basic import algebra.algebra.subalgebra import algebra.category.CommRing.basic import algebra.category.Module.basic open category_theory open category_theory.limits universes v u variables (R : Type u) [comm_ring R] /-- The category of R-modules and their morphisms. -/ structure Algebra := (carrier : Type v) [is_ring : ring carrier] [is_algebra : algebra R carrier] attribute [instance] Algebra.is_ring Algebra.is_algebra namespace Algebra instance : has_coe_to_sort (Algebra R) := { S := Type v, coe := Algebra.carrier } instance : category (Algebra.{v} R) := { hom := λ A B, A →ₐ[R] B, id := λ A, alg_hom.id R A, comp := λ A B C f g, g.comp f } instance : concrete_category (Algebra.{v} R) := { forget := { obj := λ R, R, map := λ R S f, (f : R → S) }, forget_faithful := { } } instance has_forget_to_Ring : has_forget₂ (Algebra R) Ring.{v} := { forget₂ := { obj := λ A, Ring.of A, map := λ A₁ A₂ f, alg_hom.to_ring_hom f, } } instance has_forget_to_Module : has_forget₂ (Algebra R) (Module R) := { forget₂ := { obj := λ M, Module.of R M, map := λ M₁ M₂ f, alg_hom.to_linear_map f, } } /-- The object in the category of R-algebras associated to a type equipped with the appropriate typeclasses. -/ def of (X : Type v) [ring X] [algebra R X] : Algebra R := ⟨X⟩ instance : inhabited (Algebra R) := ⟨of R R⟩ @[simp] lemma coe_of (X : Type u) [ring X] [algebra R X] : (of R X : Type u) = X := rfl variables {R} /-- Forgetting to the underlying type and then building the bundled object returns the original algebra. -/ @[simps] def of_self_iso (M : Algebra R) : Algebra.of R M ≅ M := { hom := 𝟙 M, inv := 𝟙 M } variables {R} {M N U : Module.{v} R} @[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl @[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) : ((f ≫ g) : M → U) = g ∘ f := rfl end Algebra variables {R} variables {X₁ X₂ : Type u} /-- Build an isomorphism in the category `Algebra R` from a `alg_equiv` between `algebra`s. -/ @[simps] def alg_equiv.to_Algebra_iso {g₁ : ring X₁} {g₂ : ring X₂} {m₁ : algebra R X₁} {m₂ : algebra R X₂} (e : X₁ ≃ₐ[R] X₂) : Algebra.of R X₁ ≅ Algebra.of R X₂ := { hom := (e : X₁ →ₐ[R] X₂), inv := (e.symm : X₂ →ₐ[R] X₁), hom_inv_id' := begin ext, exact e.left_inv x, end, inv_hom_id' := begin ext, exact e.right_inv x, end, } namespace category_theory.iso /-- Build a `alg_equiv` from an isomorphism in the category `Algebra R`. -/ @[simps] def to_alg_equiv {X Y : Algebra R} (i : X ≅ Y) : X ≃ₐ[R] Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_mul' := by tidy, commutes' := by tidy, }. end category_theory.iso /-- algebra equivalences between `algebras`s are the same as (isomorphic to) isomorphisms in `Algebra` -/ @[simps] def alg_equiv_iso_Algebra_iso {X Y : Type u} [ring X] [ring Y] [algebra R X] [algebra R Y] : (X ≃ₐ[R] Y) ≅ (Algebra.of R X ≅ Algebra.of R Y) := { hom := λ e, e.to_Algebra_iso, inv := λ i, i.to_alg_equiv, } instance (X : Type u) [ring X] [algebra R X] : has_coe (subalgebra R X) (Algebra R) := ⟨ λ N, Algebra.of R N ⟩ instance Algebra.forget_reflects_isos : reflects_isomorphisms (forget (Algebra.{u} R)) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget (Algebra.{u} R)).map f), let e : X ≃ₐ[R] Y := { ..f, ..i.to_equiv }, exact { ..e.to_Algebra_iso }, end }
b5e02f6716c22d11bb1852d897aeef0692b4405e
4727251e0cd73359b15b664c3170e5d754078599
/src/data/bool/all_any.lean
42d41296aec8ccc47e58cefda66d11bb03369fd4
[ "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
1,872
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.basic /-! # Boolean quantifiers This proves a few properties about `list.all` and `list.any`, which are the `bool` universal and existential quantifiers. Their definitions are in core Lean. -/ variables {α : Type*} {p : α → Prop} [decidable_pred p] {l : list α} {a : α} namespace list @[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} : all l p ↔ ∀ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_true rfl (forall_mem_nil _) }, simp only [all_cons, band_coe_iff, ih, forall_mem_cons] end theorem all_iff_forall_prop : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp only [all_iff_forall, bool.of_to_bool_iff] @[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl @[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) : any (a :: l) p = (p a || any l p) := rfl theorem any_iff_exists {p : α → bool} : any l p ↔ ∃ a ∈ l, p a := begin induction l with a l ih, { exact iff_of_false bool.not_ff (not_exists_mem_nil _) }, simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff] end theorem any_iff_exists_prop : any l (λ a, p a) ↔ ∃ a ∈ l, p a := by simp [any_iff_exists] theorem any_of_mem {p : α → bool} (h₁ : a ∈ l) (h₂ : p a) : any l p := any_iff_exists.2 ⟨_, h₁, h₂⟩ @[priority 500] instance decidable_forall_mem (l : list α) : decidable (∀ x ∈ l, p x) := decidable_of_iff _ all_iff_forall_prop instance decidable_exists_mem (l : list α) : decidable (∃ x ∈ l, p x) := decidable_of_iff _ any_iff_exists_prop end list
f8acb0372c57bccc123115476b39f953e8aa6367
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1293.lean
d0bb50baa89c3da5012eb40614f1f259d516fbe3
[ "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
386
lean
open expr tactic example : true := by whnf (var 0) >> return () example : true := by whnf (app (var 0) (var 0)) >> return () example : true := by head_zeta (var 0) >> return () example : true := by unify (var 0) (var 0) >> return () example : true := by is_def_eq (var 0) (var 0) >> return () example (foo trivial) := by do t ← infer_type (var 0), to_expr ``(trivial) >>= apply
21768703f80237ab60f7894284e4baf9f5cf8420
2d34dfb0a1cc250584282618dc10ea03d3fa858e
/src/pseudo_normed_group/basic.lean
aa41a7bc01f41c513e2fd12c31e4af737d9e2a49
[]
no_license
zeta1999/lean-liquid
61e294ec5adae959d8ee1b65d015775484ff58c2
96bb0fa3afc3b451bcd1fb7d974348de2f290541
refs/heads/master
1,676,579,150,248
1,610,771,445,000
1,610,771,445,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,949
lean
import data.real.nnreal import algebra.group.hom import algebra.big_operators import algebra.module.pi import topology.basic import type_pow noncomputable theory open_locale nnreal big_operators local attribute [instance] type_pow section for_mathlib @[simp] lemma function.nsmul_apply {X M : Type*} [add_comm_monoid M] (n : ℕ) (f : X → M) (x : X) : (n •ℕ f) x = n •ℕ (f x) := by rw [nsmul_eq_smul, nsmul_eq_smul, pi.smul_apply] @[simp, to_additive] lemma monoid_hom.coe_one {M₁ M₂ : Type*} [monoid M₁] [monoid M₂] : ⇑(1 : M₁ →* M₂) = 1 := rfl @[simp, to_additive] lemma monoid_hom.coe_mul {M₁ M₂ : Type*} [monoid M₁] [comm_monoid M₂] (f g : M₁ →* M₂) : ⇑(f * g) = f * g := rfl @[simp, to_additive] lemma monoid_hom.coe_div {M₁ M₂ : Type*} [monoid M₁] [comm_group M₂] (f g : M₁ →* M₂) : ⇑(f / g) = f / g := rfl @[simp, to_additive] lemma monoid_hom.coe_inv {M₁ M₂ : Type*} [monoid M₁] [comm_group M₂] (f : M₁ →* M₂) : ⇑(f⁻¹) = f⁻¹ := rfl @[simp] lemma add_monoid_hom.coe_nsmul {M₁ M₂ : Type*} [add_monoid M₁] [add_comm_monoid M₂] (n : ℕ) (f : M₁ →+ M₂) : ⇑(n •ℕ f) = n •ℕ (f : M₁ → M₂) := begin induction n with n ih, { simp only [add_monoid_hom.zero_apply, zero_nsmul, add_monoid_hom.coe_zero], }, { simp only [succ_nsmul, add_monoid_hom.coe_add, ih] } end @[simp] lemma function.gsmul_apply {X M : Type*} [add_comm_group M] (n : ℤ) (f : X → M) (x : X) : (n •ℤ f) x = n •ℤ (f x) := begin apply int.induction_on n, { simp only [zero_gsmul, pi.zero_apply] }, { simp only [add_gsmul, function.nsmul_apply, forall_const, pi.add_apply, one_gsmul, eq_self_iff_true, gsmul_coe_nat] }, { intro, simp only [sub_gsmul, neg_gsmul, forall_prop_of_true, function.nsmul_apply, pi.neg_apply, one_gsmul, gsmul_coe_nat, pi.sub_apply (-(i •ℕ f)) f x] } end @[simp] lemma add_monoid_hom.coe_gsmul {M₁ M₂ : Type*} [add_monoid M₁] [add_comm_group M₂] (n : ℤ) (f : M₁ →+ M₂) : ⇑(n •ℤ f) = n •ℤ (f : M₁ → M₂) := begin apply int.induction_on n, { simp only [zero_gsmul, add_monoid_hom.coe_zero] }, { simp only [add_monoid_hom.coe_nsmul, gsmul_coe_nat, add_gsmul, forall_const, one_gsmul, eq_self_iff_true, add_monoid_hom.coe_add] }, { simp only [forall_prop_of_true, gsmul_coe_nat, sub_gsmul, neg_gsmul, one_gsmul, neg_gsmul, add_monoid_hom.coe_neg, add_monoid_hom.coe_nsmul, add_monoid_hom.coe_sub, eq_self_iff_true, forall_const] } end end for_mathlib /-- See top of p66 in [Analytic.pdf]. -/ class pseudo_normed_group (M : Type*) := [to_add_comm_group : add_comm_group M] (filtration [] : ℝ≥0 → set M) (filtration_mono : ∀ ⦃c₁ c₂⦄, c₁ ≤ c₂ → filtration c₁ ⊆ filtration c₂) (zero_mem_filtration : ∀ c, (0:M) ∈ filtration c) (neg_mem_filtration : ∀ ⦃c x⦄, x ∈ filtration c → (-x) ∈ filtration c) (add_mem_filtration : ∀ ⦃c₁ c₂ x₁ x₂⦄, x₁ ∈ filtration c₁ → x₂ ∈ filtration c₂ → x₁ + x₂ ∈ filtration (c₁ + c₂)) open function class pseudo_normed_group' (B_ : ℝ≥0 → Type*) (M : out_param Type*) := [to_add_comm_group : add_comm_group M] [has_zero : Π r, has_zero (B_ r)] [has_neg : Π r, has_neg (B_ r)] (map : ∀ ⦃c₁ c₂⦄, c₁ ≤ c₂ → B_ c₁ → B_ c₂) -- rename (incl : ∀ c, B_ c → M) (incl_injective : ∀ c, injective (incl c)) (incl_zero : ∀ c, incl c 0 = 0) (incl_neg : ∀ {c} (f : B_ c), incl c (-f) = - (incl c f)) (incl_map : ∀ {c₁ c₂} (h : c₁ ≤ c₂), (incl c₂) ∘ (map h) = (incl c₁)) (B_add {c₁ c₂} : B_ c₁ → B_ c₂ → B_ (c₁ + c₂)) (incl_add {c₁ c₂} (f : B_ c₁) (g : B_ c₂) : incl _ (B_add f g) = incl _ f + incl _ g) (map_refl {c} : map (le_refl c) = id) (map_trans {c₁ c₂ c₃} (h1 : c₁ ≤ c₂) (h2 : c₂ ≤ c₃) : map (h1.trans h2) = map h2 ∘ map h1) /- class topological_pseudo_normed_group' (B_ : ℝ≥0 → Type*) (M : Type*) extends pseudo_normed_group' B_ M := [is_top_space : Π r, topological_space (B_ r)] -/ /- Thought by Johan: Maybe we want both defintions above, and write a bit of glue to move between them. Both seem useful for different bits of what we want to do. -/ attribute [instance] pseudo_normed_group.to_add_comm_group namespace pseudo_normed_group variables {M : Type*} [pseudo_normed_group M] lemma sub_mem_filtration ⦃c₁ c₂ x₁ x₂⦄ (h₁ : x₁ ∈ filtration M c₁) (h₂ : x₂ ∈ filtration M c₂) : x₁ - x₂ ∈ filtration M (c₁ + c₂) := by { rw [sub_eq_add_neg], exact add_mem_filtration h₁ (neg_mem_filtration h₂) } lemma neg_mem_filtration_iff (c x) : -x ∈ filtration M c ↔ x ∈ filtration M c := ⟨λ h, by { rw [← neg_neg x], exact neg_mem_filtration h }, λ h, neg_mem_filtration h⟩ lemma sum_mem_filtration {ι : Type*} (x : ι → M) (c : ι → ℝ≥0) (s : finset ι) (h : ∀ i ∈ s, x i ∈ filtration M (c i)) : (∑ i in s, x i) ∈ filtration M (∑ i in s, (c i)) := begin classical, revert h, apply finset.induction_on s; clear s, { intro, simpa only [finset.sum_empty] using zero_mem_filtration _ }, { intros i s his IH h, rw [finset.sum_insert his, finset.sum_insert his], apply add_mem_filtration (h _ _) (IH _), { exact finset.mem_insert_self i s }, { intros j hj, apply h, exact finset.mem_insert_of_mem hj } } end lemma smul_nat_mem_filtration (n : ℕ) (x : M) (c : ℝ≥0) (hx : x ∈ filtration M c) : n • x ∈ filtration M (n * c) := begin induction n with n ih, { simpa only [nat.cast_zero, zero_mul, zero_smul] using zero_mem_filtration _ }, { simp only [nat.succ_eq_add_one, add_smul, one_smul, nat.cast_succ, add_mul, one_mul], exact add_mem_filtration ih hx } end lemma smul_int_mem_filtration (n : ℤ) (x : M) (c : ℝ≥0) (hx : x ∈ filtration M c) : n • x ∈ filtration M (n.nat_abs * c) := begin induction n with n n, { exact smul_nat_mem_filtration n x c hx }, { rw [int.nat_abs_of_neg_succ_of_nat, int.neg_succ_of_nat_coe, neg_smul, neg_mem_filtration_iff], exact smul_nat_mem_filtration _ _ _ hx } end instance pi {ι : Type*} (M : ι → Type*) [Π i, pseudo_normed_group (M i)] : pseudo_normed_group (Π i, M i) := { filtration := λ c, { x | ∀ i, x i ∈ filtration (M i) c }, -- TODO: check with Peter filtration_mono := λ c₁ c₂ h x hx i, filtration_mono h (hx i), zero_mem_filtration := λ c i, zero_mem_filtration _, neg_mem_filtration := λ c x h i, neg_mem_filtration (h i), add_mem_filtration := λ c₁ c₂ x₁ x₂ h₁ h₂ i, add_mem_filtration (h₁ i) (h₂ i) } lemma mem_filtration_pi {ι : Type*} (M : ι → Type*) [Π i, pseudo_normed_group (M i)] (c : ℝ≥0) (x : Π i, M i) : x ∈ filtration (Π i, M i) c ↔ ∀ i, x i ∈ filtration (M i) c := iff.rfl end pseudo_normed_group open pseudo_normed_group namespace add_monoid_hom variables {M M₁ M₂ M₃ : Type*} variables [pseudo_normed_group M] [pseudo_normed_group M₁] variables [pseudo_normed_group M₂] [pseudo_normed_group M₃] instance : pseudo_normed_group (M₁ →+ M₂) := { filtration := λ N, { f | ∀ ⦃c⦄ ⦃x : M₁⦄, x ∈ filtration M₁ c → f x ∈ filtration M₂ (N * c) }, filtration_mono := λ N₁ N₂ h f hf c x hx, filtration_mono (mul_le_mul_right' h c) (hf hx), zero_mem_filtration := λ N c x hx, zero_mem_filtration _, neg_mem_filtration := λ N f hf c x hx, neg_mem_filtration $ hf hx, add_mem_filtration := λ N₁ N₂ f₁ f₂ hf₁ hf₂ c x hx, by { rw add_mul, apply add_mem_filtration (hf₁ hx) (hf₂ hx) }, .. add_monoid_hom.add_comm_group } lemma comp_mem_filtration {g f cg cf} (hg : g ∈ filtration (M₂ →+ M₃) cg) (hf : f ∈ filtration (M₁ →+ M₂) cf) : g.comp f ∈ filtration (M₁ →+ M₃) (cg * cf) := λ c x hx, by { rw mul_assoc, exact hg (hf hx) } @[simp] lemma id_mem_filtration (c : ℝ≥0) (hc : 1 ≤ c) : id M ∈ filtration (M →+ M) c := λ c' x hx, by refine filtration_mono _ hx; calc c' = 1 * c' : by rw one_mul ... ≤ c * c' : mul_le_mul_right' hc c' -- move this, maybe it already exists? @[simps {rhs_md:=semireducible, fully_applied:=ff}] def mk_to_pi {M₁} [add_monoid M₁] {ι : Type*} {M : ι → Type*} [Π i, add_monoid (M i)] (f : Π i, M₁ →+ (M i)) : M₁ →+ (Π i, M i) := { to_fun := λ v i, f i v, map_zero' := by { simp only [map_zero], refl }, map_add' := by { intros, simp only [map_add], refl } } lemma mk_to_pi_mem_filtration {ι : Type*} {M : ι → Type*} [Π i, pseudo_normed_group (M i)] (f : Π i, M₁ →+ (M i)) {c} (hfc : ∀ i, f i ∈ filtration (M₁ →+ (M i)) c) : mk_to_pi f ∈ filtration (M₁ →+ (Π i, M i)) c := λ c' x h i, hfc i h lemma apply_mem_filtration {ι : Type*} (M : ι → Type*) [Π i, pseudo_normed_group (M i)] (i : ι) (c : ℝ≥0) (hc : 1 ≤ c) : (apply M i) ∈ filtration ((Π i, M i) →+ M i) c := λ c' x hx, by refine filtration_mono _ (hx i); calc c' = 1 * c' : by rw one_mul ... ≤ c * c' : mul_le_mul_right' hc c' def mk_from_pi {ι : Type*} [fintype ι] {M : ι → Type*} {M₂} [Π i, add_monoid (M i)] [add_comm_monoid M₂] (f : Π i, (M i) →+ M₂) : (Π i, M i) →+ M₂ := ∑ i, (f i).comp (apply M i) @[simp] lemma mk_from_pi_apply {ι : Type*} [fintype ι] {M : ι → Type*} [Π i, add_comm_monoid (M i)] (f : Π i, M i →+ M₂) (x : Π i, M i) : mk_from_pi f x = (∑ i, f i (x i)) := begin show add_monoid_hom.eval x (mk_from_pi f) = _, simp only [mk_from_pi, add_monoid_hom.map_sum], refl end @[simp] lemma coe_mk_from_pi {ι : Type*} [fintype ι] {M : ι → Type*} [Π i, add_comm_monoid (M i)] (f : Π i, M i →+ M₂) : ⇑(mk_from_pi f) = ∑ i, (f i ∘ apply M i) := by { ext x, rw [@mk_from_pi_apply M₂ _ ι _ M _ f x, fintype.sum_apply], refl } lemma mk_from_pi_mem_filtration {ι : Type*} [fintype ι] {M : ι → Type*} [Π i, pseudo_normed_group (M i)] (f : Π i, (M i) →+ M₂) {c : ι → ℝ≥0} (hfc : ∀ i, f i ∈ filtration ((M i) →+ M₂) (c i)) : (mk_from_pi f) ∈ filtration ((Π i, M i) →+ M₂) (∑ i, c i) := λ c' x h, begin rw [finset.sum_mul, @mk_from_pi_apply M₂ _ ι _ M _ f x], refine sum_mem_filtration _ _ _ _, rintro i -, exact hfc i (h i) end lemma const_smul_hom_nat_mem_filtration (n : ℕ) (c : ℝ≥0) (h : ↑n ≤ c) : const_smul_hom M n ∈ filtration (M →+ M) c := λ c' x hx, by simpa only [const_smul_hom_apply] using filtration_mono (mul_le_mul_right' h c') (smul_nat_mem_filtration _ _ _ hx) lemma const_smul_hom_int_mem_filtration (n : ℤ) (c : ℝ≥0) (h : ↑(n.nat_abs) ≤ c) : const_smul_hom M n ∈ filtration (M →+ M) c := λ c' x hx, by simpa only [const_smul_hom_apply] using filtration_mono (mul_le_mul_right' h c') (smul_int_mem_filtration _ _ _ hx) end add_monoid_hom
7e998acd2d28fb1ed924509f8576ee375461156e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/nested_inductive_sizeof.lean
8bd72957b62185f2113ede26c4ab541d43eb2063
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,303
lean
set_option trace.inductive_compiler.nested.define.failure true set_option max_memory 1000000 inductive {u} vec (A : Type u) : nat -> Type u | vnil : vec 0 | vcons : Pi (n : nat), A -> vec n -> vec (n+1) namespace X6 #print "locals + nested-reflexive locals in indices" inductive {u} foo (A : Type u) : Type u | mk : Pi (n : nat), A -> (Pi (m : nat), vec foo (n + m)) -> foo #check foo.sizeof #check foo.mk.sizeof_spec end X6 namespace X8 #print "many different nestings, some sharing" inductive {u} foo (A : Type u) : Type u | mk₁ : Pi (n : nat), A -> (Pi (m : nat), vec (list foo) (n + m)) -> vec foo n -> foo | mk₂ : Pi (n : nat), A -> list A -> prod A A -> (Pi (m : nat), vec foo (n + m)) -> vec foo n -> foo #check foo.sizeof #check foo.mk₁.sizeof_spec #check foo.mk₂.sizeof_spec end X8 namespace X9b #print "mutual + nesting" mutual inductive {u} foo, bar with foo : Type u | mk : list (list foo) -> foo with bar : Type u | mk : list foo -> bar #check foo.sizeof #check foo.mk.sizeof_spec #check bar.sizeof #check bar.mk.sizeof_spec end X9b namespace X11 #print "intro rule that introduces additional nesting" inductive {u} wrap (A : Type u) : Type u | mk : list A -> wrap inductive {u} foo : Type u | mk : wrap foo -> foo #check foo.sizeof #check foo.mk.sizeof_spec end X11
4ef63e40007d09865fa70dd789d366ddd9c9933c
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/subtype.lean
5dd326422b4cb4b3e71920d0767656f43dc02ba1
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
8,194
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import logic.function.basic import tactic.ext import tactic.simps /-! # Subtypes > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides basic API for subtypes, which are defined in core. A subtype is a type made from restricting another type, say `α`, to its elements that satisfy some predicate, say `p : α → Prop`. Specifically, it is the type of pairs `⟨val, property⟩` where `val : α` and `property : p val`. It is denoted `subtype p` and notation `{val : α // p val}` is available. A subtype has a natural coercion to the parent type, by coercing `⟨val, property⟩` to `val`. As such, subtypes can be thought of as bundled sets, the difference being that elements of a set are still of type `α` while elements of a subtype aren't. -/ open function namespace subtype variables {α β γ : Sort*} {p q : α → Prop} /-- See Note [custom simps projection] -/ def simps.coe (x : subtype p) : α := x initialize_simps_projections subtype (val → coe) /-- A version of `x.property` or `x.2` where `p` is syntactically applied to the coercion of `x` instead of `x.1`. A similar result is `subtype.mem` in `data.set.basic`. -/ lemma prop (x : subtype p) : p x := x.2 @[simp] lemma val_eq_coe {x : subtype p} : x.1 = ↑x := rfl @[simp] protected theorem «forall» {q : {a // p a} → Prop} : (∀ x, q x) ↔ (∀ a b, q ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ /-- An alternative version of `subtype.forall`. This one is useful if Lean cannot figure out `q` when using `subtype.forall` from right to left. -/ protected theorem forall' {q : ∀ x, p x → Prop} : (∀ x h, q x h) ↔ (∀ x : {a // p a}, q x x.2) := (@subtype.forall _ _ (λ x, q x.1 x.2)).symm @[simp] protected theorem «exists» {q : {a // p a} → Prop} : (∃ x, q x) ↔ (∃ a b, q ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ /-- An alternative version of `subtype.exists`. This one is useful if Lean cannot figure out `q` when using `subtype.exists` from right to left. -/ protected theorem exists' {q : ∀x, p x → Prop} : (∃ x h, q x h) ↔ (∃ x : {a // p a}, q x x.2) := (@subtype.exists _ _ (λ x, q x.1 x.2)).symm @[ext] protected lemma ext : ∀ {a1 a2 : {x // p x}}, (a1 : α) = (a2 : α) → a1 = a2 | ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl lemma ext_iff {a1 a2 : {x // p x}} : a1 = a2 ↔ (a1 : α) = (a2 : α) := ⟨congr_arg _, subtype.ext⟩ lemma heq_iff_coe_eq (h : ∀ x, p x ↔ q x) {a1 : {x // p x}} {a2 : {x // q x}} : a1 == a2 ↔ (a1 : α) = (a2 : α) := eq.rec (λ a2', heq_iff_eq.trans ext_iff) (funext $ λ x, propext (h x)) a2 lemma heq_iff_coe_heq {α β : Sort*} {p : α → Prop} {q : β → Prop} {a : {x // p x}} {b : {y // q y}} (h : α = β) (h' : p == q) : a == b ↔ (a : α) == (b : β) := by { subst h, subst h', rw [heq_iff_eq, heq_iff_eq, ext_iff] } lemma ext_val {a1 a2 : {x // p x}} : a1.1 = a2.1 → a1 = a2 := subtype.ext lemma ext_iff_val {a1 a2 : {x // p x}} : a1 = a2 ↔ a1.1 = a2.1 := ext_iff @[simp] theorem coe_eta (a : {a // p a}) (h : p a) : mk ↑a h = a := subtype.ext rfl @[simp] theorem coe_mk (a h) : (@mk α p a h : α) = a := rfl @[simp, nolint simp_nf] -- built-in reduction doesn't always work theorem mk_eq_mk {a h a' h'} : @mk α p a h = @mk α p a' h' ↔ a = a' := ext_iff lemma coe_eq_of_eq_mk {a : {a // p a}} {b : α} (h : ↑a = b) : a = ⟨b, h ▸ a.2⟩ := subtype.ext h theorem coe_eq_iff {a : {a // p a}} {b : α} : ↑a = b ↔ ∃ h, a = ⟨b, h⟩ := ⟨λ h, h ▸ ⟨a.2, (coe_eta _ _).symm⟩, λ ⟨hb, ha⟩, ha.symm ▸ rfl⟩ lemma coe_injective : injective (coe : subtype p → α) := λ a b, subtype.ext lemma val_injective : injective (@val _ p) := coe_injective lemma coe_inj {a b : subtype p} : (a : α) = b ↔ a = b := coe_injective.eq_iff lemma val_inj {a b : subtype p} : a.val = b.val ↔ a = b := coe_inj @[simp] lemma _root_.exists_eq_subtype_mk_iff {a : subtype p} {b : α} : (∃ h : p b, a = subtype.mk b h) ↔ ↑a = b := coe_eq_iff.symm @[simp] lemma _root_.exists_subtype_mk_eq_iff {a : subtype p} {b : α} : (∃ h : p b, subtype.mk b h = a) ↔ b = a := by simp only [@eq_comm _ b, exists_eq_subtype_mk_iff, @eq_comm _ _ a] /-- Restrict a (dependent) function to a subtype -/ def restrict {α} {β : α → Type*} (p : α → Prop) (f : Π x, β x) (x : subtype p) : β x.1 := f x lemma restrict_apply {α} {β : α → Type*} (f : Π x, β x) (p : α → Prop) (x : subtype p) : restrict p f x = f x.1 := by refl lemma restrict_def {α β} (f : α → β) (p : α → Prop) : restrict p f = f ∘ coe := by refl lemma restrict_injective {α β} {f : α → β} (p : α → Prop) (h : injective f) : injective (restrict p f) := h.comp coe_injective lemma surjective_restrict {α} {β : α → Type*} [ne : Π a, nonempty (β a)] (p : α → Prop) : surjective (λ f : Π x, β x, restrict p f) := begin letI := classical.dec_pred p, refine λ f, ⟨λ x, if h : p x then f ⟨x, h⟩ else nonempty.some (ne x), funext $ _⟩, rintro ⟨x, hx⟩, exact dif_pos hx end /-- Defining a map into a subtype, this can be seen as an "coinduction principle" of `subtype`-/ @[simps] def coind {α β} (f : α → β) {p : β → Prop} (h : ∀ a, p (f a)) : α → subtype p := λ a, ⟨f a, h a⟩ theorem coind_injective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a)) (hf : injective f) : injective (coind f h) := λ x y hxy, hf $ by apply congr_arg subtype.val hxy theorem coind_surjective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a)) (hf : surjective f) : surjective (coind f h) := λ x, let ⟨a, ha⟩ := hf x in ⟨a, coe_injective ha⟩ theorem coind_bijective {α β} {f : α → β} {p : β → Prop} (h : ∀ a, p (f a)) (hf : bijective f) : bijective (coind f h) := ⟨coind_injective h hf.1, coind_surjective h hf.2⟩ /-- Restriction of a function to a function on subtypes. -/ @[simps] def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀ a, p a → q (f a)) : subtype p → subtype q := λ x, ⟨f x, h x x.prop⟩ theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p} (f : α → β) (h : ∀ a, p a → q (f a)) (g : β → γ) (l : ∀ a, q a → r (g a)) : map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x := rfl theorem map_id {p : α → Prop} {h : ∀ a, p a → p (id a)} : map (@id α) h = id := funext $ assume ⟨v, h⟩, rfl lemma map_injective {p : α → Prop} {q : β → Prop} {f : α → β} (h : ∀ a, p a → q (f a)) (hf : injective f) : injective (map f h) := coind_injective _ $ hf.comp coe_injective lemma map_involutive {p : α → Prop} {f : α → α} (h : ∀ a, p a → p (f a)) (hf : involutive f) : involutive (map f h) := λ x, subtype.ext (hf x) instance [has_equiv α] (p : α → Prop) : has_equiv (subtype p) := ⟨λ s t, (s : α) ≈ (t : α)⟩ theorem equiv_iff [has_equiv α] {p : α → Prop} {s t : subtype p} : s ≈ t ↔ (s : α) ≈ (t : α) := iff.rfl variables [setoid α] protected theorem refl (s : subtype p) : s ≈ s := setoid.refl ↑s protected theorem symm {s t : subtype p} (h : s ≈ t) : t ≈ s := setoid.symm h protected theorem trans {s t u : subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u := setoid.trans h₁ h₂ theorem equivalence (p : α → Prop) : equivalence (@has_equiv.equiv (subtype p) _) := mk_equivalence _ subtype.refl (@subtype.symm _ p _) (@subtype.trans _ p _) instance (p : α → Prop) : setoid (subtype p) := setoid.mk (≈) (equivalence p) end subtype namespace subtype /-! Some facts about sets, which require that `α` is a type. -/ variables {α β γ : Type*} {p : α → Prop} @[simp] lemma coe_prop {S : set α} (a : {a // a ∈ S}) : ↑a ∈ S := a.prop lemma val_prop {S : set α} (a : {a // a ∈ S}) : a.val ∈ S := a.property end subtype
0f41a401002e0c719ea43f612ccabca068cfa160
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/computability/primrec.lean
f67742e7b230c3dd9ac2faab416bbc0fb804dadd
[ "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
52,141
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 data.list.join import logic.equiv.list import logic.function.iterate /-! # The primitive recursive functions The primitive recursive functions are the least collection of functions `nat → nat` which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open denumerable encodable function namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ, add_comm] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, pow_succ'] end primrec end nat /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim [] : nat.primrec (λ n, encodable.encode (decode n))) namespace primcodable open nat.primrec @[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := by letI : primcodable β := primcodable.of_equiv α e; exact encode_iff.1 primrec.encode theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1, { simp }, cases decode β n.unpair.2; simp end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, function.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ @default α _) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem option_get_or_else : primrec₂ (@option.get_or_else α) := primrec.of_eq (option_cases primrec₂.left primrec₂.right primrec₂.right) $ λ ⟨o, a⟩, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [swap], cases e : p.1 - p.2 with n, { simp [tsub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite (nat_le.comp primrec.snd primrec.fst) fst snd theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode₂ : primrec (decode₂ α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := finite.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := (G a)^[n] (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_le (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, { simp }, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_right_le n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_nthd (d : α) : primrec₂ (list.nthd d) := begin suffices : list.nthd d = λ l n, (list.nth l n).get_or_else d, { rw this, exact option_get_or_else.comp₂ list_nth (const _) }, funext, exact list.nthd_eq_get_or_else_nth _ _ _ end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := list_nthd _ theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_succ]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, simp [*, list.find_index]] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_succ] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) (equiv.refl _) instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) section ulower local attribute [instance, priority 100] encodable.decidable_range_encode encodable.decidable_eq_of_encodable instance ulower : primcodable (ulower α) := have primrec_pred (λ n, encodable.decode₂ α n ≠ none), from primrec.not (primrec.eq.comp (primrec.option_bind primrec.decode (primrec.ite (primrec.eq.comp (primrec.encode.comp primrec.snd) primrec.fst) (primrec.option_some.comp primrec.snd) (primrec.const _))) (primrec.const _)), primcodable.subtype $ primrec_pred.of_eq this (λ n, decode₂_ne_none_iff) end ulower end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem subtype_mk {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → β} {h : ∀ a, p (f a)} (hf : primrec f) : by haveI := primcodable.subtype hp; exact primrec (λ a, @subtype.mk β p (f a) (h a)) := subtype_val_iff.1 hf theorem option_get {f : α → option β} {h : ∀ a, (f a).is_some} : primrec f → primrec (λ a, option.get (h a)) := begin intro hf, refine (nat.primrec.pred.comp hf).of_eq (λ n, _), generalize hx : decode α n = x, cases x; simp end theorem ulower_down : primrec (ulower.down : α → ulower α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact subtype_mk primrec.encode theorem ulower_up : primrec (ulower.up : ulower α → α) := by letI : ∀ a, decidable (a ∈ set.range (encode : α → ℕ)) := decidable_range_encode _; exact option_get (primrec.decode₂.comp subtype_val) theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (coe : fin n → ℕ) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y ::ᵥ IH ::ᵥ v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' n f) (hg : @vec n m g) : vec (λ v, (f v ::ᵥ g v)) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y ::ᵥ IH ::ᵥ v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (tsub_eq_zero_iff_le.mp e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {simp}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
d3278d545ede8f9a93995dd269bee70ea437781c
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/algebra/lattice/zorn.lean
ee648c70b70b956e3b6a69fc23f308cb143a7e4e
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
8,711
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 Zorn's lemmas. Ported from Isabelle/HOL (written by Jacques D. Fleuriot, Tobias Nipkow, and Christian Sternagel). -/ import ...data.set noncomputable theory universes u open set classical local attribute [instance] decidable_inhabited local attribute [instance] prop_decidable namespace zorn section chain parameters {α : Type u} {r : α → α → Prop} local infix ` ≺ `:50 := r def chain (c : set α) := pairwise_on c (λx y, x ≺ y ∨ y ≺ x) lemma chain_insert {c : set α} {a : α} (hc : chain c) (ha : ∀b∈c, b ≠ a → a ≺ b ∨ b ≺ a) : chain (insert a c) := forall_insert_of_forall (assume x hx, forall_insert_of_forall (hc x hx) (assume hneq, (ha x hx hneq).symm)) (forall_insert_of_forall (assume x hx hneq, ha x hx $ assume h', hneq h'.symm) (assume h, (h rfl).rec _)) def super_chain (c₁ c₂ : set α) := chain c₂ ∧ c₁ ⊂ c₂ def is_max_chain (c : set α) := chain c ∧ ¬ (∃c', super_chain c c') def succ_chain (c : set α) := if h : ∃c', chain c ∧ super_chain c c' then some h else c lemma succ_spec {c : set α} (h : ∃c', chain c ∧ super_chain c c') : super_chain c (succ_chain c) := let ⟨c', hc'⟩ := h in have chain c ∧ super_chain c (some h), from @some_spec _ (λc', chain c ∧ super_chain c c') _, by simp [succ_chain, dif_pos, h, this.right] lemma chain_succ {c : set α} (hc : chain c) : chain (succ_chain c) := if h : ∃c', chain c ∧ super_chain c c' then (succ_spec h).left else by simp [succ_chain, dif_neg, h]; exact hc lemma super_of_not_max {c : set α} (hc₁ : chain c) (hc₂ : ¬ is_max_chain c) : super_chain c (succ_chain c) := begin simp [is_max_chain, not_and_iff, not_not_iff] at hc₂, exact have ∃c', super_chain c c', from hc₂.neg_resolve_left hc₁, let ⟨c', hc'⟩ := this in show super_chain c (succ_chain c), from succ_spec ⟨c', hc₁, hc'⟩ end lemma succ_increasing {c : set α} : c ⊆ succ_chain c := if h : ∃c', chain c ∧ super_chain c c' then have super_chain c (succ_chain c), from succ_spec h, this.right.left else by simp [succ_chain, dif_neg, h, subset.refl] inductive chain_closure : set α → Prop | succ : ∀{s}, chain_closure s → chain_closure (succ_chain s) | union : ∀{s}, (∀a∈s, chain_closure a) → chain_closure (⋃₀ s) lemma chain_closure_empty : chain_closure ∅ := have chain_closure (⋃₀ ∅), from chain_closure.union $ assume a h, h.rec _, by simp at this; assumption lemma chain_closure_closure : chain_closure (⋃₀ {s | chain_closure s}) := chain_closure.union $ assume s hs, hs variables {c c₁ c₂ c₃ : set α} private lemma chain_closure_succ_total_aux (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : ∀{c₃}, chain_closure c₃ → c₃ ⊆ c₂ → c₂ = c₃ ∨ succ_chain c₃ ⊆ c₂) : c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁ := begin induction hc₁, case _root_.zorn.chain_closure.succ c₃ hc₃ ih { cases ih with ih ih, { have h := h hc₃ ih, cases h with h h, { exact (or.inr $ h ▸ subset.refl _) }, { exact (or.inl h) } }, { exact (or.inr $ subset.trans ih succ_increasing) } }, case _root_.zorn.chain_closure.union s hs ih { exact (or_of_not_implies $ assume hn, sUnion_subset $ assume a ha, have a ⊆ c₂ ∨ succ_chain c₂ ⊆ a, from ih a ha, this.resolve_right $ assume h, hn $ subset.trans h $ subset_sUnion_of_mem ha) } end private lemma chain_closure_succ_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h : c₁ ⊆ c₂) : c₂ = c₁ ∨ succ_chain c₁ ⊆ c₂ := begin induction hc₂ generalizing c₁ hc₁ h, case _root_.zorn.chain_closure.succ c₂ hc₂ ih { have h₁ : c₁ ⊆ c₂ ∨ @succ_chain α r c₂ ⊆ c₁ := (chain_closure_succ_total_aux hc₁ hc₂ $ assume c₁, ih), cases h₁ with h₁ h₁, { have h₂ := ih hc₁ h₁, cases h₂ with h₂ h₂, { exact (or.inr $ h₂ ▸ subset.refl _) }, { exact (or.inr $ subset.trans h₂ succ_increasing) } }, { exact (or.inl $ subset.antisymm h₁ h) } }, case _root_.zorn.chain_closure.union s hs ih { apply or.imp (assume h', subset.antisymm h' h) id, apply classical.by_contradiction, simp [not_or_iff, sUnion_subset_iff, not_forall_iff_exists_not, not_implies_iff_and_not], intro h, cases h with h₁ h₂, cases h₂ with c₃ h₂, cases h₂ with h₂ hc₃, have h := chain_closure_succ_total_aux hc₁ (hs c₃ hc₃) (assume c₄, ih _ hc₃), cases h with h h, { have h' := ih c₃ hc₃ hc₁ h, cases h' with h' h', { exact (h₂ $ h' ▸ subset.refl _) }, { exact (h₁ $ subset.trans h' $ subset_sUnion_of_mem hc₃) } }, { exact (h₂ $ subset.trans succ_increasing h) } } end lemma chain_closure_total (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) : c₁ ⊆ c₂ ∨ c₂ ⊆ c₁ := have c₁ ⊆ c₂ ∨ succ_chain c₂ ⊆ c₁, from chain_closure_succ_total_aux hc₁ hc₂ $ assume c₃ hc₃, chain_closure_succ_total hc₃ hc₂, or.imp_right (assume : succ_chain c₂ ⊆ c₁, subset.trans succ_increasing this) this lemma chain_closure_succ_fixpoint (hc₁ : chain_closure c₁) (hc₂ : chain_closure c₂) (h_eq : succ_chain c₂ = c₂) : c₁ ⊆ c₂ := begin induction hc₁, case _root_.zorn.chain_closure.succ c₁ hc₁ h { exact or.elim (chain_closure_succ_total hc₁ hc₂ h) (assume h, h ▸ h_eq.symm ▸ subset.refl c₂) id }, case _root_.zorn.chain_closure.union s hs ih { exact (sUnion_subset $ assume c₁ hc₁, ih c₁ hc₁) } end lemma chain_closure_succ_fixpoint_iff (hc : chain_closure c) : succ_chain c = c ↔ c = ⋃₀ {c | chain_closure c} := ⟨assume h, subset.antisymm (subset_sUnion_of_mem hc) (chain_closure_succ_fixpoint chain_closure_closure hc h), assume : c = ⋃₀{c : set α | chain_closure c}, subset.antisymm (calc succ_chain c ⊆ ⋃₀{c : set α | chain_closure c} : subset_sUnion_of_mem $ chain_closure.succ hc ... = c : this.symm) succ_increasing⟩ lemma chain_chain_closure (hc : chain_closure c) : chain c := begin induction hc, case _root_.zorn.chain_closure.succ c hc h { exact chain_succ h }, case _root_.zorn.chain_closure.union s hs h { have h : ∀c∈s, zorn.chain c := h, exact assume c₁ ⟨t₁, ht₁, (hc₁ : c₁ ∈ t₁)⟩ c₂ ⟨t₂, ht₂, (hc₂ : c₂ ∈ t₂)⟩ hneq, have t₁ ⊆ t₂ ∨ t₂ ⊆ t₁, from chain_closure_total (hs _ ht₁) (hs _ ht₂), or.elim this (assume : t₁ ⊆ t₂, h t₂ ht₂ c₁ (this hc₁) c₂ hc₂ hneq) (assume : t₂ ⊆ t₁, h t₁ ht₁ c₁ hc₁ c₂ (this hc₂) hneq) } end def max_chain := (⋃₀ {c | chain_closure c}) /-- Hausdorff's maximality principle There exists a maximal totally ordered subset of `α`. Note that we do not require `α` to be partially ordered by `r`. -/ lemma max_chain_spec : is_max_chain max_chain := classical.by_contradiction $ assume : ¬ is_max_chain (⋃₀ {c | chain_closure c}), have super_chain (⋃₀ {c | chain_closure c}) (succ_chain (⋃₀ {c | chain_closure c})), from super_of_not_max (chain_chain_closure chain_closure_closure) this, let ⟨h₁, h₂, (h₃ : (⋃₀ {c | chain_closure c}) ≠ succ_chain (⋃₀ {c | chain_closure c}))⟩ := this in have succ_chain (⋃₀ {c | chain_closure c}) = (⋃₀ {c | chain_closure c}), from (chain_closure_succ_fixpoint_iff chain_closure_closure).mpr rfl, h₃ this.symm /-- Zorn's lemma If every chain has an upper bound, then there is a maximal element -/ lemma zorn (h : ∀c, chain c → ∃ub, ∀a∈c, a ≺ ub) (trans : ∀{a b c}, a ≺ b → b ≺ c → a ≺ c) : ∃m, ∀a, m ≺ a → a ≺ m := have ∃ub, ∀a∈max_chain, a ≺ ub, from h _ $ max_chain_spec.left, let ⟨ub, (hub : ∀a∈max_chain, a ≺ ub)⟩ := this in ⟨ub, assume a ha, have chain (insert a max_chain), from chain_insert max_chain_spec.left $ assume b hb _, or.inr $ trans (hub b hb) ha, have a ∈ max_chain, from classical.by_contradiction $ assume h : a ∉ max_chain, max_chain_spec.right $ ⟨insert a max_chain, this, ssubset_insert h⟩, hub a this⟩ end chain lemma zorn_weak_order {α : Type u} [weak_order α] (h : ∀c:set α, @chain α (≤) c → ∃ub, ∀a∈c, a ≤ ub) : ∃m:α, ∀a, m ≤ a → a = m := let ⟨m, hm⟩ := @zorn α (≤) h (assume a b c, le_trans) in ⟨m, assume a ha, le_antisymm (hm a ha) ha⟩ end zorn
e726a74d2d5f8b663a3a1aa5d1a822037e695b8d
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/1011.lean
4c5357e34709bacc8d3f61fe9ce6a219ad05ff31
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
77
lean
def f (x : A) := x set_option relaxedAutoImplicit false def g (x : A) := x