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
7f4593c1d54d9c98dfe7616fa2bc5dc0dd01e371
2f2aa789c57653a0a047d209e0401875a9427cfc
/src/instructor/lectures/lecture_9.lean
5184668fed699a1f595425067094bf4ae0225f56
[]
no_license
AlexFetea/cs2120f21
dc288aa4a907b116555758b7f63c37aa14f952ae
a2cf406a33e66aac2287341b1c3e9954db9b36ab
refs/heads/main
1,693,910,053,038
1,636,678,382,000
1,636,678,382,000
399,946,831
0
0
null
null
null
null
UTF-8
Lean
false
false
3,698
lean
/- Negation -/ /- Given an proposition, P, we can form a new proposition, usually written as ¬P, which we pronounce as "not P," and which we define in such as way as to assert that P is not true. -/ /- So what does it mean when we say that *it is true that P is not true*? -/ /- First, if ¬P is true, there should be a proof of it. Second, what that proof should show is that *there can be no proof of P*. -/ /- So the way we're going to say ¬P is to say if P were true then something that is completely impossible would happen. Because the impossible cannot happen, therefore there must be no proof of P. -/ /- What we're going take as "the impossible thing" is that there is a proof of false. Have defined false to be exactly a proposition with no proofs (otherwise it'd be true), so to have a proof of false is an impossibility.) -/ example : false → false := begin assume f, exact f, end example : false → true := begin assume f, exact true.intro, end example : true → true := begin assume t, exact true.intro, end example : true → false := begin assume t, -- stuck end /- It's this analysis that leads to the definition of ¬P. For any proposition P, we *define* ¬P to be the proposition, P → false. What this means is that if there is a proof of P → false, then you can conclude (by definition) ¬P. This is the introduction rule for ¬. -/ #check not -- see definition in Lean library /- So how do you prove P → false? It's just like any other implication: *assume* that P is true and show that with that you can construct a proof of false. -/ /- Example. Prove ¬ 0 = 1. -/ example : false := begin end example : ¬ false := begin assume f, exact f, end example : ¬ (0 = 1) := begin assume h, end /- To understand how to finish off this last proof, we need to talk more case analysis again. Remember that we've used it to reason from a proof of a disjunction. Suppose we want to know that P ∨ Q → R. We start by assuming that we have a proof, pq, of P ∨ Q, and then we need to show that R follows as a logical consequence. But there are exactly two possible forms that a proof of P ∨ Q can take (or.intro_left p) and (or.intro_right q), where p and q are proofs of P and of Q, respectively. What we therefore need to show is that no matter which of those two forms of proof we have, of P ∨ Q, that the truth of R follows. So we do a case analysis on pq. In the first case, we assume P ∨ Q is true because P is (or.intro_left was used to create the proof). In this case we need to show that P → R. In the second case, where P ∨ Q is true because Q is (or.intro_right was used to create the proof of P ∨ Q), we need to show that Q → R. The general principle is that if you can show that a proposition, R, is true no matter which form of proof you have of some proposition, X, then you have proven that X → R. This is the key idea behind *proof by case analysis*. Show that given any possible proof of P, that Q follows, and that's what gives you a proof of P → Q. A good start is to know just how many cases you have to consider! Given proof of P ∨ Q, how many cases are there? Two. -/ example : ∀ (P Q R : Prop), P ∨ Q → R := begin assume P Q R, assume pq, cases pq, -- or elimination -- stuck here of course end example : true → true := begin assume t, cases t, end example : ¬(0 = 1) := begin assume h, cases h, end example : false → false := begin assume f, cases f, end example : false → false := begin assume f, exact false.elim f, end theorem false_elim (P : Prop) (f : false) : P := begin cases f, end
12c29a1964aa71535e1d1dcdf2827868a8c70322
abd85493667895c57a7507870867b28124b3998f
/src/algebra/ring.lean
79704da61081e157b86a6dc2d40d0633a13c2cbd
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
40,854
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland -/ import algebra.group.hom import algebra.group.units import tactic.alias import tactic.norm_cast import tactic.split_ifs /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types. The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. Throughout the section on `ring_hom` implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `ring_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags `ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `integral_domain`, `nonzero`, `units` -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true 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." @[protect_proj, ancestor has_mul has_add] class distrib (α : Type u) extends has_mul α, has_add α := (left_distrib : ∀ a b c : α, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : α, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib α] (a b c : α) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c alias left_distrib ← mul_add lemma right_distrib [distrib α] (a b c : α) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c alias right_distrib ← add_mul @[protect_proj, ancestor has_mul has_zero] class mul_zero_class (α : Type u) extends has_mul α, has_zero α := (zero_mul : ∀ a : α, 0 * a = 0) (mul_zero : ∀ a : α, a * 0 = 0) @[ematch, simp] lemma zero_mul [mul_zero_class α] (a : α) : 0 * a = 0 := mul_zero_class.zero_mul a @[ematch, simp] lemma mul_zero [mul_zero_class α] (a : α) : a * 0 = 0 := mul_zero_class.mul_zero a /-- Predicate typeclass for expressing that a (semi)ring or similar algebraic structure is nonzero. -/ @[protect_proj] class nonzero (α : Type u) [has_zero α] [has_one α] : Prop := (zero_ne_one : 0 ≠ (1:α)) @[simp] lemma zero_ne_one [has_zero α] [has_one α] [nonzero α] : 0 ≠ (1:α) := nonzero.zero_ne_one @[simp] lemma one_ne_zero [has_zero α] [has_one α] [nonzero α] : (1:α) ≠ 0 := zero_ne_one.symm /-! ### Semirings -/ @[protect_proj, ancestor add_comm_monoid monoid distrib mul_zero_class] class semiring (α : Type u) extends add_comm_monoid α, monoid α, distrib α, mul_zero_class α section semiring variables [semiring α] lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma ne_zero_of_mul_ne_zero_right {a b : α} (h : a * b ≠ 0) : a ≠ 0 := assume : a = 0, have a * b = 0, by rw [this, zero_mul], h this lemma ne_zero_of_mul_ne_zero_left {a b : α} (h : a * b ≠ 0) : b ≠ 0 := assume : b = 0, have a * b = 0, by rw [this, mul_zero], h this lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `s.sum (λ x, f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp variable (α) /-- Either zero and one are nonequal in a semiring, or the semiring is the zero ring. -/ lemma zero_ne_one_or_forall_eq_0 : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) := by haveI := classical.dec; refine not_or_of_imp (λ h a, _); simpa using congr_arg ((*) a) h.symm /-- If zero equals one in a semiring, the semiring is the zero ring. -/ lemma eq_zero_of_zero_eq_one (h : (0 : α) = 1) : (∀a:α, a = 0) := (zero_ne_one_or_forall_eq_0 α).neg_resolve_left h /-- If zero equals one in a semiring, all elements of that semiring are equal. -/ theorem subsingleton_of_zero_eq_one (h : (0 : α) = 1) : subsingleton α := ⟨λa b, by rw [eq_zero_of_zero_eq_one α h a, eq_zero_of_zero_eq_one α h b]⟩ end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma mul_right_apply {R : Type*} [semiring R] (a r : R) : (mul_right r : R → R) a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β infixr ` →+* `:25 := ring_hom @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp, norm_cast] lemma coe_add_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) : ⇑(f : α →+ β) = f := rfl namespace ring_hom variables [rα : semiring α] [rβ : semiring β] section include rα rβ @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl variables (f : α →+* β) {x y : α} {rα rβ} theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ theorem coe_add_monoid_hom_inj : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, coe_inj $ show ((f : α →+ β) : α → β) = (g : α →+ β), from congr_arg coe_fn h theorem coe_monoid_hom_inj : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, coe_inj $ show ((f : α →* β) : α → β) = (g : α →* β), from congr_arg coe_fn h /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b end /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : function.surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : function.injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} instance comm_semiring_has_dvd : has_dvd α := has_dvd.mk (λ a b, ∃ c, b = a * c) -- TODO: this used to not have c explicit, but that seems to be important -- for use with tactics, similar to exist.intro theorem dvd.intro (c : α) (h : a * c = b) : a ∣ b := exists.intro c h^.symm def dvd_of_mul_right_eq := @dvd.intro theorem dvd.intro_left (c : α) (h : c * a = b) : a ∣ b := dvd.intro _ (begin rewrite mul_comm at h, apply h end) def dvd_of_mul_left_eq := @dvd.intro_left theorem exists_eq_mul_right_of_dvd (h : a ∣ b) : ∃ c, b = a * c := h theorem dvd.elim {P : Prop} {a b : α} (H₁ : a ∣ b) (H₂ : ∀ c, b = a * c → P) : P := exists.elim H₁ H₂ theorem exists_eq_mul_left_of_dvd (h : a ∣ b) : ∃ c, b = c * a := dvd.elim h (assume c, assume H1 : b = a * c, exists.intro c (eq.trans H1 (mul_comm a c))) theorem dvd.elim_left {P : Prop} (h₁ : a ∣ b) (h₂ : ∀ c, b = c * a → P) : P := exists.elim (exists_eq_mul_left_of_dvd h₁) (assume c, assume h₃ : b = c * a, h₂ c h₃) @[refl, simp] theorem dvd_refl (a : α) : a ∣ a := dvd.intro 1 (by simp) local attribute [simp] mul_assoc mul_comm mul_left_comm @[trans] theorem dvd_trans (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := match h₁, h₂ with | ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ := ⟨d * e, show c = a * (d * e), by simp [h₃, h₄]⟩ end def dvd.trans := @dvd_trans theorem eq_zero_of_zero_dvd (h : 0 ∣ a) : a = 0 := dvd.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (zero_mul c)) /-- Given an element a of a commutative semiring, there exists another element whose product with zero equals a iff a equals zero. -/ @[simp] lemma zero_dvd_iff : 0 ∣ a ↔ a = 0 := ⟨eq_zero_of_zero_dvd, λ h, by rw h⟩ @[simp] theorem dvd_zero (a : α) : a ∣ 0 := dvd.intro 0 (by simp) @[simp] theorem one_dvd (a : α) : 1 ∣ a := dvd.intro a (by simp) @[simp] theorem dvd_mul_right (a b : α) : a ∣ a * b := dvd.intro b rfl @[simp] theorem dvd_mul_left (a b : α) : a ∣ b * a := dvd.intro b (by simp) theorem dvd_mul_of_dvd_left (h : a ∣ b) (c : α) : a ∣ b * c := dvd.elim h (λ d h', begin rw [h', mul_assoc], apply dvd_mul_right end) theorem dvd_mul_of_dvd_right (h : a ∣ b) (c : α) : a ∣ c * b := begin rw mul_comm, exact dvd_mul_of_dvd_left h _ end theorem mul_dvd_mul : ∀ {a b c d : α}, a ∣ b → c ∣ d → a * c ∣ b * d | a ._ c ._ ⟨e, rfl⟩ ⟨f, rfl⟩ := ⟨e * f, by simp⟩ theorem mul_dvd_mul_left (a : α) {b c : α} (h : b ∣ c) : a * b ∣ a * c := mul_dvd_mul (dvd_refl a) h theorem mul_dvd_mul_right (h : a ∣ b) (c : α) : a * c ∣ b * c := mul_dvd_mul h (dvd_refl c) theorem dvd_add (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) theorem dvd_of_mul_right_dvd (h : a * b ∣ c) : a ∣ c := dvd.elim h (begin intros d h₁, rw [h₁, mul_assoc], apply dvd_mul_right end) theorem dvd_of_mul_left_dvd (h : a * b ∣ c) : b ∣ c := dvd.elim h (λ d ceq, dvd.intro (a * d) (by simp [ceq])) lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /-! ### Rings -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} lemma ring.mul_zero (a : α) : a * 0 = 0 := have a * 0 + 0 = a * 0 + a * 0, from calc a * 0 + 0 = a * (0 + 0) : by simp ... = a * 0 + a * 0 : by rw left_distrib, show a * 0 = 0, from (add_left_cancel this).symm lemma ring.zero_mul (a : α) : 0 * a = 0 := have 0 * a + 0 = 0 * a + 0 * a, from calc 0 * a + 0 = (0 + 0) * a : by simp ... = 0 * a + 0 * a : by rewrite right_distrib, show 0 * a = 0, from (add_left_cancel this).symm instance ring.to_semiring : semiring α := { mul_zero := ring.mul_zero, zero_mul := ring.zero_mul, ..‹ring α› } /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ attribute [instance, priority 200] ring.to_semiring lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp [sub_eq_add_neg] alias mul_sub_left_distrib ← mul_sub lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp [sub_eq_add_neg] alias mul_sub_right_distrib ← sub_mul /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end /-- If the product of two elements of a ring is nonzero, both elements are nonzero. -/ theorem ne_zero_and_ne_zero_of_mul_ne_zero (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, { intro ha, apply h, simp [ha] }, { intro hb, apply h, simp [hb] } end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [ring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_semigroup α instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} local attribute [simp] add_assoc add_comm add_left_comm mul_comm lemma mul_self_sub_mul_self_eq (a b : α) : a * a - b * b = (a + b) * (a - b) := begin simp [right_distrib, left_distrib, sub_eq_add_neg] end lemma mul_self_sub_one_eq (a : α) : a * a - 1 = (a + 1) * (a - 1) := begin simp [right_distrib, left_distrib, sub_eq_add_neg], rw [add_left_comm, add_comm (-a), add_left_comm a], simp end lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [right_distrib, left_distrib] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := dvd_add h₁ (dvd_neg_of_dvd h₂) theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end lemma dvd_mul_sub_mul {α : Type*} [comm_ring α] {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end lemma dvd_iff_dvd_of_dvd_sub {R : Type*} [comm_ring R] {a b c : R} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end comm_ring lemma succ_ne_self [ring α] [nonzero α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nonzero α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_inj ((add_right_inj a).mp (by { convert h, simp }))) /-- An element of the unit group of a nonzero semiring represented as an element of the semiring is nonzero. -/ lemma units.coe_ne_zero [semiring α] [nonzero α] (u : units α) : (u : α) ≠ 0 := λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3 /-- Proves that a semiring that contains at least two distinct elements is nonzero. -/ theorem nonzero.of_ne [semiring α] {x y : α} (h : x ≠ y) : nonzero α := { zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul] } @[protect_proj] class no_zero_divisors (α : Type u) [has_mul α] [has_zero α] : Prop := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) lemma eq_zero_or_eq_zero_of_mul_eq_zero [has_mul α] [has_zero α] [no_zero_divisors α] {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := no_zero_divisors.eq_zero_or_eq_zero_of_mul_eq_zero a b h lemma eq_zero_of_mul_self_eq_zero [has_mul α] [has_zero α] [no_zero_divisors α] {a : α} (h : a * a = 0) : a = 0 := or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h', h') (assume h', h') /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) (zero_ne_one : (0 : α) ≠ 1) section domain variable [domain α] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ instance domain.to_nonzero : nonzero α := ⟨domain.zero_ne_one⟩ /-- Simplification theorems for the definition of a domain. -/ @[simp] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ @[simp] theorem zero_eq_mul {a b : α} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, mul_eq_zero] lemma mul_self_eq_zero {α} [domain α] {x : α} : x * x = 0 ↔ x = 0 := by simp lemma zero_eq_mul_self {α} [domain α] {x : α} : 0 = x * x ↔ x = 0 := by simp /-- The product of two nonzero elements of a domain is nonzero. -/ theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂ /-- Right multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- Left multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- An element of a domain fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁); rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂] /-- An element of a domain fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁); rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂] /-- For elements `a`, `b` of a domain, if `a*b` is nonzero, so is `b*a`. -/ theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h) end domain /- integral domains -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} lemma mul_eq_zero_iff_eq_zero_or_eq_zero : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ lemma mul_ne_zero (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) (assume h₃, h₁ h₃) (assume h₄, h₂ h₄) lemma eq_of_mul_eq_mul_right (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, from sub_eq_zero_of_eq h, have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this lemma eq_of_mul_eq_mul_left (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, from sub_eq_zero_of_eq h, have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this lemma eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := have hb : b - 1 ≠ 0, from assume : b - 1 = 0, have b = 0 + 1, from eq_add_of_sub_eq this, have b = 1, by rwa zero_add at this, h₁ this, have a * b - a = 0, by simp [h₂], have a * (b - 1) = 0, by rwa [mul_sub_left_distrib, mul_one], show a = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right hb lemma eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := eq_zero_of_mul_eq_self_right h₁ (by rwa mul_comm at h₂) lemma mul_self_eq_mul_self_iff (a b : α) : a * a = b * b ↔ a = b ∨ a = -b := iff.intro (assume : a * a = b * b, have (a - b) * (a + b) = 0, by rewrite [mul_comm, ← mul_self_sub_mul_self_eq, this, sub_self], have a - b = 0 ∨ a + b = 0, from eq_zero_or_eq_zero_of_mul_eq_zero this, or.elim this (assume : a - b = 0, or.inl (eq_of_sub_eq_zero this)) (assume : a + b = 0, or.inr (eq_neg_of_add_eq_zero this))) (assume : a = b ∨ a = -b, or.elim this (assume : a = b, by rewrite this) (assume : a = -b, by rewrite [this, neg_mul_neg])) lemma mul_self_eq_one_iff (a : α) : a * a = 1 ↔ a = 1 ∨ a = -1 := have a * a = 1 * 1 ↔ a = 1 ∨ a = -1, from mul_self_eq_mul_self_iff a 1, by rwa mul_one at this /-- Right multiplcation by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_right_of_ne_zero (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this /-- Left multiplication by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_left_of_ne_zero (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this /-- Given two elements b, c of an integral domain and a nonzero element a, a*b divides a*c iff b divides c. -/ theorem mul_dvd_mul_iff_left (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, domain.mul_right_inj ha] /-- Given two elements a, b of an integral domain and a nonzero element c, a*c divides b*c iff a divides b. -/ theorem mul_dvd_mul_iff_right (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, domain.mul_left_inj hc] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by conv {to_lhs, rw [inv_eq_iff_mul_eq_one, ← mul_one (1 : units α), units.ext_iff, units.coe_mul, units.coe_mul, mul_self_eq_mul_self_iff, ← units.ext_iff, ← units.coe_neg, ← units.ext_iff] } end integral_domain /- units in various rings -/ namespace units section semiring variables [semiring α] @[simp] theorem mul_left_eq_zero_iff_eq_zero {r : α} (u : units α) : r * u = 0 ↔ r = 0 := ⟨λ h, (mul_left_inj u).1 $ (zero_mul (u : α)).symm ▸ h, λ h, h.symm ▸ zero_mul (u : α)⟩ @[simp] theorem mul_right_eq_zero_iff_eq_zero {r : α} (u : units α) : (u : α) * r = 0 ↔ r = 0 := ⟨λ h, (mul_right_inj u).1 $ (mul_zero (u : α)).symm ▸ h, λ h, h.symm ▸ mul_zero (u : α)⟩ end semiring section comm_semiring variables [comm_semiring α] (a b : α) (u : units α) /-- Elements of the unit group of a commutative semiring represented as elements of the semiring divide any element of the semiring. -/ @[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩ /-- In a commutative semiring, an element a divides an element b iff a divides all associates of b. -/ @[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩) (assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) /-- An element of a commutative semiring divides a unit iff the element divides one. -/ @[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 := suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa, dvd_coe_mul _ _ _ /-- In a commutative semiring, an element a divides an element b iff all associates of a divide b.-/ @[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩) (assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _)) end comm_semiring end units namespace is_unit section semiring variables [semiring α] theorem mul_left_eq_zero_iff_eq_zero {r u : α} (hu : is_unit u) : r * u = 0 ↔ r = 0 := by cases hu with u hu; exact hu ▸ units.mul_left_eq_zero_iff_eq_zero u theorem mul_right_eq_zero_iff_eq_zero {r u : α} (hu : is_unit u) : u * r = 0 ↔ r = 0 := by cases hu with u hu; exact hu ▸ units.mul_right_eq_zero_iff_eq_zero u end semiring end is_unit /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) (zero_ne_one : (0 : R) ≠ 1) /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) } namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] @[simp] lemma zero_right [mul_zero_class R] (a : R) : semiconj_by a 0 0 := by simp only [semiconj_by, mul_zero, zero_mul] @[simp] lemma zero_left [mul_zero_class R] (x y : R) : semiconj_by 0 x y := by simp only [semiconj_by, mul_zero, zero_mul] variables [ring R] {a b x y x' y' : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := ha.add_left hb.neg_left end semiconj_by namespace commute @[simp] theorem add_right [distrib R] {a b c : R} : commute a b → commute a c → commute a (b + c) := semiconj_by.add_right @[simp] theorem add_left [distrib R] {a b c : R} : commute a c → commute b c → commute (a + b) c := semiconj_by.add_left @[simp] theorem zero_right [mul_zero_class R] (a : R) :commute a 0 := semiconj_by.zero_right a @[simp] theorem zero_left [mul_zero_class R] (a : R) : commute 0 a := semiconj_by.zero_left a a variables [ring R] {a b c : R} theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right @[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left @[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff @[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a @[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a @[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right @[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left end commute
b0d5bae3263432f4ba08ada7f4a1368160899f47
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/interactive/findp.lean
223b3287c37ac224b25f5e41051133f999f905c7
[ "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
65
lean
import logic.eq algebra.relation check proof_irrel check false
f369851905d73578c9815f882eba4a34efa6e65d
976d2334b51721ddc405deb2e1754016d454286e
/src/game_files/group.lean
7cfd958c91154e7be4ec04b5a613cba3035d630a
[]
no_license
kbuzzard/lean-at-MC2020
11bb6ac9ec38a6caace9d5d9a1705d6794d9f477
1f7ca65a7ba5cc17eb49f525c02dc6b0e65d6543
refs/heads/master
1,668,496,422,317
1,594,131,838,000
1,594,131,838,000
277,877,735
0
0
null
1,594,142,006,000
1,594,142,005,000
null
UTF-8
Lean
false
false
1,458
lean
import data.fintype.basic import data.nat.prime import group_theory.order_of_element import tactic import data.int.modeq import data.zmod.basic noncomputable theory open_locale classical variables {G : Type*} [group G] lemma mul_comm_of_cyclic (g : G) (cyclic : ∀ x, ∃ n : ℤ, x = g^n) : ∀ a b : G, a * b = b * a := begin intros a b, cases cyclic a with na hna, cases cyclic b with nb hnb, rw [hna, hnb], repeat { rw ← gpow_add }, rw add_comm, end example : 0 < 4 := by norm_num lemma mul_comm_of_exponent_two (g : G) (exponent_two : ∀ x, x^2 = 1) : ∀ a b : G, a * b = b * a := begin intros a b, end lemma factors_of_4 {n : ℕ} (h4 : n ≠ 4) (hn : n ∣ 4) : n = 1 ∨ n = 2 := begin have := nat.le_of_dvd (by norm_num) hn, interval_cases n, -- n = 0 {cases hn with _ h, norm_num at h}, -- n = 1 { tauto }, -- n = 2 { tauto }, -- n = 3 exfalso, cases hn with k hk, revert hk, omega, end example /-- Every group of order 4 is commutative -/ lemma mul_comm_of_card_eq_four (G : Type*) [fintype G] [group G] (hG4 : fintype.card G = 4) : ∀ g h : G, g * h = h * g := begin by_cases ∃ (x : G), order_of x = 4, cases h with x hx, apply mul_comm_of_cyclic x, have := is_cyclic_of_order_of_eq_card x, end lemma sq_mod_8 (x : zmod 8) : x ^ 2 = 0 ∨ x^2 = 1 := begin cases x with x x_lt, have := nat.le_of_lt_succ x_lt, interval_cases x, -- why doesn't this work end
9febd0a4d2ee7d8d1971e5ccc734d4f3d2fcbb75
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/products/associator.lean
3895577177c10460ddd97ea25893c9b6165884c6
[ "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
1,752
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import category_theory.products.basic /-# The associator functor `((C × D) × E) ⥤ (C × (D × E))` and its inverse form an equivalence. -/ universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory namespace category_theory.prod variables (C : Type u₁) [𝒞 : category.{v₁} C] (D : Type u₂) [𝒟 : category.{v₂} D] (E : Type u₃) [ℰ : category.{v₃} E] include 𝒞 𝒟 ℰ -- Here and below we specify explicitly the projections to generate `@[simp]` lemmas for, -- as the default behaviour of `@[simps]` will generate projections all the way down to components of pairs. @[simps obj map] def associator : ((C × D) × E) ⥤ (C × (D × E)) := { obj := λ X, (X.1.1, (X.1.2, X.2)), map := λ _ _ f, (f.1.1, (f.1.2, f.2)) } @[simps obj map] def inverse_associator : (C × (D × E)) ⥤ ((C × D) × E) := { obj := λ X, ((X.1, X.2.1), X.2.2), map := λ _ _ f, ((f.1, f.2.1), f.2.2) } def associativity : (C × D) × E ≌ C × (D × E) := equivalence.mk (associator C D E) (inverse_associator C D E) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by simp)) (by tidy)) instance associator_is_equivalence : is_equivalence (associator C D E) := (by apply_instance : is_equivalence (associativity C D E).functor) instance inverse_associator_is_equivalence : is_equivalence (inverse_associator C D E) := (by apply_instance : is_equivalence (associativity C D E).inverse) -- TODO unitors? -- TODO pentagon natural transformation? ...satisfying? end category_theory.prod
96927bc62ac1c36bba1995ceddb6addc95bf5bd7
1c5436fdb875cae9acae86580cd113fa83c005a2
/tutorial/ch2.lean
99718dd63ad31a9084ceeb447b39b6183d3b42ca
[ "MIT" ]
permissive
Talndir/lean
cde18a381fa3f26ee65139e660ade1a6efbf56ae
86439ef51d4fbfbaad91972c72de56ead9ad80ae
refs/heads/master
1,587,482,425,928
1,549,677,236,000
1,549,677,236,000
169,666,359
0
0
null
null
null
null
UTF-8
Lean
false
false
1,513
lean
namespace q1 -- Setup def double : ℕ → ℕ := λ x, x + x def do_twice : (ℕ → ℕ) → ℕ → ℕ := λ f x, f (f x) -- Solution def Do_Twice : ((ℕ → ℕ) → (ℕ → ℕ)) → (ℕ → ℕ) → (ℕ → ℕ) := λ f g, f (f g) #reduce Do_Twice do_twice double 2 end q1 namespace q2 -- Setup variables (α β γ : Type) variables (a : α) (b : β) (p : α × β) -- Solution def curry : (α × β → γ) → (α → β → γ) := λ f, λ a b, f (a, b) def uncurry : (α → β → γ) → (α × β → γ) := λ f, λ p, f p.1 p.2 end q2 namespace q3 -- Setup universe u variable {α : Type u} variables {n m : ℕ} constant vec : Type u → ℕ → Type u variables (x : vec α n) {y : vec α m} constant empty : vec α 0 constant cons : α → vec α n → vec α (n + 1) constant append : vec α m → vec α n → vec α (n + m) -- Solution constant vec_add : vec α n → vec α n → vec α n constant vec_reverse : vec α n → vec α n end q3 namespace q4 -- Setup open q3 -- Solution universe u variable {α : Type u} variables {a b c : ℕ} constant matrix : Type u → ℕ → ℕ → Type u constant mat_add : matrix α a b → matrix α a b → matrix α a b constant mat_mat_mul: matrix α a b → matrix α b c → matrix α a c constant mat_vec_mul: matrix α a b → vec α b → vec α a end q4
6071805198cc1a63e5fcbd13d0fbaa40bf06fd36
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/monotonicity/interactive.lean
29b942863210b3bb4bba372f9df03a33e5988b68
[ "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
23,545
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.monotonicity.basic import category.basic import category.traversable import category.traversable.derive import data.dlist import logic.basic import tactic.core variables {a b c p : Prop} namespace tactic.interactive open lean lean.parser interactive open interactive.types open tactic local postfix `?`:9001 := optional local postfix *:9001 := many meta inductive mono_function (elab : bool := tt) | non_assoc : expr elab → list (expr elab) → list (expr elab) → mono_function | assoc : expr elab → option (expr elab) → option (expr elab) → mono_function | assoc_comm : expr elab → expr elab → mono_function meta instance : decidable_eq mono_function := by mk_dec_eq_instance meta def mono_function.to_tactic_format : mono_function → tactic format | (mono_function.non_assoc fn xs ys) := do fn' ← pp fn, xs' ← mmap pp xs, ys' ← mmap pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc fn xs ys) := do fn' ← pp fn, xs' ← pp xs, ys' ← pp ys, return format!"{fn'} {xs'} _ {ys'}" | (mono_function.assoc_comm fn xs) := do fn' ← pp fn, xs' ← pp xs, return format!"{fn'} _ {xs'}" meta instance has_to_tactic_format_mono_function : has_to_tactic_format mono_function := { to_tactic_format := mono_function.to_tactic_format } @[derive traversable] meta structure ac_mono_ctx' (rel : Type) := (to_rel : rel) (function : mono_function) (left right rel_def : expr) @[reducible] meta def ac_mono_ctx := ac_mono_ctx' (option (expr → expr → expr)) @[reducible] meta def ac_mono_ctx_ne := ac_mono_ctx' (expr → expr → expr) meta def ac_mono_ctx.to_tactic_format (ctx : ac_mono_ctx) : tactic format := do fn ← pp ctx.function, l ← pp ctx.left, r ← pp ctx.right, rel ← pp ctx.rel_def, return format!"{{ function := {fn}\n, left := {l}\n, right := {r}\n, rel_def := {rel} }" meta instance has_to_tactic_format_mono_ctx : has_to_tactic_format ac_mono_ctx := { to_tactic_format := ac_mono_ctx.to_tactic_format } meta def as_goal (e : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [e], tac, set_goals gs open list (hiding map) functor dlist section config parameter opt : mono_cfg parameter asms : list expr meta def unify_with_instance (e : expr) : tactic unit := as_goal e $ apply_instance <|> apply_opt_param <|> apply_auto_param <|> tactic.solve_by_elim { lemmas := some asms } <|> reflexivity <|> applyc ``id <|> return () private meta def match_rule_head (p : expr) : list expr → expr → expr → tactic expr | vs e t := (unify t p >> mmap' unify_with_instance vs >> instantiate_mvars e) <|> do (expr.pi _ _ d b) ← return t | failed, v ← mk_meta_var d, match_rule_head (v::vs) (expr.app e v) (b.instantiate_var v) meta def pi_head : expr → tactic expr | (expr.pi n _ t b) := do v ← mk_meta_var t, pi_head (b.instantiate_var v) | e := return e meta def delete_expr (e : expr) : list expr → tactic (option (list expr)) | [] := return none | (x :: xs) := (compare opt e x >> return (some xs)) <|> (map (cons x) <$> delete_expr xs) meta def match_ac' : list expr → list expr → tactic (list expr × list expr × list expr) | es (x :: xs) := do es' ← delete_expr x es, match es' with | (some es') := do (c,l,r) ← match_ac' es' xs, return (x::c,l,r) | none := do (c,l,r) ← match_ac' es xs, return (c,l,x::r) end | es [] := do return ([],es,[]) meta def match_ac (unif : bool) (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr) := do (s',l',r') ← match_ac' l r, s' ← mmap instantiate_mvars s', l' ← mmap instantiate_mvars l', r' ← mmap instantiate_mvars r', return (s',l',r') meta def match_prefix : list expr → list expr → tactic (list expr × list expr × list expr) | (x :: xs) (y :: ys) := (do compare opt x y, prod.map ((::) x) id <$> match_prefix xs ys) <|> return ([],x :: xs,y :: ys) | xs ys := return ([],xs,ys) /-- `(prefix,left,right,suffix) ← match_assoc unif l r` finds the longest prefix and suffix common to `l` and `r` and returns them along with the differences -/ meta def match_assoc (l : list expr) (r : list expr) : tactic (list expr × list expr × list expr × list expr) := do (pre,l₁,r₁) ← match_prefix l r, (suf,l₂,r₂) ← match_prefix (reverse l₁) (reverse r₁), return (pre,reverse l₂,reverse r₂,reverse suf) meta def check_ac : expr → tactic (bool × bool × option (expr × expr × expr) × expr) | (expr.app (expr.app f x) y) := do t ← infer_type x, a ← try_core $ to_expr ``(is_associative %%t %%f) >>= mk_instance, c ← try_core $ to_expr ``(is_commutative %%t %%f) >>= mk_instance, i ← try_core (do v ← mk_meta_var t, l_inst_p ← to_expr ``(is_left_id %%t %%f %%v), r_inst_p ← to_expr ``(is_right_id %%t %%f %%v), l_v ← mk_meta_var l_inst_p, r_v ← mk_meta_var r_inst_p , l_id ← mk_mapp `is_left_id.left_id [some t,f,v,some l_v], mk_instance l_inst_p >>= unify l_v, r_id ← mk_mapp `is_right_id.right_id [none,f,v,some r_v], mk_instance r_inst_p >>= unify r_v, v' ← instantiate_mvars v, return (l_id,r_id,v')), return (a.is_some,c.is_some,i,f) | _ := return (ff,ff,none,expr.var 1) meta def parse_assoc_chain' (f : expr) : expr → tactic (dlist expr) | e := (do (expr.app (expr.app f' x) y) ← return e, is_def_eq f f', (++) <$> parse_assoc_chain' x <*> parse_assoc_chain' y) <|> return (singleton e) meta def parse_assoc_chain (f : expr) : expr → tactic (list expr) := map dlist.to_list ∘ parse_assoc_chain' f meta def fold_assoc (op : expr) : option (expr × expr × expr) → list expr → option (expr × list expr) | _ (x::xs) := some (foldl (expr.app ∘ expr.app op) x xs, []) | none [] := none | (some (l_id,r_id,x₀)) [] := some (x₀,[l_id,r_id]) meta def fold_assoc1 (op : expr) : list expr → option expr | (x::xs) := some $ foldl (expr.app ∘ expr.app op) x xs | [] := none meta def same_function_aux : list expr → list expr → expr → expr → tactic (expr × list expr × list expr) | xs₀ xs₁ (expr.app f₀ a₀) (expr.app f₁ a₁) := same_function_aux (a₀ :: xs₀) (a₁ :: xs₁) f₀ f₁ | xs₀ xs₁ e₀ e₁ := is_def_eq e₀ e₁ >> return (e₀,xs₀,xs₁) meta def same_function : expr → expr → tactic (expr × list expr × list expr) := same_function_aux [] [] meta def parse_ac_mono_function (l r : expr) : tactic (expr × expr × list expr × mono_function) := do (full_f,ls,rs) ← same_function l r, (a,c,i,f) ← check_ac l, if a then if c then do (s,ls,rs) ← monad.join (match_ac tt <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, s' ← fold_assoc1 f s, return (l',r',l_id ++ r_id,mono_function.assoc_comm f s') else do -- a ∧ ¬ c (pre,ls,rs,suff) ← monad.join (match_assoc <$> parse_assoc_chain f l <*> parse_assoc_chain f r), (l',l_id) ← fold_assoc f i ls, (r',r_id) ← fold_assoc f i rs, let pre' := fold_assoc1 f pre, let suff' := fold_assoc1 f suff, return (l',r',l_id ++ r_id,mono_function.assoc f pre' suff') else do -- ¬ a (xs₀,x₀,x₁,xs₁) ← find_one_difference opt ls rs, return (x₀,x₁,[],mono_function.non_assoc full_f xs₀ xs₁) meta def parse_ac_mono_function' (l r : pexpr) := do l' ← to_expr l, r' ← to_expr r, parse_ac_mono_function l' r' meta def ac_monotonicity_goal : expr → tactic (expr × expr × list expr × ac_mono_ctx) | `(%%e₀ → %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) → (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := some $ expr.pi `x binder_info.default , rel_def := rel_def }) | `(%%e₀ = %%e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, t₀ ← infer_type e₀, t₁ ← infer_type e₁, rel_def ← to_expr ``(λ x₀ x₁, (x₀ : %%t₀) = (x₁ : %%t₁)), return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := none , rel_def := rel_def }) | (expr.app (expr.app rel e₀) e₁) := do (l,r,id_rs,f) ← parse_ac_mono_function e₀ e₁, return (e₀, e₁, id_rs, { function := f , left := l, right := r , to_rel := expr.app ∘ expr.app rel , rel_def := rel }) | _ := fail "invalid monotonicity goal" meta def bin_op_left (f : expr) : option expr → expr → expr | none e := e | (some e₀) e₁ := f.mk_app [e₀,e₁] meta def bin_op (f a b : expr) : expr := f.mk_app [a,b] meta def bin_op_right (f : expr) : expr → option expr → expr | e none := e | e₀ (some e₁) := f.mk_app [e₀,e₁] meta def mk_fun_app : mono_function → expr → expr | (mono_function.non_assoc f x y) z := f.mk_app (x ++ z :: y) | (mono_function.assoc f x y) z := bin_op_left f x (bin_op_right f z y) | (mono_function.assoc_comm f x) z := f.mk_app [z,x] meta inductive mono_law /- `assoc (l₀,r₀) (r₁,l₁)` gives first how to find rules to prove x+(y₀+z) R x+(y₁+z); if that fails, helps prove (x+y₀)+z R (x+y₁)+z -/ | assoc : expr × expr → expr × expr → mono_law /- `congr r` gives the rule to prove `x = y → f x = f y` -/ | congr : expr → mono_law | other : expr → mono_law meta def mono_law.to_tactic_format : mono_law → tactic format | (mono_law.other e) := do e ← pp e, return format!"other {e}" | (mono_law.congr r) := do e ← pp r, return format!"congr {e}" | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := do x₀ ← pp x₀, x₁ ← pp x₁, y₀ ← pp y₀, y₁ ← pp y₁, return format!"assoc {x₀}; {x₁} | {y₀}; {y₁}" meta instance has_to_tactic_format_mono_law : has_to_tactic_format mono_law := { to_tactic_format := mono_law.to_tactic_format } meta def mk_rel (ctx : ac_mono_ctx_ne) (f : expr → expr) : expr := ctx.to_rel (f ctx.left) (f ctx.right) meta def mk_congr_args (fn : expr) (xs₀ xs₁ : list expr) (l r : expr) : tactic expr := do p ← mk_app `eq [fn.mk_app $ xs₀ ++ l :: xs₁,fn.mk_app $ xs₀ ++ r :: xs₁], prod.snd <$> solve_aux p (do iterate_exactly (xs₁.length) (applyc `congr_fun), applyc `congr_arg) meta def mk_congr_law (ctx : ac_mono_ctx) : tactic expr := match ctx.function with | (mono_function.assoc f x₀ x₁) := if (x₀ <|> x₁).is_some then mk_congr_args f x₀.to_monad x₁.to_monad ctx.left ctx.right else failed | (mono_function.assoc_comm f x₀) := mk_congr_args f [x₀] [] ctx.left ctx.right | (mono_function.non_assoc f x₀ x₁) := mk_congr_args f x₀ x₁ ctx.left ctx.right end meta def mk_pattern (ctx : ac_mono_ctx) : tactic mono_law := match (sequence ctx : option (ac_mono_ctx' _)) with | (some ctx) := match ctx.function with | (mono_function.assoc f (some x) (some y)) := return $ mono_law.assoc ( mk_rel ctx (λ i, bin_op f x (bin_op f i y)) , mk_rel ctx (λ i, bin_op f i y)) ( mk_rel ctx (λ i, bin_op f (bin_op f x i) y) , mk_rel ctx (λ i, bin_op f x i)) | (mono_function.assoc f (some x) none) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none (some y)) := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) | (mono_function.assoc f none none) := none | _ := return $ mono_law.other $ mk_rel ctx (λ e, mk_fun_app ctx.function e) end | none := mono_law.congr <$> mk_congr_law ctx end meta def match_rule (pat : expr) (r : name) : tactic expr := do r' ← mk_const r, t ← infer_type r', match_rule_head pat [] r' t meta def find_lemma (pat : expr) : list name → tactic (list expr) | [] := return [] | (r :: rs) := do (cons <$> match_rule pat r <|> pure id) <*> find_lemma rs meta def match_chaining_rules (ls : list name) (x₀ x₁ : expr) : tactic (list expr) := do x' ← to_expr ``(%%x₁ → %%x₀), r₀ ← find_lemma x' ls, r₁ ← find_lemma x₁ ls, return (expr.app <$> r₀ <*> r₁) meta def find_rule (ls : list name) : mono_law → tactic (list expr) | (mono_law.assoc (x₀,x₁) (y₀,y₁)) := (match_chaining_rules ls x₀ x₁) <|> (match_chaining_rules ls y₀ y₁) | (mono_law.congr r) := return [r] | (mono_law.other p) := find_lemma p ls universes u v def apply_rel {α : Sort u} (R : α → α → Sort v) {x y : α} (x' y' : α) (h : R x y) (hx : x = x') (hy : y = y') : R x' y' := by { rw [← hx,← hy], apply h } meta def ac_refine (e : expr) : tactic unit := refine ``(eq.mp _ %%e) ; ac_refl meta def one_line (e : expr) : tactic format := do lbl ← pp e, asm ← infer_type e >>= pp, return format!"\t{asm}\n" meta def side_conditions (e : expr) : tactic format := do let vs := e.list_meta_vars, ts ← mmap one_line vs.tail, let r := e.get_app_fn.const_name, return format!"{r}:\n{format.join ts}" open monad /-- tactic-facing function, similar to `interactive.tactic.generalize` with the exception that meta variables -/ private meta def monotonicity.generalize' (h : name) (v : expr) (x : name) : tactic (expr × expr) := do tgt ← target, t ← infer_type v, tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize v x >> target), to_expr ``(λ y : %%t, Π x, y = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(λ y : %%t, Π x, %%v = x → %%tgt), t ← head_beta (tgt' v) >>= assert h, swap, r ← mk_eq_refl v, solve1 $ tactic.exact (t v r), prod.mk <$> tactic.intro x <*> tactic.intro h private meta def hide_meta_vars (tac : list expr → tactic unit) : tactic unit := focus1 $ do tgt ← target >>= instantiate_mvars, tactic.change tgt, ctx ← local_context, let vs := tgt.list_meta_vars, vs' ← mmap (λ v, do h ← get_unused_name `h, x ← get_unused_name `x, prod.snd <$> monotonicity.generalize' h v x) vs, tac ctx; vs'.mmap' (try ∘ tactic.subst) meta def hide_meta_vars' (tac : itactic) : itactic := hide_meta_vars $ λ _, tac end config meta def solve_mvar (v : expr) (tac : tactic unit) : tactic unit := do gs ← get_goals, set_goals [v], target >>= instantiate_mvars >>= tactic.change, tac, done, set_goals $ gs def list.minimum_on {α β} [decidable_linear_order β] (f : α → β) : list α → list α | [] := [] | (x :: xs) := prod.snd $ xs.foldl (λ ⟨k,a⟩ b, let k' := f b in if k < k' then (k,a) else if k' < k then (k', [b]) else (k,b :: a)) (f x, [x]) open format mono_selection meta def best_match {β} (xs : list expr) (tac : expr → tactic β) : tactic unit := do t ← target, xs ← xs.mmap (λ x, try_core $ prod.mk x <$> solve_aux t (tac x >> get_goals)), let xs := xs.filter_map id, let r := list.minimum_on (list.length ∘ prod.fst ∘ prod.snd) xs, match r with | [(_,gs,pr)] := tactic.exact pr >> set_goals gs | [] := fail "no good match found" | _ := do lmms ← r.mmap (λ ⟨l,gs,_⟩, do ts ← gs.mmap infer_type, msg ← ts.mmap pp, pure $ foldl compose "\n\n" (list.intersperse "\n" $ to_fmt l.get_app_fn.const_name :: msg)), let msg := foldl compose "" lmms, fail format!"ambiguous match: {msg}\n\nTip: try asserting a side condition to distinguish between the lemmas" end meta def mono_aux (dir : parse side) (cfg : mono_cfg := { mono_cfg . }) : tactic unit := do t ← target >>= instantiate_mvars, ns ← get_monotonicity_lemmas t dir, asms ← local_context, rs ← find_lemma asms t ns, focus1 $ () <$ best_match rs (λ law, tactic.refine $ to_pexpr law) /-- - `mono` applies a monotonicity rule. - `mono*` applies monotonicity rules repetitively. - `mono with x ≤ y` or `mono with [0 ≤ x,0 ≤ y]` creates an assertion for the listed propositions. Those help to select the right monotonicity rule. - `mono left` or `mono right` is useful when proving strict orderings: for `x + y < w + z` could be broken down into either - left: `x ≤ w` and `y < z` or - right: `x < w` and `y ≤ z` - `mono using [rule1,rule2]` calls `simp [rule1,rule2]` before applying mono. - The general syntax is `mono '*'? ('with' hyp | 'with' [hyp1,hyp2])? ('using' [hyp1,hyp2])? mono_cfg? To use it, first import `tactic.monotonicity`. Here is an example of mono: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, -- unfold `(-)`, apply add_le_add { -- ⊢ k + 3 + x ≤ k + 4 + x mono, -- apply add_le_add, refl -- ⊢ k + 3 ≤ k + 4 mono }, { -- ⊢ -y ≤ -z mono /- apply neg_le_neg -/ } end ``` More succinctly, we can prove the same goal as: ```lean example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := by mono* ``` -/ meta def mono (many : parse (tk "*")?) (dir : parse side) (hyps : parse $ tk "with" *> pexpr_list_or_texpr <|> pure []) (simp_rules : parse $ tk "using" *> simp_arg_list <|> pure []) (cfg : mono_cfg := { mono_cfg . }) : tactic unit := do hyps ← hyps.mmap (λ p, to_expr p >>= mk_meta_var), hyps.mmap' (λ pr, do h ← get_unused_name `h, note h none pr), when (¬ simp_rules.empty) (simp_core { } failed tt simp_rules [] (loc.ns [none])), if many.is_some then repeat $ mono_aux dir cfg else mono_aux dir cfg, gs ← get_goals, set_goals $ hyps ++ gs add_tactic_doc { name := "mono", category := doc_category.tactic, decl_names := [`tactic.interactive.mono], tags := ["monotonicity"] } /-- transforms a goal of the form `f x ≼ f y` into `x ≤ y` using lemmas marked as `monotonic`. Special care is taken when `f` is the repeated application of an associative operator and if the operator is commutative -/ meta def ac_mono_aux (cfg : mono_cfg := { mono_cfg . }) : tactic unit := hide_meta_vars $ λ asms, do try `[dunfold has_sub.sub algebra.sub], tgt ← target >>= instantiate_mvars, (l,r,id_rs,g) ← ac_monotonicity_goal cfg tgt <|> fail "monotonic context not found", ns ← get_monotonicity_lemmas tgt both, p ← mk_pattern g, rules ← find_rule asms ns p <|> fail "no applicable rules found", when (rules = []) (fail "no applicable rules found"), err ← format.join <$> mmap side_conditions rules, focus1 $ best_match rules (λ rule, do t₀ ← mk_meta_var `(Prop), v₀ ← mk_meta_var t₀, t₁ ← mk_meta_var `(Prop), v₁ ← mk_meta_var t₁, tactic.refine $ ``(apply_rel %%(g.rel_def) %%l %%r %%rule %%v₀ %%v₁), solve_mvar v₀ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), solve_mvar v₁ (try (any_of id_rs rewrite_target) >> ( done <|> refl <|> ac_refl <|> `[simp only [is_associative.assoc]]) ), n ← num_goals, iterate_exactly (n-1) (try $ solve1 $ apply_instance <|> tactic.solve_by_elim { lemmas := some asms })) open sum nat /-- (repeat_until_or_at_most n t u): repeat tactic `t` at most n times or until u succeeds -/ meta def repeat_until_or_at_most : nat → tactic unit → tactic unit → tactic unit | 0 t _ := fail "too many applications" | (succ n) t u := u <|> (t >> repeat_until_or_at_most n t u) meta def repeat_until : tactic unit → tactic unit → tactic unit := repeat_until_or_at_most 100000 @[derive _root_.has_reflect, derive _root_.inhabited] inductive rep_arity : Type | one | exactly (n : ℕ) | many meta def repeat_or_not : rep_arity → tactic unit → option (tactic unit) → tactic unit | rep_arity.one tac none := tac | rep_arity.many tac none := repeat tac | (rep_arity.exactly n) tac none := iterate_exactly n tac | rep_arity.one tac (some until) := tac >> until | rep_arity.many tac (some until) := repeat_until tac until | (rep_arity.exactly n) tac (some until) := iterate_exactly n tac >> until meta def assert_or_rule : lean.parser (pexpr ⊕ pexpr) := (tk ":=" *> inl <$> texpr <|> (tk ":" *> inr <$> texpr)) meta def arity : lean.parser rep_arity := rep_arity.many <$ tk "*" <|> rep_arity.exactly <$> (tk "^" *> small_nat) <|> pure rep_arity.one /-- `ac_mono` reduces the `f x ⊑ f y`, for some relation `⊑` and a monotonic function `f` to `x ≺ y`. `ac_mono*` unwraps monotonic functions until it can't. `ac_mono^k`, for some literal number `k` applies monotonicity `k` times. `ac_mono h`, with `h` a hypothesis, unwraps monotonic functions and uses `h` to solve the remaining goal. Can be combined with `*` or `^k`: `ac_mono* h` `ac_mono : p` asserts `p` and uses it to discharge the goal result unwrapping a series of monotonic functions. Can be combined with * or ^k: `ac_mono* : p` In the case where `f` is an associative or commutative operator, `ac_mono` will consider any possible permutation of its arguments and use the one the minimizes the difference between the left-hand side and the right-hand side. To use it, first import `tactic.monotonicity`. `ac_mono` can be used as follows: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end ``` As with `mono*`, `ac_mono*` solves the goal in one go and so does `ac_mono* h₁`. The latter syntax becomes especially interesting in the following example: ```lean example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by ac_mono* h₁. ``` By giving `ac_mono` the assumption `h₁`, we are asking `ac_refl` to stop earlier than it would normally would. -/ meta def ac_mono (rep : parse arity) : parse assert_or_rule? → opt_param mono_cfg { mono_cfg . } → tactic unit | none opt := focus1 $ repeat_or_not rep (ac_mono_aux opt) none | (some (inl h)) opt := do focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> to_expr h >>= ac_refine) | (some (inr t)) opt := do h ← i_to_expr t >>= assert `h, tactic.swap, focus1 $ repeat_or_not rep (ac_mono_aux opt) (some $ done <|> ac_refine h) /- TODO(Simon): with `ac_mono h` and `ac_mono : p` split the remaining gaol if the provided rule does not solve it completely. -/ add_tactic_doc { name := "ac_mono", category := doc_category.tactic, decl_names := [`tactic.interactive.ac_mono], tags := ["monotonicity"] } attribute [mono] and.imp or.imp end tactic.interactive
078c93f6a099f37ea750d3e7e760640460642366
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/conditionally_complete_lattice/finset.lean
ad588569add270fb8388d81ac09a250b34e23652
[ "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
3,493
lean
/- Copyright (c) 2018 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 order.conditionally_complete_lattice.basic import data.set.finite /-! # Conditionally complete lattices and finite sets. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open set variables {α β γ : Type*} section conditionally_complete_lattice variables [conditionally_complete_lattice α] {s t : set α} {a b : α} lemma finset.nonempty.sup'_eq_cSup_image {s : finset β} (hs : s.nonempty) (f : β → α) : s.sup' hs f = Sup (f '' s) := eq_of_forall_ge_iff $ λ a, by simp [cSup_le_iff (s.finite_to_set.image f).bdd_above (hs.to_set.image f)] lemma finset.nonempty.sup'_id_eq_cSup {s : finset α} (hs : s.nonempty) : s.sup' hs id = Sup s := by rw [hs.sup'_eq_cSup_image, image_id] end conditionally_complete_lattice section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] {s t : set α} {a b : α} lemma finset.nonempty.cSup_eq_max' {s : finset α} (h : s.nonempty) : Sup ↑s = s.max' h := eq_of_forall_ge_iff $ λ a, (cSup_le_iff s.bdd_above h.to_set).trans (s.max'_le_iff h).symm lemma finset.nonempty.cInf_eq_min' {s : finset α} (h : s.nonempty) : Inf ↑s = s.min' h := @finset.nonempty.cSup_eq_max' αᵒᵈ _ s h lemma finset.nonempty.cSup_mem {s : finset α} (h : s.nonempty) : Sup (s : set α) ∈ s := by { rw h.cSup_eq_max', exact s.max'_mem _ } lemma finset.nonempty.cInf_mem {s : finset α} (h : s.nonempty) : Inf (s : set α) ∈ s := @finset.nonempty.cSup_mem αᵒᵈ _ _ h lemma set.nonempty.cSup_mem (h : s.nonempty) (hs : s.finite) : Sup s ∈ s := by { lift s to finset α using hs, exact finset.nonempty.cSup_mem h } lemma set.nonempty.cInf_mem (h : s.nonempty) (hs : s.finite) : Inf s ∈ s := @set.nonempty.cSup_mem αᵒᵈ _ _ h hs lemma set.finite.cSup_lt_iff (hs : s.finite) (h : s.nonempty) : Sup s < a ↔ ∀ x ∈ s, x < a := ⟨λ h x hx, (le_cSup hs.bdd_above hx).trans_lt h, λ H, H _ $ h.cSup_mem hs⟩ lemma set.finite.lt_cInf_iff (hs : s.finite) (h : s.nonempty) : a < Inf s ↔ ∀ x ∈ s, a < x := @set.finite.cSup_lt_iff αᵒᵈ _ _ _ hs h end conditionally_complete_linear_order /-! ### Relation between `Sup` / `Inf` and `finset.sup'` / `finset.inf'` Like the `Sup` of a `conditionally_complete_lattice`, `finset.sup'` also requires the set to be non-empty. As a result, we can translate between the two. -/ namespace finset lemma sup'_eq_cSup_image [conditionally_complete_lattice β] (s : finset α) (H) (f : α → β) : s.sup' H f = Sup (f '' s) := begin apply le_antisymm, { refine (finset.sup'_le _ _ $ λ a ha, _), refine le_cSup ⟨s.sup' H f, _⟩ ⟨a, ha, rfl⟩, rintros i ⟨j, hj, rfl⟩, exact finset.le_sup' _ hj }, { apply cSup_le ((coe_nonempty.mpr H).image _), rintros _ ⟨a, ha, rfl⟩, exact finset.le_sup' _ ha, } end lemma inf'_eq_cInf_image [conditionally_complete_lattice β] (s : finset α) (H) (f : α → β) : s.inf' H f = Inf (f '' s) := @sup'_eq_cSup_image _ βᵒᵈ _ _ H _ lemma sup'_id_eq_cSup [conditionally_complete_lattice α] (s : finset α) (H) : s.sup' H id = Sup s := by rw [sup'_eq_cSup_image s H, set.image_id] lemma inf'_id_eq_cInf [conditionally_complete_lattice α] (s : finset α) (H) : s.inf' H id = Inf s := @sup'_id_eq_cSup αᵒᵈ _ _ H end finset
c379d5625176586ad50702e25983ab56b5f21029
682dc1c167e5900ba3168b89700ae1cf501cfa29
/src/basicmodal/semantics/completeness.lean
c8ac5d9b5f0595ffe213d0e2a236fad5e3ff158f
[]
no_license
paulaneeley/modal
834558c87f55cdd6d8a29bb46c12f4d1de3239bc
ee5d149d4ecb337005b850bddf4453e56a5daf04
refs/heads/master
1,675,911,819,093
1,609,785,144,000
1,609,785,144,000
270,388,715
13
1
null
null
null
null
UTF-8
Lean
false
false
10,263
lean
/- Copyright (c) 2021 Paula Neeley. All rights reserved. Author: Paula Neeley -/ import basicmodal.semantics.consistency basicmodal.syntax.soundness local attribute [instance] classical.prop_decidable open prfK ---------------------- Canonical Model Construction ---------------------- namespace canonical def canonical (AX : ctx) [hax : sem_cons AX] : frame := { states := {xΓ : ctx // max_ax_consist AX xΓ}, h := begin have h1 := max_ax_exists AX hax, choose Γ h1 using h1, exact ⟨⟨Γ, h1⟩⟩ end, rel := λ xΓ yΔ, ∀ φ : form, □φ ∈ xΓ.val → φ ∈ yΔ.val } def T_canonical : frame := @canonical T_axioms sem_consT def S4_canonical : frame := @canonical S4_axioms sem_consS4 def S5_canonical : frame := @canonical S5_axioms sem_consS5 def val_canonical (AX : ctx) [hax : sem_cons AX] : nat → (canonical AX).states → Prop := λ n, λ xΓ : (canonical AX).states, (p n) ∈ xΓ.val lemma existence (AX : ctx) (hax : sem_cons AX) (xΓ : (canonical AX).states) : ∀ φ, ◇φ ∈ xΓ.val ↔ ∃ yΔ : (canonical AX).states, φ ∈ yΔ.val ∧ (canonical AX).rel xΓ yΔ := begin intro φ, split, intro h1, let Γbox : ctx := {ψ : form | □ψ ∈ xΓ.val}, have h1 : ax_consist AX (Γbox ∪ {φ}), {by_contradiction h2, simp at h2, have h3 := five AX Γbox φ h2, cases h3 with L h3, cases h3 with h3 h4, have h5 := cut fin_conj_boxn (mp kdist (nec h4)), have h6 := exercise1, have h7 : ∀ ψ ∈ (list.map □ L), ψ ∈ xΓ.1, intros ψ h8, simp at *, cases h8 with a h8, cases h8 with h8l h8r, subst h8r, exact h3 a h8l, specialize h6 xΓ.2 h7 h5, have h8 := (six AX xΓ.1 (max_imp_ax xΓ.2)).mp xΓ.2 (¬φ).box, cases h8 with h8l h8r, simp at *, exact absurd h1 (h8r h6) }, have h2 := lindenbaum AX (Γbox ∪ {φ}) h1, cases h2 with Δ h2, cases h2 with h2 h3, let xΔ : (canonical AX).states := ⟨Δ, h2⟩, existsi (xΔ : (canonical AX).states), have h5 := set.union_subset_iff.mp h3, cases h5, split, simp at h5_right, exact h5_right, have h3 : ∀ φ : form, □φ ∈ xΓ.val → φ ∈ xΔ.val, intros ψ h4, apply h5_left, exact h4, exact h3, simp at *, intros yΔ h1 h2, by_contradiction h3, have h4 := (max_notiff AX xΓ.1 xΓ.2 (◇φ)).mp h3, have h5 := (max_dn AX xΓ.1 xΓ.2 (□¬φ)).mpr h4, have h6 := (max_notiff AX yΔ.1 yΔ.2 φ).mpr (h2 (¬φ) h5), exact absurd h1 h6 end lemma truth (AX : ctx) (hax : sem_cons AX) (xΓ : (canonical AX).states) : ∀ φ, forces (canonical AX) (val_canonical AX) xΓ φ ↔ (φ ∈ xΓ.val) := begin intro φ, induction φ with n φ ψ ih_φ ih_ψ φ ψ ih_φ ih_ψ φ ih_φ generalizing xΓ, split, intro h1, exact false.elim h1, intro h1, have h2 := xΓ.2, cases h2, specialize h2_left [⊥], simp at *, exact absurd not_contra (h2_left h1), repeat {rw forces, rw val_canonical}, split, intro h1, cases h1 with h1 h2, exact max_conj_1 xΓ.2 (and.intro ((ih_φ xΓ).mp h1) ((ih_ψ xΓ).mp h2)), intro h1, split, apply (ih_φ xΓ).mpr, exact max_conj_2 xΓ.2 h1, apply (ih_ψ xΓ).mpr, exact max_conj_3 xΓ.2 h1, split, intro h1, apply max_imp_1 xΓ.2, intro h2, exact (ih_ψ xΓ).mp (h1 ((ih_φ xΓ).mpr h2)), intros h1 h2, apply (ih_ψ xΓ).mpr, exact max_imp_2 xΓ.2 h1 ((ih_φ xΓ).mp h2), split, intros h1, by_contradiction h2, have h4 := (existence AX hax xΓ (¬φ)).mp, have h5 := max_boxdn AX xΓ.1 xΓ.2 φ ((max_notiff AX xΓ.1 xΓ.2 φ.box).mp h2), cases h4 h5 with xΔ h4, cases h4 with h4 h6, have h7 := max_notiff AX xΔ.1 xΔ.2 φ, cases h7 with h7l h7r, exact absurd ((ih_φ xΔ).mp (h1 xΔ h6)) (h7r h4), intros h1 xΔ h2, apply (ih_φ xΔ).mpr, exact h2 φ h1, end lemma comphelper (AX : ctx) (φ : form) (hax : sem_cons AX) : ¬ prfK AX φ → ax_consist AX {¬φ} := begin intro h1, intros L h2, rw fin_ax_consist, induction L, by_contradiction h3, exact absurd (mp dne h3) (nprfalse AX hax), have h4 : (∀ ψ ∈ L_hd::L_tl, ψ = ¬φ) → prfK AX (¬fin_conj (L_hd::L_tl)) → prfK AX φ, from fin_conj_repeat hax, simp at *, cases h2 with h2 h3, intro h6, apply h1, apply h4 h2, exact h3, exact h6 end theorem forcesAX (AX : ctx) (hax : sem_cons AX) : forces_ctx (canonical AX) (val_canonical AX) AX := begin intros φ xΓ h1, have h2 : ∀ ψ ∈ list.nil, ψ ∈ xΓ.val, {intros ψ h3, have h4 := list.ne_nil_of_length_pos (list.length_pos_of_mem h3), simp at *, exact false.elim h4}, exact (truth AX hax xΓ φ).mpr (exercise1 xΓ.2 h2 (mp pl1 (ax h1))) end theorem completeness (AX : ctx) (hax : sem_cons AX) (φ : form) : global_sem_csq AX φ → prfK AX φ := begin rw ←not_imp_not, intro h1, have h2 := comphelper AX φ hax h1, have h3 := lindenbaum AX {¬φ} h2, simp at *, cases h3 with Γ' h3, cases h3 with h3 h4, rw global_sem_csq, push_neg, let f := canonical, use f AX, let v := val_canonical, use v AX, let xΓ' : (f AX).states := ⟨Γ', h3⟩, split, exact forcesAX AX hax, use xΓ', have h5 := truth AX hax xΓ' ¬φ, cases h5 with h5 h6, have h7 := not_forces_imp (f AX) (v AX) xΓ' φ, cases h7 with h7 h8, apply h8, apply h6, exact h4 end lemma T_reflexive : T_canonical ∈ ref_class := begin intros x φ h1, have h2 : (∀ ψ ∈ [□φ], ψ ∈ x.1) → prfK T_axioms (fin_conj [□φ] ⊃ φ) → φ ∈ x.1, from exercise1 x.2, simp at *, have h3 : prfK T_axioms (fin_conj [φ.box] ⊃ φ), {repeat {rw fin_conj}, have h4 : prfK T_axioms (φ.box ⊃ φ), {refine ax _, rw T_axioms, simp}, exact cut (mp pl5 phi_and_true) h4}, exact h2 h1 h3 end theorem T_completeness (φ : form) : F_valid φ ref_class → prfK T_axioms φ := begin rw ←not_imp_not, intro h1, have h2 := completeness T_axioms sem_consT φ, rw ←not_imp_not at h2, specialize h2 h1, rw F_valid, push_neg, let f := T_canonical, use f, split, exact T_reflexive, let v := val_canonical, use (@v T_axioms sem_consT), have h4 := lindenbaum T_axioms {¬φ} (comphelper T_axioms φ sem_consT h1), simp at *, cases h4 with Γ' h4, cases h4 with h4 h5, let xΓ : f.states := ⟨Γ', h4⟩, use xΓ, have h6 := truth T_axioms sem_consT xΓ ¬φ, cases h6 with h6 h7, have h8 := not_forces_imp f (@v T_axioms sem_consT) xΓ φ, cases h8 with h8 h9, apply h9, apply h7, exact h5 end lemma S4_reftrans : S4_canonical ∈ ref_trans_class := begin split, intros x φ h1, have h2 : (∀ ψ ∈ [□φ], ψ ∈ x.1) → prfK S4_axioms (fin_conj [□φ] ⊃ φ) → φ ∈ x.1, from exercise1 x.2, simp at *, have h3 : prfK S4_axioms (fin_conj [φ.box] ⊃ φ), {repeat {rw fin_conj}, have h4 : prfK S4_axioms (φ.box ⊃ φ), {refine ax _, rw S4_axioms, simp, rw T_axioms, simp}, exact cut (mp pl5 phi_and_true) h4}, exact h2 h1 h3, intros x y z h1 h2 φ h3, apply h2 φ, apply h1 (□φ), have h4 : prfK S4_axioms (fin_conj [φ.box] ⊃ φ.box.box), {repeat {rw fin_conj}, have h5 : prfK S4_axioms (φ.box ⊃ φ.box.box), {refine ax _, rw S4_axioms, simp}, exact cut (mp pl5 phi_and_true) h5}, have h6 : (∀ ψ ∈ [□φ], ψ ∈ x.1) → prfK S4_axioms (fin_conj [□φ] ⊃ φ.box.box) → φ.box.box ∈ x.1, from exercise1 x.2, simp at *, exact h6 h3 h4 end theorem S4_completeness (φ : form) : F_valid φ ref_trans_class → prfK S4_axioms φ := begin rw ←not_imp_not, intro h1, have h2 := completeness S4_axioms sem_consS4 φ, rw ←not_imp_not at h2, specialize h2 h1, rw F_valid, push_neg, let f := S4_canonical, use f, split, exact S4_reftrans, let v := val_canonical, use (@v S4_axioms sem_consS4), have h4 := lindenbaum S4_axioms {¬φ} (comphelper S4_axioms φ sem_consS4 h1), simp at *, cases h4 with Γ' h4, cases h4 with h4 h5, let xΓ : f.states := ⟨Γ', h4⟩, use xΓ, have h6 := truth S4_axioms sem_consS4 xΓ ¬φ, cases h6 with h6 h7, have h8 := not_forces_imp f (@v S4_axioms sem_consS4) xΓ φ, cases h8 with h8 h9, apply h9, apply h7, exact h5 end lemma euclid_dual {φ : form} : prfK S5_axioms ((◇(¬φ) ⊃ □(◇(¬φ))) ⊃ (◇(□φ) ⊃ □φ)) := begin simp, have h1 : prfK S5_axioms (◇(¬φ) ⊃ □(◇¬φ)), refine ax _, rw S5_axioms, simp, simp at *, have h2 := contrapos.mpr h1, have h3 := cut h2 (mp pl6 dual_equiv1), have h4 : prfK S5_axioms ((¬□(◇¬φ)) ↔ (¬¬◇(¬(◇¬φ)))), from (mp (mp pl4 (contrapos.mpr (mp pl6 dual_equiv1))) (contrapos.mpr (mp pl5 dual_equiv1))), have h5 := cut dni (cut (mp pl6 h4) h3), have h6 := (contrapos.mpr (mp kdist (nec (contrapos.mpr (mp pl5 dual_equiv1))))), exact (mp pl1 (cut h6 h5)) end lemma S5_equiv : S5_canonical ∈ equiv_class := begin rw equiv_ref_euclid, split, intros x φ h1, have h2 : (∀ ψ ∈ [□φ], ψ ∈ x.1) → prfK S5_axioms (fin_conj [□φ] ⊃ φ) → φ ∈ x.1, from exercise1 x.2, simp at *, have h3 : prfK S5_axioms (fin_conj [φ.box] ⊃ φ), {repeat {rw fin_conj}, have h4 : prfK S5_axioms (φ.box ⊃ φ), {refine ax _, rw S5_axioms, simp, rw T_axioms, simp}, exact cut (mp pl5 phi_and_true) h4}, exact h2 h1 h3, intros x y z h1 h2 φ h3, apply h2 φ, clear h2, have h2 : prfK S5_axioms (◇(¬φ) ⊃ □(◇¬φ)), {refine ax _, rw S5_axioms, simp}, have h4 : prfK S5_axioms (◇(□φ) ⊃ □φ), from mp euclid_dual h2, have h5 : (∀ ψ ∈ [◇(□φ)], ψ ∈ x.1) → prfK S5_axioms (fin_conj [◇(□φ)] ⊃ □φ) → □φ ∈ x.1, from exercise1 x.2, simp at *, apply h5, by_contradiction h6, have h7 := (max_notiff S5_axioms x.1 x.2 (¬(¬φ.box).box)).mp h6, have h8 := (max_dn S5_axioms x.1 x.2 ((¬φ.box).box)).mpr h7, have h9 := (max_notiff S5_axioms y.1 y.2 (φ.box)).mpr (h1 (¬φ.box) h8), exact absurd h3 h9, exact (cut (mp pl5 phi_and_true) h4) end theorem S5_completeness (φ : form) : F_valid φ equiv_class → prfK S5_axioms φ := begin rw ←not_imp_not, intro h1, have h2 := completeness S5_axioms sem_consS5 φ, rw ←not_imp_not at h2, specialize h2 h1, rw F_valid, push_neg, let f := S5_canonical, use f, split, exact S5_equiv, let v := val_canonical, use (@v S5_axioms sem_consS5), have h4 := lindenbaum S5_axioms {¬φ} (comphelper S5_axioms φ sem_consS5 h1), simp at *, cases h4 with Γ' h4, cases h4 with h4 h5, let xΓ : f.states := ⟨Γ', h4⟩, use xΓ, have h6 := truth S5_axioms sem_consS5 xΓ ¬φ, cases h6 with h6 h7, have h8 := not_forces_imp f (@v S5_axioms sem_consS5) xΓ φ, cases h8 with h8 h9, apply h9, apply h7, exact h5 end end canonical
07b5314b7a4f5da415f77f33ae08d04ff04f89d4
e38e95b38a38a99ecfa1255822e78e4b26f65bb0
/src/certigrad/aevb/transformations.lean
79070bd8a5cca17f4bfbfa99317a3562cf5873b1
[ "Apache-2.0" ]
permissive
ColaDrill/certigrad
fefb1be3670adccd3bed2f3faf57507f156fd501
fe288251f623ac7152e5ce555f1cd9d3a20203c2
refs/heads/master
1,593,297,324,250
1,499,903,753,000
1,499,903,753,000
97,075,797
1
0
null
1,499,916,210,000
1,499,916,210,000
null
UTF-8
Lean
false
false
3,582
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Proofs that integrating out the KL and reparametizing are sound when applied to the naive variational encoder. -/ import .util .prog .graph ..prove_model_ok ..kl namespace certigrad namespace aevb open graph list tactic certigrad.tactic meta def prove_transformation (e : pexpr) := do whnf_target, [tgt, idx, H_at_idx, θ] ← intro_lst [`tgt, `idx, `H_at_idx, `θ] | failed, forall_idxs prove_model_base (do H_at_idx ← get_local `H_at_idx, mk_app `and.right [H_at_idx] >>= note `H_tgt_eq, H_tgt_eq_type ← get_local `H_tgt_eq >>= infer_type, s ← join_user_simp_lemmas true [`cgsimp], (H_tgt_eq_new_type, pr) ← simplify s H_tgt_eq_type {}, get_local `H_tgt_eq >>= λ H_tgt_eq, replace_hyp H_tgt_eq H_tgt_eq_new_type pr, get_local `H_tgt_eq >>= subst, to_expr e >>= apply, all_goals (cgsimp >> try prove_is_mvn_integrable >> try prove_preconditions)) idx #print "proving integrate_kl_sound..." lemma integrate_kl_sound (a : arch) (ws : weights a) (x_data : T [a^.n_in, a^.n_x]) : let g₀ : graph := graph_naive a x_data, fdict : env := mk_input_dict ws x_data g₀ in ∀ (tgt : reference) (idx : ℕ) (H_at_idx : at_idx g₀^.targets idx tgt) (θ : T tgt.2), E (graph.to_dist (λ m, ⟦sum_costs m (integrate_kl g₀)^.costs⟧) (env.insert tgt θ fdict) (integrate_kl g₀)^.nodes) dvec.head = E (graph.to_dist (λ m, ⟦sum_costs m g₀^.costs⟧) (env.insert tgt θ fdict) g₀^.nodes) dvec.head := by prove_transformation ```(integrate_mvn_iso_kl_correct (ID.str label.encoding_loss) [ID.str label.decoding_loss] (graph_naive a x_data)^.nodes) #print "proving reparam_sound..." lemma reparam_sound (a : arch) (ws : weights a) (x_data : T [a^.n_in, a^.n_x]) : let g₁ : graph := integrate_kl (graph_naive a x_data), fdict : env := mk_input_dict ws x_data g₁ in ∀ (tgt : reference) (idx : ℕ) (H_at_idx : at_idx g₁^.targets idx tgt) (θ : T tgt.2), E (graph.to_dist (λ m, ⟦sum_costs m (reparam g₁)^.costs⟧) (env.insert tgt θ fdict) (reparam g₁)^.nodes) dvec.head = E (graph.to_dist (λ m, ⟦sum_costs m g₁^.costs⟧) (env.insert tgt θ fdict) g₁^.nodes) dvec.head := by prove_transformation ```(reparameterize_correct [ID.str label.encoding_loss, ID.str label.decoding_loss] (integrate_kl $ graph_naive a x_data)^.nodes _ (ID.str label.ε, [a^.nz, a^.bs])) #print "proving aevb_transformations_sound..." lemma aevb_transformations_sound {a : arch} (ws : weights a) (x_data : T [a^.n_in, a^.n_x]) : let g₀ : graph := naive_aevb a x_data, g_aevb : graph := reparam (integrate_kl g₀), fdict : env := mk_input_dict ws x_data g₀ in ∀ (tgt : reference) (idx : ℕ) (H_at_idx : at_idx g₀^.targets idx tgt) (θ : T tgt.2), E (graph.to_dist (λ m, ⟦sum_costs m g₀^.costs⟧) (env.insert tgt θ fdict) g₀^.nodes) dvec.head = E (graph.to_dist (λ m, ⟦sum_costs m g_aevb^.costs⟧) (env.insert tgt θ fdict) g_aevb^.nodes) dvec.head := begin whnf_target, intros tgt idx H_at_idx θ, -- TODO(dhs): this is annoying, rw and simp should whnf the let note H₁ := @reparam_sound a ws x_data tgt idx, note H₂ := @integrate_kl_sound a ws x_data tgt idx, simp only [naive_aevb_as_graph] at *, erw [H₁, H₂], all_goals { assumption } end end aevb end certigrad
82690c0473559b385280aa7207af6f0f54c457a4
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/io_process_env.lean
cab749a94c6cc4dad8b5bdfca13f1d31b29275f6
[ "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
199
lean
import system.io variable [io.interface] #eval do res ← io.cmd {cmd := "printenv", args := ["foo"], env := [("foo", "bar")]}, when (res ≠ "bar\n") $ io.fail $ "unexpected value for foo: " ++ res
0d807197b2104866331612fc0d6a8b08b8c00c57
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/nullstellensatz.lean
def2196661005d9857b5d5ca7d47bb7509969642
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,319
lean
/- Copyright (c) 2021 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import ring_theory.jacobson import field_theory.is_alg_closed.basic import field_theory.mv_polynomial import algebraic_geometry.prime_spectrum.basic /-! # Nullstellensatz > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file establishes a version of Hilbert's classical Nullstellensatz for `mv_polynomial`s. The main statement of the theorem is `vanishing_ideal_zero_locus_eq_radical`. The statement is in terms of new definitions `vanishing_ideal` and `zero_locus`. Mathlib already has versions of these in terms of the prime spectrum of a ring, but those are not well-suited for expressing this result. Suggestions for better ways to state this theorem or organize things are welcome. The machinery around `vanishing_ideal` and `zero_locus` is also minimal, I only added lemmas directly needed in this proof, since I'm not sure if they are the right approach. -/ open ideal noncomputable theory namespace mv_polynomial open mv_polynomial variables {k : Type*} [field k] variables {σ : Type*} /-- Set of points that are zeroes of all polynomials in an ideal -/ def zero_locus (I : ideal (mv_polynomial σ k)) : set (σ → k) := {x : σ → k | ∀ p ∈ I, eval x p = 0} @[simp] lemma mem_zero_locus_iff {I : ideal (mv_polynomial σ k)} {x : σ → k} : x ∈ zero_locus I ↔ ∀ p ∈ I, eval x p = 0 := iff.rfl lemma zero_locus_anti_mono {I J : ideal (mv_polynomial σ k)} (h : I ≤ J) : zero_locus J ≤ zero_locus I := λ x hx p hp, hx p $ h hp lemma zero_locus_bot : zero_locus (⊥ : ideal (mv_polynomial σ k)) = ⊤ := eq_top_iff.2 (λ x hx p hp, trans (congr_arg (eval x) (mem_bot.1 hp)) (eval x).map_zero) lemma zero_locus_top : zero_locus (⊤ : ideal (mv_polynomial σ k)) = ⊥ := eq_bot_iff.2 $ λ x hx, one_ne_zero ((eval x).map_one ▸ (hx 1 submodule.mem_top) : (1 : k) = 0) /-- Ideal of polynomials with common zeroes at all elements of a set -/ def vanishing_ideal (V : set (σ → k)) : ideal (mv_polynomial σ k) := { carrier := {p | ∀ x ∈ V, eval x p = 0}, zero_mem' := λ x hx, ring_hom.map_zero _, add_mem' := λ p q hp hq x hx, by simp only [hq x hx, hp x hx, add_zero, ring_hom.map_add], smul_mem' := λ p q hq x hx, by simp only [hq x hx, algebra.id.smul_eq_mul, mul_zero, ring_hom.map_mul] } @[simp] lemma mem_vanishing_ideal_iff {V : set (σ → k)} {p : mv_polynomial σ k} : p ∈ vanishing_ideal V ↔ ∀ x ∈ V, eval x p = 0 := iff.rfl lemma vanishing_ideal_anti_mono {A B : set (σ → k)} (h : A ≤ B) : vanishing_ideal B ≤ vanishing_ideal A := λ p hp x hx, hp x $ h hx lemma vanishing_ideal_empty : vanishing_ideal (∅ : set (σ → k)) = ⊤ := le_antisymm le_top (λ p hp x hx, absurd hx (set.not_mem_empty x)) lemma le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial σ k)) : I ≤ vanishing_ideal (zero_locus I) := λ p hp x hx, hx p hp lemma zero_locus_vanishing_ideal_le (V : set (σ → k)) : V ≤ zero_locus (vanishing_ideal V) := λ V hV p hp, hp V hV theorem zero_locus_vanishing_ideal_galois_connection : @galois_connection (ideal (mv_polynomial σ k)) (set (σ → k))ᵒᵈ _ _ zero_locus vanishing_ideal := λ I V, ⟨λ h, le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono h), λ h, le_trans (zero_locus_anti_mono h) (zero_locus_vanishing_ideal_le V)⟩ lemma mem_vanishing_ideal_singleton_iff (x : σ → k) (p : mv_polynomial σ k) : p ∈ (vanishing_ideal {x} : ideal (mv_polynomial σ k)) ↔ (eval x p = 0) := ⟨λ h, h x rfl, λ hpx y hy, hy.symm ▸ hpx⟩ instance vanishing_ideal_singleton_is_maximal {x : σ → k} : (vanishing_ideal {x} : ideal (mv_polynomial σ k)).is_maximal := begin have : mv_polynomial σ k ⧸ vanishing_ideal {x} ≃+* k := ring_equiv.of_bijective (ideal.quotient.lift _ (eval x) (λ p h, (mem_vanishing_ideal_singleton_iff x p).mp h)) begin refine ⟨(injective_iff_map_eq_zero _).mpr (λ p hp, _), λ z, ⟨(ideal.quotient.mk (vanishing_ideal {x} : ideal (mv_polynomial σ k))) (C z), by simp⟩⟩, obtain ⟨q, rfl⟩ := quotient.mk_surjective p, rwa [ideal.quotient.lift_mk, ← mem_vanishing_ideal_singleton_iff, ← quotient.eq_zero_iff_mem] at hp, end, rw [← bot_quotient_is_maximal_iff, ring_equiv.bot_maximal_iff this], exact bot_is_maximal, end lemma radical_le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial σ k)) : I.radical ≤ vanishing_ideal (zero_locus I) := begin intros p hp x hx, rw ← mem_vanishing_ideal_singleton_iff, rw radical_eq_Inf at hp, refine (mem_Inf.mp hp) ⟨le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono (λ y hy, hy.symm ▸ hx)), is_maximal.is_prime' _⟩, end /-- The point in the prime spectrum assosiated to a given point -/ def point_to_point (x : σ → k) : prime_spectrum (mv_polynomial σ k) := ⟨(vanishing_ideal {x} : ideal (mv_polynomial σ k)), by apply_instance⟩ @[simp] lemma vanishing_ideal_point_to_point (V : set (σ → k)) : prime_spectrum.vanishing_ideal (point_to_point '' V) = mv_polynomial.vanishing_ideal V := le_antisymm (λ p hp x hx, (((prime_spectrum.mem_vanishing_ideal _ _).1 hp) ⟨vanishing_ideal {x}, by apply_instance⟩ ⟨x, ⟨hx, rfl⟩⟩) x rfl) (λ p hp, (prime_spectrum.mem_vanishing_ideal _ _).2 (λ I hI, let ⟨x, hx⟩ := hI in hx.2 ▸ λ x' hx', (set.mem_singleton_iff.1 hx').symm ▸ hp x hx.1)) lemma point_to_point_zero_locus_le (I : ideal (mv_polynomial σ k)) : point_to_point '' (mv_polynomial.zero_locus I) ≤ prime_spectrum.zero_locus ↑I := λ J hJ, let ⟨x, hx⟩ := hJ in (le_trans (le_vanishing_ideal_zero_locus I) (hx.2 ▸ vanishing_ideal_anti_mono (set.singleton_subset_iff.2 hx.1)) : I ≤ J.as_ideal) variables [is_alg_closed k] [finite σ] lemma is_maximal_iff_eq_vanishing_ideal_singleton (I : ideal (mv_polynomial σ k)) : I.is_maximal ↔ ∃ (x : σ → k), I = vanishing_ideal {x} := begin casesI nonempty_fintype σ, refine ⟨λ hI, _, λ h, let ⟨x, hx⟩ := h in hx.symm ▸ (mv_polynomial.vanishing_ideal_singleton_is_maximal)⟩, letI : I.is_maximal := hI, letI : field (mv_polynomial σ k ⧸ I) := quotient.field I, let ϕ : k →+* mv_polynomial σ k ⧸ I := (ideal.quotient.mk I).comp C, have hϕ : function.bijective ϕ := ⟨quotient_mk_comp_C_injective _ _ I hI.ne_top, is_alg_closed.algebra_map_surjective_of_is_integral' ϕ (mv_polynomial.comp_C_integral_of_surjective_of_jacobson _ quotient.mk_surjective)⟩, obtain ⟨φ, hφ⟩ := function.surjective.has_right_inverse hϕ.2, let x : σ → k := λ s, φ ((ideal.quotient.mk I) (X s)), have hx : ∀ s : σ, ϕ (x s) = (ideal.quotient.mk I) (X s) := λ s, hφ ((ideal.quotient.mk I) (X s)), refine ⟨x, (is_maximal.eq_of_le (by apply_instance) hI.ne_top _).symm⟩, intros p hp, rw [← quotient.eq_zero_iff_mem, map_mv_polynomial_eq_eval₂ (ideal.quotient.mk I) p, eval₂_eq'], rw [mem_vanishing_ideal_singleton_iff, eval_eq'] at hp, simpa only [ϕ.map_sum, ϕ.map_mul, ϕ.map_prod, ϕ.map_pow, ϕ.map_zero, hx] using congr_arg ϕ hp, end /-- Main statement of the Nullstellensatz -/ @[simp] theorem vanishing_ideal_zero_locus_eq_radical (I : ideal (mv_polynomial σ k)) : vanishing_ideal (zero_locus I) = I.radical := begin rw I.radical_eq_jacobson, refine le_antisymm (le_Inf _) (λ p hp x hx, _), { rintros J ⟨hJI, hJ⟩, obtain ⟨x, hx⟩ := (is_maximal_iff_eq_vanishing_ideal_singleton J).1 hJ, refine hx.symm ▸ vanishing_ideal_anti_mono (λ y hy p hp, _), rw [← mem_vanishing_ideal_singleton_iff, set.mem_singleton_iff.1 hy, ← hx], refine hJI hp }, { rw ← mem_vanishing_ideal_singleton_iff x p, refine (mem_Inf.mp hp) ⟨le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono (λ y hy, hy.symm ▸ hx)), mv_polynomial.vanishing_ideal_singleton_is_maximal⟩ }, end @[simp] lemma is_prime.vanishing_ideal_zero_locus (P : ideal (mv_polynomial σ k)) [h : P.is_prime] : vanishing_ideal (zero_locus P) = P := trans (vanishing_ideal_zero_locus_eq_radical P) h.radical end mv_polynomial
74a48b00dc23e4e633a809ad92a95a30f7de51b4
43390109ab88557e6090f3245c47479c123ee500
/src/Geometry/axioms.lean
2c991cf83a2027784f302d6f729c323712d228e5
[ "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,303
lean
class Euclidean_plane (point : Type) := -- Equidistance of 4 Points (eqd : point → point → point → point → Prop) -- Between A B C means B is on the line segment AC (B : point → point → point → Prop) [dec_B : ∀ a b c, decidable (B a b c)] -- Existence of three points for two_dim (P1 {} : point) (P2 {} : point) (P3 {} : point) (eqd_refl : ∀ a b : point, eqd a b b a) (eqd_trans : ∀ {a b p q r s}, eqd a b p q → eqd a b r s → eqd p q r s) (id_eqd : ∀ {a b c}, eqd a b c c → a = b) (seg_cons : ∀ a b c q, {x // B q a x ∧ eqd a x b c}) (five_seg : ∀ {a b c d a' b' c' d'}, a ≠ b → B a b c → B a' b' c' → eqd a b a' b' → eqd b c b' c' → eqd a d a' d' → eqd b d b' d' → eqd c d c' d') (bet_same : ∀ {a b}, B a b a → a = b) (pasch : ∀ {a b c p q}, B a p c → B b q c → {x // B p x b ∧ B q x a}) (two_dim : ¬B P1 P2 P3 ∧ ¬B P2 P3 P1 ∧ ¬B P3 P1 P2) (not_3dim : ∀ {a b c p q}, p ≠ q → eqd a p a q → eqd b p b q → eqd c p c q → (B a b c ∨ B b c a ∨ B c a b)) (euclids : ∀ {a b c d t}, B a d t → B b d c → a ≠ d → { X : point × point // B a b X.1 ∧ B a c X.2 ∧ B X.1 t X.2}) (cont : ∀ X Y : set point, (∃ a, ∀ x y, x ∈ X → y ∈ Y → B a x y) → (∃ b, ∀ x y, x ∈ X → y ∈ Y → B x b y))
356597e8c9be7990d47735f9ef4fb207ef7be123
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/monoidal/category.lean
5b9c3057f2fade55ca1772feca272864cb466ec3
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
18,772
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import category_theory.products.basic open category_theory universes v u open category_theory open category_theory.category open category_theory.iso namespace category_theory /-- In a monoidal category, we can take the tensor product of objects, `X ⊗ Y` and of morphisms `f ⊗ g`. Tensor product does not need to be strictly associative on objects, but there is a specified associator, `α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)`. There is a tensor unit `𝟙_ C`, with specified left and right unitor isomorphisms `λ_ X : 𝟙_ C ⊗ X ≅ X` and `ρ_ X : X ⊗ 𝟙_ C ≅ X`. These associators and unitors satisfy the pentagon and triangle equations. -/ class monoidal_category (C : Type u) [𝒞 : category.{v} C] := -- curried tensor product of objects: (tensor_obj : C → C → C) (infixr ` ⊗ `:70 := tensor_obj) -- This notation is only temporary -- curried tensor product of morphisms: (tensor_hom : Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))) (infixr ` ⊗' `:69 := tensor_hom) -- This notation is only temporary -- tensor product laws: (tensor_id' : ∀ (X₁ X₂ : C), (𝟙 X₁) ⊗' (𝟙 X₂) = 𝟙 (X₁ ⊗ X₂) . obviously) (tensor_comp' : ∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂), (f₁ ≫ g₁) ⊗' (f₂ ≫ g₂) = (f₁ ⊗' f₂) ≫ (g₁ ⊗' g₂) . obviously) -- tensor unit: (tensor_unit [] : C) (notation `𝟙_` := tensor_unit) -- associator: (associator : Π X Y Z : C, (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)) (notation `α_` := associator) (associator_naturality' : ∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃), ((f₁ ⊗' f₂) ⊗' f₃) ≫ (α_ Y₁ Y₂ Y₃).hom = (α_ X₁ X₂ X₃).hom ≫ (f₁ ⊗' (f₂ ⊗' f₃)) . obviously) -- left unitor: (left_unitor : Π X : C, 𝟙_ ⊗ X ≅ X) (notation `λ_` := left_unitor) (left_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), ((𝟙 𝟙_) ⊗' f) ≫ (λ_ Y).hom = (λ_ X).hom ≫ f . obviously) -- right unitor: (right_unitor : Π X : C, X ⊗ 𝟙_ ≅ X) (notation `ρ_` := right_unitor) (right_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), (f ⊗' (𝟙 𝟙_)) ≫ (ρ_ Y).hom = (ρ_ X).hom ≫ f . obviously) -- pentagon identity: (pentagon' : ∀ W X Y Z : C, ((α_ W X Y).hom ⊗' (𝟙 Z)) ≫ (α_ W (X ⊗ Y) Z).hom ≫ ((𝟙 W) ⊗' (α_ X Y Z).hom) = (α_ (W ⊗ X) Y Z).hom ≫ (α_ W X (Y ⊗ Z)).hom . obviously) -- triangle identity: (triangle' : ∀ X Y : C, (α_ X 𝟙_ Y).hom ≫ ((𝟙 X) ⊗' (λ_ Y).hom) = (ρ_ X).hom ⊗' (𝟙 Y) . obviously) restate_axiom monoidal_category.tensor_id' attribute [simp] monoidal_category.tensor_id restate_axiom monoidal_category.tensor_comp' attribute [simp] monoidal_category.tensor_comp restate_axiom monoidal_category.associator_naturality' attribute [reassoc] monoidal_category.associator_naturality restate_axiom monoidal_category.left_unitor_naturality' attribute [reassoc] monoidal_category.left_unitor_naturality restate_axiom monoidal_category.right_unitor_naturality' attribute [reassoc] monoidal_category.right_unitor_naturality restate_axiom monoidal_category.pentagon' restate_axiom monoidal_category.triangle' attribute [simp] monoidal_category.triangle open monoidal_category infixr ` ⊗ `:70 := tensor_obj infixr ` ⊗ `:70 := tensor_hom notation `𝟙_` := tensor_unit notation `α_` := associator notation `λ_` := left_unitor notation `ρ_` := right_unitor /-- The tensor product of two isomorphisms is an isomorphism. -/ def tensor_iso {C : Type u} {X Y X' Y' : C} [category.{v} C] [monoidal_category.{v} C] (f : X ≅ Y) (g : X' ≅ Y') : X ⊗ X' ≅ Y ⊗ Y' := { hom := f.hom ⊗ g.hom, inv := f.inv ⊗ g.inv, hom_inv_id' := by rw [←tensor_comp, iso.hom_inv_id, iso.hom_inv_id, ←tensor_id], inv_hom_id' := by rw [←tensor_comp, iso.inv_hom_id, iso.inv_hom_id, ←tensor_id] } infixr ` ⊗ `:70 := tensor_iso namespace monoidal_category section variables {C : Type u} [category.{v} C] [monoidal_category.{v} C] instance tensor_is_iso {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : is_iso (f ⊗ g) := { ..(as_iso f ⊗ as_iso g) } @[simp] lemma inv_tensor {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : inv (f ⊗ g) = inv f ⊗ inv g := rfl variables {U V W X Y Z : C} -- When `rewrite_search` lands, add @[search] attributes to -- monoidal_category.tensor_id monoidal_category.tensor_comp monoidal_category.associator_naturality -- monoidal_category.left_unitor_naturality monoidal_category.right_unitor_naturality -- monoidal_category.pentagon monoidal_category.triangle -- tensor_comp_id tensor_id_comp comp_id_tensor_tensor_id -- triangle_assoc_comp_left triangle_assoc_comp_right triangle_assoc_comp_left_inv triangle_assoc_comp_right_inv -- left_unitor_tensor left_unitor_tensor_inv -- right_unitor_tensor right_unitor_tensor_inv -- pentagon_inv -- associator_inv_naturality -- left_unitor_inv_naturality -- right_unitor_inv_naturality @[simp] lemma comp_tensor_id (f : W ⟶ X) (g : X ⟶ Y) : (f ≫ g) ⊗ (𝟙 Z) = (f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) := by { rw ←tensor_comp, simp } @[simp] lemma id_tensor_comp (f : W ⟶ X) (g : X ⟶ Y) : (𝟙 Z) ⊗ (f ≫ g) = (𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) := by { rw ←tensor_comp, simp } @[simp] lemma id_tensor_comp_tensor_id (f : W ⟶ X) (g : Y ⟶ Z) : ((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = g ⊗ f := by { rw [←tensor_comp], simp } @[simp] lemma tensor_id_comp_id_tensor (f : W ⟶ X) (g : Y ⟶ Z) : (g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) = g ⊗ f := by { rw [←tensor_comp], simp } lemma left_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (λ_ X').inv = (λ_ X).inv ≫ (𝟙 _ ⊗ f) := begin apply (cancel_mono (λ_ X').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end lemma right_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (ρ_ X').inv = (ρ_ X).inv ≫ (f ⊗ 𝟙 _) := begin apply (cancel_mono (ρ_ X').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end @[simp] lemma right_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (ρ_ X).inv ≫ (f ⊗ (𝟙 (𝟙_ C))) ≫ (ρ_ Y).hom = f := by rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] @[simp] lemma left_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (λ_ X).inv ≫ ((𝟙 (𝟙_ C)) ⊗ f) ≫ (λ_ Y).hom = f := by rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] @[simp] lemma tensor_left_iff {X Y : C} (f g : X ⟶ Y) : ((𝟙 (𝟙_ C)) ⊗ f = (𝟙 (𝟙_ C)) ⊗ g) ↔ (f = g) := begin split, { intro h, have h' := congr_arg (λ k, (λ_ _).inv ≫ k) h, dsimp at h', rw [←left_unitor_inv_naturality, ←left_unitor_inv_naturality] at h', exact (cancel_mono _).1 h', }, { intro h, subst h, } end @[simp] lemma tensor_right_iff {X Y : C} (f g : X ⟶ Y) : (f ⊗ (𝟙 (𝟙_ C)) = g ⊗ (𝟙 (𝟙_ C))) ↔ (f = g) := begin split, { intro h, have h' := congr_arg (λ k, (ρ_ _).inv ≫ k) h, dsimp at h', rw [←right_unitor_inv_naturality, ←right_unitor_inv_naturality] at h', exact (cancel_mono _).1 h' }, { intro h, subst h, } end -- We now prove: -- ((α_ (𝟙_ C) X Y).hom) ≫ -- ((λ_ (X ⊗ Y)).hom) -- = ((λ_ X).hom ⊗ (𝟙 Y)) -- (and the corresponding fact for right unitors) -- following the proof on nLab: -- Lemma 2.2 at <https://ncatlab.org/nlab/revision/monoidal+category/115> lemma left_unitor_product_aux_perimeter (X Y : C) : ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom ≫ ((𝟙 (𝟙_ C)) ⊗ (α_ (𝟙_ C) X Y).hom) ≫ ((𝟙 (𝟙_ C)) ⊗ (λ_ (X ⊗ Y)).hom) = (((ρ_ (𝟙_ C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) X Y).hom := begin conv_lhs { congr, skip, rw [←category.assoc] }, rw [←category.assoc, monoidal_category.pentagon, associator_naturality, tensor_id, ←monoidal_category.triangle, ←category.assoc] end lemma left_unitor_product_aux_triangle (X Y : C) : ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y)) ≫ (((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom) ⊗ (𝟙 Y)) = ((ρ_ (𝟙_ C)).hom ⊗ (𝟙 X)) ⊗ (𝟙 Y) := by rw [←comp_tensor_id, ←monoidal_category.triangle] lemma left_unitor_product_aux_square (X Y : C) : (α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom ≫ ((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom ⊗ (𝟙 Y)) = (((𝟙 (𝟙_ C)) ⊗ (λ_ X).hom) ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) X Y).hom := by rw associator_naturality lemma left_unitor_product_aux (X Y : C) : ((𝟙 (𝟙_ C)) ⊗ (α_ (𝟙_ C) X Y).hom) ≫ ((𝟙 (𝟙_ C)) ⊗ (λ_ (X ⊗ Y)).hom) = (𝟙 (𝟙_ C)) ⊗ ((λ_ X).hom ⊗ (𝟙 Y)) := begin rw ←(cancel_epi (α_ (𝟙_ C) ((𝟙_ C) ⊗ X) Y).hom), rw left_unitor_product_aux_square, rw ←(cancel_epi ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ (𝟙 Y))), slice_rhs 1 2 { rw left_unitor_product_aux_triangle }, conv_lhs { rw [left_unitor_product_aux_perimeter] } end lemma right_unitor_product_aux_perimeter (X Y : C) : ((α_ X Y (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫ (α_ X (Y ⊗ (𝟙_ C)) (𝟙_ C)).hom ≫ ((𝟙 X) ⊗ (α_ Y (𝟙_ C) (𝟙_ C)).hom) ≫ ((𝟙 X) ⊗ (𝟙 Y) ⊗ (λ_ (𝟙_ C)).hom) = ((ρ_ (X ⊗ Y)).hom ⊗ (𝟙 (𝟙_ C))) ≫ (α_ X Y (𝟙_ C)).hom := begin transitivity (((α_ X Y _).hom ⊗ 𝟙 _) ≫ (α_ X _ _).hom ≫ (𝟙 X ⊗ (α_ Y _ _).hom)) ≫ (𝟙 X ⊗ 𝟙 Y ⊗ (λ_ _).hom), { conv_lhs { congr, skip, rw [←category.assoc] }, conv_rhs { rw [category.assoc] } }, { conv_lhs { congr, rw [monoidal_category.pentagon] }, conv_rhs { congr, rw [←monoidal_category.triangle] }, conv_rhs { rw [category.assoc] }, conv_rhs { congr, skip, congr, congr, rw [←tensor_id] }, conv_rhs { congr, skip, rw [associator_naturality] }, conv_rhs { rw [←category.assoc] } } end lemma right_unitor_product_aux_triangle (X Y : C) : ((𝟙 X) ⊗ (α_ Y (𝟙_ C) (𝟙_ C)).hom) ≫ ((𝟙 X) ⊗ (𝟙 Y) ⊗ (λ_ (𝟙_ C)).hom) = (𝟙 X) ⊗ (ρ_ Y).hom ⊗ (𝟙 (𝟙_ C)) := by rw [←id_tensor_comp, ←monoidal_category.triangle] lemma right_unitor_product_aux_square (X Y : C) : (α_ X (Y ⊗ (𝟙_ C)) (𝟙_ C)).hom ≫ ((𝟙 X) ⊗ (ρ_ Y).hom ⊗ (𝟙 (𝟙_ C))) = (((𝟙 X) ⊗ (ρ_ Y).hom) ⊗ (𝟙 (𝟙_ C))) ≫ (α_ X Y (𝟙_ C)).hom := by rw [associator_naturality] lemma right_unitor_product_aux (X Y : C) : ((α_ X Y (𝟙_ C)).hom ⊗ (𝟙 (𝟙_ C))) ≫ (((𝟙 X) ⊗ (ρ_ Y).hom) ⊗ (𝟙 (𝟙_ C))) = ((ρ_ (X ⊗ Y)).hom ⊗ (𝟙 (𝟙_ C))) := begin rw ←(cancel_mono (α_ X Y (𝟙_ C)).hom), slice_lhs 2 3 { rw ←right_unitor_product_aux_square }, rw [←right_unitor_product_aux_triangle, ←right_unitor_product_aux_perimeter], end -- See Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf> @[simp] lemma left_unitor_tensor (X Y : C) : ((α_ (𝟙_ C) X Y).hom) ≫ ((λ_ (X ⊗ Y)).hom) = ((λ_ X).hom ⊗ (𝟙 Y)) := by rw [←tensor_left_iff, id_tensor_comp, left_unitor_product_aux] @[simp] lemma left_unitor_tensor_inv (X Y : C) : ((λ_ (X ⊗ Y)).inv) ≫ ((α_ (𝟙_ C) X Y).inv) = ((λ_ X).inv ⊗ (𝟙 Y)) := eq_of_inv_eq_inv (by simp) @[simp] lemma right_unitor_tensor (X Y : C) : ((α_ X Y (𝟙_ C)).hom) ≫ ((𝟙 X) ⊗ (ρ_ Y).hom) = ((ρ_ (X ⊗ Y)).hom) := by rw [←tensor_right_iff, comp_tensor_id, right_unitor_product_aux] @[simp] lemma right_unitor_tensor_inv (X Y : C) : ((𝟙 X) ⊗ (ρ_ Y).inv) ≫ ((α_ X Y (𝟙_ C)).inv) = ((ρ_ (X ⊗ Y)).inv) := eq_of_inv_eq_inv (by simp) lemma associator_inv_naturality {X Y Z X' Y' Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') : (f ⊗ (g ⊗ h)) ≫ (α_ X' Y' Z').inv = (α_ X Y Z).inv ≫ ((f ⊗ g) ⊗ h) := begin apply (cancel_mono (α_ X' Y' Z').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [associator_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end lemma pentagon_inv (W X Y Z : C) : ((𝟙 W) ⊗ (α_ X Y Z).inv) ≫ (α_ W (X ⊗ Y) Z).inv ≫ ((α_ W X Y).inv ⊗ (𝟙 Z)) = (α_ W X (Y ⊗ Z)).inv ≫ (α_ (W ⊗ X) Y Z).inv := begin apply category_theory.eq_of_inv_eq_inv, dsimp, rw [category.assoc, monoidal_category.pentagon] end lemma triangle_assoc_comp_left (X Y : C) : (α_ X (𝟙_ C) Y).hom ≫ ((𝟙 X) ⊗ (λ_ Y).hom) = (ρ_ X).hom ⊗ 𝟙 Y := monoidal_category.triangle X Y @[simp] lemma triangle_assoc_comp_right (X Y : C) : (α_ X (𝟙_ C) Y).inv ≫ ((ρ_ X).hom ⊗ 𝟙 Y) = ((𝟙 X) ⊗ (λ_ Y).hom) := by rw [←triangle_assoc_comp_left, ←category.assoc, iso.inv_hom_id, category.id_comp] @[simp] lemma triangle_assoc_comp_right_inv (X Y : C) : ((ρ_ X).inv ⊗ 𝟙 Y) ≫ (α_ X (𝟙_ C) Y).hom = ((𝟙 X) ⊗ (λ_ Y).inv) := begin apply (cancel_mono (𝟙 X ⊗ (λ_ Y).hom)).1, simp only [assoc, triangle_assoc_comp_left], rw [←comp_tensor_id, iso.inv_hom_id, ←id_tensor_comp, iso.inv_hom_id] end @[simp] lemma triangle_assoc_comp_left_inv (X Y : C) : ((𝟙 X) ⊗ (λ_ Y).inv) ≫ (α_ X (𝟙_ C) Y).inv = ((ρ_ X).inv ⊗ 𝟙 Y) := begin apply (cancel_mono ((ρ_ X).hom ⊗ 𝟙 Y)).1, simp only [triangle_assoc_comp_right, assoc], rw [←id_tensor_comp, iso.inv_hom_id, ←comp_tensor_id, iso.inv_hom_id] end end section variables (C : Type u) [category.{v} C] [monoidal_category.{v} C] /-- The tensor product expressed as a functor. -/ def tensor : (C × C) ⥤ C := { obj := λ X, X.1 ⊗ X.2, map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 } /-- The left-associated triple tensor product as a functor. -/ def left_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2, map := λ {X Y : C × C × C} (f : X ⟶ Y), (f.1 ⊗ f.2.1) ⊗ f.2.2 } @[simp] lemma left_assoc_tensor_obj (X) : (left_assoc_tensor C).obj X = (X.1 ⊗ X.2.1) ⊗ X.2.2 := rfl @[simp] lemma left_assoc_tensor_map {X Y} (f : X ⟶ Y) : (left_assoc_tensor C).map f = (f.1 ⊗ f.2.1) ⊗ f.2.2 := rfl /-- The right-associated triple tensor product as a functor. -/ def right_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2), map := λ {X Y : C × C × C} (f : X ⟶ Y), f.1 ⊗ (f.2.1 ⊗ f.2.2) } @[simp] lemma right_assoc_tensor_obj (X) : (right_assoc_tensor C).obj X = X.1 ⊗ (X.2.1 ⊗ X.2.2) := rfl @[simp] lemma right_assoc_tensor_map {X Y} (f : X ⟶ Y) : (right_assoc_tensor C).map f = f.1 ⊗ (f.2.1 ⊗ f.2.2) := rfl /-- The functor `λ X, 𝟙_ C ⊗ X`. -/ def tensor_unit_left : C ⥤ C := { obj := λ X, 𝟙_ C ⊗ X, map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (𝟙_ C)) ⊗ f } /-- The functor `λ X, X ⊗ 𝟙_ C`. -/ def tensor_unit_right : C ⥤ C := { obj := λ X, X ⊗ 𝟙_ C, map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (𝟙_ C)) } -- We can express the associator and the unitors, given componentwise above, -- as natural isomorphisms. /-- The associator as a natural isomorphism. -/ @[simps {rhs_md := semireducible}] def associator_nat_iso : left_assoc_tensor C ≅ right_assoc_tensor C := nat_iso.of_components (by { intros, apply monoidal_category.associator }) (by { intros, apply monoidal_category.associator_naturality }) /-- The left unitor as a natural isomorphism. -/ @[simps {rhs_md := semireducible}] def left_unitor_nat_iso : tensor_unit_left C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.left_unitor }) (by { intros, apply monoidal_category.left_unitor_naturality }) /-- The right unitor as a natural isomorphism. -/ @[simps {rhs_md := semireducible}] def right_unitor_nat_iso : tensor_unit_right C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.right_unitor }) (by { intros, apply monoidal_category.right_unitor_naturality }) section variables {C} /-- Tensoring on the left with as fixed object, as a functor. -/ @[simps] def tensor_left (X : C) : C ⥤ C := { obj := λ Y, X ⊗ Y, map := λ Y Y' f, (𝟙 X) ⊗ f, } /-- Tensoring on the left with `X ⊗ Y` is naturally isomorphic to tensoring on the left with `Y`, and then again with `X`. -/ def tensor_left_tensor (X Y : C) : tensor_left (X ⊗ Y) ≅ tensor_left Y ⋙ tensor_left X := nat_iso.of_components (associator _ _) (λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_naturality }) @[simp] lemma tensor_left_tensor_hom_app (X Y Z : C) : (tensor_left_tensor X Y).hom.app Z = (associator X Y Z).hom := rfl @[simp] lemma tensor_left_tensor_inv_app (X Y Z : C) : (tensor_left_tensor X Y).inv.app Z = (associator X Y Z).inv := rfl /-- Tensoring on the right with as fixed object, as a functor. -/ @[simps] def tensor_right (X : C) : C ⥤ C := { obj := λ Y, Y ⊗ X, map := λ Y Y' f, f ⊗ (𝟙 X), } variables (C) /-- Tensoring on the right, as a functor from `C` into endofunctors of `C`. We later show this is a monoidal functor. -/ @[simps] def tensoring_right : C ⥤ (C ⥤ C) := { obj := tensor_right, map := λ X Y f, { app := λ Z, (𝟙 Z) ⊗ f } } instance : faithful (tensoring_right C) := { map_injective' := λ X Y f g h, begin injections with h, replace h := congr_fun h (𝟙_ C), simpa using h, end } variables {C} /-- Tensoring on the right with `X ⊗ Y` is naturally isomorphic to tensoring on the right with `X`, and then again with `Y`. -/ def tensor_right_tensor (X Y : C) : tensor_right (X ⊗ Y) ≅ tensor_right X ⋙ tensor_right Y := nat_iso.of_components (λ Z, (associator Z X Y).symm) (λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_inv_naturality }) @[simp] lemma tensor_right_tensor_hom_app (X Y Z : C) : (tensor_right_tensor X Y).hom.app Z = (associator Z X Y).inv := rfl @[simp] lemma tensor_right_tensor_inv_app (X Y Z : C) : (tensor_right_tensor X Y).inv.app Z = (associator Z X Y).hom := rfl end end end monoidal_category end category_theory
21741dfe9dc2c7e1fac4b3d3f4d5b9b6eda68571
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/data/fin/ops.lean
96f81a7f97a9f34aeecb007dfada4087bebbdfe0
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
3,886
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat init.data.fin.basic namespace fin open nat variable {n : nat} protected def succ : fin n → fin (succ n) | ⟨a, h⟩ := ⟨nat.succ a, succ_lt_succ h⟩ def of_nat {n : nat} (a : nat) : fin (succ n) := ⟨a % succ n, nat.mod_lt _ (nat.zero_lt_succ _)⟩ private lemma mlt {n b : nat} : ∀ {a}, n > a → b % n < n | 0 h := nat.mod_lt _ h | (a+1) h := have n > 0, from lt.trans (nat.zero_lt_succ _) h, nat.mod_lt _ this protected def add : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a + b) % n, mlt h⟩ protected def mul : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a * b) % n, mlt h⟩ private lemma sublt {a b n : nat} (h : a < n) : a - b < n := lt_of_le_of_lt (nat.sub_le a b) h protected def sub : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a - b, sublt h⟩ private lemma modlt {a b n : nat} (h₁ : a < n) (h₂ : b < n) : a % b < n := begin cases b with b, {simp [mod_zero], assumption}, {assert h : a % (succ b) < succ b, apply nat.mod_lt _ (nat.zero_lt_succ _), exact lt.trans h h₂} end protected def mod : fin n → fin n → fin n | ⟨a, h₁⟩ ⟨b, h₂⟩ := ⟨a % b, modlt h₁ h₂⟩ private lemma divlt {a b n : nat} (h : a < n) : a / b < n := lt_of_le_of_lt (nat.div_le_self a b) h protected def div : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a / b, divlt h⟩ protected def lt : fin n → fin n → Prop | ⟨a, _⟩ ⟨b, _⟩ := a < b protected def le : fin n → fin n → Prop | ⟨a, _⟩ ⟨b, _⟩ := a ≤ b instance : has_zero (fin (succ n)) := ⟨⟨0, succ_pos n⟩⟩ instance : has_one (fin (succ n)) := ⟨of_nat 1⟩ instance : has_add (fin n) := ⟨fin.add⟩ instance : has_sub (fin n) := ⟨fin.sub⟩ instance : has_mul (fin n) := ⟨fin.mul⟩ instance : has_mod (fin n) := ⟨fin.mod⟩ instance : has_div (fin n) := ⟨fin.div⟩ instance : has_lt (fin n) := ⟨fin.lt⟩ instance : has_le (fin n) := ⟨fin.le⟩ instance decidable_lt : ∀ (a b : fin n), decidable (a < b) | ⟨a, _⟩ ⟨b, _⟩ := by apply nat.decidable_lt instance decidable_le : ∀ (a b : fin n), decidable (a ≤ b) | ⟨a, _⟩ ⟨b, _⟩ := by apply nat.decidable_le lemma of_nat_zero : @of_nat n 0 = 0 := fin.eq_of_veq $ zero_mod n.succ lemma add_def (a b : fin n) : (a + b).val = (a.val + b.val) % n := show (fin.add a b).val = (a.val + b.val) % n, from by cases a; cases b; simp [fin.add] lemma mul_def (a b : fin n) : (a * b).val = (a.val * b.val) % n := show (fin.mul a b).val = (a.val * b.val) % n, from by cases a; cases b; simp [fin.mul] lemma sub_def (a b : fin n) : (a - b).val = a.val - b.val := show (fin.sub a b).val = a.val - b.val, from by cases a; cases b; simp [fin.sub] lemma mod_def (a b : fin n) : (a % b).val = a.val % b.val := show (fin.mod a b).val = a.val % b.val, from by cases a; cases b; simp [fin.mod] lemma div_def (a b : fin n) : (a / b).val = a.val / b.val := show (fin.div a b).val = a.val / b.val, from by cases a; cases b; simp [fin.div] lemma lt_def (a b : fin n) : (a < b) = (a.val < b.val) := show (fin.lt a b) = (a.val < b.val), from by cases a; cases b; simp [fin.lt] lemma le_def (a b : fin n) : (a ≤ b) = (a.val ≤ b.val) := show (fin.le a b) = (a.val ≤ b.val), from by cases a; cases b; simp [fin.le] lemma val_zero : (0 : fin (succ n)).val = 0 := rfl def pred {n : nat} : ∀ i : fin (succ n), i ≠ 0 → fin n | ⟨a, h₁⟩ h₂ := ⟨a.pred, begin assert this : a ≠ 0, { note aux₁ := vne_of_ne h₂, dsimp at aux₁, rw val_zero at aux₁, exact aux₁ }, exact nat.pred_lt_pred this (nat.succ_ne_zero n) h₁ end⟩ end fin
0087733e21f4e5f3940031a75e42191887054ae4
7cef822f3b952965621309e88eadf618da0c8ae9
/src/geometry/manifold/manifold.lean
f480957ed31a0e41e138e6a931a5efb17feee1f6
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
26,430
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.local_homeomorph /-! # Manifolds A manifold is a topological space M locally modelled on a model space H, i.e., the manifold is covered by open subsets on which there are local homeomorphisms (the charts) going to H. If the changes of charts satisfy some additional property (for instance if they are smooth), then M inherits additional structure (it makes sense to talk about smooth manifolds). There are therefore two different ingredients in a manifold: * the set of charts, which is data * the fact that changes of charts belong to some group (in fact groupoid), which is additional Prop. We separate these two parts in the definition: the manifold structure is just the set of charts, and then the different smoothness requirements (smooth manifold, orientable manifold, contact manifold, and so on) are additional properties of these charts. These properties are formalized through the notion of structure groupoid, i.e., a set of local homeomorphisms stable under composition and inverse, to which the change of coordinates should belong. ## Main definitions `structure_groupoid H` : a subset of local homeomorphisms of `H` stable under composition, inverse and restriction (ex: local diffeos) `pregroupoid H` : a subset of local homeomorphisms of `H` stable under composition and restriction, but not inverse (ex: smooth maps) `groupoid_of_pregroupoid`: construct a groupoid from a pregroupoid, by requiring that a map and its inverse both belong to the pregroupoid (ex: construct diffeos from smooth maps) `continuous_groupoid H` : the groupoid of all local homeomorphisms of `H` `manifold H M` : manifold structure on M modelled on H, given by an atlas of local homeomorphisms from M to H whose sources cover M. This is a type class. `has_groupoid M G` : when `G` is a structure groupoid on `H` and `M` is a manifold modelled on `H`, require that all coordinate changes belong to `G`. This is a type class `atlas H M` : when `M` is a manifold modelled on `H`, the atlas of this manifold structure, i.e., the set of charts `structomorph G M M'` : the set of diffeomorphisms between the manifolds M and M' for the groupoid G. We avoid the word diffeomorphisms, keeping it for the smooth category. As a basic example, we give the instance `instance manifold_model_space (H : Type*) [topological_space H] : manifold H H` saying that a topological space is a manifold over itself, with the identity as unique chart. This manifold structure is compatible with any groupoid. ## Implementation notes The atlas in a manifold is *not* a maximal atlas in general: the notion of maximality depends on the groupoid one considers, and changing groupoids changes the maximal atlas. With the current formalization, it makes sense first to choose the atlas, and then to ask whether this precise atlas defines a smooth manifold, an orientable manifold, and so on. A consequence is that structomorphisms between M and M' do *not* induce a bijection between the atlases of M and M': the definition is only that, read in charts, the structomorphism locally belongs to the groupoid under consideration. (This is equivalent to inducing a bijection between elements of the maximal atlas). A consequence is that the invariance under structomorphisms of properties defined in terms of the atlas is not obvious in general, and could require some work in theory (amounting to the fact that these properties only depend on the maximal atlas, for instance). In practice, this does not create any real difficulty. We use the letter `H` for the model space thinking of the case of manifolds with boundary, where the model space is a half space. Manifolds are sometimes defined as topological spaces with an atlas of local diffeomorphisms, and sometimes as spaces with an atlas from which a topology is deduced. We use the former approach: otherwise, there would be an instance from manifolds to topological spaces, which means that any instance search for topological spaces would try to find manifold structures involving a yet unknown model space, leading to problems. However, we also introduce the latter approach, through a structure `manifold_core` making it possible to construct a topology out of a set of local equivs with compatibility conditions (but we do not register it as an instance). In the definition of a manifold, the model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over ℂ^n) will also be seen sometimes as a real manifold modelled over ℝ^(2n). -/ noncomputable theory local attribute [instance, priority 0] classical.decidable_inhabited classical.prop_decidable universes u variables {H : Type u} {M : Type*} {M' : Type*} {M'' : Type*} /- Notational shortcut for the composition of local homeomorphisms, i.e., `local_homeomorph.trans`. Note that, as is usual for equivs, the composition is from left to right, hence the direction of the arrow. -/ local infixr ` ≫ₕ `:100 := local_homeomorph.trans open set local_homeomorph section groupoid /- One could add to the definition of a structure groupoid the fact that the restriction of an element of the groupoid to any open set still belongs to the groupoid. (This is in Kobayashi-Nomizu.) I am not sure I want this, for instance on H × E where E is a vector space, and the groupoid is made of functions respecting the fibers and linear in the fibers (so that a manifold over this groupoid is naturally a vector bundle) I prefer that the members of the groupoid are always defined on sets of the form s × E The only nontrivial requirement is locality: if a local homeomorphism belongs to the groupoid around each point in its domain of definition, then it belongs to the groupoid. Without this requirement, the composition of diffeomorphisms does not have to be a diffeomorphism. Note that this implies that a local homeomorphism with empty source belongs to any structure groupoid, as it trivially satisfies this condition. There is also a technical point, related to the fact that a local homeomorphism is by definition a global map which is a homeomorphism when restricted to its source subset (and its values outside of the source are not relevant). Therefore, we also require that being a member of the groupoid only depends on the values on the source. -/ /-- A structure groupoid is a set of local homeomorphisms of a topological space stable under composition and inverse. They appear in the definition of the smoothness class of a manifold. -/ structure structure_groupoid (H : Type u) [topological_space H] := (members : set (local_homeomorph H H)) (comp : ∀e e' : local_homeomorph H H, e ∈ members → e' ∈ members → e ≫ₕ e' ∈ members) (inv : ∀e : local_homeomorph H H, e ∈ members → e.symm ∈ members) (id_mem : local_homeomorph.refl H ∈ members) (locality : ∀e : local_homeomorph H H, (∀x ∈ e.source, ∃s, is_open s ∧ x ∈ s ∧ e.restr s ∈ members) → e ∈ members) (eq_on_source : ∀ e e' : local_homeomorph H H, e ∈ members → e' ≈ e → e' ∈ members) variable [topological_space H] @[reducible] instance : has_mem (local_homeomorph H H) (structure_groupoid H) := ⟨λ(e : local_homeomorph H H) (G : structure_groupoid H), e ∈ G.members⟩ /-- Partial order on the set of groupoids, given by inclusion of the members of the groupoid -/ instance structure_groupoid.partial_order : partial_order (structure_groupoid H) := partial_order.lift structure_groupoid.members (λa b h, by { cases a, cases b, dsimp at h, induction h, refl }) (by apply_instance) /-- The trivial groupoid, containing only the identity (and maps with empty source, as this is necessary from the definition) -/ def id_groupoid (H : Type u) [topological_space H] : structure_groupoid H := { members := {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅}, comp := λe e' he he', begin cases he; simp at he he', { simpa [he] }, { have : (e ≫ₕ e').source ⊆ e.source := sep_subset _ _, rw he at this, have : (e ≫ₕ e') ∈ {e : local_homeomorph H H | e.source = ∅} := disjoint_iff.1 this, exact (mem_union _ _ _).2 (or.inr this) }, end, inv := λe he, begin cases (mem_union _ _ _).1 he with E E, { finish }, { right, simpa [e.to_local_equiv.image_source_eq_target.symm] using E }, end, id_mem := mem_union_left _ (mem_insert _ ∅), locality := λe he, begin by_cases h : e.source = ∅, { right, exact h }, { left, rcases ne_empty_iff_exists_mem.1 h with ⟨x, hx⟩, rcases he x hx with ⟨s, open_s, xs, hs⟩, have x's : x ∈ (e.restr s).source, { rw [restr_source, interior_eq_of_open open_s], exact ⟨hx, xs⟩ }, cases hs, { replace hs : local_homeomorph.restr e s = local_homeomorph.refl H, by simpa using hs, have : (e.restr s).source = univ, by { rw hs, simp }, change (e.to_local_equiv).source ∩ interior s = univ at this, have : univ ⊆ interior s, by { rw ← this, exact inter_subset_right _ _ }, have : s = univ, by rwa [interior_eq_of_open open_s, univ_subset_iff] at this, simpa [this, restr_univ] using hs }, { exfalso, rw mem_set_of_eq at hs, rwa hs at x's } }, end, eq_on_source := λe e' he he'e, begin cases he, { left, have : e = e', { refine eq_of_eq_on_source_univ (setoid.symm he'e) _ _; rw set.mem_singleton_iff.1 he ; refl }, rwa ← this }, { right, change (e.to_local_equiv).source = ∅ at he, rwa [set.mem_set_of_eq, source_eq_of_eq_on_source he'e] } end } /-- Every structure groupoid contains the identity groupoid -/ instance : lattice.order_bot (structure_groupoid H) := { bot := id_groupoid H, bot_le := begin assume u f hf, change f ∈ {local_homeomorph.refl H} ∪ {e : local_homeomorph H H | e.source = ∅} at hf, simp only [singleton_union, mem_set_of_eq, mem_insert_iff] at hf, cases hf, { rw hf, apply u.id_mem }, { apply u.locality, assume x hx, rw [hf, mem_empty_eq] at hx, exact hx.elim } end, ..structure_groupoid.partial_order } /-- To construct a groupoid, one may consider classes of local homeos such that both the function and its inverse have some property. If this property is stable under composition, one gets a groupoid. `pregroupoid` bundles the properties needed for this construction, with the groupoid of smooth functions with smooth inverses as an application. -/ structure pregroupoid (H : Type*) [topological_space H] := (property : (H → H) → (set H) → Prop) (comp : ∀{f g u v}, property f u → property g v → is_open (u ∩ f ⁻¹' v) → property (g ∘ f) (u ∩ f ⁻¹' v)) (id_mem : property id univ) (locality : ∀{f u}, is_open u → (∀x∈u, ∃v, is_open v ∧ x ∈ v ∧ property f (u ∩ v)) → property f u) (congr : ∀{f g : H → H} {u}, is_open u → (∀x∈u, g x = f x) → property f u → property g u) /-- Construct a groupoid of local homeos for which the map and its inverse have some property, from a pregroupoid asserting that this property is stable under composition. -/ def pregroupoid.groupoid (PG : pregroupoid H) : structure_groupoid H := { members := {e : local_homeomorph H H | PG.property e.to_fun e.source ∧ PG.property e.inv_fun e.target}, comp := λe e' he he', begin split, { apply PG.comp he.1 he'.1, apply e.continuous_to_fun.preimage_open_of_open e.open_source e'.open_source }, { apply PG.comp he'.2 he.2, apply e'.continuous_inv_fun.preimage_open_of_open e'.open_target e.open_target } end, inv := λe he, ⟨he.2, he.1⟩, id_mem := ⟨PG.id_mem, PG.id_mem⟩, locality := λe he, begin split, { apply PG.locality e.open_source (λx xu, _), rcases he x xu with ⟨s, s_open, xs, hs⟩, refine ⟨s, s_open, xs, _⟩, convert hs.1, exact (interior_eq_of_open s_open).symm }, { apply PG.locality e.open_target (λx xu, _), rcases he (e.inv_fun x) (e.map_target xu) with ⟨s, s_open, xs, hs⟩, refine ⟨e.target ∩ e.inv_fun ⁻¹' s, _, ⟨xu, xs⟩, _⟩, { exact continuous_on.preimage_open_of_open e.continuous_inv_fun e.open_target s_open }, { rw [← inter_assoc, inter_self], convert hs.2, exact (interior_eq_of_open s_open).symm } }, end, eq_on_source := λe e' he ee', begin split, { apply PG.congr e'.open_source ee'.2, simp only [ee'.1, he.1] }, { have A := eq_on_source_symm ee', apply PG.congr e'.symm.open_source A.2, convert he.2, rw A.1, refl } end } lemma mem_groupoid_of_pregroupoid (PG : pregroupoid H) (e : local_homeomorph H H) : e ∈ PG.groupoid ↔ PG.property e.to_fun e.source ∧ PG.property e.inv_fun e.target := iff.rfl lemma groupoid_of_pregroupoid_le (PG₁ PG₂ : pregroupoid H) (h : ∀f s, PG₁.property f s → PG₂.property f s) : PG₁.groupoid ≤ PG₂.groupoid := begin assume e he, rw mem_groupoid_of_pregroupoid at he ⊢, exact ⟨h _ _ he.1, h _ _ he.2⟩ end lemma mem_pregroupoid_of_eq_on_source (PG : pregroupoid H) {e e' : local_homeomorph H H} (he' : e ≈ e') (he : PG.property e.to_fun e.source) : PG.property e'.to_fun e'.source := begin rw ← he'.1, exact PG.congr e.open_source (λx hx, (he'.2 x hx).symm) he, end /-- The groupoid of all local homeomorphisms on a topological space H -/ def continuous_groupoid (H : Type*) [topological_space H] : structure_groupoid H := pregroupoid.groupoid { property := λf s, true, comp := λf g u v hf hg huv, trivial, id_mem := trivial, locality := λf u u_open h, trivial, congr := λf g u u_open hcongr hf, trivial } /-- Every structure groupoid is contained in the groupoid of all local homeomorphisms -/ instance : lattice.order_top (structure_groupoid H) := { top := continuous_groupoid H, le_top := λ u f hf, by { split; exact dec_trivial }, ..structure_groupoid.partial_order } end groupoid /-- A manifold is a topological space endowed with an atlas, i.e., a set of local homeomorphisms taking value in a model space H, called charts, such that the domains of the charts cover the whole space. We express the covering property by chosing for each x a member `chart_at x` of the atlas containing x in its source: in the smooth case, this is convenient to construct the tangent bundle in an efficient way. The model space is written as an explicit parameter as there can be several model spaces for a given topological space. For instance, a complex manifold (modelled over ℂ^n) will also be seen sometimes as a real manifold over ℝ^(2n). -/ class manifold (H : Type*) [topological_space H] (M : Type*) [topological_space M] := (atlas : set (local_homeomorph M H)) (chart_at : M → local_homeomorph M H) (mem_chart_source : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas : ∀x, chart_at x ∈ atlas) export manifold attribute [simp] mem_chart_source chart_mem_atlas section manifold /-- Any space is a manifold modelled over itself, by just using the identity chart -/ instance manifold_model_space (H : Type*) [topological_space H] : manifold H H := { atlas := {local_homeomorph.refl H}, chart_at := λx, local_homeomorph.refl H, mem_chart_source := λx, mem_univ x, chart_mem_atlas := λx, mem_singleton _ } /-- In the trivial manifold structure of a space modelled over itself through the identity, the atlas members are just the identity -/ @[simp] lemma model_space_atlas {H : Type*} [topological_space H] {e : local_homeomorph H H} : e ∈ atlas H H ↔ e = local_homeomorph.refl H := by simp [atlas, manifold.atlas] /-- In the model space, chart_at is always the identity -/ @[simp] lemma chart_at_model_space_eq {H : Type*} [topological_space H] {x : H} : chart_at H x = local_homeomorph.refl H := by simpa using chart_mem_atlas H x end manifold /-- Sometimes, one may want to construct a manifold structure on a space which does not yet have a topological structure, where the topology would come from the charts. For this, one needs charts that are only local equivs, and continuity properties for their composition. This is formalised in `manifold_core`. -/ structure manifold_core (H : Type*) [topological_space H] (M : Type*) := (atlas : set (local_equiv M H)) (chart_at : M → local_equiv M H) (mem_chart_source : ∀x, x ∈ (chart_at x).source) (chart_mem_atlas : ∀x, chart_at x ∈ atlas) (open_source : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → is_open (e.symm.trans e').source) (continuous_to_fun : ∀e e' : local_equiv M H, e ∈ atlas → e' ∈ atlas → continuous_on (e.symm.trans e').to_fun (e.symm.trans e').source) namespace manifold_core variables [topological_space H] (c : manifold_core H M) {e : local_equiv M H} /-- Topology generated by a set of charts on a Type. -/ protected def to_topological_space : topological_space M := topological_space.generate_from $ ⋃ (e : local_equiv M H) (he : e ∈ c.atlas) (s : set H) (s_open : is_open s), {e.to_fun ⁻¹' s ∩ e.source} lemma open_source' (he : e ∈ c.atlas) : @is_open M c.to_topological_space e.source := begin apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], refine ⟨e, he, univ, is_open_univ, _⟩, simp only [set.univ_inter, set.preimage_univ] end lemma open_target (he : e ∈ c.atlas) : is_open e.target := begin have E : e.target ∩ e.inv_fun ⁻¹' e.source = e.target := subset.antisymm (inter_subset_left _ _) (λx hx, ⟨hx, local_equiv.target_subset_preimage_source _ hx⟩), simpa [local_equiv.trans_source, E] using c.open_source e e he he end def local_homeomorph (e : local_equiv M H) (he : e ∈ c.atlas) : @local_homeomorph M H c.to_topological_space _ := { open_source := by convert c.open_source' he, open_target := by convert c.open_target he, continuous_to_fun := begin letI : topological_space M := c.to_topological_space, rw continuous_on_open_iff (c.open_source' he), assume s s_open, rw inter_comm, apply topological_space.generate_open.basic, simp only [exists_prop, mem_Union, mem_singleton_iff], exact ⟨e, he, ⟨s, s_open, rfl⟩⟩ end, continuous_inv_fun := begin letI : topological_space M := c.to_topological_space, apply continuous_on_open_of_generate_from (c.open_target he), assume t ht, simp only [exists_prop, mem_Union, mem_singleton_iff] at ht, rcases ht with ⟨e', e'_atlas, s, s_open, ts⟩, rw ts, let f := e.symm.trans e', have : is_open (f.to_fun ⁻¹' s ∩ f.source), by simpa [inter_comm] using (continuous_on_open_iff (c.open_source e e' he e'_atlas)).1 (c.continuous_to_fun e e' he e'_atlas) s s_open, have A : e'.to_fun ∘ e.inv_fun ⁻¹' s ∩ (e.target ∩ e.inv_fun ⁻¹' e'.source) = e.target ∩ (e'.to_fun ∘ e.inv_fun ⁻¹' s ∩ e.inv_fun ⁻¹' e'.source), by { rw [← inter_assoc, ← inter_assoc], congr' 1, exact inter_comm _ _ }, simpa [local_equiv.trans_source, preimage_inter, preimage_comp.symm, A] using this end, ..e } def to_manifold : @manifold H _ M c.to_topological_space := { atlas := ⋃ (e : local_equiv M H) (he : e ∈ c.atlas), {c.local_homeomorph e he}, chart_at := λx, c.local_homeomorph (c.chart_at x) (c.chart_mem_atlas x), mem_chart_source := λx, c.mem_chart_source x, chart_mem_atlas := λx, begin simp only [mem_Union, mem_singleton_iff], exact ⟨c.chart_at x, c.chart_mem_atlas x, rfl⟩, end } end manifold_core section has_groupoid variables [topological_space H] [topological_space M] [manifold H M] /-- A manifold has an atlas in a groupoid G if the change of coordinates belong to the groupoid -/ class has_groupoid {H : Type*} [topological_space H] (M : Type*) [topological_space M] [manifold H M] (G : structure_groupoid H) : Prop := (compatible : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → e.symm ≫ₕ e' ∈ G) lemma has_groupoid_of_le {G₁ G₂ : structure_groupoid H} (h : has_groupoid M G₁) (hle : G₁ ≤ G₂) : has_groupoid M G₂ := ⟨ λ e e' he he', hle ((h.compatible : _) he he') ⟩ lemma has_groupoid_of_pregroupoid (PG : pregroupoid H) (h : ∀{e e' : local_homeomorph M H}, e ∈ atlas H M → e' ∈ atlas H M → PG.property (e.symm ≫ₕ e').to_fun (e.symm ≫ₕ e').source) : has_groupoid M (PG.groupoid) := ⟨assume e e' he he', (mem_groupoid_of_pregroupoid PG _).mpr ⟨h he he', h he' he⟩⟩ /-- The trivial manifold structure on the model space is compatible with any groupoid -/ instance has_groupoid_model_space (H : Type*) [topological_space H] (G : structure_groupoid H) : has_groupoid H G := { compatible := λe e' he he', begin replace he : e ∈ atlas H H := he, replace he' : e' ∈ atlas H H := he', rw model_space_atlas at he he', simp [he, he', structure_groupoid.id_mem] end } /-- Any manifold structure is compatible with the groupoid of all local homeomorphisms -/ instance has_groupoid_continuous_groupoid : has_groupoid M (continuous_groupoid H) := ⟨begin assume e e' he he', rw [continuous_groupoid, mem_groupoid_of_pregroupoid], simp only [and_self] end⟩ /-- A G-diffeomorphism between two manifolds is a homeomorphism which, when read in the charts, belongs to G. We avoid the word diffeomorph as it is too related to the smooth category, and use structomorph instead. -/ structure structomorph (G : structure_groupoid H) (M : Type*) (M' : Type*) [topological_space M] [topological_space M'] [manifold H M] [manifold H M'] extends homeomorph M M' := (to_fun_mem_groupoid : ∀c : local_homeomorph M H, ∀c' : local_homeomorph M' H, c ∈ atlas H M → c' ∈ atlas H M' → c.symm ≫ₕ to_homeomorph.to_local_homeomorph ≫ₕ c' ∈ G) variables [topological_space M'] [topological_space M''] {G : structure_groupoid H} [manifold H M'] [manifold H M''] /-- The identity is a diffeomorphism of any manifold, for any groupoid. -/ def structomorph.refl (M : Type*) [topological_space M] [manifold H M] [has_groupoid M G] : structomorph G M M := { to_fun_mem_groupoid := λc c' hc hc', begin change (local_homeomorph.symm c) ≫ₕ (local_homeomorph.refl M) ≫ₕ c' ∈ G, rw local_homeomorph.refl_trans, exact has_groupoid.compatible G hc hc' end, ..homeomorph.refl M } /-- The inverse of a structomorphism is a structomorphism -/ def structomorph.symm (e : structomorph G M M') : structomorph G M' M := { to_fun_mem_groupoid := begin assume c c' hc hc', have : (c'.symm ≫ₕ e.to_homeomorph.to_local_homeomorph ≫ₕ c).symm ∈ G := G.inv _ (e.to_fun_mem_groupoid c' c hc' hc), simp at this, rwa [trans_symm_eq_symm_trans_symm, trans_symm_eq_symm_trans_symm, symm_symm, trans_assoc] at this, end, ..e.to_homeomorph.symm} /-- The composition of structomorphisms is a structomorphism -/ def structomorph.trans (e : structomorph G M M') (e' : structomorph G M' M'') : structomorph G M M'' := { to_fun_mem_groupoid := begin /- Let c and c' be two charts in M and M''. We want to show that e' ∘ e is smooth in these charts, around any point x. For this, let y = e (c⁻¹ x), and consider a chart g around y. Then g ∘ e ∘ c⁻¹ and c' ∘ e' ∘ g⁻¹ are both smooth as e and e' are structomorphisms, so their composition is smooth, and it coincides with c' ∘ e' ∘ e ∘ c⁻¹ around x. -/ assume c c' hc hc', refine G.locality _ (λx hx, _), let f₁ := e.to_homeomorph.to_local_homeomorph, let f₂ := e'.to_homeomorph.to_local_homeomorph, let f := (e.to_homeomorph.trans e'.to_homeomorph).to_local_homeomorph, have feq : f = f₁ ≫ₕ f₂ := homeomorph.trans_to_local_homeomorph _ _, -- define the atlas g around y let y := (c.symm ≫ₕ f₁).to_fun x, let g := chart_at H y, have hg₁ := chart_mem_atlas H y, have hg₂ := mem_chart_source H y, let s := (c.symm ≫ₕ f₁).source ∩ (c.symm ≫ₕ f₁).to_fun ⁻¹' g.source, have open_s : is_open s, by apply (c.symm ≫ₕ f₁).continuous_to_fun.preimage_open_of_open; apply open_source, have : x ∈ s, { split, { simp only [trans_source, preimage_univ, inter_univ, homeomorph.to_local_homeomorph_source], rw trans_source at hx, exact hx.1 }, { exact hg₂ } }, refine ⟨s, open_s, ⟨this, _⟩⟩, let F₁ := (c.symm ≫ₕ f₁ ≫ₕ g) ≫ₕ (g.symm ≫ₕ f₂ ≫ₕ c'), have A : F₁ ∈ G := G.comp _ _ (e.to_fun_mem_groupoid c g hc hg₁) (e'.to_fun_mem_groupoid g c' hg₁ hc'), let F₂ := (c.symm ≫ₕ f ≫ₕ c').restr s, have : F₁ ≈ F₂ := calc F₁ ≈ c.symm ≫ₕ f₁ ≫ₕ (g ≫ₕ g.symm) ≫ₕ f₂ ≫ₕ c' : by simp [F₁, trans_assoc] ... ≈ c.symm ≫ₕ f₁ ≫ₕ (of_set g.source g.open_source) ≫ₕ f₂ ≫ₕ c' : by simp [eq_on_source_trans, trans_self_symm g] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (of_set g.source g.open_source)) ≫ₕ (f₂ ≫ₕ c') : by simp [trans_assoc] ... ≈ ((c.symm ≫ₕ f₁).restr s) ≫ₕ (f₂ ≫ₕ c') : by simp [s, trans_of_set'] ... ≈ ((c.symm ≫ₕ f₁) ≫ₕ (f₂ ≫ₕ c')).restr s : by simp [restr_trans] ... ≈ (c.symm ≫ₕ (f₁ ≫ₕ f₂) ≫ₕ c').restr s : by simp [eq_on_source_restr, trans_assoc] ... ≈ F₂ : by simp [F₂, feq], have : F₂ ∈ G := G.eq_on_source F₁ F₂ A (setoid.symm this), exact this end, ..homeomorph.trans e.to_homeomorph e'.to_homeomorph } end has_groupoid
33d4d92e726a8316fac6f4a702d39841e00deaf4
fd3506535396cef3d1bdcf4ae5b87c8ed9ff2c2e
/group_theory/pgroup.lean
52bfef9feb413c851d5b1e18966b2472a3b8c331
[ "Apache-2.0" ]
permissive
williamdemeo/leanproved
77933dbcb8bfbae61a753ae31fa669b3ed8cda9d
d8c2e2ca0002b252fce049c4ff9be0e9e83a6374
refs/heads/master
1,598,674,802,432
1,437,528,488,000
1,437,528,488,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,394
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import theories.number_theory.primes data algebra.group algebra.group_power algebra.group_bigops .cyclic .finsubg .hom .perm .action open nat fin list algebra function subtype namespace group section pgroup open finset fintype variables {G S : Type} [ambientG : group G] [deceqG : decidable_eq G] [finS : fintype S] [deceqS : decidable_eq S] include ambientG definition psubg (H : finset G) (p m : nat) : Prop := prime p ∧ card H = p^m include deceqG finS deceqS variables {H : finset G} [subgH : is_finsubg H] include subgH variables {hom : G → perm S} [Hom : is_hom_class hom] include Hom open finset.partition lemma card_mod_eq_of_action_by_psubg {p : nat} : ∀ {m : nat}, psubg H p m → (card S) mod p = (card (fixed_points hom H)) mod p | 0 := by rewrite [↑psubg, pow_zero]; intro Psubg; rewrite [finsubg_eq_singleton_one_of_card_one (and.right Psubg), fixed_points_of_one] | (succ m) := take Ppsubg, begin rewrite [@orbit_class_equation' G S ambientG finS deceqS hom Hom H subgH], apply add_mod_eq_of_dvd, apply dvd_Sum_of_dvd, intro s Psin, rewrite mem_filter_iff at Psin, cases Psin with Psinorbs Pcardne, esimp [orbits, equiv_classes, orbit_partition] at Psinorbs, rewrite mem_image_iff at Psinorbs, cases Psinorbs with a Pa, cases Pa with Pain Porb, substvars, cases Ppsubg with Pprime PcardH, assert Pdvd : card (orbit hom H a) ∣ p ^ (succ m), rewrite -PcardH, apply dvd_of_eq_mul (finset.card (stab hom H a)), apply orbit_stabilizer_theorem, apply or.elim (eq_one_or_dvd_of_dvd_prime_pow Pprime Pdvd), intro Pcardeq, contradiction, intro Ppdvd, exact Ppdvd end end pgroup section psubg_cosets open finset fintype variables {G : Type} [ambientG : group G] [finG : fintype G] [deceqG : decidable_eq G] include ambientG deceqG finG variables {H : finset G} [finsubgH : is_finsubg H] include finsubgH lemma card_psubg_cosets_mod_eq {p : nat} {m : nat} : psubg H p m → (card (lcoset_type univ H)) mod p = card (lcoset_type (normalizer H) H) mod p := assume Psubg, by rewrite [-card_aol_fixed_points_eq_card_cosets]; exact card_mod_eq_of_action_by_psubg Psubg end psubg_cosets section cauchy lemma prodl_rotl_eq_one_of_prodl_eq_one {A B : Type} [gB : group B] {f : A → B} : ∀ {l : list A}, Prodl l f = 1 → Prodl (list.rotl l) f = 1 | nil := assume Peq, rfl | (a::l) := begin rewrite [rotl_cons, Prodl_cons f, Prodl_append _ _ f, Prodl_singleton], exact mul_eq_one_of_mul_eq_one end section rotl_peo variables {A : Type} [ambA : group A] include ambA variable [finA : fintype A] include finA variable (A) definition all_prodl_eq_one (n : nat) : list (list A) := map (λ l, cons (Prodl l id)⁻¹ l) (all_lists_of_len n) variable {A} lemma prodl_eq_one_of_mem_all_prodl_eq_one {n : nat} {l : list A} : l ∈ all_prodl_eq_one A n → Prodl l id = 1 := assume Plin, obtain l' Pl' Pl, from exists_of_mem_map Plin, by substvars; rewrite [Prodl_cons id _ l', mul.left_inv] lemma length_of_mem_all_prodl_eq_one {n : nat} {l : list A} : l ∈ all_prodl_eq_one A n → length l = succ n := assume Plin, obtain l' Pl' Pl, from exists_of_mem_map Plin, begin substvars, rewrite [length_cons, length_mem_all_lists Pl'] end lemma nodup_all_prodl_eq_one {n : nat} : nodup (all_prodl_eq_one A n) := nodup_map (take l₁ l₂ Peq, tail_eq_of_cons_eq Peq) nodup_all_lists lemma all_prodl_eq_one_complete {n : nat} : ∀ {l : list A}, length l = succ n → Prodl l id = 1 → l ∈ all_prodl_eq_one A n | nil := assume Pleq, by contradiction | (a::l) := assume Pleq Pprod, begin rewrite length_cons at Pleq, rewrite (Prodl_cons id a l) at Pprod, rewrite [eq_inv_of_mul_eq_one Pprod], apply mem_map, apply mem_all_lists, apply succ.inj Pleq end open fintype lemma length_all_prodl_eq_one {n : nat} : length (@all_prodl_eq_one A _ _ n) = (card A)^n := eq.trans !length_map length_all_lists open fin definition prodseq {n : nat} (s : seq A n) : A := Prodl (upto n) s definition peo [reducible] {n : nat} (s : seq A n) := prodseq s = 1 definition constseq {n : nat} (s : seq A (succ n)) := ∀ i, s i = s !zero lemma prodseq_eq {n :nat} {s : seq A n} : prodseq s = Prodl (fun_to_list s) id := Prodl_map lemma prodseq_eq_pow_of_constseq {n : nat} (s : seq A (succ n)) : constseq s → prodseq s = (s !zero) ^ succ n := assume Pc, assert Pcl : ∀ i, i ∈ upto (succ n) → s i = s !zero, from take i, assume Pin, Pc i, by rewrite [↑prodseq, Prodl_eq_pow_of_const _ Pcl, fin.length_upto] lemma seq_eq_of_constseq_of_eq {n : nat} {s₁ s₂ : seq A (succ n)} : constseq s₁ → constseq s₂ → s₁ !zero = s₂ !zero → s₁ = s₂ := assume Pc₁ Pc₂ Peq, funext take i, by rewrite [Pc₁ i, Pc₂ i, Peq] lemma peo_const_one : ∀ {n : nat}, peo (λ i : fin n, (1 : A)) | 0 := rfl | (succ n) := let s := λ i : fin (succ n), (1 : A) in assert Pconst : constseq s, from take i, rfl, calc prodseq s = (s !zero) ^ succ n : prodseq_eq_pow_of_constseq s Pconst ... = (1 : A) ^ succ n : rfl ... = 1 : algebra.one_pow variable [deceqA : decidable_eq A] include deceqA variable (A) definition peo_seq [reducible] (n : nat) := {s : seq A (succ n) | peo s} definition peo_seq_one (n : nat) : peo_seq A n := tag (λ i : fin (succ n), (1 : A)) peo_const_one definition all_prodseq_eq_one (n : nat) : list (seq A (succ n)) := dmap (λ l, length l = card (fin (succ n))) list_to_fun (all_prodl_eq_one A n) definition all_peo_seqs (n : nat) : list (peo_seq A n) := dmap peo tag (all_prodseq_eq_one A n) variable {A} lemma prodseq_eq_one_of_mem_all_prodseq_eq_one {n : nat} {s : seq A (succ n)} : s ∈ all_prodseq_eq_one A n → prodseq s = 1 := assume Psin, obtain l Pex, from exists_of_mem_dmap Psin, obtain leq Pin Peq, from Pex, by rewrite [prodseq_eq, Peq, list_to_fun_to_list, prodl_eq_one_of_mem_all_prodl_eq_one Pin] lemma all_prodseq_eq_one_complete {n : nat} {s : seq A (succ n)} : prodseq s = 1 → s ∈ all_prodseq_eq_one A n := assume Peq, assert Plin : map s (elems (fin (succ n))) ∈ all_prodl_eq_one A n, from begin apply all_prodl_eq_one_complete, rewrite [length_map], exact length_upto (succ n), rewrite prodseq_eq at Peq, exact Peq end, assert Psin : list_to_fun (map s (elems (fin (succ n)))) (length_map_of_fintype s) ∈ all_prodseq_eq_one A n, from mem_dmap _ Plin, by rewrite [fun_eq_list_to_fun_map s (length_map_of_fintype s)]; apply Psin lemma nodup_all_prodseq_eq_one {n : nat} : nodup (all_prodseq_eq_one A n) := dmap_nodup_of_dinj dinj_list_to_fun nodup_all_prodl_eq_one lemma rotl1_peo_of_peo {n : nat} {s : seq A n} : peo s → peo (rotl_fun 1 s) := begin rewrite [↑peo, *prodseq_eq, seq_rotl_eq_list_rotl], apply prodl_rotl_eq_one_of_prodl_eq_one end section local attribute perm.f [coercion] lemma rotl_perm_peo_of_peo {n : nat} : ∀ {m} {s : seq A n}, peo s → peo (rotl_perm A n m s) | 0 := begin rewrite [↑rotl_perm, rotl_seq_zero], intros, assumption end | (succ m) := take s, assert Pmul : rotl_perm A n (m + 1) s = rotl_fun 1 (rotl_perm A n m s), from calc s ∘ (rotl (m + 1)) = s ∘ ((rotl m) ∘ (rotl 1)) : rotl_compose ... = s ∘ (rotl m) ∘ (rotl 1) : compose.assoc, begin rewrite [-add_one, Pmul], intro P, exact rotl1_peo_of_peo (rotl_perm_peo_of_peo P) end end lemma nodup_all_peo_seqs {n : nat} : nodup (all_peo_seqs A n) := dmap_nodup_of_dinj (dinj_tag peo) nodup_all_prodseq_eq_one lemma all_peo_seqs_complete {n : nat} : ∀ s : peo_seq A n, s ∈ all_peo_seqs A n := take ps, subtype.destruct ps (take s, assume Ps, assert Pin : s ∈ all_prodseq_eq_one A n, from all_prodseq_eq_one_complete Ps, mem_dmap Ps Pin) lemma length_all_peo_seqs {n : nat} : length (all_peo_seqs A n) = (card A)^n := eq.trans (eq.trans (show length (all_peo_seqs A n) = length (all_prodseq_eq_one A n), from assert Pmap : map elt_of (all_peo_seqs A n) = all_prodseq_eq_one A n, from map_dmap_of_inv_of_pos (λ s P, rfl) (λ s, prodseq_eq_one_of_mem_all_prodseq_eq_one), by rewrite [-Pmap, length_map]) (show length (all_prodseq_eq_one A n) = length (all_prodl_eq_one A n), from assert Pmap : map fun_to_list (all_prodseq_eq_one A n) = all_prodl_eq_one A n, from map_dmap_of_inv_of_pos list_to_fun_to_list (λ l Pin, by rewrite [length_of_mem_all_prodl_eq_one Pin, card_fin]), by rewrite [-Pmap, length_map])) length_all_prodl_eq_one definition peo_seq_is_fintype [instance] {n : nat} : fintype (peo_seq A n) := fintype.mk (all_peo_seqs A n) nodup_all_peo_seqs all_peo_seqs_complete lemma card_peo_seq {n : nat} : card (peo_seq A n) = (card A)^n := length_all_peo_seqs section variable (A) local attribute perm.f [coercion] definition rotl_peo_seq (n : nat) (m : nat) (s : peo_seq A n) : peo_seq A n := tag (rotl_perm A (succ n) m (elt_of s)) (rotl_perm_peo_of_peo (has_property s)) variable {A} end lemma rotl_peo_seq_zero {n : nat} : rotl_peo_seq A n 0 = id := funext take s, subtype.eq begin rewrite [↑rotl_peo_seq, ↑rotl_perm, rotl_seq_zero] end lemma rotl_peo_seq_id {n : nat} : rotl_peo_seq A n (succ n) = id := funext take s, subtype.eq begin rewrite [↑rotl_peo_seq, -rotl_perm_pow_eq, rotl_perm_pow_eq_one] end lemma rotl_peo_seq_compose {n i j : nat} : (rotl_peo_seq A n i) ∘ (rotl_peo_seq A n j) = rotl_peo_seq A n (j + i) := funext take s, subtype.eq begin rewrite [↑rotl_peo_seq, ↑rotl_perm, ↑rotl_fun, compose.assoc, rotl_compose] end lemma rotl_peo_seq_mod {n i : nat} : rotl_peo_seq A n i = rotl_peo_seq A n (i mod succ n) := funext take s, subtype.eq begin rewrite [↑rotl_peo_seq, rotl_perm_mod] end lemma rotl_peo_seq_inj {n m : nat} : injective (rotl_peo_seq A n m) := take ps₁ ps₂, subtype.destruct ps₁ (λ s₁ P₁, subtype.destruct ps₂ (λ s₂ P₂, assume Peq, tag_eq (rotl_fun_inj (dinj_tag peo _ _ Peq)))) variable (A) definition rotl_perm_ps [reducible] (n : nat) (m : fin (succ n)) : perm (peo_seq A n) := perm.mk (rotl_peo_seq A n m) rotl_peo_seq_inj variable {A} variable {n : nat} lemma rotl_perm_ps_eq {m : fin (succ n)} {s : peo_seq A n} : elt_of (perm.f (rotl_perm_ps A n m) s) = perm.f (rotl_perm A (succ n) m) (elt_of s) := rfl lemma rotl_perm_ps_eq_of_rotl_perm_eq {i j : fin (succ n)} : (rotl_perm A (succ n) i) = (rotl_perm A (succ n) j) → (rotl_perm_ps A n i) = (rotl_perm_ps A n j) := assume Peq, eq_of_feq (funext take s, subtype.eq (by rewrite [*rotl_perm_ps_eq, Peq])) lemma rotl_perm_ps_hom (i j : fin (succ n)) : rotl_perm_ps A n (i+j) = (rotl_perm_ps A n i) * (rotl_perm_ps A n j) := eq_of_feq (begin rewrite [↑rotl_perm_ps, {val (i+j)}val_madd, add.comm, -rotl_peo_seq_mod, -rotl_peo_seq_compose] end) section local attribute group_of_add_group [instance] definition rotl_perm_ps_is_hom [instance] : is_hom_class (rotl_perm_ps A n) := is_hom_class.mk rotl_perm_ps_hom open finset lemma const_of_is_fixed_point {s : peo_seq A n} : is_fixed_point (rotl_perm_ps A n) univ s → constseq (elt_of s) := assume Pfp, take i, begin rewrite [-(Pfp i !mem_univ) at {1}, rotl_perm_ps_eq, ↑rotl_perm, ↑rotl_fun, {i}mk_mod_eq at {2}, rotl_to_zero] end lemma const_of_rotl_fixed_point {s : peo_seq A n} : s ∈ fixed_points (rotl_perm_ps A n) univ → constseq (elt_of s) := assume Psin, take i, begin apply const_of_is_fixed_point, exact is_fixed_point_of_mem_fixed_points Psin end lemma pow_eq_one_of_mem_fixed_points {s : peo_seq A n} : s ∈ fixed_points (rotl_perm_ps A n) univ → (elt_of s !zero)^(succ n) = 1 := assume Psin, eq.trans (eq.symm (prodseq_eq_pow_of_constseq (elt_of s) (const_of_rotl_fixed_point Psin))) (has_property s) lemma peo_seq_one_is_fixed_point : is_fixed_point (rotl_perm_ps A n) univ (peo_seq_one A n) := take h, assume Pin, by esimp [rotl_perm_ps] lemma peo_seq_one_mem_fixed_points : peo_seq_one A n ∈ fixed_points (rotl_perm_ps A n) univ := mem_fixed_points_of_exists_of_is_fixed_point (exists.intro !zero !mem_univ) peo_seq_one_is_fixed_point lemma generator_of_prime_of_dvd_order {p : nat} : prime p → p ∣ card A → ∃ g : A, g ≠ 1 ∧ g^p = 1 := assume Pprime Pdvd, let pp := nat.pred p, spp := nat.succ pp in assert Peq : spp = p, from succ_pred_prime Pprime, have Ppsubg : psubg (@univ (fin spp) _) spp 1, from and.intro (eq.symm Peq ▸ Pprime) (by rewrite [Peq, card_fin, pow_one]), have Pcardmod : (nat.pow (card A) pp) mod p = (card (fixed_points (rotl_perm_ps A pp) univ)) mod p, from Peq ▸ card_peo_seq ▸ card_mod_eq_of_action_by_psubg Ppsubg, have Pfpcardmod : (card (fixed_points (rotl_perm_ps A pp) univ)) mod p = 0, from eq.trans (eq.symm Pcardmod) (mod_eq_zero_of_dvd (dvd_pow_of_dvd_of_pos Pdvd (pred_prime_pos Pprime))), have Pfpcardpos : card (fixed_points (rotl_perm_ps A pp) univ) > 0, from card_pos_of_mem peo_seq_one_mem_fixed_points, have Pfpcardgt1 : card (fixed_points (rotl_perm_ps A pp) univ) > 1, from gt_one_of_pos_of_prime_dvd Pprime Pfpcardpos Pfpcardmod, obtain s₁ s₂ Pin₁ Pin₂ Psnes, from exists_two_of_card_gt_one Pfpcardgt1, decidable.by_cases (λ Pe₁ : elt_of s₁ !zero = 1, assert Pne₂ : elt_of s₂ !zero ≠ 1, from assume Pe₂, absurd (subtype.eq (seq_eq_of_constseq_of_eq (const_of_rotl_fixed_point Pin₁) (const_of_rotl_fixed_point Pin₂) (eq.trans Pe₁ (eq.symm Pe₂)))) Psnes, exists.intro (elt_of s₂ !zero) (and.intro Pne₂ (Peq ▸ pow_eq_one_of_mem_fixed_points Pin₂))) (λ Pne, exists.intro (elt_of s₁ !zero) (and.intro Pne (Peq ▸ pow_eq_one_of_mem_fixed_points Pin₁))) end theorem cauchy_theorem {p : nat} : prime p → p ∣ card A → ∃ g : A, order g = p := assume Pprime Pdvd, obtain g Pne Pgpow, from generator_of_prime_of_dvd_order Pprime Pdvd, assert Porder : order g ∣ p, from order_dvd_of_pow_eq_one Pgpow, or.elim (eq_one_or_eq_self_of_prime_of_dvd Pprime Porder) (λ Pe, absurd (eq_one_of_order_eq_one Pe) Pne) (λ Porderp, exists.intro g Porderp) end rotl_peo end cauchy section sylow open finset fintype variables {G : Type} [ambientG : group G] [finG : fintype G] [deceqG : decidable_eq G] include ambientG deceqG finG theorem first_sylow_theorem {p : nat} (Pp : prime p) : ∀ n, p^n ∣ card G → ∃ (H : finset G) (finsubgH : is_finsubg H), card H = p^n | 0 := assume Pdvd, exists.intro (singleton 1) (exists.intro one_is_finsubg (by rewrite [card_singleton, pow_zero])) | (succ n) := assume Pdvd, obtain H PfinsubgH PcardH, from first_sylow_theorem n (pow_dvd_of_pow_succ_dvd Pdvd), assert Ppsubg : psubg H p n, from and.intro Pp PcardH, assert Ppowsucc : p^(succ n) ∣ (card (lcoset_type univ H) * p^n), by rewrite [-PcardH, -(lagrange_theorem' !subset_univ)]; exact Pdvd, assert Ppdvd : p ∣ card (lcoset_type (normalizer H) H), from dvd_of_mod_eq_zero (by rewrite [-(card_psubg_cosets_mod_eq Ppsubg), -dvd_iff_mod_eq_zero]; exact dvd_of_pow_succ_dvd_mul_pow (pos_of_prime Pp) Ppowsucc), obtain J PJ, from cauchy_theorem Pp Ppdvd, exists.intro (fin_coset_Union (cyc J)) (exists.intro _ (by rewrite [pow_succ', -PcardH, -PJ]; apply card_Union_lcosets)) end sylow end group
ecdf38acfc35b10135a1d5bcd74c1ba427342fbd
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Init/Algebra/Order.lean
b8c2eadc160172484c88d9cb5c81dff83684540d
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
10,253
lean
/- Ported by Deniz Aydin from the lean3 prelude: https://github.com/leanprover-community/lean/blob/master/library/init/algebra/order.lean Original file's license: 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.Init.Logic /-! # Orders Defines classes for preorders, partial orders, and linear orders and proves some basic lemmas about them. -/ /- TODO: Does Lean4 have an equivalent for this: Make sure instances defined in this file have lower priority than the ones defined for concrete structures set_option default_priority 100 -/ universe u variable {α : Type u} -- set_option auto_param.check_exists false section Preorder /-! ### Definition of `Preorder` and lemmas about types with a `Preorder` -/ /-- A preorder is a reflexive, transitive relation `≤` with `a < b` defined in the obvious way. -/ class Preorder (α : Type u) extends LE α, LT α := (le_refl : ∀ a : α, a ≤ a) (le_trans : ∀ a b c : α, a ≤ b → b ≤ c → a ≤ c) (lt := λ a b => a ≤ b ∧ ¬ b ≤ a) (lt_iff_le_not_le : ∀ a b : α, a < b ↔ (a ≤ b ∧ ¬ b ≤ a)) -- . order_laws_tac) variable [Preorder α] /-- The relation `≤` on a preorder is reflexive. -/ theorem le_refl : ∀ (a : α), a ≤ a := Preorder.le_refl /-- The relation `≤` on a preorder is transitive. -/ theorem le_trans : ∀ {a b c : α}, a ≤ b → b ≤ c → a ≤ c := Preorder.le_trans _ _ _ theorem lt_iff_le_not_le : ∀ {a b : α}, a < b ↔ (a ≤ b ∧ ¬ b ≤ a) := Preorder.lt_iff_le_not_le _ _ theorem lt_of_le_not_le : ∀ {a b : α}, a ≤ b → ¬ b ≤ a → a < b | a, b, hab, hba => lt_iff_le_not_le.mpr ⟨hab, hba⟩ theorem le_not_le_of_lt : ∀ {a b : α}, a < b → a ≤ b ∧ ¬ b ≤ a | a, b, hab => lt_iff_le_not_le.mp hab theorem le_of_eq {a b : α} : a = b → a ≤ b := λ h => h ▸ le_refl a theorem ge_trans : ∀ {a b c : α}, a ≥ b → b ≥ c → a ≥ c := λ h₁ h₂ => le_trans h₂ h₁ theorem lt_irrefl : ∀ a : α, ¬ a < a | a, haa => match le_not_le_of_lt haa with | ⟨h1, h2⟩ => h2 h1 theorem gt_irrefl : ∀ a : α, ¬ a > a := lt_irrefl theorem lt_trans : ∀ {a b c : α}, a < b → b < c → a < c | a, b, c, hab, hbc => match le_not_le_of_lt hab, le_not_le_of_lt hbc with | ⟨hab, hba⟩, ⟨hbc, hcb⟩ => lt_of_le_not_le (le_trans hab hbc) (λ hca => hcb (le_trans hca hab)) theorem gt_trans : ∀ {a b c : α}, a > b → b > c → a > c := λ h₁ h₂ => lt_trans h₂ h₁ theorem ne_of_lt {a b : α} (h : a < b) : a ≠ b := λ he => absurd h (he ▸ lt_irrefl a) theorem ne_of_gt {a b : α} (h : b < a) : a ≠ b := λ he => absurd h (he ▸ lt_irrefl a) theorem lt_asymm {a b : α} (h : a < b) : ¬ b < a := λ h1 : b < a => lt_irrefl a (lt_trans h h1) theorem le_of_lt : ∀ {a b : α}, a < b → a ≤ b | a, b, hab => (le_not_le_of_lt hab).left theorem lt_of_lt_of_le : ∀ {a b c : α}, a < b → b ≤ c → a < c | a, b, c, hab, hbc => let ⟨hab, hba⟩ := le_not_le_of_lt hab lt_of_le_not_le (le_trans hab hbc) $ λ hca => hba (le_trans hbc hca) theorem lt_of_le_of_lt : ∀ {a b c : α}, a ≤ b → b < c → a < c | a, b, c, hab, hbc => let ⟨hbc, hcb⟩ := le_not_le_of_lt hbc lt_of_le_not_le (le_trans hab hbc) $ λ hca => hcb (le_trans hca hab) theorem gt_of_gt_of_ge {a b c : α} (h₁ : a > b) (h₂ : b ≥ c) : a > c := lt_of_le_of_lt h₂ h₁ theorem gt_of_ge_of_gt {a b c : α} (h₁ : a ≥ b) (h₂ : b > c) : a > c := lt_of_lt_of_le h₂ h₁ theorem not_le_of_gt {a b : α} (h : a > b) : ¬ a ≤ b := (le_not_le_of_lt h).right theorem not_lt_of_ge {a b : α} (h : a ≥ b) : ¬ a < b := λ hab => not_le_of_gt hab h theorem le_of_lt_or_eq : ∀ {a b : α}, (a < b ∨ a = b) → a ≤ b | a, b, (Or.inl hab) => le_of_lt hab | a, b, (Or.inr hab) => hab ▸ le_refl _ theorem le_of_eq_or_lt {a b : α} (h : a = b ∨ a < b) : a ≤ b := match h with | (Or.inl h) => le_of_eq h | (Or.inr h) => le_of_lt h instance decidableLt_of_decidableLe [DecidableRel (. ≤ . : α → α → Prop)] : DecidableRel (. < . : α → α → Prop) | a, b => if hab : a ≤ b then if hba : b ≤ a then isFalse $ λ hab' => not_le_of_gt hab' hba else isTrue $ lt_of_le_not_le hab hba else isFalse $ λ hab' => hab (le_of_lt hab') end Preorder section PartialOrder /-! ### Definition of `PartialOrder` and lemmas about types with a partial order -/ /-- A partial order is a reflexive, transitive, antisymmetric relation `≤`. -/ class PartialOrder (α : Type u) extends Preorder α := (le_antisymm : ∀ a b : α, a ≤ b → b ≤ a → a = b) variable [PartialOrder α] theorem le_antisymm : ∀ {a b : α}, a ≤ b → b ≤ a → a = b := PartialOrder.le_antisymm _ _ theorem le_antisymm_iff {a b : α} : a = b ↔ a ≤ b ∧ b ≤ a := ⟨λ e => ⟨le_of_eq e, le_of_eq e.symm⟩, λ ⟨h1, h2⟩ => le_antisymm h1 h2⟩ theorem lt_of_le_of_ne {a b : α} : a ≤ b → a ≠ b → a < b := λ h₁ h₂ => lt_of_le_not_le h₁ $ mt (le_antisymm h₁) h₂ instance decidableEq_of_decidableLe [DecidableRel (. ≤ . : α → α → Prop)] : DecidableEq α | a, b => if hab : a ≤ b then if hba : b ≤ a then isTrue (le_antisymm hab hba) else isFalse (λ heq => hba (heq ▸ le_refl _)) else isFalse (λ heq => hab (heq ▸ le_refl _)) namespace Decidable variable [@DecidableRel α (. ≤ .)] theorem lt_or_eq_of_le {a b : α} (hab : a ≤ b) : a < b ∨ a = b := if hba : b ≤ a then Or.inr (le_antisymm hab hba) else Or.inl (lt_of_le_not_le hab hba) theorem eq_or_lt_of_le {a b : α} (hab : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le hab).symm theorem le_iff_lt_or_eq {a b : α} : a ≤ b ↔ a < b ∨ a = b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ end Decidable attribute [local instance] Classical.propDecidable theorem lt_or_eq_of_le {a b : α} : a ≤ b → a < b ∨ a = b := Decidable.lt_or_eq_of_le theorem le_iff_lt_or_eq {a b : α} : a ≤ b ↔ a < b ∨ a = b := Decidable.le_iff_lt_or_eq end PartialOrder section LinearOrder /-! ### Definition of `LinearOrder` and lemmas about types with a linear order -/ /-- A linear order is reflexive, transitive, antisymmetric and total relation `≤`. We assume that every linear ordered type has decidable `(≤)`, `(<)`, and `(=)`. -/ class LinearOrder (α : Type u) extends PartialOrder α := (le_total : ∀ a b : α, a ≤ b ∨ b ≤ a) (decidable_le : DecidableRel (. ≤ . : α → α → Prop)) (decidable_eq : DecidableEq α := @decidableEq_of_decidableLe _ _ decidable_le) (decidable_lt : DecidableRel (. < . : α → α → Prop) := @decidableLt_of_decidableLe _ _ decidable_le) variable [LinearOrder α] attribute [local instance] LinearOrder.decidable_le theorem le_total : ∀ a b : α, a ≤ b ∨ b ≤ a := LinearOrder.le_total theorem le_of_not_ge {a b : α} : ¬ a ≥ b → a ≤ b := Or.resolve_left (le_total b a) theorem le_of_not_le {a b : α} : ¬ a ≤ b → b ≤ a := Or.resolve_left (le_total a b) theorem not_lt_of_gt {a b : α} (h : a > b) : ¬ a < b := lt_asymm h theorem lt_trichotomy (a b : α) : a < b ∨ a = b ∨ b < a := Or.elim (le_total a b) (λ h : a ≤ b => Or.elim (Decidable.lt_or_eq_of_le h) (λ h : a < b => Or.inl h) (λ h : a = b => Or.inr (Or.inl h))) (λ h : b ≤ a => Or.elim (Decidable.lt_or_eq_of_le h) (λ h : b < a => Or.inr (Or.inr h)) (λ h : b = a => Or.inr (Or.inl h.symm))) theorem le_of_not_lt {a b : α} (h : ¬ b < a) : a ≤ b := match lt_trichotomy a b with | Or.inl hlt => le_of_lt hlt | Or.inr (Or.inl heq) => heq ▸ le_refl a | Or.inr (Or.inr hgt) => absurd hgt h theorem le_of_not_gt {a b : α} : ¬ a > b → a ≤ b := le_of_not_lt theorem lt_of_not_ge {a b : α} (h : ¬ a ≥ b) : a < b := lt_of_le_not_le ((le_total _ _).resolve_right h) h theorem lt_or_le (a b : α) : a < b ∨ b ≤ a := if hba : b ≤ a then Or.inr hba else Or.inl $ lt_of_not_ge hba theorem le_or_lt (a b : α) : a ≤ b ∨ b < a := (lt_or_le b a).symm theorem lt_or_ge : ∀ (a b : α), a < b ∨ a ≥ b := lt_or_le theorem le_or_gt : ∀ (a b : α), a ≤ b ∨ a > b := le_or_lt theorem lt_or_gt_of_ne {a b : α} (h : a ≠ b) : a < b ∨ a > b := match lt_trichotomy a b with | Or.inl hlt => Or.inl hlt | Or.inr (Or.inl heq) => absurd heq h | Or.inr (Or.inr hgt) => Or.inr hgt theorem ne_iff_lt_or_gt {a b : α} : a ≠ b ↔ a < b ∨ a > b := ⟨lt_or_gt_of_ne, λ o => match o with | Or.inl ol => ne_of_lt ol | Or.inr or => ne_of_gt or ⟩ theorem lt_iff_not_ge (x y : α) : x < y ↔ ¬ x ≥ y := ⟨not_le_of_gt, lt_of_not_ge⟩ @[simp] theorem not_lt {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_gt, not_lt_of_ge⟩ @[simp] theorem not_le {a b : α} : ¬ a ≤ b ↔ b < a := (lt_iff_not_ge _ _).symm instance (a b : α) : Decidable (a < b) := LinearOrder.decidable_lt a b instance (a b : α) : Decidable (a ≤ b) := LinearOrder.decidable_le a b instance (a b : α) : Decidable (a = b) := LinearOrder.decidable_eq a b theorem eq_or_lt_of_not_lt {a b : α} (h : ¬ a < b) : a = b ∨ b < a := if h₁ : a = b then Or.inl h₁ else Or.inr (lt_of_not_ge (λ hge => h (lt_of_le_of_ne hge h₁))) /- TODO: instances of classes that haven't been defined. instance : is_total_preorder α (≤) := {trans := @le_trans _ _, total := le_total} instance is_strict_weak_order_of_linear_order : is_strict_weak_order α (<) := is_strict_weak_order_of_is_total_preorder lt_iff_not_ge instance is_strict_total_order_of_linear_order : is_strict_total_order α (<) := { trichotomous := lt_trichotomy } -/ /-- Perform a case-split on the ordering of `x` and `y` in a decidable linear order. -/ def lt_by_cases (x y : α) {P : Sort _} (h₁ : x < y → P) (h₂ : x = y → P) (h₃ : y < x → P) : P := if h : x < y then h₁ h else if h' : y < x then h₃ h' else h₂ (le_antisymm (le_of_not_gt h') (le_of_not_gt h)) theorem le_imp_le_of_lt_imp_lt {β} [Preorder α] [LinearOrder β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_lt $ λ h' => not_le_of_gt (H h') h end LinearOrder
6428e88b6b7d26a9aadf01b62172427c0a75a75c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/logic/basic_auto.lean
d049e65769acf1afc42cd1cbbc162ae3b75542e4
[]
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
64,651
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.doc_commands import Mathlib.tactic.reserved_notation import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u l w v namespace Mathlib /-! # Basic logic properties This file is one of the earliest imports in mathlib. ## Implementation notes Theorems that require decidability hypotheses are in the namespace "decidable". Classical versions are in the namespace "classical". In the presence of automation, this whole file may be unnecessary. On the other hand, maybe it is useful for writing automation. -/ /- We add the `inline` attribute to optimize VM computation using these declarations. For example, `if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/ /-- An identity function with its main argument implicit. This will be printed as `hidden` even if it is applied to a large term, so it can be used for elision, as done in the `elide` and `unelide` tactics. -/ def hidden {α : Sort u_1} {a : α} : α := a /-- Ex falso, the nondependent eliminator for the `empty` type. -/ def empty.elim {C : Sort u_1} : empty → C := sorry protected instance empty.subsingleton : subsingleton empty := subsingleton.intro fun (a : empty) => empty.elim a protected instance subsingleton.prod {α : Type u_1} {β : Type u_2} [subsingleton α] [subsingleton β] : subsingleton (α × β) := subsingleton.intro fun (a b : α × β) => prod.cases_on a fun (a_fst : α) (a_snd : β) => prod.cases_on b fun (b_fst : α) (b_snd : β) => (fun (fst fst_1 : α) (snd snd_1 : β) => Eq.trans ((fun (fst : α) (snd : β) => Eq.refl (fst, snd)) fst snd) (congr (congr (Eq.refl Prod.mk) (subsingleton.elim fst fst_1)) (subsingleton.elim snd snd_1))) a_fst b_fst a_snd b_snd protected instance empty.decidable_eq : DecidableEq empty := fun (a : empty) => empty.elim a protected instance sort.inhabited : Inhabited (Sort u_1) := { default := PUnit } protected instance sort.inhabited' : Inhabited Inhabited.default := { default := PUnit.unit } protected instance psum.inhabited_left {α : Sort u_1} {β : Sort u_2} [Inhabited α] : Inhabited (psum α β) := { default := psum.inl Inhabited.default } protected instance psum.inhabited_right {α : Sort u_1} {β : Sort u_2} [Inhabited β] : Inhabited (psum α β) := { default := psum.inr Inhabited.default } protected instance decidable_eq_of_subsingleton {α : Sort u_1} [subsingleton α] : DecidableEq α := sorry @[simp] theorem eq_iff_true_of_subsingleton {α : Type u_1} [subsingleton α] (x : α) (y : α) : x = y ↔ True := of_eq_true (Eq.trans (iff_eq_of_eq_true_right (Eq.refl True)) (eq_true_intro (Eq.symm (subsingleton.elim y x)))) /-- Add an instance to "undo" coercion transitivity into a chain of coercions, because most simp lemmas are stated with respect to simple coercions and will not match when part of a chain. -/ @[simp] theorem coe_coe {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t β γ] (a : α) : ↑a = ↑↑a := rfl theorem coe_fn_coe_trans {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ] (x : α) : ⇑x = ⇑↑x := rfl @[simp] theorem coe_fn_coe_base {α : Sort u_1} {β : Sort u_2} [has_coe α β] [has_coe_to_fun β] (x : α) : ⇑x = ⇑↑x := rfl theorem coe_sort_coe_trans {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ] (x : α) : ↥x = ↥↑x := rfl /-- Many structures such as bundled morphisms coerce to functions so that you can transparently apply them to arguments. For example, if `e : α ≃ β` and `a : α` then you can write `e a` and this is elaborated as `⇑e a`. This type of coercion is implemented using the `has_coe_to_fun` type class. There is one important consideration: If a type coerces to another type which in turn coerces to a function, then it **must** implement `has_coe_to_fun` directly: ```lean structure sparkling_equiv (α β) extends α ≃ β -- if we add a `has_coe` instance, -- if we add a `has_coe` instance, instance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) := ⟨sparkling_equiv.to_equiv⟩ -- then a `has_coe_to_fun` instance **must** be added as well: -- then a `has_coe_to_fun` instance **must** be added as well: instance {α β} : has_coe_to_fun (sparkling_equiv α β) := ⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩ ``` (Rationale: if we do not declare the direct coercion, then `⇑e a` is not in simp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This often causes loops in the simplifier.) -/ @[simp] theorem coe_sort_coe_base {α : Sort u_1} {β : Sort u_2} [has_coe α β] [has_coe_to_sort β] (x : α) : ↥x = ↥↑x := rfl /-- `pempty` is the universe-polymorphic analogue of `empty`. -/ inductive pempty where /-- Ex falso, the nondependent eliminator for the `pempty` type. -/ def pempty.elim {C : Sort u_1} : pempty → C := sorry protected instance subsingleton_pempty : subsingleton pempty := subsingleton.intro fun (a : pempty) => pempty.elim a @[simp] theorem not_nonempty_pempty : ¬Nonempty pempty := fun (_x : Nonempty pempty) => (fun (_a : Nonempty pempty) => nonempty.dcases_on _a fun (val : pempty) => idRhs False (pempty.elim val)) _x @[simp] theorem forall_pempty {P : pempty → Prop} : (∀ (x : pempty), P x) ↔ True := { mp := fun (h : ∀ (x : pempty), P x) => trivial, mpr := fun (h : True) (x : pempty) => pempty.cases_on (fun (x : pempty) => P x) x } @[simp] theorem exists_pempty {P : pempty → Prop} : (∃ (x : pempty), P x) ↔ False := sorry theorem congr_arg_heq {α : Sort u_1} {β : α → Sort u_2} (f : (a : α) → β a) {a₁ : α} {a₂ : α} : a₁ = a₂ → f a₁ == f a₂ := sorry theorem plift.down_inj {α : Sort u_1} (a : plift α) (b : plift α) : plift.down a = plift.down b → a = b := sorry -- missing [symm] attribute for ne in core. theorem ne_comm {α : Sort u_1} {a : α} {b : α} : a ≠ b ↔ b ≠ a := { mp := ne.symm, mpr := ne.symm } @[simp] theorem eq_iff_eq_cancel_left {α : Type u_1} {b : α} {c : α} : (∀ {a : α}, a = b ↔ a = c) ↔ b = c := { mp := fun (h : ∀ {a : α}, a = b ↔ a = c) => eq.mpr (id (Eq._oldrec (Eq.refl (b = c)) (Eq.symm (propext h)))) (Eq.refl b), mpr := fun (h : b = c) (a : α) => eq.mpr (id (Eq._oldrec (Eq.refl (a = b ↔ a = c)) h)) (iff.refl (a = c)) } @[simp] theorem eq_iff_eq_cancel_right {α : Type u_1} {a : α} {b : α} : (∀ {c : α}, a = c ↔ b = c) ↔ a = b := { mp := fun (h : ∀ {c : α}, a = c ↔ b = c) => eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (propext h))) (Eq.refl b), mpr := fun (h : a = b) (a_1 : α) => eq.mpr (id (Eq._oldrec (Eq.refl (a = a_1 ↔ b = a_1)) h)) (iff.refl (b = a_1)) } /-- Wrapper for adding elementary propositions to the type class systems. Warning: this can easily be abused. See the rest of this docstring for details. Certain propositions should not be treated as a class globally, but sometimes it is very convenient to be able to use the type class system in specific circumstances. For example, `zmod p` is a field if and only if `p` is a prime number. In order to be able to find this field instance automatically by type class search, we have to turn `p.prime` into an instance implicit assumption. On the other hand, making `nat.prime` a class would require a major refactoring of the library, and it is questionable whether making `nat.prime` a class is desirable at all. The compromise is to add the assumption `[fact p.prime]` to `zmod.field`. In particular, this class is not intended for turning the type class system into an automated theorem prover for first order logic. -/ def fact (p : Prop) := p theorem fact.elim {p : Prop} (h : fact p) : p := h /-! ### Declarations about propositional connectives -/ theorem false_ne_true : False ≠ True := fun (ᾰ : False = True) => idRhs ((fun (_x : Prop) => _x) False) (Eq.symm ᾰ ▸ trivial) /-! ### Declarations about `implies` -/ theorem iff_of_eq {a : Prop} {b : Prop} (e : a = b) : a ↔ b := e ▸ iff.rfl theorem iff_iff_eq {a : Prop} {b : Prop} : a ↔ b ↔ a = b := { mp := propext, mpr := iff_of_eq } @[simp] theorem eq_iff_iff {p : Prop} {q : Prop} : p = q ↔ (p ↔ q) := iff.symm iff_iff_eq @[simp] theorem imp_self {a : Prop} : a → a ↔ True := iff_true_intro id theorem imp_intro {α : Prop} {β : Prop} (h : α) : β → α := fun (_x : β) => h theorem imp_false {a : Prop} : a → False ↔ ¬a := iff.rfl theorem imp_and_distrib {b : Prop} {c : Prop} {α : Sort u_1} : α → b ∧ c ↔ (α → b) ∧ (α → c) := { mp := fun (h : α → b ∧ c) => { left := fun (ha : α) => and.left (h ha), right := fun (ha : α) => and.right (h ha) }, mpr := fun (h : (α → b) ∧ (α → c)) (ha : α) => { left := and.left h ha, right := and.right h ha } } @[simp] theorem and_imp {a : Prop} {b : Prop} {c : Prop} : a ∧ b → c ↔ a → b → c := sorry theorem iff_def {a : Prop} {b : Prop} : a ↔ b ↔ (a → b) ∧ (b → a) := iff_iff_implies_and_implies a b theorem iff_def' {a : Prop} {b : Prop} : a ↔ b ↔ (b → a) ∧ (a → b) := iff.trans iff_def and.comm theorem imp_true_iff {α : Sort u_1} : α → True ↔ True := iff_true_intro fun (_x : α) => trivial @[simp] theorem imp_iff_right {a : Prop} {b : Prop} (ha : a) : a → b ↔ b := { mp := fun (f : a → b) => f ha, mpr := imp_intro } /-! ### Declarations about `not` -/ /-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with the arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/ def not.elim {a : Prop} {α : Sort u_1} (H1 : ¬a) (H2 : a) : α := absurd H2 H1 theorem not.imp {a : Prop} {b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a := mt H1 H2 theorem not_not_of_not_imp {a : Prop} {b : Prop} : ¬(a → b) → ¬¬a := mt not.elim theorem not_of_not_imp {b : Prop} {a : Prop} : ¬(a → b) → ¬b := mt imp_intro theorem dec_em (p : Prop) [Decidable p] : p ∨ ¬p := decidable.em p theorem em (p : Prop) : p ∨ ¬p := classical.em p theorem or_not {p : Prop} : p ∨ ¬p := em p theorem by_contradiction {p : Prop} : (¬p → False) → p := decidable.by_contradiction -- alias by_contradiction ← by_contra theorem by_contra {p : Prop} : (¬p → False) → p := decidable.by_contradiction /-- In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely. The `decidable` namespace contains versions of lemmas from the root namespace that explicitly attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs. You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if `classical.choice` appears in the list. -/ -- See Note [decidable namespace] protected theorem decidable.not_not {a : Prop} [Decidable a] : ¬¬a ↔ a := { mp := decidable.by_contradiction, mpr := not_not_intro } /-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`. The left-to-right direction, double negation elimination (DNE), is classically true but not constructively. -/ @[simp] theorem not_not {a : Prop} : ¬¬a ↔ a := decidable.not_not theorem of_not_not {a : Prop} : ¬¬a → a := by_contra -- See Note [decidable namespace] protected theorem decidable.of_not_imp {a : Prop} {b : Prop} [Decidable a] (h : ¬(a → b)) : a := decidable.by_contradiction (not_not_of_not_imp h) theorem of_not_imp {a : Prop} {b : Prop} : ¬(a → b) → a := decidable.of_not_imp -- See Note [decidable namespace] protected theorem decidable.not_imp_symm {a : Prop} {b : Prop} [Decidable a] (h : ¬a → b) (hb : ¬b) : a := decidable.by_contradiction (hb ∘ h) theorem not.decidable_imp_symm {a : Prop} {b : Prop} [Decidable a] : (¬a → b) → ¬b → a := decidable.not_imp_symm theorem not.imp_symm {a : Prop} {b : Prop} : (¬a → b) → ¬b → a := not.decidable_imp_symm -- See Note [decidable namespace] protected theorem decidable.not_imp_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a → b ↔ ¬b → a := { mp := not.decidable_imp_symm, mpr := not.decidable_imp_symm } theorem not_imp_comm {a : Prop} {b : Prop} : ¬a → b ↔ ¬b → a := decidable.not_imp_comm @[simp] theorem imp_not_self {a : Prop} : a → ¬a ↔ ¬a := { mp := fun (h : a → ¬a) (ha : a) => h ha ha, mpr := fun (h : ¬a) (_x : a) => h } theorem decidable.not_imp_self {a : Prop} [Decidable a] : ¬a → a ↔ a := eq.mp (Eq._oldrec (Eq.refl (¬a → ¬¬a ↔ ¬¬a)) (propext decidable.not_not)) imp_not_self @[simp] theorem not_imp_self {a : Prop} : ¬a → a ↔ a := decidable.not_imp_self theorem imp.swap {a : Prop} {b : Prop} {c : Prop} : a → b → c ↔ b → a → c := { mp := function.swap, mpr := function.swap } theorem imp_not_comm {a : Prop} {b : Prop} : a → ¬b ↔ b → ¬a := imp.swap /-! ### Declarations about `and` -/ theorem and_congr_left {a : Prop} {b : Prop} {c : Prop} (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c := iff.trans and.comm (iff.trans (and_congr_right h) and.comm) theorem and_congr_left' {a : Prop} {b : Prop} {c : Prop} (h : a ↔ b) : a ∧ c ↔ b ∧ c := and_congr h iff.rfl theorem and_congr_right' {a : Prop} {b : Prop} {c : Prop} (h : b ↔ c) : a ∧ b ↔ a ∧ c := and_congr iff.rfl h theorem not_and_of_not_left {a : Prop} (b : Prop) : ¬a → ¬(a ∧ b) := mt and.left theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) := mt and.right theorem and.imp_left {a : Prop} {b : Prop} {c : Prop} (h : a → b) : a ∧ c → b ∧ c := and.imp h id theorem and.imp_right {a : Prop} {b : Prop} {c : Prop} (h : a → b) : c ∧ a → c ∧ b := and.imp id h theorem and.right_comm {a : Prop} {b : Prop} {c : Prop} : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := sorry theorem and.rotate {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∧ c ↔ b ∧ c ∧ a := sorry theorem and_not_self_iff (a : Prop) : a ∧ ¬a ↔ False := { mp := fun (h : a ∧ ¬a) => and.right h (and.left h), mpr := fun (h : False) => false.elim h } theorem not_and_self_iff (a : Prop) : ¬a ∧ a ↔ False := sorry theorem and_iff_left_of_imp {a : Prop} {b : Prop} (h : a → b) : a ∧ b ↔ a := { mp := and.left, mpr := fun (ha : a) => { left := ha, right := h ha } } theorem and_iff_right_of_imp {a : Prop} {b : Prop} (h : b → a) : a ∧ b ↔ b := { mp := and.right, mpr := fun (hb : b) => { left := h hb, right := hb } } @[simp] theorem and_iff_left_iff_imp {a : Prop} {b : Prop} : a ∧ b ↔ a ↔ a → b := { mp := fun (h : a ∧ b ↔ a) (ha : a) => and.right (iff.mpr h ha), mpr := and_iff_left_of_imp } @[simp] theorem and_iff_right_iff_imp {a : Prop} {b : Prop} : a ∧ b ↔ b ↔ b → a := { mp := fun (h : a ∧ b ↔ b) (ha : b) => and.left (iff.mpr h ha), mpr := and_iff_right_of_imp } @[simp] theorem and.congr_right_iff {a : Prop} {b : Prop} {c : Prop} : a ∧ b ↔ a ∧ c ↔ a → (b ↔ c) := sorry @[simp] theorem and.congr_left_iff {a : Prop} {b : Prop} {c : Prop} : a ∧ c ↔ b ∧ c ↔ c → (a ↔ b) := sorry @[simp] theorem and_self_left {a : Prop} {b : Prop} : a ∧ a ∧ b ↔ a ∧ b := { mp := fun (h : a ∧ a ∧ b) => { left := and.left h, right := and.right (and.right h) }, mpr := fun (h : a ∧ b) => { left := and.left h, right := { left := and.left h, right := and.right h } } } @[simp] theorem and_self_right {a : Prop} {b : Prop} : (a ∧ b) ∧ b ↔ a ∧ b := { mp := fun (h : (a ∧ b) ∧ b) => { left := and.left (and.left h), right := and.right h }, mpr := fun (h : a ∧ b) => { left := { left := and.left h, right := and.right h }, right := and.right h } } /-! ### Declarations about `or` -/ theorem or_congr_left {a : Prop} {b : Prop} {c : Prop} (h : a ↔ b) : a ∨ c ↔ b ∨ c := or_congr h iff.rfl theorem or_congr_right {a : Prop} {b : Prop} {c : Prop} (h : b ↔ c) : a ∨ b ↔ a ∨ c := or_congr iff.rfl h theorem or.right_comm {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b := eq.mpr (id (Eq._oldrec (Eq.refl ((a ∨ b) ∨ c ↔ (a ∨ c) ∨ b)) (propext (or_assoc a b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ∨ c ↔ (a ∨ c) ∨ b)) (propext (or_assoc a c)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ∨ c ↔ a ∨ c ∨ b)) (propext (or_comm b c)))) (iff.refl (a ∨ c ∨ b)))) theorem or_of_or_of_imp_of_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d := or.imp h₂ h₃ h₁ theorem or_of_or_of_imp_left {a : Prop} {b : Prop} {c : Prop} (h₁ : a ∨ c) (h : a → b) : b ∨ c := or.imp_left h h₁ theorem or_of_or_of_imp_right {a : Prop} {b : Prop} {c : Prop} (h₁ : c ∨ a) (h : a → b) : c ∨ b := or.imp_right h h₁ theorem or.elim3 {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d := or.elim h ha fun (h₂ : b ∨ c) => or.elim h₂ hb hc theorem or_imp_distrib {a : Prop} {b : Prop} {c : Prop} : a ∨ b → c ↔ (a → c) ∧ (b → c) := sorry -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_left {a : Prop} {b : Prop} [Decidable a] : a ∨ b ↔ ¬a → b := { mp := or.resolve_left, mpr := fun (h : ¬a → b) => dite a Or.inl (Or.inr ∘ h) } theorem or_iff_not_imp_left {a : Prop} {b : Prop} : a ∨ b ↔ ¬a → b := decidable.or_iff_not_imp_left -- See Note [decidable namespace] protected theorem decidable.or_iff_not_imp_right {a : Prop} {b : Prop} [Decidable b] : a ∨ b ↔ ¬b → a := iff.trans or.comm decidable.or_iff_not_imp_left theorem or_iff_not_imp_right {a : Prop} {b : Prop} : a ∨ b ↔ ¬b → a := decidable.or_iff_not_imp_right -- See Note [decidable namespace] protected theorem decidable.not_imp_not {a : Prop} {b : Prop} [Decidable a] : ¬a → ¬b ↔ b → a := { mp := fun (h : ¬a → ¬b) (hb : b) => decidable.by_contradiction fun (na : ¬a) => h na hb, mpr := mt } theorem not_imp_not {a : Prop} {b : Prop} : ¬a → ¬b ↔ b → a := decidable.not_imp_not @[simp] theorem or_iff_left_iff_imp {a : Prop} {b : Prop} : a ∨ b ↔ a ↔ b → a := { mp := fun (h : a ∨ b ↔ a) (hb : b) => iff.mp h (Or.inr hb), mpr := or_iff_left_of_imp } @[simp] theorem or_iff_right_iff_imp {a : Prop} {b : Prop} : a ∨ b ↔ b ↔ a → b := eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ b ↔ a → b)) (propext (or_comm a b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (b ∨ a ↔ b ↔ a → b)) (propext or_iff_left_iff_imp))) (iff.refl (a → b))) /-! ### Declarations about distributivity -/ /-- `∧` distributes over `∨` (on the left). -/ theorem and_or_distrib_left {a : Prop} {b : Prop} {c : Prop} : a ∧ (b ∨ c) ↔ a ∧ b ∨ a ∧ c := sorry /-- `∧` distributes over `∨` (on the right). -/ theorem or_and_distrib_right {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∧ c ↔ a ∧ c ∨ b ∧ c := iff.trans (iff.trans and.comm and_or_distrib_left) (or_congr and.comm and.comm) /-- `∨` distributes over `∧` (on the left). -/ theorem or_and_distrib_left {a : Prop} {b : Prop} {c : Prop} : a ∨ b ∧ c ↔ (a ∨ b) ∧ (a ∨ c) := { mp := Or._oldrec (fun (ha : a) => { left := Or.inl ha, right := Or.inl ha }) (and.imp Or.inr Or.inr), mpr := And._oldrec (Or._oldrec (imp_intro ∘ Or.inl) (or.imp_right ∘ And.intro)) } /-- `∨` distributes over `∧` (on the right). -/ theorem and_or_distrib_right {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∨ c ↔ (a ∨ c) ∧ (b ∨ c) := iff.trans (iff.trans or.comm or_and_distrib_left) (and_congr or.comm or.comm) @[simp] theorem or_self_left {a : Prop} {b : Prop} : a ∨ a ∨ b ↔ a ∨ b := { mp := fun (h : a ∨ a ∨ b) => or.elim h Or.inl id, mpr := fun (h : a ∨ b) => or.elim h Or.inl (Or.inr ∘ Or.inr) } @[simp] theorem or_self_right {a : Prop} {b : Prop} : (a ∨ b) ∨ b ↔ a ∨ b := { mp := fun (h : (a ∨ b) ∨ b) => or.elim h id Or.inr, mpr := fun (h : a ∨ b) => or.elim h (Or.inl ∘ Or.inl) Or.inr } /-! Declarations about `iff` -/ theorem iff_of_true {a : Prop} {b : Prop} (ha : a) (hb : b) : a ↔ b := { mp := fun (_x : a) => hb, mpr := fun (_x : b) => ha } theorem iff_of_false {a : Prop} {b : Prop} (ha : ¬a) (hb : ¬b) : a ↔ b := { mp := not.elim ha, mpr := not.elim hb } theorem iff_true_left {a : Prop} {b : Prop} (ha : a) : a ↔ b ↔ b := { mp := fun (h : a ↔ b) => iff.mp h ha, mpr := iff_of_true ha } theorem iff_true_right {a : Prop} {b : Prop} (ha : a) : b ↔ a ↔ b := iff.trans iff.comm (iff_true_left ha) theorem iff_false_left {a : Prop} {b : Prop} (ha : ¬a) : a ↔ b ↔ ¬b := { mp := fun (h : a ↔ b) => mt (iff.mpr h) ha, mpr := iff_of_false ha } theorem iff_false_right {a : Prop} {b : Prop} (ha : ¬a) : b ↔ a ↔ ¬b := iff.trans iff.comm (iff_false_left ha) -- See Note [decidable namespace] protected theorem decidable.not_or_of_imp {a : Prop} {b : Prop} [Decidable a] (h : a → b) : ¬a ∨ b := dite a (fun (ha : a) => Or.inr (h ha)) fun (ha : ¬a) => Or.inl ha theorem not_or_of_imp {a : Prop} {b : Prop} : (a → b) → ¬a ∨ b := decidable.not_or_of_imp -- See Note [decidable namespace] protected theorem decidable.imp_iff_not_or {a : Prop} {b : Prop} [Decidable a] : a → b ↔ ¬a ∨ b := { mp := decidable.not_or_of_imp, mpr := or.neg_resolve_left } theorem imp_iff_not_or {a : Prop} {b : Prop} : a → b ↔ ¬a ∨ b := decidable.imp_iff_not_or -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib {a : Prop} {b : Prop} {c : Prop} [Decidable a] : a → b ∨ c ↔ (a → b) ∨ (a → c) := sorry theorem imp_or_distrib {a : Prop} {b : Prop} {c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib -- See Note [decidable namespace] protected theorem decidable.imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} [Decidable b] : a → b ∨ c ↔ (a → b) ∨ (a → c) := sorry theorem imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) := decidable.imp_or_distrib' theorem not_imp_of_and_not {a : Prop} {b : Prop} : a ∧ ¬b → ¬(a → b) := fun (ᾰ : a ∧ ¬b) (ᾰ_1 : a → b) => and.dcases_on ᾰ fun (ᾰ_left : a) (ᾰ_right : ¬b) => idRhs False (ᾰ_right (ᾰ_1 ᾰ_left)) -- See Note [decidable namespace] protected theorem decidable.not_imp {a : Prop} {b : Prop} [Decidable a] : ¬(a → b) ↔ a ∧ ¬b := { mp := fun (h : ¬(a → b)) => { left := decidable.of_not_imp h, right := not_of_not_imp h }, mpr := not_imp_of_and_not } theorem not_imp {a : Prop} {b : Prop} : ¬(a → b) ↔ a ∧ ¬b := decidable.not_imp -- for monotonicity theorem imp_imp_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₀ : c → a) (h₁ : b → d) : (a → b) → c → d := fun (h₂ : a → b) => h₁ ∘ h₂ ∘ h₀ -- See Note [decidable namespace] protected theorem decidable.peirce (a : Prop) (b : Prop) [Decidable a] : ((a → b) → a) → a := dite a (fun (ha : a) (h : (a → b) → a) => ha) fun (ha : ¬a) (h : (a → b) → a) => h (not.elim ha) theorem peirce (a : Prop) (b : Prop) : ((a → b) → a) → a := decidable.peirce a b theorem peirce' {a : Prop} (H : ∀ (b : Prop), (a → b) → a) : a := H a id -- See Note [decidable namespace] protected theorem decidable.not_iff_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a ↔ ¬b ↔ (a ↔ b) := eq.mpr (id (Eq._oldrec (Eq.refl (¬a ↔ ¬b ↔ (a ↔ b))) (propext iff_def))) (eq.mpr (id (Eq._oldrec (Eq.refl ((¬a → ¬b) ∧ (¬b → ¬a) ↔ (a ↔ b))) (propext iff_def'))) (and_congr decidable.not_imp_not decidable.not_imp_not)) theorem not_iff_not {a : Prop} {b : Prop} : ¬a ↔ ¬b ↔ (a ↔ b) := decidable.not_iff_not -- See Note [decidable namespace] protected theorem decidable.not_iff_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a ↔ b ↔ (¬b ↔ a) := eq.mpr (id (Eq._oldrec (Eq.refl (¬a ↔ b ↔ (¬b ↔ a))) (propext iff_def))) (eq.mpr (id (Eq._oldrec (Eq.refl ((¬a → b) ∧ (b → ¬a) ↔ (¬b ↔ a))) (propext iff_def))) (and_congr decidable.not_imp_comm imp_not_comm)) theorem not_iff_comm {a : Prop} {b : Prop} : ¬a ↔ b ↔ (¬b ↔ a) := decidable.not_iff_comm -- See Note [decidable namespace] protected theorem decidable.not_iff {a : Prop} {b : Prop} [Decidable b] : ¬(a ↔ b) ↔ (¬a ↔ b) := sorry theorem not_iff {a : Prop} {b : Prop} : ¬(a ↔ b) ↔ (¬a ↔ b) := decidable.not_iff -- See Note [decidable namespace] protected theorem decidable.iff_not_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ↔ ¬b ↔ (b ↔ ¬a) := eq.mpr (id (Eq._oldrec (Eq.refl (a ↔ ¬b ↔ (b ↔ ¬a))) (propext iff_def))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a → ¬b) ∧ (¬b → a) ↔ (b ↔ ¬a))) (propext iff_def))) (and_congr imp_not_comm decidable.not_imp_comm)) theorem iff_not_comm {a : Prop} {b : Prop} : a ↔ ¬b ↔ (b ↔ ¬a) := decidable.iff_not_comm -- See Note [decidable namespace] protected theorem decidable.iff_iff_and_or_not_and_not {a : Prop} {b : Prop} [Decidable b] : a ↔ b ↔ a ∧ b ∨ ¬a ∧ ¬b := sorry theorem iff_iff_and_or_not_and_not {a : Prop} {b : Prop} : a ↔ b ↔ a ∧ b ∨ ¬a ∧ ¬b := decidable.iff_iff_and_or_not_and_not theorem decidable.iff_iff_not_or_and_or_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ↔ b ↔ (¬a ∨ b) ∧ (a ∨ ¬b) := sorry theorem iff_iff_not_or_and_or_not {a : Prop} {b : Prop} : a ↔ b ↔ (¬a ∨ b) ∧ (a ∨ ¬b) := decidable.iff_iff_not_or_and_or_not -- See Note [decidable namespace] protected theorem decidable.not_and_not_right {a : Prop} {b : Prop} [Decidable b] : ¬(a ∧ ¬b) ↔ a → b := sorry theorem not_and_not_right {a : Prop} {b : Prop} : ¬(a ∧ ¬b) ↔ a → b := decidable.not_and_not_right /-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent. **Important**: this function should be used instead of `rw` on `decidable b`, because the kernel will get stuck reducing the usage of `propext` otherwise, and `dec_trivial` will not work. -/ def decidable_of_iff {b : Prop} (a : Prop) (h : a ↔ b) [D : Decidable a] : Decidable b := decidable_of_decidable_of_iff D h /-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent. This is the same as `decidable_of_iff` but the iff is flipped. -/ def decidable_of_iff' {a : Prop} (b : Prop) (h : a ↔ b) [D : Decidable b] : Decidable a := decidable_of_decidable_of_iff D (iff.symm h) /-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`. (This is sometimes taken as an alternate definition of decidability.) -/ def decidable_of_bool {a : Prop} (b : Bool) (h : ↥b ↔ a) : Decidable a := sorry /-! ### De Morgan's laws -/ theorem not_and_of_not_or_not {a : Prop} {b : Prop} (h : ¬a ∨ ¬b) : ¬(a ∧ b) := fun (ᾰ : a ∧ b) => and.dcases_on ᾰ fun (ᾰ_left : a) (ᾰ_right : b) => idRhs False (or.elim h (absurd ᾰ_left) (absurd ᾰ_right)) -- See Note [decidable namespace] protected theorem decidable.not_and_distrib {a : Prop} {b : Prop} [Decidable a] : ¬(a ∧ b) ↔ ¬a ∨ ¬b := sorry -- See Note [decidable namespace] protected theorem decidable.not_and_distrib' {a : Prop} {b : Prop} [Decidable b] : ¬(a ∧ b) ↔ ¬a ∨ ¬b := sorry /-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the disjunction of the negations. -/ theorem not_and_distrib {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ ¬a ∨ ¬b := decidable.not_and_distrib @[simp] theorem not_and {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ a → ¬b := and_imp theorem not_and' {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ b → ¬a := iff.trans not_and imp_not_comm /-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the conjunction of the negations. -/ theorem not_or_distrib {a : Prop} {b : Prop} : ¬(a ∨ b) ↔ ¬a ∧ ¬b := sorry -- See Note [decidable namespace] protected theorem decidable.or_iff_not_and_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ∨ b ↔ ¬(¬a ∧ ¬b) := eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ ¬(¬a ∧ ¬b))) (Eq.symm (propext not_or_distrib)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ ¬¬(a ∨ b))) (propext decidable.not_not))) (iff.refl (a ∨ b))) theorem or_iff_not_and_not {a : Prop} {b : Prop} : a ∨ b ↔ ¬(¬a ∧ ¬b) := decidable.or_iff_not_and_not -- See Note [decidable namespace] protected theorem decidable.and_iff_not_or_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ∧ b ↔ ¬(¬a ∨ ¬b) := eq.mpr (id (Eq._oldrec (Eq.refl (a ∧ b ↔ ¬(¬a ∨ ¬b))) (Eq.symm (propext decidable.not_and_distrib)))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ∧ b ↔ ¬¬(a ∧ b))) (propext decidable.not_not))) (iff.refl (a ∧ b))) theorem and_iff_not_or_not {a : Prop} {b : Prop} : a ∧ b ↔ ¬(¬a ∨ ¬b) := decidable.and_iff_not_or_not /-! ### Declarations about equality -/ @[simp] theorem heq_iff_eq {α : Sort u_1} {a : α} {b : α} : a == b ↔ a = b := { mp := eq_of_heq, mpr := heq_of_eq } theorem proof_irrel_heq {p : Prop} {q : Prop} (hp : p) (hq : q) : hp == hq := (fun (this : p = q) => Eq._oldrec (fun (hq : p) => HEq.refl hp) this hq) (propext { mp := fun (_x : p) => hq, mpr := fun (_x : q) => hp }) theorem ne_of_mem_of_not_mem {α : outParam (Type u_1)} {β : Type u_2} [has_mem α β] {s : β} {a : α} {b : α} (h : a ∈ s) : ¬b ∈ s → a ≠ b := mt fun (e : a = b) => e ▸ h theorem eq_equivalence {α : Sort u_1} : equivalence Eq := { left := Eq.refl, right := { left := Eq.symm, right := Eq.trans } } /-- Transport through trivial families is the identity. -/ @[simp] theorem eq_rec_constant {α : Sort u_1} {a : α} {a' : α} {β : Sort u_2} (y : β) (h : a = a') : Eq._oldrec y h = y := sorry @[simp] theorem eq_mp_rfl {α : Sort u_1} {a : α} : eq.mp (Eq.refl α) a = a := rfl @[simp] theorem eq_mpr_rfl {α : Sort u_1} {a : α} : eq.mpr (Eq.refl α) a = a := rfl theorem heq_of_eq_mp {α : Sort u_1} {β : Sort u_1} {a : α} {a' : β} (e : α = β) (h₂ : eq.mp e a = a') : a == a' := sorry theorem rec_heq_of_heq {α : Sort u_1} {a : α} {b : α} {β : Sort u_2} {C : α → Sort u_2} {x : C a} {y : β} (eq : a = b) (h : x == y) : Eq._oldrec x eq == y := eq.drec h eq @[simp] theorem eq_mpr_heq {α : Sort u} {β : Sort u} (h : β = α) (x : α) : eq.mpr h x == x := eq.drec (fun (x : β) => HEq.refl (eq.mpr (Eq.refl β) x)) h x protected theorem eq.congr {α : Sort u_1} {x₁ : α} {x₂ : α} {y₁ : α} {y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) : x₁ = x₂ ↔ y₁ = y₂ := Eq._oldrec (Eq._oldrec (iff.refl (x₁ = x₂)) h₂) h₁ theorem eq.congr_left {α : Sort u_1} {x : α} {y : α} {z : α} (h : x = y) : x = z ↔ y = z := eq.mpr (id (Eq._oldrec (Eq.refl (x = z ↔ y = z)) h)) (iff.refl (y = z)) theorem eq.congr_right {α : Sort u_1} {x : α} {y : α} {z : α} (h : x = y) : z = x ↔ z = y := eq.mpr (id (Eq._oldrec (Eq.refl (z = x ↔ z = y)) h)) (iff.refl (z = y)) theorem congr_arg2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) {x : α} {x' : α} {y : β} {y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' := Eq._oldrec (Eq._oldrec (Eq.refl (f x y)) hy) hx /-! ### Declarations about quantifiers -/ theorem forall_imp {α : Sort u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a → q a) : (∀ (a : α), p a) → ∀ (a : α), q a := fun (h' : ∀ (a : α), p a) (a : α) => h a (h' a) theorem forall₂_congr {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} {q : α → β → Prop} (h : ∀ (a : α) (b : β), p a b ↔ q a b) : (∀ (a : α) (b : β), p a b) ↔ ∀ (a : α) (b : β), q a b := forall_congr fun (a : α) => forall_congr (h a) theorem forall₃_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → β → γ → Prop} {q : α → β → γ → Prop} (h : ∀ (a : α) (b : β) (c : γ), p a b c ↔ q a b c) : (∀ (a : α) (b : β) (c : γ), p a b c) ↔ ∀ (a : α) (b : β) (c : γ), q a b c := forall_congr fun (a : α) => forall₂_congr (h a) theorem forall₄_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {δ : Sort u_4} {p : α → β → γ → δ → Prop} {q : α → β → γ → δ → Prop} (h : ∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d ↔ q a b c d) : (∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d) ↔ ∀ (a : α) (b : β) (c : γ) (d : δ), q a b c d := forall_congr fun (a : α) => forall₃_congr (h a) theorem Exists.imp {α : Sort u_1} {q : α → Prop} {p : α → Prop} (h : ∀ (a : α), p a → q a) : (∃ (a : α), p a) → ∃ (a : α), q a := fun (p_1 : ∃ (a : α), p a) => exists_imp_exists h p_1 theorem exists_imp_exists' {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ (a : α), p a → q (f a)) (hp : ∃ (a : α), p a) : ∃ (b : β), q b := exists.elim hp fun (a : α) (hp' : p a) => Exists.intro (f a) (hpq a hp') theorem exists₂_congr {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} {q : α → β → Prop} (h : ∀ (a : α) (b : β), p a b ↔ q a b) : (∃ (a : α), ∃ (b : β), p a b) ↔ ∃ (a : α), ∃ (b : β), q a b := exists_congr fun (a : α) => exists_congr (h a) theorem exists₃_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → β → γ → Prop} {q : α → β → γ → Prop} (h : ∀ (a : α) (b : β) (c : γ), p a b c ↔ q a b c) : (∃ (a : α), ∃ (b : β), ∃ (c : γ), p a b c) ↔ ∃ (a : α), ∃ (b : β), ∃ (c : γ), q a b c := exists_congr fun (a : α) => exists₂_congr (h a) theorem exists₄_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {δ : Sort u_4} {p : α → β → γ → δ → Prop} {q : α → β → γ → δ → Prop} (h : ∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d ↔ q a b c d) : (∃ (a : α), ∃ (b : β), ∃ (c : γ), ∃ (d : δ), p a b c d) ↔ ∃ (a : α), ∃ (b : β), ∃ (c : γ), ∃ (d : δ), q a b c d := exists_congr fun (a : α) => exists₃_congr (h a) theorem forall_swap {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∀ (x : α) (y : β), p x y) ↔ ∀ (y : β) (x : α), p x y := { mp := function.swap, mpr := function.swap } theorem exists_swap {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∃ (x : α), ∃ (y : β), p x y) ↔ ∃ (y : β), ∃ (x : α), p x y := sorry @[simp] theorem exists_imp_distrib {α : Sort u_1} {p : α → Prop} {b : Prop} : (∃ (x : α), p x) → b ↔ ∀ (x : α), p x → b := sorry /-- Extract an element from a existential statement, using `classical.some`. -/ -- This enables projection notation. def Exists.some {α : Sort u_1} {p : α → Prop} (P : ∃ (a : α), p a) : α := classical.some P /-- Show that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`. -/ theorem Exists.some_spec {α : Sort u_1} {p : α → Prop} (P : ∃ (a : α), p a) : p (Exists.some P) := classical.some_spec P --theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x := --forall_imp_of_exists_imp h theorem not_exists_of_forall_not {α : Sort u_1} {p : α → Prop} (h : ∀ (x : α), ¬p x) : ¬∃ (x : α), p x := iff.mpr exists_imp_distrib h @[simp] theorem not_exists {α : Sort u_1} {p : α → Prop} : (¬∃ (x : α), p x) ↔ ∀ (x : α), ¬p x := exists_imp_distrib theorem not_forall_of_exists_not {α : Sort u_1} {p : α → Prop} : (∃ (x : α), ¬p x) → ¬∀ (x : α), p x := fun (ᾰ : ∃ (x : α), ¬p x) (ᾰ_1 : ∀ (x : α), p x) => Exists.dcases_on ᾰ fun (ᾰ_w : α) (ᾰ_h : ¬p ᾰ_w) => idRhs False (ᾰ_h (ᾰ_1 ᾰ_w)) -- See Note [decidable namespace] protected theorem decidable.not_forall {α : Sort u_1} {p : α → Prop} [Decidable (∃ (x : α), ¬p x)] [(x : α) → Decidable (p x)] : (¬∀ (x : α), p x) ↔ ∃ (x : α), ¬p x := sorry @[simp] theorem not_forall {α : Sort u_1} {p : α → Prop} : (¬∀ (x : α), p x) ↔ ∃ (x : α), ¬p x := decidable.not_forall -- See Note [decidable namespace] protected theorem decidable.not_forall_not {α : Sort u_1} {p : α → Prop} [Decidable (∃ (x : α), p x)] : (¬∀ (x : α), ¬p x) ↔ ∃ (x : α), p x := iff.mp decidable.not_iff_comm not_exists theorem not_forall_not {α : Sort u_1} {p : α → Prop} : (¬∀ (x : α), ¬p x) ↔ ∃ (x : α), p x := decidable.not_forall_not -- See Note [decidable namespace] protected theorem decidable.not_exists_not {α : Sort u_1} {p : α → Prop} [(x : α) → Decidable (p x)] : (¬∃ (x : α), ¬p x) ↔ ∀ (x : α), p x := sorry @[simp] theorem not_exists_not {α : Sort u_1} {p : α → Prop} : (¬∃ (x : α), ¬p x) ↔ ∀ (x : α), p x := decidable.not_exists_not @[simp] theorem forall_true_iff {α : Sort u_1} : α → True ↔ True := iff_true_intro fun (_x : α) => trivial -- Unfortunately this causes simp to loop sometimes, so we -- add the 2 and 3 cases as simp lemmas instead theorem forall_true_iff' {α : Sort u_1} {p : α → Prop} (h : ∀ (a : α), p a ↔ True) : (∀ (a : α), p a) ↔ True := iff_true_intro fun (_x : α) => of_iff_true (h _x) @[simp] theorem forall_2_true_iff {α : Sort u_1} {β : α → Sort u_2} : (∀ (a : α), β a → True) ↔ True := forall_true_iff' fun (_x : α) => forall_true_iff @[simp] theorem forall_3_true_iff {α : Sort u_1} {β : α → Sort u_2} {γ : (a : α) → β a → Sort u_3} : (∀ (a : α) (b : β a), γ a b → True) ↔ True := forall_true_iff' fun (_x : α) => forall_2_true_iff @[simp] theorem forall_const {b : Prop} (α : Sort u_1) [i : Nonempty α] : α → b ↔ b := { mp := nonempty.elim i, mpr := fun (hb : b) (x : α) => hb } @[simp] theorem exists_const {b : Prop} (α : Sort u_1) [i : Nonempty α] : (∃ (x : α), b) ↔ b := { mp := fun (_x : ∃ (x : α), b) => (fun (_a : ∃ (x : α), b) => Exists.dcases_on _a fun (w : α) (h : b) => idRhs b h) _x, mpr := nonempty.elim i exists.intro } theorem forall_and_distrib {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∀ (x : α), p x ∧ q x) ↔ (∀ (x : α), p x) ∧ ∀ (x : α), q x := sorry theorem exists_or_distrib {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), p x ∨ q x) ↔ (∃ (x : α), p x) ∨ ∃ (x : α), q x := sorry @[simp] theorem exists_and_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} : (∃ (x : α), q ∧ p x) ↔ q ∧ ∃ (x : α), p x := sorry @[simp] theorem exists_and_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} : (∃ (x : α), p x ∧ q) ↔ (∃ (x : α), p x) ∧ q := sorry @[simp] theorem forall_eq {α : Sort u_1} {p : α → Prop} {a' : α} : (∀ (a : α), a = a' → p a) ↔ p a' := { mp := fun (h : ∀ (a : α), a = a' → p a) => h a' rfl, mpr := fun (h : p a') (a : α) (e : a = a') => Eq.symm e ▸ h } @[simp] theorem forall_eq' {α : Sort u_1} {p : α → Prop} {a' : α} : (∀ (a : α), a' = a → p a) ↔ p a' := sorry -- this lemma is needed to simplify the output of `list.mem_cons_iff` @[simp] theorem forall_eq_or_imp {α : Sort u_1} {p : α → Prop} {q : α → Prop} {a' : α} : (∀ (a : α), a = a' ∨ q a → p a) ↔ p a' ∧ ∀ (a : α), q a → p a := sorry @[simp] theorem exists_eq {α : Sort u_1} {a' : α} : ∃ (a : α), a = a' := Exists.intro a' rfl @[simp] theorem exists_eq' {α : Sort u_1} {a' : α} : ∃ (a : α), a' = a := Exists.intro a' rfl @[simp] theorem exists_eq_left {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), a = a' ∧ p a) ↔ p a' := sorry @[simp] theorem exists_eq_right {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), p a ∧ a = a') ↔ p a' := iff.trans (exists_congr fun (a : α) => and.comm) exists_eq_left @[simp] theorem exists_eq_right_right {α : Sort u_1} {p : α → Prop} {b : Prop} {a' : α} : (∃ (a : α), p a ∧ b ∧ a = a') ↔ p a' ∧ b := sorry @[simp] theorem exists_eq_right_right' {α : Sort u_1} {p : α → Prop} {b : Prop} {a' : α} : (∃ (a : α), p a ∧ b ∧ a' = a) ↔ p a' ∧ b := sorry @[simp] theorem exists_apply_eq_apply {α : Type u_1} {β : Type u_2} (f : α → β) (a' : α) : ∃ (a : α), f a = f a' := Exists.intro a' rfl @[simp] theorem exists_apply_eq_apply' {α : Type u_1} {β : Type u_2} (f : α → β) (a' : α) : ∃ (a : α), f a' = f a := Exists.intro a' rfl @[simp] theorem exists_exists_and_eq_and {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : α → Prop} {q : β → Prop} : (∃ (b : β), (∃ (a : α), p a ∧ f a = b) ∧ q b) ↔ ∃ (a : α), p a ∧ q (f a) := sorry @[simp] theorem exists_exists_eq_and {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∃ (b : β), (∃ (a : α), f a = b) ∧ p b) ↔ ∃ (a : α), p (f a) := sorry @[simp] theorem forall_apply_eq_imp_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (a : α) (b : β), f a = b → p b) ↔ ∀ (a : α), p (f a) := { mp := fun (h : ∀ (a : α) (b : β), f a = b → p b) (a : α) => h a (f a) rfl, mpr := fun (h : ∀ (a : α), p (f a)) (a : α) (b : β) (hab : f a = b) => hab ▸ h a } @[simp] theorem forall_apply_eq_imp_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (b : β) (a : α), f a = b → p b) ↔ ∀ (a : α), p (f a) := sorry @[simp] theorem forall_eq_apply_imp_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (a : α) (b : β), b = f a → p b) ↔ ∀ (a : α), p (f a) := sorry @[simp] theorem forall_eq_apply_imp_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (b : β) (a : α), b = f a → p b) ↔ ∀ (a : α), p (f a) := sorry @[simp] theorem forall_apply_eq_imp_iff₂ {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : α → Prop} {q : β → Prop} : (∀ (b : β) (a : α), p a → f a = b → q b) ↔ ∀ (a : α), p a → q (f a) := { mp := fun (h : ∀ (b : β) (a : α), p a → f a = b → q b) (a : α) (ha : p a) => h (f a) a ha rfl, mpr := fun (h : ∀ (a : α), p a → q (f a)) (b : β) (a : α) (ha : p a) (hb : f a = b) => hb ▸ h a ha } @[simp] theorem exists_eq_left' {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), a' = a ∧ p a) ↔ p a' := sorry @[simp] theorem exists_eq_right' {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), p a ∧ a' = a) ↔ p a' := sorry theorem exists_comm {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∃ (a : α), ∃ (b : β), p a b) ↔ ∃ (b : β), ∃ (a : α), p a b := sorry theorem forall_or_of_or_forall {α : Sort u_1} {p : α → Prop} {b : Prop} (h : b ∨ ∀ (x : α), p x) (x : α) : b ∨ p x := or.imp_right (fun (h₂ : ∀ (x : α), p x) => h₂ x) h -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} [Decidable q] : (∀ (x : α), q ∨ p x) ↔ q ∨ ∀ (x : α), p x := sorry theorem forall_or_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} : (∀ (x : α), q ∨ p x) ↔ q ∨ ∀ (x : α), p x := decidable.forall_or_distrib_left -- See Note [decidable namespace] protected theorem decidable.forall_or_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} [Decidable q] : (∀ (x : α), p x ∨ q) ↔ (∀ (x : α), p x) ∨ q := sorry theorem forall_or_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} : (∀ (x : α), p x ∨ q) ↔ (∀ (x : α), p x) ∨ q := decidable.forall_or_distrib_right /-- A predicate holds everywhere on the image of a surjective functions iff it holds everywhere. -/ theorem forall_iff_forall_surj {α : Type u_1} {β : Type u_2} {f : α → β} (h : function.surjective f) {P : β → Prop} : (∀ (a : α), P (f a)) ↔ ∀ (b : β), P b := sorry @[simp] theorem exists_prop {p : Prop} {q : Prop} : (∃ (h : p), q) ↔ p ∧ q := sorry @[simp] theorem exists_false {α : Sort u_1} : ¬∃ (a : α), False := fun (_x : ∃ (a : α), False) => (fun (_a : ∃ (a : α), False) => Exists.dcases_on _a fun (w : α) (h : False) => idRhs False h) _x @[simp] theorem exists_unique_false {α : Sort u_1} : ¬exists_unique fun (a : α) => False := sorry theorem Exists.fst {b : Prop} {p : b → Prop} : Exists p → b := fun (ᾰ : Exists p) => Exists.dcases_on ᾰ fun (ᾰ_w : b) (ᾰ_h : p ᾰ_w) => idRhs b ᾰ_w theorem Exists.snd {b : Prop} {p : b → Prop} (h : Exists p) : p (Exists.fst h) := Exists.dcases_on h fun (h_w : b) (h_h : p h_w) => idRhs (p h_w) h_h @[simp] theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ (h' : p), q h') ↔ q h := forall_const p @[simp] theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ (h' : p), q h') ↔ q h := exists_const p @[simp] theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬p) : (∀ (h' : p), q h') ↔ True := iff_true_intro fun (h : p) => not.elim hn h @[simp] theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬p → ¬∃ (h' : p), q h' := mt Exists.fst theorem exists_unique.exists {α : Sort u_1} {p : α → Prop} (h : exists_unique fun (x : α) => p x) : ∃ (x : α), p x := exists.elim h fun (x : α) (hx : (fun (x : α) => p x) x ∧ ∀ (y : α), p y → y = x) => Exists.intro x (and.left hx) theorem exists_unique.unique {α : Sort u_1} {p : α → Prop} (h : exists_unique fun (x : α) => p x) {y₁ : α} {y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := unique_of_exists_unique h py₁ py₂ @[simp] theorem exists_unique_iff_exists {α : Sort u_1} [subsingleton α] {p : α → Prop} : (exists_unique fun (x : α) => p x) ↔ ∃ (x : α), p x := { mp := fun (h : exists_unique fun (x : α) => p x) => exists_unique.exists h, mpr := Exists.imp fun (x : α) (hx : p x) => { left := hx, right := fun (y : α) (_x : p y) => subsingleton.elim y x } } theorem exists_unique.elim2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} {b : Prop} (h₂ : exists_unique fun (x : α) => exists_unique fun (h : p x) => q x h) (h₁ : ∀ (x : α) (h : p x), q x h → (∀ (y : α) (hy : p y), q y hy → y = x) → b) : b := sorry theorem exists_unique.intro2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} (w : α) (hp : p w) (hq : q w hp) (H : ∀ (y : α) (hy : p y), q y hy → y = w) : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx := sorry theorem exists_unique.exists2 {α : Sort u_1} {p : α → Sort u_2} {q : (x : α) → p x → Prop} (h : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx) : ∃ (x : α), ∃ (hx : p x), q x hx := Exists.imp (fun (x : α) (hx : exists_unique fun (hx : p x) => q x hx) => exists_unique.exists hx) (exists_unique.exists h) theorem exists_unique.unique2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} (h : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx) {y₁ : α} {y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ := sorry /-! ### Classical lemmas -/ namespace classical theorem cases {p : Prop → Prop} (h1 : p True) (h2 : p False) (a : Prop) : p a := cases_on a h1 h2 /- use shortened names to avoid conflict when classical namespace is open. -/ theorem dec (p : Prop) : Decidable p := prop_decidable p theorem dec_pred {α : Sort u_1} (p : α → Prop) : decidable_pred p := fun (a : α) => prop_decidable (p a) theorem dec_rel {α : Sort u_1} (p : α → α → Prop) : DecidableRel p := fun (a b : α) => prop_decidable (p a b) theorem dec_eq (α : Sort u_1) : DecidableEq α := fun (a b : α) => prop_decidable (a = b) /-- We make decidability results that depends on `classical.choice` noncomputable lemmas. * We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode for them, and fail because it depends on `classical.choice`. * We make them lemmas, and not definitions, because otherwise later definitions will raise \"failed to generate bytecode\" errors when writing something like `letI := classical.dec_eq _`. Cf. <https://leanprover-community.github.io/archive/113488general/08268noncomputabletheorem.html> -/ /-- Construct a function from a default value `H0`, and a function to use if there exists a value satisfying the predicate. -/ def exists_cases {α : Sort u_1} {p : α → Prop} {C : Sort u} (H0 : C) (H : (a : α) → p a → C) : C := dite (∃ (a : α), p a) (fun (h : ∃ (a : α), p a) => H (some h) sorry) fun (h : ¬∃ (a : α), p a) => H0 theorem some_spec2 {α : Sort u_1} {p : α → Prop} {h : ∃ (a : α), p a} (q : α → Prop) (hpq : ∀ (a : α), p a → q a) : q (some h) := hpq (some h) (some_spec h) /-- A version of classical.indefinite_description which is definitionally equal to a pair -/ def subtype_of_exists {α : Type u_1} {P : α → Prop} (h : ∃ (x : α), P x) : Subtype fun (x : α) => P x := { val := some h, property := sorry } end classical /-- This function has the same type as `exists.rec_on`, and can be used to case on an equality, but `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe using the axiom of choice. -/ def exists.classical_rec_on {α : Sort u_1} {p : α → Prop} (h : ∃ (a : α), p a) {C : Sort u} (H : (a : α) → p a → C) : C := H (classical.some h) sorry /-! ### Declarations about bounded quantifiers -/ theorem bex_def {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (h : p x), q x) ↔ ∃ (x : α), p x ∧ q x := sorry theorem bex.elim {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {b : Prop} : (∃ (x : α), ∃ (h : p x), P x h) → (∀ (a : α) (h : p a), P a h → b) → b := sorry theorem bex.intro {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ (x : α), ∃ (h : p x), P x h := Exists.intro a (Exists.intro h₁ h₂) theorem ball_congr {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h ↔ Q x h) : (∀ (x : α) (h : p x), P x h) ↔ ∀ (x : α) (h : p x), Q x h := forall_congr fun (x : α) => forall_congr (H x) theorem bex_congr {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h ↔ Q x h) : (∃ (x : α), ∃ (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), Q x h := exists_congr fun (x : α) => exists_congr (H x) theorem bex_eq_left {α : Sort u_1} {p : α → Prop} {a : α} : (∃ (x : α), ∃ (_x : x = a), p x) ↔ p a := sorry theorem ball.imp_right {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h → Q x h) (h₁ : ∀ (x : α) (h : p x), P x h) (x : α) (h : p x) : Q x h := H x h (h₁ x h) theorem bex.imp_right {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h → Q x h) : (∃ (x : α), ∃ (h : p x), P x h) → ∃ (x : α), ∃ (h : p x), Q x h := sorry theorem ball.imp_left {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x → q x) (h₁ : ∀ (x : α), q x → r x) (x : α) (h : p x) : r x := h₁ x (H x h) theorem bex.imp_left {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x → q x) : (∃ (x : α), ∃ (_x : p x), r x) → ∃ (x : α), ∃ (_x : q x), r x := sorry theorem ball_of_forall {α : Sort u_1} {p : α → Prop} (h : ∀ (x : α), p x) (x : α) : p x := h x theorem forall_of_ball {α : Sort u_1} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x) (h : ∀ (x : α), p x → q x) (x : α) : q x := h x (H x) theorem bex_of_exists {α : Sort u_1} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x) : (∃ (x : α), q x) → ∃ (x : α), ∃ (_x : p x), q x := fun (ᾰ : ∃ (x : α), q x) => Exists.dcases_on ᾰ fun (ᾰ_w : α) (ᾰ_h : q ᾰ_w) => idRhs (∃ (x : α), ∃ (_x : p x), q x) (Exists.intro ᾰ_w (Exists.intro (H ᾰ_w) ᾰ_h)) theorem exists_of_bex {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (_x : p x), q x) → ∃ (x : α), q x := sorry @[simp] theorem bex_imp_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {b : Prop} : (∃ (x : α), ∃ (h : p x), P x h) → b ↔ ∀ (x : α) (h : p x), P x h → b := sorry theorem not_bex {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∃ (x : α), ∃ (h : p x), P x h) ↔ ∀ (x : α) (h : p x), ¬P x h := bex_imp_distrib theorem not_ball_of_bex_not {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (∃ (x : α), ∃ (h : p x), ¬P x h) → ¬∀ (x : α) (h : p x), P x h := sorry -- See Note [decidable namespace] protected theorem decidable.not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} [Decidable (∃ (x : α), ∃ (h : p x), ¬P x h)] [(x : α) → (h : p x) → Decidable (P x h)] : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h := sorry theorem not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h := decidable.not_ball theorem ball_true_iff {α : Sort u_1} (p : α → Prop) : (∀ (x : α), p x → True) ↔ True := iff_true_intro fun (h : α) (hrx : p h) => trivial theorem ball_and_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} : (∀ (x : α) (h : p x), P x h ∧ Q x h) ↔ (∀ (x : α) (h : p x), P x h) ∧ ∀ (x : α) (h : p x), Q x h := iff.trans (forall_congr fun (x : α) => forall_and_distrib) forall_and_distrib theorem bex_or_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} : (∃ (x : α), ∃ (h : p x), P x h ∨ Q x h) ↔ (∃ (x : α), ∃ (h : p x), P x h) ∨ ∃ (x : α), ∃ (h : p x), Q x h := iff.trans (exists_congr fun (x : α) => exists_or_distrib) exists_or_distrib theorem ball_or_left_distrib {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} : (∀ (x : α), p x ∨ q x → r x) ↔ (∀ (x : α), p x → r x) ∧ ∀ (x : α), q x → r x := iff.trans (forall_congr fun (x : α) => or_imp_distrib) forall_and_distrib theorem bex_or_left_distrib {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (_x : p x ∨ q x), r x) ↔ (∃ (x : α), ∃ (_x : p x), r x) ∨ ∃ (x : α), ∃ (_x : q x), r x := sorry namespace classical theorem not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h := not_ball end classical theorem ite_eq_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} {c : α} : ite p a b = c ↔ p ∧ a = c ∨ ¬p ∧ b = c := sorry @[simp] theorem ite_eq_left_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} : ite p a b = a ↔ ¬p → b = a := sorry @[simp] theorem ite_eq_right_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} : ite p a b = b ↔ p → a = b := sorry /-! ### Declarations about `nonempty` -/ protected instance has_zero.nonempty {α : Type u} [HasZero α] : Nonempty α := Nonempty.intro 0 protected instance has_one.nonempty {α : Type u} [HasOne α] : Nonempty α := Nonempty.intro 1 theorem exists_true_iff_nonempty {α : Sort u_1} : (∃ (a : α), True) ↔ Nonempty α := sorry @[simp] theorem nonempty_Prop {p : Prop} : Nonempty p ↔ p := { mp := fun (_x : Nonempty p) => (fun (_a : Nonempty p) => nonempty.dcases_on _a fun (val : p) => idRhs p val) _x, mpr := fun (h : p) => Nonempty.intro h } theorem not_nonempty_iff_imp_false {α : Type u} : ¬Nonempty α ↔ α → False := sorry @[simp] theorem nonempty_sigma {α : Type u} {γ : α → Type w} : Nonempty (sigma fun (a : α) => γ a) ↔ ∃ (a : α), Nonempty (γ a) := sorry @[simp] theorem nonempty_subtype {α : Sort u} {p : α → Prop} : Nonempty (Subtype p) ↔ ∃ (a : α), p a := sorry @[simp] theorem nonempty_prod {α : Type u} {β : Type v} : Nonempty (α × β) ↔ Nonempty α ∧ Nonempty β := sorry @[simp] theorem nonempty_pprod {α : Sort u} {β : Sort v} : Nonempty (PProd α β) ↔ Nonempty α ∧ Nonempty β := sorry @[simp] theorem nonempty_sum {α : Type u} {β : Type v} : Nonempty (α ⊕ β) ↔ Nonempty α ∨ Nonempty β := sorry @[simp] theorem nonempty_psum {α : Sort u} {β : Sort v} : Nonempty (psum α β) ↔ Nonempty α ∨ Nonempty β := sorry @[simp] theorem nonempty_psigma {α : Sort u} {β : α → Sort v} : Nonempty (psigma β) ↔ ∃ (a : α), Nonempty (β a) := sorry @[simp] theorem nonempty_empty : ¬Nonempty empty := fun (_x : Nonempty empty) => (fun (_a : Nonempty empty) => nonempty.dcases_on _a fun (val : empty) => idRhs False (empty.elim val)) _x @[simp] theorem nonempty_ulift {α : Type u} : Nonempty (ulift α) ↔ Nonempty α := sorry @[simp] theorem nonempty_plift {α : Sort u} : Nonempty (plift α) ↔ Nonempty α := sorry @[simp] theorem nonempty.forall {α : Sort u} {p : Nonempty α → Prop} : (∀ (h : Nonempty α), p h) ↔ ∀ (a : α), p (Nonempty.intro a) := sorry @[simp] theorem nonempty.exists {α : Sort u} {p : Nonempty α → Prop} : (∃ (h : Nonempty α), p h) ↔ ∃ (a : α), p (Nonempty.intro a) := sorry theorem classical.nonempty_pi {α : Sort u} {β : α → Sort v} : Nonempty ((a : α) → β a) ↔ ∀ (a : α), Nonempty (β a) := sorry /-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued) `inhabited` instance. `classical.inhabited_of_nonempty` already exists, in `core/init/classical.lean`, but the assumption is not a type class argument, which makes it unsuitable for some applications. -/ def classical.inhabited_of_nonempty' {α : Sort u} [h : Nonempty α] : Inhabited α := { default := Classical.choice h } /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ protected def nonempty.some {α : Sort u} (h : Nonempty α) : α := Classical.choice h /-- Using `classical.choice`, extracts a term from a `nonempty` type. -/ protected def classical.arbitrary (α : Sort u) [h : Nonempty α] : α := Classical.choice h /-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty. `nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/ theorem nonempty.map {α : Sort u} {β : Sort v} (f : α → β) : Nonempty α → Nonempty β := fun (ᾰ : Nonempty α) => nonempty.dcases_on ᾰ fun (ᾰ : α) => idRhs (Nonempty β) (Nonempty.intro (f ᾰ)) protected theorem nonempty.map2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) : Nonempty α → Nonempty β → Nonempty γ := fun (ᾰ : Nonempty α) (ᾰ_1 : Nonempty β) => nonempty.dcases_on ᾰ fun (ᾰ_1_1 : α) => nonempty.dcases_on ᾰ_1 fun (ᾰ : β) => idRhs (Nonempty γ) (Nonempty.intro (f ᾰ_1_1 ᾰ)) protected theorem nonempty.congr {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) : Nonempty α ↔ Nonempty β := { mp := nonempty.map f, mpr := nonempty.map g } theorem nonempty.elim_to_inhabited {α : Sort u_1} [h : Nonempty α] {p : Prop} (f : Inhabited α → p) : p := nonempty.elim h (f ∘ Inhabited.mk) protected instance prod.nonempty {α : Type u_1} {β : Type u_2} [h : Nonempty α] [h2 : Nonempty β] : Nonempty (α × β) := nonempty.elim h fun (g : α) => nonempty.elim h2 fun (g2 : β) => Nonempty.intro (g, g2) /-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/ theorem apply_dite {α : Sort u_1} {β : Sort u_2} (f : α → β) (P : Prop) [Decidable P] (x : P → α) (y : ¬P → α) : f (dite P x y) = dite P (fun (h : P) => f (x h)) fun (h : ¬P) => f (y h) := sorry /-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/ theorem apply_ite {α : Sort u_1} {β : Sort u_2} (f : α → β) (P : Prop) [Decidable P] (x : α) (y : α) : f (ite P x y) = ite P (f x) (f y) := apply_dite f P (fun (_x : P) => x) fun (_x : ¬P) => y /-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function applied to each of the branches. -/ theorem apply_dite2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) (P : Prop) [Decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) : f (dite P a b) (dite P c d) = dite P (fun (h : P) => f (a h) (c h)) fun (h : ¬P) => f (b h) (d h) := sorry /-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function applied to each of the branches. -/ theorem apply_ite2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) (P : Prop) [Decidable P] (a : α) (b : α) (c : β) (d : β) : f (ite P a b) (ite P c d) = ite P (f a c) (f b d) := apply_dite2 f P (fun (_x : P) => a) (fun (_x : ¬P) => b) (fun (_x : P) => c) fun (_x : ¬P) => d /-- A 'dite' producing a `Pi` type `Π a, β a`, applied to a value `x : α` is a `dite` that applies either branch to `x`. -/ theorem dite_apply {α : Sort u_1} {β : α → Sort u_2} (P : Prop) [Decidable P] (f : P → (a : α) → β a) (g : ¬P → (a : α) → β a) (x : α) : dite P f g x = dite P (fun (h : P) => f h x) fun (h : ¬P) => g h x := sorry /-- A 'ite' producing a `Pi` type `Π a, β a`, applied to a value `x : α` is a `ite` that applies either branch to `x` -/ theorem ite_apply {α : Sort u_1} {β : α → Sort u_2} (P : Prop) [Decidable P] (f : (a : α) → β a) (g : (a : α) → β a) (x : α) : ite P f g x = ite P (f x) (g x) := dite_apply P (fun (_x : P) => f) (fun (_x : ¬P) => g) x /-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/ @[simp] theorem dite_not {α : Sort u_1} (P : Prop) [Decidable P] (x : ¬P → α) (y : ¬¬P → α) : dite (¬P) x y = dite P (fun (h : P) => y (not_not_intro h)) x := sorry /-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/ @[simp] theorem ite_not {α : Sort u_1} (P : Prop) [Decidable P] (x : α) (y : α) : ite (¬P) x y = ite P y x := dite_not P (fun (_x : ¬P) => x) fun (_x : ¬¬P) => y theorem ite_and {α : Sort u_1} {p : Prop} {q : Prop} [Decidable p] [Decidable q] {x : α} {y : α} : ite (p ∧ q) x y = ite p (ite q x y) y := sorry end Mathlib
641a52e7d26d752b47e0220af2377b4df127edf4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/free_abelian_group.lean
d9e4dbc8d640544d158a67df180963d1453497ad
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
19,519
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.group.pi import group_theory.free_group import group_theory.abelianization import algebra.module.basic /-! # Free abelian groups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The free abelian group on a type `α`, defined as the abelianisation of the free group on `α`. The free abelian group on `α` can be abstractly defined as the left adjoint of the forgetful functor from abelian groups to types. Alternatively, one could define it as the functions `α → ℤ` which send all but finitely many `(a : α)` to `0`, under pointwise addition. In this file, it is defined as the abelianisation of the free group on `α`. All the constructions and theorems required to show the adjointness of the construction and the forgetful functor are proved in this file, but the category-theoretic adjunction statement is in `algebra.category.Group.adjunctions` . ## Main definitions Here we use the following variables: `(α β : Type*) (A : Type*) [add_comm_group A]` * `free_abelian_group α` : the free abelian group on a type `α`. As an abelian group it is `α →₀ ℤ`, the functions from `α` to `ℤ` such that all but finitely many elements get mapped to zero, however this is not how it is implemented. * `lift f : free_abelian_group α →+ A` : the group homomorphism induced by the map `f : α → A`. * `map (f : α → β) : free_abelian_group α →+ free_abelian_group β` : functoriality of `free_abelian_group` * `instance [monoid α] : semigroup (free_abelian_group α)` * `instance [comm_monoid α] : comm_ring (free_abelian_group α)` It has been suggested that we would be better off refactoring this file and using `finsupp` instead. ## Implementation issues The definition is `def free_abelian_group : Type u := additive $ abelianization $ free_group α` Chris Hughes has suggested that this all be rewritten in terms of `finsupp`. Johan Commelin has written all the API relating the definition to `finsupp` in the lean-liquid repo. The lemmas `map_pure`, `map_of`, `map_zero`, `map_add`, `map_neg` and `map_sub` are proved about the `functor.map` `<$>` construction, and need `α` and `β` to be in the same universe. But `free_abelian_group.map (f : α → β)` is defined to be the `add_group` homomorphism `free_abelian_group α →+ free_abelian_group β` (with `α` and `β` now allowed to be in different universes), so `(map f).map_add` etc can be used to prove that `free_abelian_group.map` preserves addition. The functions `map_id`, `map_id_apply`, `map_comp`, `map_comp_apply` and `map_of_apply` are about `free_abelian_group.map`. -/ universes u v variables (α : Type u) /-- The free abelian group on a type. -/ def free_abelian_group : Type u := additive $ abelianization $ free_group α instance : add_comm_group (free_abelian_group α) := @additive.add_comm_group _ $ abelianization.comm_group _ instance : inhabited (free_abelian_group α) := ⟨0⟩ variable {α} namespace free_abelian_group /-- The canonical map from α to `free_abelian_group α` -/ def of (x : α) : free_abelian_group α := abelianization.of $ free_group.of x /-- The map `free_abelian_group α →+ A` induced by a map of types `α → A`. -/ def lift {β : Type v} [add_comm_group β] : (α → β) ≃ (free_abelian_group α →+ β) := (@free_group.lift _ (multiplicative β) _).trans $ (@abelianization.lift _ _ (multiplicative β) _).trans monoid_hom.to_additive namespace lift variables {β : Type v} [add_comm_group β] (f : α → β) open free_abelian_group @[simp] protected lemma of (x : α) : lift f (of x) = f x := begin convert @abelianization.lift.of (free_group α) _ (multiplicative β) _ _ _, convert free_group.lift.of.symm end protected theorem unique (g : free_abelian_group α →+ β) (hg : ∀ x, g (of x) = f x) {x} : g x = lift f x := add_monoid_hom.congr_fun ((lift.symm_apply_eq).mp (funext hg : g ∘ of = f)) _ /-- See note [partially-applied ext lemmas]. -/ @[ext] protected theorem ext (g h : free_abelian_group α →+ β) (H : ∀ x, g (of x) = h (of x)) : g = h := lift.symm.injective $ funext H lemma map_hom {α β γ} [add_comm_group β] [add_comm_group γ] (a : free_abelian_group α) (f : α → β) (g : β →+ γ) : g (lift f a) = lift (g ∘ f) a := begin suffices : (g.comp (lift f)) a = lift (g ∘ f) a, exact this, apply @lift.unique, assume a, show g ((lift f) (of a)) = g (f a), simp only [(∘), lift.of], end end lift section open_locale classical lemma of_injective : function.injective (of : α → free_abelian_group α) := λ x y hoxy, classical.by_contradiction $ assume hxy : x ≠ y, let f : free_abelian_group α →+ ℤ := lift (λ z, if x = z then (1 : ℤ) else 0) in have hfx1 : f (of x) = 1, from (lift.of _ _).trans $ if_pos rfl, have hfy1 : f (of y) = 1, from hoxy ▸ hfx1, have hfy0 : f (of y) = 0, from (lift.of _ _).trans $ if_neg hxy, one_ne_zero $ hfy1.symm.trans hfy0 end local attribute [instance] quotient_group.left_rel @[elab_as_eliminator] protected theorem induction_on {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ of x) (Cn : ∀ x, C (of x) → C (-of x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := quotient.induction_on' z $ λ x, quot.induction_on x $ λ L, list.rec_on L C0 $ λ ⟨x, b⟩ tl ih, bool.rec_on b (Cp _ _ (Cn _ (C1 x)) ih) (Cp _ _ (C1 x) ih) theorem lift.add' {α β} [add_comm_group β] (a : free_abelian_group α) (f g : α → β) : lift (f + g) a = lift f a + lift g a := begin refine free_abelian_group.induction_on a _ _ _ _, { simp only [(lift _).map_zero, zero_add] }, { assume x, simp only [lift.of, pi.add_apply] }, { assume x h, simp only [map_neg, lift.of, pi.add_apply, neg_add] }, { assume x y hx hy, simp only [(lift _).map_add, hx, hy, add_add_add_comm] } end /-- If `g : free_abelian_group X` and `A` is an abelian group then `lift_add_group_hom g` is the additive group homomorphism sending a function `X → A` to the term of type `A` corresponding to the evaluation of the induced map `free_abelian_group X → A` at `g`. -/ @[simps] def lift_add_group_hom {α} (β) [add_comm_group β] (a : free_abelian_group α) : (α → β) →+ β := add_monoid_hom.mk' (λ f, lift f a) (lift.add' a) lemma lift_neg' {β} [add_comm_group β] (f : α → β) : lift (-f) = -lift f := add_monoid_hom.ext $ λ _, (lift_add_group_hom _ _ : (α → β) →+ β).map_neg _ section monad variables {β : Type u} instance : monad free_abelian_group.{u} := { pure := λ α, of, bind := λ α β x f, lift f x } @[elab_as_eliminator] protected theorem induction_on' {C : free_abelian_group α → Prop} (z : free_abelian_group α) (C0 : C 0) (C1 : ∀ x, C $ pure x) (Cn : ∀ x, C (pure x) → C (-pure x)) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := free_abelian_group.induction_on z C0 C1 Cn Cp @[simp] lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_abelian_group α) = pure (f x) := rfl @[simp] protected lemma map_zero (f : α → β) : f <$> (0 : free_abelian_group α) = 0 := (lift (of ∘ f)).map_zero @[simp] protected lemma map_add (f : α → β) (x y : free_abelian_group α) : f <$> (x + y) = f <$> x + f <$> y := (lift _).map_add _ _ @[simp] protected lemma map_neg (f : α → β) (x : free_abelian_group α) : f <$> (-x) = -(f <$> x) := map_neg (lift $ of ∘ f) _ @[simp] protected lemma map_sub (f : α → β) (x y : free_abelian_group α) : f <$> (x - y) = f <$> x - f <$> y := map_sub (lift $ of ∘ f) _ _ @[simp] lemma map_of (f : α → β) (y : α) : f <$> of y = of (f y) := rfl @[simp] lemma pure_bind (f : α → free_abelian_group β) (x) : pure x >>= f = f x := lift.of _ _ @[simp] lemma zero_bind (f : α → free_abelian_group β) : 0 >>= f = 0 := (lift f).map_zero @[simp] lemma add_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x + y >>= f = (x >>= f) + (y >>= f) := (lift _).map_add _ _ @[simp] lemma neg_bind (f : α → free_abelian_group β) (x : free_abelian_group α) : -x >>= f = -(x >>= f) := map_neg (lift f) _ @[simp] lemma sub_bind (f : α → free_abelian_group β) (x y : free_abelian_group α) : x - y >>= f = (x >>= f) - (y >>= f) := map_sub (lift f) _ _ @[simp] lemma pure_seq (f : α → β) (x : free_abelian_group α) : pure f <*> x = f <$> x := pure_bind _ _ @[simp] lemma zero_seq (x : free_abelian_group α) : (0 : free_abelian_group (α → β)) <*> x = 0 := zero_bind _ @[simp] lemma add_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f + g <*> x = (f <*> x) + (g <*> x) := add_bind _ _ _ @[simp] lemma neg_seq (f : free_abelian_group (α → β)) (x : free_abelian_group α) : -f <*> x = -(f <*> x) := neg_bind _ _ @[simp] lemma sub_seq (f g : free_abelian_group (α → β)) (x : free_abelian_group α) : f - g <*> x = (f <*> x) - (g <*> x) := sub_bind _ _ _ /-- If `f : free_abelian_group (α → β)`, then `f <*>` is an additive morphism `free_abelian_group α →+ free_abelian_group β`. -/ def seq_add_group_hom (f : free_abelian_group (α → β)) : free_abelian_group α →+ free_abelian_group β := add_monoid_hom.mk' ((<*>) f) (λ x y, show lift (<$> (x+y)) _ = _, by { simp only [free_abelian_group.map_add], exact lift.add' f _ _, }) @[simp] lemma seq_zero (f : free_abelian_group (α → β)) : f <*> 0 = 0 := (seq_add_group_hom f).map_zero @[simp] lemma seq_add (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x + y) = (f <*> x) + (f <*> y) := (seq_add_group_hom f).map_add x y @[simp] lemma seq_neg (f : free_abelian_group (α → β)) (x : free_abelian_group α) : f <*> (-x) = -(f <*> x) := (seq_add_group_hom f).map_neg x @[simp] lemma seq_sub (f : free_abelian_group (α → β)) (x y : free_abelian_group α) : f <*> (x - y) = (f <*> x) - (f <*> y) := (seq_add_group_hom f).map_sub x y instance : is_lawful_monad free_abelian_group.{u} := { id_map := λ α x, free_abelian_group.induction_on' x (free_abelian_group.map_zero id) (map_pure id) (λ x ih, by rw [free_abelian_group.map_neg, ih]) (λ x y ihx ihy, by rw [free_abelian_group.map_add, ihx, ihy]), pure_bind := λ α β x f, pure_bind f x, bind_assoc := λ α β γ x f g, free_abelian_group.induction_on' x (by iterate 3 { rw zero_bind }) (λ x, by iterate 2 { rw pure_bind }) (λ x ih, by iterate 3 { rw neg_bind }; rw ih) (λ x y ihx ihy, by iterate 3 { rw add_bind }; rw [ihx, ihy]) } instance : is_comm_applicative free_abelian_group.{u} := { commutative_prod := λ α β x y, free_abelian_group.induction_on' x (by rw [free_abelian_group.map_zero, zero_seq, seq_zero]) (λ p, by rw [map_pure, pure_seq]; exact free_abelian_group.induction_on' y (by rw [free_abelian_group.map_zero, free_abelian_group.map_zero, zero_seq]) (λ q, by rw [map_pure, map_pure, pure_seq, map_pure]) (λ q ih, by rw [free_abelian_group.map_neg, free_abelian_group.map_neg, neg_seq, ih]) (λ y₁ y₂ ih1 ih2, by rw [free_abelian_group.map_add, free_abelian_group.map_add, add_seq, ih1, ih2])) (λ p ih, by rw [free_abelian_group.map_neg, neg_seq, seq_neg, ih]) (λ x₁ x₂ ih1 ih2, by rw [free_abelian_group.map_add, add_seq, seq_add, ih1, ih2]) } end monad universe w variables {β : Type v} {γ : Type w} /-- The additive group homomorphism `free_abelian_group α →+ free_abelian_group β` induced from a map `α → β` -/ def map (f : α → β) : free_abelian_group α →+ free_abelian_group β := lift (of ∘ f) lemma lift_comp {α} {β} {γ} [add_comm_group γ] (f : α → β) (g : β → γ) (x : free_abelian_group α) : lift (g ∘ f) x = lift g (map f x) := begin apply free_abelian_group.induction_on x, { exact add_monoid_hom.map_zero _ }, { intro y, refl }, { intros x h, simp only [h, add_monoid_hom.map_neg] }, { intros x y h₁ h₂, simp only [h₁, h₂, add_monoid_hom.map_add] } end lemma map_id : map id = add_monoid_hom.id (free_abelian_group α) := eq.symm $ lift.ext _ _ $ λ x, lift.unique of (add_monoid_hom.id _) $ λ y, add_monoid_hom.id_apply _ _ lemma map_id_apply (x : free_abelian_group α) : map id x = x := by {rw map_id, refl } lemma map_comp {f : α → β} {g : β → γ} : map (g ∘ f) = (map g).comp (map f) := eq.symm $ lift.ext _ _ $ λ x, eq.symm $ lift_comp _ _ _ lemma map_comp_apply {f : α → β} {g : β → γ} (x : free_abelian_group α) : map (g ∘ f) x = (map g) ((map f) x) := by { rw map_comp, refl } -- version of map_of which uses `map` @[simp] lemma map_of_apply {f : α → β} (a : α) : map f (of a) = of (f a) := rfl variable (α) section has_mul variables [has_mul α] instance : has_mul (free_abelian_group α) := ⟨λ x, lift $ λ x₂, lift (λ x₁, of $ x₁ * x₂) x⟩ variable {α} lemma mul_def (x y : free_abelian_group α) : x * y = lift (λ x₂, lift (λ x₁, of (x₁ * x₂)) x) y := rfl @[simp] lemma of_mul_of (x y : α) : of x * of y = of (x * y) := rfl lemma of_mul (x y : α) : of (x * y) = of x * of y := rfl instance : distrib (free_abelian_group α) := { add := (+), left_distrib := λ x y z, (lift _).map_add _ _, right_distrib := λ x y z, by simp only [(*), map_add, ←pi.add_def, lift.add'], ..free_abelian_group.has_mul _ } instance : non_unital_non_assoc_ring (free_abelian_group α) := { zero_mul := λ a, by { have h : 0 * a + 0 * a = 0 * a, by simp [←add_mul], simpa using h }, mul_zero := λ a, rfl, ..free_abelian_group.distrib, ..free_abelian_group.add_comm_group _ } end has_mul instance [has_one α] : has_one (free_abelian_group α) := ⟨of 1⟩ instance [semigroup α] : non_unital_ring (free_abelian_group α) := { mul := (*), mul_assoc := λ x y z, begin refine free_abelian_group.induction_on z (by simp) (λ L3, _) (λ L3 ih, _) (λ z₁ z₂ ih₁ ih₂, _), { refine free_abelian_group.induction_on y (by simp) (λ L2, _) (λ L2 ih, _) (λ y₁ y₂ ih₁ ih₂, _), { refine free_abelian_group.induction_on x (by simp) (λ L1, _) (λ L1 ih, _) (λ x₁ x₂ ih₁ ih₂, _), { rw [of_mul_of, of_mul_of, of_mul_of, of_mul_of, mul_assoc] }, { rw [neg_mul, neg_mul, neg_mul, ih] }, { rw [add_mul, add_mul, add_mul, ih₁, ih₂] } }, { rw [neg_mul, mul_neg, mul_neg, neg_mul, ih] }, { rw [add_mul, mul_add, mul_add, add_mul, ih₁, ih₂] } }, { rw [mul_neg, mul_neg, mul_neg, ih] }, { rw [mul_add, mul_add, mul_add, ih₁, ih₂] } end, .. free_abelian_group.non_unital_non_assoc_ring } section monoid variables {R : Type*} [monoid α] [ring R] instance : ring (free_abelian_group α) := { mul := (*), mul_one := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, rw lift.of, refine free_abelian_group.induction_on x rfl (λ L, _) (λ L ih, _) (λ x1 x2 ih1 ih2, _), { erw [lift.of], congr' 1, exact mul_one L }, { rw [map_neg, ih] }, { rw [map_add, ih1, ih2] } end, one_mul := λ x, begin unfold has_mul.mul semigroup.mul has_one.one, refine free_abelian_group.induction_on x rfl _ _ _, { intros L, rw [lift.of, lift.of], congr' 1, exact one_mul L }, { intros L ih, rw [map_neg, ih] }, { intros x1 x2 ih1 ih2, rw [map_add, ih1, ih2] } end, .. free_abelian_group.non_unital_ring _, ..free_abelian_group.has_one _ } variable {α} /-- `free_abelian_group.of` is a `monoid_hom` when `α` is a `monoid`. -/ def of_mul_hom : α →* free_abelian_group α := { to_fun := of, map_one' := rfl, map_mul' := of_mul } @[simp] lemma of_mul_hom_coe : (of_mul_hom : α → free_abelian_group α) = of := rfl /-- If `f` preserves multiplication, then so does `lift f`. -/ def lift_monoid : (α →* R) ≃ (free_abelian_group α →+* R) := { to_fun := λ f, { to_fun := lift f, map_one' := (lift.of f _).trans f.map_one, map_mul' := λ x y, begin refine free_abelian_group.induction_on y (mul_zero _).symm (λ L2, _) (λ L2 ih, _) _, { refine free_abelian_group.induction_on x (zero_mul _).symm (λ L1, _) (λ L1 ih, _) _, { simp_rw [of_mul_of, lift.of], exact f.map_mul _ _ }, { simp_rw [neg_mul, map_neg, neg_mul], exact congr_arg has_neg.neg ih }, { intros x1 x2 ih1 ih2, simp only [add_mul, map_add, ih1, ih2] } }, { rw [mul_neg, map_neg, map_neg, mul_neg, ih] }, { intros y1 y2 ih1 ih2, rw [mul_add, map_add, map_add, mul_add, ih1, ih2] }, end, .. lift f }, inv_fun := λ F, monoid_hom.comp ↑F of_mul_hom, left_inv := λ f, monoid_hom.ext $ lift.of _, right_inv := λ F, ring_hom.coe_add_monoid_hom_injective $ lift.apply_symm_apply (↑F : free_abelian_group α →+ R) } @[simp] lemma lift_monoid_coe_add_monoid_hom (f : α →* R) : ↑(lift_monoid f) = lift f := rfl @[simp] lemma lift_monoid_coe (f : α →* R) : ⇑(lift_monoid f) = lift f := rfl @[simp] lemma lift_monoid_symm_coe (f : free_abelian_group α →+* R) : ⇑(lift_monoid.symm f) = lift.symm ↑f := rfl lemma one_def : (1 : free_abelian_group α) = of 1 := rfl lemma of_one : (of 1 : free_abelian_group α) = 1 := rfl end monoid instance [comm_monoid α] : comm_ring (free_abelian_group α) := { mul_comm := λ x y, begin refine free_abelian_group.induction_on x (zero_mul y) _ _ _, { intros s, refine free_abelian_group.induction_on y (zero_mul _).symm _ _ _, { intros t, unfold has_mul.mul semigroup.mul ring.mul, iterate 4 { rw lift.of }, congr' 1, exact mul_comm _ _ }, { intros t ih, rw [mul_neg, ih, neg_mul_eq_neg_mul] }, { intros y1 y2 ih1 ih2, rw [mul_add, add_mul, ih1, ih2] } }, { intros s ih, rw [neg_mul, ih, neg_mul_eq_mul_neg] }, { intros x1 x2 ih1 ih2, rw [add_mul, mul_add, ih1, ih2] } end, .. free_abelian_group.ring α } instance pempty_unique : unique (free_abelian_group pempty) := { default := 0, uniq := λ x, free_abelian_group.induction_on x rfl (λ x, pempty.elim x) (λ x, pempty.elim x) (by { rintros - - rfl rfl, simp }) } /-- The free abelian group on a type with one term is isomorphic to `ℤ`. -/ def punit_equiv (T : Type*) [unique T] : free_abelian_group T ≃+ ℤ := { to_fun := free_abelian_group.lift (λ _, (1 : ℤ)), inv_fun := λ n, n • of (inhabited.default), left_inv := λ z, free_abelian_group.induction_on z (by simp only [zero_smul, add_monoid_hom.map_zero]) (unique.forall_iff.2 $ by simp only [one_smul, lift.of]) (unique.forall_iff.2 $ by simp) (λ x y hx hy, by { simp only [add_monoid_hom.map_add, add_smul] at *, rw [hx, hy]}), right_inv := λ n, begin rw [add_monoid_hom.map_zsmul, lift.of], exact zsmul_int_one n end, map_add' := add_monoid_hom.map_add _ } /-- Isomorphic types have isomorphic free abelian groups. -/ def equiv_of_equiv {α β : Type*} (f : α ≃ β) : free_abelian_group α ≃+ free_abelian_group β := { to_fun := map f, inv_fun := map f.symm, left_inv := begin intros x, rw [← map_comp_apply, equiv.symm_comp_self, map_id], refl, end, right_inv := begin intros x, rw [← map_comp_apply, equiv.self_comp_symm, map_id], refl, end, map_add' := add_monoid_hom.map_add _ } end free_abelian_group
7064fc82209c52a9f0c1bc7535b7a09428b7f3f0
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch5/ex0701.lean
84c1ac2a7cbeb938d91ca16d3b4064248028881e
[]
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
215
lean
variables (x y z : ℕ) (p : ℕ → Prop) variable (h : p (x * y)) example : (x + 0) * (0 + y * 1 + z * 0) = x * y := by simp include h example : p ((x + 0) * (0 + y * 1 + z * 0)) := by { simp, assumption }
140e08c98d421dcc56093adb4abde235ac9cf5e1
69d4931b605e11ca61881fc4f66db50a0a875e39
/archive/100-theorems-list/9_area_of_a_circle.lean
c08ef02a6124c21a75d35f1ca7a2b427fa0edd7d
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
6,417
lean
/- Copyright (c) 2021 James Arthur, Benjamin Davidson, Andrew Souther. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: James Arthur, Benjamin Davidson, Andrew Souther -/ import measure_theory.interval_integral import analysis.special_functions.sqrt /-! # Freek № 9: The Area of a Circle In this file we show that the area of a disc with nonnegative radius `r` is `π * r^2`. The main tools our proof uses are `volume_region_between_eq_integral`, which allows us to represent the area of the disc as an integral, and `interval_integral.integral_eq_sub_of_has_deriv_at'_of_le`, the second fundamental theorem of calculus. We begin by defining `disc` in `ℝ × ℝ`, then show that `disc` can be represented as the `region_between` two functions. Though not necessary for the main proof, we nonetheless choose to include a proof of the measurability of the disc in order to convince the reader that the set whose volume we will be calculating is indeed measurable and our result is therefore meaningful. In the main proof, `area_disc`, we use `volume_region_between_eq_integral` followed by `interval_integral.integral_of_le` to reduce our goal to a single `interval_integral`: `∫ (x : ℝ) in -r..r, 2 * sqrt (r ^ 2 - x ^ 2) = π * r ^ 2`. After disposing of the trivial case `r = 0`, we show that `λ x, 2 * sqrt (r ^ 2 - x ^ 2)` is equal to the derivative of `λ x, r ^ 2 * arcsin (x / r) + x * sqrt (r ^ 2 - x ^ 2)` everywhere on `Ioo (-r) r` and that those two functions are continuous, then apply the second fundamental theorem of calculus with those facts. Some simple algebra then completes the proof. Note that we choose to define `disc` as a set of points in `ℝ ⨯ ℝ`. This is admittedly not ideal; it would be more natural to define `disc` as a `metric.ball` in `euclidean_space ℝ (fin 2)` (as well as to provide a more general proof in higher dimensions). However, our proof indirectly relies on a number of theorems (particularly `measure_theory.measure.prod_apply`) which do not yet exist for Euclidean space, thus forcing us to use this less-preferable definition. As `measure_theory.pi` continues to develop, it should eventually become possible to redefine `disc` and extend our proof to the n-ball. -/ open set real measure_theory interval_integral open_locale real nnreal /-- A disc of radius `r` is defined as the collection of points `(p.1, p.2)` in `ℝ × ℝ` such that `p.1 ^ 2 + p.2 ^ 2 < r ^ 2`. Note that this definition is not equivalent to `metric.ball (0 : ℝ × ℝ) r`. This was done intentionally because `dist` in `ℝ × ℝ` is defined as the uniform norm, making the `metric.ball` in `ℝ × ℝ` a square, not a disc. See the module docstring for an explanation of why we don't define the disc in Euclidean space. -/ def disc (r : ℝ) := {p : ℝ × ℝ | p.1 ^ 2 + p.2 ^ 2 < r ^ 2} variable (r : ℝ≥0) /-- A disc of radius `r` can be represented as the region between the two curves `λ x, - sqrt (r ^ 2 - x ^ 2)` and `λ x, sqrt (r ^ 2 - x ^ 2)`. -/ lemma disc_eq_region_between : disc r = region_between (λ x, -sqrt (r^2 - x^2)) (λ x, sqrt (r^2 - x^2)) (Ioc (-r) r) := begin ext p, simp only [disc, region_between, mem_set_of_eq, mem_Ioo, mem_Ioc, pi.neg_apply], split; intro h, { cases abs_lt_of_sq_lt_sq' (lt_of_add_lt_of_nonneg_left h (sq_nonneg p.2)) r.2, rw [add_comm, ← lt_sub_iff_add_lt] at h, exact ⟨⟨left, right.le⟩, sq_lt.mp h⟩ }, { rw [add_comm, ← lt_sub_iff_add_lt], exact sq_lt.mpr h.2 }, end /-- The disc is a `measurable_set`. -/ theorem measurable_set_disc : measurable_set (disc r) := by apply measurable_set_lt; apply continuous.measurable; continuity /-- The area of a disc with radius `r` is `π * r ^ 2`. -/ theorem area_disc : volume (disc r) = nnreal.pi * r ^ 2 := begin let f := λ x, sqrt (r ^ 2 - x ^ 2), let F := λ x, (r:ℝ) ^ 2 * arcsin (r⁻¹ * x) + x * sqrt (r ^ 2 - x ^ 2), have hf : continuous f := by continuity, suffices : ∫ x in -r..r, 2 * f x = nnreal.pi * r ^ 2, { have h : integrable_on f (Ioc (-r) r) := (hf.integrable_on_compact compact_Icc).mono_set Ioc_subset_Icc_self, calc volume (disc r) = volume (region_between (λ x, -f x) f (Ioc (-r) r)) : by rw disc_eq_region_between ... = ennreal.of_real (∫ x in Ioc (-r:ℝ) r, (f - has_neg.neg ∘ f) x) : volume_region_between_eq_integral h.neg h measurable_set_Ioc (λ x hx, neg_le_self (sqrt_nonneg _)) ... = ennreal.of_real (∫ x in (-r:ℝ)..r, 2 * f x) : by simp [two_mul, integral_of_le] ... = nnreal.pi * r ^ 2 : by rw_mod_cast [this, ← ennreal.coe_nnreal_eq], }, obtain ⟨hle, (heq | hlt)⟩ := ⟨nnreal.coe_nonneg r, hle.eq_or_lt⟩, { simp [← heq] }, have hderiv : ∀ x ∈ Ioo (-r:ℝ) r, has_deriv_at F (2 * f x) x, { rintros x ⟨hx1, hx2⟩, convert ((has_deriv_at_const x ((r:ℝ)^2)).mul ((has_deriv_at_arcsin _ _).comp x ((has_deriv_at_const x (r:ℝ)⁻¹).mul (has_deriv_at_id' x)))).add ((has_deriv_at_id' x).mul (((has_deriv_at_id' x).pow.const_sub ((r:ℝ)^2)).sqrt _)), { have h : sqrt (1 - x ^ 2 / r ^ 2) * r = sqrt (r ^ 2 - x ^ 2), { rw [← sqrt_sq hle, ← sqrt_mul, sub_mul, sqrt_sq hle, div_mul_eq_mul_div_comm, div_self (pow_ne_zero 2 hlt.ne'), one_mul, mul_one], simpa [sqrt_sq hle, div_le_one (pow_pos hlt 2)] using sq_le_sq' hx1.le hx2.le }, field_simp, rw [h, mul_left_comm, ← sq, neg_mul_eq_mul_neg, mul_div_mul_left (-x^2) _ two_ne_zero, add_left_comm, div_add_div_same, tactic.ring.add_neg_eq_sub, div_sqrt, two_mul] }, { suffices : -(1:ℝ) < r⁻¹ * x, by exact this.ne', calc -(1:ℝ) = r⁻¹ * -r : by simp [hlt.ne'] ... < r⁻¹ * x : by nlinarith [inv_pos.mpr hlt] }, { suffices : (r:ℝ)⁻¹ * x < 1, by exact this.ne, calc (r:ℝ)⁻¹ * x < r⁻¹ * r : by nlinarith [inv_pos.mpr hlt] ... = 1 : inv_mul_cancel hlt.ne' }, { nlinarith } }, have hcont := (by continuity : continuous F).continuous_on, have hcont' := (continuous_const.mul hf).continuous_on, calc ∫ x in -r..r, 2 * f x = F r - F (-r) : integral_eq_sub_of_has_deriv_at'_of_le (neg_le_self r.2) hcont hderiv hcont' ... = nnreal.pi * r ^ 2 : by norm_num [F, inv_mul_cancel hlt.ne', ← mul_div_assoc, mul_comm π], end
628b15d6fb455821a686f3e8a4ed994053cf4985
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Init/Prelude.lean
fd3bcb19d99f30c0fbdb28c6ea09fb97b4498c18
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
75,067
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 -/ prelude universe u v w @[inline] def id {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a set_option checkBinderAnnotations false in @[reducible] def inferInstance {α : Sort u} [i : α] : α := i set_option checkBinderAnnotations false in @[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a @[simp] abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have : (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b := fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary deriving instance Inhabited for Bool /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : [s : Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse h, _ => rfl theorem ofDecideEqTrue [s : Decidable p] : Eq (decide p) true → p := fun h => match (generalizing := false) s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse [s : Decidable p] : Eq (decide p) false → Not p := fun h => match (generalizing := false) s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class LE (α : Type u) where le : α → α → Prop class LT (α : Type u) where lt : α → α → Prop @[reducible] def GE.ge {α : Type u} [LE α] (a b : α) : Prop := LE.le b a @[reducible] def GT.gt {α : Type u} [LT α] (a b : α) : Prop := LT.lt b a @[inline] def max [LT α] [DecidableRel (@LT.lt α _)] (a b : α) : α := ite (LT.lt b a) a b @[inline] def min [LE α] [DecidableRel (@LE.le α _)] (a b : α) : α := ite (LE.le a b) a b class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → β → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → β → γ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAnd : α → β → γ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where hXor : α → β → γ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOr : α → β → γ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftLeft : α → β → γ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftRight : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) where pow : α → α → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → α → α class AndThen (α : Type u) where andThen : α → α → α class AndOp (α : Type u) where and : α → α → α class Xor (α : Type u) where xor : α → α → α class OrOp (α : Type u) where or : α → α → α class Complement (α : Type u) where complement : α → α class ShiftLeft (α : Type u) where shiftLeft : α → α → α class ShiftRight (α : Type u) where shiftRight : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α] : HPow α α α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[defaultInstance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[defaultInstance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[defaultInstance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[defaultInstance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[defaultInstance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) set_option bootstrap.genMatcherCode false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eqOfBeqEqTrue : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : Eq (beq n m) true := h have : Eq n m := eqOfBeqEqTrue this this ▸ rfl theorem Nat.neOfBeqEqFalse : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have : Eq (beq n m) false := h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFalse this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eqOfBeqEqTrue h) | false => isFalse (neOfBeqEqFalse h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := Eq (ble n m) true instance : LE Nat where le := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : LT Nat where lt := Nat.lt theorem Nat.notSuccLeZero : ∀ (n : Nat), LE.le (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.notLtZero (n : Nat) : Not (LT.lt n 0) := notSuccLeZero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LE.le n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (LT.lt n m) := decLe (succ n) m theorem Nat.zeroLe : (n : Nat) → LE.le 0 n | zero => rfl | succ n => rfl theorem Nat.succLeSucc {n m : Nat} (h : LE.le n m) : LE.le (succ n) (succ m) := h theorem Nat.zeroLtSucc (n : Nat) : LT.lt 0 (succ n) := succLeSucc (zeroLe n) theorem Nat.leStep : {n m : Nat} → LE.le n m → LE.le n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : LE.le n m := h have : LE.le n (succ m) := leStep this succLeSucc this protected theorem Nat.leTrans : {n m k : Nat} → LE.le n m → LE.le m k → LE.le n k | zero, m, k, h₁, h₂ => zeroLe _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LE.le n m := h₁ have h₂' : LE.le m k := h₂ show LE.le n k from Nat.leTrans h₁' h₂' protected theorem Nat.ltTrans {n m k : Nat} (h₁ : LT.lt n m) : LT.lt m k → LT.lt n k := Nat.leTrans (leStep h₁) theorem Nat.leSucc : (n : Nat) → LE.le n (succ n) | zero => rfl | succ n => leSucc n theorem Nat.leSuccOfLe {n m : Nat} (h : LE.le n m) : LE.le n (succ m) := Nat.leTrans h (leSucc m) protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LE.le n m → Or (Eq n m) (LT.lt n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zeroLe n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have : LE.le n m := h match Nat.eqOrLtOfLe this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succLeSucc h) protected def Nat.leRefl : (n : Nat) → LE.le n n | zero => rfl | succ n => Nat.leRefl n protected theorem Nat.ltOrGe (n m : Nat) : Or (LT.lt n m) (GE.ge n m) := match m with | zero => Or.inr (zeroLe n) | succ m => match Nat.ltOrGe n m with | Or.inl h => Or.inl (leSuccOfLe h) | Or.inr h => match Nat.eqOrLtOfLe h with | Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.leAntisymm : {n m : Nat} → LE.le n m → LE.le m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LE.le n m := h₁ have h₂' : LE.le m n := h₂ (Nat.leAntisymm h₁' h₂') ▸ rfl protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LE.le n m) (h₂ : Not (Eq n m)) : LT.lt n m := match Nat.ltOrGe n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂ set_option bootstrap.genMatcherCode false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub theorem Nat.predLePred : {n m : Nat} → LE.le n m → LE.le (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.leOfSuccLeSucc {n m : Nat} : LE.le (succ n) (succ m) → LE.le n m := predLePred theorem Nat.leOfLtSucc {m n : Nat} : LT.lt m (succ n) → LE.le m n := leOfSuccLeSucc @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : LT.lt val n theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (veqOfEq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eqOfVeq h) | isFalse h => isFalse (Fin.neOfVne h) instance {n} : LT (Fin n) where lt a b := LT.lt a.val b.val instance {n} : LE (Fin n) where le a b := LE.le a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (LT.lt a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LE.le a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : LT.lt n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : LT.lt n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : LT.lt n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : LT UInt32 where lt a b := LT.lt a.val b.val instance : LE UInt32 where le a b := LE.le a.val b.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (LT.lt a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LT.lt n m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (LE.le a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LE.le n m)) instance (a b : UInt32) : Decidable (LT.lt a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LE.le a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : LT.lt n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) def USize.size : Nat := hPow 2 System.Platform.numBits theorem usizeSzEq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBitsEq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : LT.lt n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usizeSzEq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : LT.lt n 4294967296) : USize := { val := { val := n isLt := match USize.size, usizeSzEq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.ltTrans h (by decide) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (LT.lt n 0xd800) (And (LT.lt 0xdfff n) (LT.lt n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : LT.lt n UInt32.size := match h with | Or.inl h => Nat.ltTrans h (by decide) | Or.inr ⟨_, h⟩ => Nat.ltTrans h (by decide) @[extern "lean_uint32_of_nat"] private def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (veqOfEq h') h theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eqOfVeq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eqOfVeq h) | isFalse h => isFalse (Char.neOfVne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LE.le v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LE.le v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none @[macroInline] def Option.getD : Option α → α → α | some x, _ => x | none, e => e inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.lengthAux {α : Type u} : List α → Nat → Nat | nil, n => n | cons a as, n => lengthAux as (Nat.succ n) def List.length {α : Type u} (as : List α) : Nat := lengthAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ := match as with | nil => fun _ => rfl | cons a as => fun n => aux a as n.succ aux a as 0 def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → LT.lt i as.length → α | nil, i, h => absurd h (Nat.notLtZero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have : LT.lt i.succ as.length.succ := length_cons .. ▸ h get as i (Nat.leOfSuccLeSucc this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.sub b def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s startPos := 0 stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (LT.lt i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (LT.lt i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (LT.lt j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as @[inlineIfReduce] def List.toArrayAux : List α → Array α → Array α | nil, r => r | cons a as, r => toArrayAux as (r.push a) @[inlineIfReduce] def List.redLength : List α → Nat | nil => 0 | cons _ as => as.redLength.succ @[inline, matchPattern, export lean_list_to_array] def List.toArray (as : List α) : Array α := as.toArrayAux (Array.mkEmpty as.redLength) class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → f α → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α β : Type u} → f α → f β → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {α β : Type u} → f α → f β → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y x seqLeft x y := bind x fun a => bind y (fun _ => pure a) seqRight x y := bind x fun _ => y instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (LT.lt j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orelse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error arbitrary s @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ α) (y : EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Sort u) where hash : α → UInt64 export Hashable (hash) @[extern c inline "(size_t)#1"] constant UInt64.toUSize (u : UInt64) : USize @[extern c inline "(uint64_t)#1"] constant USize.toUInt64 (u : USize) : UInt64 @[extern "lean_uint64_mix_hash"] constant mixHash (u₁ u₂ : UInt64) : UInt64 @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : UInt64 instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → UInt64 → Name | num : Name → Nat → UInt64 → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → UInt64 | Name.anonymous => UInt64.ofNatCore 1723 (by decide) | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (LT.lt v UInt64.size) (fun h => UInt64.ofNatCore v h) (fun _ => UInt64.ofNatCore 17 (by decide)))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) (endPos : String.Pos) /- Synthesized token (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) /- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax where | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def groupKind : SyntaxNodeKind := `group def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ args => args.size | _ => 0 def isMissing : Syntax → Bool | Syntax.missing => true | _ => false def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def matchesNull (stx : Syntax) (n : Nat) : Bool := isNodeOf stx nullKind n def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId id) def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node k _ => node k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node k args => node k (args.setD i arg) | stx => stx /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (LT.lt i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (endPos := pos) ..) .., _ => some pos | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (endPos := pos) ..) .., _ => some pos | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (LT.lt i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none def mkAtom (val : String) : Syntax := Syntax.atom SourceInfo.none val def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom (SourceInfo.fromRef src) val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ private constant MethodsRefPointed : PointedType.{0} private def MethodsRef : Type := MethodsRefPointed.type structure Context where methods : MethodsRef mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception structure State where macroScope : MacroScope traceMsgs : List (Prod Name String) := List.nil deriving Inhabited end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception Macro.State) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s.macroScope, { s with macroScope := hAdd s.macroScope 1 }))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope structure Methods where expandMacro? : Syntax → MacroM (Option Syntax) getCurrNamespace : MacroM Name hasDecl : Name → MacroM Bool resolveNamespace? : Name → MacroM (Option Name) resolveGlobalName : Name → MacroM (List (Prod Name (List String))) deriving Inhabited unsafe def mkMethodsImp (methods : Methods) : MethodsRef := unsafeCast methods @[implementedBy mkMethodsImp] constant mkMethods (methods : Methods) : MethodsRef := MethodsRefPointed.val instance : Inhabited MethodsRef where default := mkMethods arbitrary unsafe def getMethodsImp : MacroM Methods := bind read fun ctx => pure (unsafeCast (ctx.methods)) @[implementedBy getMethodsImp] constant getMethods : MacroM Methods /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ def expandMacro? (stx : Syntax) : MacroM (Option Syntax) := do (← getMethods).expandMacro? stx /-- Return `true` if the environment contains a declaration with name `declName` -/ def hasDecl (declName : Name) : MacroM Bool := do (← getMethods).hasDecl declName def getCurrNamespace : MacroM Name := do (← getMethods).getCurrNamespace def resolveNamespace? (n : Name) : MacroM (Option Name) := do (← getMethods).resolveNamespace? n def resolveGlobalName (n : Name) : MacroM (List (Prod Name (List String))) := do (← getMethods).resolveGlobalName n def trace (clsName : Name) (msg : String) : MacroM Unit := do modify fun s => { s with traceMsgs := List.cons (Prod.mk clsName msg) s.traceMsgs } end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
058f4fca351b2da0f7bfb376f3bd59647ec0903d
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Meta/Basic.lean
2a7df070f54f94061d661d796e8c0777246f8e37
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
72,674
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.ReplaceExpr import Lean.Util.MonadBacktrack import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode /-! This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck /-- Configuration flags for the `MetaM` monad. Many of them are used to control the `isDefEq` function that checks whether two terms are definitionally equal or not. Recall that when `isDefEq` is trying to check whether `?m@C a₁ ... aₙ` and `t` are definitionally equal (`?m@C a₁ ... aₙ =?= t`), where `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. We solve it using the assignment `?m := fun a₁ ... aₙ => t` if 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` -/ structure Config where /-- If `foApprox` is set to true, and some `aᵢ` is not a free variable, then we use first-order unification ``` ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k ``` reduces to ``` ?m a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k ``` -/ foApprox : Bool := false /-- When `ctxApprox` is set to true, we relax condition 4, by creating an auxiliary metavariable `?n'` with a smaller context than `?m'`. -/ ctxApprox : Bool := false /-- When `quasiPatternApprox` is set to true, we ignore condition 2. -/ quasiPatternApprox : Bool := false /-- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ constApprox : Bool := false /-- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ isDefEqStuckEx : Bool := false /-- Controls which definitions and theorems can be unfolded by `isDefEq` and `whnf`. -/ transparency : TransparencyMode := TransparencyMode.default /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ zetaNonDep : Bool := true /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ trackZeta : Bool := false /-- Enable/disable the unification hints feature. -/ unificationHints : Bool := true /-- Enables proof irrelevance at `isDefEq` -/ proofIrrelevance : Bool := true /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make sure typing constraints resolved during elaboration should not "fill" holes that are supposed to be filled using tactics. However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because this last unification step is not really part of the term elaboration. -/ assignSyntheticOpaque : Bool := false /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/ offsetCnstrs : Bool := true /-- Eta for structures configuration mode. -/ etaStruct : EtaStructMode := .all /-- Function parameter information cache. -/ structure ParamInfo where /-- The binder annotation for the parameter. -/ binderInfo : BinderInfo := BinderInfo.default /-- `hasFwdDeps` is true if there is another parameter whose type depends on this one. -/ hasFwdDeps : Bool := false /-- `backDeps` contains the backwards dependencies. That is, the (0-indexed) position of previous parameters that this one depends on. -/ backDeps : Array Nat := #[] /-- `isProp` is true if the parameter is always a proposition. -/ isProp : Bool := false /-- `isDecInst` is true if the parameter's type is of the form `Decidable ...`. This information affects the generation of congruence theorems. -/ isDecInst : Bool := false /-- `higherOrderOutParam` is true if this parameter is a higher-order output parameter of local instance. Example: ``` getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` This flag is true for the parameter `dom` because it is output parameter of `[self : GetElem cont idx elem dom]` -/ higherOrderOutParam : Bool := false /-- `dependsOnHigherOrderOutParam` is true if the type of this parameter depends on the higher-order output parameter of a previous local instance. Example: ``` getElem : {cont : Type u_1} → {idx : Type u_2} → {elem : Type u_3} → {dom : cont → idx → Prop} → [self : GetElem cont idx elem dom] → (xs : cont) → (i : idx) → dom xs i → elem ``` This flag is true for the parameter with type `dom xs i` since `dom` is an output parameter of the instance `[self : GetElem cont idx elem dom]` -/ dependsOnHigherOrderOutParam : Bool := false deriving Inhabited def ParamInfo.isImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.implicit def ParamInfo.isInstImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.instImplicit def ParamInfo.isStrictImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.strictImplicit def ParamInfo.isExplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.default /-- Function information cache. See `ParamInfo`. -/ structure FunInfo where /-- Parameter information cache. -/ paramInfo : Array ParamInfo := #[] /-- `resultDeps` contains the function result type backwards dependencies. That is, the (0-indexed) position of parameters that the result type depends on. -/ resultDeps : Array Nat := #[] /-- Key for the function information cache. -/ structure InfoCacheKey where /-- The transparency mode used to compute the `FunInfo`. -/ transparency : TransparencyMode /-- The function being cached information about. It is quite often an `Expr.const`. -/ expr : Expr /-- `nargs? = some n` if the cached information was computed assuming the function has arity `n`. If `nargs? = none`, then the cache information consumed the arrow type as much as possible unsing the current transparency setting. X-/ nargs? : Option Nat deriving Inhabited, BEq namespace InfoCacheKey instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩ end InfoCacheKey abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) abbrev InferTypeCache := PersistentExprStructMap Expr abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo abbrev WhnfCache := PersistentExprStructMap Expr /-- A mapping `(s, t) ↦ isDefEq s t`. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache). We should also investigate the impact on memory consumption. -/ abbrev DefEqCache := PersistentHashMap (Expr × Expr) Bool /-- Cache datastructures for type inference, type class resolution, whnf, and definitional equality. -/ structure Cache where inferType : InferTypeCache := {} funInfo : FunInfoCache := {} synthInstance : SynthInstanceCache := {} whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default` whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all` defEq : DefEqCache := {} deriving Inhabited /-- "Context" for a postponed universe constraint. `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created. -/ structure DefEqContext where lhs : Expr rhs : Expr lctx : LocalContext localInstances : LocalInstances /-- Auxiliary structure for representing postponed universe constraints. Remark: the fields `ref` and `rootDefEq?` are used for error message generation only. Remark: we may consider improving the error message generation in the future. -/ structure PostponedEntry where /-- We save the `ref` at entry creation time. This is used for reporting errors back to the user. -/ ref : Syntax lhs : Level rhs : Level /-- Context for the surrounding `isDefEq` call when entry was created. -/ ctx? : Option DefEqContext deriving Inhabited /-- `MetaM` monad state. -/ structure State where mctx : MetavarContext := {} cache : Cache := {} /-- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ zetaFVarIds : FVarIdSet := {} /-- Array of postponed universe level constraints -/ postponed : PersistentArray PostponedEntry := {} deriving Inhabited /-- Backtrackable state for the `MetaM` monad. -/ structure SavedState where core : Core.State meta : State deriving Nonempty /-- Contextual information for the `MetaM` monad. -/ structure Context where config : Config := {} /-- Local context -/ lctx : LocalContext := {} /-- Local instances in `lctx`. -/ localInstances : LocalInstances := #[] /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/ defEqCtx? : Option DefEqContext := none /-- Track the number of nested `synthPending` invocations. Nested invocations can happen when the type class resolution invokes `synthPending`. Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`. We will add a configuration option if necessary. -/ synthPendingDepth : Nat := 0 /-- A predicate to control whether a constant can be unfolded or not at `whnf`. Note that we do not cache results at `whnf` when `canUnfold?` is not `none`. -/ canUnfold? : Option (Config → ConstantInfo → CoreM Bool) := none abbrev MetaM := ReaderT Context $ StateRefT State CoreM -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. @[always_inline] instance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind } instance : Inhabited (MetaM α) where default := fun _ _ => default instance : MonadLCtx MetaM where getLCtx := return (← read).lctx instance : MonadMCtx MetaM where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : MonadEnv MetaM where getEnv := return (← getThe Core.State).env modifyEnv f := do modifyThe Core.State fun s => { s with env := f s.env, cache := {} }; modify fun s => { s with cache := {} } instance : AddMessageContext MetaM where addMessageContext := addMessageContextFull protected def saveState : MetaM SavedState := return { core := (← getThe Core.State), meta := (← get) } /-- Restore backtrackable parts of the state. -/ def SavedState.restore (b : SavedState) : MetaM Unit := do Core.restore b.core modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed } instance : MonadBacktrack SavedState MetaM where saveState := Meta.saveState restoreState s := s.restore @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck : MetaM α := throw <| Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug export Core (instantiateTypeLevelParams instantiateValueLevelParams) @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f <| runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase <| k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c section Methods variable [MonadControlT MetaM n] [Monad n] @[inline] def modifyCache (f : Cache → Cache) : MetaM Unit := modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩ @[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit := modifyCache fun ⟨ic, c1, c2, c3, c4, c5⟩ => ⟨f ic, c1, c2, c3, c4, c5⟩ @[inline] def modifyDefEqCache (f : DefEqCache → DefEqCache) : MetaM Unit := modifyCache fun ⟨c1, c2, c3, c4, c5, defeq⟩ => ⟨c1, c2, c3, c4, c5, f defeq⟩ def getLocalInstances : MetaM LocalInstances := return (← read).localInstances def getConfig : MetaM Config := return (← read).config def resetZetaFVarIds : MetaM Unit := modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : MetaM FVarIdSet := return (← get).zetaFVarIds /-- Return the array of postponed universe level constraints. -/ def getPostponed : MetaM (PersistentArray PostponedEntry) := return (← get).postponed /-- Set the array of postponed universe level constraints. -/ def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := postponed } /-- Modify the array of postponed universe level constraints. -/ @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := f s.postponed } /-- `useEtaStruct inductName` return `true` if we eta for structures is enabled for for the inductive datatype `inductName`. Recall we have three different settings: `.none` (never use it), `.all` (always use it), `.notClasses` (enabled only for structure-like inductive types that are not classes). The parameter `inductName` affects the result only if the current setting is `.notClasses`. -/ def useEtaStruct (inductName : Name) : MetaM Bool := do match (← getConfig).etaStruct with | .none => return false | .all => return true | .notClasses => return !isClass (← getEnv) inductName /-! WARNING: The following 4 constants are a hack for simulating forward declarations. They are defined later using the `export` attribute. This is hackish because we have to hard-code the true arity of these definitions here, and make sure the C names match. We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/ /-- Reduces an expression to its Weak Head Normal Form. This is when the topmost expression has been fully reduced, but may contain subexpressions which have not been reduced. -/ @[extern 6 "lean_whnf"] opaque whnf : Expr → MetaM Expr /-- Returns the inferred type of the given expression, or fails if it is not type-correct. -/ @[extern 6 "lean_infer_type"] opaque inferType : Expr → MetaM Expr @[extern 7 "lean_is_expr_def_eq"] opaque isExprDefEqAux : Expr → Expr → MetaM Bool @[extern 7 "lean_is_level_def_eq"] opaque isLevelDefEqAux : Level → Level → MetaM Bool @[extern 6 "lean_synth_pending"] protected opaque synthPending : MVarId → MetaM Bool def whnfForall (e : Expr) : MetaM Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; return mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore (← mkFreshMVarId) lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : MetaM Level := do let mvarId ← mkFreshLMVarId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; return mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do mkFreshExprMVarAt (← getLCtx) (← getLocalInstances) type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /-- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore mvarId (← getLCtx) (← getLocalInstances) type kind userName numScopeArgs def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def mkFreshLevelMVars (num : Nat) : MetaM (List Level) := num.foldM (init := []) fun _ us => return (← mkFreshLevelMVar)::us def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) := mkFreshLevelMVars info.numLevelParams /-- Create a constant with the given name and new universe metavariables. Example: ``mkConstWithFreshMVarLevels `Monad`` returns `@Monad.{?u, ?v}` -/ def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do let info ← getConstInfo declName return mkConst declName (← mkFreshLevelMVarsFor info) /-- Return current transparency setting/mode. -/ def getTransparency : MetaM TransparencyMode := return (← getConfig).transparency def shouldReduceAll : MetaM Bool := return (← getTransparency) == TransparencyMode.all def shouldReduceReducibleOnly : MetaM Bool := return (← getTransparency) == TransparencyMode.reducible /-- Return `some mvarDecl` where `mvarDecl` is `mvarId` declaration in the current metavariable context. Return `none` if `mvarId` has no declaration in the current metavariable context. -/ def _root_.Lean.MVarId.findDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) := return (← getMCtx).findDecl? mvarId @[deprecated MVarId.findDecl?] def findMVarDecl? (mvarId : MVarId) : MetaM (Option MetavarDecl) := mvarId.findDecl? /-- Return `mvarId` declaration in the current metavariable context. Throw an exception if `mvarId` is not declarated in the current metavariable context. -/ def _root_.Lean.MVarId.getDecl (mvarId : MVarId) : MetaM MetavarDecl := do match (← mvarId.findDecl?) with | some d => pure d | none => throwError "unknown metavariable '?{mvarId.name}'" @[deprecated MVarId.getDecl] def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do mvarId.getDecl /-- Return `mvarId` kind. Throw an exception if `mvarId` is not declarated in the current metavariable context. -/ def _root_.Lean.MVarId.getKind (mvarId : MVarId) : MetaM MetavarKind := return (← mvarId.getDecl).kind @[deprecated MVarId.getKind] def getMVarDeclKind (mvarId : MVarId) : MetaM MetavarKind := mvarId.getKind /-- Reture `true` if `e` is a synthetic (or synthetic opaque) metavariable -/ def isSyntheticMVar (e : Expr) : MetaM Bool := do if e.isMVar then return (← e.mvarId!.getKind) matches .synthetic | .syntheticOpaque else return false /-- Set `mvarId` kind in the current metavariable context. -/ def _root_.Lean.MVarId.setKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarKind mvarId kind @[deprecated MVarId.setKind] def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := mvarId.setKind kind /-- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def _root_.Lean.MVarId.setType (mvarId : MVarId) (type : Expr) : MetaM Unit := do modifyMCtx fun mctx => mctx.setMVarType mvarId type @[deprecated MVarId.setType] def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do mvarId.setType type /-- Return true if the given metavariable is "read-only". That is, its `depth` is different from the current metavariable context depth. -/ def _root_.Lean.MVarId.isReadOnly (mvarId : MVarId) : MetaM Bool := do return (← mvarId.getDecl).depth != (← getMCtx).depth @[deprecated MVarId.isReadOnly] def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do mvarId.isReadOnly /-- Return true if `mvarId.isReadOnly` return true or if `mvarId` is a synthetic opaque metavariable. Recall `isDefEq` will not assign a value to `mvarId` if `mvarId.isReadOnlyOrSyntheticOpaque`. -/ def _root_.Lean.MVarId.isReadOnlyOrSyntheticOpaque (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← mvarId.getDecl match mvarDecl.kind with | MetavarKind.syntheticOpaque => return !(← getConfig).assignSyntheticOpaque | _ => return mvarDecl.depth != (← getMCtx).depth @[deprecated MVarId.isReadOnlyOrSyntheticOpaque] def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do mvarId.isReadOnlyOrSyntheticOpaque /-- Return the level of the given universe level metavariable. -/ def _root_.Lean.LMVarId.getLevel (mvarId : LMVarId) : MetaM Nat := do match (← getMCtx).findLevelDepth? mvarId with | some depth => return depth | _ => throwError "unknown universe metavariable '?{mvarId.name}'" @[deprecated LMVarId.getLevel] def getLevelMVarDepth (mvarId : LMVarId) : MetaM Nat := mvarId.getLevel /-- Return true if the given universe metavariable is "read-only". That is, its `depth` is different from the current metavariable context depth. -/ def _root_.Lean.LMVarId.isReadOnly (mvarId : LMVarId) : MetaM Bool := return (← mvarId.getLevel) < (← getMCtx).levelAssignDepth @[deprecated LMVarId.isReadOnly] def isReadOnlyLevelMVar (mvarId : LMVarId) : MetaM Bool := do mvarId.isReadOnly /-- Set the user-facing name for the given metavariable. -/ def _root_.Lean.MVarId.setUserName (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarUserName mvarId newUserName @[deprecated MVarId.setUserName] def setMVarUserName (mvarId : MVarId) (userNameNew : Name) : MetaM Unit := mvarId.setUserName userNameNew /-- Throw an exception saying `fvarId` is not declared in the current local context. -/ def _root_.Lean.FVarId.throwUnknown (fvarId : FVarId) : CoreM α := throwError "unknown free variable '{mkFVar fvarId}'" @[deprecated FVarId.throwUnknown] def throwUnknownFVar (fvarId : FVarId) : MetaM α := fvarId.throwUnknown /-- Return `some decl` if `fvarId` is declared in the current local context. -/ def _root_.Lean.FVarId.findDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := return (← getLCtx).find? fvarId @[deprecated FVarId.findDecl?] def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := fvarId.findDecl? /-- Return the local declaration for the given free variable. Throw an exception if local declaration is not in the current local context. -/ def _root_.Lean.FVarId.getDecl (fvarId : FVarId) : MetaM LocalDecl := do match (← getLCtx).find? fvarId with | some d => return d | none => fvarId.throwUnknown @[deprecated FVarId.getDecl] def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do fvarId.getDecl /-- Return the type of the given free variable. -/ def _root_.Lean.FVarId.getType (fvarId : FVarId) : MetaM Expr := return (← fvarId.getDecl).type /-- Return the binder information for the given free variable. -/ def _root_.Lean.FVarId.getBinderInfo (fvarId : FVarId) : MetaM BinderInfo := return (← fvarId.getDecl).binderInfo /-- Return `some value` if the given free variable is a let-declaration, and `none` otherwise. -/ def _root_.Lean.FVarId.getValue? (fvarId : FVarId) : MetaM (Option Expr) := return (← fvarId.getDecl).value? /-- Return the user-facing name for the given free variable. -/ def _root_.Lean.FVarId.getUserName (fvarId : FVarId) : MetaM Name := return (← fvarId.getDecl).userName /-- Return `true` is the free variable is a let-variable. -/ def _root_.Lean.FVarId.isLetVar (fvarId : FVarId) : MetaM Bool := return (← fvarId.getDecl).isLet /-- Get the local declaration associated to the given `Expr` in the current local context. Fails if the given expression is not a fvar or if no such declaration exists. -/ def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := fvar.fvarId!.getDecl /-- Given a user-facing name for a free variable, return its declaration in the current local context. Throw an exception if free variable is not declared. -/ def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError "unknown local declaration '{userName}'" /-- Given a user-facing name for a free variable, return the free variable or throw if not declared. -/ def getFVarFromUserName (userName : Name) : MetaM Expr := do let d ← getLocalDeclFromUserName userName return Expr.fvar d.fvarId /-- Lift a `MkBindingM` monadic action `x` to `MetaM`. -/ @[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do match x { lctx := (← getLCtx), mainModule := (← getEnv).mainModule } { mctx := (← getMCtx), ngen := (← getNGen), nextMacroScope := (← getThe Core.State).nextMacroScope } with | .ok e sNew => do setMCtx sNew.mctx modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope } pure e | .error (.revertFailure ..) sNew => do setMCtx sNew.mctx modifyThe Core.State fun s => { s with ngen := sNew.ngen, nextMacroScope := sNew.nextMacroScope } throwError "failed to create binder due to failure when reverting variable dependencies" /-- Similar to `abstracM` but consider only the first `min n xs.size` entries in `xs` It is also similar to `Expr.abstractRange`, but handles metavariables correctly. It uses `elimMVarDeps` to ensure `e` and the type of the free variables `xs` do not contain a metavariable `?m` s.t. local context of `?m` contains a free variable in `xs`. -/ def _root_.Lean.Expr.abstractRangeM (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := liftMkBindingM <| MetavarContext.abstractRange e n xs @[deprecated Expr.abstractRangeM] def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := e.abstractRangeM n xs /-- Replace free (or meta) variables `xs` with loose bound variables. Similar to `Expr.abstract`, but handles metavariables correctly. -/ def _root_.Lean.Expr.abstractM (e : Expr) (xs : Array Expr) : MetaM Expr := e.abstractRangeM xs.size xs @[deprecated Expr.abstractM] def abstract (e : Expr) (xs : Array Expr) : MetaM Expr := e.abstractM xs /-- Collect forward dependencies for the free variables in `toRevert`. Recall that when reverting free variables `xs`, we must also revert their forward dependencies. -/ def collectForwardDeps (toRevert : Array Expr) (preserveOrder : Bool) : MetaM (Array Expr) := do liftMkBindingM <| MetavarContext.collectForwardDeps toRevert preserveOrder /-- Takes an array `xs` of free variables or metavariables and a term `e` that may contain those variables, and abstracts and binds them as universal quantifiers. - if `usedOnly = true` then only variables that the expression body depends on will appear. - if `usedLetOnly = true` same as `usedOnly` except for let-bound variables. (That is, local constants which have been assigned a value.) -/ def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly binderInfoForMVars /-- Takes an array `xs` of free variables and metavariables and a body term `e` and creates `fun ..xs => e`, suitably abstracting `e` and the types in `xs`. -/ def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := if xs.isEmpty then return e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly binderInfoForMVars def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) (binderInfoForMVars := BinderInfo.implicit) : MetaM Expr := mkLambdaFVars xs e (usedLetOnly := usedLetOnly) (binderInfoForMVars := binderInfoForMVars) /-- `fun _ : Unit => a` -/ def mkFunUnit (a : Expr) : MetaM Expr := return Lean.mkLambda (← mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder /-- `withConfig f x` executes `x` using the updated configuration object obtained by applying `f`. -/ @[inline] def withConfig (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withoutProofIrrelevance (x : n α) : n α := withConfig (fun cfg => { cfg with proofIrrelevance := false }) x @[inline] def withTransparency (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) /-- `withDefault x` excutes `x` using the default transparency setting. -/ @[inline] def withDefault (x : n α) : n α := withTransparency TransparencyMode.default x /-- `withReducible x` excutes `x` using the reducible transparency setting. In this setting only definitions tagged as `[reducible]` are unfolded. -/ @[inline] def withReducible (x : n α) : n α := withTransparency TransparencyMode.reducible x /-- `withReducibleAndInstances x` excutes `x` using the `.instances` transparency setting. In this setting only definitions tagged as `[reducible]` or type class instances are unfolded. -/ @[inline] def withReducibleAndInstances (x : n α) : n α := withTransparency TransparencyMode.instances x /-- Execute `x` ensuring the transparency setting is at least `mode`. Recall that `.all > .default > .instances > .reducible`. -/ @[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x /-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/ @[inline] def withAssignableSyntheticOpaque (x : n α) : n α := withConfig (fun config => { config with assignSyntheticOpaque := true }) x /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do let savedCache := (← get).cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache : n α → n α := mapMetaM savingCacheImpl def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do if (← shouldReduceAll) then return some info else return none private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← getTransparency) with | TransparencyMode.all => return some info | TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none /-- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`. This method is only used to implement `isClassQuickConst?`. It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/ private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do match (← getEnv).find? constName with | some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do if isClass (← getEnv) constName then return .some constName else match (← getConstTemp? constName) with | some (.defnInfo ..) => return .undef -- We may be able to unfold the definition | _ => return .none private partial def isClassQuick? : Expr → MetaM (LOption Name) | .bvar .. => return .none | .lit .. => return .none | .fvar .. => return .none | .sort .. => return .none | .lam .. => return .none | .letE .. => return .undef | .proj .. => return .undef | .forallE _ _ b _ => isClassQuick? b | .mdata _ e => isClassQuick? e | .const n _ => isClassQuickConst? n | .mvar mvarId => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => return .none | .app f _ => match f.getAppFn with | .const n .. => isClassQuickConst? n | .lam .. => return .undef | _ => return .none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let savedSythInstance := (← get).cache.synthInstance modifyCache fun c => { c with synthInstance := {} } return savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modifyCache fun c => { c with synthInstance := cache } @[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar if localDecl.isImplementationDetail then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α := mapMetaM <| withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | .none => withNewLocalInstancesImp fvars (i+1) k | .undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k | .some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | .forallE n d b bi => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d bi let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? (type : Expr) : MetaM (Option Name) := withReducible do -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun _ type => do let env ← getEnv match type.getAppFn with | .const c _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← whnf type).getAppFn with | .const c _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | .none => return none | .some c => return (some c) | .undef => isClassExpensive? type end /-- `isClass? type` return `some ClsName` if `type` is an instance of the class `ClsName`. Example: ``` #eval do let x ← mkAppM ``Inhabited #[mkConst ``Nat] IO.println (← isClass? x) -- (some Inhabited) ``` -/ def isClass? (type : Expr) : MetaM (Option Name) := try isClassImp? type catch _ => return none private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImp fvars j partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImpAux fvars j @[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do process consumeLet (← getLCtx) #[] 0 e where process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, .lam n d b bi => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d bi let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, .letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e /-- Similar to `lambdaTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope (e : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp e true k) k /-- Given `e` of the form `fun ..xs => A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def lambdaTelescope (e : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp e false k) k /-- Return the parameter names for the given global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do forallTelescopeReducing (← getConstInfo declName).type fun xs _ => do xs.mapM fun x => do let localDecl ← x.fvarId!.getDecl return localDecl.userName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do if maxMVars?.isEqSome mvars.size then let type := type.instantiateRevRange j mvars.size mvars; return (mvars, bis, type) else match type with | .forallE n d b bi => let d := d.instantiateRevRange j mvars.size mvars let k := if bi.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push bi process mvars bis j b | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else return (mvars, bis, type) else return (mvars, bis, type) /-- Given `e` of the form `forall ..xs, A`, this combinator will create a new metavariable for each `x` in `xs` and instantiate `A` with these. Returns a product containing - the new metavariables - the binder info for the `xs` - the instantiated `A` -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallMetaTelescope`, but if `e = forall ..xs, A` it will reduce `A` to construct further mvars. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/ def forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind) /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars return (mvars, bis, type) if maxMVars?.isEqSome mvars.size then finalize () else match type with | .lam _ d b bi => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push bi process mvars bis j b | _ => finalize () private def withNewFVar (n : Name) (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do if let some c ← isClass? fvarType then withNewLocalInstance c fvar <| k fvar else k fvar private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) (kind : LocalDeclKind) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi kind let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar n fvar type k /-- Create a free variable `x` with name, binderInfo and type, add it to the context and run in `k`. Then revert the context. -/ def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) (kind : LocalDeclKind := .default) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k kind) k def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k /-- Append an array of free variables `xs` to the local context and execute `k xs`. declInfos takes the form of an array consisting of: - the name of the variable - the binder info of the variable - a type constructor for the variable, where the array consists of all of the free variables defined prior to this one. This is needed because the type of the variable may depend on prior variables. -/ partial def withLocalDecls [Inhabited α] (declInfos : Array (Name × BinderInfo × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := loop #[] where loop [Inhabited α] (acc : Array Expr) : n α := do if acc.size < declInfos.size then let (name, bi, typeCtor) := declInfos[acc.size]! withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x) else k acc def withLocalDeclsD [Inhabited α] (declInfos : Array (Name × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := withLocalDecls (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) => lctx.setBinderInfo fvarId bi withReader (fun ctx => { ctx with lctx := lctx }) k def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α := mapMetaM (fun k => withNewBinderInfosImp bs k) k /-- Execute `k` using a local context where any `x` in `xs` that is tagged as instance implicit is treated as a regular implicit. -/ def withInstImplicitAsImplict (xs : Array Expr) (k : MetaM α) : MetaM α := do let newBinderInfos ← xs.filterMapM fun x => do let bi ← x.fvarId!.getBinderInfo if bi == .instImplicit then return some (x.fvarId!, .implicit) else return none withNewBinderInfos newBinderInfos k private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) (kind : LocalDeclKind) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val (nonDep := false) kind let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar n fvar type k /-- Add the local declaration `<name> : <type> := <val>` to the local context and execute `k x`, where `x` is a new free variable corresponding to the `let`-declaration. After executing `k x`, the local context is restored. -/ def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) (kind : LocalDeclKind := .default) : n α := map1MetaM (fun k => withLetDeclImp name type val k kind) k def withLocalInstancesImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let mut localInsts := (← read).localInstances let size := localInsts.size for decl in decls do unless decl.isImplementationDetail do if let some className ← isClass? decl.type then localInsts := localInsts.push { className, fvar := decl.toExpr } if localInsts.size == size then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := localInsts }) k /-- Register any local instance in `decls` -/ def withLocalInstances (decls : List LocalDecl) : n α → n α := mapMetaM <| withLocalInstancesImp decls private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do withLocalInstancesImp decls k /-- `withExistingLocalDecls decls k`, adds the given local declarations to the local context, and then executes `k`. This method assumes declarations in `decls` have valid `FVarId`s. After executing `k`, the local context is restored. Remark: this method is used, for example, to implement the `match`-compiler. Each `match`-alternative commes with a local declarations (corresponding to pattern variables), and we use `withExistingLocalDecls` to add them to the local context before we process them. -/ def withExistingLocalDecls (decls : List LocalDecl) : n α → n α := mapMetaM <| withExistingLocalDeclsImp decls private def withNewMCtxDepthImp (allowLevelAssignments : Bool) (x : MetaM α) : MetaM α := do let saved ← get modify fun s => { s with mctx := s.mctx.incDepth allowLevelAssignments, postponed := {} } try x finally modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed } /-- `withNewMCtxDepth k` executes `k` with a higher metavariable context depth, where metavariables created outside the `withNewMCtxDepth` (with a lower depth) cannot be assigned. If `allowLevelAssignments` is set to true, then the level metavariable depth is not increased, and level metavariables from the outer scope can be assigned. (This is used by TC synthesis.) -/ def withNewMCtxDepth (k : n α) (allowLevelAssignments := false) : n α := mapMetaM (withNewMCtxDepthImp allowLevelAssignments) k private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x /-- `withLCtx lctx localInsts k` replaces the local context and local instances, and then executes `k`. The local context and instances are restored after executing `k`. This method assumes that the local instances in `localInsts` are in the local context `lctx`. -/ def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM <| withLocalContextImp lctx localInsts private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← mvarId.getDecl withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def _root_.Lean.MVarId.withContext (mvarId : MVarId) : n α → n α := mapMetaM <| withMVarContextImp mvarId @[deprecated MVarId.withContext] def withMVarContext (mvarId : MVarId) : n α → n α := mvarId.withContext private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' /-- `withMCtx mctx k` replaces the metavariable context and then executes `k`. The metavariable context is restored after executing `k`. This method is used to implement the type class resolution procedure. -/ def withMCtx (mctx : MetavarContext) : n α → n α := mapMetaM <| withMCtxImp mctx @[inline] private def approxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq : n α → n α := mapMetaM fullApproxDefEqImp /-- Instantiate assigned universe metavariables in `u`, and then normalize it. -/ def normalizeLevel (u : Level) : MetaM Level := do let u ← instantiateLevelMVars u pure u.normalize /-- `whnf` with reducible transparency.-/ def whnfR (e : Expr) : MetaM Expr := withTransparency TransparencyMode.reducible <| whnf e /-- `whnf` with default transparency.-/ def whnfD (e : Expr) : MetaM Expr := withTransparency TransparencyMode.default <| whnf e /-- `whnf` with instances transparency.-/ def whnfI (e : Expr) : MetaM Expr := withTransparency TransparencyMode.instances <| whnf e /-- Mark declaration `declName` with the attribute `[inline]`. This method does not check whether the given declaration is a definition. Recall that this attribute can only be set in the same module where `declName` has been declared. -/ def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | .ok env => setEnv env | .error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | .forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else return e /-- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | .lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else return e /-- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateLambdaAux ps 0 e /-- Pretty-print the given expression. -/ def ppExprWithInfos (e : Expr) : MetaM FormatWithInfos := do let ctxCore ← readThe Core.Context Lean.ppExprWithInfos { env := (← getEnv), mctx := (← getMCtx), lctx := (← getLCtx), opts := (← getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e /-- Pretty-print the given expression. -/ def ppExpr (e : Expr) : MetaM Format := (·.fmt) <$> ppExprWithInfos e @[inline] protected def orElse (x : MetaM α) (y : Unit → MetaM α) : MetaM α := do let s ← saveState try x catch _ => s.restore; y () instance : OrElse (MetaM α) := ⟨Meta.orElse⟩ instance : Alternative MetaM where failure := fun {_} => throwError "failed" orElse := Meta.orElse @[inline] private def orelseMergeErrorsImp (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ _ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ _ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw <| Exception.error ref <| f msg | ex => throw ex @[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- Sort free variables using an order `x < y` iff `x` was defined before `y`. If a free variable is not in the local context, we use their id. -/ def sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do let lctx ← getLCtx return fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index < d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁.name fvarId₂.name end Methods /-- Return `true` if `declName` is an inductive predicate. That is, `inductive` type in `Prop`. -/ def isInductivePredicate (declName : Name) : MetaM Bool := do match (← getEnv).find? declName with | some (.inductInfo { type := type, ..}) => forallTelescopeReducing type fun _ type => do match (← whnfD type) with | .sort u .. => return u == levelZero | _ => return false | _ => return false def isListLevelDefEqAux : List Level → List Level → MetaM Bool | [], [] => return true | u::us, v::vs => isLevelDefEqAux u v <&&> isListLevelDefEqAux us vs | _, _ => return false def getNumPostponed : MetaM Nat := do return (← getPostponed).size def getResetPostponed : MetaM (PersistentArray PostponedEntry) := do let ps ← getPostponed setPostponed {} return ps /-- Annotate any constant and sort in `e` that satisfies `p` with `pp.universes true` -/ private def exposeRelevantUniverses (e : Expr) (p : Level → Bool) : Expr := e.replace fun | .const _ us => if us.any p then some (e.setPPUniverses true) else none | .sort u => if p u then some (e.setPPUniverses true) else none | _ => none private def mkLeveErrorMessageCore (header : String) (entry : PostponedEntry) : MetaM MessageData := do match entry.ctx? with | none => return m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}" | some ctx => withLCtx ctx.lctx ctx.localInstances do let s := entry.lhs.collectMVars entry.rhs.collectMVars /- `p u` is true if it contains a universe metavariable in `s` -/ let p (u : Level) := u.any fun | .mvar m => s.contains m | _ => false let lhs := exposeRelevantUniverses (← instantiateMVars ctx.lhs) p let rhs := exposeRelevantUniverses (← instantiateMVars ctx.rhs) p try addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD m!"{lhs} : {← inferType lhs}"}\nwith{indentD m!"{rhs} : {← inferType rhs}"}" catch _ => addMessageContext m!"{header}{indentD m!"{entry.lhs} =?= {entry.rhs}"}\nwhile trying to unify{indentD lhs}\nwith{indentD rhs}" def mkLevelStuckErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "stuck at solving universe constraint" entry def mkLevelErrorMessage (entry : PostponedEntry) : MetaM MessageData := do mkLeveErrorMessageCore "failed to solve universe constraint" entry private def processPostponedStep (exceptionOnFailure : Bool) : MetaM Bool := do let ps ← getResetPostponed for p in ps do unless (← withReader (fun ctx => { ctx with defEqCtx? := p.ctx? }) <| isLevelDefEqAux p.lhs p.rhs) do if exceptionOnFailure then withRef p.ref do throwError (← mkLevelErrorMessage p) else return false return true partial def processPostponed (mayPostpone : Bool := true) (exceptionOnFailure := false) : MetaM Bool := do if (← getNumPostponed) == 0 then return true else let numPostponedBegin ← getNumPostponed withTraceNode `Meta.isLevelDefEq.postponed (fun _ => return m!"processing #{numPostponedBegin} postponed is-def-eq level constraints") do let rec loop : MetaM Bool := do let numPostponed ← getNumPostponed if numPostponed == 0 then return true else if !(← processPostponedStep exceptionOnFailure) then return false else let numPostponed' ← getNumPostponed if numPostponed' == 0 then return true else if numPostponed' < numPostponed then loop else trace[Meta.isLevelDefEq.postponed] "no progress solving pending is-def-eq level constraints" return mayPostpone loop /-- `checkpointDefEq x` executes `x` and process all postponed universe level constraints produced by `x`. We keep the modifications only if `processPostponed` return true and `x` returned `true`. If `mayPostpone == false`, all new postponed universe level constraints must be solved before returning. We currently try to postpone universe constraints as much as possible, even when by postponing them we are not sure whether `x` really succeeded or not. -/ @[specialize] def checkpointDefEq (x : MetaM Bool) (mayPostpone : Bool := true) : MetaM Bool := do let s ← saveState /- It is not safe to use the `isDefEq` cache between different `isDefEq` calls. Reason: different configuration settings, and result depends on the state of the `MetavarContext` We have tried in the past to track when the result was independent of the `MetavarContext` state but it was not effective. It is more important to cache aggressively inside of a single `isDefEq` call because some of the heuristics create many similar subproblems. See issue #1102 for an example that triggers an exponential blowup if we don't use this more aggresive form of caching. -/ modifyDefEqCache fun _ => {} let postponed ← getResetPostponed try if (← x) then if (← processPostponed mayPostpone) then let newPostponed ← getPostponed setPostponed (postponed ++ newPostponed) return true else s.restore return false else s.restore return false catch ex => s.restore throw ex /-- Determines whether two universe level expressions are definitionally equal to each other. -/ def isLevelDefEq (u v : Level) : MetaM Bool := checkpointDefEq (mayPostpone := true) <| Meta.isLevelDefEqAux u v /-- See `isDefEq`. -/ def isExprDefEq (t s : Expr) : MetaM Bool := withReader (fun ctx => { ctx with defEqCtx? := some { lhs := t, rhs := s, lctx := ctx.lctx, localInstances := ctx.localInstances } }) do checkpointDefEq (mayPostpone := true) <| Meta.isExprDefEqAux t s /-- Determines whether two expressions are definitionally equal to each other. To control how metavariables are assigned and unified, metavariables and their context have a "depth". Given a metavariable `?m` and a `MetavarContext` `mctx`, `?m` is not assigned if `?m.depth != mctx.depth`. The combinator `withNewMCtxDepth x` will bump the depth while executing `x`. So, `withNewMCtxDepth (isDefEq a b)` is `isDefEq` without any mvar assignment happening whereas `isDefEq a b` will assign any metavariables of the current depth in `a` and `b` to unify them. For matching (where only mvars in `b` should be assigned), we create the term inside the `withNewMCtxDepth`. For an example, see [Lean.Meta.Simp.tryTheoremWithExtraArgs?](https://github.com/leanprover/lean4/blob/master/src/Lean/Meta/Tactic/Simp/Rewrite.lean#L100-L106) -/ abbrev isDefEq (t s : Expr) : MetaM Bool := isExprDefEq t s def isExprDefEqGuarded (a b : Expr) : MetaM Bool := do try isExprDefEq a b catch _ => return false /-- Similar to `isDefEq`, but returns `false` if an exception has been thrown. -/ abbrev isDefEqGuarded (t s : Expr) : MetaM Bool := isExprDefEqGuarded t s def isDefEqNoConstantApprox (t s : Expr) : MetaM Bool := approxDefEq <| isDefEq t s /-- Eta expand the given expression. Example: ``` etaExpand (mkConst ``Nat.add) ``` produces `fun x y => Nat.add x y` -/ def etaExpand (e : Expr) : MetaM Expr := withDefault do forallTelescopeReducing (← inferType e) fun xs _ => mkLambdaFVars xs (mkAppN e xs) end Meta builtin_initialize registerTraceClass `Meta.isLevelDefEq.postponed export Meta (MetaM) end Lean
8e7d096e6cf8b64226678a5e19764ae540c4dad8
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/pequiv.lean
60388ba25f00253266f5a21dd3c4f0aa8ba14829
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
11,688
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.equiv.basic data.set.lattice tactic.tauto universes u v w x /-- A `pequiv` is a partial equivalence, a representation of a bijection between a subset of `α` and a subset of `β` -/ structure pequiv (α : Type u) (β : Type v) := (to_fun : α → option β) (inv_fun : β → option α) (inv : ∀ (a : α) (b : β), a ∈ inv_fun b ↔ b ∈ to_fun a) infixr ` ≃. `:25 := pequiv namespace pequiv variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} open function option instance : has_coe_to_fun (α ≃. β) := ⟨_, to_fun⟩ @[simp] lemma coe_mk_apply (f₁ : α → option β) (f₂ : β → option α) (h) (x : α) : (pequiv.mk f₁ f₂ h : α → option β) x = f₁ x := rfl @[ext] lemma ext : ∀ {f g : α ≃. β} (h : ∀ x, f x = g x), f = g | ⟨f₁, f₂, hf⟩ ⟨g₁, g₂, hg⟩ h := have h : f₁ = g₁, from funext h, have ∀ b, f₂ b = g₂ b, begin subst h, assume b, have hf := λ a, hf a b, have hg := λ a, hg a b, cases h : g₂ b with a, { simp only [h, option.not_mem_none, false_iff] at hg, simp only [hg, iff_false] at hf, rwa [option.eq_none_iff_forall_not_mem] }, { rw [← option.mem_def, hf, ← hg, h, option.mem_def] } end, by simp [*, funext_iff] lemma ext_iff {f g : α ≃. β} : f = g ↔ ∀ x, f x = g x := ⟨congr_fun ∘ congr_arg _, ext⟩ @[refl] protected def refl (α : Type*) : α ≃. α := { to_fun := some, inv_fun := some, inv := λ _ _, eq_comm } @[symm] protected def symm (f : α ≃. β) : β ≃. α := { to_fun := f.2, inv_fun := f.1, inv := λ _ _, (f.inv _ _).symm } lemma mem_iff_mem (f : α ≃. β) : ∀ {a : α} {b : β}, a ∈ f.symm b ↔ b ∈ f a := f.3 lemma eq_some_iff (f : α ≃. β) : ∀ {a : α} {b : β}, f.symm b = some a ↔ f a = some b := f.3 @[trans] protected def trans (f : α ≃. β) (g : β ≃. γ) : pequiv α γ := { to_fun := λ a, (f a).bind g, inv_fun := λ a, (g.symm a).bind f.symm, inv := λ a b, by simp [*, and.comm, eq_some_iff f, eq_some_iff g] at * } @[simp] lemma refl_apply (a : α) : pequiv.refl α a = some a := rfl @[simp] lemma symm_refl : (pequiv.refl α).symm = pequiv.refl α := rfl @[simp] lemma symm_refl_apply (a : α) : (pequiv.refl α).symm a = some a := rfl @[simp] lemma symm_symm (f : α ≃. β) : f.symm.symm = f := by cases f; refl @[simp] lemma symm_symm_apply (f : α ≃. β) (a : α) : f.symm.symm a = f a := by rw symm_symm lemma symm_injective : function.injective (@pequiv.symm α β) := injective_of_has_left_inverse ⟨_, symm_symm⟩ lemma trans_assoc (f : α ≃. β) (g : β ≃. γ) (h : γ ≃. δ) : (f.trans g).trans h = f.trans (g.trans h) := ext (λ _, option.bind_assoc _ _ _) lemma mem_trans (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) : c ∈ f.trans g a ↔ ∃ b, b ∈ f a ∧ c ∈ g b := option.bind_eq_some' lemma trans_eq_some (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) : f.trans g a = some c ↔ ∃ b, f a = some b ∧ g b = some c := option.bind_eq_some' lemma trans_eq_none (f : α ≃. β) (g : β ≃. γ) (a : α) : f.trans g a = none ↔ (∀ b c, b ∉ f a ∨ c ∉ g b) := by simp only [eq_none_iff_forall_not_mem, mem_trans]; push_neg; tauto @[simp] lemma refl_trans (f : α ≃. β) : (pequiv.refl α).trans f = f := by ext; dsimp [pequiv.trans]; refl @[simp] lemma trans_refl (f : α ≃. β) : f.trans (pequiv.refl β) = f := by ext; dsimp [pequiv.trans]; simp @[simp] lemma refl_trans_apply (f : α ≃. β) (a : α) : (pequiv.refl α).trans f a = f a := by rw refl_trans @[simp] lemma trans_refl_apply (f : α ≃. β) (a : α) : f.trans (pequiv.refl β) a = f a := by rw trans_refl protected lemma inj (f : α ≃. β) {a₁ a₂ : α} {b : β} (h₁ : b ∈ f a₁) (h₂ : b ∈ f a₂) : a₁ = a₂ := by rw ← mem_iff_mem at *; cases h : f.symm b; simp * at * lemma injective_of_forall_ne_is_some (f : α ≃. β) (a₂ : α) (h : ∀ (a₁ : α), a₁ ≠ a₂ → is_some (f a₁)) : injective f := injective_of_has_left_inverse ⟨λ b, option.rec_on b a₂ (λ b', option.rec_on (f.symm b') a₂ id), λ x, begin classical, cases hfx : f x, { have : x = a₂, from not_imp_comm.1 (h x) (hfx.symm ▸ by simp), simp [this] }, { simp only [hfx], rw [(eq_some_iff f).2 hfx], refl } end⟩ lemma injective_of_forall_is_some {f : α ≃. β} (h : ∀ (a : α), is_some (f a)) : injective f := (classical.em (nonempty α)).elim (λ hn, injective_of_forall_ne_is_some f (classical.choice hn) (λ a _, h a)) (λ hn x, (hn ⟨x⟩).elim) section of_set variables (s : set α) [decidable_pred s] def of_set (s : set α) [decidable_pred s] : α ≃. α := { to_fun := λ a, if a ∈ s then some a else none, inv_fun := λ a, if a ∈ s then some a else none, inv := λ a b, by split_ifs; finish [eq_comm] } lemma mem_of_set_self_iff {s : set α} [decidable_pred s] {a : α} : a ∈ of_set s a ↔ a ∈ s := by dsimp [of_set]; split_ifs; simp * lemma mem_of_set_iff {s : set α} [decidable_pred s] {a b : α} : a ∈ of_set s b ↔ a = b ∧ a ∈ s := by dsimp [of_set]; split_ifs; split; finish @[simp] lemma of_set_eq_some_self_iff {s : set α} {h : decidable_pred s} {a : α} : of_set s a = some a ↔ a ∈ s := mem_of_set_self_iff @[simp] lemma of_set_eq_some_iff {s : set α} {h : decidable_pred s} {a b : α} : of_set s b = some a ↔ a = b ∧ a ∈ s := mem_of_set_iff @[simp] lemma of_set_symm : (of_set s).symm = of_set s := rfl @[simp] lemma of_set_univ : of_set set.univ = pequiv.refl α := by ext; dsimp [of_set]; simp [eq_comm] @[simp] lemma of_set_eq_refl {s : set α} [decidable_pred s] : of_set s = pequiv.refl α ↔ s = set.univ := ⟨λ h, begin rw [set.eq_univ_iff_forall], intro, rw [← mem_of_set_self_iff, h], exact rfl end, λ h, by simp only [of_set_univ.symm, h]; congr⟩ end of_set lemma symm_trans_rev (f : α ≃. β) (g : β ≃. γ) : (f.trans g).symm = g.symm.trans f.symm := rfl lemma trans_symm (f : α ≃. β) : f.trans f.symm = of_set {a | (f a).is_some} := begin ext, dsimp [pequiv.trans], simp only [eq_some_iff f, option.is_some_iff_exists, option.mem_def, bind_eq_some', of_set_eq_some_iff], split, { rintros ⟨b, hb₁, hb₂⟩, exact ⟨pequiv.inj _ hb₂ hb₁, b, hb₂⟩ }, { simp {contextual := tt} } end lemma symm_trans (f : α ≃. β) : f.symm.trans f = of_set {b | (f.symm b).is_some} := symm_injective $ by simp [symm_trans_rev, trans_symm, -symm_symm] lemma trans_symm_eq_iff_forall_is_some {f : α ≃. β} : f.trans f.symm = pequiv.refl α ↔ ∀ a, is_some (f a) := by rw [trans_symm, of_set_eq_refl, set.eq_univ_iff_forall]; refl instance : lattice.has_bot (α ≃. β) := ⟨{ to_fun := λ _, none, inv_fun := λ _, none, inv := by simp }⟩ @[simp] lemma bot_apply (a : α) : (⊥ : α ≃. β) a = none := rfl @[simp] lemma symm_bot : (⊥ : α ≃. β).symm = ⊥ := rfl @[simp] lemma trans_bot (f : α ≃. β) : f.trans (⊥ : β ≃. γ) = ⊥ := by ext; dsimp [pequiv.trans]; simp @[simp] lemma bot_trans (f : β ≃. γ) : (⊥ : α ≃. β).trans f = ⊥ := by ext; dsimp [pequiv.trans]; simp lemma is_some_symm_get (f : α ≃. β) {a : α} (h : is_some (f a)) : is_some (f.symm (option.get h)) := is_some_iff_exists.2 ⟨a, by rw [f.eq_some_iff, some_get]⟩ section single variables [decidable_eq α] [decidable_eq β] [decidable_eq γ] def single (a : α) (b : β) : α ≃. β := { to_fun := λ x, if x = a then some b else none, inv_fun := λ x, if x = b then some a else none, inv := λ _ _, by simp; split_ifs; cc } lemma mem_single (a : α) (b : β) : b ∈ single a b a := if_pos rfl lemma mem_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : b₁ ∈ single a₂ b₂ a₁ ↔ a₁ = a₂ ∧ b₁ = b₂ := by dsimp [single]; split_ifs; simp [*, eq_comm] @[simp] lemma symm_single (a : α) (b : β) : (single a b).symm = single b a := rfl @[simp] lemma single_apply (a : α) (b : β) : single a b a = some b := if_pos rfl @[simp] lemma symm_single_apply (a : α) (b : β) : (single a b).symm b = some a := by dsimp; simp lemma single_apply_of_ne {a₁ a₂ : α} (h : a₁ ≠ a₂) (b : β) : single a₁ b a₂ = none := if_neg h.symm lemma single_trans_of_mem (a : α) {b : β} {c : γ} {f : β ≃. γ} (h : c ∈ f b) : (single a b).trans f = single a c := begin ext, dsimp [single, pequiv.trans], split_ifs; simp * at * end lemma trans_single_of_mem {a : α} {b : β} (c : γ) {f : α ≃. β} (h : b ∈ f a) : f.trans (single b c) = single a c := symm_injective $ single_trans_of_mem _ ((mem_iff_mem f).2 h) @[simp] lemma single_trans_single (a : α) (b : β) (c : γ) : (single a b).trans (single b c) = single a c := single_trans_of_mem _ (mem_single _ _) @[simp] lemma single_subsingleton_eq_refl [subsingleton α] (a b : α) : single a b = pequiv.refl α := begin ext i j, dsimp [single], rw [if_pos (subsingleton.elim i a), subsingleton.elim i j, subsingleton.elim b j] end lemma trans_single_of_eq_none {b : β} (c : γ) {f : α ≃. β} (h : f.symm b = none) : f.trans (single b c) = ⊥ := begin ext, simp only [eq_none_iff_forall_not_mem, option.mem_def, f.eq_some_iff] at h, dsimp [pequiv.trans, single], simp, intros, split_ifs; simp * at * end lemma single_trans_of_eq_none (a : α) {b : β} {f : β ≃. γ} (h : f b = none) : (single a b).trans f = ⊥ := symm_injective $ trans_single_of_eq_none _ h lemma single_trans_single_of_ne {b₁ b₂ : β} (h : b₁ ≠ b₂) (a : α) (c : γ) : (single a b₁).trans (single b₂ c) = ⊥ := single_trans_of_eq_none _ (single_apply_of_ne h.symm _) end single section order open lattice instance : partial_order (α ≃. β) := { le := λ f g, ∀ (a : α) (b : β), b ∈ f a → b ∈ g a, le_refl := λ _ _ _, id, le_trans := λ f g h fg gh a b, (gh a b) ∘ (fg a b), le_antisymm := λ f g fg gf, ext begin assume a, cases h : g a with b, { exact eq_none_iff_forall_not_mem.2 (λ b hb, option.not_mem_none b $ h ▸ fg a b hb) }, { exact gf _ _ h } end } lemma le_def {f g : α ≃. β} : f ≤ g ↔ (∀ (a : α) (b : β), b ∈ f a → b ∈ g a) := iff.rfl instance : order_bot (α ≃. β) := { bot_le := λ _ _ _ h, (not_mem_none _ h).elim, ..pequiv.partial_order, ..pequiv.lattice.has_bot } instance [decidable_eq α] [decidable_eq β] : semilattice_inf_bot (α ≃. β) := { inf := λ f g, { to_fun := λ a, if f a = g a then f a else none, inv_fun := λ b, if f.symm b = g.symm b then f.symm b else none, inv := λ a b, begin have := @mem_iff_mem _ _ f a b, have := @mem_iff_mem _ _ g a b, split_ifs; finish end }, inf_le_left := λ _ _ _ _, by simp; split_ifs; cc, inf_le_right := λ _ _ _ _, by simp; split_ifs; cc, le_inf := λ f g h fg gh a b, begin have := fg a b, have := gh a b, simp [le_def], split_ifs; finish end, ..pequiv.lattice.order_bot } end order end pequiv namespace equiv variables {α : Type*} {β : Type*} {γ : Type*} def to_pequiv (f : α ≃ β) : α ≃. β := { to_fun := some ∘ f, inv_fun := some ∘ f.symm, inv := by simp [equiv.eq_symm_apply, eq_comm] } @[simp] lemma to_pequiv_refl : (equiv.refl α).to_pequiv = pequiv.refl α := rfl lemma to_pequiv_trans (f : α ≃ β) (g : β ≃ γ) : (f.trans g).to_pequiv = f.to_pequiv.trans g.to_pequiv := rfl lemma to_pequiv_symm (f : α ≃ β) : f.symm.to_pequiv = f.to_pequiv.symm := rfl end equiv
453e7a366e5869e6940fedd0160a912f1d872b04
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/seqToCodeIssue.lean
5c785ba615b1386cffcc8a6fc769834f5f430bd7
[ "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
229
lean
@[noinline] def print (n : Nat) : IO Unit := IO.println n set_option trace.Compiler.saveMono true def f (b : Bool) : IO Unit := do let a : Nat ← match b with | true => pure 0 | false => pure 1 print a print a
89afd617c1a0fe6f2729107c369269192d02db19
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/100-theorems-list/83_friendship_graphs.lean
c6213d261b059188da53ca4f71fbe896cf0422a0
[ "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
13,746
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller -/ import combinatorics.simple_graph.adj_matrix import linear_algebra.char_poly.coeff import data.int.modeq import data.zmod.basic import tactic.interval_cases /-! # The Friendship Theorem ## Definitions and Statement - A `friendship` graph is one in which any two distinct vertices have exactly one neighbor in common - A `politician`, at least in the context of this problem, is a vertex in a graph which is adjacent to every other vertex. - The friendship theorem (Erdős, Rényi, Sós 1966) states that every finite friendship graph has a politician. ## Proof outline The proof revolves around the theory of adjacency matrices, although some steps could equivalently be phrased in terms of counting walks. - Assume `G` is a finite friendship graph. - First we show that any two nonadjacent vertices have the same degree - Assume for contradiction that `G` does not have a politician. - Conclude from the last two points that `G` is `d`-regular for some `d : ℕ`. - Show that `G` has `d ^ 2 - d + 1` vertices. - By casework, show that if `d = 0, 1, 2`, then `G` has a politician. - If `3 ≤ d`, let `p` be a prime factor of `d - 1`. - If `A` is the adjacency matrix of `G` with entries in `ℤ/pℤ`, we show that `A ^ p` has trace `1`. - This gives a contradiction, as `A` has trace `0`, and thus `A ^ p` has trace `0`. ## References - [P. Erdős, A. Rényi, V. Sós, *On A Problem of Graph Theory*][erdosrenyisos] - [C. Huneke, *The Friendship Theorem*][huneke2002] -/ open_locale classical big_operators noncomputable theory open finset simple_graph matrix universes u v variables {V : Type u} {R : Type v} [semiring R] section friendship_def variables (G : simple_graph V) /-- This property of a graph is the hypothesis of the friendship theorem: every pair of nonadjacent vertices has exactly one common friend, a vertex to which both are adjacent. -/ def friendship [fintype V] : Prop := ∀ ⦃v w : V⦄, v ≠ w → fintype.card (G.common_neighbors v w) = 1 /-- A politician is a vertex that is adjacent to all other vertices. -/ def exists_politician : Prop := ∃ (v : V), ∀ (w : V), v ≠ w → G.adj v w end friendship_def variables [fintype V] {G : simple_graph V} {d : ℕ} (hG : friendship G) include hG namespace friendship variables (R) /-- One characterization of a friendship graph is that there is exactly one walk of length 2 between distinct vertices. These walks are counted in off-diagonal entries of the square of the adjacency matrix, so for a friendship graph, those entries are all 1. -/ theorem adj_matrix_sq_of_ne {v w : V} (hvw : v ≠ w) : ((G.adj_matrix R) ^ 2) v w = 1 := begin rw [sq, ← nat.cast_one, ← hG hvw], simp [common_neighbors, neighbor_finset_eq_filter, finset.filter_filter, finset.filter_inter, and_comm], end /-- This calculation amounts to counting the number of length 3 walks between nonadjacent vertices. We use it to show that nonadjacent vertices have equal degrees. -/ lemma adj_matrix_pow_three_of_not_adj {v w : V} (non_adj : ¬ G.adj v w) : ((G.adj_matrix R) ^ 3) v w = degree G v := begin rw [pow_succ, mul_eq_mul, adj_matrix_mul_apply, degree, card_eq_sum_ones, sum_nat_cast], apply sum_congr rfl, intros x hx, rw [adj_matrix_sq_of_ne _ hG, nat.cast_one], rintro ⟨rfl⟩, rw mem_neighbor_finset at hx, exact non_adj hx, end variable {R} /-- As `v` and `w` not being adjacent implies `degree G v = ((G.adj_matrix R) ^ 3) v w` and `degree G w = ((G.adj_matrix R) ^ 3) v w`, the degrees are equal if `((G.adj_matrix R) ^ 3) v w = ((G.adj_matrix R) ^ 3) w v` This is true as the adjacency matrix is symmetric. -/ lemma degree_eq_of_not_adj {v w : V} (hvw : ¬ G.adj v w) : degree G v = degree G w := begin rw [← nat.cast_id (G.degree v), ← nat.cast_id (G.degree w), ← adj_matrix_pow_three_of_not_adj ℕ hG hvw, ← adj_matrix_pow_three_of_not_adj ℕ hG (λ h, hvw (G.sym h))], conv_lhs {rw ← transpose_adj_matrix}, simp only [pow_succ, sq, mul_eq_mul, ← transpose_mul, transpose_apply], simp only [← mul_eq_mul, mul_assoc], end /-- Let `A` be the adjacency matrix of a graph `G`. If `G` is a friendship graph, then all of the off-diagonal entries of `A^2` are 1. If `G` is `d`-regular, then all of the diagonal entries of `A^2` are `d`. Putting these together determines `A^2` exactly for a `d`-regular friendship graph. -/ theorem adj_matrix_sq_of_regular (hd : G.is_regular_of_degree d) : ((G.adj_matrix R) ^ 2) = λ v w, if v = w then d else 1 := begin ext v w, by_cases h : v = w, { rw [h, sq, mul_eq_mul, adj_matrix_mul_self_apply_self, hd], simp, }, { rw [adj_matrix_sq_of_ne R hG h, if_neg h], }, end lemma adj_matrix_sq_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) ^ 2 = λ _ _, 1 := by simp [adj_matrix_sq_of_regular hG hd, dmod] section nonempty variable [nonempty V] /-- If `G` is a friendship graph without a politician (a vertex adjacent to all others), then it is regular. We have shown that nonadjacent vertices of a friendship graph have the same degree, and if there isn't a politician, we can show this for adjacent vertices by finding a vertex neither is adjacent to, and then using transitivity. -/ theorem is_regular_of_not_exists_politician (hG' : ¬exists_politician G) : ∃ (d : ℕ), G.is_regular_of_degree d := begin have v := classical.arbitrary V, use G.degree v, intro x, by_cases hvx : G.adj v x, swap, { exact (degree_eq_of_not_adj hG hvx).symm, }, dunfold exists_politician at hG', push_neg at hG', rcases hG' v with ⟨w, hvw', hvw⟩, rcases hG' x with ⟨y, hxy', hxy⟩, by_cases hxw : G.adj x w, swap, { rw degree_eq_of_not_adj hG hvw, exact degree_eq_of_not_adj hG hxw }, rw degree_eq_of_not_adj hG hxy, by_cases hvy : G.adj v y, swap, { exact (degree_eq_of_not_adj hG hvy).symm }, rw degree_eq_of_not_adj hG hvw, apply degree_eq_of_not_adj hG, intro hcontra, rcases finset.card_eq_one.mp (hG hvw') with ⟨⟨a, ha⟩, h⟩, have key : ∀ {x}, x ∈ G.common_neighbors v w → x = a, { intros x hx, have h' := mem_univ (subtype.mk x hx), rw [h, mem_singleton] at h', injection h', }, apply hxy', rw [key ((mem_common_neighbors G).mpr ⟨hvx, G.sym hxw⟩), key ((mem_common_neighbors G).mpr ⟨hvy, G.sym hcontra⟩)], end /-- Let `A` be the adjacency matrix of a `d`-regular friendship graph, and let `v` be a vector all of whose components are `1`. Then `v` is an eigenvector of `A ^ 2`, and we can compute the eigenvalue to be `d * d`, or as `d + (fintype.card V - 1)`, so those quantities must be equal. This essentially means that the graph has `d ^ 2 - d + 1` vertices. -/ lemma card_of_regular (hd : G.is_regular_of_degree d) : d + (fintype.card V - 1) = d * d := begin have v := classical.arbitrary V, transitivity ((G.adj_matrix ℕ) ^ 2).mul_vec (λ _, 1) v, { rw [adj_matrix_sq_of_regular hG hd, mul_vec, dot_product, ← insert_erase (mem_univ v)], simp only [sum_insert, mul_one, if_true, nat.cast_id, eq_self_iff_true, mem_erase, not_true, ne.def, not_false_iff, add_right_inj, false_and], rw [finset.sum_const_nat, card_erase_of_mem (mem_univ v), mul_one], { refl }, intros x hx, simp [(ne_of_mem_erase hx).symm], }, { rw [sq, mul_eq_mul, ← mul_vec_mul_vec], simp [adj_matrix_mul_vec_const_apply_of_regular hd, neighbor_finset, card_neighbor_set_eq_degree, hd v], } end /-- The size of a `d`-regular friendship graph is `1 mod (d-1)`, and thus `1 mod p` for a factor `p ∣ d-1`. -/ lemma card_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (fintype.card V : zmod p) = 1 := begin have hpos : 0 < fintype.card V := fintype.card_pos_iff.mpr infer_instance, rw [← nat.succ_pred_eq_of_pos hpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], have h := congr_arg (λ n, (↑n : zmod p)) (card_of_regular hG hd), revert h, simp [dmod], end end nonempty omit hG lemma adj_matrix_sq_mul_const_one_of_regular (hd : G.is_regular_of_degree d) : (G.adj_matrix R) * (λ _ _, 1) = λ _ _, d := by { ext x, simp [← hd x, degree] } lemma adj_matrix_mul_const_one_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) * (λ _ _, 1) = λ _ _, 1 := by rw [adj_matrix_sq_mul_const_one_of_regular hd, dmod] include hG /-- Modulo a factor of `d-1`, the square and all higher powers of the adjacency matrix of a `d`-regular friendship graph reduce to the matrix whose entries are all 1. -/ lemma adj_matrix_pow_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) {k : ℕ} (hk : 2 ≤ k) : (G.adj_matrix (zmod p)) ^ k = λ _ _, 1 := begin iterate 2 {cases k with k, { exfalso, linarith, }, }, induction k with k hind, { exact adj_matrix_sq_mod_p_of_regular hG dmod hd, }, rw [pow_succ, hind (nat.le_add_left 2 k)], exact adj_matrix_mul_const_one_mod_p_of_regular dmod hd, end variable [nonempty V] /-- This is the main proof. Assuming that `3 ≤ d`, we take `p` to be a prime factor of `d-1`. Then the `p`th power of the adjacency matrix of a `d`-regular friendship graph must have trace 1 mod `p`, but we can also show that the trace must be the `p`th power of the trace of the original adjacency matrix, which is 0, a contradiction. -/ lemma false_of_three_le_degree (hd : G.is_regular_of_degree d) (h : 3 ≤ d) : false := begin -- get a prime factor of d - 1 let p : ℕ := (d - 1).min_fac, have p_dvd_d_pred := (zmod.nat_coe_zmod_eq_zero_iff_dvd _ _).mpr (d - 1).min_fac_dvd, have dpos : 0 < d := by linarith, have d_cast : ↑(d - 1) = (d : ℤ) - 1 := by norm_cast, haveI : fact p.prime := ⟨nat.min_fac_prime (by linarith)⟩, have hp2 : 2 ≤ p := (fact.out p.prime).two_le, have dmod : (d : zmod p) = 1, { rw [← nat.succ_pred_eq_of_pos dpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], exact p_dvd_d_pred, }, have Vmod := card_mod_p_of_regular hG dmod hd, -- now we reduce to a trace calculation have := zmod.trace_pow_card (G.adj_matrix (zmod p)), contrapose! this, clear this, -- the trace is 0 mod p when computed one way rw [trace_adj_matrix, zero_pow (fact.out p.prime).pos], -- but the trace is 1 mod p when computed the other way rw adj_matrix_pow_mod_p_of_regular hG dmod hd hp2, dunfold fintype.card at Vmod, simp only [matrix.trace, diag_apply, mul_one, nsmul_eq_mul, linear_map.coe_mk, sum_const], rw [Vmod, ← nat.cast_one, zmod.nat_coe_zmod_eq_zero_iff_dvd, nat.dvd_one, nat.min_fac_eq_one_iff], linarith, end /-- If `d ≤ 1`, a `d`-regular friendship graph has at most one vertex, which is trivially a politician. -/ lemma exists_politician_of_degree_le_one (hd : G.is_regular_of_degree d) (hd1 : d ≤ 1) : exists_politician G := begin have sq : d * d = d := by { interval_cases d; norm_num }, have h := card_of_regular hG hd, rw sq at h, have : fintype.card V ≤ 1, { cases fintype.card V with n, { exact zero_le _, }, { have : n = 0, { rw [nat.succ_sub_succ_eq_sub, nat.sub_zero] at h, linarith }, subst n, } }, use classical.arbitrary V, intros w h, exfalso, apply h, apply fintype.card_le_one_iff.mp this, end /-- If `d = 2`, a `d`-regular friendship graph has 3 vertices, so it must be complete graph, and all the vertices are politicians. -/ lemma neighbor_finset_eq_of_degree_eq_two (hd : G.is_regular_of_degree 2) (v : V) : G.neighbor_finset v = finset.univ.erase v := begin apply finset.eq_of_subset_of_card_le, { rw finset.subset_iff, intro x, rw [mem_neighbor_finset, finset.mem_erase], exact λ h, ⟨(G.ne_of_adj h).symm, finset.mem_univ _⟩ }, convert_to 2 ≤ _, { convert_to _ = fintype.card V - 1, { have hfr:= card_of_regular hG hd, linarith }, { exact finset.card_erase_of_mem (finset.mem_univ _), }, }, { dsimp [is_regular_of_degree, degree] at hd, rw hd, } end lemma exists_politician_of_degree_eq_two (hd : G.is_regular_of_degree 2) : exists_politician G := begin have v := classical.arbitrary V, use v, intros w hvw, rw [← mem_neighbor_finset, neighbor_finset_eq_of_degree_eq_two hG hd v, finset.mem_erase], exact ⟨hvw.symm, finset.mem_univ _⟩, end lemma exists_politician_of_degree_le_two (hd : G.is_regular_of_degree d) (h : d ≤ 2) : exists_politician G := begin interval_cases d, iterate 2 { apply exists_politician_of_degree_le_one hG hd, norm_num }, { exact exists_politician_of_degree_eq_two hG hd }, end end friendship /-- We wish to show that a friendship graph has a politician (a vertex adjacent to all others). We proceed by contradiction, and assume the graph has no politician. We have already proven that a friendship graph with no politician is `d`-regular for some `d`, and now we do casework on `d`. If the degree is at most 2, we observe by casework that it has a politician anyway. If the degree is at least 3, the graph cannot exist. -/ theorem friendship_theorem [nonempty V] : exists_politician G := begin by_contradiction npG, rcases hG.is_regular_of_not_exists_politician npG with ⟨d, dreg⟩, cases lt_or_le d 3 with dle2 dge3, { exact npG (hG.exists_politician_of_degree_le_two dreg (nat.lt_succ_iff.mp dle2)) }, { exact hG.false_of_three_le_degree dreg dge3 }, end
c296064929d6bb5100482e23457ba1c69bc66443
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/group/ext.lean
94cd7bb95a965564756919fe9231ec60b91e503e
[ "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
5,125
lean
/- Copyright (c) 2021 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bryan Gin-ge Chen, Yury Kudryashov -/ import algebra.hom.group /-! # Extensionality lemmas for monoid and group structures > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove extensionality lemmas for `monoid` and higher algebraic structures with one binary operation. Extensionality lemmas for structures that are lower in the hierarchy can be found in `algebra.group.defs`. ## Implementation details To get equality of `npow` etc, we define a monoid homomorphism between two monoid structures on the same type, then apply lemmas like `monoid_hom.map_div`, `monoid_hom.map_pow` etc. ## Tags monoid, group, extensionality -/ universe u @[ext, to_additive] lemma monoid.ext {M : Type u} ⦃m₁ m₂ : monoid M⦄ (h_mul : m₁.mul = m₂.mul) : m₁ = m₂ := begin have h₁ : (@monoid.to_mul_one_class _ m₁).one = (@monoid.to_mul_one_class _ m₂).one, from congr_arg (@mul_one_class.one M) (mul_one_class.ext h_mul), set f : @monoid_hom M M (@monoid.to_mul_one_class _ m₁) (@monoid.to_mul_one_class _ m₂) := { to_fun := id, map_one' := h₁, map_mul' := λ x y, congr_fun (congr_fun h_mul x) y }, have hpow : m₁.npow = m₂.npow, by { ext n x, exact @monoid_hom.map_pow M M m₁ m₂ f x n }, unfreezingI { cases m₁, cases m₂ }, congr; assumption end @[to_additive] lemma comm_monoid.to_monoid_injective {M : Type u} : function.injective (@comm_monoid.to_monoid M) := begin rintros ⟨⟩ ⟨⟩ h, congr'; injection h, end @[ext, to_additive] lemma comm_monoid.ext {M : Type*} ⦃m₁ m₂ : comm_monoid M⦄ (h_mul : m₁.mul = m₂.mul) : m₁ = m₂ := comm_monoid.to_monoid_injective $ monoid.ext h_mul @[to_additive] lemma left_cancel_monoid.to_monoid_injective {M : Type u} : function.injective (@left_cancel_monoid.to_monoid M) := begin rintros ⟨⟩ ⟨⟩ h, congr'; injection h, end @[ext, to_additive] lemma left_cancel_monoid.ext {M : Type u} ⦃m₁ m₂ : left_cancel_monoid M⦄ (h_mul : m₁.mul = m₂.mul) : m₁ = m₂ := left_cancel_monoid.to_monoid_injective $ monoid.ext h_mul @[to_additive] lemma right_cancel_monoid.to_monoid_injective {M : Type u} : function.injective (@right_cancel_monoid.to_monoid M) := begin rintros ⟨⟩ ⟨⟩ h, congr'; injection h, end @[ext, to_additive] lemma right_cancel_monoid.ext {M : Type u} ⦃m₁ m₂ : right_cancel_monoid M⦄ (h_mul : m₁.mul = m₂.mul) : m₁ = m₂ := right_cancel_monoid.to_monoid_injective $ monoid.ext h_mul @[to_additive] lemma cancel_monoid.to_left_cancel_monoid_injective {M : Type u} : function.injective (@cancel_monoid.to_left_cancel_monoid M) := begin rintros ⟨⟩ ⟨⟩ h, congr'; injection h, end @[ext, to_additive] lemma cancel_monoid.ext {M : Type*} ⦃m₁ m₂ : cancel_monoid M⦄ (h_mul : m₁.mul = m₂.mul) : m₁ = m₂ := cancel_monoid.to_left_cancel_monoid_injective $ left_cancel_monoid.ext h_mul @[to_additive] lemma cancel_comm_monoid.to_comm_monoid_injective {M : Type u} : function.injective (@cancel_comm_monoid.to_comm_monoid M) := begin rintros ⟨⟩ ⟨⟩ h, congr'; injection h, end @[ext, to_additive] lemma cancel_comm_monoid.ext {M : Type*} ⦃m₁ m₂ : cancel_comm_monoid M⦄ (h_mul : m₁.mul = m₂.mul) : m₁ = m₂ := cancel_comm_monoid.to_comm_monoid_injective $ comm_monoid.ext h_mul @[ext, to_additive] lemma div_inv_monoid.ext {M : Type*} ⦃m₁ m₂ : div_inv_monoid M⦄ (h_mul : m₁.mul = m₂.mul) (h_inv : m₁.inv = m₂.inv) : m₁ = m₂ := begin have h₁ : (@div_inv_monoid.to_monoid _ m₁).one = (@div_inv_monoid.to_monoid _ m₂).one, from congr_arg (@monoid.one M) (monoid.ext h_mul), set f : @monoid_hom M M (by letI := m₁; apply_instance) (by letI := m₂; apply_instance) := { to_fun := id, map_one' := h₁, map_mul' := λ x y, congr_fun (congr_fun h_mul x) y }, have hpow : (@div_inv_monoid.to_monoid _ m₁).npow = (@div_inv_monoid.to_monoid _ m₂).npow := congr_arg (@monoid.npow M) (monoid.ext h_mul), have hzpow : m₁.zpow = m₂.zpow, { ext m x, exact @monoid_hom.map_zpow' M M m₁ m₂ f (congr_fun h_inv) x m }, have hdiv : m₁.div = m₂.div, { ext a b, exact @map_div' M M _ m₁ m₂ _ f (congr_fun h_inv) a b }, unfreezingI { cases m₁, cases m₂ }, congr, exacts [h_mul, h₁, hpow, h_inv, hdiv, hzpow] end @[ext, to_additive] lemma group.ext {G : Type*} ⦃g₁ g₂ : group G⦄ (h_mul : g₁.mul = g₂.mul) : g₁ = g₂ := begin set f := @monoid_hom.mk' G G (by letI := g₁; apply_instance) g₂ id (λ a b, congr_fun (congr_fun h_mul a) b), exact group.to_div_inv_monoid_injective (div_inv_monoid.ext h_mul (funext $ @monoid_hom.map_inv G G g₁ (@group.to_division_monoid _ g₂) f)) end @[ext, to_additive] lemma comm_group.ext {G : Type*} ⦃g₁ g₂ : comm_group G⦄ (h_mul : g₁.mul = g₂.mul) : g₁ = g₂ := comm_group.to_group_injective $ group.ext h_mul
54d7007b0f87e74ae51e84484be937f0d849b6ef
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/box_integral/partition/tagged.lean
ea6c3b12ebe9b2f841502437a158e316e52c0467
[ "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
16,128
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.partition.basic /-! # Tagged partitions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A tagged (pre)partition is a (pre)partition `π` enriched with a tagged point for each box of ‵π`. For simplicity we require that the function `box_integral.tagged_prepartition.tag` is defined on all boxes `J : box ι` but use its values only on boxes of the partition. Given `π : box_integral.tagged_partition I`, we require that each `box_integral.tagged_partition π J` belongs to `box_integral.box.Icc I`. If for every `J ∈ π`, `π.tag J` belongs to `J.Icc`, then `π` is called a *Henstock* partition. We do not include this assumption into the definition of a tagged (pre)partition because McShane integral is defined as a limit along tagged partitions without this requirement. ### Tags rectangular box, box partition -/ noncomputable theory open_locale classical ennreal nnreal open set function namespace box_integral variables {ι : Type*} /-- A tagged prepartition is a prepartition enriched with a tagged point for each box of the prepartition. For simiplicity we require that `tag` is defined for all boxes in `ι → ℝ` but we will use onle the values of `tag` on the boxes of the partition. -/ structure tagged_prepartition (I : box ι) extends prepartition I := (tag : box ι → ι → ℝ) (tag_mem_Icc : ∀ J, tag J ∈ I.Icc) namespace tagged_prepartition variables {I J J₁ J₂ : box ι} (π : tagged_prepartition I) {x : ι → ℝ} instance : has_mem (box ι) (tagged_prepartition I) := ⟨λ J π, J ∈ π.boxes⟩ @[simp] lemma mem_to_prepartition {π : tagged_prepartition I} : J ∈ π.to_prepartition ↔ J ∈ π := iff.rfl @[simp] lemma mem_mk (π : prepartition I) (f h) : J ∈ mk π f h ↔ J ∈ π := iff.rfl /-- Union of all boxes of a tagged prepartition. -/ def Union : set (ι → ℝ) := π.to_prepartition.Union lemma Union_def : π.Union = ⋃ J ∈ π, ↑J := rfl @[simp] lemma Union_mk (π : prepartition I) (f h) : (mk π f h).Union = π.Union := rfl @[simp] lemma Union_to_prepartition : π.to_prepartition.Union = π.Union := rfl @[simp] lemma mem_Union : x ∈ π.Union ↔ ∃ J ∈ π, x ∈ J := set.mem_Union₂ lemma subset_Union (h : J ∈ π) : ↑J ⊆ π.Union := subset_bUnion_of_mem h lemma Union_subset : π.Union ⊆ I := Union₂_subset π.le_of_mem' /-- A tagged prepartition is a partition if it covers the whole box. -/ def is_partition := π.to_prepartition.is_partition lemma is_partition_iff_Union_eq : is_partition π ↔ π.Union = I := prepartition.is_partition_iff_Union_eq /-- The tagged partition made of boxes of `π` that satisfy predicate `p`. -/ @[simps { fully_applied := ff }] def filter (p : box ι → Prop) : tagged_prepartition I := ⟨π.1.filter p, π.2, π.3⟩ @[simp] lemma mem_filter {p : box ι → Prop} : J ∈ π.filter p ↔ J ∈ π ∧ p J := finset.mem_filter @[simp] lemma Union_filter_not (π : tagged_prepartition I) (p : box ι → Prop) : (π.filter (λ J, ¬p J)).Union = π.Union \ (π.filter p).Union := π.to_prepartition.Union_filter_not p end tagged_prepartition namespace prepartition variables {I J : box ι} /-- Given a partition `π` of `I : box_integral.box ι` and a collection of tagged partitions `πi J` of all boxes `J ∈ π`, returns the tagged partition of `I` into all the boxes of `πi J` with tags coming from `(πi J).tag`. -/ def bUnion_tagged (π : prepartition I) (πi : Π J, tagged_prepartition J) : tagged_prepartition I := { to_prepartition := π.bUnion (λ J, (πi J).to_prepartition), tag := λ J, (πi (π.bUnion_index (λ J, (πi J).to_prepartition) J)).tag J, tag_mem_Icc := λ J, box.le_iff_Icc.1 (π.bUnion_index_le _ _) ((πi _).tag_mem_Icc _) } @[simp] lemma mem_bUnion_tagged (π : prepartition I) {πi : Π J, tagged_prepartition J} : J ∈ π.bUnion_tagged πi ↔ ∃ J' ∈ π, J ∈ πi J' := π.mem_bUnion lemma tag_bUnion_tagged (π : prepartition I) {πi : Π J, tagged_prepartition J} (hJ : J ∈ π) {J'} (hJ' : J' ∈ πi J) : (π.bUnion_tagged πi).tag J' = (πi J).tag J' := begin have : J' ∈ π.bUnion_tagged πi, from π.mem_bUnion.2 ⟨J, hJ, hJ'⟩, obtain rfl := π.bUnion_index_of_mem hJ hJ', refl end @[simp] lemma Union_bUnion_tagged (π : prepartition I) (πi : Π J, tagged_prepartition J) : (π.bUnion_tagged πi).Union = ⋃ J ∈ π, (πi J).Union := Union_bUnion _ _ lemma forall_bUnion_tagged (p : (ι → ℝ) → box ι → Prop) (π : prepartition I) (πi : Π J, tagged_prepartition J) : (∀ J ∈ π.bUnion_tagged πi, p ((π.bUnion_tagged πi).tag J) J) ↔ ∀ (J ∈ π) (J' ∈ πi J), p ((πi J).tag J') J' := begin simp only [bex_imp_distrib, mem_bUnion_tagged], refine ⟨λ H J hJ J' hJ', _, λ H J' J hJ hJ', _⟩, { rw ← π.tag_bUnion_tagged hJ hJ', exact H J' J hJ hJ' }, { rw π.tag_bUnion_tagged hJ hJ', exact H J hJ J' hJ' } end lemma is_partition.bUnion_tagged {π : prepartition I} (h : is_partition π) {πi : Π J, tagged_prepartition J} (hi : ∀ J ∈ π, (πi J).is_partition) : (π.bUnion_tagged πi).is_partition := h.bUnion hi end prepartition namespace tagged_prepartition variables {I J : box ι} {π π₁ π₂ : tagged_prepartition I} {x : ι → ℝ} /-- Given a tagged partition `π` of `I` and a (not tagged) partition `πi J hJ` of each `J ∈ π`, returns the tagged partition of `I` into all the boxes of all `πi J hJ`. The tag of a box `J` is defined to be the `π.tag` of the box of the partition `π` that includes `J`. Note that usually the result is not a Henstock partition. -/ @[simps tag { fully_applied := ff }] def bUnion_prepartition (π : tagged_prepartition I) (πi : Π J, prepartition J) : tagged_prepartition I := { to_prepartition := π.to_prepartition.bUnion πi, tag := λ J, π.tag (π.to_prepartition.bUnion_index πi J), tag_mem_Icc := λ J, π.tag_mem_Icc _ } lemma is_partition.bUnion_prepartition {π : tagged_prepartition I} (h : is_partition π) {πi : Π J, prepartition J} (hi : ∀ J ∈ π, (πi J).is_partition) : (π.bUnion_prepartition πi).is_partition := h.bUnion hi /-- Given two partitions `π₁` and `π₁`, one of them tagged and the other is not, returns the tagged partition with `to_partition = π₁.to_partition ⊓ π₂` and tags coming from `π₁`. Note that usually the result is not a Henstock partition. -/ def inf_prepartition (π : tagged_prepartition I) (π' : prepartition I) : tagged_prepartition I := π.bUnion_prepartition $ λ J, π'.restrict J @[simp] lemma inf_prepartition_to_prepartition (π : tagged_prepartition I) (π' : prepartition I) : (π.inf_prepartition π').to_prepartition = π.to_prepartition ⊓ π' := rfl lemma mem_inf_prepartition_comm : J ∈ π₁.inf_prepartition π₂.to_prepartition ↔ J ∈ π₂.inf_prepartition π₁.to_prepartition := by simp only [← mem_to_prepartition, inf_prepartition_to_prepartition, inf_comm] lemma is_partition.inf_prepartition (h₁ : π₁.is_partition) {π₂ : prepartition I} (h₂ : π₂.is_partition) : (π₁.inf_prepartition π₂).is_partition := h₁.inf h₂ open metric /-- A tagged partition is said to be a Henstock partition if for each `J ∈ π`, the tag of `J` belongs to `J.Icc`. -/ def is_Henstock (π : tagged_prepartition I) : Prop := ∀ J ∈ π, π.tag J ∈ J.Icc @[simp] lemma is_Henstock_bUnion_tagged {π : prepartition I} {πi : Π J, tagged_prepartition J} : is_Henstock (π.bUnion_tagged πi) ↔ ∀ J ∈ π, (πi J).is_Henstock := π.forall_bUnion_tagged (λ x J, x ∈ J.Icc) πi /-- In a Henstock prepartition, there are at most `2 ^ fintype.card ι` boxes with a given tag. -/ lemma is_Henstock.card_filter_tag_eq_le [fintype ι] (h : π.is_Henstock) (x : ι → ℝ) : (π.boxes.filter (λ J, π.tag J = x)).card ≤ 2 ^ fintype.card ι := calc (π.boxes.filter (λ J, π.tag J = x)).card ≤ (π.boxes.filter (λ J : box ι, x ∈ J.Icc)).card : begin refine finset.card_le_of_subset (λ J hJ, _), rw finset.mem_filter at hJ ⊢, rcases hJ with ⟨hJ, rfl⟩, exact ⟨hJ, h J hJ⟩ end ... ≤ 2 ^ fintype.card ι : π.to_prepartition.card_filter_mem_Icc_le x /-- A tagged partition `π` is subordinate to `r : (ι → ℝ) → ℝ` if each box `J ∈ π` is included in the closed ball with center `π.tag J` and radius `r (π.tag J)`. -/ def is_subordinate [fintype ι] (π : tagged_prepartition I) (r : (ι → ℝ) → Ioi (0 : ℝ)) : Prop := ∀ J ∈ π, (J : _).Icc ⊆ closed_ball (π.tag J) (r $ π.tag J) variables {r r₁ r₂ : (ι → ℝ) → Ioi (0 : ℝ)} @[simp] lemma is_subordinate_bUnion_tagged [fintype ι] {π : prepartition I} {πi : Π J, tagged_prepartition J} : is_subordinate (π.bUnion_tagged πi) r ↔ ∀ J ∈ π, (πi J).is_subordinate r := π.forall_bUnion_tagged (λ x J, J.Icc ⊆ closed_ball x (r x)) πi lemma is_subordinate.bUnion_prepartition [fintype ι] (h : is_subordinate π r) (πi : Π J, prepartition J) : is_subordinate (π.bUnion_prepartition πi) r := λ J hJ, subset.trans (box.le_iff_Icc.1 $ π.to_prepartition.le_bUnion_index hJ) $ h _ $ π.to_prepartition.bUnion_index_mem hJ lemma is_subordinate.inf_prepartition [fintype ι] (h : is_subordinate π r) (π' : prepartition I) : is_subordinate (π.inf_prepartition π') r := h.bUnion_prepartition _ lemma is_subordinate.mono' [fintype ι] {π : tagged_prepartition I} (hr₁ : π.is_subordinate r₁) (h : ∀ J ∈ π, r₁ (π.tag J) ≤ r₂ (π.tag J)) : π.is_subordinate r₂ := λ J hJ x hx, closed_ball_subset_closed_ball (h _ hJ) (hr₁ _ hJ hx) lemma is_subordinate.mono [fintype ι] {π : tagged_prepartition I} (hr₁ : π.is_subordinate r₁) (h : ∀ x ∈ I.Icc, r₁ x ≤ r₂ x) : π.is_subordinate r₂ := hr₁.mono' $ λ J _, h _ $ π.tag_mem_Icc J lemma is_subordinate.diam_le [fintype ι] {π : tagged_prepartition I} (h : π.is_subordinate r) (hJ : J ∈ π.boxes) : diam J.Icc ≤ 2 * r (π.tag J) := calc diam J.Icc ≤ diam (closed_ball (π.tag J) (r $ π.tag J)) : diam_mono (h J hJ) bounded_closed_ball ... ≤ 2 * r (π.tag J) : diam_closed_ball (le_of_lt (r _).2) /-- Tagged prepartition with single box and prescribed tag. -/ @[simps { fully_applied := ff }] def single (I J : box ι) (hJ : J ≤ I) (x : ι → ℝ) (h : x ∈ I.Icc) : tagged_prepartition I := ⟨prepartition.single I J hJ, λ J, x, λ J, h⟩ @[simp] lemma mem_single {J'} (hJ : J ≤ I) (h : x ∈ I.Icc) : J' ∈ single I J hJ x h ↔ J' = J := finset.mem_singleton instance (I : box ι) : inhabited (tagged_prepartition I) := ⟨single I I le_rfl I.upper I.upper_mem_Icc⟩ lemma is_partition_single_iff (hJ : J ≤ I) (h : x ∈ I.Icc) : (single I J hJ x h).is_partition ↔ J = I := prepartition.is_partition_single_iff hJ lemma is_partition_single (h : x ∈ I.Icc) : (single I I le_rfl x h).is_partition := prepartition.is_partition_top I lemma forall_mem_single (p : (ι → ℝ) → (box ι) → Prop) (hJ : J ≤ I) (h : x ∈ I.Icc) : (∀ J' ∈ single I J hJ x h, p ((single I J hJ x h).tag J') J') ↔ p x J := by simp @[simp] lemma is_Henstock_single_iff (hJ : J ≤ I) (h : x ∈ I.Icc) : is_Henstock (single I J hJ x h) ↔ x ∈ J.Icc := forall_mem_single (λ x J, x ∈ J.Icc) hJ h @[simp] lemma is_Henstock_single (h : x ∈ I.Icc) : is_Henstock (single I I le_rfl x h) := (is_Henstock_single_iff (le_refl I) h).2 h @[simp] lemma is_subordinate_single [fintype ι] (hJ : J ≤ I) (h : x ∈ I.Icc) : is_subordinate (single I J hJ x h) r ↔ J.Icc ⊆ closed_ball x (r x) := forall_mem_single (λ x J, J.Icc ⊆ closed_ball x (r x)) hJ h @[simp] lemma Union_single (hJ : J ≤ I) (h : x ∈ I.Icc) : (single I J hJ x h).Union = J := prepartition.Union_single hJ /-- Union of two tagged prepartitions with disjoint unions of boxes. -/ def disj_union (π₁ π₂ : tagged_prepartition I) (h : disjoint π₁.Union π₂.Union) : tagged_prepartition I := { to_prepartition := π₁.to_prepartition.disj_union π₂.to_prepartition h, tag := π₁.boxes.piecewise π₁.tag π₂.tag, tag_mem_Icc := λ J, by { dunfold finset.piecewise, split_ifs, exacts [π₁.tag_mem_Icc J, π₂.tag_mem_Icc J] } } @[simp] lemma disj_union_boxes (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).boxes = π₁.boxes ∪ π₂.boxes := rfl @[simp] lemma mem_disj_union (h : disjoint π₁.Union π₂.Union) : J ∈ π₁.disj_union π₂ h ↔ J ∈ π₁ ∨ J ∈ π₂ := finset.mem_union @[simp] lemma Union_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).Union = π₁.Union ∪ π₂.Union := prepartition.Union_disj_union _ lemma disj_union_tag_of_mem_left (h : disjoint π₁.Union π₂.Union) (hJ : J ∈ π₁) : (π₁.disj_union π₂ h).tag J = π₁.tag J := dif_pos hJ lemma disj_union_tag_of_mem_right (h : disjoint π₁.Union π₂.Union) (hJ : J ∈ π₂) : (π₁.disj_union π₂ h).tag J = π₂.tag J := dif_neg $ λ h₁, h.le_bot ⟨π₁.subset_Union h₁ J.upper_mem, π₂.subset_Union hJ J.upper_mem⟩ lemma is_subordinate.disj_union [fintype ι] (h₁ : is_subordinate π₁ r) (h₂ : is_subordinate π₂ r) (h : disjoint π₁.Union π₂.Union) : is_subordinate (π₁.disj_union π₂ h) r := begin refine λ J hJ, (finset.mem_union.1 hJ).elim (λ hJ, _) (λ hJ, _), { rw disj_union_tag_of_mem_left _ hJ, exact h₁ _ hJ }, { rw disj_union_tag_of_mem_right _ hJ, exact h₂ _ hJ } end lemma is_Henstock.disj_union (h₁ : is_Henstock π₁) (h₂ : is_Henstock π₂) (h : disjoint π₁.Union π₂.Union) : is_Henstock (π₁.disj_union π₂ h) := begin refine λ J hJ, (finset.mem_union.1 hJ).elim (λ hJ, _) (λ hJ, _), { rw disj_union_tag_of_mem_left _ hJ, exact h₁ _ hJ }, { rw disj_union_tag_of_mem_right _ hJ, exact h₂ _ hJ } end /-- If `I ≤ J`, then every tagged prepartition of `I` is a tagged prepartition of `J`. -/ def embed_box (I J : box ι) (h : I ≤ J) : tagged_prepartition I ↪ tagged_prepartition J := { to_fun := λ π, { le_of_mem' := λ J' hJ', (π.le_of_mem' J' hJ').trans h, tag_mem_Icc := λ J, box.le_iff_Icc.1 h (π.tag_mem_Icc J), .. π }, inj' := by { rintro ⟨⟨b₁, h₁le, h₁d⟩, t₁, ht₁⟩ ⟨⟨b₂, h₂le, h₂d⟩, t₂, ht₂⟩ H, simpa using H } } section distortion variables [fintype ι] (π) open finset /-- The distortion of a tagged prepartition is the maximum of distortions of its boxes. -/ def distortion : ℝ≥0 := π.to_prepartition.distortion lemma distortion_le_of_mem (h : J ∈ π) : J.distortion ≤ π.distortion := le_sup h lemma distortion_le_iff {c : ℝ≥0} : π.distortion ≤ c ↔ ∀ J ∈ π, box.distortion J ≤ c := finset.sup_le_iff @[simp] lemma _root_.box_integral.prepartition.distortion_bUnion_tagged (π : prepartition I) (πi : Π J, tagged_prepartition J) : (π.bUnion_tagged πi).distortion = π.boxes.sup (λ J, (πi J).distortion) := sup_bUnion _ _ @[simp] lemma distortion_bUnion_prepartition (π : tagged_prepartition I) (πi : Π J, prepartition J) : (π.bUnion_prepartition πi).distortion = π.boxes.sup (λ J, (πi J).distortion) := sup_bUnion _ _ @[simp] lemma distortion_disj_union (h : disjoint π₁.Union π₂.Union) : (π₁.disj_union π₂ h).distortion = max π₁.distortion π₂.distortion := sup_union lemma distortion_of_const {c} (h₁ : π.boxes.nonempty) (h₂ : ∀ J ∈ π, box.distortion J = c) : π.distortion = c := (sup_congr rfl h₂).trans (sup_const h₁ _) @[simp] lemma distortion_single (hJ : J ≤ I) (h : x ∈ I.Icc) : distortion (single I J hJ x h) = J.distortion := sup_singleton lemma distortion_filter_le (p : box ι → Prop) : (π.filter p).distortion ≤ π.distortion := sup_mono (filter_subset _ _) end distortion end tagged_prepartition end box_integral
22f772fc5950c21d7b2fe298039ef70f68f5549d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/closure_auto.lean
3d2c162b2709abf22f4086770dcd607699fa24ac
[]
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
7,574
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.basic import Mathlib.order.preorder_hom import Mathlib.order.galois_connection import Mathlib.tactic.monotonicity.default import Mathlib.PostPort universes u l namespace Mathlib /-! # Closure operators on a partial order We define (bundled) closure operators on a partial order as an monotone (increasing), extensive (inflationary) and idempotent function. We define closed elements for the operator as elements which are fixed by it. Note that there is close connection to Galois connections and Galois insertions: every closure operator induces a Galois insertion (from the set of closed elements to the underlying type), and every Galois connection induces a closure operator (namely the composition). In particular, a Galois insertion can be seen as a general case of a closure operator, where the inclusion is given by coercion, see `closure_operator.gi`. ## References * https://en.wikipedia.org/wiki/Closure_operator#Closure_operators_on_partially_ordered_sets -/ /-- A closure operator on the partial order `α` is a monotone function which is extensive (every `x` is less than its closure) and idempotent. -/ structure closure_operator (α : Type u) [partial_order α] extends α →ₘ α where le_closure' : ∀ (x : α), x ≤ preorder_hom.to_fun _to_preorder_hom x idempotent' : ∀ (x : α), preorder_hom.to_fun _to_preorder_hom (preorder_hom.to_fun _to_preorder_hom x) = preorder_hom.to_fun _to_preorder_hom x protected instance closure_operator.has_coe_to_fun (α : Type u) [partial_order α] : has_coe_to_fun (closure_operator α) := has_coe_to_fun.mk (fun (c : closure_operator α) => α → α) fun (c : closure_operator α) => preorder_hom.to_fun (closure_operator.to_preorder_hom c) namespace closure_operator /-- The identity function as a closure operator. -/ @[simp] theorem id_to_preorder_hom_to_fun (α : Type u) [partial_order α] (x : α) : coe_fn (to_preorder_hom (id α)) x = x := Eq.refl (coe_fn (to_preorder_hom (id α)) x) protected instance inhabited (α : Type u) [partial_order α] : Inhabited (closure_operator α) := { default := id α } theorem ext {α : Type u} [partial_order α] (c₁ : closure_operator α) (c₂ : closure_operator α) : ⇑c₁ = ⇑c₂ → c₁ = c₂ := sorry /-- Constructor for a closure operator using the weaker idempotency axiom: `f (f x) ≤ f x`. -/ def mk' {α : Type u} [partial_order α] (f : α → α) (hf₁ : monotone f) (hf₂ : ∀ (x : α), x ≤ f x) (hf₃ : ∀ (x : α), f (f x) ≤ f x) : closure_operator α := mk (preorder_hom.mk f hf₁) hf₂ sorry /-- theorem monotone {α : Type u} [partial_order α] (c : closure_operator α) : monotone ⇑c := preorder_hom.monotone' (to_preorder_hom c) Every element is less than its closure. This property is sometimes referred to as extensivity or inflationary. -/ theorem le_closure {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : x ≤ coe_fn c x := le_closure' c x @[simp] theorem idempotent {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : coe_fn c (coe_fn c x) = coe_fn c x := idempotent' c x theorem le_closure_iff {α : Type u} [partial_order α] (c : closure_operator α) (x : α) (y : α) : x ≤ coe_fn c y ↔ coe_fn c x ≤ coe_fn c y := { mp := fun (h : x ≤ coe_fn c y) => idempotent c y ▸ monotone c h, mpr := fun (h : coe_fn c x ≤ coe_fn c y) => le_trans (le_closure c x) h } theorem closure_top {α : Type u} [order_top α] (c : closure_operator α) : coe_fn c ⊤ = ⊤ := le_antisymm le_top (le_closure c ⊤) theorem closure_inter_le {α : Type u} [semilattice_inf α] (c : closure_operator α) (x : α) (y : α) : coe_fn c (x ⊓ y) ≤ coe_fn c x ⊓ coe_fn c y := le_inf (monotone c inf_le_left) (monotone c inf_le_right) theorem closure_union_closure_le {α : Type u} [semilattice_sup α] (c : closure_operator α) (x : α) (y : α) : coe_fn c x ⊔ coe_fn c y ≤ coe_fn c (x ⊔ y) := sup_le (monotone c le_sup_left) (monotone c le_sup_right) /-- An element `x` is closed for the closure operator `c` if it is a fixed point for it. -/ def closed {α : Type u} [partial_order α] (c : closure_operator α) : set α := fun (x : α) => coe_fn c x = x theorem mem_closed_iff {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : x ∈ closed c ↔ coe_fn c x = x := iff.rfl theorem mem_closed_iff_closure_le {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : x ∈ closed c ↔ coe_fn c x ≤ x := { mp := le_of_eq, mpr := fun (h : coe_fn c x ≤ x) => le_antisymm h (le_closure c x) } theorem closure_eq_self_of_mem_closed {α : Type u} [partial_order α] (c : closure_operator α) {x : α} (h : x ∈ closed c) : coe_fn c x = x := h @[simp] theorem closure_is_closed {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : coe_fn c x ∈ closed c := idempotent c x /-- The set of closed elements for `c` is exactly its range. -/ theorem closed_eq_range_close {α : Type u} [partial_order α] (c : closure_operator α) : closed c = set.range ⇑c := sorry /-- Send an `x` to an element of the set of closed elements (by taking the closure). -/ def to_closed {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : ↥(closed c) := { val := coe_fn c x, property := closure_is_closed c x } theorem top_mem_closed {α : Type u} [order_top α] (c : closure_operator α) : ⊤ ∈ closed c := closure_top c theorem closure_le_closed_iff_le {α : Type u} [partial_order α] (c : closure_operator α) {x : α} {y : α} (hy : closed c y) : x ≤ y ↔ coe_fn c x ≤ y := eq.mpr (id (Eq._oldrec (Eq.refl (x ≤ y ↔ coe_fn c x ≤ y)) (Eq.symm (closure_eq_self_of_mem_closed c hy)))) (eq.mpr (id (Eq._oldrec (Eq.refl (x ≤ coe_fn c y ↔ coe_fn c x ≤ coe_fn c y)) (propext (le_closure_iff c x y)))) (iff.refl (coe_fn c x ≤ coe_fn c y))) /-- The set of closed elements has a Galois insertion to the underlying type. -/ def gi {α : Type u} [partial_order α] (c : closure_operator α) : galois_insertion (to_closed c) coe := galois_insertion.mk (fun (x : α) (hx : ↑(to_closed c x) ≤ x) => { val := x, property := sorry }) sorry sorry sorry end closure_operator /-- Every Galois connection induces a closure operator given by the composition. This is the partial order version of the statement that every adjunction induces a monad. -/ @[simp] theorem galois_connection.closure_operator_to_preorder_hom_to_fun {α : Type u} [partial_order α] {β : Type u} [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) (x : α) : coe_fn (closure_operator.to_preorder_hom (galois_connection.closure_operator gc)) x = u (l x) := Eq.refl (coe_fn (closure_operator.to_preorder_hom (galois_connection.closure_operator gc)) x) /-- The Galois insertion associated to a closure operator can be used to reconstruct the closure operator. Note that the inverse in the opposite direction does not hold in general. -/ @[simp] theorem closure_operator_gi_self {α : Type u} [partial_order α] (c : closure_operator α) : galois_connection.closure_operator (galois_insertion.gc (closure_operator.gi c)) = c := sorry end Mathlib
5d7d456e065de586831991f06c80440bf0fbacdc
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/ring_theory/power_basis.lean
b4534d0d39f2dd7045ecb49e24f34cf8471fad3e
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,372
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.minpoly /-! # Power basis This file defines a structure `power_basis R S`, giving a basis of the `R`-algebra `S` as a finite list of powers `1, x, ..., x^n`. For example, if `x` is algebraic over a ring/field, adjoining `x` gives a `power_basis` structure generated by `x`. ## Definitions * `power_basis R A`: a structure containing an `x` and an `n` such that `1, x, ..., x^n` is a basis for the `R`-algebra `A` (viewed as an `R`-module). * `finrank (hf : f ≠ 0) : finite_dimensional.finrank K (adjoin_root f) = f.nat_degree`, the dimension of `adjoin_root f` equals the degree of `f` * `power_basis.lift (pb : power_basis R S)`: if `y : S'` satisfies the same equations as `pb.gen`, this is the map `S →ₐ[R] S'` sending `pb.gen` to `y` * `power_basis.equiv`: if two power bases satisfy the same equations, they are equivalent as algebras ## Implementation notes Throughout this file, `R`, `S`, ... are `comm_ring`s, `A`, `B`, ... are `integral_domain`s and `K`, `L`, ... are `field`s. `S` is an `R`-algebra, `B` is an `A`-algebra, `L` is a `K`-algebra. ## Tags power basis, powerbasis -/ open polynomial variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T] variables [algebra R S] [algebra S T] [algebra R T] [is_scalar_tower R S T] variables {A B : Type*} [integral_domain A] [integral_domain B] [algebra A B] variables {K L : Type*} [field K] [field L] [algebra K L] /-- `pb : power_basis R S` states that `1, pb.gen, ..., pb.gen ^ (pb.dim - 1)` is a basis for the `R`-algebra `S` (viewed as `R`-module). This is a structure, not a class, since the same algebra can have many power bases. For the common case where `S` is defined by adjoining an integral element to `R`, the canonical power basis is given by `{algebra,intermediate_field}.adjoin.power_basis`. -/ @[nolint has_inhabited_instance] structure power_basis (R S : Type*) [comm_ring R] [ring S] [algebra R S] := (gen : S) (dim : ℕ) (basis : basis (fin dim) R S) (basis_eq_pow : ∀ i, basis i = gen ^ (i : ℕ)) namespace power_basis @[simp] lemma coe_basis (pb : power_basis R S) : ⇑pb.basis = λ (i : fin pb.dim), pb.gen ^ (i : ℕ) := funext pb.basis_eq_pow /-- Cannot be an instance because `power_basis` cannot be a class. -/ lemma finite_dimensional [algebra K S] (pb : power_basis K S) : finite_dimensional K S := finite_dimensional.of_fintype_basis pb.basis lemma finrank [algebra K S] (pb : power_basis K S) : finite_dimensional.finrank K S = pb.dim := by rw [finite_dimensional.finrank_eq_card_basis pb.basis, fintype.card_fin] lemma mem_span_pow' {x y : S} {d : ℕ} : y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔ ∃ f : polynomial R, f.degree < d ∧ y = aeval x f := begin have : set.range (λ (i : fin d), x ^ (i : ℕ)) = (λ (i : ℕ), x ^ i) '' ↑(finset.range d), { ext n, simp_rw [set.mem_range, set.mem_image, finset.mem_coe, finset.mem_range], exact ⟨λ ⟨⟨i, hi⟩, hy⟩, ⟨i, hi, hy⟩, λ ⟨i, hi, hy⟩, ⟨⟨i, hi⟩, hy⟩⟩ }, simp only [this, finsupp.mem_span_image_iff_total, degree_lt_iff_coeff_zero, exists_iff_exists_finsupp, coeff, aeval, eval₂_ring_hom', eval₂_eq_sum, polynomial.sum, support, finsupp.mem_supported', finsupp.total, finsupp.sum, algebra.smul_def, eval₂_zero, exists_prop, linear_map.id_coe, eval₂_one, id.def, not_lt, finsupp.coe_lsum, linear_map.coe_smul_right, finset.mem_range, alg_hom.coe_mk, finset.mem_coe], simp_rw [@eq_comm _ y], exact iff.rfl end lemma mem_span_pow {x y : S} {d : ℕ} (hd : d ≠ 0) : y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔ ∃ f : polynomial R, f.nat_degree < d ∧ y = aeval x f := begin rw mem_span_pow', split; { rintros ⟨f, h, hy⟩, refine ⟨f, _, hy⟩, by_cases hf : f = 0, { simp only [hf, nat_degree_zero, degree_zero] at h ⊢, exact lt_of_le_of_ne (nat.zero_le d) hd.symm <|> exact with_bot.bot_lt_some d }, simpa only [degree_eq_nat_degree hf, with_bot.coe_lt_coe] using h }, end lemma dim_ne_zero [nontrivial S] (pb : power_basis R S) : pb.dim ≠ 0 := λ h, one_ne_zero $ show (1 : S) = 0, by { rw [← pb.basis.total_repr 1, finsupp.total_apply, finsupp.sum_fintype], { refine finset.sum_eq_zero (λ x hx, _), cases x with x x_lt, rw h at x_lt, cases x_lt }, { simp } } lemma dim_pos [nontrivial S] (pb : power_basis R S) : 0 < pb.dim := nat.pos_of_ne_zero pb.dim_ne_zero lemma exists_eq_aeval [nontrivial S] (pb : power_basis R S) (y : S) : ∃ f : polynomial R, f.nat_degree < pb.dim ∧ y = aeval pb.gen f := (mem_span_pow pb.dim_ne_zero).mp (by simpa using pb.basis.mem_span y) lemma exists_eq_aeval' (pb : power_basis R S) (y : S) : ∃ f : polynomial R, y = aeval pb.gen f := begin nontriviality S, obtain ⟨f, _, hf⟩ := exists_eq_aeval pb y, exact ⟨f, hf⟩ end lemma alg_hom_ext {S' : Type*} [semiring S'] [algebra R S'] (pb : power_basis R S) ⦃f g : S →ₐ[R] S'⦄ (h : f pb.gen = g pb.gen) : f = g := begin ext x, obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, rw [← polynomial.aeval_alg_hom_apply, ← polynomial.aeval_alg_hom_apply, h] end section minpoly open_locale big_operators variable [algebra A S] /-- `pb.minpoly_gen` is a minimal polynomial for `pb.gen`. If `A` is not a field, it might not necessarily be *the* minimal polynomial, however `nat_degree_minpoly` shows its degree is indeed minimal. -/ noncomputable def minpoly_gen (pb : power_basis A S) : polynomial A := X ^ pb.dim - ∑ (i : fin pb.dim), C (pb.basis.repr (pb.gen ^ pb.dim) i) * X ^ (i : ℕ) @[simp] lemma degree_minpoly_gen (pb : power_basis A S) : degree (minpoly_gen pb) = pb.dim := begin unfold minpoly_gen, rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow, apply degree_sum_fin_lt end @[simp] lemma nat_degree_minpoly_gen (pb : power_basis A S) : nat_degree (minpoly_gen pb) = pb.dim := nat_degree_eq_of_degree_eq_some pb.degree_minpoly_gen lemma minpoly_gen_monic (pb : power_basis A S) : monic (minpoly_gen pb) := begin apply monic_sub_of_left (monic_pow (monic_X) _), rw degree_X_pow, exact degree_sum_fin_lt _ end @[simp] lemma aeval_minpoly_gen (pb : power_basis A S) : aeval pb.gen (minpoly_gen pb) = 0 := begin simp_rw [minpoly_gen, alg_hom.map_sub, alg_hom.map_sum, alg_hom.map_mul, alg_hom.map_pow, aeval_C, ← algebra.smul_def, aeval_X], refine sub_eq_zero.mpr ((pb.basis.total_repr (pb.gen ^ pb.dim)).symm.trans _), rw [finsupp.total_apply, finsupp.sum_fintype]; simp only [pb.coe_basis, zero_smul, eq_self_iff_true, implies_true_iff] end lemma is_integral_gen (pb : power_basis A S) : is_integral A pb.gen := ⟨minpoly_gen pb, minpoly_gen_monic pb, aeval_minpoly_gen pb⟩ lemma dim_le_nat_degree_of_root (h : power_basis A S) {p : polynomial A} (ne_zero : p ≠ 0) (root : aeval h.gen p = 0) : h.dim ≤ p.nat_degree := begin refine le_of_not_lt (λ hlt, ne_zero _), let p_coeff : fin (h.dim) → A := λ i, p.coeff i, suffices : ∀ i, p_coeff i = 0, { ext i, by_cases hi : i < h.dim, { exact this ⟨i, hi⟩ }, exact coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)) }, intro i, refine linear_independent_iff'.mp h.basis.linear_independent _ _ _ i (finset.mem_univ _), rw aeval_eq_sum_range' hlt at root, rw finset.sum_fin_eq_sum_range, convert root, ext i, split_ifs with hi, { simp_rw [coe_basis, p_coeff, fin.coe_mk] }, { rw [coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)), zero_smul] } end lemma dim_le_degree_of_root (h : power_basis A S) {p : polynomial A} (ne_zero : p ≠ 0) (root : aeval h.gen p = 0) : ↑h.dim ≤ p.degree := by { rw [degree_eq_nat_degree ne_zero, with_bot.coe_le_coe], exact h.dim_le_nat_degree_of_root ne_zero root } @[simp] lemma nat_degree_minpoly (pb : power_basis A S) : (minpoly A pb.gen).nat_degree = pb.dim := begin refine le_antisymm _ (dim_le_nat_degree_of_root pb (minpoly.ne_zero pb.is_integral_gen) (minpoly.aeval _ _)), rw ← nat_degree_minpoly_gen, apply nat_degree_le_of_degree_le, rw ← degree_eq_nat_degree (minpoly_gen_monic pb).ne_zero, exact minpoly.min _ _ (minpoly_gen_monic pb) (aeval_minpoly_gen pb) end @[simp] lemma minpoly_gen_eq [algebra K S] (pb : power_basis K S) : pb.minpoly_gen = minpoly K pb.gen := minpoly.unique K pb.gen pb.minpoly_gen_monic pb.aeval_minpoly_gen (λ p p_monic p_root, pb.degree_minpoly_gen.symm ▸ pb.dim_le_degree_of_root p_monic.ne_zero p_root) end minpoly section equiv variables [algebra A S] {S' : Type*} [comm_ring S'] [algebra A S'] lemma nat_degree_lt_nat_degree {p q : polynomial R} (hp : p ≠ 0) (hpq : p.degree < q.degree) : p.nat_degree < q.nat_degree := begin by_cases hq : q = 0, { rw [hq, degree_zero] at hpq, have := not_lt_bot hpq, contradiction }, rwa [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe] at hpq end lemma constr_pow_aeval (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (f : polynomial A) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (aeval pb.gen f) = aeval y f := begin rw [← aeval_mod_by_monic_eq_self_of_root (minpoly.monic pb.is_integral_gen) (minpoly.aeval _ _), ← @aeval_mod_by_monic_eq_self_of_root _ _ _ _ _ f _ (minpoly.monic pb.is_integral_gen) y hy], by_cases hf : f %ₘ minpoly A pb.gen = 0, { simp only [hf, alg_hom.map_zero, linear_map.map_zero] }, have : (f %ₘ minpoly A pb.gen).nat_degree < pb.dim, { rw ← pb.nat_degree_minpoly, apply nat_degree_lt_nat_degree hf, exact degree_mod_by_monic_lt _ (minpoly.monic pb.is_integral_gen) (minpoly.ne_zero pb.is_integral_gen) }, rw [aeval_eq_sum_range' this, aeval_eq_sum_range' this, linear_map.map_sum], refine finset.sum_congr rfl (λ i (hi : i ∈ finset.range pb.dim), _), rw finset.mem_range at hi, rw linear_map.map_smul, congr, rw [← fin.coe_mk hi, ← pb.basis_eq_pow ⟨i, hi⟩, basis.constr_basis] end lemma constr_pow_gen (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) : pb.basis.constr A (λ i, y ^ (i : ℕ)) pb.gen = y := by { convert pb.constr_pow_aeval hy X; rw aeval_X } lemma constr_pow_algebra_map (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (x : A) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (algebra_map A S x) = algebra_map A S' x := by { convert pb.constr_pow_aeval hy (C x); rw aeval_C } lemma constr_pow_mul (pb : power_basis A S) {y : S'} (hy : aeval y (minpoly A pb.gen) = 0) (x x' : S) : pb.basis.constr A (λ i, y ^ (i : ℕ)) (x * x') = pb.basis.constr A (λ i, y ^ (i : ℕ)) x * pb.basis.constr A (λ i, y ^ (i : ℕ)) x' := begin obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, obtain ⟨g, rfl⟩ := pb.exists_eq_aeval' x', simp only [← aeval_mul, pb.constr_pow_aeval hy] end /-- `pb.lift y hy` is the algebra map sending `pb.gen` to `y`, where `hy` states the higher powers of `y` are the same as the higher powers of `pb.gen`. See `power_basis.lift_equiv` for a bundled equiv sending `⟨y, hy⟩` to the algebra map. -/ noncomputable def lift (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) : S →ₐ[A] S' := { map_one' := by { convert pb.constr_pow_algebra_map hy 1 using 2; rw ring_hom.map_one }, map_zero' := by { convert pb.constr_pow_algebra_map hy 0 using 2; rw ring_hom.map_zero }, map_mul' := pb.constr_pow_mul hy, commutes' := pb.constr_pow_algebra_map hy, .. pb.basis.constr A (λ i, y ^ (i : ℕ)) } @[simp] lemma lift_gen (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) : pb.lift y hy pb.gen = y := pb.constr_pow_gen hy @[simp] lemma lift_aeval (pb : power_basis A S) (y : S') (hy : aeval y (minpoly A pb.gen) = 0) (f : polynomial A) : pb.lift y hy (aeval pb.gen f) = aeval y f := pb.constr_pow_aeval hy f /-- `pb.lift_equiv` states that roots of the minimal polynomial of `pb.gen` correspond to maps sending `pb.gen` to that root. This is the bundled equiv version of `power_basis.lift`. If the codomain of the `alg_hom`s is an integral domain, then the roots form a multiset, see `lift_equiv'` for the corresponding statement. -/ @[simps] noncomputable def lift_equiv (pb : power_basis A S) : (S →ₐ[A] S') ≃ {y : S' // aeval y (minpoly A pb.gen) = 0} := { to_fun := λ f, ⟨f pb.gen, by rw [aeval_alg_hom_apply, minpoly.aeval, f.map_zero]⟩, inv_fun := λ y, pb.lift y y.2, left_inv := λ f, pb.alg_hom_ext $ lift_gen _ _ _, right_inv := λ y, subtype.ext $ lift_gen _ _ y.prop } /-- `pb.lift_equiv'` states that elements of the root set of the minimal polynomial of `pb.gen` correspond to maps sending `pb.gen` to that root. -/ noncomputable def lift_equiv' (pb : power_basis A S) : (S →ₐ[A] B) ≃ {y : B // y ∈ ((minpoly A pb.gen).map (algebra_map A B)).roots} := pb.lift_equiv.trans ((equiv.refl _).subtype_equiv (λ x, begin rw [mem_roots, is_root.def, equiv.refl_apply, ← eval₂_eq_eval_map, ← aeval_def], exact map_monic_ne_zero (minpoly.monic pb.is_integral_gen) end)) /-- There are finitely many algebra homomorphisms `S →ₐ[A] B` if `S` is of the form `A[x]` and `B` is an integral domain. -/ noncomputable def alg_hom.fintype (pb : power_basis A S) : fintype (S →ₐ[A] B) := by letI := classical.dec_eq B; exact fintype.of_equiv _ pb.lift_equiv'.symm /-- `pb.equiv pb' h` is an equivalence of algebras with the same power basis. -/ noncomputable def equiv (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : S ≃ₐ[A] S' := alg_equiv.of_alg_hom (pb.lift pb'.gen (h.symm ▸ minpoly.aeval A pb'.gen)) (pb'.lift pb.gen (h ▸ minpoly.aeval A pb.gen)) (by { ext x, obtain ⟨f, hf, rfl⟩ := pb'.exists_eq_aeval' x, simp }) (by { ext x, obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval' x, simp }) @[simp] lemma equiv_aeval (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) (f : polynomial A) : pb.equiv pb' h (aeval pb.gen f) = aeval pb'.gen f := pb.lift_aeval _ (h.symm ▸ minpoly.aeval A _) _ @[simp] lemma equiv_gen (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : pb.equiv pb' h pb.gen = pb'.gen := pb.lift_gen _ (h.symm ▸ minpoly.aeval A _) local attribute [irreducible] power_basis.lift @[simp] lemma equiv_symm (pb : power_basis A S) (pb' : power_basis A S') (h : minpoly A pb.gen = minpoly A pb'.gen) : (pb.equiv pb' h).symm = pb'.equiv pb h.symm := rfl end equiv end power_basis open power_basis /-- Useful lemma to show `x` generates a power basis: the powers of `x` less than the degree of `x`'s minimal polynomial are linearly independent. -/ lemma is_integral.linear_independent_pow [algebra K S] {x : S} (hx : is_integral K x) : linear_independent K (λ (i : fin (minpoly K x).nat_degree), x ^ (i : ℕ)) := begin rw linear_independent_iff, intros p hp, set f : polynomial K := p.sum (λ i, monomial i) with hf0, have f_def : ∀ (i : fin _), f.coeff i = p i, { intro i, simp only [f, finsupp.sum, coeff_monomial, finset_sum_coeff], rw [finset.sum_eq_single, if_pos rfl], { intros b _ hb, rw if_neg (mt (λ h, _) hb), exact fin.coe_injective h }, { intro hi, split_ifs; { exact finsupp.not_mem_support_iff.mp hi } } }, have f_def' : ∀ i, f.coeff i = if hi : i < _ then p ⟨i, hi⟩ else 0, { intro i, split_ifs with hi, { exact f_def ⟨i, hi⟩ }, simp only [f, finsupp.sum, coeff_monomial, finset_sum_coeff], apply finset.sum_eq_zero, rintro ⟨j, hj⟩ -, apply if_neg (mt _ hi), rintro rfl, exact hj }, suffices : f = 0, { ext i, rw [← f_def, this, coeff_zero, finsupp.zero_apply] }, contrapose hp with hf, intro h, have : (minpoly K x).degree ≤ f.degree, { apply minpoly.degree_le_of_ne_zero K x hf, convert h, simp_rw [finsupp.total_apply, aeval_def, hf0, finsupp.sum, eval₂_finset_sum], apply finset.sum_congr rfl, rintro i -, simp only [algebra.smul_def, eval₂_monomial] }, have : ¬ (minpoly K x).degree ≤ f.degree, { apply not_le_of_lt, rw [degree_eq_nat_degree (minpoly.ne_zero hx), degree_lt_iff_coeff_zero], intros i hi, rw [f_def' i, dif_neg], exact hi.not_lt }, contradiction end lemma is_integral.mem_span_pow [nontrivial R] {x y : S} (hx : is_integral R x) (hy : ∃ f : polynomial R, y = aeval x f) : y ∈ submodule.span R (set.range (λ (i : fin (minpoly R x).nat_degree), x ^ (i : ℕ))) := begin obtain ⟨f, rfl⟩ := hy, apply mem_span_pow'.mpr _, have := minpoly.monic hx, refine ⟨f.mod_by_monic (minpoly R x), lt_of_lt_of_le (degree_mod_by_monic_lt _ this (ne_zero_of_monic this)) degree_le_nat_degree, _⟩, conv_lhs { rw ← mod_by_monic_add_div f this }, simp only [add_zero, zero_mul, minpoly.aeval, aeval_add, alg_hom.map_mul] end namespace power_basis section map variables {S' : Type*} [comm_ring S'] [algebra R S'] /-- `power_basis.map pb (e : S ≃ₐ[R] S')` is the power basis for `S'` generated by `e pb.gen`. -/ @[simps] noncomputable def map (pb : power_basis R S) (e : S ≃ₐ[R] S') : power_basis R S' := { dim := pb.dim, basis := pb.basis.map e.to_linear_equiv, gen := e pb.gen, basis_eq_pow := λ i, by rw [basis.map_apply, pb.basis_eq_pow, e.to_linear_equiv_apply, e.map_pow] } variables [algebra A S] [algebra A S'] @[simp] lemma minpoly_gen_map (pb : power_basis A S) (e : S ≃ₐ[A] S') : (pb.map e).minpoly_gen = pb.minpoly_gen := by { dsimp only [minpoly_gen, map_dim], -- Turn `fin (pb.map e).dim` into `fin pb.dim` simp only [linear_equiv.trans_apply, map_basis, basis.map_repr, map_gen, alg_equiv.to_linear_equiv_apply, e.to_linear_equiv_symm, alg_equiv.map_pow, alg_equiv.symm_apply_apply, sub_right_inj] } @[simp] lemma equiv_map (pb : power_basis A S) (e : S ≃ₐ[A] S') (h : minpoly A pb.gen = minpoly A (pb.map e).gen) : pb.equiv (pb.map e) h = e := by { ext x, obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, simp [aeval_alg_equiv] } end map end power_basis
c9dadf59f96594d92af306807e88fd687234cb49
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/init/quot.lean
97055225ed7f6043fb70f2ea089576d6b46ef1c3
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,022
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Quotient types. -/ prelude import init.sigma init.setoid init.logic open sigma.ops setoid constant quot.{l} : Π {A : Type.{l}}, setoid A → Type.{l} -- Remark: if we do not use propext here, then we would need a quot.lift for propositions. constant propext {a b : Prop} : (a ↔ b) → a = b -- iff can now be used to do substitutions in a calculation theorem iff_subst [subst] {a b : Prop} {P : Prop → Prop} (H₁ : a ↔ b) (H₂ : P a) : P b := eq.subst (propext H₁) H₂ namespace quot protected constant mk : Π {A : Type} [s : setoid A], A → quot s notation `⟦`:max a `⟧`:0 := quot.mk a constant sound : Π {A : Type} [s : setoid A] {a b : A}, a ≈ b → ⟦a⟧ = ⟦b⟧ constant lift : Π {A B : Type} [s : setoid A] (f : A → B), (∀ a b, a ≈ b → f a = f b) → quot s → B constant ind : ∀ {A : Type} [s : setoid A] {B : quot s → Prop}, (∀ a, B ⟦a⟧) → ∀ q, B q init_quotient protected theorem lift_beta {A B : Type} [s : setoid A] (f : A → B) (c : ∀ a b, a ≈ b → f a = f b) (a : A) : lift f c ⟦a⟧ = f a := rfl protected theorem ind_beta {A : Type} [s : setoid A] {B : quot s → Prop} (p : ∀ a, B ⟦a⟧) (a : A) : ind p ⟦a⟧ = p a := rfl protected definition lift_on [reducible] {A B : Type} [s : setoid A] (q : quot s) (f : A → B) (c : ∀ a b, a ≈ b → f a = f b) : B := lift f c q protected theorem induction_on {A : Type} [s : setoid A] {B : quot s → Prop} (q : quot s) (H : ∀ a, B ⟦a⟧) : B q := ind H q theorem exists_rep {A : Type} [s : setoid A] (q : quot s) : ∃ a : A, ⟦a⟧ = q := quot.induction_on q (λ a, exists.intro a rfl) section variable {A : Type} variable [s : setoid A] variable {B : quot s → Type} include s protected definition indep [reducible] (f : Π a, B ⟦a⟧) (a : A) : Σ q, B q := ⟨⟦a⟧, f a⟩ protected lemma indep_coherent (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) : ∀ a b, a ≈ b → quot.indep f a = quot.indep f b := λa b e, sigma.eq (sound e) (H a b e) protected lemma lift_indep_pr1 (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) (q : quot s) : (lift (quot.indep f) (quot.indep_coherent f H) q).1 = q := quot.ind (λ a, by esimp) q protected definition rec [reducible] (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) (q : quot s) : B q := let p := lift (quot.indep f) (quot.indep_coherent f H) q in eq.rec_on (quot.lift_indep_pr1 f H q) (p.2) protected definition rec_on [reducible] (q : quot s) (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) : B q := quot.rec f H q protected definition rec_on_subsingleton [reducible] [H : ∀ a, subsingleton (B ⟦a⟧)] (q : quot s) (f : Π a, B ⟦a⟧) : B q := quot.rec f (λ a b h, !subsingleton.elim) q protected definition hrec_on [reducible] (q : quot s) (f : Π a, B ⟦a⟧) (c : ∀ (a b : A) (p : a ≈ b), f a == f b) : B q := quot.rec_on q f (λ a b p, heq.to_eq (calc eq.rec (f a) (sound p) == f a : eq_rec_heq ... == f b : c a b p)) end section variables {A B C : Type} variables [s₁ : setoid A] [s₂ : setoid B] include s₁ s₂ protected definition lift₂ [reducible] (f : A → B → C)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (q₁ : quot s₁) (q₂ : quot s₂) : C := quot.lift (λ a₁, lift (λ a₂, f a₁ a₂) (λ a b H, c a₁ a a₁ b (setoid.refl a₁) H) q₂) (λ a b H, ind (λ a', proof c a a' b a' H (setoid.refl a') qed) q₂) q₁ protected definition lift_on₂ [reducible] (q₁ : quot s₁) (q₂ : quot s₂) (f : A → B → C) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : C := quot.lift₂ f c q₁ q₂ protected theorem ind₂ {C : quot s₁ → quot s₂ → Prop} (H : ∀ a b, C ⟦a⟧ ⟦b⟧) (q₁ : quot s₁) (q₂ : quot s₂) : C q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, H a₁ a₂) q₂) q₁ protected theorem induction_on₂ {C : quot s₁ → quot s₂ → Prop} (q₁ : quot s₁) (q₂ : quot s₂) (H : ∀ a b, C ⟦a⟧ ⟦b⟧) : C q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, H a₁ a₂) q₂) q₁ protected theorem induction_on₃ [s₃ : setoid C] {D : quot s₁ → quot s₂ → quot s₃ → Prop} (q₁ : quot s₁) (q₂ : quot s₂) (q₃ : quot s₃) (H : ∀ a b c, D ⟦a⟧ ⟦b⟧ ⟦c⟧) : D q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, H a₁ a₂ a₃) q₃) q₂) q₁ end section exact variable {A : Type} variable [s : setoid A] include s private definition rel (q₁ q₂ : quot s) : Prop := quot.lift_on₂ q₁ q₂ (λ a₁ a₂, a₁ ≈ a₂) (λ a₁ a₂ b₁ b₂ a₁b₁ a₂b₂, propext (iff.intro (λ a₁a₂, setoid.trans (setoid.symm a₁b₁) (setoid.trans a₁a₂ a₂b₂)) (λ b₁b₂, setoid.trans a₁b₁ (setoid.trans b₁b₂ (setoid.symm a₂b₂))))) local infix `~` := rel private lemma rel.refl : ∀ q : quot s, q ~ q := λ q, quot.induction_on q (λ a, setoid.refl a) private lemma eq_imp_rel {q₁ q₂ : quot s} : q₁ = q₂ → q₁ ~ q₂ := assume h, eq.rec_on h (rel.refl q₁) theorem exact {a b : A} : ⟦a⟧ = ⟦b⟧ → a ≈ b := assume h, eq_imp_rel h end exact section variables {A B : Type} variables [s₁ : setoid A] [s₂ : setoid B] include s₁ s₂ variable {C : quot s₁ → quot s₂ → Type} protected definition rec_on_subsingleton₂ [reducible] {C : quot s₁ → quot s₂ → Type₁} [H : ∀ a b, subsingleton (C ⟦a⟧ ⟦b⟧)] (q₁ : quot s₁) (q₂ : quot s₂) (f : Π a b, C ⟦a⟧ ⟦b⟧) : C q₁ q₂:= @quot.rec_on_subsingleton _ _ _ (λ a, quot.ind _ _) q₁ (λ a, quot.rec_on_subsingleton q₂ (λ b, f a b)) protected definition hrec_on₂ [reducible] {C : quot s₁ → quot s₂ → Type₁} (q₁ : quot s₁) (q₂ : quot s₂) (f : Π a b, C ⟦a⟧ ⟦b⟧) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ == f b₁ b₂) : C q₁ q₂:= quot.hrec_on q₁ (λ a, quot.hrec_on q₂ (λ b, f a b) (λ b₁ b₂ p, c _ _ _ _ !setoid.refl p)) (λ a₁ a₂ p, quot.induction_on q₂ (λ b, have aux : f a₁ b == f a₂ b, from c _ _ _ _ p !setoid.refl, calc quot.hrec_on ⟦b⟧ (λ (b : B), f a₁ b) _ == f a₁ b : eq_rec_heq ... == f a₂ b : aux ... == quot.hrec_on ⟦b⟧ (λ (b : B), f a₂ b) _ : eq_rec_heq)) end end quot attribute quot.mk [constructor] attribute quot.lift_on [unfold 4] attribute quot.rec [unfold 6] attribute quot.rec_on [unfold 4] attribute quot.hrec_on [unfold 4] attribute quot.rec_on_subsingleton [unfold 5] attribute quot.lift₂ [unfold 8] attribute quot.lift_on₂ [unfold 6] attribute quot.hrec_on₂ [unfold 6] attribute quot.rec_on_subsingleton₂ [unfold 7] open decidable definition quot.has_decidable_eq [instance] {A : Type} {s : setoid A} [decR : ∀ a b : A, decidable (a ≈ b)] : decidable_eq (quot s) := λ q₁ q₂ : quot s, quot.rec_on_subsingleton₂ q₁ q₂ (λ a₁ a₂, match decR a₁ a₂ with | inl h₁ := inl (quot.sound h₁) | inr h₂ := inr (λ h, absurd (quot.exact h) h₂) end)
e637ec10a71e57440e3d44dc2c38fb633dfe93ed
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/algebra/bundled.hlean
69eaea99e5823105f7366c29f4c37614bc93688b
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
2,745
hlean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Bundled structures -/ import algebra.group homotopy.interval open algebra namespace algebra structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] structure Group := (carrier : Type) (struct : group carrier) attribute Group.carrier [coercion] definition AddGroup : Type := Group definition AddGroup.mk [constructor] [reducible] (G : Type) (H : add_group G) : AddGroup := Group.mk G H definition AddGroup.struct [reducible] (G : AddGroup) : add_group G := Group.struct G attribute AddGroup.struct Group.struct [instance] [priority 2000] structure CommGroup := (carrier : Type) (struct : comm_group carrier) attribute CommGroup.carrier [coercion] definition AddCommGroup : Type := CommGroup definition AddCommGroup.mk [constructor] [reducible] (G : Type) (H : add_comm_group G) : AddCommGroup := CommGroup.mk G H definition AddCommGroup.struct [reducible] (G : AddCommGroup) : add_comm_group G := CommGroup.struct G attribute AddCommGroup.struct CommGroup.struct [instance] [priority 2000] -- structure AddSemigroup := -- (carrier : Type) (struct : add_semigroup carrier) -- attribute AddSemigroup.carrier [coercion] -- attribute AddSemigroup.struct [instance] -- structure AddCommSemigroup := -- (carrier : Type) (struct : add_comm_semigroup carrier) -- attribute AddCommSemigroup.carrier [coercion] -- attribute AddCommSemigroup.struct [instance] -- structure AddMonoid := -- (carrier : Type) (struct : add_monoid carrier) -- attribute AddMonoid.carrier [coercion] -- attribute AddMonoid.struct [instance] -- structure AddCommMonoid := -- (carrier : Type) (struct : add_comm_monoid carrier) -- attribute AddCommMonoid.carrier [coercion] -- attribute AddCommMonoid.struct [instance] -- structure AddGroup := -- (carrier : Type) (struct : add_group carrier) -- attribute AddGroup.carrier [coercion] -- attribute AddGroup.struct [instance] -- structure AddCommGroup := -- (carrier : Type) (struct : add_comm_group carrier) -- attribute AddCommGroup.carrier [coercion] -- attribute AddCommGroup.struct [instance] end algebra
fcf312cf66dbbb0512b88c1e0450c16ac8bd3e8e
439bc6c3e74a118aa51df633b8e1f24415804d86
/yoneda2.lean
867987afe7aeb90086a675536ea5515c860808cc
[]
no_license
jcommelin/lt2019_slides
4ca498db02b5187c5778c21b985126d52d260696
3234cd92920d3d4321cc2cef78b48e5fa55be413
refs/heads/master
1,586,718,101,957
1,546,930,855,000
1,546,930,855,000
162,697,592
1
0
null
null
null
null
UTF-8
Lean
false
false
182
lean
def yoneda_2 : C ⥤ ((Cᵒᵖ) ⥤ (Type v₁)) := { obj := λ X, { obj := λ Y : C, Y ⟶ X, map := λ Y Y' f g, f ≫ g }, map := λ X X' f, { app := λ Y g, g ≫ f } }
9d93026ab1becdce29a5d1fd16687991b649ae3a
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/metric_space/closeds.lean
37119221f2877724f52c3a14011f82447559f0c2
[ "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
21,419
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.hausdorff_distance import analysis.specific_limits /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical open_locale topological_space universe u open classical set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right' inf_edist_le_inf_edist_add_edist ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, add_left_comm, Hausdorff_edist_comm, -subtype.val_eq_coe] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left' (add_le_add (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff.2 (λε εpos, _), rcases mem_closure_iff.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa hs.closure_eq at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ennreal := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ennreal) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.div_def, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.div_def, ennreal.inv_pow], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim begin simp only [exists_prop, set.mem_Union, filter.eventually_at_top, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine (tendsto_at_top _).2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.const_mul (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b, from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top, exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { exact subtype.val_injective.inj_on F }, { refine fs.finite_subsets.subset (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : is_closed t0 := (fs.subset t0s).compact.is_closed, let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [s.property.2.is_closed.closure_eq, t.property.2.is_closed.closure_eq] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (range $ @nonempty_compacts.to_closeds α _ _) := begin have : range nonempty_compacts.to_closeds = {s : closeds α | s.val.nonempty ∧ compact s.val}, from range_inclusion _, rw this, refine is_closed_of_closure_subset (λs hs, ⟨_, _⟩), { -- take a set set t which is nonempty and at a finite distance of s rcases mem_closure_iff.1 hs ⊤ ennreal.coe_lt_top with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- since `t` is nonempty, so is `s` exact nonempty_of_Hausdorff_edist_ne_top ht.1 (ne_of_lt Dst) }, { refine compact_iff_totally_bounded_complete.2 ⟨_, s.property.is_complete⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := (complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding).2 $ nonempty_compacts.is_closed_in_closeds.is_complete /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw embedding.compact_iff_compact_image nonempty_compacts.to_closeds.uniform_embedding.embedding, rw [image_univ], exact nonempty_compacts.is_closed_in_closeds.compact end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ have : separable_space α := by apply_instance, rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine (countable_set_of_finite_subset cs).mono (λx hx, _), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply subtype.val_injective.inj_on }, { refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff.2 (λε εpos, _)), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases dense εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, have : x ∈ closure s := by rw s_dense; exact mem_univ _, rcases mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := af.image _, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := ‹finite b›.subset (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have hc : c.nonempty, from nonempty_of_Hausdorff_edist_ne_top t.property.1 (ne_top_of_lt Dtc), -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.compact⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.uniform_continuous end --section end metric --namespace
0d8736d944a5658a563bfaf1a061f5699649661b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/char_poly/coeff.lean
fe592ba0e052a8101da18aec9d89acaee2b87d19
[ "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
10,746
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark -/ import algebra.polynomial.big_operators import data.matrix.char_p import field_theory.finite.basic import group_theory.perm.cycles import linear_algebra.char_poly.basic import linear_algebra.matrix.trace import ring_theory.polynomial.basic import ring_theory.power_basis /-! # Characteristic polynomials We give methods for computing coefficients of the characteristic polynomial. ## Main definitions - `char_poly_degree_eq_dim` proves that the degree of the characteristic polynomial over a nonzero ring is the dimension of the matrix - `det_eq_sign_char_poly_coeff` proves that the determinant is the constant term of the characteristic polynomial, up to sign. - `trace_eq_neg_char_poly_coeff` proves that the trace is the negative of the (d-1)th coefficient of the characteristic polynomial, where d is the dimension of the matrix. For a nonzero ring, this is the second-highest coefficient. -/ noncomputable theory universes u v w z open polynomial matrix open_locale big_operators variables {R : Type u} [comm_ring R] variables {n G : Type v} [decidable_eq n] [fintype n] variables {α β : Type v} [decidable_eq α] open finset open polynomial variable {M : matrix n n R} lemma char_matrix_apply_nat_degree [nontrivial R] (i j : n) : (char_matrix M i j).nat_degree = ite (i = j) 1 0 := by { by_cases i = j; simp [h, ← degree_eq_iff_nat_degree_eq_of_pos (nat.succ_pos 0)], } lemma char_matrix_apply_nat_degree_le (i j : n) : (char_matrix M i j).nat_degree ≤ ite (i = j) 1 0 := by split_ifs; simp [h, nat_degree_X_sub_C_le] variable (M) lemma char_poly_sub_diagonal_degree_lt : (char_poly M - ∏ (i : n), (X - C (M i i))).degree < ↑(fintype.card n - 1) := begin rw [char_poly, det_apply', ← insert_erase (mem_univ (equiv.refl n)), sum_insert (not_mem_erase (equiv.refl n) univ), add_comm], simp only [char_matrix_apply_eq, one_mul, equiv.perm.sign_refl, id.def, int.cast_one, units.coe_one, add_sub_cancel, equiv.coe_refl], rw ← mem_degree_lt, apply submodule.sum_mem (degree_lt R (fintype.card n - 1)), intros c hc, rw [← C_eq_int_cast, C_mul'], apply submodule.smul_mem (degree_lt R (fintype.card n - 1)) ↑↑(equiv.perm.sign c), rw mem_degree_lt, apply lt_of_le_of_lt degree_le_nat_degree _, rw with_bot.coe_lt_coe, apply lt_of_le_of_lt _ (equiv.perm.fixed_point_card_lt_of_ne_one (ne_of_mem_erase hc)), apply le_trans (polynomial.nat_degree_prod_le univ (λ i : n, (char_matrix M (c i) i))) _, rw card_eq_sum_ones, rw sum_filter, apply sum_le_sum, intros, apply char_matrix_apply_nat_degree_le, end lemma char_poly_coeff_eq_prod_coeff_of_le {k : ℕ} (h : fintype.card n - 1 ≤ k) : (char_poly M).coeff k = (∏ i : n, (X - C (M i i))).coeff k := begin apply eq_of_sub_eq_zero, rw ← coeff_sub, apply polynomial.coeff_eq_zero_of_degree_lt, apply lt_of_lt_of_le (char_poly_sub_diagonal_degree_lt M) _, rw with_bot.coe_le_coe, apply h, end lemma det_of_card_zero (h : fintype.card n = 0) (M : matrix n n R) : M.det = 1 := by { rw fintype.card_eq_zero_iff at h, suffices : M = 1, { simp [this] }, ext i, exact h.elim i } theorem char_poly_degree_eq_dim [nontrivial R] (M : matrix n n R) : (char_poly M).degree = fintype.card n := begin by_cases fintype.card n = 0, { rw h, unfold char_poly, rw det_of_card_zero, {simp}, {assumption} }, rw ← sub_add_cancel (char_poly M) (∏ (i : n), (X - C (M i i))), have h1 : (∏ (i : n), (X - C (M i i))).degree = fintype.card n, { rw degree_eq_iff_nat_degree_eq_of_pos, swap, apply nat.pos_of_ne_zero h, rw nat_degree_prod', simp_rw nat_degree_X_sub_C, unfold fintype.card, simp, simp_rw (monic_X_sub_C _).leading_coeff, simp, }, rw degree_add_eq_right_of_degree_lt, exact h1, rw h1, apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem char_poly_nat_degree_eq_dim [nontrivial R] (M : matrix n n R) : (char_poly M).nat_degree = fintype.card n := nat_degree_eq_of_degree_eq_some (char_poly_degree_eq_dim M) lemma char_poly_monic (M : matrix n n R) : monic (char_poly M) := begin nontriviality, by_cases fintype.card n = 0, {rw [char_poly, det_of_card_zero h], apply monic_one}, have mon : (∏ (i : n), (X - C (M i i))).monic, { apply monic_prod_of_monic univ (λ i : n, (X - C (M i i))), simp [monic_X_sub_C], }, rw ← sub_add_cancel (∏ (i : n), (X - C (M i i))) (char_poly M) at mon, rw monic at *, rw leading_coeff_add_of_degree_lt at mon, rw ← mon, rw char_poly_degree_eq_dim, rw ← neg_sub, rw degree_neg, apply lt_trans (char_poly_sub_diagonal_degree_lt M), rw with_bot.coe_lt_coe, rw ← nat.pred_eq_sub_one, apply nat.pred_lt, apply h, end theorem trace_eq_neg_char_poly_coeff [nonempty n] (M : matrix n n R) : (matrix.trace n R R) M = -(char_poly M).coeff (fintype.card n - 1) := begin nontriviality, rw char_poly_coeff_eq_prod_coeff_of_le, swap, refl, rw [fintype.card, prod_X_sub_C_coeff_card_pred univ (λ i : n, M i i)], simp, rw [← fintype.card, fintype.card_pos_iff], apply_instance, end -- I feel like this should use polynomial.alg_hom_eval₂_algebra_map lemma mat_poly_equiv_eval (M : matrix n n (polynomial R)) (r : R) (i j : n) : (mat_poly_equiv M).eval ((scalar n) r) i j = (M i j).eval r := begin unfold polynomial.eval, unfold eval₂, transitivity polynomial.sum (mat_poly_equiv M) (λ (e : ℕ) (a : matrix n n R), (a * (scalar n) r ^ e) i j), { unfold polynomial.sum, rw matrix.sum_apply, dsimp, refl }, { simp_rw [←ring_hom.map_pow, ←(matrix.scalar.commute _ _).eq], simp only [coe_scalar, matrix.one_mul, ring_hom.id_apply, pi.smul_apply, smul_eq_mul, mul_eq_mul, algebra.smul_mul_assoc], have h : ∀ x : ℕ, (λ (e : ℕ) (a : R), r ^ e * a) x 0 = 0 := by simp, simp only [polynomial.sum, mat_poly_equiv_coeff_apply, mul_comm], apply (finset.sum_subset (support_subset_support_mat_poly_equiv _ _ _) _).symm, assume n hn h'n, rw not_mem_support_iff at h'n, simp only [h'n, zero_mul] } end lemma eval_det (M : matrix n n (polynomial R)) (r : R) : polynomial.eval r M.det = (polynomial.eval (matrix.scalar n r) (mat_poly_equiv M)).det := begin rw [polynomial.eval, ← coe_eval₂_ring_hom, ring_hom.map_det], apply congr_arg det, ext, symmetry, convert mat_poly_equiv_eval _ _ _ _, end theorem det_eq_sign_char_poly_coeff (M : matrix n n R) : M.det = (-1)^(fintype.card n) * (char_poly M).coeff 0:= begin rw [coeff_zero_eq_eval_zero, char_poly, eval_det, mat_poly_equiv_char_matrix, ← det_smul], simp end variables {p : ℕ} [fact p.prime] lemma mat_poly_equiv_eq_X_pow_sub_C {K : Type*} (k : ℕ) [field K] (M : matrix n n K) : mat_poly_equiv ((expand K (k) : polynomial K →+* polynomial K).map_matrix (char_matrix (M ^ k))) = X ^ k - C (M ^ k) := begin ext m, rw [coeff_sub, coeff_C, mat_poly_equiv_coeff_apply, ring_hom.map_matrix_apply, matrix.map_apply, alg_hom.coe_to_ring_hom, dmatrix.sub_apply, coeff_X_pow], by_cases hij : i = j, { rw [hij, char_matrix_apply_eq, alg_hom.map_sub, expand_C, expand_X, coeff_sub, coeff_X_pow, coeff_C], split_ifs with mp m0; simp only [matrix.one_apply_eq, dmatrix.zero_apply] }, { rw [char_matrix_apply_ne _ _ _ hij, alg_hom.map_neg, expand_C, coeff_neg, coeff_C], split_ifs with m0 mp; simp only [hij, zero_sub, dmatrix.zero_apply, sub_zero, neg_zero, matrix.one_apply_ne, ne.def, not_false_iff] } end @[simp] lemma finite_field.char_poly_pow_card {K : Type*} [field K] [fintype K] (M : matrix n n K) : char_poly (M ^ (fintype.card K)) = char_poly M := begin casesI (is_empty_or_nonempty n).symm, { cases char_p.exists K with p hp, letI := hp, rcases finite_field.card K p with ⟨⟨k, kpos⟩, ⟨hp, hk⟩⟩, haveI : fact p.prime := ⟨hp⟩, dsimp at hk, rw hk at *, apply (frobenius_inj (polynomial K) p).iterate k, repeat { rw iterate_frobenius, rw ← hk }, rw ← finite_field.expand_card, unfold char_poly, rw [alg_hom.map_det, ← is_monoid_hom.map_pow], apply congr_arg det, refine mat_poly_equiv.injective _, rw [alg_equiv.map_pow, mat_poly_equiv_char_matrix, hk, sub_pow_char_pow_of_commute, ← C_pow], { exact (id (mat_poly_equiv_eq_X_pow_sub_C (p ^ k) M) : _) }, { exact (C M).commute_X } }, { -- TODO[gh-6025]: remove this `haveI` once `subsingleton_of_empty_right` is a global instance haveI : subsingleton (matrix n n K) := matrix.subsingleton_of_empty_right, exact congr_arg _ (subsingleton.elim _ _), }, end @[simp] lemma zmod.char_poly_pow_card (M : matrix n n (zmod p)) : char_poly (M ^ p) = char_poly M := by { have h := finite_field.char_poly_pow_card M, rwa zmod.card at h, } lemma finite_field.trace_pow_card {K : Type*} [field K] [fintype K] [nonempty n] (M : matrix n n K) : trace n K K (M ^ (fintype.card K)) = (trace n K K M) ^ (fintype.card K) := by rw [trace_eq_neg_char_poly_coeff, trace_eq_neg_char_poly_coeff, finite_field.char_poly_pow_card, finite_field.pow_card] lemma zmod.trace_pow_card {p:ℕ} [fact p.prime] [nonempty n] (M : matrix n n (zmod p)) : trace n (zmod p) (zmod p) (M ^ p) = (trace n (zmod p) (zmod p) M)^p := by { have h := finite_field.trace_pow_card M, rwa zmod.card at h, } namespace matrix theorem is_integral : is_integral R M := ⟨char_poly M, ⟨char_poly_monic M, aeval_self_char_poly M⟩⟩ theorem min_poly_dvd_char_poly {K : Type*} [field K] (M : matrix n n K) : (minpoly K M) ∣ char_poly M := minpoly.dvd _ _ (aeval_self_char_poly M) end matrix section power_basis open algebra /-- The characteristic polynomial of the map `λ x, a * x` is the minimal polynomial of `a`. In combination with `det_eq_sign_char_poly_coeff` or `trace_eq_neg_char_poly_coeff` and a bit of rewriting, this will allow us to conclude the field norm resp. trace of `x` is the product resp. sum of `x`'s conjugates. -/ lemma char_poly_left_mul_matrix {K S : Type*} [field K] [comm_ring S] [algebra K S] (h : power_basis K S) : char_poly (left_mul_matrix h.basis h.gen) = minpoly K h.gen := begin apply minpoly.unique, { apply char_poly_monic }, { apply (left_mul_matrix _).injective_iff.mp (left_mul_matrix_injective h.basis), rw [← polynomial.aeval_alg_hom_apply, aeval_self_char_poly] }, { intros q q_monic root_q, rw [char_poly_degree_eq_dim, fintype.card_fin, degree_eq_nat_degree q_monic.ne_zero], apply with_bot.some_le_some.mpr, exact h.dim_le_nat_degree_of_root q_monic.ne_zero root_q } end end power_basis
8335eb8d77d252b2eec0d57159bef2444082b2a2
e6b8240a90527fd55d42d0ec6649253d5d0bd414
/src/algebra/order.lean
d282939845079c0f028dc6980b9f8d68992ab552
[ "Apache-2.0" ]
permissive
mattearnshaw/mathlib
ac90f9fb8168aa642223bea3ffd0286b0cfde44f
d8dc1445cf8a8c74f8df60b9f7a1f5cf10946666
refs/heads/master
1,606,308,351,137
1,576,594,130,000
1,576,594,130,000
228,666,195
0
0
Apache-2.0
1,576,603,094,000
1,576,603,093,000
null
UTF-8
Lean
false
false
9,763
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ universe u variables {α : Type u} @[simp] lemma ge_iff_le [preorder α] {a b : α} : a ≥ b ↔ b ≤ a := iff.rfl @[simp] lemma gt_iff_lt [preorder α] {a b : α} : a > b ↔ b < a := iff.rfl lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a := (le_not_le_of_lt h).right lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a | hab := not_le_of_gt hab h lemma le_iff_eq_or_lt [partial_order α] {a b : α} : a ≤ b ↔ a = b ∨ a < b := le_iff_lt_or_eq.trans or.comm lemma lt_of_le_of_ne' [partial_order α] {a b : α} (h₁ : a ≤ b) (h₂ : a ≠ b) : a < b := lt_of_le_not_le h₁ $ mt (le_antisymm h₁) h₂ lemma lt_iff_le_and_ne [partial_order α] {a b : α} : a < b ↔ a ≤ b ∧ a ≠ b := ⟨λ h, ⟨le_of_lt h, ne_of_lt h⟩, λ ⟨h1, h2⟩, lt_of_le_of_ne h1 h2⟩ lemma eq_iff_le_not_lt [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b := ⟨λ h, ⟨le_of_eq h, h ▸ lt_irrefl _⟩, λ ⟨h₁, h₂⟩, le_antisymm h₁ $ classical.by_contradiction $ λ h₃, h₂ (lt_of_le_not_le h₁ h₃)⟩ lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le h).symm lemma lt_of_not_ge' [linear_order α] {a b : α} (h : ¬ b ≤ a) : a < b := lt_of_le_not_le ((le_total _ _).resolve_right h) h lemma lt_iff_not_ge' [linear_order α] {x y : α} : x < y ↔ ¬ y ≤ x := ⟨not_le_of_gt, lt_of_not_ge'⟩ @[simp] lemma not_lt [linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_gt, not_lt_of_ge⟩ lemma le_of_not_lt [linear_order α] {a b : α} : ¬ a < b → b ≤ a := not_lt.1 @[simp] lemma not_le [linear_order α] {a b : α} : ¬ a ≤ b ↔ b < a := lt_iff_not_ge'.symm lemma lt_or_le [linear_order α] : ∀ a b : α, a < b ∨ b ≤ a := lt_or_ge lemma le_or_lt [linear_order α] : ∀ a b : α, a ≤ b ∨ b < a := le_or_gt lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a := not_lt.trans $ le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl lemma exists_ge_of_linear [linear_order α] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := match le_total a b with | or.inl h := ⟨_, h, le_refl _⟩ | or.inr h := ⟨_, le_refl _, h⟩ end lemma lt_imp_lt_of_le_imp_le {β} [linear_order α] [preorder β] {a b : α} {c d : β} (H : a ≤ b → c ≤ d) (h : d < c) : b < a := lt_of_not_ge' $ λ h', not_lt_of_ge (H h') h lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_gt $ λ h', not_le_of_gt (H h') h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma lt_iff_lt_of_le_iff_le' {β} [preorder α] [preorder β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c := lt_iff_le_not_le.trans $ (and_congr H' (not_congr H)).trans lt_iff_le_not_le.symm lemma lt_iff_lt_of_le_iff_le {β} [linear_order α] [linear_order β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c := not_le.symm.trans $ iff.trans (not_congr H) $ not_le lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ iff.trans (not_congr H) $ not_lt⟩ lemma eq_of_forall_le_iff [partial_order α] {a b : α} (H : ∀ c, c ≤ a ↔ c ≤ b) : a = b := le_antisymm ((H _).1 (le_refl _)) ((H _).2 (le_refl _)) lemma le_of_forall_le [preorder α] {a b : α} (H : ∀ c, c ≤ a → c ≤ b) : a ≤ b := H _ (le_refl _) lemma le_of_forall_le' [preorder α] {a b : α} (H : ∀ c, a ≤ c → b ≤ c) : b ≤ a := H _ (le_refl _) lemma le_of_forall_lt [linear_order α] {a b : α} (H : ∀ c, c < a → c < b) : a ≤ b := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le [linear_order α] {a b : α} : (∀ ⦃c⦄, c < a → c < b) ↔ a ≤ b := ⟨le_of_forall_lt, λ h c hca, lt_of_lt_of_le hca h⟩ lemma le_of_forall_lt' [linear_order α] {a b : α} (H : ∀ c, a < c → b < c) : b ≤ a := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le' [linear_order α] {a b : α} : (∀ ⦃c⦄, a < c → b < c) ↔ b ≤ a := ⟨le_of_forall_lt', λ h c hac, lt_of_le_of_lt h hac⟩ lemma eq_of_forall_ge_iff [partial_order α] {a b : α} (H : ∀ c, a ≤ c ↔ b ≤ c) : a = b := le_antisymm ((H _).2 (le_refl _)) ((H _).1 (le_refl _)) /-- monotonicity of `≤` with respect to `→` -/ lemma le_implies_le_of_le_of_le {a b c d : α} [preorder α] (h₀ : c ≤ a) (h₁ : b ≤ d) : a ≤ b → c ≤ d := assume h₂ : a ≤ b, calc c ≤ a : h₀ ... ≤ b : h₂ ... ≤ d : h₁ namespace decidable lemma lt_or_eq_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a < b ∨ a = b := if hba : b ≤ a then or.inr (le_antisymm hab hba) else or.inl (lt_of_le_not_le hab hba) lemma eq_or_lt_of_le [partial_order α] [@decidable_rel α (≤)] {a b : α} (hab : a ≤ b) : a = b ∨ a < b := (lt_or_eq_of_le hab).swap lemma le_iff_lt_or_eq [partial_order α] [@decidable_rel α (≤)] {a b : α} : a ≤ b ↔ a < b ∨ a = b := ⟨lt_or_eq_of_le, le_of_lt_or_eq⟩ lemma le_of_not_lt [decidable_linear_order α] {a b : α} (h : ¬ b < a) : a ≤ b := decidable.by_contradiction $ λ h', h $ lt_of_le_not_le ((le_total _ _).resolve_right h') h' lemma not_lt [decidable_linear_order α] {a b : α} : ¬ a < b ↔ b ≤ a := ⟨le_of_not_lt, not_lt_of_ge⟩ lemma lt_or_le [decidable_linear_order α] (a b : α) : a < b ∨ b ≤ a := if hba : b ≤ a then or.inr hba else or.inl $ not_le.1 hba lemma le_or_lt [decidable_linear_order α] (a b : α) : a ≤ b ∨ b < a := (lt_or_le b a).swap lemma lt_trichotomy [decidable_linear_order α] (a b : α) : a < b ∨ a = b ∨ b < a := (lt_or_le _ _).imp_right $ λ h, (eq_or_lt_of_le h).imp_left eq.symm lemma lt_or_gt_of_ne [decidable_linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ b < a := (lt_trichotomy a b).imp_right $ λ h', h'.resolve_left h def lt_by_cases [decidable_linear_order α] (x y : α) {P : Sort*} (h₁ : x < y → P) (h₂ : x = y → P) (h₃ : y < x → P) : P := begin by_cases h : x < y, { exact h₁ h }, by_cases h' : y < x, { exact h₃ h' }, apply h₂, apply le_antisymm; apply le_of_not_gt; assumption end lemma ne_iff_lt_or_gt [decidable_linear_order α] {a b : α} : a ≠ b ↔ a < b ∨ b < a := ⟨lt_or_gt_of_ne, λo, o.elim ne_of_lt ne_of_gt⟩ lemma le_imp_le_of_lt_imp_lt {β} [preorder α] [decidable_linear_order β] {a b : α} {c d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d := le_of_not_lt $ λ h', not_le_of_gt (H h') h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [decidable_linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma le_iff_le_iff_lt_iff_lt {β} [decidable_linear_order α] [decidable_linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ iff.trans (not_congr H) $ not_lt⟩ lemma min_le_max [decidable_linear_order α] (a b : α) : min a b ≤ max a b := le_trans (min_le_left a b) (le_max_left a b) end decidable namespace ordering /-- `compares o a b` means that `a` and `b` have the ordering relation `o` between them, assuming that the relation `a < b` is defined -/ @[simp] def compares [has_lt α] : ordering → α → α → Prop | lt a b := a < b | eq a b := a = b | gt a b := a > b theorem compares.eq_lt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = lt ↔ a < b) | lt a b h := ⟨λ _, h, λ _, rfl⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h' h).elim⟩ | gt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ theorem compares.eq_eq [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = eq ↔ a = b) | lt a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h h').elim⟩ | eq a b h := ⟨λ _, h, λ _, rfl⟩ | gt a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h h').elim⟩ theorem compares.eq_gt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = gt ↔ a > b) | lt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h' h).elim⟩ | gt a b h := ⟨λ _, h, λ _, rfl⟩ theorem compares.inj [preorder α] {o₁} : ∀ {o₂} {a b : α}, compares o₁ a b → compares o₂ a b → o₁ = o₂ | lt a b h₁ h₂ := h₁.eq_lt.2 h₂ | eq a b h₁ h₂ := h₁.eq_eq.2 h₂ | gt a b h₁ h₂ := h₁.eq_gt.2 h₂ theorem swap_or_else (o₁ o₂) : (or_else o₁ o₂).swap = or_else o₁.swap o₂.swap := by cases o₁; try {refl}; cases o₂; refl theorem or_else_eq_lt (o₁ o₂) : or_else o₁ o₂ = lt ↔ o₁ = lt ∨ (o₁ = eq ∧ o₂ = lt) := by cases o₁; cases o₂; exact dec_trivial end ordering theorem cmp_compares [decidable_linear_order α] (a b : α) : (cmp a b).compares a b := begin unfold cmp cmp_using, by_cases a < b; simp [h], by_cases h₂ : b < a; simp [h₂, gt], exact (lt_or_eq_of_le (le_of_not_gt h₂)).resolve_left h end theorem cmp_swap [preorder α] [@decidable_rel α (<)] (a b : α) : (cmp a b).swap = cmp b a := begin unfold cmp cmp_using, by_cases a < b; by_cases h₂ : b < a; simp [h, h₂, gt, ordering.swap], exact lt_asymm h h₂ end
746d7094ff468278db1ce6adc7fbe75eb0d3c37f
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/geometry/manifold/algebra/lie_group.lean
26bcd31688f4a9dd4df832feb1cd620723fb4817
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
6,311
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.algebra.monoid /-! # Lie groups A Lie group is a group that is also a smooth manifold, in which the group operations of multiplication and inversion are smooth maps. Smoothness of the group multiplication means that multiplication is a smooth mapping of the product manifold `G` × `G` into `G`. Note that, since a manifold here is not second-countable and Hausdorff a Lie group here is not guaranteed to be second-countable (even though it can be proved it is Hausdorff). Note also that Lie groups here are not necessarily finite dimensional. ## Main definitions and statements * `lie_add_group I G` : a Lie additive group where `G` is a manifold on the model with corners `I`. * `lie_group I G` : a Lie multiplicative group where `G` is a manifold on the model with corners `I`. * `normed_space_lie_add_group` : a normed vector space over a nondiscrete normed field is an additive Lie group. ## Implementation notes A priori, a Lie group here is a manifold with corners. The definition of Lie group cannot require `I : model_with_corners 𝕜 E E` with the same space as the model space and as the model vector space, as one might hope, beause in the product situation, the model space is `model_prod E E'` and the model vector space is `E × E'`, which are not the same, so the definition does not apply. Hence the definition should be more general, allowing `I : model_with_corners 𝕜 E H`. -/ noncomputable theory open_locale manifold section set_option old_structure_cmd true /-- A Lie (additive) group is a group and a smooth manifold at the same time in which the addition and negation operations are smooth. -/ -- See note [Design choices about smooth algebraic structures] @[ancestor has_smooth_add] class lie_add_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [add_group G] [topological_space G] [charted_space H G] extends has_smooth_add I G : Prop := (smooth_neg : smooth I I (λ a:G, -a)) /-- A Lie group is a group and a smooth manifold at the same time in which the multiplication and inverse operations are smooth. -/ -- See note [Design choices about smooth algebraic structures] @[ancestor has_smooth_mul, to_additive] class lie_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H) (G : Type*) [group G] [topological_space G] [charted_space H G] extends has_smooth_mul I G : Prop := (smooth_inv : smooth I I (λ a:G, a⁻¹)) end section lie_group variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {F : Type*} [normed_group F] [normed_space 𝕜 F] {J : model_with_corners 𝕜 F F} {G : Type*} [topological_space G] [charted_space H G] [group G] [lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M : Type*} [topological_space M] [charted_space H' M] {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M' : Type*} [topological_space M'] [charted_space H'' M'] localized "notation `L_add` := left_add" in lie_group localized "notation `R_add` := right_add" in lie_group localized "notation `L` := left_mul" in lie_group localized "notation `R` := right_mul" in lie_group section variable (I) @[to_additive] lemma smooth_inv : smooth I I (λ x : G, x⁻¹) := lie_group.smooth_inv /-- A Lie group is a topological group. This is not an instance for technical reasons, see note [Design choices about smooth algebraic structures]. -/ @[to_additive "An additive Lie group is an additive topological group. This is not an instance for technical reasons, see note [Design choices about smooth algebraic structures]."] lemma topological_group_of_lie_group : topological_group G := { continuous_inv := (smooth_inv I).continuous, .. has_continuous_mul_of_smooth I } end @[to_additive] lemma smooth.inv {f : M → G} (hf : smooth I' I f) : smooth I' I (λx, (f x)⁻¹) := (smooth_inv I).comp hf @[to_additive] lemma smooth_on.inv {f : M → G} {s : set M} (hf : smooth_on I' I f s) : smooth_on I' I (λx, (f x)⁻¹) s := (smooth_inv I).comp_smooth_on hf @[to_additive] lemma smooth.div {f g : M → G} (hf : smooth I' I f) (hg : smooth I' I g) : smooth I' I (f / g) := by { rw div_eq_mul_inv, exact ((smooth_mul I).comp (hf.prod_mk hg.inv) : _), } @[to_additive] lemma smooth_on.div {f g : M → G} {s : set M} (hf : smooth_on I' I f s) (hg : smooth_on I' I g s) : smooth_on I' I (f / g) s := by { rw div_eq_mul_inv, exact ((smooth_mul I).comp_smooth_on (hf.prod_mk hg.inv) : _), } end lie_group section prod_lie_group /- Instance of product group -/ @[to_additive] instance {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {H : Type*} [topological_space H] {E : Type*} [normed_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H} {G : Type*} [topological_space G] [charted_space H G] [group G] [lie_group I G] {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {G' : Type*} [topological_space G'] [charted_space H' G'] [group G'] [lie_group I' G'] : lie_group (I.prod I') (G×G') := { smooth_inv := smooth_fst.inv.prod_mk smooth_snd.inv, ..has_smooth_mul.prod _ _ _ _ } end prod_lie_group /-! ### Normed spaces are Lie groups -/ instance normed_space_lie_add_group {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] : lie_add_group (𝓘(𝕜, E)) E := { smooth_add := smooth_iff.2 ⟨continuous_add, λ x y, times_cont_diff_add.times_cont_diff_on⟩, smooth_neg := smooth_iff.2 ⟨continuous_neg, λ x y, times_cont_diff_neg.times_cont_diff_on⟩, .. model_space_smooth }
185b11657df0727fc499c4ddad9ac72ec97b42a7
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Init/Dynamic.lean
ec1cc5b8f4dc408478c56edd9805a5571aebc166
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
2,842
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ prelude import Init.Core open Lean -- Implementation detail of TypeName, since classes cannot be opaque private opaque TypeNameData (α : Type u) : NonemptyType.{0} := ⟨Name, inferInstance⟩ /-- Dynamic type name information. Types with an instance of `TypeName` can be stored in an `Dynamic`. The type class contains the declaration name of the type, which must not have any universe parameters and be of type `Sort ..` (i.e., monomorphic). The preferred way to declare instances of this type is using the derive handler, which will internally use the unsafe `TypeName.mk` function. Morally, this is the same as: ```lean class TypeName (α : Type) where unsafe mk :: typeName : Name ``` -/ @[nospecialize] class TypeName (α : Type u) where private mk' :: private data : (TypeNameData α).type instance : Nonempty (TypeName α) := (TypeNameData α).property.elim (⟨⟨·⟩⟩) /-- Creates a `TypeName` instance. For safety, it is required that the constant `typeName` is definitionally equal to `α`. -/ unsafe def TypeName.mk (α : Type u) (typeName : Name) : TypeName α := ⟨unsafeCast typeName⟩ private unsafe def TypeName.typeNameImpl (α) [TypeName α] : Name := unsafeCast (@TypeName.data α _) /-- Returns a declaration name of the type. -/ @[implementedBy TypeName.typeNameImpl] opaque TypeName.typeName (α) [TypeName α] : Name private opaque DynamicPointed : NonemptyType.{0} := ⟨Name × NonScalar, inferInstance⟩ /-- Type-tagged union that can store any type with a `TypeName` instance. This is roughly equivalent to `(α : Type) × TypeName α × α` but without the universe bump. -/ def Dynamic : Type := DynamicPointed.type instance : Nonempty Dynamic := DynamicPointed.property private unsafe def Dynamic.typeNameImpl (any : Dynamic) : Name := (unsafeCast any : Name × NonScalar).1 /-- The name of the type of the value stored in the `Dynamic`. -/ @[implementedBy Dynamic.typeNameImpl] opaque Dynamic.typeName (any : Dynamic) : Name private unsafe def Dynamic.get?Impl (α) (any : Dynamic) [TypeName α] : Option α := let ((typeName, obj) : Name × NonScalar) := unsafeCast any if typeName == TypeName.typeName α then some (unsafeCast obj) else none /-- Retrieves the value stored in the `Dynamic`. Returns `some a` if the value has the right type, and `none` otherwise. -/ @[implementedBy Dynamic.get?Impl] opaque Dynamic.get? (α) (any : Dynamic) [TypeName α] : Option α private unsafe def Dynamic.mkImpl [TypeName α] (obj : α) : Dynamic := unsafeCast (TypeName.typeName α, (unsafeCast obj : NonScalar)) @[implementedBy Dynamic.mkImpl] opaque Dynamic.mk [TypeName α] (obj : α) : Dynamic
1585724ca66a809d1c3de92b208edb2a3046880c
a975e2962782fb953969766cc7133ba18aaa60c9
/src/more.lean
f5d58cfe849fb25a9f702347b0973fd48a51cbfe
[]
no_license
leodemoura/alc-lean
f3d3efa0f11b0a663ea74c74c10085212ba52295
6e3fce980ec3bb95aeda667062da86a45036fce9
refs/heads/master
1,678,082,711,848
1,612,907,314,000
1,612,907,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,457
lean
definition satisfiable (C : Concept) : Prop := exists I : Interp, @interp I C ≠ ∅ definition subsumption (C D: Concept) : Prop := forall I : Interp, @interp I C ⊂ @interp I D infix `⊑` : 50 := subsumption -- \sqsubseteq definition equivalence (C D: Concept) : Prop := C⊑D∧D⊑C infix `≡` : 50 := equivalence -- \== definition TBOX_subsumption (D : @Set Prop) (α : Prop) : Prop := (forall p: Prop, (p∈D → p)) → α infix `⊧` : 1 := TBOX_subsumption --\models definition models_proof (Ω: @Set Prop) (α: Prop) (h: (∀p: Prop, (p∈ Ω → p)) → α) : Ω⊧α := h example (C D : Concept) : C ⊓ D ⊑ C := take (I : Interp), take x : Interp.δ I, assume h : x ∈ interp (C⊓D), have l: x ∈ (interp C)∩(interp D), from h, have l2: x∈(interp C)∧x∈(interp D), from (iff.elim_left (IntersMember x)) l, show x∈(interp C), from and.elim_left l2 example (A B : Concept) : A ⊓ B ⊑ A ⊔ B := sorry example (C D E : Concept) : (Set.spec (λp: Prop, p = C ⊑ D ∨ p = D ⊑ E)) ⊧ C ⊑ E := assume h: forall (p: Prop), (p∈(Set.spec (λp: Prop, p = C⊑D ∨ p = D⊑E)) → p), have l1: C⊑D = C⊑D, from rfl, have l2: C⊑D = C⊑D ∨ C⊑D = D⊑E, from or.intro_left (C⊑D = D⊑E) l1, have l3: C⊑D ∈ (Set.spec (λp: Prop, p = C⊑D ∨ p = D⊑E)), from l2, have l4: D⊑E = D⊑E, from rfl, have l5: D⊑E = C⊑D ∨ D⊑E = D⊑E, from or.intro_right (D⊑E = C⊑D) l4, have l6: D⊑E ∈ (Set.spec (λp: Prop, p = C⊑D ∨ p = D⊑E)), from l5, have l7: C⊑D, from h (C⊑D) l3, have l8: D⊑E, from h (D⊑E) l6, assume I : Interp, take x : Interp.δ I, assume h2: x∈ interp C, have l9: x∈ interp D, from l7 I x h2, show x ∈ interp E, from l8 I x l9 inductive Label : Type := | all : Role → Label | ex : Role → Label notation `∀;` R := Label.all R inductive LabelConc : Type := -- labeled concept | mk : list Label → Concept → LabelConc notation L `[` C `]` := LabelConc.mk L C -- label to prefix definition LabelToPrefix [reducible] : list Label → (Concept → Concept) | LabelToPrefix nil C := C | LabelToPrefix ((Label.all R)::L) C := ∀;R . (LabelToPrefix L C) | LabelToPrefix ((Label.ex R)::L) C := ∃;R .(LabelToPrefix L C) definition getLabelList : LabelConc → list Label | getLabelList (LabelConc.mk L C) := L definition σ [reducible] : LabelConc → Concept | σ (LabelConc.mk L C) := (LabelToPrefix L) C -- negation of a list of labels definition negLabel: list Label → list Label | negLabel nil := nil | negLabel ((Label.all R)::L) := (Label.ex R)::(negLabel L) | negLabel ((Label.ex R)::L) := (Label.all R)::(negLabel L) definition AppendLabelList (L: list Label) (α: LabelConc) : LabelConc := LabelConc.rec_on α (λ(R: list Label) (C: Concept), (L++R)[C]) definition isNullLabelList : list Label → bool | isNullLabelList nil := tt | isNullLabelList (L::R) := ff definition isAllLabel : Label → bool | isAllLabel (Label.all R) := tt | isAllLabel (Label.ex R) := ff definition isExLabel : Label → bool | isExLabel (Label.all R) := ff | isExLabel (Label.ex R) := tt definition internalLabel : list Label → list Label | internalLabel nil := nil | internalLabel (R::L) := cond (isNullLabelList L) (R::nil) (internalLabel L) definition remainderLabel : list Label → list Label | remainderLabel nil := nil | remainderLabel (R::L) := cond (isNullLabelList L) nil (R::(remainderLabel L)) definition downLabelConc : LabelConc → Concept | downLabelConc (LabelConc.mk L C) := LabelToPrefix L C definition downInternalLabel : LabelConc → LabelConc | downInternalLabel (LabelConc.mk L C) := LabelConc.mk (remainderLabel L) ((LabelToPrefix (internalLabel L)) C) definition isOnlyAllLabel : list Label → bool | isOnlyAllLabel nil := tt | isOnlyAllLabel ((Label.all R)::L) := isOnlyAllLabel L | isOnlyAllLabel ((Label.ex R)::L) := ff definition isOnlyExLabel : list Label → bool | isOnlyExLabel nil := tt | isOnlyExLabel ((Label.all R)::L) := ff | isOnlyExLabel ((Label.ex R)::L) := (isOnlyExLabel L) definition is_true [reducible] (b : bool) := b = tt /- namespace tests -- tests constant C: Concept constants R1 R2 R3 : Role eval internalLabel (Label.ex R3 (Label.ex R1 (Label.all R2 (Label.null)))) eval remainderLabel (Label.ex R3 (Label.ex R1 (Label.all R2 (Label.null)))) definition test := LabelConc.mk (Label.ex R3 (Label.ex R1 (Label.all R2 (Label.null)))) C eval downInternalLabel test end tests-/ -- Structural Rules definition isNil {A: Type} : list A → bool | isNil nil := tt | isNil (a :: l) := ff definition AntecedentWrap : list LabelConc → Concept -- Não está sendo utilizado | AntecedentWrap nil := ⊤ | AntecedentWrap (α :: L) := list.rec_on L (σ α) (λα2 L2 C2, (σ α)⊓(AntecedentWrap L)) definition ConsequentWrap : list LabelConc → Concept | ConsequentWrap nil := ⊥ | ConsequentWrap (α :: L) := list.rec_on L (σ α) (λα2 L2 C2, (σ α)⊔(ConsequentWrap L)) definition AInterp [reducible] {I: Interp} : list LabelConc → @Set (Interp.δ I) -- Antecedent Interpretation | AInterp nil := U | AInterp (α :: L) := (interp (σ α))∩(AInterp L) definition CInterp [reducible] {I: Interp} : list LabelConc → @Set (Interp.δ I) -- Consequent Interpretation | CInterp nil := ∅ | CInterp (α::L) := (interp (σ α))∪(CInterp L) set_option pp.universes true set_option unifier.max_steps 1000000 definition AInterp_append {I: Interp} (Δ1 Δ2: list LabelConc) : @AInterp I ((Δ1)++Δ2) = (AInterp Δ1)∩(AInterp Δ2) := begin apply (list.induction_on Δ1), apply eq.trans, rewrite (eq.refl (nil++Δ2)), apply (eq.refl (AInterp Δ2)), rewrite (Inters_commu (AInterp nil) (AInterp Δ2)), apply (eq.symm IntersUniv), intro a, intro Δ, intro IndHyp, rewrite (append_cons a Δ Δ2), rewrite {AInterp (a::Δ)}(eq.refl ((interp (σ a))∩(AInterp Δ))), rewrite -(!Inters_assoc), rewrite -IndHyp, end definition CInterp_append {I: Interp} (Δ1 Δ2: list LabelConc) : @CInterp I ((Δ1)++Δ2) = (CInterp Δ1)∪(CInterp Δ2) := begin apply (list.induction_on Δ1), apply eq.trans, rewrite (eq.refl (nil++Δ2)), apply (eq.refl (CInterp Δ2)), rewrite (Union_commu (CInterp nil) (CInterp Δ2)), rewrite {CInterp nil}(eq.refl ∅), rewrite -(eq.symm UnionEmpty), intro a, intro Δ, intro IndHyp, rewrite (append_cons a Δ Δ2), rewrite {CInterp (a::Δ)}(eq.refl ((interp (σ a))∪(CInterp Δ))), rewrite -(!Union_assoc), rewrite -IndHyp, end inductive sequent (Δ : list LabelConc) (Γ: list LabelConc) : Prop := infix `⇒`:51 := sequent | intro : (∀I: Interp, (@AInterp I Δ) ⊂ CInterp Γ) → Δ⇒Γ infix `⇒`:51 := sequent -- Duas definições apenas para conseguir usar a notação {a,b} para as listas de LabelConc e somente para elas definition label_conc_append (a: list LabelConc) (b: list LabelConc): list LabelConc := append a b local notation `{` a `,` b`}` := label_conc_append a b definition label_conc_cons (a: list LabelConc) (b: LabelConc): list LabelConc := b::a local notation `{` b `,` a`}` := label_conc_cons a b -- notation overload definition label.to_labellist [coercion] (l: Label) : list Label := l::nil definition Concept.to_LabelConc [coercion] (C: Concept) : LabelConc := nil[C] definition LabelConc.to_ListLabelConc [coercion] (a: LabelConc) : list LabelConc := a::nil namespace test constants X R : Role constant C: Concept constant L: Label constant M: list Label check ∃;R check (L::L)[C] check ((∀;R) ++ (∀;R))[C] check ∀; R . C check { M[C] , M[C] } eval { ((∀;R)::L)[C] , C} check M[C] check L[C] check (∀;R : list Label)[C] end test namnespace test2 constant a: list LabelConc constant b: list LabelConc constant c: LabelConc constant d: Label constant e: Concept constant d2: Label check a++b check {a,b} check {c,a} check {(d::nil)[e],a} check {d[e],a} check {(d2::d2::d)[e],a} -- Seria interessante conseguir utilizar a notação {a, b, b}... end test2 namespace sequent definition meaning {Δ : list LabelConc} {Γ: list LabelConc} (h: Δ⇒Γ) : ∀I: Interp, (@AInterp I Δ) ⊂ CInterp Γ := -- elimination rule for sequents sequent.rec_on h (assume h2: ∀I: Interp, (@AInterp I Δ) ⊂ CInterp Γ, take I: Interp, h2 I) end sequent open Label inductive SCALCproof (Ω: @Set Prop) : Prop → Prop := infix `⊢` : 25 := SCALCproof -- \vdash | hypo : Π{α: Concept}, Ω⊢(nil[α]::nil)⇒(nil[α]::nil) -- fazer uma coercion concept -> labeled concept | ex_falsum : Π(α: Concept), Ω⊢(nil[⊥]::nil) ⇒ (nil[α]::nil) | weak_l : Π(Δ Γ: list LabelConc) (δ: LabelConc), Ω⊢(Δ⇒Γ) → Ω⊢(δ::Δ)⇒Γ | weak_r : Π(Δ Γ: list LabelConc) (γ: LabelConc), Ω⊢Δ⇒Γ → Ω⊢Δ⇒(γ::Γ) | contraction_l : Π(Δ Γ: list LabelConc) (δ: LabelConc), Ω⊢(δ::δ::Δ)⇒Γ → Ω⊢(δ::Δ)⇒Γ | contraction_r : Π(Δ Γ: list LabelConc) (γ: LabelConc), Ω⊢Δ⇒(γ::γ::Γ) → Ω⊢Δ⇒(γ::Γ) | perm_l : Π(Δ1 Δ2 Γ: list LabelConc) (δ1 δ2: LabelConc), Ω⊢Δ1++(δ1::δ2::Δ2)⇒Γ → Ω⊢(Δ1++(δ2::δ1::Δ2))⇒Γ | perm_r : Π(Δ Γ1 Γ2: list LabelConc) (γ1 γ2: LabelConc), Ω⊢Δ⇒Γ1++(γ1::γ2::Γ2) → Ω⊢Δ⇒Γ1++(γ2::γ1::Γ2) | cut : Π(Δ1 Δ2 Γ1 Γ2: list LabelConc) (α: LabelConc), Ω⊢Δ1⇒α::Γ1 → Ω⊢α::Δ2⇒Γ2 → Ω⊢Δ1++Δ2⇒Γ1++Γ2 | and_l : Π(Δ Γ : list LabelConc) (L: list Label) (α β : Concept) (p: is_true (isOnlyAllLabel L)), Ω⊢(L[α]::L[β]::Δ)⇒Γ → Ω⊢(L[α⊓β]::Δ)⇒Γ | all_r : Π(Δ Γ: list LabelConc) (L: list Label) (α: Concept) (R: Role), Ω⊢ Δ⇒{ (L++(∀;R))[α], Γ} → Ω⊢ Δ⇒{ (L[∀;R .α]), Γ} infix `⊢` : 25 := SCALCproof definition cut_soundness (Ω: @Set Prop) (Δ1 Δ2 Γ1 Γ2: list LabelConc) (α: LabelConc) : (Ω⊧ Δ1⇒α::Γ1) → (Ω⊧ α::Δ2⇒Γ2) → (Ω⊧ Δ1++Δ2⇒Γ1++Γ2) := assume h: Ω⊧Δ1⇒α::Γ1, assume h2: Ω⊧α::Δ2⇒Γ2, assume h3: ∀p: Prop, (p∈ Ω → p), have l1: Δ1⇒α::Γ1, from h h3, have l2: α::Δ2⇒Γ2, from h2 h3, have l3: ∀I: Interp, AInterp Δ1 ⊂ CInterp (α::Γ1), from sequent.meaning l1, have l4: ∀I: Interp, AInterp (α::Δ2) ⊂ CInterp Γ2, from sequent.meaning l2, assert l5: (∀I: Interp, AInterp Δ1 ⊂ (interp (σ α)∪(CInterp Γ1))), from take I: Interp, eq.subst rfl (l3 I), assert l6: (∀I: Interp, (@interp I (σ α)) ∩ (AInterp Δ2) ⊂ (CInterp Γ2)), from take I: Interp, eq.subst rfl (l4 I), show Δ1++Δ2⇒(Γ1++Γ2), from begin apply sequent.intro, intro I, rewrite [(AInterp_append Δ1 Δ2), (CInterp_append Γ1 Γ2)], exact (SetCut (l5 I) (l6 I)), end definition drop_last_all_label {L: list Label} {α: Concept} {R: Role} : σ ((L++(∀;R))[α]) = σ(L[∀;R . α]) := sorry definition all_r_soundness (Ω: @Set Prop) (Δ Γ: list LabelConc) (L: list Label) (α: Concept) (R: Role): (Ω⊧ (Δ⇒{ (L++(∀;R))[α], Γ})) → (Ω⊧ Δ⇒{ L[∀;R .α], Γ}) := assume h: Ω⊧( Δ⇒{ (L++(∀;R))[α], Γ}), assume h2: ∀p: Prop, (p∈Ω → p), have l1: Δ⇒{ (L++(∀;R))[α], Γ}, from h h2, assert l2: ∀I: Interp, AInterp Δ ⊂ CInterp { (L++(∀;R))[α], Γ}, from sequent.meaning l1, assert l3: (σ ((L++(∀;R))[α])) = (σ (L[∀;R . α])), from drop_last_all_label, have l4: (CInterp {(L++(∀;R))[α], Γ}) = (CInterp {L[∀;R. α], Γ}), from begin esimp, rewrite l3, end, --have l3: (CInterp {(L++(∀;R))[α], Γ}) = (CInterp {L[∀;R. α], Γ}), from sorry, show Δ ⇒ {(L[∀;R .α]), Γ}, from begin apply sequent.intro, intro I, end section hide constants (Δ Γ: list LabelConc) (L: list Label) (α: Concept) (R: Role) check (eq.refl (CInterp { (L++(∀;R))[α], Γ})) end hide axiom Axiom2_1 (R: Role) (α β: Concept) : ValueRestr R α⊓β ≡ (ValueRestr R α) ⊓ (ValueRestr R β) /- definition and_l_soundness (Ω: @Set Prop) (Δ Γ: list LabelConc) (L: list Label) (α β: Concept) (p: is_true (isOnlyAllLabel L)) : (Ω⊧ (L[α]::L[β]::Δ)⇒Γ) → (Ω⊧ (L[α⊓β]::Δ)⇒Γ) := assume h: Ω⊧ (L[α]::L[β]::Δ)⇒Γ, assume h2: ∀q: Prop, (q∈ Ω → q), assert l1: (L[α]::L[β]::Δ)⇒Γ, from h h2, begin apply sequent.meaning, end -/ end ALC
a3a99bf6e61df50a3c321d46e541fb155f5dee5f
3d2a7f1582fe5bae4d0bdc2fe86e997521239a65
/spatial-reasoning/spatial-reasoning-problem-15.lean
5a4b4360f3faaa7c1f8f1d71ddb15d48e587da1c
[]
no_license
own-pt/common-sense-lean
e4fa643ae010459de3d1bf673be7cbc7062563c9
f672210aecb4172f5bae265e43e6867397e13b1c
refs/heads/master
1,622,065,660,261
1,589,487,533,000
1,589,487,533,000
254,167,782
3
2
null
1,589,487,535,000
1,586,370,214,000
Lean
UTF-8
Lean
false
false
195
lean
/- Spatial Reasoning Problem 15 -/ /- It can be found at: SpatialQs.txt -/ /- (15) John is standing to the left of the platform and jumps over it. Is he still to the left of the platform? -/
c5de8a70f79707a9936ced03281315dc1a9eccb3
92c6b42948d74fe325c2d88530f1d36da388b2f7
/src/smtlib.lean
c6d66fa360832de807775e949ad96443c3216494
[ "MIT" ]
permissive
riaqn/smtlean
8ad65055b6c1600cd03b9e345059a3b24419b6d5
c11768cfb43cd634340b552f5039cba094701a87
refs/heads/master
1,584,569,627,940
1,535,314,713,000
1,535,314,713,000
135,333,334
0
1
null
null
null
null
UTF-8
Lean
false
false
2,950
lean
import system.io import .sexp import .common attribute [reducible] def sort := string structure declare : Type := (symbol : symbol) (sort : sort) -- term as in smtlib inductive term : Type | literal : literal → term | symbol : symbol → term | app : symbol → list term → term -- application structure query := (declares : list declare) (asserts : list term) -- a value assignment in model structure value := (symbol : symbol) (sort : sort) (term : term) -- a model is a list of assignments def model := list value inductive cmd : Type | assert : term → cmd | check_sat : cmd | exit : cmd | set_logic : string -> cmd | declare_const : declare -> cmd | get_model : cmd | get_proof : cmd mutual def term_from_sexp, list_term_from_sexp with term_from_sexp : sexp → except string term | (! s) := except.ok $ term.symbol s | (# lit) := except.ok $ term.literal lit | (. (! func) :: l) := term.app func <$> monad.sequence (list_term_from_sexp l) | _ := except.error "doesn't seem like a term" with list_term_from_sexp : list sexp → list (except string term) | [ ] := [] | (e :: l') := term_from_sexp e :: list_term_from_sexp l' instance : has_from_sexp string := ⟨ λ e, match e with | ! x := except.ok x | _ := except.error "doesn't look like a string" end ⟩ instance : has_from_sexp term := ⟨ term_from_sexp ⟩ instance : has_from_sexp value := ⟨ λ e, match e with | . [ ! "define-fun", symbol, . [], sort, term] := value.mk <$> (from_sexp symbol) <*> (from_sexp sort) <*> (from_sexp term) | _ := except.error "doesn't looks like a assignment" end ⟩ instance : has_from_sexp model := ⟨ λ e, match e with | . (! "model") :: l := monad.sequence $ l.map from_sexp | _ := except.error "doesn't seem like a model" end ⟩ mutual def term_to_sexp, list_term_to_sexp with term_to_sexp : term → sexp | (term.literal l) := # l | (term.symbol i) := ! i | (term.app f l) := . (! f) :: list_term_to_sexp l with list_term_to_sexp : list term → list sexp | [ ] := [ ] | (t :: l') := term_to_sexp t :: list_term_to_sexp l' instance : has_to_sexp term := ⟨ term_to_sexp ⟩ instance : has_to_sexp value := ⟨ λ v, . [ ! v.symbol, ! v.sort, to_sexp v.term ]⟩ instance : has_to_sexp model := ⟨ λ m, . ( (! "model") :: m.map to_sexp )⟩ instance has_to_string_via_sexp {α : Type } [has_to_sexp α] : has_to_string α := ⟨ λ a, to_string $ to_sexp a ⟩ instance has_from_buffer_via_sexp {α : Type _} [has_from_sexp α] : has_from_buffer α := ⟨ λ s, do e ← from_buffer s, from_sexp e ⟩ def cmd_to_sexp : cmd → sexp | (cmd.assert t) := . [! "assert" , term_to_sexp t] | (cmd.check_sat) := . [! "check-sat"] | (cmd.exit) := . [! "exit"] | (cmd.set_logic s) := . [! "set-logic", ! s] | (cmd.declare_const d) := . [! "declare-const", ! d.symbol, ! d.sort ] | (cmd.get_model) := . [! "get-model"] | (cmd.get_proof) := . [! "get-proof"] instance : has_to_sexp cmd := ⟨ cmd_to_sexp ⟩
1d947cf85bd686b2fc39f2b04f152f432dc9502f
b0d97c09d47e3b0a68128c64cad26ab132d23108
/src/compcont/ex1.lean
81290aab870e64eeee2e9e7ce105647f87a68db5
[]
no_license
jmvlangen/RIP-seminar
2ad32c1c6fceb59ac7ae3b2251baf08f4c0c0caa
ed6771404dd4bcec298de2dfdc89d5e9cfd331bb
refs/heads/master
1,585,865,817,237
1,546,865,823,000
1,546,865,823,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,985
lean
import analysis.topology.topological_space import analysis.topology.continuity import analysis.topology.topological_structures open tactic expr variables {X : Type*} {Y : Type*} {Z : Type*} {W : Type*} {f f₁ f₂ : X → Y} {g : Y → Z} {h : Z → W} variables [topological_space X] [topological_space Y] [topological_space Z] [topological_space W] -- Finish a goal of the form continuous (f ∘ g ∘ ... ) given all functions are continuous. meta def contcomp : tactic unit := do `(continuous %%e) ← target <|> fail "goal has to be of the form 'continuous _'", -- if the goal is to show that the expression e is continuous, check if it is an assumption assumption <|> -- if e is not continuous by assumption, check if it is of the form 'f ∘ g' for some f and g do `(%%outer ∘ %%inner) ← return e <|> fail "not continuous by assumption, and not a compsition", -- assert that the outer function is continuous, if not, rotate the goal away outer_continuous ← to_expr ``(continuous %%outer), outer_is_continuous ← assert "h_outer_cont" outer_continuous, contcomp <|> rotate 1, -- assert that the inner function is continuous, if not, rotate the goal away inner_continuous ← to_expr ``(continuous %%inner), inner_is_continuous ← assert "h_inner_cont" inner_continuous, contcomp <|> rotate 1, -- knowing that inner and outer function are continuous, apply the theorem continuous.comp -- which shows that the composite is continuous cont_comp ← to_expr ``(continuous.comp %%inner_is_continuous %%outer_is_continuous), exact cont_comp example (_ : continuous f) (_ : continuous g) (_ : continuous h) : continuous (h ∘ g ∘ f) := by contcomp example (_ : continuous f₁) (_ : continuous f₂) [add_monoid Y] : continuous (λ x, f₁ x + f₂ x) := sorry example (_ : continuous f) (_ : continuous g) [add_monoid Y] : continuous (λ x, g $ f x) := by contcomp
1d1451c4edf0902b015069e6031179dbf65406ac
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/sec_bug.lean
c7500b97dd5f7b491a59454168ee6ad302ae2072
[ "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
96
lean
import logic namespace foo section bla definition tst := true end bla end foo check foo.tst
113fc6a7ae890b1b64260fabca77311c0be2ee5a
94637389e03c919023691dcd05bd4411b1034aa5
/src/assignments/assignment_6/field_rename.lean
60ada55355ad440156674dedab7228710735cef7
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
1,022
lean
import ...inClassNotes.typeclasses.algebra /- Inheriting two fields with same name -/ open alg -- need to enable "old_structure" option here class another_two_muls (A : Type) extends mul_groupoid A renaming mul→mul1, mul_groupoid A renaming mul→mul2 instance another_two_muls_nat : another_two_muls nat := ⟨ nat.mul, nat.add ⟩ def nat_nat_mul1 [another_two_muls nat] (a b : ℕ) := another_two_muls.mul2 a b #eval nat_nat_mul1 2 3 /- Inheriting same field twice -/ class inh_mul1 (A : Type) extends mul_groupoid A := (n : ℕ) instance inh_mul1_nat : inh_mul1 nat := ⟨ nat.mul, 3 ⟩ class inh_mul2 (A : Type) extends mul_groupoid A := (b : bool) instance inh_mul2_nat : inh_mul2 nat := ⟨ nat.add, tt ⟩ class inh_mul_twice (A : Type) extends inh_mul1 A, inh_mul2 A := (s : string) instance inh_mul_twice_nat : inh_mul_twice nat := ⟨ nat.mul, 5, ff, "Hi" ⟩ instance inh_mul_twice_nat2 : inh_mul_twice nat := ⟨ inh_mul2.mul, 5, ff, "Hi" ⟩
3cd80784bfe78288db8864b9d029843b608a9534
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/elabissues/issues2.lean
9842c31f17dc33134845899c4e1a8a784a18ef54
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,547
lean
inductive Syntax | atom : String → Syntax | node : String → Array Syntax → Syntax instance coe1 : HasCoe String Syntax := ⟨Syntax.atom⟩ instance coe2 {α} : HasCoe (List α) (Array α) := ⟨List.toArray⟩ def ex7 : Syntax := /- We try to elaborate `["bla"]` with expected type `Array Syntax`. The expected type is "discarded" since we fail to unify `Array Syntax =?= List ?A` where `List ?A` is the resulting type for `List.cons` application before we process its children. Remark: the elaborator does **not** try to use coercions here. Even if it tried, it would fail since `List ?A` contains a meta-variable. Then, we elaborate `["bla"]` without an expected type and produce a term of type `List String`. Finally, we fail with a type mismatch between `List String` and `Array Nat`. We can make it work by using: ``` instance coe3 {α β} [HasCoe α β] : HasCoe (List α) (Array β) := ⟨fun xs => (xs.map (fun x => (coe x : β))).toArray⟩ ``` -/ Syntax.node "foo" ["bla"] def ex8 : Syntax := Syntax.node "foo" (List.toArray ["boo"]) -- Works def ex9 : Syntax := /- We need the type of `["boo"]` to be able to apply `.toArray`. So, we elaborate `["boo"]` first without expected type, and then obtain `Array String`, and then a type mismatch between `Array String` and `Array Syntax`. We can make it work by using: ``` instance coe3 {α β} [HasCoe α β] : HasCoe (Array α) (Array β) := ⟨fun xs => (xs.map (fun x => (coe x : β)))⟩ ``` But, the behavior is still confusing to users. -/ Syntax.node "foo" ["boo"].toArray
6532635306c6ae501f7a642bf8d16f88808a321b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/collectDepsIssue.lean
5c3d4dba63563dd198fcdddf37c2ed344b86f55d
[ "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
244
lean
variable {α : Type} in def f (a : α) : List α := _ variable (P : List Nat → List Nat → Prop) in theorem foo (xs : List Nat) : (ns : List Nat) → P xs ns | [] => sorry | (n::ns) => by { cases xs; exact sorry; exact sorry }
2330eaf5e3fcb809bf03467280ca1d490a3bcce1
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/tests/lean/vm_sorry.lean
c9df8971c9d08f04acded8e5a6941f05db3d8d1d
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
419
lean
def half_baked : bool → ℕ | tt := 42 | ff := sorry #eval (half_baked tt) #eval (half_baked ff) meta def my_partial_fun : bool → ℕ | tt := 42 | ff := undefined #eval (my_partial_fun ff) open expr tactic run_cmd (do v ← to_expr ``(half_baked ff) >>= whnf, trace $ to_string v^.is_sorry) example : 0 = 1 := by sorry example : 0 = 1 := by mk_sorry >>= exact example : 0 = 1 := by exact sorry
9e713702224a9997e6a8986caffc3a88b32fb80b
3ef5255cebe505e5ab251615d9fbf31a132f461d
/lean/old/semisimplicial.lean
f836ff81112443cae3e7165c853408b255a4ea9a
[]
no_license
avigad/scratch
42441a2ea94918049391e44d7adab304d3adea51
3fb9cef15bc5581c9602561427a7f295917990a2
refs/heads/master
1,608,917,412,424
1,473,078,921,000
1,473,078,921,000
17,224,172
0
0
null
null
null
null
UTF-8
Lean
false
false
10,432
lean
-- Copyright (c) 2014 Jeremy Avigad. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jeremy Avigad -- semisimplicial types -- ==================== -- This construction was explained to me by Richard Garner. I believe it is essentially the -- same as one presented by Vladimir Voevodsky. -- -- The intuition: (SS n) and (Bd n) are defined recursively. For each n: -- -- SS n represents the (n-1)-dimensional simplicial types. -- For each X : SS n, Bd n X m represents the maps from sk_n (Delta_m) into X. import logic algebra.category.constructions data.nat import logic.axioms.funext open nat sigma function category functor open category.opposite -- some cast calculus -- clean up and move theorem eq_rec_on_heq {A : Type} {a a' : A} {B : Πa' : A, a = a' → Type} (H1 : a = a') (H2 : B a (eq.refl a)) : eq.rec_on H1 H2 == H2 := eq.rec_on H1 (heq.from_eq rfl) theorem eq_cast_to_heq {A B : Type} {a : A} {b : B} {H : A = B} (H1 : b = cast H a) : b == a := heq.symm (cast_eq_to_heq (eq.symm H1)) -- For now, axiomatize increasing maps from i to j. -- Later we can construct them using lists or ordinal types. universe u constant inc_map (i j : nat) : Type.{u} constant inc_id {i : nat} : inc_map i i constant inc_comp ⦃i j k : nat⦄ (α : inc_map j k) (β : inc_map i j) : inc_map i k axiom inc_comp_assoc ⦃i j k l : nat⦄ (α : inc_map k l) (β : inc_map j k) (γ : inc_map i j) : inc_comp α (inc_comp β γ) = inc_comp (inc_comp α β) γ axiom inc_comp_idr ⦃i j : nat⦄ (α : inc_map i j) : inc_comp α inc_id = α axiom inc_comp_idl ⦃i j : nat⦄ (α : inc_map i j) : inc_comp inc_id α = α definition Delta := category.mk (λi j, inc_map i j) inc_comp @inc_id inc_comp_assoc inc_comp_idl inc_comp_idr definition Delta_op [instance] := opposite Delta instance type_category -- level 0: the connected components -- --------------------------------- definition SS0 := Type context Bd0 parameter X : SS0 definition Bd0_object (m : nat) := X definition Bd0_morphism {i j : nat} (α : inc_map j i) (x : Bd0_object i) : Bd0_object j := x theorem Bd0_respect_id (i : nat) : Bd0_morphism (@inc_id i) = λx, x := rfl theorem Bd0_respect_comp (i j k : nat) (β : inc_map k j) (α : inc_map j i) : Bd0_morphism (inc_comp α β) = Bd0_morphism β ∘ Bd0_morphism α := rfl definition Bd0 : functor Delta_op type_category := functor.mk Bd0_object (@Bd0_morphism) Bd0_respect_id Bd0_respect_comp end Bd0 -- successor step -- -------------- context SSn' parameter n : nat -- assume n case is done parameter SSn : Type parameter Bdn (X : SSn) : functor Delta_op type_category definition SSn' := ΣX : SSn, (Bdn X (succ n) → Type) context Bdn' parameter X : SSn' definition dpr1_X := dpr1 X definition dpr2_X := dpr2 X definition BdnX_obj := @(object (Bdn (dpr1_X))) definition BdnX_mor := @(morphism (Bdn (dpr1_X))) definition Bdn'_object (m : nat) := Σb : BdnX_obj m, Πα : inc_map (succ n) m, dpr2_X (BdnX_mor α b) definition Bdn'_dpair {m : nat} (b : BdnX_obj m) (f : Πα : inc_map (succ n) m, dpr2_X (BdnX_mor α b)) : Bdn'_object m := dpair b f definition Bdn'_dpr1 {m : nat} (b : Bdn'_object m) := dpr1 b definition Bdn'_dpr2 {m : nat} (b : Bdn'_object m) := dpr2 b theorem Bdn'_object_equal {m : nat} {b1 b2 : Bdn'_object m} (H1 : Bdn'_dpr1 b1 = Bdn'_dpr1 b2) (H2 : eq.rec_on H1 (Bdn'_dpr2 b1) = Bdn'_dpr2 b2) : b1 = b2 := sigma.equal H1 H2 theorem Bdn'_object_equal' {m : nat} {b1 b2 : Bdn'_object m} (H1 : Bdn'_dpr1 b1 = Bdn'_dpr1 b2) (H2 : ∀α : inc_map (succ n) m, eq.rec_on H1 (Bdn'_dpr2 b1 α) = Bdn'_dpr2 b2 α) : b1 = b2 := have H3 : eq.rec_on H1 (Bdn'_dpr2 b1) = λα : inc_map (succ n) m, eq.rec_on H1 (Bdn'_dpr2 b1 α), from eq.rec_on H1 rfl, have H4 : (λα : inc_map (succ n) m, eq.rec_on H1 (Bdn'_dpr2 b1 α)) = Bdn'_dpr2 b2, from funext H2, Bdn'_object_equal H1 (eq.trans H3 H4) theorem Bdn'_fun_eq {i j : nat} {f1 f2 : Bdn'_object i → Bdn'_object j} (H : ∀b : BdnX_obj i, ∀f : Πα : inc_map (succ n) i, dpr2 X (Bdn (dpr1 X) α b), f1 (Bdn'_dpair b f) = f2 (Bdn'_dpair b f)) : f1 = f2 := funext (take b : Bdn'_object i, sigma.destruct b H) theorem comp_eq_aux {i j : nat} (α : inc_map j i) (α' : inc_map (succ n) j) (b : Bdn'_object i) : dpr2_X (BdnX_mor (inc_comp α α') (Bdn'_dpr1 b)) = dpr2_X (((BdnX_mor α') ∘ (BdnX_mor α)) (Bdn'_dpr1 b)) := have H1 : BdnX_mor (inc_comp α α') = (BdnX_mor α') ∘ (BdnX_mor α), from !respect_comp, congr_arg _ (congr_fun H1 _) definition Bdn'_morphism {i j : nat} (α : inc_map j i) (b : Bdn'_object i) : Bdn'_object j := Bdn'_dpair (BdnX_mor α (Bdn'_dpr1 b)) (take α' : inc_map (succ n) j, cast (comp_eq_aux α α' b) (Bdn'_dpr2 b (inc_comp α α'))) -- TODO: why do I have to supply the predicate for eq.rec_on? theorem aux (i : nat) (b : BdnX_obj i) (f : Πα : inc_map (succ n) i, dpr2_X (BdnX_mor α b)) (H1 : Bdn'_dpr1 (Bdn'_morphism (@inc_id i) (Bdn'_dpair b f)) = Bdn'_dpr1 (Bdn'_dpair b f)) (α : inc_map (succ n) i) : @eq.rec_on _ _ _ (fun b e, dpr2_X (BdnX_mor α b)) H1 (Bdn'_dpr2 (Bdn'_morphism (@inc_id i) (Bdn'_dpair b f)) α) = Bdn'_dpr2 (Bdn'_dpair b f) α := let H' := comp_eq_aux (@inc_id i) α (Bdn'_dpair b f) in have H2 : Bdn'_dpr2 (Bdn'_morphism (@inc_id i) (Bdn'_dpair b f)) α = cast H' (f (inc_comp (@inc_id i) α)), from rfl, have H3 : @eq.rec_on _ _ _ (fun b e, dpr2_X (BdnX_mor α b)) H1 (Bdn'_dpr2 (Bdn'_morphism (@inc_id i) (Bdn'_dpair b f)) α) == Bdn'_dpr2 (Bdn'_dpair b f) α, from calc @eq.rec_on _ _ _ (fun b e, dpr2_X (BdnX_mor α b)) H1 (Bdn'_dpr2 (Bdn'_morphism (@inc_id i) (Bdn'_dpair b f)) α) == Bdn'_dpr2 (Bdn'_morphism (@inc_id i) (Bdn'_dpair b f)) α : !eq_rec_on_heq ... == f (inc_comp (@inc_id i) α) : eq_cast_to_heq H2 ... == f α : dcongr_arg _ (inc_comp_idl _) ... == Bdn'_dpr2 (Bdn'_dpair b f) α : heq.refl _, heq.to_eq H3 theorem Bdn'_respect_id (i : nat) : Bdn'_morphism (@inc_id i) = λx, x := have H : ∀b : BdnX_obj i, ∀f : Πα : inc_map (succ n) i, dpr2 X (Bdn (dpr1 X) α b), Bdn'_morphism (@inc_id i) (Bdn'_dpair b f) = (Bdn'_dpair b f), proof take b f, have H1 : Bdn'_dpr1 (Bdn'_morphism (@inc_id i) (Bdn'_dpair b f)) = b, from calc Bdn'_dpr1 (Bdn'_morphism (@inc_id i) (Bdn'_dpair b f)) = (BdnX_mor (@inc_id i) b) : rfl ... = id b : congr_fun (@respect_id _ _ _ type_category (Bdn (dpr1_X)) i) b ... = b : rfl, -- TODO: why do we need to supply type_category? show Bdn'_morphism (@inc_id i) (Bdn'_dpair b f) = (Bdn'_dpair b f), from Bdn'_object_equal' H1 (aux i b f H1) qed, Bdn'_fun_eq H theorem aux2a {i j k : nat} (β : inc_map k j) (α : inc_map j i) (b : BdnX_obj i) (f : Πα : inc_map (succ n) i, dpr2_X (BdnX_mor α b)) (α' : inc_map (succ n) k) : Bdn'_dpr2 ((Bdn'_morphism β) ((Bdn'_morphism α) (Bdn'_dpair b f))) α' == f (inc_comp α (inc_comp β α')) := let b_aux := (BdnX_mor α b), f_aux := (take α' : inc_map (succ n) j, cast (comp_eq_aux α α' (Bdn'_dpair b f)) (f (inc_comp α α'))) in show Bdn'_dpr2 ((Bdn'_morphism β) ((Bdn'_morphism α) (Bdn'_dpair b f))) α' == f (inc_comp α (inc_comp β α')), from calc Bdn'_dpr2 ((Bdn'_morphism β) ((Bdn'_morphism α) (Bdn'_dpair b f))) α' == cast (comp_eq_aux β α' (Bdn'_dpair b_aux f_aux)) (f_aux (inc_comp β α')) : !heq.refl ... == f_aux (inc_comp β α') : !cast_heq ... == f (inc_comp α (inc_comp β α')) : !cast_heq theorem aux2 (i j k : nat) (β : inc_map k j) (α : inc_map j i) (b : BdnX_obj i) (f : Πα : inc_map (succ n) i, dpr2_X (BdnX_mor α b)) (H1 : Bdn'_dpr1 (Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f)) = Bdn'_dpr1 ((Bdn'_morphism β ∘ Bdn'_morphism α) (Bdn'_dpair b f))) (α' : inc_map (succ n) k) : @eq.rec_on _ _ _ (fun b e, dpr2_X (BdnX_mor α' b)) H1 (Bdn'_dpr2 (Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f)) α') = Bdn'_dpr2 ((Bdn'_morphism β ∘ Bdn'_morphism α) (Bdn'_dpair b f)) α' := let H' := comp_eq_aux (inc_comp α β) α' (Bdn'_dpair b f) in have H2 : Bdn'_dpr2 (Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f)) α' = cast H' (f (inc_comp (inc_comp α β) α')), from rfl, have H3 : @eq.rec_on _ _ _ (fun b e, dpr2_X (BdnX_mor α' b)) H1 (Bdn'_dpr2 (Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f)) α') == Bdn'_dpr2 ((Bdn'_morphism β ∘ Bdn'_morphism α) (Bdn'_dpair b f)) α', from calc @eq.rec_on _ _ _ (fun b e, dpr2_X (BdnX_mor α' b)) H1 (Bdn'_dpr2 (Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f)) α') == Bdn'_dpr2 (Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f)) α' : !eq_rec_on_heq ... == f (inc_comp (inc_comp α β) α') : eq_cast_to_heq H2 ... == f (inc_comp α (inc_comp β α')) : dcongr_arg _ (eq.symm (inc_comp_assoc _ _ _)) ... == Bdn'_dpr2 ((Bdn'_morphism β) ((Bdn'_morphism α) (Bdn'_dpair b f))) α' : heq.symm (aux2a β α b f α') ... == Bdn'_dpr2 ((Bdn'_morphism β ∘ Bdn'_morphism α) (Bdn'_dpair b f)) α' : !heq.refl, heq.to_eq H3 theorem Bdn'_respect_comp (i j k : nat) (β : inc_map k j) (α : inc_map j i) : Bdn'_morphism (inc_comp α β) = Bdn'_morphism β ∘ Bdn'_morphism α := have H0 : BdnX_mor (inc_comp α β) = (BdnX_mor β) ∘ (BdnX_mor α), from !respect_comp, have H : ∀b : BdnX_obj i, ∀f : Πα : inc_map (succ n) i, dpr2 X (Bdn (dpr1 X) α b), Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f) = (Bdn'_morphism β ∘ Bdn'_morphism α) (Bdn'_dpair b f), proof take b f, have H1 : Bdn'_dpr1 (Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f)) = Bdn'_dpr1 ((Bdn'_morphism β ∘ Bdn'_morphism α) (Bdn'_dpair b f)), from calc Bdn'_dpr1 (Bdn'_morphism (inc_comp α β) (Bdn'_dpair b f)) = (BdnX_mor (inc_comp α β) b) : rfl ... = ((BdnX_mor β) ∘ (BdnX_mor α)) b : congr_fun H0 b ... = Bdn'_dpr1 ((Bdn'_morphism β ∘ Bdn'_morphism α) (Bdn'_dpair b f)) : rfl, Bdn'_object_equal' H1 (aux2 i j k β α b f H1) qed, Bdn'_fun_eq H definition Bdn' : functor Delta_op type_category := functor.mk Bdn'_object (@Bdn'_morphism) Bdn'_respect_id Bdn'_respect_comp end Bdn' end SSn'
a2474ce1b759d27f1103360a24c58044c954a4cf
827a8a5c2041b1d7f55e128581f583dfbd65ecf6
/vector.hlean
14a344f30577b0963c7a768c1084d0ab313fd625
[ "Apache-2.0" ]
permissive
fpvandoorn/leansnippets
6af0499f6f3fd2c07e4b580734d77b67574e7c27
601bafbe07e9534af76f60994d6bdf741996ef93
refs/heads/master
1,590,063,910,882
1,545,093,878,000
1,545,093,878,000
36,044,957
2
2
null
1,442,619,708,000
1,432,256,875,000
Lean
UTF-8
Lean
false
false
1,413
hlean
open nat eq is_trunc inductive vector (A : Type) : ℕ → Type := | nil {} : vector A zero | cons : Π {n}, A → vector A n → vector A (succ n) print vector.no_confusion open vector notation a :: b := cons a b definition head {A : Type} {n : ℕ} (v : vector A (n+1)) : A := begin cases v with _ a v', exact a end definition tail {A : Type} {n : ℕ} (v : vector A (n+1)) : vector A n := begin cases v with _ a v', exact v' end definition head' {A : Type} : Π {n : ℕ}, vector A (succ n) → A | n (x :: xs) := x definition tail' {A : Type} : Π {n : ℕ}, vector A (succ n) → vector A n | n (x :: xs) := xs definition cons_inj {A : Type} {n : ℕ} (a a' : A) (v : vector A n) (v' : vector A n) (p : a :: v = a' :: v') : a = a' × v = v' := begin injection p with p₁ p₂ p₃, split, exact p₂, have p₄ : rfl = p₁, from !is_set.elim, induction p₄, exact p₃ end definition const {A : Type} : Π (n : ℕ), A → vector A n | zero a := nil | (succ n) a := a :: const n a -- theorem singlenton_vector_unit : ∀ {n : ℕ} (v w : vector unit n), v = w -- | zero nil nil := rfl -- | (succ n) (star::xs) (star::ys) := -- begin -- have h₁ : xs = ys, from singlenton_vector_unit xs ys, -- rewrite h₁ -- end definition swap {A : Type} : Π {n}, vector A (succ (succ n)) → vector A (succ (succ n)) | swap (a :: b :: vs) := b :: a :: vs
bf7b61d9e118265cb81b184b3e18fb916baaafb8
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/logic/heq.lean
74f0745ac8db1d5b8d6983d7924821300c28d664
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,555
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import logic.eq inductive heq {A : Type} (a : A) : Π {B : Type}, B → Prop := refl : heq a a infixl `==`:50 := heq namespace heq universe variable u variables {A B C : Type.{u}} {a a' : A} {b b' : B} {c : C} theorem drec_on {C : Π {B : Type} (b : B), a == b → Type} (H₁ : a == b) (H₂ : C a (refl a)) : C b H₁ := rec (λ H₁ : a == a, show C a H₁, from H₂) H₁ H₁ theorem subst {P : ∀T : Type, T → Prop} (H₁ : a == b) (H₂ : P A a) : P B b := rec_on H₁ H₂ theorem symm (H : a == b) : b == a := subst H (refl a) theorem type_eq (H : a == b) : A = B := subst H (eq.refl A) theorem from_eq (H : a = a') : a == a' := eq.subst H (refl a) theorem to_eq (H : a == a') : a = a' := have H₁ : ∀ (Ht : A = A), eq.rec_on Ht a = a, from take Ht, eq.refl (eq.rec_on Ht a), have H₂ : ∀ (Ht : A = A), eq.rec_on Ht a = a', from heq.rec_on H H₁, H₂ (type_eq H) theorem trans (H₁ : a == b) (H₂ : b == c) : a == c := subst H₂ H₁ theorem trans_left (H₁ : a == b) (H₂ : b = b') : a == b' := trans H₁ (from_eq H₂) theorem trans_right (H₁ : a = a') (H₂ : a' == b) : a == b := trans (from_eq H₁) H₂ theorem true_elim {a : Prop} (H : a == true) : a := eq_true_elim (heq.to_eq H) end heq calc_trans heq.trans calc_trans heq.trans_left calc_trans heq.trans_right calc_symm heq.symm
50dbff14dfb4c86973f2959666a2706f235312af
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/Quotation/Precheck.lean
31b57d84f60f3cbaf5a4fcab65c43676f85a9943
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
5,797
lean
/- Copyright (c) 2021 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.KeyedDeclsAttribute import Lean.Parser.Command -- for `precheckedQuot` import Lean.Elab.Term import Lean.Elab.Quotation.Util namespace Lean.Elab.Term.Quotation open Lean.Elab.Term open Lean.Parser.Term structure Precheck.Context where quotLCtx : NameSet abbrev PrecheckM := ReaderT Precheck.Context TermElabM abbrev Precheck := Syntax → PrecheckM Unit protected def withNewLocal (l : Name) (x : PrecheckM α) : PrecheckM α := withReader (fun ctx => { ctx with quotLCtx := ctx.quotLCtx.insert l }) x protected def withNewLocals (ls : Array Name) (x : PrecheckM α) : PrecheckM α := withReader (fun ctx => { ctx with quotLCtx := ls.foldl NameSet.insert ctx.quotLCtx }) x register_builtin_option quotPrecheck : Bool := { defValue := true descr := "Enable eager name analysis on notations in order to find unbound identifiers early. Note that type-sensitive syntax (\"elaborators\") needs special support for this kind of check, so it might need to be turned off when using such syntax." } register_builtin_option quotPrecheck.allowSectionVars : Bool := { defValue := false descr := "Allow occurrences of section variables in checked quotations, it is useful when declaring local notation." } unsafe def mkPrecheckAttribute : IO (KeyedDeclsAttribute Precheck) := KeyedDeclsAttribute.init { builtinName := `builtin_quot_precheck, name := `quot_precheck, descr := "Register a double backtick syntax quotation pre-check. [quot_precheck k] registers a declaration of type `Lean.Elab.Term.Quotation.Precheck` for the `SyntaxNodeKind` `k`. It should implement eager name analysis on the passed syntax by throwing an exception on unbound identifiers, and calling `precheck` recursively on nested terms, potentially with an extended local context (`withNewLocal`). Macros without registered precheck hook are unfolded, and identifier-less syntax is ultimately assumed to be well-formed.", valueTypeName := ``Precheck } `Lean.Elab.Term.Quotation.precheckAttribute @[builtin_init mkPrecheckAttribute] opaque precheckAttribute : KeyedDeclsAttribute Precheck partial def precheck : Precheck := fun stx => do if let p::_ := precheckAttribute.getValues (← getEnv) stx.getKind then if ← catchInternalId unsupportedSyntaxExceptionId (do withRef stx <| p stx; pure true) (fun _ => pure false) then return if stx.isAnyAntiquot then return if !hasQuotedIdent stx then return -- we only precheck identifiers, so there is nothing to check here if let some stx' ← liftMacroM <| expandMacro? stx then precheck stx' return throwErrorAt stx "no macro or `[quot_precheck]` instance for syntax kind '{stx.getKind}' found{indentD stx} This means we cannot eagerly check your notation/quotation for unbound identifiers; you can use `set_option quotPrecheck false` to disable this check." where hasQuotedIdent | Syntax.ident .. => true | stx => if stx.isAnyAntiquot then false else stx.getArgs.any hasQuotedIdent def runPrecheck (stx : Syntax) : TermElabM Unit := do let opts ← getOptions if quotPrecheck.get opts && hygiene.get opts then precheck stx |>.run { quotLCtx := {} } private def isSectionVariable (e : Expr) : TermElabM Bool := do return (← read).sectionFVars.any fun _ v => e == v @[builtin_quot_precheck ident] def precheckIdent : Precheck := fun stx => match stx with | Syntax.ident _ _ val preresolved => do if !preresolved.isEmpty then return /- The precheck currently ignores field notation. For example: the following notation is accepted although `foo` is not a valid field name for a `Nat` value. ``` def x := 0 notation "x++" => x.foo ``` -/ if let _::_ ← resolveGlobalNameWithInfos stx val then return if (← read).quotLCtx.contains val then return let rs ← try resolveName stx val [] [] catch _ => pure [] for (e, _) in rs do match e with | Expr.fvar _ .. => if quotPrecheck.allowSectionVars.get (← getOptions) && (← isSectionVariable e) then return | _ => pure () throwError "unknown identifier '{val}' at quotation precheck; you can use `set_option quotPrecheck false` to disable this check." | _ => throwUnsupportedSyntax @[builtin_quot_precheck Lean.Parser.Term.app] def precheckApp : Precheck | `($f $args*) => do precheck f for arg in args.raw do match arg with | `(argument| ($_ := $e)) => precheck e | `(argument| ..) => pure () | `(argument| $e:term) => precheck e | _ => throwUnsupportedSyntax @[builtin_quot_precheck Lean.Parser.Term.typeAscription] def precheckTypeAscription : Precheck | `(($e : $type)) => do precheck e precheck type | `(($e :)) => precheck e | _ => throwUnsupportedSyntax @[builtin_quot_precheck choice] def precheckChoice : Precheck := fun stx => do let checks ← stx.getArgs.mapM (_root_.observing ∘ precheck) let fails := checks.zip stx.getArgs |>.filterMap fun | (.error e, stx) => some m!"{stx}\n{e.toMessageData}" | _ => none unless fails.isEmpty do throwErrorAt stx "ambiguous notation with at least one interpretation that failed quotation precheck, possible interpretations {indentD (MessageData.joinSep fails.toList m!"\n\n")}" @[builtin_term_elab precheckedQuot] def elabPrecheckedQuot : TermElab := fun stx expectedType? => do let singleQuot := stx[1] runPrecheck singleQuot.getQuotContent adaptExpander (fun _ => pure singleQuot) stx expectedType? end Lean.Elab.Term.Quotation
feec01453af03c49345b8490d7ce069a9ed3b004
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Init/Data/Hashable.lean
00dfdc5c1d2bc3628e51013019a98614146b0dd3
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
893
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.Data.UInt import Init.Data.String universes u instance : Hashable Nat where hash n := USize.ofNat n instance [Hashable α] [Hashable β] : Hashable (α × β) where hash | (a, b) => mixHash (hash a) (hash b) protected def Option.hash [Hashable α] : Option α → USize | none => 11 | some a => mixHash (hash a) 13 instance [Hashable α] : Hashable (Option α) where hash | none => 11 | some a => mixHash (hash a) 13 instance [Hashable α] : Hashable (List α) where hash as := as.foldl (fun r a => mixHash r (hash a)) 7 instance : Hashable UInt32 where hash n := n.toUSize instance : Hashable UInt64 where hash n := n.toUSize instance : Hashable USize where hash n := n
076df342cae44fd63b0e7b3567e5cab50735763b
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/algebra/monoid_algebra.lean
85766b6102d6cd0f53a2f2865ff0841e91a2d134
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,268
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, Yury G. Kudryashov, Scott Morrison -/ import algebra.algebra.basic import linear_algebra.finsupp /-! # Monoid algebras When the domain of a `finsupp` has a multiplicative or additive structure, we can define a convolution product. To mathematicians this structure is known as the "monoid algebra", i.e. the finite formal linear combinations over a given semiring of elements of the monoid. The "group ring" ℤ[G] or the "group algebra" k[G] are typical uses. In this file we define `monoid_algebra k G := G →₀ k`, and `add_monoid_algebra k G` in the same way, and then define the convolution product on these. When the domain is additive, this is used to define polynomials: ``` polynomial α := add_monoid_algebra ℕ α mv_polynomial σ α := add_monoid_algebra (σ →₀ ℕ) α ``` When the domain is multiplicative, e.g. a group, this will be used to define the group ring. ## Implementation note Unfortunately because additive and multiplicative structures both appear in both cases, it doesn't appear to be possible to make much use of `to_additive`, and we just settle for saying everything twice. Similarly, I attempted to just define `add_monoid_algebra k G := monoid_algebra k (multiplicative G)`, but the definitional equality `multiplicative G = G` leaks through everywhere, and seems impossible to use. -/ noncomputable theory open_locale classical big_operators open finset finsupp universes u₁ u₂ u₃ variables (k : Type u₁) (G : Type u₂) /-! ### Multiplicative monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid, has_coe_to_fun]] def monoid_algebra : Type (max u₁ u₂) := G →₀ k end namespace monoid_algebra variables {k G} /-! #### Semiring structure -/ section semiring variables [semiring k] [monoid G] /-- The product of `f g : monoid_algebra k 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 group ring of a group.) -/ instance : has_mul (monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)⟩ lemma mul_def {f g : monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ * a₂) (b₁ * b₂)) := rfl /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `1` and zero elsewhere. -/ instance : has_one (monoid_algebra k G) := ⟨single 1 1⟩ lemma one_def : (1 : monoid_algebra k G) = single 1 1 := rfl instance : semiring (monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, 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, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_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, zero_mul, mul_zero, sum_zero, sum_add], left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], .. finsupp.add_comm_monoid } variables {R : Type*} [semiring R] /-- A non-commutative version of `monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a multiplicative monoid homomorphism `g : G →* R`, returns the additive homomorphism from `monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : G →* R) : monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : G →* R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g a := lift_add_hom_apply_single _ _ _ @[simp] lemma lift_nc_one (f : k →+* R) (g : G →* R) : lift_nc (f : k →+ R) g 1 = 1 := by simp [one_def] lemma lift_nc_mul (f : k →+* R) (g : G →* R) (a b : monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := begin conv_rhs { rw [← sum_single a, ← sum_single b] }, simp_rw [mul_def, (lift_nc _ g).map_finsupp_sum, lift_nc_single, finsupp.sum_mul, finsupp.mul_sum], refine finset.sum_congr rfl (λ y hy, finset.sum_congr rfl (λ x hx, _)), simp [mul_assoc, (h_comm hy).left_comm] end /-- `lift_nc` as a `ring_hom`, for when `f x` and `g y` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [comm_monoid G] : comm_semiring (monoid_algebra k G) := { mul_comm := assume f g, begin simp only [mul_def, finsupp.sum, mul_comm], rw [finset.sum_comm], simp only [mul_comm] end, .. monoid_algebra.semiring } instance [semiring k] [nontrivial k] [monoid G] : nontrivial (monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [semiring k] [subsingleton k] : unique (monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_group (monoid_algebra k G) := finsupp.add_group instance [ring k] [monoid G] : ring (monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, .. monoid_algebra.semiring } instance [comm_ring k] [comm_monoid G] : comm_ring (monoid_algebra k G) := { mul_comm := mul_comm, .. monoid_algebra.ring} instance {R : Type*} [semiring R] [semiring k] [semimodule R k] : has_scalar R (monoid_algebra k G) := finsupp.has_scalar instance {R : Type*} [semiring R] [semiring k] [semimodule R k] : semimodule R (monoid_algebra k G) := finsupp.semimodule G k instance [group G] [semiring k] : distrib_mul_action G (monoid_algebra k G) := finsupp.comap_distrib_mul_action_self end derived_instances section misc_theorems variables [semiring k] [monoid G] local attribute [reducible] monoid_algebra lemma mul_apply (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ * a₂ = x then b₁ * b₂ else 0) := begin rw [mul_def], simp only [finsupp.sum_apply, single_apply], end lemma mul_apply_antidiagonal (f g : monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 * p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := let F : G × G → k := λ p, if p.1 * p.2 = x then f p.1 * g p.2 else 0 in calc (f * g) x = (∑ a₁ in f.support, ∑ a₂ in g.support, F (a₁, a₂)) : mul_apply f g x ... = ∑ p in f.support.product g.support, F p : finset.sum_product.symm ... = ∑ p in (f.support.product g.support).filter (λ p : G × G, p.1 * p.2 = x), f p.1 * g p.2 : (finset.sum_filter _ _).symm ... = ∑ p in s.filter (λ p : G × G, p.1 ∈ f.support ∧ p.2 ∈ g.support), f p.1 * g p.2 : sum_congr (by { ext, simp only [mem_filter, mem_product, hs, and_comm] }) (λ _ _, rfl) ... = ∑ p in s, f p.1 * g p.2 : sum_subset (filter_subset _ _) $ λ p hps hp, begin simp only [mem_filter, mem_support_iff, not_and, not_not] at hp ⊢, by_cases h1 : f p.1 = 0, { rw [h1, zero_mul] }, { rw [hp hps h1, mul_zero] } end lemma support_mul (a b : monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ * a₂}) := subset.trans support_sum $ bUnion_mono $ assume a₁ _, subset.trans support_sum $ bUnion_mono $ assume a₂ _, support_single_subset @[simp] lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : monoid_algebra k G) * single a₂ b₂ = single (a₁ * a₂) (b₁ * b₂) := (sum_single_index (by simp only [zero_mul, single_zero, sum_zero])).trans (sum_single_index (by rw [mul_zero, single_zero])) @[simp] lemma single_pow {a : G} {b : k} : ∀ n : ℕ, (single a b : monoid_algebra k G)^n = single (a^n) (b ^ n) | 0 := rfl | (n+1) := by simp only [pow_succ, single_pow n, single_mul_single] section /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [monoid α] [monoid α₂] {x y : monoid_algebra β α} (f : mul_hom α α₂) : (map_domain f (x * y : monoid_algebra β α) : monoid_algebra β α₂) = (map_domain f x * map_domain f y : monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, f.map_mul], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : G →* monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by rw [single_mul_single, one_mul] } end @[simp] lemma of_apply (a : G) : of k G a = single a 1 := rfl lemma of_injective [nontrivial k] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h lemma mul_single_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, a * x = z ↔ a = y) : (f * single x r) z = f y * r := have A : ∀ a₁ b₁, (single x r).sum (λ a₂ b₂, ite (a₁ * a₂ = z) (b₁ * b₂) 0) = ite (a₁ * x = z) (b₁ * r) 0, from λ a₁ b₁, sum_single_index $ by simp, calc (f * single x r) z = sum f (λ a b, if (a = y) then (b * r) else 0) : -- different `decidable` instances make it not trivial by { simp only [mul_apply, A, H], congr, funext, split_ifs; refl } ... = if y ∈ f.support then f y * r else 0 : f.support.sum_ite_eq' _ _ ... = f y * r : by split_ifs with h; simp at h; simp [h] lemma mul_single_one_apply (f : monoid_algebra k G) (r : k) (x : G) : (f * single 1 r) x = f x * r := f.mul_single_apply_aux $ λ a, by rw [mul_one] lemma single_mul_apply_aux (f : monoid_algebra k G) {r : k} {x y z : G} (H : ∀ a, x * a = y ↔ a = z) : (single x r * f) y = r * f z := have f.sum (λ a b, ite (x * a = y) (0 * b) 0) = 0, by simp, calc (single x r * f) y = sum f (λ a b, ite (x * a = y) (r * b) 0) : (mul_apply _ _ _).trans $ sum_single_index this ... = f.sum (λ a b, ite (a = z) (r * b) 0) : by { simp only [H], congr' with g s, split_ifs; refl } ... = if z ∈ f.support then (r * f z) else 0 : f.support.sum_ite_eq' _ _ ... = _ : by split_ifs with h; simp at h; simp [h] lemma single_one_mul_apply (f : monoid_algebra k G) (r : k) (x : G) : (single 1 r * f) x = r * f x := f.single_mul_apply_aux $ λ a, by rw [one_mul] lemma lift_nc_smul {R : Type*} [semiring R] (f : k →+* R) (g : G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := begin suffices : (lift_nc ↑f g).comp (smul_add_hom k (monoid_algebra k G) c) = (add_monoid_hom.mul_left (f c)).comp (lift_nc ↑f g), from add_monoid_hom.congr_fun this φ, ext a b, simp [mul_assoc] end end misc_theorems /-! #### Algebra structure -/ section algebra local attribute [reducible] monoid_algebra lemma single_one_comm [comm_semiring k] [monoid G] (r : k) (f : monoid_algebra k G) : single 1 r * f = f * single 1 r := by { ext, rw [single_one_mul_apply, mul_single_one_apply, mul_comm] } /-- `finsupp.single 1` as a `ring_hom` -/ @[simps] def single_one_ring_hom [semiring k] [monoid G] : k →+* monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, one_mul], ..finsupp.single_add_hom 1} /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [monoid G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : ∀ b, f (single 1 b) = g (single 1 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := ring_hom.coe_add_monoid_hom_injective $ add_hom_ext $ λ a b, by rw [← one_mul a, ← mul_one b, ← single_mul_single, f.coe_add_monoid_hom, g.coe_add_monoid_hom, f.map_mul, g.map_mul, h₁, h_of] /-- If two ring homomorphisms from `monoid_algebra k G` are equal on all `single a 1` and `single 1 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [monoid G] [semiring R] {f g : monoid_algebra k G →+* R} (h₁ : f.comp single_one_ring_hom = g.comp single_one_ring_hom) (h_of : (f : monoid_algebra k G →* R).comp (of k G) = (g : monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) /-- The instance `algebra k (monoid_algebra A G)` whenever we have `algebra k A`. In particular this provides the instance `algebra k (monoid_algebra k G)`. -/ instance {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : algebra k (monoid_algebra A G) := { smul_def' := λ r a, by { ext, simp [single_one_mul_apply, algebra.smul_def'', pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_one_mul_apply, mul_single_one_apply, algebra.commutes], }, ..single_one_ring_hom.comp (algebra_map k A) } /-- `finsupp.single 1` as a `alg_hom` -/ @[simps] def single_one_alg_hom {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : A →ₐ[k] monoid_algebra A G := { commutes' := λ r, by { ext, simp, refl, }, ..single_one_ring_hom} @[simp] lemma coe_algebra_map {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] : ⇑(algebra_map k (monoid_algebra A G)) = single 1 ∘ (algebra_map k A) := rfl lemma single_eq_algebra_map_mul_of [comm_semiring k] [monoid G] (a : G) (b : k) : single a b = algebra_map k (monoid_algebra k G) b * of k G a := by simp lemma single_algebra_map_eq_algebra_map_mul_of {A : Type*} [comm_semiring k] [semiring A] [algebra k A] [monoid G] (a : G) (b : k) : single a (algebra_map k A b) = algebra_map k (monoid_algebra A G) b * of A G a := by simp end algebra section lift variables {k G} [comm_semiring k] [monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := alg_hom.to_linear_map_inj $ finsupp.lhom_ext' $ λ a, linear_map.ext_ring (h a) /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : monoid_algebra k G →* A).comp (of k G) = (φ₂ : monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (G →* A) ≃ (monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : monoid_algebra k G →* A).comp (of k G), to_fun := λ F, lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, left_inv := λ f, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] }, right_inv := λ F, by { ext, simp [lift_nc_alg_hom, lift_nc_ring_hom] } } variables {k G A} lemma lift_apply' (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F a) := rfl lemma lift_apply (F : G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F a) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : monoid_algebra k G →ₐ[k] A) (x : G) : (lift k G A).symm F x = F (single x 1) := rfl lemma lift_of (F : G →* A) (x) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : G →* A) (a b) : lift k G A F (single a b) = b • F a := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } end lift section local attribute [reducible] monoid_algebra variables (k) /-- When `V` is a `k[G]`-module, multiplication by a group element `g` is a `k`-linear map. -/ def group_smul.linear_map [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [semimodule k V] [semimodule (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) : V →ₗ[k] V := { to_fun := λ v, (single g (1 : k) • v : V), map_add' := λ x y, smul_add (single g (1 : k)) x y, map_smul' := λ c x, smul_algebra_smul_comm _ _ _ } @[simp] lemma group_smul.linear_map_apply [monoid G] [comm_semiring k] (V : Type u₃) [add_comm_monoid V] [semimodule k V] [semimodule (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] (g : G) (v : V) : (group_smul.linear_map k V g) v = (single g (1 : k) • v : V) := rfl section variables {k} variables [monoid G] [comm_semiring k] {V W : Type u₃} [add_comm_monoid V] [semimodule k V] [semimodule (monoid_algebra k G) V] [is_scalar_tower k (monoid_algebra k G) V] [add_comm_monoid W] [semimodule k W] [semimodule (monoid_algebra k G) W] [is_scalar_tower k (monoid_algebra k G) W] (f : V →ₗ[k] W) (h : ∀ (g : G) (v : V), f (single g (1 : k) • v : V) = (single g (1 : k) • (f v) : W)) include h /-- Build a `k[G]`-linear map from a `k`-linear map and evidence that it is `G`-equivariant. -/ def equivariant_of_linear_of_comm : V →ₗ[monoid_algebra k G] W := { to_fun := f, map_add' := λ v v', by simp, map_smul' := λ c v, begin apply finsupp.induction c, { simp, }, { intros g r c' nm nz w, simp only [add_smul, f.map_add, w, add_left_inj, single_eq_algebra_map_mul_of, ← smul_smul], erw [algebra_map_smul (monoid_algebra k G) r, algebra_map_smul (monoid_algebra k G) r, f.map_smul, h g v, of_apply], all_goals { apply_instance } } end, } @[simp] lemma equivariant_of_linear_of_comm_apply (v : V) : (equivariant_of_linear_of_comm f h) v = f v := rfl end end section universe ui variable {ι : Type ui} local attribute [reducible] monoid_algebra lemma prod_single [comm_semiring k] [comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∏ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, prod_insert has, prod_insert has] end section -- We now prove some additional statements that hold for group algebras. variables [semiring k] [group G] local attribute [reducible] monoid_algebra @[simp] lemma mul_single_apply (f : monoid_algebra k G) (r : k) (x y : G) : (f * single x r) y = f (y * x⁻¹) * r := f.mul_single_apply_aux $ λ a, eq_mul_inv_iff_mul_eq.symm @[simp] lemma single_mul_apply (r : k) (x : G) (f : monoid_algebra k G) (y : G) : (single x r * f) y = r * f (x⁻¹ * y) := f.single_mul_apply_aux $ λ z, eq_inv_mul_iff_mul_eq.symm lemma mul_apply_left (f g : monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λ a b, b * (g (a⁻¹ * x))) := calc (f * g) x = sum f (λ a b, (single a b * g) x) : by rw [← finsupp.sum_apply, ← finsupp.sum_mul, f.sum_single] ... = _ : by simp only [single_mul_apply, finsupp.sum] -- If we'd assumed `comm_semiring`, we could deduce this from `mul_apply_left`. lemma mul_apply_right (f g : monoid_algebra k G) (x : G) : (f * g) x = (g.sum $ λa b, (f (x * a⁻¹)) * b) := calc (f * g) x = sum g (λ a b, (f * single a b) x) : by rw [← finsupp.sum_apply, ← finsupp.mul_sum, g.sum_single] ... = _ : by simp only [mul_single_apply, finsupp.sum] end end monoid_algebra /-! ### Additive monoids -/ section variables [semiring k] /-- The monoid algebra over a semiring `k` generated by the additive monoid `G`. It is the type of finite formal `k`-linear combinations of terms of `G`, endowed with the convolution product. -/ @[derive [inhabited, add_comm_monoid, has_coe_to_fun]] def add_monoid_algebra := G →₀ k end namespace add_monoid_algebra variables {k G} /-! #### Semiring structure -/ section semiring variables [semiring k] [add_monoid G] /-- The product of `f g : add_monoid_algebra k 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 additive monoid of monomial exponents.) -/ instance : has_mul (add_monoid_algebra k G) := ⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩ lemma mul_def {f g : add_monoid_algebra k G} : f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl /-- The unit of the multiplication is `single 1 1`, i.e. the function that is `1` at `0` and zero elsewhere. -/ instance : has_one (add_monoid_algebra k G) := ⟨single 0 1⟩ lemma one_def : (1 : add_monoid_algebra k G) = single 0 1 := rfl instance : semiring (add_monoid_algebra k G) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, 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, mul_zero, single_zero, sum_zero, add_zero, mul_one, sum_single], zero_mul := assume f, by simp only [mul_def, sum_zero_index], mul_zero := assume f, by simp only [mul_def, sum_zero_index, sum_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, zero_mul, mul_zero, sum_zero, sum_add], left_distrib := assume f g h, by simp only [mul_def, sum_add_index, mul_add, mul_zero, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add], right_distrib := assume f g h, by simp only [mul_def, sum_add_index, add_mul, mul_zero, zero_mul, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add], .. finsupp.add_comm_monoid } variables {R : Type*} [semiring R] /-- A non-commutative version of `add_monoid_algebra.lift`: given a additive homomorphism `f : k →+ R` and a multiplicative monoid homomorphism `g : multiplicative G →* R`, returns the additive homomorphism from `add_monoid_algebra k G` such that `lift_nc f g (single a b) = f b * g a`. If `f` is a ring homomorphism and the range of either `f` or `g` is in center of `R`, then the result is a ring homomorphism. If `R` is a `k`-algebra and `f = algebra_map k R`, then the result is an algebra homomorphism called `add_monoid_algebra.lift`. -/ def lift_nc (f : k →+ R) (g : multiplicative G →* R) : add_monoid_algebra k G →+ R := lift_add_hom (λ x : G, (add_monoid_hom.mul_right (g $ multiplicative.of_add x)).comp f) @[simp] lemma lift_nc_single (f : k →+ R) (g : multiplicative G →* R) (a : G) (b : k) : lift_nc f g (single a b) = f b * g (multiplicative.of_add a) := lift_add_hom_apply_single _ _ _ @[simp] lemma lift_nc_one (f : k →+* R) (g : multiplicative G →* R) : lift_nc (f : k →+ R) g 1 = 1 := @monoid_algebra.lift_nc_one k (multiplicative G) _ _ _ _ f g lemma lift_nc_mul (f : k →+* R) (g : multiplicative G →* R) (a b : add_monoid_algebra k G) (h_comm : ∀ {x y}, y ∈ a.support → commute (f (b x)) (g $ multiplicative.of_add y)) : lift_nc (f : k →+ R) g (a * b) = lift_nc (f : k →+ R) g a * lift_nc (f : k →+ R) g b := @monoid_algebra.lift_nc_mul k (multiplicative G) _ _ _ _ f g a b @h_comm /-- `lift_nc` as a `ring_hom`, for when `f` and `g` commute -/ def lift_nc_ring_hom (f : k →+* R) (g : multiplicative G →* R) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra k G →+* R := { to_fun := lift_nc (f : k →+ R) g, map_one' := lift_nc_one _ _, map_mul' := λ a b, lift_nc_mul _ _ _ _ $ λ _ _ _, h_comm _ _, ..(lift_nc (f : k →+ R) g)} end semiring instance [comm_semiring k] [add_comm_monoid G] : comm_semiring (add_monoid_algebra k G) := { mul_comm := @mul_comm (monoid_algebra k $ multiplicative G) _, .. add_monoid_algebra.semiring } instance [semiring k] [nontrivial k] [add_monoid G] : nontrivial (add_monoid_algebra k G) := finsupp.nontrivial /-! #### Derived instances -/ section derived_instances instance [semiring k] [subsingleton k] : unique (add_monoid_algebra k G) := finsupp.unique_of_right instance [ring k] : add_group (add_monoid_algebra k G) := finsupp.add_group instance [ring k] [add_monoid G] : ring (add_monoid_algebra k G) := { neg := has_neg.neg, add_left_neg := add_left_neg, sub := has_sub.sub, sub_eq_add_neg := finsupp.add_group.sub_eq_add_neg, .. add_monoid_algebra.semiring } instance [comm_ring k] [add_comm_monoid G] : comm_ring (add_monoid_algebra k G) := { mul_comm := mul_comm, .. add_monoid_algebra.ring} variables {R : Type*} instance [semiring R] [semiring k] [semimodule R k] : has_scalar R (add_monoid_algebra k G) := finsupp.has_scalar instance [semiring R] [semiring k] [semimodule R k] : semimodule R (add_monoid_algebra k G) := finsupp.semimodule G k /-! It is hard to state the equivalent of `distrib_mul_action G (add_monoid_algebra k G)` because we've never discussed actions of additive groups. -/ end derived_instances section misc_theorems variables [semiring k] [add_monoid G] local attribute [reducible] add_monoid_algebra lemma mul_apply (f g : add_monoid_algebra k G) (x : G) : (f * g) x = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, if a₁ + a₂ = x then b₁ * b₂ else 0) := @monoid_algebra.mul_apply k (multiplicative G) _ _ _ _ _ lemma mul_apply_antidiagonal (f g : add_monoid_algebra k G) (x : G) (s : finset (G × G)) (hs : ∀ {p : G × G}, p ∈ s ↔ p.1 + p.2 = x) : (f * g) x = ∑ p in s, (f p.1 * g p.2) := @monoid_algebra.mul_apply_antidiagonal k (multiplicative G) _ _ _ _ _ s @hs lemma support_mul (a b : add_monoid_algebra k G) : (a * b).support ⊆ a.support.bUnion (λa₁, b.support.bUnion $ λa₂, {a₁ + a₂}) := @monoid_algebra.support_mul k (multiplicative G) _ _ _ _ lemma single_mul_single {a₁ a₂ : G} {b₁ b₂ : k} : (single a₁ b₁ : add_monoid_algebra k G) * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) := @monoid_algebra.single_mul_single k (multiplicative G) _ _ _ _ _ _ /-- Like `finsupp.map_domain_add`, but for the convolutive multiplication we define in this file -/ lemma map_domain_mul {α : Type*} {β : Type*} {α₂ : Type*} [semiring β] [add_monoid α] [add_monoid α₂] {x y : add_monoid_algebra β α} (f : add_hom α α₂) : (map_domain f (x * y : add_monoid_algebra β α) : add_monoid_algebra β α₂) = (map_domain f x * map_domain f y : add_monoid_algebra β α₂) := begin simp_rw [mul_def, map_domain_sum, map_domain_single, f.map_add], rw finsupp.sum_map_domain_index, { congr, ext a b, rw finsupp.sum_map_domain_index, { simp }, { simp [mul_add] } }, { simp }, { simp [add_mul] } end section variables (k G) /-- Embedding of a monoid into its monoid algebra. -/ def of : multiplicative G →* add_monoid_algebra k G := { to_fun := λ a, single a 1, map_one' := rfl, map_mul' := λ a b, by { rw [single_mul_single, one_mul], refl } } end @[simp] lemma of_apply (a : multiplicative G) : of k G a = single a.to_add 1 := rfl lemma of_injective [nontrivial k] : function.injective (of k G) := λ a b h, by simpa using (single_eq_single_iff _ _ _ _).mp h lemma mul_single_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, a + x = z ↔ a = y) : (f * single x r) z = f y * r := @monoid_algebra.mul_single_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma mul_single_zero_apply (f : add_monoid_algebra k G) (r : k) (x : G) : (f * single 0 r) x = f x * r := f.mul_single_apply_aux r _ _ _ $ λ a, by rw [add_zero] lemma single_mul_apply_aux (f : add_monoid_algebra k G) (r : k) (x y z : G) (H : ∀ a, x + a = y ↔ a = z) : (single x r * f) y = r * f z := @monoid_algebra.single_mul_apply_aux k (multiplicative G) _ _ _ _ _ _ _ H lemma single_zero_mul_apply (f : add_monoid_algebra k G) (r : k) (x : G) : (single 0 r * f) x = r * f x := f.single_mul_apply_aux r _ _ _ $ λ a, by rw [zero_add] lemma lift_nc_smul {R : Type*} [semiring R] (f : k →+* R) (g : multiplicative G →* R) (c : k) (φ : monoid_algebra k G) : lift_nc (f : k →+ R) g (c • φ) = f c * lift_nc (f : k →+ R) g φ := @monoid_algebra.lift_nc_smul k (multiplicative G) _ _ _ _ f g c φ end misc_theorems end add_monoid_algebra /-! #### Conversions between `add_monoid_algebra` and `monoid_algebra` While we were not able to define `add_monoid_algebra k G = monoid_algebra k (multiplicative G)` due to definitional inconveniences, we can still show the types are isomorphic. -/ /-- The equivalence between `add_monoid_algebra` and `monoid_algebra` in terms of `multiplicative` -/ protected def add_monoid_algebra.to_multiplicative [semiring k] [add_monoid G] : add_monoid_algebra k G ≃+* monoid_algebra k (multiplicative G) := { map_mul' := λ x y, by convert add_monoid_algebra.map_domain_mul (add_hom.id G), ..finsupp.dom_congr multiplicative.of_add } /-- The equivalence between `monoid_algebra` and `add_monoid_algebra` in terms of `additive` -/ protected def monoid_algebra.to_additive [semiring k] [monoid G] : monoid_algebra k G ≃+* add_monoid_algebra k (additive G) := { map_mul' := λ x y, by convert monoid_algebra.map_domain_mul (mul_hom.id G), ..finsupp.dom_congr additive.of_mul } namespace add_monoid_algebra variables {k G} /-! #### Algebra structure -/ section algebra variables {R : Type*} local attribute [reducible] add_monoid_algebra /-- `finsupp.single 0` as a `ring_hom` -/ @[simps] def single_zero_ring_hom [semiring k] [add_monoid G] : k →+* add_monoid_algebra k G := { map_one' := rfl, map_mul' := λ x y, by rw [single_add_hom, single_mul_single, zero_add], ..finsupp.single_add_hom 0} /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. -/ lemma ring_hom_ext {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₀ : ∀ b, f (single 0 b) = g (single 0 b)) (h_of : ∀ a, f (single a 1) = g (single a 1)) : f = g := @monoid_algebra.ring_hom_ext k (multiplicative G) R _ _ _ _ _ h₀ h_of /-- If two ring homomorphisms from `add_monoid_algebra k G` are equal on all `single a 1` and `single 0 b`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' {R} [semiring k] [add_monoid G] [semiring R] {f g : add_monoid_algebra k G →+* R} (h₁ : f.comp single_zero_ring_hom = g.comp single_zero_ring_hom) (h_of : (f : add_monoid_algebra k G →* R).comp (of k G) = (g : add_monoid_algebra k G →* R).comp (of k G)) : f = g := ring_hom_ext (ring_hom.congr_fun h₁) (monoid_hom.congr_fun h_of) /-- The instance `algebra R (add_monoid_algebra k G)` whenever we have `algebra R k`. In particular this provides the instance `algebra k (add_monoid_algebra k G)`. -/ instance [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : algebra R (add_monoid_algebra k G) := { smul_def' := λ r a, by { ext, simp [single_zero_mul_apply, algebra.smul_def'', pi.smul_apply], }, commutes' := λ r f, by { ext, simp [single_zero_mul_apply, mul_single_zero_apply, algebra.commutes], }, ..single_zero_ring_hom.comp (algebra_map R k) } /-- `finsupp.single 0` as a `alg_hom` -/ @[simps] def single_zero_alg_hom [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : k →ₐ[R] add_monoid_algebra k G := { commutes' := λ r, by { ext, simp, refl, }, ..single_zero_ring_hom} @[simp] lemma coe_algebra_map [comm_semiring R] [semiring k] [algebra R k] [add_monoid G] : (algebra_map R (add_monoid_algebra k G) : R → add_monoid_algebra k G) = single 0 ∘ (algebra_map R k) := rfl end algebra section lift variables {k G} [comm_semiring k] [add_monoid G] variables {A : Type u₃} [semiring A] [algebra k A] {B : Type*} [semiring B] [algebra k B] /-- `lift_nc_ring_hom` as a `alg_hom`, for when `f` is an `alg_hom` -/ def lift_nc_alg_hom (f : A →ₐ[k] B) (g : multiplicative G →* B) (h_comm : ∀ x y, commute (f x) (g y)) : add_monoid_algebra A G →ₐ[k] B := { to_fun := lift_nc_ring_hom (f : A →+* B) g h_comm, commutes' := by simp [lift_nc_ring_hom], ..(lift_nc_ring_hom (f : A →+* B) g h_comm)} /-- A `k`-algebra homomorphism from `monoid_algebra k G` is uniquely defined by its values on the functions `single a 1`. -/ lemma alg_hom_ext ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : ∀ x, φ₁ (single x 1) = φ₂ (single x 1)) : φ₁ = φ₂ := @monoid_algebra.alg_hom_ext k (multiplicative G) _ _ _ _ _ _ _ h /-- See note [partially-applied ext lemmas]. -/ @[ext] lemma alg_hom_ext' ⦃φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A⦄ (h : (φ₁ : add_monoid_algebra k G →* A).comp (of k G) = (φ₂ : add_monoid_algebra k G →* A).comp (of k G)) : φ₁ = φ₂ := alg_hom_ext $ monoid_hom.congr_fun h variables (k G A) /-- Any monoid homomorphism `G →* A` can be lifted to an algebra homomorphism `monoid_algebra k G →ₐ[k] A`. -/ def lift : (multiplicative G →* A) ≃ (add_monoid_algebra k G →ₐ[k] A) := { inv_fun := λ f, (f : add_monoid_algebra k G →* A).comp (of k G), to_fun := λ F, { to_fun := lift_nc_alg_hom (algebra.of_id k A) F $ λ _ _, algebra.commutes _ _, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ F}, .. @monoid_algebra.lift k (multiplicative G) _ _ A _ _ } variables {k G A} lemma lift_apply' (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, (algebra_map k A b) * F (multiplicative.of_add a)) := rfl lemma lift_apply (F : multiplicative G →* A) (f : monoid_algebra k G) : lift k G A F f = f.sum (λ a b, b • F (multiplicative.of_add a)) := by simp only [lift_apply', algebra.smul_def] lemma lift_def (F : multiplicative G →* A) : ⇑(lift k G A F) = lift_nc ((algebra_map k A : k →+* A) : k →+ A) F := rfl @[simp] lemma lift_symm_apply (F : add_monoid_algebra k G →ₐ[k] A) (x : multiplicative G) : (lift k G A).symm F x = F (single x.to_add 1) := rfl lemma lift_of (F : multiplicative G →* A) (x : multiplicative G) : lift k G A F (of k G x) = F x := by rw [of_apply, ← lift_symm_apply, equiv.symm_apply_apply] @[simp] lemma lift_single (F : multiplicative G →* A) (a b) : lift k G A F (single a b) = b • F (multiplicative.of_add a) := by rw [lift_def, lift_nc_single, algebra.smul_def, ring_hom.coe_add_monoid_hom] lemma lift_unique' (F : add_monoid_algebra k G →ₐ[k] A) : F = lift k G A ((F : add_monoid_algebra k G →* A).comp (of k G)) := ((lift k G A).apply_symm_apply F).symm /-- Decomposition of a `k`-algebra homomorphism from `monoid_algebra k G` by its values on `F (single a 1)`. -/ lemma lift_unique (F : add_monoid_algebra k G →ₐ[k] A) (f : monoid_algebra k G) : F f = f.sum (λ a b, b • F (single a 1)) := by conv_lhs { rw lift_unique' F, simp [lift_apply] } lemma alg_hom_ext_iff {φ₁ φ₂ : add_monoid_algebra k G →ₐ[k] A} : (∀ x, φ₁ (finsupp.single x 1) = φ₂ (finsupp.single x 1)) ↔ φ₁ = φ₂ := ⟨λ h, alg_hom_ext h, by rintro rfl _; refl⟩ end lift section local attribute [reducible] add_monoid_algebra universe ui variable {ι : Type ui} lemma prod_single [comm_semiring k] [add_comm_monoid G] {s : finset ι} {a : ι → G} {b : ι → k} : (∏ i in s, single (a i) (b i)) = single (∑ i in s, a i) (∏ i in s, b i) := finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih, single_mul_single, sum_insert has, prod_insert has] end end add_monoid_algebra
e9b4387cb75b75c9c9c015283f936efa9b881625
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/finmap.lean
566f9345615f729eee672ec438fa694fb3c6c2c7
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
18,215
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro Finite maps over `multiset`. -/ import data.list.alist import data.finset import data.pfun universes u v w open list variables {α : Type u} {β : α → Type v} namespace multiset /-- Multiset of keys of an association multiset. -/ def keys (s : multiset (sigma β)) : multiset α := s.map sigma.fst @[simp] theorem coe_keys {l : list (sigma β)} : keys (l : multiset (sigma β)) = (l.keys : multiset α) := rfl /-- `nodupkeys s` means that `s` has no duplicate keys. -/ def nodupkeys (s : multiset (sigma β)) : Prop := quot.lift_on s list.nodupkeys (λ s t p, propext $ perm_nodupkeys p) @[simp] theorem coe_nodupkeys {l : list (sigma β)} : @nodupkeys α β l ↔ l.nodupkeys := iff.rfl end multiset /-- `finmap β` is the type of finite maps over a multiset. It is effectively a quotient of `alist β` by permutation of the underlying list. -/ structure finmap (β : α → Type v) : Type (max u v) := (entries : multiset (sigma β)) (nodupkeys : entries.nodupkeys) /-- The quotient map from `alist` to `finmap`. -/ def alist.to_finmap (s : alist β) : finmap β := ⟨s.entries, s.nodupkeys⟩ local notation `⟦`:max a `⟧`:0 := alist.to_finmap a theorem alist.to_finmap_eq {s₁ s₂ : alist β} : ⟦s₁⟧ = ⟦s₂⟧ ↔ s₁.entries ~ s₂.entries := by cases s₁; cases s₂; simp [alist.to_finmap] @[simp] theorem alist.to_finmap_entries (s : alist β) : ⟦s⟧.entries = s.entries := rfl def list.to_finmap [decidable_eq α] (s : list (sigma β)) : finmap β := alist.to_finmap (list.to_alist s) namespace finmap open alist /-- Lift a permutation-respecting function on `alist` to `finmap`. -/ @[elab_as_eliminator] def lift_on {γ} (s : finmap β) (f : alist β → γ) (H : ∀ a b : alist β, a.entries ~ b.entries → f a = f b) : γ := begin refine (quotient.lift_on s.1 (λ l, (⟨_, λ nd, f ⟨l, nd⟩⟩ : roption γ)) (λ l₁ l₂ p, roption.ext' (perm_nodupkeys p) _) : roption γ).get _, { exact λ h₁ h₂, H _ _ (by exact p) }, { have := s.nodupkeys, rcases s.entries with ⟨l⟩, exact id } end @[simp] theorem lift_on_to_finmap {γ} (s : alist β) (f : alist β → γ) (H) : lift_on ⟦s⟧ f H = f s := by cases s; refl /-- Lift a permutation-respecting function on 2 `alist`s to 2 `finmap`s. -/ @[elab_as_eliminator] def lift_on₂ {γ} (s₁ s₂ : finmap β) (f : alist β → alist β → γ) (H : ∀ a₁ b₁ a₂ b₂ : alist β, a₁.entries ~ a₂.entries → b₁.entries ~ b₂.entries → f a₁ b₁ = f a₂ b₂) : γ := lift_on s₁ (λ l₁, lift_on s₂ (f l₁) (λ b₁ b₂ p, H _ _ _ _ (perm.refl _) p)) (λ a₁ a₂ p, have H' : f a₁ = f a₂ := funext (λ _, H _ _ _ _ p (perm.refl _)), by simp only [H']) @[simp] theorem lift_on₂_to_finmap {γ} (s₁ s₂ : alist β) (f : alist β → alist β → γ) (H) : lift_on₂ ⟦s₁⟧ ⟦s₂⟧ f H = f s₁ s₂ := by cases s₁; cases s₂; refl @[elab_as_eliminator] theorem induction_on {C : finmap β → Prop} (s : finmap β) (H : ∀ (a : alist β), C ⟦a⟧) : C s := by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩ @[elab_as_eliminator] theorem induction_on₂ {C : finmap β → finmap β → Prop} (s₁ s₂ : finmap β) (H : ∀ (a₁ a₂ : alist β), C ⟦a₁⟧ ⟦a₂⟧) : C s₁ s₂ := induction_on s₁ $ λ l₁, induction_on s₂ $ λ l₂, H l₁ l₂ @[elab_as_eliminator] theorem induction_on₃ {C : finmap β → finmap β → finmap β → Prop} (s₁ s₂ s₃ : finmap β) (H : ∀ (a₁ a₂ a₃ : alist β), C ⟦a₁⟧ ⟦a₂⟧ ⟦a₃⟧) : C s₁ s₂ s₃ := induction_on₂ s₁ s₂ $ λ l₁ l₂, induction_on s₃ $ λ l₃, H l₁ l₂ l₃ @[ext] theorem ext : ∀ {s t : finmap β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr' @[simp] theorem ext_iff {s t : finmap β} : s.entries = t.entries ↔ s = t := ⟨ext, congr_arg _⟩ /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : has_mem α (finmap β) := ⟨λ a s, a ∈ s.entries.keys⟩ theorem mem_def {a : α} {s : finmap β} : a ∈ s ↔ a ∈ s.entries.keys := iff.rfl @[simp] theorem mem_to_finmap {a : α} {s : alist β} : a ∈ ⟦s⟧ ↔ a ∈ s := iff.rfl /-- The set of keys of a finite map. -/ def keys (s : finmap β) : finset α := ⟨s.entries.keys, induction_on s keys_nodup⟩ @[simp] theorem keys_val (s : alist β) : (keys ⟦s⟧).val = s.keys := rfl @[simp] theorem keys_ext {s₁ s₂ : alist β} : keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys := by simp [keys, alist.keys] theorem mem_keys {a : α} {s : finmap β} : a ∈ s.keys ↔ a ∈ s := induction_on s $ λ s, alist.mem_keys /-- The empty map. -/ instance : has_emptyc (finmap β) := ⟨⟨0, nodupkeys_nil⟩⟩ instance : inhabited (finmap β) := ⟨∅⟩ @[simp] theorem empty_to_finmap : (⟦∅⟧ : finmap β) = ∅ := rfl @[simp] theorem to_finmap_nil [decidable_eq α] : (list.to_finmap [] : finmap β) = ∅ := rfl theorem not_mem_empty {a : α} : a ∉ (∅ : finmap β) := multiset.not_mem_zero a @[simp] theorem keys_empty : (∅ : finmap β).keys = ∅ := rfl /-- The singleton map. -/ def singleton (a : α) (b : β a) : finmap β := ⟦ alist.singleton a b ⟧ @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = finset.singleton a := rfl @[simp] lemma mem_singleton (x y : α) (b : β y) : x ∈ singleton y b ↔ x = y := by simp only [singleton]; erw [mem_cons_eq,mem_nil_iff,or_false] variables [decidable_eq α] instance has_decidable_eq [∀ a, decidable_eq (β a)] : decidable_eq (finmap β) | s₁ s₂ := decidable_of_iff _ ext_iff /-- Look up the value associated to a key in a map. -/ def lookup (a : α) (s : finmap β) : option (β a) := lift_on s (lookup a) (λ s t, perm_lookup) @[simp] theorem lookup_to_finmap (a : α) (s : alist β) : lookup a ⟦s⟧ = s.lookup a := rfl @[simp] theorem lookup_list_to_finmap (a : α) (s : list (sigma β)) : lookup a s.to_finmap = s.lookup a := by rw [list.to_finmap,lookup_to_finmap,lookup_to_alist] @[simp] theorem lookup_empty (a) : lookup a (∅ : finmap β) = none := rfl theorem lookup_is_some {a : α} {s : finmap β} : (s.lookup a).is_some ↔ a ∈ s := induction_on s $ λ s, alist.lookup_is_some theorem lookup_eq_none {a} {s : finmap β} : lookup a s = none ↔ a ∉ s := induction_on s $ λ s, alist.lookup_eq_none @[simp] lemma lookup_singleton_eq {a : α} {b : β a} : (singleton a b).lookup a = some b := by rw [singleton,lookup_to_finmap,alist.singleton,alist.lookup,lookup_cons_eq] instance (a : α) (s : finmap β) : decidable (a ∈ s) := decidable_of_iff _ lookup_is_some /-- Replace a key with a given value in a finite map. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : finmap β) : finmap β := lift_on s (λ t, ⟦replace a b t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_replace p @[simp] theorem replace_to_finmap (a : α) (b : β a) (s : alist β) : replace a b ⟦s⟧ = ⟦s.replace a b⟧ := by simp [replace] @[simp] theorem keys_replace (a : α) (b : β a) (s : finmap β) : (replace a b s).keys = s.keys := induction_on s $ λ s, by simp @[simp] theorem mem_replace {a a' : α} {b : β a} {s : finmap β} : a' ∈ replace a b s ↔ a' ∈ s := induction_on s $ λ s, by simp /-- Fold a commutative function over the key-value pairs in the map -/ def foldl {δ : Type w} (f : δ → Π a, β a → δ) (H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁) (d : δ) (m : finmap β) : δ := m.entries.foldl (λ d s, f d s.1 s.2) (λ d s t, H _ _ _ _ _) d def any (f : Π x, β x → bool) (s : finmap β) : bool := s.foldl (λ x y z, x ∨ f y z) (by simp [or_assoc]; intros; congr' 2; rw or_comm) ff def all (f : Π x, β x → bool) (s : finmap β) : bool := s.foldl (λ x y z, x ∧ f y z) (by simp [and_assoc]; intros; congr' 2; rw and_comm) ff /-- Erase a key from the map. If the key is not present it does nothing. -/ def erase (a : α) (s : finmap β) : finmap β := lift_on s (λ t, ⟦erase a t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_erase p @[simp] theorem erase_to_finmap (a : α) (s : alist β) : erase a ⟦s⟧ = ⟦s.erase a⟧ := by simp [erase] @[simp] theorem keys_erase_to_finset (a : α) (s : alist β) : keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a := by simp [finset.erase, keys, alist.erase, keys_kerase] @[simp] theorem keys_erase (a : α) (s : finmap β) : (erase a s).keys = s.keys.erase a := induction_on s $ λ s, by simp @[simp] theorem mem_erase {a a' : α} {s : finmap β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := induction_on s $ λ s, by simp theorem not_mem_erase_self {a : α} {s : finmap β} : ¬ a ∈ erase a s := by rw [mem_erase,not_and_distrib,not_not]; left; refl @[simp] theorem lookup_erase (a) (s : finmap β) : lookup a (erase a s) = none := induction_on s $ lookup_erase a @[simp] theorem lookup_erase_ne {a a'} {s : finmap β} (h : a ≠ a') : lookup a (erase a' s) = lookup a s := induction_on s $ λ s, lookup_erase_ne h theorem erase_erase {a a' : α} {s : finmap β} : erase a (erase a' s) = erase a' (erase a s) := induction_on s $ λ s, ext (by simp [alist.erase_erase]) lemma mem_iff {a : α} {s : finmap β} : a ∈ s ↔ ∃ b, s.lookup a = some b := induction_on s $ λ s, iff.trans list.mem_keys $ exists_congr $ λ b, (mem_lookup_iff s.nodupkeys).symm lemma mem_of_lookup_eq_some {a : α} {b : β a} {s : finmap β} (h : s.lookup a = some b) : a ∈ s := mem_iff.mpr ⟨_,h⟩ /- sub -/ def sdiff (s s' : finmap β) : finmap β := s'.foldl (λ s x _, s.erase x) (λ a₀ a₁ _ a₂ _, erase_erase) s instance : has_sdiff (finmap β) := ⟨ sdiff ⟩ /- insert -/ /-- Insert a key-value pair into a finite map, replacing any existing pair with the same key. -/ def insert (a : α) (b : β a) (s : finmap β) : finmap β := lift_on s (λ t, ⟦insert a b t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_insert p @[simp] theorem insert_to_finmap (a : α) (b : β a) (s : alist β) : insert a b ⟦s⟧ = ⟦s.insert a b⟧ := by simp [insert] theorem insert_entries_of_neg {a : α} {b : β a} {s : finmap β} : a ∉ s → (insert a b s).entries = ⟨a, b⟩ :: s.entries := induction_on s $ λ s h, by simp [insert_entries_of_neg (mt mem_to_finmap.1 h)] @[simp] theorem mem_insert {a a' : α} {b' : β a'} {s : finmap β} : a ∈ insert a' b' s ↔ a = a' ∨ a ∈ s := induction_on s mem_insert @[simp] theorem lookup_insert {a} {b : β a} (s : finmap β) : lookup a (insert a b s) = some b := induction_on s $ λ s, by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert] @[simp] theorem lookup_insert_of_ne {a a'} {b : β a} (s : finmap β) (h : a' ≠ a) : lookup a' (insert a b s) = lookup a' s := induction_on s $ λ s, by simp only [insert_to_finmap, lookup_to_finmap, lookup_insert_ne h] @[simp] theorem insert_insert {a} {b b' : β a} (s : finmap β) : (s.insert a b).insert a b' = s.insert a b' := induction_on s $ λ s, by simp only [insert_to_finmap, insert_insert] theorem insert_insert_of_ne {a a'} {b : β a} {b' : β a'} (s : finmap β) (h : a ≠ a') : (s.insert a b).insert a' b' = (s.insert a' b').insert a b := induction_on s $ λ s, by simp only [insert_to_finmap,alist.to_finmap_eq,insert_insert_of_ne _ h] theorem to_finmap_cons (a : α) (b : β a) (xs : list (sigma β)) : list.to_finmap (⟨a,b⟩ :: xs) = insert a b xs.to_finmap := rfl theorem mem_list_to_finmap (a : α) (xs : list (sigma β)) : a ∈ xs.to_finmap ↔ (∃ b : β a, sigma.mk a b ∈ xs) := by { induction xs with x xs; [skip, cases x]; simp only [to_finmap_cons, *, not_mem_empty, exists_or_distrib, list.not_mem_nil, finmap.to_finmap_nil, iff_self, exists_false, mem_cons_iff, mem_insert, exists_and_distrib_left]; apply or_congr _ iff.rfl, conv { to_lhs, rw ← and_true (a = x_fst) }, apply and_congr_right, rintro ⟨⟩, simp only [exists_eq, iff_self, heq_iff_eq] } @[simp] theorem insert_singleton_eq {a : α} {b b' : β a} : insert a b (singleton a b') = singleton a b := by simp only [singleton, finmap.insert_to_finmap, alist.insert_singleton_eq] /- extract -/ /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : finmap β) : option (β a) × finmap β := lift_on s (λ t, prod.map id to_finmap (extract a t)) $ λ s₁ s₂ p, by simp [perm_lookup p, to_finmap_eq, perm_erase p] @[simp] theorem extract_eq_lookup_erase (a : α) (s : finmap β) : extract a s = (lookup a s, erase a s) := induction_on s $ λ s, by simp [extract] /- union -/ /-- `s₁ ∪ s₂` is the key-based union of two finite maps. It is left-biased: if there exists an `a ∈ s₁`, `lookup a (s₁ ∪ s₂) = lookup a s₁`. -/ def union (s₁ s₂ : finmap β) : finmap β := lift_on₂ s₁ s₂ (λ s₁ s₂, ⟦s₁ ∪ s₂⟧) $ λ s₁ s₂ s₃ s₄ p₁₃ p₂₄, to_finmap_eq.mpr $ perm_union p₁₃ p₂₄ instance : has_union (finmap β) := ⟨union⟩ @[simp] theorem mem_union {a} {s₁ s₂ : finmap β} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := induction_on₂ s₁ s₂ $ λ _ _, mem_union @[simp] theorem union_to_finmap (s₁ s₂ : alist β) : ⟦s₁⟧ ∪ ⟦s₂⟧ = ⟦s₁ ∪ s₂⟧ := by simp [(∪), union] theorem keys_union {s₁ s₂ : finmap β} : (s₁ ∪ s₂).keys = s₁.keys ∪ s₂.keys := induction_on₂ s₁ s₂ $ λ s₁ s₂, finset.ext' $ by simp [keys] @[simp] theorem lookup_union_left {a} {s₁ s₂ : finmap β} : a ∈ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₁ := induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_left @[simp] theorem lookup_union_right {a} {s₁ s₂ : finmap β} : a ∉ s₁ → lookup a (s₁ ∪ s₂) = lookup a s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂, lookup_union_right theorem lookup_union_left_of_not_in {a} {s₁ s₂ : finmap β} : a ∉ s₂ → lookup a (s₁ ∪ s₂) = lookup a s₁ := begin intros h, by_cases h' : a ∈ s₁, { rw lookup_union_left h' }, { rw [lookup_union_right h',lookup_eq_none.mpr h,lookup_eq_none.mpr h'] } end @[simp] theorem mem_lookup_union {a} {b : β a} {s₁ s₂ : finmap β} : b ∈ lookup a (s₁ ∪ s₂) ↔ b ∈ lookup a s₁ ∨ a ∉ s₁ ∧ b ∈ lookup a s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂, mem_lookup_union theorem mem_lookup_union_middle {a} {b : β a} {s₁ s₂ s₃ : finmap β} : b ∈ lookup a (s₁ ∪ s₃) → a ∉ s₂ → b ∈ lookup a (s₁ ∪ s₂ ∪ s₃) := induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, mem_lookup_union_middle theorem insert_union {a} {b : β a} {s₁ s₂ : finmap β} : insert a b (s₁ ∪ s₂) = insert a b s₁ ∪ s₂ := induction_on₂ s₁ s₂ $ λ a₁ a₂, by simp [insert_union] theorem union_assoc {s₁ s₂ s₃ : finmap β} : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := induction_on₃ s₁ s₂ s₃ $ λ s₁ s₂ s₃, by simp only [alist.to_finmap_eq,union_to_finmap,alist.union_assoc] @[simp] theorem empty_union {s₁ : finmap β} : ∅ ∪ s₁ = s₁ := induction_on s₁ $ λ s₁, by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq,union_to_finmap,alist.union_assoc] @[simp] theorem union_empty {s₁ : finmap β} : s₁ ∪ ∅ = s₁ := induction_on s₁ $ λ s₁, by rw ← empty_to_finmap; simp [- empty_to_finmap, alist.to_finmap_eq,union_to_finmap,alist.union_assoc] theorem ext_lookup {s₁ s₂ : finmap β} : (∀ x, s₁.lookup x = s₂.lookup x) → s₁ = s₂ := induction_on₂ s₁ s₂ $ λ s₁ s₂ h, by simp only [alist.lookup, lookup_to_finmap] at h; rw [alist.to_finmap_eq]; apply lookup_ext s₁.nodupkeys s₂.nodupkeys; intros x y; rw h theorem erase_union_singleton (a : α) (b : β a) (s : finmap β) (h : s.lookup a = some b) : s.erase a ∪ singleton a b = s := ext_lookup (by { intro, by_cases h' : x = a, { subst a, rw [lookup_union_right not_mem_erase_self,lookup_singleton_eq,h], }, { have : x ∉ singleton a b, { rw mem_singleton, exact h' }, rw [lookup_union_left_of_not_in this,lookup_erase_ne h'] } } ) /- disjoint -/ def disjoint (s₁ s₂ : finmap β) := ∀ x ∈ s₁, ¬ x ∈ s₂ instance : decidable_rel (@disjoint α β _) := by intros x y; dsimp [disjoint]; apply_instance lemma disjoint_empty (x : finmap β) : disjoint ∅ x . @[symm] lemma disjoint.symm (x y : finmap β) (h : disjoint x y) : disjoint y x := λ p hy hx, h p hx hy lemma disjoint.symm_iff (x y : finmap β) : disjoint x y ↔ disjoint y x := ⟨ disjoint.symm x y, disjoint.symm y x ⟩ lemma disjoint_union_left (x y z : finmap β) : disjoint (x ∪ y) z ↔ disjoint x z ∧ disjoint y z := by simp [disjoint,finmap.mem_union,or_imp_distrib,forall_and_distrib] lemma disjoint_union_right (x y z : finmap β) : disjoint x (y ∪ z) ↔ disjoint x y ∧ disjoint x z := by rw [disjoint.symm_iff,disjoint_union_left,disjoint.symm_iff _ x,disjoint.symm_iff _ x] theorem union_comm_of_disjoint {s₁ s₂ : finmap β} : disjoint s₁ s₂ → s₁ ∪ s₂ = s₂ ∪ s₁ := induction_on₂ s₁ s₂ $ λ s₁ s₂, by { intros h, simp only [alist.to_finmap_eq,union_to_finmap,alist.union_comm_of_disjoint h] } theorem union_cancel {s₁ s₂ s₃ : finmap β} (h : disjoint s₁ s₃) (h' : disjoint s₂ s₃) : s₁ ∪ s₃ = s₂ ∪ s₃ ↔ s₁ = s₂ := ⟨λ h'', begin apply ext_lookup, intro x, have : (s₁ ∪ s₃).lookup x = (s₂ ∪ s₃).lookup x, from h'' ▸ rfl, by_cases hs₁ : x ∈ s₁, { rw [lookup_union_left hs₁,lookup_union_left_of_not_in (h _ hs₁)] at this, exact this }, { by_cases hs₂ : x ∈ s₂, { rw [lookup_union_left_of_not_in (h' _ hs₂),lookup_union_left hs₂] at this; exact this }, { rw [lookup_eq_none.mpr hs₁,lookup_eq_none.mpr hs₂] } } end, λ h, h ▸ rfl⟩ end finmap
adcc533020e3a03af77634c073afdddd2ad5ab95
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/information_theory/hamming.lean
cc11ad8a3649f2681f6ea9bf4921aea91106b104
[ "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
14,141
lean
/- Copyright (c) 2022 Wrenna Robson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wrenna Robson -/ import analysis.normed.group.basic /-! # Hamming spaces The Hamming metric counts the number of places two members of a (finite) Pi type differ. The Hamming norm is the same as the Hamming metric over additive groups, and counts the number of places a member of a (finite) Pi type differs from zero. This is a useful notion in various applications, but in particular it is relevant in coding theory, in which it is fundamental for defining the minimum distance of a code. ## Main definitions * `hamming_dist x y`: the Hamming distance between `x` and `y`, the number of entries which differ. * `hamming_norm x`: the Hamming norm of `x`, the number of non-zero entries. * `hamming β`: a type synonym for `Π i, β i` with `dist` and `norm` provided by the above. * `hamming.to_hamming`, `hamming.of_hamming`: functions for casting between `hamming β` and `Π i, β i`. * `hamming.normed_add_comm_group`: the Hamming norm forms a normed group on `hamming β`. -/ section hamming_dist_norm open finset function variables {α ι : Type*} {β : ι → Type*} [fintype ι] [Π i, decidable_eq (β i)] variables {γ : ι → Type*} [Π i, decidable_eq (γ i)] /-- The Hamming distance function to the naturals. -/ def hamming_dist (x y : Π i, β i) : ℕ := (univ.filter (λ i, x i ≠ y i)).card /-- Corresponds to `dist_self`. -/ @[simp] lemma hamming_dist_self (x : Π i, β i) : hamming_dist x x = 0 := by { rw [hamming_dist, card_eq_zero, filter_eq_empty_iff], exact λ _ _ H, H rfl } /-- Corresponds to `dist_nonneg`. -/ lemma hamming_dist_nonneg {x y : Π i, β i} : 0 ≤ hamming_dist x y := zero_le _ /-- Corresponds to `dist_comm`. -/ lemma hamming_dist_comm (x y : Π i, β i) : hamming_dist x y = hamming_dist y x := by simp_rw [hamming_dist, ne_comm] /-- Corresponds to `dist_triangle`. -/ lemma hamming_dist_triangle (x y z : Π i, β i) : hamming_dist x z ≤ hamming_dist x y + hamming_dist y z := begin classical, simp_rw hamming_dist, refine le_trans (card_mono _) (card_union_le _ _), rw ← filter_or, refine monotone_filter_right _ _, intros i h, by_contra' H, exact h (eq.trans H.1 H.2) end /-- Corresponds to `dist_triangle_left`. -/ lemma hamming_dist_triangle_left (x y z : Π i, β i) : hamming_dist x y ≤ hamming_dist z x + hamming_dist z y := by { rw hamming_dist_comm z, exact hamming_dist_triangle _ _ _ } /-- Corresponds to `dist_triangle_right`. -/ lemma hamming_dist_triangle_right (x y z : Π i, β i) : hamming_dist x y ≤ hamming_dist x z + hamming_dist y z := by { rw hamming_dist_comm y, exact hamming_dist_triangle _ _ _ } /-- Corresponds to `swap_dist`. -/ theorem swap_hamming_dist : swap (@hamming_dist _ β _ _) = hamming_dist := by { funext x y, exact hamming_dist_comm _ _ } /-- Corresponds to `eq_of_dist_eq_zero`. -/ lemma eq_of_hamming_dist_eq_zero {x y : Π i, β i} : hamming_dist x y = 0 → x = y := by simp_rw [hamming_dist, card_eq_zero, filter_eq_empty_iff, not_not, funext_iff, mem_univ, forall_true_left, imp_self] /-- Corresponds to `dist_eq_zero`. -/ @[simp] lemma hamming_dist_eq_zero {x y : Π i, β i} : hamming_dist x y = 0 ↔ x = y := ⟨eq_of_hamming_dist_eq_zero, (λ H, by {rw H, exact hamming_dist_self _})⟩ /-- Corresponds to `zero_eq_dist`. -/ @[simp] lemma hamming_zero_eq_dist {x y : Π i, β i} : 0 = hamming_dist x y ↔ x = y := by rw [eq_comm, hamming_dist_eq_zero] /-- Corresponds to `dist_ne_zero`. -/ lemma hamming_dist_ne_zero {x y : Π i, β i} : hamming_dist x y ≠ 0 ↔ x ≠ y := hamming_dist_eq_zero.not /-- Corresponds to `dist_pos`. -/ @[simp] lemma hamming_dist_pos {x y : Π i, β i} : 0 < hamming_dist x y ↔ x ≠ y := by rw [←hamming_dist_ne_zero, iff_not_comm, not_lt, nat.le_zero_iff] @[simp] lemma hamming_dist_lt_one {x y : Π i, β i} : hamming_dist x y < 1 ↔ x = y := by rw [nat.lt_one_iff, hamming_dist_eq_zero] lemma hamming_dist_le_card_fintype {x y : Π i, β i} : hamming_dist x y ≤ fintype.card ι := card_le_univ _ lemma hamming_dist_comp_le_hamming_dist (f : Π i, γ i → β i) {x y : Π i, γ i} : hamming_dist (λ i, f i (x i)) (λ i, f i (y i)) ≤ hamming_dist x y := card_mono (monotone_filter_right _ $ λ i H1 H2, H1 $ congr_arg (f i) H2) lemma hamming_dist_comp (f : Π i, γ i → β i) {x y : Π i, γ i} (hf : Π i, injective (f i)) : hamming_dist (λ i, f i (x i)) (λ i, f i (y i)) = hamming_dist x y := begin refine le_antisymm (hamming_dist_comp_le_hamming_dist _) _, exact card_mono (monotone_filter_right _ $ λ i H1 H2, H1 $ hf i H2) end lemma hamming_dist_smul_le_hamming_dist [Π i, has_smul α (β i)] {k : α} {x y : Π i, β i} : hamming_dist (k • x) (k • y) ≤ hamming_dist x y := hamming_dist_comp_le_hamming_dist $ λ i, (•) k /-- Corresponds to `dist_smul` with the discrete norm on `α`. -/ lemma hamming_dist_smul [Π i, has_smul α (β i)] {k : α} {x y : Π i, β i} (hk : Π i, is_smul_regular (β i) k) : hamming_dist (k • x) (k • y) = hamming_dist x y := hamming_dist_comp (λ i, (•) k) hk section has_zero variables [Π i, has_zero (β i)] [Π i, has_zero (γ i)] /-- The Hamming weight function to the naturals. -/ def hamming_norm (x : Π i, β i) : ℕ := (univ.filter (λ i, x i ≠ 0)).card /-- Corresponds to `dist_zero_right`. -/ @[simp] lemma hamming_dist_zero_right (x : Π i, β i) : hamming_dist x 0 = hamming_norm x := rfl /-- Corresponds to `dist_zero_left`. -/ @[simp] lemma hamming_dist_zero_left : hamming_dist (0 : Π i, β i) = hamming_norm := funext $ λ x, by rw [hamming_dist_comm, hamming_dist_zero_right] /-- Corresponds to `norm_nonneg`. -/ @[simp] lemma hamming_norm_nonneg {x : Π i, β i} : 0 ≤ hamming_norm x := zero_le _ /-- Corresponds to `norm_zero`. -/ @[simp] lemma hamming_norm_zero : hamming_norm (0 : Π i, β i) = 0 := hamming_dist_self _ /-- Corresponds to `norm_eq_zero`. -/ @[simp] lemma hamming_norm_eq_zero {x : Π i, β i} : hamming_norm x = 0 ↔ x = 0 := hamming_dist_eq_zero /-- Corresponds to `norm_ne_zero_iff`. -/ lemma hamming_norm_ne_zero_iff {x : Π i, β i} : hamming_norm x ≠ 0 ↔ x ≠ 0 := hamming_norm_eq_zero.not /-- Corresponds to `norm_pos_iff`. -/ @[simp] lemma hamming_norm_pos_iff {x : Π i, β i} : 0 < hamming_norm x ↔ x ≠ 0 := hamming_dist_pos @[simp] lemma hamming_norm_lt_one {x : Π i, β i} : hamming_norm x < 1 ↔ x = 0 := hamming_dist_lt_one lemma hamming_norm_le_card_fintype {x : Π i, β i} : hamming_norm x ≤ fintype.card ι := hamming_dist_le_card_fintype lemma hamming_norm_comp_le_hamming_norm (f : Π i, γ i → β i) {x : Π i, γ i} (hf : Π i, f i 0 = 0) : hamming_norm (λ i, f i (x i)) ≤ hamming_norm x := by {convert hamming_dist_comp_le_hamming_dist f, simp_rw hf, refl} lemma hamming_norm_comp (f : Π i, γ i → β i) {x : Π i, γ i} (hf₁ : Π i, injective (f i)) (hf₂ : Π i, f i 0 = 0) : hamming_norm (λ i, f i (x i)) = hamming_norm x := by {convert hamming_dist_comp f hf₁, simp_rw hf₂, refl} lemma hamming_norm_smul_le_hamming_norm [has_zero α] [Π i, smul_with_zero α (β i)] {k : α} {x : Π i, β i} : hamming_norm (k • x) ≤ hamming_norm x := hamming_norm_comp_le_hamming_norm (λ i (c : β i), k • c) (λ i, by simp_rw smul_zero') lemma hamming_norm_smul [has_zero α] [Π i, smul_with_zero α (β i)] {k : α} (hk : ∀ i, is_smul_regular (β i) k) (x : Π i, β i) : hamming_norm (k • x) = hamming_norm x := hamming_norm_comp (λ i (c : β i), k • c) hk (λ i, by simp_rw smul_zero') end has_zero /-- Corresponds to `dist_eq_norm`. -/ lemma hamming_dist_eq_hamming_norm [Π i, add_group (β i)] (x y : Π i, β i) : hamming_dist x y = hamming_norm (x - y) := by simp_rw [hamming_norm, hamming_dist, pi.sub_apply, sub_ne_zero] end hamming_dist_norm /-! ### The `hamming` type synonym -/ /-- Type synonym for a Pi type which inherits the usual algebraic instances, but is equipped with the Hamming metric and norm, instead of `pi.normed_add_comm_group` which uses the sup norm. -/ def hamming {ι : Type*} (β : ι → Type*) : Type* := Π i, β i namespace hamming variables {α ι : Type*} {β : ι → Type*} /-! Instances inherited from normal Pi types. -/ instance [Π i, inhabited (β i)] : inhabited (hamming β) := ⟨λ i, default⟩ instance [decidable_eq ι] [fintype ι] [Π i, fintype (β i)] : fintype (hamming β) := pi.fintype instance [inhabited ι] [∀ i, nonempty (β i)] [nontrivial (β default)] : nontrivial (hamming β) := pi.nontrivial instance [fintype ι] [Π i, decidable_eq (β i)] : decidable_eq (hamming β) := fintype.decidable_pi_fintype instance [Π i, has_zero (β i)] : has_zero (hamming β) := pi.has_zero instance [Π i, has_neg (β i)] : has_neg (hamming β) := pi.has_neg instance [Π i, has_add (β i)] : has_add (hamming β) := pi.has_add instance [Π i, has_sub (β i)] : has_sub (hamming β) := pi.has_sub instance [Π i, has_smul α (β i)] : has_smul α (hamming β) := pi.has_smul instance [has_zero α] [Π i, has_zero (β i)] [Π i, smul_with_zero α (β i)] : smul_with_zero α (hamming β) := pi.smul_with_zero _ instance [Π i, add_monoid (β i)] : add_monoid (hamming β) := pi.add_monoid instance [Π i, add_comm_monoid (β i)] : add_comm_monoid (hamming β) := pi.add_comm_monoid instance [Π i, add_comm_group (β i)] : add_comm_group (hamming β) := pi.add_comm_group instance (α) [semiring α] (β : ι → Type*) [Π i, add_comm_monoid (β i)] [Π i, module α (β i)] : module α (hamming β) := pi.module _ _ _ /-! API to/from the type synonym. -/ /-- `to_hamming` is the identity function to the `hamming` of a type. -/ @[pattern] def to_hamming : (Π i, β i) ≃ hamming β := equiv.refl _ /-- `of_hamming` is the identity function from the `hamming` of a type. -/ @[pattern] def of_hamming : hamming β ≃ Π i, β i := equiv.refl _ @[simp] lemma to_hamming_symm_eq : (@to_hamming _ β).symm = of_hamming := rfl @[simp] lemma of_hamming_symm_eq : (@of_hamming _ β).symm = to_hamming := rfl @[simp] lemma to_hamming_of_hamming (x : hamming β) : to_hamming (of_hamming x) = x := rfl @[simp] lemma of_hamming_to_hamming (x : Π i, β i) : of_hamming (to_hamming x) = x := rfl @[simp] lemma to_hamming_inj {x y : Π i, β i} : to_hamming x = to_hamming y ↔ x = y := iff.rfl @[simp] lemma of_hamming_inj {x y : hamming β} : of_hamming x = of_hamming y ↔ x = y := iff.rfl @[simp] lemma to_hamming_zero [Π i, has_zero (β i)] : to_hamming (0 : Π i, β i) = 0 := rfl @[simp] lemma of_hamming_zero [Π i, has_zero (β i)] : of_hamming (0 : hamming β) = 0 := rfl @[simp] lemma to_hamming_neg [Π i, has_neg (β i)] {x : Π i, β i} : to_hamming (-x) = - to_hamming x := rfl @[simp] lemma of_hamming_neg [Π i, has_neg (β i)] {x : hamming β} : of_hamming (-x) = - of_hamming x := rfl @[simp] lemma to_hamming_add [Π i, has_add (β i)] {x y : Π i, β i} : to_hamming (x + y) = to_hamming x + to_hamming y := rfl @[simp] lemma of_hamming_add [Π i, has_add (β i)] {x y : hamming β} : of_hamming (x + y) = of_hamming x + of_hamming y := rfl @[simp] lemma to_hamming_sub [Π i, has_sub (β i)] {x y : Π i, β i} : to_hamming (x - y) = to_hamming x - to_hamming y := rfl @[simp] lemma of_hamming_sub [Π i, has_sub (β i)] {x y : hamming β} : of_hamming (x - y) = of_hamming x - of_hamming y := rfl @[simp] lemma to_hamming_smul [Π i, has_smul α (β i)] {r : α} {x : Π i, β i} : to_hamming (r • x) = r • to_hamming x := rfl @[simp] lemma of_hamming_smul [Π i, has_smul α (β i)] {r : α} {x : hamming β} : of_hamming (r • x) = r • of_hamming x := rfl section /-! Instances equipping `hamming` with `hamming_norm` and `hamming_dist`. -/ variables [fintype ι] [Π i, decidable_eq (β i)] instance : has_dist (hamming β) := ⟨λ x y, hamming_dist (of_hamming x) (of_hamming y)⟩ @[simp, push_cast] lemma dist_eq_hamming_dist (x y : hamming β) : dist x y = hamming_dist (of_hamming x) (of_hamming y) := rfl instance : pseudo_metric_space (hamming β) := { dist_self := by { push_cast, exact_mod_cast hamming_dist_self }, dist_comm := by { push_cast, exact_mod_cast hamming_dist_comm }, dist_triangle := by { push_cast, exact_mod_cast hamming_dist_triangle }, to_uniform_space := ⊥, uniformity_dist := uniformity_dist_of_mem_uniformity _ _ $ λ s, begin push_cast, split, { refine λ hs, ⟨1, zero_lt_one, λ _ _ hab, _⟩, rw_mod_cast [hamming_dist_lt_one] at hab, rw [of_hamming_inj, ← mem_id_rel] at hab, exact hs hab }, { rintros ⟨_, hε, hs⟩ ⟨_, _⟩ hab, rw mem_id_rel at hab, rw hab, refine hs (lt_of_eq_of_lt _ hε), exact_mod_cast hamming_dist_self _ } end, to_bornology := ⟨⊥, bot_le⟩, cobounded_sets := begin ext, push_cast, refine iff_of_true (filter.mem_sets.mpr filter.mem_bot) ⟨fintype.card ι, λ _ _ _ _, _⟩, exact_mod_cast hamming_dist_le_card_fintype end, ..hamming.has_dist } @[simp, push_cast] lemma nndist_eq_hamming_dist (x y : hamming β) : nndist x y = hamming_dist (of_hamming x) (of_hamming y) := rfl instance : metric_space (hamming β) := { eq_of_dist_eq_zero := by { push_cast, exact_mod_cast @eq_of_hamming_dist_eq_zero _ _ _ _ }, ..hamming.pseudo_metric_space } instance [Π i, has_zero (β i)] : has_norm (hamming β) := ⟨λ x, hamming_norm (of_hamming x)⟩ @[simp, push_cast] lemma norm_eq_hamming_norm [Π i, has_zero (β i)] (x : hamming β) : ∥x∥ = hamming_norm (of_hamming x) := rfl instance [Π i, add_comm_group (β i)] : seminormed_add_comm_group (hamming β) := { dist_eq := by { push_cast, exact_mod_cast hamming_dist_eq_hamming_norm }, ..pi.add_comm_group } @[simp, push_cast] lemma nnnorm_eq_hamming_norm [Π i, add_comm_group (β i)] (x : hamming β) : ∥x∥₊ = hamming_norm (of_hamming x) := rfl instance [Π i, add_comm_group (β i)] : normed_add_comm_group (hamming β) := { ..hamming.seminormed_add_comm_group } end end hamming
ad169bef7c2ad61bd44c946efc291755cac2001a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/semicontinuous.lean
1a42cd958b721a000d8303b2161f5cc1326a5334
[ "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
46,875
lean
/- Copyright (c) 2021 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 algebra.indicator_function import topology.continuous_on import topology.instances.ennreal /-! # Semicontinuous maps A function `f` from a topological space `α` to an ordered space `β` is lower semicontinuous at a point `x` if, for any `y < f x`, for any `x'` close enough to `x`, one has `f x' > y`. In other words, `f` can jump up, but it can not jump down. Upper semicontinuous functions are defined similarly. This file introduces these notions, and a basic API around them mimicking the API for continuous functions. ## Main definitions and results We introduce 4 definitions related to lower semicontinuity: * `lower_semicontinuous_within_at f s x` * `lower_semicontinuous_at f x` * `lower_semicontinuous_on f s` * `lower_semicontinuous f` We build a basic API using dot notation around these notions, and we prove that * constant functions are lower semicontinuous; * `indicator s (λ _, y)` is lower semicontinuous when `s` is open and `0 ≤ y`, or when `s` is closed and `y ≤ 0`; * continuous functions are lower semicontinuous; * composition with a continuous monotone functions maps lower semicontinuous functions to lower semicontinuous functions. If the function is anti-monotone, it instead maps lower semicontinuous functions to upper semicontinuous functions; * a sum of two (or finitely many) lower semicontinuous functions is lower semicontinuous; * a supremum of a family of lower semicontinuous functions is lower semicontinuous; * An infinite sum of `ℝ≥0∞`-valued lower semicontinuous functions is lower semicontinuous. Similar results are stated and proved for upper semicontinuity. We also prove that a function is continuous if and only if it is both lower and upper semicontinuous. ## Implementation details All the nontrivial results for upper semicontinuous functions are deduced from the corresponding ones for lower semicontinuous functions using `order_dual`. -/ open_locale topological_space big_operators ennreal open set function filter variables {α : Type*} [topological_space α] {β : Type*} [preorder β] {f g : α → β} {x : α} {s t : set α} {y z : β} /-! ### Main definitions -/ /-- A real function `f` is lower semicontinuous at `x` within a set `s` if, for any `ε > 0`, for all `x'` close enough to `x` in `s`, then `f x'` is at least `f x - ε`. We formulate this in a general preordered space, using an arbitrary `y < f x` instead of `f x - ε`. -/ def lower_semicontinuous_within_at (f : α → β) (s : set α) (x : α) := ∀ y < f x, ∀ᶠ x' in 𝓝[s] x, y < f x' /-- A real function `f` is lower semicontinuous on a set `s` if, for any `ε > 0`, for any `x ∈ s`, for all `x'` close enough to `x` in `s`, then `f x'` is at least `f x - ε`. We formulate this in a general preordered space, using an arbitrary `y < f x` instead of `f x - ε`.-/ def lower_semicontinuous_on (f : α → β) (s : set α) := ∀ x ∈ s, lower_semicontinuous_within_at f s x /-- A real function `f` is lower semicontinuous at `x` if, for any `ε > 0`, for all `x'` close enough to `x`, then `f x'` is at least `f x - ε`. We formulate this in a general preordered space, using an arbitrary `y < f x` instead of `f x - ε`. -/ def lower_semicontinuous_at (f : α → β) (x : α) := ∀ y < f x, ∀ᶠ x' in 𝓝 x, y < f x' /-- A real function `f` is lower semicontinuous if, for any `ε > 0`, for any `x`, for all `x'` close enough to `x`, then `f x'` is at least `f x - ε`. We formulate this in a general preordered space, using an arbitrary `y < f x` instead of `f x - ε`. -/ def lower_semicontinuous (f : α → β) := ∀ x, lower_semicontinuous_at f x /-- A real function `f` is upper semicontinuous at `x` within a set `s` if, for any `ε > 0`, for all `x'` close enough to `x` in `s`, then `f x'` is at most `f x + ε`. We formulate this in a general preordered space, using an arbitrary `y > f x` instead of `f x + ε`. -/ def upper_semicontinuous_within_at (f : α → β) (s : set α) (x : α) := ∀ y, f x < y → ∀ᶠ x' in 𝓝[s] x, f x' < y /-- A real function `f` is upper semicontinuous on a set `s` if, for any `ε > 0`, for any `x ∈ s`, for all `x'` close enough to `x` in `s`, then `f x'` is at most `f x + ε`. We formulate this in a general preordered space, using an arbitrary `y > f x` instead of `f x + ε`.-/ def upper_semicontinuous_on (f : α → β) (s : set α) := ∀ x ∈ s, upper_semicontinuous_within_at f s x /-- A real function `f` is upper semicontinuous at `x` if, for any `ε > 0`, for all `x'` close enough to `x`, then `f x'` is at most `f x + ε`. We formulate this in a general preordered space, using an arbitrary `y > f x` instead of `f x + ε`. -/ def upper_semicontinuous_at (f : α → β) (x : α) := ∀ y, f x < y → ∀ᶠ x' in 𝓝 x, f x' < y /-- A real function `f` is upper semicontinuous if, for any `ε > 0`, for any `x`, for all `x'` close enough to `x`, then `f x'` is at most `f x + ε`. We formulate this in a general preordered space, using an arbitrary `y > f x` instead of `f x + ε`.-/ def upper_semicontinuous (f : α → β) := ∀ x, upper_semicontinuous_at f x /-! ### Lower semicontinuous functions -/ /-! #### Basic dot notation interface for lower semicontinuity -/ lemma lower_semicontinuous_within_at.mono (h : lower_semicontinuous_within_at f s x) (hst : t ⊆ s) : lower_semicontinuous_within_at f t x := λ y hy, filter.eventually.filter_mono (nhds_within_mono _ hst) (h y hy) lemma lower_semicontinuous_within_at_univ_iff : lower_semicontinuous_within_at f univ x ↔ lower_semicontinuous_at f x := by simp [lower_semicontinuous_within_at, lower_semicontinuous_at, nhds_within_univ] lemma lower_semicontinuous_at.lower_semicontinuous_within_at (s : set α) (h : lower_semicontinuous_at f x) : lower_semicontinuous_within_at f s x := λ y hy, filter.eventually.filter_mono nhds_within_le_nhds (h y hy) lemma lower_semicontinuous_on.lower_semicontinuous_within_at (h : lower_semicontinuous_on f s) (hx : x ∈ s) : lower_semicontinuous_within_at f s x := h x hx lemma lower_semicontinuous_on.mono (h : lower_semicontinuous_on f s) (hst : t ⊆ s) : lower_semicontinuous_on f t := λ x hx, (h x (hst hx)).mono hst lemma lower_semicontinuous_on_univ_iff : lower_semicontinuous_on f univ ↔ lower_semicontinuous f := by simp [lower_semicontinuous_on, lower_semicontinuous, lower_semicontinuous_within_at_univ_iff] lemma lower_semicontinuous.lower_semicontinuous_at (h : lower_semicontinuous f) (x : α) : lower_semicontinuous_at f x := h x lemma lower_semicontinuous.lower_semicontinuous_within_at (h : lower_semicontinuous f) (s : set α) (x : α) : lower_semicontinuous_within_at f s x := (h x).lower_semicontinuous_within_at s lemma lower_semicontinuous.lower_semicontinuous_on (h : lower_semicontinuous f) (s : set α) : lower_semicontinuous_on f s := λ x hx, h.lower_semicontinuous_within_at s x /-! #### Constants -/ lemma lower_semicontinuous_within_at_const : lower_semicontinuous_within_at (λ x, z) s x := λ y hy, filter.eventually_of_forall (λ x, hy) lemma lower_semicontinuous_at_const : lower_semicontinuous_at (λ x, z) x := λ y hy, filter.eventually_of_forall (λ x, hy) lemma lower_semicontinuous_on_const : lower_semicontinuous_on (λ x, z) s := λ x hx, lower_semicontinuous_within_at_const lemma lower_semicontinuous_const : lower_semicontinuous (λ (x : α), z) := λ x, lower_semicontinuous_at_const /-! #### Indicators -/ section variables [has_zero β] lemma is_open.lower_semicontinuous_indicator (hs : is_open s) (hy : 0 ≤ y) : lower_semicontinuous (indicator s (λ x, y)) := begin assume x z hz, by_cases h : x ∈ s; simp [h] at hz, { filter_upwards [hs.mem_nhds h], simp [hz] { contextual := tt} }, { apply filter.eventually_of_forall (λ x', _), by_cases h' : x' ∈ s; simp [h', hz.trans_le hy, hz] } end lemma is_open.lower_semicontinuous_on_indicator (hs : is_open s) (hy : 0 ≤ y) : lower_semicontinuous_on (indicator s (λ x, y)) t := (hs.lower_semicontinuous_indicator hy).lower_semicontinuous_on t lemma is_open.lower_semicontinuous_at_indicator (hs : is_open s) (hy : 0 ≤ y) : lower_semicontinuous_at (indicator s (λ x, y)) x := (hs.lower_semicontinuous_indicator hy).lower_semicontinuous_at x lemma is_open.lower_semicontinuous_within_at_indicator (hs : is_open s) (hy : 0 ≤ y) : lower_semicontinuous_within_at (indicator s (λ x, y)) t x := (hs.lower_semicontinuous_indicator hy).lower_semicontinuous_within_at t x lemma is_closed.lower_semicontinuous_indicator (hs : is_closed s) (hy : y ≤ 0) : lower_semicontinuous (indicator s (λ x, y)) := begin assume x z hz, by_cases h : x ∈ s; simp [h] at hz, { apply filter.eventually_of_forall (λ x', _), by_cases h' : x' ∈ s; simp [h', hz, hz.trans_le hy], }, { filter_upwards [hs.is_open_compl.mem_nhds h], simp [hz] { contextual := tt } } end lemma is_closed.lower_semicontinuous_on_indicator (hs : is_closed s) (hy : y ≤ 0) : lower_semicontinuous_on (indicator s (λ x, y)) t := (hs.lower_semicontinuous_indicator hy).lower_semicontinuous_on t lemma is_closed.lower_semicontinuous_at_indicator (hs : is_closed s) (hy : y ≤ 0) : lower_semicontinuous_at (indicator s (λ x, y)) x := (hs.lower_semicontinuous_indicator hy).lower_semicontinuous_at x lemma is_closed.lower_semicontinuous_within_at_indicator (hs : is_closed s) (hy : y ≤ 0) : lower_semicontinuous_within_at (indicator s (λ x, y)) t x := (hs.lower_semicontinuous_indicator hy).lower_semicontinuous_within_at t x end /-! #### Relationship with continuity -/ theorem lower_semicontinuous_iff_is_open_preimage : lower_semicontinuous f ↔ ∀ y, is_open (f ⁻¹' (Ioi y)) := ⟨λ H y, is_open_iff_mem_nhds.2 (λ x hx, H x y hx), λ H x y y_lt, is_open.mem_nhds (H y) y_lt⟩ lemma lower_semicontinuous.is_open_preimage (hf : lower_semicontinuous f) (y : β) : is_open (f ⁻¹' (Ioi y)) := lower_semicontinuous_iff_is_open_preimage.1 hf y section variables {γ : Type*} [linear_order γ] theorem lower_semicontinuous_iff_is_closed_preimage {f : α → γ} : lower_semicontinuous f ↔ ∀ y, is_closed (f ⁻¹' (Iic y)) := begin rw lower_semicontinuous_iff_is_open_preimage, congrm (∀ y, (_ : Prop)), rw [← is_open_compl_iff, ← preimage_compl, compl_Iic] end lemma lower_semicontinuous.is_closed_preimage {f : α → γ} (hf : lower_semicontinuous f) (y : γ) : is_closed (f ⁻¹' (Iic y)) := lower_semicontinuous_iff_is_closed_preimage.1 hf y variables [topological_space γ] [order_topology γ] lemma continuous_within_at.lower_semicontinuous_within_at {f : α → γ} (h : continuous_within_at f s x) : lower_semicontinuous_within_at f s x := λ y hy, h (Ioi_mem_nhds hy) lemma continuous_at.lower_semicontinuous_at {f : α → γ} (h : continuous_at f x) : lower_semicontinuous_at f x := λ y hy, h (Ioi_mem_nhds hy) lemma continuous_on.lower_semicontinuous_on {f : α → γ} (h : continuous_on f s) : lower_semicontinuous_on f s := λ x hx, (h x hx).lower_semicontinuous_within_at lemma continuous.lower_semicontinuous {f : α → γ} (h : continuous f) : lower_semicontinuous f := λ x, h.continuous_at.lower_semicontinuous_at end /-! ### Composition -/ section variables {γ : Type*} [linear_order γ] [topological_space γ] [order_topology γ] variables {δ : Type*} [linear_order δ] [topological_space δ] [order_topology δ] lemma continuous_at.comp_lower_semicontinuous_within_at {g : γ → δ} {f : α → γ} (hg : continuous_at g (f x)) (hf : lower_semicontinuous_within_at f s x) (gmon : monotone g) : lower_semicontinuous_within_at (g ∘ f) s x := begin assume y hy, by_cases h : ∃ l, l < f x, { obtain ⟨z, zlt, hz⟩ : ∃ z < f x, Ioc z (f x) ⊆ g ⁻¹' (Ioi y) := exists_Ioc_subset_of_mem_nhds (hg (Ioi_mem_nhds hy)) h, filter_upwards [hf z zlt] with a ha, calc y < g (min (f x) (f a)) : hz (by simp [zlt, ha, le_refl]) ... ≤ g (f a) : gmon (min_le_right _ _) }, { simp only [not_exists, not_lt] at h, exact filter.eventually_of_forall (λ a, hy.trans_le (gmon (h (f a)))) } end lemma continuous_at.comp_lower_semicontinuous_at {g : γ → δ} {f : α → γ} (hg : continuous_at g (f x)) (hf : lower_semicontinuous_at f x) (gmon : monotone g) : lower_semicontinuous_at (g ∘ f) x := begin simp only [← lower_semicontinuous_within_at_univ_iff] at hf ⊢, exact hg.comp_lower_semicontinuous_within_at hf gmon end lemma continuous.comp_lower_semicontinuous_on {g : γ → δ} {f : α → γ} (hg : continuous g) (hf : lower_semicontinuous_on f s) (gmon : monotone g) : lower_semicontinuous_on (g ∘ f) s := λ x hx, (hg.continuous_at).comp_lower_semicontinuous_within_at (hf x hx) gmon lemma continuous.comp_lower_semicontinuous {g : γ → δ} {f : α → γ} (hg : continuous g) (hf : lower_semicontinuous f) (gmon : monotone g) : lower_semicontinuous (g ∘ f) := λ x, (hg.continuous_at).comp_lower_semicontinuous_at (hf x) gmon lemma continuous_at.comp_lower_semicontinuous_within_at_antitone {g : γ → δ} {f : α → γ} (hg : continuous_at g (f x)) (hf : lower_semicontinuous_within_at f s x) (gmon : antitone g) : upper_semicontinuous_within_at (g ∘ f) s x := @continuous_at.comp_lower_semicontinuous_within_at α _ x s γ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon lemma continuous_at.comp_lower_semicontinuous_at_antitone {g : γ → δ} {f : α → γ} (hg : continuous_at g (f x)) (hf : lower_semicontinuous_at f x) (gmon : antitone g) : upper_semicontinuous_at (g ∘ f) x := @continuous_at.comp_lower_semicontinuous_at α _ x γ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon lemma continuous.comp_lower_semicontinuous_on_antitone {g : γ → δ} {f : α → γ} (hg : continuous g) (hf : lower_semicontinuous_on f s) (gmon : antitone g) : upper_semicontinuous_on (g ∘ f) s := λ x hx, (hg.continuous_at).comp_lower_semicontinuous_within_at_antitone (hf x hx) gmon lemma continuous.comp_lower_semicontinuous_antitone {g : γ → δ} {f : α → γ} (hg : continuous g) (hf : lower_semicontinuous f) (gmon : antitone g) : upper_semicontinuous (g ∘ f) := λ x, (hg.continuous_at).comp_lower_semicontinuous_at_antitone (hf x) gmon end /-! #### Addition -/ section variables {ι : Type*} {γ : Type*} [linear_ordered_add_comm_monoid γ] [topological_space γ] [order_topology γ] /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `ereal`. The unprimed version of the lemma uses `[has_continuous_add]`. -/ lemma lower_semicontinuous_within_at.add' {f g : α → γ} (hf : lower_semicontinuous_within_at f s x) (hg : lower_semicontinuous_within_at g s x) (hcont : continuous_at (λ (p : γ × γ), p.1 + p.2) (f x, g x)) : lower_semicontinuous_within_at (λ z, f z + g z) s x := begin assume y hy, obtain ⟨u, v, u_open, xu, v_open, xv, h⟩ : ∃ (u v : set γ), is_open u ∧ f x ∈ u ∧ is_open v ∧ g x ∈ v ∧ u ×ˢ v ⊆ {p : γ × γ | y < p.fst + p.snd} := mem_nhds_prod_iff'.1 (hcont (is_open_Ioi.mem_nhds hy)), by_cases hx₁ : ∃ l, l < f x, { obtain ⟨z₁, z₁lt, h₁⟩ : ∃ z₁ < f x, Ioc z₁ (f x) ⊆ u := exists_Ioc_subset_of_mem_nhds (u_open.mem_nhds xu) hx₁, by_cases hx₂ : ∃ l, l < g x, { obtain ⟨z₂, z₂lt, h₂⟩ : ∃ z₂ < g x, Ioc z₂ (g x) ⊆ v := exists_Ioc_subset_of_mem_nhds (v_open.mem_nhds xv) hx₂, filter_upwards [hf z₁ z₁lt, hg z₂ z₂lt] with z h₁z h₂z, have A1 : min (f z) (f x) ∈ u, { by_cases H : f z ≤ f x, { simp [H], exact h₁ ⟨h₁z, H⟩ }, { simp [le_of_not_le H], exact h₁ ⟨z₁lt, le_rfl⟩, } }, have A2 : min (g z) (g x) ∈ v, { by_cases H : g z ≤ g x, { simp [H], exact h₂ ⟨h₂z, H⟩ }, { simp [le_of_not_le H], exact h₂ ⟨z₂lt, le_rfl⟩, } }, have : (min (f z) (f x), min (g z) (g x)) ∈ u ×ˢ v := ⟨A1, A2⟩, calc y < min (f z) (f x) + min (g z) (g x) : h this ... ≤ f z + g z : add_le_add (min_le_left _ _) (min_le_left _ _) }, { simp only [not_exists, not_lt] at hx₂, filter_upwards [hf z₁ z₁lt] with z h₁z, have A1 : min (f z) (f x) ∈ u, { by_cases H : f z ≤ f x, { simp [H], exact h₁ ⟨h₁z, H⟩ }, { simp [le_of_not_le H], exact h₁ ⟨z₁lt, le_rfl⟩, } }, have : (min (f z) (f x), g x) ∈ u ×ˢ v := ⟨A1, xv⟩, calc y < min (f z) (f x) + g x : h this ... ≤ f z + g z : add_le_add (min_le_left _ _) (hx₂ (g z)) } }, { simp only [not_exists, not_lt] at hx₁, by_cases hx₂ : ∃ l, l < g x, { obtain ⟨z₂, z₂lt, h₂⟩ : ∃ z₂ < g x, Ioc z₂ (g x) ⊆ v := exists_Ioc_subset_of_mem_nhds (v_open.mem_nhds xv) hx₂, filter_upwards [hg z₂ z₂lt] with z h₂z, have A2 : min (g z) (g x) ∈ v, { by_cases H : g z ≤ g x, { simp [H], exact h₂ ⟨h₂z, H⟩ }, { simp [le_of_not_le H], exact h₂ ⟨z₂lt, le_rfl⟩, } }, have : (f x, min (g z) (g x)) ∈ u ×ˢ v := ⟨xu, A2⟩, calc y < f x + min (g z) (g x) : h this ... ≤ f z + g z : add_le_add (hx₁ (f z)) (min_le_left _ _) }, { simp only [not_exists, not_lt] at hx₁ hx₂, apply filter.eventually_of_forall, assume z, have : (f x, g x) ∈ u ×ˢ v := ⟨xu, xv⟩, calc y < f x + g x : h this ... ≤ f z + g z : add_le_add (hx₁ (f z)) (hx₂ (g z)) } }, end /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `ereal`. The unprimed version of the lemma uses `[has_continuous_add]`. -/ lemma lower_semicontinuous_at.add' {f g : α → γ} (hf : lower_semicontinuous_at f x) (hg : lower_semicontinuous_at g x) (hcont : continuous_at (λ (p : γ × γ), p.1 + p.2) (f x, g x)) : lower_semicontinuous_at (λ z, f z + g z) x := by { simp_rw [← lower_semicontinuous_within_at_univ_iff] at *, exact hf.add' hg hcont } /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `ereal`. The unprimed version of the lemma uses `[has_continuous_add]`. -/ lemma lower_semicontinuous_on.add' {f g : α → γ} (hf : lower_semicontinuous_on f s) (hg : lower_semicontinuous_on g s) (hcont : ∀ x ∈ s, continuous_at (λ (p : γ × γ), p.1 + p.2) (f x, g x)) : lower_semicontinuous_on (λ z, f z + g z) s := λ x hx, (hf x hx).add' (hg x hx) (hcont x hx) /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `ereal`. The unprimed version of the lemma uses `[has_continuous_add]`. -/ lemma lower_semicontinuous.add' {f g : α → γ} (hf : lower_semicontinuous f) (hg : lower_semicontinuous g) (hcont : ∀ x, continuous_at (λ (p : γ × γ), p.1 + p.2) (f x, g x)) : lower_semicontinuous (λ z, f z + g z) := λ x, (hf x).add' (hg x) (hcont x) variable [has_continuous_add γ] /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with `[has_continuous_add]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `ereal`. -/ lemma lower_semicontinuous_within_at.add {f g : α → γ} (hf : lower_semicontinuous_within_at f s x) (hg : lower_semicontinuous_within_at g s x) : lower_semicontinuous_within_at (λ z, f z + g z) s x := hf.add' hg continuous_add.continuous_at /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with `[has_continuous_add]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `ereal`. -/ lemma lower_semicontinuous_at.add {f g : α → γ} (hf : lower_semicontinuous_at f x) (hg : lower_semicontinuous_at g x) : lower_semicontinuous_at (λ z, f z + g z) x := hf.add' hg continuous_add.continuous_at /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with `[has_continuous_add]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `ereal`. -/ lemma lower_semicontinuous_on.add {f g : α → γ} (hf : lower_semicontinuous_on f s) (hg : lower_semicontinuous_on g s) : lower_semicontinuous_on (λ z, f z + g z) s := hf.add' hg (λ x hx, continuous_add.continuous_at) /-- The sum of two lower semicontinuous functions is lower semicontinuous. Formulated with `[has_continuous_add]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `ereal`. -/ lemma lower_semicontinuous.add {f g : α → γ} (hf : lower_semicontinuous f) (hg : lower_semicontinuous g) : lower_semicontinuous (λ z, f z + g z) := hf.add' hg (λ x, continuous_add.continuous_at) lemma lower_semicontinuous_within_at_sum {f : ι → α → γ} {a : finset ι} (ha : ∀ i ∈ a, lower_semicontinuous_within_at (f i) s x) : lower_semicontinuous_within_at (λ z, (∑ i in a, f i z)) s x := begin classical, induction a using finset.induction_on with i a ia IH generalizing ha, { exact lower_semicontinuous_within_at_const }, { simp only [ia, finset.sum_insert, not_false_iff], exact lower_semicontinuous_within_at.add (ha _ (finset.mem_insert_self i a)) (IH (λ j ja, ha j (finset.mem_insert_of_mem ja))) } end lemma lower_semicontinuous_at_sum {f : ι → α → γ} {a : finset ι} (ha : ∀ i ∈ a, lower_semicontinuous_at (f i) x) : lower_semicontinuous_at (λ z, (∑ i in a, f i z)) x := begin simp_rw [← lower_semicontinuous_within_at_univ_iff] at *, exact lower_semicontinuous_within_at_sum ha end lemma lower_semicontinuous_on_sum {f : ι → α → γ} {a : finset ι} (ha : ∀ i ∈ a, lower_semicontinuous_on (f i) s) : lower_semicontinuous_on (λ z, (∑ i in a, f i z)) s := λ x hx, lower_semicontinuous_within_at_sum (λ i hi, ha i hi x hx) lemma lower_semicontinuous_sum {f : ι → α → γ} {a : finset ι} (ha : ∀ i ∈ a, lower_semicontinuous (f i)) : lower_semicontinuous (λ z, (∑ i in a, f i z)) := λ x, lower_semicontinuous_at_sum (λ i hi, ha i hi x) end /-! #### Supremum -/ section variables {ι : Sort*} {δ δ' : Type*} [complete_linear_order δ] [conditionally_complete_linear_order δ'] lemma lower_semicontinuous_within_at_csupr {f : ι → α → δ'} (bdd : ∀ᶠ y in 𝓝[s] x, bdd_above (range $ λ i, f i y)) (h : ∀ i, lower_semicontinuous_within_at (f i) s x) : lower_semicontinuous_within_at (λ x', ⨆ i, f i x') s x := begin casesI is_empty_or_nonempty ι, { simpa only [supr_of_empty'] using lower_semicontinuous_within_at_const }, { assume y hy, rcases exists_lt_of_lt_csupr hy with ⟨i, hi⟩, filter_upwards [h i y hi, bdd] with y hy hy' using hy.trans_le (le_csupr hy' i) } end lemma lower_semicontinuous_within_at_supr {f : ι → α → δ} (h : ∀ i, lower_semicontinuous_within_at (f i) s x) : lower_semicontinuous_within_at (λ x', ⨆ i, f i x') s x := lower_semicontinuous_within_at_csupr (by simp) h lemma lower_semicontinuous_within_at_bsupr {p : ι → Prop} {f : Π i (h : p i), α → δ} (h : ∀ i hi, lower_semicontinuous_within_at (f i hi) s x) : lower_semicontinuous_within_at (λ x', ⨆ i hi, f i hi x') s x := lower_semicontinuous_within_at_supr $ λ i, lower_semicontinuous_within_at_supr $ λ hi, h i hi lemma lower_semicontinuous_at_csupr {f : ι → α → δ'} (bdd : ∀ᶠ y in 𝓝 x, bdd_above (range $ λ i, f i y)) (h : ∀ i, lower_semicontinuous_at (f i) x) : lower_semicontinuous_at (λ x', ⨆ i, f i x') x := begin simp_rw [← lower_semicontinuous_within_at_univ_iff] at *, rw ← nhds_within_univ at bdd, exact lower_semicontinuous_within_at_csupr bdd h end lemma lower_semicontinuous_at_supr {f : ι → α → δ} (h : ∀ i, lower_semicontinuous_at (f i) x) : lower_semicontinuous_at (λ x', ⨆ i, f i x') x := lower_semicontinuous_at_csupr (by simp) h lemma lower_semicontinuous_at_bsupr {p : ι → Prop} {f : Π i (h : p i), α → δ} (h : ∀ i hi, lower_semicontinuous_at (f i hi) x) : lower_semicontinuous_at (λ x', ⨆ i hi, f i hi x') x := lower_semicontinuous_at_supr $ λ i, lower_semicontinuous_at_supr $ λ hi, h i hi lemma lower_semicontinuous_on_csupr {f : ι → α → δ'} (bdd : ∀ x ∈ s, bdd_above (range $ λ i, f i x)) (h : ∀ i, lower_semicontinuous_on (f i) s) : lower_semicontinuous_on (λ x', ⨆ i, f i x') s := λ x hx, lower_semicontinuous_within_at_csupr (eventually_nhds_within_of_forall bdd) (λ i, h i x hx) lemma lower_semicontinuous_on_supr {f : ι → α → δ} (h : ∀ i, lower_semicontinuous_on (f i) s) : lower_semicontinuous_on (λ x', ⨆ i, f i x') s := lower_semicontinuous_on_csupr (by simp) h lemma lower_semicontinuous_on_bsupr {p : ι → Prop} {f : Π i (h : p i), α → δ} (h : ∀ i hi, lower_semicontinuous_on (f i hi) s) : lower_semicontinuous_on (λ x', ⨆ i hi, f i hi x') s := lower_semicontinuous_on_supr $ λ i, lower_semicontinuous_on_supr $ λ hi, h i hi lemma lower_semicontinuous_csupr {f : ι → α → δ'} (bdd : ∀ x, bdd_above (range $ λ i, f i x)) (h : ∀ i, lower_semicontinuous (f i)) : lower_semicontinuous (λ x', ⨆ i, f i x') := λ x, lower_semicontinuous_at_csupr (eventually_of_forall bdd) (λ i, h i x) lemma lower_semicontinuous_supr {f : ι → α → δ} (h : ∀ i, lower_semicontinuous (f i)) : lower_semicontinuous (λ x', ⨆ i, f i x') := lower_semicontinuous_csupr (by simp) h lemma lower_semicontinuous_bsupr {p : ι → Prop} {f : Π i (h : p i), α → δ} (h : ∀ i hi, lower_semicontinuous (f i hi)) : lower_semicontinuous (λ x', ⨆ i hi, f i hi x') := lower_semicontinuous_supr $ λ i, lower_semicontinuous_supr $ λ hi, h i hi end /-! #### Infinite sums -/ section variables {ι : Type*} lemma lower_semicontinuous_within_at_tsum {f : ι → α → ℝ≥0∞} (h : ∀ i, lower_semicontinuous_within_at (f i) s x) : lower_semicontinuous_within_at (λ x', ∑' i, f i x') s x := begin simp_rw ennreal.tsum_eq_supr_sum, apply lower_semicontinuous_within_at_supr (λ b, _), exact lower_semicontinuous_within_at_sum (λ i hi, h i), end lemma lower_semicontinuous_at_tsum {f : ι → α → ℝ≥0∞} (h : ∀ i, lower_semicontinuous_at (f i) x) : lower_semicontinuous_at (λ x', ∑' i, f i x') x := begin simp_rw [← lower_semicontinuous_within_at_univ_iff] at *, exact lower_semicontinuous_within_at_tsum h end lemma lower_semicontinuous_on_tsum {f : ι → α → ℝ≥0∞} (h : ∀ i, lower_semicontinuous_on (f i) s) : lower_semicontinuous_on (λ x', ∑' i, f i x') s := λ x hx, lower_semicontinuous_within_at_tsum (λ i, h i x hx) lemma lower_semicontinuous_tsum {f : ι → α → ℝ≥0∞} (h : ∀ i, lower_semicontinuous (f i)) : lower_semicontinuous (λ x', ∑' i, f i x') := λ x, lower_semicontinuous_at_tsum (λ i, h i x) end /-! ### Upper semicontinuous functions -/ /-! #### Basic dot notation interface for upper semicontinuity -/ lemma upper_semicontinuous_within_at.mono (h : upper_semicontinuous_within_at f s x) (hst : t ⊆ s) : upper_semicontinuous_within_at f t x := λ y hy, filter.eventually.filter_mono (nhds_within_mono _ hst) (h y hy) lemma upper_semicontinuous_within_at_univ_iff : upper_semicontinuous_within_at f univ x ↔ upper_semicontinuous_at f x := by simp [upper_semicontinuous_within_at, upper_semicontinuous_at, nhds_within_univ] lemma upper_semicontinuous_at.upper_semicontinuous_within_at (s : set α) (h : upper_semicontinuous_at f x) : upper_semicontinuous_within_at f s x := λ y hy, filter.eventually.filter_mono nhds_within_le_nhds (h y hy) lemma upper_semicontinuous_on.upper_semicontinuous_within_at (h : upper_semicontinuous_on f s) (hx : x ∈ s) : upper_semicontinuous_within_at f s x := h x hx lemma upper_semicontinuous_on.mono (h : upper_semicontinuous_on f s) (hst : t ⊆ s) : upper_semicontinuous_on f t := λ x hx, (h x (hst hx)).mono hst lemma upper_semicontinuous_on_univ_iff : upper_semicontinuous_on f univ ↔ upper_semicontinuous f := by simp [upper_semicontinuous_on, upper_semicontinuous, upper_semicontinuous_within_at_univ_iff] lemma upper_semicontinuous.upper_semicontinuous_at (h : upper_semicontinuous f) (x : α) : upper_semicontinuous_at f x := h x lemma upper_semicontinuous.upper_semicontinuous_within_at (h : upper_semicontinuous f) (s : set α) (x : α) : upper_semicontinuous_within_at f s x := (h x).upper_semicontinuous_within_at s lemma upper_semicontinuous.upper_semicontinuous_on (h : upper_semicontinuous f) (s : set α) : upper_semicontinuous_on f s := λ x hx, h.upper_semicontinuous_within_at s x /-! #### Constants -/ lemma upper_semicontinuous_within_at_const : upper_semicontinuous_within_at (λ x, z) s x := λ y hy, filter.eventually_of_forall (λ x, hy) lemma upper_semicontinuous_at_const : upper_semicontinuous_at (λ x, z) x := λ y hy, filter.eventually_of_forall (λ x, hy) lemma upper_semicontinuous_on_const : upper_semicontinuous_on (λ x, z) s := λ x hx, upper_semicontinuous_within_at_const lemma upper_semicontinuous_const : upper_semicontinuous (λ (x : α), z) := λ x, upper_semicontinuous_at_const /-! #### Indicators -/ section variables [has_zero β] lemma is_open.upper_semicontinuous_indicator (hs : is_open s) (hy : y ≤ 0) : upper_semicontinuous (indicator s (λ x, y)) := @is_open.lower_semicontinuous_indicator α _ βᵒᵈ _ s y _ hs hy lemma is_open.upper_semicontinuous_on_indicator (hs : is_open s) (hy : y ≤ 0) : upper_semicontinuous_on (indicator s (λ x, y)) t := (hs.upper_semicontinuous_indicator hy).upper_semicontinuous_on t lemma is_open.upper_semicontinuous_at_indicator (hs : is_open s) (hy : y ≤ 0) : upper_semicontinuous_at (indicator s (λ x, y)) x := (hs.upper_semicontinuous_indicator hy).upper_semicontinuous_at x lemma is_open.upper_semicontinuous_within_at_indicator (hs : is_open s) (hy : y ≤ 0) : upper_semicontinuous_within_at (indicator s (λ x, y)) t x := (hs.upper_semicontinuous_indicator hy).upper_semicontinuous_within_at t x lemma is_closed.upper_semicontinuous_indicator (hs : is_closed s) (hy : 0 ≤ y) : upper_semicontinuous (indicator s (λ x, y)) := @is_closed.lower_semicontinuous_indicator α _ βᵒᵈ _ s y _ hs hy lemma is_closed.upper_semicontinuous_on_indicator (hs : is_closed s) (hy : 0 ≤ y) : upper_semicontinuous_on (indicator s (λ x, y)) t := (hs.upper_semicontinuous_indicator hy).upper_semicontinuous_on t lemma is_closed.upper_semicontinuous_at_indicator (hs : is_closed s) (hy : 0 ≤ y) : upper_semicontinuous_at (indicator s (λ x, y)) x := (hs.upper_semicontinuous_indicator hy).upper_semicontinuous_at x lemma is_closed.upper_semicontinuous_within_at_indicator (hs : is_closed s) (hy : 0 ≤ y) : upper_semicontinuous_within_at (indicator s (λ x, y)) t x := (hs.upper_semicontinuous_indicator hy).upper_semicontinuous_within_at t x end /-! #### Relationship with continuity -/ theorem upper_semicontinuous_iff_is_open_preimage : upper_semicontinuous f ↔ ∀ y, is_open (f ⁻¹' (Iio y)) := ⟨λ H y, is_open_iff_mem_nhds.2 (λ x hx, H x y hx), λ H x y y_lt, is_open.mem_nhds (H y) y_lt⟩ lemma upper_semicontinuous.is_open_preimage (hf : upper_semicontinuous f) (y : β) : is_open (f ⁻¹' (Iio y)) := upper_semicontinuous_iff_is_open_preimage.1 hf y section variables {γ : Type*} [linear_order γ] theorem upper_semicontinuous_iff_is_closed_preimage {f : α → γ} : upper_semicontinuous f ↔ ∀ y, is_closed (f ⁻¹' (Ici y)) := begin rw upper_semicontinuous_iff_is_open_preimage, congrm (∀ y, (_ : Prop)), rw [← is_open_compl_iff, ← preimage_compl, compl_Ici] end lemma upper_semicontinuous.is_closed_preimage {f : α → γ} (hf : upper_semicontinuous f) (y : γ) : is_closed (f ⁻¹' (Ici y)) := upper_semicontinuous_iff_is_closed_preimage.1 hf y variables [topological_space γ] [order_topology γ] lemma continuous_within_at.upper_semicontinuous_within_at {f : α → γ} (h : continuous_within_at f s x) : upper_semicontinuous_within_at f s x := λ y hy, h (Iio_mem_nhds hy) lemma continuous_at.upper_semicontinuous_at {f : α → γ} (h : continuous_at f x) : upper_semicontinuous_at f x := λ y hy, h (Iio_mem_nhds hy) lemma continuous_on.upper_semicontinuous_on {f : α → γ} (h : continuous_on f s) : upper_semicontinuous_on f s := λ x hx, (h x hx).upper_semicontinuous_within_at lemma continuous.upper_semicontinuous {f : α → γ} (h : continuous f) : upper_semicontinuous f := λ x, h.continuous_at.upper_semicontinuous_at end /-! ### Composition -/ section variables {γ : Type*} [linear_order γ] [topological_space γ] [order_topology γ] variables {δ : Type*} [linear_order δ] [topological_space δ] [order_topology δ] lemma continuous_at.comp_upper_semicontinuous_within_at {g : γ → δ} {f : α → γ} (hg : continuous_at g (f x)) (hf : upper_semicontinuous_within_at f s x) (gmon : monotone g) : upper_semicontinuous_within_at (g ∘ f) s x := @continuous_at.comp_lower_semicontinuous_within_at α _ x s γᵒᵈ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon.dual lemma continuous_at.comp_upper_semicontinuous_at {g : γ → δ} {f : α → γ} (hg : continuous_at g (f x)) (hf : upper_semicontinuous_at f x) (gmon : monotone g) : upper_semicontinuous_at (g ∘ f) x := @continuous_at.comp_lower_semicontinuous_at α _ x γᵒᵈ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon.dual lemma continuous.comp_upper_semicontinuous_on {g : γ → δ} {f : α → γ} (hg : continuous g) (hf : upper_semicontinuous_on f s) (gmon : monotone g) : upper_semicontinuous_on (g ∘ f) s := λ x hx, (hg.continuous_at).comp_upper_semicontinuous_within_at (hf x hx) gmon lemma continuous.comp_upper_semicontinuous {g : γ → δ} {f : α → γ} (hg : continuous g) (hf : upper_semicontinuous f) (gmon : monotone g) : upper_semicontinuous (g ∘ f) := λ x, (hg.continuous_at).comp_upper_semicontinuous_at (hf x) gmon lemma continuous_at.comp_upper_semicontinuous_within_at_antitone {g : γ → δ} {f : α → γ} (hg : continuous_at g (f x)) (hf : upper_semicontinuous_within_at f s x) (gmon : antitone g) : lower_semicontinuous_within_at (g ∘ f) s x := @continuous_at.comp_upper_semicontinuous_within_at α _ x s γ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon lemma continuous_at.comp_upper_semicontinuous_at_antitone {g : γ → δ} {f : α → γ} (hg : continuous_at g (f x)) (hf : upper_semicontinuous_at f x) (gmon : antitone g) : lower_semicontinuous_at (g ∘ f) x := @continuous_at.comp_upper_semicontinuous_at α _ x γ _ _ _ δᵒᵈ _ _ _ g f hg hf gmon lemma continuous.comp_upper_semicontinuous_on_antitone {g : γ → δ} {f : α → γ} (hg : continuous g) (hf : upper_semicontinuous_on f s) (gmon : antitone g) : lower_semicontinuous_on (g ∘ f) s := λ x hx, (hg.continuous_at).comp_upper_semicontinuous_within_at_antitone (hf x hx) gmon lemma continuous.comp_upper_semicontinuous_antitone {g : γ → δ} {f : α → γ} (hg : continuous g) (hf : upper_semicontinuous f) (gmon : antitone g) : lower_semicontinuous (g ∘ f) := λ x, (hg.continuous_at).comp_upper_semicontinuous_at_antitone (hf x) gmon end /-! #### Addition -/ section variables {ι : Type*} {γ : Type*} [linear_ordered_add_comm_monoid γ] [topological_space γ] [order_topology γ] /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `ereal`. The unprimed version of the lemma uses `[has_continuous_add]`. -/ lemma upper_semicontinuous_within_at.add' {f g : α → γ} (hf : upper_semicontinuous_within_at f s x) (hg : upper_semicontinuous_within_at g s x) (hcont : continuous_at (λ (p : γ × γ), p.1 + p.2) (f x, g x)) : upper_semicontinuous_within_at (λ z, f z + g z) s x := @lower_semicontinuous_within_at.add' α _ x s γᵒᵈ _ _ _ _ _ hf hg hcont /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `ereal`. The unprimed version of the lemma uses `[has_continuous_add]`. -/ lemma upper_semicontinuous_at.add' {f g : α → γ} (hf : upper_semicontinuous_at f x) (hg : upper_semicontinuous_at g x) (hcont : continuous_at (λ (p : γ × γ), p.1 + p.2) (f x, g x)) : upper_semicontinuous_at (λ z, f z + g z) x := by { simp_rw [← upper_semicontinuous_within_at_univ_iff] at *, exact hf.add' hg hcont } /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `ereal`. The unprimed version of the lemma uses `[has_continuous_add]`. -/ lemma upper_semicontinuous_on.add' {f g : α → γ} (hf : upper_semicontinuous_on f s) (hg : upper_semicontinuous_on g s) (hcont : ∀ x ∈ s, continuous_at (λ (p : γ × γ), p.1 + p.2) (f x, g x)) : upper_semicontinuous_on (λ z, f z + g z) s := λ x hx, (hf x hx).add' (hg x hx) (hcont x hx) /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with an explicit continuity assumption on addition, for application to `ereal`. The unprimed version of the lemma uses `[has_continuous_add]`. -/ lemma upper_semicontinuous.add' {f g : α → γ} (hf : upper_semicontinuous f) (hg : upper_semicontinuous g) (hcont : ∀ x, continuous_at (λ (p : γ × γ), p.1 + p.2) (f x, g x)) : upper_semicontinuous (λ z, f z + g z) := λ x, (hf x).add' (hg x) (hcont x) variable [has_continuous_add γ] /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with `[has_continuous_add]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `ereal`. -/ lemma upper_semicontinuous_within_at.add {f g : α → γ} (hf : upper_semicontinuous_within_at f s x) (hg : upper_semicontinuous_within_at g s x) : upper_semicontinuous_within_at (λ z, f z + g z) s x := hf.add' hg continuous_add.continuous_at /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with `[has_continuous_add]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `ereal`. -/ lemma upper_semicontinuous_at.add {f g : α → γ} (hf : upper_semicontinuous_at f x) (hg : upper_semicontinuous_at g x) : upper_semicontinuous_at (λ z, f z + g z) x := hf.add' hg continuous_add.continuous_at /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with `[has_continuous_add]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `ereal`. -/ lemma upper_semicontinuous_on.add {f g : α → γ} (hf : upper_semicontinuous_on f s) (hg : upper_semicontinuous_on g s) : upper_semicontinuous_on (λ z, f z + g z) s := hf.add' hg (λ x hx, continuous_add.continuous_at) /-- The sum of two upper semicontinuous functions is upper semicontinuous. Formulated with `[has_continuous_add]`. The primed version of the lemma uses an explicit continuity assumption on addition, for application to `ereal`. -/ lemma upper_semicontinuous.add {f g : α → γ} (hf : upper_semicontinuous f) (hg : upper_semicontinuous g) : upper_semicontinuous (λ z, f z + g z) := hf.add' hg (λ x, continuous_add.continuous_at) lemma upper_semicontinuous_within_at_sum {f : ι → α → γ} {a : finset ι} (ha : ∀ i ∈ a, upper_semicontinuous_within_at (f i) s x) : upper_semicontinuous_within_at (λ z, (∑ i in a, f i z)) s x := @lower_semicontinuous_within_at_sum α _ x s ι γᵒᵈ _ _ _ _ f a ha lemma upper_semicontinuous_at_sum {f : ι → α → γ} {a : finset ι} (ha : ∀ i ∈ a, upper_semicontinuous_at (f i) x) : upper_semicontinuous_at (λ z, (∑ i in a, f i z)) x := begin simp_rw [← upper_semicontinuous_within_at_univ_iff] at *, exact upper_semicontinuous_within_at_sum ha end lemma upper_semicontinuous_on_sum {f : ι → α → γ} {a : finset ι} (ha : ∀ i ∈ a, upper_semicontinuous_on (f i) s) : upper_semicontinuous_on (λ z, (∑ i in a, f i z)) s := λ x hx, upper_semicontinuous_within_at_sum (λ i hi, ha i hi x hx) lemma upper_semicontinuous_sum {f : ι → α → γ} {a : finset ι} (ha : ∀ i ∈ a, upper_semicontinuous (f i)) : upper_semicontinuous (λ z, (∑ i in a, f i z)) := λ x, upper_semicontinuous_at_sum (λ i hi, ha i hi x) end /-! #### Infimum -/ section variables {ι : Sort*} {δ δ' : Type*} [complete_linear_order δ] [conditionally_complete_linear_order δ'] lemma upper_semicontinuous_within_at_cinfi {f : ι → α → δ'} (bdd : ∀ᶠ y in 𝓝[s] x, bdd_below (range $ λ i, f i y)) (h : ∀ i, upper_semicontinuous_within_at (f i) s x) : upper_semicontinuous_within_at (λ x', ⨅ i, f i x') s x := @lower_semicontinuous_within_at_csupr α _ x s ι δ'ᵒᵈ _ f bdd h lemma upper_semicontinuous_within_at_infi {f : ι → α → δ} (h : ∀ i, upper_semicontinuous_within_at (f i) s x) : upper_semicontinuous_within_at (λ x', ⨅ i, f i x') s x := @lower_semicontinuous_within_at_supr α _ x s ι δᵒᵈ _ f h lemma upper_semicontinuous_within_at_binfi {p : ι → Prop} {f : Π i (h : p i), α → δ} (h : ∀ i hi, upper_semicontinuous_within_at (f i hi) s x) : upper_semicontinuous_within_at (λ x', ⨅ i hi, f i hi x') s x := upper_semicontinuous_within_at_infi $ λ i, upper_semicontinuous_within_at_infi $ λ hi, h i hi lemma upper_semicontinuous_at_cinfi {f : ι → α → δ'} (bdd : ∀ᶠ y in 𝓝 x, bdd_below (range $ λ i, f i y)) (h : ∀ i, upper_semicontinuous_at (f i) x) : upper_semicontinuous_at (λ x', ⨅ i, f i x') x := @lower_semicontinuous_at_csupr α _ x ι δ'ᵒᵈ _ f bdd h lemma upper_semicontinuous_at_infi {f : ι → α → δ} (h : ∀ i, upper_semicontinuous_at (f i) x) : upper_semicontinuous_at (λ x', ⨅ i, f i x') x := @lower_semicontinuous_at_supr α _ x ι δᵒᵈ _ f h lemma upper_semicontinuous_at_binfi {p : ι → Prop} {f : Π i (h : p i), α → δ} (h : ∀ i hi, upper_semicontinuous_at (f i hi) x) : upper_semicontinuous_at (λ x', ⨅ i hi, f i hi x') x := upper_semicontinuous_at_infi $ λ i, upper_semicontinuous_at_infi $ λ hi, h i hi lemma upper_semicontinuous_on_cinfi {f : ι → α → δ'} (bdd : ∀ x ∈ s, bdd_below (range $ λ i, f i x)) (h : ∀ i, upper_semicontinuous_on (f i) s) : upper_semicontinuous_on (λ x', ⨅ i, f i x') s := λ x hx, upper_semicontinuous_within_at_cinfi (eventually_nhds_within_of_forall bdd) (λ i, h i x hx) lemma upper_semicontinuous_on_infi {f : ι → α → δ} (h : ∀ i, upper_semicontinuous_on (f i) s) : upper_semicontinuous_on (λ x', ⨅ i, f i x') s := λ x hx, upper_semicontinuous_within_at_infi (λ i, h i x hx) lemma upper_semicontinuous_on_binfi {p : ι → Prop} {f : Π i (h : p i), α → δ} (h : ∀ i hi, upper_semicontinuous_on (f i hi) s) : upper_semicontinuous_on (λ x', ⨅ i hi, f i hi x') s := upper_semicontinuous_on_infi $ λ i, upper_semicontinuous_on_infi $ λ hi, h i hi lemma upper_semicontinuous_cinfi {f : ι → α → δ'} (bdd : ∀ x, bdd_below (range $ λ i, f i x)) (h : ∀ i, upper_semicontinuous (f i)) : upper_semicontinuous (λ x', ⨅ i, f i x') := λ x, upper_semicontinuous_at_cinfi (eventually_of_forall bdd) (λ i, h i x) lemma upper_semicontinuous_infi {f : ι → α → δ} (h : ∀ i, upper_semicontinuous (f i)) : upper_semicontinuous (λ x', ⨅ i, f i x') := λ x, upper_semicontinuous_at_infi (λ i, h i x) lemma upper_semicontinuous_binfi {p : ι → Prop} {f : Π i (h : p i), α → δ} (h : ∀ i hi, upper_semicontinuous (f i hi)) : upper_semicontinuous (λ x', ⨅ i hi, f i hi x') := upper_semicontinuous_infi $ λ i, upper_semicontinuous_infi $ λ hi, h i hi end section variables {γ : Type*} [linear_order γ] [topological_space γ] [order_topology γ] lemma continuous_within_at_iff_lower_upper_semicontinuous_within_at {f : α → γ} : continuous_within_at f s x ↔ lower_semicontinuous_within_at f s x ∧ upper_semicontinuous_within_at f s x:= begin refine ⟨λ h, ⟨h.lower_semicontinuous_within_at, h.upper_semicontinuous_within_at⟩, _⟩, rintros ⟨h₁, h₂⟩, assume v hv, simp only [filter.mem_map], by_cases Hl : ∃ l, l < f x, { rcases exists_Ioc_subset_of_mem_nhds hv Hl with ⟨l, lfx, hl⟩, by_cases Hu : ∃ u, f x < u, { rcases exists_Ico_subset_of_mem_nhds hv Hu with ⟨u, fxu, hu⟩, filter_upwards [h₁ l lfx, h₂ u fxu] with a lfa fau, cases le_or_gt (f a) (f x) with h h, { exact hl ⟨lfa, h⟩ }, { exact hu ⟨le_of_lt h, fau⟩ } }, { simp only [not_exists, not_lt] at Hu, filter_upwards [h₁ l lfx] with a lfa using hl ⟨lfa, Hu (f a)⟩, }, }, { simp only [not_exists, not_lt] at Hl, by_cases Hu : ∃ u, f x < u, { rcases exists_Ico_subset_of_mem_nhds hv Hu with ⟨u, fxu, hu⟩, filter_upwards [h₂ u fxu] with a lfa, apply hu, exact ⟨Hl (f a), lfa⟩ }, { simp only [not_exists, not_lt] at Hu, apply filter.eventually_of_forall, assume a, have : f a = f x := le_antisymm (Hu _) (Hl _), rw this, exact mem_of_mem_nhds hv } } end lemma continuous_at_iff_lower_upper_semicontinuous_at {f : α → γ} : continuous_at f x ↔ (lower_semicontinuous_at f x ∧ upper_semicontinuous_at f x) := by simp_rw [← continuous_within_at_univ, ← lower_semicontinuous_within_at_univ_iff, ← upper_semicontinuous_within_at_univ_iff, continuous_within_at_iff_lower_upper_semicontinuous_within_at] lemma continuous_on_iff_lower_upper_semicontinuous_on {f : α → γ} : continuous_on f s ↔ (lower_semicontinuous_on f s ∧ upper_semicontinuous_on f s) := begin simp only [continuous_on, continuous_within_at_iff_lower_upper_semicontinuous_within_at], exact ⟨λ H, ⟨λ x hx, (H x hx).1, λ x hx, (H x hx).2⟩, λ H x hx, ⟨H.1 x hx, H.2 x hx⟩⟩ end lemma continuous_iff_lower_upper_semicontinuous {f : α → γ} : continuous f ↔ (lower_semicontinuous f ∧ upper_semicontinuous f) := by simp_rw [continuous_iff_continuous_on_univ, continuous_on_iff_lower_upper_semicontinuous_on, lower_semicontinuous_on_univ_iff, upper_semicontinuous_on_univ_iff] end
59d5ede90cd69be2cb0266e0497c5038620ff4e3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/string_imp.lean
9c07cef2b5e4b27d202b0b25a526cefe926cc1f1
[ "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
340
lean
#eval ("abc" ++ "cde").length #eval ("abcd".mkIterator.nextn 2).remainingToString #eval ("abcd".mkIterator.nextn 10).remainingToString #eval "αβ".length #eval "αβcc".mkIterator.pos #eval "αβcc".mkIterator.next.pos #eval "αβcc".mkIterator.next.next.pos #eval "αβcc".mkIterator.next.setCurr 'a' #eval "αβcd".mkIterator.toEnd.pos
c13fc733ede7f3af0b7f3a51153ead6ba39626ef
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/data/set.lean
2909c49a094aab5d8dd6b6a1cf03c78bec68ff0a
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
2,273
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.interactive universes u v def set (α : Type u) := α → Prop def set_of {α : Type u} (p : α → Prop) : set α := p namespace set variables {α : Type u} {β : Type v} protected def mem (a : α) (s : set α) := s a instance : has_mem α (set α) := ⟨set.mem⟩ protected def subset (s₁ s₂ : set α) := ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂ instance : has_subset (set α) := ⟨set.subset⟩ protected def sep (p : α → Prop) (s : set α) : set α := {a | a ∈ s ∧ p a} instance : has_sep α (set α) := ⟨set.sep⟩ instance : has_emptyc (set α) := ⟨λ a, false⟩ def univ : set α := λ a, true protected def insert (a : α) (s : set α) : set α := {b | b = a ∨ b ∈ s} instance : has_insert α (set α) := ⟨set.insert⟩ protected def union (s₁ s₂ : set α) : set α := {a | a ∈ s₁ ∨ a ∈ s₂} instance : has_union (set α) := ⟨set.union⟩ protected def inter (s₁ s₂ : set α) : set α := {a | a ∈ s₁ ∧ a ∈ s₂} instance : has_inter (set α) := ⟨set.inter⟩ def compl (s : set α) : set α := {a | a ∉ s} instance : has_neg (set α) := ⟨compl⟩ protected def diff (s t : set α) : set α := {a ∈ s | a ∉ t} instance : has_sdiff (set α) := ⟨set.diff⟩ def powerset (s : set α) : set (set α) := {t | t ⊆ s} prefix `𝒫`:100 := powerset def Union (s : set (set α)) : set α := {t | ∃a ∈ s, t ∈ a} prefix `⋃`:100 := Union def image (f : α → β) (s : set α) : set β := {b | ∃ a, a ∈ s ∧ f a = b} instance : functor set := {map := @set.image, id_map := begin intros _ s, apply funext, intro b, dsimp [image, set_of], exact propext ⟨λ ⟨b', ⟨_, _⟩⟩, ‹b' = b› ▸ ‹s b'›, λ _, ⟨b, ⟨‹s b›, rfl⟩⟩⟩, end, map_comp := begin intros, apply funext, intro c, dsimp [image, set_of], exact propext ⟨λ ⟨a, ⟨h₁, h₂⟩⟩, ⟨g a, ⟨⟨a, ⟨h₁, rfl⟩⟩, h₂⟩⟩, λ ⟨b, ⟨⟨a, ⟨h₁, h₂⟩⟩, h₃⟩⟩, ⟨a, ⟨h₁, h₂.symm ▸ h₃⟩⟩⟩ end} end set
bba0d5642de19cc8907337f40b221e5c585d95ce
94d8c57c0a90adc01592a2509d65a360540671a9
/xenalib/M1Fstuff.lean
a60d88d412b0aa675202292cb777c84d3c10a96f
[]
no_license
TudorTitan/xena
ee58125263b84ca8787ea46778e7b4838c7b3057
389b9c40c43b26139722c88763f4d04d85467e0f
refs/heads/master
1,628,408,454,654
1,510,265,443,000
1,510,265,443,000
110,169,835
0
0
null
1,510,264,043,000
1,510,264,043,000
null
UTF-8
Lean
false
false
4,677
lean
import analysis.real init.classical tactic.norm_num namespace M1F theorem floor_real_exists : ∀ (x : ℝ), ∃ (n : ℤ), ↑n ≤ x ∧ x < n+1 := begin intro x, have H : ∃ (q : ℚ), x < ↑q ∧ ↑q < x + 1, exact @exists_rat_btwn x (x+1) (by simp [zero_lt_one]), cases H with q Hq, cases classical.em (x < rat.floor q) with Hb Hs, exact ⟨rat.floor q - 1, begin split, simp [rat.floor_le q,Hq.right], suffices H7 : (↑q:real) ≤ x+1, exact calc (↑(rat.floor q):ℝ) = (↑((rat.floor q):ℚ):ℝ) : by simp ... ≤ (↑q:ℝ) : rat.cast_le.mpr (rat.floor_le q) ... ≤ x+1 : H7, exact le_of_lt Hq.right, simp, rw [←add_assoc], simp [Hb] end ⟩, exact ⟨rat.floor q, begin split, { have H : (x < ↑(rat.floor q)) ∨ (x ≥ ↑(rat.floor q)), exact lt_or_ge x ↑(rat.floor q), cases H with F T, exact false.elim (Hs F), exact T }, { clear Hs, have H1 : x < ↑q, { exact Hq.left }, clear Hq, -- insanity starts here suffices H2 : q < ↑((rat.floor q)+(1:ℤ)), have H3 : ¬ (rat.floor q + 1 ≤ rat.floor q), intro H4, suffices H5 : rat.floor q < rat.floor q + 1, exact (lt_iff_not_ge (rat.floor q) ((rat.floor q)+1)).mp H5 H4, -- exact (lt_iff_not_ge q (((rat.floor q) + 1):int):rat).mpr, simp, tactic.swap, apply (lt_iff_not_ge q _).mpr, intro H2, have H3 : (rat.floor q) + 1 ≤ rat.floor q, exact rat.le_floor.mpr H2, have H4: (1:ℤ) > 0, exact int.one_pos, suffices H5 : (rat.floor q) + 1 > rat.floor q, exact (lt_iff_not_ge (rat.floor q) (rat.floor q + 1)).mp H5 H3, -- rw [add_comm (rat.floor q) (1:ℤ)], -- exact add_lt_add_left H4 (rat.floor q),add_zero (rat.floor q)], have H6 :rat.floor q + 0 < rat.floor q + 1, exact (add_lt_add_left H4 (rat.floor q)), exact @eq.subst _ (λ y, y < rat.floor q + 1) _ _ (add_zero (rat.floor q)) H6, clear H3, suffices H3 : of_rat q < ↑(rat.floor q) + 1, -- exact lt.trans H1 H3, exact calc x < ↑q : H1 ... = of_rat q : coe_rat_eq_of_rat q ... < ↑(rat.floor q) + 1 : H3, clear H1, rw [←coe_rat_eq_of_rat], have H : (↑(rat.floor q):ℝ) + (1:ℝ) = (((rat.floor q):ℚ):ℝ) + (((1:ℤ):ℚ):ℝ), simp, rw [H,←rat.cast_add,rat.cast_lt,←int.cast_add], exact H2 } end⟩ end /- lemma rat.zero_eq_int_zero (z : int) : ↑ z = (0:rat) → z = 0 := begin simp [rat.mk_eq_zero,nat.one_pos,rat.coe_int_eq_mk] end lemma rat.of_int_inj (z₁ z₂ : int) : (z₁ : rat) = (z₂ : rat) → z₁ = z₂ := begin intro H12, have H2 : ↑(z₁ - z₂) = (0:rat), exact calc ↑(z₁ - z₂) = (↑z₁ - ↑z₂ : ℚ) : by simp -- (rat.cast_sub z₁ z₂) ... = (↑ z₂ - ↑ z₂:ℚ) : by rw H12 ... = (0 : rat) : by simp, have H3 : z₁ - z₂ = 0, exact rat.zero_eq_int_zero (z₁ -z₂) H2, clear H12 H2, exact sub_eq_zero.mp H3 end -/ #print mul_inv_self lemma rational_half_not_an_integer : ¬ (∃ y : ℤ, 1/2 = (y:rat)) := begin apply not_exists.2, rw [one_div_eq_inv], assume x:ℤ, intro H, have H6 : ((1:ℤ):ℚ)=((2:ℤ):ℚ)*x, exact calc ((1:ℤ):ℚ) = (1:ℚ) : by simp ... = (2:ℚ)* 2⁻¹ : eq.symm (mul_inv_cancel (by norm_num)) ... = (2*x) : by rw[H], clear H, rw [←int.cast_mul,int.cast_inj] at H6, have H : (1:ℤ) = 0, exact calc (1:ℤ) = 1 % 2 : eq.symm (int.mod_eq_of_lt (by norm_num) (by norm_num)) ... = (2*x) % 2 : eq.symm (by rw [←H6]) ... = 0 : by simp, revert H, norm_num, end -- set_option pp.all true lemma real_half_not_an_integer : ¬ (∃ y : ℤ, ((1/2):ℝ) = (y:ℝ)) := begin assume H_real : (∃ y : ℤ, ((1/2):ℝ) = (y:ℝ)), cases H_real with a Ha, suffices H2 : ((1:ℤ):ℝ) = ((2:ℤ):ℝ)*((a:ℤ):ℝ), rw [←int.cast_mul,int.cast_inj] at H2, have H8 : (2*a) % 2 = 0, simp [@int.add_mul_mod_self 0], have H9 : (1:int) % 2 = 0, apply @eq.subst ℤ (λ t, t%2 =0) _ _ (eq.symm H2) H8, have H10 : (1:int) % 2 ≠ 0, exact dec_trivial, contradiction, have H20: (2:ℝ) ≠ 0, {norm_num}, have H1 : (↑a:ℝ) * 2 = 1, exact mul_eq_of_eq_div (a:ℝ) 1 H20 (eq.symm Ha), have H2 : 1 = 2 * (↑a:ℝ), rw [mul_comm] at H1, exact eq.symm (H1), have H3 : (1:ℝ) = ((1:ℤ):ℝ), by simp, have H4 : (2:ℝ) = ((2:ℤ):ℝ), by simp, rwa [←H3,←H4], end definition is_irrational (x : ℝ) := ¬ (∃ (q : ℚ), (q:ℝ) = x) end M1F
d699dbdb366af92e852f8d409410d3b7cf2ee553
7565ffb53cc64430691ce89265da0f944ee43051
/hott/homotopy/sphere2.hlean
94a8f90518f238e894e6e90bc77b6702962f42aa
[ "Apache-2.0" ]
permissive
EgbertRijke/lean2
cacddba3d150f8b38688e044960a208bf851f90e
519dcee739fbca5a4ab77d66db7652097b4604cd
refs/heads/master
1,606,936,954,854
1,498,836,083,000
1,498,910,882,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,187
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Calculating homotopy groups of spheres. In this file we calculate π₂(S²) = Z πₙ(S²) = πₙ(S³) for n > 2 πₙ(Sⁿ) = Z for n > 0 π₂(S³) = Z -/ import .homotopy_group .freudenthal open eq group algebra is_equiv equiv fin prod chain_complex pointed fiber nat is_trunc trunc_index sphere.ops trunc is_conn susp namespace sphere /- Corollaries of the complex hopf fibration combined with the LES of homotopy groups -/ open sphere sphere.ops int circle hopf definition π2S2 : πg[1+1] (S* 2) ≃g gℤ := begin refine _ ⬝g fundamental_group_of_circle, refine _ ⬝g homotopy_group_isomorphism_of_pequiv _ pfiber_complex_phopf, fapply isomorphism_of_equiv, { fapply equiv.mk, { exact cc_to_fn (LES_of_homotopy_groups complex_phopf) (1, 2)}, { refine LES_is_equiv_of_trivial complex_phopf 1 2 _ _, { have H : 1 ≤[ℕ] 2, from !one_le_succ, apply trivial_homotopy_group_of_is_conn, exact H, rexact is_conn_psphere 3 }, { refine tr_rev (λx, is_contr (ptrunctype._trans_of_to_pType x)) (LES_of_homotopy_groups_1 complex_phopf 2) _, apply trivial_homotopy_group_of_is_conn, apply le.refl, rexact is_conn_psphere 3 }}}, { exact homomorphism.struct (homomorphism_LES_of_homotopy_groups_fun _ (0, 2))} end open circle definition πnS3_eq_πnS2 (n : ℕ) : πg[n+2 +1] (S* 3) ≃g πg[n+2 +1] (S* 2) := begin fapply isomorphism_of_equiv, { fapply equiv.mk, { exact cc_to_fn (LES_of_homotopy_groups complex_phopf) (n+3, 0)}, { have H : is_trunc 1 (pfiber complex_phopf), from @(is_trunc_equiv_closed_rev _ pfiber_complex_phopf) is_trunc_circle, refine LES_is_equiv_of_trivial complex_phopf (n+3) 0 _ _, { have H2 : 1 ≤[ℕ] n + 1, from !one_le_succ, exact @trivial_ghomotopy_group_of_is_trunc _ _ _ H H2 }, { refine tr_rev (λx, is_contr (ptrunctype._trans_of_to_pType x)) (LES_of_homotopy_groups_2 complex_phopf _) _, have H2 : 1 ≤[ℕ] n + 2, from !one_le_succ, apply trivial_ghomotopy_group_of_is_trunc _ _ _ H2 }}}, { exact homomorphism.struct (homomorphism_LES_of_homotopy_groups_fun _ (n+2, 0))} end definition sphere_stability_pequiv (k n : ℕ) (H : k + 2 ≤ 2 * n) : π[k + 1] (S* (n+1)) ≃* π[k] (S* n) := begin rewrite [+ psphere_eq_iterate_susp], exact iterate_susp_stability_pequiv empty H end definition stability_isomorphism (k n : ℕ) (H : k + 3 ≤ 2 * n) : πg[k+1 +1] (S* (n+1)) ≃g πg[k+1] (S* n) := begin rewrite [+ psphere_eq_iterate_susp], exact iterate_susp_stability_isomorphism empty H end open int circle hopf definition πnSn (n : ℕ) : πg[n+1] (S* (succ n)) ≃g gℤ := begin cases n with n IH, { exact fundamental_group_of_circle}, { induction n with n IH, { exact π2S2}, { refine _ ⬝g IH, apply stability_isomorphism, rexact add_mul_le_mul_add n 1 2}} end theorem not_is_trunc_sphere (n : ℕ) : ¬is_trunc n (S* (succ n)) := begin intro H, note H2 := trivial_ghomotopy_group_of_is_trunc (S* (succ n)) n n !le.refl, have H3 : is_contr ℤ, from is_trunc_equiv_closed _ (equiv_of_isomorphism (πnSn n)), have H4 : (0 : ℤ) ≠ (1 : ℤ), from dec_star, apply H4, apply is_prop.elim, end section open sphere_index definition not_is_trunc_sphere' (n : ℕ₋₁) : ¬is_trunc n (S (n.+1)) := begin cases n with n, { esimp [sphere.ops.S, sphere], intro H, have H2 : is_prop bool, from @(is_trunc_equiv_closed -1 sphere_equiv_bool) H, have H3 : bool.tt ≠ bool.ff, from dec_star, apply H3, apply is_prop.elim}, { intro H, apply not_is_trunc_sphere (add_one n), rewrite [▸*, trunc_index_of_nat_add_one, -add_one_succ, sphere_index_of_nat_add_one], exact H} end end definition π3S2 : πg[2+1] (S* 2) ≃g gℤ := (πnS3_eq_πnS2 0)⁻¹ᵍ ⬝g πnSn 2 end sphere
b0dee7e194e5809866231414aed040d6cb9d25b3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/qpf/multivariate/constructions/quot.lean
cf5d8c52d80c2caa070ad1470626ec69d7de1bba
[]
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
2,817
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.qpf.multivariate.basic import Mathlib.PostPort universes u namespace Mathlib /-! # The quotient of QPF is itself a QPF The quotients are here defined using a surjective function and its right inverse. They are very similar to the `abs` and `repr` functions found in the definition of `mvqpf` -/ namespace mvqpf /-- If `F` is a QPF then `G` is a QPF as well. Can be used to construct `mvqpf` instances by transporting them across surjective functions -/ def quotient_qpf {n : ℕ} {F : typevec n → Type u} [mvfunctor F] [q : mvqpf F] {G : typevec n → Type u} [mvfunctor G] {FG_abs : {α : typevec n} → F α → G α} {FG_repr : {α : typevec n} → G α → F α} (FG_abs_repr : ∀ {α : typevec n} (x : G α), FG_abs (FG_repr x) = x) (FG_abs_map : ∀ {α β : typevec n} (f : typevec.arrow α β) (x : F α), FG_abs (mvfunctor.map f x) = mvfunctor.map f (FG_abs x)) : mvqpf G := mk (P F) (fun (α : typevec n) (p : mvpfunctor.obj (P F) α) => FG_abs (abs p)) (fun (α : typevec n) (x : G α) => repr (FG_repr x)) sorry sorry /-- Functorial quotient type -/ def quot1 {n : ℕ} {F : typevec n → Type u} (R : {α : typevec n} → F α → F α → Prop) (α : typevec n) := Quot R protected instance quot1.inhabited {n : ℕ} {F : typevec n → Type u} (R : {α : typevec n} → F α → F α → Prop) {α : typevec n} [Inhabited (F α)] : Inhabited (quot1 R α) := { default := Quot.mk R Inhabited.default } /-- `map` of the `quot1` functor -/ def quot1.map {n : ℕ} {F : typevec n → Type u} (R : {α : typevec n} → F α → F α → Prop) [mvfunctor F] (Hfunc : ∀ {α β : typevec n} (a b : F α) (f : typevec.arrow α β), R a b → R (mvfunctor.map f a) (mvfunctor.map f b)) {α : typevec n} {β : typevec n} (f : typevec.arrow α β) : quot1 R α → quot1 R β := Quot.lift (fun (x : F α) => Quot.mk R (mvfunctor.map f x)) sorry /-- `mvfunctor` instance for `quot1` with well-behaved `R` -/ def quot1.mvfunctor {n : ℕ} {F : typevec n → Type u} (R : {α : typevec n} → F α → F α → Prop) [mvfunctor F] (Hfunc : ∀ {α β : typevec n} (a b : F α) (f : typevec.arrow α β), R a b → R (mvfunctor.map f a) (mvfunctor.map f b)) : mvfunctor (quot1 R) := mvfunctor.mk (quot1.map R Hfunc) /-- `quot1` is a qpf -/ def rel_quot {n : ℕ} {F : typevec n → Type u} (R : {α : typevec n} → F α → F α → Prop) [mvfunctor F] [q : mvqpf F] (Hfunc : ∀ {α β : typevec n} (a b : F α) (f : typevec.arrow α β), R a b → R (mvfunctor.map f a) (mvfunctor.map f b)) : mvqpf (quot1 R) := quotient_qpf sorry sorry
fd525c6630a803232754c1b260e2c525e49358a3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/filter/countable_Inter.lean
b3bf7a216a60973d129a2c9016caacea17210f59
[ "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
3,987
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury G. Kudryashov -/ import order.filter.basic import data.set.countable /-! # Filters with countable intersection property In this file we define `countable_Inter_filter` to be the class of filters with the following property: for any countable collection of sets `s ∈ l` their intersection belongs to `l` as well. Two main examples are the `residual` filter defined in `topology.metric_space.baire` and the `measure.ae` filter defined in `measure_theory.measure_space`. -/ open set filter open_locale filter variables {ι α : Type*} /-- A filter `l` has the countable intersection property if for any countable collection of sets `s ∈ l` their intersection belongs to `l` as well. -/ class countable_Inter_filter (l : filter α) : Prop := (countable_sInter_mem_sets' : ∀ {S : set (set α)} (hSc : countable S) (hS : ∀ s ∈ S, s ∈ l), ⋂₀ S ∈ l) variables {l : filter α} [countable_Inter_filter l] lemma countable_sInter_mem_sets {S : set (set α)} (hSc : countable S) : ⋂₀ S ∈ l ↔ ∀ s ∈ S, s ∈ l := ⟨λ hS s hs, mem_sets_of_superset hS (sInter_subset_of_mem hs), countable_Inter_filter.countable_sInter_mem_sets' hSc⟩ lemma countable_Inter_mem_sets [encodable ι] {s : ι → set α} : (⋂ i, s i) ∈ l ↔ ∀ i, s i ∈ l := sInter_range s ▸ (countable_sInter_mem_sets (countable_range _)).trans forall_range_iff lemma countable_bInter_mem_sets {S : set ι} (hS : countable S) {s : Π i ∈ S, set α} : (⋂ i ∈ S, s i ‹_›) ∈ l ↔ ∀ i ∈ S, s i ‹_› ∈ l := begin rw [bInter_eq_Inter], haveI := hS.to_encodable, exact countable_Inter_mem_sets.trans subtype.forall end lemma eventually_countable_forall [encodable ι] {p : α → ι → Prop} : (∀ᶠ x in l, ∀ i, p x i) ↔ ∀ i, ∀ᶠ x in l, p x i := by simpa only [filter.eventually, set_of_forall] using @countable_Inter_mem_sets _ _ l _ _ (λ i, {x | p x i}) lemma eventually_countable_ball {S : set ι} (hS : countable S) {p : Π (x : α) (i ∈ S), Prop} : (∀ᶠ x in l, ∀ i ∈ S, p x i ‹_›) ↔ ∀ i ∈ S, ∀ᶠ x in l, p x i ‹_› := by simpa only [filter.eventually, set_of_forall] using @countable_bInter_mem_sets _ _ l _ _ hS (λ i hi, {x | p x i hi}) instance countable_Inter_filter_principal (s : set α) : countable_Inter_filter (𝓟 s) := ⟨λ S hSc hS, subset_sInter hS⟩ instance countable_Inter_filter_bot : countable_Inter_filter (⊥ : filter α) := by { rw ← principal_empty, apply countable_Inter_filter_principal } instance countable_Inter_filter_top : countable_Inter_filter (⊤ : filter α) := by { rw ← principal_univ, apply countable_Inter_filter_principal } /-- Infimum of two `countable_Inter_filter`s is a `countable_Inter_filter`. This is useful, e.g., to automatically get an instance for `residual α ⊓ 𝓟 s`. -/ instance countable_Inter_filter_inf (l₁ l₂ : filter α) [countable_Inter_filter l₁] [countable_Inter_filter l₂] : countable_Inter_filter (l₁ ⊓ l₂) := begin refine ⟨λ S hSc hS, _⟩, choose s hs t ht hst using hS, replace hs : (⋂ i ∈ S, s i ‹_›) ∈ l₁ := (countable_bInter_mem_sets hSc).2 hs, replace ht : (⋂ i ∈ S, t i ‹_›) ∈ l₂ := (countable_bInter_mem_sets hSc).2 ht, refine mem_sets_of_superset (inter_mem_inf_sets hs ht) (subset_sInter $ λ i hi, _), refine subset.trans (inter_subset_inter _ _) (hst i hi); exact Inter_subset_of_subset i (Inter_subset _ _) end /-- Supremum of two `countable_Inter_filter`s is a `countable_Inter_filter`. -/ instance countable_Inter_filter_sup (l₁ l₂ : filter α) [countable_Inter_filter l₁] [countable_Inter_filter l₂] : countable_Inter_filter (l₁ ⊔ l₂) := begin refine ⟨λ S hSc hS, ⟨_, _⟩⟩; refine (countable_sInter_mem_sets hSc).2 (λ s hs, _), exacts [(hS s hs).1, (hS s hs).2] end
d31012613d61cda660040ef2e06628846f0afe53
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/l_series.lean
b010d326c6b85407557a5f9d87995d368eaedaa9
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,841
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import analysis.p_series import number_theory.arithmetic_function import topology.algebra.infinite_sum /-! # L-series Given an arithmetic function, we define the corresponding L-series. ## Main Definitions * `nat.arithmetic_function.l_series` is the `l_series` with a given arithmetic function as its coefficients. This is not the analytic continuation, just the infinite series. * `nat.arithmetic_function.l_series_summable` indicates that the `l_series` converges at a given point. ## Main Results * `nat.arithmetic_function.l_series_summable_of_bounded_of_one_lt_re`: the `l_series` of a bounded arithmetic function converges when `1 < z.re`. * `nat.arithmetic_function.zeta_l_series_summable_iff_one_lt_re`: the `l_series` of `ζ` (whose analytic continuation is the Riemann ζ) converges iff `1 < z.re`. -/ noncomputable theory open_locale big_operators namespace nat namespace arithmetic_function /-- The L-series of an `arithmetic_function`. -/ def l_series (f : arithmetic_function ℂ) (z : ℂ) : ℂ := ∑'n, (f n) / (n ^ z) /-- `f.l_series_summable z` indicates that the L-series of `f` converges at `z`. -/ def l_series_summable (f : arithmetic_function ℂ) (z : ℂ) : Prop := summable (λ n, (f n) / (n ^ z)) lemma l_series_eq_zero_of_not_l_series_summable (f : arithmetic_function ℂ) (z : ℂ) : ¬ f.l_series_summable z → f.l_series z = 0 := tsum_eq_zero_of_not_summable @[simp] lemma l_series_summable_zero {z : ℂ} : l_series_summable 0 z := by simp [l_series_summable, summable_zero] theorem l_series_summable_of_bounded_of_one_lt_real {f : arithmetic_function ℂ} {m : ℝ} (h : ∀ (n : ℕ), complex.abs (f n) ≤ m) {z : ℝ} (hz : 1 < z) : f.l_series_summable z := begin by_cases h0 : m = 0, { subst h0, have hf : f = 0 := arithmetic_function.ext (λ n, complex.abs_eq_zero.1 (le_antisymm (h n) (complex.abs_nonneg _))), simp [hf] }, refine summable_of_norm_bounded (λ (n : ℕ), m / (n ^ z)) _ _, { simp_rw [div_eq_mul_inv], exact (summable_mul_left_iff h0).1 (real.summable_nat_rpow_inv.2 hz) }, { intro n, have hm : 0 ≤ m := le_trans (complex.abs_nonneg _) (h 0), cases n, { simp [hm, real.zero_rpow (ne_of_gt (lt_trans real.zero_lt_one hz))] }, simp only [complex.abs_div, complex.norm_eq_abs], apply div_le_div hm (h _) (real.rpow_pos_of_pos (nat.cast_pos.2 n.succ_pos) _) (le_of_eq _), rw [complex.abs_cpow_real, complex.abs_cast_nat] } end theorem l_series_summable_iff_of_re_eq_re {f : arithmetic_function ℂ} {w z : ℂ} (h : w.re = z.re) : f.l_series_summable w ↔ f.l_series_summable z := begin suffices h : ∀ n : ℕ, complex.abs (f n) / complex.abs (↑n ^ w) = complex.abs (f n) / complex.abs (↑n ^ z), { simp [l_series_summable, ← summable_norm_iff, h, complex.norm_eq_abs] }, intro n, cases n, { simp }, apply congr rfl, have h0 : (n.succ : ℂ) ≠ 0, { rw [ne.def, nat.cast_eq_zero], apply n.succ_ne_zero }, rw [complex.cpow_def, complex.cpow_def, if_neg h0, if_neg h0, complex.abs_exp_eq_iff_re_eq], simp only [h, complex.mul_re, mul_eq_mul_left_iff, sub_right_inj], right, rw [complex.log_im, ← complex.of_real_nat_cast], exact complex.arg_of_real_of_nonneg (le_of_lt (cast_pos.2 n.succ_pos)), end theorem l_series_summable_of_bounded_of_one_lt_re {f : arithmetic_function ℂ} {m : ℝ} (h : ∀ (n : ℕ), complex.abs (f n) ≤ m) {z : ℂ} (hz : 1 < z.re) : f.l_series_summable z := begin rw ← l_series_summable_iff_of_re_eq_re (complex.of_real_re z.re), apply l_series_summable_of_bounded_of_one_lt_real h, exact hz, end open_locale arithmetic_function theorem zeta_l_series_summable_iff_one_lt_re {z : ℂ} : l_series_summable ζ z ↔ 1 < z.re := begin rw [← l_series_summable_iff_of_re_eq_re (complex.of_real_re z.re), l_series_summable, ← summable_norm_iff, ← real.summable_one_div_nat_rpow, iff_iff_eq], by_cases h0 : z.re = 0, { rw [h0, ← summable_nat_add_iff 1], swap, { apply_instance }, apply congr rfl, ext n, simp [n.succ_ne_zero] }, { apply congr rfl, ext n, cases n, { simp [h0] }, simp only [n.succ_ne_zero, one_div, cast_one, nat_coe_apply, complex.abs_cpow_real, inv_inj, complex.abs_inv, if_false, zeta_apply, complex.norm_eq_abs, complex.abs_of_nat] } end @[simp] theorem l_series_add {f g : arithmetic_function ℂ} {z : ℂ} (hf : f.l_series_summable z) (hg : g.l_series_summable z) : (f + g).l_series z = f.l_series z + g.l_series z := begin simp only [l_series, add_apply], rw ← tsum_add hf hg, apply congr rfl (funext (λ n, _)), apply _root_.add_div, end end arithmetic_function end nat
79dd8ce440098f7e1b6c881305c044dce19b8d53
c9b68131de1dfe4e7f0ea5749b11e67a774bc839
/src/memory_aux.lean
cb9879a09c7c3149824f066746986e71ed0f3c79
[]
no_license
congge666/formal-proofs
2013f158f310abcfc07c156bb2a5113fb78f7831
b5f6964d0220c8f89668357f2c08e44861128fe3
refs/heads/master
1,691,374,567,671
1,632,704,604,000
1,632,706,366,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,783
lean
/- Interpretation of memory constraints. -/ import util noncomputable theory open_locale classical big_operators open_locale disable_subsingleton_simps /- General facts about polyomials -/ namespace polynomial_aux variables {F : Type*} [field F] [fintype F] variables {n : Type*} [fintype n] (a b : n → F) open finset polynomial def mprod := ((univ.val.map a).map (λ r, X - C r)).prod lemma nat_degree_mprod : (mprod a).nat_degree = fintype.card n := by rw [mprod, nat_degree_multiset_prod_X_sub_C _, multiset.card_map]; refl lemma eq_of_mprod_eq (h : mprod a = mprod b) : univ.val.map a = univ.val.map b := begin have : (mprod a).roots = (mprod b).roots := congr_arg _ h, rwa [mprod, mprod, multiset_prod_X_sub_C_roots, multiset_prod_X_sub_C_roots] at this end lemma prod_eq_mprod (z : F) : ∏ i : n, (z - a i) = (mprod a).eval z := by { simp [mprod], refl } theorem card_roots_le_or_all_eq [fintype F] : card (univ.filter (λ z : F, ∏ i, (z - a i) = ∏ i, (z - b i))) ≤ fintype.card n ∨ ∀ z, ∏ i, (z - a i) = ∏ i, (z - b i) := begin have h₀ : ∀ z, (∏ i, (z - a i)) - (∏ i, (z - b i)) = (mprod a - mprod b).eval z, { intro z, simp [mprod], refl }, by_cases h : mprod a - mprod b = 0, { right, intro z, rw [←sub_eq_zero, h₀, h, eval_zero] }, have : univ.filter (λ z : F, ∏ i, (z - a i) = ∏ i, (z - b i)) = (mprod a - mprod b).roots.to_finset, { ext z; simp [mem_roots h], rw [←sub_eq_zero, h₀, eval_sub] }, left, rw this, apply (multiset.to_finset_card_le _).trans, apply (card_roots' h).trans, apply (nat_degree_add (mprod a) _).trans, rw [nat_degree_neg, nat_degree_mprod, nat_degree_mprod, max_self] end def exceptional_set : finset F := if ∀ z, ∏ i, (z - a i) = ∏ i, (z - b i) then ∅ else univ.filter (λ z : F, ∏ i : n, (z - a i) = ∏ i, (z - b i)) theorem card_exceptional_set_le : card (exceptional_set a b) ≤ fintype.card n := begin by_cases h : (∀ z, ∏ i, (z - a i) = ∏ i, (z - b i)); simp [exceptional_set, h], exact (card_roots_le_or_all_eq a b).resolve_right h end theorem all_eq_of_not_mem_exceptional_set {z : F} (h₁ : z ∉ exceptional_set a b) (h₂ : ∏ i : n, (z - a i) = ∏ i, (z - b i)) : ∀ z, ∏ i, (z - a i) = ∏ i, (z - b i) := begin by_contradiction h, simp [exceptional_set, if_neg h] at h₁, contradiction end end polynomial_aux section variables {F : Type*} [field F] {n : ℕ} (a b : fin n → F) theorem prod_sub_eq_zero_iff (z : F) : ∏ i : fin n, (z - a i) = 0 ↔ ∃ j : fin n, z = a j := begin induction n with n ih, { simp, intros i _, exact fin.elim0 i }, rw [fin.prod_univ_cast_succ, mul_eq_zero, ih, fin.exists_fin_cast_succ], simp only [sub_eq_zero] end variable [fintype F] theorem exceptional_set_spec {z : F} (h₁ : z ∉ polynomial_aux.exceptional_set a b) (h₂ : ∏ i : fin n, (z - a i) = ∏ i, (z - b i)) : ∀ i, ∃ j, a i = b j := begin intro i, have : ∏ i' : fin n, (a i - a i') = 0, { rw prod_sub_eq_zero_iff, use i }, rw polynomial_aux.all_eq_of_not_mem_exceptional_set a b h₁ h₂ at this, rwa ←prod_sub_eq_zero_iff end theorem exceptional_set_spec' {z : F} (h₁ : z ∉ polynomial_aux.exceptional_set a b) (h₂ : ∏ i : fin n, (z - a i) = ∏ i, (z - b i)) : ∀ i, ∃ j, b i = a j := begin intro i, have : ∏ i' : fin n, (b i - b i') = 0, { rw prod_sub_eq_zero_iff, use i }, rw ←polynomial_aux.all_eq_of_not_mem_exceptional_set a b h₁ h₂ at this, rwa ←prod_sub_eq_zero_iff end end /- The constraints. Note: where the whitepaper assumes `n > 0`, we use `n + 1` instead. -/ section constraints variables {F : Type*} [field F] variables {n : ℕ} {a v a' v' p : fin (n + 1) → F} variables {alpha z : F} variable h_continuity : ∀ i : fin n, (a' i.succ - a' i.cast_succ) * (a' i.succ - a' i.cast_succ - 1) = 0 variable h_single_valued : ∀ i : fin n, (v' i.succ - v' i.cast_succ) * (a' i.succ - a' i.cast_succ - 1) = 0 variable h_initial : (z - (a' 0 + alpha * v' 0)) * p 0 = z - (a 0 + alpha * v 0) variable h_cumulative : ∀ i : fin n, (z - (a' i.succ + alpha * v' i.succ)) * p i.succ = (z - (a i.succ + alpha * v i.succ)) * p i.cast_succ variable h_final : p (fin.last n) = 1 /- See also `hprob₁`, `hprob₂`, and `char_lt` below. -/ def a'_step (a' : fin (n + 1) → F) (i : fin n) : ℕ := if a' i.succ = a' i.cast_succ then 0 else 1 lemma a'_step_of_eq (i : fin n) (h : a' i.succ = a' i.cast_succ) : a'_step a' i = 0 := by rw [a'_step, if_pos h] lemma a'_step_of_eq_add_one (i : fin n) (h : a' i.succ = a' i.cast_succ + 1) : a'_step a' i = 1 := by rw [a'_step, if_neg]; simp [h] def a'_nat_offset (a' : fin (n + 1) → F) (i : fin (n + 1)) : ℕ := ∑ j in fin.range i, (a'_step a') j @[simp] lemma a'_nat_offset_zero : a'_nat_offset a' 0 = 0 := fin.sum_range_zero _ @[simp] lemma a'_nat_offset_succ (i : fin n) : a'_nat_offset a' i.succ = a'_nat_offset a' i.cast_succ + a'_step a' i := by rw [a'_nat_offset, fin.sum_range_succ _ _, add_comm]; refl lemma monotone_a'_nat_offset : monotone (a'_nat_offset a') := by { intros i j ilej, apply finset.sum_mono_set, apply fin.range_subset.mpr ilej } lemma a'_nat_offset_le (i : fin (n + 1)) : a'_nat_offset a' i ≤ ↑i := begin apply fin.induction_on i; simp, intros i' ih, apply add_le_add ih _, by_cases h : a' i'.succ = a' i'.cast_succ; simp [a'_step, h] end lemma a'_nat_offset_le' (i : fin (n + 1)) : a'_nat_offset a' i ≤ n := le_trans (monotone_a'_nat_offset (fin.le_last i)) (a'_nat_offset_le _) section h_continuity include h_continuity lemma a'_succ_eq (i : fin n) : a' i.succ = a' i.cast_succ ∨ a' i.succ = a' i.cast_succ + 1 := begin cases (eq_zero_or_eq_zero_of_mul_eq_zero $ h_continuity i) with h h, { left, apply eq_of_sub_eq_zero h }, right, apply eq_of_sub_eq_zero, rw ←h, abel end lemma a'_succ_eq' (i : fin n) : a' i.succ = a' i.cast_succ + a'_step a' i := begin cases (a'_succ_eq h_continuity i) with h h, { simp [a'_step_of_eq _ h, h] }, simp [a'_step_of_eq_add_one _ h, h] end lemma a'_nat_offset_spec (i : fin (n + 1)) : a' i = a' 0 + a'_nat_offset a' i := begin apply fin.induction_on i; simp [a'_succ_eq' h_continuity], intros i' ih, rw [ih, add_assoc] end lemma nat_offset_eq (h_n_lt : n < ring_char F) {i j : fin (n + 1)} (h : a' i = a' j) : a'_nat_offset a' i = a'_nat_offset a' j := begin have : ↑i < ring_char F := lt_of_le_of_lt (nat.le_of_lt_succ i.property) h_n_lt, have : ↑j < ring_char F := lt_of_le_of_lt (nat.le_of_lt_succ j.property) h_n_lt, rw [a'_nat_offset_spec h_continuity i, a'_nat_offset_spec h_continuity j] at h, apply nat.cast_inj_of_lt_char _ _ (add_left_cancel h); { apply lt_of_le_of_lt (a'_nat_offset_le _), assumption } end lemma a'_continuous_aux (i : fin (n + 1)) : ∀ k ≤ a'_nat_offset a' i, ∃ j ≤ i, a'_nat_offset a' j = k := begin apply fin.induction_on i; simp, { use [0, le_refl _], simp }, intros i' ih k, cases (a'_succ_eq h_continuity i') with h h, { simp [a'_step_of_eq _ h, h], intro hk, rcases ih k hk with ⟨j, hj, hj'⟩, exact ⟨j, le_trans hj (le_of_lt (fin.cast_succ_lt_succ _)), hj'⟩ }, simp [a'_step_of_eq_add_one _ h, h], intro hk, cases (nat.of_le_succ hk) with hk' hk', { rcases ih k hk' with ⟨j, hj, hj'⟩, exact⟨j, le_trans hj (le_of_lt (fin.cast_succ_lt_succ _)), hj'⟩ }, refine ⟨i'.succ, le_refl _, _⟩, rw [hk', a'_nat_offset_succ, a'_step_of_eq_add_one _ h] end lemma a'_continuous (k : ℕ) (hk : k ≤ a'_nat_offset a' (fin.last n)) : ∃ j, a'_nat_offset a' j = k := begin rcases a'_continuous_aux h_continuity _ _ hk with ⟨j, _, hj⟩, exact ⟨j, hj⟩ end section single_valued include h_single_valued lemma a'_single_valued_aux {i : fin n} (h : a' i.succ = a' i.cast_succ) : v' i.succ = v' i.cast_succ := begin have := h_single_valued i, simp [h] at this, symmetry, exact eq_of_sub_eq_zero this end lemma a'_single_valued_aux' (h_n_lt : n < ring_char F) (i : fin (n + 1)) : ∀ j < i, a' i = a' j → v' i = v' j := begin apply i.induction_on, { intros j hj, exfalso, apply fin.not_lt_zero _ hj }, intros i' ih j hj a'eq, have hj' : j ≤ i'.cast_succ := fin.le_of_lt_succ hj, have a'eq2 : a' i'.succ = a' i'.cast_succ, { rw [a'eq, a'_nat_offset_spec h_continuity, a'_nat_offset_spec h_continuity i'.cast_succ], congr' 2, apply le_antisymm (monotone_a'_nat_offset $ fin.le_of_lt_succ hj), rw ←nat_offset_eq h_continuity h_n_lt a'eq, apply monotone_a'_nat_offset (le_of_lt $ fin.cast_succ_lt_succ _) }, rw [a'_single_valued_aux h_continuity h_single_valued a'eq2], cases (lt_or_eq_of_le hj') with h h, { exact ih j h (a'eq2.symm.trans a'eq) }, rw h end lemma a'_single_valued (h_n_lt : n < ring_char F) {i j : fin (n + 1)} : a' i = a' j → v' i = v' j := begin have : i < j ∨ i = j ∨ j < i := trichotomous i j, rcases this with h | rfl | h, { intro h', symmetry, exact a'_single_valued_aux' h_continuity h_single_valued h_n_lt _ _ h h'.symm }, { intro _, refl }, exact a'_single_valued_aux' h_continuity h_single_valued h_n_lt _ _ h end end single_valued end h_continuity section variable [fintype F] def bad_set_1 (a v a' v' : fin (n + 1) → F) : finset F := finset.univ.filter (λ alpha, ∃ i j, v i ≠ v' j ∧ a i + alpha * v i = a' j + alpha * v' j) theorem card_bad_set_1_le : (bad_set_1 a v a' v').card ≤ (n + 1) * (n + 1) := let f := λ p : fin (n + 1) × fin (n + 1), (a p.1 - a' p.2) / (v' p.2 - v p.1) in calc (bad_set_1 a v a' v').card ≤ (finset.image f finset.univ).card : begin apply finset.card_le_of_subset, intros alpha, simp [bad_set_1], intros i j hv ha, use [i, j], dsimp [f], have : v' j - v i ≠ 0, { intro h, apply hv, symmetry, apply eq_of_sub_eq_zero h }, rw [div_eq_iff this, mul_sub, sub_eq_iff_eq_add, sub_add_eq_add_sub, add_comm, ←ha, add_sub_cancel] end ... ≤ (finset.univ : finset (fin (n + 1) × fin (n + 1))).card : finset.card_image_le ... = fintype.card (fin (n + 1) × fin (n + 1)) : rfl ... = (n + 1) * (n + 1) : by simp theorem bad_set_1_spec (h : alpha ∉ bad_set_1 a v a' v') {i j : fin (n + 1)} (h' : a i + alpha * v i = a' j + alpha * v' j) : v i = v' j ∧ a i = a' j := begin simp [bad_set_1] at h, specialize h i j, have : v i = v' j := by_contradiction (λ h₀, h h₀ h'), split, { exact this }, rw this at h', exact add_right_cancel h' end def bad_set_2 (a v a' v' : fin (n + 1) → F) (alpha : F) : finset F := polynomial_aux.exceptional_set (λ i, a i + alpha * v i) (λ i, a' i + alpha * v' i) theorem card_bad_set_2_le : (bad_set_2 a v a' v' alpha).card ≤ n + 1 := by { transitivity, apply polynomial_aux.card_exceptional_set_le, simp } theorem bad_set_2_spec {z : F} (h₁ : z ∉ bad_set_2 a v a' v' alpha) (h₂ : ∏ i : fin (n + 1), (z - (a i + alpha * v i)) = ∏ i, (z - (a' i + alpha * v' i))) : ∀ i, ∃ j, a i + alpha * v i = a' j + alpha * v' j := exceptional_set_spec _ _ h₁ h₂ theorem bad_set_2_spec' {z : F} (h₁ : z ∉ bad_set_2 a v a' v' alpha) (h₂ : ∏ i : fin (n + 1), (z - (a i + alpha * v i)) = ∏ i, (z - (a' i + alpha * v' i))) : ∀ i, ∃ j, a' i + alpha * v' i = a j + alpha * v j := exceptional_set_spec' _ _ h₁ h₂ end section permutation include h_initial h_cumulative lemma permutation_aux (j : fin (n + 1)) : ∏ i in fin.range j.succ, (z - (a i + alpha * v i)) = (∏ i in fin.range j.succ, (z - (a' i + alpha * v' i))) * p j := begin apply fin.induction_on j, { rw [←fin.one_eq_succ_zero, fin.prod_range_one, fin.prod_range_one, h_initial] }, intros j ih, rw [fin.prod_range_succ, fin.prod_range_succ, ←fin.succ_cast_succ, ih, ←mul_assoc], conv { to_rhs, rw [mul_right_comm, h_cumulative, mul_right_comm] } end include h_final lemma permutation_prod_eq : ∏ i, (z - (a i + alpha * v i)) = ∏ i, (z - (a' i + alpha * v' i)) := by rw [←fin.range_last, ←fin.succ_last, permutation_aux h_initial h_cumulative, h_final, mul_one] end permutation /- Put it all together! -/ variable [fintype F] variable hprob₁ : alpha ∉ bad_set_1 a v a' v' variable hprob₂ : z ∉ bad_set_2 a v a' v' alpha include hprob₁ hprob₂ lemma permutation (h : ∏ (i : fin (n + 1)), (z - (a i + alpha * v i)) = ∏ (i : fin (n + 1)), (z - (a' i + alpha * v' i))) : ∀ i, ∃ j, v i = v' j ∧ a i = a' j := begin intro i, have : ∃ j, a i + alpha * v i = a' j + alpha * v' j := bad_set_2_spec hprob₂ h i, cases this with j hj, use j, show v i = v' j ∧ a i = a' j, from bad_set_1_spec hprob₁ hj end lemma permutation' (h : ∏ (i : fin (n + 1)), (z - (a i + alpha * v i)) = ∏ (i : fin (n + 1)), (z - (a' i + alpha * v' i))) : ∀ i, ∃ j, v' i = v j ∧ a' i = a j := begin intro i, have := bad_set_2_spec' hprob₂ h i, cases this with j hj, have := bad_set_1_spec hprob₁ hj.symm, use j, simp [this] end include h_continuity h_initial h_cumulative h_final lemma a_continuous : ∃ base : F, ∃ m : ℕ, (∀ i, ∃ k ≤ m, a i = base + k) ∧ (∀ k ≤ m, ∃ i, a i = base + k) := begin have h : ∏ (i : fin (n + 1)), (z - (a i + alpha * v i)) = ∏ (i : fin (n + 1)), (z - (a' i + alpha * v' i)) := permutation_prod_eq h_initial h_cumulative h_final, have perm := permutation hprob₁ hprob₂ h, use a' 0, use a'_nat_offset a' (fin.last n), split, { intro i, rcases perm i with ⟨j, veq, aeq⟩, use a'_nat_offset a' j, split, { apply monotone_a'_nat_offset, apply fin.le_last }, rw aeq, exact a'_nat_offset_spec h_continuity j }, have perm' := permutation' hprob₁ hprob₂ h, intros k kle, rcases a'_continuous h_continuity k kle with ⟨j, hj⟩, rcases perm' j with ⟨i, v'eq, a'eq⟩, use i, rw [←a'eq, ←hj], exact a'_nat_offset_spec h_continuity j end include h_single_valued lemma a_single_valued (h_char_lt : n < ring_char F) : ∀ i i', a i = a i' → v i = v i' := begin intros i i' aieq, have h : ∏ (i : fin (n + 1)), (z - (a i + alpha * v i)) = ∏ (i : fin (n + 1)), (z - (a' i + alpha * v' i)) := permutation_prod_eq h_initial h_cumulative h_final, have perm := permutation hprob₁ hprob₂ h, rcases perm i with ⟨j, veq, aeq⟩, rcases perm i' with ⟨j', veq', aeq'⟩, rw [veq, veq'], apply a'_single_valued h_continuity h_single_valued h_char_lt, rw [←aeq, ←aeq', aieq] end end constraints -- #lint
addb1e5cd55a3d6146dfa4ce1fac43f11baf3fe2
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Init/Core.lean
31c81513c6e590ce910b61041413631cb5715d88
[ "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
35,290
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude import Init.Prelude import Init.Notation universes u v w def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := fun b a => f a b /- The kernel definitional equality test (t =?= s) has special support for idDelta applications. It implements the following rules 1) (idDelta t) =?= t 2) t =?= (idDelta t) 3) (idDelta t) =?= s IF (unfoldOf t) =?= s 4) t =?= idDelta s IF t =?= (unfoldOf s) This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel. We use idDelta applications to address performance problems when Type checking theorems generated by the equation Compiler. -/ @[inline] def idDelta {α : Sort u} (a : α) : α := a /- Remark: thunks have an efficient implementation in the runtime. -/ structure Thunk (α : Type u) : Type u := (fn : Unit → α) attribute [extern "lean_mk_thunk"] Thunk.mk @[noinline, extern "lean_thunk_pure"] protected def Thunk.pure {α : Type u} (a : α) : Thunk α := ⟨fun _ => a⟩ @[noinline, extern "lean_thunk_get_own"] protected def Thunk.get {α : Type u} (x : @& Thunk α) : α := x.fn () @[noinline, extern "lean_thunk_map"] protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β := ⟨fun _ => f x.get⟩ @[noinline, extern "lean_thunk_bind"] protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨fun _ => (f x.get).get⟩ abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : Eq a b) (m : motive a) : motive b := Eq.ndrec m h structure Iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) infix:20 " <-> " => Iff infix:20 " ↔ " => Iff /- Eq basic support -/ theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ inductive Sum (α : Type u) (β : Type v) | inl (val : α) : Sum α β | inr (val : β) : Sum α β inductive PSum (α : Sort u) (β : Sort v) | inl (val : α) : PSum α β | inr (val : β) : PSum α β structure Sigma {α : Type u} (β : α → Type v) := mk :: (fst : α) (snd : β fst) attribute [unbox] Sigma structure PSigma {α : Sort u} (β : α → Sort v) := mk :: (fst : α) (snd : β fst) inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists p /- Auxiliary type used to compile `for x in xs` notation. -/ inductive ForInStep (α : Type u) | done : α → ForInStep α | yield : α → ForInStep α /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPRBC (α β σ : Type u) | «pure» : α → σ → DoResultPRBC α β σ | «return» : β → σ → DoResultPRBC α β σ | «break» : σ → DoResultPRBC α β σ | «continue» : σ → DoResultPRBC α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultPR (α β σ : Type u) | «pure» : α → σ → DoResultPR α β σ | «return» : β → σ → DoResultPR α β σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultBC (σ : Type u) | «break» : σ → DoResultBC σ | «continue» : σ → DoResultBC σ /- Auxiliary type used to compile `do` notation. -/ inductive DoResultSBC (α σ : Type u) | «pureReturn» : α → σ → DoResultSBC α σ | «break» : σ → DoResultSBC α σ | «continue» : σ → DoResultSBC α σ class HasEquiv (α : Sort u) := (Equiv : α → α → Prop) infix:50 " ≈ " => HasEquiv.Equiv class EmptyCollection (α : Type u) := (emptyCollection : α) /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u := pure :: (get : α) attribute [extern "lean_task_pure"] Task.pure attribute [extern "lean_task_get_own"] Task.get namespace Task /-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/ abbrev Priority := Nat def Priority.default : Priority := 0 -- see `LEAN_MAX_PRIO` def Priority.max : Priority := 8 /-- Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread. This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more non-dedicated workers than the number of cores to reduce context switches. -/ def Priority.dedicated : Priority := 9 @[noinline, extern "lean_task_spawn"] protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α := ⟨fn ()⟩ @[noinline, extern "lean_task_map"] protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β := ⟨f x.get⟩ @[noinline, extern "lean_task_bind"] protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β := ⟨(f x.get).get⟩ end Task /- Some type that is not a scalar value in our runtime. -/ structure NonScalar := (val : Nat) /- Some type that is not a scalar value in our runtime and is universe polymorphic. -/ inductive PNonScalar : Type u | mk (v : Nat) : PNonScalar theorem natAddZero (n : Nat) : n + 0 = n := rfl theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl /- Boolean operators -/ @[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool := !(a == b) infix:50 " != " => bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := fun hp => h₂ (h₁ hp) def trivial : True := ⟨⟩ theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := fun ha => h₂ (h₁ ha) theorem notFalse : ¬False := id -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl @[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β := h ▸ a @[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α := h ▸ b theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := h₁ ▸ h₂ theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : ∀ x, β x} (h : f = g) (a : α) : f a = g a := h ▸ rfl theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) infix:50 " ≠ " => Ne section Ne variable {α : Sort u} variables {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := fun h₁ => h (h₁.symm) theorem falseOfNe : a ≠ a → False := Ne.irrefl theorem neFalseOfSelf : p → p ≠ False := fun (hp : p) (h : p = False) => h ▸ hp theorem neTrueOfNot : ¬p → p ≠ True := fun (hnp : ¬p) (h : p = True) => have ¬True from h ▸ hnp this trivial theorem trueNeFalse : ¬True = False := neFalseOfSelf trivial end Ne section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : a ≅ b) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : motive a) : motive b := @HEq.rec α a (fun b _ => motive b) m β b h theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b := eqOfHEq h₁ ▸ h₂ theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b := HEq.ndrecOn h₁ h₂ theorem HEq.symm (h : a ≅ b) : b ≅ a := HEq.ndrecOn (motive := fun x => x ≅ a) h (HEq.refl a) theorem heqOfEq (h : a = a') : a ≅ a' := Eq.subst h (HEq.refl a) theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c := HEq.subst h₂ h₁ theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' := HEq.trans h₁ (heqOfEq h₂) theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := HEq.trans (heqOfEq h₁) h₂ def typeEqOfHEq (h : a ≅ b) : α = β := HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (Eq.refl α) end theorem eqRecHEq {α : Sort u} {φ : α → Sort v} : {a a' : α} → (h : a = a') → (p : φ a) → (Eq.recOn (motive := fun x _ => φ x) h p) ≅ p | a, _, rfl, p => HEq.refl p theorem heqOfEqRecEq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : a ≅ b := by subst h₁ apply heqOfEq exact h₂ done theorem castHEq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a | α, _, rfl, a => HEq.refl a variables {a b c d : Prop} theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (fun h => h) (fun h => h) theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (fun ha => Iff.mp h₂ (Iff.mp h₁ ha)) (fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.mpr h) (Iff.mp h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b := h₂ h₁.1 h₁.2 /- Decidable -/ theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true := match h with | isTrue h => rfl | isFalse h => False.elim $ h ⟨⟩ theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false := match h with | isFalse h => rfl | isTrue h => False.elim h /-- Similar to `decide`, but uses an explicit instance -/ @[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool := @decide p d theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true := @decideEqTrue _ d h theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p := @ofDecideEqTrue _ d h theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p := @ofDecideEqFalse _ d h instance : Decidable True := isTrue trivial instance : Decidable False := isFalse notFalse namespace Decidable variables {p q : Prop} @[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match dec with | isTrue h => h1 h | isFalse h => h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p := byCases id (fun np => False.elim (h np)) theorem ofNotNot [Decidable p] : ¬ ¬ p → p := fun hnn => byContradiction (fun hn => absurd hn hnn) theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (fun h => match d₁, d₂ with | isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h | _, isFalse h₂ => Or.inr h₂ | isFalse h₁, _ => Or.inl h₁) (fun (h) ⟨hp, hq⟩ => match h with | Or.inl h => h hp | Or.inr h => h hq) end Decidable section variables {p q : Prop} @[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse fun hq => absurd (Iff.mpr h hq) hp @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := h ▸ hp end @[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (fun h => hq) else isFalse (fun h => absurd (h hp) hq) else isTrue (fun h => absurd h hp) instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩ else isFalse fun h => hq (h.1 hp) else if hq : q then isFalse fun h => hp (h.2 hq) else isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩ /- if-then-else expression theorems -/ theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc := match h with | (isTrue hc) => rfl | (isFalse hnc) => absurd hc hnc theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc := match h with | (isTrue hc) => absurd hc hnc | (isFalse hnc) => rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e := match h with | (isTrue hc) => rfl | (isFalse hnc) => rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | (isTrue hc) => dT | (isFalse hc) => dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | (isTrue hc) => dT hc | (isFalse hc) => dE hc /- Inhabited -/ instance : Inhabited Prop := { default := True } instance : Inhabited Bool := { default := false } instance : Inhabited True := { default := trivial } instance : Inhabited NonScalar := { default := ⟨arbitrary _⟩ } instance : Inhabited PNonScalar.{u} := { default := ⟨arbitrary _⟩ } instance {α} [Inhabited α] : Inhabited (ForInStep α) := { default:= ForInStep.done (arbitrary _) } class inductive Nonempty (α : Sort u) : Prop | intro (val : α) : Nonempty α protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := h₂ h₁.1 instance {α : Sort u} [Inhabited α] : Nonempty α := { val := arbitrary α } theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α | ⟨w, h⟩ => ⟨w⟩ /- Subsingleton -/ class inductive Subsingleton (α : Sort u) : Prop | intro (h : (a b : α) → a = b) : Subsingleton α protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b := match h with | intro h => h protected def Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : a ≅ b := by subst h₂ apply heqOfEq apply Subsingleton.elim instance (p : Prop) : Subsingleton p := ⟨fun a b => proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro fun | (isTrue t₁) => fun | (isTrue t₂) => proofIrrel t₁ t₂ ▸ rfl | (isFalse f₂) => absurd t₁ f₂ | (isFalse f₁) => fun | (isTrue t₂) => absurd t₂ f₁ | (isFalse f₂) => proofIrrel f₁ f₂ ▸ rfl theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)] : Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h₂ h₁) := match h with | (isTrue h) => h₃ h | (isFalse h) => h₄ h structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop := (refl : ∀ x, r x x) (symm : ∀ {x y}, r x y → r y x) (trans : ∀ {x y z}, r x y → r y z → r x z) def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop := False def Subrelation {α : Sort u} (q r : α → α → Prop) := ∀ {x y}, q x y → r x y def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop := fun a₁ a₂ => r (f a₁) (f a₂) inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → TC r a b | trans : ∀ a b c, TC r a b → TC r b c → TC r a c /- Subtype -/ namespace Subtype def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x) | ⟨a, h⟩ => ⟨a, h⟩ variables {α : Type u} {p : α → Prop} protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨x, h1⟩, ⟨_, _⟩, rfl => rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by cases a exact rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} := { default := ⟨a, h⟩ } instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := fun ⟨a, h₁⟩ ⟨b, h₂⟩ => if h : a = b then isTrue (by subst h; exact rfl) else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h)) end Subtype /- Sum -/ section variables {α : Type u} {β : Type v} instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) := { default := Sum.inl (arbitrary α) } instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) := { default := Sum.inr (arbitrary β) } instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b => match a, b with | (Sum.inl a), (Sum.inl b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inr b) => if h : a = b then isTrue (h ▸ rfl) else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h)) | (Sum.inr a), (Sum.inl b) => isFalse (fun h => Sum.noConfusion h) | (Sum.inl a), (Sum.inr b) => isFalse (fun h => Sum.noConfusion h) end /- Product -/ section variables {α : Type u} {β : Type v} instance [Inhabited α] [Inhabited β] : Inhabited (α × β) := { default := (arbitrary α, arbitrary β) } instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := fun ⟨a, b⟩ ⟨a', b'⟩ => match (decEq a a') with | (isTrue e₁) => match (decEq b b') with | (isTrue e₂) => isTrue (e₁ ▸ e₂ ▸ rfl) | (isFalse n₂) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₂' n₂)) | (isFalse n₁) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₁' n₁)) instance [BEq α] [BEq β] : BEq (α × β) := { beq := fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => a₁ == a₂ && b₁ == b₂ } instance [HasLess α] [HasLess β] : HasLess (α × β) := { Less := fun s t => s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2) } instance prodHasDecidableLt [HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β] [(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)] : (s t : α × β) → Decidable (s < t) := fun t s => inferInstanceAs (Decidable (_ ∨ _)) theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl end def Prod.map.{u₁, u₂, v₁, v₂} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) => (f a, g b) /- Dependent products -/ theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x) | ⟨x, hx⟩ => ⟨x, hx⟩ protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} (h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by subst h₁ subst h₂ exact rfl /- Universe polymorphic unit -/ theorem punitEq (a b : PUnit) : a = b := by cases a; cases b; exact rfl theorem punitEqPUnit (a : PUnit) : a = () := punitEq a () instance : Subsingleton PUnit := Subsingleton.intro punitEq instance : Inhabited PUnit := { default := ⟨⟩ } instance : DecidableEq PUnit := fun a b => isTrue (punitEq a b) /- Setoid -/ class Setoid (α : Sort u) := (r : α → α → Prop) (iseqv {} : Equivalence r) instance {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variables {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := (Setoid.iseqv α).refl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := (Setoid.iseqv α).symm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := (Setoid.iseqv α).trans hab hbc end Setoid /- Propositional extensionality -/ axiom propext {a b : Prop} : (a ↔ b) → a = b /- Quotients -/ -- Iff can now be used to do substitutions in a calculation theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : (a b : α) → r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (p : (a : α) → motive (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a := rfl protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β := lift f c q protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop} (q : Quot r) (h : (a : α) → motive (Quot.mk r a)) : motive q := ind h q theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) := Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {motive : Quot r → Sort v} @[reducible, macroInline] protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : (a b : α) → r a b → Quot.indep f a = Quot.indep f b := fun a b e => PSigma.eta (sound e) (h a b e) protected theorem liftIndepPr1 (f : (a : α) → motive (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by induction q using Quot.ind exact rfl protected abbrev rec (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) (q : Quot r) : motive q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) protected abbrev recOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b) : motive q := Quot.rec f h q protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quot.mk r a))] (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) : motive q := by induction q using Quot.rec apply f apply Subsingleton.elim protected abbrev hrecOn (q : Quot r) (f : (a : α) → motive (Quot.mk r a)) (c : (a b : α) → (p : r a b) → f a ≅ f b) : motive q := Quot.recOn q f fun a b p => eqOfHEq $ have p₁ : Eq.ndrec (f a) (sound p) ≅ f a := eqRecHEq (sound p) (f a) HEq.trans p₁ (c a b p) end end Quot def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b := Quot.sound protected abbrev lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β := Quot.lift f protected theorem ind {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk a)) → (q : Quot Setoid.r) → motive q := Quot.ind protected abbrev liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β := Quot.liftOn q f c protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} (q : Quotient s) (h : (a : α) → motive (Quotient.mk a)) : motive q := Quot.inductionOn q h theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) := Quot.existsRep q section variable {α : Sort u} variable [s : Setoid α] variable {motive : Quotient s → Sort v} @[inline] protected def rec (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) (q : Quotient s) : motive q := Quot.rec f h q protected abbrev recOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b) : motive q := Quot.recOn q f h protected abbrev recOnSubsingleton [h : (a : α) → Subsingleton (motive (Quotient.mk a))] (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) : motive q := Quot.recOnSubsingleton (h := h) q f protected abbrev hrecOn (q : Quotient s) (f : (a : α) → motive (Quotient.mk a)) (c : (a b : α) → (p : a ≈ b) → f a ≅ f b) : motive q := Quot.hrecOn q f c end section universes uA uB uC variables {α : Sort uA} {β : Sort uB} {φ : Sort uC} variables [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev lift₂ (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := by apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁ intros induction q₂ using Quotient.ind apply c; assumption; apply Setoid.refl protected abbrev liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂) : φ := Quotient.lift₂ f c q₁ q₂ protected theorem ind₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₂ {motive : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind apply h protected theorem inductionOn₃ [s₃ : Setoid φ] {motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c)) : motive q₁ q₂ q₃ := by induction q₁ using Quotient.ind induction q₂ using Quotient.ind induction q₃ using Quotient.ind apply h end section Exact variable {α : Sort u} private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (fun a₁ a₂ => a₁ ≈ a₂) (fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ => propext (Iff.intro (fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl [s : Setoid α] (q : Quotient s) : rel q q := Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a) private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := fun h => Eq.ndrecOn h (rel.refl q₁) theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b := fun h => eqImpRel h end Exact section universes uA uB uC variables {α : Sort uA} {β : Sort uB} variables [s₁ : Setoid α] [s₂ : Setoid β] protected abbrev recOnSubsingleton₂ {motive : Quotient s₁ → Quotient s₂ → Sort uC} [s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b)) : motive q₁ q₂ := by induction q₁ using Quot.recOnSubsingleton induction q₂ using Quot.recOnSubsingleton intro a; apply s induction q₂ using Quot.recOnSubsingleton intro a; apply s apply g end end Quotient section variable {α : Type u} variable (r : α → α → Prop) instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) := fun (q₁ q₂ : Quotient s) => Quotient.recOnSubsingleton₂ (motive := fun a b => Decidable (a = b)) q₁ q₂ (fun a₁ a₂ => match (d a₁ a₂) with | (isTrue h₁) => isTrue (Quotient.sound h₁) | (isFalse h₂) => isFalse (fun h => absurd (Quotient.exact h) h₂)) /- Function extensionality -/ namespace Function variables {α : Sort u} {β : α → Sort v} def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f := fun x => rfl protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ := fun h x => Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ := fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := { refl := Equiv.refl, symm := Equiv.symm, trans := Equiv.trans } end Function section open Quotient variables {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient $ funSetoid α β) (x : α) : β x := Quot.liftOn f (fun (f : ∀ (x : α), β x) => f x) (fun f₁ f₂ h => h x) theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) apply congrArg apply Quotient.sound exact h end instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) := ⟨fun f₁ f₂ => funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))⟩ /- Squash -/ def Squash (α : Type u) := Quot (fun (a b : α) => True) def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q := Quot.ind h @[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β := Quot.lift f (fun a b _ => Subsingleton.elim _ _) s instance {α} : Subsingleton (Squash α) := ⟨fun a b => Squash.ind (motive := fun a => a = b) (fun a => Squash.ind (motive := fun b => Squash.mk a = b) (fun b => show Quot.mk _ a = Quot.mk _ b by apply Quot.sound; exact trivial) b) a⟩ namespace Lean /- Kernel reduction hints -/ /-- When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`. The kernel will not use the interpreter if `c` is not a constant. This feature is useful for performing proofs by reflection. Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with `Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled. Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base. This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using external type checkers (e.g., Trepplein) that do not implement this feature. Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter. So, you are mainly losing the capability of type checking your developement using external checkers. Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations. If an extern function is executed, then the trusted code base will also include the implementation of the associated foreign function. -/ constant reduceBool (b : Bool) : Bool := b /-- Similar to `Lean.reduceBool` for closed `Nat` terms. Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`. The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression. We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/ constant reduceNat (n : Nat) : Nat := n axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b end Lean
5292d60b99525dc37fa8079d1aa114022468a449
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/non_unital_subsemiring/basic.lean
8b32d68f380397b1d4e8fb5d0c96f2087978e187
[ "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
34,462
lean
/- Copyright (c) 2022 Jireh Loreaux All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.ring.equiv import algebra.ring.prod import data.set.finite import group_theory.submonoid.membership import group_theory.subsemigroup.membership import group_theory.subsemigroup.centralizer /-! # Bundled non-unital subsemirings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define bundled non-unital subsemirings and some standard constructions: `complete_lattice` structure, `subtype` and `inclusion` ring homomorphisms, non-unital subsemiring `map`, `comap` and range (`srange`) of a `non_unital_ring_hom` etc. -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [non_unital_non_assoc_semiring R] (M : subsemigroup R) /-- `non_unital_subsemiring_class S R` states that `S` is a type of subsets `s ⊆ R` that are both an additive submonoid and also a multiplicative subsemigroup. -/ class non_unital_subsemiring_class (S : Type*) (R : Type u) [non_unital_non_assoc_semiring R] [set_like S R] extends add_submonoid_class S R := (mul_mem : ∀ {s : S} {a b : R}, a ∈ s → b ∈ s → a * b ∈ s) @[priority 100] -- See note [lower instance priority] instance non_unital_subsemiring_class.mul_mem_class (S : Type*) (R : Type u) [non_unital_non_assoc_semiring R] [set_like S R] [h : non_unital_subsemiring_class S R] : mul_mem_class S R := { .. h } namespace non_unital_subsemiring_class variables [set_like S R] [non_unital_subsemiring_class S R] (s : S) include R S open add_submonoid_class /-- A non-unital subsemiring of a `non_unital_non_assoc_semiring` inherits a `non_unital_non_assoc_semiring` structure -/ @[priority 75] /- Prefer subclasses of `non_unital_non_assoc_semiring` over subclasses of `non_unital_subsemiring_class`. -/ instance to_non_unital_non_assoc_semiring : non_unital_non_assoc_semiring s := subtype.coe_injective.non_unital_non_assoc_semiring coe rfl (by simp) (λ _ _, rfl) (λ _ _, rfl) instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := subtype.coe_injective.no_zero_divisors coe rfl (λ x y, rfl) /-- The natural non-unital ring hom from a non-unital subsemiring of a non-unital semiring `R` to `R`. -/ def subtype : s →ₙ+* R := { to_fun := coe, .. add_submonoid_class.subtype s, .. mul_mem_class.subtype s } @[simp] theorem coe_subtype : (subtype s : s → R) = coe := rfl omit R S /-- A non-unital subsemiring of a `non_unital_semiring` is a `non_unital_semiring`. -/ instance to_non_unital_semiring {R} [non_unital_semiring R] [set_like S R] [non_unital_subsemiring_class S R] : non_unital_semiring s := subtype.coe_injective.non_unital_semiring coe rfl (by simp) (λ _ _, rfl) (λ _ _, rfl) /-- A non-unital subsemiring of a `non_unital_comm_semiring` is a `non_unital_comm_semiring`. -/ instance to_non_unital_comm_semiring {R} [non_unital_comm_semiring R] [set_like S R] [non_unital_subsemiring_class S R] : non_unital_comm_semiring s := subtype.coe_injective.non_unital_comm_semiring coe rfl (by simp) (λ _ _, rfl) (λ _ _, rfl) /-! Note: currently, there are no ordered versions of non-unital rings. -/ end non_unital_subsemiring_class variables [non_unital_non_assoc_semiring S] [non_unital_non_assoc_semiring T] set_option old_structure_cmd true /-- A non-unital subsemiring of a non-unital semiring `R` is a subset `s` that is both an additive submonoid and a semigroup. -/ structure non_unital_subsemiring (R : Type u) [non_unital_non_assoc_semiring R] extends add_submonoid R, subsemigroup R /-- Reinterpret a `non_unital_subsemiring` as a `subsemigroup`. -/ add_decl_doc non_unital_subsemiring.to_subsemigroup /-- Reinterpret a `non_unital_subsemiring` as an `add_submonoid`. -/ add_decl_doc non_unital_subsemiring.to_add_submonoid namespace non_unital_subsemiring instance : set_like (non_unital_subsemiring R) R := { coe := non_unital_subsemiring.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } instance : non_unital_subsemiring_class (non_unital_subsemiring R) R := { zero_mem := zero_mem', add_mem := add_mem', mul_mem := mul_mem' } @[simp] lemma mem_carrier {s : non_unital_subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two non-unital subsemirings are equal if they have the same elements. -/ @[ext] theorem ext {S T : non_unital_subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a non-unital subsemiring with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (S : non_unital_subsemiring R) (s : set R) (hs : s = ↑S) : non_unital_subsemiring R := { carrier := s, ..S.to_add_submonoid.copy s hs, ..S.to_subsemigroup.copy s hs } @[simp] lemma coe_copy (S : non_unital_subsemiring R) (s : set R) (hs : s = ↑S) : (S.copy s hs : set R) = s := rfl lemma copy_eq (S : non_unital_subsemiring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs lemma to_subsemigroup_injective : function.injective (to_subsemigroup : non_unital_subsemiring R → subsemigroup R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_subsemigroup_strict_mono : strict_mono (to_subsemigroup : non_unital_subsemiring R → subsemigroup R) := λ _ _, id @[mono] lemma to_subsemigroup_mono : monotone (to_subsemigroup : non_unital_subsemiring R → subsemigroup R) := to_subsemigroup_strict_mono.monotone lemma to_add_submonoid_injective : function.injective (to_add_submonoid : non_unital_subsemiring R → add_submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : non_unital_subsemiring R → add_submonoid R) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : non_unital_subsemiring R → add_submonoid R) := to_add_submonoid_strict_mono.monotone /-- Construct a `non_unital_subsemiring R` from a set `s`, a subsemigroup `sg`, and an additive submonoid `sa` such that `x ∈ s ↔ x ∈ sg ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sg : subsemigroup R) (hg : ↑sg = s) (sa : add_submonoid R) (ha : ↑sa = s) : non_unital_subsemiring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hg] using sg.mul_mem } @[simp] lemma coe_mk' {s : set R} {sg : subsemigroup R} (hg : ↑sg = s) {sa : add_submonoid R} (ha : ↑sa = s) : (non_unital_subsemiring.mk' s sg hg sa ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sg : subsemigroup R} (hg : ↑sg = s) {sa : add_submonoid R} (ha : ↑sa = s) {x : R} : x ∈ non_unital_subsemiring.mk' s sg hg sa ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_subsemigroup {s : set R} {sg : subsemigroup R} (hg : ↑sg = s) {sa : add_submonoid R} (ha : ↑sa = s) : (non_unital_subsemiring.mk' s sg hg sa ha).to_subsemigroup = sg := set_like.coe_injective hg.symm @[simp] lemma mk'_to_add_submonoid {s : set R} {sg : subsemigroup R} (hg : ↑sg = s) {sa : add_submonoid R} (ha : ↑sa =s) : (non_unital_subsemiring.mk' s sg hg sa ha).to_add_submonoid = sa := set_like.coe_injective ha.symm end non_unital_subsemiring namespace non_unital_subsemiring variables {F G : Type*} [non_unital_ring_hom_class F R S] [non_unital_ring_hom_class G S T] (s : non_unital_subsemiring R) @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl @[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl /-! Note: currently, there are no ordered versions of non-unital rings. -/ @[simp] lemma mem_to_subsemigroup {s : non_unital_subsemiring R} {x : R} : x ∈ s.to_subsemigroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_subsemigroup (s : non_unital_subsemiring R) : (s.to_subsemigroup : set R) = s := rfl @[simp] lemma mem_to_add_submonoid {s : non_unital_subsemiring R} {x : R} : x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_submonoid (s : non_unital_subsemiring R) : (s.to_add_submonoid : set R) = s := rfl /-- The non-unital subsemiring `R` of the non-unital semiring `R`. -/ instance : has_top (non_unital_subsemiring R) := ⟨{ .. (⊤ : subsemigroup R), .. (⊤ : add_submonoid R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : non_unital_subsemiring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : non_unital_subsemiring R) : set R) = set.univ := rfl /-- The preimage of a non-unital subsemiring along a non-unital ring homomorphism is a non-unital subsemiring. -/ def comap (f : F) (s : non_unital_subsemiring S) : non_unital_subsemiring R := { carrier := f ⁻¹' s, .. s.to_subsemigroup.comap (f : mul_hom R S), .. s.to_add_submonoid.comap (f : R →+ S) } @[simp] lemma coe_comap (s : non_unital_subsemiring S) (f : F) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : non_unital_subsemiring S} {f : F} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl -- this has some nasty coercions, how to deal with it? lemma comap_comap (s : non_unital_subsemiring T) (g : G) (f : F) : ((s.comap g : non_unital_subsemiring S).comap f : non_unital_subsemiring R) = s.comap ((g : S →ₙ+* T).comp (f : R →ₙ+* S)) := rfl /-- The image of a non-unital subsemiring along a ring homomorphism is a non-unital subsemiring. -/ def map (f : F) (s : non_unital_subsemiring R) : non_unital_subsemiring S := { carrier := f '' s, .. s.to_subsemigroup.map (f : R →ₙ* S), .. s.to_add_submonoid.map (f : R →+ S) } @[simp] lemma coe_map (f : F) (s : non_unital_subsemiring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : F} {s : non_unital_subsemiring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex @[simp] lemma map_id : s.map (non_unital_ring_hom.id R) = s := set_like.coe_injective $ set.image_id _ -- unavoidable coercions? lemma map_map (g : G) (f : F) : (s.map (f : R →ₙ+* S)).map (g : S →ₙ+* T) = s.map ((g : S →ₙ+* T).comp (f : R →ₙ+* S)) := set_like.coe_injective $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : F} {s : non_unital_subsemiring R} {t : non_unital_subsemiring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : F) : @galois_connection (non_unital_subsemiring R) (non_unital_subsemiring S) _ _ (map f) (comap f) := λ S T, map_le_iff_le_comap /-- A non-unital subsemiring is isomorphic to its image under an injective function -/ noncomputable def equiv_map_of_injective (f : F) (hf : function.injective (f : R → S)) : s ≃+* s.map f := { map_mul' := λ _ _, subtype.ext (map_mul f _ _), map_add' := λ _ _, subtype.ext (map_add f _ _), ..equiv.set.image f s hf } @[simp] lemma coe_equiv_map_of_injective_apply (f : F) (hf : function.injective f) (x : s) : (equiv_map_of_injective s f hf x : S) = f x := rfl end non_unital_subsemiring namespace non_unital_ring_hom open non_unital_subsemiring variables {F G : Type*} [non_unital_ring_hom_class F R S] [non_unital_ring_hom_class G S T] (f : F) (g : G) /-- The range of a non-unital ring homomorphism is a non-unital subsemiring. See note [range copy pattern]. -/ def srange : non_unital_subsemiring S := ((⊤ : non_unital_subsemiring R).map (f : R →ₙ+* S)).copy (set.range f) set.image_univ.symm @[simp] lemma coe_srange : (@srange R S _ _ _ _ f : set S) = set.range f := rfl @[simp] lemma mem_srange {f : F} {y : S} : y ∈ (@srange R S _ _ _ _ f) ↔ ∃ x, f x = y := iff.rfl lemma srange_eq_map : @srange R S _ _ _ _ f = (⊤ : non_unital_subsemiring R).map f := by { ext, simp } lemma mem_srange_self (f : F) (x : R) : f x ∈ @srange R S _ _ _ _ f := mem_srange.mpr ⟨x, rfl⟩ lemma map_srange (g : S →ₙ+* T) (f : R →ₙ+* S) : map g (srange f) = srange (g.comp f) := by simpa only [srange_eq_map] using (⊤ : non_unital_subsemiring R).map_map g f /-- The range of a morphism of non-unital semirings is finite if the domain is a finite. -/ instance finite_srange [finite R] (f : F) : finite (srange f : non_unital_subsemiring S) := (set.finite_range f).to_subtype end non_unital_ring_hom namespace non_unital_subsemiring -- should we define this as the range of the zero homomorphism? instance : has_bot (non_unital_subsemiring R) := ⟨{ carrier := {0}, add_mem' := λ _ _ _ _, by simp * at *, zero_mem' := set.mem_singleton 0, mul_mem' := λ _ _ _ _, by simp * at *}⟩ instance : inhabited (non_unital_subsemiring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : non_unital_subsemiring R) : set R) = {0} := rfl lemma mem_bot {x : R} : x ∈ (⊥ : non_unital_subsemiring R) ↔ x = 0 := set.mem_singleton_iff /-- The inf of two non-unital subsemirings is their intersection. -/ instance : has_inf (non_unital_subsemiring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_subsemigroup ⊓ t.to_subsemigroup, .. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩ @[simp] lemma coe_inf (p p' : non_unital_subsemiring R) : ((p ⊓ p' : non_unital_subsemiring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : non_unital_subsemiring R} {x : R} :x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (non_unital_subsemiring R) := ⟨λ s, non_unital_subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, non_unital_subsemiring.to_subsemigroup t) (by simp) (⨅ t ∈ s, non_unital_subsemiring.to_add_submonoid t) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (non_unital_subsemiring R)) : ((Inf S : non_unital_subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (non_unital_subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[simp] lemma Inf_to_subsemigroup (s : set (non_unital_subsemiring R)) : (Inf s).to_subsemigroup = ⨅ t ∈ s, non_unital_subsemiring.to_subsemigroup t := mk'_to_subsemigroup _ _ @[simp] lemma Inf_to_add_submonoid (s : set (non_unital_subsemiring R)) : (Inf s).to_add_submonoid = ⨅ t ∈ s, non_unital_subsemiring.to_add_submonoid t := mk'_to_add_submonoid _ _ /-- Non-unital subsemirings of a non-unital semiring form a complete lattice. -/ instance : complete_lattice (non_unital_subsemiring R) := { bot := (⊥), bot_le := λ s x hx, (mem_bot.mp hx).symm ▸ zero_mem s, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (non_unital_subsemiring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)} lemma eq_top_iff' (A : non_unital_subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ section center /-- The center of a semiring `R` is the set of elements that commute with everything in `R` -/ def center (R) [non_unital_semiring R] : non_unital_subsemiring R := { carrier := set.center R, zero_mem' := set.zero_mem_center R, add_mem' := λ a b, set.add_mem_center, .. subsemigroup.center R } lemma coe_center (R) [non_unital_semiring R] : ↑(center R) = set.center R := rfl @[simp] lemma center_to_subsemigroup (R) [non_unital_semiring R] : (center R).to_subsemigroup = subsemigroup.center R := rfl lemma mem_center_iff {R} [non_unital_semiring R] {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center {R} [non_unital_semiring R] [decidable_eq R] [fintype R] : decidable_pred (∈ center R) := λ _, decidable_of_iff' _ mem_center_iff @[simp] lemma center_eq_top (R) [non_unital_comm_semiring R] : center R = ⊤ := set_like.coe_injective (set.center_eq_univ R) /-- The center is commutative. -/ instance {R} [non_unital_semiring R] : non_unital_comm_semiring (center R) := { ..subsemigroup.center.comm_semigroup, ..(non_unital_subsemiring_class.to_non_unital_semiring (center R)) } end center section centralizer /-- The centralizer of a set as non-unital subsemiring. -/ def centralizer {R} [non_unital_semiring R] (s : set R) : non_unital_subsemiring R := { carrier := s.centralizer, zero_mem' := set.zero_mem_centralizer _, add_mem' := λ x y hx hy, set.add_mem_centralizer hx hy, ..subsemigroup.centralizer s } @[simp, norm_cast] lemma coe_centralizer {R} [non_unital_semiring R] (s : set R) : (centralizer s : set R) = s.centralizer := rfl lemma centralizer_to_subsemigroup {R} [non_unital_semiring R] (s : set R) : (centralizer s).to_subsemigroup = subsemigroup.centralizer s := rfl lemma mem_centralizer_iff {R} [non_unital_semiring R] {s : set R} {z : R} : z ∈ centralizer s ↔ ∀ g ∈ s, g * z = z * g := iff.rfl lemma center_le_centralizer {R} [non_unital_semiring R] (s) : center R ≤ centralizer s := s.center_subset_centralizer lemma centralizer_le {R} [non_unital_semiring R] (s t : set R) (h : s ⊆ t) : centralizer t ≤ centralizer s := set.centralizer_subset h @[simp] lemma centralizer_eq_top_iff_subset {R} [non_unital_semiring R] {s : set R} : centralizer s = ⊤ ↔ s ⊆ center R := set_like.ext'_iff.trans set.centralizer_eq_top_iff_subset @[simp] lemma centralizer_univ {R} [non_unital_semiring R] : centralizer set.univ = center R := set_like.ext' (set.centralizer_univ R) end centralizer /-- The `non_unital_subsemiring` generated by a set. -/ def closure (s : set R) : non_unital_subsemiring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : non_unital_subsemiring R, s ⊆ S → x ∈ S := mem_Inf /-- The non-unital subsemiring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) /-- A non-unital subsemiring `S` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : non_unital_subsemiring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : non_unital_subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ lemma mem_map_equiv {f : R ≃+* S} {K : non_unital_subsemiring R} {x : S} : x ∈ K.map (f : R →ₙ+* S) ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : non_unital_subsemiring R) : K.map (f : R →ₙ+* S) = K.comap f.symm := set_like.coe_injective (f.to_equiv.image_eq_preimage K) lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : non_unital_subsemiring S) : K.comap (f : R →ₙ+* S) = K.map f.symm := (map_equiv_eq_comap_symm f.symm K).symm end non_unital_subsemiring namespace subsemigroup /-- The additive closure of a non-unital subsemigroup is a non-unital subsemiring. -/ def non_unital_subsemiring_closure (M : subsemigroup R) : non_unital_subsemiring R := { mul_mem' := λ x y, mul_mem_class.mul_mem_add_closure, ..add_submonoid.closure (M : set R)} lemma non_unital_subsemiring_closure_coe : (M.non_unital_subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl lemma non_unital_subsemiring_closure_to_add_submonoid : M.non_unital_subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl /-- The `non_unital_subsemiring` generated by a multiplicative subsemigroup coincides with the `non_unital_subsemiring.closure` of the subsemigroup itself . -/ lemma non_unital_subsemiring_closure_eq_closure : M.non_unital_subsemiring_closure = non_unital_subsemiring.closure (M : set R) := begin ext, refine ⟨λ hx, _, λ hx, (non_unital_subsemiring.mem_closure.mp hx) M.non_unital_subsemiring_closure (λ s sM, _)⟩; rintros - ⟨H1, rfl⟩; rintros - ⟨H2, rfl⟩, { exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 }, { exact H2 sM } end end subsemigroup namespace non_unital_subsemiring @[simp] lemma closure_subsemigroup_closure (s : set R) : closure ↑(subsemigroup.closure s) = closure s := le_antisymm (closure_le.mpr (λ y hy, (subsemigroup.mem_closure.mp hy) (closure s).to_subsemigroup subset_closure)) (closure_mono (subsemigroup.subset_closure)) /-- The elements of the non-unital subsemiring closure of `M` are exactly the elements of the additive closure of a multiplicative subsemigroup `M`. -/ lemma coe_closure_eq (s : set R) : (closure s : set R) = add_submonoid.closure (subsemigroup.closure s : set R) := by simp [← subsemigroup.non_unital_subsemiring_closure_to_add_submonoid, subsemigroup.non_unital_subsemiring_closure_eq_closure] lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_submonoid.closure (subsemigroup.closure s : set R) := set.ext_iff.mp (coe_closure_eq s) x @[simp] lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s := begin ext x, refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩, rintros - ⟨H, rfl⟩, rintros - ⟨J, rfl⟩, refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _), refine (subsemigroup.mem_closure.mp hy) H.to_subsemigroup (λ z hz, _), exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw), end /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, Hadd, H0, Hmul⟩).2 Hs h /-- An induction principle for closure membership for predicates with two arguments. -/ @[elab_as_eliminator] lemma closure_induction₂ {s : set R} {p : R → R → Prop} {x} {y : R} (hx : x ∈ closure s) (hy : y ∈ closure s) (Hs : ∀ (x ∈ s) (y ∈ s), p x y) (H0_left : ∀ x, p 0 x) (H0_right : ∀ x, p x 0) (Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y) (Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂)) (Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y) (Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂)) : p x y := closure_induction hx (λ x₁ x₁s, closure_induction hy (Hs x₁ x₁s) (H0_right x₁) (Hadd_right x₁) (Hmul_right x₁)) (H0_left y) (λ z z', Hadd_left z z' y) (λ z z', Hmul_left z z' y) variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variables {R} {F : Type*} [non_unital_ring_hom_class F R S] /-- Closure of a non-unital subsemiring `S` equals `S`. -/ lemma closure_eq (s : non_unital_subsemiring R) : closure (s : set R) = s := (non_unital_subsemiring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (non_unital_subsemiring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (non_unital_subsemiring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (non_unital_subsemiring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (non_unital_subsemiring.gi R).gc.l_Sup lemma map_sup (s t : non_unital_subsemiring R) (f : F) : (map f (s ⊔ t) : non_unital_subsemiring S) = map f s ⊔ map f t := @galois_connection.l_sup _ _ s t _ _ _ _ (gc_map_comap f) lemma map_supr {ι : Sort*} (f : F) (s : ι → non_unital_subsemiring R) : (map f (supr s) : non_unital_subsemiring S) = ⨆ i, map f (s i) := @galois_connection.l_supr _ _ _ _ _ _ _ (gc_map_comap f) s lemma comap_inf (s t : non_unital_subsemiring S) (f : F) : (comap f (s ⊓ t) : non_unital_subsemiring R) = comap f s ⊓ comap f t := @galois_connection.u_inf _ _ s t _ _ _ _ (gc_map_comap f) lemma comap_infi {ι : Sort*} (f : F) (s : ι → non_unital_subsemiring S) : (comap f (infi s) : non_unital_subsemiring R) = ⨅ i, comap f (s i) := @galois_connection.u_infi _ _ _ _ _ _ _ (gc_map_comap f) s @[simp] lemma map_bot (f : F) : map f (⊥ : non_unital_subsemiring R) = (⊥ : non_unital_subsemiring S) := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : F) : comap f (⊤ : non_unital_subsemiring S) = (⊤ : non_unital_subsemiring R) := (gc_map_comap f).u_top /-- Given `non_unital_subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t` as a non-unital subsemiring of `R × S`. -/ def prod (s : non_unital_subsemiring R) (t : non_unital_subsemiring S) : non_unital_subsemiring (R × S) := { carrier := (s : set R) ×ˢ (t : set S), .. s.to_subsemigroup.prod t.to_subsemigroup, .. s.to_add_submonoid.prod t.to_add_submonoid} @[norm_cast] lemma coe_prod (s : non_unital_subsemiring R) (t : non_unital_subsemiring S) : (s.prod t : set (R × S)) = (s : set R) ×ˢ (t : set S) := rfl lemma mem_prod {s : non_unital_subsemiring R} {t : non_unital_subsemiring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : non_unital_subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : non_unital_subsemiring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : non_unital_subsemiring R) : monotone (λ t : non_unital_subsemiring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : non_unital_subsemiring S) : monotone (λ s : non_unital_subsemiring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : non_unital_subsemiring R) : s.prod (⊤ : non_unital_subsemiring S) = s.comap (non_unital_ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : non_unital_subsemiring S) : (⊤ : non_unital_subsemiring R).prod s = s.comap (non_unital_ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : non_unital_subsemiring R).prod (⊤ : non_unital_subsemiring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of non-unital subsemirings is isomorphic to their product as semigroups. -/ def prod_equiv (s : non_unital_subsemiring R) (t : non_unital_subsemiring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → non_unital_subsemiring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, let U : non_unital_subsemiring R := non_unital_subsemiring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_subsemigroup) (subsemigroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → non_unital_subsemiring R} (hS : directed (≤) S) : ((⨆ i, S i : non_unital_subsemiring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (non_unital_subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (non_unital_subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end non_unital_subsemiring namespace non_unital_ring_hom variables {F : Type*} [non_unital_non_assoc_semiring T] [non_unital_ring_hom_class F R S] {s : non_unital_subsemiring R} open non_unital_subsemiring_class non_unital_subsemiring /-- Restriction of a non-unital ring homomorphism to a non-unital subsemiring of the codomain. -/ def cod_restrict (f : F) (s : non_unital_subsemiring S) (h : ∀ x, f x ∈ s) : R →ₙ+* s := { to_fun := λ n, ⟨f n, h n⟩, .. (f : R →ₙ* S).cod_restrict s.to_subsemigroup h, .. (f : R →+ S).cod_restrict s.to_add_submonoid h } /-- Restriction of a non-unital ring homomorphism to its range interpreted as a non-unital subsemiring. This is the bundled version of `set.range_factorization`. -/ def srange_restrict (f : F) : R →ₙ+* (srange f : non_unital_subsemiring S) := cod_restrict f (srange f) (mem_srange_self f) @[simp] lemma coe_srange_restrict (f : F) (x : R) : (srange_restrict f x : S) = f x := rfl lemma srange_restrict_surjective (f : F) : function.surjective (srange_restrict f : R → (srange f : non_unital_subsemiring S)) := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩ lemma srange_top_iff_surjective {f : F} : srange f = (⊤ : non_unital_subsemiring S) ↔ function.surjective (f : R → S):= set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective /-- The range of a surjective non-unital ring homomorphism is the whole of the codomain. -/ lemma srange_top_of_surjective (f : F) (hf : function.surjective (f : R → S)) : srange f = (⊤ : non_unital_subsemiring S) := srange_top_iff_surjective.2 hf /-- The non-unital subsemiring of elements `x : R` such that `f x = g x` -/ def eq_slocus (f g : F) : non_unital_subsemiring R := { carrier := {x | f x = g x}, .. (f : R →ₙ* S).eq_mlocus (g : R →ₙ* S), .. (f : R →+ S).eq_mlocus g } /-- If two non-unital ring homomorphisms are equal on a set, then they are equal on its non-unital subsemiring closure. -/ lemma eq_on_sclosure {f g : F} {s : set R} (h : set.eq_on (f : R → S) (g : R → S) s) : set.eq_on f g (closure s) := show closure s ≤ eq_slocus f g, from closure_le.2 h lemma eq_of_eq_on_stop {f g : F} (h : set.eq_on (f : R → S) (g : R → S) (⊤ : non_unital_subsemiring R)) : f = g := fun_like.ext _ _ (λ x, h trivial) lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : F} (h : s.eq_on (f : R → S) (g : R → S)) : f = g := eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h lemma sclosure_preimage_le (f : F) (s : set S) : closure ((f : R → S) ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subsemiring generated by a set equals the subsemiring generated by the image of the set. -/ lemma map_sclosure (f : F) (s : set R) : (closure s).map f = closure ((f : R → S) '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (sclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end non_unital_ring_hom namespace non_unital_subsemiring open non_unital_ring_hom non_unital_subsemiring_class /-- The non-unital ring homomorphism associated to an inclusion of non-unital subsemirings. -/ def inclusion {S T : non_unital_subsemiring R} (h : S ≤ T) : S →ₙ+* T := cod_restrict (subtype S) _ (λ x, h x.2) @[simp] lemma srange_subtype (s : non_unital_subsemiring R) : (subtype s).srange = s := set_like.coe_injective $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := non_unital_ring_hom.srange_top_of_surjective (fst R S) prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := non_unital_ring_hom.srange_top_of_surjective (snd R S) $ prod.snd_surjective end non_unital_subsemiring namespace ring_equiv open non_unital_ring_hom non_unital_subsemiring_class variables {s t : non_unital_subsemiring R} variables {F : Type*} [non_unital_ring_hom_class F R S] /-- Makes the identity isomorphism from a proof two non-unital subsemirings of a multiplicative monoid are equal. -/ def non_unital_subsemiring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- Restrict a non-unital ring homomorphism with a left inverse to a ring isomorphism to its `non_unital_ring_hom.srange`. -/ def sof_left_inverse' {g : S → R} {f : F} (h : function.left_inverse g f) : R ≃+* srange f := { to_fun := srange_restrict f, inv_fun := λ x, g (subtype (srange f) x), left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := non_unital_ring_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..(srange_restrict f) } @[simp] lemma sof_left_inverse'_apply {g : S → R} {f : F} (h : function.left_inverse g f) (x : R) : ↑(sof_left_inverse' h x) = f x := rfl @[simp] lemma sof_left_inverse'_symm_apply {g : S → R} {f : F} (h : function.left_inverse g f) (x : srange f) : (sof_left_inverse' h).symm x = g x := rfl /-- Given an equivalence `e : R ≃+* S` of non-unital semirings and a non-unital subsemiring `s` of `R`, `non_unital_subsemiring_map e s` is the induced equivalence between `s` and `s.map e` -/ @[simps] def non_unital_subsemiring_map (e : R ≃+* S) (s : non_unital_subsemiring R) : s ≃+* non_unital_subsemiring.map e.to_non_unital_ring_hom s := { ..e.to_add_equiv.add_submonoid_map s.to_add_submonoid, ..e.to_mul_equiv.subsemigroup_map s.to_subsemigroup } end ring_equiv
d650b4e3b5a91485a4a7c99f939e149148b3214e
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/group_theory/order_of_element.lean
1f709b12afe13c0e842edd676b51dea8b6bd8ff8
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
22,702
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.set.finite group_theory.coset data.nat.totient open function variables {α : Type*} {s : set α} {a a₁ a₂ b c: α} -- TODO this lemma isn't used anywhere in this file, and should be moved elsewhere. namespace finset open finset lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) end finset lemma conj_inj [group α] {x : α} : function.injective (λ (g : α), x * g * x⁻¹) := λ a b h, by simpa [mul_left_inj, mul_right_inj] using h lemma mem_normalizer_fintype [group α] {s : set α} [fintype s] {x : α} (h : ∀ n, n ∈ s → x * n * x⁻¹ ∈ s) : x ∈ is_subgroup.normalizer s := by haveI := classical.prop_decidable; haveI := set.fintype_image s (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' s = s := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective s conj_inj), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' s := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_inj hy.2 ▸ hy.1⟩ section order_of variables [group α] [fintype α] [decidable_eq α] open quotient_group set instance quotient_group.fintype (s : set α) [is_subgroup s] [d : decidable_pred s] : fintype (quotient s) := @quotient.fintype _ _ (left_rel s) (λ _ _, d _) lemma card_eq_card_quotient_mul_card_subgroup (s : set α) [hs : is_subgroup s] [fintype s] [decidable_pred s] : fintype.card α = fintype.card (quotient s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (is_subgroup.group_equiv_quotient_times_subgroup hs) lemma card_subgroup_dvd_card (s : set α) [is_subgroup s] [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 (s : set α) [is_subgroup s] [decidable_pred s] [fintype s] : fintype.card (quotient s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s] @[simp] lemma card_trivial [fintype (is_subgroup.trivial α)] : fintype.card (is_subgroup.trivial α) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : α), by simp⟩, λ ⟨y, hy⟩, subtype.eq $ is_subgroup.mem_trivial.1 hy⟩ lemma exists_gpow_eq_one (a : α) : ∃i≠0, a ^ (i:ℤ) = 1 := have ¬ injective (λi, a ^ i), from not_injective_int_fintype, let ⟨i, j, a_eq, ne⟩ := show ∃(i j : ℤ), a ^ i = a ^ j ∧ i ≠ j, by rw [injective] at this; simpa [classical.not_forall] in have a ^ (i - j) = 1, by simp [gpow_add, gpow_neg, a_eq], ⟨i - j, sub_ne_zero.mpr ne, this⟩ lemma exists_pow_eq_one (a : α) : ∃i > 0, a ^ i = 1 := let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in begin cases i, { exact ⟨i, nat.pos_of_ne_zero (by simp [int.of_nat_eq_coe, *] at *), eq⟩ }, { exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ } end /-- `order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/ def order_of (a : α) : ℕ := nat.find (exists_pow_eq_one a) lemma pow_order_of_eq_one (a : α) : a ^ order_of a = 1 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₂ lemma order_of_pos (a : α) : order_of a > 0 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₁ private lemma pow_injective_aux {n m : ℕ} (a : α) (h : n ≤ m) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := decidable.by_contradiction $ assume ne : n ≠ m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have h₂ : a ^ (m - n) = 1, by simp [pow_sub _ h, eq], have le : order_of a ≤ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, h₂⟩, have lt : m - n < order_of a, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (lt_of_le_of_lt le lt) lemma pow_injective_of_lt_order_of {n m : ℕ} (a : α) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux a h hn hm eq) (assume h, (pow_injective_aux a h hm hn eq.symm).symm) lemma order_of_le_card_univ : order_of a ≤ fintype.card α := finset.card_le_of_inj_on ((^) a) (assume n _, fintype.complete _) (assume i j, pow_injective_of_lt_order_of a) lemma pow_eq_mod_order_of {n : ℕ} : a ^ n = a ^ (n % order_of a) := calc a ^ n = a ^ (n % order_of a + order_of a * (n / order_of a)) : by rw [nat.mod_add_div] ... = a ^ (n % order_of a) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma gpow_eq_mod_order_of {i : ℤ} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma mem_gpowers_iff_mem_range_order_of {a a' : α} : a' ∈ gpowers a ↔ a' ∈ (finset.range (order_of a)).image ((^) a : ℕ → α) := finset.mem_range_iff_mem_finset_range_of_mod_eq (order_of_pos a) (assume i, gpow_eq_mod_order_of.symm) instance decidable_gpowers : decidable_pred (gpowers a) := assume a', decidable_of_iff' (a' ∈ (finset.range (order_of a)).image ((^) a)) mem_gpowers_iff_mem_range_order_of lemma order_of_dvd_of_pow_eq_one {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := by_contradiction (λ h₁, nat.find_min _ (show n % order_of a < order_of a, from nat.mod_lt _ (order_of_pos _)) ⟨nat.pos_of_ne_zero (mt nat.dvd_of_mod_eq_zero h₁), by rwa ← pow_eq_mod_order_of⟩) lemma order_of_le_of_pow_eq_one {n : ℕ} (hn : 0 < n) (h : a ^ n = 1) : order_of a ≤ n := nat.find_min' (exists_pow_eq_one a) ⟨hn, h⟩ lemma sum_card_order_of_eq_card_pow_eq_one {n : ℕ} (hn : 0 < n) : ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = (finset.univ.filter (λ a : α, a ^ n = 1)).card := calc ((finset.range n.succ).filter (∣ n)).sum (λ m, (finset.univ.filter (λ a : α, order_of a = m)).card) = _ : (finset.card_bind (by { intros, apply finset.disjoint_filter, cc })).symm ... = _ : congr_arg finset.card (finset.ext.2 (begin assume a, suffices : order_of a ≤ n ∧ order_of a ∣ n ↔ a ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) section local attribute [instance] set_fintype lemma order_eq_card_gpowers : order_of a = fintype.card (gpowers a) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ order_of_pos a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end @[simp] lemma order_of_one : order_of (1 : α) = 1 := by rw [order_eq_card_gpowers, fintype.card_eq_one_iff]; exact ⟨⟨1, 0, rfl⟩, λ ⟨a, i, ha⟩, by simp [ha.symm]⟩ @[simp] lemma order_of_eq_one_iff : order_of a = 1 ↔ a = 1 := ⟨λ h, by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] }, λ h, by simp [h]⟩ section classical open_locale classical open quotient_group /- TODO: use cardinal theory, introduce `card : set α → ℕ`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of a ∣ fintype.card α := have ft_prod : fintype (quotient (gpowers a) × (gpowers a)), from fintype.of_equiv α (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers a), from @fintype.fintype_prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers a)), from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, is_submonoid.one_mem (gpowers a)⟩⟩, have ft : fintype (quotient (gpowers a) × (gpowers a)), from @prod.fintype _ _ ft_cosets ft_s, have eq₁ : fintype.card α = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card α = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of a = @fintype.card _ ft_s, from calc order_of a = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, dvd.intro (@fintype.card (quotient (gpowers a)) ft_cosets) $ by rw [eq₁, eq₂, mul_comm] end classical @[simp] lemma pow_card_eq_one (a : α) : a ^ fintype.card α = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ a _ _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] lemma powers_eq_gpowers (a : α) : powers a = gpowers a := set.ext (λ x, ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of a).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of]⟩⟩) open nat lemma order_of_pow (a : α) (n : ℕ) : order_of (a ^ n) = order_of a / gcd (order_of a) n := dvd_antisymm (order_of_dvd_of_pow_eq_one (by rw [← pow_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (gcd_dvd_right _ _), pow_mul, pow_order_of_eq_one, _root_.one_pow])) (have gcd_pos : 0 < gcd (order_of a) n, from gcd_pos_of_pos_left n (order_of_pos a), have hdvd : order_of a ∣ n * order_of (a ^ n), from order_of_dvd_of_pow_eq_one (by rw [pow_mul, pow_order_of_eq_one]), coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd gcd_pos) (dvd_of_mul_dvd_mul_right gcd_pos (by rwa [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc, nat.div_mul_cancel (gcd_dvd_right _ _), mul_comm]))) lemma pow_gcd_card_eq_one_iff {n : ℕ} {a : α} : a ^ n = 1 ↔ a ^ (gcd n (fintype.card α)) = 1 := ⟨λ h, have hn : order_of a ∣ n, from dvd_of_mod_eq_zero $ by_contradiction (λ ha, by rw pow_eq_mod_order_of at h; exact (not_le_of_gt (nat.mod_lt n (order_of_pos a))) (order_of_le_of_pow_eq_one (nat.pos_of_ne_zero ha) h)), let ⟨m, hm⟩ := dvd_gcd hn order_of_dvd_card_univ in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card α) in by rw [hm, pow_mul, h, _root_.one_pow]⟩ end end order_of section cyclic local attribute [instance] set_fintype class is_cyclic (α : Type*) [group α] : Prop := (exists_generator : ∃ g : α, ∀ x, x ∈ gpowers g) def is_cyclic.comm_group [hg : group α] [is_cyclic α] : comm_group α := { mul_comm := λ x y, show x * y = y * x, from let ⟨g, hg⟩ := is_cyclic.exists_generator α in let ⟨n, hn⟩ := hg x in let ⟨m, hm⟩ := hg y in hm ▸ hn ▸ gpow_mul_comm _ _ _, ..hg } lemma is_cyclic_of_order_of_eq_card [group α] [fintype α] [decidable_eq α] (x : α) (hx : order_of x = fintype.card α) : is_cyclic α := ⟨⟨x, set.eq_univ_iff_forall.1 $ set.eq_of_subset_of_card_le (set.subset_univ _) (by rw [fintype.card_congr (equiv.set.univ α), ← hx, order_eq_card_gpowers])⟩⟩ lemma order_of_eq_card_of_forall_mem_gpowers [group α] [fintype α] [decidable_eq α] {g : α} (hx : ∀ x, x ∈ gpowers g) : order_of g = fintype.card α := by rw [← fintype.card_congr (equiv.set.univ α), order_eq_card_gpowers]; simp [hx]; congr instance [group α] : is_cyclic (is_subgroup.trivial α) := ⟨⟨(1 : is_subgroup.trivial α), λ x, ⟨0, subtype.eq $ eq.symm (is_subgroup.mem_trivial.1 x.2)⟩⟩⟩ instance is_subgroup.is_cyclic [group α] [is_cyclic α] (H : set α) [is_subgroup H] : is_cyclic H := by haveI := classical.prop_decidable; exact let ⟨g, hg⟩ := is_cyclic.exists_generator α in if hx : ∃ (x : α), x ∈ H ∧ x ≠ (1 : α) then let ⟨x, hx₁, hx₂⟩ := hx in let ⟨k, hk⟩ := hg x in have hex : ∃ n : ℕ, 0 < n ∧ g ^ n ∈ H, from ⟨k.nat_abs, nat.pos_of_ne_zero (λ h, hx₂ $ by rw [← hk, int.eq_zero_of_nat_abs_eq_zero h, gpow_zero]), match k, hk with | (k : ℕ), hk := by rw [int.nat_abs_of_nat, ← gpow_coe_nat, hk]; exact hx₁ | -[1+ k], hk := by rw [int.nat_abs_of_neg_succ_of_nat, ← is_subgroup.inv_mem_iff H]; simp * at * end⟩, ⟨⟨⟨g ^ nat.find hex, (nat.find_spec hex).2⟩, λ ⟨x, hx⟩, let ⟨k, hk⟩ := hg x in have hk₁ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ gpowers (g ^ nat.find hex), from ⟨k / nat.find hex, eq.symm $ gpow_mul _ _ _⟩, have hk₂ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ H, by rw gpow_mul; exact is_subgroup.gpow_mem (nat.find_spec hex).2, have hk₃ : g ^ (k % nat.find hex) ∈ H, from (is_subgroup.mul_mem_cancel_left H hk₂).1 $ by rw [← gpow_add, int.mod_add_div, hk]; exact hx, have hk₄ : k % nat.find hex = (k % nat.find hex).nat_abs, by rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (nat.find_spec hex).1)), have hk₅ : g ^ (k % nat.find hex ).nat_abs ∈ H, by rwa [← gpow_coe_nat, ← hk₄], have hk₆ : (k % (nat.find hex : ℤ)).nat_abs = 0, from by_contradiction (λ h, nat.find_min hex (int.coe_nat_lt.1 $ by rw [← hk₄]; exact int.mod_lt_of_pos _ (int.coe_nat_pos.2 (nat.find_spec hex).1)) ⟨nat.pos_of_ne_zero h, hk₅⟩), ⟨k / (nat.find hex : ℤ), subtype.coe_ext.2 begin suffices : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) = x, { simpa [gpow_mul] }, rw [int.mul_div_cancel' (int.dvd_of_mod_eq_zero (int.eq_zero_of_nat_abs_eq_zero hk₆)), hk] end⟩⟩⟩ else have H = is_subgroup.trivial α, from set.ext $ λ x, ⟨λ h, by simp at *; tauto, λ h, by rw [is_subgroup.mem_trivial.1 h]; exact is_submonoid.one_mem _⟩, by clear _let_match; subst this; apply_instance open finset nat lemma is_cyclic.card_pow_eq_one_le [group α] [fintype α] [decidable_eq α] [is_cyclic α] {n : ℕ} (hn0 : 0 < n) : (univ.filter (λ a : α, a ^ n = 1)).card ≤ n := let ⟨g, hg⟩ := is_cyclic.exists_generator α in calc (univ.filter (λ a : α, a ^ n = 1)).card ≤ (gpowers (g ^ (fintype.card α / (gcd n (fintype.card α))))).to_finset.card : card_le_of_subset (λ x hx, let ⟨m, hm⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in set.mem_to_finset.2 ⟨(m / (fintype.card α / (gcd n (fintype.card α))) : ℕ), have hgmn : g ^ (m * gcd n (fintype.card α)) = 1, by rw [pow_mul, hm, ← pow_gcd_card_eq_one_iff]; exact (mem_filter.1 hx).2, begin rw [gpow_coe_nat, ← pow_mul, nat.mul_div_cancel_left', hm], refine dvd_of_mul_dvd_mul_right (gcd_pos_of_pos_left (fintype.card α) hn0) _, conv {to_lhs, rw [nat.div_mul_cancel (gcd_dvd_right _ _), ← order_of_eq_card_of_forall_mem_gpowers hg]}, exact order_of_dvd_of_pow_eq_one hgmn end⟩) ... ≤ n : let ⟨m, hm⟩ := gcd_dvd_right n (fintype.card α) in have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, (by rw [hm0, mul_zero, fintype.card_eq_zero_iff] at hm; exact hm 1)), begin rw [← set.card_fintype_of_finset' _ (λ _, set.mem_to_finset), ← order_eq_card_gpowers, order_of_pow, order_of_eq_card_of_forall_mem_gpowers hg], rw [hm] {occs := occurrences.pos [2,3]}, rw [nat.mul_div_cancel_left _ (gcd_pos_of_pos_left _ hn0), gcd_mul_left_left, hm, nat.mul_div_cancel _ hm0], exact le_of_dvd hn0 (gcd_dvd_left _ _) end section totient variables [group α] [fintype α] [decidable_eq α] (hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, a ^ n = 1)).card ≤ n) include hn lemma card_pow_eq_one_eq_order_of_aux (a : α) : (finset.univ.filter (λ b : α, b ^ order_of a = 1)).card = order_of a := le_antisymm (hn _ (order_of_pos _)) (calc order_of a = @fintype.card (gpowers a) (id _) : order_eq_card_gpowers ... ≤ @fintype.card (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (set.fintype_of_finset _ (λ _, iff.rfl)) : @fintype.card_le_of_injective (gpowers a) (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (id _) (id _) (λ b, ⟨b.1, mem_filter.2 ⟨mem_univ _, let ⟨i, hi⟩ := b.2 in by rw [← hi, ← gpow_coe_nat, ← gpow_mul, mul_comm, gpow_mul, gpow_coe_nat, pow_order_of_eq_one, one_gpow]⟩⟩) (λ _ _ h, subtype.eq (subtype.mk.inj h)) ... = (univ.filter (λ b : α, b ^ order_of a = 1)).card : set.card_fintype_of_finset _ _) open_locale nat -- use φ for nat.totient private lemma card_order_of_eq_totient_aux₁ : ∀ {d : ℕ}, d ∣ fintype.card α → 0 < (univ.filter (λ a : α, order_of a = d)).card → (univ.filter (λ a : α, order_of a = d)).card = φ d | 0 := λ hd hd0, absurd hd0 (mt card_pos.1 (by simp [finset.ext, nat.pos_iff_ne_zero.1 (order_of_pos _)])) | (d+1) := λ hd hd0, let ⟨a, ha⟩ := exists_mem_of_ne_empty (card_pos.1 hd0) in have ha : order_of a = d.succ, from (mem_filter.1 ha).2, have h : ((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) = ((range d.succ).filter (∣ d.succ)).sum φ, from finset.sum_congr rfl (λ m hm, have hmd : m < d.succ, from mem_range.1 (mem_filter.1 hm).1, have hm : m ∣ d.succ, from (mem_filter.1 hm).2, card_order_of_eq_totient_aux₁ (dvd.trans hm hd) (finset.card_pos.2 (ne_empty_of_mem (show a ^ (d.succ / m) ∈ _, from mem_filter.2 ⟨mem_univ _, by rw [order_of_pow, ha, gcd_eq_right (div_dvd_of_dvd hm), nat.div_div_self hm (succ_pos _)]⟩)))), have hinsert : insert d.succ ((range d.succ).filter (∣ d.succ)) = (range d.succ.succ).filter (∣ d.succ), from (finset.ext.2 $ λ x, ⟨λ h, (mem_insert.1 h).elim (λ h, by simp [h, range_succ]) (by clear _let_match; simp [range_succ]; tauto), by clear _let_match; simp [range_succ] {contextual := tt}; tauto⟩), have hinsert₁ : d.succ ∉ (range d.succ).filter (∣ d.succ), by simp [mem_range, zero_le_one, le_succ], (add_right_inj (((range d.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card))).1 (calc _ = (insert d.succ (filter (∣ d.succ) (range d.succ))).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (finset.sum_insert (by simp [mem_range, zero_le_one, le_succ])) ... = ((range d.succ.succ).filter (∣ d.succ)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : sum_congr hinsert (λ _ _, rfl) ... = (univ.filter (λ a : α, a ^ d.succ = 1)).card : sum_card_order_of_eq_card_pow_eq_one (succ_pos d) ... = ((range d.succ.succ).filter (∣ d.succ)).sum φ : ha ▸ (card_pow_eq_one_eq_order_of_aux hn a).symm ▸ (sum_totient _).symm ... = _ : by rw [h, ← sum_insert hinsert₁]; exact finset.sum_congr hinsert.symm (λ _ _, rfl)) lemma card_order_of_eq_totient_aux₂ {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = φ d := by_contradiction $ λ h, have h0 : (univ.filter (λ a : α , order_of a = d)).card = 0 := not_not.1 (mt nat.pos_iff_ne_zero.2 (mt (card_order_of_eq_totient_aux₁ hn hd) h)), let c := fintype.card α in have hc0 : 0 < c, from fintype.card_pos_iff.2 ⟨1⟩, lt_irrefl c $ calc c = (univ.filter (λ a : α, a ^ c = 1)).card : congr_arg card $ by simp [finset.ext, c] ... = ((range c.succ).filter (∣ c)).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : (sum_card_order_of_eq_card_pow_eq_one hc0).symm ... = (((range c.succ).filter (∣ c)).erase d).sum (λ m, (univ.filter (λ a : α, order_of a = m)).card) : eq.symm (sum_subset (erase_subset _ _) (λ m hm₁ hm₂, have m = d, by simp at *; cc, by simp [*, finset.ext] at *; exact h0)) ... ≤ (((range c.succ).filter (∣ c)).erase d).sum φ : sum_le_sum (λ m hm, have hmc : m ∣ c, by simp at hm; tauto, (imp_iff_not_or.1 (card_order_of_eq_totient_aux₁ hn hmc)).elim (λ h, by simp [nat.le_zero_iff.1 (le_of_not_gt h), nat.zero_le]) (by simp [le_refl] {contextual := tt})) ... < φ d + (((range c.succ).filter (∣ c)).erase d).sum φ : lt_add_of_pos_left _ (totient_pos (nat.pos_of_ne_zero (λ h, nat.pos_iff_ne_zero.1 hc0 (eq_zero_of_zero_dvd $ h ▸ hd)))) ... = (insert d (((range c.succ).filter (∣ c)).erase d)).sum φ : eq.symm (sum_insert (by simp)) ... = ((range c.succ).filter (∣ c)).sum φ : finset.sum_congr (finset.insert_erase (mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd hc0 hd)), hd⟩)) (λ _ _, rfl) ... = c : sum_totient _ lemma is_cyclic_of_card_pow_eq_one_le : is_cyclic α := have ∃ x, x ∈ univ.filter (λ a : α, order_of a = fintype.card α), from exists_mem_of_ne_empty (card_pos.1 $ by rw [card_order_of_eq_totient_aux₂ hn (dvd_refl _)]; exact totient_pos (fintype.card_pos_iff.2 ⟨1⟩)), let ⟨x, hx⟩ := this in is_cyclic_of_order_of_eq_card x (finset.mem_filter.1 hx).2 end totient lemma is_cyclic.card_order_of_eq_totient [group α] [is_cyclic α] [fintype α] [decidable_eq α] {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = totient d := card_order_of_eq_totient_aux₂ (λ n, is_cyclic.card_pow_eq_one_le) hd end cyclic
47f9fb0940ce5a3782786ddf464182319d107acb
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/rename.lean
00f34761d151c03cdf9a19b7db4e45764c23ce45
[ "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
869
lean
example {α β} (a : α) (b : β) : unit := begin rename a a', -- rename-compatible syntax guard_hyp a' : α, rename a' → a, -- more suggestive syntax guard_hyp a : α, rename [a a', b b'], -- parallel renaming guard_hyp a' : α, guard_hyp b' : β, rename [a' → a, b' → b], -- ditto with alternative syntax guard_hyp a : α, guard_hyp b : β, rename [a → b, b → a], -- renaming really is parallel guard_hyp a : β, guard_hyp b : α, rename b a, -- shadowing is allowed (but guard_hyp doesn't like it) rename d e, -- cannot rename nonexistent hypothesis exact () end example {α} [decidable α] (a : α) : unit := begin rename a a', -- renaming works after frozen local instances rename α α', -- renaming doesn't work before frozen local instances end
8f59dfe0dee422cdd1bcda1d7d1b03f1d9468859
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/quote_bas.lean
7ec2db38cc9da28a0a8a59ac103ae62595dad077
[ "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,528
lean
universes u v w namespace quote_bas inductive Expr (V : Type u) | One {} : Expr | Var (v : V) : Expr | Mult (a b : Expr) : Expr @[reducible] def Value := nat def Env (V : Type u) := V → Value open Expr def evalExpr {V} (vs : Env V) : Expr V → Value | One := 1 | (Var v) := vs v | (Mult a b) := evalExpr a * evalExpr b def novars : Env empty := empty.rec _ def singlevar (x : Value) : Env unit := λ _, x open sum def merge {A : Type u} {B : Type v} (a : Env A) (b : Env B) : Env (sum A B) | (inl j) := a j | (inr j) := b j def map_var {A : Type u} {B : Type v} (f : A → B) : Expr A → Expr B | One := One | (Var v) := Var (f v) | (Mult a b) := Mult (map_var a) (map_var b) def sum_assoc {A : Type u} {B : Type v} {C : Type w} : sum (sum A B) C → sum A (sum B C) | (inl (inl a)) := inl a | (inl (inr b)) := inr (inl b) | (inr c) := inr (inr c) attribute [simp] evalExpr map_var sum_assoc merge @[simp] lemma eval_map_var_shift {A : Type u} {B : Type v} (v : Env A) (v' : Env B) (e : Expr A) : evalExpr (merge v v') (map_var inl e) = evalExpr v e := begin induction e, reflexivity, reflexivity, simp_using_hs end @[simp] lemma eval_map_var_sum_assoc {A : Type u} {B : Type v} {C : Type w} (v : Env A) (v' : Env B) (v'' : Env C) (e : Expr (sum (sum A B) C)) : evalExpr (merge v (merge v' v'')) (map_var sum_assoc e) = evalExpr (merge (merge v v') v'') e := begin induction e, reflexivity, { cases v with v₁, cases v₁, all_goals {simp} }, { simp_using_hs } end class Quote {V : out_param (Type u)} (l : out_param (Env V)) (n : Value) {V' : out_param (Type v)} (r : out_param (Env V')) := (quote : Expr (sum V V')) (eval_quote : evalExpr (merge l r) quote = n) def quote {V : Type u} {l : Env V} (n : nat) {V' : Type v} {r : Env V'} [Quote l n r] : Expr (sum V V') := Quote.quote l n r @[simp] lemma eval_quote {V : Type u} {l : Env V} (n : nat) {V' : Type v} {r : Env V'} [Quote l n r] : evalExpr (merge l r) (quote n) = n := Quote.eval_quote l n r instance quote_one V (v : Env V) : Quote v 1 novars := { quote := One, eval_quote := rfl } instance quote_mul {V : Type u} (v : Env V) n {V' : Type v} (v' : Env V') m {V'' : Type w} (v'' : Env V'') [Quote v n v'] [Quote (merge v v') m v''] : Quote v (n * m) (merge v' v'') := { quote := Mult (map_var sum_assoc (map_var inl (quote n))) (map_var sum_assoc (quote m)), eval_quote := by simp } end quote_bas
f3704017e5db642941329d22fc62eab905b864d6
c777c32c8e484e195053731103c5e52af26a25d1
/src/representation_theory/Action.lean
21c36f2b712a8b7da567882233f4932073026d66
[ "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
28,577
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.category.Group.basic import category_theory.single_obj import category_theory.limits.functor_category import category_theory.limits.preserves.basic import category_theory.adjunction.limits import category_theory.monoidal.functor_category import category_theory.monoidal.transport import category_theory.monoidal.rigid.of_equivalence import category_theory.monoidal.rigid.functor_category import category_theory.monoidal.linear import category_theory.monoidal.braided import category_theory.monoidal.types import category_theory.abelian.functor_category import category_theory.abelian.transfer import category_theory.conj import category_theory.linear.functor_category /-! # `Action V G`, the category of actions of a monoid `G` inside some category `V`. The prototypical example is `V = Module R`, where `Action (Module R) G` is the category of `R`-linear representations of `G`. We check `Action V G ≌ (single_obj G ⥤ V)`, and construct the restriction functors `res {G H : Mon} (f : G ⟶ H) : Action V H ⥤ Action V G`. * When `V` has (co)limits so does `Action V G`. * When `V` is monoidal, braided, or symmetric, so is `Action V G`. * When `V` is preadditive, linear, or abelian so is `Action V G`. -/ universes u v open category_theory open category_theory.limits variables (V : Type (u+1)) [large_category V] /-- An `Action V G` represents a bundled action of the monoid `G` on an object of some category `V`. As an example, when `V = Module R`, this is an `R`-linear representation of `G`, while when `V = Type` this is a `G`-action. -/ -- Note: this is _not_ a categorical action of `G` on `V`. structure Action (G : Mon.{u}) := (V : V) (ρ : G ⟶ Mon.of (End V)) namespace Action variable {V} @[simp] lemma ρ_one {G : Mon.{u}} (A : Action V G) : A.ρ 1 = 𝟙 A.V := by { rw [monoid_hom.map_one], refl, } /-- When a group acts, we can lift the action to the group of automorphisms. -/ @[simps] def ρ_Aut {G : Group.{u}} (A : Action V (Mon.of G)) : G ⟶ Group.of (Aut A.V) := { to_fun := λ g, { hom := A.ρ g, inv := A.ρ (g⁻¹ : G), hom_inv_id' := ((A.ρ).map_mul (g⁻¹ : G) g).symm.trans (by rw [inv_mul_self, ρ_one]), inv_hom_id' := ((A.ρ).map_mul g (g⁻¹ : G)).symm.trans (by rw [mul_inv_self, ρ_one]), }, map_one' := by { ext, exact A.ρ.map_one }, map_mul' := λ x y, by { ext, exact A.ρ.map_mul x y }, } variable (G : Mon.{u}) section instance inhabited' : inhabited (Action (Type u) G) := ⟨⟨punit, 1⟩⟩ /-- The trivial representation of a group. -/ def trivial : Action AddCommGroup G := { V := AddCommGroup.of punit, ρ := 1, } instance : inhabited (Action AddCommGroup G) := ⟨trivial G⟩ end variables {G V} /-- A homomorphism of `Action V G`s is a morphism between the underlying objects, commuting with the action of `G`. -/ @[ext] structure hom (M N : Action V G) := (hom : M.V ⟶ N.V) (comm' : ∀ g : G, M.ρ g ≫ hom = hom ≫ N.ρ g . obviously) restate_axiom hom.comm' namespace hom /-- The identity morphism on a `Action V G`. -/ @[simps] def id (M : Action V G) : Action.hom M M := { hom := 𝟙 M.V } instance (M : Action V G) : inhabited (Action.hom M M) := ⟨id M⟩ /-- The composition of two `Action V G` homomorphisms is the composition of the underlying maps. -/ @[simps] def comp {M N K : Action V G} (p : Action.hom M N) (q : Action.hom N K) : Action.hom M K := { hom := p.hom ≫ q.hom, comm' := λ g, by rw [←category.assoc, p.comm, category.assoc, q.comm, ←category.assoc] } end hom instance : category (Action V G) := { hom := λ M N, hom M N, id := λ M, hom.id M, comp := λ M N K f g, hom.comp f g, } @[simp] lemma id_hom (M : Action V G) : (𝟙 M : hom M M).hom = 𝟙 M.V := rfl @[simp] lemma comp_hom {M N K : Action V G} (f : M ⟶ N) (g : N ⟶ K) : (f ≫ g : hom M K).hom = f.hom ≫ g.hom := rfl /-- Construct an isomorphism of `G` actions/representations from an isomorphism of the the underlying objects, where the forward direction commutes with the group action. -/ @[simps] def mk_iso {M N : Action V G} (f : M.V ≅ N.V) (comm : ∀ g : G, M.ρ g ≫ f.hom = f.hom ≫ N.ρ g) : M ≅ N := { hom := { hom := f.hom, comm' := comm, }, inv := { hom := f.inv, comm' := λ g, by { have w := comm g =≫ f.inv, simp at w, simp [w], }, }} @[priority 100] instance is_iso_of_hom_is_iso {M N : Action V G} (f : M ⟶ N) [is_iso f.hom] : is_iso f := by { convert is_iso.of_iso (mk_iso (as_iso f.hom) f.comm), ext, refl, } instance is_iso_hom_mk {M N : Action V G} (f : M.V ⟶ N.V) [is_iso f] (w) : @is_iso _ _ M N ⟨f, w⟩ := is_iso.of_iso (mk_iso (as_iso f) w) namespace functor_category_equivalence /-- Auxilliary definition for `functor_category_equivalence`. -/ @[simps] def functor : Action V G ⥤ (single_obj G ⥤ V) := { obj := λ M, { obj := λ _, M.V, map := λ _ _ g, M.ρ g, map_id' := λ _, M.ρ.map_one, map_comp' := λ _ _ _ g h, M.ρ.map_mul h g, }, map := λ M N f, { app := λ _, f.hom, naturality' := λ _ _ g, f.comm g, } } /-- Auxilliary definition for `functor_category_equivalence`. -/ @[simps] def inverse : (single_obj G ⥤ V) ⥤ Action V G := { obj := λ F, { V := F.obj punit.star, ρ := { to_fun := λ g, F.map g, map_one' := F.map_id punit.star, map_mul' := λ g h, F.map_comp h g, } }, map := λ M N f, { hom := f.app punit.star, comm' := λ g, f.naturality g, } }. /-- Auxilliary definition for `functor_category_equivalence`. -/ @[simps] def unit_iso : 𝟭 (Action V G) ≅ functor ⋙ inverse := nat_iso.of_components (λ M, mk_iso ((iso.refl _)) (by tidy)) (by tidy). /-- Auxilliary definition for `functor_category_equivalence`. -/ @[simps] def counit_iso : inverse ⋙ functor ≅ 𝟭 (single_obj G ⥤ V) := nat_iso.of_components (λ M, nat_iso.of_components (by tidy) (by tidy)) (by tidy). end functor_category_equivalence section open functor_category_equivalence variables (V G) /-- The category of actions of `G` in the category `V` is equivalent to the functor category `single_obj G ⥤ V`. -/ def functor_category_equivalence : Action V G ≌ (single_obj G ⥤ V) := { functor := functor, inverse := inverse, unit_iso := unit_iso, counit_iso := counit_iso, } attribute [simps] functor_category_equivalence lemma functor_category_equivalence.functor_def : (functor_category_equivalence V G).functor = functor_category_equivalence.functor := rfl lemma functor_category_equivalence.inverse_def : (functor_category_equivalence V G).inverse = functor_category_equivalence.inverse := rfl instance [has_finite_products V] : has_finite_products (Action V G) := { out := λ n, adjunction.has_limits_of_shape_of_equivalence (Action.functor_category_equivalence _ _).functor } instance [has_finite_limits V] : has_finite_limits (Action V G) := { out := λ J _ _, by exactI adjunction.has_limits_of_shape_of_equivalence (Action.functor_category_equivalence _ _).functor } instance [has_limits V] : has_limits (Action V G) := adjunction.has_limits_of_equivalence (Action.functor_category_equivalence _ _).functor instance [has_colimits V] : has_colimits (Action V G) := adjunction.has_colimits_of_equivalence (Action.functor_category_equivalence _ _).functor end section forget variables (V G) /-- (implementation) The forgetful functor from bundled actions to the underlying objects. Use the `category_theory.forget` API provided by the `concrete_category` instance below, rather than using this directly. -/ @[simps] def forget : Action V G ⥤ V := { obj := λ M, M.V, map := λ M N f, f.hom, } instance : faithful (forget V G) := { map_injective' := λ X Y f g w, hom.ext _ _ w, } instance [concrete_category V] : concrete_category (Action V G) := { forget := forget V G ⋙ (concrete_category.forget V), } instance has_forget_to_V [concrete_category V] : has_forget₂ (Action V G) V := { forget₂ := forget V G } /-- The forgetful functor is intertwined by `functor_category_equivalence` with evaluation at `punit.star`. -/ def functor_category_equivalence_comp_evaluation : (functor_category_equivalence V G).functor ⋙ (evaluation _ _).obj punit.star ≅ forget V G := iso.refl _ noncomputable instance [has_limits V] : limits.preserves_limits (forget V G) := limits.preserves_limits_of_nat_iso (Action.functor_category_equivalence_comp_evaluation V G) noncomputable instance [has_colimits V] : preserves_colimits (forget V G) := preserves_colimits_of_nat_iso (Action.functor_category_equivalence_comp_evaluation V G) -- TODO construct categorical images? end forget lemma iso.conj_ρ {M N : Action V G} (f : M ≅ N) (g : G) : N.ρ g = (((forget V G).map_iso f).conj (M.ρ g)) := by { rw [iso.conj_apply, iso.eq_inv_comp], simp [f.hom.comm'] } section has_zero_morphisms variables [has_zero_morphisms V] instance : has_zero_morphisms (Action V G) := { has_zero := λ X Y, ⟨⟨0, by { intro g, simp }⟩⟩, comp_zero' := λ P Q f R, by { ext1, simp }, zero_comp' := λ P Q R f, by { ext1, simp }, } instance forget_preserves_zero_morphisms : functor.preserves_zero_morphisms (forget V G) := {} instance forget₂_preserves_zero_morphisms [concrete_category V] : functor.preserves_zero_morphisms (forget₂ (Action V G) V) := {} instance functor_category_equivalence_preserves_zero_morphisms : functor.preserves_zero_morphisms (functor_category_equivalence V G).functor := {} end has_zero_morphisms section preadditive variables [preadditive V] instance : preadditive (Action V G) := { hom_group := λ X Y, { zero := ⟨0, by simp⟩, add := λ f g, ⟨f.hom + g.hom, by simp [f.comm, g.comm]⟩, neg := λ f, ⟨-f.hom, by simp [f.comm]⟩, zero_add := by { intros, ext, exact zero_add _, }, add_zero := by { intros, ext, exact add_zero _, }, add_assoc := by { intros, ext, exact add_assoc _ _ _, }, add_left_neg := by { intros, ext, exact add_left_neg _, }, add_comm := by { intros, ext, exact add_comm _ _, }, }, add_comp' := by { intros, ext, exact preadditive.add_comp _ _ _ _ _ _, }, comp_add' := by { intros, ext, exact preadditive.comp_add _ _ _ _ _ _, }, } instance forget_additive : functor.additive (forget V G) := {} instance forget₂_additive [concrete_category V] : functor.additive (forget₂ (Action V G) V) := {} instance functor_category_equivalence_additive : functor.additive (functor_category_equivalence V G).functor := {} @[simp] lemma zero_hom {X Y : Action V G} : (0 : X ⟶ Y).hom = 0 := rfl @[simp] lemma neg_hom {X Y : Action V G} (f : X ⟶ Y) : (-f).hom = -f.hom := rfl @[simp] lemma add_hom {X Y : Action V G} (f g : X ⟶ Y) : (f + g).hom = f.hom + g.hom := rfl @[simp] lemma sum_hom {X Y : Action V G} {ι : Type*} (f : ι → (X ⟶ Y)) (s : finset ι) : (s.sum f).hom = s.sum (λ i, (f i).hom) := (forget V G).map_sum f s end preadditive section linear variables [preadditive V] {R : Type*} [semiring R] [linear R V] instance : linear R (Action V G) := { hom_module := λ X Y, { smul := λ r f, ⟨r • f.hom, by simp [f.comm]⟩, one_smul := by { intros, ext, exact one_smul _ _, }, smul_zero := by { intros, ext, exact smul_zero _, }, zero_smul := by { intros, ext, exact zero_smul _ _, }, add_smul := by { intros, ext, exact add_smul _ _ _, }, smul_add := by { intros, ext, exact smul_add _ _ _, }, mul_smul := by { intros, ext, exact mul_smul _ _ _, }, }, smul_comp' := by { intros, ext, exact linear.smul_comp _ _ _ _ _ _, }, comp_smul' := by { intros, ext, exact linear.comp_smul _ _ _ _ _ _, }, } instance forget_linear : functor.linear R (forget V G) := {} instance forget₂_linear [concrete_category V] : functor.linear R (forget₂ (Action V G) V) := {} instance functor_category_equivalence_linear : functor.linear R (functor_category_equivalence V G).functor := {} @[simp] lemma smul_hom {X Y : Action V G} (r : R) (f : X ⟶ Y) : (r • f).hom = r • f.hom := rfl end linear section abelian /-- Auxilliary construction for the `abelian (Action V G)` instance. -/ def abelian_aux : Action V G ≌ (ulift.{u} (single_obj G) ⥤ V) := (functor_category_equivalence V G).trans (equivalence.congr_left ulift.equivalence) noncomputable instance [abelian V] : abelian (Action V G) := abelian_of_equivalence abelian_aux.functor end abelian section monoidal variables [monoidal_category V] instance : monoidal_category (Action V G) := monoidal.transport (Action.functor_category_equivalence _ _).symm @[simp] lemma tensor_unit_V : (𝟙_ (Action V G)).V = 𝟙_ V := rfl @[simp] lemma tensor_unit_rho {g : G} : (𝟙_ (Action V G)).ρ g = 𝟙 (𝟙_ V) := rfl @[simp] lemma tensor_V {X Y : Action V G} : (X ⊗ Y).V = X.V ⊗ Y.V := rfl @[simp] lemma tensor_rho {X Y : Action V G} {g : G} : (X ⊗ Y).ρ g = X.ρ g ⊗ Y.ρ g := rfl @[simp] lemma tensor_hom {W X Y Z : Action V G} (f : W ⟶ X) (g : Y ⟶ Z) : (f ⊗ g).hom = f.hom ⊗ g.hom := rfl @[simp] lemma associator_hom_hom {X Y Z : Action V G} : hom.hom (α_ X Y Z).hom = (α_ X.V Y.V Z.V).hom := begin dsimp [monoidal.transport_associator], simp, end @[simp] lemma associator_inv_hom {X Y Z : Action V G} : hom.hom (α_ X Y Z).inv = (α_ X.V Y.V Z.V).inv := begin dsimp [monoidal.transport_associator], simp, end @[simp] lemma left_unitor_hom_hom {X : Action V G} : hom.hom (λ_ X).hom = (λ_ X.V).hom := begin dsimp [monoidal.transport_left_unitor], simp, end @[simp] lemma left_unitor_inv_hom {X : Action V G} : hom.hom (λ_ X).inv = (λ_ X.V).inv := begin dsimp [monoidal.transport_left_unitor], simp, end @[simp] lemma right_unitor_hom_hom {X : Action V G} : hom.hom (ρ_ X).hom = (ρ_ X.V).hom := begin dsimp [monoidal.transport_right_unitor], simp, end @[simp] lemma right_unitor_inv_hom {X : Action V G} : hom.hom (ρ_ X).inv = (ρ_ X.V).inv := begin dsimp [monoidal.transport_right_unitor], simp, end /-- Given an object `X` isomorphic to the tensor unit of `V`, `X` equipped with the trivial action is isomorphic to the tensor unit of `Action V G`. -/ def tensor_unit_iso {X : V} (f : 𝟙_ V ≅ X) : 𝟙_ (Action V G) ≅ Action.mk X 1 := Action.mk_iso f (λ g, by simp only [monoid_hom.one_apply, End.one_def, category.id_comp f.hom, tensor_unit_rho, category.comp_id]) variables (V G) /-- When `V` is monoidal the forgetful functor `Action V G` to `V` is monoidal. -/ @[simps] def forget_monoidal : monoidal_functor (Action V G) V := { ε := 𝟙 _, μ := λ X Y, 𝟙 _, ..Action.forget _ _, } instance forget_monoidal_faithful : faithful (forget_monoidal V G).to_functor := by { change faithful (forget V G), apply_instance, } section variables [braided_category V] instance : braided_category (Action V G) := braided_category_of_faithful (forget_monoidal V G) (λ X Y, mk_iso (β_ _ _) (by tidy)) (by tidy) /-- When `V` is braided the forgetful functor `Action V G` to `V` is braided. -/ @[simps] def forget_braided : braided_functor (Action V G) V := { ..forget_monoidal _ _, } instance forget_braided_faithful : faithful (forget_braided V G).to_functor := by { change faithful (forget V G), apply_instance, } end instance [symmetric_category V] : symmetric_category (Action V G) := symmetric_category_of_faithful (forget_braided V G) section variables [preadditive V] [monoidal_preadditive V] local attribute [simp] monoidal_preadditive.tensor_add monoidal_preadditive.add_tensor instance : monoidal_preadditive (Action V G) := {} variables {R : Type*} [semiring R] [linear R V] [monoidal_linear R V] instance : monoidal_linear R (Action V G) := {} end variables (V G) noncomputable theory /-- Upgrading the functor `Action V G ⥤ (single_obj G ⥤ V)` to a monoidal functor. -/ def functor_category_monoidal_equivalence : monoidal_functor (Action V G) (single_obj G ⥤ V) := monoidal.from_transported (Action.functor_category_equivalence _ _).symm instance : is_equivalence ((functor_category_monoidal_equivalence V G).to_functor) := by { change is_equivalence (Action.functor_category_equivalence _ _).functor, apply_instance, } @[simp] lemma functor_category_monoidal_equivalence.μ_app (A B : Action V G) : ((functor_category_monoidal_equivalence V G).μ A B).app punit.star = 𝟙 _ := begin dunfold functor_category_monoidal_equivalence, simp only [monoidal.from_transported_to_lax_monoidal_functor_μ], show (𝟙 A.V ⊗ 𝟙 B.V) ≫ 𝟙 (A.V ⊗ B.V) ≫ (𝟙 A.V ⊗ 𝟙 B.V) = 𝟙 (A.V ⊗ B.V), simp only [monoidal_category.tensor_id, category.comp_id], end @[simp] lemma functor_category_monoidal_equivalence.μ_iso_inv_app (A B : Action V G) : ((functor_category_monoidal_equivalence V G).μ_iso A B).inv.app punit.star = 𝟙 _ := begin rw [←nat_iso.app_inv, ←is_iso.iso.inv_hom], refine is_iso.inv_eq_of_hom_inv_id _, rw [category.comp_id, nat_iso.app_hom, monoidal_functor.μ_iso_hom, functor_category_monoidal_equivalence.μ_app], end @[simp] lemma functor_category_monoidal_equivalence.ε_app : (functor_category_monoidal_equivalence V G).ε.app punit.star = 𝟙 _ := begin dunfold functor_category_monoidal_equivalence, simp only [monoidal.from_transported_to_lax_monoidal_functor_ε], show 𝟙 (monoidal_category.tensor_unit V) ≫ _ = 𝟙 (monoidal_category.tensor_unit V), rw [nat_iso.is_iso_inv_app, category.id_comp], exact is_iso.inv_id, end @[simp] lemma functor_category_monoidal_equivalence.inv_counit_app_hom (A : Action V G) : ((functor_category_monoidal_equivalence _ _).inv.adjunction.counit.app A).hom = 𝟙 _ := rfl @[simp] lemma functor_category_monoidal_equivalence.counit_app (A : single_obj G ⥤ V) : ((functor_category_monoidal_equivalence _ _).adjunction.counit.app A).app punit.star = 𝟙 _ := rfl @[simp] lemma functor_category_monoidal_equivalence.inv_unit_app_app (A : single_obj G ⥤ V) : ((functor_category_monoidal_equivalence _ _).inv.adjunction.unit.app A).app punit.star = 𝟙 _ := rfl @[simp] lemma functor_category_monoidal_equivalence.unit_app_hom (A : Action V G) : ((functor_category_monoidal_equivalence _ _).adjunction.unit.app A).hom = 𝟙 _ := rfl @[simp] lemma functor_category_monoidal_equivalence.functor_map {A B : Action V G} (f : A ⟶ B) : (functor_category_monoidal_equivalence _ _).map f = functor_category_equivalence.functor.map f := rfl @[simp] lemma functor_category_monoidal_equivalence.inverse_map {A B : single_obj G ⥤ V} (f : A ⟶ B) : (functor_category_monoidal_equivalence _ _).inv.map f = functor_category_equivalence.inverse.map f := rfl variables (H : Group.{u}) instance [right_rigid_category V] : right_rigid_category (single_obj (H : Mon.{u}) ⥤ V) := by { change right_rigid_category (single_obj H ⥤ V), apply_instance } /-- If `V` is right rigid, so is `Action V G`. -/ instance [right_rigid_category V] : right_rigid_category (Action V H) := right_rigid_category_of_equivalence (functor_category_monoidal_equivalence V _) instance [left_rigid_category V] : left_rigid_category (single_obj (H : Mon.{u}) ⥤ V) := by { change left_rigid_category (single_obj H ⥤ V), apply_instance } /-- If `V` is left rigid, so is `Action V G`. -/ instance [left_rigid_category V] : left_rigid_category (Action V H) := left_rigid_category_of_equivalence (functor_category_monoidal_equivalence V _) instance [rigid_category V] : rigid_category (single_obj (H : Mon.{u}) ⥤ V) := by { change rigid_category (single_obj H ⥤ V), apply_instance } /-- If `V` is rigid, so is `Action V G`. -/ instance [rigid_category V] : rigid_category (Action V H) := rigid_category_of_equivalence (functor_category_monoidal_equivalence V _) variables {V H} (X : Action V H) @[simp] lemma right_dual_V [right_rigid_category V] : (Xᘁ).V = (X.V)ᘁ := rfl @[simp] lemma left_dual_V [left_rigid_category V] : (ᘁX).V = ᘁ(X.V) := rfl @[simp] lemma right_dual_ρ [right_rigid_category V] (h : H) : (Xᘁ).ρ h = (X.ρ (h⁻¹ : H))ᘁ := by { rw ←single_obj.inv_as_inv, refl } @[simp] lemma left_dual_ρ [left_rigid_category V] (h : H) : (ᘁX).ρ h = ᘁ(X.ρ (h⁻¹ : H)) := by { rw ←single_obj.inv_as_inv, refl } end monoidal /-- Actions/representations of the trivial group are just objects in the ambient category. -/ def Action_punit_equivalence : Action V (Mon.of punit) ≌ V := { functor := forget V _, inverse := { obj := λ X, ⟨X, 1⟩, map := λ X Y f, ⟨f, λ ⟨⟩, by simp⟩, }, unit_iso := nat_iso.of_components (λ X, mk_iso (iso.refl _) (λ ⟨⟩, by simpa using ρ_one X)) (by tidy), counit_iso := nat_iso.of_components (λ X, iso.refl _) (by tidy), } variables (V) /-- The "restriction" functor along a monoid homomorphism `f : G ⟶ H`, taking actions of `H` to actions of `G`. (This makes sense for any homomorphism, but the name is natural when `f` is a monomorphism.) -/ @[simps] def res {G H : Mon} (f : G ⟶ H) : Action V H ⥤ Action V G := { obj := λ M, { V := M.V, ρ := f ≫ M.ρ }, map := λ M N p, { hom := p.hom, comm' := λ g, p.comm (f g) } } /-- The natural isomorphism from restriction along the identity homomorphism to the identity functor on `Action V G`. -/ def res_id {G : Mon} : res V (𝟙 G) ≅ 𝟭 (Action V G) := nat_iso.of_components (λ M, mk_iso (iso.refl _) (by tidy)) (by tidy) attribute [simps] res_id /-- The natural isomorphism from the composition of restrictions along homomorphisms to the restriction along the composition of homomorphism. -/ def res_comp {G H K : Mon} (f : G ⟶ H) (g : H ⟶ K) : res V g ⋙ res V f ≅ res V (f ≫ g) := nat_iso.of_components (λ M, mk_iso (iso.refl _) (by tidy)) (by tidy) attribute [simps] res_comp -- TODO promote `res` to a pseudofunctor from -- the locally discrete bicategory constructed from `Monᵒᵖ` to `Cat`, sending `G` to `Action V G`. variables {G} {H : Mon.{u}} (f : G ⟶ H) instance res_additive [preadditive V] : (res V f).additive := {} variables {R : Type*} [semiring R] instance res_linear [preadditive V] [linear R V] : (res V f).linear R := {} /-- Bundles a type `H` with a multiplicative action of `G` as an `Action`. -/ def of_mul_action (G H : Type u) [monoid G] [mul_action G H] : Action (Type u) (Mon.of G) := { V := H, ρ := @mul_action.to_End_hom _ _ _ (by assumption) } @[simp] lemma of_mul_action_apply {G H : Type u} [monoid G] [mul_action G H] (g : G) (x : H) : (of_mul_action G H).ρ g x = (g • x : H) := rfl /-- Given a family `F` of types with `G`-actions, this is the limit cone demonstrating that the product of `F` as types is a product in the category of `G`-sets. -/ def of_mul_action_limit_cone {ι : Type v} (G : Type (max v u)) [monoid G] (F : ι → Type (max v u)) [Π i : ι, mul_action G (F i)] : limit_cone (discrete.functor (λ i : ι, Action.of_mul_action G (F i))) := { cone := { X := Action.of_mul_action G (Π i : ι, F i), π := { app := λ i, ⟨λ x, x i.as, λ g, by ext; refl⟩, naturality' := λ i j x, begin ext, discrete_cases, cases x, congr end } }, is_limit := { lift := λ s, { hom := λ x i, (s.π.app ⟨i⟩).hom x, comm' := λ g, begin ext x j, dsimp, exact congr_fun ((s.π.app ⟨j⟩).comm g) x, end }, fac' := λ s j, begin ext, dsimp, congr, rw discrete.mk_as, end, uniq' := λ s f h, begin ext x j, dsimp at *, rw ←h ⟨j⟩, congr, end } } /-- The `G`-set `G`, acting on itself by left multiplication. -/ @[simps] def left_regular (G : Type u) [monoid G] : Action (Type u) (Mon.of G) := Action.of_mul_action G G /-- The `G`-set `Gⁿ`, acting on itself by left multiplication. -/ @[simps] def diagonal (G : Type u) [monoid G] (n : ℕ) : Action (Type u) (Mon.of G) := Action.of_mul_action G (fin n → G) /-- We have `fin 1 → G ≅ G` as `G`-sets, with `G` acting by left multiplication. -/ def diagonal_one_iso_left_regular (G : Type u) [monoid G] : diagonal G 1 ≅ left_regular G := Action.mk_iso (equiv.fun_unique _ _).to_iso (λ g, rfl) /-- Given `X : Action (Type u) (Mon.of G)` for `G` a group, then `G × X` (with `G` acting as left multiplication on the first factor and by `X.ρ` on the second) is isomorphic as a `G`-set to `G × X` (with `G` acting as left multiplication on the first factor and trivially on the second). The isomorphism is given by `(g, x) ↦ (g, g⁻¹ • x)`. -/ @[simps] def left_regular_tensor_iso (G : Type u) [group G] (X : Action (Type u) (Mon.of G)) : left_regular G ⊗ X ≅ left_regular G ⊗ Action.mk X.V 1 := { hom := { hom := λ g, ⟨g.1, (X.ρ (g.1⁻¹ : G) g.2 : X.V)⟩, comm' := λ g, funext $ λ x, prod.ext rfl $ show (X.ρ ((g * x.1)⁻¹ : G) * X.ρ g) x.2 = _, by simpa only [mul_inv_rev, ←X.ρ.map_mul, inv_mul_cancel_right] }, inv := { hom := λ g, ⟨g.1, X.ρ g.1 g.2⟩, comm' := λ g, funext $ λ x, prod.ext rfl $ by simpa only [tensor_rho, types_comp_apply, tensor_apply, left_regular_ρ_apply, map_mul] }, hom_inv_id' := hom.ext _ _ (funext $ λ x, prod.ext rfl $ show (X.ρ x.1 * X.ρ (x.1⁻¹ : G)) x.2 = _, by simpa only [←X.ρ.map_mul, mul_inv_self, X.ρ.map_one]), inv_hom_id' := hom.ext _ _ (funext $ λ x, prod.ext rfl $ show (X.ρ (x.1⁻¹ : G) * X.ρ x.1) _ = _, by simpa only [←X.ρ.map_mul, inv_mul_self, X.ρ.map_one]) } /-- The natural isomorphism of `G`-sets `Gⁿ⁺¹ ≅ G × Gⁿ`, where `G` acts by left multiplication on each factor. -/ @[simps] def diagonal_succ (G : Type u) [monoid G] (n : ℕ) : diagonal G (n + 1) ≅ left_regular G ⊗ diagonal G n := mk_iso (equiv.pi_fin_succ_above_equiv _ 0).to_iso (λ g, rfl) end Action namespace category_theory.functor variables {V} {W : Type (u+1)} [large_category W] /-- A functor between categories induces a functor between the categories of `G`-actions within those categories. -/ @[simps] def map_Action (F : V ⥤ W) (G : Mon.{u}) : Action V G ⥤ Action W G := { obj := λ M, { V := F.obj M.V, ρ := { to_fun := λ g, F.map (M.ρ g), map_one' := by simp only [End.one_def, Action.ρ_one, F.map_id], map_mul' := λ g h, by simp only [End.mul_def, F.map_comp, map_mul], }, }, map := λ M N f, { hom := F.map f.hom, comm' := λ g, by { dsimp, rw [←F.map_comp, f.comm, F.map_comp], }, }, map_id' := λ M, by { ext, simp only [Action.id_hom, F.map_id], }, map_comp' := λ M N P f g, by { ext, simp only [Action.comp_hom, F.map_comp], }, } variables (F : V ⥤ W) (G : Mon.{u}) [preadditive V] [preadditive W] instance map_Action_preadditive [F.additive] : (F.map_Action G).additive := {} variables {R : Type*} [semiring R] [category_theory.linear R V] [category_theory.linear R W] instance map_Action_linear [F.additive] [F.linear R] : (F.map_Action G).linear R := {} end category_theory.functor namespace category_theory.monoidal_functor open Action variables {V} {W : Type (u+1)} [large_category W] [monoidal_category V] [monoidal_category W] (F : monoidal_functor V W) (G : Mon.{u}) /-- A monoidal functor induces a monoidal functor between the categories of `G`-actions within those categories. -/ @[simps] def map_Action : monoidal_functor (Action V G) (Action W G) := { ε := { hom := F.ε, comm' := λ g, by { dsimp, erw [category.id_comp, category_theory.functor.map_id, category.comp_id], }, }, μ := λ X Y, { hom := F.μ X.V Y.V, comm' := λ g, F.to_lax_monoidal_functor.μ_natural (X.ρ g) (Y.ρ g), }, ε_is_iso := by apply_instance, μ_is_iso := by apply_instance, μ_natural' := by { intros, ext, dsimp, simp, }, associativity' := by { intros, ext, dsimp, simp, dsimp, simp, }, -- See note [dsimp, simp]. left_unitality' := by { intros, ext, dsimp, simp, dsimp, simp, }, right_unitality' := by { intros, ext, dsimp, simp, dsimp, simp, }, ..F.to_functor.map_Action G, } @[simp] lemma map_Action_ε_inv_hom : (inv (F.map_Action G).ε).hom = inv F.ε := begin ext, simp only [←F.map_Action_to_lax_monoidal_functor_ε_hom G, ←Action.comp_hom, is_iso.hom_inv_id, id_hom], end @[simp] lemma map_Action_μ_inv_hom (X Y : Action V G) : (inv ((F.map_Action G).μ X Y)).hom = inv (F.μ X.V Y.V) := begin ext, simpa only [←F.map_Action_to_lax_monoidal_functor_μ_hom G, ←Action.comp_hom, is_iso.hom_inv_id, id_hom], end end category_theory.monoidal_functor
6304f02049db048173f1763c9a719271659dc56b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/int/basic.lean
51234c03666f3369579e6fc72c7251a31237a96c
[]
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
44,459
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.basic import Mathlib.algebra.order_functions import Mathlib.PostPort universes u_1 u namespace Mathlib namespace int protected instance inhabited : Inhabited ℤ := { default := int.zero } protected instance nontrivial : nontrivial ℤ := nontrivial.mk (Exists.intro 0 (Exists.intro 1 int.zero_ne_one)) protected instance comm_ring : comm_ring ℤ := comm_ring.mk int.add int.add_assoc int.zero int.zero_add int.add_zero int.neg int.sub int.add_left_neg int.add_comm int.mul int.mul_assoc int.one int.one_mul int.mul_one int.distrib_left int.distrib_right int.mul_comm /-! ### Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core protected instance add_comm_monoid : add_comm_monoid ℤ := add_comm_group.to_add_comm_monoid ℤ protected instance add_monoid : add_monoid ℤ := sub_neg_monoid.to_add_monoid ℤ protected instance monoid : monoid ℤ := ring.to_monoid ℤ protected instance comm_monoid : comm_monoid ℤ := comm_semiring.to_comm_monoid ℤ protected instance comm_semigroup : comm_semigroup ℤ := comm_ring.to_comm_semigroup ℤ protected instance semigroup : semigroup ℤ := monoid.to_semigroup ℤ protected instance add_comm_semigroup : add_comm_semigroup ℤ := add_comm_monoid.to_add_comm_semigroup ℤ protected instance add_semigroup : add_semigroup ℤ := add_monoid.to_add_semigroup ℤ protected instance comm_semiring : comm_semiring ℤ := comm_ring.to_comm_semiring protected instance semiring : semiring ℤ := ring.to_semiring protected instance ring : ring ℤ := comm_ring.to_ring ℤ protected instance distrib : distrib ℤ := ring.to_distrib ℤ protected instance linear_ordered_comm_ring : linear_ordered_comm_ring ℤ := linear_ordered_comm_ring.mk comm_ring.add comm_ring.add_assoc comm_ring.zero comm_ring.zero_add comm_ring.add_zero comm_ring.neg comm_ring.sub comm_ring.add_left_neg comm_ring.add_comm comm_ring.mul comm_ring.mul_assoc comm_ring.one comm_ring.one_mul comm_ring.mul_one comm_ring.left_distrib comm_ring.right_distrib linear_order.le linear_order.lt linear_order.le_refl linear_order.le_trans linear_order.le_antisymm int.add_le_add_left sorry int.mul_pos linear_order.le_total linear_order.decidable_le linear_order.decidable_eq linear_order.decidable_lt nontrivial.exists_pair_ne comm_ring.mul_comm protected instance linear_ordered_add_comm_group : linear_ordered_add_comm_group ℤ := linear_ordered_ring.to_linear_ordered_add_comm_group theorem abs_eq_nat_abs (a : ℤ) : abs a = ↑(nat_abs a) := int.cases_on a (fun (a : ℕ) => idRhs (abs ↑a = ↑a) (abs_of_nonneg (coe_zero_le a))) fun (a : ℕ) => idRhs (abs (Int.negSucc a) = -Int.negSucc a) (abs_of_nonpos (le_of_lt (neg_succ_lt_zero a))) theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs (abs a) = nat_abs a)) (abs_eq_nat_abs a))) (Eq.refl (nat_abs ↑(nat_abs a))) theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := eq.mpr (id (Eq._oldrec (Eq.refl (sign a * abs a = a)) (abs_eq_nat_abs a))) (eq.mpr (id (Eq._oldrec (Eq.refl (sign a * ↑(nat_abs a) = a)) (sign_mul_nat_abs a))) (Eq.refl a)) @[simp] theorem default_eq_zero : Inhabited.default = 0 := rfl @[simp] theorem add_def {a : ℤ} {b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a : ℤ} {b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m : ℕ) (n : ℕ) : ↑m * Int.negSucc n = -(↑m * ↑(Nat.succ n)) := rfl @[simp] theorem neg_succ_mul_coe_nat (m : ℕ) (n : ℕ) : Int.negSucc m * ↑n = -(↑(Nat.succ m) * ↑n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m : ℕ) (n : ℕ) : Int.negSucc m * Int.negSucc n = ↑(Nat.succ m) * ↑(Nat.succ n) := rfl @[simp] theorem coe_nat_le {m : ℕ} {n : ℕ} : ↑m ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp] theorem coe_nat_lt {m : ℕ} {n : ℕ} : ↑m < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp] theorem coe_nat_inj' {m : ℕ} {n : ℕ} : ↑m = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : 0 < ↑n ↔ 0 < n := eq.mpr (id (Eq._oldrec (Eq.refl (0 < ↑n ↔ 0 < n)) (Eq.symm int.coe_nat_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑0 < ↑n ↔ 0 < n)) (propext coe_nat_lt))) (iff.refl (0 < n))) @[simp] theorem coe_nat_eq_zero {n : ℕ} : ↑n = 0 ↔ n = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (↑n = 0 ↔ n = 0)) (Eq.symm int.coe_nat_zero))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑n = ↑0 ↔ n = 0)) (propext coe_nat_inj'))) (iff.refl (n = 0))) theorem coe_nat_ne_zero {n : ℕ} : ↑n ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero @[simp] theorem coe_nat_nonneg (n : ℕ) : 0 ≤ ↑n := iff.mpr coe_nat_le (nat.zero_le n) theorem coe_nat_ne_zero_iff_pos {n : ℕ} : ↑n ≠ 0 ↔ 0 < n := { mp := fun (h : ↑n ≠ 0) => nat.pos_of_ne_zero (iff.mp coe_nat_ne_zero h), mpr := fun (h : 0 < n) => ne.symm (ne_of_lt (iff.mpr coe_nat_lt h)) } theorem coe_nat_succ_pos (n : ℕ) : 0 < ↑(Nat.succ n) := iff.mpr coe_nat_pos (nat.succ_pos n) @[simp] theorem coe_nat_abs (n : ℕ) : abs ↑n = ↑n := abs_of_nonneg (coe_nat_nonneg n) /-! ### succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) : ℤ := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) : ℤ := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : ↑(Nat.succ n) = succ ↑n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel a 1 theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel a 1 theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add a 1 theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := eq.mpr (id (Eq._oldrec (Eq.refl (succ (-succ a) = -a)) (neg_succ a))) (eq.mpr (id (Eq._oldrec (Eq.refl (succ (pred (-a)) = -a)) (succ_pred (-a)))) (Eq.refl (-a))) theorem neg_pred (a : ℤ) : -pred a = succ (-a) := eq.mpr (id (Eq._oldrec (Eq.refl (-pred a = succ (-a))) (eq_neg_of_eq_neg (Eq.symm (neg_succ (-a)))))) (eq.mpr (id (Eq._oldrec (Eq.refl (-pred a = -pred ( --a))) (neg_neg a))) (Eq.refl (-pred a))) theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := eq.mpr (id (Eq._oldrec (Eq.refl (pred (-pred a) = -a)) (neg_pred a))) (eq.mpr (id (Eq._oldrec (Eq.refl (pred (succ (-a)) = -a)) (pred_succ (-a)))) (Eq.refl (-a))) theorem pred_nat_succ (n : ℕ) : pred ↑(Nat.succ n) = ↑n := pred_succ ↑n theorem neg_nat_succ (n : ℕ) : -↑(Nat.succ n) = pred (-↑n) := neg_succ ↑n theorem succ_neg_nat_succ (n : ℕ) : succ (-↑(Nat.succ n)) = -↑n := succ_neg_succ ↑n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right a zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self a zero_lt_one theorem add_one_le_iff {a : ℤ} {b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a : ℤ} {b : ℤ} : a < b + 1 ↔ a ≤ b := add_le_add_iff_right 1 theorem le_add_one {a : ℤ} {b : ℤ} (h : a ≤ b) : a ≤ b + 1 := le_of_lt (iff.mpr lt_add_one_iff h) theorem sub_one_lt_iff {a : ℤ} {b : ℤ} : a - 1 < b ↔ a ≤ b := iff.trans sub_lt_iff_lt_add lt_add_one_iff theorem le_sub_one_iff {a : ℤ} {b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le protected theorem induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀ (i : ℕ), p ↑i → p (↑i + 1)) (hn : ∀ (i : ℕ), p (-↑i) → p (-↑i - 1)) : p i := sorry /-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater than `b`, and the `pred` of a number less than `b`. -/ protected def induction_on' {C : ℤ → Sort u_1} (z : ℤ) (b : ℤ) : C b → ((k : ℤ) → b ≤ k → C k → C (k + 1)) → ((k : ℤ) → k ≤ b → C k → C (k - 1)) → C z := fun (H0 : C b) (Hs : (k : ℤ) → b ≤ k → C k → C (k + 1)) (Hp : (k : ℤ) → k ≤ b → C k → C (k - 1)) => eq.mpr sorry (Int.rec (fun (n : ℕ) => Nat.rec (eq.mpr sorry (eq.mpr sorry H0)) (fun (n : ℕ) (ih : C (Int.ofNat n + b)) => eq.mpr sorry (eq.mpr sorry (eq.mpr sorry (eq.mpr sorry (Hs (Int.ofNat n + b) sorry ih))))) n) (fun (n : ℕ) => Nat.rec (eq.mpr sorry (eq.mpr sorry (eq.mpr sorry (eq.mpr sorry (eq.mpr sorry (Hp b sorry H0)))))) (fun (n : ℕ) (ih : C (Int.negSucc n + b)) => eq.mpr sorry (eq.mpr sorry (eq.mpr sorry (eq.mpr sorry (Hp (Int.negSucc n + b) sorry ih))))) n) (z - b)) /-! ### nat abs -/ theorem nat_abs_add_le (a : ℤ) (b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := sorry theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := nat.cases_on n (Eq.refl (nat_abs (neg_of_nat 0))) fun (n : ℕ) => Eq.refl (nat_abs (neg_of_nat (Nat.succ n))) theorem nat_abs_mul (a : ℤ) (b : ℤ) : nat_abs (a * b) = nat_abs a * nat_abs b := sorry theorem nat_abs_mul_nat_abs_eq {a : ℤ} {b : ℤ} {c : ℕ} (h : a * b = ↑c) : nat_abs a * nat_abs b = c := eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs a * nat_abs b = c)) (Eq.symm (nat_abs_mul a b)))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs (a * b) = c)) h)) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs ↑c = c)) (nat_abs_of_nat c))) (Eq.refl c))) @[simp] theorem nat_abs_mul_self' (a : ℤ) : ↑(nat_abs a) * ↑(nat_abs a) = a * a := eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_abs a) * ↑(nat_abs a) = a * a)) (Eq.symm (int.coe_nat_mul (nat_abs a) (nat_abs a))))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(nat_abs a * nat_abs a) = a * a)) nat_abs_mul_self)) (Eq.refl (a * a))) theorem neg_succ_of_nat_eq' (m : ℕ) : Int.negSucc m = -↑m - 1 := sorry theorem nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : nat_abs z ≠ 0 := fun (h : nat_abs z = 0) => hz (eq_zero_of_nat_abs_eq_zero h) @[simp] theorem nat_abs_eq_zero {a : ℤ} : nat_abs a = 0 ↔ a = 0 := { mp := eq_zero_of_nat_abs_eq_zero, mpr := fun (h : a = 0) => Eq.symm h ▸ rfl } theorem nat_abs_lt_nat_abs_of_nonneg_of_lt {a : ℤ} {b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : nat_abs a < nat_abs b := sorry theorem nat_abs_eq_iff_mul_self_eq {a : ℤ} {b : ℤ} : nat_abs a = nat_abs b ↔ a * a = b * b := sorry theorem nat_abs_lt_iff_mul_self_lt {a : ℤ} {b : ℤ} : nat_abs a < nat_abs b ↔ a * a < b * b := sorry theorem nat_abs_le_iff_mul_self_le {a : ℤ} {b : ℤ} : nat_abs a ≤ nat_abs b ↔ a * a ≤ b * b := sorry theorem nat_abs_eq_iff_sq_eq {a : ℤ} {b : ℤ} : nat_abs a = nat_abs b ↔ a ^ bit0 1 = b ^ bit0 1 := eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs a = nat_abs b ↔ a ^ bit0 1 = b ^ bit0 1)) (pow_two a))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs a = nat_abs b ↔ a * a = b ^ bit0 1)) (pow_two b))) nat_abs_eq_iff_mul_self_eq) theorem nat_abs_lt_iff_sq_lt {a : ℤ} {b : ℤ} : nat_abs a < nat_abs b ↔ a ^ bit0 1 < b ^ bit0 1 := eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs a < nat_abs b ↔ a ^ bit0 1 < b ^ bit0 1)) (pow_two a))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs a < nat_abs b ↔ a * a < b ^ bit0 1)) (pow_two b))) nat_abs_lt_iff_mul_self_lt) theorem nat_abs_le_iff_sq_le {a : ℤ} {b : ℤ} : nat_abs a ≤ nat_abs b ↔ a ^ bit0 1 ≤ b ^ bit0 1 := eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs a ≤ nat_abs b ↔ a ^ bit0 1 ≤ b ^ bit0 1)) (pow_two a))) (eq.mpr (id (Eq._oldrec (Eq.refl (nat_abs a ≤ nat_abs b ↔ a * a ≤ b ^ bit0 1)) (pow_two b))) nat_abs_le_iff_mul_self_le) /-! ### `/` -/ @[simp] theorem of_nat_div (m : ℕ) (n : ℕ) : Int.ofNat (m / n) = Int.ofNat m / Int.ofNat n := rfl @[simp] theorem coe_nat_div (m : ℕ) (n : ℕ) : ↑(m / n) = ↑m / ↑n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : Int.negSucc m / b = -(↑m / b + 1) := sorry @[simp] protected theorem div_neg (a : ℤ) (b : ℤ) : a / -b = -(a / b) := sorry theorem div_of_neg_of_pos {a : ℤ} {b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := sorry protected theorem div_nonneg {a : ℤ} {b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := sorry protected theorem div_nonpos {a : ℤ} {b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg (eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ -(a / b))) (Eq.symm (int.div_neg a b)))) (int.div_nonneg Ha (neg_nonneg_of_nonpos Hb))) theorem div_neg' {a : ℤ} {b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := sorry -- Will be generalized to Euclidean domains. protected theorem zero_div (b : ℤ) : 0 / b = 0 := int.cases_on b (fun (b : ℕ) => nat.cases_on b (idRhs (0 / 0 = 0 / 0) rfl) fun (b : ℕ) => idRhs (0 / ↑(b + 1) = 0 / ↑(b + 1)) rfl) fun (b : ℕ) => idRhs (0 / Int.negSucc b = 0 / Int.negSucc b) rfl protected theorem div_zero (a : ℤ) : a / 0 = 0 := int.cases_on a (fun (a : ℕ) => nat.cases_on a (idRhs (0 / 0 = 0 / 0) rfl) fun (a : ℕ) => idRhs (↑(a + 1) / 0 = ↑(a + 1) / 0) rfl) fun (a : ℕ) => idRhs (Int.negSucc a / 0 = Int.negSucc a / 0) rfl @[simp] protected theorem div_one (a : ℤ) : a / 1 = a := sorry theorem div_eq_zero_of_lt {a : ℤ} {b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := sorry theorem div_eq_zero_of_lt_abs {a : ℤ} {b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := sorry protected theorem add_mul_div_right (a : ℤ) (b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := sorry protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := eq.mpr (id (Eq._oldrec (Eq.refl ((a + b * c) / b = a / b + c)) (mul_comm b c))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a + c * b) / b = a / b + c)) (int.add_mul_div_right a c H))) (Eq.refl (a / b + c))) protected theorem add_div_of_dvd_right {a : ℤ} {b : ℤ} {c : ℤ} (H : c ∣ b) : (a + b) / c = a / c + b / c := sorry protected theorem add_div_of_dvd_left {a : ℤ} {b : ℤ} {c : ℤ} (H : c ∣ a) : (a + b) / c = a / c + b / c := sorry @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := eq.mp (Eq._oldrec (Eq.refl (a * b / b = 0 + a)) (zero_add a)) (eq.mp (Eq._oldrec (Eq.refl (a * b / b = 0 / b + a)) (int.zero_div b)) (eq.mp (Eq._oldrec (Eq.refl ((0 + a * b) / b = 0 / b + a)) (zero_add (a * b))) (int.add_mul_div_right 0 a H))) @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := eq.mpr (id (Eq._oldrec (Eq.refl (a * b / a = b)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a / a = b)) (int.mul_div_cancel b H))) (Eq.refl b)) @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := eq.mp (Eq._oldrec (Eq.refl (1 * a / a = 1)) (one_mul a)) (int.mul_div_cancel 1 H) /-! ### mod -/ theorem of_nat_mod (m : ℕ) (n : ℕ) : ↑m % ↑n = Int.ofNat (m % n) := rfl @[simp] theorem coe_nat_mod (m : ℕ) (n : ℕ) : ↑(m % n) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : Int.negSucc m % b = b - 1 - ↑m % b := sorry @[simp] theorem mod_neg (a : ℤ) (b : ℤ) : a % -b = a % b := sorry @[simp] theorem mod_abs (a : ℤ) (b : ℤ) : a % abs b = a % b := abs_by_cases (fun (i : ℤ) => a % i = a % b) rfl (mod_neg a b) theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg Int.ofNat (nat.zero_mod (nat_abs b)) theorem mod_zero (a : ℤ) : a % 0 = a := int.cases_on a (fun (a : ℕ) => idRhs (Int.ofNat (a % 0) = Int.ofNat a) (congr_arg Int.ofNat (nat.mod_zero a))) fun (a : ℕ) => idRhs (Int.negSucc (a % 0) = Int.negSucc a) (congr_arg Int.negSucc (nat.mod_zero a)) theorem mod_one (a : ℤ) : a % 1 = 0 := sorry theorem mod_eq_of_lt {a : ℤ} {b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := sorry theorem mod_nonneg (a : ℤ) {b : ℤ} : b ≠ 0 → 0 ≤ a % b := sorry theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := sorry theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := eq.mpr (id (Eq._oldrec (Eq.refl (a % b < abs b)) (Eq.symm (mod_abs a b)))) (mod_lt_of_pos a (iff.mpr abs_pos H)) theorem mod_add_div_aux (m : ℕ) (n : ℕ) : ↑n - (↑m % ↑n + 1) - (↑n * (↑m / ↑n) + ↑n) = Int.negSucc m := sorry theorem mod_add_div (a : ℤ) (b : ℤ) : a % b + b * (a / b) = a := sorry theorem div_add_mod (a : ℤ) (b : ℤ) : b * (a / b) + a % b = a := Eq.trans (add_comm (b * (a / b)) (a % b)) (mod_add_div a b) theorem mod_def (a : ℤ) (b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div a b) @[simp] theorem add_mul_mod_self {a : ℤ} {b : ℤ} {c : ℤ} : (a + b * c) % c = a % c := sorry @[simp] theorem add_mul_mod_self_left (a : ℤ) (b : ℤ) (c : ℤ) : (a + b * c) % b = a % b := eq.mpr (id (Eq._oldrec (Eq.refl ((a + b * c) % b = a % b)) (mul_comm b c))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a + c * b) % b = a % b)) add_mul_mod_self)) (Eq.refl (a % b))) @[simp] theorem add_mod_self {a : ℤ} {b : ℤ} : (a + b) % b = a % b := eq.mp (Eq._oldrec (Eq.refl ((a + b * 1) % b = a % b)) (mul_one b)) (add_mul_mod_self_left a b 1) @[simp] theorem add_mod_self_left {a : ℤ} {b : ℤ} : (a + b) % a = b % a := eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % a = b % a)) (add_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl ((b + a) % a = b % a)) add_mod_self)) (Eq.refl (b % a))) @[simp] theorem mod_add_mod (m : ℤ) (n : ℤ) (k : ℤ) : (m % n + k) % n = (m + k) % n := sorry @[simp] theorem add_mod_mod (m : ℤ) (n : ℤ) (k : ℤ) : (m + n % k) % k = (m + n) % k := eq.mpr (id (Eq._oldrec (Eq.refl ((m + n % k) % k = (m + n) % k)) (add_comm m (n % k)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((n % k + m) % k = (m + n) % k)) (mod_add_mod n k m))) (eq.mpr (id (Eq._oldrec (Eq.refl ((n + m) % k = (m + n) % k)) (add_comm n m))) (Eq.refl ((m + n) % k)))) theorem add_mod (a : ℤ) (b : ℤ) (n : ℤ) : (a + b) % n = (a % n + b % n) % n := eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % n = (a % n + b % n) % n)) (add_mod_mod (a % n) b n))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a + b) % n = (a % n + b) % n)) (mod_add_mod a n b))) (Eq.refl ((a + b) % n))) theorem add_mod_eq_add_mod_right {m : ℤ} {n : ℤ} {k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := eq.mpr (id (Eq._oldrec (Eq.refl ((m + i) % n = (k + i) % n)) (Eq.symm (mod_add_mod m n i)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((m % n + i) % n = (k + i) % n)) (Eq.symm (mod_add_mod k n i)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((m % n + i) % n = (k % n + i) % n)) H)) (Eq.refl ((k % n + i) % n)))) theorem add_mod_eq_add_mod_left {m : ℤ} {n : ℤ} {k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := eq.mpr (id (Eq._oldrec (Eq.refl ((i + m) % n = (i + k) % n)) (add_comm i m))) (eq.mpr (id (Eq._oldrec (Eq.refl ((m + i) % n = (i + k) % n)) (add_mod_eq_add_mod_right i H))) (eq.mpr (id (Eq._oldrec (Eq.refl ((k + i) % n = (i + k) % n)) (add_comm k i))) (Eq.refl ((i + k) % n)))) theorem mod_add_cancel_right {m : ℤ} {n : ℤ} {k : ℤ} (i : ℤ) : (m + i) % n = (k + i) % n ↔ m % n = k % n := sorry theorem mod_add_cancel_left {m : ℤ} {n : ℤ} {k : ℤ} {i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := sorry theorem mod_sub_cancel_right {m : ℤ} {n : ℤ} {k : ℤ} (i : ℤ) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right (-i) theorem mod_eq_mod_iff_mod_sub_eq_zero {m : ℤ} {n : ℤ} {k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := sorry @[simp] theorem mul_mod_left (a : ℤ) (b : ℤ) : a * b % b = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a * b % b = 0)) (Eq.symm (zero_add (a * b))))) (eq.mpr (id (Eq._oldrec (Eq.refl ((0 + a * b) % b = 0)) add_mul_mod_self)) (eq.mpr (id (Eq._oldrec (Eq.refl (0 % b = 0)) (zero_mod b))) (Eq.refl 0))) @[simp] theorem mul_mod_right (a : ℤ) (b : ℤ) : a * b % a = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (a * b % a = 0)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a % a = 0)) (mul_mod_left b a))) (Eq.refl 0)) theorem mul_mod (a : ℤ) (b : ℤ) (n : ℤ) : a * b % n = a % n * (b % n) % n := sorry @[simp] theorem neg_mod_two (i : ℤ) : -i % bit0 1 = i % bit0 1 := sorry theorem mod_self {a : ℤ} : a % a = 0 := eq.mp (Eq._oldrec (Eq.refl (1 * a % a = 0)) (one_mul a)) (mul_mod_left 1 a) @[simp] theorem mod_mod_of_dvd (n : ℤ) {m : ℤ} {k : ℤ} (h : m ∣ k) : n % k % m = n % m := sorry @[simp] theorem mod_mod (a : ℤ) (b : ℤ) : a % b % b = a % b := sorry theorem sub_mod (a : ℤ) (b : ℤ) (n : ℤ) : (a - b) % n = (a % n - b % n) % n := sorry /-! ### properties of `/` and `%` -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b : ℤ) (c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := sorry @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := eq.mpr (id (Eq._oldrec (Eq.refl (a * b / (c * b) = a / c)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a / (c * b) = a / c)) (mul_comm c b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a / (b * c) = a / c)) (mul_div_mul_of_pos a c H))) (Eq.refl (a / c)))) @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b : ℤ) (c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := sorry theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := sorry theorem abs_div_le_abs (a : ℤ) (b : ℤ) : abs (a / b) ≤ abs a := sorry theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := eq.mp (Eq._oldrec (Eq.refl (a / b ≤ abs a)) (abs_of_nonneg Ha)) (le_trans (le_abs_self (a / b)) (abs_div_le_abs a b)) theorem mul_div_cancel_of_mod_eq_zero {a : ℤ} {b : ℤ} (H : a % b = 0) : b * (a / b) = a := eq.mp (Eq._oldrec (Eq.refl (0 + b * (a / b) = a)) (zero_add (b * (a / b)))) (eq.mp (Eq._oldrec (Eq.refl (a % b + b * (a / b) = a)) H) (mod_add_div a b)) theorem div_mul_cancel_of_mod_eq_zero {a : ℤ} {b : ℤ} (H : a % b = 0) : a / b * b = a := eq.mpr (id (Eq._oldrec (Eq.refl (a / b * b = a)) (mul_comm (a / b) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * (a / b) = a)) (mul_div_cancel_of_mod_eq_zero H))) (Eq.refl a)) theorem mod_two_eq_zero_or_one (n : ℤ) : n % bit0 1 = 0 ∨ n % bit0 1 = 1 := sorry /-! ### dvd -/ theorem coe_nat_dvd {m : ℕ} {n : ℕ} : ↑m ∣ ↑n ↔ m ∣ n := sorry theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : ↑n ∣ z ↔ n ∣ nat_abs z := sorry theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ ↑n ↔ nat_abs z ∣ n := sorry theorem dvd_antisymm {a : ℤ} {b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := sorry theorem dvd_of_mod_eq_zero {a : ℤ} {b : ℤ} (H : b % a = 0) : a ∣ b := Exists.intro (b / a) (Eq.symm (mul_div_cancel_of_mod_eq_zero H)) theorem mod_eq_zero_of_dvd {a : ℤ} {b : ℤ} : a ∣ b → b % a = 0 := sorry theorem dvd_iff_mod_eq_zero (a : ℤ) (b : ℤ) : a ∣ b ↔ b % a = 0 := { mp := mod_eq_zero_of_dvd, mpr := dvd_of_mod_eq_zero } /-- If `a % b = c` then `b` divides `a - c`. -/ theorem dvd_sub_of_mod_eq {a : ℤ} {b : ℤ} {c : ℤ} (h : a % b = c) : b ∣ a - c := sorry theorem nat_abs_dvd {a : ℤ} {b : ℤ} : ↑(nat_abs a) ∣ b ↔ a ∣ b := sorry theorem dvd_nat_abs {a : ℤ} {b : ℤ} : a ∣ ↑(nat_abs b) ↔ a ∣ b := sorry protected instance decidable_dvd : DecidableRel has_dvd.dvd := fun (a n : ℤ) => decidable_of_decidable_of_iff (int.decidable_eq (n % a) 0) sorry protected theorem div_mul_cancel {a : ℤ} {b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a : ℤ} {b : ℤ} (H : a ∣ b) : a * (b / a) = b := eq.mpr (id (Eq._oldrec (Eq.refl (a * (b / a) = b)) (mul_comm a (b / a)))) (eq.mpr (id (Eq._oldrec (Eq.refl (b / a * a = b)) (int.div_mul_cancel H))) (Eq.refl b)) protected theorem mul_div_assoc (a : ℤ) {b : ℤ} {c : ℤ} : c ∣ b → a * b / c = a * (b / c) := sorry protected theorem mul_div_assoc' (b : ℤ) {a : ℤ} {c : ℤ} (h : c ∣ a) : a * b / c = a / c * b := eq.mpr (id (Eq._oldrec (Eq.refl (a * b / c = a / c * b)) (mul_comm a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * a / c = a / c * b)) (int.mul_div_assoc b h))) (eq.mpr (id (Eq._oldrec (Eq.refl (b * (a / c) = a / c * b)) (mul_comm b (a / c)))) (Eq.refl (a / c * b)))) theorem div_dvd_div {a : ℤ} {b : ℤ} {c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c) : b / a ∣ c / a := sorry protected theorem eq_mul_of_div_eq_right {a : ℤ} {b : ℤ} {c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := eq.mpr (id (Eq._oldrec (Eq.refl (a = b * c)) (Eq.symm H2))) (eq.mpr (id (Eq._oldrec (Eq.refl (a = b * (a / b))) (int.mul_div_cancel' H1))) (Eq.refl a)) protected theorem div_eq_of_eq_mul_right {a : ℤ} {b : ℤ} {c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := eq.mpr (id (Eq._oldrec (Eq.refl (a / b = c)) H2)) (eq.mpr (id (Eq._oldrec (Eq.refl (b * c / b = c)) (int.mul_div_cancel_left c H1))) (Eq.refl c)) protected theorem eq_div_of_mul_eq_right {a : ℤ} {b : ℤ} {c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) : b = c / a := Eq.symm (int.div_eq_of_eq_mul_right H1 (Eq.symm H2)) protected theorem div_eq_iff_eq_mul_right {a : ℤ} {b : ℤ} {c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := { mp := int.eq_mul_of_div_eq_right H', mpr := int.div_eq_of_eq_mul_right H } protected theorem div_eq_iff_eq_mul_left {a : ℤ} {b : ℤ} {c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := eq.mpr (id (Eq._oldrec (Eq.refl (a / b = c ↔ a = c * b)) (mul_comm c b))) (int.div_eq_iff_eq_mul_right H H') protected theorem eq_mul_of_div_eq_left {a : ℤ} {b : ℤ} {c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := eq.mpr (id (Eq._oldrec (Eq.refl (a = c * b)) (mul_comm c b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a = b * c)) (int.eq_mul_of_div_eq_right H1 H2))) (Eq.refl (b * c))) protected theorem div_eq_of_eq_mul_left {a : ℤ} {b : ℤ} {c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (eq.mpr (id (Eq._oldrec (Eq.refl (a = b * c)) (mul_comm b c))) (eq.mpr (id (Eq._oldrec (Eq.refl (a = c * b)) H2)) (Eq.refl (c * b)))) theorem neg_div_of_dvd {a : ℤ} {b : ℤ} (H : b ∣ a) : -a / b = -(a / b) := sorry theorem sub_div_of_dvd {a : ℤ} {b : ℤ} {c : ℤ} (hcb : c ∣ b) : (a - b) / c = a / c - b / c := sorry theorem sub_div_of_dvd_sub {a : ℤ} {b : ℤ} {c : ℤ} (hcab : c ∣ a - b) : (a - b) / c = a / c - b / c := eq.mpr (id (Eq._oldrec (Eq.refl ((a - b) / c = a / c - b / c)) (propext eq_sub_iff_add_eq))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a - b) / c + b / c = a / c)) (Eq.symm (int.add_div_of_dvd_left hcab)))) (eq.mpr (id (Eq._oldrec (Eq.refl ((a - b + b) / c = a / c)) (sub_add_cancel a b))) (Eq.refl (a / c)))) theorem div_sign (a : ℤ) (b : ℤ) : a / sign b = a * sign b := sorry @[simp] theorem sign_mul (a : ℤ) (b : ℤ) : sign (a * b) = sign a * sign b := sorry protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / abs a := sorry theorem mul_sign (i : ℤ) : i * sign i = ↑(nat_abs i) := sorry theorem le_of_dvd {a : ℤ} {b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := sorry theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := sorry theorem eq_one_of_mul_eq_one_right {a : ℤ} {b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H (Exists.intro b (Eq.symm H')) theorem eq_one_of_mul_eq_one_left {a : ℤ} {b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (eq.mpr (id (Eq._oldrec (Eq.refl (b * a = 1)) (mul_comm b a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a * b = 1)) H')) (Eq.refl 1))) theorem of_nat_dvd_of_dvd_nat_abs {a : ℕ} {z : ℤ} (haz : a ∣ nat_abs z) : ↑a ∣ z := sorry theorem dvd_nat_abs_of_of_nat_dvd {a : ℕ} {z : ℤ} (haz : ↑a ∣ z) : a ∣ nat_abs z := sorry theorem pow_dvd_of_le_of_pow_dvd {p : ℕ} {m : ℕ} {n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := sorry theorem dvd_of_pow_dvd {p : ℕ} {k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p ^ k) ∣ m) : ↑p ∣ m := eq.mpr (id (Eq._oldrec (Eq.refl (↑p ∣ m)) (Eq.symm (pow_one p)))) (pow_dvd_of_le_of_pow_dvd hk hpk) /-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)` for some `k`. -/ theorem exists_lt_and_lt_iff_not_dvd (m : ℤ) {n : ℤ} (hn : 0 < n) : (∃ (k : ℤ), n * k < m ∧ m < n * (k + 1)) ↔ ¬n ∣ m := sorry /-! ### `/` and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg (eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ a - a / b * b)) (mul_comm (a / b) b))) (eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ a - b * (a / b))) (Eq.symm (mod_def a b)))) (mod_nonneg a H))) protected theorem div_le_of_le_mul {a : ℤ} {b : ℤ} {c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le a (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a : ℤ} {b : ℤ} {c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge (mt (int.div_le_of_le_mul H) (not_le_of_gt H3)) protected theorem mul_le_of_le_div {a : ℤ} {b : ℤ} {c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le b (ne_of_gt H1)) protected theorem le_div_of_mul_le {a : ℤ} {b : ℤ} {c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one (lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self b H1)) (le_of_lt H1)) protected theorem le_div_iff_mul_le {a : ℤ} {b : ℤ} {c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := { mp := int.mul_le_of_le_div H, mpr := int.le_div_of_mul_le H } protected theorem div_le_div {a : ℤ} {b : ℤ} {c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le a (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a : ℤ} {b : ℤ} {c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge (mt (int.mul_le_of_le_div H) (not_le_of_gt H')) protected theorem lt_mul_of_div_lt {a : ℤ} {b : ℤ} {c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge (mt (int.le_div_of_mul_le H1) (not_le_of_gt H2)) protected theorem div_lt_iff_lt_mul {a : ℤ} {b : ℤ} {c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := { mp := int.lt_mul_of_div_lt H, mpr := int.div_lt_of_lt_mul H } protected theorem le_mul_of_div_le {a : ℤ} {b : ℤ} {c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ c * b)) (Eq.symm (int.div_mul_cancel H2)))) (mul_le_mul_of_nonneg_right H3 H1) protected theorem lt_div_of_mul_lt {a : ℤ} {b : ℤ} {c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge (mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3)) protected theorem lt_div_iff_mul_lt {a : ℤ} {b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := { mp := int.mul_lt_of_lt_div H, mpr := int.lt_div_of_mul_lt (le_of_lt H) H' } theorem div_pos_of_pos_of_dvd {a : ℤ} {b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (eq.mpr (id (Eq._oldrec (Eq.refl (0 * b < a)) (zero_mul b))) H1) theorem div_eq_div_of_mul_eq_mul {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 (eq.mpr (id (Eq._oldrec (Eq.refl (a = b * (c / d))) (Eq.symm (int.mul_div_assoc b H2)))) (Eq.symm (int.div_eq_of_eq_mul_left H4 (Eq.symm H5)))) theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a : ℤ} {b : ℤ} {c : ℤ} {d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := sorry /-- If an integer with larger absolute value divides an integer, it is zero. -/ theorem eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a : ℤ} {b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := sorry theorem eq_zero_of_dvd_of_nonneg_of_lt {a : ℤ} {b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ theorem eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a : ℤ} {b : ℤ} {c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m : ℕ} {n : ℕ} (h : m < Nat.succ n) : Int.ofNat m + Int.negSucc n = Int.negSucc (n - m) := sorry theorem of_nat_add_neg_succ_of_nat_of_ge {m : ℕ} {n : ℕ} (h : Nat.succ n ≤ m) : Int.ofNat m + Int.negSucc n = Int.ofNat (m - Nat.succ n) := sorry @[simp] theorem neg_add_neg (m : ℕ) (n : ℕ) : Int.negSucc m + Int.negSucc n = Int.negSucc (Nat.succ (m + n)) := rfl /-! ### to_nat -/ theorem to_nat_eq_max (a : ℤ) : ↑(to_nat a) = max a 0 := int.cases_on a (fun (a : ℕ) => idRhs (↑a = max (↑a) 0) (Eq.symm (max_eq_left (coe_zero_le a)))) fun (a : ℕ) => idRhs (0 = max (Int.negSucc a) 0) (Eq.symm (max_eq_right (le_of_lt (neg_succ_lt_zero a)))) @[simp] theorem to_nat_zero : to_nat 0 = 0 := rfl @[simp] theorem to_nat_one : to_nat 1 = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : ↑(to_nat a) = a := eq.mpr (id (Eq._oldrec (Eq.refl (↑(to_nat a) = a)) (to_nat_eq_max a))) (eq.mpr (id (Eq._oldrec (Eq.refl (max a 0 = a)) (max_eq_left h))) (Eq.refl a)) @[simp] theorem to_nat_sub_of_le (a : ℤ) (b : ℤ) (h : b ≤ a) : ↑(to_nat (a + -b)) = a + -b := to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] theorem to_nat_coe_nat_add_one {n : ℕ} : to_nat (↑n + 1) = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ ↑(to_nat a) := eq.mpr (id (Eq._oldrec (Eq.refl (a ≤ ↑(to_nat a))) (to_nat_eq_max a))) (le_max_left a 0) @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ ↑n := eq.mpr (id (Eq._oldrec (Eq.refl (to_nat a ≤ n ↔ a ≤ ↑n)) (propext (iff.symm (coe_nat_le_coe_nat_iff (to_nat a) n))))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(to_nat a) ≤ ↑n ↔ a ≤ ↑n)) (to_nat_eq_max a))) (eq.mpr (id (Eq._oldrec (Eq.refl (max a 0 ≤ ↑n ↔ a ≤ ↑n)) (propext max_le_iff))) (and_iff_left (coe_zero_le n)))) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ ↑n < a := iff.mp le_iff_le_iff_lt_iff_lt to_nat_le theorem to_nat_le_to_nat {a : ℤ} {b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := eq.mpr (id (Eq._oldrec (Eq.refl (to_nat a ≤ to_nat b)) (propext to_nat_le))) (le_trans h (le_to_nat b)) theorem to_nat_lt_to_nat {a : ℤ} {b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := sorry theorem lt_of_to_nat_lt {a : ℤ} {b : ℤ} (h : to_nat a < to_nat b) : a < b := iff.mp (to_nat_lt_to_nat (iff.mp lt_to_nat (lt_of_le_of_lt (nat.zero_le (to_nat a)) h))) h theorem to_nat_add {a : ℤ} {b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : to_nat (a + b) = to_nat a + to_nat b := sorry theorem to_nat_add_one {a : ℤ} (h : 0 ≤ a) : to_nat (a + 1) = to_nat a + 1 := to_nat_add h zero_le_one /-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`. -/ def to_nat' : ℤ → Option ℕ := sorry theorem mem_to_nat' (a : ℤ) (n : ℕ) : n ∈ to_nat' a ↔ a = ↑n := sorry theorem to_nat_zero_of_neg {z : ℤ} : z < 0 → to_nat z = 0 := sorry /-! ### units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs ↑u = 1 := sorry theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := sorry theorem units_inv_eq_self (u : units ℤ) : u⁻¹ = u := or.elim (units_eq_one_or u) (fun (h : u = 1) => Eq.symm h ▸ rfl) fun (h : u = -1) => Eq.symm h ▸ rfl @[simp] theorem units_mul_self (u : units ℤ) : u * u = 1 := or.elim (units_eq_one_or u) (fun (h : u = 1) => Eq.symm h ▸ rfl) fun (h : u = -1) => Eq.symm h ▸ rfl -- `units.coe_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further @[simp] theorem units_coe_mul_self (u : units ℤ) : ↑u * ↑u = 1 := eq.mpr (id (Eq._oldrec (Eq.refl (↑u * ↑u = 1)) (Eq.symm (units.coe_mul u u)))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑(u * u) = 1)) (units_mul_self u))) (eq.mpr (id (Eq._oldrec (Eq.refl (↑1 = 1)) units.coe_one)) (Eq.refl 1))) /-! ### bitwise ops -/ @[simp] theorem bodd_zero : bodd 0 = false := rfl @[simp] theorem bodd_one : bodd 1 = tt := rfl theorem bodd_two : bodd (bit0 1) = false := rfl @[simp] theorem bodd_coe (n : ℕ) : bodd ↑n = nat.bodd n := rfl @[simp] theorem bodd_sub_nat_nat (m : ℕ) (n : ℕ) : bodd (sub_nat_nat m n) = bxor (nat.bodd m) (nat.bodd n) := sorry @[simp] theorem bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = nat.bodd n := sorry @[simp] theorem bodd_neg (n : ℤ) : bodd (-n) = bodd n := sorry @[simp] theorem bodd_add (m : ℤ) (n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := sorry @[simp] theorem bodd_mul (m : ℤ) (n : ℤ) : bodd (m * n) = bodd m && bodd n := sorry theorem bodd_add_div2 (n : ℤ) : cond (bodd n) 1 0 + bit0 1 * div2 n = n := sorry theorem div2_val (n : ℤ) : div2 n = n / bit0 1 := int.cases_on n (fun (n : ℕ) => idRhs (Int.ofNat (nat.div2 n) = Int.ofNat (n / bit0 1)) (congr_arg Int.ofNat (nat.div2_val n))) fun (n : ℕ) => idRhs (Int.negSucc (nat.div2 n) = Int.negSucc (n / bit0 1)) (congr_arg Int.negSucc (nat.div2_val n)) theorem bit0_val (n : ℤ) : bit0 n = bit0 1 * n := Eq.symm (two_mul n) theorem bit1_val (n : ℤ) : bit1 n = bit0 1 * n + 1 := congr_arg (fun (_x : ℤ) => _x + 1) (bit0_val n) theorem bit_val (b : Bool) (n : ℤ) : bit b n = bit0 1 * n + cond b 1 0 := bool.cases_on b (Eq.trans (bit0_val n) (Eq.symm (add_zero (bit0 1 * n)))) (bit1_val n) theorem bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := Eq.trans (bit_val (bodd n) (div2 n)) (Eq.trans (add_comm (bit0 1 * div2 n) (cond (bodd n) 1 0)) (bodd_add_div2 n)) /-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately using `bit`. -/ def bit_cases_on {C : ℤ → Sort u} (n : ℤ) (h : (b : Bool) → (n : ℤ) → C (bit b n)) : C n := eq.mpr sorry (h (bodd n) (div2 n)) @[simp] theorem bit_zero : bit false 0 = 0 := rfl @[simp] theorem bit_coe_nat (b : Bool) (n : ℕ) : bit b ↑n = ↑(nat.bit b n) := eq.mpr (id (Eq._oldrec (Eq.refl (bit b ↑n = ↑(nat.bit b n))) (bit_val b ↑n))) (eq.mpr (id (Eq._oldrec (Eq.refl (bit0 1 * ↑n + cond b 1 0 = ↑(nat.bit b n))) (nat.bit_val b n))) (bool.cases_on b (Eq.refl (bit0 1 * ↑n + cond false 1 0)) (Eq.refl (bit0 1 * ↑n + cond tt 1 0)))) @[simp] theorem bit_neg_succ (b : Bool) (n : ℕ) : bit b (Int.negSucc n) = Int.negSucc (nat.bit (!b) n) := sorry @[simp] theorem bodd_bit (b : Bool) (n : ℤ) : bodd (bit b n) = b := sorry @[simp] theorem bodd_bit0 (n : ℤ) : bodd (bit0 n) = false := bodd_bit false n @[simp] theorem bodd_bit1 (n : ℤ) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] theorem div2_bit (b : Bool) (n : ℤ) : div2 (bit b n) = n := sorry theorem bit0_ne_bit1 (m : ℤ) (n : ℤ) : bit0 m ≠ bit1 n := sorry theorem bit1_ne_bit0 (m : ℤ) (n : ℤ) : bit1 m ≠ bit0 n := ne.symm (bit0_ne_bit1 n m) theorem bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 := sorry @[simp] theorem test_bit_zero (b : Bool) (n : ℤ) : test_bit (bit b n) 0 = b := sorry @[simp] theorem test_bit_succ (m : ℕ) (b : Bool) (n : ℤ) : test_bit (bit b n) (Nat.succ m) = test_bit n m := sorry theorem bitwise_or : bitwise bor = lor := sorry theorem bitwise_and : bitwise band = land := sorry theorem bitwise_diff : (bitwise fun (a b : Bool) => a && !b) = ldiff := sorry theorem bitwise_xor : bitwise bxor = lxor := sorry @[simp] theorem bitwise_bit (f : Bool → Bool → Bool) (a : Bool) (m : ℤ) (b : Bool) (n : ℤ) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := sorry @[simp] theorem lor_bit (a : Bool) (m : ℤ) (b : Bool) (n : ℤ) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := sorry @[simp] theorem land_bit (a : Bool) (m : ℤ) (b : Bool) (n : ℤ) : land (bit a m) (bit b n) = bit (a && b) (land m n) := sorry @[simp] theorem ldiff_bit (a : Bool) (m : ℤ) (b : Bool) (n : ℤ) : ldiff (bit a m) (bit b n) = bit (a && !b) (ldiff m n) := sorry @[simp] theorem lxor_bit (a : Bool) (m : ℤ) (b : Bool) (n : ℤ) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := sorry @[simp] theorem lnot_bit (b : Bool) (n : ℤ) : lnot (bit b n) = bit (!b) (lnot n) := sorry @[simp] theorem test_bit_bitwise (f : Bool → Bool → Bool) (m : ℤ) (n : ℤ) (k : ℕ) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := sorry @[simp] theorem test_bit_lor (m : ℤ) (n : ℤ) (k : ℕ) : test_bit (lor m n) k = test_bit m k || test_bit n k := sorry @[simp] theorem test_bit_land (m : ℤ) (n : ℤ) (k : ℕ) : test_bit (land m n) k = test_bit m k && test_bit n k := sorry @[simp] theorem test_bit_ldiff (m : ℤ) (n : ℤ) (k : ℕ) : test_bit (ldiff m n) k = test_bit m k && !test_bit n k := sorry @[simp] theorem test_bit_lxor (m : ℤ) (n : ℤ) (k : ℕ) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := sorry @[simp] theorem test_bit_lnot (n : ℤ) (k : ℕ) : test_bit (lnot n) k = !test_bit n k := sorry theorem shiftl_add (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (↑n + k) = shiftl (shiftl m ↑n) k := sorry theorem shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (↑n - k) = shiftr (shiftl m ↑n) k := shiftl_add m n (-k) @[simp] theorem shiftl_neg (m : ℤ) (n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] theorem shiftr_neg (m : ℤ) (n : ℤ) : shiftr m (-n) = shiftl m n := eq.mpr (id (Eq._oldrec (Eq.refl (shiftr m (-n) = shiftl m n)) (Eq.symm (shiftl_neg m (-n))))) (eq.mpr (id (Eq._oldrec (Eq.refl (shiftl m ( --n) = shiftl m n)) (neg_neg n))) (Eq.refl (shiftl m n))) @[simp] theorem shiftl_coe_nat (m : ℕ) (n : ℕ) : shiftl ↑m ↑n = ↑(nat.shiftl m n) := rfl @[simp] theorem shiftr_coe_nat (m : ℕ) (n : ℕ) : shiftr ↑m ↑n = ↑(nat.shiftr m n) := nat.cases_on n (Eq.refl (shiftr ↑m ↑0)) fun (n : ℕ) => Eq.refl (shiftr ↑m ↑(Nat.succ n)) @[simp] theorem shiftl_neg_succ (m : ℕ) (n : ℕ) : shiftl (Int.negSucc m) ↑n = Int.negSucc (nat.shiftl' tt m n) := rfl @[simp] theorem shiftr_neg_succ (m : ℕ) (n : ℕ) : shiftr (Int.negSucc m) ↑n = Int.negSucc (nat.shiftr m n) := nat.cases_on n (Eq.refl (shiftr (Int.negSucc m) ↑0)) fun (n : ℕ) => Eq.refl (shiftr (Int.negSucc m) ↑(Nat.succ n)) theorem shiftr_add (m : ℤ) (n : ℕ) (k : ℕ) : shiftr m (↑n + ↑k) = shiftr (shiftr m ↑n) ↑k := sorry theorem shiftl_eq_mul_pow (m : ℤ) (n : ℕ) : shiftl m ↑n = m * ↑(bit0 1 ^ n) := sorry theorem shiftr_eq_div_pow (m : ℤ) (n : ℕ) : shiftr m ↑n = m / ↑(bit0 1 ^ n) := sorry theorem one_shiftl (n : ℕ) : shiftl 1 ↑n = ↑(bit0 1 ^ n) := congr_arg coe (nat.one_shiftl n) @[simp] theorem zero_shiftl (n : ℤ) : shiftl 0 n = 0 := int.cases_on n (fun (n : ℕ) => idRhs (↑(nat.shiftl 0 n) = ↑0) (congr_arg coe (nat.zero_shiftl n))) fun (n : ℕ) => idRhs (↑(nat.shiftr 0 (Nat.succ n)) = ↑0) (congr_arg coe (nat.zero_shiftr (Nat.succ n))) @[simp] theorem zero_shiftr (n : ℤ) : shiftr 0 n = 0 := zero_shiftl (-n) /-! ### Least upper bound property for integers -/ theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ (b : ℤ), ∀ (z : ℤ), P z → b ≤ z) (Hinh : ∃ (z : ℤ), P z) : ∃ (lb : ℤ), P lb ∧ ∀ (z : ℤ), P z → lb ≤ z := sorry theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ (b : ℤ), ∀ (z : ℤ), P z → z ≤ b) (Hinh : ∃ (z : ℤ), P z) : ∃ (ub : ℤ), P ub ∧ ∀ (z : ℤ), P z → z ≤ ub := sorry
dddec8966d86bae40b955c286dce71ab4b562141
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/library/data/monad/transformers.lean
12c617b659c42bd3a812ad24080d55f2855af7dc
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
1,469
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ namespace monad class monad_transformer (transformer : ∀m [monad m], Type → Type) := (is_monad : ∀m [monad m], monad (transformer m)) (monad_lift : ∀m [monad m] α, m α → transformer m α) instance transformed_monad (m t) [monad_transformer t] [monad m] : monad (t m) := monad_transformer.is_monad t m class has_monad_lift (m n : Type → Type) := (monad_lift : ∀α, m α → n α) instance monad_transformer_lift (t m) [monad_transformer t] [monad m] : has_monad_lift m (t m) := ⟨monad_transformer.monad_lift t m⟩ class has_monad_lift_t (m n : Type → Type) := (monad_lift : ∀α, m α → n α) def monad_lift {m n} [has_monad_lift_t m n] {α} : m α → n α := has_monad_lift_t.monad_lift n α prefix `♯ `:0 := monad_lift instance has_monad_lift_t_trans (m n o) [has_monad_lift n o] [has_monad_lift_t m n] : has_monad_lift_t m o := ⟨ λα (ma : m α), has_monad_lift.monad_lift o α $ has_monad_lift_t.monad_lift n α ma ⟩ instance has_monad_lift_t_refl (m) [monad m] : has_monad_lift_t m m := ⟨ λα, id ⟩ end monad namespace state_t def state_t_monad_lift (S) (m) [monad m] (α) (f : m α) : state_t S m α := take state, do res ← f, return (res, state) instance (S) : monad.monad_transformer (state_t S) := ⟨ state_t.monad S, state_t_monad_lift S ⟩ end state_t
01e5dd94afa22dd1b36d65ccea3b42870343c5dd
d0c6b2ba2af981e9ab0a98f6e169262caad4b9b9
/src/Std/Data/RBTree.lean
8facea0ecb25e67f30bb1da3d4ebb3a4262629e0
[ "Apache-2.0" ]
permissive
fizruk/lean4
953b7dcd76e78c17a0743a2c1a918394ab64bbc0
545ed50f83c570f772ade4edbe7d38a078cbd761
refs/heads/master
1,677,655,987,815
1,612,393,885,000
1,612,393,885,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,215
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.RBMap namespace Std universes u v w def RBTree (α : Type u) (lt : α → α → Bool) : Type u := RBMap α Unit lt instance : Inhabited (RBTree α p) where default := RBMap.empty @[inline] def mkRBTree (α : Type u) (lt : α → α → Bool) : RBTree α lt := mkRBMap α Unit lt instance (α : Type u) (lt : α → α → Bool) : EmptyCollection (RBTree α lt) := ⟨mkRBTree α lt⟩ namespace RBTree variable {α : Type u} {β : Type v} {lt : α → α → Bool} @[inline] def empty : RBTree α lt := RBMap.empty @[inline] def depth (f : Nat → Nat → Nat) (t : RBTree α lt) : Nat := RBMap.depth f t @[inline] def fold (f : β → α → β) (init : β) (t : RBTree α lt) : β := RBMap.fold (fun r a _ => f r a) init t @[inline] def revFold (f : β → α → β) (init : β) (t : RBTree α lt) : β := RBMap.revFold (fun r a _ => f r a) init t @[inline] def foldM {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (t : RBTree α lt) : m β := RBMap.foldM (fun r a _ => f r a) init t @[inline] def forM {m : Type v → Type w} [Monad m] (f : α → m PUnit) (t : RBTree α lt) : m PUnit := t.foldM (fun _ a => f a) ⟨⟩ @[inline] def forIn [Monad m] (t : RBTree α lt) (init : σ) (f : α → σ → m (ForInStep σ)) : m σ := t.val.forIn init (fun a _ acc => f a acc) @[inline] def isEmpty (t : RBTree α lt) : Bool := RBMap.isEmpty t @[specialize] def toList (t : RBTree α lt) : List α := t.revFold (fun as a => a::as) [] @[inline] protected def min (t : RBTree α lt) : Option α := match RBMap.min t with | some ⟨a, _⟩ => some a | none => none @[inline] protected def max (t : RBTree α lt) : Option α := match RBMap.max t with | some ⟨a, _⟩ => some a | none => none instance [Repr α] : Repr (RBTree α lt) where reprPrec t prec := Repr.addAppParen ("Std.rbtreeOf " ++ repr t.toList) prec @[inline] def insert (t : RBTree α lt) (a : α) : RBTree α lt := RBMap.insert t a () @[inline] def erase (t : RBTree α lt) (a : α) : RBTree α lt := RBMap.erase t a @[specialize] def ofList : List α → RBTree α lt | [] => mkRBTree .. | x::xs => (ofList xs).insert x @[inline] def find? (t : RBTree α lt) (a : α) : Option α := match RBMap.findCore? t a with | some ⟨a, _⟩ => some a | none => none @[inline] def contains (t : RBTree α lt) (a : α) : Bool := (t.find? a).isSome def fromList (l : List α) (lt : α → α → Bool) : RBTree α lt := l.foldl insert (mkRBTree α lt) @[inline] def all (t : RBTree α lt) (p : α → Bool) : Bool := RBMap.all t (fun a _ => p a) @[inline] def any (t : RBTree α lt) (p : α → Bool) : Bool := RBMap.any t (fun a _ => p a) def subset (t₁ t₂ : RBTree α lt) : Bool := t₁.all fun a => (t₂.find? a).toBool def seteq (t₁ t₂ : RBTree α lt) : Bool := subset t₁ t₂ && subset t₂ t₁ end RBTree def rbtreeOf {α : Type u} (l : List α) (lt : α → α → Bool) : RBTree α lt := RBTree.fromList l lt end Std
1a67ae51a4b3dd5eefa6053296c1070111ac3e35
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/Scheme.lean
7a76e19a7d62ec7d22ef5fe3f8b0fdf36c29d72e
[ "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,870
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 algebraic_geometry.Spec import algebra.category.Ring.constructions /-! # The category of schemes A scheme is a locally ringed space such that every point is contained in some open set where there is an isomorphism of presheaves between the restriction to that open set, and the structure sheaf of `Spec R`, for some commutative ring `R`. A morphism of schemes is just a morphism of the underlying locally ringed spaces. -/ noncomputable theory open topological_space open category_theory open Top open opposite namespace algebraic_geometry /-- We define `Scheme` as a `X : LocallyRingedSpace`, along with a proof that every point has an open neighbourhood `U` so that that the restriction of `X` to `U` is isomorphic, as a locally ringed space, to `Spec.to_LocallyRingedSpace.obj (op R)` for some `R : CommRing`. -/ structure Scheme extends to_LocallyRingedSpace : LocallyRingedSpace := (local_affine : ∀ x : to_LocallyRingedSpace, ∃ (U : open_nhds x) (R : CommRing), nonempty (to_LocallyRingedSpace.restrict U.open_embedding ≅ Spec.to_LocallyRingedSpace.obj (op R))) namespace Scheme /-- A morphism between schemes is a morphism between the underlying locally ringed spaces. -/ @[nolint has_nonempty_instance] -- There isn't nessecarily a morphism between two schemes. def hom (X Y : Scheme) : Type* := X.to_LocallyRingedSpace ⟶ Y.to_LocallyRingedSpace /-- Schemes are a full subcategory of locally ringed spaces. -/ instance : category Scheme := { hom := hom, ..(induced_category.category Scheme.to_LocallyRingedSpace) } /-- The structure sheaf of a Scheme. -/ protected abbreviation sheaf (X : Scheme) := X.to_SheafedSpace.sheaf /-- The forgetful functor from `Scheme` to `LocallyRingedSpace`. -/ @[simps, derive[full, faithful]] def forget_to_LocallyRingedSpace : Scheme ⥤ LocallyRingedSpace := induced_functor _ @[simp] lemma forget_to_LocallyRingedSpace_preimage {X Y : Scheme} (f : X ⟶ Y) : Scheme.forget_to_LocallyRingedSpace.preimage f = f := rfl /-- The forgetful functor from `Scheme` to `Top`. -/ @[simps] def forget_to_Top : Scheme ⥤ Top := Scheme.forget_to_LocallyRingedSpace ⋙ LocallyRingedSpace.forget_to_Top @[simp] lemma id_val_base (X : Scheme) : (𝟙 X : _).1.base = 𝟙 _ := rfl @[simp] lemma id_app {X : Scheme} (U : (opens X.carrier)ᵒᵖ) : (𝟙 X : _).val.c.app U = X.presheaf.map (eq_to_hom (by { induction U using opposite.rec, cases U, refl })) := PresheafedSpace.id_c_app X.to_PresheafedSpace U @[reassoc] lemma comp_val {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val = f.val ≫ g.val := rfl @[reassoc, simp] lemma comp_coe_base {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val.base = f.val.base ≫ g.val.base := rfl @[reassoc, elementwise] lemma comp_val_base {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val.base = f.val.base ≫ g.val.base := rfl @[reassoc, simp] lemma comp_val_c_app {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (f ≫ g).val.c.app U = g.val.c.app U ≫ f.val.c.app _ := rfl lemma congr_app {X Y : Scheme} {f g : X ⟶ Y} (e : f = g) (U) : f.val.c.app U = g.val.c.app U ≫ X.presheaf.map (eq_to_hom (by subst e)) := by { subst e, dsimp, simp } lemma app_eq {X Y : Scheme} (f : X ⟶ Y) {U V : opens Y.carrier} (e : U = V) : f.val.c.app (op U) = Y.presheaf.map (eq_to_hom e.symm).op ≫ f.val.c.app (op V) ≫ X.presheaf.map (eq_to_hom (congr_arg (opens.map f.val.base).obj e)).op := begin rw [← is_iso.inv_comp_eq, ← functor.map_inv, f.val.c.naturality, presheaf.pushforward_obj_map], congr end instance is_LocallyRingedSpace_iso {X Y : Scheme} (f : X ⟶ Y) [is_iso f] : @is_iso LocallyRingedSpace _ _ _ f := forget_to_LocallyRingedSpace.map_is_iso f @[simp] lemma inv_val_c_app {X Y : Scheme} (f : X ⟶ Y) [is_iso f] (U : opens X.carrier) : (inv f).val.c.app (op U) = X.presheaf.map (eq_to_hom $ by { rw is_iso.hom_inv_id, ext1, refl } : (opens.map (f ≫ inv f).1.base).obj U ⟶ U).op ≫ inv (f.val.c.app (op $ (opens.map _).obj U)) := begin rw [is_iso.eq_comp_inv], erw ← Scheme.comp_val_c_app, rw [Scheme.congr_app (is_iso.hom_inv_id f), Scheme.id_app, ← functor.map_comp, eq_to_hom_trans, eq_to_hom_op], refl end /-- Given a morphism of schemes `f : X ⟶ Y`, and open sets `U ⊆ Y`, `V ⊆ f ⁻¹' U`, this is the induced map `Γ(Y, U) ⟶ Γ(X, V)`. -/ abbreviation hom.app_le {X Y : Scheme} (f : X ⟶ Y) {V : opens X.carrier} {U : opens Y.carrier} (e : V ≤ (opens.map f.1.base).obj U) : Y.presheaf.obj (op U) ⟶ X.presheaf.obj (op V) := f.1.c.app (op U) ≫ X.presheaf.map (hom_of_le e).op /-- The spectrum of a commutative ring, as a scheme. -/ def Spec_obj (R : CommRing) : Scheme := { local_affine := λ x, ⟨⟨⊤, trivial⟩, R, ⟨(Spec.to_LocallyRingedSpace.obj (op R)).restrict_top_iso⟩⟩, to_LocallyRingedSpace := Spec.LocallyRingedSpace_obj R } @[simp] lemma Spec_obj_to_LocallyRingedSpace (R : CommRing) : (Spec_obj R).to_LocallyRingedSpace = Spec.LocallyRingedSpace_obj R := rfl /-- The induced map of a ring homomorphism on the ring spectra, as a morphism of schemes. -/ def Spec_map {R S : CommRing} (f : R ⟶ S) : Spec_obj S ⟶ Spec_obj R := (Spec.LocallyRingedSpace_map f : Spec.LocallyRingedSpace_obj S ⟶ Spec.LocallyRingedSpace_obj R) @[simp] lemma Spec_map_id (R : CommRing) : Spec_map (𝟙 R) = 𝟙 (Spec_obj R) := Spec.LocallyRingedSpace_map_id R lemma Spec_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) : Spec_map (f ≫ g) = Spec_map g ≫ Spec_map f := Spec.LocallyRingedSpace_map_comp f g /-- The spectrum, as a contravariant functor from commutative rings to schemes. -/ @[simps] def Spec : CommRingᵒᵖ ⥤ Scheme := { obj := λ R, Spec_obj (unop R), map := λ R S f, Spec_map f.unop, map_id' := λ R, by rw [unop_id, Spec_map_id], map_comp' := λ R S T f g, by rw [unop_comp, Spec_map_comp] } /-- The empty scheme. -/ @[simps] def {u} empty : Scheme.{u} := { carrier := Top.of pempty, presheaf := (category_theory.functor.const _).obj (CommRing.of punit), is_sheaf := presheaf.is_sheaf_of_is_terminal _ CommRing.punit_is_terminal, local_ring := λ x, pempty.elim x, local_affine := λ x, pempty.elim x } instance : has_emptyc Scheme := ⟨empty⟩ instance : inhabited Scheme := ⟨∅⟩ /-- The global sections, notated Gamma. -/ def Γ : Schemeᵒᵖ ⥤ CommRing := (induced_functor Scheme.to_LocallyRingedSpace).op ⋙ LocallyRingedSpace.Γ lemma Γ_def : Γ = (induced_functor Scheme.to_LocallyRingedSpace).op ⋙ LocallyRingedSpace.Γ := rfl @[simp] lemma Γ_obj (X : Schemeᵒᵖ) : Γ.obj X = (unop X).presheaf.obj (op ⊤) := rfl lemma Γ_obj_op (X : Scheme) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl @[simp] lemma Γ_map {X Y : Schemeᵒᵖ} (f : X ⟶ Y) : Γ.map f = f.unop.1.c.app (op ⊤) := rfl lemma Γ_map_op {X Y : Scheme} (f : X ⟶ Y) : Γ.map f.op = f.1.c.app (op ⊤) := rfl section basic_open variables (X : Scheme) {V U : opens X.carrier} (f g : X.presheaf.obj (op U)) /-- The subset of the underlying space where the given section does not vanish. -/ def basic_open : opens X.carrier := X.to_LocallyRingedSpace.to_RingedSpace.basic_open f @[simp] lemma mem_basic_open (x : U) : ↑x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ x f) := RingedSpace.mem_basic_open _ _ _ @[simp] lemma mem_basic_open_top (f : X.presheaf.obj (op ⊤)) (x : X.carrier) : x ∈ X.basic_open f ↔ is_unit (X.presheaf.germ (⟨x, trivial⟩ : (⊤ : opens _)) f) := RingedSpace.mem_basic_open _ f ⟨x, trivial⟩ @[simp] lemma basic_open_res (i : op U ⟶ op V) : X.basic_open (X.presheaf.map i f) = V ⊓ X.basic_open f := RingedSpace.basic_open_res _ i f -- This should fire before `basic_open_res`. @[simp, priority 1100] lemma basic_open_res_eq (i : op U ⟶ op V) [is_iso i] : X.basic_open (X.presheaf.map i f) = X.basic_open f := RingedSpace.basic_open_res_eq _ i f @[sheaf_restrict] lemma basic_open_le : X.basic_open f ≤ U := RingedSpace.basic_open_le _ _ @[simp] lemma preimage_basic_open {X Y : Scheme} (f : X ⟶ Y) {U : opens Y.carrier} (r : Y.presheaf.obj $ op U) : (opens.map f.1.base).obj (Y.basic_open r) = @Scheme.basic_open X ((opens.map f.1.base).obj U) (f.1.c.app _ r) := LocallyRingedSpace.preimage_basic_open f r @[simp] lemma basic_open_zero (U : opens X.carrier) : X.basic_open (0 : X.presheaf.obj $ op U) = ⊥ := LocallyRingedSpace.basic_open_zero _ U @[simp] lemma basic_open_mul : X.basic_open (f * g) = X.basic_open f ⊓ X.basic_open g := RingedSpace.basic_open_mul _ _ _ lemma basic_open_of_is_unit {f : X.presheaf.obj (op U)} (hf : is_unit f) : X.basic_open f = U := RingedSpace.basic_open_of_is_unit _ hf end basic_open end Scheme lemma basic_open_eq_of_affine {R : CommRing} (f : R) : (Scheme.Spec.obj $ op R).basic_open ((Spec_Γ_identity.app R).inv f) = prime_spectrum.basic_open f := begin ext, erw Scheme.mem_basic_open_top, suffices : is_unit (structure_sheaf.to_stalk R x f) ↔ f ∉ prime_spectrum.as_ideal x, { exact this }, erw [← is_unit_map_iff (structure_sheaf.stalk_to_fiber_ring_hom R x), structure_sheaf.stalk_to_fiber_ring_hom_to_stalk], exact (is_localization.at_prime.is_unit_to_map_iff (localization.at_prime (prime_spectrum.as_ideal x)) (prime_spectrum.as_ideal x) f : _) end @[simp] lemma basic_open_eq_of_affine' {R : CommRing} (f : (Spec.to_SheafedSpace.obj (op R)).presheaf.obj (op ⊤)) : (Scheme.Spec.obj $ op R).basic_open f = prime_spectrum.basic_open ((Spec_Γ_identity.app R).hom f) := begin convert basic_open_eq_of_affine ((Spec_Γ_identity.app R).hom f), exact (iso.hom_inv_id_apply _ _).symm end end algebraic_geometry
f4ce6492103df8048e182a7b07dd361076e8e29b
35960c5b117752aca7e3e7767c0b393e4dbd72a7
/src/typ/fv.lean
57bc0d6ea8722ae446c992eb70564ab1fe6eea8b
[ "Apache-2.0" ]
permissive
spl/tts
461dc76b83df8db47e4660d0941dc97e6d4fd7d1
b65298fea68ce47c8ed3ba3dbce71c1a20dd3481
refs/heads/master
1,541,049,198,347
1,537,967,023,000
1,537,967,029,000
119,653,145
1
0
null
null
null
null
UTF-8
Lean
false
false
1,380
lean
import .core namespace tts ------------------------------------------------------------------ namespace typ ------------------------------------------------------------------ variables {V : Type} [_root_.decidable_eq V] -- Type of variable names variables {x y : tagged V} -- Variable variables {t t₁ t₂ : typ V} -- Types variables {ts ts₁ ts₂ : list (typ V)} -- Lists of types open occurs /-- Free variables of a type -/ def fv : typ V → finset (tagged V) | (var bound _) := ∅ | (var free x) := {x} | (arr t₁ t₂) := fv t₁ ∪ fv t₂ @[simp] theorem fv_not_mem_var_free : x ∉ fv (var free y) ↔ x ≠ y := by simp [fv] @[simp] theorem fv_not_mem_arr : x ∉ fv (arr t₁ t₂) ↔ x ∉ fv t₁ ∧ x ∉ fv t₂ := by simp [fv, not_or_distrib] /-- Free variables of a list of types -/ def fv_list : list (typ V) → finset (tagged V) | [] := ∅ | (t :: ts) := fv t ∪ fv_list ts @[simp] theorem fv_list_nil : fv_list ([] : list (typ V)) = ∅ := rfl @[simp] theorem fv_list_cons : fv_list (t :: ts) = fv t ∪ fv_list ts := rfl @[simp] theorem fv_list_append : fv_list (ts₁ ++ ts₂) = fv_list ts₁ ∪ fv_list ts₂ := by induction ts₁ with _ _ ih; [simp, simp [ih]] end /- namespace -/ typ -------------------------------------------------------- end /- namespace -/ tts --------------------------------------------------------
4edcb313c33e75a6457a044ede0d7dfd5e95a3e3
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/mutual_inductive.lean
7a654501ba7dfe3e1187e2cadf94b4afe96962e6
[ "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
2,574
lean
namespace X1 mutual inductive foo, bar with foo : Type | mk : foo with bar : Type | mk : bar #check @foo #check @bar #check @foo.rec #check @bar.rec #check @foo.has_sizeof_inst #check @bar.has_sizeof_inst end X1 namespace X2 mutual inductive foo, bar with foo : Type | mk : bar -> foo with bar : Type | mk : foo -> bar #check @foo #check @bar #check @foo.rec #check @bar.rec #check @foo.has_sizeof_inst #check @bar.has_sizeof_inst end X2 namespace X3 mutual inductive foo, bar with foo : bool -> Type | mk : bar -> foo tt with bar : Type | mk : foo tt -> bar #check @foo #check @bar #check @foo.rec #check @bar.rec #check @foo.has_sizeof_inst #check @bar.has_sizeof_inst end X3 namespace X4 mutual inductive foo, bar, rig with foo : bool -> bool -> Type | mk : bar tt -> foo tt tt with bar : bool -> Type | mk : foo tt tt -> bar tt with rig : Type | mk : foo tt tt -> bar tt -> rig #check @foo #check @bar #check @rig #check @foo.rec #check @bar.rec #check @rig.rec #check @foo.has_sizeof_inst #check @bar.has_sizeof_inst #check @rig.has_sizeof_inst end X4 namespace X5 mutual inductive foo, bar, rig (A : Type) with foo : Pi (b : bool), b = b -> Type | mk : A -> bar tt ff tt -> foo tt rfl with bar : bool -> bool -> bool -> Type | mk : A -> foo tt rfl -> bar tt ff tt with rig : Type | mk : A -> foo tt rfl -> bar tt ff tt -> rig | put : A -> foo tt rfl -> bar tt ff tt -> rig #check @foo #check @bar #check @rig #check @foo.rec #check @bar.rec #check @rig.rec #check @foo.has_sizeof_inst #check @bar.has_sizeof_inst #check @rig.has_sizeof_inst end X5 namespace X6 mutual inductive {l₁ l₂} foo, bar, rig (A : Type.{l₁}) (B : Type.{l₂}) with foo : Pi (b : bool), b = b -> Type.{max l₁ l₂} | mk : A -> B -> bar tt ff tt -> foo tt rfl with bar : bool -> bool -> bool -> Type.{max l₁ l₂} | mk : A -> B -> foo tt rfl -> bar tt ff tt with rig : Type.{max l₁ l₂} | mk : A -> B -> foo tt rfl -> bar tt ff tt -> rig #check @foo #check @bar #check @rig #check @foo.rec #check @bar.rec #check @rig.rec end X6 namespace X7 mutual inductive {l₁ l₂ l₃} foo, bar, rig (A : Type.{l₁}) (B : Type.{l₂}) (a : A) with foo : Pi (b : bool), b = b -> Type.{max l₁ l₂ l₃} | mk : A -> B -> Pi x : A, x = a -> bar tt ff tt -> foo tt rfl with bar : bool -> bool -> bool -> Type.{max l₁ l₂ l₃} | mk : A -> B -> foo tt rfl -> bar tt ff tt with rig : Type.{max l₁ l₂ l₃} | mk : A -> B -> (Pi x : A, x = a -> foo tt rfl) -> bar tt ff tt -> rig #check @foo #check @bar #check @rig #check @foo.rec #check @bar.rec #check @rig.rec end X7
3d861a8ca79e9778c3318c1bb8de86a86dabab3e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/control/except_auto.lean
6d0f7c69f8c97c2b5a0f28b0d166636b2aafd799
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,710
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch, Sebastian Ullrich The except monad transformer. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.control.alternative import Mathlib.Lean3Lib.init.control.lift universes u v l u_1 w u_2 namespace Mathlib inductive except (ε : Type u) (α : Type v) where | error : ε → except ε α | ok : α → except ε α namespace except protected def return {ε : Type u} {α : Type v} (a : α) : except ε α := ok a protected def map {ε : Type u} {α : Type v} {β : Type v} (f : α → β) : except ε α → except ε β := sorry protected def map_error {ε : Type u} {ε' : Type u} {α : Type v} (f : ε → ε') : except ε α → except ε' α := sorry protected def bind {ε : Type u} {α : Type v} {β : Type v} (ma : except ε α) (f : α → except ε β) : except ε β := sorry protected def to_bool {ε : Type u} {α : Type v} : except ε α → Bool := sorry protected def to_option {ε : Type u} {α : Type v} : except ε α → Option α := sorry protected instance monad {ε : Type u} : Monad (except ε) := sorry end except structure except_t (ε : Type u) (m : Type u → Type v) (α : Type u) where run : m (except ε α) namespace except_t protected def return {ε : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (a : α) : except_t ε m α := mk (pure (except.ok a)) protected def bind_cont {ε : Type u} {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} (f : α → except_t ε m β) : except ε α → m (except ε β) := sorry protected def bind {ε : Type u} {m : Type u → Type v} [Monad m] {α : Type u} {β : Type u} (ma : except_t ε m α) (f : α → except_t ε m β) : except_t ε m β := mk (run ma >>= except_t.bind_cont f) protected def lift {ε : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (t : m α) : except_t ε m α := mk (except.ok <$> t) protected instance has_monad_lift {ε : Type u} {m : Type u → Type v} [Monad m] : has_monad_lift m (except_t ε m) := has_monad_lift.mk except_t.lift protected def catch {ε : Type u} {m : Type u → Type v} [Monad m] {α : Type u} (ma : except_t ε m α) (handle : ε → except_t ε m α) : except_t ε m α := mk do run ma sorry protected def monad_map {ε : Type u} {m : Type u → Type v} [Monad m] {m' : Type u → Type u_1} [Monad m'] {α : Type u} (f : {α : Type u} → m α → m' α) : except_t ε m α → except_t ε m' α := fun (x : except_t ε m α) => mk (f (run x)) protected instance monad_functor {ε : Type u} {m : Type u → Type v} [Monad m] (m' : Type u → Type v) [Monad m'] : monad_functor m m' (except_t ε m) (except_t ε m') := monad_functor.mk except_t.monad_map protected instance monad {ε : Type u} {m : Type u → Type v} [Monad m] : Monad (except_t ε m) := sorry protected def adapt {ε : Type u} {m : Type u → Type v} [Monad m] {ε' : Type u} {α : Type u} (f : ε → ε') : except_t ε m α → except_t ε' m α := fun (x : except_t ε m α) => mk (except.map_error f <$> run x) end except_t /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class monad_except (ε : outParam (Type u)) (m : Type v → Type w) where throw : {α : Type v} → ε → m α catch : {α : Type v} → m α → (ε → m α) → m α namespace monad_except protected def orelse {ε : Type u} {m : Type v → Type w} [monad_except ε m] {α : Type v} (t₁ : m α) (t₂ : m α) : m α := catch t₁ fun (_x : ε) => t₂ /-- 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. -/ end monad_except protected instance except_t.monad_except (m : Type u_1 → Type u_2) (ε : outParam (Type u_1)) [Monad m] : monad_except ε (except_t ε m) := monad_except.mk (fun (α : Type u_1) => except_t.mk ∘ pure ∘ except.error) except_t.catch /-- Adapt a monad stack, changing its top-most error type. Note: This class can be seen as a simplification of the more "principled" definition ``` class monad_except_functor (ε ε' : out_param (Type u)) (n n' : Type u → Type u) := (map {α : Type u} : (∀ {m : Type u → Type u} [monad m], except_t ε m α → except_t ε' m α) → n α → n' α) ``` -/ class monad_except_adapter (ε : outParam (Type u)) (ε' : outParam (Type u)) (m : Type u → Type v) (m' : Type u → Type v) where adapt_except : {α : Type u} → (ε → ε') → m α → m' α protected instance monad_except_adapter_trans {ε : Type u} {ε' : Type u} {m : Type u → Type v} {m' : Type u → Type v} {n : Type u → Type v} {n' : Type u → Type v} [monad_functor m m' n n'] [monad_except_adapter ε ε' m m'] : monad_except_adapter ε ε' n n' := monad_except_adapter.mk fun (α : Type u) (f : ε → ε') => monad_map fun (α : Type u) => adapt_except f protected instance except_t.monad_except_adapter {ε : Type u} {ε' : Type u} {m : Type u → Type v} [Monad m] : monad_except_adapter ε ε' (except_t ε m) (except_t ε' m) := monad_except_adapter.mk fun (α : Type u) => except_t.adapt protected instance except_t.monad_run (ε : Type u_1) (m : Type u_1 → Type u_2) (out : outParam (Type u_1 → Type u_2)) [monad_run out m] : monad_run (fun (α : Type u_1) => out (except ε α)) (except_t ε m) := monad_run.mk fun (α : Type u_1) => run ∘ except_t.run end Mathlib
8152c69ef830eaa53cefc4805502bb196e053ac1
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Module/adjunctions.lean
6a52ae82bbc3d14ee46da8b8799080327ee8be50
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
10,033
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin -/ import algebra.category.Module.monoidal import category_theory.monoidal.functorial import category_theory.monoidal.types import linear_algebra.direct_sum.finsupp import category_theory.linear.linear_functor /-! The functor of forming finitely supported functions on a type with values in a `[ring R]` is the left adjoint of the forgetful functor from `R`-modules to types. -/ noncomputable theory open category_theory namespace Module universe u open_locale classical variables (R : Type u) section variables [ring R] /-- The free functor `Type u ⥤ Module R` sending a type `X` to the free `R`-module with generators `x : X`, implemented as the type `X →₀ R`. -/ @[simps] def free : Type u ⥤ Module R := { obj := λ X, Module.of R (X →₀ R), map := λ X Y f, finsupp.lmap_domain _ _ f, map_id' := by { intros, exact finsupp.lmap_domain_id _ _ }, map_comp' := by { intros, exact finsupp.lmap_domain_comp _ _ _ _, } } /-- The free-forgetful adjunction for R-modules. -/ def adj : free R ⊣ forget (Module.{u} R) := adjunction.mk_of_hom_equiv { hom_equiv := λ X M, (finsupp.lift M R X).to_equiv.symm, hom_equiv_naturality_left_symm' := λ _ _ M f g, finsupp.lhom_ext' (λ x, linear_map.ext_ring (finsupp.sum_map_domain_index_add_monoid_hom (λ y, ((smul_add_hom R M).flip) (g y))).symm) } instance : is_right_adjoint (forget (Module.{u} R)) := ⟨_, adj R⟩ end namespace free variables [comm_ring R] local attribute [ext] tensor_product.ext /-- (Implementation detail) The unitor for `free R`. -/ def ε : 𝟙_ (Module.{u} R) ⟶ (free R).obj (𝟙_ (Type u)) := finsupp.lsingle punit.star /-- (Implementation detail) The tensorator for `free R`. -/ def μ (α β : Type u) : (free R).obj α ⊗ (free R).obj β ⟶ (free R).obj (α ⊗ β) := (finsupp_tensor_finsupp' R α β).to_linear_map lemma μ_natural {X Y X' Y' : Type u} (f : X ⟶ Y) (g : X' ⟶ Y') : ((free R).map f ⊗ (free R).map g) ≫ (μ R Y Y') = (μ R X X') ≫ (free R).map (f ⊗ g) := begin intros, ext x x' ⟨y, y'⟩, dsimp [μ], simp_rw [finsupp.map_domain_single, finsupp_tensor_finsupp'_single_tmul_single, mul_one, finsupp.map_domain_single, category_theory.tensor_apply], end lemma left_unitality (X : Type u) : (λ_ ((free R).obj X)).hom = (ε R ⊗ 𝟙 ((free R).obj X)) ≫ μ R (𝟙_ (Type u)) X ≫ map (free R).obj (λ_ X).hom := begin intros, ext, dsimp [ε, μ], simp_rw [finsupp_tensor_finsupp'_single_tmul_single, Module.monoidal_category.left_unitor_hom_apply, finsupp.smul_single', mul_one, finsupp.map_domain_single, category_theory.left_unitor_hom_apply], end lemma right_unitality (X : Type u) : (ρ_ ((free R).obj X)).hom = (𝟙 ((free R).obj X) ⊗ ε R) ≫ μ R X (𝟙_ (Type u)) ≫ map (free R).obj (ρ_ X).hom := begin intros, ext, dsimp [ε, μ], simp_rw [finsupp_tensor_finsupp'_single_tmul_single, Module.monoidal_category.right_unitor_hom_apply, finsupp.smul_single', mul_one, finsupp.map_domain_single, category_theory.right_unitor_hom_apply], end lemma associativity (X Y Z : Type u) : (μ R X Y ⊗ 𝟙 ((free R).obj Z)) ≫ μ R (X ⊗ Y) Z ≫ map (free R).obj (α_ X Y Z).hom = (α_ ((free R).obj X) ((free R).obj Y) ((free R).obj Z)).hom ≫ (𝟙 ((free R).obj X) ⊗ μ R Y Z) ≫ μ R X (Y ⊗ Z) := begin intros, ext, dsimp [μ], simp_rw [finsupp_tensor_finsupp'_single_tmul_single, finsupp.map_domain_single, mul_one, category_theory.associator_hom_apply], end /-- The free R-module functor is lax monoidal. -/ -- In fact, it's strong monoidal, but we don't yet have a typeclass for that. instance : lax_monoidal.{u} (free R).obj := { -- Send `R` to `punit →₀ R` ε := ε R, -- Send `(α →₀ R) ⊗ (β →₀ R)` to `α × β →₀ R` μ := μ R, μ_natural' := λ X Y X' Y' f g, μ_natural R f g, left_unitality' := left_unitality R, right_unitality' := right_unitality R, associativity' := associativity R, } end free end Module namespace category_theory universes v u /-- `Free R C` is a type synonym for `C`, which, given `[comm_ring R]` and `[category C]`, we will equip with a category structure where the morphisms are formal `R`-linear combinations of the morphisms in `C`. -/ @[nolint unused_arguments has_inhabited_instance] def Free (R : Type*) (C : Type u) := C /-- Consider an object of `C` as an object of the `R`-linear completion. -/ def Free.of (R : Type*) {C : Type u} (X : C) : Free R C := X variables (R : Type*) [comm_ring R] (C : Type u) [category.{v} C] open finsupp -- Conceptually, it would be nice to construct this via "transport of enrichment", -- using the fact that `Module.free R : Type ⥤ Module R` and `Module.forget` are both lax monoidal. -- This still seems difficult, so we just do it by hand. instance category_Free : category (Free R C) := { hom := λ (X Y : C), (X ⟶ Y) →₀ R, id := λ (X : C), finsupp.single (𝟙 X) 1, comp := λ (X Y Z : C) f g, f.sum (λ f' s, g.sum (λ g' t, finsupp.single (f' ≫ g') (s * t))), assoc' := λ W X Y Z f g h, begin dsimp, -- This imitates the proof of associativity for `monoid_algebra`. simp only [sum_sum_index, sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff, add_mul, mul_add, category.assoc, mul_assoc, zero_mul, mul_zero, sum_zero, sum_add], end }. namespace Free section local attribute [simp] category_theory.category_Free @[simp] lemma single_comp_single {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (r s : R) : (single f r ≫ single g s : (Free.of R X) ⟶ (Free.of R Z)) = single (f ≫ g) (r * s) := by { dsimp, simp, } instance : preadditive (Free R C) := { hom_group := λ X Y, finsupp.add_comm_group, add_comp' := λ X Y Z f f' g, begin dsimp, rw [finsupp.sum_add_index]; { simp [add_mul], } end, comp_add' := λ X Y Z f g g', begin dsimp, rw ← finsupp.sum_add, congr, ext r h, rw [finsupp.sum_add_index]; { simp [mul_add], }, end, } instance : linear R (Free R C) := { hom_module := λ X Y, finsupp.module (X ⟶ Y) R, smul_comp' := λ X Y Z r f g, begin dsimp, rw [finsupp.sum_smul_index]; simp [finsupp.smul_sum, mul_assoc], end, comp_smul' := λ X Y Z f r g, begin dsimp, simp_rw [finsupp.smul_sum], congr, ext h s, rw [finsupp.sum_smul_index]; simp [finsupp.smul_sum, mul_left_comm], end, } end /-- A category embeds into its `R`-linear completion. -/ @[simps] def embedding : C ⥤ Free R C := { obj := λ X, X, map := λ X Y f, finsupp.single f 1, map_id' := λ X, rfl, map_comp' := λ X Y Z f g, by simp, } variables (R) {C} {D : Type u} [category.{v} D] [preadditive D] [linear R D] open preadditive linear /-- A functor to a preadditive category lifts to a functor from its `R`-linear completion. -/ @[simps] def lift (F : C ⥤ D) : Free R C ⥤ D := { obj := λ X, F.obj X, map := λ X Y f, f.sum (λ f' r, r • (F.map f')), map_id' := by { dsimp [category_theory.category_Free], simp }, map_comp' := λ X Y Z f g, begin apply finsupp.induction_linear f, { simp, }, { intros f₁ f₂ w₁ w₂, rw add_comp, rw [finsupp.sum_add_index, finsupp.sum_add_index], { simp [w₁, w₂, add_comp], }, { simp, }, { intros, simp only [add_smul], }, { simp, }, { intros, simp only [add_smul], }, }, { intros f' r, apply finsupp.induction_linear g, { simp, }, { intros f₁ f₂ w₁ w₂, rw comp_add, rw [finsupp.sum_add_index, finsupp.sum_add_index], { simp [w₁, w₂, add_comp], }, { simp, }, { intros, simp only [add_smul], }, { simp, }, { intros, simp only [add_smul], }, }, { intros g' s, erw single_comp_single, simp [mul_comm r s, mul_smul], } } end, } @[simp] lemma lift_map_single (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) (r : R) : (lift R F).map (single f r) = r • F.map f := by simp instance lift_additive (F : C ⥤ D) : (lift R F).additive := { map_add' := λ X Y f g, begin dsimp, rw finsupp.sum_add_index; simp [add_smul] end, } instance lift_linear (F : C ⥤ D) : (lift R F).linear R := { map_smul' := λ X Y f r, begin dsimp, rw finsupp.sum_smul_index; simp [finsupp.smul_sum, mul_smul], end, } /-- The embedding into the `R`-linear completion, followed by the lift, is isomorphic to the original functor. -/ def embedding_lift_iso (F : C ⥤ D) : embedding R C ⋙ lift R F ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) /-- Two `R`-linear functors out of the `R`-linear completion are isomorphic iff their compositions with the embedding functor are isomorphic. -/ @[ext] def ext {F G : Free R C ⥤ D} [F.additive] [F.linear R] [G.additive] [G.linear R] (α : embedding R C ⋙ F ≅ embedding R C ⋙ G) : F ≅ G := nat_iso.of_components (λ X, α.app X) begin intros X Y f, apply finsupp.induction_linear f, { simp, }, { intros f₁ f₂ w₁ w₂, simp only [F.map_add, G.map_add, add_comp, comp_add, w₁, w₂], }, { intros f' r, rw [iso.app_hom, iso.app_hom, ←smul_single_one, F.map_smul, G.map_smul, smul_comp, comp_smul], change r • (embedding R C ⋙ F).map f' ≫ _ = r • _ ≫ (embedding R C ⋙ G).map f', rw α.hom.naturality f', apply_instance, -- Why are these not picked up automatically when we rewrite? apply_instance, } end /-- `Free.lift` is unique amongst `R`-linear functors `Free R C ⥤ D` which compose with `embedding ℤ C` to give the original functor. -/ def lift_unique (F : C ⥤ D) (L : Free R C ⥤ D) [L.additive] [L.linear R] (α : embedding R C ⋙ L ≅ F) : L ≅ lift R F := ext R (α.trans (embedding_lift_iso R F).symm) end Free end category_theory
d80abce7c7baba17ed73b53376752493d914009a
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Init/Prelude.lean
81ab8175c19af51a434c14b9dd410a266a8f2170
[ "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
73,282
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 -/ prelude universes u v w @[inline] def id {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a @[reducible] def inferInstance {α : Sort u} [i : α] : α := i @[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b from fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : [s : Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse h, _ => rfl theorem ofDecideEqTrue [s : Decidable p] : Eq (decide p) true → p := fun h => match (generalizing := false) s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse [s : Decidable p] : Eq (decide p) false → Not p := fun h => match (generalizing := false) s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class HasLessEq (α : Type u) where LessEq : α → α → Prop class HasLess (α : Type u) where Less : α → α → Prop export HasLess (Less) export HasLessEq (LessEq) class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → β → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → β → γ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAnd : α → β → γ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where hXor : α → β → γ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOr : α → β → γ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftLeft : α → β → γ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftRight : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) where pow : α → α → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → α → α class AndThen (α : Type u) where andThen : α → α → α class AndOp (α : Type u) where and : α → α → α class Xor (α : Type u) where xor : α → α → α class OrOp (α : Type u) where or : α → α → α class Complement (α : Type u) where complement : α → α class ShiftLeft (α : Type u) where shiftLeft : α → α → α class ShiftRight (α : Type u) where shiftRight : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α] : HPow α α α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[defaultInstance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[defaultInstance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[defaultInstance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[defaultInstance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[defaultInstance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) @[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := LessEq b a @[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := Less b a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eqOfBeqEqTrue : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have Eq (beq n m) true from h have Eq n m from eqOfBeqEqTrue this this ▸ rfl theorem Nat.neOfBeqEqFalse : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have Eq (beq n m) false from h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFalse this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eqOfBeqEqTrue h) | false => isFalse (neOfBeqEqFalse h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := Eq (ble n m) true instance : HasLessEq Nat where LessEq := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : HasLess Nat where Less := Nat.lt theorem Nat.notSuccLeZero : ∀ (n : Nat), LessEq (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.notLtZero (n : Nat) : Not (Less n 0) := notSuccLeZero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LessEq n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (Less n m) := decLe (succ n) m theorem Nat.zeroLe : (n : Nat) → LessEq 0 n | zero => rfl | succ n => rfl theorem Nat.succLeSucc {n m : Nat} (h : LessEq n m) : LessEq (succ n) (succ m) := h theorem Nat.zeroLtSucc (n : Nat) : Less 0 (succ n) := succLeSucc (zeroLe n) theorem Nat.leStep : {n m : Nat} → LessEq n m → LessEq n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h have LessEq n (succ m) from leStep this succLeSucc this protected theorem Nat.leTrans : {n m k : Nat} → LessEq n m → LessEq m k → LessEq n k | zero, m, k, h₁, h₂ => zeroLe _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m k from h₂ show LessEq n k from Nat.leTrans h₁' h₂' protected theorem Nat.ltTrans {n m k : Nat} (h₁ : Less n m) : Less m k → Less n k := Nat.leTrans (leStep h₁) theorem Nat.leSucc : (n : Nat) → LessEq n (succ n) | zero => rfl | succ n => leSucc n theorem Nat.leSuccOfLe {n m : Nat} (h : LessEq n m) : LessEq n (succ m) := Nat.leTrans h (leSucc m) protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LessEq n m → Or (Eq n m) (Less n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zeroLe n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h match Nat.eqOrLtOfLe this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succLeSucc h) protected def Nat.leRefl : (n : Nat) → LessEq n n | zero => rfl | succ n => Nat.leRefl n protected theorem Nat.ltOrGe (n m : Nat) : Or (Less n m) (GreaterEq n m) := match m with | zero => Or.inr (zeroLe n) | succ m => match Nat.ltOrGe n m with | Or.inl h => Or.inl (leSuccOfLe h) | Or.inr h => match Nat.eqOrLtOfLe h with | Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.leAntisymm : {n m : Nat} → LessEq n m → LessEq m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m n from h₂ (Nat.leAntisymm h₁' h₂') ▸ rfl protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LessEq n m) (h₂ : Not (Eq n m)) : Less n m := match Nat.ltOrGe n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂ set_option bootstrap.genMatcherCode false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub theorem Nat.predLePred : {n m : Nat} → LessEq n m → LessEq (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.leOfSuccLeSucc {n m : Nat} : LessEq (succ n) (succ m) → LessEq n m := predLePred theorem Nat.leOfLtSucc {m n : Nat} : Less m (succ n) → LessEq m n := leOfSuccLeSucc @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : Less val n theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (veqOfEq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eqOfVeq h) | isFalse h => isFalse (Fin.neOfVne h) instance {n} : HasLess (Fin n) where Less a b := Less a.val b.val instance {n} : HasLessEq (Fin n) where LessEq a b := LessEq a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (Less a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LessEq a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : Less n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : Less n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : Less n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : HasLess UInt32 where Less a b := Less a.val b.val instance : HasLessEq UInt32 where LessEq a b := LessEq a.val b.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (Less a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (Less n m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (LessEq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LessEq n m)) instance (a b : UInt32) : Decidable (Less a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LessEq a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : Less n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) def USize.size : Nat := hPow 2 System.Platform.numBits theorem usizeSzEq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBitsEq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : Less n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usizeSzEq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : Less n 4294967296) : USize := { val := { val := n isLt := match USize.size, usizeSzEq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.ltTrans h (by decide) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (Less n 0xd800) (And (Less 0xdfff n) (Less n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : Less n UInt32.size := match h with | Or.inl h => Nat.ltTrans h (by decide) | Or.inr ⟨_, h⟩ => Nat.ltTrans h (by decide) @[extern "lean_uint32_of_nat"] private def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (veqOfEq h') h theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eqOfVeq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eqOfVeq h) | isFalse h => isFalse (Char.neOfVne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LessEq v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LessEq v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LessEq v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.lengthAux {α : Type u} : List α → Nat → Nat | nil, n => n | cons a as, n => lengthAux as (Nat.succ n) def List.length {α : Type u} (as : List α) : Nat := lengthAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ := match as with | nil => fun _ => rfl | cons a as => fun n => aux a as n.succ aux a as 0 def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → Less i as.length → α | nil, i, h => absurd h (Nat.notLtZero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have Less i.succ as.length.succ from length_cons .. ▸ h get as i (Nat.leOfSuccLeSucc this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.sub b def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s startPos := 0 stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (Less i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (Less i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (Less j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → f α → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α β : Type u} → f α → f β → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {α β : Type u} → f α → f β → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y x seqLeft x y := bind x fun a => bind y (fun _ => pure a) seqRight x y := bind x fun _ => y instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (Less j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orelse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error arbitrary s @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ α) (y : EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Sort u) where hash : α → USize export Hashable (hash) @[extern "lean_usize_mix_hash"] constant mixHash (u₁ u₂ : USize) : USize @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : USize instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → USize → Name | num : Name → Nat → USize → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → USize | Name.anonymous => USize.ofNat32 1723 (by decide) | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (Less v USize.size) (fun h => USize.ofNatCore v h) (fun _ => USize.ofNat32 17 (by decide)))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) /- Synthesized token (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) /- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax where | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def groupKind : SyntaxNodeKind := `group def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ args => args.size | _ => 0 def isMissing : Syntax → Bool | Syntax.missing => true | _ => false def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def matchesNull (stx : Syntax) (n : Nat) : Bool := isNodeOf stx nullKind n def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId id) def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node k _ => node k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node k args => node k (args.setD i arg) | stx => stx /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (Less i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (pos := pos) ..) val, _ => some (pos.add val.bsize) | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (pos := pos) ..) val .., _ => some (pos.add val.bsize) | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (Less i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom src.getHeadInfo val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ constant MacroEnvPointed : PointedType.{0} def MacroEnv : Type := MacroEnvPointed.type instance : Inhabited MacroEnv where default := MacroEnvPointed.val structure Context where macroEnv : MacroEnv mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception MacroScope) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s, hAdd s 1))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope unsafe def mkMacroEnvImp (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv := unsafeCast expandMacro? @[implementedBy mkMacroEnvImp] constant mkMacroEnv (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv def expandMacroNotAvailable? (stx : Syntax) : MacroM (Option Syntax) := throwErrorAt stx "expandMacro has not been set" def mkMacroEnvSimple : MacroEnv := mkMacroEnv expandMacroNotAvailable? unsafe def expandMacro?Imp (stx : Syntax) : MacroM (Option Syntax) := bind read fun ctx => let f : Syntax → MacroM (Option Syntax) := unsafeCast (ctx.macroEnv) f stx /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ @[implementedBy expandMacro?Imp] constant expandMacro? : Syntax → MacroM (Option Syntax) end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
e92875d540c5ace76166f3c9fc606a46e1c311d6
e61a235b8468b03aee0120bf26ec615c045005d2
/tests/lean/run/trace.lean
3ad86865e012cba7db0b739901e5dc7248a1d223
[ "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
1,844
lean
import Init.Lean.Util.Trace open Lean structure MyState := (traceState : TraceState := {}) (s : Nat := 0) abbrev M := ReaderT Options (EStateM String MyState) /- We can enable tracing for a monad M by adding an instance of `SimpleMonadTracerAdapter M` -/ instance : SimpleMonadTracerAdapter M := { getOptions := read, getTraceState := MyState.traceState <$> get, addContext := pure, modifyTraceState := fun f => modify $ fun s => { s with traceState := f s.traceState } } def tst1 : M Unit := do trace! `module ("hello" ++ MessageData.nest 9 (Format.line ++ "world")); trace! `module.aux "another message"; pure () def tst2 (b : Bool) : M Unit := traceCtx `module $ do tst1; trace! `bughunt "at test2"; when b $ throw "error"; tst1; pure () partial def ack : Nat → Nat → Nat | 0, n => n+1 | m+1, 0 => ack m 1 | m+1, n+1 => ack m (ack (m+1) n) def slow (b : Bool) : Nat := ack 4 (cond b 0 1) def tst3 (b : Bool) : M Unit := do traceCtx `module $ do { tst2 b; tst1 }; trace! `bughunt "at end of tst3"; -- Messages are computed lazily. The following message will only be computed -- if `trace.slow is active. trace! `slow ("slow message: " ++ toString (slow b)) def runM (x : M Unit) : IO Unit := let opts := Options.empty; -- Try commeting/uncommeting the following `setBool`s let opts := opts.setBool `trace.module true; -- let opts := opts.setBool `trace.module.aux false; let opts := opts.setBool `trace.bughunt true; -- let opts := opts.setBool `trace.slow true; match x.run opts {} with | EStateM.Result.ok _ s => IO.println s.traceState | EStateM.Result.error _ s => do IO.println "Error"; IO.println s.traceState def main : IO Unit := do IO.println "----"; runM (tst3 true); IO.println "----"; runM (tst3 false); pure () #eval main
8fe5b85cf4179912cb82402d51c50f17aa8a41bd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/free_algebra.lean
b8bdac6c6853f419d3d6e461d29aa65ea3a42795
[ "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,186
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import linear_algebra.exterior_algebra.basic import linear_algebra.clifford_algebra.basic /-! Tests that the ring instances for `free_algebra` and derived quotient types actually work. There is some discussion about this in https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 In essence, the use of `attribute [irreducible] the_type` was breaking instance resolution on that type. -/ variables {S : Type*} {M : Type*} section free variables [comm_ring S] example : (1 : free_algebra S M) - (1 : free_algebra S M) = 0 := by rw sub_self end free section exterior variables [comm_ring S] [add_comm_group M] [module S M] example : (1 : exterior_algebra S M) - (1 : exterior_algebra S M) = 0 := by rw sub_self end exterior section clifford variables [comm_ring S] [add_comm_group M] [module S M] (Q : quadratic_form S M) example : (1 : clifford_algebra Q) - (1 : clifford_algebra Q) = 0 := by rw sub_self end clifford
77153a815569774f2f10a94be128bec6ec22b107
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.21.lean
c6e66ae337effdc4a4c74724f90c5b3c76da9a7d
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
167
lean
/- page 40 -/ import standard variables p q : Prop -- BEGIN example (Hp : p) : p ∨ q := or.intro_left q Hp example (Hq : q) : p ∨ q := or.intro_right p Hq -- END
4fefda0bdc3c712bb1602abd04e9e19c565403b8
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/secnot.lean
2feae895005cefa91a851c7a1e9f61df127a06c2
[ "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
396
lean
section variable {A : Type} definition f (a b : A) := a infixl ` ◀ `:65 := f variables a b : A #check a ◀ b end inductive List (T : Type) : Type | nil {} : List | cons : T → List → List namespace List section variable {T : Type} notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l #check [(10:nat), 20, 30] end end List open List #check [(10:nat), 20, 40] #check (10:nat) ◀ 20
9e566769c6c38c1f25e2d339efcda592d14be1d2
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/convex/quasiconvex.lean
a61ed4d00ffc2e8a878dbbf14d18f193090f262e
[ "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
7,890
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import analysis.convex.function /-! # Quasiconvex and quasiconcave functions This file defines quasiconvexity, quasiconcavity and quasilinearity of functions, which are generalizations of unimodality and monotonicity. Convexity implies quasiconvexity, concavity implies quasiconcavity, and monotonicity implies quasilinearity. ## Main declarations * `quasiconvex_on 𝕜 s f`: Quasiconvexity of the function `f` on the set `s` with scalars `𝕜`. This means that, for all `r`, `{x ∈ s | f x ≤ r}` is `𝕜`-convex. * `quasiconcave_on 𝕜 s f`: Quasiconcavity of the function `f` on the set `s` with scalars `𝕜`. This means that, for all `r`, `{x ∈ s | r ≤ f x}` is `𝕜`-convex. * `quasilinear_on 𝕜 s f`: Quasilinearity of the function `f` on the set `s` with scalars `𝕜`. This means that `f` is both quasiconvex and quasiconcave. ## TODO Prove that a quasilinear function between two linear orders is either monotone or antitone. This is not hard but quite a pain to go about as there are many cases to consider. ## References * https://en.wikipedia.org/wiki/Quasiconvex_function -/ open function set variables {𝕜 E F β : Type*} section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section ordered_add_comm_monoid variables (𝕜) [ordered_add_comm_monoid β] [has_scalar 𝕜 E] (s : set E) (f : E → β) /-- A function is quasiconvex if all its sublevels are convex. This means that, for all `r`, `{x ∈ s | f x ≤ r}` is `𝕜`-convex. -/ def quasiconvex_on : Prop := ∀ r, convex 𝕜 {x ∈ s | f x ≤ r} /-- A function is quasiconcave if all its superlevels are convex. This means that, for all `r`, `{x ∈ s | r ≤ f x}` is `𝕜`-convex. -/ def quasiconcave_on : Prop := ∀ r, convex 𝕜 {x ∈ s | r ≤ f x} /-- A function is quasilinear if it is both quasiconvex and quasiconcave. This means that, for all `r`, the sets `{x ∈ s | f x ≤ r}` and `{x ∈ s | r ≤ f x}` are `𝕜`-convex. -/ def quasilinear_on : Prop := quasiconvex_on 𝕜 s f ∧ quasiconcave_on 𝕜 s f variables {𝕜 s f} lemma quasiconvex_on.dual (hf : quasiconvex_on 𝕜 s f) : @quasiconcave_on 𝕜 E (order_dual β) _ _ _ _ s f := hf lemma quasiconcave_on.dual (hf : quasiconcave_on 𝕜 s f) : @quasiconvex_on 𝕜 E (order_dual β) _ _ _ _ s f := hf lemma quasilinear_on.dual (hf : quasilinear_on 𝕜 s f) : @quasilinear_on 𝕜 E (order_dual β) _ _ _ _ s f := ⟨hf.2, hf.1⟩ lemma convex.quasiconvex_on_of_convex_le (hs : convex 𝕜 s) (h : ∀ r, convex 𝕜 {x | f x ≤ r}) : quasiconvex_on 𝕜 s f := λ r, hs.inter (h r) lemma convex.quasiconcave_on_of_convex_ge (hs : convex 𝕜 s) (h : ∀ r, convex 𝕜 {x | r ≤ f x}) : quasiconcave_on 𝕜 s f := @convex.quasiconvex_on_of_convex_le 𝕜 E (order_dual β) _ _ _ _ _ _ hs h lemma quasiconvex_on.convex [is_directed β (≤)] (hf : quasiconvex_on 𝕜 s f) : convex 𝕜 s := λ x y hx hy a b ha hb hab, let ⟨z, hxz, hyz⟩ := exists_ge_ge (f x) (f y) in (hf _ ⟨hx, hxz⟩ ⟨hy, hyz⟩ ha hb hab).1 lemma quasiconcave_on.convex [is_directed β (swap (≤))] (hf : quasiconcave_on 𝕜 s f) : convex 𝕜 s := hf.dual.convex end ordered_add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid β] section has_scalar variables [has_scalar 𝕜 E] {s : set E} {f g : E → β} lemma quasiconvex_on.sup (hf : quasiconvex_on 𝕜 s f) (hg : quasiconvex_on 𝕜 s g) : quasiconvex_on 𝕜 s (f ⊔ g) := begin intro r, simp_rw [pi.sup_def, sup_le_iff, ←set.sep_inter_sep], exact (hf r).inter (hg r), end lemma quasiconcave_on.inf (hf : quasiconcave_on 𝕜 s f) (hg : quasiconcave_on 𝕜 s g) : quasiconcave_on 𝕜 s (f ⊓ g) := hf.dual.sup hg lemma quasiconvex_on_iff_le_max : quasiconvex_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ max (f x) (f y) := ⟨λ hf, ⟨hf.convex, λ x y hx hy a b ha hb hab, (hf _ ⟨hx, le_max_left _ _⟩ ⟨hy, le_max_right _ _⟩ ha hb hab).2⟩, λ hf r x y hx hy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha hb hab, (hf.2 hx.1 hy.1 ha hb hab).trans $ max_le hx.2 hy.2⟩⟩ lemma quasiconcave_on_iff_min_le : quasiconcave_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → min (f x) (f y) ≤ f (a • x + b • y) := @quasiconvex_on_iff_le_max 𝕜 E (order_dual β) _ _ _ _ _ _ lemma quasilinear_on_iff_mem_interval : quasilinear_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ∈ interval (f x) (f y) := begin rw [quasilinear_on, quasiconvex_on_iff_le_max, quasiconcave_on_iff_min_le, and_and_and_comm, and_self], apply and_congr_right', simp_rw [←forall_and_distrib, interval, mem_Icc, and_comm], end lemma quasiconvex_on.convex_lt (hf : quasiconvex_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | f x < r} := begin refine λ x y hx hy a b ha hb hab, _, have h := hf _ ⟨hx.1, le_max_left _ _⟩ ⟨hy.1, le_max_right _ _⟩ ha hb hab, exact ⟨h.1, h.2.trans_lt $ max_lt hx.2 hy.2⟩, end lemma quasiconcave_on.convex_gt (hf : quasiconcave_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | r < f x} := hf.dual.convex_lt r end has_scalar section ordered_smul variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β} lemma convex_on.quasiconvex_on (hf : convex_on 𝕜 s f) : quasiconvex_on 𝕜 s f := hf.convex_le lemma concave_on.quasiconcave_on (hf : concave_on 𝕜 s f) : quasiconcave_on 𝕜 s f := hf.convex_ge end ordered_smul end linear_ordered_add_comm_monoid end add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid E] [ordered_add_comm_monoid β] [module 𝕜 E] [ordered_smul 𝕜 E] {s : set E} {f : E → β} lemma monotone_on.quasiconvex_on (hf : monotone_on f s) (hs : convex 𝕜 s) : quasiconvex_on 𝕜 s f := hf.convex_le hs lemma monotone_on.quasiconcave_on (hf : monotone_on f s) (hs : convex 𝕜 s) : quasiconcave_on 𝕜 s f := hf.convex_ge hs lemma monotone_on.quasilinear_on (hf : monotone_on f s) (hs : convex 𝕜 s) : quasilinear_on 𝕜 s f := ⟨hf.quasiconvex_on hs, hf.quasiconcave_on hs⟩ lemma antitone_on.quasiconvex_on (hf : antitone_on f s) (hs : convex 𝕜 s) : quasiconvex_on 𝕜 s f := hf.convex_le hs lemma antitone_on.quasiconcave_on (hf : antitone_on f s) (hs : convex 𝕜 s) : quasiconcave_on 𝕜 s f := hf.convex_ge hs lemma antitone_on.quasilinear_on (hf : antitone_on f s) (hs : convex 𝕜 s) : quasilinear_on 𝕜 s f := ⟨hf.quasiconvex_on hs, hf.quasiconcave_on hs⟩ lemma monotone.quasiconvex_on (hf : monotone f) : quasiconvex_on 𝕜 univ f := (hf.monotone_on _).quasiconvex_on convex_univ lemma monotone.quasiconcave_on (hf : monotone f) : quasiconcave_on 𝕜 univ f := (hf.monotone_on _).quasiconcave_on convex_univ lemma monotone.quasilinear_on (hf : monotone f) : quasilinear_on 𝕜 univ f := ⟨hf.quasiconvex_on, hf.quasiconcave_on⟩ lemma antitone.quasiconvex_on (hf : antitone f) : quasiconvex_on 𝕜 univ f := (hf.antitone_on _).quasiconvex_on convex_univ lemma antitone.quasiconcave_on (hf : antitone f) : quasiconcave_on 𝕜 univ f := (hf.antitone_on _).quasiconcave_on convex_univ lemma antitone.quasilinear_on (hf : antitone f) : quasilinear_on 𝕜 univ f := ⟨hf.quasiconvex_on, hf.quasiconcave_on⟩ end linear_ordered_add_comm_monoid end ordered_semiring
d02f37cfbd2e43fc11ea51781f66cc29a80a682d
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/affine_space/affine_map.lean
cc91f90be1ac5ba50671dec15cd3f579ceb87b57
[ "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
20,787
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.basic import linear_algebra.tensor_product import linear_algebra.prod import linear_algebra.pi import data.set.intervals.unordered_interval /-! # Affine maps This file defines affine maps. ## Main definitions * `affine_map` is the type of affine maps between two affine spaces with the same ring `k`. Various basic examples of affine maps are defined, including `const`, `id`, `line_map` and `homothety`. ## Notations * `P1 →ᵃ[k] P2` is a notation for `affine_map k P1 P2`; * `affine_space V P`: a localized notation for `add_torsor V P` defined in `linear_algebra.affine_space.basic`. ## Implementation notes `out_param` is used in the definition of `[add_torsor V P]` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ open_locale affine /-- An `affine_map k P1 P2` (notation: `P1 →ᵃ[k] P2`) is a map from `P1` to `P2` that induces a corresponding linear map from `V1` to `V2`. -/ structure affine_map (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] := (to_fun : P1 → P2) (linear : V1 →ₗ[k] V2) (map_vadd' : ∀ (p : P1) (v : V1), to_fun (v +ᵥ p) = linear v +ᵥ to_fun p) notation P1 ` →ᵃ[`:25 k:25 `] `:0 P2:0 := affine_map k P1 P2 instance (k : Type*) {V1 : Type*} (P1 : Type*) {V2 : Type*} (P2 : Type*) [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2]: has_coe_to_fun (P1 →ᵃ[k] P2) := ⟨_, affine_map.to_fun⟩ namespace linear_map variables {k : Type*} {V₁ : Type*} {V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_comm_group V₂] [module k V₂] (f : V₁ →ₗ[k] V₂) /-- Reinterpret a linear map as an affine map. -/ def to_affine_map : V₁ →ᵃ[k] V₂ := { to_fun := f, linear := f, map_vadd' := λ p v, f.map_add v p } @[simp] lemma coe_to_affine_map : ⇑f.to_affine_map = f := rfl @[simp] lemma to_affine_map_linear : f.to_affine_map.linear = f := rfl end linear_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} {P2 : Type*} {V3 : Type*} {P3 : Type*} {V4 : Type*} {P4 : Type*} [ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] [affine_space V2 P2] [add_comm_group V3] [module k V3] [affine_space V3 P3] [add_comm_group V4] [module k V4] [affine_space V4 P4] include V1 V2 /-- Constructing an affine map and coercing back to a function produces the same map. -/ @[simp] lemma coe_mk (f : P1 → P2) (linear add) : ((mk f linear add : P1 →ᵃ[k] P2) : P1 → P2) = f := rfl /-- `to_fun` is the same as the result of coercing to a function. -/ @[simp] lemma to_fun_eq_coe (f : P1 →ᵃ[k] P2) : f.to_fun = ⇑f := rfl /-- An affine map on the result of adding a vector to a point produces the same result as the linear map applied to that vector, added to the affine map applied to that point. -/ @[simp] lemma map_vadd (f : P1 →ᵃ[k] P2) (p : P1) (v : V1) : f (v +ᵥ p) = f.linear v +ᵥ f p := f.map_vadd' p v /-- The linear map on the result of subtracting two points is the result of subtracting the result of the affine map on those two points. -/ @[simp] lemma linear_map_vsub (f : P1 →ᵃ[k] P2) (p1 p2 : P1) : f.linear (p1 -ᵥ p2) = f p1 -ᵥ f p2 := by conv_rhs { rw [←vsub_vadd p1 p2, map_vadd, vadd_vsub] } /-- Two affine maps are equal if they coerce to the same function. -/ @[ext] lemma ext {f g : P1 →ᵃ[k] P2} (h : ∀ p, f p = g p) : f = g := begin rcases f with ⟨f, f_linear, f_add⟩, rcases g with ⟨g, g_linear, g_add⟩, have : f = g := funext h, subst g, congr' with v, cases (add_torsor.nonempty : nonempty P1) with p, apply vadd_right_cancel (f p), erw [← f_add, ← g_add] end lemma ext_iff {f g : P1 →ᵃ[k] P2} : f = g ↔ ∀ p, f p = g p := ⟨λ h p, h ▸ rfl, ext⟩ lemma coe_fn_injective : @function.injective (P1 →ᵃ[k] P2) (P1 → P2) coe_fn := λ f g H, ext $ congr_fun H protected lemma congr_arg (f : P1 →ᵃ[k] P2) {x y : P1} (h : x = y) : f x = f y := congr_arg _ h protected lemma congr_fun {f g : P1 →ᵃ[k] P2} (h : f = g) (x : P1) : f x = g x := h ▸ rfl variables (k P1) /-- Constant function as an `affine_map`. -/ def const (p : P2) : P1 →ᵃ[k] P2 := { to_fun := function.const P1 p, linear := 0, map_vadd' := λ p v, by simp } @[simp] lemma coe_const (p : P2) : ⇑(const k P1 p) = function.const P1 p := rfl @[simp] lemma const_linear (p : P2) : (const k P1 p).linear = 0 := rfl variables {k P1} instance nonempty : nonempty (P1 →ᵃ[k] P2) := (add_torsor.nonempty : nonempty P2).elim $ λ p, ⟨const k P1 p⟩ /-- Construct an affine map by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `f : P₁ → P₂`, a linear map `f' : V₁ →ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `f p' = f' (p' -ᵥ p) +ᵥ f p`. -/ def mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p : P1) (h : ∀ p' : P1, f p' = f' (p' -ᵥ p) +ᵥ f p) : P1 →ᵃ[k] P2 := { to_fun := f, linear := f', map_vadd' := λ p' v, by rw [h, h p', vadd_vsub_assoc, f'.map_add, vadd_vadd] } @[simp] lemma coe_mk' (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : ⇑(mk' f f' p h) = f := rfl @[simp] lemma mk'_linear (f : P1 → P2) (f' : V1 →ₗ[k] V2) (p h) : (mk' f f' p h).linear = f' := rfl /-- The set of affine maps to a vector space is an additive commutative group. -/ instance : add_comm_group (P1 →ᵃ[k] V2) := { zero := ⟨0, 0, λ p v, (zero_vadd _ _).symm⟩, add := λ f g, ⟨f + g, f.linear + g.linear, λ p v, by simp [add_add_add_comm]⟩, neg := λ f, ⟨-f, -f.linear, λ p v, by simp [add_comm]⟩, add_assoc := λ f₁ f₂ f₃, ext $ λ p, add_assoc _ _ _, zero_add := λ f, ext $ λ p, zero_add (f p), add_zero := λ f, ext $ λ p, add_zero (f p), add_comm := λ f g, ext $ λ p, add_comm (f p) (g p), add_left_neg := λ f, ext $ λ p, add_left_neg (f p) } @[simp, norm_cast] lemma coe_zero : ⇑(0 : P1 →ᵃ[k] V2) = 0 := rfl @[simp] lemma zero_linear : (0 : P1 →ᵃ[k] V2).linear = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : P1 →ᵃ[k] V2) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : P1 →ᵃ[k] V2) : ⇑(-f) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : P1 →ᵃ[k] V2) : ⇑(f - g) = f - g := by simp [sub_eq_add_neg] @[simp] lemma add_linear (f g : P1 →ᵃ[k] V2) : (f + g).linear = f.linear + g.linear := rfl /-- The space of affine maps from `P1` to `P2` is an affine space over the space of affine maps from `P1` to the vector space `V2` corresponding to `P2`. -/ instance : affine_space (P1 →ᵃ[k] V2) (P1 →ᵃ[k] P2) := { vadd := λ f g, ⟨λ p, f p +ᵥ g p, f.linear + g.linear, λ p v, by simp [vadd_vadd, add_right_comm]⟩, zero_vadd := λ f, ext $ λ p, zero_vadd _ (f p), add_vadd := λ f₁ f₂ f₃, ext $ λ p, add_vadd (f₁ p) (f₂ p) (f₃ p), vsub := λ f g, ⟨λ p, f p -ᵥ g p, f.linear - g.linear, λ p v, by simp [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, sub_add_eq_add_sub]⟩, vsub_vadd' := λ f g, ext $ λ p, vsub_vadd (f p) (g p), vadd_vsub' := λ f g, ext $ λ p, vadd_vsub (f p) (g p) } @[simp] lemma vadd_apply (f : P1 →ᵃ[k] V2) (g : P1 →ᵃ[k] P2) (p : P1) : (f +ᵥ g) p = f p +ᵥ g p := rfl @[simp] lemma vsub_apply (f g : P1 →ᵃ[k] P2) (p : P1) : (f -ᵥ g : P1 →ᵃ[k] V2) p = f p -ᵥ g p := rfl /-- `prod.fst` as an `affine_map`. -/ def fst : (P1 × P2) →ᵃ[k] P1 := { to_fun := prod.fst, linear := linear_map.fst k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_fst : ⇑(fst : (P1 × P2) →ᵃ[k] P1) = prod.fst := rfl @[simp] lemma fst_linear : (fst : (P1 × P2) →ᵃ[k] P1).linear = linear_map.fst k V1 V2 := rfl /-- `prod.snd` as an `affine_map`. -/ def snd : (P1 × P2) →ᵃ[k] P2 := { to_fun := prod.snd, linear := linear_map.snd k V1 V2, map_vadd' := λ _ _, rfl } @[simp] lemma coe_snd : ⇑(snd : (P1 × P2) →ᵃ[k] P2) = prod.snd := rfl @[simp] lemma snd_linear : (snd : (P1 × P2) →ᵃ[k] P2).linear = linear_map.snd k V1 V2 := rfl variables (k P1) omit V2 /-- Identity map as an affine map. -/ def id : P1 →ᵃ[k] P1 := { to_fun := id, linear := linear_map.id, map_vadd' := λ p v, rfl } /-- The identity affine map acts as the identity. -/ @[simp] lemma coe_id : ⇑(id k P1) = _root_.id := rfl @[simp] lemma id_linear : (id k P1).linear = linear_map.id := rfl variable {P1} /-- The identity affine map acts as the identity. -/ lemma id_apply (p : P1) : id k P1 p = p := rfl variables {k P1} instance : inhabited (P1 →ᵃ[k] P1) := ⟨id k P1⟩ include V2 V3 /-- Composition of affine maps. -/ def comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : P1 →ᵃ[k] P3 := { to_fun := f ∘ g, linear := f.linear.comp g.linear, map_vadd' := begin intros p v, rw [function.comp_app, g.map_vadd, f.map_vadd], refl end } /-- Composition of affine maps acts as applying the two functions. -/ @[simp] lemma coe_comp (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) : ⇑(f.comp g) = f ∘ g := rfl /-- Composition of affine maps acts as applying the two functions. -/ lemma comp_apply (f : P2 →ᵃ[k] P3) (g : P1 →ᵃ[k] P2) (p : P1) : f.comp g p = f (g p) := rfl omit V3 @[simp] lemma comp_id (f : P1 →ᵃ[k] P2) : f.comp (id k P1) = f := ext $ λ p, rfl @[simp] lemma id_comp (f : P1 →ᵃ[k] P2) : (id k P2).comp f = f := ext $ λ p, rfl include V3 V4 lemma comp_assoc (f₃₄ : P3 →ᵃ[k] P4) (f₂₃ : P2 →ᵃ[k] P3) (f₁₂ : P1 →ᵃ[k] P2) : (f₃₄.comp f₂₃).comp f₁₂ = f₃₄.comp (f₂₃.comp f₁₂) := rfl omit V2 V3 V4 instance : monoid (P1 →ᵃ[k] P1) := { one := id k P1, mul := comp, one_mul := id_comp, mul_one := comp_id, mul_assoc := comp_assoc } @[simp] lemma coe_mul (f g : P1 →ᵃ[k] P1) : ⇑(f * g) = f ∘ g := rfl @[simp] lemma coe_one : ⇑(1 : P1 →ᵃ[k] P1) = _root_.id := rfl include V2 @[simp] lemma injective_iff_linear_injective (f : P1 →ᵃ[k] P2) : function.injective f.linear ↔ function.injective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_injective, equiv.injective_comp], end @[simp] lemma surjective_iff_linear_surjective (f : P1 →ᵃ[k] P2) : function.surjective f.linear ↔ function.surjective f := begin obtain ⟨p⟩ := (infer_instance : nonempty P1), have h : ⇑f.linear = (equiv.vadd_const (f p)).symm ∘ f ∘ (equiv.vadd_const p), { ext v, simp [f.map_vadd, vadd_vsub_assoc], }, rw [h, equiv.comp_surjective, equiv.surjective_comp], end lemma image_vsub_image {s t : set P1} (f : P1 →ᵃ[k] P2) : (f '' s) -ᵥ (f '' t) = f.linear '' (s -ᵥ t) := begin ext v, simp only [set.mem_vsub, set.mem_image, exists_exists_and_eq_and, exists_and_distrib_left, ← f.linear_map_vsub], split, { rintros ⟨x, hx, y, hy, hv⟩, exact ⟨x -ᵥ y, ⟨x, hx, y, hy, rfl⟩, hv⟩, }, { rintros ⟨-, ⟨x, hx, y, hy, rfl⟩, rfl⟩, exact ⟨x, hx, y, hy, rfl⟩, }, end omit V2 /-! ### Definition of `affine_map.line_map` and lemmas about it -/ /-- The affine map from `k` to `P1` sending `0` to `p₀` and `1` to `p₁`. -/ def line_map (p₀ p₁ : P1) : k →ᵃ[k] P1 := ((linear_map.id : k →ₗ[k] k).smul_right (p₁ -ᵥ p₀)).to_affine_map +ᵥ const k k p₀ lemma coe_line_map (p₀ p₁ : P1) : (line_map p₀ p₁ : k → P1) = λ c, c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c = c • (p₁ -ᵥ p₀) +ᵥ p₀ := rfl lemma line_map_apply_module' (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = c • (p₁ - p₀) + p₀ := rfl lemma line_map_apply_module (p₀ p₁ : V1) (c : k) : line_map p₀ p₁ c = (1 - c) • p₀ + c • p₁ := by simp [line_map_apply_module', smul_sub, sub_smul]; abel omit V1 lemma line_map_apply_ring' (a b c : k) : line_map a b c = c * (b - a) + a := rfl lemma line_map_apply_ring (a b c : k) : line_map a b c = (1 - c) * a + c * b := line_map_apply_module a b c include V1 lemma line_map_vadd_apply (p : P1) (v : V1) (c : k) : line_map p (v +ᵥ p) c = c • v +ᵥ p := by rw [line_map_apply, vadd_vsub] @[simp] lemma line_map_linear (p₀ p₁ : P1) : (line_map p₀ p₁ : k →ᵃ[k] P1).linear = linear_map.id.smul_right (p₁ -ᵥ p₀) := add_zero _ lemma line_map_same_apply (p : P1) (c : k) : line_map p p c = p := by simp [line_map_apply] @[simp] lemma line_map_same (p : P1) : line_map p p = const k k p := ext $ line_map_same_apply p @[simp] lemma line_map_apply_zero (p₀ p₁ : P1) : line_map p₀ p₁ (0:k) = p₀ := by simp [line_map_apply] @[simp] lemma line_map_apply_one (p₀ p₁ : P1) : line_map p₀ p₁ (1:k) = p₁ := by simp [line_map_apply] include V2 @[simp] lemma apply_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) (c : k) : f (line_map p₀ p₁ c) = line_map (f p₀) (f p₁) c := by simp [line_map_apply] @[simp] lemma comp_line_map (f : P1 →ᵃ[k] P2) (p₀ p₁ : P1) : f.comp (line_map p₀ p₁) = line_map (f p₀) (f p₁) := ext $ f.apply_line_map p₀ p₁ @[simp] lemma fst_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).1 = line_map p₀.1 p₁.1 c := fst.apply_line_map p₀ p₁ c @[simp] lemma snd_line_map (p₀ p₁ : P1 × P2) (c : k) : (line_map p₀ p₁ c).2 = line_map p₀.2 p₁.2 c := snd.apply_line_map p₀ p₁ c omit V2 lemma line_map_symm (p₀ p₁ : P1) : line_map p₀ p₁ = (line_map p₁ p₀).comp (line_map (1:k) (0:k)) := by { rw [comp_line_map], simp } lemma line_map_apply_one_sub (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ (1 - c) = line_map p₁ p₀ c := by { rw [line_map_symm p₀, comp_apply], congr, simp [line_map_apply] } @[simp] lemma line_map_vsub_left (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₀ = c • (p₁ -ᵥ p₀) := vadd_vsub _ _ @[simp] lemma left_vsub_line_map (p₀ p₁ : P1) (c : k) : p₀ -ᵥ line_map p₀ p₁ c = c • (p₀ -ᵥ p₁) := by rw [← neg_vsub_eq_vsub_rev, line_map_vsub_left, ← smul_neg, neg_vsub_eq_vsub_rev] @[simp] lemma line_map_vsub_right (p₀ p₁ : P1) (c : k) : line_map p₀ p₁ c -ᵥ p₁ = (1 - c) • (p₀ -ᵥ p₁) := by rw [← line_map_apply_one_sub, line_map_vsub_left] @[simp] lemma right_vsub_line_map (p₀ p₁ : P1) (c : k) : p₁ -ᵥ line_map p₀ p₁ c = (1 - c) • (p₁ -ᵥ p₀) := by rw [← line_map_apply_one_sub, left_vsub_line_map] lemma line_map_vadd_line_map (v₁ v₂ : V1) (p₁ p₂ : P1) (c : k) : line_map v₁ v₂ c +ᵥ line_map p₁ p₂ c = line_map (v₁ +ᵥ p₁) (v₂ +ᵥ p₂) c := ((fst : V1 × P1 →ᵃ[k] V1) +ᵥ snd).apply_line_map (v₁, p₁) (v₂, p₂) c lemma line_map_vsub_line_map (p₁ p₂ p₃ p₄ : P1) (c : k) : line_map p₁ p₂ c -ᵥ line_map p₃ p₄ c = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) c := -- Why Lean fails to find this instance without a hint? by letI : affine_space (V1 × V1) (P1 × P1) := prod.add_torsor; exact ((fst : P1 × P1 →ᵃ[k] P1) -ᵥ (snd : P1 × P1 →ᵃ[k] P1)).apply_line_map (_, _) (_, _) c /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp (f : V1 →ᵃ[k] V2) : (f : V1 → V2) = f.linear + (λ z, f 0) := begin ext x, calc f x = f.linear x +ᵥ f 0 : by simp [← f.map_vadd] ... = (f.linear.to_fun + λ (z : V1), f 0) x : by simp end /-- Decomposition of an affine map in the special case when the point space and vector space are the same. -/ lemma decomp' (f : V1 →ᵃ[k] V2) : (f.linear : V1 → V2) = f - (λ z, f 0) := by rw decomp ; simp only [linear_map.map_zero, pi.add_apply, add_sub_cancel, zero_add] omit V1 lemma image_interval {k : Type*} [linear_ordered_field k] (f : k →ᵃ[k] k) (a b : k) : f '' set.interval a b = set.interval (f a) (f b) := begin have : ⇑f = (λ x, x + f 0) ∘ λ x, x * (f 1 - f 0), { ext x, change f x = x • (f 1 -ᵥ f 0) +ᵥ f 0, rw [← f.linear_map_vsub, ← f.linear.map_smul, ← f.map_vadd], simp only [vsub_eq_sub, add_zero, mul_one, vadd_eq_add, sub_zero, smul_eq_mul] }, rw [this, set.image_comp], simp only [set.image_add_const_interval, set.image_mul_const_interval] end section variables {ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [Π i, add_comm_group (V i)] [Π i, module k (V i)] [Π i, add_torsor (V i) (P i)] include V /-- Evaluation at a point as an affine map. -/ def proj (i : ι) : (Π i : ι, P i) →ᵃ[k] P i := { to_fun := λ f, f i, linear := @linear_map.proj k ι _ V _ _ i, map_vadd' := λ p v, rfl } @[simp] lemma proj_apply (i : ι) (f : Π i, P i) : @proj k _ ι V P _ _ _ i f = f i := rfl @[simp] lemma proj_linear (i : ι) : (@proj k _ ι V P _ _ _ i).linear = @linear_map.proj k ι _ V _ _ i := rfl lemma pi_line_map_apply (f g : Π i, P i) (c : k) (i : ι) : line_map f g c i = line_map (f i) (g i) c := (proj i : (Π i, P i) →ᵃ[k] P i).apply_line_map f g c end end affine_map namespace affine_map variables {k : Type*} {V1 : Type*} {P1 : Type*} {V2 : Type*} [comm_ring k] [add_comm_group V1] [module k V1] [affine_space V1 P1] [add_comm_group V2] [module k V2] include V1 /-- If `k` is a commutative ring, then the set of affine maps with codomain in a `k`-module is a `k`-module. -/ instance : module k (P1 →ᵃ[k] V2) := { smul := λ c f, ⟨c • f, c • f.linear, λ p v, by simp [smul_add]⟩, one_smul := λ f, ext $ λ p, one_smul _ _, mul_smul := λ c₁ c₂ f, ext $ λ p, mul_smul _ _ _, smul_add := λ c f g, ext $ λ p, smul_add _ _ _, smul_zero := λ c, ext $ λ p, smul_zero _, add_smul := λ c₁ c₂ f, ext $ λ p, add_smul _ _ _, zero_smul := λ f, ext $ λ p, zero_smul _ _ } @[simp] lemma coe_smul (c : k) (f : P1 →ᵃ[k] V2) : ⇑(c • f) = c • f := rfl /-- `homothety c r` is the homothety (also known as dilation) about `c` with scale factor `r`. -/ def homothety (c : P1) (r : k) : P1 →ᵃ[k] P1 := r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c lemma homothety_def (c : P1) (r : k) : homothety c r = r • (id k P1 -ᵥ const k P1 c) +ᵥ const k P1 c := rfl lemma homothety_apply (c : P1) (r : k) (p : P1) : homothety c r p = r • (p -ᵥ c : V1) +ᵥ c := rfl lemma homothety_eq_line_map (c : P1) (r : k) (p : P1) : homothety c r p = line_map c p r := rfl @[simp] lemma homothety_one (c : P1) : homothety c (1:k) = id k P1 := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_apply_same (c : P1) (r : k) : homothety c r c = c := line_map_same_apply c r lemma homothety_mul (c : P1) (r₁ r₂ : k) : homothety c (r₁ * r₂) = (homothety c r₁).comp (homothety c r₂) := by { ext p, simp [homothety_apply, mul_smul] } @[simp] lemma homothety_zero (c : P1) : homothety c (0:k) = const k P1 c := by { ext p, simp [homothety_apply] } @[simp] lemma homothety_add (c : P1) (r₁ r₂ : k) : homothety c (r₁ + r₂) = r₁ • (id k P1 -ᵥ const k P1 c) +ᵥ homothety c r₂ := by simp only [homothety_def, add_smul, vadd_vadd] /-- `homothety` as a multiplicative monoid homomorphism. -/ def homothety_hom (c : P1) : k →* P1 →ᵃ[k] P1 := ⟨homothety c, homothety_one c, homothety_mul c⟩ @[simp] lemma coe_homothety_hom (c : P1) : ⇑(homothety_hom c : k →* _) = homothety c := rfl /-- `homothety` as an affine map. -/ def homothety_affine (c : P1) : k →ᵃ[k] (P1 →ᵃ[k] P1) := ⟨homothety c, (linear_map.lsmul k _).flip (id k P1 -ᵥ const k P1 c), function.swap (homothety_add c)⟩ @[simp] lemma coe_homothety_affine (c : P1) : ⇑(homothety_affine c : k →ᵃ[k] _) = homothety c := rfl end affine_map
8e2a3a401f928b1a1d7aa94d4b648ade58e95637
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/measure_theory/giry_monad.lean
1493985e45219b866201963943a0893c85d1da32
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
6,951
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 Giry monad: `measure` is a monad in the category of `measurable_space` and `measurable` functions. -/ import measure_theory.integration noncomputable theory local attribute [instance, priority 0] classical.prop_decidable open classical set lattice filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ε : Type*} namespace measure_theory namespace measure variables [measurable_space α] [measurable_space β] /-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/ instance : measurable_space (measure α) := ⨆ (s : set α) (hs : is_measurable s), (borel ennreal).comap (λμ, μ s) lemma measurable_coe {s : set α} (hs : is_measurable s) : measurable (λμ : measure α, μ s) := measurable_space.comap_le_iff_le_map.1 $ le_supr_of_le s $ le_supr_of_le hs $ le_refl _ lemma measurable_of_measurable_coe (f : β → measure α) (h : ∀(s : set α) (hs : is_measurable s), measurable (λb, f b s)) : measurable f := supr_le $ assume s, supr_le $ assume hs, measurable_space.comap_le_iff_le_map.2 $ by rw [measurable_space.map_comp]; exact h s hs lemma measurable_map (f : α → β) (hf : measurable f) : measurable (λμ : measure α, μ.map f) := measurable_of_measurable_coe _ $ assume s hs, suffices measurable (λ (μ : measure α), μ (f ⁻¹' s)), by simpa [map_apply, hs, hf], measurable_coe (hf.preimage hs) lemma measurable_dirac : measurable (measure.dirac : α → measure α) := measurable_of_measurable_coe _ $ assume s hs, begin simp [hs, lattice.supr_eq_if], exact measurable_const.if hs measurable_const end lemma measurable_integral (f : α → ennreal) (hf : measurable f) : measurable (λμ : measure α, μ.integral f) := suffices measurable (λμ : measure α, (⨆n:ℕ, @simple_func.integral α { μ := μ } (simple_func.eapprox f n)) : _ → ennreal), begin convert this, funext μ, exact @lintegral_eq_supr_eapprox_integral α {μ := μ} f hf end, measurable.supr $ assume n, begin dunfold simple_func.integral, refine measurable_finset_sum (simple_func.eapprox f n).range _, assume i, refine ennreal.measurable_mul measurable_const _, exact measurable_coe ((simple_func.eapprox f n).preimage_measurable _) end /-- Monadic join on `measure` in the category of measurable spaces and measurable functions. -/ def join (m : measure (measure α)) : measure α := measure.of_measurable (λs hs, m.integral (λμ, μ s)) (by simp [integral]) begin assume f hf h, simp [measure_Union h hf], apply lintegral_tsum, assume i, exact measurable_coe (hf i) end @[simp] lemma join_apply {m : measure (measure α)} : ∀{s : set α}, is_measurable s → join m s = m.integral (λμ, μ s) := measure.of_measurable_apply lemma measurable_join : measurable (join : measure (measure α) → measure α) := measurable_of_measurable_coe _ $ assume s hs, by simp [hs]; exact measurable_integral _ (measurable_coe hs) lemma integral_join {m : measure (measure α)} {f : α → ennreal} (hf : measurable f) : integral (join m) f = integral m (λμ, integral μ f) := begin transitivity, apply lintegral_eq_supr_eapprox_integral, { exact hf }, have : ∀n x, @volume α { μ := join m} (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}) = m.integral (λμ, @volume α { μ := μ } ((⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}))) := assume n x, join_apply (simple_func.measurable_sn _ _), conv { to_lhs, congr, funext, rw [simple_func.integral] }, simp [this], transitivity, have : ∀(s : ℕ → finset ennreal) (f : ℕ → ennreal → measure α → ennreal) (hf : ∀n r, measurable (f n r)) (hm : monotone (λn μ, (s n).sum (λ r, r * f n r μ))), (⨆n:ℕ, (s n).sum (λr, r * integral m (f n r))) = integral m (λμ, ⨆n:ℕ, (s n).sum (λr, r * f n r μ)), { assume s f hf hm, symmetry, transitivity, apply lintegral_supr, { exact assume n, measurable_finset_sum _ (assume r, ennreal.measurable_mul measurable_const (hf _ _)) }, { exact hm }, congr, funext n, transitivity, apply lintegral_finset_sum, { exact assume r, ennreal.measurable_mul measurable_const (hf _ _) }, congr, funext r, apply lintegral_const_mul, exact hf _ _ }, specialize this (λn, simple_func.range (simple_func.eapprox f n)), specialize this (λn r μ, @volume α { μ := μ } (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {r})), refine this _ _; clear this, { assume n r, apply measurable_coe, exact simple_func.measurable_sn _ _ }, { change monotone (λn μ, @simple_func.integral α {μ := μ} (simple_func.eapprox f n)), assume n m h μ, apply simple_func.integral_le_integral, apply simple_func.monotone_eapprox, assumption }, congr, funext μ, symmetry, apply lintegral_eq_supr_eapprox_integral, exact hf end /-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable functions. When the function `f` is not measurable the result is not well defined. -/ def bind (m : measure α) (f : α → measure β) : measure β := join (map f m) @[simp] lemma bind_apply {m : measure α} {f : α → measure β} {s : set β} (hs : is_measurable s) (hf : measurable f) : bind m f s = m.integral (λa, f a s) := by rw [bind, join_apply hs, integral_map (measurable_coe hs) hf] lemma measurable_bind' {g : α → measure β} (hg : measurable g) : measurable (λm, bind m g) := measurable.comp (measurable_map _ hg) measurable_join lemma integral_bind {m : measure α} {g : α → measure β} {f : β → ennreal} (hg : measurable g) (hf : measurable f) : integral (bind m g) f = integral m (λa, integral (g a) f) := begin transitivity, exact integral_join hf, exact integral_map (measurable_integral _ hf) hg end lemma bind_bind {γ} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ} (hf : measurable f) (hg : measurable g) : bind (bind m f) g = bind m (λa, bind (f a) g) := measure.ext $ assume s hs, begin rw [bind_apply hs hg, bind_apply hs (hf.comp $ measurable_bind' hg), integral_bind hf], { congr, funext a, exact (bind_apply hs hg).symm }, exact hg.comp (measurable_coe hs) end lemma bind_dirac {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a := measure.ext $ assume s hs, by rw [bind_apply hs hf, integral_dirac a (hf.comp (measurable_coe hs))] lemma dirac_bind {m : measure α} : bind m dirac = m := measure.ext $ assume s hs, begin rw [bind_apply hs measurable_dirac], simp [dirac_apply _ hs], transitivity, apply lintegral_supr_const, assumption, exact one_mul _ end end measure end measure_theory
5a01b71aff04e060e5495d891c57d92f899e1d9a
7da5ceac20aaab989eeb795a4be9639982e7b35a
/src/group_theory/mclaughlin.lean
e6f764e9d5a8a6e9d7461bc393eecfe3732b1f53
[ "MIT" ]
permissive
formalabstracts/formalabstracts
46c2f1b3a172e62ca6ffeb46fbbdf1705718af49
b0173da1af45421239d44492eeecd54bf65ee0f6
refs/heads/master
1,606,896,370,374
1,572,988,776,000
1,572,988,776,000
96,763,004
165
28
null
1,555,709,319,000
1,499,680,948,000
Lean
UTF-8
Lean
false
false
2,243
lean
import ..data.dvector .presentation .monster local notation `⟪`:50 a `⟫`:50 := free_group.of a local notation h :: t := dvector.cons h t local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l /- From the corresponding entry in the atlas (p. 100) the McLaughlin sporadic group is given by a generalized Coxeter-type presentation modulo additional relations -/ open coxeter_vertices namespace mclaughlin /- The graph is question is a--b-5-c--d 4 ↖ ↗ ↖ 4 e -6-f which we'll write as the annotated_graph of a Coxeter Y-diagram with the diagonal edges inserted -/ def mclaughlin_prediagram : annotated_graph := annotated_graph_of_graph $ coxeter_edges [5] noncomputable instance : decidable_rel mclaughlin_prediagram.edge := λ _ _, classical.prop_decidable _ private def a : mclaughlin_prediagram.vertex := torso private def b : mclaughlin_prediagram.vertex := arm (by to_dfin 0) (by to_dfin 0) private def c : mclaughlin_prediagram.vertex := arm (by to_dfin 0) (by to_dfin 1) private def e : mclaughlin_prediagram.vertex := arm (by to_dfin 0) (by to_dfin 2) private def d : mclaughlin_prediagram.vertex := arm (by to_dfin 0) (by to_dfin 3) private def f : mclaughlin_prediagram.vertex := arm (by to_dfin 0) (by to_dfin 4) noncomputable def mclaughlin_diagram : annotated_graph := insert_edge (insert_edge (insert_edge (annotate mclaughlin_prediagram (b,c) 5) (a,e) 4) (c,e) 3) (c,f) 4 noncomputable instance mclaughlin_diagram_decidable_rel : decidable_rel mclaughlin_diagram.edge := λ _ _, classical.prop_decidable _ noncomputable def mclaughlin_diagram_group : Group := coxeter_group $ matrix_of_annotated_graph mclaughlin_diagram private def a : mclaughlin_diagram_group := generated_of $ a private def b : mclaughlin_diagram_group := generated_of $ b private def c : mclaughlin_diagram_group := generated_of $ c private def e : mclaughlin_diagram_group := generated_of $ d private def d : mclaughlin_diagram_group := generated_of $ d private def f : mclaughlin_diagram_group := generated_of $ f noncomputable def McL : Group := mclaughlin_diagram_group/⟪{(c*f)^2 * a⁻¹, (e * f)^3 * b⁻¹, (e*a*b)^3, (b*c*e)^5, (a*e*c*d)^4, (c*e*f)^21, (c*e*f)^7}⟫ end mclaughlin
cc2c3fe28783871f198296c2abb825d0eeff9fa0
b3c7090f393c11bd47c82d2f8bb4edf8213173f5
/src/bundled_subgroup.lean
99835c6057da0e9d31dd13beb69fba15983eb0b4
[]
no_license
ImperialCollegeLondon/lean-groups
964b197478f0313d826073576a3e0ae8b166a584
9a82d2a66ef7f549107fcb4e1504d734c43ebb33
refs/heads/master
1,592,371,184,330
1,567,197,270,000
1,567,197,270,000
195,810,480
4
0
null
null
null
null
UTF-8
Lean
false
false
3,533
lean
-- Sian's work on bundled subgroups import group_theory.subgroup import algebra.group.hom import bundled_group_homs /- functions banned from this file: 1) is_submonoid 2) is_subgroup 3) is_group_hom 4) is_monoid_hom -/ -- we want -- The place for easy lemmas about group homs is in the group_hom namespace namespace group_hom variables {G : Type*} {H : Type*} [group G] [group H] @[extensionality] theorem ext {G : Type*} {H : Type*} [group G] [group H] {f f' : G →* H} (H : ∀ (x : G), f x = f' x) : f = f' := by cases f; cases f'; congr'; exact funext H theorem ext_iff {f f' : G →* H} : f = f' ↔ ∀ x, f x = f' x := ⟨by rintro rfl; simp, ext⟩ variable (f : G →* H) @[simp] lemma map_mul : ∀ (x y : G), f (x * y) = f x * f y := f.map_mul @[simp] lemma map_one : f 1 = 1 := f.map_one end group_hom -- namespace -- bundled submonoids! set_option old_structure_cmd true structure submonoid (M : Type*) [monoid M] := (carrier : set M) (one_mem : (1 : M) ∈ carrier) (mul_mem {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) variables {M : Type*} [monoid M] instance submonoid.has_coe : has_coe (submonoid M) (set M) := ⟨submonoid.carrier⟩ -- bundled subgroups structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem {a} : a ∈ carrier → a⁻¹ ∈ carrier) variables {G : Type*} [group G] {H : Type*} [group H] instance : has_mem G (subgroup G) := ⟨λ g H, g ∈ H.carrier⟩ namespace subgroup instance (K : subgroup G) : is_subgroup K.carrier := { one_mem := K.one_mem, mul_mem := K.mul_mem, inv_mem := K.inv_mem } instance has_coe : has_coe (subgroup G) (set G) := ⟨subgroup.carrier⟩ theorem ext' {G : Type*} [group G] (H K : subgroup G) : H = K ↔ (H : set G) = (K : set G) := begin cases H;cases K, unfold_coes, simp, end @[extensionality] theorem ext_iff {G : Type*} [group G] (H K : subgroup G) : H = K ↔ ∀ x : G, x ∈ H ↔ x ∈ K := begin split, intro h, intro x, rw h, intro h, rw ext', apply set.ext, exact h end definition map (f : G →* H) (G1 : subgroup G) : subgroup H := { carrier := f '' (G1 : set G), one_mem := begin use 1, split, { exact G1.one_mem, }, { exact group_hom.map_one f, } end, mul_mem := begin rintro j k ⟨j', hj', rfl⟩ ⟨k', hk', rfl⟩, rw [← group_hom.map_mul f j' k'], use j'*k', split, apply G1.mul_mem, assumption, assumption, refl, end, inv_mem := begin rintro j ⟨j', hj', rfl⟩, rw [←f.map_inv j'], use j'⁻¹, split, apply subgroup.inv_mem, assumption, refl, end } definition comap (f : G →* H) (H1 : subgroup H) : subgroup G := { carrier := f ⁻¹' (H1 : set H), one_mem := begin unfold set.preimage, dsimp, rw monoid_hom.map_one f, apply subgroup.one_mem, end, mul_mem := begin intros, unfold set.preimage, dsimp, rw monoid_hom.map_mul f, apply subgroup.mul_mem, assumption, assumption, end, inv_mem := begin intros, unfold set.preimage, dsimp, rw f.map_inv, apply subgroup.inv_mem, assumption, end } end subgroup def is_normal_subgroup {G : Type*} [group G] (S : subgroup G) := normal_subgroup S.carrier theorem is_normal_subgroup_def {G : Type*} [group G] (S : subgroup G) : is_normal_subgroup S ↔ (∀ n : G, n ∈ S → ∀ g : G, g * n * g⁻¹ ∈ S) := begin split, intro h, cases h, exact h_normal, intro h, constructor, exact h end
283ef327a4ddfb7695a403269d6e323c0678901a
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/decl_olean.lean
a9de7186503416e2579a575e168b67a9fe6ea3af
[ "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
502
lean
open tactic def g : nat → nat := λ n, 0 meta def show_pos (n : name) : command := do env ← get_env, pos ← returnopt (env^.decl_pos n), olean ← returnopt (env^.decl_olean n) <|> return "current file", trace $ to_string n ++ " was defined at " ++ olean ++ " : " ++ to_string pos.1 ++ ":" ++ to_string pos.2 run_cmd show_pos `nat.succ run_cmd show_pos `subsingleton.intro run_cmd show_pos `subsingleton.rec run_cmd show_pos `nat.add run_cmd show_pos `quotient run_cmd show_pos `g
56a6aa4811cd4464152fdd247e93ee190506d02b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/sizeof6.lean
cf1f6d67f21a4fbaebae144bbe0e331ab8d08b4f
[ "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
170
lean
import Lean.Data.PersistentArray inductive Foo where | mk (args : Lean.PersistentArray Foo) #print Foo.mk.sizeOf_spec #print Foo._sizeOf_2_eq #print Foo._sizeOf_3_eq
4e699cd5a0a38a10faac31f75f130af6e51454d5
e21db629d2e37a833531fdcb0b37ce4d71825408
/alt/ac_loop.lean
b5096882bb5eef928b2e791a7b996ba86efcce1d
[]
no_license
fischerman/GPU-transformation-verifier
614a28cb4606a05a0eb27e8d4eab999f4f5ea60c
75a5016f05382738ff93ce5859c4cfa47ccb63c1
refs/heads/master
1,586,985,789,300
1,579,290,514,000
1,579,290,514,000
165,031,073
1
0
null
null
null
null
UTF-8
Lean
false
false
5,494
lean
import parlang import parlang_nonmono namespace parlang namespace ac_loop open parlang open parlang.kernel open parlang_nonmono variables {n : ℕ} {σ : Type} {ι : Type} {τ : ι → Type} {s t u : state n σ τ} {ac : vector bool n} {f f' : σ → bool} [decidable_eq ι] {semantics : kernel σ τ → vector bool n → state n σ τ → state n σ τ → Prop} class has_unique (semantics : kernel σ τ → vector bool n → state n σ τ → state n σ τ → Prop) := (unique : ∀ {k : kernel σ τ} {ac : vector bool n} {s t t' : state n σ τ}, semantics k ac s t → semantics k ac s t' → t = t') variables [has_unique semantics] instance unique2 : has_unique $ @parlang.exec_state σ ι τ _ n := ⟨begin intros _ _ _ _ _ a b, apply parlang.exec_state_unique b a, end⟩ instance unique1 : has_unique $ @exec_state σ ι τ _ n := sorry notation `v[` v:(foldr `, ` (h t, vector.cons h t) vector.nil `]`) := v -- this is similar to the semantic itself except we are not interested in states but the resulting active maps inductive ac_after_n_iteration (semantics : kernel σ τ → vector bool n → state n σ τ → state n σ τ → Prop) (k : kernel σ τ) (f : σ → bool) : state n σ τ → vector bool n → vector bool n → ℕ → Prop | base (ac : vector bool n) (s : state n σ τ) : ac_after_n_iteration s ac ac 0 | step {ac : vector bool n} (s t : state n σ τ) {i : ℕ} {ac' : vector bool n} : ac_after_n_iteration t (deactivate_threads (bnot ∘ f) ac s) ac' i → semantics k (deactivate_threads (bnot ∘ f) ac s) s t → ac_after_n_iteration s ac ac' (i + 1) example : ac_after_n_iteration exec_state (compute (λ (m : bool), ff)) id (@parlang.init_state bool string (λs, ℕ) _ (λ_, tt) (λ_,1) (λs:string, 0)) v[tt] v[tt] 1 := begin apply ac_after_n_iteration.step _ (@parlang.init_state bool string (λs, ℕ) _ (λ_, ff) (λ_,1) (λs:string, 0)), swap, sorry, sorry, end lemma ac_after_n_iteration_unique {k : kernel σ τ} {f : σ → bool} {ac' ac'' : vector bool n} {i} : ac_after_n_iteration semantics k f s ac ac' i → ac_after_n_iteration semantics k f s ac ac'' i → ac' = ac'' := begin admit, end lemma ac_ge_single {k : kernel σ τ} {f : σ → bool} {ac' : vector bool n} {i : ℕ} : ac_after_n_iteration semantics k f s ac ac' i → ac ≥ ac' := begin intros h, induction i generalizing s ac ac', case nat.zero { cases h, intros t hna, assumption, }, case nat.succ { cases h, specialize i_ih h_a, have : ac ≥ (deactivate_threads (bnot ∘ f) ac s) := by apply ac_sub_deac, sorry, -- proof by transitivity } end lemma ac_ge_two {k : kernel σ τ} {f : σ → bool} {i i' : ℕ} {ac' ac'' : vector bool n} : ac_after_n_iteration semantics k f s ac ac' i → ac_after_n_iteration semantics k f s ac ac'' (i + i') → ac' ≥ ac'' := begin intros h₁ h₂, induction i generalizing s ac, case nat.zero { cases h₁, apply ac_ge_single h₂, }, case nat.succ { cases h₁, have : nat.succ i_n + i' = nat.succ (i_n + i') := by rw nat.succ_add, rw this at h₂, cases h₂, have : h₁_t = h₂_t := has_unique.unique _ _ _ h₁_a_1 h₂_a_1, subst this, apply i_ih h₁_a h₂_a, } end def monotone_loop (semantics : kernel σ τ → vector bool n → state n σ τ → state n σ τ → Prop) (f k) (s : state n σ τ) (ac : vector bool n) : Prop := ∀ (i i' : ℕ) (ac' ac'' : vector bool n), ac_after_n_iteration semantics k f s ac ac' i → ac_after_n_iteration semantics k f s ac ac'' (i + i') → ac' ≥ ac'' lemma par_loop_ac' {k : kernel σ τ} : parlang.exec_state (loop f k) ac s t → ∃ i ac', ac_after_n_iteration parlang.exec_state k f s ac ac' i ∧ no_thread_active (deactivate_threads (bnot ∘ f) ac' t) := begin generalize eq_l : (loop f k) = l, intro h, induction h; cases eq_l, { use 0, use h_ac, split, apply ac_after_n_iteration.base, assumption, }, { clear h_ih_a, specialize h_ih_a_1 rfl, cases h_ih_a_1 with i ih, cases ih with ac' ih, cases ih with ha hb, use i + 1, use ac', split, swap, assumption, apply ac_after_n_iteration.step, repeat { assumption }, } end lemma loop_ac' {k : kernel σ τ} : exec_state (loop f k) ac s t → ∃ i ac', ac_after_n_iteration exec_state k f s ac ac' i ∧ no_thread_active (deactivate_threads (bnot ∘ f) ac' t) := begin generalize eq_l : (loop f k) = l, intro h, induction h generalizing; cases eq_l, { use 0, use h_ac, split, apply ac_after_n_iteration.base, assumption, }, { clear h_ih_a, specialize h_ih_a_1 rfl, cases h_ih_a_1 with i ih, cases ih with ac' ih, cases ih with ha hb, use i + 1, use ac', split, swap, assumption, { apply ac_after_n_iteration.step, swap, exact h_a_1, induction ha, case ac_after_n_iteration.base { have : monotone_loop exec_state f k h_s ha_ac := by apply ac_ge_two, have : monotone_loop exec_state f k h_s ha_ac := by apply ac_ge_two, } } } end end ac_loop end parlang
481893f6317754a5fe9b796f2f7b37493f164650
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/shapes/biproducts.lean
ec5d92a0b23ab53b3131e99748ec4f8e4040e145
[ "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
41,528
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.binary_products import category_theory.preadditive /-! # Biproducts and binary biproducts We introduce the notion of (finite) biproducts and binary biproducts. These are slightly unusual relative to the other shapes in the library, as they are simultaneously limits and colimits. (Zero objects are similar; they are "biterminal".) We treat first the case of a general category with zero morphisms, and subsequently the case of a preadditive category. In a category with zero morphisms, we model the (binary) biproduct of `P Q : C` using a `binary_bicone`, which has a cone point `X`, and morphisms `fst : X ⟶ P`, `snd : X ⟶ Q`, `inl : P ⟶ X` and `inr : X ⟶ Q`, such that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q`. Such a `binary_bicone` is a biproduct if the cone is a limit cone, and the cocone is a colimit cocone. In a preadditive category, * any `binary_biproduct` satisfies `total : fst ≫ inl + snd ≫ inr = 𝟙 X` * any `binary_product` is a `binary_biproduct` * any `binary_coproduct` is a `binary_biproduct` For biproducts indexed by a `fintype J`, a `bicone` again consists of a cone point `X` and morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`, such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise. In a preadditive category, * any `biproduct` satisfies `total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` * any `product` is a `biproduct` * any `coproduct` is a `biproduct` ## Notation As `⊕` is already taken for the sum of types, we introduce the notation `X ⊞ Y` for a binary biproduct. We introduce `⨁ f` for the indexed biproduct. -/ noncomputable theory universes v u open category_theory open category_theory.functor namespace category_theory.limits variables {J : Type v} [decidable_eq J] variables {C : Type u} [category.{v} C] [has_zero_morphisms C] /-- A `c : bicone F` is: * an object `c.X` and * morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`, * such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise. -/ @[nolint has_inhabited_instance] structure bicone (F : J → C) := (X : C) (π : Π j, X ⟶ F j) (ι : Π j, F j ⟶ X) (ι_π : ∀ j j', ι j ≫ π j' = if h : j = j' then eq_to_hom (congr_arg F h) else 0) @[simp] lemma bicone_ι_π_self {F : J → C} (B : bicone F) (j : J) : B.ι j ≫ B.π j = 𝟙 (F j) := by simpa using B.ι_π j j @[simp] lemma bicone_ι_π_ne {F : J → C} (B : bicone F) {j j' : J} (h : j ≠ j') : B.ι j ≫ B.π j' = 0 := by simpa [h] using B.ι_π j j' variables {F : J → C} namespace bicone /-- Extract the cone from a bicone. -/ @[simps] def to_cone (B : bicone F) : cone (discrete.functor F) := { X := B.X, π := { app := λ j, B.π j }, } /-- Extract the cocone from a bicone. -/ @[simps] def to_cocone (B : bicone F) : cocone (discrete.functor F) := { X := B.X, ι := { app := λ j, B.ι j }, } end bicone /-- A bicone over `F : J → C`, which is both a limit cone and a colimit cocone. -/ @[nolint has_inhabited_instance] structure limit_bicone (F : J → C) := (bicone : bicone F) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) /-- `has_biproduct F` expresses the mere existence of a bicone which is simultaneously a limit and a colimit of the diagram `F`. -/ class has_biproduct (F : J → C) : Prop := mk' :: (exists_biproduct : nonempty (limit_bicone F)) lemma has_biproduct.mk {F : J → C} (d : limit_bicone F) : has_biproduct F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `biproduct_data F` from `has_biproduct F`. -/ def get_biproduct_data (F : J → C) [has_biproduct F] : limit_bicone F := classical.choice has_biproduct.exists_biproduct /-- A bicone for `F` which is both a limit cone and a colimit cocone. -/ def biproduct.bicone (F : J → C) [has_biproduct F] : bicone F := (get_biproduct_data F).bicone /-- `biproduct.bicone F` is a limit cone. -/ def biproduct.is_limit (F : J → C) [has_biproduct F] : is_limit (biproduct.bicone F).to_cone := (get_biproduct_data F).is_limit /-- `biproduct.bicone F` is a colimit cocone. -/ def biproduct.is_colimit (F : J → C) [has_biproduct F] : is_colimit (biproduct.bicone F).to_cocone := (get_biproduct_data F).is_colimit @[priority 100] instance has_product_of_has_biproduct [has_biproduct F] : has_limit (discrete.functor F) := has_limit.mk { cone := (biproduct.bicone F).to_cone, is_limit := biproduct.is_limit F, } @[priority 100] instance has_coproduct_of_has_biproduct [has_biproduct F] : has_colimit (discrete.functor F) := has_colimit.mk { cocone := (biproduct.bicone F).to_cocone, is_colimit := biproduct.is_colimit F, } variables (J C) /-- `C` has biproducts of shape `J` if we have a limit and a colimit, with the same cone points, of every function `F : J → C`. -/ class has_biproducts_of_shape : Prop := (has_biproduct : Π F : J → C, has_biproduct F) attribute [instance, priority 100] has_biproducts_of_shape.has_biproduct /-- `has_finite_biproducts C` represents a choice of biproduct for every family of objects in `C` indexed by a finite type with decidable equality. -/ class has_finite_biproducts : Prop := (has_biproducts_of_shape : Π (J : Type v) [decidable_eq J] [fintype J], has_biproducts_of_shape J C) attribute [instance, priority 100] has_finite_biproducts.has_biproducts_of_shape @[priority 100] instance has_finite_products_of_has_finite_biproducts [has_finite_biproducts C] : has_finite_products C := { out := λ J _ _, ⟨λ F, by exactI has_limit_of_iso discrete.nat_iso_functor.symm⟩ } @[priority 100] instance has_finite_coproducts_of_has_finite_biproducts [has_finite_biproducts C] : has_finite_coproducts C := { out := λ J _ _, ⟨λ F, by exactI has_colimit_of_iso discrete.nat_iso_functor⟩ } variables {J C} /-- The isomorphism between the specified limit and the specified colimit for a functor with a bilimit. -/ def biproduct_iso (F : J → C) [has_biproduct F] : limits.pi_obj F ≅ limits.sigma_obj F := (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (biproduct.is_limit F)).trans $ is_colimit.cocone_point_unique_up_to_iso (biproduct.is_colimit F) (colimit.is_colimit _) end category_theory.limits namespace category_theory.limits variables {J : Type v} [decidable_eq J] variables {C : Type u} [category.{v} C] [has_zero_morphisms C] /-- `biproduct f` computes the biproduct of a family of elements `f`. (It is defined as an abbreviation for `limit (discrete.functor f)`, so for most facts about `biproduct f`, you will just use general facts about limits and colimits.) -/ abbreviation biproduct (f : J → C) [has_biproduct f] : C := (biproduct.bicone f).X notation `⨁ ` f:20 := biproduct f /-- The projection onto a summand of a biproduct. -/ abbreviation biproduct.π (f : J → C) [has_biproduct f] (b : J) : ⨁ f ⟶ f b := (biproduct.bicone f).π b @[simp] lemma biproduct.bicone_π (f : J → C) [has_biproduct f] (b : J) : (biproduct.bicone f).π b = biproduct.π f b := rfl /-- The inclusion into a summand of a biproduct. -/ abbreviation biproduct.ι (f : J → C) [has_biproduct f] (b : J) : f b ⟶ ⨁ f := (biproduct.bicone f).ι b @[simp] lemma biproduct.bicone_ι (f : J → C) [has_biproduct f] (b : J) : (biproduct.bicone f).ι b = biproduct.ι f b := rfl @[reassoc] lemma biproduct.ι_π (f : J → C) [has_biproduct f] (j j' : J) : biproduct.ι f j ≫ biproduct.π f j' = if h : j = j' then eq_to_hom (congr_arg f h) else 0 := (biproduct.bicone f).ι_π j j' @[simp,reassoc] lemma biproduct.ι_π_self (f : J → C) [has_biproduct f] (j : J) : biproduct.ι f j ≫ biproduct.π f j = 𝟙 _ := by simp [biproduct.ι_π] @[simp,reassoc] lemma biproduct.ι_π_ne (f : J → C) [has_biproduct f] {j j' : J} (h : j ≠ j') : biproduct.ι f j ≫ biproduct.π f j' = 0 := by simp [biproduct.ι_π, h] /-- Given a collection of maps into the summands, we obtain a map into the biproduct. -/ abbreviation biproduct.lift {f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ⨁ f := (biproduct.is_limit f).lift (fan.mk P p) /-- Given a collection of maps out of the summands, we obtain a map out of the biproduct. -/ abbreviation biproduct.desc {f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) : ⨁ f ⟶ P := (biproduct.is_colimit f).desc (cofan.mk P p) @[simp, reassoc] lemma biproduct.lift_π {f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) (j : J) : biproduct.lift p ≫ biproduct.π f j = p j := (biproduct.is_limit f).fac _ _ @[simp, reassoc] lemma biproduct.ι_desc {f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) (j : J) : biproduct.ι f j ≫ biproduct.desc p = p j := (biproduct.is_colimit f).fac _ _ /-- Given a collection of maps between corresponding summands of a pair of biproducts indexed by the same type, we obtain a map between the biproducts. -/ abbreviation biproduct.map [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := is_limit.map (biproduct.bicone f).to_cone (biproduct.is_limit g) (discrete.nat_trans p) /-- An alternative to `biproduct.map` constructed via colimits. This construction only exists in order to show it is equal to `biproduct.map`. -/ abbreviation biproduct.map' [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := is_colimit.map (biproduct.is_colimit f) (biproduct.bicone g).to_cocone (discrete.nat_trans p) @[ext] lemma biproduct.hom_ext {f : J → C} [has_biproduct f] {Z : C} (g h : Z ⟶ ⨁ f) (w : ∀ j, g ≫ biproduct.π f j = h ≫ biproduct.π f j) : g = h := (biproduct.is_limit f).hom_ext w @[ext] lemma biproduct.hom_ext' {f : J → C} [has_biproduct f] {Z : C} (g h : ⨁ f ⟶ Z) (w : ∀ j, biproduct.ι f j ≫ g = biproduct.ι f j ≫ h) : g = h := (biproduct.is_colimit f).hom_ext w lemma biproduct.map_eq_map' [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ⟶ g b) : biproduct.map p = biproduct.map' p := begin ext j j', simp only [discrete.nat_trans_app, limits.is_colimit.ι_map, limits.is_limit.map_π, category.assoc, ←bicone.to_cone_π_app, ←biproduct.bicone_π, ←bicone.to_cocone_ι_app, ←biproduct.bicone_ι], simp only [biproduct.bicone_ι, biproduct.bicone_π, bicone.to_cocone_ι_app, bicone.to_cone_π_app], rw [biproduct.ι_π_assoc, biproduct.ι_π], split_ifs, { subst h, rw [eq_to_hom_refl, category.id_comp], erw category.comp_id, }, { simp, }, end @[simp, reassoc] lemma biproduct.map_π [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π j, f j ⟶ g j) (j : J) : biproduct.map p ≫ biproduct.π g j = biproduct.π f j ≫ p j := limits.is_limit.map_π _ _ _ _ @[simp, reassoc] lemma biproduct.ι_map [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π j, f j ⟶ g j) (j : J) : biproduct.ι f j ≫ biproduct.map p = p j ≫ biproduct.ι g j := begin rw biproduct.map_eq_map', convert limits.is_colimit.ι_map _ _ _ _; refl end @[simp, reassoc] lemma biproduct.map_desc [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π j, f j ⟶ g j) {P : C} (k : Π j, g j ⟶ P) : biproduct.map p ≫ biproduct.desc k = biproduct.desc (λ j, p j ≫ k j) := by { ext, simp, } @[simp, reassoc] lemma biproduct.lift_map [fintype J] {f g : J → C} [has_finite_biproducts C] {P : C} (k : Π j, P ⟶ f j) (p : Π j, f j ⟶ g j) : biproduct.lift k ≫ biproduct.map p = biproduct.lift (λ j, k j ≫ p j) := by { ext, simp, } /-- Given a collection of isomorphisms between corresponding summands of a pair of biproducts indexed by the same type, we obtain an isomorphism between the biproducts. -/ @[simps] def biproduct.map_iso [fintype J] {f g : J → C} [has_finite_biproducts C] (p : Π b, f b ≅ g b) : ⨁ f ≅ ⨁ g := { hom := biproduct.map (λ b, (p b).hom), inv := biproduct.map (λ b, (p b).inv), } section variables [fintype J] {K : Type v} [fintype K] [decidable_eq K] {f : J → C} {g : K → C} [has_finite_biproducts C] /-- Convert a (dependently typed) matrix to a morphism of biproducts. -/ def biproduct.matrix (m : Π j k, f j ⟶ g k) : ⨁ f ⟶ ⨁ g := biproduct.desc (λ j, biproduct.lift (λ k, m j k)) @[simp, reassoc] lemma biproduct.matrix_π (m : Π j k, f j ⟶ g k) (k : K) : biproduct.matrix m ≫ biproduct.π g k = biproduct.desc (λ j, m j k) := by { ext, simp [biproduct.matrix], } @[simp, reassoc] lemma biproduct.ι_matrix (m : Π j k, f j ⟶ g k) (j : J) : biproduct.ι f j ≫ biproduct.matrix m = biproduct.lift (λ k, m j k) := by { ext, simp [biproduct.matrix], } /-- Extract the matrix components from a morphism of biproducts. -/ def biproduct.components (m : ⨁ f ⟶ ⨁ g) (j : J) (k : K) : f j ⟶ g k := biproduct.ι f j ≫ m ≫ biproduct.π g k @[simp] lemma biproduct.matrix_components (m : Π j k, f j ⟶ g k) (j : J) (k : K) : biproduct.components (biproduct.matrix m) j k = m j k := by simp [biproduct.components] @[simp] lemma biproduct.components_matrix (m : ⨁ f ⟶ ⨁ g) : biproduct.matrix (λ j k, biproduct.components m j k) = m := by { ext, simp [biproduct.components], } /-- Morphisms between direct sums are matrices. -/ @[simps] def biproduct.matrix_equiv : (⨁ f ⟶ ⨁ g) ≃ (Π j k, f j ⟶ g k) := { to_fun := biproduct.components, inv_fun := biproduct.matrix, left_inv := biproduct.components_matrix, right_inv := λ m, by { ext, apply biproduct.matrix_components } } end instance biproduct.ι_mono (f : J → C) [has_biproduct f] (b : J) : split_mono (biproduct.ι f b) := { retraction := biproduct.desc $ λ b', if h : b' = b then eq_to_hom (congr_arg f h) else biproduct.ι f b' ≫ biproduct.π f b } instance biproduct.π_epi (f : J → C) [has_biproduct f] (b : J) : split_epi (biproduct.π f b) := { section_ := biproduct.lift $ λ b', if h : b = b' then eq_to_hom (congr_arg f h) else biproduct.ι f b ≫ biproduct.π f b' } variables {C} /-- A binary bicone for a pair of objects `P Q : C` consists of the cone point `X`, maps from `X` to both `P` and `Q`, and maps from both `P` and `Q` to `X`, so that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q` -/ @[nolint has_inhabited_instance] structure binary_bicone (P Q : C) := (X : C) (fst : X ⟶ P) (snd : X ⟶ Q) (inl : P ⟶ X) (inr : Q ⟶ X) (inl_fst' : inl ≫ fst = 𝟙 P . obviously) (inl_snd' : inl ≫ snd = 0 . obviously) (inr_fst' : inr ≫ fst = 0 . obviously) (inr_snd' : inr ≫ snd = 𝟙 Q . obviously) restate_axiom binary_bicone.inl_fst' restate_axiom binary_bicone.inl_snd' restate_axiom binary_bicone.inr_fst' restate_axiom binary_bicone.inr_snd' attribute [simp, reassoc] binary_bicone.inl_fst binary_bicone.inl_snd binary_bicone.inr_fst binary_bicone.inr_snd namespace binary_bicone variables {P Q : C} /-- Extract the cone from a binary bicone. -/ def to_cone (c : binary_bicone P Q) : cone (pair P Q) := binary_fan.mk c.fst c.snd @[simp] lemma to_cone_X (c : binary_bicone P Q) : c.to_cone.X = c.X := rfl @[simp] lemma to_cone_π_app_left (c : binary_bicone P Q) : c.to_cone.π.app (walking_pair.left) = c.fst := rfl @[simp] lemma to_cone_π_app_right (c : binary_bicone P Q) : c.to_cone.π.app (walking_pair.right) = c.snd := rfl /-- Extract the cocone from a binary bicone. -/ def to_cocone (c : binary_bicone P Q) : cocone (pair P Q) := binary_cofan.mk c.inl c.inr @[simp] lemma to_cocone_X (c : binary_bicone P Q) : c.to_cocone.X = c.X := rfl @[simp] lemma to_cocone_ι_app_left (c : binary_bicone P Q) : c.to_cocone.ι.app (walking_pair.left) = c.inl := rfl @[simp] lemma to_cocone_ι_app_right (c : binary_bicone P Q) : c.to_cocone.ι.app (walking_pair.right) = c.inr := rfl end binary_bicone namespace bicone /-- Convert a `bicone` over a function on `walking_pair` to a binary_bicone. -/ @[simps] def to_binary_bicone {X Y : C} (b : bicone (pair X Y).obj) : binary_bicone X Y := { X := b.X, fst := b.π walking_pair.left, snd := b.π walking_pair.right, inl := b.ι walking_pair.left, inr := b.ι walking_pair.right, inl_fst' := by { simp [bicone.ι_π], refl, }, inr_fst' := by simp [bicone.ι_π], inl_snd' := by simp [bicone.ι_π], inr_snd' := by { simp [bicone.ι_π], refl, }, } /-- If the cone obtained from a bicone over `pair X Y` is a limit cone, so is the cone obtained by converting that bicone to a binary_bicone, then to a cone. -/ def to_binary_bicone_is_limit {X Y : C} {b : bicone (pair X Y).obj} (c : is_limit (b.to_cone)) : is_limit (b.to_binary_bicone.to_cone) := { lift := λ s, c.lift s, fac' := λ s j, by { cases j; erw c.fac, }, uniq' := λ s m w, begin apply c.uniq s, rintro (⟨⟩|⟨⟩), exact w walking_pair.left, exact w walking_pair.right, end, } /-- If the cocone obtained from a bicone over `pair X Y` is a colimit cocone, so is the cocone obtained by converting that bicone to a binary_bicone, then to a cocone. -/ def to_binary_bicone_is_colimit {X Y : C} {b : bicone (pair X Y).obj} (c : is_colimit (b.to_cocone)) : is_colimit (b.to_binary_bicone.to_cocone) := { desc := λ s, c.desc s, fac' := λ s j, by { cases j; erw c.fac, }, uniq' := λ s m w, begin apply c.uniq s, rintro (⟨⟩|⟨⟩), exact w walking_pair.left, exact w walking_pair.right, end, } end bicone /-- A bicone over `P Q : C`, which is both a limit cone and a colimit cocone. -/ @[nolint has_inhabited_instance] structure binary_biproduct_data (P Q : C) := (bicone : binary_bicone P Q) (is_limit : is_limit bicone.to_cone) (is_colimit : is_colimit bicone.to_cocone) /-- `has_binary_biproduct P Q` expresses the mere existence of a bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`. -/ class has_binary_biproduct (P Q : C) : Prop := mk' :: (exists_binary_biproduct : nonempty (binary_biproduct_data P Q)) lemma has_binary_biproduct.mk {P Q : C} (d : binary_biproduct_data P Q) : has_binary_biproduct P Q := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `binary_biproduct_data F` from `has_binary_biproduct F`. -/ def get_binary_biproduct_data (P Q : C) [has_binary_biproduct P Q] : binary_biproduct_data P Q := classical.choice has_binary_biproduct.exists_binary_biproduct /-- A bicone for `P Q ` which is both a limit cone and a colimit cocone. -/ def binary_biproduct.bicone (P Q : C) [has_binary_biproduct P Q] : binary_bicone P Q := (get_binary_biproduct_data P Q).bicone /-- `binary_biproduct.bicone P Q` is a limit cone. -/ def binary_biproduct.is_limit (P Q : C) [has_binary_biproduct P Q] : is_limit (binary_biproduct.bicone P Q).to_cone := (get_binary_biproduct_data P Q).is_limit /-- `binary_biproduct.bicone P Q` is a colimit cocone. -/ def binary_biproduct.is_colimit (P Q : C) [has_binary_biproduct P Q] : is_colimit (binary_biproduct.bicone P Q).to_cocone := (get_binary_biproduct_data P Q).is_colimit section variable (C) /-- `has_binary_biproducts C` represents the existence of a bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`, for every `P Q : C`. -/ class has_binary_biproducts : Prop := (has_binary_biproduct : Π (P Q : C), has_binary_biproduct P Q) attribute [instance, priority 100] has_binary_biproducts.has_binary_biproduct /-- A category with finite biproducts has binary biproducts. This is not an instance as typically in concrete categories there will be an alternative construction with nicer definitional properties. -/ lemma has_binary_biproducts_of_finite_biproducts [has_finite_biproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ P Q, has_binary_biproduct.mk { bicone := (biproduct.bicone (pair P Q).obj).to_binary_bicone, is_limit := bicone.to_binary_bicone_is_limit (biproduct.is_limit _), is_colimit := bicone.to_binary_bicone_is_colimit (biproduct.is_colimit _) } } end variables {P Q : C} instance has_binary_biproduct.has_limit_pair [has_binary_biproduct P Q] : has_limit (pair P Q) := has_limit.mk ⟨_, binary_biproduct.is_limit P Q⟩ instance has_binary_biproduct.has_colimit_pair [has_binary_biproduct P Q] : has_colimit (pair P Q) := has_colimit.mk ⟨_, binary_biproduct.is_colimit P Q⟩ @[priority 100] instance has_binary_products_of_has_binary_biproducts [has_binary_biproducts C] : has_binary_products C := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } @[priority 100] instance has_binary_coproducts_of_has_binary_biproducts [has_binary_biproducts C] : has_binary_coproducts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } /-- The isomorphism between the specified binary product and the specified binary coproduct for a pair for a binary biproduct. -/ def biprod_iso (X Y : C) [has_binary_biproduct X Y] : limits.prod X Y ≅ limits.coprod X Y := (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (binary_biproduct.is_limit X Y)).trans $ is_colimit.cocone_point_unique_up_to_iso (binary_biproduct.is_colimit X Y) (colimit.is_colimit _) /-- An arbitrary choice of biproduct of a pair of objects. -/ abbreviation biprod (X Y : C) [has_binary_biproduct X Y] := (binary_biproduct.bicone X Y).X notation X ` ⊞ `:20 Y:20 := biprod X Y /-- The projection onto the first summand of a binary biproduct. -/ abbreviation biprod.fst {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ X := (binary_biproduct.bicone X Y).fst /-- The projection onto the second summand of a binary biproduct. -/ abbreviation biprod.snd {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ Y := (binary_biproduct.bicone X Y).snd /-- The inclusion into the first summand of a binary biproduct. -/ abbreviation biprod.inl {X Y : C} [has_binary_biproduct X Y] : X ⟶ X ⊞ Y := (binary_biproduct.bicone X Y).inl /-- The inclusion into the second summand of a binary biproduct. -/ abbreviation biprod.inr {X Y : C} [has_binary_biproduct X Y] : Y ⟶ X ⊞ Y := (binary_biproduct.bicone X Y).inr section variables {X Y : C} [has_binary_biproduct X Y] @[simp] lemma binary_biproduct.bicone_fst : (binary_biproduct.bicone X Y).fst = biprod.fst := rfl @[simp] lemma binary_biproduct.bicone_snd : (binary_biproduct.bicone X Y).snd = biprod.snd := rfl @[simp] lemma binary_biproduct.bicone_inl : (binary_biproduct.bicone X Y).inl = biprod.inl := rfl @[simp] lemma binary_biproduct.bicone_inr : (binary_biproduct.bicone X Y).inr = biprod.inr := rfl end @[simp,reassoc] lemma biprod.inl_fst {X Y : C} [has_binary_biproduct X Y] : (biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 𝟙 X := (binary_biproduct.bicone X Y).inl_fst @[simp,reassoc] lemma biprod.inl_snd {X Y : C} [has_binary_biproduct X Y] : (biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 0 := (binary_biproduct.bicone X Y).inl_snd @[simp,reassoc] lemma biprod.inr_fst {X Y : C} [has_binary_biproduct X Y] : (biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 0 := (binary_biproduct.bicone X Y).inr_fst @[simp,reassoc] lemma biprod.inr_snd {X Y : C} [has_binary_biproduct X Y] : (biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 𝟙 Y := (binary_biproduct.bicone X Y).inr_snd /-- Given a pair of maps into the summands of a binary biproduct, we obtain a map into the binary biproduct. -/ abbreviation biprod.lift {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⊞ Y := (binary_biproduct.is_limit X Y).lift (binary_fan.mk f g) /-- Given a pair of maps out of the summands of a binary biproduct, we obtain a map out of the binary biproduct. -/ abbreviation biprod.desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⊞ Y ⟶ W := (binary_biproduct.is_colimit X Y).desc (binary_cofan.mk f g) @[simp, reassoc] lemma biprod.lift_fst {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : biprod.lift f g ≫ biprod.fst = f := (binary_biproduct.is_limit X Y).fac _ walking_pair.left @[simp, reassoc] lemma biprod.lift_snd {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : biprod.lift f g ≫ biprod.snd = g := (binary_biproduct.is_limit X Y).fac _ walking_pair.right @[simp, reassoc] lemma biprod.inl_desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : biprod.inl ≫ biprod.desc f g = f := (binary_biproduct.is_colimit X Y).fac _ walking_pair.left @[simp, reassoc] lemma biprod.inr_desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : biprod.inr ≫ biprod.desc f g = g := (binary_biproduct.is_colimit X Y).fac _ walking_pair.right instance biprod.mono_lift_of_mono_left {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (biprod.lift f g) := mono_of_mono_fac $ biprod.lift_fst _ _ instance biprod.mono_lift_of_mono_right {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (biprod.lift f g) := mono_of_mono_fac $ biprod.lift_snd _ _ instance biprod.epi_desc_of_epi_left {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (biprod.desc f g) := epi_of_epi_fac $ biprod.inl_desc _ _ instance biprod.epi_desc_of_epi_right {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (biprod.desc f g) := epi_of_epi_fac $ biprod.inr_desc _ _ /-- Given a pair of maps between the summands of a pair of binary biproducts, we obtain a map between the binary biproducts. -/ abbreviation biprod.map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := is_limit.map (binary_biproduct.bicone W X).to_cone (binary_biproduct.is_limit Y Z) (@map_pair _ _ (pair W X) (pair Y Z) f g) /-- An alternative to `biprod.map` constructed via colimits. This construction only exists in order to show it is equal to `biprod.map`. -/ abbreviation biprod.map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := is_colimit.map (binary_biproduct.is_colimit W X) (binary_biproduct.bicone Y Z).to_cocone (@map_pair _ _ (pair W X) (pair Y Z) f g) @[ext] lemma biprod.hom_ext {X Y Z : C} [has_binary_biproduct X Y] (f g : Z ⟶ X ⊞ Y) (h₀ : f ≫ biprod.fst = g ≫ biprod.fst) (h₁ : f ≫ biprod.snd = g ≫ biprod.snd) : f = g := binary_fan.is_limit.hom_ext (binary_biproduct.is_limit X Y) h₀ h₁ @[ext] lemma biprod.hom_ext' {X Y Z : C} [has_binary_biproduct X Y] (f g : X ⊞ Y ⟶ Z) (h₀ : biprod.inl ≫ f = biprod.inl ≫ g) (h₁ : biprod.inr ≫ f = biprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (binary_biproduct.is_colimit X Y) h₀ h₁ lemma biprod.map_eq_map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g = biprod.map' f g := begin ext, { simp only [map_pair_left, is_colimit.ι_map, is_limit.map_π, biprod.inl_fst_assoc, category.assoc, ←binary_bicone.to_cone_π_app_left, ←binary_biproduct.bicone_fst, ←binary_bicone.to_cocone_ι_app_left, ←binary_biproduct.bicone_inl], simp }, { simp only [map_pair_left, is_colimit.ι_map, is_limit.map_π, zero_comp, biprod.inl_snd_assoc, category.assoc, ←binary_bicone.to_cone_π_app_right, ←binary_biproduct.bicone_snd, ←binary_bicone.to_cocone_ι_app_left, ←binary_biproduct.bicone_inl], simp }, { simp only [map_pair_right, biprod.inr_fst_assoc, is_colimit.ι_map, is_limit.map_π, zero_comp, category.assoc, ←binary_bicone.to_cone_π_app_left, ←binary_biproduct.bicone_fst, ←binary_bicone.to_cocone_ι_app_right, ←binary_biproduct.bicone_inr], simp }, { simp only [map_pair_right, is_colimit.ι_map, is_limit.map_π, biprod.inr_snd_assoc, category.assoc, ←binary_bicone.to_cone_π_app_right, ←binary_biproduct.bicone_snd, ←binary_bicone.to_cocone_ι_app_right, ←binary_biproduct.bicone_inr], simp } end instance biprod.inl_mono {X Y : C} [has_binary_biproduct X Y] : split_mono (biprod.inl : X ⟶ X ⊞ Y) := { retraction := biprod.desc (𝟙 X) (biprod.inr ≫ biprod.fst) } instance biprod.inr_mono {X Y : C} [has_binary_biproduct X Y] : split_mono (biprod.inr : Y ⟶ X ⊞ Y) := { retraction := biprod.desc (biprod.inl ≫ biprod.snd) (𝟙 Y)} instance biprod.fst_epi {X Y : C} [has_binary_biproduct X Y] : split_epi (biprod.fst : X ⊞ Y ⟶ X) := { section_ := biprod.lift (𝟙 X) (biprod.inl ≫ biprod.snd) } instance biprod.snd_epi {X Y : C} [has_binary_biproduct X Y] : split_epi (biprod.snd : X ⊞ Y ⟶ Y) := { section_ := biprod.lift (biprod.inr ≫ biprod.fst) (𝟙 Y) } @[simp,reassoc] lemma biprod.map_fst {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g ≫ biprod.fst = biprod.fst ≫ f := is_limit.map_π _ _ _ walking_pair.left @[simp,reassoc] lemma biprod.map_snd {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g ≫ biprod.snd = biprod.snd ≫ g := is_limit.map_π _ _ _ walking_pair.right -- Because `biprod.map` is defined in terms of `lim` rather than `colim`, -- we need to provide additional `simp` lemmas. @[simp,reassoc] lemma biprod.inl_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.inl ≫ biprod.map f g = f ≫ biprod.inl := begin rw biprod.map_eq_map', exact is_colimit.ι_map (binary_biproduct.is_colimit W X) _ _ walking_pair.left end @[simp,reassoc] lemma biprod.inr_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.inr ≫ biprod.map f g = g ≫ biprod.inr := begin rw biprod.map_eq_map', exact is_colimit.ι_map (binary_biproduct.is_colimit W X) _ _ walking_pair.right end /-- Given a pair of isomorphisms between the summands of a pair of binary biproducts, we obtain an isomorphism between the binary biproducts. -/ @[simps] def biprod.map_iso {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ≅ Y) (g : X ≅ Z) : W ⊞ X ≅ Y ⊞ Z := { hom := biprod.map f.hom g.hom, inv := biprod.map f.inv g.inv } section variables [has_binary_biproducts C] /-- The braiding isomorphism which swaps a binary biproduct. -/ @[simps] def biprod.braiding (P Q : C) : P ⊞ Q ≅ Q ⊞ P := { hom := biprod.lift biprod.snd biprod.fst, inv := biprod.lift biprod.snd biprod.fst } /-- An alternative formula for the braiding isomorphism which swaps a binary biproduct, using the fact that the biproduct is a coproduct. -/ @[simps] def biprod.braiding' (P Q : C) : P ⊞ Q ≅ Q ⊞ P := { hom := biprod.desc biprod.inr biprod.inl, inv := biprod.desc biprod.inr biprod.inl } lemma biprod.braiding'_eq_braiding {P Q : C} : biprod.braiding' P Q = biprod.braiding P Q := by tidy /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma biprod.braid_natural {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : biprod.map f g ≫ (biprod.braiding _ _).hom = (biprod.braiding _ _).hom ≫ biprod.map g f := by tidy @[reassoc] lemma biprod.braiding_map_braiding {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : (biprod.braiding X W).hom ≫ biprod.map f g ≫ (biprod.braiding Y Z).hom = biprod.map g f := by tidy @[simp, reassoc] lemma biprod.symmetry' (P Q : C) : biprod.lift biprod.snd biprod.fst ≫ biprod.lift biprod.snd biprod.fst = 𝟙 (P ⊞ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma biprod.symmetry (P Q : C) : (biprod.braiding P Q).hom ≫ (biprod.braiding Q P).hom = 𝟙 _ := by simp end -- TODO: -- If someone is interested, they could provide the constructions: -- has_binary_biproducts ↔ has_finite_biproducts end category_theory.limits namespace category_theory.limits section preadditive variables {C : Type u} [category.{v} C] [preadditive C] variables {J : Type v} [decidable_eq J] [fintype J] open category_theory.preadditive open_locale big_operators /-- In a preadditive category, we can construct a biproduct for `f : J → C` from any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ lemma has_biproduct_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) : has_biproduct f := has_biproduct.mk { bicone := b, is_limit := { lift := λ s, ∑ j, s.π.app j ≫ b.ι j, uniq' := λ s m h, begin erw [←category.comp_id m, ←total, comp_sum], apply finset.sum_congr rfl, intros j m, erw [reassoc_of (h j)], end, fac' := λ s j, begin simp only [sum_comp, category.assoc, bicone.to_cone_π_app, b.ι_π, comp_dite], -- See note [dsimp, simp]. dsimp, simp, end }, is_colimit := { desc := λ s, ∑ j, b.π j ≫ s.ι.app j, uniq' := λ s m h, begin erw [←category.id_comp m, ←total, sum_comp], apply finset.sum_congr rfl, intros j m, erw [category.assoc, h], end, fac' := λ s j, begin simp only [comp_sum, ←category.assoc, bicone.to_cocone_ι_app, b.ι_π, dite_comp], dsimp, simp, end } } /-- In a preadditive category, if the product over `f : J → C` exists, then the biproduct over `f` exists. -/ lemma has_biproduct.of_has_product (f : J → C) [has_product f] : has_biproduct f := has_biproduct_of_total { X := pi_obj f, π := limits.pi.π f, ι := λ j, pi.lift (λ j', if h : j = j' then eq_to_hom (congr_arg f h) else 0), ι_π := λ j j', by simp, } (by { ext, simp [sum_comp, comp_dite] }) /-- In a preadditive category, if the coproduct over `f : J → C` exists, then the biproduct over `f` exists. -/ lemma has_biproduct.of_has_coproduct (f : J → C) [has_coproduct f] : has_biproduct f := has_biproduct_of_total { X := sigma_obj f, π := λ j, sigma.desc (λ j', if h : j' = j then eq_to_hom (congr_arg f h) else 0), ι := limits.sigma.ι f, ι_π := λ j j', by simp, } begin ext, simp only [comp_sum, limits.colimit.ι_desc_assoc, eq_self_iff_true, limits.colimit.ι_desc, category.comp_id], dsimp, simp only [dite_comp, finset.sum_dite_eq, finset.mem_univ, if_true, category.id_comp, eq_to_hom_refl, zero_comp], end /-- A preadditive category with finite products has finite biproducts. -/ lemma has_finite_biproducts.of_has_finite_products [has_finite_products C] : has_finite_biproducts C := ⟨λ J _ _, { has_biproduct := λ F, by exactI has_biproduct.of_has_product _ }⟩ /-- A preadditive category with finite coproducts has finite biproducts. -/ lemma has_finite_biproducts.of_has_finite_coproducts [has_finite_coproducts C] : has_finite_biproducts C := ⟨λ J _ _, { has_biproduct := λ F, by exactI has_biproduct.of_has_coproduct _ }⟩ section variables {f : J → C} [has_biproduct f] /-- In any preadditive category, any biproduct satsifies `∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` -/ @[simp] lemma biproduct.total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f) := begin ext j j', simp [comp_sum, sum_comp, biproduct.ι_π, comp_dite, dite_comp], end lemma biproduct.lift_eq {T : C} {g : Π j, T ⟶ f j} : biproduct.lift g = ∑ j, g j ≫ biproduct.ι f j := begin ext j, simp [sum_comp, biproduct.ι_π, comp_dite], end lemma biproduct.desc_eq {T : C} {g : Π j, f j ⟶ T} : biproduct.desc g = ∑ j, biproduct.π f j ≫ g j := begin ext j, simp [comp_sum, biproduct.ι_π_assoc, dite_comp], end @[simp, reassoc] lemma biproduct.lift_desc {T U : C} {g : Π j, T ⟶ f j} {h : Π j, f j ⟶ U} : biproduct.lift g ≫ biproduct.desc h = ∑ j : J, g j ≫ h j := by simp [biproduct.lift_eq, biproduct.desc_eq, comp_sum, sum_comp, biproduct.ι_π_assoc, comp_dite, dite_comp] lemma biproduct.map_eq [has_finite_biproducts C] {f g : J → C} {h : Π j, f j ⟶ g j} : biproduct.map h = ∑ j : J, biproduct.π f j ≫ h j ≫ biproduct.ι g j := begin ext, simp [biproduct.ι_π, biproduct.ι_π_assoc, comp_sum, sum_comp, comp_dite, dite_comp], end @[simp, reassoc] lemma biproduct.matrix_desc {K : Type v} [fintype K] [decidable_eq K] [has_finite_biproducts C] {f : J → C} {g : K → C} (m : Π j k, f j ⟶ g k) {P} (x : Π k, g k ⟶ P) : biproduct.matrix m ≫ biproduct.desc x = biproduct.desc (λ j, ∑ k, m j k ≫ x k) := by { ext, simp, } @[simp, reassoc] lemma biproduct.lift_matrix {K : Type v} [fintype K] [decidable_eq K] [has_finite_biproducts C] {f : J → C} {g : K → C} {P} (x : Π j, P ⟶ f j) (m : Π j k, f j ⟶ g k) : biproduct.lift x ≫ biproduct.matrix m = biproduct.lift (λ k, ∑ j, x j ≫ m j k) := by { ext, simp, } @[reassoc] lemma biproduct.matrix_map {K : Type v} [fintype K] [decidable_eq K] [has_finite_biproducts C] {f : J → C} {g : K → C} {h : K → C} (m : Π j k, f j ⟶ g k) (n : Π k, g k ⟶ h k) : biproduct.matrix m ≫ biproduct.map n = biproduct.matrix (λ j k, m j k ≫ n k) := by { ext, simp, } @[reassoc] lemma biproduct.map_matrix {K : Type v} [fintype K] [decidable_eq K] [has_finite_biproducts C] {f : J → C} {g : J → C} {h : K → C} (m : Π k, f k ⟶ g k) (n : Π j k, g j ⟶ h k) : biproduct.map m ≫ biproduct.matrix n = biproduct.matrix (λ j k, m j ≫ n j k) := by { ext, simp, } end /-- In a preadditive category, we can construct a binary biproduct for `X Y : C` from any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ lemma has_binary_biproduct_of_total {X Y : C} (b : binary_bicone X Y) (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : has_binary_biproduct X Y := has_binary_biproduct.mk { bicone := b, is_limit := { lift := λ s, binary_fan.fst s ≫ b.inl + binary_fan.snd s ≫ b.inr, uniq' := λ s m h, by erw [←category.comp_id m, ←total, comp_add, reassoc_of (h walking_pair.left), reassoc_of (h walking_pair.right)], fac' := λ s j, by cases j; simp, }, is_colimit := { desc := λ s, b.fst ≫ binary_cofan.inl s + b.snd ≫ binary_cofan.inr s, uniq' := λ s m h, by erw [←category.id_comp m, ←total, add_comp, category.assoc, category.assoc, h walking_pair.left, h walking_pair.right], fac' := λ s j, by cases j; simp, } } /-- In a preadditive category, if the product of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ lemma has_binary_biproduct.of_has_binary_product (X Y : C) [has_binary_product X Y] : has_binary_biproduct X Y := has_binary_biproduct_of_total { X := X ⨯ Y, fst := category_theory.limits.prod.fst, snd := category_theory.limits.prod.snd, inl := prod.lift (𝟙 X) 0, inr := prod.lift 0 (𝟙 Y) } begin ext; simp [add_comp], end /-- In a preadditive category, if all binary products exist, then all binary biproducts exist. -/ lemma has_binary_biproducts.of_has_binary_products [has_binary_products C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_product X Y, } /-- In a preadditive category, if the coproduct of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ lemma has_binary_biproduct.of_has_binary_coproduct (X Y : C) [has_binary_coproduct X Y] : has_binary_biproduct X Y := has_binary_biproduct_of_total { X := X ⨿ Y, fst := coprod.desc (𝟙 X) 0, snd := coprod.desc 0 (𝟙 Y), inl := category_theory.limits.coprod.inl, inr := category_theory.limits.coprod.inr } begin ext; simp [add_comp], end /-- In a preadditive category, if all binary coproducts exist, then all binary biproducts exist. -/ lemma has_binary_biproducts.of_has_binary_coproducts [has_binary_coproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_coproduct X Y, } section variables {X Y : C} [has_binary_biproduct X Y] /-- In any preadditive category, any binary biproduct satsifies `biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y)`. -/ @[simp] lemma biprod.total : biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y) := begin ext; simp [add_comp], end lemma biprod.lift_eq {T : C} {f : T ⟶ X} {g : T ⟶ Y} : biprod.lift f g = f ≫ biprod.inl + g ≫ biprod.inr := begin ext; simp [add_comp], end lemma biprod.desc_eq {T : C} {f : X ⟶ T} {g : Y ⟶ T} : biprod.desc f g = biprod.fst ≫ f + biprod.snd ≫ g := begin ext; simp [add_comp], end @[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T ⟶ X} {g : T ⟶ Y} {h : X ⟶ U} {i : Y ⟶ U} : biprod.lift f g ≫ biprod.desc h i = f ≫ h + g ≫ i := by simp [biprod.lift_eq, biprod.desc_eq] lemma biprod.map_eq [has_binary_biproducts C] {W X Y Z : C} {f : W ⟶ Y} {g : X ⟶ Z} : biprod.map f g = biprod.fst ≫ f ≫ biprod.inl + biprod.snd ≫ g ≫ biprod.inr := by apply biprod.hom_ext; apply biprod.hom_ext'; simp end end preadditive end category_theory.limits
a2ccca55eaedb4547d863f8976a30fddf1aefd98
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/subobject/comma.lean
76222c511100b133d0ac70b698131efc665798a9
[ "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
10,204
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.subobject.well_powered import category_theory.limits.preserves.finite import category_theory.limits.shapes.finite_limits /-! # Subobjects in the category of structured arrows We compute the subobjects of an object `A` in the category `structured_arrow S T` for `T : C ⥤ D` and `S : D` as a subtype of the subobjects of `A.right`. We deduce that `structured_arrow S T` is well-powered if `C` is. ## Main declarations * `structured_arrow.equiv_subtype`: the order-equivalence between `subobject A` and a subtype of `subobject A.right`. ## Implementation notes Our computation requires that `C` has all limits and `T` preserves all limits. Furthermore, we require that the morphisms of `C` and `D` are in the same universe. It is possible that both of these requirements can be relaxed by refining the results about limits in comma categories. We also provide the dual results. As usual, we use `subobject (op A)` for the quotient objects of `A`. -/ noncomputable theory open category_theory.limits opposite universes v u₁ u₂ namespace category_theory variables {C : Type u₁} [category.{v} C] {D : Type u₂} [category.{v} D] namespace structured_arrow variables {S : D} {T : C ⥤ D} /-- Every subobject of a structured arrow can be projected to a subobject of the underlying object. -/ def project_subobject [has_limits C] [preserves_limits T] {A : structured_arrow S T} : subobject A → subobject A.right := begin refine subobject.lift (λ P f hf, by exactI subobject.mk f.right) _, introsI P Q f g hf hg i hi, refine subobject.mk_eq_mk_of_comm _ _ ((proj S T).map_iso i) _, exact congr_arg comma_morphism.right hi end @[simp] lemma project_subobject_mk [has_limits C] [preserves_limits T] {A P : structured_arrow S T} (f : P ⟶ A) [mono f] : project_subobject (subobject.mk f) = subobject.mk f.right := rfl lemma project_subobject_factors [has_limits C] [preserves_limits T] {A : structured_arrow S T} : ∀ P : subobject A, ∃ q, q ≫ T.map (project_subobject P).arrow = A.hom := subobject.ind _ $ λ P f hf, ⟨P.hom ≫ T.map (subobject.underlying_iso _).inv, by { dsimp, simp [← T.map_comp] }⟩ /-- A subobject of the underlying object of a structured arrow can be lifted to a subobject of the structured arrow, provided that there is a morphism making the subobject into a structured arrow. -/ @[simp] def lift_subobject {A : structured_arrow S T} (P : subobject A.right) {q} (hq : q ≫ T.map P.arrow = A.hom) : subobject A := subobject.mk (hom_mk P.arrow hq : mk q ⟶ A) /-- Projecting and then lifting a subobject recovers the original subobject, because there is at most one morphism making the projected subobject into a structured arrow. -/ lemma lift_project_subobject [has_limits C] [preserves_limits T] {A : structured_arrow S T} : ∀ (P : subobject A) {q} (hq : q ≫ T.map (project_subobject P).arrow = A.hom), lift_subobject (project_subobject P) hq = P := subobject.ind _ begin introsI P f hf q hq, fapply subobject.mk_eq_mk_of_comm, { fapply iso_mk, { exact subobject.underlying_iso _ }, { exact (cancel_mono (T.map f.right)).1 (by { dsimp, simpa [← T.map_comp] using hq }) } }, { exact ext _ _ (by { dsimp, simp })} end /-- If `A : S → T.obj B` is a structured arrow for `S : D` and `T : C ⥤ D`, then we can explicitly describe the subobjects of `A` as the subobjects `P` of `B` in `C` for which `A.hom` factors through the image of `P` under `T`. -/ @[simps] def subobject_equiv [has_limits C] [preserves_limits T] (A : structured_arrow S T) : subobject A ≃o { P : subobject A.right // ∃ q, q ≫ T.map P.arrow = A.hom } := { to_fun := λ P, ⟨project_subobject P, project_subobject_factors P⟩, inv_fun := λ P, lift_subobject P.val P.prop.some_spec, left_inv := λ P, lift_project_subobject _ _, right_inv := λ P, subtype.ext (by simp), map_rel_iff' := subobject.ind₂ _ begin introsI P Q f g hf hg, refine ⟨λ h, subobject.mk_le_mk_of_comm _ (ext _ _ _), λ h, _⟩, { refine hom_mk (subobject.of_mk_le_mk _ _ h) ((cancel_mono (T.map g.right)).1 _), simp [← T.map_comp] }, { simp only [mono_over.mk'_arrow, subobject.of_mk_le_mk_comp, comma.comp_right, hom_mk_right] }, { refine subobject.mk_le_mk_of_comm (subobject.of_mk_le_mk _ _ h).right _, exact congr_arg comma_morphism.right (subobject.of_mk_le_mk_comp h) } end } /-- If `C` is well-powered and complete and `T` preserves limits, then `structured_arrow S T` is well-powered. -/ instance well_powered_structured_arrow [well_powered C] [has_limits C] [preserves_limits T] : well_powered (structured_arrow S T) := { subobject_small := λ X, small_map (subobject_equiv X).to_equiv } end structured_arrow namespace costructured_arrow variables {S : C ⥤ D} {T : D} /-- Every quotient of a costructured arrow can be projected to a quotient of the underlying object. -/ def project_quotient [has_colimits C] [preserves_colimits S] {A : costructured_arrow S T} : subobject (op A) → subobject (op A.left) := begin refine subobject.lift (λ P f hf, by exactI subobject.mk f.unop.left.op) _, introsI P Q f g hf hg i hi, refine subobject.mk_eq_mk_of_comm _ _ ((proj S T).map_iso i.unop).op (quiver.hom.unop_inj _), have := congr_arg quiver.hom.unop hi, simpa using congr_arg comma_morphism.left this, end @[simp] lemma project_quotient_mk [has_colimits C] [preserves_colimits S] {A : costructured_arrow S T} {P : (costructured_arrow S T)ᵒᵖ} (f : P ⟶ op A) [mono f] : (project_quotient (subobject.mk f)) = subobject.mk f.unop.left.op := rfl lemma project_quotient_factors [has_colimits C] [preserves_colimits S] {A : costructured_arrow S T} : ∀ P : subobject (op A), ∃ q, S.map (project_quotient P).arrow.unop ≫ q = A.hom := subobject.ind _ $ λ P f hf, ⟨S.map (subobject.underlying_iso _).unop.inv ≫ P.unop.hom, by { dsimp, rw [← category.assoc, ← S.map_comp, ← unop_comp], simp }⟩ /-- A quotient of the underlying object of a costructured arrow can be lifted to a quotient of the costructured arrow, provided that there is a morphism making the quotient into a costructured arrow. -/ @[simp] def lift_quotient {A : costructured_arrow S T} (P : subobject (op A.left)) {q} (hq : S.map P.arrow.unop ≫ q = A.hom) : subobject (op A) := subobject.mk (hom_mk P.arrow.unop hq : A ⟶ mk q).op /-- Technical lemma for `lift_project_quotient`. -/ @[simp] lemma unop_left_comp_underlying_iso_hom_unop {A : costructured_arrow S T} {P : (costructured_arrow S T)ᵒᵖ} (f : P ⟶ op A) [mono f.unop.left.op] : f.unop.left ≫ (subobject.underlying_iso f.unop.left.op).hom.unop = (subobject.mk f.unop.left.op).arrow.unop := begin conv_lhs { congr, rw [← quiver.hom.unop_op f.unop.left] }, rw [← unop_comp, subobject.underlying_iso_hom_comp_eq_mk] end /-- Projecting and then lifting a quotient recovers the original quotient, because there is at most one morphism making the projected quotient into a costructured arrow. -/ lemma lift_project_quotient [has_colimits C] [preserves_colimits S] {A : costructured_arrow S T} : ∀ (P : subobject (op A)) {q} (hq : S.map (project_quotient P).arrow.unop ≫ q = A.hom), lift_quotient (project_quotient P) hq = P := subobject.ind _ begin introsI P f hf q hq, fapply subobject.mk_eq_mk_of_comm, { refine (iso.op (iso_mk _ _) : _ ≅ op (unop P)), { exact (subobject.underlying_iso f.unop.left.op).unop }, { refine (cancel_epi (S.map f.unop.left)).1 _, simpa [← category.assoc, ← S.map_comp] using hq } }, { exact quiver.hom.unop_inj (ext _ _ (by { dsimp, simp })) } end /-- Technical lemma for `quotient_equiv`. -/ lemma unop_left_comp_of_mk_le_mk_unop {A : costructured_arrow S T} {P Q : (costructured_arrow S T)ᵒᵖ} {f : P ⟶ op A} {g : Q ⟶ op A} [mono f.unop.left.op] [mono g.unop.left.op] (h : subobject.mk f.unop.left.op ≤ subobject.mk g.unop.left.op) : g.unop.left ≫ (subobject.of_mk_le_mk f.unop.left.op g.unop.left.op h).unop = f.unop.left := begin conv_lhs { congr, rw [← quiver.hom.unop_op g.unop.left] }, rw [← unop_comp], simp only [subobject.of_mk_le_mk_comp, quiver.hom.unop_op] end /-- If `A : S.obj B ⟶ T` is a costructured arrow for `S : C ⥤ D` and `T : D`, then we can explicitly describe the quotients of `A` as the quotients `P` of `B` in `C` for which `A.hom` factors through the image of `P` under `S`. -/ def quotient_equiv [has_colimits C] [preserves_colimits S] (A : costructured_arrow S T) : subobject (op A) ≃o { P : subobject (op A.left) // ∃ q, S.map P.arrow.unop ≫ q = A.hom } := { to_fun := λ P, ⟨project_quotient P, project_quotient_factors P⟩, inv_fun := λ P, lift_quotient P.val P.prop.some_spec, left_inv := λ P, lift_project_quotient _ _, right_inv := λ P, subtype.ext (by simp), map_rel_iff' := subobject.ind₂ _ begin introsI P Q f g hf hg, refine ⟨λ h, subobject.mk_le_mk_of_comm _ (quiver.hom.unop_inj (ext _ _ _)), λ h, _⟩, { refine (hom_mk (subobject.of_mk_le_mk _ _ h).unop ((cancel_epi (S.map g.unop.left)).1 _)).op, dsimp only [mono_over.mk'_arrow], rw [← category.assoc, ← S.map_comp, unop_left_comp_of_mk_le_mk_unop], dsimp, simp }, { exact unop_left_comp_of_mk_le_mk_unop _ }, { refine subobject.mk_le_mk_of_comm (subobject.of_mk_le_mk _ _ h).unop.left.op _, refine quiver.hom.unop_inj _, have := congr_arg quiver.hom.unop (subobject.of_mk_le_mk_comp h), simpa [-subobject.of_mk_le_mk_comp] using congr_arg comma_morphism.left this } end } /-- If `C` is well-copowered and cocomplete and `S` preserves colimits, then `costructured_arrow S T` is well-copowered. -/ instance well_copowered_costructured_arrow [well_powered Cᵒᵖ] [has_colimits C] [preserves_colimits S] : well_powered (costructured_arrow S T)ᵒᵖ := { subobject_small := λ X, small_map (quotient_equiv (unop X)).to_equiv } end costructured_arrow end category_theory
97f002b3562548e74ff9261dacef4faf9a054e9e
d718c3849c9ac45bd482d671f56c3831e5f2e699
/src/test.lean
4793abb4f82803b4687cfc29d8f153d636b670f4
[]
no_license
khoek/lean-local-cache
a4089ed9a6bdc21254b22b387b2dd4d0fb79659c
4cd64e20628be2a33d138a31dcc5b64ec57d13b7
refs/heads/master
1,588,230,294,496
1,553,071,246,000
1,553,071,246,000
176,673,783
0
0
null
null
null
null
UTF-8
Lean
false
false
1,205
lean
import tactic.local_cache open tactic section example_tactic def TEST_NS : name := `my_tactic -- Example "expensive" function meta def generate_some_data : tactic (list ℕ) := do trace "cache regenerating", return [1, 2, 3, 4] meta def my_tactic : tactic unit := do my_cached_data ← run_once TEST_NS generate_some_data, -- Do some stuff with `my_cached_data` skip end example_tactic section example_usage -- Note only a single cache regeneration (only a single trace message), -- even upon descent to a sub-tactic-block. lemma my_lemma : true := begin my_tactic, my_tactic, my_tactic, have h : true, { my_tactic, trivial }, trivial end end example_usage section test meta def fail_if_cache_miss : tactic unit := do p ← local_cache.present TEST_NS, if p then skip else fail "cache miss" meta def clear_cache : tactic unit := local_cache.clear TEST_NS lemma my_test : true := begin success_if_fail { fail_if_cache_miss }, my_tactic, fail_if_cache_miss, fail_if_cache_miss, have h : true, { fail_if_cache_miss, trivial }, clear_cache, success_if_fail { fail_if_cache_miss }, trivial end end test
970ce6ebdf646efaccfa0500a448c9557abef923
fbf512ee44de430e3d3c5869751ad95325c938d7
/nat.lean
8f709518ffe673ed82faa8ae04e383f40d040a51
[]
no_license
skbaek/clausify
4858c9005fb86a5e410bfcaa77524f82d955f655
d09b071bdcce7577c3fffacd0893b776285b1590
refs/heads/master
1,588,360,590,818
1,553,553,880,000
1,553,553,880,000
177,644,542
0
0
null
null
null
null
UTF-8
Lean
false
false
196
lean
namespace nat lemma succ_lt_succ_iff : ∀ {a b : ℕ}, nat.succ a < nat.succ b ↔ a < b := begin intros a b, apply iff.intro, apply lt_of_succ_lt_succ, apply succ_lt_succ end end nat
67c789bfadaec9629172e0d0fe7be0caf97c8c3f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/specific_groups/quaternion.lean
a94ea0c090e83eedc923007b73639ca7519903bc
[ "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
9,211
lean
/- Copyright (c) 2021 Julian Kuelshammer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Julian Kuelshammer -/ import data.zmod.basic import data.nat.basic import tactic.interval_cases import group_theory.specific_groups.dihedral import group_theory.specific_groups.cyclic /-! # Quaternion Groups We define the (generalised) quaternion groups `quaternion_group n` of order `4n`, also known as dicyclic groups, with elements `a i` and `xa i` for `i : zmod n`. The (generalised) quaternion groups can be defined by the presentation $\langle a, x | a^{2n} = 1, x^2 = a^n, x^{-1}ax=a^{-1}\rangle$. We write `a i` for $a^i$ and `xa i` for $x * a^i$. For `n=2` the quaternion group `quaternion_group 2` is isomorphic to the unit integral quaternions `(quaternion ℤ)ˣ`. ## Main definition `quaternion_group n`: The (generalised) quaternion group of order `4n`. ## Implementation notes This file is heavily based on `dihedral_group` by Shing Tak Lam. In mathematics, the name "quaternion group" is reserved for the cases `n ≥ 2`. Since it would be inconvenient to carry around this condition we define `quaternion_group` also for `n = 0` and `n = 1`. `quaternion_group 0` is isomorphic to the infinite dihedral group, while `quaternion_group 1` is isomorphic to a cyclic group of order `4`. ## References * https://en.wikipedia.org/wiki/Dicyclic_group * https://en.wikipedia.org/wiki/Quaternion_group ## TODO Show that `quaternion_group 2 ≃* (quaternion ℤ)ˣ`. -/ /-- The (generalised) quaternion group `quaternion_group n` of order `4n`. It can be defined by the presentation $\langle a, x | a^{2n} = 1, x^2 = a^n, x^{-1}ax=a^{-1}\rangle$. We write `a i` for $a^i$ and `xa i` for $x * a^i$. -/ @[derive decidable_eq] inductive quaternion_group (n : ℕ) : Type | a : zmod (2 * n) → quaternion_group | xa : zmod (2 * n) → quaternion_group namespace quaternion_group variables {n : ℕ} /-- Multiplication of the dihedral group. -/ private def mul : quaternion_group n → quaternion_group n → quaternion_group n | (a i) (a j) := a (i + j) | (a i) (xa j) := xa (j - i) | (xa i) (a j) := xa (i + j) | (xa i) (xa j) := a (n + j - i) /-- The identity `1` is given by `aⁱ`. -/ private def one : quaternion_group n := a 0 instance : inhabited (quaternion_group n) := ⟨one⟩ /-- The inverse of an element of the quaternion group. -/ private def inv : quaternion_group n → quaternion_group n | (a i) := a (-i) | (xa i) := xa (n + i) /-- The group structure on `quaternion_group n`. -/ instance : group (quaternion_group n) := { mul := mul, mul_assoc := begin rintros (i | i) (j | j) (k | k); simp only [mul]; abel, simp only [neg_mul_eq_neg_mul_symm, one_mul, int.cast_one, zsmul_eq_mul, int.cast_neg, add_right_inj], calc -(n : zmod (2 * n)) = 0 - n : by rw zero_sub ... = 2 * n - n : by { norm_cast, simp, } ... = n : by ring end, one := one, one_mul := begin rintros (i | i), { exact congr_arg a (zero_add i) }, { exact congr_arg xa (sub_zero i) }, end, mul_one := begin rintros (i | i), { exact congr_arg a (add_zero i) }, { exact congr_arg xa (add_zero i) }, end, inv := inv, mul_left_inv := begin rintros (i | i), { exact congr_arg a (neg_add_self i) }, { exact congr_arg a (sub_self (n + i)) }, end } variable {n} @[simp] lemma a_mul_a (i j : zmod (2 * n)) : a i * a j = a (i + j) := rfl @[simp] lemma a_mul_xa (i j : zmod (2 * n)) : a i * xa j = xa (j - i) := rfl @[simp] lemma xa_mul_a (i j : zmod (2 * n)) : xa i * a j = xa (i + j) := rfl @[simp] lemma xa_mul_xa (i j : zmod (2 * n)) : xa i * xa j = a (n + j - i) := rfl lemma one_def : (1 : quaternion_group n) = a 0 := rfl private def fintype_helper : (zmod (2 * n) ⊕ zmod (2 * n)) ≃ quaternion_group n := { inv_fun := λ i, match i with | (a j) := sum.inl j | (xa j) := sum.inr j end, to_fun := λ i, match i with | (sum.inl j) := a j | (sum.inr j) := xa j end, left_inv := by rintro (x | x); refl, right_inv := by rintro (x | x); refl } /-- The special case that more or less by definition `quaternion_group 0` is isomorphic to the infinite dihedral group. -/ def quaternion_group_zero_equiv_dihedral_group_zero : quaternion_group 0 ≃* dihedral_group 0 := { to_fun := λ i, quaternion_group.rec_on i dihedral_group.r dihedral_group.sr, inv_fun := λ i, match i with | (dihedral_group.r j) := a j | (dihedral_group.sr j) := xa j end, left_inv := by rintro (k | k); refl, right_inv := by rintro (k | k); refl, map_mul' := by { rintros (k | k) (l | l); { dsimp, simp, }, } } /-- Some of the lemmas on `zmod m` require that `m` is positive, as `m = 2 * n` is the case relevant in this file but we don't want to write `[fact (0 < 2 * n)]` we make this lemma a local instance. -/ private lemma succ_mul_pos_fact {m : ℕ} [hn : fact (0 < n)] : fact (0 < (nat.succ m) * n) := ⟨nat.succ_mul_pos m hn.1⟩ local attribute [instance] succ_mul_pos_fact /-- If `0 < n`, then `quaternion_group n` is a finite group. -/ instance [fact (0 < n)] : fintype (quaternion_group n) := fintype.of_equiv _ fintype_helper instance : nontrivial (quaternion_group n) := ⟨⟨a 0, xa 0, dec_trivial⟩⟩ /-- If `0 < n`, then `quaternion_group n` has `4n` elements. -/ lemma card [fact (0 < n)] : fintype.card (quaternion_group n) = 4 * n := begin rw [← fintype.card_eq.mpr ⟨fintype_helper⟩, fintype.card_sum, zmod.card, two_mul], ring end @[simp] lemma a_one_pow (k : ℕ) : (a 1 : quaternion_group n) ^ k = a k := begin induction k with k IH, { refl }, { rw [pow_succ, IH, a_mul_a], congr' 1, norm_cast, rw nat.one_add } end @[simp] lemma a_one_pow_n : (a 1 : quaternion_group n)^(2 * n) = 1 := begin cases n, { simp_rw [mul_zero, pow_zero] }, { rw [a_one_pow, one_def], congr' 1, exact zmod.nat_cast_self _ } end @[simp] lemma xa_sq (i : zmod (2 * n)) : xa i ^ 2 = a n := begin simp [sq] end @[simp] lemma xa_pow_four (i : zmod (2 * n)) : xa i ^ 4 = 1 := begin simp only [pow_succ, sq, xa_mul_xa, xa_mul_a, add_sub_cancel, add_sub_assoc, add_sub_cancel', sub_self, add_zero], norm_cast, rw ← two_mul, simp [one_def], end /-- If `0 < n`, then `xa i` has order 4. -/ @[simp] lemma order_of_xa [hpos : fact (0 < n)] (i : zmod (2 * n)) : order_of (xa i) = 4 := begin change _ = 2^2, haveI : fact(nat.prime 2) := fact.mk (nat.prime_two), apply order_of_eq_prime_pow, { intro h, simp only [pow_one, xa_sq] at h, injection h with h', apply_fun zmod.val at h', apply_fun ( / n) at h', simp only [zmod.val_nat_cast, zmod.val_zero, nat.zero_div, nat.mod_mul_left_div_self, nat.div_self hpos.1] at h', norm_num at h' }, { norm_num } end /-- In the special case `n = 1`, `quaternion 1` is a cyclic group (of order `4`). -/ lemma quaternion_group_one_is_cyclic : is_cyclic (quaternion_group 1) := begin apply is_cyclic_of_order_of_eq_card, rw [card, mul_one], exact order_of_xa 0 end /-- If `0 < n`, then `a 1` has order `2 * n`. -/ @[simp] lemma order_of_a_one : order_of (a 1 : quaternion_group n) = 2 * n := begin rcases n.eq_zero_or_pos with rfl | hn, { simp_rw [mul_zero, order_of_eq_zero_iff'], intros n hn, rw [one_def, a_one_pow], apply mt a.inj, simpa using hn.ne' }, haveI := fact.mk hn, apply (nat.le_of_dvd (nat.succ_mul_pos _ hn) (order_of_dvd_of_pow_eq_one (@a_one_pow_n n))).lt_or_eq.resolve_left, intro h, have h1 : (a 1 : quaternion_group n)^(order_of (a 1)) = 1 := pow_order_of_eq_one _, rw a_one_pow at h1, injection h1 with h2, rw [← zmod.val_eq_zero, zmod.val_nat_cast, nat.mod_eq_of_lt h] at h2, exact absurd h2.symm (order_of_pos _).ne end /-- If `0 < n`, then `a i` has order `(2 * n) / gcd (2 * n) i`. -/ lemma order_of_a [fact (0 < n)] (i : zmod (2 * n)) : order_of (a i) = (2 * n) / nat.gcd (2 * n) i.val := begin conv_lhs { rw ← zmod.nat_cast_zmod_val i }, rw [← a_one_pow, order_of_pow, order_of_a_one] end lemma exponent : monoid.exponent (quaternion_group n) = 2 * lcm n 2 := begin rw [←normalize_eq 2, ←lcm_mul_left, normalize_eq], norm_num, rcases n.eq_zero_or_pos with rfl | hn, { simp only [lcm_zero_left, mul_zero], exact monoid.exponent_eq_zero_of_order_zero order_of_a_one }, haveI := fact.mk hn, apply nat.dvd_antisymm, { apply monoid.exponent_dvd_of_forall_pow_eq_one, rintro (m | m), { rw [←order_of_dvd_iff_pow_eq_one, order_of_a], refine nat.dvd_trans ⟨gcd (2 * n) m.val, _⟩ (dvd_lcm_left (2 * n) 4), exact (nat.div_mul_cancel (nat.gcd_dvd_left (2 * n) (m.val))).symm }, { rw [←order_of_dvd_iff_pow_eq_one, order_of_xa], exact dvd_lcm_right (2 * n) 4 } }, { apply lcm_dvd, { convert monoid.order_dvd_exponent (a 1), exact order_of_a_one.symm }, { convert monoid.order_dvd_exponent (xa 0), exact (order_of_xa 0).symm } } end end quaternion_group
ed64ed53c3f1c4135d284e248af251a670717d22
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/field_power.lean
90e55770d499647cecdc845053cf9e2dc4fe9db2
[ "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
9,018
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import algebra.group_with_zero.power import tactic.linarith /-! # Integer power operation on fields and division rings This file collects basic facts about the operation of raising an element of a `division_ring` to an integer power. More specialised results are provided in the case of a linearly ordered field. -/ universe u @[simp] lemma ring_hom.map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K →+* L) : ∀ (a : K) (n : ℤ), f (a ^ n) = f a ^ n := f.to_monoid_with_zero_hom.map_fpow @[simp] lemma fpow_bit0_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit0 n) = x ^ bit0 n := by rw [fpow_bit0', fpow_bit0', neg_mul_neg] lemma fpow_even_neg {K : Type*} [division_ring K] (a : K) {n : ℤ} (h : even n) : (-a) ^ n = a ^ n := begin obtain ⟨k, rfl⟩ := h, rw [←bit0_eq_two_mul, fpow_bit0_neg], end @[simp] lemma fpow_bit1_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit1 n) = - x ^ bit1 n := by rw [fpow_bit1', fpow_bit1', neg_mul_neg, neg_mul_eq_mul_neg] section ordered_field_power open int variables {K : Type u} [linear_ordered_field K] {a : K} {n : ℤ} lemma fpow_eq_zero_iff (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨fpow_eq_zero, _⟩, rintros rfl, exact zero_fpow _ hn.ne' end lemma fpow_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z | (n : ℕ) := by { rw gpow_coe_nat, exact pow_nonneg ha _ } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) } lemma fpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z | (n : ℕ) := by { rw gpow_coe_nat, exact pow_pos ha _ } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) } lemma fpow_le_of_le {x : K} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := begin induction a with a a; induction b with b b, { simp only [of_nat_eq_coe, gpow_coe_nat], apply pow_le_pow hx, apply le_of_coe_nat_le_coe_nat h }, { apply absurd h, apply not_le_of_gt, exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) }, { simp only [gpow_neg_succ_of_nat, one_div, of_nat_eq_coe, gpow_coe_nat], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [gpow_neg_succ_of_nat], apply (inv_le_inv _ _).2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma pow_le_max_of_min_le {x : K} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) := begin wlog hle : a ≤ b, have hnle : -b ≤ -a, from neg_le_neg hle, have hfle : x ^ (-b) ≤ x ^ (-a), from fpow_le_of_le hx hnle, have : x ^ (-c) ≤ x ^ (-a), { apply fpow_le_of_le hx, simpa only [min_eq_left hle, neg_le_neg_iff] using h }, simpa only [max_eq_left hfle] end lemma fpow_le_one_of_nonpos {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 := calc p ^ z ≤ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp lemma one_le_fpow_of_nonneg {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : 0 ≤ z) : 1 ≤ p ^ z := calc p ^ z ≥ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp theorem fpow_bit0_nonneg (a : K) (n : ℤ) : 0 ≤ a ^ bit0 n := by { rw fpow_bit0, exact mul_self_nonneg _ } theorem fpow_two_nonneg (a : K) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 theorem fpow_bit0_pos {a : K} (h : a ≠ 0) (n : ℤ) : 0 < a ^ bit0 n := (fpow_bit0_nonneg a n).lt_of_ne (fpow_ne_zero _ h).symm theorem fpow_two_pos_of_ne_zero (a : K) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 @[simp] theorem fpow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ fpow_nonneg h' _, λ h, by rw [bit1, fpow_add_one h.ne]; exact mul_neg_of_pos_of_neg (fpow_bit0_pos h.ne _) h⟩ @[simp] theorem fpow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 fpow_bit1_neg_iff @[simp] theorem fpow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := begin rw [le_iff_lt_or_eq, fpow_bit1_neg_iff], split, { rintro (h | h), { exact h.le }, { exact (fpow_eq_zero h).le } }, { intro h, rcases eq_or_lt_of_le h with rfl|h, { exact or.inr (zero_fpow _ (bit1_ne_zero n)) }, { exact or.inl h } } end @[simp] theorem fpow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le fpow_bit1_nonpos_iff lemma fpow_even_nonneg (a : K) {n : ℤ} (hn : even n) : 0 ≤ a ^ n := begin cases le_or_lt 0 a with h h, { exact fpow_nonneg h _ }, { rw [←fpow_even_neg _ hn], replace h : 0 ≤ -a := neg_nonneg_of_nonpos (le_of_lt h), exact fpow_nonneg h _ } end theorem fpow_even_pos (ha : a ≠ 0) (hn : even n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit0_pos ha k theorem fpow_odd_nonneg (ha : 0 ≤ a) (hn : odd n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_nonneg_iff.mpr ha theorem fpow_odd_pos (ha : 0 < a) (hn : odd n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_pos_iff.mpr ha theorem fpow_odd_nonpos (ha : a ≤ 0) (hn : odd n) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_nonpos_iff.mpr ha theorem fpow_odd_neg (ha : a < 0) (hn : odd n) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_neg_iff.mpr ha lemma fpow_even_abs (a : K) {p : ℤ} (hp : even p) : abs a ^ p = a ^ p := begin cases abs_choice a with h h; simp only [h, fpow_even_neg _ hp], end @[simp] lemma fpow_bit0_abs (a : K) (p : ℤ) : (abs a) ^ bit0 p = a ^ bit0 p := fpow_even_abs _ (even_bit0 _) lemma abs_fpow_even (a : K) {p : ℤ} (hp : even p) : abs (a ^ p) = a ^ p := begin rw [abs_eq_self], exact fpow_even_nonneg _ hp end @[simp] lemma abs_fpow_bit0 (a : K) (p : ℤ) : abs (a ^ bit0 p) = a ^ bit0 p := abs_fpow_even _ (even_bit0 _) end ordered_field_power lemma one_lt_pow {K} [linear_ordered_semiring K] {p : K} (hp : 1 < p) : ∀ {n : ℕ}, 1 ≤ n → 1 < p ^ n | 1 h := by simp; assumption | (k+2) h := begin rw [←one_mul (1 : K), pow_succ], apply mul_lt_mul, { assumption }, { apply le_of_lt, simpa using one_lt_pow (nat.le_add_left 1 k)}, { apply zero_lt_one }, { apply le_of_lt (lt_trans zero_lt_one hp) } end lemma one_lt_fpow {K} [linear_ordered_field K] {p : K} (hp : 1 < p) : ∀ z : ℤ, 0 < z → 1 < p ^ z | (n : ℕ) h := by { rw [gpow_coe_nat], exact one_lt_pow hp (nat.succ_le_of_lt (int.lt_of_coe_nat_lt_coe_nat h)) } | -[1+ n] h := ((int.neg_succ_not_pos _).mp h).elim section ordered variables {K : Type*} [linear_ordered_field K] lemma nat.fpow_pos_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : 0 < (p:K)^n := by { apply fpow_pos_of_pos, exact_mod_cast h } lemma nat.fpow_ne_zero_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : (p:K)^n ≠ 0 := ne_of_gt (nat.fpow_pos_of_pos h n) lemma fpow_strict_mono {x : K} (hx : 1 < x) : strict_mono (λ n:ℤ, x ^ n) := λ m n h, show x ^ m < x ^ n, begin have xpos : 0 < x := zero_lt_one.trans hx, have h₀ : x ≠ 0 := xpos.ne', have hxm : 0 < x^m := fpow_pos_of_pos xpos m, have h : 1 < x ^ (n - m) := one_lt_fpow hx _ (sub_pos_of_lt h), replace h := mul_lt_mul_of_pos_right h hxm, rwa [sub_eq_add_neg, fpow_add h₀, mul_assoc, fpow_neg_mul_fpow_self _ h₀, one_mul, mul_one] at h, end @[simp] lemma fpow_lt_iff_lt {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m < x ^ n ↔ m < n := (fpow_strict_mono hx).lt_iff_lt @[simp] lemma fpow_le_iff_le {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m ≤ x ^ n ↔ m ≤ n := (fpow_strict_mono hx).le_iff_le @[simp] lemma pos_div_pow_pos {a b : K} (ha : 0 < a) (hb : 0 < b) (k : ℕ) : 0 < a/b^k := div_pos ha (pow_pos hb k) @[simp] lemma div_pow_le {a b : K} (ha : 0 < a) (hb : 1 ≤ b) (k : ℕ) : a/b^k ≤ a := (div_le_iff $ pow_pos (lt_of_lt_of_le zero_lt_one hb) k).mpr (calc a = a * 1 : (mul_one a).symm ... ≤ a*b^k : (mul_le_mul_left ha).mpr $ one_le_pow_of_one_le hb _) lemma fpow_injective {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) : function.injective ((^) x : ℤ → K) := begin intros m n h, rcases h₁.lt_or_lt with H|H, { apply (fpow_strict_mono (one_lt_inv h₀ H)).injective, show x⁻¹ ^ m = x⁻¹ ^ n, rw [← fpow_neg_one, ← fpow_mul, ← fpow_mul, mul_comm _ m, mul_comm _ n, fpow_mul, fpow_mul, h], }, { exact (fpow_strict_mono H).injective h, }, end @[simp] lemma fpow_inj {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) {m n : ℤ} : x ^ m = x ^ n ↔ m = n := (fpow_injective h₀ h₁).eq_iff end ordered section variables {K : Type*} [field K] @[simp, norm_cast] theorem rat.cast_fpow [char_zero K] (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : K) = q ^ n := (rat.cast_hom K).map_fpow q n end
fc5a5e39c318fba6c896ef66e6f0ee89355cc1ae
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/Tactic/Simp/SimpLemmas.lean
11c4adb48a80e68fa4ffc72c95e285ad9ca127aa
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,021
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.LevelDefEq import Lean.Meta.DiscrTree import Lean.Meta.AppBuilder namespace Lean.Meta inductive SimpLemmaKind where | eq | iff | ne | pos | neg deriving Inhabited, BEq structure SimpLemma where keys : Array DiscrTree.Key val : Expr priority : Nat post : Bool perm : Bool -- true is lhs and rhs are identical modulo permutation of variables name? : Option Name := none -- for debugging and tracing purposes kind : SimpLemmaKind deriving Inhabited def SimpLemma.getName (s : SimpLemma) : Name := match s.name? with | some n => n | none => "<unknown>" instance : ToFormat SimpLemma where format s := let perm := if s.perm then ":perm" else "" let name := fmt s.getName let prio := f!":{s.priority}" name ++ prio ++ perm instance : ToMessageData SimpLemma where toMessageData s := fmt s instance : BEq SimpLemma where beq e₁ e₂ := e₁.val == e₂.val structure SimpLemmas where pre : DiscrTree SimpLemma := DiscrTree.empty post : DiscrTree SimpLemma := DiscrTree.empty deriving Inhabited def addSimpLemmaEntry (d : SimpLemmas) (e : SimpLemma) : SimpLemmas := if e.post then { d with post := d.post.insertCore e.keys e } else { d with pre := d.pre.insertCore e.keys e } builtin_initialize simpExtension : SimpleScopedEnvExtension SimpLemma SimpLemmas ← registerSimpleScopedEnvExtension { name := `simpExt initial := {} addEntry := addSimpLemmaEntry } private partial def isPerm : Expr → Expr → MetaM Bool | Expr.app f₁ a₁ _, Expr.app f₂ a₂ _ => isPerm f₁ f₂ <&&> isPerm a₁ a₂ | Expr.mdata _ s _, t => isPerm s t | s, Expr.mdata _ t _ => isPerm s t | s@(Expr.mvar ..), t@(Expr.mvar ..) => isDefEq s t | Expr.forallE n₁ d₁ b₁ _, Expr.forallE n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.lam n₁ d₁ b₁ _, Expr.lam n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.letE n₁ t₁ v₁ b₁ _, Expr.letE n₂ t₂ v₂ b₂ _ => isPerm t₁ t₂ <&&> isPerm v₁ v₂ <&&> withLetDecl n₁ t₁ v₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.proj _ i₁ b₁ _, Expr.proj _ i₂ b₂ _ => i₁ == i₂ <&&> isPerm b₁ b₂ | s, t => s == t def mkSimpLemmaCore (e : Expr) (val : Expr) (post : Bool) (prio : Nat) (name? : Option Name) : MetaM SimpLemma := do let type ← instantiateMVars (← inferType e) unless (← isProp type) do throwError! "invalid 'simp', proposition expected{indentExpr type}" withNewMCtxDepth do let (xs, _, type) ← withReducible <| forallMetaTelescopeReducing type let (keys, perm, kind) ← match type.eq? with | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs, SimpLemmaKind.eq) | none => match type.iff? with | some (lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs, SimpLemmaKind.iff) | none => match type.ne? with | some (_, lhs, rhs) => pure (← DiscrTree.mkPath (← mkEq lhs rhs), false, SimpLemmaKind.ne) | none => match type.not? with | some lhs => pure (← DiscrTree.mkPath lhs, false, SimpLemmaKind.neg) | none => pure (← DiscrTree.mkPath type, false, SimpLemmaKind.pos) return { keys := keys, perm := perm, kind := kind, post := post, val := val, name? := name?, priority := prio } def addSimpLemma (declName : Name) (post : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let cinfo ← getConstInfo declName /- The `simp` tactic uses fresh universe metavariables when using a global simp lemma. See `SimpLemma.getValue` -/ let lemma ← mkSimpLemmaCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) (mkConst declName) post prio declName simpExtension.add lemma attrKind builtin_initialize registerBuiltinAttribute { name := `simp descr := "simplification lemma" add := fun declName stx attrKind => do let post := if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost let prio ← getAttrParamOptPrio stx[2] discard <| addSimpLemma declName post attrKind prio |>.run {} {} } def getSimpLemmas : MetaM SimpLemmas := return simpExtension.getState (← getEnv) /- Auxiliary method for creating a local simp lemma. -/ def mkSimpLemma (e : Expr) (post : Bool := true) (prio : Nat := evalPrio! default) (name? : Option Name := none) : MetaM SimpLemma := do mkSimpLemmaCore e e post prio name? /- Auxiliary method for adding a local simp lemma to a `SimpLemmas` datastructure. -/ def SimpLemmas.add (s : SimpLemmas) (e : Expr) (post : Bool := true) (prio : Nat := evalPrio! default) (name? : Option Name := none) : MetaM SimpLemmas := do let lemma ← mkSimpLemma e post prio name? return addSimpLemmaEntry s lemma /- Auxiliary method for adding a global declaration to a `SimpLemmas` datastructure. -/ def SimpLemmas.addConst (s : SimpLemmas) (declName : Name) (post : Bool := true) (prio : Nat := evalPrio! default) : MetaM SimpLemmas := do let cinfo ← getConstInfo declName let lemma ← mkSimpLemmaCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) (mkConst declName) post prio declName return addSimpLemmaEntry s lemma def SimpLemma.getValue (lemma : SimpLemma) : MetaM Expr := do match lemma.val with | Expr.const declName [] _ => let info ← getConstInfo declName if info.levelParams.isEmpty then return lemma.val else return lemma.val.updateConst! (← info.levelParams.mapM (fun _ => mkFreshLevelMVar)) | _ => return lemma.val end Lean.Meta
5a9ad8d5a425ee660b45df7dfa02cc86cde185fb
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/topology/uniform_space/separation.lean
d3e57e6e5731b749715c4ad8db9e419a3e983706
[ "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
20,757
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, Patrick Massot -/ import topology.uniform_space.basic import tactic.apply_fun /-! # Hausdorff properties of uniform spaces. Separation quotient. This file studies uniform spaces whose underlying topological spaces are separated (also known as Hausdorff or T₂). This turns out to be equivalent to asking that the intersection of all entourages is the diagonal only. This condition actually implies the stronger separation property that the space is regular (T₃), hence those conditions are equivalent for topologies coming from a uniform structure. More generally, the intersection `𝓢 X` of all entourages of `X`, which has type `set (X × X)` is an equivalence relation on `X`. Points which are equivalent under the relation are basically undistinguishable from the point of view of the uniform structure. For instance any uniformly continuous function will send equivalent points to the same value. The quotient `separation_quotient X` of `X` by `𝓢 X` has a natural uniform structure which is separated, and satisfies a universal property: every uniformly continuous function from `X` to a separated uniform space uniquely factors through `separation_quotient X`. As usual, this allows to turn `separation_quotient` into a functor (but we don't use the category theory library in this file). These notions admit relative versions, one can ask that `s : set X` is separated, this is equivalent to asking that the uniform structure induced on `s` is separated. ## Main definitions * `separation_relation X : set (X × X)`: the separation relation * `separated_space X`: a predicate class asserting that `X` is separated * `is_separated s`: a predicate asserting that `s : set X` is separated * `separation_quotient X`: the maximal separated quotient of `X`. * `separation_quotient.lift f`: factors a map `f : X → Y` through the separation quotient of `X`. * `separation_quotient.map f`: turns a map `f : X → Y` into a map between the separation quotients of `X` and `Y`. ## Main results * `separated_iff_t2`: the equivalence between being separated and being Hausdorff for uniform spaces. * `separation_quotient.uniform_continuous_lift`: factoring a uniformly continuous map through the separation quotient gives a uniformly continuous map. * `separation_quotient.uniform_continuous_map`: maps induced between separation quotients are uniformly continuous. ## Notations Localized in `uniformity`, we have the notation `𝓢 X` for the separation relation on a uniform space `X`, ## Implementation notes The separation setoid `separation_setoid` is not declared as a global instance. It is made a local instance while building the theory of `separation_quotient`. The factored map `separation_quotient.lift f` is defined without imposing any condition on `f`, but returns junk if `f` is not uniformly continuous (constant junk hence it is always uniformly continuous). -/ open filter topological_space set classical function uniform_space open_locale classical topological_space uniformity filter noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] /-! ### Separated uniform spaces -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets localized "notation `𝓢` := separation_rel" in uniformity lemma separated_equiv : equivalence (λx y, (x, y) ∈ 𝓢 α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ 𝓢 α) (hyz : (y, z) ∈ 𝓢 α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ /-- A uniform space is separated if its separation relation is trivial (each point is related only to itself). -/ @[class] def separated_space (α : Type u) [uniform_space α] := 𝓢 α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated_space, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [not_forall] lemma id_rel_sub_separation_relation (α : Type*) [uniform_space α] : id_rel ⊆ 𝓢 α := begin unfold separation_rel, rw id_rel_subset, intros x, suffices : ∀ t ∈ 𝓤 α, (x, x) ∈ t, by simpa only [refl_mem_uniformity], exact λ t, refl_mem_uniformity, end lemma separation_rel_comap {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓢 α = (prod.map f f) ⁻¹' 𝓢 β := begin dsimp [separation_rel], rw [uniformity_comap h, (filter.comap_has_basis (prod.map f f) (𝓤 β)).sInter_sets, ← preimage_bInter, sInter_eq_bInter], refl, end protected lemma filter.has_basis.separation_rel {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (h : has_basis (𝓤 α) p s) : 𝓢 α = ⋂ i ∈ set_of p, s i := by { unfold separation_rel, rw h.sInter_sets } lemma separation_rel_eq_inter_closure : 𝓢 α = ⋂₀ (closure '' (𝓤 α).sets) := by simpa [uniformity_has_basis_closure.separation_rel] lemma is_closed_separation_rel : is_closed (𝓢 α) := begin rw separation_rel_eq_inter_closure, apply is_closed_sInter, rintros _ ⟨t, t_in, rfl⟩, exact is_closed_closure, end lemma separated_iff_t2 : separated_space α ↔ t2_space α := begin classical, split ; intro h, { rw [t2_iff_is_closed_diagonal, ← show 𝓢 α = diagonal α, from h], exact is_closed_separation_rel }, { rw separated_def', intros x y hxy, have : 𝓝 x ⊓ 𝓝 y = ⊥, { rw t2_iff_nhds at h, by_contra H, exact hxy (h H) }, rcases inf_eq_bot_iff.mp this with ⟨U, U_in, V, V_in, H⟩, rcases mem_nhds_iff.mp U_in with ⟨S, S_in, S_sub⟩, use [S, S_in], change y ∉ ball x S, intro y_in, have : y ∈ U ∩ V := ⟨S_sub y_in, mem_of_nhds V_in⟩, rwa H at this }, end @[priority 100] -- see Note [lower instance priority] instance separated_regular [separated_space α] : regular_space α := { regular := λs a hs ha, have sᶜ ∈ 𝓝 a, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ sᶜ} ∈ 𝓤 α, from mem_nhds_uniformity_iff_right.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ sᶜ, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ 𝓟 (closure e)ᶜ = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (𝓟 (closure e)ᶜ) (𝓟 (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨(closure e)ᶜ, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..@t2_space.t1_space _ _ (separated_iff_t2.mp ‹_›) } /-! ### Separated sets -/ /-- A set `s` in a uniform space `α` is separated if the separation relation `𝓢 α` induces the trivial relation on `s`. -/ def is_separated (s : set α) : Prop := ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y lemma is_separated_def (s : set α) : is_separated s ↔ ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y := iff.rfl lemma is_separated_def' (s : set α) : is_separated s ↔ (s.prod s) ∩ 𝓢 α ⊆ id_rel := begin rw is_separated_def, split, { rintros h ⟨x, y⟩ ⟨⟨x_in, y_in⟩, H⟩, simp [h x y x_in y_in H] }, { intros h x y x_in y_in xy_in, rw ← mem_id_rel, exact h ⟨mk_mem_prod x_in y_in, xy_in⟩ } end lemma univ_separated_iff : is_separated (univ : set α) ↔ separated_space α := begin simp only [is_separated, mem_univ, true_implies_iff, separated_space], split, { intro h, exact subset.antisymm (λ ⟨x, y⟩ xy_in, h x y xy_in) (id_rel_sub_separation_relation α), }, { intros h x y xy_in, rwa h at xy_in }, end lemma is_separated_of_separated_space [separated_space α] (s : set α) : is_separated s := begin rw [is_separated, show 𝓢 α = diagonal α, from ‹separated_space α›], tauto, end lemma is_separated_iff_induced {s : set α} : is_separated s ↔ separated_space s := begin change _ ↔ 𝓢 ({x // x ∈ s}) = _, rw [separation_rel_comap rfl, is_separated_def'], split; intro h, { ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, suffices : (x, y) ∈ 𝓢 α ↔ x = y, by simpa only [mem_id_rel], refine ⟨λ H, h ⟨mk_mem_prod x_in y_in, H⟩, _⟩, rintro rfl, exact id_rel_sub_separation_relation α rfl }, { rintros ⟨x, y⟩ ⟨⟨x_in, y_in⟩, hS⟩, have A : (⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩ : ↥s × ↥s) ∈ prod.map (coe : s → α) (coe : s → α) ⁻¹' 𝓢 α, from hS, simpa using h.subset A } end lemma eq_of_uniformity_inf_nhds_of_is_separated {s : set α} (hs : is_separated s) : ∀ {x y : α}, x ∈ s → y ∈ s → cluster_pt (x, y) (𝓤 α) → x = y := begin intros x y x_in y_in H, have : ∀ V ∈ 𝓤 α, (x, y) ∈ closure V, { intros V V_in, rw mem_closure_iff_cluster_pt, have : 𝓤 α ≤ 𝓟 V, by rwa le_principal_iff, exact H.mono this }, apply hs x y x_in y_in, simpa [separation_rel_eq_inter_closure], end lemma eq_of_uniformity_inf_nhds [separated_space α] : ∀ {x y : α}, cluster_pt (x, y) (𝓤 α) → x = y := begin have : is_separated (univ : set α), { rw univ_separated_iff, assumption }, introv, simpa using eq_of_uniformity_inf_nhds_of_is_separated this, end /-! ### Separation quotient -/ namespace uniform_space /-- The separation relation of a uniform space seen as a setoid. -/ def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ 𝓢 α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ 𝓢 α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ 𝓢 α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ 𝓢 α → (c, d) ∈ 𝓢 β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated_space (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated_space β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h /-- The maximal separated quotient of a uniform space `α`. -/ def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance [inhabited α] : inhabited (separation_quotient α) := by unfold separation_quotient; apply_instance /-- Factoring functions to a separated space through the separation quotient. -/ def lift [separated_space β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (classical.inhabited_of_nonempty $ (nonempty_quotient_iff $ separation_setoid α).1 ⟨x⟩).default lemma lift_mk [separated_space β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated_space β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end /-- The separation quotient functor acting on functions. -/ def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated_space α] [separated_space β] : separated_space (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space