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
544180ac7a740dd20a80a8e1f4bd685aaa17a5b0
a3c8de9b16e7a374b04f35a66da33cafd3b82569
/gateway/Dockerfile.Lean
762f0e13259b45fc6b09952a48f168262cf70530
[]
no_license
wupoyi1020/skypay
c6c7383e6bddb205760c46ad62d1d672e23a6a79
bd4de266ad65403f53476a14da95bbb73034e5da
refs/heads/master
1,588,601,029,481
1,554,254,105,000
1,554,254,105,000
179,183,188
0
0
null
null
null
null
UTF-8
Lean
false
false
605
lean
# Run following commands before you run docker build. # ./mvnw clean package # mkdir -p target/dependency && (cd target/dependency; jar -xf ../*.jar) FROM openjdk:8-jdk-alpine VOLUME /tmp ARG DEPENDENCY=target/dependency COPY ${DEPENDENCY}/BOOT-INF/lib /app/lib COPY ${DEPENDENCY}/META-INF /app/META-INF COPY ${DEPENDENCY}/BOOT-INF/classes /app ENTRYPOINT ["java","-noverify","-XX:TieredStopAtLevel=1","-XX:+UnlockExperimentalVMOptions","-XX:+UseCGroupMemoryLimitForHeap","-Dspring.backgroundpreinitializer.ignore=true","-Dspring.jmx.enabled=false","-cp","app:app/lib/*","com.example.skypay.Application"]
79190efc0546bb0e9ca6f9eb1a64a85bb5434934
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_1834.lean
4b43a4b0f9aa854316b28c07e6e401bf0ea350e9
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
242
lean
import tactic -- BEGIN variables {α : Type*} [preorder α] variables a b c : α example : ¬ a < a := begin rw lt_iff_le_not_le, sorry end example : a < b → b < c → a < c := begin simp only [lt_iff_le_not_le], sorry end -- END
b8357bfa5a124c60e7b1936c057f023860873fcb
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/algebra/module/submodule_lattice.lean
bb48cc9df28c56d5e5f2149b741210b5bec6e69a
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,241
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov -/ import algebra.module.submodule import algebra.punit_instances /-! # The lattice structure on `submodule`s This file defines the lattice structure on submodules, `submodule.complete_lattice`, with `⊥` defined as `{0}` and `⊓` defined as intersection of the underlying carrier. If `p` and `q` are submodules of a module, `p ≤ q` means that `p ⊆ q`. Many results about operations on this lattice structure are defined in `linear_algebra/basic.lean`, most notably those which use `span`. ## Implementation notes This structure should match the `add_submonoid.complete_lattice` structure, and we should try to unify the APIs where possible. -/ variables {R S M : Type*} section add_comm_monoid variables [semiring R] [semiring S] [add_comm_monoid M] [module R M] [module S M] variables [has_scalar S R] [is_scalar_tower S R M] variables {p q : submodule R M} namespace submodule /-- The set `{0}` is the bottom element of the lattice of submodules. -/ instance : has_bot (submodule R M) := ⟨{ carrier := {0}, smul_mem' := by simp { contextual := tt }, .. (⊥ : add_submonoid M)}⟩ instance inhabited' : inhabited (submodule R M) := ⟨⊥⟩ @[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl @[simp] lemma bot_to_add_submonoid : (⊥ : submodule R M).to_add_submonoid = ⊥ := rfl section variables (R) @[simp] lemma restrict_scalars_bot : restrict_scalars S (⊥ : submodule R M) = ⊥ := rfl @[simp] lemma mem_bot {x : M} : x ∈ (⊥ : submodule R M) ↔ x = 0 := set.mem_singleton_iff end instance unique_bot : unique (⊥ : submodule R M) := ⟨infer_instance, λ x, subtype.ext $ (mem_bot R).1 x.mem⟩ instance : order_bot (submodule R M) := { bot := ⊥, bot_le := λ p x, by simp {contextual := tt}, ..set_like.partial_order } protected lemma eq_bot_iff (p : submodule R M) : p = ⊥ ↔ ∀ x ∈ p, x = (0 : M) := ⟨ λ h, h.symm ▸ λ x hx, (mem_bot R).mp hx, λ h, eq_bot_iff.mpr (λ x hx, (mem_bot R).mpr (h x hx)) ⟩ @[ext] protected lemma bot_ext (x y : (⊥ : submodule R M)) : x = y := begin rcases x with ⟨x, xm⟩, rcases y with ⟨y, ym⟩, congr, rw (submodule.eq_bot_iff _).mp rfl x xm, rw (submodule.eq_bot_iff _).mp rfl y ym, end protected lemma ne_bot_iff (p : submodule R M) : p ≠ ⊥ ↔ ∃ x ∈ p, x ≠ (0 : M) := by { haveI := classical.prop_decidable, simp_rw [ne.def, p.eq_bot_iff, not_forall] } lemma nonzero_mem_of_bot_lt {p : submodule R M} (bot_lt : ⊥ < p) : ∃ a : p, a ≠ 0 := let ⟨b, hb₁, hb₂⟩ := p.ne_bot_iff.mp bot_lt.ne' in ⟨⟨b, hb₁⟩, hb₂ ∘ (congr_arg coe)⟩ lemma exists_mem_ne_zero_of_ne_bot {p : submodule R M} (h : p ≠ ⊥) : ∃ b : M, b ∈ p ∧ b ≠ 0 := let ⟨b, hb₁, hb₂⟩ := p.ne_bot_iff.mp h in ⟨b, hb₁, hb₂⟩ /-- The bottom submodule is linearly equivalent to punit as an `R`-module. -/ @[simps] def bot_equiv_punit : (⊥ : submodule R M) ≃ₗ[R] punit := { to_fun := λ x, punit.star, inv_fun := λ x, 0, map_add' := by { intros, ext, }, map_smul' := by { intros, ext, }, left_inv := by { intro x, ext, }, right_inv := by { intro x, ext, }, } lemma eq_bot_of_subsingleton (p : submodule R M) [subsingleton p] : p = ⊥ := begin rw eq_bot_iff, intros v hv, exact congr_arg coe (subsingleton.elim (⟨v, hv⟩ : p) 0) end /-- The universal set is the top element of the lattice of submodules. -/ instance : has_top (submodule R M) := ⟨{ carrier := set.univ, smul_mem' := λ _ _ _, trivial, .. (⊤ : add_submonoid M)}⟩ @[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = set.univ := rfl @[simp] lemma top_to_add_submonoid : (⊤ : submodule R M).to_add_submonoid = ⊤ := rfl @[simp] lemma mem_top {x : M} : x ∈ (⊤ : submodule R M) := trivial section variables (R) @[simp] lemma restrict_scalars_top : restrict_scalars S (⊤ : submodule R M) = ⊤ := rfl end instance : order_top (submodule R M) := { top := ⊤, le_top := λ p x _, trivial, ..set_like.partial_order } lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p := eq_top_iff.trans ⟨λ h x, h trivial, λ h x _, h x⟩ /-- The top submodule is linearly equivalent to the module. -/ @[simps] def top_equiv_self : (⊤ : submodule R M) ≃ₗ[R] M := { to_fun := λ x, x, inv_fun := λ x, ⟨x, by simp⟩, map_add' := by { intros, refl, }, map_smul' := by { intros, refl, }, left_inv := by { intro x, ext, refl, }, right_inv := by { intro x, refl, }, } instance : has_Inf (submodule R M) := ⟨λ S, { carrier := ⋂ s ∈ S, (s : set M), zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p := set.bInter_subset_of_mem private lemma le_Inf' {S : set (submodule R M)} {p} : (∀q ∈ S, p ≤ q) → p ≤ Inf S := set.subset_bInter instance : has_inf (submodule R M) := ⟨λ p q, { carrier := p ∩ q, zero_mem' := by simp, add_mem' := by simp [add_mem] {contextual := tt}, smul_mem' := by simp [smul_mem] {contextual := tt} }⟩ instance : complete_lattice (submodule R M) := { sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha, le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb, sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩, inf := (⊓), le_inf := λ a b c, set.subset_inter, inf_le_left := λ a b, set.inter_subset_left _ _, inf_le_right := λ a b, set.inter_subset_right _ _, Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t}, le_Sup := λ s p hs, le_Inf' $ λ q hq, hq _ hs, Sup_le := λ s p hs, Inf_le' hs, Inf := Inf, le_Inf := λ s a, le_Inf', Inf_le := λ s a, Inf_le', ..submodule.order_top, ..submodule.order_bot } @[simp] theorem inf_coe : ↑(p ⊓ q) = (p ∩ q : set M) := rfl @[simp] theorem mem_inf {p q : submodule R M} {x : M} : x ∈ p ⊓ q ↔ x ∈ p ∧ x ∈ q := iff.rfl @[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl @[simp] theorem infi_coe {ι} (p : ι → submodule R M) : (↑⨅ i, p i : set M) = ⋂ i, ↑(p i) := by rw [infi, Inf_coe]; ext a; simp; exact ⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩ @[simp] lemma mem_Inf {S : set (submodule R M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[simp] theorem mem_infi {ι} (p : ι → submodule R M) {x} : x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i := by rw [← set_like.mem_coe, infi_coe, set.mem_Inter]; refl lemma mem_sup_left {S T : submodule R M} : ∀ {x : M}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : submodule R M} : ∀ {x : M}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma add_mem_sup {S T : submodule R M} {s t : M} (hs : s ∈ S) (ht : t ∈ T) : s + t ∈ S ⊔ T := add_mem _ (mem_sup_left hs) (mem_sup_right ht) lemma mem_supr_of_mem {ι : Sort*} {b : M} {p : ι → submodule R M} (i : ι) (h : b ∈ p i) : b ∈ (⨆i, p i) := have p i ≤ (⨆i, p i) := le_supr p i, @this b h open_locale big_operators lemma sum_mem_supr {ι : Type*} [fintype ι] {f : ι → M} {p : ι → submodule R M} (h : ∀ i, f i ∈ p i) : ∑ i, f i ∈ ⨆ i, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i (h i) lemma sum_mem_bsupr {ι : Type*} {s : finset ι} {f : ι → M} {p : ι → submodule R M} (h : ∀ i ∈ s, f i ∈ p i) : ∑ i in s, f i ∈ ⨆ i ∈ s, p i := sum_mem _ $ λ i hi, mem_supr_of_mem i $ mem_supr_of_mem hi (h i hi) /-! Note that `submodule.mem_supr` is provided in `linear_algebra/basic.lean`. -/ lemma mem_Sup_of_mem {S : set (submodule R M)} {s : submodule R M} (hs : s ∈ S) : ∀ {x : M}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs end submodule section nat_submodule /-- An additive submonoid is equivalent to a ℕ-submodule. -/ def add_submonoid.to_nat_submodule : add_submonoid M ≃o submodule ℕ M := { to_fun := λ S, { smul_mem' := λ r s hs, S.nsmul_mem hs _, ..S }, inv_fun := submodule.to_add_submonoid, left_inv := λ ⟨S, _, _⟩, rfl, right_inv := λ ⟨S, _, _, _⟩, rfl, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma add_submonoid.to_nat_submodule_symm : ⇑(add_submonoid.to_nat_submodule.symm : _ ≃o add_submonoid M) = submodule.to_add_submonoid := rfl @[simp] lemma add_submonoid.coe_to_nat_submodule (S : add_submonoid M) : (S.to_nat_submodule : set M) = S := rfl @[simp] lemma add_submonoid.to_nat_submodule_to_add_submonoid (S : add_submonoid M) : S.to_nat_submodule.to_add_submonoid = S := add_submonoid.to_nat_submodule.symm_apply_apply S @[simp] lemma submodule.to_add_submonoid_to_nat_submodule (S : submodule ℕ M) : S.to_add_submonoid.to_nat_submodule = S := add_submonoid.to_nat_submodule.apply_symm_apply S end nat_submodule end add_comm_monoid section int_submodule variables [add_comm_group M] /-- An additive subgroup is equivalent to a ℤ-submodule. -/ def add_subgroup.to_int_submodule : add_subgroup M ≃o submodule ℤ M := { to_fun := λ S, { smul_mem' := λ r s hs, S.zsmul_mem hs _, ..S}, inv_fun := submodule.to_add_subgroup, left_inv := λ ⟨S, _, _, _⟩, rfl, right_inv := λ ⟨S, _, _, _⟩, rfl, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma add_subgroup.to_int_submodule_symm : ⇑(add_subgroup.to_int_submodule.symm : _ ≃o add_subgroup M) = submodule.to_add_subgroup := rfl @[simp] lemma add_subgroup.coe_to_int_submodule (S : add_subgroup M) : (S.to_int_submodule : set M) = S := rfl @[simp] lemma add_subgroup.to_int_submodule_to_add_subgroup (S : add_subgroup M) : S.to_int_submodule.to_add_subgroup = S := add_subgroup.to_int_submodule.symm_apply_apply S @[simp] lemma submodule.to_add_subgroup_to_int_submodule (S : submodule ℤ M) : S.to_add_subgroup.to_int_submodule = S := add_subgroup.to_int_submodule.apply_symm_apply S end int_submodule
5a3b673c2641d3c4868fbd5606f7647898881595
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/types/nat/dm_nat.lean
f912c1cef19290c63f24b3527b5ffda00a776bc4
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
5,559
lean
/- Our own implementation of Lean's nat type. We call it dm_nat to avoid any possible name conflicts. We also leave the type's namespace closed. -/ namespace hidden inductive dm_nat : Type | zero : dm_nat | succ (n' : dm_nat) : dm_nat def successor (n : dm_nat) := dm_nat.succ n def pred (n : dm_nat) := match n with | dm_nat.zero := dm_nat.zero | (dm_nat.succ n') := n' end /- It's essential to understand pattern matching, i.e., destructuring, in Lean. The second rule not only matches any argument value that starts with "succ" (or more precisely dm_nat.succ), but it also temporarily binds the identifier, n', to the *rest* of the argument value: to the one-smaller natural number term that comes after the "succ". For example, if the argument is 5, n' will be bound to 4, and that of course is exactly what we want to return as the value of the predecessor of 5. pred (S ( S (S (S (S Z))))) pred (S n' ) -/ def pred2 (n : dm_nat) := match n with | dm_nat.zero := dm_nat.zero | (dm_nat.succ dm_nat.zero) := dm_nat.zero | (dm_nat.succ (dm_nat.succ n')) := n' end #reduce pred2 dm_nat.zero #reduce pred2 (dm_nat.succ dm_nat.zero) #reduce pred2 (dm_nat.succ (dm_nat.succ dm_nat.zero)) /- **** RECURSION **** -/ -- addition as recursively iterated successorr def add : dm_nat → dm_nat → dm_nat | dm_nat.zero m := m | (dm_nat.succ n') m := dm_nat.succ (add n' m) -- by case analysis on *both* arguments def equals : dm_nat → dm_nat → bool | dm_nat.zero dm_nat.zero := tt | dm_nat.zero _ := ff | _ dm_nat.zero := ff | (dm_nat.succ n') (dm_nat.succ m') := equals n' m' #eval equals dm_nat.zero dm_nat.zero #eval equals dm_nat.zero (dm_nat.succ dm_nat.zero) #eval equals (dm_nat.succ dm_nat.zero) dm_nat.zero #eval equals (dm_nat.succ dm_nat.zero) (dm_nat.succ dm_nat.zero) #eval equals (dm_nat.succ dm_nat.zero) (dm_nat.succ (dm_nat.succ dm_nat.zero)) #eval equals (dm_nat.succ (dm_nat.succ dm_nat.zero)) (dm_nat.succ dm_nat.zero) def sub : dm_nat → dm_nat → dm_nat | dm_nat.zero dm_nat.zero := dm_nat.zero | dm_nat.zero _ := dm_nat.zero | n dm_nat.zero := n | (dm_nat.succ n') (dm_nat.succ m') := sub n' m' #reduce sub dm_nat.zero dm_nat.zero #reduce sub dm_nat.zero (dm_nat.succ dm_nat.zero) #reduce sub (dm_nat.succ dm_nat.zero) dm_nat.zero #reduce sub (dm_nat.succ dm_nat.zero) (dm_nat.succ dm_nat.zero) #reduce sub (dm_nat.succ dm_nat.zero) (dm_nat.succ (dm_nat.succ dm_nat.zero)) #reduce sub (dm_nat.succ (dm_nat.succ dm_nat.zero)) (dm_nat.succ dm_nat.zero) def fib : dm_nat → dm_nat | dm_nat.zero := dm_nat.zero | (dm_nat.succ dm_nat.zero) := (dm_nat.succ dm_nat.zero) | (dm_nat.succ (dm_nat.succ n'')) := add (fib n'') (fib (dm_nat.succ n'')) /- fib 0 = 0 fib 1 = 1 fib 2 = 1 fib 3 = 2 fib 4 = 3 fib 5 = 5 fib 6 = 8 -/ #reduce fib (dm_nat.succ (dm_nat.succ dm_nat.zero)) def fac : ℕ → ℕ | 0 := 1 | (nat.succ n') := (nat.succ n') * (fac n') #eval fac 5 -- 3 + 3 /- Let's give the convenient name, three, to the term that we use to represent the natural number three. We then use this shorthand to test add. -/ def three := dm_nat.succ (dm_nat.succ (dm_nat.succ dm_nat.zero) ) #reduce add three three -- 2 + 2 #reduce add (dm_nat.succ (dm_nat.succ dm_nat.zero)) (dm_nat.succ (dm_nat.succ dm_nat.zero)) /- It's also essential to understand how the application of a recursive function to an argument is evaluated. We repeatedly apply the function definition until there are no more applications of the given function left in the resulting term. -/ /- Here, for example, is how "add two two" gets evaluated. Study this! add (dm_nat.succ (dm_nat.succ dm_nat.zero)) (dm_nat.succ (dm_nat.succ dm_nat.zero)) dm_nat.succ (add (dm_nat.succ dm_nat.zero) (dm_nat.succ (dm_nat.succ dm_nat.zero))) dm_nat.succ (dm_nat.succ (add dm_nat.zero (dm_nat.succ (dm_nat.succ dm_nat.zero)))) dm_nat.succ (dm_nat.succ (dm_nat.succ (dm_nat.succ dm_nat.zero))) That's (our representation of) four! Using ordinary numerals add 2 2 succ (add 1 2) succ (succ (add 0 2)) succ (succ (2)) = 4 -/ /- Using shorthands S, Z, and 4 in expression for 3 + 4: add (S (S (S Z))) (S (S (S (S Z)))) add (S (S (S Z))) 4 S (add (S (S Z)) 4) S (S (add (S Z) 4)) S (S (S (add Z 4))) S (S (S (4))) That's 7 -/ -- multiplication is defined as recursive iteration of add def mult : dm_nat → dm_nat → dm_nat | dm_nat.zero m := dm_nat.zero | (dm_nat.succ n') m := add m (mult n' m) #reduce mult three three /- 4 * 3 3 + (3 * 3) 3 + (3 + (2 * 3)) -/ /- mult 3 2 2 + mult 2 2 2 + (2 + mult 1 2) 2 + (2 + (2 + mult 0 2)) 2 + (2 + (2 + 0)) = 6 -/ -- exponentiation is recursive iteration of mult def exp : dm_nat → dm_nat → dm_nat | n dm_nat.zero := dm_nat.succ dm_nat.zero | n (dm_nat.succ m') := mult n (exp n m') #reduce exp three three /- exp 2 3 2 * exp 2 2 2 * (2 * exp 2 1) 2 * (2 * (2 * exp 2 0)) 2 * (2 * (2 * (1))) = 8 -/ -- a funtion to compute sum from 0 to n (here n down to 0) def sum_to : dm_nat → dm_nat | dm_nat.zero := dm_nat.zero | (dm_nat.succ n') := add (dm_nat.succ n') (sum_to n') def fac : dm_nat → dm_nat | dm_nat.zero := dm_nat.succ dm_nat.zero | (dm_nat.succ n') := mult (dm_nat.succ n') (fac n') end hidden /- sum_to 5 5 + sum_to 4 5 + (4 + sum_to 3) 5 + (4 + (3 + sum_to 2)) 5 + (4 + (3 + 2 + sum_to 1)) 5 + (4 + (3 + 2 + (1 + sum_to 0))) 5 + 4 + 3 + 2 + 1 + 0 = 15 -/ -- let's look at Lean's definition of nat #check nat -- it's exactly as we've written it #eval nat.succ nat.zero #eval nat.pred (nat.succ nat.zero)
f80f3ca6b7115c3a93105dfd5735a525df2fdc4d
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/field_theory/splitting_field.lean
81069116411275436ba09c3c9996ff57d7f6dccb
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
7,741
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import ring_theory.adjoin_root ring_theory.unique_factorization_domain universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial noncomputable theory local attribute [instance, priority 0] classical.prop_decidable variables [discrete_field α] [discrete_field β] [discrete_field γ] open polynomial adjoin_root section splits variables (i : α → β) [is_field_hom i] /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _ _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 (is_field_hom.injective i) _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (classical.not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tautology)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_domain.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_map_iff (j : β → γ) [is_field_hom j] {f : polynomial α} : splits j (f.map i) ↔ splits (λ x, j (i x)) f := by simp [splits, polynomial.map_map] lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := is_noetherian_ring.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (by rw [ne.def, map_eq_zero]; exact hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits id (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, is_noetherian_ring.irreducible_induction_on (f.map i) (λ _, ⟨{37}, by simp [is_ring_hom.map_zero i]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero (nonzero_of_irreducible hp) hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 :: s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, domain.mul_right_inj hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit (nonzero_of_irreducible hp), mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 (nonzero_of_irreducible hp)), one_mul], end⟩) section UFD local attribute [instance, priority 0] principal_ideal_domain.to_unique_factorization_domain local infix ` ~ᵤ ` : 50 := associated open unique_factorization_domain associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := unique (λ p hp, irreducible_factors (mt (map_eq_zero i).1 hf0) _ hp) (λ p, by simp [@eq_comm _ _ p, -sub_eq_add_neg, irreducible_of_degree_eq_one (degree_X_sub_C _)] {contextual := tt}) (associated.symm $ calc _ ~ᵤ f.map i : ⟨units.map C (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (mt (map_eq_zero i).1 hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_domain.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits id f → splits i f := unique_factorization_domain.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β → γ) [is_field_hom j] {f : polynomial α} (h : splits i f) : splits (λ x, j (i x)) f := begin change i with (λ x, id (i x)) at h, rw [← splits_map_iff], rw [← splits_map_iff i id] at h, exact splits_of_splits_id _ h end end splits end polynomial
a364a6279da80551008bd7ee2582def6c5a279d1
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Meta/Reduce.lean
fbb390dfdf61fcd0f2ea1283f4267aea3cc1fa99
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,417
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Basic import Lean.Meta.FunInfo import Lean.Util.MonadCache namespace Lean.Meta partial def reduce (e : Expr) (explicitOnly skipTypes skipProofs := true) : MetaM Expr := let rec visit (e : Expr) : MonadCacheT Expr Expr MetaM Expr := checkCache e fun _ => Core.withIncRecDepth do if (← (skipTypes <&&> isType e)) then return e else if (← (skipProofs <&&> isProof e)) then return e else let e ← whnf e match e with | Expr.app .. => let f := e.getAppFn let nargs := e.getAppNumArgs let finfo ← getFunInfoNArgs f nargs let mut args := e.getAppArgs for i in [:args.size] do if i < finfo.paramInfo.size then let info := finfo.paramInfo[i] if !explicitOnly || info.isExplicit then args ← args.modifyM i visit else args ← args.modifyM i visit pure (mkAppN f args) | Expr.lam .. => lambdaTelescope e fun xs b => do mkLambdaFVars xs (← visit b) | Expr.forallE .. => forallTelescope e fun xs b => do mkForallFVars xs (← visit b) | _ => return e visit e |>.run end Lean.Meta
dcfa9e286fe3abd7ad36697217621a0a669ac272
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/AdditiveSemigroup.lean
4b309d74efbab98a21ee5278c45dcf260c9fd319
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
6,402
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section AdditiveSemigroup structure AdditiveSemigroup (A : Type) : Type := (plus : (A → (A → A))) (associative_plus : (∀ {x y z : A} , (plus (plus x y) z) = (plus x (plus y z)))) open AdditiveSemigroup structure Sig (AS : Type) : Type := (plusS : (AS → (AS → AS))) structure Product (A : Type) : Type := (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (associative_plusP : (∀ {xP yP zP : (Prod A A)} , (plusP (plusP xP yP) zP) = (plusP xP (plusP yP zP)))) structure Hom {A1 : Type} {A2 : Type} (Ad1 : (AdditiveSemigroup A1)) (Ad2 : (AdditiveSemigroup A2)) : Type := (hom : (A1 → A2)) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus Ad1) x1 x2)) = ((plus Ad2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (Ad1 : (AdditiveSemigroup A1)) (Ad2 : (AdditiveSemigroup A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus Ad1) x1 x2) ((plus Ad2) y1 y2)))))) inductive AdditiveSemigroupTerm : Type | plusL : (AdditiveSemigroupTerm → (AdditiveSemigroupTerm → AdditiveSemigroupTerm)) open AdditiveSemigroupTerm inductive ClAdditiveSemigroupTerm (A : Type) : Type | sing : (A → ClAdditiveSemigroupTerm) | plusCl : (ClAdditiveSemigroupTerm → (ClAdditiveSemigroupTerm → ClAdditiveSemigroupTerm)) open ClAdditiveSemigroupTerm inductive OpAdditiveSemigroupTerm (n : ℕ) : Type | v : ((fin n) → OpAdditiveSemigroupTerm) | plusOL : (OpAdditiveSemigroupTerm → (OpAdditiveSemigroupTerm → OpAdditiveSemigroupTerm)) open OpAdditiveSemigroupTerm inductive OpAdditiveSemigroupTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpAdditiveSemigroupTerm2) | sing2 : (A → OpAdditiveSemigroupTerm2) | plusOL2 : (OpAdditiveSemigroupTerm2 → (OpAdditiveSemigroupTerm2 → OpAdditiveSemigroupTerm2)) open OpAdditiveSemigroupTerm2 def simplifyCl {A : Type} : ((ClAdditiveSemigroupTerm A) → (ClAdditiveSemigroupTerm A)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpAdditiveSemigroupTerm n) → (OpAdditiveSemigroupTerm n)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpAdditiveSemigroupTerm2 n A) → (OpAdditiveSemigroupTerm2 n A)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((AdditiveSemigroup A) → (AdditiveSemigroupTerm → A)) | Ad (plusL x1 x2) := ((plus Ad) (evalB Ad x1) (evalB Ad x2)) def evalCl {A : Type} : ((AdditiveSemigroup A) → ((ClAdditiveSemigroupTerm A) → A)) | Ad (sing x1) := x1 | Ad (plusCl x1 x2) := ((plus Ad) (evalCl Ad x1) (evalCl Ad x2)) def evalOpB {A : Type} {n : ℕ} : ((AdditiveSemigroup A) → ((vector A n) → ((OpAdditiveSemigroupTerm n) → A))) | Ad vars (v x1) := (nth vars x1) | Ad vars (plusOL x1 x2) := ((plus Ad) (evalOpB Ad vars x1) (evalOpB Ad vars x2)) def evalOp {A : Type} {n : ℕ} : ((AdditiveSemigroup A) → ((vector A n) → ((OpAdditiveSemigroupTerm2 n A) → A))) | Ad vars (v2 x1) := (nth vars x1) | Ad vars (sing2 x1) := x1 | Ad vars (plusOL2 x1 x2) := ((plus Ad) (evalOp Ad vars x1) (evalOp Ad vars x2)) def inductionB {P : (AdditiveSemigroupTerm → Type)} : ((∀ (x1 x2 : AdditiveSemigroupTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : AdditiveSemigroupTerm) , (P x))) | pplusl (plusL x1 x2) := (pplusl _ _ (inductionB pplusl x1) (inductionB pplusl x2)) def inductionCl {A : Type} {P : ((ClAdditiveSemigroupTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClAdditiveSemigroupTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClAdditiveSemigroupTerm A)) , (P x)))) | psing ppluscl (sing x1) := (psing x1) | psing ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ppluscl x1) (inductionCl psing ppluscl x2)) def inductionOpB {n : ℕ} {P : ((OpAdditiveSemigroupTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpAdditiveSemigroupTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpAdditiveSemigroupTerm n)) , (P x)))) | pv pplusol (v x1) := (pv x1) | pv pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv pplusol x1) (inductionOpB pv pplusol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpAdditiveSemigroupTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpAdditiveSemigroupTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpAdditiveSemigroupTerm2 n A)) , (P x))))) | pv2 psing2 pplusol2 (v2 x1) := (pv2 x1) | pv2 psing2 pplusol2 (sing2 x1) := (psing2 x1) | pv2 psing2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 pplusol2 x1) (inductionOp pv2 psing2 pplusol2 x2)) def stageB : (AdditiveSemigroupTerm → (Staged AdditiveSemigroupTerm)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClAdditiveSemigroupTerm A) → (Staged (ClAdditiveSemigroupTerm A))) | (sing x1) := (Now (sing x1)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpAdditiveSemigroupTerm n) → (Staged (OpAdditiveSemigroupTerm n))) | (v x1) := (const (code (v x1))) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpAdditiveSemigroupTerm2 n A) → (Staged (OpAdditiveSemigroupTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (plusT : ((Repr A) → ((Repr A) → (Repr A)))) end AdditiveSemigroup
b26dc7d438bdb3148f16783813db35bef16630da
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/meta5.lean
0bd47839593def86ca862141dc2a81f84a91f889
[ "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
641
lean
import Lean.Meta open Lean open Lean.Meta def tst1 : MetaM Unit := withLocalDeclD `y (mkConst `Nat) $ fun y => do withLetDecl `x (mkConst `Nat) (mkNatLit 0) $ fun x => do { let mvar ← mkFreshExprMVar (mkConst `Nat) MetavarKind.syntheticOpaque; trace[Meta.debug]! mvar; let r ← mkLambdaFVars #[y, x] mvar; trace[Message.debug]! r; let v := mkApp2 (mkConst `Nat.add) x y; assignExprMVar mvar.mvarId! v; trace[Meta.debug]! mvar; trace[Meta.debug]! r; let mctx ← getMCtx; mctx.decls.forM fun mvarId mvarDecl => do trace[Meta.debug]! m!"?{mvarId} : {mvarDecl.type}" } set_option trace.Meta.debug true #eval tst1
e9cd77bb4567d5dbb7b34c0c05e80fca357a5f54
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/sym/sym2.lean
46cf48127ba215e7806309856d9bd3b2961ef0ae
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,217
lean
/- Copyright (c) 2020 Kyle Miller All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.sym.basic import tactic.linarith /-! # The symmetric square This file defines the symmetric square, which is `α × α` modulo swapping. This is also known as the type of unordered pairs. More generally, the symmetric square is the second symmetric power (see `data.sym.basic`). The equivalence is `sym2.equiv_sym`. From the point of view that an unordered pair is equivalent to a multiset of cardinality two (see `sym2.equiv_multiset`), there is a `has_mem` instance `sym2.mem`, which is a `Prop`-valued membership test. Given `h : a ∈ z` for `z : sym2 α`, then `h.other` is the other element of the pair, defined using `classical.choice`. If `α` has decidable equality, then `h.other'` computably gives the other element. The universal property of `sym2` is provided as `sym2.lift`, which states that functions from `sym2 α` are equivalent to symmetric two-argument functions from `α`. Recall that an undirected graph (allowing self loops, but no multiple edges) is equivalent to a symmetric relation on the vertex type `α`. Given a symmetric relation on `α`, the corresponding edge set is constructed by `sym2.from_rel` which is a special case of `sym2.lift`. ## Notation The symmetric square has a setoid instance, so `⟦(a, b)⟧` denotes a term of the symmetric square. ## Tags symmetric square, unordered pairs, symmetric powers -/ open finset fintype function sym universe u variables {α : Type u} namespace sym2 /-- This is the relation capturing the notion of pairs equivalent up to permutations. -/ inductive rel (α : Type u) : (α × α) → (α × α) → Prop | refl (x y : α) : rel (x, y) (x, y) | swap (x y : α) : rel (x, y) (y, x) attribute [refl] rel.refl @[symm] lemma rel.symm {x y : α × α} : rel α x y → rel α y x := by rintro ⟨_, _⟩; constructor @[trans] lemma rel.trans {x y z : α × α} : rel α x y → rel α y z → rel α x z := by { intros a b, cases_matching* rel _ _ _; apply rel.refl <|> apply rel.swap } lemma rel.is_equivalence : equivalence (rel α) := by tidy; apply rel.trans; assumption instance rel.setoid (α : Type u) : setoid (α × α) := ⟨rel α, rel.is_equivalence⟩ end sym2 /-- `sym2 α` is the symmetric square of `α`, which, in other words, is the type of unordered pairs. It is equivalent in a natural way to multisets of cardinality 2 (see `sym2.equiv_multiset`). -/ @[reducible] def sym2 (α : Type u) := quotient (sym2.rel.setoid α) namespace sym2 lemma eq_swap {a b : α} : ⟦(a, b)⟧ = ⟦(b, a)⟧ := by { rw quotient.eq, apply rel.swap } lemma congr_right {a b c : α} : ⟦(a, b)⟧ = ⟦(a, c)⟧ ↔ b = c := by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h } lemma congr_left {a b c : α} : ⟦(b, a)⟧ = ⟦(c, a)⟧ ↔ b = c := by { split; intro h, { rw quotient.eq at h, cases h; refl }, rw h } lemma eq_iff {x y z w : α} : ⟦(x, y)⟧ = ⟦(z, w)⟧ ↔ (x = z ∧ y = w) ∨ (x = w ∧ y = z) := begin split; intro h, { rw quotient.eq at h, cases h; tidy }, { cases h; rw [h.1, h.2], rw eq_swap } end /-- The universal property of `sym2`; symmetric functions of two arguments are equivalent to functions from `sym2`. Note that when `β` is `Prop`, it can sometimes be more convenient to use `sym2.from_rel` instead. -/ def lift {β : Type*} : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁} ≃ (sym2 α → β) := { to_fun := λ f, quotient.lift (uncurry ↑f) $ by { rintro _ _ ⟨⟩, exacts [rfl, f.prop _ _] }, inv_fun := λ F, ⟨curry (F ∘ quotient.mk), λ a₁ a₂, congr_arg F eq_swap⟩, left_inv := λ f, subtype.ext rfl, right_inv := λ F, funext $ quotient.ind $ prod.rec $ by exact λ _ _, rfl } @[simp] lemma lift_mk {β : Type*} (f : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁}) (a₁ a₂ : α) : lift f ⟦(a₁, a₂)⟧ = (f : α → α → β) a₁ a₂ := rfl @[simp] lemma coe_lift_symm_apply {β : Type*} (F : sym2 α → β) (a₁ a₂ : α) : (lift.symm F : α → α → β) a₁ a₂ = F ⟦(a₁, a₂)⟧ := rfl /-- The functor `sym2` is functorial, and this function constructs the induced maps. -/ def map {α β : Type*} (f : α → β) : sym2 α → sym2 β := quotient.map (prod.map f f) (by { rintros _ _ h, cases h, { refl }, apply rel.swap }) @[simp] lemma map_id : sym2.map (@id α) = id := by tidy lemma map_comp {α β γ : Type*} {g : β → γ} {f : α → β} : sym2.map (g ∘ f) = sym2.map g ∘ sym2.map f := by tidy lemma map_map {α β γ : Type*} {g : β → γ} {f : α → β} (x : sym2 α) : map g (map f x) = map (g ∘ f) x := by tidy @[simp] lemma map_pair_eq {α β : Type*} (f : α → β) (x y : α) : map f ⟦(x, y)⟧ = ⟦(f x, f y)⟧ := rfl lemma map.injective {α β : Type*} {f : α → β} (hinj : injective f) : injective (map f) := begin intros z z', refine quotient.ind₂ (λ z z', _) z z', cases z with x y, cases z' with x' y', repeat { rw [map_pair_eq, eq_iff] }, rintro (h|h); simp [hinj h.1, hinj h.2], end section membership /-! ### Declarations about membership -/ /-- This is a predicate that determines whether a given term is a member of a term of the symmetric square. From this point of view, the symmetric square is the subtype of cardinality-two multisets on `α`. -/ def mem (x : α) (z : sym2 α) : Prop := ∃ (y : α), z = ⟦(x, y)⟧ instance : has_mem α (sym2 α) := ⟨mem⟩ lemma mk_has_mem (x y : α) : x ∈ ⟦(x, y)⟧ := ⟨y, rfl⟩ lemma mk_has_mem_right (x y : α) : y ∈ ⟦(x, y)⟧ := by { rw eq_swap, apply mk_has_mem } /-- Given an element of the unordered pair, give the other element using `classical.some`. See also `mem.other'` for the computable version. -/ noncomputable def mem.other {a : α} {z : sym2 α} (h : a ∈ z) : α := classical.some h @[simp] lemma mem_other_spec {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other)⟧ = z := by erw ← classical.some_spec h @[simp] lemma mem_iff {a b c : α} : a ∈ ⟦(b, c)⟧ ↔ a = b ∨ a = c := { mp := by { rintro ⟨_, h⟩, rw eq_iff at h, tidy }, mpr := by { rintro ⟨_⟩; subst a, { apply mk_has_mem }, apply mk_has_mem_right } } lemma mem_other_mem {a : α} {z : sym2 α} (h : a ∈ z) : h.other ∈ z := by { convert mk_has_mem_right a h.other, rw mem_other_spec h } lemma elems_iff_eq {x y : α} {z : sym2 α} (hne : x ≠ y) : x ∈ z ∧ y ∈ z ↔ z = ⟦(x, y)⟧ := begin split, { refine quotient.rec_on_subsingleton z _, rintros ⟨z₁, z₂⟩ ⟨hx, hy⟩, rw eq_iff, cases mem_iff.mp hx with hx hx; cases mem_iff.mp hy with hy hy; subst x; subst y; try { exact (hne rfl).elim }; simp only [true_or, eq_self_iff_true, and_self, or_true] }, { rintro rfl, simp }, end @[ext] lemma sym2_ext (z z' : sym2 α) (h : ∀ x, x ∈ z ↔ x ∈ z') : z = z' := begin refine quotient.rec_on_subsingleton z (λ w, _) h, refine quotient.rec_on_subsingleton z' (λ w', _), intro h, cases w with x y, cases w' with x' y', simp only [mem_iff] at h, apply eq_iff.mpr, have hx := h x, have hy := h y, have hx' := h x', have hy' := h y', simp only [true_iff, true_or, eq_self_iff_true, iff_true, or_true] at hx hy hx' hy', cases hx; subst x; cases hy; subst y; cases hx'; try { subst x' }; cases hy'; try { subst y' }; simp only [eq_self_iff_true, and_self, or_self, true_or, or_true], end instance mem.decidable [decidable_eq α] (x : α) (z : sym2 α) : decidable (x ∈ z) := quotient.rec_on_subsingleton z (λ ⟨y₁, y₂⟩, decidable_of_iff' _ mem_iff) end membership /-- A type `α` is naturally included in the diagonal of `α × α`, and this function gives the image of this diagonal in `sym2 α`. -/ def diag (x : α) : sym2 α := ⟦(x, x)⟧ lemma diag_injective : function.injective (sym2.diag : α → sym2 α) := λ x y h, by cases quotient.exact h; refl /-- A predicate for testing whether an element of `sym2 α` is on the diagonal. -/ def is_diag : sym2 α → Prop := lift ⟨eq, λ _ _, propext eq_comm⟩ lemma is_diag_iff_eq {x y : α} : is_diag ⟦(x, y)⟧ ↔ x = y := iff.rfl @[simp] lemma is_diag_iff_proj_eq (z : α × α) : is_diag ⟦z⟧ ↔ z.1 = z.2 := prod.rec_on z $ λ _ _, is_diag_iff_eq @[simp] lemma diag_is_diag (a : α) : is_diag (diag a) := eq.refl a lemma is_diag.mem_range_diag {z : sym2 α} : is_diag z → z ∈ set.range (@diag α) := begin induction z using quotient.induction_on, cases z, rintro (rfl : z_fst = z_snd), exact ⟨z_fst, rfl⟩, end lemma is_diag_iff_mem_range_diag (z : sym2 α) : is_diag z ↔ z ∈ set.range (@diag α) := ⟨is_diag.mem_range_diag, λ ⟨i, hi⟩, hi ▸ diag_is_diag i⟩ instance is_diag.decidable_pred (α : Type u) [decidable_eq α] : decidable_pred (@is_diag α) := by { refine λ z, quotient.rec_on_subsingleton z (λ a, _), erw is_diag_iff_proj_eq, apply_instance } lemma mem_other_ne {a : α} {z : sym2 α} (hd : ¬is_diag z) (h : a ∈ z) : h.other ≠ a := begin intro hn, apply hd, have h' := sym2.mem_other_spec h, rw hn at h', rw ←h', simp, end section relations /-! ### Declarations about symmetric relations -/ variables {r : α → α → Prop} /-- Symmetric relations define a set on `sym2 α` by taking all those pairs of elements that are related. -/ def from_rel (sym : symmetric r) : set (sym2 α) := set_of (lift ⟨r, λ x y, propext ⟨λ h, sym h, λ h, sym h⟩⟩) @[simp] lemma from_rel_proj_prop {sym : symmetric r} {z : α × α} : ⟦z⟧ ∈ from_rel sym ↔ r z.1 z.2 := iff.rfl @[simp] lemma from_rel_prop {sym : symmetric r} {a b : α} : ⟦(a, b)⟧ ∈ from_rel sym ↔ r a b := iff.rfl lemma from_rel_irreflexive {sym : symmetric r} : irreflexive r ↔ ∀ {z}, z ∈ from_rel sym → ¬is_diag z := { mp := λ h, quotient.ind $ prod.rec $ by { rintros a b hr (rfl : a = b), exact h _ hr }, mpr := λ h x hr, h (from_rel_prop.mpr hr) rfl } lemma mem_from_rel_irrefl_other_ne {sym : symmetric r} (irrefl : irreflexive r) {a : α} {z : sym2 α} (hz : z ∈ from_rel sym) (h : a ∈ z) : h.other ≠ a := mem_other_ne (from_rel_irreflexive.mp irrefl hz) h instance from_rel.decidable_pred (sym : symmetric r) [h : decidable_rel r] : decidable_pred (∈ sym2.from_rel sym) := λ z, quotient.rec_on_subsingleton z (λ x, h _ _) end relations section sym_equiv /-! ### Equivalence to the second symmetric power -/ local attribute [instance] vector.perm.is_setoid private def from_vector {α : Type*} : vector α 2 → α × α | ⟨[a, b], h⟩ := (a, b) private lemma perm_card_two_iff {α : Type*} {a₁ b₁ a₂ b₂ : α} : [a₁, b₁].perm [a₂, b₂] ↔ (a₁ = a₂ ∧ b₁ = b₂) ∨ (a₁ = b₂ ∧ b₁ = a₂) := { mp := by { simp [← multiset.coe_eq_coe, ← multiset.cons_coe, multiset.cons_eq_cons]; tidy }, mpr := by { intro h, cases h; rw [h.1, h.2], apply list.perm.swap', refl } } /-- The symmetric square is equivalent to length-2 vectors up to permutations. -/ def sym2_equiv_sym' {α : Type*} : equiv (sym2 α) (sym' α 2) := { to_fun := quotient.map (λ (x : α × α), ⟨[x.1, x.2], rfl⟩) (by { rintros _ _ ⟨_⟩, { refl }, apply list.perm.swap', refl }), inv_fun := quotient.map from_vector (begin rintros ⟨x, hx⟩ ⟨y, hy⟩ h, cases x with _ x, { simpa using hx, }, cases x with _ x, { simpa using hx, }, cases x with _ x, swap, { exfalso, simp at hx, linarith [hx] }, cases y with _ y, { simpa using hy, }, cases y with _ y, { simpa using hy, }, cases y with _ y, swap, { exfalso, simp at hy, linarith [hy] }, rcases perm_card_two_iff.mp h with ⟨rfl,rfl⟩|⟨rfl,rfl⟩, { refl }, apply sym2.rel.swap, end), left_inv := by tidy, right_inv := λ x, begin refine quotient.rec_on_subsingleton x (λ x, _), { cases x with x hx, cases x with _ x, { simpa using hx, }, cases x with _ x, { simpa using hx, }, cases x with _ x, swap, { exfalso, simp at hx, linarith [hx] }, refl }, end } /-- The symmetric square is equivalent to the second symmetric power. -/ def equiv_sym (α : Type*) : sym2 α ≃ sym α 2 := equiv.trans sym2_equiv_sym' sym_equiv_sym'.symm /-- The symmetric square is equivalent to multisets of cardinality two. (This is currently a synonym for `equiv_sym`, but it's provided in case the definition for `sym` changes.) -/ def equiv_multiset (α : Type*) : sym2 α ≃ {s : multiset α // s.card = 2} := equiv_sym α end sym_equiv section decidable /-- An algorithm for computing `sym2.rel`. -/ def rel_bool [decidable_eq α] (x y : α × α) : bool := if x.1 = y.1 then x.2 = y.2 else if x.1 = y.2 then x.2 = y.1 else ff lemma rel_bool_spec [decidable_eq α] (x y : α × α) : ↥(rel_bool x y) ↔ rel α x y := begin cases x with x₁ x₂, cases y with y₁ y₂, dsimp [rel_bool], split_ifs; simp only [false_iff, bool.coe_sort_ff, bool.of_to_bool_iff], rotate 2, { contrapose! h, cases h; cc }, all_goals { subst x₁, split; intro h1, { subst h1; apply sym2.rel.swap }, { cases h1; cc } } end /-- Given `[decidable_eq α]` and `[fintype α]`, the following instance gives `fintype (sym2 α)`. -/ instance (α : Type*) [decidable_eq α] : decidable_rel (sym2.rel α) := λ x y, decidable_of_bool (rel_bool x y) (rel_bool_spec x y) /-- A function that gives the other element of a pair given one of the elements. Used in `mem.other'`. -/ private def pair_other [decidable_eq α] (a : α) (z : α × α) : α := if a = z.1 then z.2 else z.1 /-- Get the other element of the unordered pair using the decidable equality. This is the computable version of `mem.other`. -/ def mem.other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : α := quot.rec (λ x h', pair_other a x) (begin clear h z, intros x y h, ext hy, convert_to pair_other a x = _, { have h' : ∀ {c e h}, @eq.rec _ ⟦x⟧ (λ s, a ∈ s → α) (λ _, pair_other a x) c e h = pair_other a x, { intros _ e _, subst e }, apply h', }, have h' := (rel_bool_spec x y).mpr h, cases x with x₁ x₂, cases y with y₁ y₂, cases mem_iff.mp hy with hy'; subst a; dsimp [rel_bool] at h'; split_ifs at h'; try { rw bool.of_to_bool_iff at h', subst x₁, subst x₂ }; dsimp [pair_other], simp only [ne.symm h_1, if_true, eq_self_iff_true, if_false], exfalso, exact bool.not_ff h', simp only [h_1, if_true, eq_self_iff_true, if_false], exfalso, exact bool.not_ff h', end) z h @[simp] lemma mem_other_spec' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : ⟦(a, h.other')⟧ = z := begin induction z, cases z with x y, have h' := mem_iff.mp h, dsimp [mem.other', quot.rec, pair_other], cases h'; subst a, { simp only [if_true, eq_self_iff_true], refl, }, { split_ifs, subst h_1, refl, rw eq_swap, refl, }, refl, end @[simp] lemma other_eq_other' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other = h.other' := by rw [←congr_right, mem_other_spec' h, mem_other_spec] lemma mem_other_mem' [decidable_eq α] {a : α} {z : sym2 α} (h : a ∈ z) : h.other' ∈ z := by { rw ←other_eq_other', exact mem_other_mem h } lemma other_invol' [decidable_eq α] {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other' ∈ z): hb.other' = a := begin induction z, cases z with x y, dsimp [mem.other', quot.rec, pair_other] at hb, split_ifs at hb; dsimp [mem.other', quot.rec, pair_other], simp only [h, if_true, eq_self_iff_true], split_ifs, assumption, refl, simp only [h, if_false, if_true, eq_self_iff_true], exact ((mem_iff.mp ha).resolve_left h).symm, refl, end lemma other_invol {a : α} {z : sym2 α} (ha : a ∈ z) (hb : ha.other ∈ z): hb.other = a := begin classical, rw other_eq_other' at hb ⊢, convert other_invol' ha hb, rw other_eq_other', end lemma filter_image_quotient_mk_is_diag [decidable_eq α] (s : finset α) : ((s.product s).image quotient.mk).filter is_diag = s.diag.image quotient.mk := begin ext z, induction z using quotient.induction_on, rcases z with ⟨x, y⟩, simp only [mem_image, mem_diag, exists_prop, mem_filter, prod.exists, mem_product], split, { rintro ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩, rw [←h, sym2.is_diag_iff_eq] at hab, exact ⟨a, b, ⟨ha, hab⟩, h⟩ }, { rintro ⟨a, b, ⟨ha, rfl⟩, h⟩, rw ←h, exact ⟨⟨a, a, ⟨ha, ha⟩, rfl⟩, rfl⟩ } end lemma filter_image_quotient_mk_not_is_diag [decidable_eq α] (s : finset α) : ((s.product s).image quotient.mk).filter (λ a : sym2 α, ¬a.is_diag) = s.off_diag.image quotient.mk := begin ext z, induction z using quotient.induction_on, rcases z with ⟨x, y⟩, simp only [mem_image, mem_off_diag, exists_prop, mem_filter, prod.exists, mem_product], split, { rintro ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩, rw [←h, sym2.is_diag_iff_eq] at hab, exact ⟨a, b, ⟨ha, hb, hab⟩, h⟩ }, { rintro ⟨a, b, ⟨ha, hb, hab⟩, h⟩, rw [ne.def, ←sym2.is_diag_iff_eq, h] at hab, exact ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩ } end end decidable end sym2
9d8418566d5a14e350b4324291b3052f8790ded9
6e36ebd5594a0d512dea8bc6ffe78c71b5b5032d
/src/mywork/Lectures/lecture_5.lean
42f2b214018e7215e17c7f040bfec0bac4ea5662
[]
no_license
wrw2ztk/cs2120f21
cdc4b1b4043c8ae8f3c8c3c0e91cdacb2cfddb16
f55df4c723d3ce989908679f5653e4be669334ae
refs/heads/main
1,691,764,473,342
1,633,707,809,000
1,633,707,809,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,725
lean
/- INTRODUCTION and ELIMINATION RULES -/ /- For ∀ x, P x (every x has property P) - introduction rule: assume arbitrary x, then show P x - elimination rule: *apply* a proof of ∀ x, P x, as a kind of function to a specific value of x, say k, to produce a proof of P k. -/ theorem silly : ∀ (n : ℕ), true := begin assume (n : ℕ), exact true.intro, end /- The proposition true is unconditionally true, as proven by an always available proof called (in Lean) true.intro. -/ #check silly 7 /- The check command will tell you the type of any expression (aka term) in Lean. Here we can see that silly is like a function, and that when we apply it to the specific argument, 7, we get back a proof of the resulting proposition (which is just, "true"). We'll soon be equipped to deal with more interesting "return types". -/ /- For P → Q (if P is true then Q must also be true) - introduction rule: assume arbitrary P, then show Q - elimination rule: *apply* a proof of P → Q, as a kind of function, to any proof of P to derive a proof of Q! -/ lemma foo : ∀ (x : ℕ), x = 0 → x + 1 = 1 := begin assume x h, rw h, end /- Wow! ∀ and → sure do seem similar. Indeed they're the same! They define function types. We construct a proof of ∀ or → by assuming the premise and showing that in that context we can derive a result of the conclusion type. We can then use a proof of a ∀ or → by treating it as a function that can be applied to a specific value to derive a proof *for that specific value. Indeed, in Lean, → is really just another notation for forall! -/ example: 0 = 0 ∧ 1 = 1 := begin apply and.intro _ _, apply eq.refl 0, apply eq.refl 1, end def
0b38722a117036654b544537fffa47e5b5cf7813
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/power_series/well_known.lean
4d6decaf50f78bc8b046334191b73c1d928fc256
[ "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
5,638
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import ring_theory.power_series.basic import data.nat.parity import algebra.big_operators.nat_antidiagonal /-! # Definition of well-known power series In this file we define the following power series: * `power_series.inv_units_sub`: given `u : Rˣ`, this is the series for `1 / (u - x)`. It is given by `∑ n, x ^ n /ₚ u ^ (n + 1)`. * `power_series.sin`, `power_series.cos`, `power_series.exp` : power series for sin, cosine, and exponential functions. -/ namespace power_series section ring variables {R S : Type*} [ring R] [ring S] /-- The power series for `1 / (u - x)`. -/ def inv_units_sub (u : Rˣ) : power_series R := mk $ λ n, 1 /ₚ u ^ (n + 1) @[simp] lemma coeff_inv_units_sub (u : Rˣ) (n : ℕ) : coeff R n (inv_units_sub u) = 1 /ₚ u ^ (n + 1) := coeff_mk _ _ @[simp] lemma constant_coeff_inv_units_sub (u : Rˣ) : constant_coeff R (inv_units_sub u) = 1 /ₚ u := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_units_sub, zero_add, pow_one] @[simp] lemma inv_units_sub_mul_X (u : Rˣ) : inv_units_sub u * X = inv_units_sub u * C R u - 1 := begin ext (_|n), { simp }, { simp [n.succ_ne_zero, pow_succ] } end @[simp] lemma inv_units_sub_mul_sub (u : Rˣ) : inv_units_sub u * (C R u - X) = 1 := by simp [mul_sub, sub_sub_cancel] lemma map_inv_units_sub (f : R →+* S) (u : Rˣ) : map f (inv_units_sub u) = inv_units_sub (units.map (f : R →* S) u) := by { ext, simp [← map_pow] } end ring section field variables (A A' : Type*) [ring A] [ring A'] [algebra ℚ A] [algebra ℚ A'] open_locale nat /-- Power series for the exponential function at zero. -/ def exp : power_series A := mk $ λ n, algebra_map ℚ A (1 / n!) /-- Power series for the sine function at zero. -/ def sin : power_series A := mk $ λ n, if even n then 0 else algebra_map ℚ A ((-1) ^ (n / 2) / n!) /-- Power series for the cosine function at zero. -/ def cos : power_series A := mk $ λ n, if even n then algebra_map ℚ A ((-1) ^ (n / 2) / n!) else 0 variables {A A'} (n : ℕ) (f : A →+* A') @[simp] lemma coeff_exp : coeff A n (exp A) = algebra_map ℚ A (1 / n!) := coeff_mk _ _ @[simp] lemma constant_coeff_exp : constant_coeff A (exp A) = 1 := by { rw [← coeff_zero_eq_constant_coeff_apply, coeff_exp], simp } @[simp] lemma coeff_sin_bit0 : coeff A (bit0 n) (sin A) = 0 := by rw [sin, coeff_mk, if_pos (even_bit0 n)] @[simp] lemma coeff_sin_bit1 : coeff A (bit1 n) (sin A) = (-1) ^ n * coeff A (bit1 n) (exp A) := by rw [sin, coeff_mk, if_neg n.not_even_bit1, nat.bit1_div_two, ←mul_one_div, map_mul, map_pow, map_neg, map_one, coeff_exp] @[simp] lemma coeff_cos_bit0 : coeff A (bit0 n) (cos A) = (-1) ^ n * coeff A (bit0 n) (exp A) := by rw [cos, coeff_mk, if_pos (even_bit0 n), nat.bit0_div_two, ←mul_one_div, map_mul, map_pow, map_neg, map_one, coeff_exp] @[simp] lemma coeff_cos_bit1 : coeff A (bit1 n) (cos A) = 0 := by rw [cos, coeff_mk, if_neg n.not_even_bit1] @[simp] lemma map_exp : map (f : A →+* A') (exp A) = exp A' := by { ext, simp } @[simp] lemma map_sin : map f (sin A) = sin A' := by { ext, simp [sin, apply_ite f] } @[simp] lemma map_cos : map f (cos A) = cos A' := by { ext, simp [cos, apply_ite f] } end field open ring_hom open finset nat variables {A : Type*} [comm_ring A] /-- Shows that $e^{aX} * e^{bX} = e^{(a + b)X}$ -/ theorem exp_mul_exp_eq_exp_add [algebra ℚ A] (a b : A) : rescale a (exp A) * rescale b (exp A) = rescale (a + b) (exp A) := begin ext, simp only [coeff_mul, exp, rescale, coeff_mk, coe_mk, factorial, nat.sum_antidiagonal_eq_sum_range_succ_mk, add_pow, sum_mul], apply sum_congr rfl, rintros x hx, suffices : a^x * b^(n - x) * (algebra_map ℚ A (1 / ↑(x.factorial)) * algebra_map ℚ A (1 / ↑((n - x).factorial))) = a^x * b^(n - x) * ((↑(n.choose x) * (algebra_map ℚ A) (1 / ↑(n.factorial)))), { convert this using 1; ring }, congr' 1, rw [←map_nat_cast (algebra_map ℚ A) (n.choose x), ←map_mul, ←map_mul], refine ring_hom.congr_arg _ _, rw [mul_one_div ↑(n.choose x) _, one_div_mul_one_div], symmetry, rw [div_eq_iff, div_mul_eq_mul_div, one_mul, choose_eq_factorial_div_factorial], norm_cast, rw cast_div_char_zero, { apply factorial_mul_factorial_dvd_factorial (mem_range_succ_iff.1 hx), }, { apply mem_range_succ_iff.1 hx, }, { rintros h, apply factorial_ne_zero n, rw cast_eq_zero.1 h, }, end /-- Shows that $e^{x} * e^{-x} = 1$ -/ theorem exp_mul_exp_neg_eq_one [algebra ℚ A] : exp A * eval_neg_hom (exp A) = 1 := by convert exp_mul_exp_eq_exp_add (1 : A) (-1); simp /-- Shows that $(e^{X})^k = e^{kX}$. -/ theorem exp_pow_eq_rescale_exp [algebra ℚ A] (k : ℕ) : (exp A)^k = rescale (k : A) (exp A) := begin induction k with k h, { simp only [rescale_zero, constant_coeff_exp, function.comp_app, map_one, cast_zero, pow_zero, coe_comp], }, simpa only [succ_eq_add_one, cast_add, ←exp_mul_exp_eq_exp_add (k : A), ←h, cast_one, id_apply, rescale_one] using pow_succ' (exp A) k, end /-- Shows that $\sum_{k = 0}^{n - 1} (e^{X})^k = \sum_{p = 0}^{\infty} \sum_{k = 0}^{n - 1} \frac{k^p}{p!}X^p$. -/ theorem exp_pow_sum [algebra ℚ A] (n : ℕ) : (finset.range n).sum (λ k, (exp A)^k) = power_series.mk (λ p, (finset.range n).sum (λ k, k^p * algebra_map ℚ A p.factorial⁻¹)) := begin simp only [exp_pow_eq_rescale_exp, rescale], ext, simp only [one_div, coeff_mk, coe_mk, coeff_exp, factorial, linear_map.map_sum], end end power_series
39c21a7da0524e765800f792b8517f6c99ca5ceb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/orientation.lean
107bd5f34b839ab4a98d482d6997dd4de642c4ed
[ "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,865
lean
/- Copyright (c) 2021 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.ray import linear_algebra.determinant /-! # Orientations of modules > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines orientations of modules. ## Main definitions * `orientation` is a type synonym for `module.ray` for the case where the module is that of alternating maps from a module to its underlying ring. An orientation may be associated with an alternating map or with a basis. * `module.oriented` is a type class for a choice of orientation of a module that is considered the positive orientation. ## Implementation notes `orientation` is defined for an arbitrary index type, but the main intended use case is when that index type is a `fintype` and there exists a basis of the same cardinality. ## References * https://en.wikipedia.org/wiki/Orientation_(vector_space) -/ noncomputable theory open_locale big_operators section ordered_comm_semiring variables (R : Type*) [strict_ordered_comm_semiring R] variables (M : Type*) [add_comm_monoid M] [module R M] variables {N : Type*} [add_comm_monoid N] [module R N] variables (ι ι' : Type*) /-- An orientation of a module, intended to be used when `ι` is a `fintype` with the same cardinality as a basis. -/ abbreviation orientation := module.ray R (alternating_map R M R ι) /-- A type class fixing an orientation of a module. -/ class module.oriented := (positive_orientation : orientation R M ι) export module.oriented (positive_orientation) variables {R M} /-- An equivalence between modules implies an equivalence between orientations. -/ def orientation.map (e : M ≃ₗ[R] N) : orientation R M ι ≃ orientation R N ι := module.ray.map $ alternating_map.dom_lcongr R R ι R e @[simp] lemma orientation.map_apply (e : M ≃ₗ[R] N) (v : alternating_map R M R ι) (hv : v ≠ 0) : orientation.map ι e (ray_of_ne_zero _ v hv) = ray_of_ne_zero _ (v.comp_linear_map e.symm) (mt (v.comp_linear_equiv_eq_zero_iff e.symm).mp hv) := rfl @[simp] lemma orientation.map_refl : (orientation.map ι $ linear_equiv.refl R M) = equiv.refl _ := by rw [orientation.map, alternating_map.dom_lcongr_refl, module.ray.map_refl] @[simp] lemma orientation.map_symm (e : M ≃ₗ[R] N) : (orientation.map ι e).symm = orientation.map ι e.symm := rfl section reindex variables (R M) {ι ι'} /-- An equivalence between indices implies an equivalence between orientations. -/ def orientation.reindex (e : ι ≃ ι') : orientation R M ι ≃ orientation R M ι' := module.ray.map $ alternating_map.dom_dom_lcongr R e @[simp] lemma orientation.reindex_apply (e : ι ≃ ι') (v : alternating_map R M R ι) (hv : v ≠ 0) : orientation.reindex R M e (ray_of_ne_zero _ v hv) = ray_of_ne_zero _ (v.dom_dom_congr e) (mt (v.dom_dom_congr_eq_zero_iff e).mp hv) := rfl @[simp] lemma orientation.reindex_refl : (orientation.reindex R M $ equiv.refl ι) = equiv.refl _ := by rw [orientation.reindex, alternating_map.dom_dom_lcongr_refl, module.ray.map_refl] @[simp] lemma orientation.reindex_symm (e : ι ≃ ι') : (orientation.reindex R M e).symm = orientation.reindex R M e.symm := rfl end reindex /-- A module is canonically oriented with respect to an empty index type. -/ @[priority 100] instance is_empty.oriented [nontrivial R] [is_empty ι] : module.oriented R M ι := { positive_orientation := ray_of_ne_zero R (alternating_map.const_linear_equiv_of_is_empty 1) $ alternating_map.const_linear_equiv_of_is_empty.injective.ne (by simp) } @[simp] lemma orientation.map_positive_orientation_of_is_empty [nontrivial R] [is_empty ι] (f : M ≃ₗ[R] N) : orientation.map ι f positive_orientation = positive_orientation := rfl @[simp] lemma orientation.map_of_is_empty [is_empty ι] (x : orientation R M ι) (f : M ≃ₗ[R] M) : orientation.map ι f x = x := begin induction x using module.ray.ind with g hg, rw orientation.map_apply, congr, ext i, rw alternating_map.comp_linear_map_apply, congr, end end ordered_comm_semiring section ordered_comm_ring variables {R : Type*} [strict_ordered_comm_ring R] variables {M N : Type*} [add_comm_group M] [add_comm_group N] [module R M] [module R N] @[simp] protected lemma orientation.map_neg {ι : Type*} (f : M ≃ₗ[R] N) (x : orientation R M ι) : orientation.map ι f (-x) = - orientation.map ι f x := module.ray.map_neg _ x @[simp] protected lemma orientation.reindex_neg {ι ι' : Type*} (e : ι ≃ ι') (x : orientation R M ι) : orientation.reindex R M e (-x) = - orientation.reindex R M e x := module.ray.map_neg _ x namespace basis variables {ι ι' : Type*} /-- The value of `orientation.map` when the index type has the cardinality of a basis, in terms of `f.det`. -/ lemma map_orientation_eq_det_inv_smul [finite ι] (e : basis ι R M) (x : orientation R M ι) (f : M ≃ₗ[R] M) : orientation.map ι f x = (f.det)⁻¹ • x := begin casesI nonempty_fintype ι, letI := classical.dec_eq ι, induction x using module.ray.ind with g hg, rw [orientation.map_apply, smul_ray_of_ne_zero, ray_eq_iff, units.smul_def, (g.comp_linear_map ↑f.symm).eq_smul_basis_det e, g.eq_smul_basis_det e, alternating_map.comp_linear_map_apply, alternating_map.smul_apply, basis.det_comp, basis.det_self, mul_one, smul_eq_mul, mul_comm, mul_smul, linear_equiv.coe_inv_det], end variables [fintype ι] [decidable_eq ι] [fintype ι'] [decidable_eq ι'] /-- The orientation given by a basis. -/ protected def orientation [nontrivial R] (e : basis ι R M) : orientation R M ι := ray_of_ne_zero R _ e.det_ne_zero lemma orientation_map [nontrivial R] (e : basis ι R M) (f : M ≃ₗ[R] N) : (e.map f).orientation = orientation.map ι f e.orientation := by simp_rw [basis.orientation, orientation.map_apply, basis.det_map'] lemma orientation_reindex [nontrivial R] (e : basis ι R M) (eι : ι ≃ ι') : (e.reindex eι).orientation = orientation.reindex R M eι e.orientation := by simp_rw [basis.orientation, orientation.reindex_apply, basis.det_reindex'] /-- The orientation given by a basis derived using `units_smul`, in terms of the product of those units. -/ lemma orientation_units_smul [nontrivial R] (e : basis ι R M) (w : ι → units R) : (e.units_smul w).orientation = (∏ i, w i)⁻¹ • e.orientation := begin rw [basis.orientation, basis.orientation, smul_ray_of_ne_zero, ray_eq_iff, e.det.eq_smul_basis_det (e.units_smul w), det_units_smul_self, units.smul_def, smul_smul], norm_cast, simp end @[simp] lemma orientation_is_empty [nontrivial R] [is_empty ι] (b : basis ι R M) : b.orientation = positive_orientation := begin congrm ray_of_ne_zero _ _ _, convert b.det_is_empty, end end basis end ordered_comm_ring section linear_ordered_comm_ring variables {R : Type*} [linear_ordered_comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {ι : Type*} namespace orientation /-- A module `M` over a linearly ordered commutative ring has precisely two "orientations" with respect to an empty index type. (Note that these are only orientations of `M` of in the conventional mathematical sense if `M` is zero-dimensional.) -/ lemma eq_or_eq_neg_of_is_empty [nontrivial R] [is_empty ι] (o : orientation R M ι) : o = positive_orientation ∨ o = - positive_orientation := begin induction o using module.ray.ind with x hx, dsimp [positive_orientation], simp only [ray_eq_iff, same_ray_neg_swap], rw same_ray_or_same_ray_neg_iff_not_linear_independent, intros h, let a : R := alternating_map.const_linear_equiv_of_is_empty.symm x, have H : linear_independent R ![a, 1], { convert h.map' ↑alternating_map.const_linear_equiv_of_is_empty.symm (linear_equiv.ker _), ext i, fin_cases i; simp [a] }, rw linear_independent_iff' at H, simpa using H finset.univ ![1, -a] (by simp [fin.sum_univ_succ]) 0 (by simp), end end orientation namespace basis variables [fintype ι] [decidable_eq ι] /-- The orientations given by two bases are equal if and only if the determinant of one basis with respect to the other is positive. -/ lemma orientation_eq_iff_det_pos (e₁ e₂ : basis ι R M) : e₁.orientation = e₂.orientation ↔ 0 < e₁.det e₂ := calc e₁.orientation = e₂.orientation ↔ same_ray R e₁.det e₂.det : ray_eq_iff _ _ ... ↔ same_ray R (e₁.det e₂ • e₂.det) e₂.det : by rw [← e₁.det.eq_smul_basis_det e₂] ... ↔ 0 < e₁.det e₂ : same_ray_smul_left_iff_of_ne e₂.det_ne_zero (e₁.is_unit_det e₂).ne_zero /-- Given a basis, any orientation equals the orientation given by that basis or its negation. -/ lemma orientation_eq_or_eq_neg (e : basis ι R M) (x : orientation R M ι) : x = e.orientation ∨ x = -e.orientation := begin induction x using module.ray.ind with x hx, rw ← x.map_basis_ne_zero_iff e at hx, rwa [basis.orientation, ray_eq_iff, neg_ray_of_ne_zero, ray_eq_iff, x.eq_smul_basis_det e, same_ray_neg_smul_left_iff_of_ne e.det_ne_zero hx, same_ray_smul_left_iff_of_ne e.det_ne_zero hx, lt_or_lt_iff_ne, ne_comm] end /-- Given a basis, an orientation equals the negation of that given by that basis if and only if it does not equal that given by that basis. -/ lemma orientation_ne_iff_eq_neg (e : basis ι R M) (x : orientation R M ι) : x ≠ e.orientation ↔ x = -e.orientation := ⟨λ h, (e.orientation_eq_or_eq_neg x).resolve_left h, λ h, h.symm ▸ (module.ray.ne_neg_self e.orientation).symm⟩ /-- Composing a basis with a linear equiv gives the same orientation if and only if the determinant is positive. -/ lemma orientation_comp_linear_equiv_eq_iff_det_pos (e : basis ι R M) (f : M ≃ₗ[R] M) : (e.map f).orientation = e.orientation ↔ 0 < (f : M →ₗ[R] M).det := by rw [orientation_map, e.map_orientation_eq_det_inv_smul, units_inv_smul, units_smul_eq_self_iff, linear_equiv.coe_det] /-- Composing a basis with a linear equiv gives the negation of that orientation if and only if the determinant is negative. -/ lemma orientation_comp_linear_equiv_eq_neg_iff_det_neg (e : basis ι R M) (f : M ≃ₗ[R] M) : (e.map f).orientation = -e.orientation ↔ (f : M →ₗ[R] M).det < 0 := by rw [orientation_map, e.map_orientation_eq_det_inv_smul, units_inv_smul, units_smul_eq_neg_iff, linear_equiv.coe_det] /-- Negating a single basis vector (represented using `units_smul`) negates the corresponding orientation. -/ @[simp] lemma orientation_neg_single [nontrivial R] (e : basis ι R M) (i : ι) : (e.units_smul (function.update 1 i (-1))).orientation = -e.orientation := begin rw [orientation_units_smul, finset.prod_update_of_mem (finset.mem_univ _)], simp end /-- Given a basis and an orientation, return a basis giving that orientation: either the original basis, or one constructed by negating a single (arbitrary) basis vector. -/ def adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : basis ι R M := by haveI := classical.dec_eq (orientation R M ι); exact if e.orientation = x then e else (e.units_smul (function.update 1 (classical.arbitrary ι) (-1))) /-- `adjust_to_orientation` gives a basis with the required orientation. -/ @[simp] lemma orientation_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : (e.adjust_to_orientation x).orientation = x := begin rw adjust_to_orientation, split_ifs with h, { exact h }, { rw [orientation_neg_single, eq_comm, ←orientation_ne_iff_eq_neg, ne_comm], exact h } end /-- Every basis vector from `adjust_to_orientation` is either that from the original basis or its negation. -/ lemma adjust_to_orientation_apply_eq_or_eq_neg [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) (i : ι) : e.adjust_to_orientation x i = e i ∨ e.adjust_to_orientation x i = -(e i) := begin rw adjust_to_orientation, split_ifs with h, { simp }, { by_cases hi : i = classical.arbitrary ι; simp [units_smul_apply, hi] } end lemma det_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) : (e.adjust_to_orientation x).det = e.det ∨ (e.adjust_to_orientation x).det = - e.det := begin dsimp [basis.adjust_to_orientation], split_ifs, { left, refl }, { right, simp [e.det_units_smul, ← units.coe_prod, finset.prod_update_of_mem] } end @[simp] lemma abs_det_adjust_to_orientation [nontrivial R] [nonempty ι] (e : basis ι R M) (x : orientation R M ι) (v : ι → M) : |(e.adjust_to_orientation x).det v| = |e.det v| := begin cases e.det_adjust_to_orientation x with h h; simp [h] end end basis end linear_ordered_comm_ring section linear_ordered_field variables {R : Type*} [linear_ordered_field R] variables {M : Type*} [add_comm_group M] [module R M] variables {ι : Type*} namespace orientation variables [fintype ι] [_i : finite_dimensional R M] open finite_dimensional include _i /-- If the index type has cardinality equal to the finite dimension, any two orientations are equal or negations. -/ lemma eq_or_eq_neg (x₁ x₂ : orientation R M ι) (h : fintype.card ι = finrank R M) : x₁ = x₂ ∨ x₁ = -x₂ := begin have e := (fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm, letI := classical.dec_eq ι, rcases e.orientation_eq_or_eq_neg x₁ with h₁|h₁; rcases e.orientation_eq_or_eq_neg x₂ with h₂|h₂; simp [h₁, h₂] end /-- If the index type has cardinality equal to the finite dimension, an orientation equals the negation of another orientation if and only if they are not equal. -/ lemma ne_iff_eq_neg (x₁ x₂ : orientation R M ι) (h : fintype.card ι = finrank R M) : x₁ ≠ x₂ ↔ x₁ = -x₂ := ⟨λ hn, (eq_or_eq_neg x₁ x₂ h).resolve_left hn, λ he, he.symm ▸ (module.ray.ne_neg_self x₂).symm⟩ /-- The value of `orientation.map` when the index type has cardinality equal to the finite dimension, in terms of `f.det`. -/ lemma map_eq_det_inv_smul (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = (f.det)⁻¹ • x := begin have e := (fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm, exact e.map_orientation_eq_det_inv_smul x f end omit _i /-- If the index type has cardinality equal to the finite dimension, composing an alternating map with the same linear equiv on each argument gives the same orientation if and only if the determinant is positive. -/ lemma map_eq_iff_det_pos (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = x ↔ 0 < (f : M →ₗ[R] M).det := begin casesI is_empty_or_nonempty ι, { have H : finrank R M = 0, { refine h.symm.trans _, convert fintype.card_of_is_empty, apply_instance }, simp [linear_map.det_eq_one_of_finrank_eq_zero H] }, have H : 0 < finrank R M, { rw ← h, exact fintype.card_pos }, haveI : finite_dimensional R M := finite_dimensional_of_finrank H, rw [map_eq_det_inv_smul _ _ h, units_inv_smul, units_smul_eq_self_iff, linear_equiv.coe_det] end /-- If the index type has cardinality equal to the finite dimension, composing an alternating map with the same linear equiv on each argument gives the negation of that orientation if and only if the determinant is negative. -/ lemma map_eq_neg_iff_det_neg (x : orientation R M ι) (f : M ≃ₗ[R] M) (h : fintype.card ι = finrank R M) : orientation.map ι f x = -x ↔ (f : M →ₗ[R] M).det < 0 := begin casesI is_empty_or_nonempty ι, { have H : finrank R M = 0, { refine h.symm.trans _, convert fintype.card_of_is_empty, apply_instance }, simp [linear_map.det_eq_one_of_finrank_eq_zero H, module.ray.ne_neg_self x] }, have H : 0 < finrank R M, { rw ← h, exact fintype.card_pos }, haveI : finite_dimensional R M := finite_dimensional_of_finrank H, rw [map_eq_det_inv_smul _ _ h, units_inv_smul, units_smul_eq_neg_iff, linear_equiv.coe_det] end include _i /-- If the index type has cardinality equal to the finite dimension, a basis with the given orientation. -/ def some_basis [nonempty ι] [decidable_eq ι] (x : orientation R M ι) (h : fintype.card ι = finrank R M) : basis ι R M := ((fin_basis R M).reindex (fintype.equiv_fin_of_card_eq h).symm).adjust_to_orientation x /-- `some_basis` gives a basis with the required orientation. -/ @[simp] lemma some_basis_orientation [nonempty ι] [decidable_eq ι] (x : orientation R M ι) (h : fintype.card ι = finrank R M) : (x.some_basis h).orientation = x := basis.orientation_adjust_to_orientation _ _ end orientation end linear_ordered_field
fa7b3829744241ae319cf6c42d1922f930911c85
947b78d97130d56365ae2ec264df196ce769371a
/src/Init/Control/MonadRun.lean
2263dd5cbde85d85d3481fc2a75a9a2f2eb29abb
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
859
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ prelude import Init.Control.MonadLift universes u v /-- Run a Monad stack to completion. `run` should be the composition of the transformers' individual `run` functions. This class mostly saves some typing when using highly nested Monad stacks: ``` @[reducible] def MyMonad := ReaderT myCfg $ StateT myState $ ExceptT myErr id -- def MyMonad.run {α : Type} (x : MyMonad α) (cfg : myCfg) (st : myState) := ((x.run cfg).run st).run def MyMonad.run {α : Type} (x : MyMonad α) := MonadRun.run x ``` -/ class MonadRun (out : outParam $ Type u → Type v) (m : Type u → Type v) := (run {α : Type u} : m α → out α) export MonadRun (run)
03e02c525bf079771c3eff9bbb1acba8235bbc11
c86b74188c4b7a462728b1abd659ab4e5828dd61
/stage0/src/Lean/Elab/Term.lean
0d41b3974a87c0c4d5895cac44600b8d5eb28e75
[ "Apache-2.0" ]
permissive
cwb96/lean4
75e1f92f1ba98bbaa6b34da644b3dfab2ce7bf89
b48831cda76e64f13dd1c0edde7ba5fb172ed57a
refs/heads/master
1,686,347,881,407
1,624,483,842,000
1,624,483,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
74,314
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.ResolveName import Lean.Util.Sorry import Lean.Util.ReplaceExpr import Lean.Structure import Lean.Meta.ExprDefEq import Lean.Meta.AppBuilder import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Coe import Lean.Meta.Tactic.Util import Lean.Hygiene import Lean.Util.RecDepth import Lean.Elab.Log import Lean.Elab.Level import Lean.Elab.Attributes import Lean.Elab.AutoBound import Lean.Elab.InfoTree import Lean.Elab.Open import Lean.Elab.SetOption namespace Lean.Elab.Term /- Set isDefEq configuration for the elaborator. Note that we enable all approximations but `quasiPatternApprox` In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration. The example: ``` def ex : StateT δ (StateT σ Id) σ := monadLift (get : StateT σ Id σ) ``` demonstrates why it produces counterintuitive behavior. We have the `Monad-lift` application: ``` @monadLift ?m ?n ?c ?α (get : StateT σ id σ) : ?n ?α ``` It produces the following unification problem when we process the expected type: ``` ?n ?α =?= StateT δ (StateT σ id) σ ==> (approximate using first-order unification) ?n := StateT δ (StateT σ id) ?α := σ ``` Then, we need to solve: ``` ?m ?α =?= StateT σ id σ ==> instantiate metavars ?m σ =?= StateT σ id σ ==> (approximate since it is a quasi-pattern unification constraint) ?m := fun σ => StateT σ id σ ``` Note that the constraint is not a Milner pattern because σ is in the local context of `?m`. We are ignoring the other possible solutions: ``` ?m := fun σ' => StateT σ id σ ?m := fun σ' => StateT σ' id σ ?m := fun σ' => StateT σ id σ' ``` We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions). If we had use first-order unification, then we would have produced the right answer: `?m := StateT σ id` Haskell would work on this example since it always uses first-order unification. -/ def setElabConfig (cfg : Meta.Config) : Meta.Config := { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false } structure Context where fileName : String fileMap : FileMap declName? : Option Name := none macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ mayPostpone : Bool := true /- When `errToSorry` is set to true, the method `elabTerm` catches exceptions and converts them into synthetic `sorry`s. The implementation of choice nodes and overloaded symbols rely on the fact that when `errToSorry` is set to false for an elaboration function `F`, then `errToSorry` remains `false` for all elaboration functions invoked by `F`. That is, it is safe to transition `errToSorry` from `true` to `false`, but we must not set `errToSorry` to `true` when it is currently set to `false`. -/ errToSorry : Bool := true /- When `autoBoundImplicit` is set to true, instead of producing an "unknown identifier" error for unbound variables, we generate an internal exception. This exception is caught at `elabBinders` and `elabTypeWithUnboldImplicit`. Both methods add implicit declarations for the unbound variable and try again. -/ autoBoundImplicit : Bool := false autoBoundImplicits : Std.PArray Expr := {} /-- Map from user name to internal unique name -/ sectionVars : NameMap Name := {} /-- Map from internal name to fvar -/ sectionFVars : NameMap Expr := {} /-- Enable/disable implicit lambdas feature. -/ implicitLambda : Bool := true /-- Saved context for postponed terms and tactics to be executed. -/ structure SavedContext where declName? : Option Name options : Options openDecls : List OpenDecl macroStack : MacroStack errToSorry : Bool /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind where -- typeclass instance search | typeClass /- Similar to typeClass, but error messages are different. if `f?` is `some f`, we produce an application type mismatch error message. Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/ | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) (ctx : SavedContext) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (ctx : SavedContext) instance : ToString SyntheticMVarKind where toString | SyntheticMVarKind.typeClass => "typeclass" | SyntheticMVarKind.coe .. => "coe" | SyntheticMVarKind.tactic .. => "tactic" | SyntheticMVarKind.postponed .. => "postponed" structure SyntheticMVarDecl where mvarId : MVarId stx : Syntax kind : SyntheticMVarKind inductive MVarErrorKind where | implicitArg (ctx : Expr) | hole | custom (msgData : MessageData) instance : ToString MVarErrorKind where toString | MVarErrorKind.implicitArg ctx => "implicitArg" | MVarErrorKind.hole => "hole" | MVarErrorKind.custom msg => "custom" structure MVarErrorInfo where mvarId : MVarId ref : Syntax kind : MVarErrorKind structure LetRecToLift where ref : Syntax fvarId : FVarId attrs : Array Attribute shortDeclName : Name declName : Name lctx : LocalContext localInstances : LocalInstances type : Expr val : Expr mvarId : MVarId structure State where levelNames : List Name := [] syntheticMVars : List SyntheticMVarDecl := [] mvarErrorInfos : List MVarErrorInfo := [] messages : MessageLog := {} letRecsToLift : List LetRecToLift := [] infoState : InfoState := {} deriving Inhabited abbrev TermElabM := ReaderT Context $ StateRefT State MetaM abbrev TermElab := Syntax → Option Expr → TermElabM Expr -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad TermElabM := { inferInstanceAs (Monad TermElabM) with } open Meta instance : Inhabited (TermElabM α) where default := throw arbitrary structure SavedState where meta : Meta.SavedState «elab» : State deriving Inhabited protected def saveState : TermElabM SavedState := do pure { meta := (← Meta.saveState), «elab» := (← get) } def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do let traceState ← getTraceState -- We never backtrack trace message let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false` s.meta.restore set s.elab setTraceState traceState unless restoreInfo do modify fun s => { s with infoState := infoState } instance : MonadBacktrack SavedState TermElabM where saveState := Term.saveState restoreState b := b.restore abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α instance [Inhabited α] : Inhabited (TermElabResult α) where default := EStateM.Result.ok arbitrary arbitrary def setMessageLog (messages : MessageLog) : TermElabM Unit := modify fun s => { s with messages := messages } def resetMessageLog : TermElabM Unit := setMessageLog {} def getMessageLog : TermElabM MessageLog := return (← get).messages /-- Execute `x`, save resulting expression and new state. We remove any `Info` created by `x`. The info nodes are committed when we execute `applyResult`. We use `observing` to implement overloaded notation and decls. We want to save `Info` nodes for the chosen alternative. -/ @[inline] def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do let s ← saveState try let e ← x let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.ok e sNew) catch | ex@(Exception.error _ _) => let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.error ex sNew) | ex@(Exception.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) throw ex /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ @[inline] def applyResult (result : TermElabResult α) : TermElabM α := match result with | EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex /-- Execute `x`, but keep state modifications only if `x` did not postpone. This method is useful to implement elaboration functions that cannot decide whether they need to postpone or not without updating the state. -/ def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do -- We just reuse the implementation of `observing` and `applyResult`. let r ← observing x applyResult r /-- Execute `x` but discard changes performed at `Term.State` and `Meta.State`. Recall that the environment is at `Core.State`. Thus, any updates to it will be preserved. This method is useful for performing computations where all metavariable must be resolved or discarded. -/ def withoutModifyingElabMetaState (x : TermElabM α) : TermElabM α := do let s ← get let sMeta ← getThe Meta.State try x finally set s set sMeta def getLevelNames : TermElabM (List Name) := return (← get).levelNames def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do match (← getLCtx).find? fvar.fvarId! with | some d => pure d | none => unreachable! instance : AddErrorMessageContext TermElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack pure (ref, msg) instance : MonadLog TermElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName logMessage msg := do let ctx ← readThe Core.Context let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data }; modify fun s => { s with messages := s.messages.add msg } protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule @[inline] protected def withFreshMacroScope (x : TermElabM α) : TermElabM α := do let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation TermElabM where getCurrMacroScope := Term.getCurrMacroScope getMainModule := Term.getMainModule withFreshMacroScope := Term.withFreshMacroScope instance : MonadInfoTree TermElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" @[implementedBy mkTermElabAttributeUnsafe] constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab) builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`. Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/ inductive LVal where | fieldIdx (ref : Syntax) (i : Nat) /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name. `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/ | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax) | getOp (ref : Syntax) (idx : Syntax) def LVal.getRef : LVal → Syntax | LVal.fieldIdx ref _ => ref | LVal.fieldName ref .. => ref | LVal.getOp ref _ => ref def LVal.isFieldName : LVal → Bool | LVal.fieldName .. => true | _ => false instance : ToString LVal where toString | LVal.fieldIdx _ i => toString i | LVal.fieldName _ n .. => n | LVal.getOp _ idx => "[" ++ toString idx ++ "]" def getDeclName? : TermElabM (Option Name) := return (← read).declName? def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val } def withDeclName (name : Name) (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with declName? := name }) x def setLevelNames (levelNames : List Name) : TermElabM Unit := modify fun s => { s with levelNames := levelNames } def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do let levelNamesSaved ← getLevelNames setLevelNames levelNames try x finally setLevelNames levelNamesSaved def withoutErrToSorry (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with errToSorry := false }) x /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do if (← get).messages.hasErrors then throwError "Error(s)" @[inline] def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := withRef Syntax.missing $ trace cls msg def ppGoal (mvarId : MVarId) : TermElabM Format := Meta.ppGoal mvarId open Level (LevelElabM) def liftLevelM (x : LevelElabM α) : TermElabM α := do let ctx ← read let mctx ← getMCtx let ngen ← getNGen let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit } match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with | EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a | EStateM.Result.error ex _ => throw ex def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := withMacroExpansionInfo beforeStx afterStx do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars } def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do registerSyntheticMVar (← getRef) mvarId kind def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos } def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos } def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos } def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := match e.getAppFn with | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData | _ => pure () /- Auxiliary method for reporting errors of the form "... contains metavariables ...". This kind of error is thrown, for example, at `Match.lean` where elaboration cannot continue if there are metavariables in patterns. We only want to log it if we haven't logged any error so far. -/ def throwMVarError (m : MessageData) : TermElabM α := do if (← get).messages.hasErrors then throwAbortTerm else throwError m def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do match mvarErrorInfo.kind with | MVarErrorKind.implicitArg app => do let app ← instantiateMVars app let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (appendExtra msg) | MVarErrorKind.hole => do let msg : MessageData := "don't know how to synthesize placeholder" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg) | MVarErrorKind.custom msg => logErrorAt mvarErrorInfo.ref (appendExtra msg) where appendExtra (msg : MessageData) : MessageData := match extraMsg? with | none => msg | some extraMsg => msg ++ extraMsg /-- Try to log errors for the unassigned metavariables `pendingMVarIds`. Return `true` if there were "unfilled holes", and we should "abort" declaration. TODO: try to fill "all" holes using synthetic "sorry's" Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/ def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do let s ← get let hasOtherErrors := s.messages.hasErrors let mut hasNewErrors := false let mut alreadyVisited : NameSet := {} for mvarErrorInfo in s.mvarErrorInfos do let mvarId := mvarErrorInfo.mvarId unless alreadyVisited.contains mvarId do alreadyVisited := alreadyVisited.insert mvarId let foundError ← withMVarContext mvarId do /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or delayed assigned to another metavariable that is unassigned. -/ let mvarDeps ← getMVars (mkMVar mvarId) if mvarDeps.any pendingMVarIds.contains then do unless hasOtherErrors do mvarErrorInfo.logError extraMsg? pure true else pure false if foundError then hasNewErrors := true return hasNewErrors /-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/ def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do let pendingMVarIds ← getMVarsAtDecl decl if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ @[inline] def withoutPostponing (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. The new parameter names are of the form `u_i` where `i >= nextParamIdx`. The method returns the updated expression and new `nextParamIdx`. Remark: we make sure the generated parameter names do not clash with the universes at `ctx.levelNames`. -/ def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr × Nat) := do let mctx ← getMCtx let levelNames ← getLevelNames let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx setMCtx r.mctx pure (r.expr, r.nextParamIdx) /-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/ def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do let nextParamIdx ← get let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx set nextParamIdx pure e /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name := withFreshMacroScope $ MonadQuotation.addMacroScope `x /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshUserName`. -/ def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax := return mkIdentFrom ref (← mkFreshBinderName) private def applyAttributesCore (declName : Name) (attrs : Array Attribute) (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := for attr in attrs do let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => match applicationTime? with | none => attrImpl.add declName attr.stx attr.kind | some applicationTime => if applicationTime == attrImpl.applicationTime then attrImpl.add declName attr.stx attr.kind /-- Apply given attributes **at** a given application time -/ def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit := applyAttributesCore declName attrs applicationTime def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit := applyAttributesCore declName attrs none def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do let header : MessageData := match header? with | some header => m!"{header} " | none => m!"type mismatch{indentExpr e}\n" return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}" def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do /- We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was always of the form: ``` failed to synthesize instance CoeT <eType> <e> <expectedType> ``` We should revisit this decision in the future and decide whether it may contain useful information or not. -/ let extraMsg := Format.nil /- let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; -/ match f? with | none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}" | some f => Meta.throwAppTypeMismatch f e extraMsg @[inline] def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α := withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x /- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do let instMVarDecl ← getMVarDecl instMVar let type := instMVarDecl.type let type ← instantiateMVars type let result ← trySynthInstance type maxResultSize? match result with | LOption.some val => if (← isExprMVarAssigned instMVar) then let oldVal ← instantiateMVars (mkMVar instMVar) unless (← isDefEq oldVal val) do let oldValType ← inferType oldVal let valType ← inferType val unless (← isDefEq oldValType valType) do throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}" throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}" else unless (← isDefEq (mkMVar instMVar) val) do throwError "failed to assign synthesized type class instance{indentExpr val}" pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError "failed to synthesize instance{indentExpr type}" register_builtin_option autoLift : Bool := { defValue := true descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed" } register_builtin_option maxCoeSize : Nat := { defValue := 16 descr := "maximum number of instances used to construct an automatic coercion" } def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions))) /- The coercion from `α` to `Thunk α` cannot be implemented using an instance because it would eagerly evaluate `e` -/ def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do match expectedType with | Expr.app (Expr.const ``Thunk u _) arg _ => if (← isDefEq eType arg) then pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e))) else pure none | _ => pure none /-- Try to apply coercion to make sure `e` has type `expectedType`. Relevant definitions: ``` class CoeT (α : Sort u) (a : α) (β : Sort v) abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β ``` -/ private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do if (← isDefEq expectedType eType) then return e else match (← tryCoeThunk? expectedType eType e) with | some r => return r | none => let u ← getLevel eType let v ← getLevel expectedType let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType] let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar] let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe eNew else -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe` -- after we syntheze `mvar` let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?) return mvarAux catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f? def isTypeApp? (type : Expr) : TermElabM (Option (Expr × Expr)) := do let type ← withReducible $ whnf type match type with | Expr.app m α _ => pure (some ((← instantiateMVars m), (← instantiateMVars α))) | _ => pure none def synthesizeInst (type : Expr) : TermElabM Expr := do let type ← instantiateMVars type match (← trySynthInstance type) with | LOption.some val => pure val | LOption.undef => throwError "failed to synthesize instance{indentExpr type}" | LOption.none => throwError "failed to synthesize instance{indentExpr type}" def isMonadApp (type : Expr) : TermElabM Bool := do let some (m, _) ← isTypeApp? type | pure false return (← isMonad? m) |>.isSome /-- Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`. The method is only applied if `α` is not monadic (e.g., `Nat → IO Unit`), and the head symbol of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool → ?m Nat`). The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y` since none of them is polymorphic ``` def f (x : Bool) : IO Bool := do let y ← if x == 0 then IO.println "hello"; true else false; !y ``` On the other hand, the following fails since `+` is polymorphic ``` def f (x : Bool) : IO Nat := do IO.prinln x x + x -- Error: failed to synthesize `Add (IO Nat)` ``` -/ private def tryPureCoe? (errorMsgHeader? : Option String) (m β α a : Expr) : TermElabM (Option Expr) := commitWhenSome? do let doIt : TermElabM (Option Expr) := do try let aNew ← tryCoe errorMsgHeader? β α a none let aNew ← mkPure m aNew pure (some aNew) catch _ => pure none forallTelescope α fun _ α => do if (← isMonadApp α) then pure none else if !α.getAppFn.isMVar then doIt else pure none /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n β`, we try monad lifts and other extensions. Otherwise, we just use the basic `tryCoe`. Extensions for monads. Given an expected type of the form `n β`, if `eType` is of the form `α`, but not `m α` 1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`. It only works if `n` implements `Pure` If `eType` is of the form `m α`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we use ``` coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β ``` `n` must be a `Monad` to use this one. 2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use ``` liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : MonadLiftT m n] {α : Type u_1}, m α → n α ``` Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as ``` def g (x : Nat) : IO Nat := do IO.println x pure x def f {m} [MonadLiftT IO m] : m Nat := g 10 ``` 3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use ``` liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β ``` Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`. This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)` using the instance `pureCoeDepProp`. Note that, approach 2 is more powerful than `tryCoe`. Recall that type class resolution never assigns metavariables created by other modules. Now, consider the following scenario ```lean def g (x : Nat) : IO Nat := ... deg h (x : Nat) : StateT Nat IO Nat := do v ← g x; IO.Println v; ... ``` Let's assume there is no other occurrence of `v` in `h`. Thus, we have that the expected of `g x` is `StateT Nat IO ?α`, and the given type is `IO Nat`. So, even if we add a coercion. ``` instance {α m n} [MonadLiftT m n] {α} : Coe (m α) (n α) := ... ``` It is not applicable because TC would have to assign `?α := Nat`. On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do let expectedType ← instantiateMVars expectedType let eType ← instantiateMVars eType let throwMismatch {α} : TermElabM α := throwTypeMismatchError errorMsgHeader? expectedType eType e f? let tryCoeSimple : TermElabM Expr := tryCoe errorMsgHeader? expectedType eType e f? let some (n, β) ← isTypeApp? expectedType | tryCoeSimple let tryPureCoeAndSimple : TermElabM Expr := do if autoLift.get (← getOptions) then match (← tryPureCoe? errorMsgHeader? n β eType e) with | some eNew => pure eNew | none => tryCoeSimple else tryCoeSimple let some (m, α) ← isTypeApp? eType | tryPureCoeAndSimple if (← isDefEq m n) then let some monadInst ← isMonad? n | tryCoeSimple try expandCoe (← mkAppOptM ``coeM #[m, α, β, none, monadInst, e]) catch _ => throwMismatch else if autoLift.get (← getOptions) then try -- Construct lift from `m` to `n` let monadLiftType ← mkAppM ``MonadLiftT #[m, n] let monadLiftVal ← synthesizeInst monadLiftType let u_1 ← getDecLevel α let u_2 ← getDecLevel eType let u_3 ← getDecLevel expectedType let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, α, e] let eNewType ← inferType eNew if (← isDefEq expectedType eNewType) then return eNew -- approach 2 worked else let some monadInst ← isMonad? n | tryCoeSimple let u ← getLevel α let v ← getLevel β let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst ``CoeT [u, v]) #[α, mkBVar 0, β] let coeTInstVal ← synthesizeInst coeTInstType let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, monadLiftVal, coeTInstVal, monadInst, e]) let eNewType ← inferType eNew unless (← isDefEq expectedType eNewType) do throwMismatch return eNew -- approach 3 worked catch _ => /- If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`. Otherwise, we just try `tryCoe?`. -/ match (← isMonad? m) with | none => tryPureCoeAndSimple | some _ => tryCoeSimple else tryCoeSimple /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do match expectedType? with | none => pure e | some expectedType => if (← isDefEq eType expectedType) then pure e else tryLiftAndCoe errorMsgHeader? expectedType eType e f? /-- If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal. If they are not, then try coercions. -/ def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr := match expectedType? with | none => pure e | _ => do let eType ← inferType e ensureHasTypeAux expectedType? eType e none errorMsgHeader? private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← match expectedType? with | none => mkFreshTypeMVar | some expectedType => pure expectedType mkSyntheticSorry expectedType private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do let syntheticSorry ← mkSyntheticSorryFor expectedType? logException ex pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do if (← read).mayPostpone then throwPostpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do if e.getAppFn.isMVar then let e ← instantiateMVars e if e.getAppFn.isMVar then tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "{msg}, expected type must be known" let expectedType ← instantiateMVars expectedType if expectedType.hasExprMVar then tryPostpone throwError "{msg}, expected type contains metavariables{indentExpr expectedType}" pure expectedType private def saveContext : TermElabM SavedContext := return { macroStack := (← read).macroStack declName? := (← read).declName? options := (← getOptions) openDecls := (← getOpenDecls) errToSorry := (← read).errToSorry } def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <| withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) x private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace[Elab.postpone] "{stx} : {expectedType?}" let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque let ctx ← read registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext)) pure mvar def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) := return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) : TermElabM (Sum Info MVarId) := do let isHole? : TermElabM (Option MVarId) := do match e with | Expr.mvar mvarId _ => match (← getSyntheticMVarDecl? mvarId) with | some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId | _ => return none | _ => pure none match (← isHole?) with | none => return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType? } | some mvarId => return Sum.inr mvarId def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) : TermElabM Unit := do withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx?) |> discard /- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr | [] => do throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => try -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`) withInfoContext' (mkInfo := mkTermInfo elabFn.decl (expectedType? := expectedType?) stx) (try elabFn.value stx expectedType? catch ex => match ex with | Exception.error ref msg => if (← read).errToSorry then exceptionToSorry ex expectedType? else throw ex | Exception.internal id _ => if (← read).errToSorry && id == abortTermExceptionId then exceptionToSorry ex expectedType? else if id == unsupportedSyntaxExceptionId then throw ex -- to outer try else if catchExPostpone && id == postponeExceptionId then /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ s.restore postponeElabTerm stx expectedType? else throw ex) catch ex => match ex with | Exception.internal id _ => if id == unsupportedSyntaxExceptionId then s.restore -- also removes the info tree created above elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns else throw ex | _ => throw ex private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do let s ← saveState let k := stx.getKind match termElabAttribute.getEntries (← getEnv) k with | [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}" | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns instance : MonadMacroAdapter TermElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← getThe Core.State).nextMacroScope setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next } private def isExplicit (stx : Syntax) : Bool := match stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0] /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {α} (a : α) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match stx with | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false private partial def dropTermParens : Syntax → Syntax := fun stx => match stx with | `(($stx)) => dropTermParens stx | _ => stx private def isHole (stx : Syntax) : Bool := match stx with | `(_) => true | `(? _) => true | `(? $x:ident) => true | _ => false private def isTacticBlock (stx : Syntax) : Bool := match stx with | `(by $x:tacticSeq) => true | _ => false private def isNoImplicitLambda (stx : Syntax) : Bool := match stx with | `(noImplicitLambda% $x:term) => true | _ => false private def isTypeAscription (stx : Syntax) : Bool := match stx with | `(($e : $type)) => true | _ => false def mkNoImplicitLambdaAnnotation (type : Expr) : Expr := mkAnnotation `noImplicitLambda type def hasNoImplicitLambdaAnnotation (type : Expr) : Bool := annotation? `noImplicitLambda type |>.isSome /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx -- TODO: make it extensible isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx || isTypeAscription stx /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. -/ private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then pure none else match expectedType? with | some expectedType => do if hasNoImplicitLambdaAnnotation expectedType then pure none else let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ _ _ c => if c.binderInfo.isExplicit then pure none else pure $ some expectedType | _ => pure none | _ => pure none private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do match ex with | Exception.error ref msg => if impFVars.isEmpty then return Exception.error ref msg else let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature" for impFVar in impFVars do let auxMsg := m!"{impFVar} : {← inferType impFVar}" let auxMsg ← addMessageContext auxMsg msg := m!"{msg}{indentD auxMsg}" msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations." return Exception.error ref msg | _ => return ex private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do let body ← elabUsingElabFns stx expectedType catchExPostpone try let body ← ensureHasType expectedType body let r ← mkLambdaFVars impFVars body trace[Elab.implicitForall] r pure r catch ex => throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars) private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr := loop type #[] where loop | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope do let n ← MonadQuotation.addMacroScope n withLocalDecl n c.binderInfo d fun fvar => do let type ← whnfForall (b.instantiate1 fvar) loop type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /- Main loop for `elabTerm` -/ private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | Syntax.missing => mkSyntheticSorryFor expectedType? | stx => withFreshMacroScope <| withIncRecDepth do trace[Elab.step] "expected type: {expectedType?}, term\n{stx}" checkMaxHeartbeats "elaborator" withNestedTraces do let env ← getEnv match (← liftMacroM (expandMacroImpl? env stx)) with | some (decl, stxNew) => withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <| withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew | _ => let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType | none => elabUsingElabFns stx expectedType? catchExPostpone /-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/ def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?) /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms. We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr := withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let e ← elabTerm stx expectedType? catchExPostpone implicitLambda withRef stx <| ensureHasType expectedType? e errorMsgHeader? /-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/ def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do let saved ← saveState modify fun s => { s with messages := {} } try let a ← x if (← get).messages.hasErrors then restoreState saved return none else modify fun s => { s with messages := saved.elab.messages ++ s.messages } return a catch _ => restoreState saved return none /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do let stx' ← exp stx withMacroExpansion stx stx' $ elabTerm stx' expectedType? def mkInstMVar (type : Expr) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.synthetic let mvarId := mvar.mvarId! unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass pure mvar /- Relevant definitions: ``` class CoeSort (α : Sort u) (β : outParam (Sort v)) abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β ``` -/ private def tryCoeSort (α : Expr) (a : Expr) : TermElabM Expr := do let β ← mkFreshTypeMVar let u ← getLevel α let v ← getLevel β let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[α, β] let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[α, β, a, mvar] else throwError "type expected" catch | Exception.error _ msg => throwError "type expected\n{msg}" | _ => throwError "type expected" /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (e : Expr) : TermElabM Expr := do if (← isType e) then pure e else let eType ← inferType e let u ← mkFreshLevelMVar if (← isDefEq eType (mkSort u)) then pure e else tryCoeSort eType e /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do let u ← mkFreshLevelMVar let type ← elabTerm stx (mkSort u) withRef stx $ ensureType type /-- Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught, a new local declaration is created, registered, and `k` is tried to be executed again. -/ partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do let flag := autoBoundImplicitLocal.get (← getOptions) if flag then withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do let rec loop (s : SavedState) : TermElabM α := do try k catch | ex => match isAutoBoundImplicitLocalException? ex with | some n => -- Restore state, declare `n`, and try again s.restore withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x => withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do loop (← saveState) | none => throw ex loop (← saveState) else k def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k /-- Return `autoBoundImplicits ++ xs. This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/ def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do let autoBoundImplicits := (← read).autoBoundImplicits for auto in autoBoundImplicits do let localDecl ← getLocalDecl auto.fvarId! for x in xs do if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'" return autoBoundImplicits.toArray ++ xs def mkAuxName (suffix : Name) : TermElabM Name := do match (← read).declName? with | none => throwError "auxiliary declaration cannot be created when declaration name is not available" | some declName => Lean.mkAuxName (declName ++ suffix) 1 builtin_initialize registerTraceClass `Elab.letrec /- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it is delayed assigned to one. -/ def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}" let mvarId := (← getMCtx).getDelayedRoot mvarId trace[Elab.letrec] "mvarId root: {mkMVar mvarId}" return (← get).letRecsToLift.any (·.mvarId == mvarId) /- ======================================= Builtin elaboration functions ======================================= -/ @[builtinTermElab «prop»] def elabProp : TermElab := fun _ _ => return mkSort levelZero private def elabOptLevel (stx : Syntax) : TermElabM Level := if stx.isNone then pure levelZero else elabLevel stx[0] @[builtinTermElab «sort»] def elabSort : TermElab := fun stx _ => return mkSort (← elabOptLevel stx[1]) @[builtinTermElab «type»] def elabTypeStx : TermElab := fun stx _ => return mkSort (mkLevelSucc (← elabOptLevel stx[1])) /- the method `resolveName` adds a completion point for it using the given expected type. Thus, we propagate the expected type if `stx[0]` is an identifier. It doesn't "hurt" if the identifier can be resolved because the expected type is not used in this case. Recall that if the name resolution fails a synthetic sorry is returned.-/ @[builtinTermElab «pipeCompletion»] def elabPipeCompletion : TermElab := fun stx expectedType? => do let e ← elabTerm stx[0] none unless e.isSorry do addDotCompletionInfo stx e expectedType? throwErrorAt stx[1] "invalid field notation, identifier or numeral expected" @[builtinTermElab «completion»] def elabCompletion : TermElab := fun stx expectedType? => do /- `ident.` is ambiguous in Lean, we may try to be completing a declaration name or access a "field". -/ if stx[0].isIdent then /- If we can elaborate the identifier successfully, we assume it a dot-completion. Otherwise, we treat it as identifier completion with a dangling `.`. Recall that the server falls back to identifier completion when dot-completion fails. -/ let s ← saveState try let e ← elabTerm stx[0] none addDotCompletionInfo stx e expectedType? catch _ => s.restore addCompletionInfo <| CompletionInfo.id stx stx[0].getId (danglingDot := true) (← getLCtx) expectedType? throwErrorAt stx[1] "invalid field notation, identifier or numeral expected" else elabPipeCompletion stx expectedType? @[builtinTermElab «hole»] def elabHole : TermElab := fun stx expectedType? => do let mvar ← mkFreshExprMVar expectedType? registerMVarErrorHoleInfo mvar.mvarId! stx pure mvar @[builtinTermElab «syntheticHole»] def elabSyntheticHole : TermElab := fun stx expectedType? => do let arg := stx[1] let userName := if arg.isIdent then arg.getId else Name.anonymous let mkNewHole : Unit → TermElabM Expr := fun _ => do let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque userName registerMVarErrorHoleInfo mvar.mvarId! stx pure mvar if userName.isAnonymous then mkNewHole () else let mctx ← getMCtx match mctx.findUserName? userName with | none => mkNewHole () | some mvarId => let mvar := mkMVar mvarId let mvarDecl ← getMVarDecl mvarId let lctx ← getLCtx if mvarDecl.lctx.isSubPrefixOf lctx then pure mvar else match mctx.getExprAssignment? mvarId with | some val => let val ← instantiateMVars val if mctx.isWellFormed lctx val then pure val else withLCtx mvarDecl.lctx mvarDecl.localInstances do throwError "synthetic hole has already been defined and assigned to value incompatible with the current context{indentExpr val}" | none => if mctx.isDelayedAssigned mvarId then -- We can try to improve this case if needed. throwError "synthetic hole has already beend defined and delayed assigned with an incompatible local context" else if lctx.isSubPrefixOf mvarDecl.lctx then let mvarNew ← mkNewHole () modifyMCtx fun mctx => mctx.assignExpr mvarId mvarNew pure mvarNew else throwError "synthetic hole has already been defined with an incompatible local context" private def mkTacticMVar (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.syntheticOpaque let mvarId := mvar.mvarId! let ref ← getRef let declName? ← getDeclName? registerSyntheticMVar ref mvarId <| SyntheticMVarKind.tactic tacticCode (← saveContext) return mvar @[builtinTermElab byTactic] def elabByTactic : TermElab := fun stx expectedType? => match expectedType? with | some expectedType => mkTacticMVar expectedType stx | none => throwError ("invalid 'by' tactic, expected type has not been provided") @[builtinTermElab noImplicitLambda] def elabNoImplicitLambda : TermElab := fun stx expectedType? => elabTerm stx[1] (mkNoImplicitLambdaAnnotation <$> expectedType?) def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do let lctx ← getLCtx let view := extractMacroScopes n let rec loop (n : Name) (projs : List String) := match lctx.findFromUserName? { view with name := n }.review with | some decl => some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => loop pre (s::projs) | _ => none return loop view.name [] /- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/ def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val _ => do let r? ← resolveLocalName val match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do let cinfo ← getConstInfo constName if explicitLevels.length > cinfo.levelParams.length then throwError "too many explicit universe levels" else let numMissingLevels := cinfo.levelParams.length - explicitLevels.length let us ← mkFreshLevelMVars numMissingLevels pure $ Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do candidates.foldlM (init := []) fun result (constName, projs) => do -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. let const ← mkConst constName explicitLevels return (const, projs) :: result def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do try if let some (e, projs) ← resolveLocalName n then unless explicitLevels.isEmpty do throwError "invalid use of explicit universe parameters, '{e}' is a local" return [(e, projs)] -- check for section variable capture by a quotation let ctx ← read if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then return [(e, projs)] -- section variables should shadow global decls if preresolved.isEmpty then process (← resolveGlobalName n) else process preresolved catch ex => if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? throw ex where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do if candidates.isEmpty then if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then throwAutoBoundImplicitLocal n else throwError "unknown identifier '{Lean.mkConst n}'" if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? mkConsts candidates explicitLevels /-- Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`. Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces `(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/ def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do match ident with | Syntax.ident info rawStr n preresolved => let r ← resolveName ident n preresolved explicitLevels expectedType? r.mapM fun (c, fields) => do let (cSstr, fields) := fields.foldr (init := (rawStr, [])) fun field (restSstr, fs) => let fieldSstr := restSstr.takeRightWhile (· ≠ '.') ({ restSstr with stopPos := restSstr.stopPos - (fieldSstr.bsize + 1) }, (field, fieldSstr) :: fs) let mkIdentFromPos pos rawVal val := let info := match info with | SourceInfo.original .. => SourceInfo.original "".toSubstring pos "".toSubstring (pos + rawVal.bsize) | _ => SourceInfo.synthetic pos (pos + rawVal.bsize) Syntax.ident info rawVal val [] let id := match c with | Expr.const id _ _ => id | Expr.fvar id _ => id | _ => unreachable! let id := mkIdentFromPos (ident.getPos?.getD 0) cSstr id match info.getPos? with | none => return (c, id, fields.map fun (field, _) => mkIdentFrom ident (Name.mkSimple field)) | some pos => let mut pos := pos + cSstr.bsize + 1 let mut newFields := #[] for (field, fieldSstr) in fields do newFields := newFields.push <| mkIdentFromPos pos fieldSstr (Name.mkSimple field) pos := pos + fieldSstr.bsize + 1 return (c, id, newFields.toList) | _ => throwError "identifier expected" def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val preresolved => do let rs ← try resolveName stx val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => pure none | [f] => if withInfo then addTermInfo stx f pure (some f) | _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}" | _ => throwError "identifier expected" @[builtinTermElab cdot] def elabBadCDot : TermElab := fun stx _ => throwError "invalid occurrence of `·` notation, it must be surrounded by parentheses (e.g. `(· + 1)`)" @[builtinTermElab strLit] def elabStrLit : TermElab := fun stx _ => do match stx.isStrLit? with | some val => pure $ mkStrLit val | none => throwIllFormedSyntax private def mkFreshTypeMVarFor (expectedType? : Option Expr) : TermElabM Expr := do let typeMVar ← mkFreshTypeMVar MetavarKind.synthetic match expectedType? with | some expectedType => discard <| isDefEq expectedType typeMVar | _ => pure () return typeMVar @[builtinTermElab numLit] def elabNumLit : TermElab := fun stx expectedType? => do let val ← match stx.isNatLit? with | some val => pure val | none => throwIllFormedSyntax let typeMVar ← mkFreshTypeMVarFor expectedType? let u ← getDecLevel typeMVar let mvar ← mkInstMVar (mkApp2 (Lean.mkConst ``OfNat [u]) typeMVar (mkNatLit val)) let r := mkApp3 (Lean.mkConst ``OfNat.ofNat [u]) typeMVar (mkNatLit val) mvar registerMVarErrorImplicitArgInfo mvar.mvarId! stx r return r @[builtinTermElab rawNatLit] def elabRawNatLit : TermElab := fun stx expectedType? => do match stx[1].isNatLit? with | some val => return mkNatLit val | none => throwIllFormedSyntax @[builtinTermElab scientificLit] def elabScientificLit : TermElab := fun stx expectedType? => do match stx.isScientificLit? with | none => throwIllFormedSyntax | some (m, sign, e) => let typeMVar ← mkFreshTypeMVarFor expectedType? let u ← getDecLevel typeMVar let mvar ← mkInstMVar (mkApp (Lean.mkConst ``OfScientific [u]) typeMVar) return mkApp5 (Lean.mkConst ``OfScientific.ofScientific [u]) typeMVar mvar (mkNatLit m) (toExpr sign) (mkNatLit e) @[builtinTermElab charLit] def elabCharLit : TermElab := fun stx _ => do match stx.isCharLit? with | some val => return mkApp (Lean.mkConst ``Char.ofNat) (mkNatLit val.toNat) | none => throwIllFormedSyntax @[builtinTermElab quotedName] def elabQuotedName : TermElab := fun stx _ => match stx[0].isNameLit? with | some val => pure $ toExpr val | none => throwIllFormedSyntax @[builtinTermElab doubleQuotedName] def elabDoubleQuotedName : TermElab := fun stx _ => do match stx[1].isNameLit? with | some val => toExpr (← resolveGlobalConstNoOverloadWithInfo stx[1] val) | none => throwIllFormedSyntax @[builtinTermElab typeOf] def elabTypeOf : TermElab := fun stx _ => do inferType (← elabTerm stx[1] none) @[builtinTermElab ensureTypeOf] def elabEnsureTypeOf : TermElab := fun stx expectedType? => match stx[2].isStrLit? with | none => throwIllFormedSyntax | some msg => do let refTerm ← elabTerm stx[1] none let refTermType ← inferType refTerm elabTermEnsuringType stx[3] refTermType (errorMsgHeader? := msg) @[builtinTermElab ensureExpectedType] def elabEnsureExpectedType : TermElab := fun stx expectedType? => match stx[1].isStrLit? with | none => throwIllFormedSyntax | some msg => elabTermEnsuringType stx[2] expectedType? (errorMsgHeader? := msg) @[builtinTermElab «open»] def elabOpen : TermElab := fun stx expectedType? => do try pushScope let openDecls ← elabOpenDecl stx[1] withTheReader Core.Context (fun ctx => { ctx with openDecls := openDecls }) do elabTerm stx[3] expectedType? finally popScope @[builtinTermElab «set_option»] def elabSetOption : TermElab := fun stx expectedType? => do let options ← Elab.elabSetOption stx[1] stx[2] withTheReader Core.Context (fun ctx => { ctx with maxRecDepth := maxRecDepth.get options, options := options }) do elabTerm stx[4] expectedType? private def mkSomeContext : Context := { fileName := "<TermElabM>" fileMap := arbitrary } @[inline] def TermElabM.run (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (α × State) := withConfig setElabConfig (x ctx |>.run s) @[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM α := (·.1) <$> x.run ctx s @[inline] def TermElabM.toIO (x : TermElabM α) (ctxCore : Core.Context) (sCore : Core.State) (ctxMeta : Meta.Context) (sMeta : Meta.State) (ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta pure (a, sCore, sMeta, s) instance [MetaEval α] : MetaEval (TermElabM α) where eval env opts x _ := let x : TermElabM α := do try x finally let s ← get s.messages.forM fun msg => do IO.println (← msg.toString) MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext unsafe def evalExpr (α) (typeName : Name) (value : Expr) : TermElabM α := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let type ← inferType value let type ← whnfD type unless type.isConstOf typeName do throwError "unexpected type at evalExpr{indentExpr type}" let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.unsafe } ensureNoUnassignedMVars decl addAndCompile decl evalConst α name private def throwStuckAtUniverseCnstr : TermElabM Unit := do -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property let entries ← getPostponed let mut found : Std.HashSet (Level × Level) := {} let mut uniqueEntries := #[] for entry in entries do let mut lhs := entry.lhs let mut rhs := entry.rhs if Level.normLt rhs lhs then (lhs, rhs) := (rhs, lhs) unless found.contains (lhs, rhs) do found := found.insert (lhs, rhs) uniqueEntries := uniqueEntries.push entry for i in [1:uniqueEntries.size] do logErrorAt uniqueEntries[i].ref (← mkLevelStuckErrorMessage uniqueEntries[i]) throwErrorAt uniqueEntries[0].ref (← mkLevelStuckErrorMessage uniqueEntries[0]) @[specialize] def withoutPostponingUniverseConstraints (x : TermElabM α) : TermElabM α := do let postponed ← getResetPostponed try let a ← x unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do throwStuckAtUniverseCnstr setPostponed postponed return a catch ex => setPostponed postponed throw ex end Term builtin_initialize registerTraceClass `Elab.postpone registerTraceClass `Elab.coe registerTraceClass `Elab.debug export Term (TermElabM) end Lean.Elab
33294650ba9e38b6a2c4f2be6fab58bec5bb2963
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Lean/ProjFns.lean
75222dec2e5f01827fd9eb91c1e18290435ceae4
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
2,891
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Environment namespace Lean /- Given a structure `S`, Lean automatically creates an auxiliary definition (projection function) for each field. This structure caches information about these auxiliary definitions. -/ structure ProjectionFunctionInfo := (ctorName : Name) -- Constructor associated with the auxiliary projection function. (nparams : Nat) -- Number of parameters in the structure (i : Nat) -- The field index associated with the auxiliary projection function. (fromClass : Bool) -- `true` if the structure is a class @[export lean_mk_projection_info] def mkProjectionInfoEx (ctorName : Name) (nparams : Nat) (i : Nat) (fromClass : Bool) : ProjectionFunctionInfo := {ctorName := ctorName, nparams := nparams, i := i, fromClass := fromClass } @[export lean_projection_info_from_class] def ProjectionFunctionInfo.fromClassEx (info : ProjectionFunctionInfo) : Bool := info.fromClass instance ProjectionFunctionInfo.inhabited : Inhabited ProjectionFunctionInfo := ⟨{ ctorName := arbitrary _, nparams := arbitrary _, i := 0, fromClass := false }⟩ def mkProjectionFnInfoExtension : IO (SimplePersistentEnvExtension (Name × ProjectionFunctionInfo) (NameMap ProjectionFunctionInfo)) := registerSimplePersistentEnvExtension { name := `projinfo, addImportedFn := fun as => {}, addEntryFn := fun s p => s.insert p.1 p.2, toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1) } @[init mkProjectionFnInfoExtension] constant projectionFnInfoExt : SimplePersistentEnvExtension (Name × ProjectionFunctionInfo) (NameMap ProjectionFunctionInfo) := arbitrary _ @[export lean_add_projection_info] def addProjectionFnInfo (env : Environment) (projName : Name) (ctorName : Name) (nparams : Nat) (i : Nat) (fromClass : Bool) : Environment := projectionFnInfoExt.addEntry env (projName, { ctorName := ctorName, nparams := nparams, i := i, fromClass := fromClass }) namespace Environment @[export lean_get_projection_info] def getProjectionFnInfo (env : Environment) (projName : Name) : Option ProjectionFunctionInfo := match env.getModuleIdxFor? projName with | some modIdx => match (projectionFnInfoExt.getModuleEntries env modIdx).binSearch (projName, arbitrary _) (fun a b => Name.quickLt a.1 b.1) with | some e => some e.2 | none => none | none => (projectionFnInfoExt.getState env).find? projName def isProjectionFn (env : Environment) (n : Name) : Bool := match env.getModuleIdxFor? n with | some modIdx => (projectionFnInfoExt.getModuleEntries env modIdx).binSearchContains (n, arbitrary _) (fun a b => Name.quickLt a.1 b.1) | none => (projectionFnInfoExt.getState env).contains n end Environment end Lean
3dccc01d6fd1d718671de8c6505c5e7327397919
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/analysis/calculus/mean_value.lean
36be002ad414a7df250e29d6cae3ad3e6afc4f03
[ "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
38,640
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, Yury Kudryashov -/ import analysis.calculus.local_extr import analysis.convex.topology /-! # The mean value inequality and equalities In this file we prove the following facts: * `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentaible on a convex set `s` and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with constant `C`. * `image_le_of*`, `image_norm_le_of_*` : several similar lemmas deducing `f x ≤ B x` or `∥f x∥ ≤ B x` from upper estimates on `f'` or `∥f'∥`, respectively. These lemmas differ by their assumptions: * `of_liminf_*` lemmas assume that limit inferior of some ratio is less than `B' x`; * `of_deriv_right_*`, `of_norm_deriv_right_*` lemmas assume that the right derivative or its norm is less than `B' x`; * `of_*_lt_*` lemmas assume a strict inequality whenever `f x = B x` or `∥f x∥ = B x`; * `of_*_le_*` lemmas assume a non-strict inequality everywhere on `[a, b)`; * name of a lemma ends with `'` if (1) it assumes that `B` is continuous on `[a, b]` and has a right derivative at every point of `[a, b)`, and (2) the lemma has a counterpart assuming that `B` is differentiable everywhere on `ℝ` * `norm_image_sub_le_*_segment` : if derivative of `f` on `[a, b]` is bounded above by a constant `C`, then `∥f x - f a∥ ≤ C * ∥x - a∥`; several versions deal with right derivative and derivative within `[a, b]` (`has_deriv_within_at` or `deriv_within`). * `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`, then it is a constant on `s`. * `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` : Cauchy's Mean Value Theorem. * `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem. * `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`, `convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`, if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`. * `convex.mono_of_deriv_nonneg`, `convex.antimono_of_deriv_nonpos`, `convex.strict_mono_of_deriv_pos`, `convex.strict_antimono_of_deriv_neg` : if the derivative of a function is non-negative/non-positive/positive/negative, then the function is monotone/monotonically decreasing/strictly monotone/strictly monotonically decreasing. * `convex_on_of_deriv_mono`, `convex_on_of_deriv2_nonneg` : if the derivative of a function is increasing or its second derivative is nonnegative, then the original function is convex. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set asymptotics continuous_linear_map filter open_locale classical topological_space /-! ### One-dimensional fencing inequalities -/ /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin change Icc a b ⊆ {x | f x ≤ B x}, set s := {x | f x ≤ B x} ∩ Icc a b, have A : continuous_on (λ x, (f x, B x)) (Icc a b), from hf.prod hB, have : is_closed s, { simp only [s, inter_comm], exact A.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, apply this.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxB, xab⟩ y hy, change f x ≤ B x at hxB, cases lt_or_eq_of_le hxB with hxB hxB, { -- If `f x < B x`, then all we need is continuity of both sides apply nonempty_of_mem_sets (nhds_within_Ioi_self_ne_bot x), refine inter_mem_sets _ (Ioc_mem_nhds_within_Ioi ⟨le_refl x, hy⟩), have : ∀ᶠ x in nhds_within x (Icc a b), f x < B x, from A x (Ico_subset_Icc_self xab) (mem_nhds_sets (is_open_lt continuous_fst continuous_snd) hxB), have : ∀ᶠ x in nhds_within x (Ioi x), f x < B x, from nhds_within_le_of_mem (Icc_mem_nhds_within_Ioi xab) this, refine mem_sets_of_superset this (set_of_subset_set_of.2 $ λ y, le_of_lt) }, { rcases dense (bound x xab hxB) with ⟨r, hfr, hrB⟩, specialize hf' x xab r hfr, have HB : ∀ᶠ z in nhds_within x (Ioi x), r < (z - x)⁻¹ * (B z - B x), from (has_deriv_within_at_iff_tendsto_slope' $ lt_irrefl x).1 (hB' x xab) (mem_nhds_sets is_open_Ioi hrB), obtain ⟨z, ⟨hfz, hzB⟩, hz⟩ : ∃ z, ((z - x)⁻¹ * (f z - f x) < r ∧ r < (z - x)⁻¹ * (B z - B x)) ∧ z ∈ Ioc x y, from ((hf'.and_eventually HB).and_eventually (Ioc_mem_nhds_within_Ioi ⟨le_refl _, hy⟩)).exists, have := le_of_lt (lt_trans hfz hzB), refine ⟨z, _, hz⟩, rw [mul_le_mul_left (inv_pos.2 $ sub_pos.2 hz.1), hxB, sub_le_sub_iff_right] at this, exact this } end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by `B'`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_le_deriv_boundary {f : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) -- `bound` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ B' x` (bound : ∀ x ∈ Ico a b, ∀ r, B' x < r → ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin have Hr : ∀ x ∈ Icc a b, ∀ r ∈ Ioi (0:ℝ), f x ≤ B x + r * (x - a), { intros x hx r hr, apply image_le_of_liminf_slope_right_lt_deriv_boundary' hf bound, { rwa [sub_self, mul_zero, add_zero] }, { exact hB.add (continuous_on_const.mul (continuous_id.continuous_on.sub continuous_on_const)) }, { assume x hx, exact (hB' x hx).add (((has_deriv_within_at_id x (Ioi x)).sub_const a).const_mul r) }, { assume x hx _, rw [mul_one], exact (lt_add_iff_pos_right _).2 hr }, exact hx }, assume x hx, have : continuous_within_at (λ r, B x + r * (x - a)) (Ioi 0) 0, from continuous_within_at_const.add (continuous_within_at_id.mul continuous_within_at_const), convert continuous_within_at_const.closure_le _ this (Hr x hx); simp [closure_Ioi] end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf (λ x hx r hr, (hf' x hx).liminf_right_slope_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x ≤ B' x` on `[a, b)`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_le_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, f' x ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary hf ha hB hB' $ assume x hx r hr, (hf' x hx).liminf_right_slope_le (lt_of_le_of_lt (bound x hx) hr) /-! ### Vector-valued functions `f : ℝ → E` -/ section variables {f : ℝ → E} {a b : ℝ} /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `B` has right derivative at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(∥f z∥ - ∥f x∥) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. -/ lemma image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary {E : Type*} [normed_group E] {f : ℝ → E} {f' : ℝ → ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' (continuous_norm.comp_continuous_on hf) hf' ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary hf (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ioi x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary (continuous_norm.comp_continuous_on hf) ha hB hB' $ (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le (lt_of_le_of_lt (bound x hx) hr)) /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_le_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- A function on `[a, b]` with the norm of the right derivative bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`. -/ theorem norm_image_sub_le_of_norm_deriv_right_le_segment {f' : ℝ → E} {C : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ioi x) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin let g := λ x, f x - f a, have hg : continuous_on g (Icc a b), from hf.sub continuous_on_const, have hg' : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ioi x) x, { assume x hx, simpa using (hf' x hx).sub (has_deriv_within_at_const _ _ _) }, let B := λ x, C * (x - a), have hB : ∀ x, has_deriv_at B C x, { assume x, simpa using (has_deriv_at_const x C).mul ((has_deriv_at_id x).sub (has_deriv_at_const x a)) }, convert image_norm_le_of_norm_deriv_right_le_deriv_boundary hg hg' _ hB bound, { simp only [g, B] }, { simp only [g, B], rw [sub_self, _root_.norm_zero, sub_self, mul_zero] } end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc a b, has_deriv_within_at f (f' x) (Icc a b) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_right_le_segment (λ x hx, (hf x hx).continuous_within_at) (λ x hx, _) bound, apply (hf x $ Ico_subset_Icc_self hx).nhds_within, exact Icc_mem_nhds_within_Ioi hx end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment {C : ℝ} (hf : differentiable_on ℝ f (Icc a b)) (bound : ∀x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_le_segment' _ bound, exact λ x hx, (hf x hx).has_deriv_within_at end /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc (0:ℝ) 1, has_deriv_within_at f (f' x) (Icc (0:ℝ) 1) x) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥f' x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment' hf bound 1 (right_mem_Icc.2 zero_le_one) /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01 {C : ℝ} (hf : differentiable_on ℝ f (Icc (0:ℝ) 1)) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥deriv_within f (Icc (0:ℝ) 1) x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment hf bound 1 (right_mem_Icc.2 zero_le_one) end /-! ### Vector-valued functions `f : E → F` -/ /-- The mean value theorem on a convex set: if the derivative of a function is bounded by C, then the function is C-Lipschitz -/ theorem convex.norm_image_sub_le_of_norm_deriv_le {f : E → F} {C : ℝ} {s : set E} {x y : E} (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥fderiv_within ℝ f s x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := begin /- By composition with t ↦ x + t • (y-x), we reduce to a statement for functions defined on [0,1], for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`. We just have to check the differentiability of the composition and bounds on its derivative, which is straightforward but tedious for lack of automation. -/ have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs), set g : ℝ → E := λ t, x + t • (y - x), have Dg : ∀ t, has_deriv_at g (y-x) t, { assume t, simpa only [one_smul] using ((has_deriv_at_id t).smul_const (y - x)).const_add x }, have segm : Icc 0 1 ⊆ g ⁻¹' s, { rw [← image_subset_iff, ← segment_eq_image'], apply hs.segment_subset xs ys }, have : f x = f (g 0), by { simp only [g], rw [zero_smul, add_zero] }, rw this, have : f y = f (g 1), by { simp only [g], rw [one_smul, add_sub_cancel'_right] }, rw this, have D2: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) ((fderiv_within ℝ f s (g t) : E → F) (y-x)) (Icc (0:ℝ) 1) t, { intros t ht, exact (hf (g t) $ segm ht).has_fderiv_within_at.comp_has_deriv_within_at _ (Dg t).has_deriv_within_at segm }, apply norm_image_sub_le_of_norm_deriv_le_segment_01' D2, assume t ht, refine le_trans (le_op_norm _ _) (mul_le_mul_of_nonneg_right _ (norm_nonneg _)), exact bound (g t) (segm $ Ico_subset_Icc_self ht) end /-- If a function has zero Fréchet derivative at every point of a convex set, then it is a constant on this set. -/ theorem convex.is_const_of_fderiv_within_eq_zero {s : set E} (hs : convex s) {f : E → F} (hf : differentiable_on ℝ f s) (hf' : ∀ x ∈ s, fderiv_within ℝ f s x = 0) {x y : E} (hx : x ∈ s) (hy : y ∈ s) : f x = f y := have bound : ∀ x ∈ s, ∥fderiv_within ℝ f s x∥ ≤ 0, from λ x hx, by simp only [hf' x hx, _root_.norm_zero], by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm] using hs.norm_image_sub_le_of_norm_deriv_le hf bound hx hy theorem is_const_of_fderiv_eq_zero {f : E → F} (hf : differentiable ℝ f) (hf' : ∀ x, fderiv ℝ f x = 0) (x y : E) : f x = f y := convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on (λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial /-! ### Functions `[a, b] → ℝ`. -/ section interval -- Declare all variables here to make sure they come in a correct order variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b)) (g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hgd : differentiable_on ℝ g (Ioo a b)) include hab hfc hff' hgc hgg' /-- Cauchy's Mean Value Theorem, `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c := begin let h := λ x, (g b - g a) * f x - (f b - f a) * g x, have hI : h a = h b, { simp only [h], ring }, let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)), have hhc : continuous_on h (Icc a b), from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc), rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end omit hgc hgg' /-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) := begin rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff' id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩, use [c, cmem], simp only [_root_.id, pi.one_apply, mul_one] at hc, rw [← hc, mul_div_cancel_left], exact ne_of_gt (sub_pos.2 hab) end omit hff' /-- Cauchy's Mean Value Theorem, `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) g (deriv g) hgc (λ x hx, ((hgd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) /-- Lagrange's Mean Value Theorem, `deriv` version. -/ lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) := exists_has_deriv_at_eq_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ mem_nhds_sets is_open_Ioo hx).has_deriv_at) end interval /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then `f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) : ∀ x y ∈ D, x < y → C * (y - x) < f y - f x := begin assume x y hx hy hxy, have hxyD : Icc x y ⊆ D, from convex_real_iff.1 hD hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) }, exact (lt_div_iff (sub_pos.2 hxy)).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than `C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/ theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) : C * (y - x) < f y - f x := convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_gt x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then `f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x := begin assume x y hx hy hxy, cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero], have hxyD : Icc x y ⊆ D, from convex_real_iff.1 hD hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'), have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) }, exact (le_div_iff (sub_pos.2 hxy')).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/ theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) : C * (y - x) ≤ f y - f x := convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_ge x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) : ∀ x y ∈ D, x < y → f y - f x < C * (y - x) := begin assume x y hx hy hxy, have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x, { assume x hx, rw [deriv_neg, neg_lt_neg_iff], exact lt_hf' x hx }, simpa [-neg_lt_neg_iff] using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/ theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) : f y - f x < C * (y - x) := convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on (λ x _, lt_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then `f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) : ∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) := begin assume x y hx hy hxy, have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x, { assume x hx, rw [deriv_neg, neg_le_neg_iff], exact le_hf' x hx }, simpa [-neg_le_neg_iff] using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/ theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) : f y - f x ≤ C * (y - x) := convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on (λ x _, le_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then `f` is a strictly monotonically increasing function on `D`. -/ theorem convex.strict_mono_of_deriv_pos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_pos : ∀ x ∈ interior D, 0 < deriv f x) : ∀ x y ∈ D, x < y → f x < f y := by simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf hf' hf'_pos /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then `f` is a strictly monotonically increasing function. -/ theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_pos : ∀ x, 0 < deriv f x) : strict_mono f := λ x y hxy, convex_univ.strict_mono_of_deriv_pos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_pos x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then `f` is a monotonically increasing function on `D`. -/ theorem convex.mono_of_deriv_nonneg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → f x ≤ f y := by simpa only [zero_mul, sub_nonneg] using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then `f` is a monotonically increasing function. -/ theorem mono_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) : monotone f := λ x y hxy, convex_univ.mono_of_deriv_nonneg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then `f` is a strictly monotonically decreasing function on `D`. -/ theorem convex.strict_antimono_of_deriv_neg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_neg : ∀ x ∈ interior D, deriv f x < 0) : ∀ x y ∈ D, x < y → f y < f x := by simpa only [zero_mul, sub_lt_zero] using hD.image_sub_lt_mul_sub_of_deriv_lt hf hf' hf'_neg /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then `f` is a strictly monotonically decreasing function. -/ theorem strict_antimono_of_deriv_neg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x < 0) : ∀ ⦃x y⦄, x < y → f y < f x := λ x y hxy, convex_univ.strict_antimono_of_deriv_neg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then `f` is a monotonically decreasing function on `D`. -/ theorem convex.antimono_of_deriv_nonpos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) : ∀ x y ∈ D, x ≤ y → f y ≤ f x := by simpa only [zero_mul, sub_nonpos] using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then `f` is a monotonically decreasing function. -/ theorem antimono_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) : ∀ ⦃x y⦄, x ≤ y → f y ≤ f x := λ x y hxy, convex_univ.antimono_of_deriv_nonpos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv_mono {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : ∀ x y ∈ interior D, x ≤ y → deriv f x ≤ deriv f y) : convex_on D f := convex_on_real_of_slope_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from convex_real_iff.1 hD hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono a b (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (le_of_lt $ lt_trans hay hyb) end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv_mono {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : monotone (deriv f)) : convex_on univ f := convex_on_of_deriv_mono convex_univ hf.continuous.continuous_on hf.differentiable_on (λ x y _ _ h, hf'_mono h) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) : convex_on D f := convex_on_of_deriv_mono hD hf hf' $ assume x y hx hy hxy, hD.interior.mono_of_deriv_nonneg hf''.continuous_on (by rwa [interior_interior]) (by rwa [interior_interior]) _ _ hx hy hxy /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f x)) : convex_on univ f := convex_on_of_deriv2_nonneg convex_univ hf'.continuous.continuous_on hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonneg x)
4352f92380e17fc824707ce2b8dc3e8155d1809e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/free_module/pid.lean
bc89bc4ca277797a1d78b5531fe173385191a870
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,523
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 linear_algebra.finsupp_vector_space import ring_theory.principal_ideal_domain import ring_theory.finiteness /-! # Free modules over PID A free `R`-module `M` is a module with a basis over `R`, equivalently it is an `R`-module linearly equivalent to `ι →₀ R` for some `ι`. This file proves a submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain (PID), i.e. we have instances `[is_domain R] [is_principal_ideal_ring R]`. We express "free `R`-module of finite rank" as a module `M` which has a basis `b : ι → R`, where `ι` is a `fintype`. We call the cardinality of `ι` the rank of `M` in this file; it would be equal to `finrank R M` if `R` is a field and `M` is a vector space. ## Main results In this section, `M` is a free and finitely generated `R`-module, and `N` is a submodule of `M`. - `submodule.induction_on_rank`: if `P` holds for `⊥ : submodule R M` and if `P N` follows from `P N'` for all `N'` that are of lower rank, then `P` holds on all submodules - `submodule.exists_basis_of_pid`: if `R` is a PID, then `N : submodule R M` is free and finitely generated. This is the first part of the structure theorem for modules. - `submodule.smith_normal_form`: if `R` is a PID, then `M` has a basis `bM` and `N` has a basis `bN` such that `bN i = a i • bM i`. Equivalently, a linear map `f : M →ₗ M` with `range f = N` can be written as a matrix in Smith normal form, a diagonal matrix with the coefficients `a i` along the diagonal. ## Tags free module, finitely generated module, rank, structure theorem -/ open_locale big_operators universes u v section ring variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] variables {ι : Type*} (b : basis ι R M) open submodule.is_principal submodule lemma eq_bot_of_generator_maximal_map_eq_zero (b : basis ι R M) {N : submodule R M} {ϕ : M →ₗ[R] R} (hϕ : ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ) [(N.map ϕ).is_principal] (hgen : generator (N.map ϕ) = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine b.ext_elem (λ i, _), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], exact (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr) bot_le) _ ⟨x, hx, rfl⟩ end lemma eq_bot_of_generator_maximal_submodule_image_eq_zero {N O : submodule R M} (b : basis ι R O) (hNO : N ≤ O) {ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N) [(ϕ.submodule_image N).is_principal] (hgen : generator (ϕ.submodule_image N) = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine congr_arg coe (show (⟨x, hNO hx⟩ : O) = 0, from b.ext_elem (λ i, _)), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], refine (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i) ∘ₗ ↑b.repr) bot_le) _ _, exact (linear_map.mem_submodule_image_of_le hNO).mpr ⟨x, hx, rfl⟩ end end ring section is_domain variables {ι : Type*} {R : Type*} [comm_ring R] [is_domain R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open submodule.is_principal set submodule lemma dvd_generator_iff {I : ideal R} [I.is_principal] {x : R} (hx : x ∈ I) : x ∣ generator I ↔ I = ideal.span {x} := begin conv_rhs { rw [← span_singleton_generator I] }, erw [ideal.span_singleton_eq_span_singleton, ← dvd_dvd_iff_associated, ← mem_iff_generator_dvd], exact ⟨λ h, ⟨hx, h⟩, λ h, h.2⟩ end end is_domain section principal_ideal_domain open submodule.is_principal set submodule variables {ι : Type*} {R : Type*} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open submodule.is_principal lemma generator_maximal_submodule_image_dvd {N O : submodule R M} (hNO : N ≤ O) {ϕ : O →ₗ[R] R} (hϕ : ∀ (ψ : O →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N) [(ϕ.submodule_image N).is_principal] (y : M) (yN : y ∈ N) (ϕy_eq : ϕ ⟨y, hNO yN⟩ = generator (ϕ.submodule_image N)) (ψ : O →ₗ[R] R) : generator (ϕ.submodule_image N) ∣ ψ ⟨y, hNO yN⟩ := begin let a : R := generator (ϕ.submodule_image N), let d : R := is_principal.generator (submodule.span R {a, ψ ⟨y, hNO yN⟩}), have d_dvd_left : d ∣ a := (mem_iff_generator_dvd _).mp (subset_span (mem_insert _ _)), have d_dvd_right : d ∣ ψ ⟨y, hNO yN⟩ := (mem_iff_generator_dvd _).mp (subset_span (mem_insert_of_mem _ (mem_singleton _))), refine dvd_trans _ d_dvd_right, rw [dvd_generator_iff, ideal.span, ← span_singleton_generator (submodule.span R {a, ψ ⟨y, hNO yN⟩})], obtain ⟨r₁, r₂, d_eq⟩ : ∃ r₁ r₂ : R, d = r₁ * a + r₂ * ψ ⟨y, hNO yN⟩, { obtain ⟨r₁, r₂', hr₂', hr₁⟩ := mem_span_insert.mp (is_principal.generator_mem (submodule.span R {a, ψ ⟨y, hNO yN⟩})), obtain ⟨r₂, rfl⟩ := mem_span_singleton.mp hr₂', exact ⟨r₁, r₂, hr₁⟩ }, let ψ' : O →ₗ[R] R := r₁ • ϕ + r₂ • ψ, have : span R {d} ≤ ψ'.submodule_image N, { rw [span_le, singleton_subset_iff, set_like.mem_coe, linear_map.mem_submodule_image_of_le hNO], refine ⟨y, yN, _⟩, change r₁ * ϕ ⟨y, hNO yN⟩ + r₂ * ψ ⟨y, hNO yN⟩ = d, rw [d_eq, ϕy_eq] }, refine le_antisymm (this.trans (le_of_eq _)) (ideal.span_singleton_le_span_singleton.mpr d_dvd_left), rw span_singleton_generator, refine hϕ ψ' (le_trans _ this), rw [← span_singleton_generator (ϕ.submodule_image N)], exact ideal.span_singleton_le_span_singleton.mpr d_dvd_left, { exact subset_span (mem_insert _ _) } end /-- The induction hypothesis of `submodule.basis_of_pid` and `submodule.smith_normal_form`. Basically, it says: let `N ≤ M` be a pair of submodules, then we can find a pair of submodules `N' ≤ M'` of strictly smaller rank, whose basis we can extend to get a basis of `N` and `M`. Moreover, if the basis for `M'` is up to scalars a basis for `N'`, then the basis we find for `M` is up to scalars a basis for `N`. For `basis_of_pid` we only need the first half and can fix `M = ⊤`, for `smith_normal_form` we need the full statement, but must also feed in a basis for `M` using `basis_of_pid` to keep the induction going. -/ lemma submodule.basis_of_pid_aux [fintype ι] {O : Type*} [add_comm_group O] [module R O] (M N : submodule R O) (b'M : basis ι R M) (N_bot : N ≠ ⊥) (N_le_M : N ≤ M) : ∃ (y ∈ M) (a : R) (hay : a • y ∈ N) (M' ≤ M) (N' ≤ N) (N'_le_M' : N' ≤ M') (y_ortho_M' : ∀ (c : R) (z : O), z ∈ M' → c • y + z = 0 → c = 0) (ay_ortho_N' : ∀ (c : R) (z : O), z ∈ N' → c • a • y + z = 0 → c = 0), ∀ (n') (bN' : basis (fin n') R N'), ∃ (bN : basis (fin (n' + 1)) R N), ∀ (m') (hn'm' : n' ≤ m') (bM' : basis (fin m') R M'), ∃ (hnm : (n' + 1) ≤ (m' + 1)) (bM : basis (fin (m' + 1)) R M), ∀ (as : fin n' → R) (h : ∀ (i : fin n'), (bN' i : O) = as i • (bM' (fin.cast_le hn'm' i) : O)), ∃ (as' : fin (n' + 1) → R), ∀ (i : fin (n' + 1)), (bN i : O) = as' i • (bM (fin.cast_le hnm i) : O) := begin -- Let `ϕ` be a maximal projection of `M` onto `R`, in the sense that there is -- no `ψ` whose image of `N` is larger than `ϕ`'s image of `N`. have : ∃ ϕ : M →ₗ[R] R, ∀ (ψ : M →ₗ[R] R), ϕ.submodule_image N ≤ ψ.submodule_image N → ψ.submodule_image N = ϕ.submodule_image N, { obtain ⟨P, P_eq, P_max⟩ := set_has_maximal_iff_noetherian.mpr (infer_instance : is_noetherian R R) _ (show (set.range (λ ψ : M →ₗ[R] R, ψ.submodule_image N)).nonempty, from ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩), obtain ⟨ϕ, rfl⟩ := set.mem_range.mp P_eq, exact ⟨ϕ, λ ψ hψ, P_max _ ⟨_, rfl⟩ hψ⟩ }, let ϕ := this.some, have ϕ_max := this.some_spec, -- Since `ϕ(N)` is a `R`-submodule of the PID `R`, -- it is principal and generated by some `a`. let a := generator (ϕ.submodule_image N), have a_mem : a ∈ ϕ.submodule_image N := generator_mem _, -- If `a` is zero, then the submodule is trivial. So let's assume `a ≠ 0`, `N ≠ ⊥`. by_cases a_zero : a = 0, { have := eq_bot_of_generator_maximal_submodule_image_eq_zero b'M N_le_M ϕ_max a_zero, contradiction }, -- We claim that `ϕ⁻¹ a = y` can be taken as basis element of `N`. obtain ⟨y, yN, ϕy_eq⟩ := (linear_map.mem_submodule_image_of_le N_le_M).mp a_mem, have ϕy_ne_zero : ϕ ⟨y, N_le_M yN⟩ ≠ 0 := λ h, a_zero (ϕy_eq.symm.trans h), -- Write `y` as `a • y'` for some `y'`. have hdvd : ∀ i, a ∣ b'M.coord i ⟨y, N_le_M yN⟩ := λ i, generator_maximal_submodule_image_dvd N_le_M ϕ_max y yN ϕy_eq (b'M.coord i), choose c hc using hdvd, let y' : O := ∑ i, c i • b'M i, have y'M : y' ∈ M := M.sum_mem (λ i _, M.smul_mem (c i) (b'M i).2), have mk_y' : (⟨y', y'M⟩ : M) = ∑ i, c i • b'M i := subtype.ext (show y' = M.subtype _, by { simp only [linear_map.map_sum, linear_map.map_smul], refl }), have a_smul_y' : a • y' = y, { refine congr_arg coe (show (a • ⟨y', y'M⟩ : M) = ⟨y, N_le_M yN⟩, from _), rw [← b'M.sum_repr ⟨y, N_le_M yN⟩, mk_y', finset.smul_sum], refine finset.sum_congr rfl (λ i _, _), rw [← mul_smul, ← hc], refl }, -- We found an `y` and an `a`! refine ⟨y', y'M, a, a_smul_y'.symm ▸ yN, _⟩, have ϕy'_eq : ϕ ⟨y', y'M⟩ = 1 := mul_left_cancel₀ a_zero (calc a • ϕ ⟨y', y'M⟩ = ϕ ⟨a • y', _⟩ : (ϕ.map_smul a ⟨y', y'M⟩).symm ... = ϕ ⟨y, N_le_M yN⟩ : by simp only [a_smul_y'] ... = a : ϕy_eq ... = a * 1 : (mul_one a).symm), have ϕy'_ne_zero : ϕ ⟨y', y'M⟩ ≠ 0 := by simpa only [ϕy'_eq] using one_ne_zero, -- `M' := ker (ϕ : M → R)` is smaller than `M` and `N' := ker (ϕ : N → R)` is smaller than `N`. let M' : submodule R O := ϕ.ker.map M.subtype, let N' : submodule R O := (ϕ.comp (of_le N_le_M)).ker.map N.subtype, have M'_le_M : M' ≤ M := M.map_subtype_le ϕ.ker, have N'_le_M' : N' ≤ M', { intros x hx, simp only [mem_map, linear_map.mem_ker] at hx ⊢, obtain ⟨⟨x, xN⟩, hx, rfl⟩ := hx, exact ⟨⟨x, N_le_M xN⟩, hx, rfl⟩ }, have N'_le_N : N' ≤ N := N.map_subtype_le (ϕ.comp (of_le N_le_M)).ker, -- So fill in those results as well. refine ⟨M', M'_le_M, N', N'_le_N, N'_le_M', _⟩, -- Note that `y'` is orthogonal to `M'`. have y'_ortho_M' : ∀ (c : R) z ∈ M', c • y' + z = 0 → c = 0, { intros c x xM' hc, obtain ⟨⟨x, xM⟩, hx', rfl⟩ := submodule.mem_map.mp xM', rw linear_map.mem_ker at hx', have hc' : (c • ⟨y', y'M⟩ + ⟨x, xM⟩ : M) = 0 := subtype.coe_injective hc, simpa only [linear_map.map_add, linear_map.map_zero, linear_map.map_smul, smul_eq_mul, add_zero, mul_eq_zero, ϕy'_ne_zero, hx', or_false] using congr_arg ϕ hc' }, -- And `a • y'` is orthogonal to `N'`. have ay'_ortho_N' : ∀ (c : R) z ∈ N', c • a • y' + z = 0 → c = 0, { intros c z zN' hc, refine (mul_eq_zero.mp (y'_ortho_M' (a * c) z (N'_le_M' zN') _)).resolve_left a_zero, rw [mul_comm, mul_smul, hc] }, -- So we can extend a basis for `N'` with `y` refine ⟨y'_ortho_M', ay'_ortho_N', λ n' bN', ⟨_, _⟩⟩, { refine basis.mk_fin_cons_of_le y yN bN' N'_le_N _ _, { intros c z zN' hc, refine ay'_ortho_N' c z zN' _, rwa ← a_smul_y' at hc }, { intros z zN, obtain ⟨b, hb⟩ : _ ∣ ϕ ⟨z, N_le_M zN⟩ := generator_submodule_image_dvd_of_mem N_le_M ϕ zN, refine ⟨-b, submodule.mem_map.mpr ⟨⟨_, N.sub_mem zN (N.smul_mem b yN)⟩, _, _⟩⟩, { refine linear_map.mem_ker.mpr (show ϕ (⟨z, N_le_M zN⟩ - b • ⟨y, N_le_M yN⟩) = 0, from _), rw [linear_map.map_sub, linear_map.map_smul, hb, ϕy_eq, smul_eq_mul, mul_comm, sub_self] }, { simp only [sub_eq_add_neg, neg_smul], refl } } }, -- And extend a basis for `M'` with `y'` intros m' hn'm' bM', refine ⟨nat.succ_le_succ hn'm', _, _⟩, { refine basis.mk_fin_cons_of_le y' y'M bM' M'_le_M y'_ortho_M' _, intros z zM, refine ⟨-ϕ ⟨z, zM⟩, ⟨⟨z, zM⟩ - (ϕ ⟨z, zM⟩) • ⟨y', y'M⟩, linear_map.mem_ker.mpr _, _⟩⟩, { rw [linear_map.map_sub, linear_map.map_smul, ϕy'_eq, smul_eq_mul, mul_one, sub_self] }, { rw [linear_map.map_sub, linear_map.map_smul, sub_eq_add_neg, neg_smul], refl } }, -- It remains to show the extended bases are compatible with each other. intros as h, refine ⟨fin.cons a as, _⟩, intro i, rw [basis.coe_mk_fin_cons_of_le, basis.coe_mk_fin_cons_of_le], refine fin.cases _ (λ i, _) i, { simp only [fin.cons_zero, fin.cast_le_zero], exact a_smul_y'.symm }, { rw fin.cast_le_succ, simp only [fin.cons_succ, coe_of_le, h i] } end /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. This is a `lemma` to make the induction a bit easier. To actually access the basis, see `submodule.basis_of_pid`. See also the stronger version `submodule.smith_normal_form`. -/ lemma submodule.nonempty_basis_of_pid {ι : Type*} [fintype ι] (b : basis ι R M) (N : submodule R M) : ∃ (n : ℕ), nonempty (basis (fin n) R N) := begin haveI := classical.dec_eq M, refine N.induction_on_rank b _ _, intros N ih, let b' := (b.reindex (fintype.equiv_fin ι)).map (linear_equiv.of_top _ rfl).symm, by_cases N_bot : N = ⊥, { subst N_bot, exact ⟨0, ⟨basis.empty _⟩⟩ }, obtain ⟨y, -, a, hay, M', -, N', N'_le_N, -, -, ay_ortho, h'⟩ := submodule.basis_of_pid_aux ⊤ N b' N_bot le_top, obtain ⟨n', ⟨bN'⟩⟩ := ih N' N'_le_N _ hay ay_ortho, obtain ⟨bN, hbN⟩ := h' n' bN', exact ⟨n' + 1, ⟨bN⟩⟩ end /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. See also the stronger version `submodule.smith_normal_form`. -/ noncomputable def submodule.basis_of_pid {ι : Type*} [fintype ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), (basis (fin n) R N) := ⟨_, (N.nonempty_basis_of_pid b).some_spec.some⟩ lemma submodule.basis_of_pid_bot {ι : Type*} [fintype ι] (b : basis ι R M) : submodule.basis_of_pid b ⊥ = ⟨0, basis.empty _⟩ := begin obtain ⟨n, b'⟩ := submodule.basis_of_pid b ⊥, let e : fin n ≃ fin 0 := b'.index_equiv (basis.empty _ : basis (fin 0) R (⊥ : submodule R M)), have : n = 0 := by simpa using fintype.card_eq.mpr ⟨e⟩, subst this, exact sigma.eq rfl (basis.eq_of_apply_eq $ fin_zero_elim) end /-- A submodule inside a free `R`-submodule of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. See also the stronger version `submodule.smith_normal_form_of_le`. -/ noncomputable def submodule.basis_of_pid_of_le {ι : Type*} [fintype ι] {N O : submodule R M} (hNO : N ≤ O) (b : basis ι R O) : Σ (n : ℕ), basis (fin n) R N := let ⟨n, bN'⟩ := submodule.basis_of_pid b (N.comap O.subtype) in ⟨n, bN'.map (submodule.comap_subtype_equiv_of_le hNO)⟩ /-- A submodule inside the span of a linear independent family is a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid_of_le_span {ι : Type*} [fintype ι] {b : ι → M} (hb : linear_independent R b) {N : submodule R M} (le : N ≤ submodule.span R (set.range b)) : Σ (n : ℕ), basis (fin n) R N := submodule.basis_of_pid_of_le le (basis.span hb) variable {M} /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free [fintype ι] {s : ι → M} (hs : span R (range s) = ⊤) [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := begin classical, -- We define `N` as the submodule spanned by a maximal linear independent subfamily of `s` have := exists_maximal_independent R s, let I : set ι := this.some, obtain ⟨indepI : linear_independent R (s ∘ coe : I → M), hI : ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I)⟩ := this.some_spec, let N := span R (range $ (s ∘ coe : I → M)), -- same as `span R (s '' I)` but more convenient let sI : I → N := λ i, ⟨s i.1, subset_span (mem_range_self i)⟩, -- `s` restricted to `I` let sI_basis : basis I R N, -- `s` restricted to `I` is a basis of `N` from basis.span indepI, -- Our first goal is to build `A ≠ 0` such that `A • M ⊆ N` have exists_a : ∀ i : ι, ∃ a : R, a ≠ 0 ∧ a • s i ∈ N, { intro i, by_cases hi : i ∈ I, { use [1, zero_ne_one.symm], rw one_smul, exact subset_span (mem_range_self (⟨i, hi⟩ : I)) }, { simpa [image_eq_range s I] using hI i hi } }, choose a ha ha' using exists_a, let A := ∏ i, a i, have hA : A ≠ 0, { rw finset.prod_ne_zero_iff, simpa using ha }, -- `M ≃ A • M` because `M` is torsion free and `A ≠ 0` let φ : M →ₗ[R] M := linear_map.lsmul R M A, have : φ.ker = ⊥, from linear_map.ker_lsmul hA, let ψ : M ≃ₗ[R] φ.range := linear_equiv.of_injective φ (linear_map.ker_eq_bot.mp this), have : φ.range ≤ N, -- as announced, `A • M ⊆ N` { suffices : ∀ i, φ (s i) ∈ N, { rw [linear_map.range_eq_map, ← hs, φ.map_span_le], rintros _ ⟨i, rfl⟩, apply this }, intro i, calc (∏ j, a j) • s i = (∏ j in {i}ᶜ, a j) • a i • s i : by rw [fintype.prod_eq_prod_compl_mul i, mul_smul] ... ∈ N : N.smul_mem _ (ha' i) }, -- Since a submodule of a free `R`-module is free, we get that `A • M` is free obtain ⟨n, b : basis (fin n) R φ.range⟩ := submodule.basis_of_pid_of_le this sI_basis, -- hence `M` is free. exact ⟨n, b.map ψ.symm⟩ end /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free' [module.finite R M] [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := module.free_of_finite_type_torsion_free module.finite.exists_fin.some_spec.some_spec section smith_normal /-- A Smith normal form basis for a submodule `N` of a module `M` consists of bases for `M` and `N` such that the inclusion map `N → M` can be written as a (rectangular) matrix with `a` along the diagonal: in Smith normal form. -/ @[nolint has_inhabited_instance] structure basis.smith_normal_form (N : submodule R M) (ι : Type*) (n : ℕ) := (bM : basis ι R M) (bN : basis (fin n) R N) (f : fin n ↪ ι) (a : fin n → R) (snf : ∀ i, (bN i : M) = a i • bM (f i)) /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. See `submodule.smith_normal_form_of_le` for a version of this theorem that returns a `basis.smith_normal_form`. This is a strengthening of `submodule.basis_of_pid_of_le`. -/ theorem submodule.exists_smith_normal_form_of_le [fintype ι] (b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) : ∃ (n o : ℕ) (hno : n ≤ o) (bO : basis (fin o) R O) (bN : basis (fin n) R N) (a : fin n → R), ∀ i, (bN i : M) = a i • bO (fin.cast_le hno i) := begin revert N, refine induction_on_rank b _ _ O, intros M ih N N_le_M, obtain ⟨m, b'M⟩ := M.basis_of_pid b, by_cases N_bot : N = ⊥, { subst N_bot, exact ⟨0, m, nat.zero_le _, b'M, basis.empty _, fin_zero_elim, fin_zero_elim⟩ }, obtain ⟨y, hy, a, hay, M', M'_le_M, N', N'_le_N, N'_le_M', y_ortho, ay_ortho, h⟩ := submodule.basis_of_pid_aux M N b'M N_bot N_le_M, obtain ⟨n', m', hn'm', bM', bN', as', has'⟩ := ih M' M'_le_M y hy y_ortho N' N'_le_M', obtain ⟨bN, h'⟩ := h n' bN', obtain ⟨hmn, bM, h''⟩ := h' m' hn'm' bM', obtain ⟨as, has⟩ := h'' as' has', exact ⟨_, _, hmn, bM, bN, as, has⟩ end /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. See `submodule.exists_smith_normal_form_of_le` for a version of this theorem that doesn't need to map `N` into a submodule of `O`. This is a strengthening of `submodule.basis_of_pid_of_le`. -/ noncomputable def submodule.smith_normal_form_of_le [fintype ι] (b : basis ι R M) (N O : submodule R M) (N_le_O : N ≤ O) : Σ (o n : ℕ), basis.smith_normal_form (N.comap O.subtype) (fin o) n := begin choose n o hno bO bN a snf using N.exists_smith_normal_form_of_le b O N_le_O, refine ⟨o, n, bO, bN.map (comap_subtype_equiv_of_le N_le_O).symm, (fin.cast_le hno).to_embedding, a, λ i, _⟩, ext, simp only [snf, basis.map_apply, submodule.comap_subtype_equiv_of_le_symm_apply_coe_coe, submodule.coe_smul_of_tower, rel_embedding.coe_fn_to_embedding] end /-- If `M` is finite free over a PID `R`, then any submodule `N` is free and we can find a basis for `M` and `N` such that the inclusion map is a diagonal matrix in Smith normal form. This is a strengthening of `submodule.basis_of_pid`. See also `ideal.smith_normal_form`, which moreover proves that the dimension of an ideal is the same as the dimension of the whole ring. -/ noncomputable def submodule.smith_normal_form [fintype ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), basis.smith_normal_form N ι n := let ⟨m, n, bM, bN, f, a, snf⟩ := N.smith_normal_form_of_le b ⊤ le_top, bM' := bM.map (linear_equiv.of_top _ rfl), e := bM'.index_equiv b in ⟨n, bM'.reindex e, bN.map (comap_subtype_equiv_of_le le_top), f.trans e.to_embedding, a, λ i, by simp only [snf, basis.map_apply, linear_equiv.of_top_apply, submodule.coe_smul_of_tower, submodule.comap_subtype_equiv_of_le_apply_coe, coe_coe, basis.reindex_apply, equiv.to_embedding_apply, function.embedding.trans_apply, equiv.symm_apply_apply]⟩ /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. See `ideal.exists_smith_normal_form` for a version of this theorem that doesn't need to map `I` into a submodule of `R`. This is a strengthening of `submodule.basis_of_pid`. -/ noncomputable def ideal.smith_normal_form [fintype ι] {S : Type*} [comm_ring S] [is_domain S] [algebra R S] (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : basis.smith_normal_form (I.restrict_scalars R) ι (fintype.card ι) := let ⟨n, bS, bI, f, a, snf⟩ := (I.restrict_scalars R).smith_normal_form b in have eq : _ := ideal.rank_eq bS hI (bI.map ((restrict_scalars_equiv R S S I).restrict_scalars _)), let e : fin n ≃ fin (fintype.card ι) := fintype.equiv_of_card_eq (by rw [eq, fintype.card_fin]) in ⟨bS, bI.reindex e, e.symm.to_embedding.trans f, a ∘ e.symm, λ i, by simp only [snf, basis.coe_reindex, function.embedding.trans_apply, equiv.to_embedding_apply]⟩ /-- If `S` a finite-dimensional ring extension of a PID `R` which is free as an `R`-module, then any nonzero `S`-ideal `I` is free as an `R`-submodule of `S`, and we can find a basis for `S` and `I` such that the inclusion map is a square diagonal matrix. See also `ideal.smith_normal_form` for a version of this theorem that returns a `basis.smith_normal_form`. -/ theorem ideal.exists_smith_normal_form [fintype ι] {S : Type*} [comm_ring S] [is_domain S] [algebra R S] (b : basis ι R S) (I : ideal S) (hI : I ≠ ⊥) : ∃ (b' : basis ι R S) (a : ι → R) (ab' : basis ι R I), ∀ i, (ab' i : S) = a i • b' i := let ⟨bS, bI, f, a, snf⟩ := I.smith_normal_form b hI, e : fin (fintype.card ι) ≃ ι := equiv.of_bijective f ((fintype.bijective_iff_injective_and_card f).mpr ⟨f.injective, fintype.card_fin _⟩) in have fe : ∀ i, f (e.symm i) = i := e.apply_symm_apply, ⟨bS, a ∘ e.symm, (bI.reindex e).map ((restrict_scalars_equiv _ _ _ _).restrict_scalars R), λ i, by simp only [snf, fe, basis.map_apply, linear_equiv.restrict_scalars_apply, submodule.restrict_scalars_equiv_apply, basis.coe_reindex]⟩ end smith_normal end principal_ideal_domain /-- A set of linearly independent vectors in a module `M` over a semiring `S` is also linearly independent over a subring `R` of `K`. -/ lemma linear_independent.restrict_scalars_algebras {R S M ι : Type*} [comm_semiring R] [semiring S] [add_comm_monoid M] [algebra R S] [module R M] [module S M] [is_scalar_tower R S M] (hinj : function.injective (algebra_map R S)) {v : ι → M} (li : linear_independent S v) : linear_independent R v := linear_independent.restrict_scalars (by rwa algebra.algebra_map_eq_smul_one' at hinj) li
5c61643144ffd45f3b6f8211bfbc5cf7f7d47e3f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/field_theory/subfield.lean
d79dd355a8b2a55469d2092dfb27fd1f0a2108cc
[]
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
27,003
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.algebra.basic import Mathlib.PostPort universes u l u_1 v w namespace Mathlib /-! # Subfields Let `K` be a field. This file defines the "bundled" subfield type `subfield K`, a type whose terms correspond to subfields of `K`. This is the preferred way to talk about subfields in mathlib. Unbundled subfields (`s : set K` and `is_subfield s`) are not in this file, and they will ultimately be deprecated. We prove that subfields are a complete lattice, and that you can `map` (pushforward) and `comap` (pull back) them along ring homomorphisms. We define the `closure` construction from `set R` to `subfield R`, sending a subset of `R` to the subfield it generates, and prove that it is a Galois insertion. ## Main definitions Notation used here: `(K : Type u) [field K] (L : Type u) [field L] (f g : K →+* L)` `(A : subfield K) (B : subfield L) (s : set K)` * `subfield R` : the type of subfields of a ring `R`. * `instance : complete_lattice (subfield R)` : the complete lattice structure on the subfields. * `subfield.closure` : subfield closure of a set, i.e., the smallest subfield that includes the set. * `subfield.gi` : `closure : set M → subfield M` and coercion `coe : subfield M → set M` form a `galois_insertion`. * `comap f B : subfield K` : the preimage of a subfield `B` along the ring homomorphism `f` * `map f A : subfield L` : the image of a subfield `A` along the ring homomorphism `f`. * `prod A B : subfield (K × L)` : the product of subfields * `f.field_range : subfield B` : the range of the ring homomorphism `f`. * `eq_locus_field f g : subfield K` : given ring homomorphisms `f g : K →+* R`, the subfield of `K` where `f x = g x` ## Implementation notes A subfield is implemented as a subring which is is closed under `⁻¹`. Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although `∈` is defined as membership of a subfield's underlying set. ## Tags subfield, subfields -/ /-- `subfield R` is the type of subfields of `R`. A subfield of `R` is a subset `s` that is a multiplicative submonoid and an additive subgroup. Note in particular that it shares the same 0 and 1 as R. -/ structure subfield (K : Type u) [field K] extends subring K where inv_mem' : ∀ (x : K), x ∈ carrier → x⁻¹ ∈ carrier /-- Reinterpret a `subfield` as a `subring`. -/ namespace subfield /-- The underlying `add_subgroup` of a subfield. -/ def to_add_subgroup {K : Type u} [field K] (s : subfield K) : add_subgroup K := add_subgroup.mk (add_subgroup.carrier (subring.to_add_subgroup (to_subring s))) sorry sorry sorry /-- The underlying submonoid of a subfield. -/ def to_submonoid {K : Type u} [field K] (s : subfield K) : submonoid K := submonoid.mk (submonoid.carrier (subring.to_submonoid (to_subring s))) sorry sorry protected instance set.has_coe {K : Type u} [field K] : has_coe (subfield K) (set K) := has_coe.mk carrier @[simp] theorem coe_to_subring {K : Type u} [field K] (s : subfield K) : ↑(to_subring s) = ↑s := rfl protected instance has_coe_to_sort {K : Type u} [field K] : has_coe_to_sort (subfield K) := has_coe_to_sort.mk (Type u) fun (S : subfield K) => ↥(carrier S) protected instance has_mem {K : Type u} [field K] : has_mem K (subfield K) := has_mem.mk fun (m : K) (S : subfield K) => m ∈ ↑S @[simp] theorem mem_mk {K : Type u} [field K] (s : set K) (ho : 1 ∈ s) (hm : ∀ {a b : K}, a ∈ s → b ∈ s → a * b ∈ s) (hz : 0 ∈ s) (ha : ∀ {a b : K}, a ∈ s → b ∈ s → a + b ∈ s) (hn : ∀ {x : K}, x ∈ s → -x ∈ s) (hi : ∀ (x : K), x ∈ s → x⁻¹ ∈ s) (x : K) : x ∈ mk s ho hm hz ha hn hi ↔ x ∈ s := iff.rfl @[simp] theorem mem_to_subring {K : Type u} [field K] (s : subfield K) (x : K) : x ∈ to_subring s ↔ x ∈ s := iff.rfl end subfield protected theorem subfield.exists {K : Type u} [field K] {s : subfield K} {p : ↥s → Prop} : (∃ (x : ↥s), p x) ↔ ∃ (x : K), ∃ (H : x ∈ s), p { val := x, property := H } := set_coe.exists protected theorem subfield.forall {K : Type u} [field K] {s : subfield K} {p : ↥s → Prop} : (∀ (x : ↥s), p x) ↔ ∀ (x : K) (H : x ∈ s), p { val := x, property := H } := set_coe.forall /-- A `subring` containing inverses is a `subfield`. -/ def subring.to_subfield {K : Type u} [field K] (s : subring K) (hinv : ∀ (x : K), x ∈ s → x⁻¹ ∈ s) : subfield K := subfield.mk (subring.carrier s) sorry sorry sorry sorry sorry hinv namespace subfield /-- Two subfields are equal if the underlying subsets are equal. -/ theorem ext' {K : Type u} [field K] {s : subfield K} {t : subfield K} (h : ↑s = ↑t) : s = t := sorry /-- Two subfields are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {K : Type u} [field K] {s : subfield K} {t : subfield K} : s = t ↔ ↑s = ↑t := { mp := fun (h : s = t) => h ▸ rfl, mpr := fun (h : ↑s = ↑t) => ext' h } /-- Two subfields are equal if they have the same elements. -/ theorem ext {K : Type u} [field K] {S : subfield K} {T : subfield K} (h : ∀ (x : K), x ∈ S ↔ x ∈ T) : S = T := ext' (set.ext h) /-- A subfield contains the ring's 1. -/ theorem one_mem {K : Type u} [field K] (s : subfield K) : 1 ∈ s := one_mem' s /-- A subfield contains the ring's 0. -/ theorem zero_mem {K : Type u} [field K] (s : subfield K) : 0 ∈ s := zero_mem' s /-- A subfield is closed under multiplication. -/ theorem mul_mem {K : Type u} [field K] (s : subfield K) {x : K} {y : K} : x ∈ s → y ∈ s → x * y ∈ s := mul_mem' s /-- A subfield is closed under addition. -/ theorem add_mem {K : Type u} [field K] (s : subfield K) {x : K} {y : K} : x ∈ s → y ∈ s → x + y ∈ s := add_mem' s /-- A subfield is closed under negation. -/ theorem neg_mem {K : Type u} [field K] (s : subfield K) {x : K} : x ∈ s → -x ∈ s := neg_mem' s /-- A subfield is closed under subtraction. -/ theorem sub_mem {K : Type u} [field K] (s : subfield K) {x : K} {y : K} : x ∈ s → y ∈ s → x - y ∈ s := subring.sub_mem (to_subring s) /-- A subfield is closed under inverses. -/ theorem inv_mem {K : Type u} [field K] (s : subfield K) {x : K} : x ∈ s → x⁻¹ ∈ s := inv_mem' s /-- A subfield is closed under division. -/ theorem div_mem {K : Type u} [field K] (s : subfield K) {x : K} {y : K} (hx : x ∈ s) (hy : y ∈ s) : x / y ∈ s := eq.mpr (id (Eq._oldrec (Eq.refl (x / y ∈ s)) (div_eq_mul_inv x y))) (mul_mem s hx (inv_mem s hy)) /-- Product of a list of elements in a subfield is in the subfield. -/ theorem list_prod_mem {K : Type u} [field K] (s : subfield K) {l : List K} : (∀ (x : K), x ∈ l → x ∈ s) → list.prod l ∈ s := submonoid.list_prod_mem (to_submonoid s) /-- Sum of a list of elements in a subfield is in the subfield. -/ theorem list_sum_mem {K : Type u} [field K] (s : subfield K) {l : List K} : (∀ (x : K), x ∈ l → x ∈ s) → list.sum l ∈ s := add_subgroup.list_sum_mem (to_add_subgroup s) /-- Product of a multiset of elements in a subfield is in the subfield. -/ theorem multiset_prod_mem {K : Type u} [field K] (s : subfield K) (m : multiset K) : (∀ (a : K), a ∈ m → a ∈ s) → multiset.prod m ∈ s := submonoid.multiset_prod_mem (to_submonoid s) m /-- Sum of a multiset of elements in a `subfield` is in the `subfield`. -/ theorem multiset_sum_mem {K : Type u} [field K] (s : subfield K) (m : multiset K) : (∀ (a : K), a ∈ m → a ∈ s) → multiset.sum m ∈ s := add_subgroup.multiset_sum_mem (to_add_subgroup s) m /-- Product of elements of a subfield indexed by a `finset` is in the subfield. -/ theorem prod_mem {K : Type u} [field K] (s : subfield K) {ι : Type u_1} {t : finset ι} {f : ι → K} (h : ∀ (c : ι), c ∈ t → f c ∈ s) : (finset.prod t fun (i : ι) => f i) ∈ s := submonoid.prod_mem (to_submonoid s) h /-- Sum of elements in a `subfield` indexed by a `finset` is in the `subfield`. -/ theorem sum_mem {K : Type u} [field K] (s : subfield K) {ι : Type u_1} {t : finset ι} {f : ι → K} (h : ∀ (c : ι), c ∈ t → f c ∈ s) : (finset.sum t fun (i : ι) => f i) ∈ s := add_subgroup.sum_mem (to_add_subgroup s) h theorem pow_mem {K : Type u} [field K] (s : subfield K) {x : K} (hx : x ∈ s) (n : ℕ) : x ^ n ∈ s := submonoid.pow_mem (to_submonoid s) hx n theorem gsmul_mem {K : Type u} [field K] (s : subfield K) {x : K} (hx : x ∈ s) (n : ℤ) : n •ℤ x ∈ s := add_subgroup.gsmul_mem (to_add_subgroup s) hx n theorem coe_int_mem {K : Type u} [field K] (s : subfield K) (n : ℤ) : ↑n ∈ s := sorry /-- A subfield inherits a field structure -/ protected instance to_field {K : Type u} [field K] (s : subfield K) : field ↥s := field.mk integral_domain.add sorry integral_domain.zero sorry sorry integral_domain.neg integral_domain.sub sorry sorry integral_domain.mul sorry integral_domain.one sorry sorry sorry sorry sorry (fun (x : ↥s) => { val := ↑x⁻¹, property := sorry }) sorry sorry sorry @[simp] theorem coe_add {K : Type u} [field K] (s : subfield K) (x : ↥s) (y : ↥s) : ↑(x + y) = ↑x + ↑y := rfl @[simp] theorem coe_neg {K : Type u} [field K] (s : subfield K) (x : ↥s) : ↑(-x) = -↑x := rfl @[simp] theorem coe_mul {K : Type u} [field K] (s : subfield K) (x : ↥s) (y : ↥s) : ↑(x * y) = ↑x * ↑y := rfl @[simp] theorem coe_inv {K : Type u} [field K] (s : subfield K) (x : ↥s) : ↑(x⁻¹) = (↑x⁻¹) := rfl @[simp] theorem coe_zero {K : Type u} [field K] (s : subfield K) : ↑0 = 0 := rfl @[simp] theorem coe_one {K : Type u} [field K] (s : subfield K) : ↑1 = 1 := rfl /-- The embedding from a subfield of the field `K` to `K`. -/ def subtype {K : Type u} [field K] (s : subfield K) : ↥s →+* K := ring_hom.mk coe sorry sorry sorry sorry protected instance to_algebra {K : Type u} [field K] (s : subfield K) : algebra (↥s) K := ring_hom.to_algebra (subtype s) @[simp] theorem coe_subtype {K : Type u} [field K] (s : subfield K) : ⇑(subtype s) = coe := rfl /-! # Partial order -/ protected instance partial_order {K : Type u} [field K] : partial_order (subfield K) := partial_order.mk (fun (s t : subfield K) => ∀ {x : K}, x ∈ s → x ∈ t) partial_order.lt sorry sorry sorry theorem le_def {K : Type u} [field K] {s : subfield K} {t : subfield K} : s ≤ t ↔ ∀ {x : K}, x ∈ s → x ∈ t := iff.rfl @[simp] theorem coe_subset_coe {K : Type u} [field K] {s : subfield K} {t : subfield K} : ↑s ⊆ ↑t ↔ s ≤ t := iff.rfl @[simp] theorem coe_ssubset_coe {K : Type u} [field K] {s : subfield K} {t : subfield K} : ↑s ⊂ ↑t ↔ s < t := iff.rfl @[simp] theorem mem_coe {K : Type u} [field K] {s : subfield K} {m : K} : m ∈ ↑s ↔ m ∈ s := iff.rfl @[simp] theorem coe_coe {K : Type u} [field K] (s : subfield K) : ↥↑s = ↥s := rfl @[simp] theorem mem_to_submonoid {K : Type u} [field K] {s : subfield K} {x : K} : x ∈ to_submonoid s ↔ x ∈ s := iff.rfl @[simp] theorem coe_to_submonoid {K : Type u} [field K] (s : subfield K) : ↑(to_submonoid s) = ↑s := rfl @[simp] theorem mem_to_add_subgroup {K : Type u} [field K] {s : subfield K} {x : K} : x ∈ to_add_subgroup s ↔ x ∈ s := iff.rfl @[simp] theorem coe_to_add_subgroup {K : Type u} [field K] (s : subfield K) : ↑(to_add_subgroup s) = ↑s := rfl /-! # top -/ /-- The subfield of `K` containing all elements of `K`. -/ protected instance has_top {K : Type u} [field K] : has_top (subfield K) := has_top.mk (mk (subring.carrier ⊤) sorry sorry sorry sorry sorry sorry) protected instance inhabited {K : Type u} [field K] : Inhabited (subfield K) := { default := ⊤ } @[simp] theorem mem_top {K : Type u} [field K] (x : K) : x ∈ ⊤ := set.mem_univ x @[simp] theorem coe_top {K : Type u} [field K] : ↑⊤ = set.univ := rfl /-! # comap -/ /-- The preimage of a subfield along a ring homomorphism is a subfield. -/ def comap {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (s : subfield L) : subfield K := mk (subring.carrier (subring.comap f (to_subring s))) sorry sorry sorry sorry sorry sorry @[simp] theorem coe_comap {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (s : subfield L) : ↑(comap f s) = ⇑f ⁻¹' ↑s := rfl @[simp] theorem mem_comap {K : Type u} {L : Type v} [field K] [field L] {s : subfield L} {f : K →+* L} {x : K} : x ∈ comap f s ↔ coe_fn f x ∈ s := iff.rfl theorem comap_comap {K : Type u} {L : Type v} {M : Type w} [field K] [field L] [field M] (s : subfield M) (g : L →+* M) (f : K →+* L) : comap f (comap g s) = comap (ring_hom.comp g f) s := rfl /-! # map -/ /-- The image of a subfield along a ring homomorphism is a subfield. -/ def map {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (s : subfield K) : subfield L := mk (subring.carrier (subring.map f (to_subring s))) sorry sorry sorry sorry sorry sorry @[simp] theorem coe_map {K : Type u} {L : Type v} [field K] [field L] (s : subfield K) (f : K →+* L) : ↑(map f s) = ⇑f '' ↑s := rfl @[simp] theorem mem_map {K : Type u} {L : Type v} [field K] [field L] {f : K →+* L} {s : subfield K} {y : L} : y ∈ map f s ↔ ∃ (x : K), ∃ (H : x ∈ s), coe_fn f x = y := set.mem_image_iff_bex theorem map_map {K : Type u} {L : Type v} {M : Type w} [field K] [field L] [field M] (s : subfield K) (g : L →+* M) (f : K →+* L) : map g (map f s) = map (ring_hom.comp g f) s := ext' (set.image_image (fun (a : L) => coe_fn g a) (fun (a : K) => coe_fn f a) (subring.carrier (to_subring s))) theorem map_le_iff_le_comap {K : Type u} {L : Type v} [field K] [field L] {f : K →+* L} {s : subfield K} {t : subfield L} : map f s ≤ t ↔ s ≤ comap f t := set.image_subset_iff theorem gc_map_comap {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) : galois_connection (map f) (comap f) := fun (S : subfield K) (T : subfield L) => map_le_iff_le_comap end subfield namespace ring_hom /-! # range -/ /-- The range of a ring homomorphism, as a subfield of the target. -/ def field_range {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) : subfield L := subfield.map f ⊤ @[simp] theorem coe_field_range {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) : ↑(field_range f) = set.range ⇑f := set.image_univ @[simp] theorem mem_field_range {K : Type u} {L : Type v} [field K] [field L] {f : K →+* L} {y : L} : y ∈ range f ↔ ∃ (x : K), coe_fn f x = y := sorry theorem map_field_range {K : Type u} {L : Type v} {M : Type w} [field K] [field L] [field M] (g : L →+* M) (f : K →+* L) : subfield.map g (field_range f) = field_range (comp g f) := subfield.map_map ⊤ g f end ring_hom namespace subfield /-! # inf -/ /-- The inf of two subfields is their intersection. -/ protected instance has_inf {K : Type u} [field K] : has_inf (subfield K) := has_inf.mk fun (s t : subfield K) => mk (subring.carrier (to_subring s ⊓ to_subring t)) sorry sorry sorry sorry sorry sorry @[simp] theorem coe_inf {K : Type u} [field K] (p : subfield K) (p' : subfield K) : ↑(p ⊓ p') = ↑p ∩ ↑p' := rfl @[simp] theorem mem_inf {K : Type u} [field K] {p : subfield K} {p' : subfield K} {x : K} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl protected instance has_Inf {K : Type u} [field K] : has_Inf (subfield K) := has_Inf.mk fun (S : set (subfield K)) => mk (subring.carrier (Inf (to_subring '' S))) sorry sorry sorry sorry sorry sorry @[simp] theorem coe_Inf {K : Type u} [field K] (S : set (subfield K)) : ↑(Inf S) = set.Inter fun (s : subfield K) => set.Inter fun (H : s ∈ S) => ↑s := sorry theorem mem_Inf {K : Type u} [field K] {S : set (subfield K)} {x : K} : x ∈ Inf S ↔ ∀ (p : subfield K), p ∈ S → x ∈ p := sorry @[simp] theorem Inf_to_subring {K : Type u} [field K] (s : set (subfield K)) : to_subring (Inf s) = infi fun (t : subfield K) => infi fun (H : t ∈ s) => to_subring t := sorry theorem is_glb_Inf {K : Type u} [field K] (S : set (subfield K)) : is_glb S (Inf S) := sorry /-- Subfields of a ring form a complete lattice. -/ protected instance complete_lattice {K : Type u} [field K] : complete_lattice (subfield K) := complete_lattice.mk complete_lattice.sup complete_lattice.le complete_lattice.lt sorry sorry sorry sorry sorry sorry has_inf.inf sorry sorry sorry ⊤ sorry complete_lattice.bot sorry complete_lattice.Sup complete_lattice.Inf sorry sorry sorry sorry /-! # subfield closure of a subset -/ /-- The `subfield` generated by a set. -/ def closure {K : Type u} [field K] (s : set K) : subfield K := mk (set_of fun (_x : K) => ∃ (x : K), ∃ (H : x ∈ subring.closure s), ∃ (y : K), ∃ (H : y ∈ subring.closure s), x / y = _x) sorry sorry sorry sorry sorry sorry theorem mem_closure_iff {K : Type u} [field K] {s : set K} {x : K} : x ∈ closure s ↔ ∃ (y : K), ∃ (H : y ∈ subring.closure s), ∃ (z : K), ∃ (H : z ∈ subring.closure s), y / z = x := iff.rfl theorem subring_closure_le {K : Type u} [field K] (s : set K) : subring.closure s ≤ to_subring (closure s) := fun (x : K) (hx : x ∈ subring.closure s) => Exists.intro x (Exists.intro hx (Exists.intro 1 (Exists.intro (subring.one_mem (subring.closure s)) (div_one x)))) /-- The subfield generated by a set includes the set. -/ @[simp] theorem subset_closure {K : Type u} [field K] {s : set K} : s ⊆ ↑(closure s) := set.subset.trans subring.subset_closure (subring_closure_le s) theorem mem_closure {K : Type u} [field K] {x : K} {s : set K} : x ∈ closure s ↔ ∀ (S : subfield K), s ⊆ ↑S → x ∈ S := sorry /-- A subfield `t` includes `closure s` if and only if it includes `s`. -/ @[simp] theorem closure_le {K : Type u} [field K] {s : set K} {t : subfield K} : closure s ≤ t ↔ s ⊆ ↑t := { mp := set.subset.trans subset_closure, mpr := fun (h : s ⊆ ↑t) (x : K) (hx : x ∈ closure s) => iff.mp mem_closure hx t h } /-- Subfield closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ theorem closure_mono {K : Type u} [field K] {s : set K} {t : set K} (h : s ⊆ t) : closure s ≤ closure t := iff.mpr closure_le (set.subset.trans h subset_closure) theorem closure_eq_of_le {K : Type u} [field K] {s : set K} {t : subfield K} (h₁ : s ⊆ ↑t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (iff.mpr closure_le h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1`, and all elements of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements of the closure of `s`. -/ theorem closure_induction {K : Type u} [field K] {s : set K} {p : K → Prop} {x : K} (h : x ∈ closure s) (Hs : ∀ (x : K), x ∈ s → p x) (H1 : p 1) (Hadd : ∀ (x y : K), p x → p y → p (x + y)) (Hneg : ∀ (x : K), p x → p (-x)) (Hinv : ∀ (x : K), p x → p (x⁻¹)) (Hmul : ∀ (x y : K), p x → p y → p (x * y)) : p x := iff.mpr closure_le Hs x h /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi (K : Type u) [field K] : galois_insertion closure coe := galois_insertion.mk (fun (s : set K) (_x : ↑(closure s) ≤ s) => closure s) sorry sorry sorry /-- Closure of a subfield `S` equals `S`. -/ theorem closure_eq {K : Type u} [field K] (s : subfield K) : closure ↑s = s := galois_insertion.l_u_eq (subfield.gi K) s @[simp] theorem closure_empty {K : Type u} [field K] : closure ∅ = ⊥ := galois_connection.l_bot (galois_insertion.gc (subfield.gi K)) @[simp] theorem closure_univ {K : Type u} [field K] : closure set.univ = ⊤ := coe_top ▸ closure_eq ⊤ theorem closure_union {K : Type u} [field K] (s : set K) (t : set K) : closure (s ∪ t) = closure s ⊔ closure t := galois_connection.l_sup (galois_insertion.gc (subfield.gi K)) theorem closure_Union {K : Type u} [field K] {ι : Sort u_1} (s : ι → set K) : closure (set.Union fun (i : ι) => s i) = supr fun (i : ι) => closure (s i) := galois_connection.l_supr (galois_insertion.gc (subfield.gi K)) theorem closure_sUnion {K : Type u} [field K] (s : set (set K)) : closure (⋃₀s) = supr fun (t : set K) => supr fun (H : t ∈ s) => closure t := galois_connection.l_Sup (galois_insertion.gc (subfield.gi K)) theorem map_sup {K : Type u} {L : Type v} [field K] [field L] (s : subfield K) (t : subfield K) (f : K →+* L) : map f (s ⊔ t) = map f s ⊔ map f t := galois_connection.l_sup (gc_map_comap f) theorem map_supr {K : Type u} {L : Type v} [field K] [field L] {ι : Sort u_1} (f : K →+* L) (s : ι → subfield K) : map f (supr s) = supr fun (i : ι) => map f (s i) := galois_connection.l_supr (gc_map_comap f) theorem comap_inf {K : Type u} {L : Type v} [field K] [field L] (s : subfield L) (t : subfield L) (f : K →+* L) : comap f (s ⊓ t) = comap f s ⊓ comap f t := galois_connection.u_inf (gc_map_comap f) theorem comap_infi {K : Type u} {L : Type v} [field K] [field L] {ι : Sort u_1} (f : K →+* L) (s : ι → subfield L) : comap f (infi s) = infi fun (i : ι) => comap f (s i) := galois_connection.u_infi (gc_map_comap f) @[simp] theorem map_bot {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) : map f ⊥ = ⊥ := galois_connection.l_bot (gc_map_comap f) @[simp] theorem comap_top {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) : comap f ⊤ = ⊤ := galois_connection.u_top (gc_map_comap f) /-- The underlying set of a non-empty directed Sup of subfields is just a union of the subfields. Note that this fails without the directedness assumption (the union of two subfields is typically not a subfield) -/ theorem mem_supr_of_directed {K : Type u} [field K] {ι : Sort u_1} [hι : Nonempty ι] {S : ι → subfield K} (hS : directed LessEq S) {x : K} : (x ∈ supr fun (i : ι) => S i) ↔ ∃ (i : ι), x ∈ S i := sorry theorem coe_supr_of_directed {K : Type u} [field K] {ι : Sort u_1} [hι : Nonempty ι] {S : ι → subfield K} (hS : directed LessEq S) : ↑(supr fun (i : ι) => S i) = set.Union fun (i : ι) => ↑(S i) := sorry theorem mem_Sup_of_directed_on {K : Type u} [field K] {S : set (subfield K)} (Sne : set.nonempty S) (hS : directed_on LessEq S) {x : K} : x ∈ Sup S ↔ ∃ (s : subfield K), ∃ (H : s ∈ S), x ∈ s := sorry theorem coe_Sup_of_directed_on {K : Type u} [field K] {S : set (subfield K)} (Sne : set.nonempty S) (hS : directed_on LessEq S) : ↑(Sup S) = set.Union fun (s : subfield K) => set.Union fun (H : s ∈ S) => ↑s := sorry end subfield namespace ring_hom /-- Restrict the codomain of a ring homomorphism to a subfield that includes the range. -/ def cod_restrict_field {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (s : subfield L) (h : ∀ (x : K), coe_fn f x ∈ s) : K →+* ↥s := mk (fun (x : K) => { val := coe_fn f x, property := h x }) sorry sorry sorry sorry /-- Restriction of a ring homomorphism to a subfield of the domain. -/ def restrict_field {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (s : subfield K) : ↥s →+* L := comp f (subfield.subtype s) @[simp] theorem restrict_field_apply {K : Type u} {L : Type v} [field K] [field L] {s : subfield K} (f : K →+* L) (x : ↥s) : coe_fn (restrict_field f s) x = coe_fn f ↑x := rfl /-- Restriction of a ring homomorphism to its range interpreted as a subfield. -/ def range_restrict_field {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) : K →+* ↥(range f) := cod_restrict' f (range f) sorry @[simp] theorem coe_range_restrict_field {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (x : K) : ↑(coe_fn (range_restrict_field f) x) = coe_fn f x := rfl /-- The subfield of elements `x : R` such that `f x = g x`, i.e., the equalizer of f and g as a subfield of R -/ def eq_locus_field {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (g : K →+* L) : subfield K := subfield.mk (set_of fun (x : K) => coe_fn f x = coe_fn g x) sorry sorry sorry sorry sorry sorry /-- If two ring homomorphisms are equal on a set, then they are equal on its subfield closure. -/ theorem eq_on_field_closure {K : Type u} {L : Type v} [field K] [field L] {f : K →+* L} {g : K →+* L} {s : set K} (h : set.eq_on (⇑f) (⇑g) s) : set.eq_on ⇑f ⇑g ↑(subfield.closure s) := (fun (this : subfield.closure s ≤ eq_locus_field f g) => this) (iff.mpr subfield.closure_le h) theorem eq_of_eq_on_subfield_top {K : Type u} {L : Type v} [field K] [field L] {f : K →+* L} {g : K →+* L} (h : set.eq_on ⇑f ⇑g ↑⊤) : f = g := ext fun (x : K) => h trivial theorem eq_of_eq_on_of_field_closure_eq_top {K : Type u} {L : Type v} [field K] [field L] {s : set K} (hs : subfield.closure s = ⊤) {f : K →+* L} {g : K →+* L} (h : set.eq_on (⇑f) (⇑g) s) : f = g := eq_of_eq_on_subfield_top (hs ▸ eq_on_field_closure h) theorem field_closure_preimage_le {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (s : set L) : subfield.closure (⇑f ⁻¹' s) ≤ subfield.comap f (subfield.closure s) := iff.mpr subfield.closure_le fun (x : K) (hx : x ∈ ⇑f ⁻¹' s) => iff.mpr subfield.mem_coe (iff.mpr subfield.mem_comap (subfield.subset_closure hx)) /-- The image under a ring homomorphism of the subfield generated by a set equals the subfield generated by the image of the set. -/ theorem map_field_closure {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (s : set K) : subfield.map f (subfield.closure s) = subfield.closure (⇑f '' s) := sorry end ring_hom namespace subfield /-- The ring homomorphism associated to an inclusion of subfields. -/ def inclusion {K : Type u} [field K] {S : subfield K} {T : subfield K} (h : S ≤ T) : ↥S →+* ↥T := ring_hom.cod_restrict_field (subtype S) T sorry @[simp] theorem field_range_subtype {K : Type u} [field K] (s : subfield K) : ring_hom.field_range (subtype s) = s := ext' (Eq.trans (ring_hom.coe_srange (subtype s)) subtype.range_coe) end subfield namespace ring_equiv /-- Makes the identity isomorphism from a proof two subfields of a multiplicative monoid are equal. -/ def subfield_congr {K : Type u} [field K] {s : subfield K} {t : subfield K} (h : s = t) : ↥s ≃+* ↥t := mk (equiv.to_fun (equiv.set_congr sorry)) (equiv.inv_fun (equiv.set_congr sorry)) sorry sorry sorry sorry end ring_equiv namespace subfield theorem closure_preimage_le {K : Type u} {L : Type v} [field K] [field L] (f : K →+* L) (s : set L) : closure (⇑f ⁻¹' s) ≤ comap f (closure s) := iff.mpr closure_le fun (x : K) (hx : x ∈ ⇑f ⁻¹' s) => iff.mpr mem_coe (iff.mpr mem_comap (subset_closure hx))
40a8ca5f4efd5f1c55aee8711bf76f89ecf9d29a
f57749ca63d6416f807b770f67559503fdb21001
/tests/lean/hott/433.hlean
eaa162e8acb24ba67bb58a073bb14db28df3ba04
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,838
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about pi-types (dependent function spaces) -/ import types.sigma open eq equiv is_equiv funext namespace pi universe variables l k variables {A A' : Type.{l}} {B : A → Type.{k}} {B' : A' → Type.{k}} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a} /- Paths -/ /- Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ∼ g]. This equivalence, however, is just the combination of [apD10] and function extensionality [funext], and as such, [path_forall], et seq. are given in axioms.funext and path: -/ /- Now we show how these things compute. -/ definition apd10_path_pi (H : funext) (h : f ~ g) : apd10 (eq_of_homotopy h) ~ h := apd10 (right_inv apd10 h) definition path_pi_eta (H : funext) (p : f = g) : eq_of_homotopy (apd10 p) = p := left_inv apd10 p print classes definition path_pi_idp (H : funext) : eq_of_homotopy (λx : A, refl (f x)) = refl f := path_pi_eta H _ /- The identification of the path space of a dependent function space, up to equivalence, is of course just funext. -/ definition path_equiv_homotopy (H : funext) (f g : Πx, B x) : (f = g) ≃ (f ~ g) := equiv.mk _ !is_equiv_apd definition is_equiv_path_pi [instance] (H : funext) (f g : Πx, B x) : is_equiv (@eq_of_homotopy _ _ f g) := is_equiv_inv apd10 definition homotopy_equiv_path (H : funext) (f g : Πx, B x) : (f ~ g) ≃ (f = g) := equiv.mk _ (is_equiv_path_pi H f g) /- Transport -/ protected definition transport (p : a = a') (f : Π(b : B a), C a b) : (transport (λa, Π(b : B a), C a b) p f) ~ (λb, transport (C a') !tr_inv_tr (transportD _ p _ (f (p⁻¹ ▸ b)))) := eq.rec_on p (λx, idp) /- A special case of [transport_pi] where the type [B] does not depend on [A], and so it is just a fixed type [B]. -/ definition transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) : (eq.transport (λa, Π(b : A'), C a b) p f) ~ (λb, eq.transport (λa, C a b) p (f b)) := eq.rec_on p (λx, idp) /- Maps on paths -/ /- The action of maps given by lambda. -/ definition ap_lambdaD (H : funext) {C : A' → Type} (p : a = a') (f : Πa b, C b) : ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) := begin apply (eq.rec_on p), apply inverse, apply (path_pi_idp H) end /- Dependent paths -/ /- with more implicit arguments the conclusion of the following theorem is (Π(b : B a), transportD B C p b (f b) = g (eq.transport B p b)) ≃ (eq.transport (λa, Π(b : B a), C a b) p f = g) -/ definition dpath_pi (H : funext) (p : a = a') (f : Π(b : B a), C a b) (g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▸D (f b) = g (p ▸ b)) ≃ (p ▸ f = g) := eq.rec_on p (λg, homotopy_equiv_path H f g) g section open sigma sigma.ops /- more implicit arguments: (Π(b : B a), eq.transport C (sigma.path p idp) (f b) = g (p ▸ b)) ≃ (Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (eq.transport B p b)) -/ definition dpath_pi_sigma {C : (Σa, B a) → Type} (p : a = a') (f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) : (Π(b : B a), (sigma.sigma_eq p !pathover_tr) ▸ (f b) = g (p ▸ b)) ≃ (Π(b : B a), p ▸D (f b) = g (p ▸ b)) := eq.rec_on p (λg, !equiv.refl) g end variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') definition transport_V [reducible] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition functor_pi : (Π(a:A), B a) → (Π(a':A'), B' a') := (λg a', f1 a' (g (f0 a'))) /- Equivalences -/ definition isequiv_functor_pi [instance] (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') [H0 : is_equiv f0] [H1 : Πa', @is_equiv (B (f0 a')) (B' a') (f1 a')] : is_equiv (functor_pi f0 f1) := begin apply (adjointify (functor_pi f0 f1) (functor_pi (f0⁻¹) (λ(a : A) (b' : B' (f0⁻¹ a)), transport B (right_inv f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))), intro h, apply eq_of_homotopy, esimp [functor_pi, function.compose], -- simplify (and unfold function_pi and function.compose) --first subgoal intro a', esimp, rewrite adj, rewrite -transport_compose, rewrite {f1 a' _}(fn_tr_eq_tr_fn _ f1 _), rewrite (right_inv (f1 _) _), apply apd, intro h, apply eq_of_homotopy, intro a, esimp, apply (transport_V (λx, right_inv f0 a ▸ x = h a) (left_inv (f1 _) _)), apply apd end end pi
96981b9b996ef6094b7f68a5e2042fdf396d520a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/set/disjointed_auto.lean
dcec9e2024dec14667f2f2050dd222e539171e09
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,158
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 Disjointed sets -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.lattice import Mathlib.tactic.wlog import Mathlib.PostPort universes u_1 u v namespace Mathlib /-- A relation `p` holds pairwise if `p i j` for all `i ≠ j`. -/ def pairwise {α : Type u_1} (p : α → α → Prop) := ∀ (i j : α), i ≠ j → p i j theorem set.pairwise_on_univ {α : Type u} {r : α → α → Prop} : set.pairwise_on set.univ r ↔ pairwise r := sorry theorem set.pairwise_on.on_injective {α : Type u} {β : Type v} {s : set α} {r : α → α → Prop} (hs : set.pairwise_on s r) {f : β → α} (hf : function.injective f) (hfs : ∀ (x : β), f x ∈ s) : pairwise (r on f) := fun (i j : β) (hij : i ≠ j) => hs (f i) (hfs i) (f j) (hfs j) (function.injective.ne hf hij) theorem pairwise.mono {α : Type u} {p : α → α → Prop} {q : α → α → Prop} (h : ∀ {i j : α}, p i j → q i j) (hp : pairwise p) : pairwise q := fun (i j : α) (hij : i ≠ j) => h (hp i j hij) theorem pairwise_on_bool {α : Type u} {r : α → α → Prop} (hr : symmetric r) {a : α} {b : α} : pairwise (r on fun (c : Bool) => cond c a b) ↔ r a b := sorry theorem pairwise_disjoint_on_bool {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} : pairwise (disjoint on fun (c : Bool) => cond c a b) ↔ disjoint a b := pairwise_on_bool disjoint.symm theorem pairwise.pairwise_on {α : Type u} {p : α → α → Prop} (h : pairwise p) (s : set α) : set.pairwise_on s p := fun (x : α) (hx : x ∈ s) (y : α) (hy : y ∈ s) => h x y theorem pairwise_disjoint_fiber {α : Type u} {β : Type v} (f : α → β) : pairwise (disjoint on fun (y : β) => f ⁻¹' singleton y) := iff.mp set.pairwise_on_univ (set.pairwise_on_disjoint_fiber f set.univ) namespace set /-- If `f : ℕ → set α` is a sequence of sets, then `disjointed f` is the sequence formed with each set subtracted from the later ones in the sequence, to form a disjoint sequence. -/ def disjointed {α : Type u} (f : ℕ → set α) (n : ℕ) : set α := f n ∩ Inter fun (i : ℕ) => Inter fun (H : i < n) => f iᶜ theorem disjoint_disjointed {α : Type u} {f : ℕ → set α} : pairwise (disjoint on disjointed f) := sorry theorem disjoint_disjointed' {α : Type u} {f : ℕ → set α} (i : ℕ) (j : ℕ) : i ≠ j → disjointed f i ∩ disjointed f j = ∅ := fun (hij : i ≠ j) => iff.mp disjoint_iff (disjoint_disjointed i j hij) theorem disjointed_subset {α : Type u} {f : ℕ → set α} {n : ℕ} : disjointed f n ⊆ f n := inter_subset_left (f n) (Inter fun (i : ℕ) => Inter fun (H : i < n) => f iᶜ) theorem Union_lt_succ {α : Type u} {f : ℕ → set α} {n : ℕ} : (Union fun (i : ℕ) => Union fun (H : i < Nat.succ n) => f i) = f n ∪ Union fun (i : ℕ) => Union fun (H : i < n) => f i := sorry theorem Inter_lt_succ {α : Type u} {f : ℕ → set α} {n : ℕ} : (Inter fun (i : ℕ) => Inter fun (H : i < Nat.succ n) => f i) = f n ∩ Inter fun (i : ℕ) => Inter fun (H : i < n) => f i := sorry theorem subset_Union_disjointed {α : Type u} {f : ℕ → set α} {n : ℕ} : f n ⊆ Union fun (i : ℕ) => Union fun (H : i < Nat.succ n) => disjointed f i := sorry theorem Union_disjointed {α : Type u} {f : ℕ → set α} : (Union fun (n : ℕ) => disjointed f n) = Union fun (n : ℕ) => f n := sorry theorem disjointed_induct {α : Type u} {f : ℕ → set α} {n : ℕ} {p : set α → Prop} (h₁ : p (f n)) (h₂ : ∀ (t : set α) (i : ℕ), p t → p (t \ f i)) : p (disjointed f n) := sorry theorem disjointed_of_mono {α : Type u} {f : ℕ → set α} {n : ℕ} (hf : monotone f) : disjointed f (n + 1) = f (n + 1) \ f n := sorry theorem Union_disjointed_of_mono {α : Type u} {f : ℕ → set α} (hf : monotone f) (n : ℕ) : (Union fun (i : ℕ) => Union fun (H : i < Nat.succ n) => disjointed f i) = f n := sorry end Mathlib
644014ec888af61239ad74ee889a3a17a6c530ff
1dd482be3f611941db7801003235dc84147ec60a
/src/algebra/big_operators.lean
d6528daf2af054a1d6b22004769925e52f6b8f6f
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
28,628
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 Some big operators for lists and finite sets. -/ import data.list.basic data.list.perm data.finset import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive finset.sum] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod attribute [to_additive finset.sum.equations._eqn_1] finset.prod.equations._eqn_1 @[to_additive finset.sum_eq_fold] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive finset.sum_empty] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive finset.sum_insert] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive finset.sum_singleton] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive finset.sum_const_zero] prod_const_one @[simp, to_additive finset.sum_image] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[congr, to_additive finset.sum_congr] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive finset.sum_union_inter] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive finset.sum_union] lemma prod_union [decidable_eq α] (h : s₁ ∩ s₂ = ∅) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, h]; exact (mul_one _).symm @[to_additive finset.sum_sdiff] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union (sdiff_inter_self _ _), sdiff_union_of_subset h] @[to_additive finset.sum_bind] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅, from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have t x ∩ finset.bind s t = ∅, from eq_empty_of_forall_not_mem $ assume a, by rw [mem_inter, mem_bind]; rintro ⟨h₁, y, hys, hy₂⟩; exact eq_empty_iff_forall_not_mem.1 (hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hys) (assume h, hxs (h.symm ▸ hys))) _ (mem_inter_of_mem h₁ hy₂), by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive finset.sum_product] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind (λ x hx y hy h, eq_empty_of_forall_not_mem _)], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [mem_inter, mem_image], rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩, apply h, cc end @[to_additive finset.sum_sigma] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_image]; rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive finset.sum_image'] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine disjoint_iff_inter_eq_empty.1 (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive finset.sum_add_distrib] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive finset.sum_comm] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom (λ _ _, is_monoid_hom.map_mul g)) @[to_additive finset.sum_hom_rel] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive finset.sum_subset] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive finset.sum_eq_single] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive finset.sum_attach] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive finset.sum_bij] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = s.attach.prod (λx, f x.val) : prod_attach.symm ... = s.attach.prod (λx, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _ ... = (s.attach.image $ λx:{x // x ∈ s}, i x.1 x.2).prod g : (prod_image $ assume (a₁:{x // x ∈ s}) _ a₂ _ eq, subtype.eq $ i_inj a₁.1 a₂.1 a₁.2 a₂.2 eq).symm ... = t.prod g : prod_subset (by simp only [subset_iff, mem_image, mem_attach]; rintro _ ⟨⟨_, _⟩, _, rfl⟩; solve_by_elim) (assume b hb hb1, false.elim $ hb1 $ by rcases i_surj b hb with ⟨a, ha, rfl⟩; exact mem_image.2 ⟨⟨_, _⟩, mem_attach _ _, rfl⟩) @[to_additive finset.sum_bij_ne_zero] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive finset.exists_ne_zero_of_sum_ne_zero] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive finset.sum_range_succ] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive finset.sum_involution] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive finset.sum_eq_zero] lemma prod_eq_one [comm_monoid β] {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid lemma sum_hom [add_comm_monoid β] [add_comm_monoid γ] (g : β → γ) [is_add_monoid_hom g] : s.sum (λx, g (f x)) = g (s.sum f) := eq.trans (by rw is_add_monoid_hom.map_zero g; refl) (fold_hom (λ _ _, is_add_monoid_hom.map_add g)) attribute [to_additive finset.sum_hom] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive finset.sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive finset.sum_const] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive finset.sum_range_succ'] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm section comm_group variables [comm_group β] @[simp, to_additive finset.sum_neg_distrib] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → t x ∩ t y = ∅) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section ordered_cancel_comm_monoid variables [decidable_eq α] [ordered_cancel_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma zero_le_sum (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_le_zero (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) end ordered_cancel_comm_monoid section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, image (pi.cons s a x) (pi s t) ∩ image (pi.cons s a y) (pi s t) = ∅, { assume x hx y hy h, apply eq_empty_of_forall_not_mem, simp only [mem_inter, mem_image], rintro p₁ ⟨⟨p₂, hp, eq⟩, ⟨p₃, hp₃, rfl⟩⟩, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum' : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma zero_le_sum' (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum' h) lemma sum_le_zero' (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum' h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ zero_le_sum' $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union (sdiff_inter_self _ _)).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (zero_le_sum' this), forall_mem_insert, ih this] lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] [@decidable_rel β (≤)] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; apply filter_inter_filter_neg_eq ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_le_zero' $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section discrete_linear_ordered_field variables [discrete_linear_ordered_field α] [decidable_eq β] lemma abs_sum_le_sum_abs {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := finset.induction_on s (le_of_eq abs_zero) $ assume a s has ih, calc abs (sum (insert a s) f) ≤ abs (f a) + abs (sum s f) : by rw sum_insert has; exact abs_add_le_abs_add_abs _ _ ... ≤ abs (f a) + s.sum (λa, abs (f a)) : add_le_add (le_refl _) ih ... ≤ sum (insert a s) (λ (a : β), abs (f a)) : by rw sum_insert has end discrete_linear_ordered_field @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ @[simp] lemma prod_range_id_eq_fact (n : ℕ) : ((range n.succ).erase 0).prod (λ x, x) = nat.fact n := calc ((range n.succ).erase 0).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, mem_erase.2 ⟨nat.succ_ne_zero _, mem_range.2 $ nat.succ_lt_succ $ by simpa using h₁⟩) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset section geom_sum open finset theorem geom_sum_mul_add [semiring α] (x : α) : ∀ (n : ℕ), ((range n).sum (λ i, (x+1)^i)) * x + 1 = (x+1)^n | 0 := by simp | (n+1) := calc (range (n + 1)).sum (λi, (x + 1) ^ i) * x + 1 = (x + 1)^n * x + (((range n).sum (λ i, (x+1)^i)) * x + 1) : by simp [range_add_one, add_mul] ... = (x + 1)^n * x + (x + 1)^n : by rw geom_sum_mul_add n ... = (x + 1) ^ (n + 1) : by simp [pow_add, mul_add] theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : ((range n).sum (λ i, x^i)) * (x-1) = x^n-1 := have _ := geom_sum_mul_add (x-1) n, by rw [sub_add_cancel] at this; rw [← this, add_sub_cancel] theorem geom_sum [division_ring α] (x : α) (h : x ≠ 1) (n : ℕ) : (range n).sum (λ i, x^i) = (x^n-1)/(x-1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] end geom_sum section group open list variables [group α] [group β] @[to_additive is_add_group_hom.sum] theorem is_group_hom.prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_group_hom.mul f, is_group_hom.one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.one f, simp only [prod_cons, is_group_anti_hom.mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive is_add_group_hom.multiset_sum] lemma is_group_hom.multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.prod f l] @[to_additive is_add_group_hom.finset_sum] lemma is_group_hom.finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := ⟨assume a b, by simp only [λc, is_group_hom.mul (f c), finset.prod_mul_distrib]⟩ attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset
6e70fd03c36c6a0e40c87dc414db302a37c3d10d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebraic_geometry/morphisms/quasi_compact.lean
b0914f8516fd2a4fb1f7ec8e8d051061917154e4
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,437
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebraic_geometry.morphisms.basic import topology.spectral.hom import algebraic_geometry.limits /-! # Quasi-compact morphisms > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A morphism of schemes is quasi-compact if the preimages of quasi-compact open sets are quasi-compact. It suffices to check that preimages of affine open sets are compact (`quasi_compact_iff_forall_affine`). -/ noncomputable theory open category_theory category_theory.limits opposite topological_space universe u open_locale algebraic_geometry namespace algebraic_geometry variables {X Y : Scheme.{u}} (f : X ⟶ Y) /-- A morphism is `quasi-compact` if the underlying map of topological spaces is, i.e. if the preimages of quasi-compact open sets are quasi-compact. -/ @[mk_iff] class quasi_compact (f : X ⟶ Y) : Prop := (is_compact_preimage : ∀ U : set Y.carrier, is_open U → is_compact U → is_compact (f.1.base ⁻¹' U)) lemma quasi_compact_iff_spectral : quasi_compact f ↔ is_spectral_map f.1.base := ⟨λ ⟨h⟩, ⟨by continuity, h⟩, λ h, ⟨h.2⟩⟩ /-- The `affine_target_morphism_property` corresponding to `quasi_compact`, asserting that the domain is a quasi-compact scheme. -/ def quasi_compact.affine_property : affine_target_morphism_property := λ X Y f hf, compact_space X.carrier @[priority 900] instance quasi_compact_of_is_iso {X Y : Scheme} (f : X ⟶ Y) [is_iso f] : quasi_compact f := begin constructor, intros U hU hU', convert hU'.image (inv f.1.base).continuous_to_fun using 1, rw set.image_eq_preimage_of_inverse, delta function.left_inverse, exacts [is_iso.inv_hom_id_apply f.1.base, is_iso.hom_inv_id_apply f.1.base] end instance quasi_compact_comp {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) [quasi_compact f] [quasi_compact g] : quasi_compact (f ≫ g) := begin constructor, intros U hU hU', rw [Scheme.comp_val_base, coe_comp, set.preimage_comp], apply quasi_compact.is_compact_preimage, { exact continuous.is_open_preimage (by continuity) _ hU }, apply quasi_compact.is_compact_preimage; assumption end lemma is_compact_open_iff_eq_finset_affine_union {X : Scheme} (U : set X.carrier) : is_compact U ∧ is_open U ↔ ∃ (s : set X.affine_opens), s.finite ∧ U = ⋃ (i : X.affine_opens) (h : i ∈ s), i := begin apply opens.is_basis.is_compact_open_iff_eq_finite_Union (coe : X.affine_opens → opens X.carrier), { rw subtype.range_coe, exact is_basis_affine_open X }, { exact λ i, i.2.is_compact } end lemma is_compact_open_iff_eq_basic_open_union {X : Scheme} [is_affine X] (U : set X.carrier) : is_compact U ∧ is_open U ↔ ∃ (s : set (X.presheaf.obj (op ⊤))), s.finite ∧ U = ⋃ (i : X.presheaf.obj (op ⊤)) (h : i ∈ s), X.basic_open i := (is_basis_basic_open X).is_compact_open_iff_eq_finite_Union _ (λ i, ((top_is_affine_open _).basic_open_is_affine _).is_compact) _ lemma quasi_compact_iff_forall_affine : quasi_compact f ↔ ∀ U : opens Y.carrier, is_affine_open U → is_compact (f.1.base ⁻¹' (U : set Y.carrier)) := begin rw quasi_compact_iff, refine ⟨λ H U hU, H U U.is_open hU.is_compact, _⟩, intros H U hU hU', obtain ⟨S, hS, rfl⟩ := (is_compact_open_iff_eq_finset_affine_union U).mp ⟨hU', hU⟩, simp only [set.preimage_Union, subtype.val_eq_coe], exact hS.is_compact_bUnion (λ i _, H i i.prop) end @[simp] lemma quasi_compact.affine_property_to_property {X Y : Scheme} (f : X ⟶ Y) : (quasi_compact.affine_property : _).to_property f ↔ is_affine Y ∧ compact_space X.carrier := by { delta affine_target_morphism_property.to_property quasi_compact.affine_property, simp } lemma quasi_compact_iff_affine_property : quasi_compact f ↔ target_affine_locally quasi_compact.affine_property f := begin rw quasi_compact_iff_forall_affine, transitivity (∀ U : Y.affine_opens, is_compact (f.1.base ⁻¹' (U : set Y.carrier))), { exact ⟨λ h U, h U U.prop, λ h U hU, h ⟨U, hU⟩⟩ }, apply forall_congr, exact λ _, is_compact_iff_compact_space, end lemma quasi_compact_eq_affine_property : @quasi_compact = target_affine_locally quasi_compact.affine_property := by { ext, exact quasi_compact_iff_affine_property _ } lemma is_compact_basic_open (X : Scheme) {U : opens X.carrier} (hU : is_compact (U : set X.carrier)) (f : X.presheaf.obj (op U)) : is_compact (X.basic_open f : set X.carrier) := begin classical, refine ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1, obtain ⟨s, hs, e⟩ := (is_compact_open_iff_eq_finset_affine_union _).mp ⟨hU, U.is_open⟩, let g : s → X.affine_opens, { intro V, use V.1 ⊓ X.basic_open f, have : V.1.1 ⟶ U, { apply hom_of_le, change _ ⊆ (U : set X.carrier), rw e, convert @set.subset_Union₂ _ _ _ (λ (U : X.affine_opens) (h : U ∈ s), ↑U) V V.prop using 1, refl }, erw ← X.to_LocallyRingedSpace.to_RingedSpace.basic_open_res this.op, exact is_affine_open.basic_open_is_affine V.1.prop _ }, haveI : finite s := hs.to_subtype, refine ⟨set.range g, set.finite_range g, _⟩, refine (set.inter_eq_right_iff_subset.mpr (set_like.coe_subset_coe.2 $ RingedSpace.basic_open_le _ _)).symm.trans _, rw [e, set.Union₂_inter], apply le_antisymm; apply set.Union₂_subset, { intros i hi, refine set.subset.trans _ (set.subset_Union₂ _ (set.mem_range_self ⟨i, hi⟩)), exact set.subset.rfl }, { rintro ⟨i, hi⟩ ⟨⟨j, hj⟩, hj'⟩, rw ← hj', refine set.subset.trans _ (set.subset_Union₂ j hj), exact set.subset.rfl } end lemma quasi_compact.affine_property_is_local : (quasi_compact.affine_property : _).is_local := begin split, { apply affine_target_morphism_property.respects_iso_mk; rintros X Y Z _ _ _ H, exacts [@@homeomorph.compact_space _ _ H (Top.homeo_of_iso (as_iso e.inv.1.base)), H] }, { introv H, delta quasi_compact.affine_property at H ⊢, change compact_space ((opens.map f.val.base).obj (Y.basic_open r)), rw Scheme.preimage_basic_open f r, erw ← is_compact_iff_compact_space, rw ← is_compact_univ_iff at H, exact is_compact_basic_open X H _ }, { rintros X Y H f S hS hS', resetI, rw ← is_affine_open.basic_open_union_eq_self_iff at hS, delta quasi_compact.affine_property, rw ← is_compact_univ_iff, change is_compact ((opens.map f.val.base).obj ⊤).1, rw ← hS, dsimp [opens.map], simp only [opens.coe_supr, set.preimage_Union, subtype.val_eq_coe], exacts [is_compact_Union (λ i, is_compact_iff_compact_space.mpr (hS' i)), top_is_affine_open _] } end lemma quasi_compact.affine_open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) : tfae [quasi_compact f, ∃ (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)], ∀ (i : 𝒰.J), compact_space (pullback f (𝒰.map i)).carrier, ∀ (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)] (i : 𝒰.J), compact_space (pullback f (𝒰.map i)).carrier, ∀ {U : Scheme} (g : U ⟶ Y) [is_affine U] [is_open_immersion g], compact_space (pullback f g).carrier, ∃ {ι : Type u} (U : ι → opens Y.carrier) (hU : supr U = ⊤) (hU' : ∀ i, is_affine_open (U i)), ∀ i, compact_space (f.1.base ⁻¹' (U i).1)] := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.affine_open_cover_tfae f lemma quasi_compact.is_local_at_target : property_is_local_at_target @quasi_compact := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.target_affine_locally_is_local lemma quasi_compact.open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) : tfae [quasi_compact f, ∃ (𝒰 : Scheme.open_cover.{u} Y), ∀ (i : 𝒰.J), quasi_compact (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i), ∀ (𝒰 : Scheme.open_cover.{u} Y) (i : 𝒰.J), quasi_compact (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i), ∀ (U : opens Y.carrier), quasi_compact (f ∣_ U), ∀ {U : Scheme} (g : U ⟶ Y) [is_open_immersion g], quasi_compact (pullback.snd : pullback f g ⟶ _), ∃ {ι : Type u} (U : ι → opens Y.carrier) (hU : supr U = ⊤), ∀ i, quasi_compact (f ∣_ (U i))] := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.target_affine_locally_is_local.open_cover_tfae f lemma quasi_compact_over_affine_iff {X Y : Scheme} (f : X ⟶ Y) [is_affine Y] : quasi_compact f ↔ compact_space X.carrier := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.affine_target_iff f lemma compact_space_iff_quasi_compact (X : Scheme) : compact_space X.carrier ↔ quasi_compact (terminal.from X) := (quasi_compact_over_affine_iff _).symm lemma quasi_compact.affine_open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)] (f : X ⟶ Y) : quasi_compact f ↔ ∀ i, compact_space (pullback f (𝒰.map i)).carrier := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.affine_open_cover_iff f 𝒰 lemma quasi_compact.open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y) (f : X ⟶ Y) : quasi_compact f ↔ ∀ i, quasi_compact (pullback.snd : pullback f (𝒰.map i) ⟶ _) := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.target_affine_locally_is_local.open_cover_iff f 𝒰 lemma quasi_compact_respects_iso : morphism_property.respects_iso @quasi_compact := quasi_compact_eq_affine_property.symm ▸ target_affine_locally_respects_iso quasi_compact.affine_property_is_local.1 lemma quasi_compact_stable_under_composition : morphism_property.stable_under_composition @quasi_compact := λ _ _ _ _ _ _ _, by exactI infer_instance local attribute [-simp] PresheafedSpace.as_coe SheafedSpace.as_coe lemma quasi_compact.affine_property_stable_under_base_change : quasi_compact.affine_property.stable_under_base_change := begin intros X Y S _ _ f g h, rw quasi_compact.affine_property at h ⊢, resetI, let 𝒰 := Scheme.pullback.open_cover_of_right Y.affine_cover.finite_subcover f g, haveI : finite 𝒰.J, { dsimp [𝒰], apply_instance }, haveI : ∀ i, compact_space (𝒰.obj i).carrier, { intro i, dsimp, apply_instance }, exact 𝒰.compact_space, end lemma quasi_compact_stable_under_base_change : morphism_property.stable_under_base_change @quasi_compact := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.stable_under_base_change quasi_compact.affine_property_stable_under_base_change variables {Z : Scheme.{u}} instance (f : X ⟶ Z) (g : Y ⟶ Z) [quasi_compact g] : quasi_compact (pullback.fst : pullback f g ⟶ X) := quasi_compact_stable_under_base_change.fst f g infer_instance instance (f : X ⟶ Z) (g : Y ⟶ Z) [quasi_compact f] : quasi_compact (pullback.snd : pullback f g ⟶ Y) := quasi_compact_stable_under_base_change.snd f g infer_instance @[elab_as_eliminator] lemma compact_open_induction_on {P : opens X.carrier → Prop} (S : opens X.carrier) (hS : is_compact S.1) (h₁ : P ⊥) (h₂ : ∀ (S : opens X.carrier) (hS : is_compact S.1) (U : X.affine_opens), P S → P (S ⊔ U)) : P S := begin classical, obtain ⟨s, hs, hs'⟩ := (is_compact_open_iff_eq_finset_affine_union S.1).mp ⟨hS, S.2⟩, replace hs' : S = supr (λ i : s, (i : opens X.carrier)) := by { ext1, simpa using hs' }, subst hs', apply hs.induction_on, { convert h₁, rw supr_eq_bot, rintro ⟨_, h⟩, exact h.elim }, { intros x s h₃ hs h₄, have : is_compact (⨆ i : s, (i : opens X.carrier)).1, { refine ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1, exact ⟨s, hs, by simp⟩ }, convert h₂ _ this x h₄, simp only [coe_coe], rw [supr_subtype, sup_comm], conv_rhs { rw supr_subtype }, exact supr_insert } end lemma exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_affine_open (X : Scheme) {U : opens X.carrier} (hU : is_affine_open U) (x f : X.presheaf.obj (op U)) (H : x |_ X.basic_open f = 0) : ∃ n : ℕ, f ^ n * x = 0 := begin rw ← map_zero (X.presheaf.map (hom_of_le $ X.basic_open_le f : X.basic_open f ⟶ U).op) at H, have := (is_localization_basic_open hU f).3, obtain ⟨⟨_, n, rfl⟩, e⟩ := this.mp H, exact ⟨n, by simpa [mul_comm x] using e⟩, end /-- If `x : Γ(X, U)` is zero on `D(f)` for some `f : Γ(X, U)`, and `U` is quasi-compact, then `f ^ n * x = 0` for some `n`. -/ lemma exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_compact (X : Scheme) {U : opens X.carrier} (hU : is_compact U.1) (x f : X.presheaf.obj (op U)) (H : x |_ X.basic_open f = 0) : ∃ n : ℕ, f ^ n * x = 0 := begin obtain ⟨s, hs, e⟩ := (is_compact_open_iff_eq_finset_affine_union U.1).mp ⟨hU, U.2⟩, replace e : U = supr (λ i : s, (i : opens X.carrier)), { ext1, simpa using e }, have h₁ : ∀ i : s, i.1.1 ≤ U, { intro i, change (i : opens X.carrier) ≤ U, rw e, exact le_supr _ _ }, have H' := λ (i : s), exists_pow_mul_eq_zero_of_res_basic_open_eq_zero_of_is_affine_open X i.1.2 (X.presheaf.map (hom_of_le (h₁ i)).op x) (X.presheaf.map (hom_of_le (h₁ i)).op f) _, swap, { delta Top.presheaf.restrict_open Top.presheaf.restrict at H ⊢, convert congr_arg (X.presheaf.map (hom_of_le _).op) H, { simp only [← comp_apply, ← functor.map_comp], congr }, { rw map_zero }, { rw X.basic_open_res, exact set.inter_subset_right _ _ } }, choose n hn using H', haveI := hs.to_subtype, casesI nonempty_fintype s, use finset.univ.sup n, suffices : ∀ (i : s), X.presheaf.map (hom_of_le (h₁ i)).op (f ^ (finset.univ.sup n) * x) = 0, { subst e, apply X.sheaf.eq_of_locally_eq (λ (i : s), (i : opens X.carrier)), intro i, rw map_zero, apply this }, intro i, replace hn := congr_arg (λ x, X.presheaf.map (hom_of_le (h₁ i)).op (f ^ (finset.univ.sup n - n i)) * x) (hn i), dsimp at hn, simp only [← map_mul, ← map_pow] at hn, rwa [mul_zero, ← mul_assoc, ← pow_add, tsub_add_cancel_of_le] at hn, apply finset.le_sup (finset.mem_univ i) end end algebraic_geometry
aee12cf5e41a0cdd557e9320fdb01c0e1a65083b
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/monadCache.lean
4d0c071fb88a39bea83cdc5c1baff856e2b2dc1c
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,352
lean
import Lean new_frontend open Lean partial def mkTower : Nat → Expr | 0 => mkConst `a | n+1 => mkApp2 (mkConst `f) (mkTower n) (mkTower n) partial def depth : Expr → MonadCacheT Expr Nat CoreM Nat | e => checkCache e fun e => match e with | Expr.const c [] _ => pure 1 | Expr.app f a _ => do pure $ Nat.max (← depth f) (← depth a) + 1 | _ => pure 0 #eval (depth (mkTower 100)).run partial def visit : Expr → MonadCacheT Expr Expr CoreM Expr | e => checkCache e fun e => match e with | Expr.const `a [] _ => pure $ mkConst `b | Expr.app f a _ => e.updateApp! <$> visit f <*> visit a | _ => pure e #eval (visit (mkTower 4)).run def tst : CoreM Nat := do let e ← (visit (mkTower 100)).run; (depth e).run #eval tst partial def visitNoCache : Expr → CoreM Expr | e => match e with | Expr.const `a [] _ => pure $ mkConst `b | Expr.app f a _ => e.updateApp! <$> visitNoCache f <*> visitNoCache a | _ => pure e -- The following is super slow -- #eval do e ← visitNoCache (mkTower 30); (depth e).run def displayConsts (e : Expr) : CoreM Unit := e.forEach fun e => match e with | Expr.const c _ _ => do IO.println c | _ => pure () def tst2 : CoreM Unit := do let e ← (visit (mkTower 100)).run; displayConsts e #eval tst2
79a77ed660143932b602bad3ce3e98a487fccd28
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/pnat/defs.lean
8c520024fe70fcad2751e477683702b4ae752354
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,831
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Neil Strickland -/ import order.basic import algebra.ne_zero /-! # The positive natural numbers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/604 > Any changes to this file require a corresponding PR to mathlib4. This file contains the definitions, and basic results. Most algebraic facts are deferred to `data.pnat.basic`, as they need more imports. -/ /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ @[derive [decidable_eq, linear_order]] def pnat := {n : ℕ // 0 < n} notation `ℕ+` := pnat instance : has_one ℕ+ := ⟨⟨1, nat.zero_lt_one⟩⟩ instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩ instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩ namespace pnat @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl /-- Predecessor of a `ℕ+`, as a `ℕ`. -/ def nat_pred (i : ℕ+) : ℕ := i - 1 @[simp] lemma nat_pred_eq_pred {n : ℕ} (h : 0 < n) : nat_pred (⟨n, h⟩ : ℕ+) = n.pred := rfl end pnat namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : ℕ) (h : 0 < n . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩ /-- Write a successor as an element of `ℕ+`. -/ def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl @[simp] theorem nat_pred_succ_pnat (n : ℕ) : n.succ_pnat.nat_pred = n := rfl @[simp] theorem _root_.pnat.succ_pnat_nat_pred (n : ℕ+) : n.nat_pred.succ_pnat = n := subtype.eq $ succ_pred_eq_of_pos n.2 /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n) @[simp] theorem to_pnat'_coe : ∀ (n : ℕ), ((to_pnat' n) : ℕ) = ite (0 < n) n 1 | 0 := rfl | (m + 1) := by {rw [if_pos (succ_pos m)], refl} end nat namespace pnat open nat /-- We now define a long list of structures on ℕ+ induced by similar structures on ℕ. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ @[simp] lemma mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k := iff.rfl @[simp] lemma mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k := iff.rfl @[simp, norm_cast] lemma coe_le_coe (n k : ℕ+) : (n : ℕ) ≤ k ↔ n ≤ k := iff.rfl @[simp, norm_cast] lemma coe_lt_coe (n k : ℕ+) : (n : ℕ) < k ↔ n < k := iff.rfl @[simp] theorem pos (n : ℕ+) : 0 < (n : ℕ) := n.2 theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq lemma coe_injective : function.injective (coe : ℕ+ → ℕ) := subtype.coe_injective @[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := n.2.ne' instance _root_.ne_zero.pnat {a : ℕ+} : _root_.ne_zero (a : ℕ) := ⟨a.ne_zero⟩ theorem to_pnat'_coe {n : ℕ} : 0 < n → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos) @[simp] lemma one_le (n : ℕ+) : (1 : ℕ+) ≤ n := n.2 @[simp] lemma not_lt_one (n : ℕ+) : ¬ n < 1 := not_lt_of_le n.one_le instance : inhabited ℕ+ := ⟨1⟩ -- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] lemma mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) := rfl @[norm_cast] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl @[simp, norm_cast] lemma coe_eq_one_iff {m : ℕ+} : (m : ℕ) = 1 ↔ m = 1 := subtype.coe_injective.eq_iff' one_coe instance : has_well_founded ℕ+ := ⟨(<), measure_wf coe⟩ /-- Strong induction on `ℕ+`. -/ def strong_induction_on {p : ℕ+ → Sort*} : ∀ (n : ℕ+) (h : ∀ k, (∀ m, m < k → p m) → p k), p n | n := λ IH, IH _ (λ a h, strong_induction_on a IH) using_well_founded { dec_tac := `[assumption] } /-- We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div_aux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ | k 0 q := ⟨k, q.pred⟩ | k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩ /-- `mod_div m k = (m % k, m / k)`. We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div (m k : ℕ+) : ℕ+ × ℕ := mod_div_aux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) /-- We define `m % k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive. -/ def mod (m k : ℕ+) : ℕ+ := (mod_div m k).1 /-- We define `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def div (m k : ℕ+) : ℕ := (mod_div m k).2 theorem mod_coe (m k : ℕ+) : ((mod m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) := begin dsimp [mod, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem div_coe (m k : ℕ+) : ((div m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) := begin dsimp [div, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end /-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/ def div_exact (m k : ℕ+) : ℕ+ := ⟨(div m k).succ, nat.succ_pos _⟩ end pnat section can_lift instance nat.can_lift_pnat : can_lift ℕ ℕ+ coe ((<) 0) := ⟨λ n hn, ⟨nat.to_pnat' n, pnat.to_pnat'_coe hn⟩⟩ instance int.can_lift_pnat : can_lift ℤ ℕ+ coe ((<) 0) := ⟨λ n hn, ⟨nat.to_pnat' (int.nat_abs n), by rw [coe_coe, nat.to_pnat'_coe, if_pos (int.nat_abs_pos_of_ne_zero hn.ne'), int.nat_abs_of_nonneg hn.le]⟩⟩ end can_lift
3fc0858ce9f297790c280a2aff4dae9d61477d0a
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Server/FileWorker/Utils.lean
558b9ddcf4ecbe2b7cde7673751bea6abb1dddbb
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,415
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Marc Huisinga -/ import Lean.Server.Utils import Lean.Server.Snapshots import Lean.Server.AsyncList namespace Lean.Server.FileWorker open Snapshots open IO def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit := IO.eprintln s!"[{s.beginPos}, {s.endPos}]: ```\n{text.source.extract s.beginPos (s.endPos-1)}\n```" inductive ElabTaskError where | aborted | eof | ioError (e : IO.Error) instance : Coe IO.Error ElabTaskError := ⟨ElabTaskError.ioError⟩ structure CancelToken where ref : IO.Ref Bool deriving Inhabited namespace CancelToken def new : IO CancelToken := CancelToken.mk <$> IO.mkRef false def check [MonadExceptOf ElabTaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do let c ← tk.ref.get if c then throw ElabTaskError.aborted def set (tk : CancelToken) : IO Unit := tk.ref.set true end CancelToken /-- A document editable in the sense that we track the environment and parser state after each command so that edits can be applied without recompiling code appearing earlier in the file. -/ structure EditableDocument where meta : DocumentMeta /- The first snapshot is that after the header. -/ headerSnap : Snapshot /- Subsequent snapshots occur after each command. -/ cmdSnaps : AsyncList ElabTaskError Snapshot cancelTk : CancelToken deriving Inhabited /-- Concurrently modifiable part of an RPC session. -/ structure RpcSessionState where /-- Objects that are being kept alive for the RPC client, together with their type names, mapped to by their RPC reference. Note that we may currently have multiple references to the same object. It is only disposed of once all of those are gone. This simplifies the client a bit as it can drop every reference received separately. -/ aliveRefs : Std.PersistentHashMap Lsp.RpcRef (Name × NonScalar) /-- Value to use for the next `RpcRef`. It is monotonically increasing to avoid any possible bugs resulting from its reuse. -/ nextRef : USize namespace RpcSessionState def store (st : RpcSessionState) (typeName : Name) (obj : NonScalar) : Lsp.RpcRef × RpcSessionState := let ref := ⟨st.nextRef⟩ let st' := { st with aliveRefs := st.aliveRefs.insert ref (typeName, obj) nextRef := st.nextRef + 1 } (ref, st') def release (st : RpcSessionState) (ref : Lsp.RpcRef) : Bool × RpcSessionState := let released := st.aliveRefs.contains ref (released, { st with aliveRefs := st.aliveRefs.erase ref }) end RpcSessionState structure RpcSession where sessionId : UInt64 clientConnected : Bool -- A single `Ref` ensures atomic transactions. state : IO.Ref RpcSessionState namespace RpcSession def new (clientConnected := false) : IO RpcSession := do /- We generate a random ID to ensure that session IDs do not repeat across re-initializations and worker restarts. Otherwise, the client may attempt to use outdated references. -/ let newId ← ByteArray.toUInt64LE! <$> IO.getRandomBytes 8 let newState ← IO.mkRef { aliveRefs := Std.PersistentHashMap.empty nextRef := 0 } return { sessionId := newId clientConnected state := newState } end RpcSession end Lean.Server.FileWorker
eb054cdd230fdb3c9b0a81a744a57b26735b41d1
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/lean3_zulip_issues_1.lean
497f9030bcfba5fd562fcbe093228c3552f5278b
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,317
lean
example : Prop := ∀ n, (n:Nat) + n = n.succ example : Prop := ∀ n, n.succ = (n:Nat) + n example : Prop := ∀ n, (n:Nat) + n.succ = n example : Prop := ∀ n, n.succ + (n:Nat) = n example : Prop := ∀ n, (n.succ:Nat) + n = n example : Prop := ∀ n, (n:Nat).succ + n = n def fib: Nat → Nat | 0 => 0 | 1 => 1 | n + 2 => fib n + fib (n + 1) theorem fib50Eq : fib 50 = 12586269025 := rfl inductive type : Type | A : type | B : type inductive val : type → Type | cA : val type.A | cB : val type.B inductive wrap : Type | val : ∀ {t : type}, (val t) → wrap def f : wrap → Nat | wrap.val val.cA => 1 | _ => 1 example (a : Nat) : True := by have : ∀ n, n ≥ 0 → a ≤ a := fun _ _ => Nat.leRefl .. exact True.intro example (ᾰ : Nat) : True := by have : ∀ n, n ≥ 0 → ᾰ ≤ ᾰ := fun _ _ => Nat.leRefl .. exact True.intro inductive Vec.{u} (α : Type u) : Nat → Type u | nil : Vec α 0 | cons : α → {n : Nat} → Vec α n → Vec α (Nat.succ n) -- TODO: investigate why +1 doesn't work here constant Vars : Type structure Lang := (funcs : Nat → Type) (consts : Type) inductive Term (L : Lang) : Type | const_term : L.consts → Term L | var_term : Vars → Term L | func_term (n : Nat) (f : L.funcs n) (v : Vec (Term L) n) : Term L
44242605e91baa6bd32d521578c42969f94c0b86
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/category/Group/colimits.lean
bc049da3dfcc620fca9b940de1df533a8f8f2d37
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
8,530
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 algebra.category.Group.basic import category_theory.limits.limits import category_theory.limits.concrete_category /-! # The category of additive commutative groups has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `add_comm_group` and `monoid_hom`. TODO: In fact, in `AddCommGroup` there is a much nicer model of colimits as quotients of finitely supported functions, and we really should implement this as well (or instead). -/ universes u v open category_theory open category_theory.limits -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. namespace AddCommGroup.colimits /-! We build the colimit of a diagram in `AddCommGroup` by constructing the free group on the disjoint union of all the abelian groups in the diagram, then taking the quotient by the abelian group laws within each abelian group, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ AddCommGroup.{v}) /-- An inductive type representing all group expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero : prequotient | neg : prequotient → prequotient | add : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.zero⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the abelian group laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Π (j), relation (of j 0) zero | neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) -- Then one relation per argument of each operation | neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y') -- And one relation per axiom | zero_add : Π (x), relation (add zero x) x | add_zero : Π (x), relation (add x zero) x | add_left_neg : Π (x), relation (add (neg x) x) zero | add_comm : Π (x y), relation (add x y) (add y x) | add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z)) /-- The setoid corresponding to group expressions modulo abelian group relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `AddCommGroup`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance : add_comm_group (colimit_type F) := { zero := begin exact quot.mk _ zero end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, zero_add := λ x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, add_left_neg := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled abelian group giving the colimit of a diagram. -/ def colimit : AddCommGroup := AddCommGroup.of (colimit_type F) /-- The function from a given abelian group in the diagram to the colimit abelian group. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The group homomorphism from a given abelian group in the diagram to the colimit abelian group. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_zero' := by apply quot.sound; apply relation.zero, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit abelian group. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F } }. /-- The function from the free abelian group on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | zero := 0 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y /-- The function from the colimit abelian group to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- zero { simp, }, -- neg { simp, }, -- add { simp, }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- add_assoc { rw add_assoc, }, } end /-- The group homomorphism from the colimit abelian group to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_zero' := rfl, map_add' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp *, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_AddCommGroup : has_colimits AddCommGroup := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit_cocone F, is_colimit := colimit_is_colimit F } } } end AddCommGroup.colimits
a01ccef04805d4d1be9b757f621939e3dabfcb76
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/polynomial/derivative.lean
5c670a3bb1b617109943b2fe240315357513d2c8
[]
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,930
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.polynomial.eval import Mathlib.PostPort universes u u_1 y v namespace Mathlib /-! # The derivative map on polynomials ## Main definitions * `polynomial.derivative`: The formal derivative of polynomials, expressed as a linear map. -/ namespace polynomial /-- `derivative p` is the formal derivative of the polynomial `p` -/ def derivative {R : Type u} [semiring R] : linear_map R (polynomial R) (polynomial R) := finsupp.total ℕ (polynomial R) R fun (n : ℕ) => coe_fn C ↑n * X ^ (n - 1) theorem derivative_apply {R : Type u} [semiring R] (p : polynomial R) : coe_fn derivative p = finsupp.sum p fun (n : ℕ) (a : R) => coe_fn C (a * ↑n) * X ^ (n - 1) := sorry theorem coeff_derivative {R : Type u} [semiring R] (p : polynomial R) (n : ℕ) : coeff (coe_fn derivative p) n = coeff p (n + 1) * (↑n + 1) := sorry theorem derivative_zero {R : Type u} [semiring R] : coe_fn derivative 0 = 0 := linear_map.map_zero derivative theorem derivative_monomial {R : Type u} [semiring R] (a : R) (n : ℕ) : coe_fn derivative (coe_fn (monomial n) a) = coe_fn (monomial (n - 1)) (a * ↑n) := sorry theorem derivative_C_mul_X_pow {R : Type u} [semiring R] (a : R) (n : ℕ) : coe_fn derivative (coe_fn C a * X ^ n) = coe_fn C (a * ↑n) * X ^ (n - 1) := sorry @[simp] theorem derivative_X_pow {R : Type u} [semiring R] (n : ℕ) : coe_fn derivative (X ^ n) = ↑n * X ^ (n - 1) := sorry @[simp] theorem derivative_C {R : Type u} [semiring R] {a : R} : coe_fn derivative (coe_fn C a) = 0 := sorry @[simp] theorem derivative_X {R : Type u} [semiring R] : coe_fn derivative X = 1 := sorry @[simp] theorem derivative_one {R : Type u} [semiring R] : coe_fn derivative 1 = 0 := derivative_C @[simp] theorem derivative_bit0 {R : Type u} [semiring R] {a : polynomial R} : coe_fn derivative (bit0 a) = bit0 (coe_fn derivative a) := sorry @[simp] theorem derivative_bit1 {R : Type u} [semiring R] {a : polynomial R} : coe_fn derivative (bit1 a) = bit0 (coe_fn derivative a) := sorry @[simp] theorem derivative_add {R : Type u} [semiring R] {f : polynomial R} {g : polynomial R} : coe_fn derivative (f + g) = coe_fn derivative f + coe_fn derivative g := linear_map.map_add derivative f g @[simp] theorem derivative_neg {R : Type u_1} [ring R] (f : polynomial R) : coe_fn derivative (-f) = -coe_fn derivative f := linear_map.map_neg derivative f @[simp] theorem derivative_sub {R : Type u_1} [ring R] (f : polynomial R) (g : polynomial R) : coe_fn derivative (f - g) = coe_fn derivative f - coe_fn derivative g := linear_map.map_sub derivative f g @[simp] theorem derivative_sum {R : Type u} {ι : Type y} [semiring R] {s : finset ι} {f : ι → polynomial R} : coe_fn derivative (finset.sum s fun (b : ι) => f b) = finset.sum s fun (b : ι) => coe_fn derivative (f b) := linear_map.map_sum derivative @[simp] theorem derivative_smul {R : Type u} [semiring R] (r : R) (p : polynomial R) : coe_fn derivative (r • p) = r • coe_fn derivative p := linear_map.map_smul derivative r p theorem derivative_eval {R : Type u} [comm_semiring R] (p : polynomial R) (x : R) : eval x (coe_fn derivative p) = finsupp.sum p fun (n : ℕ) (a : R) => a * ↑n * x ^ (n - 1) := sorry @[simp] theorem derivative_mul {R : Type u} [comm_semiring R] {f : polynomial R} {g : polynomial R} : coe_fn derivative (f * g) = coe_fn derivative f * g + f * coe_fn derivative g := sorry theorem derivative_pow_succ {R : Type u} [comm_semiring R] (p : polynomial R) (n : ℕ) : coe_fn derivative (p ^ (n + 1)) = (↑n + 1) * p ^ n * coe_fn derivative p := sorry theorem derivative_pow {R : Type u} [comm_semiring R] (p : polynomial R) (n : ℕ) : coe_fn derivative (p ^ n) = ↑n * p ^ (n - 1) * coe_fn derivative p := sorry theorem derivative_map {R : Type u} {S : Type v} [comm_semiring R] [comm_semiring S] (p : polynomial R) (f : R →+* S) : coe_fn derivative (map f p) = map f (coe_fn derivative p) := sorry /-- Chain rule for formal derivative of polynomials. -/ theorem derivative_eval₂_C {R : Type u} [comm_semiring R] (p : polynomial R) (q : polynomial R) : coe_fn derivative (eval₂ C q p) = eval₂ C q (coe_fn derivative p) * coe_fn derivative q := sorry theorem of_mem_support_derivative {R : Type u} [comm_semiring R] {p : polynomial R} {n : ℕ} (h : n ∈ finsupp.support (coe_fn derivative p)) : n + 1 ∈ finsupp.support p := sorry theorem degree_derivative_lt {R : Type u} [comm_semiring R] {p : polynomial R} (hp : p ≠ 0) : degree (coe_fn derivative p) < degree p := iff.mpr (finset.sup_lt_iff (iff.mpr bot_lt_iff_ne_bot (mt (iff.mp degree_eq_bot) hp))) fun (n : ℕ) (hp : n ∈ finsupp.support (coe_fn derivative p)) => lt_of_lt_of_le (iff.mpr with_bot.some_lt_some (nat.lt_succ_self n)) (finset.le_sup (of_mem_support_derivative hp)) theorem nat_degree_derivative_lt {R : Type u} [comm_semiring R] {p : polynomial R} (hp : coe_fn derivative p ≠ 0) : nat_degree (coe_fn derivative p) < nat_degree p := sorry theorem degree_derivative_le {R : Type u} [comm_semiring R] {p : polynomial R} : degree (coe_fn derivative p) ≤ degree p := sorry theorem mem_support_derivative {R : Type u} [integral_domain R] [char_zero R] (p : polynomial R) (n : ℕ) : n ∈ finsupp.support (coe_fn derivative p) ↔ n + 1 ∈ finsupp.support p := sorry @[simp] theorem degree_derivative_eq {R : Type u} [integral_domain R] [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) : degree (coe_fn derivative p) = ↑(nat_degree p - 1) := sorry theorem nat_degree_eq_zero_of_derivative_eq_zero {R : Type u} [integral_domain R] [char_zero R] {f : polynomial R} (h : coe_fn derivative f = 0) : nat_degree f = 0 := sorry
e926655c5e779917cbcec411ba7c5f5ab7553792
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Control/Lift.lean
2611c7f8d158c8428e4604426e292f7b3d5b05bc
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,599
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich Classy functions for lifting monadic actions of different shapes. This theory is roughly modeled after the Haskell 'layers' package https://hackage.haskell.org/package/layers-0.1. Please see https://hackage.haskell.org/package/layers-0.1/docs/Documentation-Layers-Overview.html for an exhaustive discussion of the different approaches to lift functions. -/ prelude import Init.Coe import Init.Control.Monad universes u v w /-- 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 HasMonadLift (m : Type u → Type v) (n : Type u → Type w) := (monadLift {} : ∀ {α}, m α → n α) /-- The reflexive-transitive closure of `HasMonadLift`. `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 HasMonadLiftT (m : Type u → Type v) (n : Type u → Type w) := (monadLift {} : ∀ {α}, m α → n α) export HasMonadLiftT (monadLift) abbrev liftM := @monadLift /-- A coercion that may reduce the need for explicit lifting. Because of [limitations of the current coercion resolution](https://github.com/leanprover/Lean/issues/1402), this definition is not marked as a global instance and should be marked locally instead. -/ @[reducible] def hasMonadLiftToHasCoe {m n} [HasMonadLiftT m n] {α} : HasCoe (m α) (n α) := ⟨monadLift⟩ instance hasMonadLiftTTrans (m n o) [HasMonadLift n o] [HasMonadLiftT m n] : HasMonadLiftT m o := ⟨fun α ma => HasMonadLift.monadLift (monadLift ma : n α)⟩ instance hasMonadLiftTRefl (m) : HasMonadLiftT m m := ⟨fun α => id⟩ theorem monadLiftRefl {m : Type u → Type v} {α} : (monadLift : m α → m α) = id := rfl /-- A Functor in the control 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). Remark: other libraries equate `m` and `m'`, and `n` and `n'`. We need to distinguish them to be able to implement gadgets such as `MonadStateAdapter` and `MonadReaderAdapter`. -/ class MonadFunctor (m m' : Type u → Type v) (n n' : Type u → Type w) := (monadMap {} {α : Type u} : (∀ {β}, m β → m' β) → n α → n' α) /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms such as `StateT.zoom`. A generalization of [MonadLiftFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadLiftFunctor), which can only lift endomorphisms (i.e. m = m', n = n'). -/ class MonadFunctorT (m m' : Type u → Type v) (n n' : Type u → Type w) := (monadMap {} {α : Type u} : (∀ {β}, m β → m' β) → n α → n' α) export MonadFunctorT (monadMap) instance monadFunctorTTrans (m m' n n' o o') [MonadFunctorT m m' n n'] [MonadFunctor n n' o o'] : MonadFunctorT m m' o o' := ⟨fun α f => MonadFunctor.monadMap (fun β => (monadMap @f : n β → n' β))⟩ instance monadFunctorTRefl (m m') : MonadFunctorT m m' m m' := ⟨fun α f => f⟩ theorem monadMapRefl {m m' : Type u → Type v} (f : ∀ {β}, m β → m' β) {α} : (monadMap @f : m α → m' α) = f := rfl /-- Run a Monad stack to completion. `run` should be the composition of the transformers' individual `run` functions. This class mostly saves some typing when using highly nested Monad stacks: ``` @[reducible] def MyMonad := ReaderT myCfg $ StateT myState $ ExceptT myErr id -- def MyMonad.run {α : Type} (x : MyMonad α) (cfg : myCfg) (st : myState) := ((x.run cfg).run st).run def MyMonad.run {α : Type} (x : MyMonad α) := MonadRun.run x ``` -/ class MonadRun (out : outParam $ Type u → Type v) (m : Type u → Type v) := (run {} {α : Type u} : m α → out α) export MonadRun (run)
c45f963275b2a90c3693f1c97572fd3db07432b9
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/fin.lean
f48d855b0dab38de29e38d6c95537ffacf3cab8b
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
78,564
lean
/- Copyright (c) 2017 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Keeley Hoek -/ import data.nat.cast import data.int.basic import tactic.localized import tactic.apply_fun import order.rel_iso /-! # The finite type with `n` elements `fin n` is the type whose elements are natural numbers smaller than `n`. This file expands on the development in the core library. ## Main definitions ### Induction principles * `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`. * `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. * `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument; * `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the `nat`-like base cases of `C 0` and `C (i.succ)`. * `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument. * `fin.cases` : define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = fin.succ j`, `j : fin n`, defined using `fin.induction`. * `fin.reverse_induction`: reverse induction on `i : fin (n + 1)`; given `C (fin.last n)` and `∀ i : fin n, C (fin.succ i) → C (fin.cast_succ i)`, constructs all values `C i` by going down; * `fin.last_cases`: define `f : Π i, fin (n + 1), C i` by separately handling the cases `i = fin.last n` and `i = fin.cast_succ j`, a special case of `fin.reverse_induction`; * `fin.add_cases`: define a function on `fin (m + n)` by separately handling the cases `fin.cast_add n i` and `fin.nat_add m i`; * `fin.succ_above_cases`: given `i : fin (n + 1)`, define a function on `fin (n + 1)` by separately handling the cases `j = i` and `j = fin.succ_above i k`, same as `fin.insert_nth` but marked as eliminator and works for `Sort*`. ### Order embeddings and an order isomorphism * `fin.coe_embedding` : coercion to natural numbers as an `order_embedding`; * `fin.succ_embedding` : `fin.succ` as an `order_embedding`; * `fin.cast_le h` : embed `fin n` into `fin m`, `h : n ≤ m`; * `fin.cast eq` : order isomorphism between `fin n` and fin m` provided that `n = m`, see also `equiv.fin_congr`; * `fin.cast_add m` : embed `fin n` into `fin (n+m)`; * `fin.cast_succ` : embed `fin n` into `fin (n+1)`; * `fin.succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`; * `fin.add_nat m i` : add `m` on `i` on the right, generalizes `fin.succ`; * `fin.nat_add n i` adds `n` on `i` on the left; ### Other casts * `fin.of_nat'`: given a positive number `n` (deduced from `[fact (0 < n)]`), `fin.of_nat' i` is `i % n` interpreted as an element of `fin n`; * `fin.cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into; * `fin.pred_above (p : fin n) i` : embed `i : fin (n+1)` into `fin n` by subtracting one if `p < i`; * `fin.cast_pred` : embed `fin (n + 2)` into `fin (n + 1)` by mapping `fin.last (n + 1)` to `fin.last n`; * `fin.sub_nat i h` : subtract `m` from `i ≥ m`, generalizes `fin.pred`; * `fin.clamp n m` : `min n m` as an element of `fin (m + 1)`; ### Operation on tuples We interpret maps `Π i : fin n, α i` as tuples `(α 0, …, α (n-1))`. If `α i` is a constant map, then tuples are isomorphic (but not definitionally equal) to `vector`s. We define the following operations: * `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries; * `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple; * `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries; * `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. * `insert_nth` : insert an element to a tuple at a given position. * `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. ### Misc definitions * `fin.last n` : The greatest value of `fin (n+1)`. -/ universes u v open fin nat function /-- Elimination principle for the empty set `fin 0`, dependent version. -/ def fin_zero_elim {α : fin 0 → Sort u} (x : fin 0) : α x := x.elim0 lemma fact.succ.pos {n} : fact (0 < succ n) := ⟨zero_lt_succ _⟩ lemma fact.bit0.pos {n} [h : fact (0 < n)] : fact (0 < bit0 n) := ⟨nat.zero_lt_bit0 $ ne_of_gt h.1⟩ lemma fact.bit1.pos {n} : fact (0 < bit1 n) := ⟨nat.zero_lt_bit1 _⟩ lemma fact.pow.pos {p n : ℕ} [h : fact $ 0 < p] : fact (0 < p ^ n) := ⟨pow_pos h.1 _⟩ localized "attribute [instance] fact.succ.pos" in fin_fact localized "attribute [instance] fact.bit0.pos" in fin_fact localized "attribute [instance] fact.bit1.pos" in fin_fact localized "attribute [instance] fact.pow.pos" in fin_fact namespace fin variables {n m : ℕ} {a b : fin n} instance fin_to_nat (n : ℕ) : has_coe (fin n) nat := ⟨subtype.val⟩ lemma pos_iff_nonempty {n : ℕ} : 0 < n ↔ nonempty (fin n) := ⟨λ h, ⟨⟨0, h⟩⟩, λ ⟨i⟩, lt_of_le_of_lt (nat.zero_le _) i.2⟩ section coe /-! ### coercions and constructions -/ @[simp] protected lemma eta (a : fin n) (h : (a : ℕ) < n) : (⟨(a : ℕ), h⟩ : fin n) = a := by cases a; refl @[ext] lemma ext {a b : fin n} (h : (a : ℕ) = b) : a = b := eq_of_veq h lemma ext_iff (a b : fin n) : a = b ↔ (a : ℕ) = b := iff.intro (congr_arg _) fin.eq_of_veq lemma coe_injective {n : ℕ} : injective (coe : fin n → ℕ) := subtype.coe_injective lemma eq_iff_veq (a b : fin n) : a = b ↔ a.1 = b.1 := ⟨veq_of_eq, eq_of_veq⟩ lemma ne_iff_vne (a b : fin n) : a ≠ b ↔ a.1 ≠ b.1 := ⟨vne_of_ne, ne_of_vne⟩ @[simp] lemma mk_eq_subtype_mk (a : ℕ) (h : a < n) : mk a h = ⟨a, h⟩ := rfl protected lemma mk.inj_iff {n a b : ℕ} {ha : a < n} {hb : b < n} : (⟨a, ha⟩ : fin n) = ⟨b, hb⟩ ↔ a = b := subtype.mk_eq_mk lemma mk_val {m n : ℕ} (h : m < n) : (⟨m, h⟩ : fin n).val = m := rfl lemma eq_mk_iff_coe_eq {k : ℕ} {hk : k < n} : a = ⟨k, hk⟩ ↔ (a : ℕ) = k := fin.eq_iff_veq a ⟨k, hk⟩ @[simp, norm_cast] lemma coe_mk {m n : ℕ} (h : m < n) : ((⟨m, h⟩ : fin n) : ℕ) = m := rfl lemma mk_coe (i : fin n) : (⟨i, i.property⟩ : fin n) = i := fin.eta _ _ lemma coe_eq_val (a : fin n) : (a : ℕ) = a.val := rfl @[simp] lemma val_eq_coe (a : fin n) : a.val = a := rfl /-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element, then they coincide (in the heq sense). -/ protected lemma heq_fun_iff {α : Sort*} {k l : ℕ} (h : k = l) {f : fin k → α} {g : fin l → α} : f == g ↔ (∀ (i : fin k), f i = g ⟨(i : ℕ), h ▸ i.2⟩) := by { induction h, simp [heq_iff_eq, function.funext_iff] } protected lemma heq_ext_iff {k l : ℕ} (h : k = l) {i : fin k} {j : fin l} : i == j ↔ (i : ℕ) = (j : ℕ) := by { induction h, simp [ext_iff] } lemma exists_iff {p : fin n → Prop} : (∃ i, p i) ↔ ∃ i h, p ⟨i, h⟩ := ⟨λ h, exists.elim h (λ ⟨i, hi⟩ hpi, ⟨i, hi, hpi⟩), λ h, exists.elim h (λ i hi, ⟨⟨i, hi.fst⟩, hi.snd⟩)⟩ lemma forall_iff {p : fin n → Prop} : (∀ i, p i) ↔ ∀ i h, p ⟨i, h⟩ := ⟨λ h i hi, h ⟨i, hi⟩, λ h ⟨i, hi⟩, h i hi⟩ end coe section order /-! ### order -/ lemma is_lt (i : fin n) : (i : ℕ) < n := i.2 lemma is_le (i : fin (n + 1)) : (i : ℕ) ≤ n := le_of_lt_succ i.is_lt lemma lt_iff_coe_lt_coe : a < b ↔ (a : ℕ) < b := iff.rfl lemma le_iff_coe_le_coe : a ≤ b ↔ (a : ℕ) ≤ b := iff.rfl lemma mk_lt_of_lt_coe {a : ℕ} (h : a < b) : (⟨a, h.trans b.is_lt⟩ : fin n) < b := h lemma mk_le_of_le_coe {a : ℕ} (h : a ≤ b) : (⟨a, h.trans_lt b.is_lt⟩ : fin n) ≤ b := h /-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_lt {n : ℕ} {a b : fin n} : (a : ℕ) < (b : ℕ) ↔ a < b := iff.rfl /-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `fin n`. -/ @[norm_cast, simp] lemma coe_fin_le {n : ℕ} {a b : fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b := iff.rfl instance {n : ℕ} : linear_order (fin n) := { le := (≤), lt := (<), decidable_le := fin.decidable_le, decidable_lt := fin.decidable_lt, decidable_eq := fin.decidable_eq _, ..linear_order.lift (coe : fin n → ℕ) (@fin.eq_of_veq _) } /-- The inclusion map `fin n → ℕ` is a relation embedding. -/ def coe_embedding (n) : (fin n) ↪o ℕ := ⟨⟨coe, @fin.eq_of_veq _⟩, λ a b, iff.rfl⟩ /-- The ordering on `fin n` is a well order. -/ instance fin.lt.is_well_order (n) : is_well_order (fin n) (<) := (coe_embedding n).is_well_order /-- Use the ordering on `fin n` for checking recursive definitions. For example, the following definition is not accepted by the termination checker, unless we declare the `has_well_founded` instance: ```lean def factorial {n : ℕ} : fin n → ℕ | ⟨0, _⟩ := 1 | ⟨i + 1, hi⟩ := (i + 1) * factorial ⟨i, i.lt_succ_self.trans hi⟩ ``` -/ instance {n : ℕ} : has_well_founded (fin n) := ⟨_, measure_wf coe⟩ @[simp] lemma coe_zero {n : ℕ} : ((0 : fin (n+1)) : ℕ) = 0 := rfl attribute [simp] val_zero @[simp] lemma val_zero' (n) : (0 : fin (n+1)).val = 0 := rfl @[simp] lemma mk_zero : (⟨0, nat.succ_pos'⟩ : fin (n + 1)) = (0 : fin _) := rfl lemma zero_le (a : fin (n + 1)) : 0 ≤ a := zero_le a.1 lemma zero_lt_one : (0 : fin (n + 2)) < 1 := nat.zero_lt_one lemma pos_iff_ne_zero (a : fin (n+1)) : 0 < a ↔ a ≠ 0 := by rw [← coe_fin_lt, coe_zero, pos_iff_ne_zero, ne.def, ne.def, ext_iff, coe_zero] lemma eq_zero_or_eq_succ {n : ℕ} (i : fin (n+1)) : i = 0 ∨ ∃ j : fin n, i = j.succ := begin rcases i with ⟨_|j, h⟩, { left, refl, }, { right, exact ⟨⟨j, nat.lt_of_succ_lt_succ h⟩, rfl⟩, } end /-- The greatest value of `fin (n+1)` -/ def last (n : ℕ) : fin (n+1) := ⟨_, n.lt_succ_self⟩ @[simp, norm_cast] lemma coe_last (n : ℕ) : (last n : ℕ) = n := rfl lemma last_val (n : ℕ) : (last n).val = n := rfl theorem le_last (i : fin (n+1)) : i ≤ last n := le_of_lt_succ i.is_lt instance : bounded_lattice (fin (n + 1)) := { top := last n, le_top := le_last, bot := 0, bot_le := zero_le, .. fin.linear_order, .. lattice_of_linear_order } lemma last_pos : (0 : fin (n + 2)) < last (n + 1) := by simp [lt_iff_coe_lt_coe] lemma eq_last_of_not_lt {i : fin (n+1)} (h : ¬ (i : ℕ) < n) : i = last n := le_antisymm (le_last i) (not_lt.1 h) section variables {α : Type*} [preorder α] open set /-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity map. In this lemma we state that for each `i : fin n` we have `(e i : ℕ) = (i : ℕ)`. -/ @[simp] lemma coe_order_iso_apply (e : fin n ≃o fin m) (i : fin n) : (e i : ℕ) = i := begin rcases i with ⟨i, hi⟩, rw [subtype.coe_mk], induction i using nat.strong_induction_on with i h, refine le_antisymm (forall_lt_iff_le.1 $ λ j hj, _) (forall_lt_iff_le.1 $ λ j hj, _), { have := e.symm.lt_iff_lt.2 (mk_lt_of_lt_coe hj), rw e.symm_apply_apply at this, convert this, simpa using h _ this (e.symm _).is_lt }, { rwa [← h j hj (hj.trans hi), ← lt_iff_coe_lt_coe, e.lt_iff_lt] } end instance order_iso_subsingleton : subsingleton (fin n ≃o α) := ⟨λ e e', by { ext i, rw [← e.symm.apply_eq_iff_eq, e.symm_apply_apply, ← e'.trans_apply, ext_iff, coe_order_iso_apply] }⟩ instance order_iso_subsingleton' : subsingleton (α ≃o fin n) := order_iso.symm_injective.subsingleton instance order_iso_unique : unique (fin n ≃o fin n) := unique.mk' _ /-- Two strictly monotone functions from `fin n` are equal provided that their ranges are equal. -/ lemma strict_mono_unique {f g : fin n → α} (hf : strict_mono f) (hg : strict_mono g) (h : range f = range g) : f = g := have (hf.order_iso f).trans (order_iso.set_congr _ _ h) = hg.order_iso g, from subsingleton.elim _ _, congr_arg (function.comp (coe : range g → α)) (funext $ rel_iso.ext_iff.1 this) /-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/ lemma order_embedding_eq {f g : fin n ↪o α} (h : range f = range g) : f = g := rel_embedding.ext $ funext_iff.1 $ strict_mono_unique f.strict_mono g.strict_mono h end /-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/ lemma strict_mono_iff_lt_succ {α : Type*} [preorder α] {f : fin n → α} : strict_mono f ↔ ∀ i (h : i + 1 < n), f ⟨i, lt_of_le_of_lt (nat.le_succ i) h⟩ < f ⟨i+1, h⟩ := begin split, { assume H i hi, apply H, exact nat.lt_succ_self _ }, { assume H, have A : ∀ i j (h : i < j) (h' : j < n), f ⟨i, lt_trans h h'⟩ < f ⟨j, h'⟩, { assume i j h h', induction h with k h IH, { exact H _ _ }, { exact lt_trans (IH (nat.lt_of_succ_lt h')) (H _ _) } }, assume i j hij, convert A (i : ℕ) (j : ℕ) hij j.2; ext; simp only [subtype.coe_eta] } end end order section add /-! ### addition, numerals, and coercion from nat -/ /-- Given a positive `n`, `fin.of_nat' i` is `i % n` as an element of `fin n`. -/ def of_nat' [h : fact (0 < n)] (i : ℕ) : fin n := ⟨i%n, mod_lt _ h.1⟩ lemma one_val {n : ℕ} : (1 : fin (n+1)).val = 1 % (n+1) := rfl lemma coe_one' {n : ℕ} : ((1 : fin (n+1)) : ℕ) = 1 % (n+1) := rfl @[simp] lemma val_one {n : ℕ} : (1 : fin (n+2)).val = 1 := rfl @[simp] lemma coe_one {n : ℕ} : ((1 : fin (n+2)) : ℕ) = 1 := rfl @[simp] lemma mk_one : (⟨1, nat.succ_lt_succ (nat.succ_pos n)⟩ : fin (n + 2)) = (1 : fin _) := rfl instance {n : ℕ} : nontrivial (fin (n + 2)) := ⟨⟨0, 1, dec_trivial⟩⟩ section monoid @[simp] protected lemma add_zero (k : fin (n + 1)) : k + 0 = k := by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)] @[simp] protected lemma zero_add (k : fin (n + 1)) : (0 : fin (n + 1)) + k = k := by simp [eq_iff_veq, add_def, mod_eq_of_lt (is_lt k)] instance add_comm_monoid (n : ℕ) : add_comm_monoid (fin (n + 1)) := { add := (+), add_assoc := by simp [eq_iff_veq, add_def, add_assoc], zero := 0, zero_add := fin.zero_add, add_zero := fin.add_zero, add_comm := by simp [eq_iff_veq, add_def, add_comm] } end monoid lemma val_add {n : ℕ} : ∀ a b : fin n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add {n : ℕ} : ∀ a b : fin n, ((a + b : fin n) : ℕ) = (a + b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_add_eq_ite {n : ℕ} (a b : fin n) : (↑(a + b) : ℕ) = if n ≤ a + b then a + b - n else a + b := by rw [fin.coe_add, nat.add_mod_eq_ite, nat.mod_eq_of_lt (show ↑a < n, from a.2), nat.mod_eq_of_lt (show ↑b < n, from b.2)] lemma coe_bit0 {n : ℕ} (k : fin n) : ((bit0 k : fin n) : ℕ) = bit0 (k : ℕ) % n := by { cases k, refl } lemma coe_bit1 {n : ℕ} (k : fin (n + 1)) : ((bit1 k : fin (n + 1)) : ℕ) = bit1 (k : ℕ) % (n + 1) := begin cases n, { cases k with k h, cases k, {show _ % _ = _, simp}, cases h with _ h, cases h }, simp [bit1, fin.coe_bit0, fin.coe_add, fin.coe_one], end lemma coe_add_one_of_lt {n : ℕ} {i : fin n.succ} (h : i < last _) : (↑(i + 1) : ℕ) = i + 1 := begin -- First show that `((1 : fin n.succ) : ℕ) = 1`, because `n.succ` is at least 2. cases n, { cases h }, -- Then just unfold the definitions. rw [fin.coe_add, fin.coe_one, nat.mod_eq_of_lt (nat.succ_lt_succ _)], exact h end @[simp] lemma last_add_one : ∀ n, last n + 1 = 0 | 0 := subsingleton.elim _ _ | (n + 1) := by { ext, rw [coe_add, coe_zero, coe_last, coe_one, nat.mod_self] } lemma coe_add_one {n : ℕ} (i : fin (n + 1)) : ((i + 1 : fin (n + 1)) : ℕ) = if i = last _ then 0 else i + 1 := begin rcases (le_last i).eq_or_lt with rfl|h, { simp }, { simpa [h.ne] using coe_add_one_of_lt h } end section bit @[simp] lemma mk_bit0 {m n : ℕ} (h : bit0 m < n) : (⟨bit0 m, h⟩ : fin n) = (bit0 ⟨m, (nat.le_add_right m m).trans_lt h⟩ : fin _) := eq_of_veq (nat.mod_eq_of_lt h).symm @[simp] lemma mk_bit1 {m n : ℕ} (h : bit1 m < n + 1) : (⟨bit1 m, h⟩ : fin (n + 1)) = (bit1 ⟨m, (nat.le_add_right m m).trans_lt ((m + m).lt_succ_self.trans h)⟩ : fin _) := begin ext, simp only [bit1, bit0] at h, simp only [bit1, bit0, coe_add, coe_one', coe_mk, ←nat.add_mod, nat.mod_eq_of_lt h], end end bit @[simp] lemma val_two {n : ℕ} : (2 : fin (n+3)).val = 2 := rfl @[simp] lemma coe_two {n : ℕ} : ((2 : fin (n+3)) : ℕ) = 2 := rfl section of_nat_coe @[simp] lemma of_nat_eq_coe (n : ℕ) (a : ℕ) : (of_nat a : fin (n+1)) = a := begin induction a with a ih, { refl }, ext, show (a+1) % (n+1) = subtype.val (a+1 : fin (n+1)), { rw [val_add, ← ih, of_nat], exact add_mod _ _ _ } end /-- Converting an in-range number to `fin (n + 1)` produces a result whose value is the original number. -/ lemma coe_val_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)).val) = a := begin rw ←of_nat_eq_coe, exact nat.mod_eq_of_lt h end /-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results in the same value. -/ lemma coe_val_eq_self {n : ℕ} (a : fin (n + 1)) : (a.val : fin (n + 1)) = a := begin rw fin.eq_iff_veq, exact coe_val_of_lt a.property end /-- Coercing an in-range number to `fin (n + 1)`, and converting back to `ℕ`, results in that number. -/ lemma coe_coe_of_lt {n : ℕ} {a : ℕ} (h : a < n + 1) : ((a : fin (n + 1)) : ℕ) = a := coe_val_of_lt h /-- Converting a `fin (n + 1)` to `ℕ` and back results in the same value. -/ @[simp] lemma coe_coe_eq_self {n : ℕ} (a : fin (n + 1)) : ((a : ℕ) : fin (n + 1)) = a := coe_val_eq_self a lemma coe_nat_eq_last (n) : (n : fin (n + 1)) = fin.last n := by { rw [←fin.of_nat_eq_coe, fin.of_nat, fin.last], simp only [nat.mod_eq_of_lt n.lt_succ_self] } lemma le_coe_last (i : fin (n + 1)) : i ≤ n := by { rw fin.coe_nat_eq_last, exact fin.le_last i } end of_nat_coe lemma add_one_pos (i : fin (n + 1)) (h : i < fin.last n) : (0 : fin (n + 1)) < i + 1 := begin cases n, { exact absurd h (nat.not_lt_zero _) }, { rw [lt_iff_coe_lt_coe, coe_last, ←add_lt_add_iff_right 1] at h, rw [lt_iff_coe_lt_coe, coe_add, coe_zero, coe_one, nat.mod_eq_of_lt h], exact nat.zero_lt_succ _ } end lemma one_pos : (0 : fin (n + 2)) < 1 := succ_pos 0 lemma zero_ne_one : (0 : fin (n + 2)) ≠ 1 := ne_of_lt one_pos @[simp] lemma zero_eq_one_iff : (0 : fin (n + 1)) = 1 ↔ n = 0 := begin split, { cases n; intro h, { refl }, { have := zero_ne_one, contradiction } }, { rintro rfl, refl } end @[simp] lemma one_eq_zero_iff : (1 : fin (n + 1)) = 0 ↔ n = 0 := by rw [eq_comm, zero_eq_one_iff] end add section succ /-! ### succ and casts into larger fin types -/ @[simp] lemma coe_succ (j : fin n) : (j.succ : ℕ) = j + 1 := by cases j; simp [fin.succ] lemma succ_pos (a : fin n) : (0 : fin (n + 1)) < a.succ := by simp [lt_iff_coe_lt_coe] /-- `fin.succ` as an `order_embedding` -/ def succ_embedding (n : ℕ) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono fin.succ $ λ ⟨i, hi⟩ ⟨j, hj⟩ h, succ_lt_succ h @[simp] lemma coe_succ_embedding : ⇑(succ_embedding n) = fin.succ := rfl @[simp] lemma succ_le_succ_iff : a.succ ≤ b.succ ↔ a ≤ b := (succ_embedding n).le_iff_le @[simp] lemma succ_lt_succ_iff : a.succ < b.succ ↔ a < b := (succ_embedding n).lt_iff_lt lemma succ_injective (n : ℕ) : injective (@fin.succ n) := (succ_embedding n).injective @[simp] lemma succ_inj {a b : fin n} : a.succ = b.succ ↔ a = b := (succ_injective n).eq_iff lemma succ_ne_zero {n} : ∀ k : fin n, fin.succ k ≠ 0 | ⟨k, hk⟩ heq := nat.succ_ne_zero k $ (ext_iff _ _).1 heq @[simp] lemma succ_zero_eq_one : fin.succ (0 : fin (n + 1)) = 1 := rfl @[simp] lemma succ_one_eq_two : fin.succ (1 : fin (n + 2)) = 2 := rfl @[simp] lemma succ_mk (n i : ℕ) (h : i < n) : fin.succ ⟨i, h⟩ = ⟨i + 1, nat.succ_lt_succ h⟩ := rfl lemma mk_succ_pos (i : ℕ) (h : i < n) : (0 : fin (n + 1)) < ⟨i.succ, add_lt_add_right h 1⟩ := by { rw [lt_iff_coe_lt_coe, coe_zero], exact nat.succ_pos i } lemma one_lt_succ_succ (a : fin n) : (1 : fin (n + 2)) < a.succ.succ := begin cases n, { exact fin_zero_elim a }, { rw [←succ_zero_eq_one, succ_lt_succ_iff], exact succ_pos a } end lemma succ_succ_ne_one (a : fin n) : fin.succ (fin.succ a) ≠ 1 := ne_of_gt (one_lt_succ_succ a) /-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/ def cast_lt (i : fin m) (h : i.1 < n) : fin n := ⟨i.1, h⟩ @[simp] lemma coe_cast_lt (i : fin m) (h : i.1 < n) : (cast_lt i h : ℕ) = i := rfl @[simp] lemma cast_lt_mk (i n m : ℕ) (hn : i < n) (hm : i < m) : cast_lt ⟨i, hn⟩ hm = ⟨i, hm⟩ := rfl /-- `cast_le h i` embeds `i` into a larger `fin` type. -/ def cast_le (h : n ≤ m) : fin n ↪o fin m := order_embedding.of_strict_mono (λ a, cast_lt a (lt_of_lt_of_le a.2 h)) $ λ a b h, h @[simp] lemma coe_cast_le (h : n ≤ m) (i : fin n) : (cast_le h i : ℕ) = i := rfl @[simp] lemma cast_le_mk (i n m : ℕ) (hn : i < n) (h : n ≤ m) : cast_le h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h⟩ := rfl @[simp] lemma cast_le_zero {n m : ℕ} (h : n.succ ≤ m.succ) : cast_le h 0 = 0 := by simp [eq_iff_veq] @[simp] lemma range_cast_le {n k : ℕ} (h : n ≤ k) : set.range (cast_le h) = {i | (i : ℕ) < n} := set.ext (λ x, ⟨λ ⟨y, hy⟩, hy ▸ y.2, λ hx, ⟨⟨x, hx⟩, fin.ext rfl⟩⟩) @[simp] lemma coe_of_injective_cast_le_symm {n k : ℕ} (h : n ≤ k) (i : fin k) (hi) : ((equiv.of_injective _ (cast_le h).injective).symm ⟨i, hi⟩ : ℕ) = i := begin rw ← coe_cast_le, exact congr_arg coe (equiv.apply_of_injective_symm _ _ _) end @[simp] lemma cast_le_succ {m n : ℕ} (h : (m + 1) ≤ (n + 1)) (i : fin m) : cast_le h i.succ = (cast_le (nat.succ_le_succ_iff.mp h) i).succ := by simp [fin.eq_iff_veq] /-- `cast eq i` embeds `i` into a equal `fin` type, see also `equiv.fin_congr`. -/ def cast (eq : n = m) : fin n ≃o fin m := { to_equiv := ⟨cast_le eq.le, cast_le eq.symm.le, λ a, eq_of_veq rfl, λ a, eq_of_veq rfl⟩, map_rel_iff' := λ a b, iff.rfl } @[simp] lemma symm_cast (h : n = m) : (cast h).symm = cast h.symm := rfl lemma coe_cast (h : n = m) (i : fin n) : (cast h i : ℕ) = i := rfl @[simp] lemma cast_mk (h : n = m) (i : ℕ) (hn : i < n) : cast h ⟨i, hn⟩ = ⟨i, lt_of_lt_of_le hn h.le⟩ := rfl @[simp] lemma cast_trans {k : ℕ} (h : n = m) (h' : m = k) {i : fin n} : cast h' (cast h i) = cast (eq.trans h h') i := rfl @[simp] lemma cast_refl (h : n = n := rfl) : cast h = order_iso.refl (fin n) := by { ext, refl } /-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma cast_to_equiv (h : n = m) : (cast h).to_equiv = equiv.cast (h ▸ rfl) := by { subst h, simp } /-- While in many cases `fin.cast` is better than `equiv.cast`/`cast`, sometimes we want to apply a generic theorem about `cast`. -/ lemma cast_eq_cast (h : n = m) : (cast h : fin n → fin m) = _root_.cast (h ▸ rfl) := by { subst h, ext, simp } /-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. See also `fin.nat_add` and `fin.add_nat`. -/ def cast_add (m) : fin n ↪o fin (n + m) := cast_le $ nat.le_add_right n m @[simp] lemma coe_cast_add (m : ℕ) (i : fin n) : (cast_add m i : ℕ) = i := rfl lemma cast_add_lt {m : ℕ} (n : ℕ) (i : fin m) : (cast_add n i : ℕ) < m := i.2 @[simp] lemma cast_add_mk (m : ℕ) (i : ℕ) (h : i < n) : cast_add m ⟨i, h⟩ = ⟨i, lt_add_right i n m h⟩ := rfl @[simp] lemma cast_add_cast_lt (m : ℕ) (i : fin (n + m)) (hi : i.val < n) : cast_add m (cast_lt i hi) = i := ext rfl @[simp] lemma cast_lt_cast_add (m : ℕ) (i : fin n) : cast_lt (cast_add m i) (cast_add_lt m i) = i := ext rfl /-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/ def cast_succ : fin n ↪o fin (n + 1) := cast_add 1 @[simp] lemma coe_cast_succ (i : fin n) : (i.cast_succ : ℕ) = i := rfl @[simp] lemma cast_succ_mk (n i : ℕ) (h : i < n) : cast_succ ⟨i, h⟩ = ⟨i, nat.lt.step h⟩ := rfl lemma cast_succ_lt_succ (i : fin n) : i.cast_succ < i.succ := lt_iff_coe_lt_coe.2 $ by simp only [coe_cast_succ, coe_succ, nat.lt_succ_self] lemma le_cast_succ_iff {i : fin (n + 1)} {j : fin n} : i ≤ j.cast_succ ↔ i < j.succ := by simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe] using nat.succ_le_succ_iff.symm @[simp] lemma succ_last (n : ℕ) : (last n).succ = last (n.succ) := rfl @[simp] lemma succ_eq_last_succ {n : ℕ} (i : fin n.succ) : i.succ = last (n + 1) ↔ i = last n := by rw [← succ_last, (succ_injective _).eq_iff] @[simp] lemma cast_succ_cast_lt (i : fin (n + 1)) (h : (i : ℕ) < n) : cast_succ (cast_lt i h) = i := fin.eq_of_veq rfl @[simp] lemma cast_lt_cast_succ {n : ℕ} (a : fin n) (h : (a : ℕ) < n) : cast_lt (cast_succ a) h = a := by cases a; refl @[simp] lemma cast_succ_lt_cast_succ_iff : a.cast_succ < b.cast_succ ↔ a < b := (@cast_succ n).lt_iff_lt lemma cast_succ_injective (n : ℕ) : injective (@fin.cast_succ n) := (cast_succ : fin n ↪o _).injective lemma cast_succ_inj {a b : fin n} : a.cast_succ = b.cast_succ ↔ a = b := (cast_succ_injective n).eq_iff lemma cast_succ_lt_last (a : fin n) : cast_succ a < last n := lt_iff_coe_lt_coe.mpr a.is_lt @[simp] lemma cast_succ_zero : cast_succ (0 : fin (n + 1)) = 0 := rfl @[simp] lemma cast_succ_one {n : ℕ} : fin.cast_succ (1 : fin (n + 2)) = 1 := rfl /-- `cast_succ i` is positive when `i` is positive -/ lemma cast_succ_pos {i : fin (n + 1)} (h : 0 < i) : 0 < cast_succ i := by simpa [lt_iff_coe_lt_coe] using h @[simp] lemma cast_succ_eq_zero_iff (a : fin (n + 1)) : a.cast_succ = 0 ↔ a = 0 := subtype.ext_iff.trans $ (subtype.ext_iff.trans $ by exact iff.rfl).symm lemma cast_succ_ne_zero_iff (a : fin (n + 1)) : a.cast_succ ≠ 0 ↔ a ≠ 0 := not_iff_not.mpr $ cast_succ_eq_zero_iff a lemma cast_succ_fin_succ (n : ℕ) (j : fin n) : cast_succ (fin.succ j) = fin.succ (cast_succ j) := by simp [fin.ext_iff] @[norm_cast, simp] lemma coe_eq_cast_succ : (a : fin (n + 1)) = a.cast_succ := begin ext, exact coe_val_of_lt (nat.lt.step a.is_lt), end @[simp] lemma coe_succ_eq_succ : a.cast_succ + 1 = a.succ := begin cases n, { exact fin_zero_elim a }, { simp [a.is_lt, eq_iff_veq, add_def, nat.mod_eq_of_lt] } end lemma lt_succ : a.cast_succ < a.succ := by { rw [cast_succ, lt_iff_coe_lt_coe, coe_cast_add, coe_succ], exact lt_add_one a.val } @[simp] lemma range_cast_succ {n : ℕ} : set.range (cast_succ : fin n → fin n.succ) = {i | (i : ℕ) < n} := range_cast_le _ @[simp] lemma coe_of_injective_cast_succ_symm {n : ℕ} (i : fin n.succ) (hi) : ((equiv.of_injective cast_succ (cast_succ_injective _)).symm ⟨i, hi⟩ : ℕ) = i := begin rw ← coe_cast_succ, exact congr_arg coe (equiv.apply_of_injective_symm _ _ _) end lemma succ_cast_succ {n : ℕ} (i : fin n) : i.cast_succ.succ = i.succ.cast_succ := fin.ext (by simp) /-- `add_nat m i` adds `m` to `i`, generalizes `fin.succ`. -/ def add_nat (m) : fin n ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨(i : ℕ) + m, add_lt_add_right i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_right h _ @[simp] lemma coe_add_nat (m : ℕ) (i : fin n) : (add_nat m i : ℕ) = i + m := rfl lemma le_coe_add_nat (m : ℕ) (i : fin n) : m ≤ add_nat m i := nat.le_add_left _ _ @[simp] lemma add_nat_mk (n i : ℕ) (hi : i < m) : add_nat n ⟨i, hi⟩ = ⟨i + n, add_lt_add_right hi n⟩ := rfl /-- `nat_add n i` adds `n` to `i` "on the left". -/ def nat_add (n) {m} : fin m ↪o fin (n + m) := order_embedding.of_strict_mono (λ i, ⟨n + (i : ℕ), add_lt_add_left i.2 _⟩) $ λ i j h, lt_iff_coe_lt_coe.2 $ add_lt_add_left h _ @[simp] lemma coe_nat_add (n : ℕ) {m : ℕ} (i : fin m) : (nat_add n i : ℕ) = n + i := rfl @[simp] lemma nat_add_mk (n i : ℕ) (hi : i < m) : nat_add n ⟨i, hi⟩ = ⟨n + i, add_lt_add_left hi n⟩ := rfl lemma le_coe_nat_add (m : ℕ) (i : fin n) : m ≤ nat_add m i := nat.le_add_right _ _ lemma nat_add_zero {n : ℕ} : fin.nat_add 0 = (fin.cast (zero_add n).symm).to_rel_embedding := by { ext, apply zero_add } @[simp] lemma cast_nat_add (n : ℕ) {m : ℕ} (i : fin m) : cast (add_comm _ _) (nat_add n i) = add_nat n i := ext $ add_comm _ _ @[simp] lemma cast_add_nat {n : ℕ} (m : ℕ) (i : fin n) : cast (add_comm _ _) (add_nat m i) = nat_add m i := ext $ add_comm _ _ end succ section pred /-! ### pred -/ @[simp] lemma coe_pred (j : fin (n+1)) (h : j ≠ 0) : (j.pred h : ℕ) = j - 1 := by { cases j, refl } @[simp] lemma succ_pred : ∀(i : fin (n+1)) (h : i ≠ 0), (i.pred h).succ = i | ⟨0, h⟩ hi := by contradiction | ⟨n + 1, h⟩ hi := rfl @[simp] lemma pred_succ (i : fin n) {h : i.succ ≠ 0} : i.succ.pred h = i := by { cases i, refl } @[simp] lemma pred_mk_succ (i : ℕ) (h : i < n + 1) : fin.pred ⟨i + 1, add_lt_add_right h 1⟩ (ne_of_vne (ne_of_gt (mk_succ_pos i h))) = ⟨i, h⟩ := by simp only [ext_iff, coe_pred, coe_mk, nat.add_sub_cancel] -- This is not a simp lemma by default, because `pred_mk_succ` is nicer when it applies. lemma pred_mk {n : ℕ} (i : ℕ) (h : i < n + 1) (w) : fin.pred ⟨i, h⟩ w = ⟨i - 1, by rwa nat.sub_lt_right_iff_lt_add (nat.pos_of_ne_zero (fin.vne_of_ne w))⟩ := rfl @[simp] lemma pred_le_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha ≤ b.pred hb ↔ a ≤ b := by rw [←succ_le_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_lt_pred_iff {n : ℕ} {a b : fin n.succ} {ha : a ≠ 0} {hb : b ≠ 0} : a.pred ha < b.pred hb ↔ a < b := by rw [←succ_lt_succ_iff, succ_pred, succ_pred] @[simp] lemma pred_inj : ∀ {a b : fin (n + 1)} {ha : a ≠ 0} {hb : b ≠ 0}, a.pred ha = b.pred hb ↔ a = b | ⟨0, _⟩ b ha hb := by contradiction | ⟨i+1, _⟩ ⟨0, _⟩ ha hb := by contradiction | ⟨i+1, hi⟩ ⟨j+1, hj⟩ ha hb := by simp [fin.eq_iff_veq] @[simp] lemma pred_one {n : ℕ} : fin.pred (1 : fin (n + 2)) (ne.symm (ne_of_lt one_pos)) = 0 := rfl lemma pred_add_one (i : fin (n + 2)) (h : (i : ℕ) < n + 1) : pred (i + 1) (ne_of_gt (add_one_pos _ (lt_iff_coe_lt_coe.mpr h))) = cast_lt i h := begin rw [ext_iff, coe_pred, coe_cast_lt, coe_add, coe_one, mod_eq_of_lt, nat.add_sub_cancel], exact add_lt_add_right h 1, end /-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/ def sub_nat (m) (i : fin (n + m)) (h : m ≤ (i : ℕ)) : fin n := ⟨(i : ℕ) - m, by { rw [nat.sub_lt_right_iff_lt_add h], exact i.is_lt }⟩ @[simp] lemma coe_sub_nat (i : fin (n + m)) (h : m ≤ i) : (i.sub_nat m h : ℕ) = i - m := rfl @[simp] lemma sub_nat_mk {i : ℕ} (h₁ : i < n + m) (h₂ : m ≤ i) : sub_nat m ⟨i, h₁⟩ h₂ = ⟨i - m, (sub_lt_iff_right h₂).2 h₁⟩ := rfl @[simp] lemma pred_cast_succ_succ (i : fin n) : pred (cast_succ i.succ) (ne_of_gt (cast_succ_pos i.succ_pos)) = i.cast_succ := by simp [eq_iff_veq] @[simp] lemma add_nat_sub_nat {i : fin (n + m)} (h : m ≤ i) : add_nat m (sub_nat m i h) = i := ext $ nat.sub_add_cancel h @[simp] lemma sub_nat_add_nat (i : fin n) (m : ℕ) (h : m ≤ add_nat m i := le_coe_add_nat m i) : sub_nat m (add_nat m i) h = i := ext $ nat.add_sub_cancel i m @[simp] lemma nat_add_sub_nat_cast {i : fin (n + m)} (h : n ≤ i) : nat_add n (sub_nat n (cast (add_comm _ _) i) h) = i := by simp [← cast_add_nat] end pred section rec /-! ### recursion and induction principles -/ /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. -/ @[elab_as_eliminator] def succ_rec {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : Π {n : ℕ} (i : fin n), C n i | 0 i := i.elim0 | (succ n) ⟨0, _⟩ := H0 _ | (succ n) ⟨succ i, h⟩ := Hs _ _ (succ_rec ⟨i, lt_of_succ_lt_succ h⟩) /-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succ…`. This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple. A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/ @[elab_as_eliminator] def succ_rec_on {n : ℕ} (i : fin n) {C : Π n, fin n → Sort*} (H0 : Π n, C (succ n) 0) (Hs : Π n i, C n i → C (succ n) i.succ) : C n i := i.succ_rec H0 Hs @[simp] theorem succ_rec_on_zero {C : ∀ n, fin n → Sort*} {H0 Hs} (n) : @fin.succ_rec_on (succ n) 0 C H0 Hs = H0 n := rfl @[simp] theorem succ_rec_on_succ {C : ∀ n, fin n → Sort*} {H0 Hs} {n} (i : fin n) : @fin.succ_rec_on (succ n) i.succ C H0 Hs = Hs n i (fin.succ_rec_on i H0 Hs) := by cases i; refl /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. -/ @[elab_as_eliminator] def induction {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : Π (i : fin (n + 1)), C i := begin rintro ⟨i, hi⟩, induction i with i IH, { rwa [fin.mk_zero] }, { refine hs ⟨i, lt_of_succ_lt_succ hi⟩ _, exact IH (lt_of_succ_lt hi) } end /-- Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `h0` handles the base case on `C 0`, and `hs` defines the inductive step using `C i.cast_succ`. A version of `fin.induction` taking `i : fin (n + 1)` as the first argument. -/ @[elab_as_eliminator] def induction_on (i : fin (n + 1)) {C : fin (n + 1) → Sort*} (h0 : C 0) (hs : ∀ i : fin n, C i.cast_succ → C i.succ) : C i := induction h0 hs i /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = 0` and `i = j.succ`, `j : fin n`. -/ @[elab_as_eliminator] def cases {C : fin (succ n) → Sort*} (H0 : C 0) (Hs : Π i : fin n, C (i.succ)) : Π (i : fin (succ n)), C i := induction H0 (λ i _, Hs i) @[simp] theorem cases_zero {n} {C : fin (succ n) → Sort*} {H0 Hs} : @fin.cases n C H0 Hs 0 = H0 := rfl @[simp] theorem cases_succ {n} {C : fin (succ n) → Sort*} {H0 Hs} (i : fin n) : @fin.cases n C H0 Hs i.succ = Hs i := by cases i; refl @[simp] theorem cases_succ' {n} {C : fin (succ n) → Sort*} {H0 Hs} {i : ℕ} (h : i + 1 < n + 1) : @fin.cases n C H0 Hs ⟨i.succ, h⟩ = Hs ⟨i, lt_of_succ_lt_succ h⟩ := by cases i; refl lemma forall_fin_succ {P : fin (n+1) → Prop} : (∀ i, P i) ↔ P 0 ∧ (∀ i:fin n, P i.succ) := ⟨λ H, ⟨H 0, λ i, H _⟩, λ ⟨H0, H1⟩ i, fin.cases H0 H1 i⟩ lemma exists_fin_succ {P : fin (n+1) → Prop} : (∃ i, P i) ↔ P 0 ∨ (∃i:fin n, P i.succ) := ⟨λ ⟨i, h⟩, fin.cases or.inl (λ i hi, or.inr ⟨i, hi⟩) i h, λ h, or.elim h (λ h, ⟨0, h⟩) $ λ⟨i, hi⟩, ⟨i.succ, hi⟩⟩ lemma forall_fin_one {p : fin 1 → Prop} : (∀ i, p i) ↔ p 0 := @unique.forall_iff (fin 1) _ p lemma exists_fin_one {p : fin 1 → Prop} : (∃ i, p i) ↔ p 0 := @unique.exists_iff (fin 1) _ p lemma forall_fin_two {p : fin 2 → Prop} : (∀ i, p i) ↔ p 0 ∧ p 1 := forall_fin_succ.trans $ and_congr_right $ λ _, forall_fin_one lemma exists_fin_two {p : fin 2 → Prop} : (∃ i, p i) ↔ p 0 ∨ p 1 := exists_fin_succ.trans $ or_congr_right exists_fin_one /-- Define `C i` by reverse induction on `i : fin (n + 1)` via induction on the underlying `nat` value. This function has two arguments: `hlast` handles the base case on `C (fin.last n)`, and `hs` defines the inductive step using `C i.succ`, inducting downwards. -/ @[elab_as_eliminator] def reverse_induction {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) : Π (i : fin (n + 1)), C i | i := if hi : i = fin.last n then _root_.cast (by rw hi) hlast else let j : fin n := ⟨i, lt_of_le_of_ne (nat.le_of_lt_succ i.2) (λ h, hi (fin.ext h))⟩ in have wf : n + 1 - j.succ < n + 1 - i, begin cases i, rw [nat.sub_lt_sub_left_iff]; simp [*, nat.succ_le_iff], end, have hi : i = fin.cast_succ j, from fin.ext rfl, _root_.cast (by rw hi) (hs _ (reverse_induction j.succ)) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ i : fin (n+1), n + 1 - i)⟩], dec_tac := `[assumption] } @[simp] lemma reverse_induction_last {n : ℕ} {C : fin (n + 1) → Sort*} (h0 : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) : (reverse_induction h0 hs (fin.last n) : C (fin.last n)) = h0 := by rw [reverse_induction]; simp @[simp] lemma reverse_induction_cast_succ {n : ℕ} {C : fin (n + 1) → Sort*} (h0 : C (fin.last n)) (hs : ∀ i : fin n, C i.succ → C i.cast_succ) (i : fin n): (reverse_induction h0 hs i.cast_succ : C i.cast_succ) = hs i (reverse_induction h0 hs i.succ) := begin rw [reverse_induction, dif_neg (ne_of_lt (fin.cast_succ_lt_last i))], cases i, refl end /-- Define `f : Π i : fin n.succ, C i` by separately handling the cases `i = fin.last n` and `i = j.cast_succ`, `j : fin n`. -/ @[elab_as_eliminator, elab_strategy] def last_cases {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin (n + 1)) : C i := reverse_induction hlast (λ i _, hcast i) i @[simp] lemma last_cases_last {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) : (fin.last_cases hlast hcast (fin.last n): C (fin.last n)) = hlast := reverse_induction_last _ _ @[simp] lemma last_cases_cast_succ {n : ℕ} {C : fin (n + 1) → Sort*} (hlast : C (fin.last n)) (hcast : (Π (i : fin n), C i.cast_succ)) (i : fin n) : (fin.last_cases hlast hcast (fin.cast_succ i): C (fin.cast_succ i)) = hcast i := reverse_induction_cast_succ _ _ _ /-- Define `f : Π i : fin (m + n), C i` by separately handling the cases `i = cast_add n i`, `j : fin m` and `i = nat_add m j`, `j : fin n`. -/ @[elab_as_eliminator, elab_strategy] def add_cases {m n : ℕ} {C : fin (m + n) → Sort u} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin (m + n)) : C i := if hi : (i : ℕ) < m then eq.rec_on (cast_add_cast_lt n i hi) (hleft (cast_lt i hi)) else eq.rec_on (nat_add_sub_nat_cast (le_of_not_lt hi)) (hright _) @[simp] lemma add_cases_left {m n : ℕ} {C : fin (m + n) → Sort*} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin m) : add_cases hleft hright (fin.cast_add n i) = hleft i := begin cases i with i hi, rw [add_cases, dif_pos (cast_add_lt _ _)], refl end @[simp] lemma add_cases_right {m n : ℕ} {C : fin (m + n) → Sort*} (hleft : Π i, C (cast_add n i)) (hright : Π i, C (nat_add m i)) (i : fin n) : add_cases hleft hright (nat_add m i) = hright i := begin have : ¬ (nat_add m i : ℕ) < m, from (le_coe_nat_add _ _).not_lt, rw [add_cases, dif_neg this], refine eq_of_heq ((eq_rec_heq _ _).trans _), congr' 1, simp end end rec section add_group open nat int /-- Negation on `fin n` -/ instance (n : ℕ) : has_neg (fin n) := ⟨λ a, ⟨(n - a) % n, nat.mod_lt _ (lt_of_le_of_lt (nat.zero_le _) a.2)⟩⟩ /-- Abelian group structure on `fin (n+1)`. -/ instance (n : ℕ) : add_comm_group (fin (n+1)) := { add_left_neg := λ ⟨a, ha⟩, fin.ext $ trans (nat.mod_add_mod _ _ _) $ by { rw [fin.coe_mk, fin.coe_zero, nat.sub_add_cancel, nat.mod_self], exact le_of_lt ha }, sub_eq_add_neg := λ ⟨a, ha⟩ ⟨b, hb⟩, fin.ext $ show (a + (n + 1 - b)) % (n + 1) = (a + (n + 1 - b) % (n + 1)) % (n + 1), by simp, sub := fin.sub, ..fin.add_comm_monoid n, ..fin.has_neg n.succ } protected lemma coe_neg (a : fin n) : ((-a : fin n) : ℕ) = (n - a) % n := rfl protected lemma coe_sub (a b : fin n) : ((a - b : fin n) : ℕ) = (a + (n - b)) % n := by cases a; cases b; refl end add_group section succ_above lemma succ_above_aux (p : fin (n + 1)) : strict_mono (λ i : fin n, if i.cast_succ < p then i.cast_succ else i.succ) := (cast_succ : fin n ↪o _).strict_mono.ite (succ_embedding n).strict_mono (λ i j hij hj, lt_trans ((cast_succ : fin n ↪o _).lt_iff_lt.2 hij) hj) (λ i, (cast_succ_lt_succ i).le) /-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/ def succ_above (p : fin (n + 1)) : fin n ↪o fin (n + 1) := order_embedding.of_strict_mono _ p.succ_above_aux /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/ lemma succ_above_below (p : fin (n + 1)) (i : fin n) (h : i.cast_succ < p) : p.succ_above i = i.cast_succ := by { rw [succ_above], exact if_pos h } @[simp] lemma succ_above_ne_zero_zero {a : fin (n + 2)} (ha : a ≠ 0) : a.succ_above 0 = 0 := begin rw fin.succ_above_below, { refl }, { exact bot_lt_iff_ne_bot.mpr ha } end lemma succ_above_eq_zero_iff {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) : a.succ_above b = 0 ↔ b = 0 := by simp only [←succ_above_ne_zero_zero ha, order_embedding.eq_iff_eq] lemma succ_above_ne_zero {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0) : a.succ_above b ≠ 0 := mt (succ_above_eq_zero_iff ha).mp hb /-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/ @[simp] lemma succ_above_zero : ⇑(succ_above (0 : fin (n + 1))) = fin.succ := rfl /-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/ @[simp] lemma succ_above_last : succ_above (fin.last n) = cast_succ := by { ext, simp only [succ_above_below, cast_succ_lt_last] } lemma succ_above_last_apply (i : fin n) : succ_above (fin.last n) i = i.cast_succ := by rw succ_above_last /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` embeds `i` by `succ` when the resulting `p < i.succ`. -/ lemma succ_above_above (p : fin (n + 1)) (i : fin n) (h : p ≤ i.cast_succ) : p.succ_above i = i.succ := by simp [succ_above, h.not_lt] /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_ge (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p ≤ i.cast_succ := lt_or_ge (cast_succ i) p /-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/ lemma succ_above_lt_gt (p : fin (n + 1)) (i : fin n) : i.cast_succ < p ∨ p < i.succ := or.cases_on (succ_above_lt_ge p i) (λ h, or.inl h) (λ h, or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i))) /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater results in a value that is less than `p`. -/ @[simp] lemma succ_above_lt_iff (p : fin (n + 1)) (i : fin n) : p.succ_above i < p ↔ i.cast_succ < p := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { exact H }, { rw succ_above_above _ _ H at h, exact lt_trans (cast_succ_lt_succ i) h } }, { intro h, rw succ_above_below _ _ h, exact h } end /-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser results in a value that is greater than `p`. -/ lemma lt_succ_above_iff (p : fin (n + 1)) (i : fin n) : p < p.succ_above i ↔ p ≤ i.cast_succ := begin refine iff.intro _ _, { intro h, cases succ_above_lt_ge p i with H H, { rw succ_above_below _ _ H at h, exact le_of_lt h }, { exact H } }, { intro h, rw succ_above_above _ _ h, exact lt_of_le_of_lt h (cast_succ_lt_succ i) }, end /-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)` never results in `p` itself -/ theorem succ_above_ne (p : fin (n + 1)) (i : fin n) : p.succ_above i ≠ p := begin intro eq, by_cases H : i.cast_succ < p, { simpa [lt_irrefl, ←succ_above_below _ _ H, eq] using H }, { simpa [←succ_above_above _ _ (le_of_not_lt H), eq] using cast_succ_lt_succ i } end /-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/ lemma succ_above_pos (p : fin (n + 2)) (i : fin (n + 1)) (h : 0 < i) : 0 < p.succ_above i := begin by_cases H : i.cast_succ < p, { simpa [succ_above_below _ _ H] using cast_succ_pos h }, { simpa [succ_above_above _ _ (le_of_not_lt H)] using succ_pos _ }, end @[simp] lemma succ_above_cast_lt {x y : fin (n + 1)} (h : x < y) (hx : x.1 < n := lt_of_lt_of_le h y.le_last) : y.succ_above (x.cast_lt hx) = x := by { rw [succ_above_below, cast_succ_cast_lt], exact h } @[simp] lemma succ_above_pred {x y : fin (n + 1)} (h : x < y) (hy : y ≠ 0 := (x.zero_le.trans_lt h).ne') : x.succ_above (y.pred hy) = y := by { rw [succ_above_above, succ_pred], simpa [le_iff_coe_le_coe] using nat.le_pred_of_lt h } lemma cast_lt_succ_above {x : fin n} {y : fin (n + 1)} (h : cast_succ x < y) (h' : (y.succ_above x).1 < n := lt_of_lt_of_le ((succ_above_lt_iff _ _).2 h) (le_last y)) : (y.succ_above x).cast_lt h' = x := by simp only [succ_above_below _ _ h, cast_lt_cast_succ] lemma pred_succ_above {x : fin n} {y : fin (n + 1)} (h : y ≤ cast_succ x) (h' : y.succ_above x ≠ 0 := (y.zero_le.trans_lt $ (lt_succ_above_iff _ _).2 h).ne') : (y.succ_above x).pred h' = x := by simp only [succ_above_above _ _ h, pred_succ] lemma exists_succ_above_eq {x y : fin (n + 1)} (h : x ≠ y) : ∃ z, y.succ_above z = x := begin cases h.lt_or_lt with hlt hlt, exacts [⟨_, succ_above_cast_lt hlt⟩, ⟨_, succ_above_pred hlt⟩], end @[simp] lemma exists_succ_above_eq_iff {x y : fin (n + 1)} : (∃ z, x.succ_above z = y) ↔ y ≠ x := begin refine ⟨_, exists_succ_above_eq⟩, rintro ⟨y, rfl⟩, exact succ_above_ne _ _ end /-- The range of `p.succ_above` is everything except `p`. -/ @[simp] lemma range_succ_above (p : fin (n + 1)) : set.range (p.succ_above) = {p}ᶜ := set.ext $ λ _, exists_succ_above_eq_iff /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_injective {x : fin (n + 1)} : injective (succ_above x) := (succ_above x).injective /-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/ lemma succ_above_right_inj {x : fin (n + 1)} : x.succ_above a = x.succ_above b ↔ a = b := succ_above_right_injective.eq_iff /-- `succ_above` is injective at the pivot -/ lemma succ_above_left_injective : injective (@succ_above n) := λ _ _ h, by simpa [range_succ_above] using congr_arg (λ f : fin n ↪o fin (n + 1), (set.range f)ᶜ) h /-- `succ_above` is injective at the pivot -/ @[simp] lemma succ_above_left_inj {x y : fin (n + 1)} : x.succ_above = y.succ_above ↔ x = y := succ_above_left_injective.eq_iff @[simp] lemma zero_succ_above {n : ℕ} (i : fin n) : (0 : fin (n + 1)).succ_above i = i.succ := rfl @[simp] lemma succ_succ_above_zero {n : ℕ} (i : fin (n + 1)) : (i.succ).succ_above 0 = 0 := succ_above_below _ _ (succ_pos _) @[simp] lemma succ_succ_above_succ {n : ℕ} (i : fin (n + 1)) (j : fin n) : (i.succ).succ_above j.succ = (i.succ_above j).succ := (lt_or_ge j.cast_succ i).elim (λ h, have h' : j.succ.cast_succ < i.succ, by simpa [lt_iff_coe_lt_coe] using h, by { ext, simp [succ_above_below _ _ h, succ_above_below _ _ h'] }) (λ h, have h' : i.succ ≤ j.succ.cast_succ, by simpa [le_iff_coe_le_coe] using h, by { ext, simp [succ_above_above _ _ h, succ_above_above _ _ h'] }) @[simp] lemma one_succ_above_zero {n : ℕ} : (1 : fin (n + 2)).succ_above 0 = 0 := succ_succ_above_zero 0 /-- By moving `succ` to the outside of this expression, we create opportunities for further simplification using `succ_above_zero` or `succ_succ_above_zero`. -/ @[simp] lemma succ_succ_above_one {n : ℕ} (i : fin (n + 2)) : (i.succ).succ_above 1 = (i.succ_above 0).succ := succ_succ_above_succ i 0 @[simp] lemma one_succ_above_succ {n : ℕ} (j : fin n) : (1 : fin (n + 2)).succ_above j.succ = j.succ.succ := succ_succ_above_succ 0 j @[simp] lemma one_succ_above_one {n : ℕ} : (1 : fin (n + 3)).succ_above 1 = 2 := succ_succ_above_succ 0 0 end succ_above section pred_above /-- `pred_above p i` embeds `i : fin (n+1)` into `fin n` by subtracting one if `p < i`. -/ def pred_above (p : fin n) (i : fin (n+1)) : fin n := if h : p.cast_succ < i then i.pred (ne_of_lt (lt_of_le_of_lt (zero_le p.cast_succ) h)).symm else i.cast_lt (lt_of_le_of_lt (le_of_not_lt h) p.2) lemma pred_above_right_monotone (p : fin n) : monotone p.pred_above := λ a b H, begin dsimp [pred_above], split_ifs with ha hb hb, all_goals { simp only [le_iff_coe_le_coe, coe_pred], }, { exact pred_le_pred H, }, { calc _ ≤ _ : nat.pred_le _ ... ≤ _ : H, }, { simp at ha, exact le_pred_of_lt (lt_of_le_of_lt ha hb), }, { exact H, }, end lemma pred_above_left_monotone (i : fin (n + 1)) : monotone (λ p, pred_above p i) := λ a b H, begin dsimp [pred_above], split_ifs with ha hb hb, all_goals { simp only [le_iff_coe_le_coe, coe_pred] }, { exact pred_le _, }, { have : b < a := cast_succ_lt_cast_succ_iff.mpr (hb.trans_le (le_of_not_gt ha)), exact absurd H this.not_le } end /-- `cast_pred` embeds `i : fin (n + 2)` into `fin (n + 1)` by lowering just `last (n + 1)` to `last n`. -/ def cast_pred (i : fin (n + 2)) : fin (n + 1) := pred_above (last n) i @[simp] lemma cast_pred_zero : cast_pred (0 : fin (n + 2)) = 0 := rfl @[simp] lemma cast_pred_one : cast_pred (1 : fin (n + 2)) = 1 := by { cases n, apply subsingleton.elim, refl } @[simp] theorem pred_above_zero {i : fin (n + 2)} (hi : i ≠ 0) : pred_above 0 i = i.pred hi := begin dsimp [pred_above], rw dif_pos, exact (pos_iff_ne_zero _).mpr hi, end @[simp] lemma cast_pred_last : cast_pred (last (n + 1)) = last n := by simp [eq_iff_veq, cast_pred, pred_above, cast_succ_lt_last] @[simp] lemma cast_pred_mk (n i : ℕ) (h : i < n + 1) : cast_pred ⟨i, lt_succ_of_lt h⟩ = ⟨i, h⟩ := begin have : ¬cast_succ (last n) < ⟨i, lt_succ_of_lt h⟩, { simpa [lt_iff_coe_lt_coe] using le_of_lt_succ h }, simp [cast_pred, pred_above, this] end lemma pred_above_below (p : fin (n + 1)) (i : fin (n + 2)) (h : i ≤ p.cast_succ) : p.pred_above i = i.cast_pred := begin have : i ≤ (last n).cast_succ := h.trans p.le_last, simp [pred_above, cast_pred, h.not_lt, this.not_lt] end @[simp] lemma pred_above_last : pred_above (fin.last n) = cast_pred := rfl lemma pred_above_last_apply (i : fin n) : pred_above (fin.last n) i = i.cast_pred := by rw pred_above_last lemma pred_above_above (p : fin n) (i : fin (n + 1)) (h : p.cast_succ < i) : p.pred_above i = i.pred (p.cast_succ.zero_le.trans_lt h).ne.symm := by simp [pred_above, h] lemma cast_pred_monotone : monotone (@cast_pred n) := pred_above_right_monotone (last _) /-- Sending `fin (n+1)` to `fin n` by subtracting one from anything above `p` then back to `fin (n+1)` with a gap around `p` is the identity away from `p`. -/ @[simp] lemma succ_above_pred_above {p : fin n} {i : fin (n + 1)} (h : i ≠ p.cast_succ) : p.cast_succ.succ_above (p.pred_above i) = i := begin dsimp [pred_above, succ_above], rcases p with ⟨p, _⟩, rcases i with ⟨i, _⟩, cases lt_or_le i p with H H, { rw dif_neg, rw if_pos, refl, exact H, simp, apply le_of_lt H, }, { rw dif_pos, rw if_neg, swap 3, -- For some reason `simp` doesn't fire fully unless we discharge the third goal. { exact lt_of_le_of_ne H (ne.symm h), }, { simp, }, { simp only [subtype.mk_eq_mk, ne.def, fin.cast_succ_mk] at h, simp only [pred, subtype.mk_lt_mk, not_lt], exact nat.le_pred_of_lt (nat.lt_of_le_and_ne H (ne.symm h)), }, }, end /-- Sending `fin n` into `fin (n + 1)` with a gap at `p` then back to `fin n` by subtracting one from anything above `p` is the identity. -/ @[simp] lemma pred_above_succ_above (p : fin n) (i : fin n) : p.pred_above (p.cast_succ.succ_above i) = i := begin dsimp [pred_above, succ_above], rcases p with ⟨p, _⟩, rcases i with ⟨i, _⟩, split_ifs, { rw dif_neg, { refl }, { simp_rw [if_pos h], simp only [subtype.mk_lt_mk, not_lt], exact le_of_lt h, }, }, { rw dif_pos, { refl, }, { simp_rw [if_neg h], exact lt_succ_iff.mpr (not_lt.mp h), }, }, end lemma cast_succ_pred_eq_pred_cast_succ {a : fin (n + 1)} (ha : a ≠ 0) (ha' := a.cast_succ_ne_zero_iff.mpr ha) : (a.pred ha).cast_succ = a.cast_succ.pred ha' := by { cases a, refl } /-- `pred` commutes with `succ_above`. -/ lemma pred_succ_above_pred {a : fin (n + 2)} {b : fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0) (hk := succ_above_ne_zero ha hb) : (a.pred ha).succ_above (b.pred hb) = (a.succ_above b).pred hk := begin obtain hbelow | habove := lt_or_le b.cast_succ a, -- `rwa` uses them { rw fin.succ_above_below, { rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_inj, fin.succ_above_below] }, { rwa [cast_succ_pred_eq_pred_cast_succ , pred_lt_pred_iff] } }, { rw fin.succ_above_above, have : (b.pred hb).succ = b.succ.pred (fin.succ_ne_zero _), by rw [succ_pred, pred_succ], { rwa [this, fin.pred_inj, fin.succ_above_above] }, { rwa [cast_succ_pred_eq_pred_cast_succ , fin.pred_le_pred_iff] } } end @[simp] theorem cast_pred_cast_succ (i : fin (n + 1)) : cast_pred i.cast_succ = i := by simp [cast_pred, pred_above, le_last] lemma cast_succ_cast_pred {i : fin (n + 2)} (h : i < last _) : cast_succ i.cast_pred = i := begin rw [cast_pred, pred_above, dif_neg], { simp [fin.eq_iff_veq] }, { exact h.not_le } end lemma coe_cast_pred_le_self (i : fin (n + 2)) : (i.cast_pred : ℕ) ≤ i := begin rcases i.le_last.eq_or_lt with rfl|h, { simp }, { rw [cast_pred, pred_above, dif_neg], { simp }, { simpa [lt_iff_coe_lt_coe, le_iff_coe_le_coe, lt_succ_iff] using h } } end lemma coe_cast_pred_lt_iff {i : fin (n + 2)} : (i.cast_pred : ℕ) < i ↔ i = fin.last _ := begin rcases i.le_last.eq_or_lt with rfl|H, { simp }, { simp only [ne_of_lt H], rw ←cast_succ_cast_pred H, simp } end lemma lt_last_iff_coe_cast_pred {i : fin (n + 2)} : i < fin.last _ ↔ (i.cast_pred : ℕ) = i := begin rcases i.le_last.eq_or_lt with rfl|H, { simp }, { simp only [H], rw ←cast_succ_cast_pred H, simp } end end pred_above /-- `min n m` as an element of `fin (m + 1)` -/ def clamp (n m : ℕ) : fin (m + 1) := of_nat $ min n m @[simp] lemma coe_clamp (n m : ℕ) : (clamp n m : ℕ) = min n m := nat.mod_eq_of_lt $ nat.lt_succ_iff.mpr $ min_le_right _ _ section tuple /-! ### Tuples We can think of the type `Π(i : fin n), α i` as `n`-tuples of elements of possibly varying type `α i`. A particular case is `fin n → α` of elements with all the same type. Here are some relevant operations, first about adding or removing elements at the beginning of a tuple. -/ /-- There is exactly one tuple of size zero. -/ example (α : fin 0 → Sort u) : unique (Π i : fin 0, α i) := by apply_instance @[simp] lemma tuple0_le {α : Π i : fin 0, Type*} [Π i, preorder (α i)] (f g : Π i, α i) : f ≤ g := fin_zero_elim variables {α : fin (n+1) → Type u} (x : α 0) (q : Πi, α i) (p : Π(i : fin n), α (i.succ)) (i : fin n) (y : α i.succ) (z : α 0) /-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/ def tail (q : Πi, α i) : (Π(i : fin n), α (i.succ)) := λ i, q i.succ lemma tail_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} : tail (λ k : fin (n+1), q k) = (λ k : fin n, q k.succ) := rfl /-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/ def cons (x : α 0) (p : Π(i : fin n), α (i.succ)) : Πi, α i := λ j, fin.cases x p j @[simp] lemma tail_cons : tail (cons x p) = p := by simp [tail, cons] @[simp] lemma cons_succ : cons x p i.succ = p i := by simp [cons] @[simp] lemma cons_zero : cons x p 0 = x := by simp [cons] /-- Updating a tuple and adding an element at the beginning commute. -/ @[simp] lemma cons_update : cons x (update p i y) = update (cons x p) i.succ y := begin ext j, by_cases h : j = 0, { rw h, simp [ne.symm (succ_ne_zero i)] }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ], by_cases h' : j' = i, { rw h', simp }, { have : j'.succ ≠ i.succ, by rwa [ne.def, succ_inj], rw [update_noteq h', update_noteq this, cons_succ] } } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_cons_zero : update (cons x p) 0 z = cons z p := begin ext j, by_cases h : j = 0, { rw h, simp }, { simp only [h, update_noteq, ne.def, not_false_iff], let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, cons_succ] } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma cons_self_tail : cons (q 0) (tail q) = q := begin ext j, by_cases h : j = 0, { rw h, simp }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, tail, cons_succ] } end /-- Updating the first element of a tuple does not change the tail. -/ @[simp] lemma tail_update_zero : tail (update q 0 z) = tail q := by { ext j, simp [tail, fin.succ_ne_zero] } /-- Updating a nonzero element and taking the tail commute. -/ @[simp] lemma tail_update_succ : tail (update q i.succ y) = update (tail q) i y := begin ext j, by_cases h : j = i, { rw h, simp [tail] }, { simp [tail, (fin.succ_injective n).ne h, h] } end lemma comp_cons {α : Type*} {β : Type*} (g : α → β) (y : α) (q : fin n → α) : g ∘ (cons y q) = cons (g y) (g ∘ q) := begin ext j, by_cases h : j = 0, { rw h, refl }, { let j' := pred j h, have : j'.succ = j := succ_pred j h, rw [← this, cons_succ, comp_app, cons_succ] } end lemma comp_tail {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (tail q) = tail (g ∘ q) := by { ext j, simp [tail] } lemma le_cons [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p := forall_fin_succ.trans $ and_congr iff.rfl $ forall_congr $ λ j, by simp [tail] lemma cons_le [Π i, preorder (α i)] {x : α 0} {q : Π i, α i} {p : Π i : fin n, α i.succ} : cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q := @le_cons _ (λ i, order_dual (α i)) _ x q p @[simp] lemma range_cons {α : Type*} {n : ℕ} (x : α) (b : fin n → α) : set.range (fin.cons x b : fin n.succ → α) = insert x (set.range b) := begin ext y, simp only [set.mem_range, set.mem_insert_iff], split, { rintros ⟨i, rfl⟩, refine cases (or.inl (cons_zero _ _)) (λ i, or.inr ⟨i, _⟩) i, rw cons_succ }, { rintros (rfl | ⟨i, hi⟩), { exact ⟨0, fin.cons_zero _ _⟩ }, { refine ⟨i.succ, _⟩, rw [cons_succ, hi] } } end /-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce one of length `o = m + n`. `ho` provides control of definitional equality for the vector length. -/ def append {α : Type*} {o : ℕ} (ho : o = m + n) (u : fin m → α) (v : fin n → α) : fin o → α := λ i, if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, (nat.sub_lt_left_iff_lt_add (le_of_not_lt h)).2 (ho ▸ i.property)⟩ @[simp] lemma fin_append_apply_zero {α : Type*} {o : ℕ} (ho : (o + 1) = (m + 1) + n) (u : fin (m + 1) → α) (v : fin n → α) : fin.append ho u v 0 = u 0 := rfl end tuple section tuple_right /-! In the previous section, we have discussed inserting or removing elements on the left of a tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed inductively from `fin n` starting from the left, not from the right. This implies that Lean needs more help to realize that elements belong to the right types, i.e., we need to insert casts at several places. -/ variables {α : fin (n+1) → Type u} (x : α (last n)) (q : Πi, α i) (p : Π(i : fin n), α i.cast_succ) (i : fin n) (y : α i.cast_succ) (z : α (last n)) /-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/ def init (q : Πi, α i) (i : fin n) : α i.cast_succ := q i.cast_succ lemma init_def {n : ℕ} {α : fin (n+1) → Type*} {q : Π i, α i} : init (λ k : fin (n+1), q k) = (λ k : fin n, q k.cast_succ) := rfl /-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/ def snoc (p : Π(i : fin n), α i.cast_succ) (x : α (last n)) (i : fin (n+1)) : α i := if h : i.val < n then _root_.cast (by rw fin.cast_succ_cast_lt i h) (p (cast_lt i h)) else _root_.cast (by rw eq_last_of_not_lt h) x @[simp] lemma init_snoc : init (snoc p x) = p := begin ext i, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [init, snoc, i.is_lt, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_cast_succ : snoc p x i.cast_succ = p i := begin have : i.cast_succ.val < n := i.is_lt, have h' := fin.cast_lt_cast_succ i i.is_lt, simp [snoc, this, h'], convert cast_eq rfl (p i) end @[simp] lemma snoc_last : snoc p x (last n) = x := by { simp [snoc] } /-- Updating a tuple and adding an element at the end commute. -/ @[simp] lemma snoc_update : snoc (update p i y) x = update (snoc p x) i.cast_succ y := begin ext j, by_cases h : j.val < n, { simp only [snoc, h, dif_pos], by_cases h' : j = cast_succ i, { have C1 : α i.cast_succ = α j, by rw h', have E1 : update (snoc p x) i.cast_succ y j = _root_.cast C1 y, { have : update (snoc p x) j (_root_.cast C1 y) j = _root_.cast C1 y, by simp, convert this, { exact h'.symm }, { exact heq_of_cast_eq (congr_arg α (eq.symm h')) rfl } }, have C2 : α i.cast_succ = α (cast_succ (cast_lt j h)), by rw [cast_succ_cast_lt, h'], have E2 : update p i y (cast_lt j h) = _root_.cast C2 y, { have : update p (cast_lt j h) (_root_.cast C2 y) (cast_lt j h) = _root_.cast C2 y, by simp, convert this, { simp [h, h'] }, { exact heq_of_cast_eq C2 rfl } }, rw [E1, E2], exact eq_rec_compose _ _ _ }, { have : ¬(cast_lt j h = i), by { assume E, apply h', rw [← E, cast_succ_cast_lt] }, simp [h', this, snoc, h] } }, { rw eq_last_of_not_lt h, simp [ne.symm (ne_of_lt (cast_succ_lt_last i))] } end /-- Adding an element at the beginning of a tuple and then updating it amounts to adding it directly. -/ lemma update_snoc_last : update (snoc p x) (last n) z = snoc p z := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc] }, { rw eq_last_of_not_lt h, simp } end /-- Concatenating the first element of a tuple with its tail gives back the original tuple -/ @[simp] lemma snoc_init_self : snoc (init q) (q (last n)) = q := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, update_noteq, this, snoc, init, cast_succ_cast_lt], have A : cast_succ (cast_lt j h) = j := cast_succ_cast_lt _ _, rw ← cast_eq rfl (q j), congr' 1; rw A }, { rw eq_last_of_not_lt h, simp } end /-- Updating the last element of a tuple does not change the beginning. -/ @[simp] lemma init_update_last : init (update q (last n) z) = init q := by { ext j, simp [init, ne_of_lt, cast_succ_lt_last] } /-- Updating an element and taking the beginning commute. -/ @[simp] lemma init_update_cast_succ : init (update q i.cast_succ y) = update (init q) i y := begin ext j, by_cases h : j = i, { rw h, simp [init] }, { simp [init, h] } end /-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma tail_init_eq_init_tail {β : Type*} (q : fin (n+2) → β) : tail (init q) = init (tail q) := by { ext i, simp [tail, init, cast_succ_fin_succ] } /-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it would involve a cast to convince Lean that the two types are equal, making it harder to use. -/ lemma cons_snoc_eq_snoc_cons {β : Type*} (a : β) (q : fin n → β) (b : β) : @cons n.succ (λ i, β) a (snoc q b) = snoc (cons a q) b := begin ext i, by_cases h : i = 0, { rw h, refl }, set j := pred i h with ji, have : i = j.succ, by rw [ji, succ_pred], rw [this, cons_succ], by_cases h' : j.val < n, { set k := cast_lt j h' with jk, have : j = k.cast_succ, by rw [jk, cast_succ_cast_lt], rw [this, ← cast_succ_fin_succ], simp }, rw [eq_last_of_not_lt h', succ_last], simp end lemma comp_snoc {α : Type*} {β : Type*} (g : α → β) (q : fin n → α) (y : α) : g ∘ (snoc q y) = snoc (g ∘ q) (g y) := begin ext j, by_cases h : j.val < n, { have : j ≠ last n := ne_of_lt h, simp [h, this, snoc, cast_succ_cast_lt] }, { rw eq_last_of_not_lt h, simp } end lemma comp_init {α : Type*} {β : Type*} (g : α → β) (q : fin n.succ → α) : g ∘ (init q) = init (g ∘ q) := by { ext j, simp [init] } end tuple_right section insert_nth variables {α : fin (n+1) → Type u} {β : Type v} /-- Define a function on `fin (n + 1)` from a value on `i : fin (n + 1)` and values on each `fin.succ_above i j`, `j : fin n`. This version is elaborated as eliminator and works for propositions, see also `fin.insert_nth` for a version without an `@[elab_as_eliminator]` attribute. -/ @[elab_as_eliminator] def succ_above_cases {α : fin (n + 1) → Sort u} (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) : α j := if hj : j = i then eq.rec x hj.symm else if hlt : j < i then eq.rec_on (succ_above_cast_lt hlt) (p _) else eq.rec_on (succ_above_pred $ (ne.lt_or_lt hj).resolve_left hlt) (p _) lemma forall_iff_succ_above {p : fin (n + 1) → Prop} (i : fin (n + 1)) : (∀ j, p j) ↔ p i ∧ ∀ j, p (i.succ_above j) := ⟨λ h, ⟨h _, λ j, h _⟩, λ h, succ_above_cases i h.1 h.2⟩ /-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`, for `i = fin.last n` see `fin.snoc`. See also `fin.succ_above_cases` for a version elaborated as an eliminator. -/ def insert_nth (i : fin (n + 1)) (x : α i) (p : Π j : fin n, α (i.succ_above j)) (j : fin (n + 1)) : α j := succ_above_cases i x p j @[simp] lemma insert_nth_apply_same (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) : insert_nth i x p i = x := by simp [insert_nth, succ_above_cases] @[simp] lemma insert_nth_apply_succ_above (i : fin (n + 1)) (x : α i) (p : Π j, α (i.succ_above j)) (j : fin n) : insert_nth i x p (i.succ_above j) = p j := begin simp only [insert_nth, succ_above_cases, dif_neg (succ_above_ne _ _)], by_cases hlt : j.cast_succ < i, { rw [dif_pos ((succ_above_lt_iff _ _).2 hlt)], apply eq_of_heq ((eq_rec_heq _ _).trans _), rw [cast_lt_succ_above hlt] }, { rw [dif_neg (mt (succ_above_lt_iff _ _).1 hlt)], apply eq_of_heq ((eq_rec_heq _ _).trans _), rw [pred_succ_above (le_of_not_lt hlt)] } end @[simp] lemma succ_above_cases_eq_insert_nth : @succ_above_cases.{u + 1} = @insert_nth.{u} := rfl @[simp] lemma insert_nth_comp_succ_above (i : fin (n + 1)) (x : β) (p : fin n → β) : insert_nth i x p ∘ i.succ_above = p := funext $ insert_nth_apply_succ_above i x p lemma insert_nth_eq_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p = q ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := by simp [funext_iff, forall_iff_succ_above i, eq_comm] lemma eq_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q = i.insert_nth x p ↔ q i = x ∧ p = (λ j, q (i.succ_above j)) := eq_comm.trans insert_nth_eq_iff lemma insert_nth_apply_below {i j : fin (n + 1)} (h : j < i) (x : α i) (p : Π k, α (i.succ_above k)) : i.insert_nth x p j = eq.rec_on (succ_above_cast_lt h) (p $ j.cast_lt _) := by rw [insert_nth, succ_above_cases, dif_neg h.ne, dif_pos h] lemma insert_nth_apply_above {i j : fin (n + 1)} (h : i < j) (x : α i) (p : Π k, α (i.succ_above k)) : i.insert_nth x p j = eq.rec_on (succ_above_pred h) (p $ j.pred _) := by rw [insert_nth, succ_above_cases, dif_neg h.ne', dif_neg h.not_lt] lemma insert_nth_zero (x : α 0) (p : Π j : fin n, α (succ_above 0 j)) : insert_nth 0 x p = cons x (λ j, _root_.cast (congr_arg α (congr_fun succ_above_zero j)) (p j)) := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, convert (cons_succ _ _ _).symm end @[simp] lemma insert_nth_zero' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) 0 x p = cons x p := by simp [insert_nth_zero] lemma insert_nth_last (x : α (last n)) (p : Π j : fin n, α ((last n).succ_above j)) : insert_nth (last n) x p = snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x := begin refine insert_nth_eq_iff.2 ⟨by simp, _⟩, ext j, apply eq_of_heq, transitivity snoc (λ j, _root_.cast (congr_arg α (succ_above_last_apply j)) (p j)) x j.cast_succ, { rw [snoc_cast_succ], exact (cast_heq _ _).symm }, { apply congr_arg_heq, rw [succ_above_last] } end @[simp] lemma insert_nth_last' (x : β) (p : fin n → β) : @insert_nth _ (λ _, β) (last n) x p = snoc p x := by simp [insert_nth_last] @[simp] lemma insert_nth_zero_right [Π j, has_zero (α j)] (i : fin (n + 1)) (x : α i) : i.insert_nth x 0 = pi.single i x := insert_nth_eq_iff.2 $ by simp [succ_above_ne, pi.zero_def] lemma insert_nth_binop (op : Π j, α j → α j → α j) (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (op i x y) (λ j, op _ (p j) (q j)) = λ j, op j (i.insert_nth x p j) (i.insert_nth y q j) := insert_nth_eq_iff.2 $ by simp @[simp] lemma insert_nth_mul [Π j, has_mul (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x * y) (p * q) = i.insert_nth x p * i.insert_nth y q := insert_nth_binop (λ _, (*)) i x y p q @[simp] lemma insert_nth_add [Π j, has_add (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x + y) (p + q) = i.insert_nth x p + i.insert_nth y q := insert_nth_binop (λ _, (+)) i x y p q @[simp] lemma insert_nth_div [Π j, has_div (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x / y) (p / q) = i.insert_nth x p / i.insert_nth y q := insert_nth_binop (λ _, (/)) i x y p q @[simp] lemma insert_nth_sub [Π j, has_sub (α j)] (i : fin (n + 1)) (x y : α i) (p q : Π j, α (i.succ_above j)) : i.insert_nth (x - y) (p - q) = i.insert_nth x p - i.insert_nth y q := insert_nth_binop (λ _, has_sub.sub) i x y p q @[simp] lemma insert_nth_sub_same [Π j, add_group (α j)] (i : fin (n + 1)) (x y : α i) (p : Π j, α (i.succ_above j)) : i.insert_nth x p - i.insert_nth y p = pi.single i (x - y) := by simp_rw [← insert_nth_sub, ← insert_nth_zero_right, pi.sub_def, sub_self, pi.zero_def] variables [Π i, preorder (α i)] lemma insert_nth_le_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : i.insert_nth x p ≤ q ↔ x ≤ q i ∧ p ≤ (λ j, q (i.succ_above j)) := by simp [pi.le_def, forall_iff_succ_above i] lemma le_insert_nth_iff {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q : Π j, α j} : q ≤ i.insert_nth x p ↔ q i ≤ x ∧ (λ j, q (i.succ_above j)) ≤ p := by simp [pi.le_def, forall_iff_succ_above i] open set lemma insert_nth_mem_Icc {i : fin (n + 1)} {x : α i} {p : Π j, α (i.succ_above j)} {q₁ q₂ : Π j, α j} : i.insert_nth x p ∈ Icc q₁ q₂ ↔ x ∈ Icc (q₁ i) (q₂ i) ∧ p ∈ Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := by simp only [mem_Icc, insert_nth_le_iff, le_insert_nth_iff, and.assoc, and.left_comm] lemma preimage_insert_nth_Icc_of_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∈ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = Icc (λ j, q₁ (i.succ_above j)) (λ j, q₂ (i.succ_above j)) := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, true_and] lemma preimage_insert_nth_Icc_of_not_mem {i : fin (n + 1)} {x : α i} {q₁ q₂ : Π j, α j} (hx : x ∉ Icc (q₁ i) (q₂ i)) : i.insert_nth x ⁻¹' (Icc q₁ q₂) = ∅ := set.ext $ λ p, by simp only [mem_preimage, insert_nth_mem_Icc, hx, false_and, mem_empty_eq] end insert_nth section find /-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never satisfied. -/ def find : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p], option (fin n) | 0 p _ := none | (n+1) p _ := by resetI; exact option.cases_on (@find n (λ i, p (i.cast_lt (nat.lt_succ_of_lt i.2))) _) (if h : p (fin.last n) then some (fin.last n) else none) (λ i, some (i.cast_lt (nat.lt_succ_of_lt i.2))) /-- If `find p = some i`, then `p i` holds -/ lemma find_spec : Π {n : ℕ} (p : fin n → Prop) [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p), p i | 0 p I i hi := option.no_confusion hi | (n+1) p I i hi := begin dsimp [find] at hi, resetI, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { rw h at hi, dsimp at hi, split_ifs at hi with hl hl, { exact option.some_inj.1 hi ▸ hl }, { exact option.no_confusion hi } }, { rw h at hi, rw [← option.some_inj.1 hi], exact find_spec _ h } end /-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/ lemma is_some_find_iff : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p], by exactI (find p).is_some ↔ ∃ i, p i | 0 p _ := iff_of_false (λ h, bool.no_confusion h) (λ ⟨i, _⟩, fin_zero_elim i) | (n+1) p _ := ⟨λ h, begin rw [option.is_some_iff_exists] at h, cases h with i hi, exactI ⟨i, find_spec _ hi⟩ end, λ ⟨⟨i, hin⟩, hi⟩, begin resetI, dsimp [find], cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with j, { split_ifs with hl hl, { exact option.is_some_some }, { have := (@is_some_find_iff n (λ x, p (x.cast_lt (nat.lt_succ_of_lt x.2))) _).2 ⟨⟨i, lt_of_le_of_ne (nat.le_of_lt_succ hin) (λ h, by clear_aux_decl; cases h; exact hl hi)⟩, hi⟩, rw h at this, exact this } }, { simp } end⟩ /-- `find p` returns `none` if and only if `p i` never holds. -/ lemma find_eq_none_iff {n : ℕ} {p : fin n → Prop} [decidable_pred p] : find p = none ↔ ∀ i, ¬ p i := by rw [← not_exists, ← is_some_find_iff]; cases (find p); simp /-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among the indices where `p` holds. -/ lemma find_min : Π {n : ℕ} {p : fin n → Prop} [decidable_pred p] {i : fin n} (hi : i ∈ by exactI fin.find p) {j : fin n} (hj : j < i), ¬ p j | 0 p _ i hi j hj hpj := option.no_confusion hi | (n+1) p _ i hi ⟨j, hjn⟩ hj hpj := begin resetI, dsimp [find] at hi, cases h : find (λ i : fin n, (p (i.cast_lt (nat.lt_succ_of_lt i.2)))) with k, { rw [h] at hi, split_ifs at hi with hl hl, { have := option.some_inj.1 hi, subst this, rw [find_eq_none_iff] at h, exact h ⟨j, hj⟩ hpj }, { exact option.no_confusion hi } }, { rw h at hi, dsimp at hi, have := option.some_inj.1 hi, subst this, exact find_min h (show (⟨j, lt_trans hj k.2⟩ : fin n) < k, from hj) hpj } end lemma find_min' {p : fin n → Prop} [decidable_pred p] {i : fin n} (h : i ∈ fin.find p) {j : fin n} (hj : p j) : i ≤ j := le_of_not_gt (λ hij, find_min h hij hj) lemma nat_find_mem_find {p : fin n → Prop} [decidable_pred p] (h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) : (⟨nat.find h, (nat.find_spec h).fst⟩ : fin n) ∈ find p := let ⟨i, hin, hi⟩ := h in begin cases hf : find p with f, { rw [find_eq_none_iff] at hf, exact (hf ⟨i, hin⟩ hi).elim }, { refine option.some_inj.2 (le_antisymm _ _), { exact find_min' hf (nat.find_spec h).snd }, { exact nat.find_min' _ ⟨f.2, by convert find_spec p hf; exact fin.eta _ _⟩ } } end lemma mem_find_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : i ∈ fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j := ⟨λ hi, ⟨find_spec _ hi, λ _, find_min' hi⟩, begin rintros ⟨hpi, hj⟩, cases hfp : fin.find p, { rw [find_eq_none_iff] at hfp, exact (hfp _ hpi).elim }, { exact option.some_inj.2 (le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp))) } end⟩ lemma find_eq_some_iff {p : fin n → Prop} [decidable_pred p] {i : fin n} : fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j := mem_find_iff lemma mem_find_of_unique {p : fin n → Prop} [decidable_pred p] (h : ∀ i j, p i → p j → i = j) {i : fin n} (hi : p i) : i ∈ fin.find p := mem_find_iff.2 ⟨hi, λ j hj, le_of_eq $ h i j hi hj⟩ end find @[simp] lemma coe_of_nat_eq_mod (m n : ℕ) : ((n : fin (succ m)) : ℕ) = n % succ m := by rw [← of_nat_eq_coe]; refl @[simp] lemma coe_of_nat_eq_mod' (m n : ℕ) [I : fact (0 < m)] : (@fin.of_nat' _ I n : ℕ) = n % m := rfl section mul /-! ### mul -/ lemma val_mul {n : ℕ} : ∀ a b : fin n, (a * b).val = (a.val * b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma coe_mul {n : ℕ} : ∀ a b : fin n, ((a * b : fin n) : ℕ) = (a * b) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp] protected lemma mul_one (k : fin (n + 1)) : k * 1 = k := by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] } @[simp] protected lemma one_mul (k : fin (n + 1)) : (1 : fin (n + 1)) * k = k := by { cases n, simp, simp [eq_iff_veq, mul_def, mod_eq_of_lt (is_lt k)] } @[simp] protected lemma mul_zero (k : fin (n + 1)) : k * 0 = 0 := by simp [eq_iff_veq, mul_def] @[simp] protected lemma zero_mul (k : fin (n + 1)) : (0 : fin (n + 1)) * k = 0 := by simp [eq_iff_veq, mul_def] end mul end fin
eebd84a0766adda9f817539c563a3220ba30d057
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/substlet.lean
aa903ba537c05ec1f743c364634130faf9ca19b9
[ "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
530
lean
theorem ex1 (n : Nat) : 0 + n = n := by let m := n have h : ∃ k, id k = m := ⟨m, rfl⟩ cases h with | intro a e => trace_state subst e trace_state apply Nat.zero_add theorem ex2 (n : Nat) : 0 + n = n := by let m := n have h : ∃ k, m = id k := ⟨m, rfl⟩ cases h with | intro a e => trace_state subst e trace_state apply Nat.zero_add theorem ex3 (n : Nat) (h : n = 0) : 0 + n = 0 := by let m := n + 1 let v := m + 1 have : v = n + 2 := rfl subst v -- error done
5a97313e4b757d902a872178aaf42966316e6f7b
f57749ca63d6416f807b770f67559503fdb21001
/hott/types/cubical/squareover.hlean
d01cd2910b6f41b30f00600984e9141ffa9ffa72
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,805
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Squareovers -/ import .square open eq equiv is_equiv equiv.ops namespace eq -- we give the argument B explicitly, because Lean would find (λa, B a) by itself, which -- makes the type uglier (of course the two terms are definitionally equal) inductive squareover {A : Type} (B : A → Type) {a₀₀ : A} {b₀₀ : B a₀₀} : Π{a₂₀ a₀₂ a₂₂ : A} {p₁₀ : a₀₀ = a₂₀} {p₁₂ : a₀₂ = a₂₂} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} (q₁₀ : pathover B b₀₀ p₁₀ b₂₀) (q₁₂ : pathover B b₀₂ p₁₂ b₂₂) (q₀₁ : pathover B b₀₀ p₀₁ b₀₂) (q₂₁ : pathover B b₂₀ p₂₁ b₂₂), Type := idsquareo : squareover B ids idpo idpo idpo idpo variables {A A' : Type} {B : A → Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ : A} /-a₀₀-/ {p₁₀ : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₄₀ : B a₄₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {b₄₂ : B a₄₂} {b₀₄ : B a₀₄} {b₂₄ : B a₂₄} {b₄₄ : B a₄₄} /-b₀₀-/ {q₁₀ : b₀₀ =[p₁₀] b₂₀} /-b₂₀-/ {q₃₀ : b₂₀ =[p₃₀] b₄₀} /-b₄₀-/ {q₀₁ : b₀₀ =[p₀₁] b₀₂} /-t₁₁-/ {q₂₁ : b₂₀ =[p₂₁] b₂₂} /-t₃₁-/ {q₄₁ : b₄₀ =[p₄₁] b₄₂} /-b₀₂-/ {q₁₂ : b₀₂ =[p₁₂] b₂₂} /-b₂₂-/ {q₃₂ : b₂₂ =[p₃₂] b₄₂} /-b₄₂-/ {q₀₃ : b₀₂ =[p₀₃] b₀₄} /-t₁₃-/ {q₂₃ : b₂₂ =[p₂₃] b₂₄} /-t₃₃-/ {q₄₃ : b₄₂ =[p₄₃] b₄₄} /-b₀₄-/ {q₁₄ : b₀₄ =[p₁₄] b₂₄} /-b₂₄-/ {q₃₄ : b₂₄ =[p₃₄] b₄₄} /-b₄₄-/ definition squareo := @squareover A B a₀₀ definition idsquareo [reducible] [constructor] (b₀₀ : B a₀₀) := @squareover.idsquareo A B a₀₀ b₀₀ definition idso [reducible] [constructor] := @squareover.idsquareo A B a₀₀ b₀₀ definition apds (f : Πa, B a) (s : square p₁₀ p₁₂ p₀₁ p₂₁) : squareover B s (apdo f p₁₀) (apdo f p₁₂) (apdo f p₀₁) (apdo f p₂₁) := square.rec_on s idso definition vrflo : squareover B vrfl q₁₀ q₁₀ idpo idpo := by induction q₁₀; exact idso definition hrflo : squareover B hrfl idpo idpo q₁₀ q₁₀ := by induction q₁₀; exact idso definition vdeg_squareover {q₁₀' : b₀₀ =[p₁₀] b₂₀} (r : q₁₀ = q₁₀') : squareover B vrfl q₁₀ q₁₀' idpo idpo := by induction r;exact vrflo definition hdeg_squareover {q₁₀' : b₀₀ =[p₁₀] b₂₀} (r : q₁₀ = q₁₀') : squareover B hrfl idpo idpo q₁₀ q₁₀' := by induction r; exact hrflo -- relating squareovers to squares definition square_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : square (!con_tr ⬝ ap (λa, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (ap (λq, q ▸ b₀₀) (eq_of_square s₁₁) ⬝ !con_tr ⬝ ap (λa, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁) := by induction t₁₁; esimp; constructor /- definition squareover_of_square (q : square (!con_tr ⬝ ap (λa, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (ap (λq, q ▸ b₀₀) (eq_of_square s₁₁) ⬝ !con_tr ⬝ ap (λa, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁)) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ := sorry -/ definition square_of_squareover_ids {b₀₀ b₀₂ b₂₀ b₂₂ : B a} (t : b₀₀ = b₂₀) (b : b₀₂ = b₂₂) (l : b₀₀ = b₀₂) (r : b₂₀ = b₂₂) (so : squareover B ids (pathover_idp_of_eq t) (pathover_idp_of_eq b) (pathover_idp_of_eq l) (pathover_idp_of_eq r)) : square t b l r := begin let H := square_of_squareover so, -- use apply ... in rewrite [▸* at H,+idp_con at H,+ap_id at H,↑pathover_idp_of_eq at H], rewrite [+to_right_inv !(pathover_equiv_tr_eq (refl a)) at H], exact H end definition squareover_ids_of_square {b₀₀ b₀₂ b₂₀ b₂₂ : B a} (t : b₀₀ = b₂₀) (b : b₀₂ = b₂₂) (l : b₀₀ = b₀₂) (r : b₂₀ = b₂₂) (q : square t b l r) : squareover B ids (pathover_idp_of_eq t) (pathover_idp_of_eq b) (pathover_idp_of_eq l) (pathover_idp_of_eq r) := square.rec_on q idso -- relating pathovers to squareovers definition pathover_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ ⬝o q₂₁ =[eq_of_square s₁₁] q₀₁ ⬝o q₁₂ := by induction t₁₁; constructor definition squareover_of_pathover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (r : q₁₀ ⬝o q₂₁ =[s] q₀₁ ⬝o q₁₂) : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₁₂; esimp [concato] at r;induction r;induction q₂₁;induction q₁₀;constructor definition pathover_top_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ =[eq_top_of_square s₁₁] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction t₁₁; constructor definition squareover_of_pathover_top {s : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹} (r : q₁₀ =[s] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B (square_of_eq_top s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₂₁; induction q₁₂; esimp at r;induction r;induction q₁₀;constructor /- definition squareover_equiv_pathover (q₁₀ : b₀₀ =[p₁₀] b₂₀) (q₁₂ : b₀₂ =[p₁₂] b₂₂) (q₀₁ : b₀₀ =[p₀₁] b₀₂) (q₂₁ : b₂₀ =[p₂₁] b₂₂) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ ≃ q₁₀ ⬝o q₂₁ =[eq_of_square s₁₁] q₀₁ ⬝o q₁₂ := begin fapply equiv.MK, { exact pathover_of_squareover}, { intro r, rewrite [-to_left_inv !square_equiv_eq s₁₁], apply squareover_of_pathover, exact r}, { intro r, }, --need characterization of squareover lying over ids. { intro s, induction s, apply idp}, end -/ definition eq_of_vdeg_squareover {q₁₀' : b₀₀ =[p₁₀] b₂₀} (p : squareover B vrfl q₁₀ q₁₀' idpo idpo) : q₁₀ = q₁₀' := begin let H := square_of_squareover p, -- use apply ... in induction p₁₀, -- if needed we can remove this induction and use con_tr_idp in types/eq2 rewrite [▸* at H,idp_con at H,+ap_id at H], let H' := eq_of_vdeg_square H, exact eq_of_fn_eq_fn !pathover_equiv_tr_eq H' end -- definition vdeg_tr_squareover {q₁₂ : p₀₁ ▸ b₀₀ =[p₁₂] p₂₁ ▸ b₂₀} (r : q₁₀ =[_] q₁₂) -- : squareover B s₁₁ q₁₀ q₁₂ !pathover_tr !pathover_tr := -- by induction p;exact vrflo /- charcaterization of pathovers in pathovers -/ -- in this version the fibration (B) of the pathover does not depend on the variable a definition pathover_pathover {a' a₂' : A'} {p : a' = a₂'} {f g : A' → A} {b : Πa, B (f a)} {b₂ : Πa, B (g a)} {q : Π(a' : A'), f a' = g a'} (r : pathover B (b a') (q a') (b₂ a')) (r₂ : pathover B (b a₂') (q a₂') (b₂ a₂')) (s : squareover B (natural_square_tr q p) r r₂ (pathover_ap B f (apdo b p)) (pathover_ap B g (apdo b₂ p))) : pathover (λa, pathover B (b a) (q a) (b₂ a)) r p r₂ := by induction p;esimp at s; apply pathover_idp_of_eq; apply eq_of_vdeg_squareover; exact s end eq
d3de7e18f8ced68608d83fe79d331ff4c875447c
da23b545e1653cafd4ab88b3a42b9115a0b1355f
/src/tidy/chain.lean
f3b7680205573cdc9cad9594ae141f8667388d77
[]
no_license
minchaowu/lean-tidy
137f5058896e0e81dae84bf8d02b74101d21677a
2d4c52d66cf07c59f8746e405ba861b4fa0e3835
refs/heads/master
1,585,283,406,120
1,535,094,033,000
1,535,094,033,000
145,945,792
0
0
null
null
null
null
UTF-8
Lean
false
false
7,532
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .some_goal import .repeat_at_least_once import .recover import .pretty_print import data.option open interactive namespace tactic /- This file defines a `chain` tactic, which takes a list of tactics, and exhaustively tries to apply them to the goals, until no tactic succeeds on any goal. Along the way, it generates auxiliary declarations, in order to speed up elaboration time of the resulting (sometimes long!) proofs. This tactic is used by the `tidy` tactic. -/ -- α is the return type of our tactics. When `chain` is called by `tidy`, this is string, -- describing what that tactic did as an interactive tactic. variable {α : Type} /- Because chain sometimes pauses work on the first goal and works on later goals, we need a method for combining a list of results generated while working on a later goal into a single result. This enables `tidy {trace_result := tt}` to output faithfully reproduces its operation, e.g. ```` intros, simp, apply lemma_1, work_on_goal 2 { dsimp, simp }, refl ```` -/ class has_focus (α : Type) := (work_on_goal : ℕ → list α → α) instance : has_focus unit := { work_on_goal := λ _ _, unit.star} instance string_has_focus : has_focus string := { work_on_goal := λ n ts, if false /-n = 0-/ then ", ".intercalate ts else "work_on_goal " ++ (to_string n) ++ " {\n " ++ (",\n ".intercalate ts) ++ "\n}" } namespace interactive open lean.parser meta def work_on_goal : parse small_nat → itactic → tactic unit | n t := do goals ← get_goals, let earlier_goals := goals.take n, let later_goals := goals.drop (n+1), set_goals (goals.nth n).to_list, t, new_goals ← get_goals, set_goals (earlier_goals ++ new_goals ++ later_goals) end interactive /- The chain tactic is built out of two components, * `chain_multiple_goals`, which tries working on each goal sequentially, * `chain_single_goal`, which tries out all the 'chained' tactics on a given goal, and also performs some magic making declarations for intermediate steps (to speed up elaboration), and passing control back to `chain_multiple_goals` when necessary. -/ variable (single_goal_tactic : tactic (list α)) -- because the two tactics need to call each other, we pass a reference variable [has_focus α] /- The tactic `chain_multiple_goals` repeatedly applies `chain_single_goal` to the first goal on which it succeeds. -/ meta def chain_multiple_goals : tactic (list α) := do (p, q) ← repeat_at_least_once (some_goal single_goal_tactic) <|> fail "chain did not find any goal where progress could be made", return ((list.cons p q).reverse.map $ λ x, has_focus.work_on_goal x.1 x.2.reverse) meta def chain_single_goal_aux (tactics : list (tactic α)) : tactic (list α) := do ng ← num_goals, match ng with | 0 := fail "no goals left" | 1 := first tactics >>= λ a, return [a] | _ := chain_multiple_goals single_goal_tactic end private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def close_goal_with_declaration (goal : expr) (type : expr) (metavar : expr) : tactic unit := do set_goals [goal], val ← instantiate_mvars metavar, c ← mk_aux_decl_name none, is_lemma ← is_prop type, e ← add_aux_decl c type val is_lemma, -- if ¬ is_lemma then -- set_basic_attribute `reducible c tt -- else -- tactic.skip, exact e, append_goals e.metavariables /- `chain_single_goal` requires that we start with a single goal. We first make a synthetic copy of the goal, as a new metavariable. We then follow these steps: 1. If there are no remaining goals, we attempt to make a declaration containing the result for the synthetic goal, and then close the original goal using that, and return. (Like `abstract`.) 2. Check how many goals remain: 2.a. If there is just a single goal, attempt to execute a tactic from the list, and if this succeeds return to 1. 2.b. If there are multiple goals, run `chain_multiple_goals` (which will recursively call back into this function, making a new synthetic copy of each goal), and if this succeeds return to 1. 3. At this point, we have one or more goals, which we can't make any further progress on. Without making any declaration, we use exact (which is more robust than unify) to substitute the partial solution we've found to the synthetic goal into the original goal, and return. -/ meta def chain_single_goal (make_declarations : bool) (tactics : list (tactic α)) : tactic (list α) := do gs ← get_goals, guard (gs.length = 1), if make_declarations then do type ← target >>= zeta, m ← mk_meta_var type, set_goals [m], as ← repeat_with_results (chain_single_goal_aux chain_single_goal tactics), guard (as.length > 0) <|> fail "chain tactic made no progress", ng ← num_goals, match (ng, bnot type.has_meta_var) with | (0, tt) := close_goal_with_declaration gs.head type m | _ := (do r ← instantiate_mvars m, set_goals gs, exact r, append_goals r.metavariables) <|> fail "bug: could not close goal using solution to synthetic goal!" end, return as.reverse.join else do as ← repeat_with_results (chain_single_goal_aux chain_single_goal tactics), guard (as.length > 0) <|> fail "chain tactic made no progress", return as.reverse.join structure chain_cfg := (trace_steps : bool := ff) (make_declarations : bool := tt) meta def chain_core (cfg : chain_cfg) (tactics : list (tactic α)) : tactic (list α) := do ng ← num_goals, let tac := chain_single_goal cfg.make_declarations tactics, match ng with | 0 := fail "no goals left" | 1 := tac | _ := chain_multiple_goals tac end variable [has_to_format α] meta def trace_output (t : tactic α) : tactic α := do tgt ← target, r ← t, name ← decl_name, trace format!"chain successfully applied a tactic during elaboration of {name}:", tgt ← pretty_print tgt, trace format!"old target: {tgt}", gs ← get_goals, gs' ← gs.mmap (λ g, infer_type g >>= pretty_print), trace gs', mvars ← metavariables, mvars' ← mvars.mmap (λ g, infer_type g >>= pretty_print), trace mvars', trace format!"tactic: {r}", tgt ← try_core target, tgt ← match tgt with | (some tgt) := do pretty_print tgt | none := do return "′no goals′" end, trace format!"new target: {tgt}", gs ← get_goals, gs' ← gs.mmap (λ g, infer_type g >>= pretty_print), trace gs', mvars ← metavariables, mvars' ← mvars.mmap (λ g, infer_type g >>= pretty_print), trace mvars', pure r private meta def chain_handle_trace (cfg : chain_cfg) (tactics : list (tactic α)) : tactic (list α) := if cfg.trace_steps then chain_core cfg (tactics.map trace_output) else chain_core cfg tactics meta def chain (cfg : chain_cfg) (tactics : list (tactic α)) : tactic (list α) := do sequence ← chain_handle_trace cfg tactics, guard (sequence.length > 0) <|> fail "chain tactic made no progress", pure sequence.reverse end tactic
73984fa36185a0b5226bdf785cc7fdccd9409336
7617a8700fc3eebd9200f1e620ee65b3565d2eff
/src/vc0/basic.lean
d7f82c9684ff01f4ca2a101dbdbcc5c38444fc0e
[]
no_license
digama0/vc0
9747eee791c5c2f58eb53264ca6263ee53de0f87
b8b192c8c139e0b5a25a7284b93ed53cdf7fd7a5
refs/heads/master
1,626,186,940,436
1,592,385,972,000
1,592,385,972,000
158,556,766
5
0
null
null
null
null
UTF-8
Lean
false
false
35,176
lean
import c0.dyn_ok namespace c0 open ast ast.gdecl namespace ast inductive okind : ast → Prop | nil : okind [] | cons {d Γ} : gdecl.ok Γ d → okind Γ → okind (d :: Γ) theorem ok.ind {Γ : ast} (h : Γ.ok) : Γ.okind := begin rw ← Γ.reverse_reverse, suffices : ∀ Γ ds, ok' Γ ds → okind Γ → okind (list.reverse_core ds Γ), from this [] Γ.reverse h.gdecls okind.nil, clear h Γ, introv h₁ h₂, induction h₁, {exact h₂}, exact h₁_ih (okind.cons h₁_a h₂) end inductive below (P : ast → Prop) : ast → Prop | nil {} : below [] | cons (d Γ) : gdecl.ok Γ d → P Γ → below (d :: Γ) @[elab_as_eliminator] theorem okind.induction' {P : ast → Prop} {Γ : ast} (h : Γ.okind) (H : ∀ Γ, okind Γ → below P Γ → P Γ) : P Γ := okind.rec_on h (H [] okind.nil below.nil) (λ d Γ h₁ ok h₂, H _ (okind.cons h₁ ok) (below.cons d Γ h₁ h₂)) namespace eval_ty @[elab_as_eliminator] theorem induction₁ {P : type → c0.type → Prop} {Γ : ast} {τ τ'} (H : eval_ty Γ τ τ') (Hint : P type.int c0.type.int) (Hbool : P type.bool c0.type.bool) (Href : ∀ τ τ', eval_ty Γ τ τ' → P τ τ' → P (type.ref τ) (c0.type.ref τ')) (Harr : ∀ τ τ', eval_ty Γ τ τ' → P τ τ' → P (type.arr τ) (c0.type.arr τ')) (Hstruct : ∀ s, P (type.struct s) (c0.type.struct s)) (Hweak : ∀ d Γ', Γ = d :: Γ' → ∀ τ τ', eval_ty Γ' τ τ' → P τ τ') (Hvar : ∀ v τ₀ Γ', Γ = typedef v τ₀ :: Γ' → ∀ τ', eval_ty Γ τ₀ τ' → P τ₀ τ' → P (type.var v) τ') : P τ τ' := begin generalize e : Γ = Γ', rw e at H, induction H; cases e; try {solve_by_elim}, { exact Hvar _ _ _ rfl _ (weak H_a) (Hweak _ _ rfl _ _ H_a) }, { exact Href _ _ H_a (H_ih rfl) }, { exact Harr _ _ H_a (H_ih rfl) } end theorem var_determ {Γ : ast} (ok : Γ.okind) : ∀ {v τ₁ τ₂}, typedef v τ₁ ∈ Γ → typedef v τ₂ ∈ Γ → τ₁ = τ₂ := begin induction ok with d Γ h _ IH, {rintro _ _ _ ⟨⟩}, rintro v τ₁ τ₂ (rfl | h₁) (⟨⟨⟩⟩ | h₂), { refl }, { cases h, cases h_a _ h₂ }, { cases h, cases h_a _ h₁ }, { exact IH h₁ h₂ } end theorem mem_of_var {Γ : ast} {v τ} : eval_ty Γ (type.var v) τ → ∃ τ', typedef v τ' ∈ Γ ∧ ∃ d Γ', Γ = d :: Γ' ∧ eval_ty Γ' τ' τ := begin generalize e : type.var v = x, intro h, induction h; cases e, { exact ⟨_, or.inl rfl, _, _, rfl, h_a⟩ }, { rcases h_ih rfl with ⟨τ', h₁, d', Γ'', rfl, h₂⟩, exact ⟨τ', or.inr h₁, _, _, rfl, weak h₂⟩ } end theorem int' : ∀ Γ, eval_ty Γ type.int c0.type.int | [] := int | (d::Γ) := weak (int' _) theorem bool' : ∀ Γ, eval_ty Γ type.bool c0.type.bool | [] := bool | (d::Γ) := weak (bool' _) theorem struct' (s) : ∀ Γ, eval_ty Γ (type.struct s) (c0.type.struct s) | [] := struct | (d::Γ) := weak (struct' _) theorem ref_inv {Γ t τ} (H : eval_ty Γ (type.ref t) τ) : ∃ τ', eval_ty Γ t τ' ∧ c0.type.ref τ' = τ := begin generalize e : type.ref t = t', rw e at H, induction H; cases e, { exact ⟨_, H_a, rfl⟩ }, { rcases H_ih rfl with ⟨τ', h₁, h₂⟩, exact ⟨τ', weak h₁, h₂⟩ } end theorem arr_inv {Γ t τ} (H : eval_ty Γ (type.arr t) τ) : ∃ τ', eval_ty Γ t τ' ∧ c0.type.arr τ' = τ := begin generalize e : type.arr t = t', rw e at H, induction H; cases e, { exact ⟨_, H_a, rfl⟩ }, { rcases H_ih rfl with ⟨τ', h₁, h₂⟩, exact ⟨τ', weak h₁, h₂⟩ } end theorem determ {Γ : ast} (ok : Γ.okind) : ∀ {t τ₁ τ₂} (h₁ : eval_ty Γ t τ₁) (h₂ : eval_ty Γ t τ₂), τ₁ = τ₂ := okind.induction' ok $ λ Γ ok IH t, begin induction t, { suffices : ∀ {τ}, eval_ty Γ type.int τ → τ = c0.type.int, { intros, exact (this h₁).trans (this h₂).symm }, intros, cases a, {refl}, { cases IH, exact IH_a_1 a_a (eval_ty.int' _) } }, { suffices : ∀ {τ}, eval_ty Γ type.bool τ → τ = c0.type.bool, { intros, exact (this h₁).trans (this h₂).symm }, intros, cases a, {refl}, { cases IH, exact IH_a_1 a_a (eval_ty.bool' _) } }, { intros, rcases mem_of_var h₁ with ⟨τ, m₁, d, Γ', rfl, h₁'⟩, rcases mem_of_var h₂ with ⟨τ', m₂, _, _, ⟨⟩, h₂'⟩, cases var_determ ok m₁ m₂, cases IH, exact IH_a_1 h₁' h₂' }, { intros, rcases ref_inv h₁ with ⟨τ₁', h₁', rfl⟩, rcases ref_inv h₂ with ⟨τ₂', h₂', rfl⟩, cases t_ih h₁' h₂', refl }, { intros, rcases arr_inv h₁ with ⟨τ₁', h₁', rfl⟩, rcases arr_inv h₂ with ⟨τ₂', h₂', rfl⟩, cases t_ih h₁' h₂', refl }, { suffices : ∀ {s τ}, eval_ty Γ (type.struct s) τ → τ = c0.type.struct s, { intros, exact (this h₁).trans (this h₂).symm }, intros, cases a, {refl}, { cases IH, exact IH_a_1 a_a (eval_ty.struct' _ _) } } end theorem determ_opt {Γ : ast} (ok : Γ.okind) {t τ₁ τ₂} (h₁ : option.forall₂ (eval_ty Γ) t τ₁) (h₂ : option.forall₂ (eval_ty Γ) t τ₂) : τ₁ = τ₂ := begin cases h₁; cases h₂, {refl}, cases determ ok h₁_a_1 h₂_a_1, refl end theorem determ_alist {α} {Γ : ast} (ok : Γ.okind) : ∀ {xts Δ₁ Δ₂} (h₁ : alist.forall₂ (λ _:α, eval_ty Γ) xts Δ₁) (h₂ : alist.forall₂ (λ _, eval_ty Γ) xts Δ₂), Δ₁ = Δ₂ | ⟨xts, nd⟩ ⟨L₁, nd₁⟩ ⟨L₂, nd₂⟩ h₁ h₂ := begin congr, dsimp [alist.forall₂] at h₁ h₂, clear nd nd₁ nd₂ determ_alist, induction xts with xt xts generalizing L₁ L₂; cases h₁; cases h₂, {refl}, rcases h₁_a_1 with ⟨i, x, τ, _⟩, rcases h₂_a_1 with ⟨_, _, τ', _⟩, cases xts_ih _ _ h₁_a_2 h₂_a_2, cases determ ok h₁_a_1_a h₂_a_1_a_1, refl end end eval_ty theorem get_fdef.weak {Γ f fd d} (h : get_fdef Γ f fd) : get_fdef (d :: Γ) f fd := by cases h with h f xτs τs' τ τ' body Γ h₁ h₂ h₃; exact ⟨or.inr h₁, h₂.imp (λ _ _, eval_ty.weak), h₃.imp (λ _ _, eval_ty.weak)⟩ theorem get_body.weak {Γ f τ Δ s d} (h : get_body Γ f τ Δ s) : get_body (d :: Γ) f τ Δ s := by cases h with h f xτs Δ τ τ' nd body Γ h₁ h₂ h₃; exact ⟨or.inr h₁, h₂.imp (λ _ _ _, eval_ty.weak), h₃.imp (λ _ _, eval_ty.weak)⟩ theorem is_fdef.weak {Γ f d} : is_fdef Γ f → is_fdef (d :: Γ) f | ⟨τ, xτs, s, h⟩ := ⟨τ, xτs, s, h.weak⟩ theorem is_extern.weak {Γ f d} (h : is_extern Γ f) : is_extern (d :: Γ) f := by cases h with f xτs τ body Γ h; exact ⟨or.inr h⟩ theorem get_sdef.weak {Γ s sd d} (h : get_sdef Γ s sd) : get_sdef (d :: Γ) s sd := by cases h with s xτs nd Δ Γ h₁ h₂; exact ⟨or.inr h₁, h₂.imp (λ _ _ _, eval_ty.weak)⟩ theorem sized.weak {Γ τ d} (h : sized Γ τ) : sized (d :: Γ) τ := begin cases τ; try {trivial}, exact h.imp (λ _, get_sdef.weak) end theorem get_body.get_fdef {Γ : ast} {f τ Δ s} (h : Γ.get_body f τ Δ s) : Γ.get_fdef f ⟨Δ.values, τ⟩ := begin cases h with h xτs ts _ t _ nd _ _ m tsΔ tτ, refine ⟨m, _, tτ⟩, cases Δ with Δ nd', refine list.forall₂_map_right_iff.2 ((list.forall₂_map_left_iff.1 tsΔ).imp _), rintro ⟨i, t⟩ ⟨_, τ⟩ ⟨_, _, _, h⟩, exact h end namespace exp theorem ok.weak {Γ Δ e τ d} (h : exp.ok Γ Δ e τ) : exp.ok (d :: Γ) Δ e τ := begin induction h, { exact ok.int }, { exact ok.bool }, { exact ok.null }, { exact ok.var h_a }, { exact ok.binop h_ih_a h_ih_a_1 h_a_2 }, { exact ok.unop h_ih h_a_1 }, { exact ok.cond h_ih_a h_ih_a_1 h_ih_a_2 h_a_3 }, { exact ok.nil }, { exact ok.cons h_ih_a h_ih_a_1 }, { exact ok.call h_a.weak h_ih }, { exact ok.field h_ih h_a_1.weak h_a_2 }, { exact ok.deref h_ih h_a_1 }, { exact ok.index h_ih_a h_ih_a_1 }, { exact ok.alloc_ref h_a.weak h_a_1.weak }, { exact ok.alloc_arr h_a.weak h_a_1.weak h_ih }, end theorem ok.weak' {Γ Δ e τ v t h} (H : exp.ok Γ Δ e τ) : exp.ok Γ (Δ.cons v t h) e τ := begin induction H, { exact ok.int }, { exact ok.bool }, { exact ok.null }, { exact ok.var (alist.lookup_cons_of_lookup H_a) }, { exact ok.binop H_ih_a H_ih_a_1 H_a_2 }, { exact ok.unop H_ih H_a_1 }, { exact ok.cond H_ih_a H_ih_a_1 H_ih_a_2 H_a_3 }, { exact ok.nil }, { exact ok.cons H_ih_a H_ih_a_1 }, { exact ok.call H_a H_ih }, { exact ok.field H_ih H_a_1 H_a_2 }, { exact ok.deref H_ih H_a_1 }, { exact ok.index H_ih_a H_ih_a_1 }, { exact ok.alloc_ref H_a H_a_1 }, { exact ok.alloc_arr H_a H_a_1 H_ih }, end theorem uses.mono {R δ δ'} (ss : δ ⊆ δ') : ∀ {e}, uses R δ e → uses R δ' e | (int _) h := h | (bool _) h := h | null h := h | (var v) h := ss h | (binop _ e₁ e₂) ⟨h₁, h₂⟩ := ⟨h₁.mono, h₂.mono⟩ | (unop _ e) h := @uses.mono e h | (cond c e₁ e₂) ⟨h₁, h₂, h₃⟩ := ⟨h₁.mono, h₂.mono, h₃.mono⟩ | nil h := h | (cons e es) ⟨h₁, h₂⟩ := ⟨h₁.mono, h₂.mono⟩ | (call f es) ⟨h₁, h₂⟩ := ⟨h₁, h₂.mono⟩ | (field e f) h := @uses.mono e h | (deref e) h := @uses.mono e h | (index e₁ e₂) ⟨h₁, h₂⟩ := ⟨h₁.mono, h₂.mono⟩ | (alloc_ref _) h := h | (alloc_arr _ e) h := @uses.mono e h end exp theorem lval.ok : ∀ (lv : lval), lv_ok lv.to_exp | (lval.var v) := lv_ok.var | (lval.deref e) := lv_ok.deref | (lval.index e₁ e₂) := lv_ok.index | (lval.field e f) := lv_ok.field (lval.ok e) theorem lval.uses.mono {R δ δ'} (ss : δ ⊆ δ') {lv : lval} (h : lval.uses R δ lv) : lval.uses R δ' lv := by unfold lval.uses at *; cases (lval.is_var lv).is_some; [exact h.mono ss, trivial] namespace stmt theorem ok.weak {Γ ret_τ Δ s d} (h : stmt.ok Γ ret_τ Δ s) : stmt.ok (d :: Γ) ret_τ Δ s := begin induction h, { exact ok.decl h_h h_a.weak h_a_1 h_ih }, { exact ok.decl_asgn h_h h_a.weak h_a_1 h_a_2.weak h_ih }, { exact ok.If h_a.weak h_ih_a h_ih_a_1 }, { exact ok.while h_a.weak h_ih }, { exact ok.asgn h_a.weak h_a_1.weak h_a_2 }, { exact ok.asnop h_a.weak h_a_1.weak h_a_2 }, { exact ok.eval h_a.weak h_a_1 }, { exact ok.assert h_a.weak }, { exact ok.ret (h_a.imp (λ _ _, exp.ok.weak)) }, { exact ok.nop }, { exact ok.seq h_ih_a h_ih_a_1 }, end theorem init.subset {Γ R Δ ret γ δ s δ'} (ok : stmt.ok Γ ret Δ s) (e : Δ.keys.to_finset = γ) (h : init R γ δ s δ') (ss : δ ⊆ γ) : δ ⊆ δ' ∧ δ' ⊆ γ := begin have lem : ∀ {Δ : ctx} {γ δ δ' : finset ident} {v}, list.to_finset (alist.keys Δ) = γ → v ∉ Δ → δ ⊆ γ → δ ⊆ δ' ∧ δ' ⊆ insert v γ → δ ⊆ δ'.erase v ∧ δ'.erase v ⊆ γ, { rintro Δ γ δ δ' v e hn ss ⟨ss₁, ss₂⟩, refine ⟨λ x xδ, finset.mem_erase.2 ⟨_, ss₁ xδ⟩, finset.subset.trans (finset.erase_subset_erase _ ss₂) (finset.erase_insert_subset _ _)⟩, rintro rfl, subst γ, cases hn (alist.mem_keys.1 $ list.mem_to_finset.1 $ ss xδ) }, induction ok generalizing γ δ δ'; cases h; try {exact ⟨λ x, id, ss⟩}, { refine lem e ok_h ss (ok_ih _ h_a (λ x xδ, finset.mem_insert_of_mem (ss xδ))), subst γ, simp }, { cases ok_ih _ h_a_1 (finset.insert_subset_insert _ ss) with IH₁ IH₂, refine lem e ok_h ss ⟨λ x xδ, IH₁ (finset.mem_insert_of_mem xδ), IH₂⟩, subst γ, simp }, { cases ok_ih_a e h_a_1 ss with l₁ r₁, cases ok_ih_a_1 e h_a_2 ss with l₂ r₂, exact ⟨λ x xδ, finset.mem_inter.2 ⟨l₁ xδ, l₂ xδ⟩, λ x xδ, r₁ (finset.mem_inter.1 xδ).1⟩ }, { cases ok_lv; try {exact ⟨λ x, id, ss⟩}, refine ⟨finset.subset_insert _ _, finset.insert_subset.2 ⟨_, ss⟩⟩, subst γ, cases ok_a, exact list.mem_to_finset.2 (alist.mem_keys.2 $ alist.exists_mem_lookup_iff.1 ⟨_, ok_a_a⟩) }, { exact ⟨ss, λ _, id⟩ }, { cases ok_ih_a e h_a ss with l₁ r₁, cases ok_ih_a_1 e h_a_1 r₁ with l₂ r₂, exact ⟨finset.subset.trans l₁ l₂, r₂⟩ } end theorem init.mono {R γ δ₁ δ₂ s δ₁'} (h : init R γ δ₁ s δ₁') (ss : δ₁ ⊆ δ₂) : ∃ δ₂', δ₁' ⊆ δ₂' ∧ init R γ δ₂ s δ₂' := begin induction h generalizing δ₂, { rcases h_ih ss with ⟨δ₂', ss', i⟩, exact ⟨_, finset.erase_subset_erase _ ss', init.decl i⟩ }, { rcases h_ih (finset.insert_subset_insert _ ss) with ⟨δ₂', ss', i⟩, exact ⟨_, finset.erase_subset_erase _ ss', init.decl_asgn (h_a.mono ss) i⟩ }, { rcases h_ih_a ss with ⟨δ₃, ss₁, i₁⟩, rcases h_ih_a_1 ss with ⟨δ₄, ss₂, i₂⟩, exact ⟨_, finset.inter_subset_inter ss₁ ss₂, init.If (h_a.mono ss) i₁ i₂⟩ }, { rcases h_ih ss with ⟨δ', ss', i⟩, exact ⟨_, ss, init.while (h_a.mono ss) i⟩ }, { refine ⟨_, _, init.asgn (h_a.mono ss) (h_a_1.mono ss)⟩, cases h_lv; try {exact ss}, exact finset.insert_subset_insert _ ss }, { exact ⟨_, ss, init.asnop (h_a.mono ss) (h_a_1.mono ss)⟩ }, { exact ⟨_, ss, init.eval (h_a.mono ss)⟩ }, { exact ⟨_, ss, init.assert (h_a.mono ss)⟩ }, { exact ⟨_, λ _, id, init.ret (λ e h, (h_a e h).mono ss)⟩ }, { exact ⟨_, ss, init.nop⟩ }, { rcases h_ih_a ss with ⟨δ₃, ss₁, i₁⟩, rcases h_ih_a_1 ss₁ with ⟨δ₄, ss₂, i₂⟩, exact ⟨_, ss₂, init.seq i₁ i₂⟩ } end end stmt end ast inductive fdecl_ok (Γ : ast) (header xτs ret body) : Prop | mk (Δ ret' h) : alist.forall₂ (λ (i:ident) τ τ', eval_ty Γ τ τ' ∧ τ'.small) (alist.mk' xτs h) Δ → option.forall₂ (λ τ τ', eval_ty Γ τ τ' ∧ τ'.small) ret ret' → (∀ s ∈ (body : option stmt), header = ff ∧ stmt.ok Γ ret' Δ s ∧ (s.returns ∨ ret = none)) → fdecl_ok theorem fdecl_ok_of_mem {Γ : ast} (ok : Γ.okind) {header f xτs ret body} : fdecl header f xτs ret body ∈ Γ → fdecl_ok Γ header xτs ret body := begin induction ok with d Γ g ok IH; rintro (rfl | m), { cases g with _ _ _ Δ _ ret' _ h₁ h₂ h₃ h₄, refine ⟨Δ, ret', h₁, h₂.imp (λ _ _ _ ⟨h₁, h₂⟩, ⟨h₁.weak, h₂⟩), h₃.imp (λ _ _ ⟨h₁, h₂⟩, ⟨h₁.weak, h₂⟩), λ s hs, _⟩, rcases h₄ s hs with ⟨hs₁, _, hs₂, hs₃⟩, exact ⟨hs₁, hs₂, hs₃⟩ }, { cases IH m with Δ ret' h₁ h₂ h₃ h₄, refine ⟨Δ, ret', h₁, h₂.imp (λ _ _ _ ⟨h₁, h₂⟩, ⟨h₁.weak, h₂⟩), h₃.imp (λ _ _ ⟨h₁, h₂⟩, ⟨h₁.weak, h₂⟩), λ s hs, _⟩, rcases h₄ s hs with ⟨hs₁, hs₂, hs₃⟩, exact ⟨hs₁, hs₂.weak, hs₃⟩ } end theorem get_fdecl_pairwise {Γ : ast} (ok : Γ.okind) {f} : Γ.pairwise (λ d₁ d₂, ∀ ⦃h₁ h₂ xτs₁ xτs₂ ret₁ ret₂ s₁ s₂⦄, d₁ = fdecl h₁ f xτs₁ ret₁ (some s₁) → d₂ = fdecl h₂ f xτs₂ ret₂ (some s₂) → false) := begin induction ok with d Γ g ok IH; constructor, { rintro _ h h₁ h₂ xτs₁ xτs₂ ret₁ ret₂ s₁ s₂ rfl rfl, -- rcases (get_fdef_ex_iff ok).2 ⟨_, h⟩ with ⟨sd, h'⟩, cases g, cases fdecl_ok_of_mem ok h, cases (g_a_2 _ rfl).2.1 ⟨_, _, _, ⟨h, a.imp (λ _ _ _, and.left), a_1.imp (λ _ _, and.left)⟩⟩ }, { exact IH } end theorem ast.get_body.determ {Γ : ast} (ok : Γ.okind) {f τ₁ τ₂ xτs₁ xτs₂ s₁ s₂} (h₁ : get_body Γ f τ₁ xτs₁ s₁) (h₂ : get_body Γ f τ₂ xτs₂ s₂) : (τ₁, xτs₁, s₁) = (τ₂, xτs₂, s₂) := begin have : ∀ (d₁ ∈ Γ) (d₂ ∈ Γ) ⦃h₁ h₂ xτs₁ xτs₂ τ₁ τ₂ s₁ s₂⦄, d₁ = fdecl h₁ f xτs₁ τ₁ (some s₁) → d₂ = fdecl h₂ f xτs₂ τ₂ (some s₂) → (τ₁, xτs₁, s₁) = (τ₂, xτs₂, s₂), { refine list.forall_of_forall_of_pairwise _ _ ((get_fdecl_pairwise ok).imp _), { exact λ x y H h₁ h₂ xτs₁ xτs₂ τ₁ τ₂ s₁ s₂ e₁ e₂, (H e₂ e₁).symm }, { rintro _ _ _ _ _ _ _ _ _ _ rfl ⟨⟩, refl }, swap, { rintro a b H _ _ _ _ _ _ _ _ h₁ h₂, cases H h₁ h₂ } }, cases h₁, cases h₂, cases this _ h₁_a _ h₂_a rfl rfl, cases ast.eval_ty.determ_alist ok h₁_a_1 h₂_a_1, cases ast.eval_ty.determ_opt ok h₁_a_2 h₂_a_2, refl end theorem lv_ok_of_struct {Γ : ast} {Δ e s} (ok : Γ.okind) (eok : exp.ok Γ Δ e (exp.type.reg (c0.type.struct s))) : lv_ok e := begin generalize_hyp eq : exp.type.reg (c0.type.struct s) = τ at eok, induction eok generalizing s; try {cases eq, done}; try {constructor, done}, { cases eok_a_2; cases eq }, { cases eok_a_1; cases eq }, { cases eq, cases eok_a_3 }, { cases eok_a, cases fdecl_ok_of_mem ok eok_a_a, cases eok_a_a_2; cases eq, rcases a_1 with _|⟨_, _, h₁, h₂⟩, cases ast.eval_ty.determ ok eok_a_a_2_a_1 h₁, cases h₂ }, { exact lv_ok.field (eok_ih rfl) } end theorem sdecl_ok1 {Γ : ast} {s xτs} (g : c0.ast.gdecl.ok Γ (sdecl s (some xτs))) : ∃ nd Δ, alist.forall₂ (λ _, eval_ty Γ) (alist.mk' xτs nd) Δ ∧ ∀ τ ∈ Δ.values, Γ.sized τ := begin rcases g with _|_|_|⟨_, _, h, nd, H⟩, clear h, refine ⟨nd, _⟩, induction xτs with xτ xτs IH, { exact ⟨∅, list.forall₂.nil, list.forall_mem_nil _⟩ }, cases xτ with x τ, cases list.nodup_cons.1 nd with nd₁ nd₂, rcases list.forall_mem_cons.1 H with ⟨⟨τ', h, hs⟩, H'⟩, rcases IH nd₂ H' with ⟨Δ, h₁, h₂⟩, refine ⟨Δ.cons x τ' _, list.forall₂.cons ⟨h⟩ h₁, list.forall_mem_cons.2 ⟨hs, h₂⟩⟩, rwa [← h₁.mem_iff, alist.mem_keys, alist.mk'_keys] end theorem sdecl_ok_of_mem {Γ : ast} (ok : Γ.okind) {s xτs} : sdecl s (some xτs) ∈ Γ → ∃ nd Δ, alist.forall₂ (λ _, eval_ty Γ) (alist.mk' xτs nd) Δ ∧ ∀ τ ∈ Δ.values, Γ.sized τ := begin induction ok with d Γ g ok IH; intro m, {cases m}, suffices : ∃ nd Δ, alist.forall₂ (λ _, eval_ty Γ) (alist.mk' xτs nd) Δ ∧ ∀ τ ∈ Δ.values, Γ.sized τ, { rcases this with ⟨nd, Δ, h₁, h₂⟩, exact ⟨nd, Δ, h₁.imp (λ _ _ _, eval_ty.weak), λ τ h, (h₂ τ h).weak⟩ }, rcases m with rfl | m, { exact sdecl_ok1 g }, { exact IH m } end theorem get_sdef_ex_iff {Γ : ast} (ok : Γ.okind) {s} : (∃ sd, get_sdef Γ s sd) ↔ ∃ body, gdecl.sdecl s (some body) ∈ Γ := begin split, { rintro ⟨sd, _, xτs, _, _, _, m, h⟩, exact ⟨_, m⟩ }, { rintro ⟨xτs, m⟩, rcases sdecl_ok_of_mem ok m with ⟨nd, Δ, h₁, h₂⟩, exact ⟨_, m, h₁⟩ } end theorem get_sdef_pairwise {Γ : ast} (ok : Γ.okind) {s} : Γ.pairwise (λ d₁ d₂, ∀ xτs₁ xτs₂, d₁ = sdecl s (some xτs₁) → d₂ = sdecl s (some xτs₂) → false) := begin induction ok with d Γ g ok IH; constructor, { rintro _ h xτs₁ xτs₂ rfl rfl, rcases (get_sdef_ex_iff ok).2 ⟨_, h⟩ with ⟨sd, h'⟩, cases g, cases g_a _ h' }, { exact IH } end theorem get_sdef_determ {Γ : ast} (ok : Γ.okind) {s sd₁ sd₂} (h₁ : get_sdef Γ s sd₁) (h₂ : get_sdef Γ s sd₂) : sd₁ = sd₂ := begin have : ∀ (d₁ ∈ Γ) (d₂ ∈ Γ) xτs₁ xτs₂, d₁ = sdecl s (some xτs₁) → d₂ = sdecl s (some xτs₂) → xτs₁ = xτs₂, { refine list.forall_of_forall_of_pairwise _ _ ((get_sdef_pairwise ok).imp _), { exact λ x y H xτs₁ xτs₂ h₁ h₂, (H _ _ h₂ h₁).symm }, { rintro _ _ _ _ rfl ⟨⟩, refl }, swap, { rintro a b H _ _ h₁ h₂, cases H _ _ h₁ h₂ } }, cases h₁, cases h₂, cases this _ h₁_a _ h₂_a _ _ rfl rfl, exact ast.eval_ty.determ_alist ok h₁_a_1 h₂_a_1 end instance is_sdecl (s d) : decidable (∃ body, d = gdecl.sdecl s (some body)) := by rcases d with _|_|⟨_, _|_⟩; try { apply is_false, rintro ⟨body, h⟩, cases h, done }; { simp, apply_instance } instance sdecl_mem (Γ : ast) (s) : decidable (∃ body, gdecl.sdecl s (some body) ∈ Γ) := decidable_of_iff' (∃ d ∈ Γ, ∃ body, d = gdecl.sdecl s (some body)) ⟨by rintro ⟨x, h⟩; exact ⟨_, h, x, rfl⟩, by rintro ⟨_, h, x, rfl⟩; exact ⟨x, h⟩⟩ def get_sdef_dec {Γ : ast} (ok : Γ.okind) {s} : decidable (∃ sd, get_sdef Γ s sd) := decidable_of_iff' _ (get_sdef_ex_iff ok) theorem get_body_ok' {Γ : ast} (ok : Γ.okind) {f τ Δ s} (h : Γ.get_body f τ Δ s) : stmt.ok Γ τ Δ s ∧ (stmt.returns s ∨ τ = none) := begin cases h, cases fdecl_ok_of_mem ok h_a, have : option.forall₂ (eval_ty Γ) h_τ ret' := a_1.imp (λ _ _, and.left), cases ast.eval_ty.determ_opt ok h_a_2 this, have : alist.forall₂ (λ _, eval_ty Γ) (alist.mk' h_xτs h_nd) Δ_1 := a.imp (λ _ _ _, and.left), cases ast.eval_ty.determ_alist ok h_a_1 this, refine (a_2 _ rfl).2.imp_right (or.imp_right _), rintro rfl, cases a_1, refl end theorem get_body_ok {Γ : ast} (ok : Γ.okind) {f τ Δ s} (h : Γ.get_body f τ Δ s) : stmt.ok Γ τ Δ s := (get_body_ok' ok h).1 theorem vars_ty.ok.mem {Δ σ} (σok : vars_ty.ok Δ σ) {x} (h : x ∈ σ) : x ∈ Δ := let ⟨τ, h⟩ := finmap.exists_mem_lookup_iff.2 h, ⟨v, t, h⟩ := σok _ _ h in alist.exists_mem_lookup_iff.1 ⟨v, t⟩ theorem vars_ty.ok.subset {Δ σ} (σok : vars_ty.ok Δ σ) : σ.keys ⊆ Δ.keys.to_finset := λ x h, list.mem_to_finset.2 $ alist.mem_keys.2 $ σok.mem $ finmap.mem_keys.1 h theorem vars_ty.ok.weak {Δ σ x τ} (h) (σok : vars_ty.ok Δ σ) : vars_ty.ok (Δ.cons x τ h) σ := λ x' τ' h, let ⟨t, m, h⟩ := σok _ _ h in ⟨t, alist.lookup_cons_of_lookup m, h⟩ theorem vars_ty.ok.insert {Δ σ x t τ} (σok : vars_ty.ok Δ σ) (hn : x ∉ σ) (h₁ : t ∈ alist.lookup x Δ) (h₂ : vtype.of_ty (exp.type.reg t) τ) : vars_ty.ok Δ (σ.insert x τ) := λ x' τ' h, begin rcases (finmap.lookup_insert_of_neg hn).1 h with ⟨⟨⟩⟩ | h, exacts [⟨_, h₁, h₂⟩, σok _ _ h] end theorem vars_ty.ok.erase {Δ σ x t h} (σok : vars_ty.ok (alist.cons Δ x t h) σ) : vars_ty.ok Δ (σ.erase x) := λ x' τ' h, begin rcases finmap.lookup_erase'.1 h with ⟨ne, h⟩, rcases σok _ _ h with ⟨t', m, tτ'⟩, rcases alist.lookup_cons_iff.1 m with ⟨⟨⟩⟩ | m, {cases ne rfl}, exact ⟨t', m, tτ'⟩ end theorem vars_ty.ok.ok_of_mem {Δ σ x t τ} (σok : vars_ty.ok Δ σ) (h₁ : τ ∈ σ.lookup x) (h₂ : t ∈ Δ.lookup x) : vtype.of_ty (exp.type.reg t) τ := let ⟨v', m, h⟩ := σok _ _ h₁ in option.mem_unique m h₂ ▸ h theorem vars.ok.mem {Γ E σ η} (ηok : vars.ok Γ E η σ) {x} (h : x ∈ σ) : x ∈ η := let ⟨τ, h⟩ := finmap.exists_mem_lookup_iff.2 h, ⟨v, t, h⟩ := ηok _ _ h in finmap.exists_mem_lookup_iff.1 ⟨v, t⟩ theorem vars.ok.ok_of_mem {Γ E σ η} (ηok : vars.ok Γ E η σ) {x τ} (h₁ : τ ∈ σ.lookup x) {v} (h₂ : v ∈ η.lookup x) : value.ok Γ E v τ := let ⟨v', m, h⟩ := ηok _ _ h₁ in option.mem_unique m h₂ ▸ h theorem vars.ok.insert {Γ E σ η x v τ} (ηok : vars.ok Γ E η σ) (hn : x ∉ η) (vok : value.ok Γ E v τ) : vars.ok Γ E (η.insert x v) (σ.insert x τ) := λ x' τ' h, begin rcases (finmap.lookup_insert_of_neg (mt ηok.mem hn)).1 h with ⟨⟨⟩⟩ | h, { exact ⟨_, finmap.lookup_insert_self hn, vok⟩ }, { rcases ηok _ _ h with ⟨v, vη, h⟩, exact ⟨v, (finmap.lookup_insert_of_neg hn).2 (or.inr vη), h⟩ } end theorem vars.ok.erase {Γ E σ η x} (ηok : vars.ok Γ E η σ) : vars.ok Γ E η (σ.erase x) := λ x' τ' h, ηok _ _ (finmap.lookup_erase'.1 h).2 theorem heap_le_nth {E E' : heap_ty} (EE : E ≤ E') {i τ} (h : τ ∈ E.nth i) : τ ∈ E'.nth i := begin rcases EE with ⟨l, rfl⟩, induction E with τ' E IH generalizing i, {cases h}, cases i; [{cases h, exact rfl}, exact IH h] end theorem value.ok.mono {Γ E E' v τ} (EE : E ≤ E') (h : value.ok Γ E v τ) : value.ok Γ E' v τ := begin induction h; constructor; try {assumption}, { exact λ x h, heap_le_nth EE (h_a_1 x h) }, { exact λ x h, (h_a_1 x h).imp (λ _, heap_le_nth EE) } end theorem vars.ok.mono {Γ E E' σ η} (EE : E ≤ E') (ηok : vars.ok Γ E η σ) : vars.ok Γ E' η σ := λ i τ h, let ⟨t, h₁, h₂⟩ := ηok i τ h in ⟨t, h₁, h₂.mono EE⟩ theorem addr.ok.mono {Γ E E' σ a τ} (EE : E ≤ E') (aok : addr.ok Γ E σ a τ) : addr.ok Γ E' σ a τ := begin induction aok; constructor; try {assumption}, exact heap_le_nth EE aok_a end theorem addr_opt.ok.mono {Γ E E' σ} (EE : E ≤ E') : ∀ {a τ}, addr_opt.ok Γ E σ a τ → addr_opt.ok Γ E' σ a τ | none τ h := trivial | (some a) τ h := addr.ok.mono EE h theorem cont.ok.mono {Γ E E' σ Δ ret δ α τ K} (EE : E ≤ E') (Kok : @cont.ok Γ E σ Δ ret δ α τ K) : cont.ok Γ E' σ Δ ret δ τ K := by induction Kok; constructor; { assumption <|> exact addr_opt.ok.mono EE (by assumption) <|> exact value.ok.mono EE (by assumption) <|> exact λ a h, (Kok_a _ h).imp (λ _, addr.ok.mono EE) } theorem stack.ok.mono {Γ E E' σs S ret} (EE : E ≤ E') (Sok : stack.ok Γ E σs S ret) : stack.ok Γ E' σs S ret := by induction Sok; constructor; { assumption <|> exact vars.ok.mono EE (by assumption) <|> exact cont.ok.mono EE (by assumption) } theorem heap_ty.le_add (E : heap_ty) (τ) : E ≤ E.add τ := ⟨_, rfl⟩ theorem heap.ok.add {Γ E H v τ} (Eok : heap.ok Γ H E) (vok : value.ok Γ (E.add τ) v τ) : heap.ok Γ (H ++ [v]) (E.add τ) := list.forall₂_concat.2 ⟨Eok.imp (λ _ _, value.ok.mono (E.le_add _)), vok⟩ theorem env.ok.empty {Γ} : env.ok Γ ∅ ∅ vtype.int := ⟨by rintro _ _ ⟨⟩, list.forall₂.nil, by rintro _ _ ⟨⟩, stack.ok.nil⟩ namespace vtype open ast.exp.type def of_ty_fn : ∀ τ, {vτ // of_ty τ vτ} | void := ⟨_, of_ty.void⟩ | (reg type.int) := ⟨_, of_ty.int⟩ | (reg type.bool) := ⟨_, of_ty.bool⟩ | (reg (type.ref τ)) := let f := of_ty_fn (reg τ) in ⟨_, of_ty.ref f.2⟩ | (reg (type.arr τ)) := let f := of_ty_fn (reg τ) in ⟨_, of_ty.arr f.2⟩ | (reg (type.struct s)) := ⟨_, of_ty.struct⟩ | (ls []) := ⟨_, of_ty.nil⟩ | (ls (τ :: τs)) := let f₁ := of_ty_fn (reg τ), f₂ := of_ty_fn (ls τs) in ⟨_, of_ty.cons f₁.2 f₂.2⟩ theorem of_ty_eq : ∀ {τ vτ}, of_ty τ vτ → vτ = (of_ty_fn τ).1 | void vτ h := by cases h; refl | (reg type.int) vτ h := by cases h; refl | (reg type.bool) vτ h := by cases h; refl | (reg (type.ref τ)) vτ h := by cases h; rw [of_ty_eq h_a, of_ty_fn] | (reg (type.arr τ)) vτ h := by cases h; rw [of_ty_eq h_a, of_ty_fn] | (reg (type.struct s)) vτ h := by cases h; refl | (ls []) vτ h := by cases h; refl | (ls (τ :: τs)) vτ h := by cases h; rw [of_ty_eq h_a, of_ty_eq h_a_1, of_ty_fn] theorem of_ty_determ {τ vτ₁ vτ₂} (h₁ : of_ty τ vτ₁) (h₂ : of_ty τ vτ₂) : vτ₁ = vτ₂ := (of_ty_eq h₁).trans (of_ty_eq h₂).symm @[simp] theorem of_map_cons {vs x v h} : of_map (alist.cons vs x v h) = cons (named x v) (of_map vs) := alist.rec'_cons _ _ _ _ theorem of_ty_alist (sd) : {τs // alist.forall₂ (λ (_x : ident) (t : type), vtype.of_ty (exp.type.reg t)) sd τs} := ⟨alist.map (λ _ τ, (vtype.of_ty_fn (exp.type.reg τ)).1) sd, alist.forall₂_map_right_iff.2 (alist.forall₂_same $ λ _ τ _, (vtype.of_ty_fn _).2)⟩ end vtype namespace value theorem ok.null {Γ E τ} : value.ok Γ E (value.ref none) (vtype.ref τ) := value.ok.ref $ by rintro _ ⟨⟩ theorem ok.null_arr {Γ E τ} : value.ok Γ E (value.ref none) (vtype.refarr τ) := value.ok.refarr $ by rintro _ ⟨⟩ theorem is_nth.ok {Γ E i n v v' τ} (vok : ok Γ E v (vtype.arr' τ n)) (lt : i < n) (h : is_nth i v v') : ok Γ E v' τ := begin induction h generalizing n, { cases n, {cases lt}, cases vok, exact vok_a }, { cases n, {cases lt}, cases vok, exact h_ih vok_a_1 (nat.lt_of_succ_lt_succ lt) } end def ok_type_or_sdef (Γ E) (v : value) : type ⊕ sdef → Prop | (sum.inl τ) := ∃ τ', vtype.of_ty (exp.type.reg τ) τ' ∧ value.ok Γ E v τ' | (sum.inr sd) := ∃ vs, v = of_map vs ∧ alist.forall₂ (λ _ τ v', ∃ vτ, vtype.of_ty (exp.type.reg τ) vτ ∧ value.ok Γ E v' vτ) sd vs theorem default.weak {Γ d sd v} (h : default Γ sd v) : default (d :: Γ) sd v := by induction h; constructor; try {assumption}; exact h_a.weak @[simp] theorem of_map_cons {vs x v} (h) : of_map (alist.cons vs x v h) = cons (named x v) (of_map vs) := alist.rec'_cons _ _ _ _ theorem of_map_inj {vs} : ∀ {vs'}, of_map vs = of_map vs' → vs = vs' := begin refine alist.rec' _ (λ vs x v h IH, _) vs; intro vs'; refine alist.rec' _ (λ vs' y v' h' IH', _) vs'; intro e, {refl}, {cases e}, {cases e}, rw [of_map_cons, of_map_cons] at e, injection e, cases h_1, cases IH h_2, refl end theorem of_map_ok {Γ E v τs} : ok Γ E v (vtype.of_map τs) ↔ ∃ vs, v = of_map vs ∧ alist.forall₂ (λ _, ok Γ E) vs τs := begin refine alist.rec' _ (λ τs x τ h IH, _) τs v; intro vs; split, { rintro ⟨⟩, exact ⟨∅, rfl, by constructor⟩ }, { rintro ⟨⟨vs, _⟩, rfl, ⟨⟩⟩, constructor }, { intro H, rw vtype.of_map_cons at H, generalize_hyp e₂ : vtype.of_map τs = τ' at H, cases H, cases H_a, subst τ', rcases (IH _).1 H_a_1 with ⟨vs, rfl, al⟩, exact ⟨_, (of_map_cons (mt al.mem_iff.1 h)).symm, alist.forall₂_cons.2 ⟨H_a_a, al⟩⟩ }, { rintro ⟨vs, rfl, H⟩, generalize_hyp e : alist.cons τs x τ h = τs' at H, revert e, refine alist.forall₂.induction H (by rintro ⟨⟩) _, intros vs τs x v τ h₁ h₂ vok h _ e, rcases alist.cons_inj e with ⟨⟨⟩, rfl⟩, rw [vtype.of_map_cons, of_map_cons], exact ok.cons (ok.named vok) ((IH _).2 ⟨_, rfl, h⟩) }, end end value namespace addr theorem ok.ref_opt {Γ E σ n τ} (h : value.ok Γ E (value.ref n) (vtype.ref τ)) : addr_opt.ok Γ E σ (addr.ref <$> n) τ := by cases h; cases n; [trivial, exact addr.ok.ref (h_a_1 _ rfl)] theorem ok.refarr_opt {Γ E σ n τ} (h : value.ok Γ E (value.ref n) (vtype.refarr τ)) (a ∈ addr.ref <$> n) : ∃ i, addr.ok Γ E σ a (vtype.arr τ i) := begin cases n; cases H; cases h, exact (h_a_1 _ rfl).imp (λ _, addr.ok.ref) end theorem at_head.ok {Γ E τ τs} {R : value → value → Prop} (Rok : ∀ x, value.ok Γ E x τ → ∀ y, R x y → value.ok Γ E y τ) (x) (xok : value.ok Γ E x (vtype.cons τ τs)) (y) (h : value.at_head R x y) : value.ok Γ E y (vtype.cons τ τs) := begin rcases xok with _|_|_|_|⟨x, vs, _, _, xok, xsok⟩, rcases h with ⟨x, y, vs, r⟩, exact value.ok.cons (Rok _ xok _ r) xsok end theorem at_tail.ok {Γ E τ τs} {R : value → value → Prop} (Rok : ∀ x, value.ok Γ E x τs → ∀ y, R x y → value.ok Γ E y τs) (x) (xok : value.ok Γ E x (vtype.cons τ τs)) (y) (h : value.at_tail R x y) : value.ok Γ E y (vtype.cons τ τs) := begin rcases xok with _|_|_|_|⟨x, vs, _, _, xok, xsok⟩, rcases h with ⟨x, y, vs, r⟩, exact value.ok.cons xok (Rok _ xsok _ r) end theorem at_nth'.ok {Γ E τ i n} {R : value → value → Prop} (Rok : ∀ x, value.ok Γ E x τ → ∀ y, R x y → value.ok Γ E y τ) (lt : i < n) (x) (xok : value.ok Γ E x (vtype.arr' τ n)) (y) (r : value.at_nth' R i x y) : value.ok Γ E y (vtype.arr' τ n) := begin induction i generalizing n lt x xok y, { cases n, {cases lt}, exact at_head.ok Rok _ xok _ r }, { cases n, {cases lt}, refine at_tail.ok _ _ xok _ r, exact i_ih (nat.lt_of_succ_lt_succ lt) } end theorem at_nth.ok {Γ E τ i n} {R : value → value → Prop} (Rok : ∀ x, value.ok Γ E x τ → ∀ y, R x y → value.ok Γ E y τ) (lt : i < n) (x) (xok : value.ok Γ E x (vtype.arr τ n)) (y) (h : value.at_nth R i x y) : value.ok Γ E y (vtype.arr τ n) := begin rcases xok with _|_|_|_|_|⟨x,_,n,xok'⟩, rcases h with ⟨_, y, _, lt, r⟩, exact value.ok.arr (at_nth'.ok Rok lt _ xok' _ r) end theorem at_field.ok {Γ : ast} (ok : Γ.okind) {E τ f s} {R : value → value → Prop} (Rok : ∀ x, value.ok Γ E x τ → ∀ y, R x y → value.ok Γ E y τ) {sd} (hd : Γ.get_sdef s sd) {t} (ht : t ∈ sd.lookup f) (tτ : vtype.of_ty (exp.type.reg t) τ) (x) (xok : value.ok Γ E x (vtype.struct s)) (y) (h : value.at_field R f x y) : value.ok Γ E y (vtype.struct s) := begin rcases xok with _|_|_|_|_|_|_|_|⟨_, vs, _, al, e⟩, cases h, cases value.of_map_inj (e.symm.trans h_a_2), refine value.ok.struct (λ sd' τs hd' h, _) h_a_3, cases get_sdef_determ ok hd hd', rcases value.of_map_ok.1 (al sd τs hd h) with ⟨vs', e, al'⟩, cases value.of_map_inj e, rcases alist.forall₂.rel_of_lookup_right h ht with ⟨τ', h', tτ'⟩, cases vtype.of_ty_determ tτ tτ', have al₁ := list.forall₂_and_right.2 ⟨(alist.replace_forall₂ _ _ _).flip, λ _, id⟩, have al₂ := list.forall₂_and_right.2 ⟨al', λ _, id⟩, refine value.of_map_ok.2 ⟨_, rfl, list.forall₂.mp_trans _ al₁ al₂⟩, rintro _ _ _ ⟨⟨x, v', v, h⟩, m₁⟩ ⟨⟨_, _, τ', vok⟩, m₂⟩, refine ⟨_⟩, cases h with _ _ _ h, { cases option.mem_unique h_a_1 (alist.mem_lookup_iff.2 m₁), cases option.mem_unique h' (alist.mem_lookup_iff.2 m₂), exact Rok _ vok _ h_a }, { exact vok } end theorem eq.ok {Γ E τ v} (vok : value.ok Γ E v τ) : ∀ x, value.ok Γ E x τ → ∀ y, v = y → value.ok Γ E y τ | _ _ _ rfl := vok theorem get.ok {Γ E Δ H σ η} (σok : vars_ty.ok Δ σ) (Hok : heap.ok Γ H E) (ηok : vars.ok Γ E η σ) {v a τ} (aok : addr.ok Γ E σ a τ) (h : get H η a v) : value.ok Γ E v τ := begin induction h generalizing τ, case c0.addr.get.ref : n v h { cases aok, exact list.forall₂.nth Hok h aok_a }, case c0.addr.get.var : n v h { cases aok, exact ηok.ok_of_mem aok_a h }, case c0.addr.get.head : a v vs h IH { rcases aok with _|_|⟨_, _, τs, aok⟩, cases IH aok, exact a_1 }, case c0.addr.get.tail : a v vs h IH { rcases aok with _|_|_|⟨_, τ₁, _, aok⟩, cases IH aok, exact a_2 }, case c0.addr.get.nth : a i n v v' h h' IH { rcases aok with _|_|_|_|⟨a, _, n', d, lt, aok⟩, rcases IH aok with _|_|_|_|_|⟨_, _, _, vok⟩, exact h'.ok vok lt }, case c0.addr.get.field : a f vs v h hf IH { rcases aok with _|_|_|_|_|⟨_, s, _, t, sd, _, hsd, m, tτ, aok⟩, have := IH aok, generalize_hyp e : value.of_map vs = v' at this, cases this, subst v', cases value.of_map_inj this_a_1, cases vtype.of_ty_alist sd with τs sτ, rcases value.of_map_ok.1 (this_a _ _ hsd sτ) with ⟨vs', e, h⟩, cases value.of_map_inj e, rcases sτ.rel_of_lookup_right m with ⟨τ', m', tτ'⟩, cases vtype.of_ty_determ tτ tτ', exact h.rel_of_lookup hf m' } end end addr theorem stmt_list.ok.eq_none {Γ Δ δ ret} (Kok : stmt_list.ok Γ ret Δ δ []) : ret = none := begin generalize e : ([]:list stmt) = ss, rw e at Kok, induction Kok; cases e; [exact Kok_a, exact Kok_ih rfl] end end c0
73ba57185ce06580593051aa39164bc7bbc852ec
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/pi.lean
1872e2d550b42699dde581502bd57473f130013d
[ "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
4,539
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import tactic.split_ifs import tactic.simpa import tactic.congr import algebra.group.to_additive /-! # Instances and theorems on pi types This file provides basic definitions and notation instances for Pi types. Instances of more sophisticated classes are defined in `pi.lean` files elsewhere. -/ universes u v₁ v₂ v₃ variable {I : Type u} -- The indexing type -- The families of types already equipped with instances variables {f : I → Type v₁} {g : I → Type v₂} {h : I → Type v₃} variables (x y : Π i, f i) (i : I) namespace pi /-! `1`, `0`, `+`, `*`, `-`, `⁻¹`, and `/` are defined pointwise. -/ @[to_additive] instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ _, 1⟩ @[simp, to_additive] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl @[to_additive] lemma one_def [Π i, has_one $ f i] : (1 : Π i, f i) = λ i, 1 := rfl @[to_additive] instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ f g i, f i * g i⟩ @[simp, to_additive] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl @[to_additive] lemma mul_def [Π i, has_mul $ f i] : x * y = λ i, x i * y i := rfl @[to_additive] instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ f i, (f i)⁻¹⟩ @[simp, to_additive] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl @[to_additive] instance has_div [Π i, has_div $ f i] : has_div (Π i : I, f i) := ⟨λ f g i, f i / g i⟩ @[simp, to_additive] lemma div_apply [Π i, has_div $ f i] : (x / y) i = x i / y i := rfl @[to_additive] lemma div_def [Π i, has_div $ f i] : x / y = λ i, x i / y i := rfl section variables [decidable_eq I] variables [Π i, has_zero (f i)] [Π i, has_zero (g i)] [Π i, has_zero (h i)] /-- The function supported at `i`, with value `x` there. -/ def single (i : I) (x : f i) : Π i, f i := function.update 0 i x @[simp] lemma single_eq_same (i : I) (x : f i) : single i x i = x := function.update_same i x _ @[simp] lemma single_eq_of_ne {i i' : I} (h : i' ≠ i) (x : f i) : single i x i' = 0 := function.update_noteq h x _ /-- Abbreviation for `single_eq_of_ne h.symm`, for ease of use by `simp`. -/ @[simp] lemma single_eq_of_ne' {i i' : I} (h : i ≠ i') (x : f i) : single i x i' = 0 := single_eq_of_ne h.symm x @[simp] lemma single_zero (i : I) : single i (0 : f i) = 0 := function.update_eq_self _ _ /-- On non-dependent functions, `pi.single` can be expressed as an `ite` -/ lemma single_apply {β : Sort*} [has_zero β] (i : I) (x : β) (i' : I) : single i x i' = if i' = i then x else 0 := function.update_apply 0 i x i' /-- On non-dependent functions, `pi.single` is symmetric in the two indices. -/ lemma single_comm {β : Sort*} [has_zero β] (i : I) (x : β) (i' : I) : single i x i' = single i' x i := by simp only [single_apply, eq_comm]; congr -- deal with `decidable_eq` lemma apply_single (f' : Π i, f i → g i) (hf' : ∀ i, f' i 0 = 0) (i : I) (x : f i) (j : I): f' j (single i x j) = single i (f' i x) j := by simpa only [pi.zero_apply, hf', single] using function.apply_update f' 0 i x j lemma apply_single₂ (f' : Π i, f i → g i → h i) (hf' : ∀ i, f' i 0 0 = 0) (i : I) (x : f i) (y : g i) (j : I): f' j (single i x j) (single i y j) = single i (f' i x y) j := begin by_cases h : j = i, { subst h, simp only [single_eq_same] }, { simp only [single_eq_of_ne h, hf'] }, end lemma single_op {g : I → Type*} [Π i, has_zero (g i)] (op : Π i, f i → g i) (h : ∀ i, op i 0 = 0) (i : I) (x : f i) : single i (op i x) = λ j, op j (single i x j) := eq.symm $ funext $ apply_single op h i x lemma single_op₂ {g₁ g₂ : I → Type*} [Π i, has_zero (g₁ i)] [Π i, has_zero (g₂ i)] (op : Π i, g₁ i → g₂ i → f i) (h : ∀ i, op i 0 0 = 0) (i : I) (x₁ : g₁ i) (x₂ : g₂ i) : single i (op i x₁ x₂) = λ j, op j (single i x₁ j) (single i x₂ j) := eq.symm $ funext $ apply_single₂ op h i x₁ x₂ variables (f) lemma single_injective (i : I) : function.injective (single i : f i → Π i, f i) := function.update_injective _ i end end pi lemma subsingleton.pi_single_eq {α : Type*} [decidable_eq I] [subsingleton I] [has_zero α] (i : I) (x : α) : pi.single i x = λ _, x := funext $ λ j, by rw [subsingleton.elim j i, pi.single_eq_same]
ee11a82b4ea100b6b0313b74663c1bee0701e06b
dfd42d30132c2867977fefe7edae98b6dc703aeb
/src/riemann_sphere.lean
fd951b325738a0d2141def5a00de6e9b9670f23b
[]
no_license
justadzr/lean-2021
1e42057ac75c794c94b8f148a27a24150c685f68
dfc6b30de2f27bdba5fbc51183e2b84e73a920d1
refs/heads/master
1,689,652,366,522
1,630,313,809,000
1,630,313,809,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65
lean
import riemann_surfaces import alexandroff noncomputable theory
b873d8e35ed81c23c995c2768fc7c427c781eb81
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/function/strongly_measurable/inner.lean
2d147cf26fd68525ba3221c57e4e7a8fb90d4918
[ "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,913
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Sébastien Gouëzel -/ import measure_theory.function.strongly_measurable.basic import analysis.inner_product_space.basic /-! # Inner products of strongly measurable functions are strongly measurable. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α : Type*} namespace measure_theory /-! ## Strongly measurable functions -/ namespace strongly_measurable protected lemma inner {𝕜 : Type*} {E : Type*} [is_R_or_C 𝕜] [normed_add_comm_group E] [inner_product_space 𝕜 E] {m : measurable_space α} {f g : α → E} (hf : strongly_measurable f) (hg : strongly_measurable g) : strongly_measurable (λ t, @inner 𝕜 _ _(f t) (g t)) := continuous.comp_strongly_measurable continuous_inner (hf.prod_mk hg) end strongly_measurable namespace ae_strongly_measurable variables {m : measurable_space α} {μ : measure α} {𝕜 : Type*} {E : Type*} [is_R_or_C 𝕜] [normed_add_comm_group E] [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y protected lemma re {f : α → 𝕜} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, is_R_or_C.re (f x)) μ := is_R_or_C.continuous_re.comp_ae_strongly_measurable hf protected lemma im {f : α → 𝕜} (hf : ae_strongly_measurable f μ) : ae_strongly_measurable (λ x, is_R_or_C.im (f x)) μ := is_R_or_C.continuous_im.comp_ae_strongly_measurable hf protected lemma inner {m : measurable_space α} {μ : measure α} {f g : α → E} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ae_strongly_measurable (λ x, ⟪f x, g x⟫) μ := continuous_inner.comp_ae_strongly_measurable (hf.prod_mk hg) end ae_strongly_measurable end measure_theory
2219bdf25970b0c45308f5548b47d6c61e0eca15
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/analysis/convex/basic.lean
18dc7110ab5b56a3e1f5350edd5529fc439eba61
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,511
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import data.set.intervals.ord_connected import data.set.intervals.image_preimage import data.complex.module import linear_algebra.affine_space.affine_map import algebra.module.ordered /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. Note: To define convexity for functions `f : E → β`, we need `β` to be an ordered vector space, defined using the instance `ordered_module ℝ β`. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. -/ universes u' u v v' w x variables {E : Type u} {F : Type v} {ι : Type w} {ι' : Type x} {α : Type v'} [add_comm_group E] [module ℝ E] [add_comm_group F] [module ℝ F] [linear_ordered_field α] {s : set E} open set linear_map open_locale classical big_operators local notation `I` := (Icc 0 1 : set ℝ) section sets /-! ### Segment -/ /-- Segments in a vector space. -/ def segment (x y : E) : set E := {z : E | ∃ (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} local notation `[`x `, ` y `]` := segment x y lemma segment_symm (x y : E) : [x, y] = [y, x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x, y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x, y] := segment_symm y x ▸ left_mem_segment y x lemma segment_same (x : E) : [x, x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment z z⟩ lemma segment_eq_image (x y : E) : segment x y = (λ (θ : ℝ), (1 - θ) • x + θ • y) '' I := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : segment x y = (λ (θ : ℝ), x + θ • (y - x)) '' I := by { convert segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_image₂ (x y : E) : segment x y = (λ p:ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (λ t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_const_add_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj] end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b, a + c] = [b, c] := set.ext $ λ x, mem_segment_translate a lemma segment_translate_image (a b c: E) : (λx, a + x) '' [b, c] = [a + b, a + c] := segment_translate_preimage a b c ▸ image_preimage_eq _ $ add_left_surjective a lemma segment_image (f : E →ₗ[ℝ] F) (a b : E) : f '' [a, b] = [f a, f b] := set.ext (λ x, by simp [segment_eq_image]) /-! ### Convexity of sets -/ /-- Convexity of sets. -/ def convex (s : set E) := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s lemma convex_iff_forall_pos : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x, y] ⊆ s := by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y:E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] ⊆ s := convex_iff_segment_subset.1 h hx hy /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintros hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division. -/ lemma convex_iff_div: convex s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (∅ : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex s) : convex (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s: ι → set E} (h: ∀ i : ι, convex (s i)) : convex (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma convex.combo_to_vadd {a b : ℝ} {x y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := calc a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel ... = b • (y - x) + (a + b) • x : by rw [smul_sub, add_smul] ... = b • (y - x) + (1 : ℝ) • x : by rw [h] ... = b • (y - x) + x : by rw [one_smul] /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : ℝ} {x y : E} {f : E →ᵃ[ℝ] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := begin simp only [convex.combo_to_vadd h, ← vsub_eq_sub], exact f.apply_line_map _ _ _, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᵃ[ℝ] F) {s : set F} (hs : convex s) : convex (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᵃ[ℝ] F) {s : set E} (hs : convex s) : convex (f '' s) := begin rintros x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) := hs.affine_image f.to_affine_map lemma convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) : convex (preimage f s) := hs.affine_preimage f.to_affine_map lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.neg (hs : convex s) : convex ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((λx : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((λ z, a + z) ⁻¹' s) := hs.affine_preimage $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex. -/ lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((λ z, z + a) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right a lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ c • affine_map.id ℝ E lemma real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ ord_connected s := begin simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (λ x, forall_swap) end alias real.convex_iff_ord_connected ↔ convex.ord_connected set.ord_connected.convex lemma convex_Iio (r : ℝ) : convex (Iio r) := ord_connected_Iio.convex lemma convex_Ioi (r : ℝ) : convex (Ioi r) := ord_connected_Ioi.convex lemma convex_Iic (r : ℝ) : convex (Iic r) := ord_connected_Iic.convex lemma convex_Ici (r : ℝ) : convex (Ici r) := ord_connected_Ici.convex lemma convex_Ioo (r s : ℝ) : convex (Ioo r s) := ord_connected_Ioo.convex lemma convex_Ico (r s : ℝ) : convex (Ico r s) := ord_connected_Ico.convex lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := ord_connected_Ioc.convex lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := ord_connected_Icc.convex lemma convex_interval (r : ℝ) (s : ℝ) : convex (interval r s) := ord_connected_interval.convex lemma convex_segment (a b : E) : convex [a, b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λz : E, a + z) ∘ (λt:ℝ, t • (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_halfspace_lt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ /-! ### Convex combinations in intervals -/ lemma convex.combo_self (a : α) {x y : α} (h : x + y = 1) : a = x * a + y * a := calc a = 1 * a : by rw [one_mul] ... = (x + y) * a : by rw [h] ... = x * a + y * a : by rw [add_mul] /-- If `x` is in an `Ioo`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioo {a b x : α} (h : a < b) : x ∈ Ioo a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases hab : ¬a < b, { exfalso; exact hab h }, { refine ⟨(b-x) / (b-a), (x-a) / (b-a), _⟩, refine ⟨div_pos (by linarith) (by linarith), div_pos (by linarith) (by linarith),_,_⟩; { field_simp [show b - a ≠ 0, by linarith], ring } } }, { rw [mem_Ioo], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Ioc`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioc {a b x : α} (h : a < b) : x ∈ Ioc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = b, { exact ⟨0, 1, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨h_ax, lt_of_le_of_ne h_bx h_x⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, by linarith, Ioo_case.2⟩ } }, { rw [mem_Ioc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Ico`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ico {a b x : α} (h : a < b) : x ∈ Ico a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Ico], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If `x` is in an `Icc`, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {a b x : α} (h : a ≤ b) : x ∈ Icc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { intro x_in_I, rw [Icc, mem_set_of_eq] at x_in_I, rcases x_in_I with ⟨h_ax, h_bx⟩, by_cases hab' : a = b, { exact ⟨0, 1, le_refl 0, by linarith, by ring, by linarith⟩ }, change a ≠ b at hab', replace h : a < b, exact lt_of_le_of_ne h hab', by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioc h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Icc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets /-! ### Convex and concave functions -/ section functions variables {β : Type*} [ordered_add_comm_monoid β] [module ℝ β] local notation `[`x `, ` y `]` := segment x y /-- Convexity of functions -/ def convex_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y /-- Concavity of functions -/ def concave_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) section variables [ordered_module ℝ β] /-- A function `f` is concave iff `-f` is convex. -/ @[simp] lemma neg_convex_on_iff {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] (s : set E) (f : E → γ) : convex_on s (-f) ↔ concave_on s f := begin split, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm] at h, exact h }, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm, h] } end /-- A function `f` is concave iff `-f` is convex. -/ @[simp] lemma neg_concave_on_iff {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] (s : set E) (f : E → γ) : concave_on s (-f) ↔ convex_on s f:= by rw [← neg_convex_on_iff s (-f), neg_neg f] end lemma convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := ⟨hs, by { intros, refl }⟩ lemma concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := ⟨hs, by { intros, refl }⟩ lemma convex_on_const (c : β) (hs : convex s) : convex_on s (λ x:E, c) := ⟨hs, by { intros, simp only [← add_smul, *, one_smul] }⟩ lemma concave_on_const (c : β) (hs : convex s) : concave_on s (λ x:E, c) := @convex_on_const _ _ _ _ (order_dual β) _ _ c hs variables {t : set E} lemma convex_on_iff_div {f : E → β} : convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ lemma concave_on_iff_div {f : E → β} : concave_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) := @convex_on_iff_div _ _ _ _ (order_dual β) _ _ _ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_smul, hab, one_smul, one_smul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function on a convex set in a linear ordered space, in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.concave_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) : concave_on s f := @linear_order.convex_on_of_lt _ _ _ _ (order_dual β) _ _ f _ hs hf /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : convex_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f y - f x) / (y - x) ≤ (f z - f y) / (z - y) := begin have h₁ : 0 < y - x := by linarith, have h₂ : 0 < z - y := by linarith, have h₃ : 0 < z - x := by linarith, suffices : f y / (y - x) + f y / (z - y) ≤ f x / (y - x) + f z / (z - y), by { ring_nf at this ⊢, linarith }, set a := (z - y) / (z - x), set b := (y - x) / (z - x), have heqz : a • x + b • z = y, by { field_simp, rw div_eq_iff; [ring, linarith], }, have key, from hf.2 hx hz (show 0 ≤ a, by apply div_nonneg; linarith) (show 0 ≤ b, by apply div_nonneg; linarith) (show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }), rw heqz at key, replace key := mul_le_mul_of_nonneg_left key (le_of_lt h₃), field_simp [ne_of_gt h₁, ne_of_gt h₂, ne_of_gt h₃, mul_comm (z - x) _] at key ⊢, rw div_le_div_right, { linarith, }, { nlinarith, }, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : convex_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) := ⟨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hs⟩ /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/ lemma concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) : concave_on s f := begin rw [←neg_convex_on_iff], apply convex_on_real_of_slope_mono_adjacent hs, intros x y z xs zs xy yz, rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply], end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : concave_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f z - f y) / (z - y) ≤ (f y - f x) / (y - x) := begin rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], rw [←neg_sub_neg (f y), ←neg_sub_neg (f z)], simp_rw [←pi.neg_apply], rw [←neg_convex_on_iff] at hf, apply convex_on.slope_mono_adjacent hf; assumption, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : concave_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) := ⟨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hs⟩ lemma convex_on.subset {f : E → β} (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma concave_on.subset {f : E → β} (h_concave_on : concave_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : concave_on s f := @convex_on.subset _ _ _ _ (order_dual β) _ _ t f h_concave_on h_subset h_convex lemma convex_on.add {f g : E → β} (hf : convex_on s f) (hg : convex_on s g) : convex_on s (λx, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a • f x + a • g x + b • f y + b • g y : by abel ... = a • (f x + g x) + b • (f y + g y) : by simp [smul_add, add_assoc] end lemma concave_on.add {f g : E → β} (hf : concave_on s f) (hg : concave_on s g) : concave_on s (λx, f x + g x) := @convex_on.add _ _ _ _ (order_dual β) _ _ f g hf hg lemma convex_on.smul [ordered_module ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s (λx, c • f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c • f (a • x + b • y) ≤ c • (a • f x + b • f y) : smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc ... = a • (c • f x) + b • (c • f y) : by simp only [smul_add, smul_comm c] end lemma concave_on.smul [ordered_module ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : concave_on s f) : concave_on s (λx, c • f x) := @convex_on.smul _ _ _ _ (order_dual β) _ _ _ f c hc hf /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment' {γ : Type*} [linear_ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} {x y : E} {a b : ℝ} (hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • max (f x) (f y) + b • max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb) ... ≤ max (f x) (f y) : by rw [←add_smul, hab, one_smul] /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment' {γ : Type*} [linear_ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} {x y : E} {a b : ℝ} (hf : concave_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min (f x) (f y) ≤ f (a • x + b • y) := @convex_on.le_on_segment' _ _ _ _ (order_dual γ) _ _ _ f x y a b hf hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment {γ : Type*} [linear_ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment {γ : Type*} [linear_ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : min (f x) (f y) ≤ f z := @convex_on.le_on_segment _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz lemma convex_on.convex_le [ordered_module ℝ β] {f : E → β} (hf : convex_on s f) (r : β) : convex {x ∈ s | f x ≤ r} := convex_iff_segment_subset.2 $ λ x y hx hy z hz, begin refine ⟨hf.1.segment_subset hx.1 hy.1 hz,_⟩, rcases hz with ⟨za,zb,hza,hzb,hzazb,H⟩, rw ←H, calc f (za • x + zb • y) ≤ za • (f x) + zb • (f y) : hf.2 hx.1 hy.1 hza hzb hzazb ... ≤ za • r + zb • r : add_le_add (smul_le_smul_of_nonneg hx.2 hza) (smul_le_smul_of_nonneg hy.2 hzb) ... ≤ r : by simp [←add_smul, hzazb] end lemma concave_on.concave_le [ordered_module ℝ β] {f : E → β} (hf : concave_on s f) (r : β) : convex {x ∈ s | r ≤ f x} := @convex_on.convex_le _ _ _ _ (order_dual β) _ _ _ f hf r lemma convex_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : convex_on s f) (r : γ) : convex {x ∈ s | f x < r} := begin intros a b as bs xa xb hxa hxb hxaxb, refine ⟨hf.1 as.1 bs.1 hxa hxb hxaxb, _⟩, dsimp, by_cases H : xa = 0, { have H' : xb = 1 := by rwa [H, zero_add] at hxaxb, rw [H, H', zero_smul, one_smul, zero_add], exact bs.2 }, { calc f (xa • a + xb • b) ≤ xa • (f a) + xb • (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb ... < xa • r + xb • (f b) : (add_lt_add_iff_right (xb • (f b))).mpr (smul_lt_smul_of_pos as.2 (lt_of_le_of_ne hxa (ne.symm H))) ... ≤ xa • r + xb • r : (add_le_add_iff_left (xa • r)).mpr (smul_le_smul_of_nonneg bs.2.le hxb) ... = r : by simp only [←add_smul, hxaxb, one_smul] } end lemma concave_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : concave_on s f) (r : γ) : convex {x ∈ s | r < f x} := @convex_on.convex_lt _ _ _ _ (order_dual γ) _ _ _ f hf r lemma convex_on.convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : convex_on s f) : convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha) (smul_le_smul_of_nonneg ht hb) end lemma concave_on.convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} (hf : concave_on s f) : convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on.convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f hf lemma convex_on_iff_convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} : convex_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end lemma concave_on_iff_convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [module ℝ γ] [ordered_module ℝ γ] {f : E → γ} : concave_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on_iff_convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f /-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/ lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : convex_on s f) : convex_on (g ⁻¹' s) (f ∘ g) := begin refine ⟨hf.1.affine_preimage _,_⟩, intros x y xs ys a b ha hb hab, calc (f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl ... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab] ... ≤ a • f (g x) + b • f (g y) : hf.2 xs ys ha hb hab ... = a • (f ∘ g) x + b • (f ∘ g) y : rfl end /-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/ lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : concave_on s f) : concave_on (g ⁻¹' s) (f ∘ g) := @convex_on.comp_affine_map _ _ _ _ _ _ (order_dual β) _ _ f g s hf /-- If `g` is convex on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma convex_on.comp_linear_map {g : F → β} {s : set F} (hg : convex_on s g) (f : E →ₗ[ℝ] F) : convex_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma concave_on.comp_linear_map {g : F → β} {s : set F} (hg : concave_on s g) (f : E →ₗ[ℝ] F) : concave_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If a function is convex on `s`, it remains convex after a translation. -/ lemma convex_on.translate_right {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is concave on `s`, it remains concave after a translation. -/ lemma concave_on.translate_right {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is convex on `s`, it remains convex after a translation. -/ lemma convex_on.translate_left {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right /-- If a function is concave on `s`, it remains concave after a translation. -/ lemma concave_on.translate_left {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right end functions /-! ### Center of mass -/ section center_mass /-- Center of mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ noncomputable def finset.center_mass (t : finset ι) (w : ι → ℝ) (z : ι → E) : E := (∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i) variables (i j : ι) (c : ℝ) (t : finset ι) (w : ι → ℝ) (z : ι → E) open finset lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i ≠ j) : ({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) : (insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i + ((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm, ← div_eq_inv_mul], congr' 2, rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div] end lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) : t.center_mass w z = ∑ i in t, w i • z i := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E) (hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : ℝ) (hab : a + b = 1) : a • s.center_mass ws zs + b • t.center_mass wt zt = (s.map function.embedding.inl ∪ t.map function.embedding.inr).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ι) (w₁ w₂ : ι → ℝ) (z : ι → E) (hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : ℝ) (hab : a + b = 1) : a • s.center_mass w₁ z + b • s.center_mass w₂ z = s.center_mass (λ i, a * w₁ i + b * w₂ i) z := have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (λ j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity ∑ j in t, if (i = j) then z i else 0, { congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t') (h : ∀ i ∈ t', i ∉ t → w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _ _) $ λ i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- The center of mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s := begin induction t using finset.induction with i t hi ht, { simp [lt_irrefl] }, intros h₀ hpos hmem, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : ∑ j in t, w j = 0, { have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t, have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos, { exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact h₀ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s) : ∑ i in t, w i • z i ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (∀ (t : finset E) (w : E → ℝ), (∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) := begin refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (λ z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (hpos : 0 < ∑ i in t, w i) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≤ t.center_mass w (f ∘ z) := begin have hmem' : ∀ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}, from λ i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem h₀ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hmem : ∀ i ∈ t, z i ∈ s) : f (∑ i in t, w i • z i) ≤ ∑ i in t, w i * (f (z i)) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center of mass of some points `z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E → ℝ} (h : convex_on s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) (hz : ∀ i ∈ t, z i ∈ s) : ∃ i ∈ t, f (t.center_mass w z) ≤ f (z i) := begin set y := t.center_mass w z, have : f y ≤ t.center_mass w (f ∘ z) := h.map_center_mass_le hw₀ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : ∃ i ∈ t.filter (λ i, w i ≠ 0), f y * w i ≤ w i • (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hw₀ i hi.1) hi.2.symm end end center_mass /-! ### Convex hull -/ section convex_hull variable {t : set E} /-- The convex hull of a set `s` is the minimal convex set that includes `s`. -/ def convex_hull (s : set E) : set E := ⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t variable (s) lemma subset_convex_hull : s ⊆ convex_hull s := set.subset_Inter $ λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst lemma convex_convex_hull : convex (convex_hull s) := convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id variable {s} lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t) lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s) @[simp] lemma convex_hull_empty : convex_hull (∅ : set E) = ∅ := convex_empty.convex_hull_eq @[simp] lemma convex_hull_empty_iff : convex_hull s = ∅ ↔ s = ∅ := begin split, { intro h, rw [←set.subset_empty_iff, ←h], exact subset_convex_hull _ }, { rintro rfl, exact convex_hull_empty } end @[simp] lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → ℝ) (z : ι → E) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s), t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one, finset.sum_singleton, λ _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_map, finset.mem_map] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwx₀, hwy₀] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_map, finset.mem_map] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E → ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : ∃ y ∈ s, f x ≤ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hw₀, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one) (λ i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma finset.convex_hull_eq (s : finset E) : convex_hull ↑s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1), s.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, rw [finset.mem_coe] at hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hw₀, hw₁, rfl⟩, exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx) (hw₁.symm ▸ zero_lt_one) (λ x hx, hx) } end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} := by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop] using hs.to_finset.convex_hull_eq lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull ↑t := begin refine subset.antisymm _ _, { rw [convex_hull_eq.{u}], rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, simp only [mem_Union], refine ⟨t.image z, _, _⟩, { rw [finset.coe_image, image_subset_iff], exact hz }, { apply t.center_mass_mem_convex_hull hw₀, { simp only [hw₁, zero_lt_one] }, { exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } }, { exact Union_subset (λ i, Union_subset convex_hull_mono), }, end lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ι) [fintype ι] {f : ι → ℝ} /-- The standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) := {f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1} lemma std_simplex_eq_inter : std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ι := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩ /-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ λ(i j:ι), if i = j then (1:ℝ) else 0) = std_simplex ι := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ι)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hw₀, hw₁⟩, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i) (hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) } end variable {ι} /-- The convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `∑ x in s, w x • x`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = by haveI := hs.fintype; exact (⇑(∑ x : s, (@linear_map.proj ℝ s _ (λ i, ℝ) _ _ x).smul_right x.1)) '' (std_simplex s) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)], apply congr_arg, convert subtype.range_coe.symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ι) (x) : f x ∈ I := ⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
2330de5b02172ef40b9081a1f5373f878cf1606e
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/path_category.lean
963973e54270a1fad6fab87863a5659d54433e9a
[ "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
5,246
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.eq_to_hom import category_theory.quotient import combinatorics.quiver.path /-! # The category paths on a quiver. When `C` is a quiver, `paths C` is the category of paths. ## When the quiver is itself a category We provide `path_composition : paths C ⥤ C`. We check that the quotient of the path category of a category by the canonical relation (paths are related if they compose to the same path) is equivalent to the original category. -/ universes v₁ v₂ u₁ u₂ namespace category_theory section /-- A type synonym for the category of paths in a quiver. -/ def paths (V : Type u₁) : Type u₁ := V instance (V : Type u₁) [inhabited V] : inhabited (paths V) := ⟨(default : V)⟩ variables (V : Type u₁) [quiver.{v₁+1} V] namespace paths instance category_paths : category.{max u₁ v₁} (paths V) := { hom := λ (X Y : V), quiver.path X Y, id := λ X, quiver.path.nil, comp := λ X Y Z f g, quiver.path.comp f g, } variables {V} /-- The inclusion of a quiver `V` into its path category, as a prefunctor. -/ @[simps] def of : prefunctor V (paths V) := { obj := λ X, X, map := λ X Y f, f.to_path, } local attribute [ext] functor.ext /-- Two functors out of a path category are equal when they agree on singleton paths. -/ @[ext] lemma ext_functor {C} [category C] {F G : paths V ⥤ C} (h_obj : F.obj = G.obj) (h : ∀ (a b : V) (e : a ⟶ b), F.map e.to_path = eq_to_hom (congr_fun h_obj a) ≫ G.map e.to_path ≫ eq_to_hom (congr_fun h_obj.symm b)) : F = G := begin ext X Y f, { induction f with Y' Z' g e ih, { erw [F.map_id, G.map_id, category.id_comp, eq_to_hom_trans, eq_to_hom_refl], }, { erw [F.map_comp g e.to_path, G.map_comp g e.to_path, ih, h], simp only [category.id_comp, eq_to_hom_refl, eq_to_hom_trans_assoc, category.assoc], }, }, { intro X, rw h_obj, } end end paths variables (W : Type u₂) [quiver.{v₂+1} W] -- A restatement of `prefunctor.map_path_comp` using `f ≫ g` instead of `f.comp g`. @[simp] lemma prefunctor.map_path_comp' (F : prefunctor V W) {X Y Z : paths V} (f : X ⟶ Y) (g : Y ⟶ Z) : F.map_path (f ≫ g) = (F.map_path f).comp (F.map_path g) := prefunctor.map_path_comp _ _ _ end section variables {C : Type u₁} [category.{v₁} C] open quiver /-- A path in a category can be composed to a single morphism. -/ @[simp] def compose_path {X : C} : Π {Y : C} (p : path X Y), X ⟶ Y | _ path.nil := 𝟙 X | _ (path.cons p e) := compose_path p ≫ e @[simp] lemma compose_path_to_path {X Y : C} (f : X ⟶ Y) : compose_path (f.to_path) = f := category.id_comp _ @[simp] lemma compose_path_comp {X Y Z : C} (f : path X Y) (g : path Y Z) : compose_path (f.comp g) = compose_path f ≫ compose_path g := begin induction g with Y' Z' g e ih, { simp, }, { simp [ih], }, end @[simp] lemma compose_path_id {X : paths C} : compose_path (𝟙 X) = 𝟙 X := rfl @[simp] lemma compose_path_comp' {X Y Z : paths C} (f : X ⟶ Y) (g : Y ⟶ Z) : compose_path (f ≫ g) = compose_path f ≫ compose_path g := compose_path_comp f g variables (C) /-- Composition of paths as functor from the path category of a category to the category. -/ @[simps] def path_composition : paths C ⥤ C := { obj := λ X, X, map := λ X Y f, compose_path f, } /-- The canonical relation on the path category of a category: two paths are related if they compose to the same morphism. -/ -- TODO: This, and what follows, should be generalized to -- the `hom_rel` for the kernel of any functor. -- Indeed, this should be part of an equivalence between congruence relations on a category `C` -- and full, essentially surjective functors out of `C`. @[simp] def paths_hom_rel : hom_rel (paths C) := λ X Y p q, (path_composition C).map p = (path_composition C).map q /-- The functor from a category to the canonical quotient of its path category. -/ @[simps] def to_quotient_paths : C ⥤ quotient (paths_hom_rel C) := { obj := λ X, quotient.mk X, map := λ X Y f, quot.mk _ f.to_path, map_id' := λ X, quot.sound (quotient.comp_closure.of _ _ _ (by simp)), map_comp' := λ X Y Z f g, quot.sound (quotient.comp_closure.of _ _ _ (by simp)), } /-- The functor from the canonical quotient of a path category of a category to the original category. -/ @[simps] def quotient_paths_to : quotient (paths_hom_rel C) ⥤ C := quotient.lift _ (path_composition C) (λ X Y p q w, w) /-- The canonical quotient of the path category of a category is equivalent to the original category. -/ def quotient_paths_equiv : quotient (paths_hom_rel C) ≌ C := { functor := quotient_paths_to C, inverse := to_quotient_paths C, unit_iso := nat_iso.of_components (λ X, by { cases X, refl, }) begin intros, cases X, cases Y, induction f, dsimp, simp only [category.comp_id, category.id_comp], apply quot.sound, apply quotient.comp_closure.of, simp [paths_hom_rel], end, counit_iso := nat_iso.of_components (λ X, iso.refl _) (by tidy), functor_unit_iso_comp' := by { intros, cases X, dsimp, simp, refl, }, } end end category_theory
61ae1ed37740b3767a262e9b607f5997619d3f36
4fa161becb8ce7378a709f5992a594764699e268
/src/algebra/ordered_ring.lean
ff2d3c5a692df7108a2fcc005d7932537cbb56e3
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
43,939
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, Mario Carneiro -/ import algebra.ring import algebra.ordered_group set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true universe u variable {α : Type u} /-- An `ordered_semiring α` is a semiring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_semiring (α : Type u) extends semiring α, ordered_cancel_add_comm_monoid α := (mul_lt_mul_of_pos_left : ∀ a b c : α, a < b → 0 < c → c * a < c * b) (mul_lt_mul_of_pos_right : ∀ a b c : α, a < b → 0 < c → a * c < b * c) section ordered_semiring variables [ordered_semiring α] {a b c d : α} lemma ordered_semiring.mul_le_mul_of_nonneg_left (a b c : α) (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := begin cases classical.em (b ≤ a), { simp [le_antisymm h h₁] }, cases classical.em (c ≤ 0), { simp [le_antisymm h_1 h₂] }, exact (le_not_le_of_lt (ordered_semiring.mul_lt_mul_of_pos_left a b c (lt_of_le_not_le h₁ h) (lt_of_le_not_le h₂ h_1))).left, end lemma ordered_semiring.mul_le_mul_of_nonneg_right (a b c : α) (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := begin cases classical.em (b ≤ a), { simp [le_antisymm h h₁] }, cases classical.em (c ≤ 0), { simp [le_antisymm h_1 h₂] }, exact (le_not_le_of_lt (ordered_semiring.mul_lt_mul_of_pos_right a b c (lt_of_le_not_le h₁ h) (lt_of_le_not_le h₂ h_1))).left, end lemma mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := ordered_semiring.mul_le_mul_of_nonneg_left a b c h₁ h₂ lemma mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := ordered_semiring.mul_le_mul_of_nonneg_right a b c h₁ h₂ lemma mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := ordered_semiring.mul_lt_mul_of_pos_left a b c h₁ h₂ lemma mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := ordered_semiring.mul_lt_mul_of_pos_right a b c h₁ h₂ -- TODO: there are four variations, depending on which variables we assume to be nonneg lemma mul_le_mul (hac : a ≤ c) (hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := have h : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right ha hb, by rwa [zero_mul] at h lemma mul_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a * b ≤ 0 := have h : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left hb ha, by rwa mul_zero at h lemma mul_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a * b ≤ 0 := have h : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right ha hb, by rwa zero_mul at h lemma mul_lt_mul (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left hbd nn_c lemma mul_lt_mul' (h1 : a ≤ c) (h2 : b < d) (h3 : 0 ≤ b) (h4 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right h1 h3 ... < c * d : mul_lt_mul_of_pos_left h2 h4 lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 := have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha, by rwa mul_zero at h lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 := have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb, by rwa zero_mul at h lemma mul_self_le_mul_self (h1 : 0 ≤ a) (h2 : a ≤ b) : a * a ≤ b * b := mul_le_mul h2 h2 h1 (le_trans h1 h2) lemma mul_self_lt_mul_self (h1 : 0 ≤ a) (h2 : a < b) : a * a < b * b := mul_lt_mul' (le_of_lt h2) h2 h1 (lt_of_le_of_lt h1 h2) end ordered_semiring /-- A `linear_ordered_semiring α` is a semiring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_semiring (α : Type u) extends ordered_semiring α, linear_order α := (zero_lt_one : zero < one) section linear_ordered_semiring variables [linear_ordered_semiring α] {a b c d : α} lemma zero_lt_one : 0 < (1:α) := linear_ordered_semiring.zero_lt_one lemma zero_le_one : 0 ≤ (1:α) := le_of_lt zero_lt_one lemma two_pos : 0 < (2:α) := add_pos zero_lt_one zero_lt_one @[field_simps] lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt two_pos) lemma one_lt_two : 1 < (2:α) := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma one_le_two : 1 ≤ (2:α) := le_of_lt one_lt_two lemma four_pos : 0 < (4:α) := add_pos two_pos two_pos lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 ≤ c) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left h1 hc, not_lt_of_ge h2 h) lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 ≤ c) : a < b := lt_of_not_ge (assume h1 : b ≤ a, have h2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right h1 hc, not_lt_of_ge h2 h) lemma le_of_mul_le_mul_left (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc, not_le_of_gt h2 h) lemma le_of_mul_le_mul_right (h : a * c ≤ b * c) (hc : 0 < c) : a ≤ b := le_of_not_gt (assume h1 : b < a, have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc, not_le_of_gt h2 h) lemma pos_of_mul_pos_left (h : 0 < a * b) (h1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume h2 : b ≤ 0, have h3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos h1 h2, not_lt_of_ge h3 h) lemma pos_of_mul_pos_right (h : 0 < a * b) (h1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume h2 : a ≤ 0, have h3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg h2 h1, not_lt_of_ge h3 h) lemma nonneg_of_mul_nonneg_left (h : 0 ≤ a * b) (h1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume h2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg h1 h2) h) lemma nonneg_of_mul_nonneg_right (h : 0 ≤ a * b) (h1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume h2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos h2 h1) h) lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume h2 : b ≥ 0, not_lt_of_ge (mul_nonneg h1 h2) h) lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume h2 : a ≥ 0, not_lt_of_ge (mul_nonneg h2 h1) h) lemma nonpos_of_mul_nonpos_left (h : a * b ≤ 0) (h1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume h2 : b > 0, not_le_of_gt (mul_pos h1 h2) h) lemma nonpos_of_mul_nonpos_right (h : a * b ≤ 0) (h1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume h2 : a > 0, not_le_of_gt (mul_pos h2 h1) h) /-- `0 < 2`: an alternative version of `two_pos` that only assumes `linear_ordered_semiring`. -/ lemma zero_lt_two : (0:α) < 2 := by { rw [← zero_add (0:α), bit0], exact add_lt_add zero_lt_one zero_lt_one } @[simp] lemma mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_left h' h, λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h)⟩ @[simp] lemma mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := ⟨λ h', le_of_mul_le_mul_right h' h, λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h)⟩ @[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_left h' (le_of_lt h), λ h', mul_lt_mul_of_pos_left h' h⟩ @[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le $ λ h', mul_le_mul_of_nonneg_right h' (le_of_lt h), λ h', mul_lt_mul_of_pos_right h' h⟩ @[simp] lemma zero_le_mul_left (h : 0 < c) : 0 ≤ c * b ↔ 0 ≤ b := by { convert mul_le_mul_left h, simp } @[simp] lemma zero_le_mul_right (h : 0 < c) : 0 ≤ b * c ↔ 0 ≤ b := by { convert mul_le_mul_right h, simp } @[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b ↔ 0 < b := by { convert mul_lt_mul_left h, simp } @[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c ↔ 0 < b := by { convert mul_lt_mul_right h, simp } @[simp] lemma bit0_le_bit0 : bit0 a ≤ bit0 b ↔ a ≤ b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_le_mul_left zero_lt_two] @[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b ↔ a < b := by rw [bit0, bit0, ← two_mul, ← two_mul, mul_lt_mul_left zero_lt_two] @[simp] lemma bit1_le_bit1 : bit1 a ≤ bit1 b ↔ a ≤ b := (add_le_add_iff_right 1).trans bit0_le_bit0 @[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b ↔ a < b := (add_lt_add_iff_right 1).trans bit0_lt_bit0 @[simp] lemma one_le_bit1 : (1 : α) ≤ bit1 a ↔ 0 ≤ a := by rw [bit1, le_add_iff_nonneg_left, bit0, ← two_mul, zero_le_mul_left zero_lt_two] @[simp] lemma one_lt_bit1 : (1 : α) < bit1 a ↔ 0 < a := by rw [bit1, lt_add_iff_pos_left, bit0, ← two_mul, zero_lt_mul_left zero_lt_two] @[simp] lemma zero_le_bit0 : (0 : α) ≤ bit0 a ↔ 0 ≤ a := by rw [bit0, ← two_mul, zero_le_mul_left zero_lt_two] @[simp] lemma zero_lt_bit0 : (0 : α) < bit0 a ↔ 0 < a := by rw [bit0, ← two_mul, zero_lt_mul_left zero_lt_two] lemma mul_lt_mul'' (h1 : a < c) (h2 : b < d) (h3 : 0 ≤ a) (h4 : 0 ≤ b) : a * b < c * d := (lt_or_eq_of_le h4).elim (λ b0, mul_lt_mul h1 (le_of_lt h2) b0 (le_trans h3 (le_of_lt h1))) (λ b0, by rw [← b0, mul_zero]; exact mul_pos (lt_of_le_of_lt h3 h1) (lt_of_le_of_lt h4 h2)) lemma le_mul_iff_one_le_left (hb : 0 < b) : b ≤ a * b ↔ 1 ≤ a := suffices 1 * b ≤ a * b ↔ 1 ≤ a, by rwa one_mul at this, mul_le_mul_right hb lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b ↔ 1 < a := suffices 1 * b < a * b ↔ 1 < a, by rwa one_mul at this, mul_lt_mul_right hb lemma le_mul_iff_one_le_right (hb : 0 < b) : b ≤ b * a ↔ 1 ≤ a := suffices b * 1 ≤ b * a ↔ 1 ≤ a, by rwa mul_one at this, mul_le_mul_left hb lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a ↔ 1 < a := suffices b * 1 < b * a ↔ 1 < a, by rwa mul_one at this, mul_lt_mul_left hb lemma lt_mul_of_one_lt_right' (hb : 0 < b) : 1 < a → b < b * a := (lt_mul_iff_one_lt_right hb).2 lemma le_mul_of_one_le_right' (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_one_le_left' (hb : 0 ≤ b) (h : 1 ≤ a) : b ≤ a * b := suffices 1 * b ≤ a * b, by rwa one_mul at this, mul_le_mul_of_nonneg_right h hb theorem mul_nonneg_iff_right_nonneg_of_pos (h : 0 < a) : 0 ≤ b * a ↔ 0 ≤ b := ⟨assume : 0 ≤ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 ≤ b, mul_nonneg this $ le_of_lt h⟩ lemma bit1_pos (h : 0 ≤ a) : 0 < bit1 a := lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one lemma bit1_pos' (h : 0 < a) : 0 < bit1 a := bit1_pos (le_of_lt h) lemma lt_add_one (a : α) : a < a + 1 := lt_add_of_le_of_pos (le_refl _) zero_lt_one lemma lt_one_add (a : α) : a < 1 + a := by { rw [add_comm], apply lt_add_one } lemma one_lt_mul (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := (one_mul (1 : α)) ▸ mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha) lemma mul_le_one (ha : a ≤ 1) (hb' : 0 ≤ b) (hb : b ≤ 1) : a * b ≤ 1 := begin rw ← one_mul (1 : α), apply mul_le_mul; {assumption <|> apply zero_le_one} end lemma one_lt_mul_of_le_of_lt (ha : 1 ≤ a) (hb : 1 < b) : 1 < a * b := calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul' ha hb zero_le_one (lt_of_lt_of_le zero_lt_one ha) lemma one_lt_mul_of_lt_of_le (ha : 1 < a) (hb : 1 ≤ b) : 1 < a * b := calc 1 = 1 * 1 : by rw one_mul ... < a * b : mul_lt_mul ha hb zero_lt_one (le_trans zero_le_one (le_of_lt ha)) lemma mul_le_of_le_one_right (ha : 0 ≤ a) (hb1 : b ≤ 1) : a * b ≤ a := calc a * b ≤ a * 1 : mul_le_mul_of_nonneg_left hb1 ha ... = a : mul_one a lemma mul_le_of_le_one_left (hb : 0 ≤ b) (ha1 : a ≤ 1) : a * b ≤ b := calc a * b ≤ 1 * b : mul_le_mul ha1 (le_refl b) hb zero_le_one ... = b : one_mul b lemma mul_lt_one_of_nonneg_of_lt_one_left (ha0 : 0 ≤ a) (ha : a < 1) (hb : b ≤ 1) : a * b < 1 := calc a * b ≤ a : mul_le_of_le_one_right ha0 hb ... < 1 : ha lemma mul_lt_one_of_nonneg_of_lt_one_right (ha : a ≤ 1) (hb0 : 0 ≤ b) (hb : b < 1) : a * b < 1 := calc a * b ≤ b : mul_le_of_le_one_left hb0 ha ... < 1 : hb lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 (not_lt_of_ge h)), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 (not_lt_of_ge h)) ⟩ lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 (not_le_of_gt h)), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 (not_le_of_gt h)) ⟩ lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a ≤ b ↔ a ≤ 1 := ⟨ λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 (not_lt_of_ge h)), λ h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 (not_lt_of_ge h)) ⟩ lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b ↔ a < 1 := ⟨ λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 (not_le_of_gt h)), λ h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 (not_le_of_gt h)) ⟩ lemma nonpos_of_mul_nonneg_left (h : 0 ≤ a * b) (hb : b < 0) : a ≤ 0 := le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_neg_of_pos_of_neg ha hb))) lemma nonpos_of_mul_nonneg_right (h : 0 ≤ a * b) (ha : a < 0) : b ≤ 0 := le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_neg_of_neg_of_pos ha hb))) lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b ≤ 0) : a < 0 := lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonpos_of_nonneg_of_nonpos ha hb))) lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a ≤ 0) : b < 0 := lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonpos_of_nonpos_of_nonneg ha hb))) instance linear_ordered_semiring.to_no_top_order {α : Type*} [linear_ordered_semiring α] : no_top_order α := ⟨assume a, ⟨a + 1, lt_add_of_pos_right _ zero_lt_one⟩⟩ end linear_ordered_semiring section mono variables {β : Type*} [linear_ordered_semiring α] [preorder β] {f g : β → α} {a : α} lemma monotone_mul_left_of_nonneg (ha : 0 ≤ a) : monotone (λ x, a*x) := assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha lemma monotone_mul_right_of_nonneg (ha : 0 ≤ a) : monotone (λ x, x*a) := assume b c b_le_c, mul_le_mul_of_nonneg_right b_le_c ha lemma monotone.mul_const (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, (f x) * a) := (monotone_mul_right_of_nonneg ha).comp hf lemma monotone.const_mul (hf : monotone f) (ha : 0 ≤ a) : monotone (λ x, a * (f x)) := (monotone_mul_left_of_nonneg ha).comp hf lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : monotone (λ x, f x * g x) := λ x y h, mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y) lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (λ x, a * x) := assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (λ x, x * a) := assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, (f x) * a) := (strict_mono_mul_right_of_pos ha).comp hf lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) : strict_mono (λ x, a * (f x)) := (strict_mono_mul_left_of_pos ha).comp hf lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 < g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul (hf h) (hg $ le_of_lt h) (hg0 x) (hf0 y) lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : ∀ x, 0 < f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul' (hf $ le_of_lt h) (hg h) (hg0 x) (hf0 y) lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) : strict_mono (λ x, f x * g x) := λ x y h, mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x) end mono /-- A `decidable_linear_ordered_semiring α` is a semiring `α` with a decidable linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class decidable_linear_ordered_semiring (α : Type u) extends linear_ordered_semiring α, decidable_linear_order α section decidable_linear_ordered_semiring variables [decidable_linear_ordered_semiring α] {a b c : α} @[simp] lemma decidable.mul_le_mul_left (h : 0 < c) : c * a ≤ c * b ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h @[simp] lemma decidable.mul_le_mul_right (h : 0 < c) : a * c ≤ b * c ↔ a ≤ b := decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h end decidable_linear_ordered_semiring /-- An `ordered_ring α` is a ring `α` with a partial order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class ordered_ring (α : Type u) extends ring α, ordered_add_comm_group α := (mul_pos : ∀ a b : α, 0 < a → 0 < b → 0 < a * b) (zero_ne_one : (0 : α) ≠ 1) section ordered_ring variables [ordered_ring α] {a b c : α} instance ordered_ring.to_nonzero : nonzero α := ⟨ordered_ring.zero_ne_one⟩ lemma ordered_ring.mul_nonneg (a b : α) (h₁ : 0 ≤ a) (h₂ : 0 ≤ b) : 0 ≤ a * b := begin cases classical.em (a ≤ 0), { simp [le_antisymm h h₁] }, cases classical.em (b ≤ 0), { simp [le_antisymm h_1 h₂] }, exact (le_not_le_of_lt (ordered_ring.mul_pos a b (lt_of_le_not_le h₁ h) (lt_of_le_not_le h₂ h_1))).left, end lemma ordered_ring.mul_le_mul_of_nonneg_left (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c * a ≤ c * b := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ c * (b - a), from ordered_ring.mul_nonneg c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_le_mul_of_nonneg_right (h₁ : a ≤ b) (h₂ : 0 ≤ c) : a * c ≤ b * c := have 0 ≤ b - a, from sub_nonneg_of_le h₁, have 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply le_of_sub_nonneg this end lemma ordered_ring.mul_lt_mul_of_pos_left (h₁ : a < b) (h₂ : 0 < c) : c * a < c * b := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) h₂ this, begin rw mul_sub_left_distrib at this, apply lt_of_sub_pos this end lemma ordered_ring.mul_lt_mul_of_pos_right (h₁ : a < b) (h₂ : 0 < c) : a * c < b * c := have 0 < b - a, from sub_pos_of_lt h₁, have 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c this h₂, begin rw mul_sub_right_distrib at this, apply lt_of_sub_pos this end instance ordered_ring.to_ordered_semiring : ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right α _, ..‹ordered_ring α› } lemma mul_le_mul_of_nonpos_left {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : c * a ≤ c * b := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left h this, have -(c * b) ≤ -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, le_of_neg_le_neg this lemma mul_le_mul_of_nonpos_right {a b c : α} (h : b ≤ a) (hc : c ≤ 0) : a * c ≤ b * c := have -c ≥ 0, from neg_nonneg_of_nonpos hc, have b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right h this, have -(b * c) ≤ -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, le_of_neg_le_neg this lemma mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b := have 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right ha hb, by rwa zero_mul at this lemma mul_lt_mul_of_neg_left {a b c : α} (h : b < a) (hc : c < 0) : c * a < c * b := have -c > 0, from neg_pos_of_neg hc, have -c * b < -c * a, from mul_lt_mul_of_pos_left h this, have -(c * b) < -(c * a), by rwa [← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul] at this, lt_of_neg_lt_neg this lemma mul_lt_mul_of_neg_right {a b c : α} (h : b < a) (hc : c < 0) : a * c < b * c := have -c > 0, from neg_pos_of_neg hc, have b * -c < a * -c, from mul_lt_mul_of_pos_right h this, have -(b * c) < -(a * c), by rwa [← neg_mul_eq_mul_neg, ← neg_mul_eq_mul_neg] at this, lt_of_neg_lt_neg this lemma mul_pos_of_neg_of_neg {a b : α} (ha : a < 0) (hb : b < 0) : 0 < a * b := have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb, by rwa zero_mul at this end ordered_ring /-- A `linear_ordered_ring α` is a ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_ring (α : Type u) extends ordered_ring α, linear_order α := (zero_lt_one : zero < one) section linear_ordered_ring variables [linear_ordered_ring α] {a b c : α} instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add_left_cancel α _, add_right_cancel := @add_right_cancel α _, le_of_add_le_add_left := @le_of_add_le_add_left α _, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left α _, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right α _, le_total := linear_ordered_ring.le_total, ..‹linear_ordered_ring α› } lemma mul_self_nonneg (a : α) : 0 ≤ a * a := or.elim (le_total 0 a) (assume h : a ≥ 0, mul_nonneg h h) (assume h : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos h h) lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) : (0 < a ∧ 0 < b) ∨ (a < 0 ∧ b < 0) := match lt_trichotomy 0 a with | or.inl hlt₁ := match lt_trichotomy 0 b with | or.inl hlt₂ := or.inl ⟨hlt₁, hlt₂⟩ | or.inr (or.inl heq₂) := begin rw [← heq₂, mul_zero] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₂) := absurd hab (lt_asymm (mul_neg_of_pos_of_neg hlt₁ hgt₂)) end | or.inr (or.inl heq₁) := begin rw [← heq₁, zero_mul] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₁) := match lt_trichotomy 0 b with | or.inl hlt₂ := absurd hab (lt_asymm (mul_neg_of_neg_of_pos hgt₁ hlt₂)) | or.inr (or.inl heq₂) := begin rw [← heq₂, mul_zero] at hab, exact absurd hab (lt_irrefl _) end | or.inr (or.inr hgt₂) := or.inr ⟨hgt₁, hgt₂⟩ end end lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c ≤ 0) : b < a := have nhc : 0 ≤ -c, from neg_nonneg_of_nonpos hc, have h2 : -(c * b) < -(c * a), from neg_lt_neg h, have h3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul ... < -(c * a) : h2 ... = (-c) * a : by rewrite neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left h3 nhc lemma neg_one_lt_zero : -1 < (0:α) := begin have this := neg_lt_neg (@zero_lt_one α _), rwa neg_zero at this end lemma le_of_mul_le_of_one_le {a b c : α} (h : a * c ≤ b) (hb : 0 ≤ b) (hc : 1 ≤ c) : a ≤ b := have h' : a * c ≤ b * c, from calc a * c ≤ b : h ... = b * 1 : by rewrite mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left hc hb, le_of_mul_le_mul_right h' (lt_of_lt_of_le zero_lt_one hc) lemma nonneg_le_nonneg_of_squares_le {a b : α} (hb : 0 ≤ b) (h : a * a ≤ b * b) : a ≤ b := le_of_not_gt (λhab, not_le_of_gt (mul_self_lt_mul_self hb hab) h) lemma mul_self_le_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a ≤ b ↔ a * a ≤ b * b := ⟨mul_self_le_mul_self h1, nonneg_le_nonneg_of_squares_le h2⟩ lemma mul_self_lt_mul_self_iff {a b : α} (h1 : 0 ≤ a) (h2 : 0 ≤ b) : a < b ↔ a * a < b * b := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff $ mul_self_le_mul_self_iff h2 h1) $ iff.symm (lt_iff_not_ge _ _) lemma linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero {a b : α} (h : a * b = 0) : a = 0 ∨ b = 0 := match lt_trichotomy 0 a with | or.inl hlt₁ := match lt_trichotomy 0 b with | or.inl hlt₂ := have 0 < a * b, from mul_pos hlt₁ hlt₂, begin rw h at this, exact absurd this (lt_irrefl _) end | or.inr (or.inl heq₂) := or.inr heq₂.symm | or.inr (or.inr hgt₂) := have 0 > a * b, from mul_neg_of_pos_of_neg hlt₁ hgt₂, begin rw h at this, exact absurd this (lt_irrefl _) end end | or.inr (or.inl heq₁) := or.inl heq₁.symm | or.inr (or.inr hgt₁) := match lt_trichotomy 0 b with | or.inl hlt₂ := have 0 > a * b, from mul_neg_of_neg_of_pos hgt₁ hlt₂, begin rw h at this, exact absurd this (lt_irrefl _) end | or.inr (or.inl heq₂) := or.inr heq₂.symm | or.inr (or.inr hgt₂) := have 0 < a * b, from mul_pos_of_neg_of_neg hgt₁ hgt₂, begin rw h at this, exact absurd this (lt_irrefl _) end end end instance linear_ordered_ring.to_no_bot_order : no_bot_order α := ⟨assume a, ⟨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_one⟩⟩ @[priority 100] -- see Note [lower instance priority] instance linear_ordered_ring.to_domain : domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α _, ..‹linear_ordered_ring α› } @[simp] lemma mul_le_mul_left_of_neg {a b c : α} (h : c < 0) : c * a ≤ c * b ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_left h' h, λ h', mul_le_mul_of_nonpos_left h' (le_of_lt h)⟩ @[simp] lemma mul_le_mul_right_of_neg {a b c : α} (h : c < 0) : a * c ≤ b * c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ λ h', mul_lt_mul_of_neg_right h' h, λ h', mul_le_mul_of_nonpos_right h' (le_of_lt h)⟩ @[simp] lemma mul_lt_mul_left_of_neg {a b c : α} (h : c < 0) : c * a < c * b ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h) @[simp] lemma mul_lt_mul_right_of_neg {a b c : α} (h : c < 0) : a * c < b * c ↔ b < a := lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h) lemma sub_one_lt (a : α) : a - 1 < a := sub_lt_iff_lt_add.2 (lt_add_one a) lemma mul_self_pos {a : α} (ha : a ≠ 0) : 0 < a * a := by rcases lt_trichotomy a 0 with h|h|h; [exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h] lemma mul_self_le_mul_self_of_le_of_neg_le {x y : α} (h₁ : x ≤ y) (h₂ : -x ≤ y) : x * x ≤ y * y := begin cases le_total 0 x, { exact mul_self_le_mul_self h h₁ }, { rw ← neg_mul_neg, exact mul_self_le_mul_self (neg_nonneg_of_nonpos h) h₂ } end lemma nonneg_of_mul_nonpos_left {a b : α} (h : a * b ≤ 0) (hb : b < 0) : 0 ≤ a := le_of_not_gt (λ ha, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb))) lemma nonneg_of_mul_nonpos_right {a b : α} (h : a * b ≤ 0) (ha : a < 0) : 0 ≤ b := le_of_not_gt (λ hb, absurd h (not_le_of_gt (mul_pos_of_neg_of_neg ha hb))) lemma pos_of_mul_neg_left {a b : α} (h : a * b < 0) (hb : b ≤ 0) : 0 < a := lt_of_not_ge (λ ha, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb))) lemma pos_of_mul_neg_right {a b : α} (h : a * b < 0) (ha : a ≤ 0) : 0 < b := lt_of_not_ge (λ hb, absurd h (not_lt_of_ge (mul_nonneg_of_nonpos_of_nonpos ha hb))) /- The sum of two squares is zero iff both elements are zero. -/ lemma mul_self_add_mul_self_eq_zero {x y : α} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 := begin split; intro h, swap, { rcases h with ⟨rfl, rfl⟩, simp }, have : y * y ≤ 0, { rw [← h], apply le_add_of_nonneg_left (mul_self_nonneg x) }, have : y * y = 0 := le_antisymm this (mul_self_nonneg y), have hx : x = 0, { rwa [this, add_zero, mul_self_eq_zero] at h }, rw mul_self_eq_zero at this, split; assumption end end linear_ordered_ring /-- A `linear_ordered_comm_ring α` is a commutative ring `α` with a linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class linear_ordered_comm_ring (α : Type u) extends linear_ordered_ring α, comm_monoid α instance linear_ordered_comm_ring.to_integral_domain [s: linear_ordered_comm_ring α] : integral_domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_ring.eq_zero_or_eq_zero_of_mul_eq_zero α _, ..s } /-- A `decidable_linear_ordered_comm_ring α` is a commutative ring `α` with a decidable linear order such that multiplication with a positive number and addition are monotone. -/ @[protect_proj] class decidable_linear_ordered_comm_ring (α : Type u) extends linear_ordered_comm_ring α, decidable_linear_ordered_add_comm_group α instance decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [d : decidable_linear_ordered_comm_ring α] : decidable_linear_ordered_semiring α := let s : linear_ordered_semiring α := @linear_ordered_ring.to_linear_ordered_semiring α _ in { zero_mul := @linear_ordered_semiring.zero_mul α s, mul_zero := @linear_ordered_semiring.mul_zero α s, add_left_cancel := @linear_ordered_semiring.add_left_cancel α s, add_right_cancel := @linear_ordered_semiring.add_right_cancel α s, le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left α s, mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left α s, mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right α s, ..d } section decidable_linear_ordered_comm_ring variables [decidable_linear_ordered_comm_ring α] {a b c : α} lemma abs_mul (a b : α) : abs (a * b) = abs a * abs b := or.elim (le_total 0 a) (assume h1 : 0 ≤ a, or.elim (le_total 0 b) (assume h2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg h1 h2) ... = abs a * b : by rw (abs_of_nonneg h1) ... = abs a * abs b : by rw (abs_of_nonneg h2)) (assume h2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos h1 h2) ... = a * -b : by rw neg_mul_eq_mul_neg ... = abs a * -b : by rw (abs_of_nonneg h1) ... = abs a * abs b : by rw (abs_of_nonpos h2))) (assume h1 : a ≤ 0, or.elim (le_total 0 b) (assume h2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg h1 h2) ... = -a * b : by rw neg_mul_eq_neg_mul ... = abs a * b : by rw (abs_of_nonpos h1) ... = abs a * abs b : by rw (abs_of_nonneg h2)) (assume h2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos h1 h2) ... = -a * -b : by rw neg_mul_neg ... = abs a * -b : by rw (abs_of_nonpos h1) ... = abs a * abs b : by rw (abs_of_nonpos h2))) lemma abs_mul_abs_self (a : α) : abs a * abs a = a * a := abs_by_cases (λ x, x * x = a * a) rfl (neg_mul_neg a a) lemma abs_mul_self (a : α) : abs (a * a) = a * a := by rw [abs_mul, abs_mul_abs_self] lemma sub_le_of_abs_sub_le_left (h : abs (a - b) ≤ c) : b - c ≤ a := if hz : 0 ≤ a - b then (calc a ≥ b : le_of_sub_nonneg hz ... ≥ b - c : sub_le_self _ (le_trans (abs_nonneg _) h)) else have habs : b - a ≤ c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b ≤ c + a, from le_add_of_sub_right_le habs, sub_left_le_of_le_add habs' lemma sub_le_of_abs_sub_le_right (h : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (abs_sub a b ▸ h) lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a := if hz : 0 ≤ a - b then (calc a ≥ b : le_of_sub_nonneg hz ... > b - c : sub_lt_self _ (lt_of_le_of_lt (abs_nonneg _) h)) else have habs : b - a < c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h, have habs' : b < c + a, from lt_add_of_sub_right_lt habs, sub_left_lt_of_lt_add habs' lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (abs_sub a b ▸ h) lemma abs_sub_square (a b : α) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := begin rw abs_mul_abs_self, simp [left_distrib, right_distrib, add_assoc, add_comm, add_left_comm, mul_comm, sub_eq_add_neg] end lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 := have a * a ≤ (0 : α), from calc a * a ≤ a * a + b * b : le_add_of_nonneg_right (mul_self_nonneg b) ... = 0 : h, eq_zero_of_mul_self_eq_zero (le_antisymm this (mul_self_nonneg a)) lemma abs_abs_sub_abs_le_abs_sub (a b : α) : abs (abs a - abs b) ≤ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, apply abs_nonneg, iterate {rw abs_sub_square}, iterate {rw abs_mul_abs_self}, apply sub_le_sub_left, iterate {rw mul_assoc}, apply mul_le_mul_of_nonneg_left, rw [← abs_mul], apply le_abs_self, apply le_of_lt, apply add_pos, apply zero_lt_one, apply zero_lt_one end -- The proof doesn't need commutativity but we have no `decidable_linear_ordered_ring` @[simp] lemma abs_two : abs (2:α) = 2 := abs_of_pos $ by refine zero_lt_two end decidable_linear_ordered_comm_ring /-- Extend `nonneg_add_comm_group` to support ordered rings specified by their nonnegative elements -/ class nonneg_ring (α : Type*) extends ring α, nonneg_add_comm_group α := (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (mul_pos : ∀ {a b}, pos a → pos b → pos (a * b)) (zero_ne_one : (0 : α) ≠ 1) /-- Extend `nonneg_add_comm_group` to support linearly ordered rings specified by their nonnegative elements -/ class linear_nonneg_ring (α : Type*) extends domain α, nonneg_add_comm_group α := (mul_nonneg : ∀ {a b}, nonneg a → nonneg b → nonneg (a * b)) (nonneg_total : ∀ a, nonneg a ∨ nonneg (-a)) namespace nonneg_ring open nonneg_add_comm_group variable [nonneg_ring α] instance to_ordered_ring : ordered_ring α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, add_le_add_left := @add_le_add_left _ _, mul_pos := λ a b, by simp [pos_def.symm]; exact mul_pos, ..‹nonneg_ring α› } /-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a total order is a `domain`, hence a `linear_nonneg_ring`. -/ def to_linear_nonneg_ring (nonneg_total : ∀ a : α, nonneg a ∨ nonneg (-a)) : linear_nonneg_ring α := { nonneg_total := nonneg_total, eq_zero_or_eq_zero_of_mul_eq_zero := suffices ∀ {a} b : α, nonneg a → a * b = 0 → a = 0 ∨ b = 0, from λ a b, (nonneg_total a).elim (this b) (λ na, by simpa using this b na), suffices ∀ {a b : α}, nonneg a → nonneg b → a * b = 0 → a = 0 ∨ b = 0, from λ a b na, (nonneg_total b).elim (this na) (λ nb, by simpa using this na nb), λ a b na nb z, classical.by_cases (λ nna : nonneg (-a), or.inl (nonneg_antisymm na nna)) (λ pa, classical.by_cases (λ nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb)) (λ pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos ((pos_iff _).2 ⟨na, pa⟩) ((pos_iff _).2 ⟨nb, pb⟩))), ..‹nonneg_ring α› } end nonneg_ring namespace linear_nonneg_ring open nonneg_add_comm_group variable [linear_nonneg_ring α] @[priority 100] -- see Note [lower instance priority] instance to_nonneg_ring : nonneg_ring α := { mul_pos := λ a b pa pb, let ⟨a1, a2⟩ := (pos_iff a).1 pa, ⟨b1, b2⟩ := (pos_iff b).1 pb in have ab : nonneg (a * b), from mul_nonneg a1 b1, (pos_iff _).2 ⟨ab, λ hn, have a * b = 0, from nonneg_antisymm ab hn, (eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim (ne_of_gt (pos_def.1 pa)) (ne_of_gt (pos_def.1 pb))⟩, ..‹linear_nonneg_ring α› } @[priority 100] -- see Note [lower instance priority] instance to_linear_order : linear_order α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := nonneg_total_iff.1 nonneg_total, ..‹linear_nonneg_ring α› } @[priority 100] -- see Note [lower instance priority] instance to_linear_ordered_ring : linear_ordered_ring α := { le := (≤), lt := (<), lt_iff_le_not_le := @lt_iff_le_not_le _ _, le_refl := @le_refl _ _, le_trans := @le_trans _ _, le_antisymm := @le_antisymm _ _, le_total := @le_total _ _, add_le_add_left := @add_le_add_left _ _, mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _, zero_lt_one := lt_of_not_ge $ λ (h : nonneg (0 - 1)), begin rw [zero_sub] at h, have := mul_nonneg h h, simp at this, exact zero_ne_one (nonneg_antisymm this h).symm end, ..‹linear_nonneg_ring α› } /-- Convert a `linear_nonneg_ring` with a commutative multiplication and decidable non-negativity into a `decidable_linear_ordered_comm_ring` -/ def to_decidable_linear_ordered_comm_ring [decidable_pred (@nonneg α _)] [comm : @is_commutative α (*)] : decidable_linear_ordered_comm_ring α := { decidable_le := by apply_instance, decidable_lt := by apply_instance, mul_comm := is_commutative.comm, ..@linear_nonneg_ring.to_linear_ordered_ring _ _ } end linear_nonneg_ring /-- A canonically ordered commutative semiring is an ordered, commutative semiring in which `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other ordered groups. -/ class canonically_ordered_comm_semiring (α : Type*) extends canonically_ordered_add_monoid α, comm_semiring α := (mul_eq_zero_iff (a b : α) : a * b = 0 ↔ a = 0 ∨ b = 0) (zero_ne_one : (0 : α) ≠ 1) namespace canonically_ordered_semiring variables [canonically_ordered_comm_semiring α] {a b : α} open canonically_ordered_add_monoid (le_iff_exists_add) instance canonically_ordered_comm_semiring.to_nonzero : nonzero α := ⟨canonically_ordered_comm_semiring.zero_ne_one⟩ lemma mul_le_mul {a b c d : α} (hab : a ≤ b) (hcd : c ≤ d) : a * c ≤ b * d := begin rcases (le_iff_exists_add _ _).1 hab with ⟨b, rfl⟩, rcases (le_iff_exists_add _ _).1 hcd with ⟨d, rfl⟩, suffices : a * c ≤ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul, _root_.add_assoc], exact (le_iff_exists_add _ _).2 ⟨_, rfl⟩ end /-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/ lemma zero_lt_one : (0:α) < 1 := lt_of_le_of_ne (zero_le 1) zero_ne_one lemma mul_pos : 0 < a * b ↔ (0 < a) ∧ (0 < b) := by simp only [zero_lt_iff_ne_zero, ne.def, canonically_ordered_comm_semiring.mul_eq_zero_iff, not_or_distrib] end canonically_ordered_semiring namespace with_top variables [canonically_ordered_comm_semiring α] instance : has_one (with_top α) := ⟨↑(1:α)⟩ @[simp] theorem top_ne_zero : ⊤ ≠ (0 : with_top α) . @[simp] theorem zero_ne_top : (0 : with_top α) ≠ ⊤ . @[simp] theorem coe_eq_zero {a : α} : (a : with_top α) = 0 ↔ a = 0 := iff.intro (assume h, match a, h with _, rfl := rfl end) (assume h, h.symm ▸ rfl) @[simp] theorem zero_eq_coe {a : α} : 0 = (a : with_top α) ↔ a = 0 := by rw [eq_comm, coe_eq_zero] @[simp] theorem coe_zero : ↑(0 : α) = (0 : with_top α) := rfl variable [decidable_eq α] instance : mul_zero_class (with_top α) := { zero := 0, mul := λm n, if m = 0 ∨ n = 0 then 0 else m.bind (λa, n.bind $ λb, ↑(a * b)), zero_mul := assume a, if_pos $ or.inl rfl, mul_zero := assume a, if_pos $ or.inr rfl } lemma mul_def {a b : with_top α} : a * b = if a = 0 ∨ b = 0 then 0 else a.bind (λa, b.bind $ λb, ↑(a * b)) := rfl @[simp] lemma mul_top {a : with_top α} (h : a ≠ 0) : a * ⊤ = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul {a : with_top α} (h : a ≠ 0) : ⊤ * a = ⊤ := by cases a; simp [mul_def, h]; refl @[simp] lemma top_mul_top : (⊤ * ⊤ : with_top α) = ⊤ := top_mul top_ne_zero lemma coe_mul {a b : α} : (↑(a * b) : with_top α) = a * b := decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha, decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb, by simp [*, mul_def]; refl lemma mul_coe {b : α} (hb : b ≠ 0) : ∀{a : with_top α}, a * b = a.bind (λa:α, ↑(a * b)) | none := show (if (⊤:with_top α) = 0 ∨ (b:with_top α) = 0 then 0 else ⊤ : with_top α) = ⊤, by simp [hb] | (some a) := show ↑a * ↑b = ↑(a * b), from coe_mul.symm private lemma comm (a b : with_top α) : a * b = b * a := begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, simp [ha, hb, mul_def, option.bind_comm a b, mul_comm] end @[simp] lemma mul_eq_top_iff {a b : with_top α} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := begin have H : ∀x:α, (¬x = 0) ↔ (⊤ : with_top α) * ↑x = ⊤ := λx, ⟨λhx, by simp [top_mul, hx], λhx f, by simpa [f] using hx⟩, cases a; cases b; simp [none_eq_top, top_mul, coe_ne_top, some_eq_coe, coe_mul.symm], { rw [H b] }, { rw [H a, comm] } end private lemma distrib' (a b c : with_top α) : (a + b) * c = a * c + b * c := begin cases c, { show (a + b) * ⊤ = a * ⊤ + b * ⊤, by_cases ha : a = 0; simp [ha] }, { show (a + b) * c = a * c + b * c, by_cases hc : c = 0, { simp [hc] }, simp [mul_coe hc], cases a; cases b, repeat { refl <|> exact congr_arg some (add_mul _ _ _) } } end private lemma mul_eq_zero (a b : with_top α) : a * b = 0 ↔ a = 0 ∨ b = 0 := by cases a; cases b; dsimp [mul_def]; split_ifs; simp [*, none_eq_top, some_eq_coe, canonically_ordered_comm_semiring.mul_eq_zero_iff] at * private lemma assoc (a b c : with_top α) : (a * b) * c = a * (b * c) := begin cases a, { by_cases hb : b = 0; by_cases hc : c = 0; simp [*, none_eq_top, mul_eq_zero b c] }, cases b, { by_cases ha : a = 0; by_cases hc : c = 0; simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a c] }, cases c, { by_cases ha : a = 0; by_cases hb : b = 0; simp [*, none_eq_top, some_eq_coe, mul_eq_zero ↑a ↑b] }, simp [some_eq_coe, coe_mul.symm, mul_assoc] end private lemma one_mul' : ∀a : with_top α, 1 * a = a | none := show ((1:α) : with_top α) * ⊤ = ⊤, by simp [-with_bot.coe_one] | (some a) := show ((1:α) : with_top α) * a = a, by simp [coe_mul.symm, -with_bot.coe_one] instance : canonically_ordered_comm_semiring (with_top α) := { one := (1 : α), right_distrib := distrib', left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl, mul_assoc := assoc, mul_comm := comm, mul_eq_zero_iff := mul_eq_zero, one_mul := one_mul', mul_one := assume a, by rw [comm, one_mul'], zero_ne_one := assume h : ((0 : α) : with_top α) = 1, zero_ne_one $ option.some.inj h, .. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_add_monoid } end with_top
b78cef760debf7cf569e9af3f0244a5077d7ae6d
7e6221dc7a7676e3cf6c16a885e41c71809ee528
/src/tactic/ring.lean
8990d24e9c94b4713e2209e0462ec38e997e9935
[ "Apache-2.0" ]
permissive
jpburelle/mathlib
e89f5a032d1b8d0f8bfe4aeaaf2520a8f4e1560d
b44fa3ca86bc6ccc6366f8246d0ee10dffaeea4e
refs/heads/master
1,659,493,177,351
1,589,529,475,000
1,589,529,475,000
264,193,699
0
0
Apache-2.0
1,589,547,412,000
1,589,547,412,000
null
UTF-8
Lean
false
false
21,795
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) @[derive [monad, alternative]] meta def ring_m (α : Type) : Type := reader_t cache (state_t (buffer expr) tactic) α meta def get_cache : ring_m cache := reader_t.read meta def get_atom (n : ℕ) : ring_m expr := reader_t.lift $ (λ es : buffer expr, es.read' n) <$> state_t.get meta def get_transparency : ring_m transparency := cache.red <$> get_cache meta def add_atom (e : expr) : ring_m ℕ := do red ← get_transparency, reader_t.lift ⟨λ es, (do n ← es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)), return (n, es)) <|> return (es.size, es.push_back e)⟩ meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift (state_t.lift m) meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, c ← mk_app ``comm_semiring [α] >>= mk_instance, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, prod.fst <$> state_t.run (reader_t.run m ⟨α, u, c, red⟩) mk_buffer meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app meta def ring_m.mk_app (n inst : name) (l : list expr) : ring_m expr := do c ← get_cache, m ← lift $ mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ (@expr.const tt n [c.univ] c.α m).mk_app l meta inductive horner_expr : Type | const (e : expr) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr meta def horner_expr.e : horner_expr → expr | (horner_expr.const e) := e | (horner_expr.xadd e _ _ _ _) := e meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr meta def horner_expr.to_string : horner_expr → string | (const e) := to_string e | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string meta def horner_expr.pp : horner_expr → tactic format | (const e) := pp e | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a) x n b := do c ← get_cache, if a.to_nat = some 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← lift $ mk_app ``has_add.add [n₁.1, n.1] >>= norm_num, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm]; cc meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁) (const e₂) := do (e, p) ← lift $ mk_app ``has_add.add [e₁, e₂] >>= norm_num, return (const e, p) | he₁@(const e₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if e₁.to_nat = some 0 then do p ← lift $ mk_app ``zero_add [e₂], return (he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂) := do c ← get_cache, if e₂.to_nat = some 0 then do p ← lift $ mk_app ``add_zero [e₁], return (he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, ek ← lift $ expr.of_nat (expr.const `nat []) k, (_, h₁) ← lift $ mk_app ``has_add.add [n₁.1, ek] >>= norm_num, α0 ← lift $ expr.of_nat c.α 0, (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, ek ← lift $ expr.of_nat (expr.const `nat []) k, (_, h₁) ← lift $ mk_app ``has_add.add [n₂.1, ek] >>= norm_num, α0 ← lift $ expr.of_nat c.α 0, (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e) := do (e', p) ← lift $ mk_app ``has_neg.neg [e] >>= norm_num, return (const e', p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ring_m.mk_app ``horner_neg ``comm_ring [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] meta def eval_const_mul (k : expr) : horner_expr → ring_m (horner_expr × expr) | (const e) := do (e', p) ← lift $ mk_app ``has_mul.mul [k, e] >>= norm_num, return (const e', p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁) (const e₂) := do (e', p) ← lift $ mk_app ``has_mul.mul [e₁, e₂] >>= norm_num, return (const e', p) | (const e₁) e₂ := match e₁.to_nat with | (some 0) := do c ← get_cache, α0 ← lift $ expr.of_nat c.α 0, p ← lift $ mk_app ``zero_mul [e₂], return (const α0, p) | (some 1) := do p ← lift $ mk_app ``one_mul [e₂], return (e₂, p) | _ := eval_const_mul e₁ e₂ end | e₁ he₂@(const e₂) := do p₁ ← lift $ mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← lift $ expr.of_nat c.α 0, (haa, h₂) ← eval_horner aa x₁ n₂ (const α0), if b₂.e.to_nat = some 0 then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← lift $ expr.of_nat c.α 1, p ← lift $ mk_app ``pow_zero [e], return (const α1, p) | e (_, 1) := do p ← lift $ mk_app ``pow_one [e], return (e, p) | (const e) (e₂, m) := do (e', p) ← lift $ mk_app ``monoid.pow [e, e₂] >>= norm_num.derive', return (const e', p) | he@(xadd e a x n b) m := do c ← get_cache, let N : expr := expr.const `nat [], match b.e.to_nat with | some 0 := do (n', h₁) ← lift $ mk_app ``has_mul.mul [n.1, m.1] >>= norm_num.derive', (a', h₂) ← eval_pow a m, α0 ← lift $ expr.of_nat c.α 0, return (xadd' c a' x (n', n.2 * m.2) (const α0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← lift $ expr.of_nat N (m.2-1), l ← lift $ mk_app ``monoid.pow [e, e₂], (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, hr ← lift $ mk_eq_refl e, p₂ ← ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [l, e, tl, e, t, hl, hr, p₂], p₁ ← lift $ mk_app ``pow_succ' [e, e₂], p ← lift $ mk_eq_trans p₁ p₂, return (t, p) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← lift $ expr.of_nat c.α 0, α1 ← lift $ expr.of_nat c.α 1, n1 ← lift $ expr.of_nat (expr.const `nat []) 1, return (xadd' c (const α1) (e, i) (n1, 1) (const α0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by simp [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := h lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := h meta def eval : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ring_m.mk_app ``norm_num.subst_into_sum ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%P %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← lift $ mk_app ``has_neg.neg [e₂], e ← lift $ mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ring_m.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ring_m.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, lift $ e'.to_rat, return (const e', p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ring_m.mk_app ``division_ring_has_div ``division_ring [], lift $ is_def_eq inst inst')) (do e₂' ← lift $ mk_app ``has_inv.inv [e₂], e ← lift $ mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ring_m.mk_app ``unfold_div ``division_ring [e₁, e₂, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ring_m.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | some k, `(nat.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p₃ ← ring_m.mk_app ``subst_into_pow ``monoid [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], p₄ ← lift $ mk_app ``nat.pow_eq_pow [e₁, e₂] >>= mk_eq_symm, p ← lift $ mk_eq_trans p₄ p₃, return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e).refl_conv | none := eval_atom e end meta def eval' (red : transparency) (e : expr) : tactic (expr × expr) := ring_m.run red e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := rfl @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red | normalize_mode.horner := trans_conv (eval' red) (simplify lemmas []) | normalize_mode.SOP := trans_conv (eval' red) $ trans_conv (simplify lemmas []) $ simp_bottom_up' (λ e, norm_num e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Tactic for solving equations in the language of *commutative* (semi)rings. Attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails it falls back to rewriting all ring expressions into a normal form. When writing a normal form, `ring SOP` will use sum-of-products form instead of horner form. `ring!` will use a more aggressive reducibility setting to identify atoms. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red | _ := failed end <|> do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring failed to simplify", when loc.include_goal $ try tactic.reflexivity add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [`tactic.interactive.ring], tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> replace_lhs (normalize transp SOP) <|> fail "ring failed to simplify" end conv.interactive
d04d2c24edec5d02e869d5125a919c326ca6068d
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast7.lean
dd49488eb3d3ef4640535bcd060bc0844e04f55b
[ "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
136
lean
set_option blast.strategy "preprocess" lemma lemma1 (p : Prop) (a b : nat) : a = b → p → p := by blast reveal lemma1 print lemma1
1921d824605b7c1211d85e1032a53c550b4cd987
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/convex/strict_convex_space.lean
efab1f4c5916dd8b0cb8bc2afa166fda0d11aae1
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
14,990
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Yury Kudryashov -/ import analysis.convex.strict import analysis.convex.topology import analysis.normed_space.ordered import analysis.normed_space.pointwise import analysis.normed_space.affine_isometry /-! # Strictly convex spaces This file defines strictly convex spaces. A normed space is strictly convex if all closed balls are strictly convex. This does **not** mean that the norm is strictly convex (in fact, it never is). ## Main definitions `strict_convex_space`: a typeclass saying that a given normed space over a normed linear ordered field (e.g., `ℝ` or `ℚ`) is strictly convex. The definition requires strict convexity of a closed ball of positive radius with center at the origin; strict convexity of any other closed ball follows from this assumption. ## Main results In a strictly convex space, we prove - `strict_convex_closed_ball`: a closed ball is strictly convex. - `combo_mem_ball_of_ne`, `open_segment_subset_ball_of_ne`, `norm_combo_lt_of_ne`: a nontrivial convex combination of two points in a closed ball belong to the corresponding open ball; - `norm_add_lt_of_not_same_ray`, `same_ray_iff_norm_add`, `dist_add_dist_eq_iff`: the triangle inequality `dist x y + dist y z ≤ dist x z` is a strict inequality unless `y` belongs to the segment `[x -[ℝ] z]`. - `isometry.affine_isometry_of_strict_convex_space`: an isometry of `normed_add_torsor`s for real normed spaces, strictly convex in the case of the codomain, is an affine isometry. We also provide several lemmas that can be used as alternative constructors for `strict_convex ℝ E`: - `strict_convex_space.of_strict_convex_closed_unit_ball`: if `closed_ball (0 : E) 1` is strictly convex, then `E` is a strictly convex space; - `strict_convex_space.of_norm_add`: if `∥x + y∥ = ∥x∥ + ∥y∥` implies `same_ray ℝ x y` for all `x y : E`, then `E` is a strictly convex space. ## Implementation notes While the definition is formulated for any normed linear ordered field, most of the lemmas are formulated only for the case `𝕜 = ℝ`. ## Tags convex, strictly convex -/ open set metric open_locale convex pointwise /-- A *strictly convex space* is a normed space where the closed balls are strictly convex. We only require balls of positive radius with center at the origin to be strictly convex in the definition, then prove that any closed ball is strictly convex in `strict_convex_closed_ball` below. See also `strict_convex_space.of_strict_convex_closed_unit_ball`. -/ class strict_convex_space (𝕜 E : Type*) [normed_linear_ordered_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] : Prop := (strict_convex_closed_ball : ∀ r : ℝ, 0 < r → strict_convex 𝕜 (closed_ball (0 : E) r)) variables (𝕜 : Type*) {E : Type*} [normed_linear_ordered_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] /-- A closed ball in a strictly convex space is strictly convex. -/ lemma strict_convex_closed_ball [strict_convex_space 𝕜 E] (x : E) (r : ℝ) : strict_convex 𝕜 (closed_ball x r) := begin cases le_or_lt r 0 with hr hr, { exact (subsingleton_closed_ball x hr).strict_convex }, rw ← vadd_closed_ball_zero, exact (strict_convex_space.strict_convex_closed_ball r hr).vadd _, end variables [normed_space ℝ E] /-- A real normed vector space is strictly convex provided that the unit ball is strictly convex. -/ lemma strict_convex_space.of_strict_convex_closed_unit_ball [linear_map.compatible_smul E E 𝕜 ℝ] (h : strict_convex 𝕜 (closed_ball (0 : E) 1)) : strict_convex_space 𝕜 E := ⟨λ r hr, by simpa only [smul_closed_unit_ball_of_nonneg hr.le] using h.smul r⟩ /-- If `∥x + y∥ = ∥x∥ + ∥y∥` implies that `x y : E` are in the same ray, then `E` is a strictly convex space. -/ lemma strict_convex_space.of_norm_add (h : ∀ x y : E, ∥x + y∥ = ∥x∥ + ∥y∥ → same_ray ℝ x y) : strict_convex_space ℝ E := begin refine strict_convex_space.of_strict_convex_closed_unit_ball ℝ (λ x hx y hy hne a b ha hb hab, _), have hx' := hx, have hy' := hy, rw [← closure_closed_ball, closure_eq_interior_union_frontier, frontier_closed_ball (0 : E) one_ne_zero] at hx hy, cases hx, { exact (convex_closed_ball _ _).combo_interior_self_mem_interior hx hy' ha hb.le hab }, cases hy, { exact (convex_closed_ball _ _).combo_self_interior_mem_interior hx' hy ha.le hb hab }, rw [interior_closed_ball (0 : E) one_ne_zero, mem_ball_zero_iff], have hx₁ : ∥x∥ = 1, from mem_sphere_zero_iff_norm.1 hx, have hy₁ : ∥y∥ = 1, from mem_sphere_zero_iff_norm.1 hy, have ha' : ∥a∥ = a, from real.norm_of_nonneg ha.le, have hb' : ∥b∥ = b, from real.norm_of_nonneg hb.le, calc ∥a • x + b • y∥ < ∥a • x∥ + ∥b • y∥ : (norm_add_le _ _).lt_of_ne (λ H, hne _) ... = 1 : by simpa only [norm_smul, hx₁, hy₁, mul_one, ha', hb'], simpa only [norm_smul, hx₁, hy₁, ha', hb', mul_one, smul_comm a, smul_right_inj ha.ne', smul_right_inj hb.ne'] using (h _ _ H).norm_smul_eq.symm end lemma strict_convex_space.of_norm_add_lt_aux {a b c d : ℝ} (ha : 0 < a) (hab : a + b = 1) (hc : 0 < c) (hd : 0 < d) (hcd : c + d = 1) (hca : c ≤ a) {x y : E} (hy : ∥y∥ ≤ 1) (hxy : ∥a • x + b • y∥ < 1) : ∥c • x + d • y∥ < 1 := begin have hbd : b ≤ d, { refine le_of_add_le_add_left (hab.trans_le _), rw ←hcd, exact add_le_add_right hca _ }, have h₁ : 0 < c / a := div_pos hc ha, have h₂ : 0 ≤ d - c / a * b, { rw [sub_nonneg, mul_comm_div, ←le_div_iff' hc], exact div_le_div hd.le hbd hc hca }, calc ∥c • x + d • y∥ = ∥(c / a) • (a • x + b • y) + (d - c / a * b) • y∥ : by rw [smul_add, ←mul_smul, ←mul_smul, div_mul_cancel _ ha.ne', sub_smul, add_add_sub_cancel] ... ≤ ∥(c / a) • (a • x + b • y)∥ + ∥(d - c / a * b) • y∥ : norm_add_le _ _ ... = c / a * ∥a • x + b • y∥ + (d - c / a * b) * ∥y∥ : by rw [norm_smul_of_nonneg h₁.le, norm_smul_of_nonneg h₂] ... < c / a * 1 + (d - c / a * b) * 1 : add_lt_add_of_lt_of_le (mul_lt_mul_of_pos_left hxy h₁) (mul_le_mul_of_nonneg_left hy h₂) ... = 1 : begin nth_rewrite 0 ←hab, rw [mul_add, div_mul_cancel _ ha.ne', mul_one, add_add_sub_cancel, hcd], end, end /-- Strict convexity is equivalent to `∥a • x + b • y∥ < 1` for all `x` and `y` of norm at most `1` and all strictly positive `a` and `b` such that `a + b = 1`. This shows that we only need to check it for fixed `a` and `b`. -/ lemma strict_convex_space.of_norm_add_lt {a b : ℝ} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (h : ∀ x y : E, ∥x∥ ≤ 1 → ∥y∥ ≤ 1 → x ≠ y → ∥a • x + b • y∥ < 1) : strict_convex_space ℝ E := begin refine strict_convex_space.of_strict_convex_closed_unit_ball _ (λ x hx y hy hxy c d hc hd hcd, _), rw [interior_closed_ball (0 : E) one_ne_zero, mem_ball_zero_iff], rw mem_closed_ball_zero_iff at hx hy, obtain hca | hac := le_total c a, { exact strict_convex_space.of_norm_add_lt_aux ha hab hc hd hcd hca hy (h _ _ hx hy hxy) }, rw add_comm at ⊢ hab hcd, refine strict_convex_space.of_norm_add_lt_aux hb hab hd hc hcd _ hx _, { refine le_of_add_le_add_right (hcd.trans_le _), rw ←hab, exact add_le_add_left hac _ }, { rw add_comm, exact h _ _ hx hy hxy } end variables [strict_convex_space ℝ E] {x y z : E} {a b r : ℝ} /-- If `x ≠ y` belong to the same closed ball, then a convex combination of `x` and `y` with positive coefficients belongs to the corresponding open ball. -/ lemma combo_mem_ball_of_ne (hx : x ∈ closed_ball z r) (hy : y ∈ closed_ball z r) (hne : x ≠ y) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : a • x + b • y ∈ ball z r := begin rcases eq_or_ne r 0 with rfl|hr, { rw [closed_ball_zero, mem_singleton_iff] at hx hy, exact (hne (hx.trans hy.symm)).elim }, { simp only [← interior_closed_ball _ hr] at hx hy ⊢, exact strict_convex_closed_ball ℝ z r hx hy hne ha hb hab } end /-- If `x ≠ y` belong to the same closed ball, then the open segment with endpoints `x` and `y` is included in the corresponding open ball. -/ lemma open_segment_subset_ball_of_ne (hx : x ∈ closed_ball z r) (hy : y ∈ closed_ball z r) (hne : x ≠ y) : open_segment ℝ x y ⊆ ball z r := (open_segment_subset_iff _).2 $ λ a b, combo_mem_ball_of_ne hx hy hne /-- If `x` and `y` are two distinct vectors of norm at most `r`, then a convex combination of `x` and `y` with positive coefficients has norm strictly less than `r`. -/ lemma norm_combo_lt_of_ne (hx : ∥x∥ ≤ r) (hy : ∥y∥ ≤ r) (hne : x ≠ y) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : ∥a • x + b • y∥ < r := begin simp only [← mem_ball_zero_iff, ← mem_closed_ball_zero_iff] at hx hy ⊢, exact combo_mem_ball_of_ne hx hy hne ha hb hab end /-- In a strictly convex space, if `x` and `y` are not in the same ray, then `∥x + y∥ < ∥x∥ + ∥y∥`. -/ lemma norm_add_lt_of_not_same_ray (h : ¬same_ray ℝ x y) : ∥x + y∥ < ∥x∥ + ∥y∥ := begin simp only [same_ray_iff_inv_norm_smul_eq, not_or_distrib, ← ne.def] at h, rcases h with ⟨hx, hy, hne⟩, rw ← norm_pos_iff at hx hy, have hxy : 0 < ∥x∥ + ∥y∥ := add_pos hx hy, have := combo_mem_ball_of_ne (inv_norm_smul_mem_closed_unit_ball x) (inv_norm_smul_mem_closed_unit_ball y) hne (div_pos hx hxy) (div_pos hy hxy) (by rw [← add_div, div_self hxy.ne']), rwa [mem_ball_zero_iff, div_eq_inv_mul, div_eq_inv_mul, mul_smul, mul_smul, smul_inv_smul₀ hx.ne', smul_inv_smul₀ hy.ne', ← smul_add, norm_smul, real.norm_of_nonneg (inv_pos.2 hxy).le, ← div_eq_inv_mul, div_lt_one hxy] at this end lemma lt_norm_sub_of_not_same_ray (h : ¬same_ray ℝ x y) : ∥x∥ - ∥y∥ < ∥x - y∥ := begin nth_rewrite 0 ←sub_add_cancel x y at ⊢ h, exact sub_lt_iff_lt_add.2 (norm_add_lt_of_not_same_ray $ λ H', h $ H'.add_left same_ray.rfl), end lemma abs_lt_norm_sub_of_not_same_ray (h : ¬same_ray ℝ x y) : |∥x∥ - ∥y∥| < ∥x - y∥ := begin refine abs_sub_lt_iff.2 ⟨lt_norm_sub_of_not_same_ray h, _⟩, rw norm_sub_rev, exact lt_norm_sub_of_not_same_ray (mt same_ray.symm h), end /-- In a strictly convex space, two vectors `x`, `y` are in the same ray if and only if the triangle inequality for `x` and `y` becomes an equality. -/ lemma same_ray_iff_norm_add : same_ray ℝ x y ↔ ∥x + y∥ = ∥x∥ + ∥y∥ := ⟨same_ray.norm_add, λ h, not_not.1 $ λ h', (norm_add_lt_of_not_same_ray h').ne h⟩ /-- If `x` and `y` are two vectors in a strictly convex space have the same norm and the norm of their sum is equal to the sum of their norms, then they are equal. -/ lemma eq_of_norm_eq_of_norm_add_eq (h₁ : ∥x∥ = ∥y∥) (h₂ : ∥x + y∥ = ∥x∥ + ∥y∥) : x = y := (same_ray_iff_norm_add.mpr h₂).eq_of_norm_eq h₁ /-- In a strictly convex space, two vectors `x`, `y` are not in the same ray if and only if the triangle inequality for `x` and `y` is strict. -/ lemma not_same_ray_iff_norm_add_lt : ¬ same_ray ℝ x y ↔ ∥x + y∥ < ∥x∥ + ∥y∥ := same_ray_iff_norm_add.not.trans (norm_add_le _ _).lt_iff_ne.symm lemma same_ray_iff_norm_sub : same_ray ℝ x y ↔ ∥x - y∥ = |∥x∥ - ∥y∥| := ⟨same_ray.norm_sub, λ h, not_not.1 $ λ h', (abs_lt_norm_sub_of_not_same_ray h').ne' h⟩ lemma not_same_ray_iff_abs_lt_norm_sub : ¬ same_ray ℝ x y ↔ |∥x∥ - ∥y∥| < ∥x - y∥ := same_ray_iff_norm_sub.not.trans $ ne_comm.trans (abs_norm_sub_norm_le _ _).lt_iff_ne.symm /-- In a strictly convex space, the triangle inequality turns into an equality if and only if the middle point belongs to the segment joining two other points. -/ lemma dist_add_dist_eq_iff : dist x y + dist y z = dist x z ↔ y ∈ [x -[ℝ] z] := by simp only [mem_segment_iff_same_ray, same_ray_iff_norm_add, dist_eq_norm', sub_add_sub_cancel', eq_comm] lemma norm_midpoint_lt_iff (h : ∥x∥ = ∥y∥) : ∥(1/2 : ℝ) • (x + y)∥ < ∥x∥ ↔ x ≠ y := by rw [norm_smul, real.norm_of_nonneg (one_div_nonneg.2 zero_le_two), ←inv_eq_one_div, ←div_eq_inv_mul, div_lt_iff (@zero_lt_two ℝ _ _), mul_two, ←not_same_ray_iff_of_norm_eq h, not_same_ray_iff_norm_add_lt, h] variables {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] variables {PF : Type*} {PE : Type*} [metric_space PF] [metric_space PE] variables [normed_add_torsor F PF] [normed_add_torsor E PE] include E lemma eq_line_map_of_dist_eq_mul_of_dist_eq_mul {x y z : PE} (hxy : dist x y = r * dist x z) (hyz : dist y z = (1 - r) * dist x z) : y = affine_map.line_map x z r := begin have : y -ᵥ x ∈ [(0 : E) -[ℝ] z -ᵥ x], { rw [← dist_add_dist_eq_iff, dist_zero_left, dist_vsub_cancel_right, ← dist_eq_norm_vsub', ← dist_eq_norm_vsub', hxy, hyz, ← add_mul, add_sub_cancel'_right, one_mul] }, rcases eq_or_ne x z with rfl|hne, { obtain rfl : y = x, by simpa, simp }, { rw [← dist_ne_zero] at hne, rcases this with ⟨a, b, ha, hb, hab, H⟩, rw [smul_zero, zero_add] at H, have H' := congr_arg norm H, rw [norm_smul, real.norm_of_nonneg hb, ← dist_eq_norm_vsub', ← dist_eq_norm_vsub', hxy, mul_left_inj' hne] at H', rw [affine_map.line_map_apply, ← H', H, vsub_vadd] }, end lemma eq_midpoint_of_dist_eq_half {x y z : PE} (hx : dist x y = dist x z / 2) (hy : dist y z = dist x z / 2) : y = midpoint ℝ x z := begin apply eq_line_map_of_dist_eq_mul_of_dist_eq_mul, { rwa [inv_of_eq_inv, ← div_eq_inv_mul] }, { rwa [inv_of_eq_inv, ← one_div, sub_half, one_div, ← div_eq_inv_mul] } end namespace isometry include F /-- An isometry of `normed_add_torsor`s for real normed spaces, strictly convex in the case of the codomain, is an affine isometry. Unlike Mazur-Ulam, this does not require the isometry to be surjective. -/ noncomputable def affine_isometry_of_strict_convex_space {f : PF → PE} (hi : isometry f) : PF →ᵃⁱ[ℝ] PE := { norm_map := λ x, by simp [affine_map.of_map_midpoint, ←dist_eq_norm_vsub E, hi.dist_eq], ..affine_map.of_map_midpoint f (λ x y, begin apply eq_midpoint_of_dist_eq_half, { rw [hi.dist_eq, hi.dist_eq, dist_left_midpoint, real.norm_of_nonneg zero_le_two, div_eq_inv_mul] }, { rw [hi.dist_eq, hi.dist_eq, dist_midpoint_right, real.norm_of_nonneg zero_le_two, div_eq_inv_mul] }, end) hi.continuous } @[simp] lemma coe_affine_isometry_of_strict_convex_space {f : PF → PE} (hi : isometry f) : ⇑(hi.affine_isometry_of_strict_convex_space) = f := rfl @[simp] lemma affine_isometry_of_strict_convex_space_apply {f : PF → PE} (hi : isometry f) (p : PF) : hi.affine_isometry_of_strict_convex_space p = f p := rfl end isometry
e26705982ce61357377635b6f1317903b582a151
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/homotopy/complex_hopf.hlean
a425af5a15be1000640c5bd9be53fb70b90ba3a5
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
1,611
hlean
/- Copyright (c) 2016 Ulrik Buchholtz and Egbert Rijke. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ulrik Buchholtz, Egbert Rijke, Floris van Doorn The H-space structure on S¹ and the complex Hopf fibration (the standard one). -/ import .hopf .circle types.fin open eq equiv is_equiv circle is_conn trunc is_trunc sphere susp pointed fiber sphere.ops function join namespace hopf definition circle_h_space [instance] : h_space S¹ := ⦃ h_space, one := base, mul := circle_mul, one_mul := circle_base_mul, mul_one := circle_mul_base ⦄ definition circle_assoc (x y z : S¹) : (x * y) * z = x * (y * z) := begin induction x, { reflexivity }, { apply eq_pathover, induction y, { exact natural_square (λa : S¹, ap (λb : S¹, b * z) (circle_mul_base a)) loop }, { apply is_prop.elimo, apply is_trunc_square }} end definition complex_hopf' : S 3 → S 2 := begin intro x, apply @sigma.pr1 (susp S¹) (hopf S¹), apply inv (hopf.total S¹), exact (join_sphere 1 1)⁻¹ᵉ x end definition complex_hopf [constructor] : S 3 →* S 2 := proof pmap.mk complex_hopf' idp qed definition pfiber_complex_hopf : pfiber complex_hopf ≃* S 1 := begin fapply pequiv_of_equiv, { esimp, unfold [complex_hopf'], refine fiber.equiv_precompose (sigma.pr1 ∘ (hopf.total S¹)⁻¹ᵉ) (join_sphere 1 1)⁻¹ᵉ _ ⬝e _, refine fiber.equiv_precompose _ (hopf.total S¹)⁻¹ᵉ _ ⬝e _, apply fiber_pr1 }, { reflexivity } end end hopf
e710f9384ac8b28722de29f294edcda9c006f44f
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/index.lean
52bcb63b48b14766454cb3b238dd8f7611f7c3f7
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
12,492
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import group_theory.quotient_group import set_theory.cardinal.finite /-! # Index of a Subgroup In this file we define the index of a subgroup, and prove several divisibility properties. Several theorems proved in this file are known as Lagrange's theorem. ## Main definitions - `H.index` : the index of `H : subgroup G` as a natural number, and returns 0 if the index is infinite. - `H.relindex K` : the relative index of `H : subgroup G` in `K : subgroup G` as a natural number, and returns 0 if the relative index is infinite. # Main results - `card_mul_index` : `nat.card H * H.index = nat.card G` - `index_mul_card` : `H.index * fintype.card H = fintype.card G` - `index_dvd_card` : `H.index ∣ fintype.card G` - `index_eq_mul_of_le` : If `H ≤ K`, then `H.index = K.index * (H.subgroup_of K).index` - `index_dvd_of_le` : If `H ≤ K`, then `K.index ∣ H.index` - `relindex_mul_relindex` : `relindex` is multiplicative in towers -/ namespace subgroup open_locale cardinal variables {G : Type*} [group G] (H K L : subgroup G) /-- The index of a subgroup as a natural number, and returns 0 if the index is infinite. -/ @[to_additive "The index of a subgroup as a natural number, and returns 0 if the index is infinite."] noncomputable def index : ℕ := nat.card (G ⧸ H) /-- The relative index of a subgroup as a natural number, and returns 0 if the relative index is infinite. -/ @[to_additive "The relative index of a subgroup as a natural number, and returns 0 if the relative index is infinite."] noncomputable def relindex : ℕ := (H.subgroup_of K).index @[to_additive] lemma index_comap_of_surjective {G' : Type*} [group G'] {f : G' →* G} (hf : function.surjective f) : (H.comap f).index = H.index := begin letI := quotient_group.left_rel H, letI := quotient_group.left_rel (H.comap f), have key : ∀ x y : G', setoid.r x y ↔ setoid.r (f x) (f y), { simp only [quotient_group.left_rel_apply], exact λ x y, iff_of_eq (congr_arg (∈ H) (by rw [f.map_mul, f.map_inv])) }, refine cardinal.to_nat_congr (equiv.of_bijective (quotient.map' f (λ x y, (key x y).mp)) ⟨_, _⟩), { simp_rw [←quotient.eq'] at key, refine quotient.ind' (λ x, _), refine quotient.ind' (λ y, _), exact (key x y).mpr }, { refine quotient.ind' (λ x, _), obtain ⟨y, hy⟩ := hf x, exact ⟨y, (quotient.map'_mk' f _ y).trans (congr_arg quotient.mk' hy)⟩ }, end @[to_additive] lemma index_comap {G' : Type*} [group G'] (f : G' →* G) : (H.comap f).index = H.relindex f.range := eq.trans (congr_arg index (by refl)) ((H.subgroup_of f.range).index_comap_of_surjective f.range_restrict_surjective) variables {H K L} @[to_additive relindex_mul_index] lemma relindex_mul_index (h : H ≤ K) : H.relindex K * K.index = H.index := ((mul_comm _ _).trans (cardinal.to_nat_mul _ _).symm).trans (congr_arg cardinal.to_nat (equiv.cardinal_eq (quotient_equiv_prod_of_le h))).symm @[to_additive] lemma index_dvd_of_le (h : H ≤ K) : K.index ∣ H.index := dvd_of_mul_left_eq (H.relindex K) (relindex_mul_index h) @[to_additive] lemma relindex_dvd_index_of_le (h : H ≤ K) : H.relindex K ∣ H.index := dvd_of_mul_right_eq K.index (relindex_mul_index h) @[to_additive] lemma relindex_subgroup_of (hKL : K ≤ L) : (H.subgroup_of L).relindex (K.subgroup_of L) = H.relindex K := ((index_comap (H.subgroup_of L) (inclusion hKL)).trans (congr_arg _ (inclusion_range hKL))).symm variables (H K L) @[to_additive relindex_mul_relindex] lemma relindex_mul_relindex (hHK : H ≤ K) (hKL : K ≤ L) : H.relindex K * K.relindex L = H.relindex L := begin rw [←relindex_subgroup_of hKL], exact relindex_mul_index (λ x hx, hHK hx), end @[to_additive] lemma inf_relindex_right : (H ⊓ K).relindex K = H.relindex K := begin rw [←subgroup_of_map_subtype, relindex, relindex, subgroup_of, comap_map_eq_self_of_injective], exact subtype.coe_injective, end @[to_additive] lemma inf_relindex_left : (H ⊓ K).relindex H = K.relindex H := by rw [inf_comm, inf_relindex_right] @[to_additive relindex_inf_mul_relindex] lemma relindex_inf_mul_relindex : H.relindex (K ⊓ L) * K.relindex L = (H ⊓ K).relindex L := by rw [←inf_relindex_right H (K ⊓ L), ←inf_relindex_right K L, ←inf_relindex_right (H ⊓ K) L, inf_assoc, relindex_mul_relindex (H ⊓ (K ⊓ L)) (K ⊓ L) L inf_le_right inf_le_right] @[to_additive] lemma inf_relindex_eq_relindex_sup [K.normal] : (H ⊓ K).relindex H = K.relindex (H ⊔ K) := cardinal.to_nat_congr (quotient_group.quotient_inf_equiv_prod_normal_quotient H K).to_equiv @[to_additive] lemma relindex_eq_relindex_sup [K.normal] : K.relindex H = K.relindex (H ⊔ K) := by rw [←inf_relindex_left, inf_relindex_eq_relindex_sup] @[to_additive] lemma relindex_dvd_index_of_normal [H.normal] : H.relindex K ∣ H.index := (relindex_eq_relindex_sup K H).symm ▸ relindex_dvd_index_of_le le_sup_right variables {H K} @[to_additive] lemma relindex_dvd_of_le_left (hHK : H ≤ K) : K.relindex L ∣ H.relindex L := begin apply dvd_of_mul_left_eq ((H ⊓ L).relindex (K ⊓ L)), rw [←inf_relindex_right H L, ←inf_relindex_right K L], exact relindex_mul_relindex (H ⊓ L) (K ⊓ L) L (inf_le_inf_right L hHK) inf_le_right, end variables (H K) @[simp, to_additive] lemma index_top : (⊤ : subgroup G).index = 1 := cardinal.to_nat_eq_one_iff_unique.mpr ⟨quotient_group.subsingleton_quotient_top, ⟨1⟩⟩ @[simp, to_additive] lemma index_bot : (⊥ : subgroup G).index = nat.card G := cardinal.to_nat_congr (quotient_group.quotient_bot.to_equiv) @[to_additive] lemma index_bot_eq_card [fintype G] : (⊥ : subgroup G).index = fintype.card G := index_bot.trans nat.card_eq_fintype_card @[simp, to_additive] lemma relindex_top_left : (⊤ : subgroup G).relindex H = 1 := index_top @[simp, to_additive] lemma relindex_top_right : H.relindex ⊤ = H.index := by rw [←relindex_mul_index (show H ≤ ⊤, from le_top), index_top, mul_one] @[simp, to_additive] lemma relindex_bot_left : (⊥ : subgroup G).relindex H = nat.card H := by rw [relindex, bot_subgroup_of, index_bot] @[to_additive] lemma relindex_bot_left_eq_card [fintype H] : (⊥ : subgroup G).relindex H = fintype.card H := H.relindex_bot_left.trans nat.card_eq_fintype_card @[simp, to_additive] lemma relindex_bot_right : H.relindex ⊥ = 1 := by rw [relindex, subgroup_of_bot_eq_top, index_top] @[simp, to_additive] lemma relindex_self : H.relindex H = 1 := by rw [relindex, subgroup_of_self, index_top] @[simp, to_additive card_mul_index] lemma card_mul_index : nat.card H * H.index = nat.card G := by { rw [←relindex_bot_left, ←index_bot], exact relindex_mul_index bot_le } @[to_additive] lemma nat_card_dvd_of_injective {G H : Type*} [group G] [group H] (f : G →* H) (hf : function.injective f) : nat.card G ∣ nat.card H := begin rw nat.card_congr (monoid_hom.of_injective hf).to_equiv, exact dvd.intro f.range.index f.range.card_mul_index, end @[to_additive] lemma nat_card_dvd_of_surjective {G H : Type*} [group G] [group H] (f : G →* H) (hf : function.surjective f) : nat.card H ∣ nat.card G := begin rw ← nat.card_congr (quotient_group.quotient_ker_equiv_of_surjective f hf).to_equiv, exact dvd.intro_left (nat.card f.ker) f.ker.card_mul_index, end @[to_additive] lemma card_dvd_of_surjective {G H : Type*} [group G] [group H] [fintype G] [fintype H] (f : G →* H) (hf : function.surjective f) : fintype.card H ∣ fintype.card G := by simp only [←nat.card_eq_fintype_card, nat_card_dvd_of_surjective f hf] @[to_additive] lemma index_map {G' : Type*} [group G'] (f : G →* G') : (H.map f).index = (H ⊔ f.ker).index * f.range.index := by rw [←comap_map_eq, index_comap, relindex_mul_index (H.map_le_range f)] @[to_additive] lemma index_map_dvd {G' : Type*} [group G'] {f : G →* G'} (hf : function.surjective f) : (H.map f).index ∣ H.index := begin rw [index_map, f.range_top_of_surjective hf, index_top, mul_one], exact index_dvd_of_le le_sup_left, end @[to_additive] lemma dvd_index_map {G' : Type*} [group G'] {f : G →* G'} (hf : f.ker ≤ H) : H.index ∣ (H.map f).index := begin rw [index_map, sup_of_le_left hf], apply dvd_mul_right, end @[to_additive] lemma index_map_eq {G' : Type*} [group G'] {f : G →* G'} (hf1 : function.surjective f) (hf2 : f.ker ≤ H) : (H.map f).index = H.index := nat.dvd_antisymm (H.index_map_dvd hf1) (H.dvd_index_map hf2) @[to_additive] lemma index_eq_card [fintype (G ⧸ H)] : H.index = fintype.card (G ⧸ H) := nat.card_eq_fintype_card @[to_additive index_mul_card] lemma index_mul_card [fintype G] [hH : fintype H] : H.index * fintype.card H = fintype.card G := by rw [←relindex_bot_left_eq_card, ←index_bot_eq_card, mul_comm]; exact relindex_mul_index bot_le @[to_additive] lemma index_dvd_card [fintype G] : H.index ∣ fintype.card G := begin classical, exact ⟨fintype.card H, H.index_mul_card.symm⟩, end variables {H K L} @[to_additive] lemma relindex_eq_zero_of_le_left (hHK : H ≤ K) (hKL : K.relindex L = 0) : H.relindex L = 0 := eq_zero_of_zero_dvd (hKL ▸ (relindex_dvd_of_le_left L hHK)) @[to_additive] lemma relindex_eq_zero_of_le_right (hKL : K ≤ L) (hHK : H.relindex K = 0) : H.relindex L = 0 := cardinal.to_nat_apply_of_aleph_0_le (le_trans (le_of_not_lt (λ h, cardinal.mk_ne_zero _ ((cardinal.cast_to_nat_of_lt_aleph_0 h).symm.trans (cardinal.nat_cast_inj.mpr hHK)))) (quotient_subgroup_of_embedding_of_le H hKL).cardinal_le) @[to_additive] lemma relindex_le_of_le_left (hHK : H ≤ K) (hHL : H.relindex L ≠ 0) : K.relindex L ≤ H.relindex L := nat.le_of_dvd (nat.pos_of_ne_zero hHL) (relindex_dvd_of_le_left L hHK) @[to_additive] lemma relindex_le_of_le_right (hKL : K ≤ L) (hHL : H.relindex L ≠ 0) : H.relindex K ≤ H.relindex L := cardinal.to_nat_le_of_le_of_lt_aleph_0 (lt_of_not_ge (mt cardinal.to_nat_apply_of_aleph_0_le hHL)) (cardinal.mk_le_of_injective (quotient_subgroup_of_embedding_of_le H hKL).2) @[to_additive] lemma relindex_ne_zero_trans (hHK : H.relindex K ≠ 0) (hKL : K.relindex L ≠ 0) : H.relindex L ≠ 0 := λ h, mul_ne_zero (mt (relindex_eq_zero_of_le_right (show K ⊓ L ≤ K, from inf_le_left)) hHK) hKL ((relindex_inf_mul_relindex H K L).trans (relindex_eq_zero_of_le_left inf_le_left h)) @[to_additive] lemma relindex_inf_ne_zero (hH : H.relindex L ≠ 0) (hK : K.relindex L ≠ 0) : (H ⊓ K).relindex L ≠ 0 := begin replace hH : H.relindex (K ⊓ L) ≠ 0 := mt (relindex_eq_zero_of_le_right inf_le_right) hH, rw ← inf_relindex_right at hH hK ⊢, rw inf_assoc, exact relindex_ne_zero_trans hH hK, end @[to_additive] lemma index_inf_ne_zero (hH : H.index ≠ 0) (hK : K.index ≠ 0) : (H ⊓ K).index ≠ 0 := begin rw ← relindex_top_right at hH hK ⊢, exact relindex_inf_ne_zero hH hK, end @[to_additive] lemma relindex_inf_le : (H ⊓ K).relindex L ≤ H.relindex L * K.relindex L := begin by_cases h : H.relindex L = 0, { exact (le_of_eq (relindex_eq_zero_of_le_left (by exact inf_le_left) h)).trans (zero_le _) }, rw [←inf_relindex_right, inf_assoc, ←relindex_mul_relindex _ _ L inf_le_right inf_le_right, inf_relindex_right, inf_relindex_right], exact mul_le_mul_right' (relindex_le_of_le_right inf_le_right h) (K.relindex L), end @[to_additive] lemma index_inf_le : (H ⊓ K).index ≤ H.index * K.index := by simp_rw [←relindex_top_right, relindex_inf_le] @[simp, to_additive index_eq_one] lemma index_eq_one : H.index = 1 ↔ H = ⊤ := ⟨λ h, quotient_group.subgroup_eq_top_of_subsingleton H (cardinal.to_nat_eq_one_iff_unique.mp h).1, λ h, (congr_arg index h).trans index_top⟩ @[to_additive] lemma index_ne_zero_of_finite [hH : finite (G ⧸ H)] : H.index ≠ 0 := by { casesI nonempty_fintype (G ⧸ H), rw index_eq_card, exact fintype.card_ne_zero } /-- Finite index implies finite quotient. -/ @[to_additive "Finite index implies finite quotient."] noncomputable def fintype_of_index_ne_zero (hH : H.index ≠ 0) : fintype (G ⧸ H) := (cardinal.lt_aleph_0_iff_fintype.mp (lt_of_not_ge (mt cardinal.to_nat_apply_of_aleph_0_le hH))).some @[to_additive one_lt_index_of_ne_top] lemma one_lt_index_of_ne_top [finite (G ⧸ H)] (hH : H ≠ ⊤) : 1 < H.index := nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨index_ne_zero_of_finite, mt index_eq_one.mp hH⟩ end subgroup
e0d8f4406b5c8eeacd2e6a0279a7d241989591f1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/products/default_auto.lean
b82167d2f1c6cfd85084f9050b0fa213a83fdec5
[]
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
216
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.products.bifunctor import Mathlib.category_theory.products.associator import Mathlib.PostPort namespace Mathlib end Mathlib
58255fd9bf2dd5afdf84963509653c573628cb2f
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Init/Classical.lean
92e0d4f8f3ccf56ce23729b5944dd41c0a7097c2
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,391
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 import Init.Core import Init.NotationExtra universe u v /- Classical reasoning support -/ namespace Classical axiom choice {α : Sort u} : Nonempty α → α noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop) (h : ∃ x, p x) : {x // p x} := choice <| let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩ noncomputable def choose {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : α := (indefiniteDescription p h).val theorem choose_spec {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : p (choose h) := (indefiniteDescription p h).property /- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/ theorem em (p : Prop) : p ∨ ¬p := let U (x : Prop) : Prop := x = True ∨ p; let V (x : Prop) : Prop := x = False ∨ p; have exU : ∃ x, U x := ⟨True, Or.inl rfl⟩; have exV : ∃ x, V x := ⟨False, Or.inl rfl⟩; let u : Prop := choose exU; let v : Prop := choose exV; have uDef : U u := choose_spec exU; have vDef : V v := choose_spec exV; have notUvOrP : u ≠ v ∨ p := match uDef, vDef with | Or.inr h, _ => Or.inr h | _, Or.inr h => Or.inr h | Or.inl hut, Or.inl hvf => have hne : u ≠ v := hvf.symm ▸ hut.symm ▸ true_ne_false Or.inl hne have pImpliesUv : p → u = v := fun hp => have hpred : U = V := funext fun x => have hl : (x = True ∨ p) → (x = False ∨ p) := fun a => Or.inr hp; have hr : (x = False ∨ p) → (x = True ∨ p) := fun a => Or.inr hp; show (x = True ∨ p) = (x = False ∨ p) from propext (Iff.intro hl hr); have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV := hpred ▸ fun exU exV => rfl; show u = v from h₀ ..; match notUvOrP with | Or.inl hne => Or.inr (mt pImpliesUv hne) | Or.inr h => Or.inl h theorem exists_true_of_nonempty {α : Sort u} : Nonempty α → ∃ x : α, True | ⟨x⟩ => ⟨x, trivial⟩ noncomputable def inhabited_of_nonempty {α : Sort u} (h : Nonempty α) : Inhabited α := ⟨choice h⟩ noncomputable def inhabited_of_exists {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : Inhabited α := inhabited_of_nonempty (Exists.elim h (fun w hw => ⟨w⟩)) /- all propositions are Decidable -/ noncomputable scoped instance (priority := low) propDecidable (a : Prop) : Decidable a := choice <| match em a with | Or.inl h => ⟨isTrue h⟩ | Or.inr h => ⟨isFalse h⟩ noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) where default := inferInstance noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α := fun x y => inferInstance noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) := match (propDecidable (Nonempty α)) with | (isTrue hp) => PSum.inl (@arbitrary _ (inhabited_of_nonempty hp)) | (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn) noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop) (h : Nonempty α) : {x : α // (∃ y : α, p y) → p x} := @dite _ (∃ x : α, p x) (propDecidable _) (fun (hp : ∃ x : α, p x) => show {x : α // (∃ y : α, p y) → p x} from let xp := indefiniteDescription _ hp; ⟨xp.val, fun h' => xp.property⟩) (fun hp => ⟨choice h, fun h => absurd h hp⟩) /- the Hilbert epsilon Function -/ noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α := (strongIndefiniteDescription p h).val theorem epsilon_spec_aux {α : Sort u} (h : Nonempty α) (p : α → Prop) : (∃ y, p y) → p (@epsilon α h p) := (strongIndefiniteDescription p h).property theorem epsilon_spec {α : Sort u} {p : α → Prop} (hex : ∃ y, p y) : p (@epsilon α (nonempty_of_exists hex) p) := epsilon_spec_aux (nonempty_of_exists hex) p hex theorem epsilon_singleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x := @epsilon_spec α (fun y => y = x) ⟨x, rfl⟩ /- the axiom of choice -/ theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, ∃ y, r x y) : ∃ (f : ∀ x, β x), ∀ x, r x (f x) := ⟨_, fun x => choose_spec (h x)⟩ theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} : (∀ x, ∃ y, p x y) ↔ ∃ (f : ∀ x, b x), ∀ x, p x (f x) := ⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩ theorem propComplete (a : Prop) : a = True ∨ a = False := by cases em a with | inl _ => apply Or.inl; apply propext; apply Iff.intro; { intros; apply True.intro }; { intro; assumption } | inr hn => apply Or.inr; apply propext; apply Iff.intro; { intro h; exact hn h }; { intro h; apply False.elim h } -- this supercedes byCases in Decidable theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := Decidable.byCases (dec := propDecidable _) hpq hnpq -- this supercedes byContradiction in Decidable theorem byContradiction {p : Prop} (h : ¬p → False) : p := Decidable.byContradiction (dec := propDecidable _) h macro "byCases" h:ident ":" e:term : tactic => `(cases em $e:term with | inl $h:ident => _ | inr $h:ident => _) end Classical
838eae6488637ca246ca030edb91dafe4f5725f2
d1bbf1801b3dcb214451d48214589f511061da63
/src/order/atoms.lean
0a57488fb49e9055abd924d479d9ac5bd26b5d8a
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,629
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson. -/ import order.complete_boolean_algebra import order.order_dual import order.lattice_intervals import order.rel_iso import data.fintype.basic /-! # Atoms, Coatoms, and Simple Lattices This module defines atoms, which are minimal non-`⊥` elements in bounded lattices, simple lattices, which are lattices with only two elements, and related ideas. ## Main definitions ### Atoms and Coatoms * `is_atom a` indicates that the only element below `a` is `⊥`. * `is_coatom a` indicates that the only element above `a` is `⊤`. ### Simple Lattices * `is_simple_lattice` indicates that a bounded lattice has only two elements, `⊥` and `⊤`. * `is_simple_lattice.bounded_distrib_lattice` * Given an instance of `is_simple_lattice`, we provide the following definitions. These are not made global instances as they contain data : * `is_simple_lattice.boolean_algebra` * `is_simple_lattice.complete_lattice` * `is_simple_lattice.complete_boolean_algebra` ## Main results * `is_atom_iff_is_coatom_dual` and `is_coatom_iff_is_atom_dual` express the (definitional) duality of `is_atom` and `is_coatom`. * `is_simple_lattice_iff_is_atom_top` and `is_simple_lattice_iff_is_coatom_bot` express the connection between atoms, coatoms, and simple lattices -/ variable {α : Type*} section atoms section is_atom variable [order_bot α] /-- An atom of an `order_bot` is an element with no other element between it and `⊥`, which is not `⊥`. -/ def is_atom (a : α) : Prop := a ≠ ⊥ ∧ (∀ b, b < a → b = ⊥) lemma eq_bot_or_eq_of_le_atom {a b : α} (ha : is_atom a) (hab : b ≤ a) : b = ⊥ ∨ b = a := or.imp_left (ha.2 b) (lt_or_eq_of_le hab) end is_atom section is_coatom variable [order_top α] /-- A coatom of an `order_top` is an element with no other element between it and `⊤`, which is not `⊤`. -/ def is_coatom (a : α) : Prop := a ≠ ⊤ ∧ (∀ b, a < b → b = ⊤) lemma eq_top_or_eq_of_coatom_le {a b : α} (ha : is_coatom a) (hab : a ≤ b) : b = ⊤ ∨ b = a := or.imp (ha.2 b) eq_comm.2 (lt_or_eq_of_le hab) end is_coatom section pairwise lemma is_atom.inf_eq_bot_of_ne [semilattice_inf_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : a ⊓ b = ⊥ := or.elim (eq_bot_or_eq_of_le_atom ha inf_le_left) id (λ h1, or.elim (eq_bot_or_eq_of_le_atom hb inf_le_right) id (λ h2, false.rec _ (hab (le_antisymm (inf_eq_left.mp h1) (inf_eq_right.mp h2))))) lemma is_atom.disjoint_of_ne [semilattice_inf_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : disjoint a b := disjoint_iff.mpr (is_atom.inf_eq_bot_of_ne ha hb hab) lemma is_coatom.sup_eq_top_of_ne [semilattice_sup_top α] {a b : α} (ha : is_coatom a) (hb : is_coatom b) (hab : a ≠ b) : a ⊔ b = ⊤ := or.elim (eq_top_or_eq_of_coatom_le ha le_sup_left) id (λ h1, or.elim (eq_top_or_eq_of_coatom_le hb le_sup_right) id (λ h2, false.rec _ (hab (le_antisymm (sup_eq_right.mp h2) (sup_eq_left.mp h1))))) end pairwise variables [bounded_lattice α] {a : α} lemma is_atom_iff_is_coatom_dual : is_atom a ↔ is_coatom (order_dual.to_dual a) := iff.refl _ lemma is_coatom_iff_is_atom_dual : is_coatom a ↔ is_atom (order_dual.to_dual a) := iff.refl _ end atoms /-- A lattice is simple iff it has only two elements, `⊥` and `⊤`. -/ class is_simple_lattice (α : Type*) [bounded_lattice α] extends nontrivial α : Prop := (eq_bot_or_eq_top : ∀ (a : α), a = ⊥ ∨ a = ⊤) export is_simple_lattice (eq_bot_or_eq_top) theorem is_simple_lattice_iff_is_simple_lattice_order_dual [bounded_lattice α] : is_simple_lattice α ↔ is_simple_lattice (order_dual α) := begin split; intro i; haveI := i, { exact { exists_pair_ne := @exists_pair_ne α _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top ((order_dual.of_dual a)) : _ ∨ _) } }, { exact { exists_pair_ne := @exists_pair_ne (order_dual α) _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top (order_dual.to_dual a)) } } end section is_simple_lattice variables [bounded_lattice α] [is_simple_lattice α] instance : is_simple_lattice (order_dual α) := is_simple_lattice_iff_is_simple_lattice_order_dual.1 (by apply_instance) @[simp] lemma is_atom_top : is_atom (⊤ : α) := ⟨top_ne_bot, λ a ha, or.resolve_right (eq_bot_or_eq_top a) (ne_of_lt ha)⟩ @[simp] lemma is_coatom_bot : is_coatom (⊥ : α) := is_coatom_iff_is_atom_dual.2 is_atom_top end is_simple_lattice namespace is_simple_lattice variables [bounded_lattice α] [is_simple_lattice α] /-- A simple `bounded_lattice` is also distributive. -/ @[priority 100] instance : bounded_distrib_lattice α := { le_sup_inf := λ x y z, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp }, .. (infer_instance : bounded_lattice α) } section decidable_eq variable [decidable_eq α] /-- Every simple lattice is order-isomorphic to `bool`. -/ def order_iso_bool : α ≃o bool := { to_fun := λ x, x = ⊤, inv_fun := λ x, cond x ⊤ ⊥, left_inv := λ x, by { rcases (eq_bot_or_eq_top x) with rfl | rfl; simp [bot_ne_top] }, right_inv := λ x, by { cases x; simp [bot_ne_top] }, map_rel_iff' := λ a b, begin rcases (eq_bot_or_eq_top a) with rfl | rfl, { simp [bot_ne_top] }, { rcases (eq_bot_or_eq_top b) with rfl | rfl, { simp [bot_ne_top.symm, bot_ne_top, bool.ff_lt_tt] }, { simp [bot_ne_top] } } end } @[priority 200] instance : fintype α := fintype.of_equiv bool (order_iso_bool.to_equiv).symm /-- A simple `bounded_lattice` is also a `boolean_algebra`. -/ protected def boolean_algebra : boolean_algebra α := { compl := λ x, if x = ⊥ then ⊤ else ⊥, sdiff := λ x y, if x = ⊤ ∧ y = ⊥ then ⊤ else ⊥, sdiff_eq := λ x y, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp [bot_ne_top] }, inf_compl_le_bot := λ x, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp }, top_le_sup_compl := λ x, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp }, .. is_simple_lattice.bounded_distrib_lattice } end decidable_eq open_locale classical /-- A simple `bounded_lattice` is also complete. -/ protected noncomputable def complete_lattice : complete_lattice α := { Sup := λ s, if ⊤ ∈ s then ⊤ else ⊥, Inf := λ s, if ⊥ ∈ s then ⊥ else ⊤, le_Sup := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_pos h } }, Sup_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_neg, intro con, exact bot_ne_top (eq_top_iff.2 (h ⊤ con)) }, { exact le_top } }, Inf_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_pos h }, { exact le_top } }, le_Inf := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_neg, intro con, exact top_ne_bot (eq_bot_iff.2 (h ⊥ con)) } }, .. (infer_instance : bounded_lattice α) } /-- A simple `bounded_lattice` is also a `complete_boolean_algebra`. -/ protected noncomputable def complete_boolean_algebra : complete_boolean_algebra α := { infi_sup_le_sup_Inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_sup_eq, ← Inf_eq_infi], apply le_refl }, { simp only [top_sup_eq, le_top] }, }, inf_Sup_le_supr_inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_inf_eq, bot_le] }, { simp only [top_inf_eq, ← Sup_eq_supr], apply le_refl } }, .. is_simple_lattice.complete_lattice, .. is_simple_lattice.boolean_algebra } end is_simple_lattice namespace fintype namespace is_simple_lattice variables [bounded_lattice α] [is_simple_lattice α] [decidable_eq α] lemma univ : (finset.univ : finset α) = {⊤, ⊥} := begin change finset.map _ (finset.univ : finset bool) = _, rw fintype.univ_bool, simp only [finset.map_insert, function.embedding.coe_fn_mk, finset.map_singleton], refl, end lemma card : fintype.card α = 2 := (fintype.of_equiv_card _).trans fintype.card_bool end is_simple_lattice end fintype namespace bool instance : is_simple_lattice bool := ⟨λ a, begin rw [← finset.mem_singleton, or.comm, ← finset.mem_insert, top_eq_tt, bot_eq_ff, ← fintype.univ_bool], apply finset.mem_univ, end⟩ end bool theorem is_simple_lattice_iff_is_atom_top [bounded_lattice α] : is_simple_lattice α ↔ is_atom (⊤ : α) := ⟨λ h, @is_atom_top _ _ h, λ h, { exists_pair_ne := ⟨⊤, ⊥, h.1⟩, eq_bot_or_eq_top := λ a, ((eq_or_lt_of_le (@le_top _ _ a)).imp_right (h.2 a)).symm }⟩ theorem is_simple_lattice_iff_is_coatom_bot [bounded_lattice α] : is_simple_lattice α ↔ is_coatom (⊥ : α) := is_simple_lattice_iff_is_simple_lattice_order_dual.trans is_simple_lattice_iff_is_atom_top namespace set theorem is_simple_lattice_Iic_iff_is_atom [bounded_lattice α] {a : α} : is_simple_lattice (Iic a) ↔ is_atom a := is_simple_lattice_iff_is_atom_top.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ theorem is_simple_lattice_Ici_iff_is_coatom [bounded_lattice α] {a : α} : is_simple_lattice (Ici a) ↔ is_coatom a := is_simple_lattice_iff_is_coatom_bot.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ end set namespace order_iso variables [bounded_lattice α] {β : Type*} [bounded_lattice β] (f : α ≃o β) include f @[simp] lemma is_atom_iff (a : α) : is_atom (f a) ↔ is_atom a := and_congr (not_congr ⟨λ h, f.injective (f.map_bot.symm ▸ h), λ h, f.map_bot ▸ (congr rfl h)⟩) ⟨λ h b hb, f.injective ((h (f b) ((f : α ↪o β).lt_iff_lt.2 hb)).trans f.map_bot.symm), λ h b hb, f.symm.injective begin rw f.symm.map_bot, apply h, rw [← f.symm_apply_apply a], exact (f.symm : β ↪o α).lt_iff_lt.2 hb, end⟩ @[simp] lemma is_coatom_iff (a : α) : is_coatom (f a) ↔ is_coatom a := f.dual.is_atom_iff a lemma is_simple_lattice_iff (f : α ≃o β) : is_simple_lattice α ↔ is_simple_lattice β := by rw [is_simple_lattice_iff_is_atom_top, is_simple_lattice_iff_is_atom_top, ← f.is_atom_iff ⊤, f.map_top] lemma is_simple_lattice [h : is_simple_lattice β] (f : α ≃o β) : is_simple_lattice α := f.is_simple_lattice_iff.mpr h end order_iso
83ddde34f65d335af7d7a59e4102f71838404349
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/CompilerPullInstances.lean
2d419e91e9dbfd945f8a8f64a5e860a17ed6e022
[ "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
674
lean
import Lean.Compiler.Main import Lean.Compiler.LCNF.Testing import Lean.Elab.Do open Lean open Lean.Compiler.LCNF -- Run compilation twice to avoid the output caused by the inliner #eval Compiler.compile #[``Lean.Meta.synthInstance, ``Lean.Elab.Term.Do.elabDo] @[cpass] def pullInstancesFixTest : PassInstaller := Testing.assertIsAtFixPoint |>.install `pullInstances `pullInstancesFix @[cpass] def pullInstancesSizeTest : PassInstaller := Testing.assertPreservesSize "Pulling instances changed size" |>.install `pullInstances `pullInstancesSizeEq set_option trace.Compiler.test true in #eval Compiler.compile #[``Lean.Meta.synthInstance, ``Lean.Elab.Term.Do.elabDo]
2f9c9e9ff4ecaf0ca658670c3bc755d8db77e146
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/multiset/lattice_auto.lean
769725f00cf3b9f489198ad6bf3c5b61a9a72462
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
4,410
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.multiset.finset_ops import Mathlib.data.multiset.fold import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Lattice operations on multisets -/ namespace multiset /-! ### sup -/ /-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/ def sup {α : Type u_1} [semilattice_sup_bot α] (s : multiset α) : α := fold has_sup.sup ⊥ s @[simp] theorem sup_zero {α : Type u_1} [semilattice_sup_bot α] : sup 0 = ⊥ := fold_zero has_sup.sup ⊥ @[simp] theorem sup_cons {α : Type u_1} [semilattice_sup_bot α] (a : α) (s : multiset α) : sup (a ::ₘ s) = a ⊔ sup s := fold_cons_left has_sup.sup ⊥ a s @[simp] theorem sup_singleton {α : Type u_1} [semilattice_sup_bot α] {a : α} : sup (a ::ₘ 0) = a := sorry @[simp] theorem sup_add {α : Type u_1} [semilattice_sup_bot α] (s₁ : multiset α) (s₂ : multiset α) : sup (s₁ + s₂) = sup s₁ ⊔ sup s₂ := sorry theorem sup_le {α : Type u_1} [semilattice_sup_bot α] {s : multiset α} {a : α} : sup s ≤ a ↔ ∀ (b : α), b ∈ s → b ≤ a := sorry theorem le_sup {α : Type u_1} [semilattice_sup_bot α] {s : multiset α} {a : α} (h : a ∈ s) : a ≤ sup s := iff.mp sup_le (le_refl (sup s)) a h theorem sup_mono {α : Type u_1} [semilattice_sup_bot α] {s₁ : multiset α} {s₂ : multiset α} (h : s₁ ⊆ s₂) : sup s₁ ≤ sup s₂ := iff.mpr sup_le fun (b : α) (hb : b ∈ s₁) => le_sup (h hb) @[simp] theorem sup_erase_dup {α : Type u_1} [semilattice_sup_bot α] [DecidableEq α] (s : multiset α) : sup (erase_dup s) = sup s := fold_erase_dup_idem has_sup.sup s ⊥ @[simp] theorem sup_ndunion {α : Type u_1} [semilattice_sup_bot α] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) : sup (ndunion s₁ s₂) = sup s₁ ⊔ sup s₂ := sorry @[simp] theorem sup_union {α : Type u_1} [semilattice_sup_bot α] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) : sup (s₁ ∪ s₂) = sup s₁ ⊔ sup s₂ := sorry @[simp] theorem sup_ndinsert {α : Type u_1} [semilattice_sup_bot α] [DecidableEq α] (a : α) (s : multiset α) : sup (ndinsert a s) = a ⊔ sup s := sorry /-! ### inf -/ /-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/ def inf {α : Type u_1} [semilattice_inf_top α] (s : multiset α) : α := fold has_inf.inf ⊤ s @[simp] theorem inf_zero {α : Type u_1} [semilattice_inf_top α] : inf 0 = ⊤ := fold_zero has_inf.inf ⊤ @[simp] theorem inf_cons {α : Type u_1} [semilattice_inf_top α] (a : α) (s : multiset α) : inf (a ::ₘ s) = a ⊓ inf s := fold_cons_left has_inf.inf ⊤ a s @[simp] theorem inf_singleton {α : Type u_1} [semilattice_inf_top α] {a : α} : inf (a ::ₘ 0) = a := sorry @[simp] theorem inf_add {α : Type u_1} [semilattice_inf_top α] (s₁ : multiset α) (s₂ : multiset α) : inf (s₁ + s₂) = inf s₁ ⊓ inf s₂ := sorry theorem le_inf {α : Type u_1} [semilattice_inf_top α] {s : multiset α} {a : α} : a ≤ inf s ↔ ∀ (b : α), b ∈ s → a ≤ b := sorry theorem inf_le {α : Type u_1} [semilattice_inf_top α] {s : multiset α} {a : α} (h : a ∈ s) : inf s ≤ a := iff.mp le_inf (le_refl (inf s)) a h theorem inf_mono {α : Type u_1} [semilattice_inf_top α] {s₁ : multiset α} {s₂ : multiset α} (h : s₁ ⊆ s₂) : inf s₂ ≤ inf s₁ := iff.mpr le_inf fun (b : α) (hb : b ∈ s₁) => inf_le (h hb) @[simp] theorem inf_erase_dup {α : Type u_1} [semilattice_inf_top α] [DecidableEq α] (s : multiset α) : inf (erase_dup s) = inf s := fold_erase_dup_idem has_inf.inf s ⊤ @[simp] theorem inf_ndunion {α : Type u_1} [semilattice_inf_top α] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) : inf (ndunion s₁ s₂) = inf s₁ ⊓ inf s₂ := sorry @[simp] theorem inf_union {α : Type u_1} [semilattice_inf_top α] [DecidableEq α] (s₁ : multiset α) (s₂ : multiset α) : inf (s₁ ∪ s₂) = inf s₁ ⊓ inf s₂ := sorry @[simp] theorem inf_ndinsert {α : Type u_1} [semilattice_inf_top α] [DecidableEq α] (a : α) (s : multiset α) : inf (ndinsert a s) = a ⊓ inf s := sorry end Mathlib
d37f8cabf007f4bda61a17277e6cede68f385b35
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/order/rel_classes.lean
d6a165327257e3b1af91523435bcbf54de65e0dd
[ "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
14,218
lean
/- Copyright (c) 2020 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Yury G. Kudryashov -/ import order.basic /-! # Unbundled relation classes In this file we prove some properties of `is_*` classes defined in `init.algebra.classes`. The main difference between these classes and the usual order classes (`preorder` etc) is that usual classes extend `has_le` and/or `has_lt` while these classes take a relation as an explicit argument. -/ universes u v variables {α : Type u} {β : Type v} {r : α → α → Prop} {s : β → β → Prop} open function theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩ theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) := ⟨λ a b h₁ h₂, antisymm h₂ h₁⟩ theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) := ⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩ theorem is_total.swap (r) [is_total α r] : is_total α (swap r) := ⟨λ a b, (total_of r a b).swap⟩ theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩ theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) := {..@is_refl.swap α r _, ..@is_trans.swap α r _} theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..@is_irrefl.swap α r _, ..@is_trans.swap α r _} theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) := {..@is_preorder.swap α r _, ..@is_antisymm.swap α r _} theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) := {..@is_preorder.swap α r _, ..@is_total.swap α r _} theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) := {..@is_partial_order.swap α r _, ..@is_total.swap α r _} protected theorem is_asymm.is_antisymm (r) [is_asymm α r] : is_antisymm α r := ⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩ protected theorem is_asymm.is_irrefl [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ /- Convert algebraic structure style to explicit relation style typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ instance [preorder α] : is_refl α (≥) := is_refl.swap _ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ instance [preorder α] : is_trans α (≥) := is_trans.swap _ instance [preorder α] : is_preorder α (≤) := {} instance [preorder α] : is_preorder α (≥) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ instance [preorder α] : is_trans α (>) := is_trans.swap _ instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ instance [preorder α] : is_asymm α (>) := is_asymm.swap _ instance [preorder α] : is_antisymm α (<) := is_asymm.is_antisymm _ instance [preorder α] : is_antisymm α (>) := is_asymm.is_antisymm _ instance [preorder α] : is_strict_order α (<) := {} instance [preorder α] : is_strict_order α (>) := {} instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _ instance [partial_order α] : is_partial_order α (≤) := {} instance [partial_order α] : is_partial_order α (≥) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ instance [linear_order α] : is_total α (≥) := is_total.swap _ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance instance [linear_order α] : is_total_preorder α (≥) := {} instance [linear_order α] : is_linear_order α (≤) := {} instance [linear_order α] : is_linear_order α (≥) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _ instance order_dual.is_total_le [has_le α] [is_total α (≤)] : is_total (order_dual α) (≤) := @is_total.swap α _ _ lemma ne_of_irrefl {r} [is_irrefl α r] : ∀ {x y : α}, r x y → x ≠ y | _ _ h rfl := irrefl _ h lemma trans_trichotomous_left [is_trans α r] [is_trichotomous α r] {a b c : α} : ¬r b a → r b c → r a c := begin intros h₁ h₂, rcases trichotomous_of r a b with h₃|h₃|h₃, exact trans h₃ h₂, rw h₃, exact h₂, exfalso, exact h₁ h₃ end lemma trans_trichotomous_right [is_trans α r] [is_trichotomous α r] {a b c : α} : r a b → ¬r c b → r a c := begin intros h₁ h₂, rcases trichotomous_of r b c with h₃|h₃|h₃, exact trans h₁ h₃, rw ←h₃, exact h₁, exfalso, exact h₂ h₃ end /-- Construct a partial order from a `is_strict_order` relation -/ def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } /-- This is basically the same as `is_strict_total_order`, but that definition is in Type (probably by mistake) and also has redundant assumptions. -/ @[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop. /-- Construct a linear order from an `is_strict_total_order'` relation -/ def linear_order_of_STO' (r) [is_strict_total_order' α r] [Π x y, decidable (¬ r x y)] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, decidable_le := λ x y, decidable_of_iff (¬ r y x) ⟨λ h, ((trichotomous_of r y x).resolve_left h).imp eq.symm id, λ h, h.elim (λ h, h ▸ irrefl_of _ _) (asymm_of r)⟩, ..partial_order_of_SO r } theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} instance [linear_order α] : is_strict_total_order' α (<) := {} /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_asymm.is_irrefl α r _ } @[priority 100] -- see Note [lower instance priority] instance is_order_connected_of_is_strict_total_order' [is_strict_total_order' α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ @[priority 100] -- see Note [lower instance priority] instance is_strict_total_order_of_is_strict_total_order' [is_strict_total_order' α r] : is_strict_total_order α r := {..is_strict_weak_order_of_is_order_connected} instance [linear_order α] : is_strict_total_order α (<) := by apply_instance instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance /-- An extensional relation is one in which an element is determined by its set of predecessors. It is named for the `x ∈ y` relation in set theory, whose extensionality is one of the first axioms of ZFC. -/ @[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop := (ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b) @[priority 100] -- see Note [lower instance priority] instance is_extensional_of_is_strict_total_order' [is_strict_total_order' α r] : is_extensional α r := ⟨λ a b H, ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 (irrefl a)) .resolve_right $ mt (H _).1 (irrefl b)⟩ /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop := (wf : well_founded r) @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance /-- Construct a decidable linear order from a well-founded linear order. -/ noncomputable def is_well_order.linear_order (r : α → α → Prop) [is_well_order α r] : linear_order α := by { letI := λ x y, classical.dec (¬r x y), exact linear_order_of_STO' r } instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _, irrefl := λ a, id, trans := λ a b c, false.elim, wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ } instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩ instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous, irrefl := λ a, by cases a; simp; apply irrefl, trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans, wf := sum.lex_wf is_well_order.wf is_well_order.wf } instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h; [exact irrefl _ h, exact irrefl _ h], trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ (trans ab bc) }, { exact prod.lex.left _ _ ab }, { exact prod.lex.left _ _ bc }, { exact prod.lex.right _ (trans ab bc) } end, wf := prod.lex_wf is_well_order.wf is_well_order.wf } /-- An unbounded or cofinal set -/ def unbounded (r : α → α → Prop) (s : set α) : Prop := ∀ a, ∃ b ∈ s, ¬ r b a /-- A bounded or final set -/ def bounded (r : α → α → Prop) (s : set α) : Prop := ∃a, ∀ b ∈ s, r b a @[simp] lemma not_bounded_iff {r : α → α → Prop} (s : set α) : ¬bounded r s ↔ unbounded r s := begin classical, simp only [bounded, unbounded, not_forall, not_exists, exists_prop, not_and, not_not] end @[simp] lemma not_unbounded_iff {r : α → α → Prop} (s : set α) : ¬unbounded r s ↔ bounded r s := by { classical, rw [not_iff_comm, not_bounded_iff] } namespace prod instance is_refl_preimage_fst {r : α → α → Prop} [h : is_refl α r] : is_refl (α × α) (prod.fst ⁻¹'o r) := ⟨λ a, refl_of r a.1⟩ instance is_refl_preimage_snd {r : α → α → Prop} [h : is_refl α r] : is_refl (α × α) (prod.snd ⁻¹'o r) := ⟨λ a, refl_of r a.2⟩ instance is_trans_preimage_fst {r : α → α → Prop} [h : is_trans α r] : is_trans (α × α) (prod.fst ⁻¹'o r) := ⟨λ _ _ _, trans_of r⟩ instance is_trans_preimage_snd {r : α → α → Prop} [h : is_trans α r] : is_trans (α × α) (prod.snd ⁻¹'o r) := ⟨λ _ _ _, trans_of r⟩ end prod
849a2c28189d8c4e754306d120f2a8051ca05eed
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/thm95/modify_complex.lean
af33e7059bba52c254ecd8abcafb9e03732bd17f
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,612
lean
import algebra.homology.homological_complex import category_theory.preadditive.additive_functor namespace homological_complex open category_theory category_theory.limits variables {ι : Type} {V₁ V₂ : Type*} {c : complex_shape ι} variables [category V₁] [category V₂] [preadditive V₁] [preadditive V₂] -- this is of course functorial in `C`, see below @[simps] def modify (C : homological_complex V₁ c) (F : ι → V₁ ⥤ V₂) (α : Π i j, F i ⟶ F j) [Π i, (F i).additive] : homological_complex V₂ c := { X := λ i, (F i).obj (C.X i), d := λ i j, (F i).map (C.d i j) ≫ (α i j).app _, shape' := λ i j h, by rw [C.shape _ _ h, category_theory.functor.map_zero, zero_comp], d_comp_d' := λ i j k hij hjk, by simp only [nat_trans.naturality_assoc, ← functor.map_comp_assoc, category.assoc, C.d_comp_d, category_theory.functor.map_zero, zero_comp, comp_zero], } -- this is a generalization of `functor.map_homological_complex` @[simps { fully_applied := ff }] def modify_functor (F : ι → V₁ ⥤ V₂) (α : Π i j, F i ⟶ F j) [Π i, (F i).additive] : homological_complex V₁ c ⥤ homological_complex V₂ c := { obj := λ C, C.modify F α, map := λ C₁ C₂ f, { f := λ i, (F i).map (f.f i), comm' := begin intros i j hij, dsimp, rw [← category.assoc, ← (F i).map_comp, f.comm, (F i).map_comp, category.assoc, (α _ _).naturality, category.assoc], end }, map_id' := by { intros X, dsimp at *, simp at *, refl }, map_comp' := by { intros X Y Z f g, dsimp at *, simp at *, refl } } end homological_complex
20fbd7fa50e65fb9b05e1072abeb0be8485724b2
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/algebra/lattice.lean
30f70f78e7a2b30bc71c7b68c333c7b7384750d1
[ "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
4,099
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import .order namespace algebra variable {A : Type} /- lattices (we could split this to upper- and lower-semilattices, if needed) -/ structure lattice [class] (A : Type) extends weak_order A := (inf : A → A → A) (sup : A → A → A) (inf_le_left : ∀ a b, le (inf a b) a) (inf_le_right : ∀ a b, le (inf a b) b) (le_inf : ∀a b c, le c a → le c b → le c (inf a b)) (le_sup_left : ∀ a b, le a (sup a b)) (le_sup_right : ∀ a b, le b (sup a b)) (sup_le : ∀ a b c, le a c → le b c → le (sup a b) c) definition inf := @lattice.inf definition sup := @lattice.sup infix ` ⊓ `:70 := inf infix ` ⊔ `:65 := sup section variable [s : lattice A] include s theorem inf_le_left (a b : A) : a ⊓ b ≤ a := !lattice.inf_le_left theorem inf_le_right (a b : A) : a ⊓ b ≤ b := !lattice.inf_le_right theorem le_inf {a b c : A} (H₁ : c ≤ a) (H₂ : c ≤ b) : c ≤ a ⊓ b := !lattice.le_inf H₁ H₂ theorem le_sup_left (a b : A) : a ≤ a ⊔ b := !lattice.le_sup_left theorem le_sup_right (a b : A) : b ≤ a ⊔ b := !lattice.le_sup_right theorem sup_le {a b c : A} (H₁ : a ≤ c) (H₂ : b ≤ c) : a ⊔ b ≤ c := !lattice.sup_le H₁ H₂ /- inf -/ theorem eq_inf {a b c : A} (H₁ : c ≤ a) (H₂ : c ≤ b) (H₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) : c = a ⊓ b := le.antisymm (le_inf H₁ H₂) (H₃ !inf_le_left !inf_le_right) theorem inf.comm (a b : A) : a ⊓ b = b ⊓ a := eq_inf !inf_le_right !inf_le_left (λ c H₁ H₂, le_inf H₂ H₁) theorem inf.assoc (a b c : A) : (a ⊓ b) ⊓ c = a ⊓ (b ⊓ c) := begin apply eq_inf, { apply le.trans, apply inf_le_left, apply inf_le_left }, { apply le_inf, apply le.trans, apply inf_le_left, apply inf_le_right, apply inf_le_right }, { intros [d, H₁, H₂], apply le_inf, apply le_inf H₁, apply le.trans H₂, apply inf_le_left, apply le.trans H₂, apply inf_le_right } end theorem inf.left_comm (a b c : A) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) := binary.left_comm (@inf.comm A s) (@inf.assoc A s) a b c theorem inf.right_comm (a b c : A) : (a ⊓ b) ⊓ c = (a ⊓ c) ⊓ b := binary.right_comm (@inf.comm A s) (@inf.assoc A s) a b c theorem inf_self (a : A) : a ⊓ a = a := by apply eq.symm; apply eq_inf (le.refl a) !le.refl; intros; assumption theorem inf_eq_left {a b : A} (H : a ≤ b) : a ⊓ b = a := by apply eq.symm; apply eq_inf !le.refl H; intros; assumption theorem inf_eq_right {a b : A} (H : b ≤ a) : a ⊓ b = b := eq.subst !inf.comm (inf_eq_left H) /- sup -/ theorem eq_sup {a b c : A} (H₁ : a ≤ c) (H₂ : b ≤ c) (H₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = a ⊔ b := le.antisymm (H₃ !le_sup_left !le_sup_right) (sup_le H₁ H₂) theorem sup.comm (a b : A) : a ⊔ b = b ⊔ a := eq_sup !le_sup_right !le_sup_left (λ c H₁ H₂, sup_le H₂ H₁) theorem sup.assoc (a b c : A) : (a ⊔ b) ⊔ c = a ⊔ (b ⊔ c) := begin apply eq_sup, { apply le.trans, apply le_sup_left a b, apply le_sup_left }, { apply sup_le, apply le.trans, apply le_sup_right a b, apply le_sup_left, apply le_sup_right }, { intros [d, H₁, H₂], apply sup_le, apply sup_le H₁, apply le.trans !le_sup_left H₂, apply le.trans !le_sup_right H₂} end theorem sup.left_comm (a b c : A) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) := binary.left_comm (@sup.comm A s) (@sup.assoc A s) a b c theorem sup.right_comm (a b c : A) : (a ⊔ b) ⊔ c = (a ⊔ c) ⊔ b := binary.right_comm (@sup.comm A s) (@sup.assoc A s) a b c theorem sup_self (a : A) : a ⊔ a = a := by apply eq.symm; apply eq_sup (le.refl a) !le.refl; intros; assumption theorem sup_eq_left {a b : A} (H : b ≤ a) : a ⊔ b = a := by apply eq.symm; apply eq_sup !le.refl H; intros; assumption theorem sup_eq_right {a b : A} (H : a ≤ b) : a ⊔ b = b := eq.subst !sup.comm (sup_eq_left H) end end algebra
e0286e4da4f26811b06a5e82518893536a8f8edf
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/group_theory/congruence.lean
f78a2af87d12eb72cdd00c1b27b926dbf7104407
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
48,299
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.group.pi import algebra.group.prod import data.equiv.mul_add import group_theory.submonoid.operations /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) /-- The equivalence relation underlying an additive congruence relation. -/ add_decl_doc add_con.to_setoid /-- The equivalence relation underlying a multiplicative congruence relation. -/ add_decl_doc con.to_setoid variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) (λ _, M → M → Prop) := ⟨λ c, λ x y, @setoid.r _ c.to_setoid x y⟩ @[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.to_setoid.refl' x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.to_setoid.symm' h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.to_setoid.trans' h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.mul' h1 h2 @[simp, to_additive] lemma rel_mk {s : setoid M} {h a b} : con.mk s h a b ↔ r a b := iff.rfl /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by { rcases c with ⟨⟨⟩⟩, rcases d with ⟨⟨⟩⟩, cases H, congr, } /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { to_setoid := setoid.ker f, mul' := λ _ _ _ _ h1 h2, by { dsimp [setoid.ker, on_fun] at *, rw [h, h1, h2, h], } } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient by a decidable congruence relation has decidable equality. -/ @[to_additive "The quotient by a decidable additive congruence relation has decidable equality.", priority 500] -- Lower the priority since it unifies with any quotient type. instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d @[simp, to_additive] lemma quot_mk_eq_coe {M : Type*} [has_mul M] (c : con M) (x : M) : quot.mk c x = (x : c.quotient) := rfl /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h /-- A version of `quotient.hrec_on₂'` for quotients by `con`. -/ @[to_additive "A version of `quotient.hrec_on₂'` for quotients by `add_con`."] protected def hrec_on₂ {cM : con M} {cN : con N} {φ : cM.quotient → cN.quotient → Sort*} (a : cM.quotient) (b : cN.quotient) (f : Π (x : M) (y : N), φ x y) (h : ∀ x y x' y', cM x x' → cN y y' → f x y == f x' y') : φ a b := quotient.hrec_on₂' a b f h @[simp, to_additive] lemma hrec_on₂_coe {cM : con M} {cN : con N} {φ : cM.quotient → cN.quotient → Sort*} (a : M) (b : N) (f : Π (x : M) (y : N), φ x y) (h : ∀ x y x' y', cM x x' → cN y y' → f x y == f x' y') : con.hrec_on₂ ↑a ↑b f h = f a b := rfl variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_coe {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : ⇑(Inf S) = Inf (@set.image (con M) (M → M → Prop) coe_fn S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid), λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → @setoid.r _ c.to_setoid x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (@set.image (con M) (M → M → Prop) coe_fn S)) := begin rw [Sup_eq_con_gen, Sup_image], congr' with x y, simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe] end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected noncomputable def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen coe_fn := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } @[simp, to_additive] lemma comap_rel {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) {c : con N} {x y : M} : comap f H c x y ↔ c (f x) (f y) := iff.rfl section open _root_.quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : {d // c ≤ d} ≃o (con c.quotient) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy, λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ } end end section mul_one_class variables {M} [mul_one_class M] [mul_one_class N] [mul_one_class P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance mul_one_class : mul_one_class c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[simp, to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := quotient.surjective_quotient_mk' @[simp, to_additive] lemma coe_mk' : (c.mk' : M → c.quotient) = coe := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by { subst f, refl } /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨by rintros ⟨⟨y⟩, hy⟩; exact ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨↑y, hy⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a homomorphism with right inverse. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a homomorphism with right inverse.", simps] def quotient_ker_equiv_of_right_inverse (f : M →* P) (g : P → M) (hf : function.right_inverse g f) : (ker f).quotient ≃* P := { to_fun := ker_lift f, inv_fun := coe ∘ g, left_inv := λ x, ker_lift_injective _ (by rw [function.comp_app, ker_lift_mk, hf]), right_inv := hf, .. ker_lift f } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. For a `computable` version, see `con.quotient_ker_equiv_of_right_inverse`. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism. For a `computable` version, see `add_con.quotient_ker_equiv_of_right_inverse`. "] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := quotient_ker_equiv_of_right_inverse _ _ hf.has_right_inverse.some_spec /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end mul_one_class section monoids /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid {M : Type*} [monoid M] (c : con M): monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, .. c.mul_one_class } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {M : Type*} [comm_monoid M] (c : con M) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} end monoids section groups variables {M} [group M] [group N] [group P] (c : con M) /-- Multiplicative congruence relations preserve inversion. -/ @[to_additive "Additive congruence relations preserve negation."] protected lemma inv : ∀ {w x}, c w x → c w⁻¹ x⁻¹ := λ x y h, by simpa using c.symm (c.mul (c.mul (c.refl x⁻¹) h) (c.refl y⁻¹)) /-- The inversion induced on the quotient by a congruence relation on a type with a inversion. -/ @[to_additive "The negation induced on the quotient by an additive congruence relation on a type with an negation."] instance has_inv : has_inv c.quotient := ⟨λ x, quotient.lift_on' x (λ w, ((w⁻¹ : M) : c.quotient)) $ λ x y h, c.eq.2 $ c.inv h⟩ /-- The quotient of a group by a congruence relation is a group. -/ @[to_additive "The quotient of an `add_group` by an additive congruence relation is an `add_group`."] instance group : group c.quotient := { inv := λ x, x⁻¹, mul_left_inv := λ x, show x⁻¹ * x = 1, from quotient.induction_on' x $ λ _, congr_arg coe $ mul_left_inv _, .. con.monoid c} end groups section units variables {α : Type*} [monoid M] {c : con M} /-- In order to define a function `units (con.quotient c) → α` on the units of `con.quotient c`, where `c : con M` is a multiplicative congruence on a monoid, it suffices to define a function `f` that takes elements `x y : M` with proofs of `c (x * y) 1` and `c (y * x) 1`, and returns an element of `α` provided that `f x y _ _ = f x' y' _ _` whenever `c x x'` and `c y y'`. -/ @[to_additive lift_on_add_units] def lift_on_units (u : units c.quotient) (f : Π (x y : M), c (x * y) 1 → c (y * x) 1 → α) (Hf : ∀ x y hxy hyx x' y' hxy' hyx', c x x' → c y y' → f x y hxy hyx = f x' y' hxy' hyx') : α := begin refine @con.hrec_on₂ M M _ _ c c (λ x y, x * y = 1 → y * x = 1 → α) (u : c.quotient) (↑u⁻¹ : c.quotient) (λ (x y : M) (hxy : (x * y : c.quotient) = 1) (hyx : (y * x : c.quotient) = 1), f x y (c.eq.1 hxy) (c.eq.1 hyx)) (λ x y x' y' hx hy, _) u.3 u.4, ext1, { rw [c.eq.2 hx, c.eq.2 hy] }, rintro Hxy Hxy' -, ext1, { rw [c.eq.2 hx, c.eq.2 hy] }, rintro Hyx Hyx' -, exact heq_of_eq (Hf _ _ _ _ _ _ _ _ hx hy) end /-- In order to define a function `units (con.quotient c) → α` on the units of `con.quotient c`, where `c : con M` is a multiplicative congruence on a monoid, it suffices to define a function `f` that takes elements `x y : M` with proofs of `c (x * y) 1` and `c (y * x) 1`, and returns an element of `α` provided that `f x y _ _ = f x' y' _ _` whenever `c x x'` and `c y y'`. -/ add_decl_doc add_con.lift_on_add_units @[simp, to_additive] lemma lift_on_units_mk (f : Π (x y : M), c (x * y) 1 → c (y * x) 1 → α) (Hf : ∀ x y hxy hyx x' y' hxy' hyx', c x x' → c y y' → f x y hxy hyx = f x' y' hxy' hyx') (x y : M) (hxy hyx) : lift_on_units ⟨(x : c.quotient), y, hxy, hyx⟩ f Hf = f x y (c.eq.1 hxy) (c.eq.1 hyx) := rfl @[elab_as_eliminator, to_additive induction_on_add_units] lemma induction_on_units {p : units c.quotient → Prop} (u : units c.quotient) (H : ∀ (x y : M) (hxy : c (x * y) 1) (hyx : c (y * x) 1), p ⟨x, y, c.eq.2 hxy, c.eq.2 hyx⟩) : p u := begin rcases u with ⟨⟨x⟩, ⟨y⟩, h₁, h₂⟩, exact H x y (c.eq.1 h₁) (c.eq.1 h₂) end end units end con
5d45fb113703b962438f2d3e3a693d907f3f4f48
e38d5e91d30731bef617cc9b6de7f79c34cdce9a
/src/core/connection/meet.lean
7327700169fe131086fb223eeefcc73141429343
[ "Apache-2.0" ]
permissive
bbentzen/cubicalean
55e979c303fbf55a81ac46b1000c944b2498be7a
3b94cd2aefdfc2163c263bd3fc6f2086fef814b5
refs/heads/master
1,588,314,875,258
1,554,412,699,000
1,554,412,699,000
177,333,390
0
0
null
null
null
null
UTF-8
Lean
false
false
3,321
lean
/- Copyright (c) 2019 Bruno Bentzen. All rights reserved. Released under the Apache License 2.0 (see "License"); Author: Bruno Bentzen -/ import logic.function ...path.groupoid.ops open interval -- the meet connection def meet.horn {A : Type} (kan : has_hcom2 A) (p : I → A) : horn2 A := let u := horn1.mk (λ _, p i0) (λ _, p i0) p rfl rfl in let meet' := kan.has1.hcom u in horn2.mk (λ _ _, p i0) (λ _ _, p i0) (λ j i, meet' i j) (λ _ _, p i0) (λ j i, meet' i j) rfl ((kan.has1.t0 u).symm) rfl ((kan.has1.t0 u).symm) rfl ((kan.has1.lid u).symm) (kan.has1.lid u) rfl def meet.filler {A : Type} (kan : has_hcom2 A) (p : I → A) : I → I → I → A := kan.hcom2 (meet.horn kan p) def meet {A : Type} (kan : has_hcom2 A) (p : I → A) : I → I → A := (meet.filler kan p) i1 --notation p `[` j `∧` i `]` kan := meet kan p j i namespace meet lemma face0j {A : Type} (kan : has_hcom2 A) (p : I → A) : meet kan p i0 = λ _, p i0 := kan.eq0j (meet.horn kan p) lemma face1j {A : Type} (kan : has_hcom2 A) (p : I → A) : meet kan p i1 = p := begin transitivity, apply kan.eq1j (meet.horn kan p), apply (kan.has1.t1 (horn1.mk (λ _, p i0) (λ _, p i0) p rfl rfl)) end lemma face0i {A : Type} (kan : has_hcom2 A) (p : I → A) : (λ i, meet kan p i i0) = λ _, p i0 := kan.eq0i (meet.horn kan p) lemma face0i' {A : Type} (kan : has_hcom2 A) (p : I → A) (i : I) : meet kan p i i0 = p i0 := by revert i; apply function.funext_iff.1; apply face0i lemma face1i {A : Type} (kan : has_hcom2 A) (p : I → A) : (λ j, meet kan p j i1) = p := begin transitivity, apply kan.eq1i (meet.horn kan p), apply (kan.has1.t1 (horn1.mk (λ _, p i0) (λ _, p i0) p rfl rfl)) end lemma face1i' {A : Type} (kan : has_hcom2 A) (p : I → A) (i : I) : meet kan p i i1 = p i := by revert i; apply function.funext_iff.1; apply face1i lemma face0j0i {A : Type} (kan : has_hcom2 A) (p : I → A) : meet kan p i0 i0 = ( λ _, p i0) i0 := by apply function.funext_iff.1; apply face0j lemma face0j1i {A : Type} (kan : has_hcom2 A) (p : I → A) : meet kan p i0 i1 = ( λ _, p i0) i1 := by apply function.funext_iff.1; apply face0j lemma face1j0i {A : Type} (kan : has_hcom2 A) (p : I → A) : meet kan p i1 i0 = p i0 := by rw face1j lemma face1j1i {A : Type} (kan : has_hcom2 A) (p : I → A) : meet kan p i1 i1 = p i1 := by rw face1j end meet /- λ _, p i1 --> i p i1 ================== p i0 j | || | v || | || | λ _, p i1 || meet p j i | p || | || | || v p i1 -----------------> p i1 p -/ namespace refl open path lemma meet {A : Type} {a b : A} (kan : has_hcom2 A) (p : path A a b) : path.refl a = abs (meet kan (app p) i0) (eq.trans (meet.face0j0i kan (app p)) (app0 p)) (eq.trans (meet.face0j1i kan (app p)) (app0 p)) := begin apply eq, transitivity, apply meet.face0j kan (app p), apply funext, intro, apply path.app0 end end refl
a4ae65120f2182e1ed033c2c9eae7f9167fbf736
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1057.lean
790677c0962626ea26544315e84eab167bd020c8
[ "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
166
lean
inductive T | t : T @[reducible] def T.eval : T → Type | T.t => Int def T.default (τ : T) : τ.eval := match τ, τ.eval with | T.t, .(Int) => (0 : Int)
864b6d16eec688e7cdc0fadabbbacd2d267a8f1d
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/data/indicator_function.lean
36eeab71baa822bda55e84440ac1052d9958802c
[ "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
19,969
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.group.pi import group_theory.group_action import data.support import data.finset.lattice /-! # Indicator function - `indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `0` otherwise. - `mul_indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `1` otherwise. ## Implementation note In mathematics, an indicator function or a characteristic function is a function used to indicate membership of an element in a set `s`, having the value `1` for all elements of `s` and the value `0` otherwise. But since it is usually used to restrict a function to a certain set `s`, we let the indicator function take the value `f x` for some function `f`, instead of `1`. If the usual indicator function is needed, just set `f` to be the constant function `λx, 1`. ## Tags indicator, characteristic -/ noncomputable theory open_locale classical big_operators open function variables {α β ι M N : Type*} namespace set section has_one variables [has_one M] [has_one N] {s t : set α} {f g : α → M} {a : α} /-- `indicator s f a` is `f a` if `a ∈ s`, `0` otherwise. -/ def indicator {M} [has_zero M] (s : set α) (f : α → M) : α → M := λ x, if x ∈ s then f x else 0 /-- `mul_indicator s f a` is `f a` if `a ∈ s`, `1` otherwise. -/ @[to_additive] def mul_indicator (s : set α) (f : α → M) : α → M := λ x, if x ∈ s then f x else 1 @[simp, to_additive] lemma piecewise_eq_mul_indicator : s.piecewise f 1 = s.mul_indicator f := rfl @[to_additive] lemma mul_indicator_apply (s : set α) (f : α → M) (a : α) : mul_indicator s f a = if a ∈ s then f a else 1 := rfl @[simp, to_additive] lemma mul_indicator_of_mem (h : a ∈ s) (f : α → M) : mul_indicator s f a = f a := if_pos h @[simp, to_additive] lemma mul_indicator_of_not_mem (h : a ∉ s) (f : α → M) : mul_indicator s f a = 1 := if_neg h @[to_additive] lemma mul_indicator_eq_one_or_self (s : set α) (f : α → M) (a : α) : mul_indicator s f a = 1 ∨ mul_indicator s f a = f a := if h : a ∈ s then or.inr (mul_indicator_of_mem h f) else or.inl (mul_indicator_of_not_mem h f) @[simp, to_additive] lemma mul_indicator_apply_eq_self : s.mul_indicator f a = f a ↔ (a ∉ s → f a = 1) := ite_eq_left_iff.trans $ by rw [@eq_comm _ (f a)] @[simp, to_additive] lemma mul_indicator_eq_self : s.mul_indicator f = f ↔ mul_support f ⊆ s := by simp only [funext_iff, subset_def, mem_mul_support, mul_indicator_apply_eq_self, not_imp_comm] @[to_additive] lemma mul_indicator_eq_self_of_superset (h1 : s.mul_indicator f = f) (h2 : s ⊆ t) : t.mul_indicator f = f := by { rw mul_indicator_eq_self at h1 ⊢, exact subset.trans h1 h2 } @[simp, to_additive] lemma mul_indicator_apply_eq_one : mul_indicator s f a = 1 ↔ (a ∈ s → f a = 1) := ite_eq_right_iff @[simp, to_additive] lemma mul_indicator_eq_one : mul_indicator s f = (λ x, 1) ↔ disjoint (mul_support f) s := by simp only [funext_iff, mul_indicator_apply_eq_one, set.disjoint_left, mem_mul_support, not_imp_not] @[simp, to_additive] lemma mul_indicator_eq_one' : mul_indicator s f = 1 ↔ disjoint (mul_support f) s := mul_indicator_eq_one @[simp, to_additive] lemma mul_support_mul_indicator : function.mul_support (s.mul_indicator f) = s ∩ function.mul_support f := ext $ λ x, by simp [function.mem_mul_support, mul_indicator_apply_eq_one] /-- If a multiplicative indicator function is not equal to one at a point, then that point is in the set. -/ @[to_additive] lemma mem_of_mul_indicator_ne_one (h : mul_indicator s f a ≠ 1) : a ∈ s := not_imp_comm.1 (λ hn, mul_indicator_of_not_mem hn f) h @[to_additive] lemma eq_on_mul_indicator : eq_on (mul_indicator s f) f s := λ x hx, mul_indicator_of_mem hx f @[to_additive] lemma mul_support_mul_indicator_subset : mul_support (s.mul_indicator f) ⊆ s := λ x hx, hx.imp_symm (λ h, mul_indicator_of_not_mem h f) @[simp, to_additive] lemma mul_indicator_mul_support : mul_indicator (mul_support f) f = f := mul_indicator_eq_self.2 subset.rfl @[simp, to_additive] lemma mul_indicator_range_comp {ι : Sort*} (f : ι → α) (g : α → M) : mul_indicator (range f) g ∘ f = g ∘ f := piecewise_range_comp _ _ _ @[to_additive] lemma mul_indicator_congr (h : eq_on f g s) : mul_indicator s f = mul_indicator s g := funext $ λx, by { simp only [mul_indicator], split_ifs, { exact h h_1 }, refl } @[simp, to_additive] lemma mul_indicator_univ (f : α → M) : mul_indicator (univ : set α) f = f := mul_indicator_eq_self.2 $ subset_univ _ @[simp, to_additive] lemma mul_indicator_empty (f : α → M) : mul_indicator (∅ : set α) f = λa, 1 := mul_indicator_eq_one.2 $ disjoint_empty _ variable (M) @[simp, to_additive] lemma mul_indicator_one (s : set α) : mul_indicator s (λx, (1:M)) = λx, (1:M) := mul_indicator_eq_one.2 $ by simp only [mul_support_one, empty_disjoint] @[simp, to_additive] lemma mul_indicator_one' {s : set α} : s.mul_indicator (1 : α → M) = 1 := mul_indicator_one M s variable {M} @[to_additive] lemma mul_indicator_mul_indicator (s t : set α) (f : α → M) : mul_indicator s (mul_indicator t f) = mul_indicator (s ∩ t) f := funext $ λx, by { simp only [mul_indicator], split_ifs, repeat {simp * at * {contextual := tt}} } @[simp, to_additive] lemma mul_indicator_inter_mul_support (s : set α) (f : α → M) : mul_indicator (s ∩ mul_support f) f = mul_indicator s f := by rw [← mul_indicator_mul_indicator, mul_indicator_mul_support] @[to_additive] lemma comp_mul_indicator (h : M → β) (f : α → M) {s : set α} {x : α} : h (s.mul_indicator f x) = s.piecewise (h ∘ f) (const α (h 1)) x := s.apply_piecewise _ _ (λ _, h) @[to_additive] lemma mul_indicator_comp_right {s : set α} (f : β → α) {g : α → M} {x : β} : mul_indicator (f ⁻¹' s) (g ∘ f) x = mul_indicator s g (f x) := by { simp only [mul_indicator], split_ifs; refl } @[to_additive] lemma mul_indicator_comp_of_one {g : M → N} (hg : g 1 = 1) : mul_indicator s (g ∘ f) = g ∘ (mul_indicator s f) := begin funext, simp only [mul_indicator], split_ifs; simp [*] end @[to_additive] lemma mul_indicator_preimage (s : set α) (f : α → M) (B : set M) : (mul_indicator s f)⁻¹' B = s.ite (f ⁻¹' B) (1 ⁻¹' B) := piecewise_preimage s f 1 B @[to_additive] lemma mul_indicator_preimage_of_not_mem (s : set α) (f : α → M) {t : set M} (ht : (1:M) ∉ t) : (mul_indicator s f)⁻¹' t = f ⁻¹' t ∩ s := by simp [mul_indicator_preimage, pi.one_def, set.preimage_const_of_not_mem ht] @[to_additive] lemma mem_range_mul_indicator {r : M} {s : set α} {f : α → M} : r ∈ range (mul_indicator s f) ↔ (r = 1 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by simp [mul_indicator, ite_eq_iff, exists_or_distrib, eq_univ_iff_forall, and_comm, or_comm, @eq_comm _ r 1] @[to_additive] lemma mul_indicator_rel_mul_indicator {r : M → M → Prop} (h1 : r 1 1) (ha : a ∈ s → r (f a) (g a)) : r (mul_indicator s f a) (mul_indicator s g a) := by { simp only [mul_indicator], split_ifs with has has, exacts [ha has, h1] } end has_one section monoid variables [mul_one_class M] {s t : set α} {f g : α → M} {a : α} @[to_additive] lemma mul_indicator_union_mul_inter_apply (f : α → M) (s t : set α) (a : α) : mul_indicator (s ∪ t) f a * mul_indicator (s ∩ t) f a = mul_indicator s f a * mul_indicator t f a := by by_cases hs : a ∈ s; by_cases ht : a ∈ t; simp * @[to_additive] lemma mul_indicator_union_mul_inter (f : α → M) (s t : set α) : mul_indicator (s ∪ t) f * mul_indicator (s ∩ t) f = mul_indicator s f * mul_indicator t f := funext $ mul_indicator_union_mul_inter_apply f s t @[to_additive] lemma mul_indicator_union_of_not_mem_inter (h : a ∉ s ∩ t) (f : α → M) : mul_indicator (s ∪ t) f a = mul_indicator s f a * mul_indicator t f a := by rw [← mul_indicator_union_mul_inter_apply f s t, mul_indicator_of_not_mem h, mul_one] @[to_additive] lemma mul_indicator_union_of_disjoint (h : disjoint s t) (f : α → M) : mul_indicator (s ∪ t) f = λa, mul_indicator s f a * mul_indicator t f a := funext $ λa, mul_indicator_union_of_not_mem_inter (λ ha, h ha) _ @[to_additive] lemma mul_indicator_mul (s : set α) (f g : α → M) : mul_indicator s (λa, f a * g a) = λa, mul_indicator s f a * mul_indicator s g a := by { funext, simp only [mul_indicator], split_ifs, { refl }, rw mul_one } @[simp, to_additive] lemma mul_indicator_compl_mul_self_apply (s : set α) (f : α → M) (a : α) : mul_indicator sᶜ f a * mul_indicator s f a = f a := classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha]) @[simp, to_additive] lemma mul_indicator_compl_mul_self (s : set α) (f : α → M) : mul_indicator sᶜ f * mul_indicator s f = f := funext $ mul_indicator_compl_mul_self_apply s f @[simp, to_additive] lemma mul_indicator_self_mul_compl_apply (s : set α) (f : α → M) (a : α) : mul_indicator s f a * mul_indicator sᶜ f a = f a := classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha]) @[simp, to_additive] lemma mul_indicator_self_mul_compl (s : set α) (f : α → M) : mul_indicator s f * mul_indicator sᶜ f = f := funext $ mul_indicator_self_mul_compl_apply s f @[to_additive] lemma mul_indicator_mul_eq_left {f g : α → M} (h : disjoint (mul_support f) (mul_support g)) : (mul_support f).mul_indicator (f * g) = f := begin refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support, have : g x = 1, from nmem_mul_support.1 (disjoint_left.1 h hx), rw [pi.mul_apply, this, mul_one] end @[to_additive] lemma mul_indicator_mul_eq_right {f g : α → M} (h : disjoint (mul_support f) (mul_support g)) : (mul_support g).mul_indicator (f * g) = g := begin refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support, have : f x = 1, from nmem_mul_support.1 (disjoint_right.1 h hx), rw [pi.mul_apply, this, one_mul] end /-- `set.mul_indicator` as a `monoid_hom`. -/ @[to_additive "`set.indicator` as an `add_monoid_hom`."] def mul_indicator_hom {α} (M) [mul_one_class M] (s : set α) : (α → M) →* (α → M) := { to_fun := mul_indicator s, map_one' := mul_indicator_one M s, map_mul' := mul_indicator_mul s } end monoid section distrib_mul_action variables {A : Type*} [add_monoid A] [monoid M] [distrib_mul_action M A] lemma indicator_smul (s : set α) (r : M) (f : α → A) : indicator s (λ (x : α), r • f x) = λ (x : α), r • indicator s f x := by { simp only [indicator], funext, split_ifs, refl, exact (smul_zero r).symm } end distrib_mul_action section group variables {G : Type*} [group G] {s t : set α} {f g : α → G} {a : α} @[to_additive] lemma mul_indicator_inv' (s : set α) (f : α → G) : mul_indicator s (f⁻¹) = (mul_indicator s f)⁻¹ := (mul_indicator_hom G s).map_inv f @[to_additive] lemma mul_indicator_inv (s : set α) (f : α → G) : mul_indicator s (λa, (f a)⁻¹) = λa, (mul_indicator s f a)⁻¹ := mul_indicator_inv' s f lemma indicator_sub {G} [add_group G] (s : set α) (f g : α → G) : indicator s (λa, f a - g a) = λa, indicator s f a - indicator s g a := (indicator_hom G s).map_sub f g @[to_additive indicator_compl'] lemma mul_indicator_compl (s : set α) (f : α → G) : mul_indicator sᶜ f = f * (mul_indicator s f)⁻¹ := eq_mul_inv_of_mul_eq $ s.mul_indicator_compl_mul_self f lemma indicator_compl {G} [add_group G] (s : set α) (f : α → G) : indicator sᶜ f = f - indicator s f := by rw [sub_eq_add_neg, indicator_compl'] @[to_additive indicator_diff'] lemma mul_indicator_diff (h : s ⊆ t) (f : α → G) : mul_indicator (t \ s) f = mul_indicator t f * (mul_indicator s f)⁻¹ := eq_mul_inv_of_mul_eq $ by rw [pi.mul_def, ← mul_indicator_union_of_disjoint disjoint_diff.symm f, diff_union_self, union_eq_self_of_subset_right h] lemma indicator_diff {G : Type*} [add_group G] {s t : set α} (h : s ⊆ t) (f : α → G) : indicator (t \ s) f = indicator t f - indicator s f := by rw [indicator_diff' h, sub_eq_add_neg] end group section comm_monoid variables [comm_monoid M] /-- Consider a product of `g i (f i)` over a `finset`. Suppose `g` is a function such as `pow`, which maps a second argument of `1` to `1`. Then if `f` is replaced by the corresponding multiplicative indicator function, the `finset` may be replaced by a possibly larger `finset` without changing the value of the sum. -/ @[to_additive] lemma prod_mul_indicator_subset_of_eq_one [has_one N] (f : α → N) (g : α → N → M) {s t : finset α} (h : s ⊆ t) (hg : ∀ a, g a 1 = 1) : ∏ i in s, g i (f i) = ∏ i in t, g i (mul_indicator ↑s f i) := begin rw ← finset.prod_subset h _, { apply finset.prod_congr rfl, intros i hi, congr, symmetry, exact mul_indicator_of_mem hi _ }, { refine λ i hi hn, _, convert hg i, exact mul_indicator_of_not_mem hn _ } end /-- Consider a sum of `g i (f i)` over a `finset`. Suppose `g` is a function such as multiplication, which maps a second argument of 0 to 0. (A typical use case would be a weighted sum of `f i * h i` or `f i • h i`, where `f` gives the weights that are multiplied by some other function `h`.) Then if `f` is replaced by the corresponding indicator function, the `finset` may be replaced by a possibly larger `finset` without changing the value of the sum. -/ add_decl_doc set.sum_indicator_subset_of_eq_zero @[to_additive] lemma prod_mul_indicator_subset (f : α → M) {s t : finset α} (h : s ⊆ t) : ∏ i in s, f i = ∏ i in t, mul_indicator ↑s f i := prod_mul_indicator_subset_of_eq_one _ (λ a b, b) h (λ _, rfl) /-- Summing an indicator function over a possibly larger `finset` is the same as summing the original function over the original `finset`. -/ add_decl_doc sum_indicator_subset @[to_additive] lemma mul_indicator_finset_prod (I : finset ι) (s : set α) (f : ι → α → M) : mul_indicator s (∏ i in I, f i) = ∏ i in I, mul_indicator s (f i) := (mul_indicator_hom M s).map_prod _ _ @[to_additive] lemma mul_indicator_finset_bUnion {ι} (I : finset ι) (s : ι → set α) {f : α → M} : (∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) → mul_indicator (⋃ i ∈ I, s i) f = λ a, ∏ i in I, mul_indicator (s i) f a := begin refine finset.induction_on I _ _, { intro h, funext, simp }, assume a I haI ih hI, funext, rw [finset.prod_insert haI, finset.set_bUnion_insert, mul_indicator_union_of_not_mem_inter, ih _], { assume i hi j hj hij, exact hI i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj) hij }, simp only [not_exists, exists_prop, mem_Union, mem_inter_eq, not_and], assume hx a' ha', refine disjoint_left.1 (hI a (finset.mem_insert_self _ _) a' (finset.mem_insert_of_mem ha') _) hx, exact (ne_of_mem_of_not_mem ha' haI).symm end end comm_monoid section mul_zero_class variables [mul_zero_class M] {s t : set α} {f g : α → M} {a : α} lemma indicator_mul (s : set α) (f g : α → M) : indicator s (λa, f a * g a) = λa, indicator s f a * indicator s g a := by { funext, simp only [indicator], split_ifs, { refl }, rw mul_zero } lemma indicator_mul_left (s : set α) (f g : α → M) : indicator s (λa, f a * g a) a = indicator s f a * g a := by { simp only [indicator], split_ifs, { refl }, rw [zero_mul] } lemma indicator_mul_right (s : set α) (f g : α → M) : indicator s (λa, f a * g a) a = f a * indicator s g a := by { simp only [indicator], split_ifs, { refl }, rw [mul_zero] } lemma inter_indicator_mul {t1 t2 : set α} (f g : α → M) (x : α) : (t1 ∩ t2).indicator (λ x, f x * g x) x = t1.indicator f x * t2.indicator g x := by { rw [← set.indicator_indicator], simp [indicator] } end mul_zero_class section monoid_with_zero variables [monoid_with_zero M] lemma indicator_prod_one {s : set α} {t : set β} {x : α} {y : β} : (s.prod t).indicator (1 : _ → M) (x, y) = s.indicator 1 x * t.indicator 1 y := by simp [indicator, ← ite_and] end monoid_with_zero section order variables [has_one M] [preorder M] {s t : set α} {f g : α → M} {a : α} {y : M} @[to_additive] lemma mul_indicator_apply_le' (hfg : a ∈ s → f a ≤ y) (hg : a ∉ s → 1 ≤ y) : mul_indicator s f a ≤ y := if ha : a ∈ s then by simpa [ha] using hfg ha else by simpa [ha] using hg ha @[to_additive] lemma mul_indicator_le' (hfg : ∀ a ∈ s, f a ≤ g a) (hg : ∀ a ∉ s, 1 ≤ g a) : mul_indicator s f ≤ g := λ a, mul_indicator_apply_le' (hfg _) (hg _) @[to_additive] lemma le_mul_indicator_apply {y} (hfg : a ∈ s → y ≤ g a) (hf : a ∉ s → y ≤ 1) : y ≤ mul_indicator s g a := @mul_indicator_apply_le' α (order_dual M) ‹_› _ _ _ _ _ hfg hf @[to_additive] lemma le_mul_indicator (hfg : ∀ a ∈ s, f a ≤ g a) (hf : ∀ a ∉ s, f a ≤ 1) : f ≤ mul_indicator s g := λ a, le_mul_indicator_apply (hfg _) (hf _) @[to_additive indicator_apply_nonneg] lemma one_le_mul_indicator_apply (h : a ∈ s → 1 ≤ f a) : 1 ≤ mul_indicator s f a := le_mul_indicator_apply h (λ _, le_rfl) @[to_additive indicator_nonneg] lemma one_le_mul_indicator (h : ∀ a ∈ s, 1 ≤ f a) (a : α) : 1 ≤ mul_indicator s f a := one_le_mul_indicator_apply (h a) @[to_additive] lemma mul_indicator_apply_le_one (h : a ∈ s → f a ≤ 1) : mul_indicator s f a ≤ 1 := mul_indicator_apply_le' h (λ _, le_rfl) @[to_additive] lemma mul_indicator_le_one (h : ∀ a ∈ s, f a ≤ 1) (a : α) : mul_indicator s f a ≤ 1 := mul_indicator_apply_le_one (h a) @[to_additive] lemma mul_indicator_le_mul_indicator (h : f a ≤ g a) : mul_indicator s f a ≤ mul_indicator s g a := mul_indicator_rel_mul_indicator (le_refl _) (λ _, h) attribute [mono] mul_indicator_le_mul_indicator indicator_le_indicator @[to_additive] lemma mul_indicator_le_mul_indicator_of_subset (h : s ⊆ t) (hf : ∀ a, 1 ≤ f a) (a : α) : mul_indicator s f a ≤ mul_indicator t f a := mul_indicator_apply_le' (λ ha, le_mul_indicator_apply (λ _, le_rfl) (λ hat, (hat $ h ha).elim)) (λ ha, one_le_mul_indicator_apply (λ _, hf _)) @[to_additive] lemma mul_indicator_le_self' (hf : ∀ x ∉ s, 1 ≤ f x) : mul_indicator s f ≤ f := mul_indicator_le' (λ _ _, le_refl _) hf @[to_additive] lemma mul_indicator_Union_apply {ι M} [complete_lattice M] [has_one M] (h1 : (⊥:M) = 1) (s : ι → set α) (f : α → M) (x : α) : mul_indicator (⋃ i, s i) f x = ⨆ i, mul_indicator (s i) f x := begin by_cases hx : x ∈ ⋃ i, s i, { rw [mul_indicator_of_mem hx], rw [mem_Union] at hx, refine le_antisymm _ (supr_le $ λ i, mul_indicator_le_self' (λ x hx, h1 ▸ bot_le) x), rcases hx with ⟨i, hi⟩, exact le_supr_of_le i (ge_of_eq $ mul_indicator_of_mem hi _) }, { rw [mul_indicator_of_not_mem hx], simp only [mem_Union, not_exists] at hx, simp [hx, ← h1] } end end order section canonically_ordered_monoid variables [canonically_ordered_monoid M] @[to_additive] lemma mul_indicator_le_self (s : set α) (f : α → M) : mul_indicator s f ≤ f := mul_indicator_le_self' $ λ _ _, one_le _ @[to_additive] lemma mul_indicator_apply_le {a : α} {s : set α} {f g : α → M} (hfg : a ∈ s → f a ≤ g a) : mul_indicator s f a ≤ g a := mul_indicator_apply_le' hfg $ λ _, one_le _ @[to_additive] lemma mul_indicator_le {s : set α} {f g : α → M} (hfg : ∀ a ∈ s, f a ≤ g a) : mul_indicator s f ≤ g := mul_indicator_le' hfg $ λ _ _, one_le _ end canonically_ordered_monoid end set @[to_additive] lemma monoid_hom.map_mul_indicator {M N : Type*} [monoid M] [monoid N] (f : M →* N) (s : set α) (g : α → M) (x : α) : f (s.mul_indicator g x) = s.mul_indicator (f ∘ g) x := congr_fun (set.mul_indicator_comp_of_one f.map_one).symm x
b25ceafbb5b6da3310c68d9feed50a03a410ca51
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/finset/default.lean
b8d3d55dabbaf7e541f2cf65f895024e261a32d6
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
273
lean
import data.finset.basic import data.finset.fold import data.finset.image import data.finset.lattice import data.finset.locally_finite import data.finset.nat_antidiagonal import data.finset.pi import data.finset.powerset import data.finset.sort import data.finset.preimage
b476da304a313d3bae1b4f56f907552538a3a8c9
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/run/newfrontend1.lean
b118ccc8472754aaf0b3fa2160e2f224a5124ae5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
8,794
lean
def x := 1 #check x variable {α : Type} def f (a : α) : α := a def tst (xs : List Nat) : Nat := xs.foldl (init := 10) (· + ·) #check tst [1, 2, 3] #check fun x y : Nat => x + y #check tst #check (fun stx => if True then let e := stx; Pure.pure e else Pure.pure stx : Nat → Id Nat) #check let x : Nat := 1; x def foo (a : Nat) (b : Nat := 10) (c : Bool := Bool.true) : Nat := a + b set_option pp.all true #check foo 1 #check foo 3 (c := false) def Nat.boo (a : Nat) := succ a -- succ here is resolved as `Nat.succ`. #check Nat.boo #check true -- apply is still a valid identifier name def apply := "hello" #check apply theorem simple1 (x y : Nat) (h : x = y) : x = y := by { assumption } theorem simple2 (x y : Nat) : x = y → x = y := by { intro h; assumption } syntax "intro2" : tactic macro_rules | `(tactic| intro2) => `(tactic| intro; intro ) theorem simple3 (x y : Nat) : x = x → x = y → x = y := by { intro2; assumption } macro "intro3" : tactic => `(intro; intro; intro) macro "check2" x:term : command => `(#check $x #check $x) macro "foo" x:term "," y:term : term => `($x + $y + $x) set_option pp.all false check2 0+1 check2 foo 0,1 theorem simple4 (x y : Nat) : y = y → x = x → x = y → x = y := by { intro3; assumption } theorem simple5 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; exact Eq.trans h3 h1 } theorem simple6 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine Eq.trans ?_ h1; assumption } theorem simple7 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro _; intro h3; refine' Eq.trans ?pre ?post; exact y; { exact h3 } { exact h1 } } theorem simple8 (x y z : Nat) : y = z → x = x → x = y → x = z := by intro h1; intro _; intro h3 refine' Eq.trans ?pre ?post case post => exact h1 case pre => exact h3 theorem simple9 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 trace_state focus refine' Eq.trans ?pre ?post first | exact h1 assumption | exact y exact h3 assumption theorem simple9b (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 trace_state focus refine' Eq.trans ?pre ?post first | exact h1 | exact y; exact h3 assumption theorem simple9c (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 solve | exact h1 | refine' Eq.trans ?pre ?post; exact y; exact h3; assumption | exact h3 theorem simple9d (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 _ h3 refine' Eq.trans ?pre ?post solve | exact h1 | exact y | exact h3 solve | exact h1 | exact h3 solve | exact h1 | assumption namespace Foo def Prod.mk := 1 #check (⟨2, 3⟩ : Prod _ _) end Foo theorem simple10 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; skip; apply Eq.trans; exact h3; assumption } theorem simple11 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; trace_state; exact h3; assumption } theorem simple12 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intro h1; intro h2; intro h3; apply @Eq.trans; try exact h1; -- `exact h1` fails trace_state; try exact h3; trace_state; try exact h1; } theorem simple13 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3 trace_state apply @Eq.trans case b => exact y trace_state repeat assumption theorem simple13b (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; trace_state; apply @Eq.trans; case b => exact y; trace_state; repeat assumption } theorem simple14 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros apply @Eq.trans case b => exact y repeat assumption theorem simple15 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; revert y; intros y h1 h3; apply Eq.trans; exact h3; exact h1 } theorem simple16 (x y z : Nat) : y = z → x = x → x = y → x = z := by { intros h1 h2 h3; try clear x; -- should fail clear h2; trace_state; apply Eq.trans; exact h3; exact h1 } macro "blabla" : tactic => `(assumption) -- Tactic head symbols do not become reserved words def blabla := 100 #check blabla theorem simple17 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple18 (x : Nat) (h : x = 0) : x = 0 := by blabla theorem simple19 (x y : Nat) (h₁ : x = 0) (h₂ : x = y) : y = 0 := by subst x; subst y; exact rfl theorem tstprec1 (x y z : Nat) : x + y * z = x + (y * z) := rfl theorem tstprec2 (x y z : Nat) : y * z + x = (y * z) + x := rfl set_option pp.all true #check fun {α} (a : α) => a #check @(fun α (a : α) => a) #check let myid := fun {α} (a : α) => a; myid [myid 1] -- In the following example, we need `@` otherwise we will try to insert mvars for α and [Add α], -- and will fail to generate instance for [Add α] #check @(fun α (s : Add α) (a : α) => a + a) def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β := (a₁, a₂, b) def id1 : {α : Type} → α → α := fun x => x def listId : List ({α : Type} → α → α) := (fun x => x) :: [] def id2 : {α : Type} → α → α := @(fun α (x : α) => id1 x) def id3 : {α : Type} → α → α := @(fun α x => id1 x) def id4 : {α : Type} → α → α := fun x => id1 x def id5 : {α : Type} → α → α := fun {α} x => id1 x def id6 : {α : Type} → α → α := @(fun {α} x => id1 x) def id7 : {α : Type} → α → α := fun {α} x => @id α x def id8 : {α : Type} → α → α := fun {α} x => id (@id α x) def altTst1 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨StateT.failure, StateT.orElse⟩ def altTst2 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨@(fun α => StateT.failure), @(fun α => StateT.orElse)⟩ def altTst3 {m σ} [Alternative m] [Monad m] : Alternative (StateT σ m) := ⟨fun {α} => StateT.failure, fun {α} => StateT.orElse⟩ #check_failure 1 + true /- universe u v /- MonadFunctorT.{u ?M_1 v} (λ (β : Type u), m α) (λ (β : Type u), m' α) n n' -/ set_option pp.raw.maxDepth 100 set_option trace.Elab true def adapt {m m' σ σ'} {n n' : Type → Type} [MonadFunctor m m' n n'] [MonadStateAdapter σ σ' m m'] : MonadStateAdapter σ σ' n n' := ⟨fun split join => monadMap (adaptState split join : m α → m' α)⟩ -/ syntax "fn" (term:max)+ "=>" term : term macro_rules | `(fn $xs* => $b) => `(fun $xs* => $b) set_option pp.all false #check fn x => x+1 #check fn α (a : α) => a def tst1 : {α : Type} → α → α := @(fn α a => a) #check @tst1 syntax ident "==>" term : term syntax "{" ident "}" "==>" term : term macro_rules | `($x:ident ==> $b) => `(fn $x => $b) | `({$x:ident} ==> $b) => `(fun {$x:ident} => $b) #check x ==> x+1 def tst2a : {α : Type} → α → α := @(α ==> a ==> a) def tst2b : {α : Type} → α → α := {α} ==> a ==> a #check @tst2a #check @tst2b def tst3a : {α : Type} → {β : Type} → α → β → α × β := @(α ==> @(β ==> a ==> b ==> (a, b))) def tst3b : {α : Type} → {β : Type} → α → β → α × β := {α} ==> {β} ==> a ==> b ==> (a, b) syntax "function" (term:max)+ "=>" term : term macro_rules | `(function $xs* => $b) => `(@(fun $xs* => $b)) def tst4 : {α : Type} → {β : Type} → α → β → α × β := function α β a b => (a, b) theorem simple20 (x y z : Nat) : y = z → x = x → x = y → x = z := by intros h1 h2 h3; try clear x; -- should fail clear h2; trace_state; apply Eq.trans; exact h3; exact h1 theorem simple21 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have : x = y := by { apply Eq.symm; assumption }; Eq.trans this (by assumption) theorem simple22 (x y z : Nat) : y = z → y = x → id (x = z + 0) := fun h1 h2 => show x = z + 0 by apply Eq.trans exact h2.symm assumption skip theorem simple23 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have : x = y := by apply Eq.symm; assumption Eq.trans this (by assumption) theorem simple24 (x y z : Nat) : y = z → x = x → y = x → x = z := fun h1 _ h3 => have h : x = y := by apply Eq.symm; assumption Eq.trans h (by assumption) def f1 (x : Nat) : Nat := let double x := x + x let rec loop x := match x with | 0 => 0 | x+1 => loop x + double x loop x #eval f1 5 def f2 (x : Nat) : String := let bad x : String := toString x bad x def f3 x y := x + y + 1 theorem f3eq x y : f3 x y = x + y + 1 := rfl def f4 (x y : Nat) : String := if x > y + 1 then "hello" else "world"
6ba93e994aaab3b7c94be43ce5401ffef6498884
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/preadditive/functor_category.lean
602be9aebf3e640e0518d82cd16e969b55ee1950
[ "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
2,703
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import category_theory.preadditive.basic /-! # Preadditive structure on functor categories If `C` and `D` are categories and `D` is preadditive, then `C ⥤ D` is also preadditive. -/ open_locale big_operators namespace category_theory open category_theory.limits preadditive variables {C D : Type*} [category C] [category D] [preadditive D] instance functor_category_preadditive : preadditive (C ⥤ D) := { hom_group := λ F G, { add := λ α β, { app := λ X, α.app X + β.app X, naturality' := by { intros, rw [comp_add, add_comp, α.naturality, β.naturality] } }, zero := { app := λ X, 0, naturality' := by { intros, rw [zero_comp, comp_zero] } }, neg := λ α, { app := λ X, -α.app X, naturality' := by { intros, rw [comp_neg, neg_comp, α.naturality] } }, sub := λ α β, { app := λ X, α.app X - β.app X, naturality' := by { intros, rw [comp_sub, sub_comp, α.naturality, β.naturality] } }, add_assoc := by { intros, ext, apply add_assoc }, zero_add := by { intros, ext, apply zero_add }, add_zero := by { intros, ext, apply add_zero }, sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg }, add_left_neg := by { intros, ext, apply add_left_neg }, add_comm := by { intros, ext, apply add_comm } }, add_comp' := by { intros, ext, apply add_comp }, comp_add' := by { intros, ext, apply comp_add } } namespace nat_trans variables {F G : C ⥤ D} /-- Application of a natural transformation at a fixed object, as group homomorphism -/ @[simps] def app_hom (X : C) : (F ⟶ G) →+ (F.obj X ⟶ G.obj X) := { to_fun := λ α, α.app X, map_zero' := rfl, map_add' := λ _ _, rfl } @[simp] lemma app_zero (X : C) : (0 : F ⟶ G).app X = 0 := rfl @[simp] lemma app_add (X : C) (α β : F ⟶ G) : (α + β).app X = α.app X + β.app X := rfl @[simp] lemma app_sub (X : C) (α β : F ⟶ G) : (α - β).app X = α.app X - β.app X := rfl @[simp] lemma app_neg (X : C) (α : F ⟶ G) : (-α).app X = -α.app X := rfl @[simp] lemma app_nsmul (X : C) (α : F ⟶ G) (n : ℕ) : (n • α).app X = n • α.app X := (app_hom X).map_nsmul α n @[simp] lemma app_zsmul (X : C) (α : F ⟶ G) (n : ℤ) : (n • α).app X = n • α.app X := (app_hom X : (F ⟶ G) →+ (F.obj X ⟶ G.obj X)).map_zsmul α n @[simp] lemma app_sum {ι : Type*} (s : finset ι) (X : C) (α : ι → (F ⟶ G)) : (∑ i in s, α i).app X = ∑ i in s, ((α i).app X) := by { rw [← app_hom_apply, add_monoid_hom.map_sum], refl } end nat_trans end category_theory
64d5a1022541d8fa13715e69c9056bd23cc56245
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/real/cardinality.lean
393e3b260983227c4e032b757326d3521f3578be
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
5,059
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The cardinality of the reals. -/ import data.real.basic set_theory.ordinal analysis.specific_limits data.rat.denumerable open nat set noncomputable theory namespace cardinal variables {c : ℝ} {f g : ℕ → bool} {n : ℕ} def cantor_function_aux (c : ℝ) (f : ℕ → bool) (n : ℕ) : ℝ := cond (f n) (c ^ n) 0 @[simp] lemma cantor_function_aux_tt (h : f n = tt) : cantor_function_aux c f n = c ^ n := by simp [cantor_function_aux, h] @[simp] lemma cantor_function_aux_ff (h : f n = ff) : cantor_function_aux c f n = 0 := by simp [cantor_function_aux, h] lemma cantor_function_aux_nonneg (h : 0 ≤ c) : 0 ≤ cantor_function_aux c f n := by { cases h' : f n; simp [h'], apply pow_nonneg h } lemma cantor_function_aux_eq (h : f n = g n) : cantor_function_aux c f n = cantor_function_aux c g n := by simp [cantor_function_aux, h] lemma cantor_function_aux_succ (f : ℕ → bool) : (λ n, cantor_function_aux c f (n + 1)) = λ n, c * cantor_function_aux c (λ n, f (n + 1)) n := by { ext n, cases h : f (n + 1); simp [h, _root_.pow_succ] } lemma summable_cantor_function (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : summable (cantor_function_aux c f) := begin apply summable_of_summable_of_sub _ _ (summable_geometric h1 h2), intro n, cases h : f n; simp [h] end def cantor_function (c : ℝ) (f : ℕ → bool) : ℝ := ∑ n, cantor_function_aux c f n lemma cantor_function_le (h1 : 0 ≤ c) (h2 : c < 1) (h3 : ∀ n, f n → g n) : cantor_function c f ≤ cantor_function c g := begin apply tsum_le_tsum _ (summable_cantor_function f h1 h2) (summable_cantor_function g h1 h2), intro n, cases h : f n, simp [h, cantor_function_aux_nonneg h1], replace h3 : g n = tt := h3 n h, simp [h, h3] end lemma cantor_function_succ (f : ℕ → bool) (h1 : 0 ≤ c) (h2 : c < 1) : cantor_function c f = cond (f 0) 1 0 + c * cantor_function c (λ n, f (n+1)) := begin rw [cantor_function, tsum_eq_zero_add (summable_cantor_function f h1 h2)], rw [cantor_function_aux_succ, tsum_mul_left _ (summable_cantor_function _ h1 h2)], refl end lemma increasing_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) {n : ℕ} {f g : ℕ → bool} (hn : ∀(k < n), f k = g k) (fn : f n = ff) (gn : g n = tt) : cantor_function c f < cantor_function c g := begin have h3 : c < 1, { apply lt_trans h2, norm_num }, induction n with n ih generalizing f g, { let f_max : ℕ → bool := λ n, nat.rec ff (λ _ _, tt) n, have hf_max : ∀n, f n → f_max n, { intros n hn, cases n, rw [fn] at hn, contradiction, apply rfl }, let g_min : ℕ → bool := λ n, nat.rec tt (λ _ _, ff) n, have hg_min : ∀n, g_min n → g n, { intros n hn, cases n, rw [gn], apply rfl, contradiction }, apply lt_of_le_of_lt (cantor_function_le (le_of_lt h1) h3 hf_max), apply lt_of_lt_of_le _ (cantor_function_le (le_of_lt h1) h3 hg_min), have : c * (1 / (1 - c)) < 1, { have : 1 / (1 - c) ≤ 2, { rw [div_le_iff, ←div_le_iff', le_sub_iff_add_le, ←le_sub_iff_add_le'], convert le_of_lt h2, norm_num, norm_num, rw [sub_pos], exact h3 }, convert mul_lt_mul h2 this _ _, norm_num, apply div_pos, norm_num, rw [sub_pos], exact h3, norm_num }, convert this, { rw [cantor_function_succ _ (le_of_lt h1) h3, ←tsum_geometric (le_of_lt h1) h3], apply zero_add }, { apply tsum_eq_single 0, intros n hn, cases n, contradiction, refl, apply_instance }}, rw [cantor_function_succ f (le_of_lt h1) h3, cantor_function_succ g (le_of_lt h1) h3], rw [hn 0 $ zero_lt_succ n], apply add_lt_add_left, rw mul_lt_mul_left h1, exact ih (λ k hk, hn _ $ succ_lt_succ hk) fn gn end lemma injective_cantor_function (h1 : 0 < c) (h2 : c < 1 / 2) : function.injective (cantor_function c) := begin intros f g hfg, classical, by_contra h, revert hfg, have : ∃n, f n ≠ g n, { rw [←not_forall], intro h', apply h, ext, apply h' }, let n := nat.find this, have hn : ∀ (k : ℕ), k < n → f k = g k, { intros k hk, apply of_not_not, exact nat.find_min this hk }, cases fn : f n, { apply ne_of_lt, refine increasing_cantor_function h1 h2 hn fn _, apply eq_tt_of_not_eq_ff, rw [←fn], apply ne.symm, exact nat.find_spec this }, { apply ne_of_gt, refine increasing_cantor_function h1 h2 (λ k hk, (hn k hk).symm) _ fn, apply eq_ff_of_not_eq_tt, rw [←fn], apply ne.symm, exact nat.find_spec this } end lemma mk_real : mk ℝ = 2 ^ omega.{0} := begin apply le_antisymm, { dsimp [real], apply le_trans mk_quotient_le, apply le_trans mk_subtype_le, rw [←power_def, mk_nat, mk_rat, power_self_eq (le_refl _)] }, { convert mk_le_of_injective (injective_cantor_function _ _), rw [←power_def, mk_bool, mk_nat], exact 1 / 3, norm_num, norm_num } end lemma not_countable_real : ¬ countable (set.univ : set ℝ) := by { rw [countable_iff, not_le, mk_univ, mk_real], apply cantor } end cardinal
3feeda2d27d157d2709c1817a0990df7954fbac2
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/ffi/lib/lean/FFI/Add.lean
cb6091bcaae22d4e28e745c4e2bd2f710a9fe996
[ "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
63
lean
@[extern "my_add"] opaque myAdd : UInt32 → UInt32 → UInt32
3ba2719e14189afc7245a014b22fb9a43e6e4ab7
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/trigonometric/complex.lean
5291d37b34aac2681e8d78d6940d5c974aa7c4ea
[ "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
9,322
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import algebra.quadratic_discriminant import analysis.convex.specific_functions /-! # Complex trigonometric functions Basic facts and derivatives for the complex trigonometric functions. Several facts about the real trigonometric functions have the proofs deferred here, rather than `analysis.special_functions.trigonometric.basic`, as they are most easily proved by appealing to the corresponding fact for complex trigonometric functions, or require additional imports which are not available in that file. -/ noncomputable theory namespace complex open set filter open_locale real theorem cos_eq_zero_iff {θ : ℂ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 := begin have h : (exp (θ * I) + exp (-θ * I)) / 2 = 0 ↔ exp (2 * θ * I) = -1, { rw [@div_eq_iff _ _ (exp (θ * I) + exp (-θ * I)) 2 0 two_ne_zero, zero_mul, add_eq_zero_iff_eq_neg, neg_eq_neg_one_mul, ← div_eq_iff (exp_ne_zero _), ← exp_sub], field_simp only, congr' 3, ring }, rw [cos, h, ← exp_pi_mul_I, exp_eq_exp_iff_exists_int, mul_right_comm], refine exists_congr (λ x, _), refine (iff_of_eq $ congr_arg _ _).trans (mul_right_inj' $ mul_ne_zero two_ne_zero I_ne_zero), field_simp, ring, end theorem cos_ne_zero_iff {θ : ℂ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 := by rw [← not_exists, not_iff_not, cos_eq_zero_iff] theorem sin_eq_zero_iff {θ : ℂ} : sin θ = 0 ↔ ∃ k : ℤ, θ = k * π := begin rw [← complex.cos_sub_pi_div_two, cos_eq_zero_iff], split, { rintros ⟨k, hk⟩, use k + 1, field_simp [eq_add_of_sub_eq hk], ring }, { rintros ⟨k, rfl⟩, use k - 1, field_simp, ring } end theorem sin_ne_zero_iff {θ : ℂ} : sin θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π := by rw [← not_exists, not_iff_not, sin_eq_zero_iff] lemma tan_eq_zero_iff {θ : ℂ} : tan θ = 0 ↔ ∃ k : ℤ, θ = k * π / 2 := begin have h := (sin_two_mul θ).symm, rw mul_assoc at h, rw [tan, div_eq_zero_iff, ← mul_eq_zero, ← zero_mul ((1/2):ℂ), mul_one_div, cancel_factors.cancel_factors_eq_div h two_ne_zero, mul_comm], simpa only [zero_div, zero_mul, ne.def, not_false_iff] with field_simps using sin_eq_zero_iff, end lemma tan_ne_zero_iff {θ : ℂ} : tan θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ k * π / 2 := by rw [← not_exists, not_iff_not, tan_eq_zero_iff] lemma tan_int_mul_pi_div_two (n : ℤ) : tan (n * π/2) = 0 := tan_eq_zero_iff.mpr (by use n) lemma cos_eq_cos_iff {x y : ℂ} : cos x = cos y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x := calc cos x = cos y ↔ cos x - cos y = 0 : sub_eq_zero.symm ... ↔ -2 * sin((x + y)/2) * sin((x - y)/2) = 0 : by rw cos_sub_cos ... ↔ sin((x + y)/2) = 0 ∨ sin((x - y)/2) = 0 : by simp [(by norm_num : (2:ℂ) ≠ 0)] ... ↔ sin((x - y)/2) = 0 ∨ sin((x + y)/2) = 0 : or.comm ... ↔ (∃ k : ℤ, y = 2 * k * π + x) ∨ (∃ k :ℤ, y = 2 * k * π - x) : begin apply or_congr; field_simp [sin_eq_zero_iff, (by norm_num : -(2:ℂ) ≠ 0), eq_sub_iff_add_eq', sub_eq_iff_eq_add, mul_comm (2:ℂ), mul_right_comm _ (2:ℂ)], split; { rintros ⟨k, rfl⟩, use -k, simp, }, end ... ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x : exists_or_distrib.symm lemma sin_eq_sin_iff {x y : ℂ} : sin x = sin y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = (2 * k + 1) * π - x := begin simp only [← complex.cos_sub_pi_div_two, cos_eq_cos_iff, sub_eq_iff_eq_add], refine exists_congr (λ k, or_congr _ _); refine eq.congr rfl _; field_simp; ring end lemma tan_add {x y : ℂ} (h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2) ∨ ((∃ k : ℤ, x = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, y = (2 * l + 1) * π / 2)) : tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) := begin rcases h with ⟨h1, h2⟩ | ⟨⟨k, rfl⟩, ⟨l, rfl⟩⟩, { rw [tan, sin_add, cos_add, ← div_div_div_cancel_right (sin x * cos y + cos x * sin y) (mul_ne_zero (cos_ne_zero_iff.mpr h1) (cos_ne_zero_iff.mpr h2)), add_div, sub_div], simp only [←div_mul_div_comm, ←tan, mul_one, one_mul, div_self (cos_ne_zero_iff.mpr h1), div_self (cos_ne_zero_iff.mpr h2)] }, { obtain ⟨t, hx, hy, hxy⟩ := ⟨tan_int_mul_pi_div_two, t (2*k+1), t (2*l+1), t (2*k+1+(2*l+1))⟩, simp only [int.cast_add, int.cast_bit0, int.cast_mul, int.cast_one, hx, hy] at hx hy hxy, rw [hx, hy, add_zero, zero_div, mul_div_assoc, mul_div_assoc, ← add_mul (2*(k:ℂ)+1) (2*l+1) (π/2), ← mul_div_assoc, hxy] }, end lemma tan_add' {x y : ℂ} (h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y ≠ (2 * l + 1) * π / 2)) : tan (x + y) = (tan x + tan y) / (1 - tan x * tan y) := tan_add (or.inl h) lemma tan_two_mul {z : ℂ} : tan (2 * z) = 2 * tan z / (1 - tan z ^ 2) := begin by_cases h : ∀ k : ℤ, z ≠ (2 * k + 1) * π / 2, { rw [two_mul, two_mul, sq, tan_add (or.inl ⟨h, h⟩)] }, { rw not_forall_not at h, rw [two_mul, two_mul, sq, tan_add (or.inr ⟨h, h⟩)] }, end lemma tan_add_mul_I {x y : ℂ} (h : ((∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, y * I ≠ (2 * l + 1) * π / 2) ∨ ((∃ k : ℤ, x = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, y * I = (2 * l + 1) * π / 2)) : tan (x + y*I) = (tan x + tanh y * I) / (1 - tan x * tanh y * I) := by rw [tan_add h, tan_mul_I, mul_assoc] lemma tan_eq {z : ℂ} (h : ((∀ k : ℤ, (z.re:ℂ) ≠ (2 * k + 1) * π / 2) ∧ ∀ l : ℤ, (z.im:ℂ) * I ≠ (2 * l + 1) * π / 2) ∨ ((∃ k : ℤ, (z.re:ℂ) = (2 * k + 1) * π / 2) ∧ ∃ l : ℤ, (z.im:ℂ) * I = (2 * l + 1) * π / 2)) : tan z = (tan z.re + tanh z.im * I) / (1 - tan z.re * tanh z.im * I) := by convert tan_add_mul_I h; exact (re_add_im z).symm open_locale topology lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} := continuous_on_sin.div continuous_on_cos $ λ x, id @[continuity] lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) := continuous_on_iff_continuous_restrict.1 continuous_on_tan lemma cos_eq_iff_quadratic {z w : ℂ} : cos z = w ↔ (exp (z * I)) ^ 2 - 2 * w * exp (z * I) + 1 = 0 := begin rw ← sub_eq_zero, field_simp [cos, exp_neg, exp_ne_zero], refine eq.congr _ rfl, ring end lemma cos_surjective : function.surjective cos := begin intro x, obtain ⟨w, w₀, hw⟩ : ∃ w ≠ 0, 1 * w * w + (-2 * x) * w + 1 = 0, { rcases exists_quadratic_eq_zero one_ne_zero ⟨_, ((cpow_nat_inv_pow _ two_ne_zero).symm.trans $ pow_two _)⟩ with ⟨w, hw⟩, refine ⟨w, _, hw⟩, rintro rfl, simpa only [zero_add, one_ne_zero, mul_zero] using hw }, refine ⟨log w / I, cos_eq_iff_quadratic.2 _⟩, rw [div_mul_cancel _ I_ne_zero, exp_log w₀], convert hw, ring end @[simp] lemma range_cos : range cos = set.univ := cos_surjective.range_eq lemma sin_surjective : function.surjective sin := begin intro x, rcases cos_surjective x with ⟨z, rfl⟩, exact ⟨z + π / 2, sin_add_pi_div_two z⟩ end @[simp] lemma range_sin : range sin = set.univ := sin_surjective.range_eq end complex namespace real open_locale real theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 := by exact_mod_cast @complex.cos_eq_zero_iff θ theorem cos_ne_zero_iff {θ : ℝ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 := by rw [← not_exists, not_iff_not, cos_eq_zero_iff] lemma cos_eq_cos_iff {x y : ℝ} : cos x = cos y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = 2 * k * π - x := by exact_mod_cast @complex.cos_eq_cos_iff x y lemma sin_eq_sin_iff {x y : ℝ} : sin x = sin y ↔ ∃ k : ℤ, y = 2 * k * π + x ∨ y = (2 * k + 1) * π - x := by exact_mod_cast @complex.sin_eq_sin_iff x y lemma lt_sin_mul {x : ℝ} (hx : 0 < x) (hx' : x < 1) : x < sin ((π / 2) * x) := by simpa [mul_comm x] using strict_concave_on_sin_Icc.2 ⟨le_rfl, pi_pos.le⟩ ⟨pi_div_two_pos.le, half_le_self pi_pos.le⟩ pi_div_two_pos.ne (sub_pos.2 hx') hx lemma le_sin_mul {x : ℝ} (hx : 0 ≤ x) (hx' : x ≤ 1) : x ≤ sin ((π / 2) * x) := by simpa [mul_comm x] using strict_concave_on_sin_Icc.concave_on.2 ⟨le_rfl, pi_pos.le⟩ ⟨pi_div_two_pos.le, half_le_self pi_pos.le⟩ (sub_nonneg.2 hx') hx lemma mul_lt_sin {x : ℝ} (hx : 0 < x) (hx' : x < π / 2) : (2 / π) * x < sin x := begin rw [←inv_div], simpa [-inv_div, pi_div_two_pos.ne'] using @lt_sin_mul ((π / 2)⁻¹ * x) _ _, { exact mul_pos (inv_pos.2 pi_div_two_pos) hx }, { rwa [←div_eq_inv_mul, div_lt_one pi_div_two_pos] }, end /-- In the range `[0, π / 2]`, we have a linear lower bound on `sin`. This inequality forms one half of Jordan's inequality, the other half is `real.sin_lt` -/ lemma mul_le_sin {x : ℝ} (hx : 0 ≤ x) (hx' : x ≤ π / 2) : (2 / π) * x ≤ sin x := begin rw [←inv_div], simpa [-inv_div, pi_div_two_pos.ne'] using @le_sin_mul ((π / 2)⁻¹ * x) _ _, { exact mul_nonneg (inv_nonneg.2 pi_div_two_pos.le) hx }, { rwa [←div_eq_inv_mul, div_le_one pi_div_two_pos] }, end end real
78c53976c1b31f51e2e8dfb82f896e901b2039fa
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/norm_cast_lemma_order.lean
ca350f1f625714b328ad47f279e6c024234499d3
[ "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
645
lean
import data.nat.cast.defs import tactic.norm_cast constant ℝ : Type @[instance] constant real.add_monoid_with_one : add_monoid_with_one ℝ -- set_option trace.simplify.rewrite true set_option pp.notation false set_option pp.numerals false -- should work run_cmd norm_cast.numeral_to_coe `(0 : ℝ) run_cmd norm_cast.numeral_to_coe `(1 : ℝ) run_cmd norm_cast.numeral_to_coe `(2 : ℝ) run_cmd norm_cast.numeral_to_coe `(3 : ℝ) run_cmd norm_cast.coe_to_numeral `((0 : ℕ) : ℝ) run_cmd norm_cast.coe_to_numeral `((1 : ℕ) : ℝ) run_cmd norm_cast.coe_to_numeral `((2 : ℕ) : ℝ) run_cmd norm_cast.coe_to_numeral `((3 : ℕ) : ℝ)
d404eb264c20fd5addb3002ee499cd4bd56c4658
618003631150032a5676f229d13a079ac875ff77
/src/order/filter/partial.lean
81a5dd74a817ea310bedf99114013b4f7130aa02
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
8,435
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Extends `tendsto` to relations and partial functions. -/ import order.filter.basic universes u v w namespace filter variables {α : Type u} {β : Type v} {γ : Type w} /- Relations. -/ def rmap (r : rel α β) (f : filter α) : filter β := { sets := r.core ⁻¹' f.sets, univ_sets := by { simp [rel.core], apply univ_mem_sets }, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ rel.core_mono _ st, inter_sets := by { simp [set.preimage, rel.core_inter], exact λ s t, inter_mem_sets } } theorem rmap_sets (r : rel α β) (f : filter α) : (rmap r f).sets = r.core ⁻¹' f.sets := rfl @[simp] theorem mem_rmap (r : rel α β) (l : filter α) (s : set β) : s ∈ l.rmap r ↔ r.core s ∈ l := iff.rfl @[simp] theorem rmap_rmap (r : rel α β) (s : rel β γ) (l : filter α) : rmap s (rmap r l) = rmap (r.comp s) l := filter_eq $ by simp [rmap_sets, set.preimage, rel.core_comp] @[simp] lemma rmap_compose (r : rel α β) (s : rel β γ) : rmap s ∘ rmap r = rmap (r.comp s) := funext $ rmap_rmap _ _ def rtendsto (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁.rmap r ≤ l₂ theorem rtendsto_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ ∀ s ∈ l₂, r.core s ∈ l₁ := iff.rfl def rcomap (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.core s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (by rw rel.core_inter) (set.inter_subset_inter ha₂ hb₂)⟩ } theorem rcomap_sets (r : rel α β) (f : filter β) : (rcomap r f).sets = rel.image (λ s t, r.core s ⊆ t) f.sets := rfl @[simp] theorem rcomap_rcomap (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap r (rcomap s l) = rcomap (r.comp s) l := filter_eq $ begin ext t, simp [rcomap_sets, rel.image, rel.core_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.core_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.core s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap_compose (r : rel α β) (s : rel β γ) : rcomap r ∘ rcomap s = rcomap (r.comp s) := funext $ rcomap_rcomap _ _ theorem rtendsto_iff_le_comap (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ l₁ ≤ l₂.rcomap r := begin rw rtendsto_def, change (∀ (s : set β), s ∈ l₂.sets → rel.core r s ∈ l₁) ↔ l₁ ≤ rcomap r l₂, simp [filter.le_def, rcomap, rel.mem_image], split, intros h s t tl₂ h', { exact mem_sets_of_superset (h t tl₂) h' }, intros h t tl₂, apply h _ t tl₂ (set.subset.refl _), end -- Interestingly, there does not seem to be a way to express this relation using a forward map. -- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f` if -- and only if `s ∈ f'`. But the intersection of two sets satsifying the lhs may be empty. def rcomap' (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.preimage s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (@rel.preimage_inter _ _ r _ _) (set.inter_subset_inter ha₂ hb₂)⟩ } @[simp] lemma mem_rcomap' (r : rel α β) (l : filter β) (s : set α) : s ∈ l.rcomap' r ↔ ∃ t ∈ l, rel.preimage r t ⊆ s := iff.rfl theorem rcomap'_sets (r : rel α β) (f : filter β) : (rcomap' r f).sets = rel.image (λ s t, r.preimage s ⊆ t) f.sets := rfl @[simp] theorem rcomap'_rcomap' (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap' r (rcomap' s l) = rcomap' (r.comp s) l := filter_eq $ begin ext t, simp [rcomap'_sets, rel.image, rel.preimage_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.preimage_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.preimage s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap'_compose (r : rel α β) (s : rel β γ) : rcomap' r ∘ rcomap' s = rcomap' (r.comp s) := funext $ rcomap'_rcomap' _ _ def rtendsto' (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' r theorem rtendsto'_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto' r l₁ l₂ ↔ ∀ s ∈ l₂, r.preimage s ∈ l₁ := begin unfold rtendsto', unfold rcomap', simp [le_def, rel.mem_image], split, { intros h s hs, apply (h _ _ hs (set.subset.refl _)) }, intros h s t ht h', apply mem_sets_of_superset (h t ht) h' end theorem tendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto_def, rel.core, set.preimage] } theorem tendsto_iff_rtendsto' (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto'_def, rel.preimage_def, set.preimage] } /- Partial functions. -/ def pmap (f : α →. β) (l : filter α) : filter β := filter.rmap f.graph' l @[simp] lemma mem_pmap (f : α →. β) (l : filter α) (s : set β) : s ∈ l.pmap f ↔ f.core s ∈ l := iff.rfl def ptendsto (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁.pmap f ≤ l₂ theorem ptendsto_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f.core s ∈ l₁ := iff.rfl theorem ptendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α →. β) : ptendsto f l₁ l₂ ↔ rtendsto f.graph' l₁ l₂ := iff.rfl theorem pmap_res (l : filter α) (s : set α) (f : α → β) : pmap (pfun.res f s) l = map f (l ⊓ principal s) := filter_eq $ begin apply set.ext, intro t, simp [pfun.core_res], split, { intro h, constructor, split, { exact h }, constructor, split, { reflexivity }, simp [set.inter_distrib_right], apply set.inter_subset_left }, rintro ⟨t₁, h₁, t₂, h₂, h₃⟩, apply mem_sets_of_superset h₁, rw ← set.inter_subset, exact set.subset.trans (set.inter_subset_inter_right _ h₂) h₃ end theorem tendsto_iff_ptendsto (l₁ : filter α) (l₂ : filter β) (s : set α) (f : α → β) : tendsto f (l₁ ⊓ principal s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ := by simp only [tendsto, ptendsto, pmap_res] theorem tendsto_iff_ptendsto_univ (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ := by { rw ← tendsto_iff_ptendsto, simp [principal_univ] } def pcomap' (f : α →. β) (l : filter β) : filter α := filter.rcomap' f.graph' l def ptendsto' (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' f.graph' theorem ptendsto'_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto' f l₁ l₂ ↔ ∀ s ∈ l₂, f.preimage s ∈ l₁ := rtendsto'_def _ _ _ theorem ptendsto_of_ptendsto' {f : α →. β} {l₁ : filter α} {l₂ : filter β} : ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h s sl₂, exacts mem_sets_of_superset (h s sl₂) (pfun.preimage_subset_core _ _), end theorem ptendsto'_of_ptendsto {f : α →. β} {l₁ : filter α} {l₂ : filter β} (h : f.dom ∈ l₁) : ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h' s sl₂, rw pfun.preimage_eq, show pfun.core f s ∩ pfun.dom f ∈ l₁, exact inter_mem_sets (h' s sl₂) h end end filter
2565c57ded781c23d2e546ff3ee2fc4b221aef3b
aa5a655c05e5359a70646b7154e7cac59f0b4132
/tests/lean/run/casesUsing.lean
e51a59a7bd5817c2b414f4651db642d2653ce96f
[ "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
4,497
lean
import Lean open Lean open Lean.Meta open Lean.Elab.Tactic universes u axiom elimEx (motive : Nat → Nat → Sort u) (x y : Nat) (diag : (a : Nat) → motive a a) (upper : (delta a : Nat) → motive a (a + delta.succ)) (lower : (delta a : Nat) → motive (a + delta.succ) a) : motive y x theorem ex1 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => apply Or.inl; apply Nat.leRefl | lower d => apply Or.inl; show p ≤ p + d.succ; admit | upper d => apply Or.inr; show q + d.succ > q; admit theorem ex2 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx case lower => admit case upper => admit case diag => apply Or.inl; apply Nat.leRefl axiom Nat.parityElim (motive : Nat → Sort u) (even : (n : Nat) → motive (2*n)) (odd : (n : Nat) → motive (2*n+1)) (n : Nat) : motive n theorem time2Eq (n : Nat) : 2*n = n + n := by rw Nat.mulComm show (0 + n) + n = n+n rw Nat.zeroAdd theorem ex3 (n : Nat) : Exists (fun m => n = m + m ∨ n = m + m + 1) := by cases n using Nat.parityElim with | even i => apply Exists.intro i apply Or.inl rw time2Eq | odd i => apply Exists.intro i apply Or.inr rw time2Eq open Nat in theorem ex3b (n : Nat) : Exists (fun m => n = m + m ∨ n = m + m + 1) := by cases n using parityElim with | even i => apply Exists.intro i apply Or.inl rw time2Eq | odd i => apply Exists.intro i apply Or.inr rw time2Eq def ex4 {α} (xs : List α) (h : xs = [] → False) : α := by cases he:xs with | nil => apply False.elim; exact h he; done | cons x _ => exact x def ex5 {α} (xs : List α) (h : xs = [] → False) : α := by cases he:xs using List.casesOn with | nil => apply False.elim; exact h he; done | cons x _ => exact x theorem ex6 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := match he:f xs with | true => False.elim (h₂ (h₁ he)) | false => rfl theorem ex7 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := by cases he:f xs with | true => exact False.elim (h₂ (h₁ he)) | false => rfl theorem ex8 {α} (f : List α → Bool) (h₁ : {xs : List α} → f xs = true → xs = []) (xs : List α) (h₂ : xs ≠ []) : f xs = false := by cases he:f xs using Bool.casesOn with | true => exact False.elim (h₂ (h₁ he)) | false => rfl theorem ex9 {α} (xs : List α) (h : xs = [] → False) : Nonempty α := by cases xs using List.rec with | nil => apply False.elim; apply h; rfl | cons x _ => apply Nonempty.intro; assumption theorem modLt (x : Nat) {y : Nat} (h : y > 0) : x % y < y := by induction x, y using Nat.mod.inductionOn generalizing h with | ind x y h₁ ih => rw [Nat.modEqSubMod h₁.2] exact ih h | base x y h₁ => match Iff.mp (Decidable.notAndIffOrNot ..) h₁ with | Or.inl h₁ => exact absurd h h₁ | Or.inr h₁ => have hgt := Nat.gtOfNotLe h₁ have heq := Nat.modEqOfLt hgt rw [← heq] at hgt assumption theorem ex11 {p q : Prop } (h : p ∨ q) : q ∨ p := by induction h using Or.casesOn with | inr h => ?myright | inl h => ?myleft case myleft => exact Or.inr h case myright => exact Or.inl h theorem ex12 {p q : Prop } (h : p ∨ q) : q ∨ p := by cases h using Or.casesOn with | inr h => ?myright | inl h => ?myleft case myleft => exact Or.inr h case myright => exact Or.inl h theorem ex13 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => ?hlower | upper d => ?hupper case hdiag => apply Or.inl; apply Nat.leRefl case hlower => apply Or.inl; show p ≤ p + d.succ; admit case hupper => apply Or.inr; show q + d.succ > q; admit theorem ex14 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => _ | upper d => ?hupper case hdiag => apply Or.inl; apply Nat.leRefl case lower => apply Or.inl; show p ≤ p + d.succ; admit case hupper => apply Or.inr; show q + d.succ > q; admit theorem ex15 (p q : Nat) : p ≤ q ∨ p > q := by cases p, q using elimEx with | diag => ?hdiag | lower d => _ | upper d => ?hupper { apply Or.inl; apply Nat.leRefl } { apply Or.inr; show q + d.succ > q; admit } { apply Or.inl; show p ≤ p + d.succ; admit }
061c5ecfb018e778c37932073d0972462aa8722b
9c1ad797ec8a5eddb37d34806c543602d9a6bf70
/functor.lean
47a806c2ae1915267bf1f9672d5edf795f44e410
[]
no_license
timjb/lean-category-theory
816eefc3a0582c22c05f4ee1c57ed04e57c0982f
12916cce261d08bb8740bc85e0175b75fb2a60f4
refs/heads/master
1,611,078,926,765
1,492,080,000,000
1,492,080,000,000
88,348,246
0
0
null
1,492,262,499,000
1,492,262,498,000
null
UTF-8
Lean
false
false
4,627
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 open tqft.categories namespace tqft.categories.functor structure {u1 v1 u2 v2} Functor (C : Category.{ u1 v1 }) (D : Category.{ u2 v2 }) := (onObjects : C.Obj → D.Obj) (onMorphisms : Π { X Y : C.Obj }, C.Hom X Y → D.Hom (onObjects X) (onObjects Y)) (identities : ∀ (X : C.Obj), onMorphisms (C.identity X) = D.identity (onObjects X)) (functoriality : ∀ { X Y Z : C.Obj } (f : C.Hom X Y) (g : C.Hom Y Z), onMorphisms (C.compose f g) = D.compose (onMorphisms f) (onMorphisms g)) attribute [simp,ematch] Functor.identities attribute [simp,ematch] Functor.functoriality attribute [pointwise] Functor.mk -- We define a coercion so that we can write `F X` for the functor `F` applied to the object `X`. -- One can still write out `onObjects F X` when needed. instance Functor_to_onObjects { C D : Category }: has_coe_to_fun (Functor C D) := { F := λ f, C.Obj → D.Obj, coe := Functor.onObjects } -- This defines a coercion allowing us to write `F f` for `onMorphisms F f` -- but sadly it doesn't work if to_onObjects is already in scope. -- instance Functor_to_onMorphisms { C D : Category } : has_coe_to_fun (Functor C D) := -- { F := λ f, Π ⦃X Y : C.Obj⦄, C.Hom X Y → D.Hom (f X) (f Y), -- contrary to usual use, `f` here denotes the Functor. -- coe := Functor.onMorphisms } definition {u1 v1} IdentityFunctor ( C: Category.{u1 v1} ) : Functor C C := { onObjects := id, onMorphisms := λ _ _ f, f, identities := ♮, functoriality := ♮ } definition {u1 v1 u2 v2 u3 v3} FunctorComposition { C : Category.{u1 v1} } { D : Category.{u2 v2} } { E : Category.{u3 v3} } ( F : Functor C D ) ( G : Functor D E ) : Functor C E := { onObjects := λ X, G (F X), onMorphisms := λ _ _ f, G.onMorphisms (F.onMorphisms f), identities := ♮, functoriality := ♮ } -- We'll want to be able to prove that two functors are equal if they are equal on objects and on morphisms. -- Implementation warning: -- When using `apply Functors_pointwise_equal`, you might expect that Lean will create two goals, -- one for `objectWitness`, and one for `morphismWitness`. -- However, because `morphismWitness` depends on `objectWitness`, it will actually only create the goal -- for `morphismWitness`, leaving the `objectWitness` goal somehow "implicit" and likely unprovable. -- See https://groups.google.com/d/msg/lean-user/bhStu87PjiI/vqsyr9ZABAAJ for details. -- If you run into this problem, use `fapply Functors_pointwise_equal` instead. @[pointwise] lemma {u1 v1 u2 v2} Functors_pointwise_equal { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( objectWitness : ∀ X : C.Obj, F.onObjects X = G.onObjects X ) ( morphismWitness : ∀ X Y : C.Obj, ∀ f : C.Hom X Y, ⟦ F.onMorphisms f ⟧ = G.onMorphisms f ) : F = G := begin induction F with F_onObjects F_onMorphisms, induction G with G_onObjects G_onMorphisms, assert h_objects : F_onObjects = G_onObjects, exact funext objectWitness, subst h_objects, assert h_morphisms : @F_onMorphisms = @G_onMorphisms, apply funext, intro X, apply funext, intro Y, apply funext, intro f, exact morphismWitness X Y f, subst h_morphisms end open tactic.interactive @[ematch] lemma {u1 v1 u2 v2 u3 v3 u4 v4} FunctorComposition.associativity { B : Category.{u1 v1} } { C : Category.{u2 v2} } { D : Category.{u3 v3} } { E : Category.{u4 v4} } ( F : Functor B C ) ( G : Functor C D ) ( H : Functor D E ) : FunctorComposition (FunctorComposition F G) H = FunctorComposition F (FunctorComposition G H) := ♮ @[simp,ematch] lemma {u1 v1 u2 v2} FunctorComposition.left_identity ( C : Category.{u1 v1} ) ( D : Category.{u2 v2} ) ( F : Functor C D ) : FunctorComposition (IdentityFunctor C) F = F := ♯ @[simp,ematch] lemma {u1 v1 u2 v2} FunctorComposition.right_identity ( C : Category.{u1 v1} ) ( D : Category.{u2 v2} ) ( F : Functor C D ) : FunctorComposition F (IdentityFunctor D) = F := ♯ -- Note that this definition fixes the universe level of all the categories involved, so the witness fields are not useful as lemmas. definition {u v} CategoryOfCategoriesAndFunctors : Category := { Obj := Category.{u v}, Hom := λ C D, Functor C D, identity := λ C, IdentityFunctor C, compose := λ _ _ _ F G, FunctorComposition F G, left_identity := ♮, right_identity := ♮, associativity := ♮ } end tqft.categories.functor
6cf1fc36af5e990f066bc4f41cf11fa9fee18d33
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/topology/urysohns_lemma.lean
7b6e6e20512f13e720eca095d5b34aff08a2b974
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,671
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.normed_space.add_torsor import linear_algebra.affine_space.ordered import topology.continuous_function.basic /-! # Urysohn's lemma In this file we prove Urysohn's lemma `exists_continuous_zero_one_of_closed`: for any two disjoint closed sets `s` and `t` in a normal topological space `X` there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. ## Implementation notes Most paper sources prove Urysohn's lemma using a family of open sets indexed by dyadic rational numbers on `[0, 1]`. There are many technical difficulties with formalizing this proof (e.g., one needs to formalize the "dyadic induction", then prove that the resulting family of open sets is monotone). So, we formalize a slightly different proof. Let `urysohns.CU` the the type of pairs `(C, U)` of a closed set `C`and an open set `U` such that `C ⊆ U`. Since `X` is a normal topological space, for each `c : CU X` there exists an open set `u` such that `c.C ⊆ u ∧ closure u ⊆ c.U`. We define `c.left` and `c.right` to be `(c.C, u)` and `(closure u, c.U)`, respectively. Then we define a family of functions `urysohns.CU.approx (c : urysohns.CU X) (n : ℕ) : X → ℝ` by recursion on `n`: * `c.approx 0` is the indicator of `c.Uᶜ`; * `c.approx (n + 1) x = (c.left.approx n x + c.right.approx n x) / 2`. For each `x` this is a monotone family of functions that are equal to zero on `c.C` and are equal to one outside of `c.U`. We also have `c.approx n x ∈ [0, 1]` for all `c`, `n`, and `x`. Let `urysohns.CU.lim c` be the supremum (or equivalently, the limit) of `c.approx n`. Then properties of `urysohns.CU.approx` immediately imply that * `c.lim x ∈ [0, 1]` for all `x`; * `c.lim` equals zero on `c.C` and equals one outside of `c.U`; * `c.lim x = (c.left.lim x + c.right.lim x) / 2`. In order to prove that `c.lim` is continuous at `x`, we prove by induction on `n : ℕ` that for `y` in a small neighborhood of `x` we have `|c.lim y - c.lim x| ≤ (3 / 4) ^ n`. Induction base follows from `c.lim x ∈ [0, 1]`, `c.lim y ∈ [0, 1]`. For the induction step, consider two cases: * `x ∈ c.left.U`; then for `y` in a small neighborhood of `x` we have `y ∈ c.left.U ⊆ c.right.C` (hence `c.right.lim x = c.right.lim y = 0`) and `|c.left.lim y - c.left.lim x| ≤ (3 / 4) ^ n`. Then `|c.lim y - c.lim x| = |c.left.lim y - c.left.lim x| / 2 ≤ (3 / 4) ^ n / 2 < (3 / 4) ^ (n + 1)`. * otherwise, `x ∉ c.left.right.C`; then for `y` in a small neighborhood of `x` we have `y ∉ c.left.right.C ⊇ c.left.left.U` (hence `c.left.left.lim x = c.left.left.lim y = 1`), `|c.left.right.lim y - c.left.right.lim x| ≤ (3 / 4) ^ n`, and `|c.right.lim y - c.right.lim x| ≤ (3 / 4) ^ n`. Combining these inequalities, the triangle inequality, and the recurrence formula for `c.lim`, we get `|c.lim x - c.lim y| ≤ (3 / 4) ^ (n + 1)`. The actual formalization uses `midpoint ℝ x y` instead of `(x + y) / 2` because we have more API lemmas about `midpoint`. ## Tags Urysohn's lemma, normal topological space -/ variables {X : Type*} [topological_space X] open set filter topological_space open_locale topological_space filter namespace urysohns /-- An auxiliary type for the proof of Urysohn's lemma: a pair of a closed set `C` and its open neighborhood `U`. -/ @[protect_proj] structure CU (X : Type*) [topological_space X] := (C U : set X) (closed_C : is_closed C) (open_U : is_open U) (subset : C ⊆ U) instance : inhabited (CU X) := ⟨⟨∅, univ, is_closed_empty, is_open_univ, empty_subset _⟩⟩ variable [normal_space X] namespace CU /-- Due to `normal_exists_closure_subset`, for each `c : CU X` there exists an open set `u` such chat `c.C ⊆ u` and `closure u ⊆ c.U`. `c.left` is the pair `(c.C, u)`. -/ @[simps C] def left (c : CU X) : CU X := { C := c.C, U := (normal_exists_closure_subset c.closed_C c.open_U c.subset).some, closed_C := c.closed_C, open_U := (normal_exists_closure_subset c.closed_C c.open_U c.subset).some_spec.1, subset := (normal_exists_closure_subset c.closed_C c.open_U c.subset).some_spec.2.1 } /-- Due to `normal_exists_closure_subset`, for each `c : CU X` there exists an open set `u` such chat `c.C ⊆ u` and `closure u ⊆ c.U`. `c.right` is the pair `(closure u, c.U)`. -/ @[simps U] def right (c : CU X) : CU X := { C := closure (normal_exists_closure_subset c.closed_C c.open_U c.subset).some, U := c.U, closed_C := is_closed_closure, open_U := c.open_U, subset := (normal_exists_closure_subset c.closed_C c.open_U c.subset).some_spec.2.2 } lemma left_U_subset_right_C (c : CU X) : c.left.U ⊆ c.right.C := subset_closure lemma left_U_subset (c : CU X) : c.left.U ⊆ c.U := subset.trans c.left_U_subset_right_C c.right.subset lemma subset_right_C (c : CU X) : c.C ⊆ c.right.C := subset.trans c.left.subset c.left_U_subset_right_C /-- `n`-th approximation to a continuous function `f : X → ℝ` such that `f = 0` on `c.C` and `f = 1` outside of `c.U`. -/ noncomputable def approx : ℕ → CU X → X → ℝ | 0 c x := indicator c.Uᶜ 1 x | (n + 1) c x := midpoint ℝ (approx n c.left x) (approx n c.right x) lemma approx_of_mem_C (c : CU X) (n : ℕ) {x : X} (hx : x ∈ c.C) : c.approx n x = 0 := begin induction n with n ihn generalizing c, { exact indicator_of_not_mem (λ hU, hU $ c.subset hx) _ }, { simp only [approx], rw [ihn, ihn, midpoint_self], exacts [c.subset_right_C hx, hx] } end lemma approx_of_nmem_U (c : CU X) (n : ℕ) {x : X} (hx : x ∉ c.U) : c.approx n x = 1 := begin induction n with n ihn generalizing c, { exact indicator_of_mem hx _ }, { simp only [approx], rw [ihn, ihn, midpoint_self], exacts [hx, λ hU, hx $ c.left_U_subset hU] } end lemma approx_nonneg (c : CU X) (n : ℕ) (x : X) : 0 ≤ c.approx n x := begin induction n with n ihn generalizing c, { exact indicator_nonneg (λ _ _, zero_le_one) _ }, { simp only [approx, midpoint_eq_smul_add, inv_of_eq_inv], refine mul_nonneg (inv_nonneg.2 zero_le_two) (add_nonneg _ _); apply ihn } end lemma approx_le_one (c : CU X) (n : ℕ) (x : X) : c.approx n x ≤ 1 := begin induction n with n ihn generalizing c, { exact indicator_apply_le' (λ _, le_rfl) (λ _, zero_le_one) }, { simp only [approx, midpoint_eq_smul_add, inv_of_eq_inv, smul_eq_mul, ← div_eq_inv_mul], refine iff.mpr (div_le_one zero_lt_two) (add_le_add _ _); apply ihn } end lemma bdd_above_range_approx (c : CU X) (x : X) : bdd_above (range $ λ n, c.approx n x) := ⟨1, λ y ⟨n, hn⟩, hn ▸ c.approx_le_one n x⟩ lemma approx_le_approx_of_U_sub_C {c₁ c₂ : CU X} (h : c₁.U ⊆ c₂.C) (n₁ n₂ : ℕ) (x : X) : c₂.approx n₂ x ≤ c₁.approx n₁ x := begin by_cases hx : x ∈ c₁.U, { calc approx n₂ c₂ x = 0 : approx_of_mem_C _ _ (h hx) ... ≤ approx n₁ c₁ x : approx_nonneg _ _ _ }, { calc approx n₂ c₂ x ≤ 1 : approx_le_one _ _ _ ... = approx n₁ c₁ x : (approx_of_nmem_U _ _ hx).symm } end lemma approx_mem_Icc_right_left (c : CU X) (n : ℕ) (x : X) : c.approx n x ∈ Icc (c.right.approx n x) (c.left.approx n x) := begin induction n with n ihn generalizing c, { exact ⟨le_rfl, indicator_le_indicator_of_subset (compl_subset_compl.2 c.left_U_subset) (λ _, zero_le_one) _⟩ }, { simp only [approx, mem_Icc], refine ⟨midpoint_le_midpoint _ (ihn _).1, midpoint_le_midpoint (ihn _).2 _⟩; apply approx_le_approx_of_U_sub_C, exacts [subset_closure, subset_closure] } end lemma approx_le_succ (c : CU X) (n : ℕ) (x : X) : c.approx n x ≤ c.approx (n + 1) x := begin induction n with n ihn generalizing c, { simp only [approx, right_U, right_le_midpoint], exact (approx_mem_Icc_right_left c 0 x).2 }, { rw [approx, approx], exact midpoint_le_midpoint (ihn _) (ihn _) } end lemma approx_mono (c : CU X) (x : X) : monotone (λ n, c.approx n x) := monotone_nat_of_le_succ $ λ n, c.approx_le_succ n x /-- A continuous function `f : X → ℝ` such that * `0 ≤ f x ≤ 1` for all `x`; * `f` equals zero on `c.C` and equals one outside of `c.U`; -/ protected noncomputable def lim (c : CU X) (x : X) : ℝ := ⨆ n, c.approx n x lemma tendsto_approx_at_top (c : CU X) (x : X) : tendsto (λ n, c.approx n x) at_top (𝓝 $ c.lim x) := tendsto_at_top_csupr (c.approx_mono x) ⟨1, λ x ⟨n, hn⟩, hn ▸ c.approx_le_one _ _⟩ lemma lim_of_mem_C (c : CU X) (x : X) (h : x ∈ c.C) : c.lim x = 0 := by simp only [CU.lim, approx_of_mem_C, h, csupr_const] lemma lim_of_nmem_U (c : CU X) (x : X) (h : x ∉ c.U) : c.lim x = 1 := by simp only [CU.lim, approx_of_nmem_U c _ h, csupr_const] lemma lim_eq_midpoint (c : CU X) (x : X) : c.lim x = midpoint ℝ (c.left.lim x) (c.right.lim x) := begin refine tendsto_nhds_unique (c.tendsto_approx_at_top x) ((tendsto_add_at_top_iff_nat 1).1 _), simp only [approx], exact (c.left.tendsto_approx_at_top x).midpoint (c.right.tendsto_approx_at_top x) end lemma approx_le_lim (c : CU X) (x : X) (n : ℕ) : c.approx n x ≤ c.lim x := le_csupr (c.bdd_above_range_approx x) _ lemma lim_nonneg (c : CU X) (x : X) : 0 ≤ c.lim x := (c.approx_nonneg 0 x).trans (c.approx_le_lim x 0) lemma lim_le_one (c : CU X) (x : X) : c.lim x ≤ 1 := csupr_le $ λ n, c.approx_le_one _ _ lemma lim_mem_Icc (c : CU X) (x : X) : c.lim x ∈ Icc (0 : ℝ) 1 := ⟨c.lim_nonneg x, c.lim_le_one x⟩ /-- Continuity of `urysohns.CU.lim`. See module docstring for a sketch of the proofs. -/ lemma continuous_lim (c : CU X) : continuous c.lim := begin obtain ⟨h0, h1234, h1⟩ : 0 < (2⁻¹ : ℝ) ∧ (2⁻¹ : ℝ) < 3 / 4 ∧ (3 / 4 : ℝ) < 1 := by norm_num, refine continuous_iff_continuous_at.2 (λ x, (metric.nhds_basis_closed_ball_pow (h0.trans h1234) h1).tendsto_right_iff.2 $ λ n _, _), simp only [metric.mem_closed_ball], induction n with n ihn generalizing c, { refine eventually_of_forall (λ y, _), rw pow_zero, exact real.dist_le_of_mem_Icc_01 (c.lim_mem_Icc _) (c.lim_mem_Icc _) }, { by_cases hxl : x ∈ c.left.U, { filter_upwards [is_open.mem_nhds c.left.open_U hxl, ihn c.left], intros y hyl hyd, rw [pow_succ, c.lim_eq_midpoint, c.lim_eq_midpoint, c.right.lim_of_mem_C _ (c.left_U_subset_right_C hyl), c.right.lim_of_mem_C _ (c.left_U_subset_right_C hxl)], refine (dist_midpoint_midpoint_le _ _ _ _).trans _, rw [dist_self, add_zero, div_eq_inv_mul], exact mul_le_mul h1234.le hyd dist_nonneg (h0.trans h1234).le }, { replace hxl : x ∈ c.left.right.Cᶜ, from compl_subset_compl.2 c.left.right.subset hxl, filter_upwards [is_open.mem_nhds (is_open_compl_iff.2 c.left.right.closed_C) hxl, ihn c.left.right, ihn c.right], intros y hyl hydl hydr, replace hxl : x ∉ c.left.left.U, from compl_subset_compl.2 c.left.left_U_subset_right_C hxl, replace hyl : y ∉ c.left.left.U, from compl_subset_compl.2 c.left.left_U_subset_right_C hyl, simp only [pow_succ, c.lim_eq_midpoint, c.left.lim_eq_midpoint, c.left.left.lim_of_nmem_U _ hxl, c.left.left.lim_of_nmem_U _ hyl], refine (dist_midpoint_midpoint_le _ _ _ _).trans _, refine (div_le_div_of_le_of_nonneg (add_le_add_right (dist_midpoint_midpoint_le _ _ _ _) _) zero_le_two).trans _, rw [dist_self, zero_add], refine (div_le_div_of_le_of_nonneg (add_le_add (div_le_div_of_le_of_nonneg hydl zero_le_two) hydr) zero_le_two).trans_eq _, generalize : (3 / 4 : ℝ) ^ n = r, field_simp [(@zero_lt_two ℝ _ _).ne'], ring } } end end CU end urysohns variable [normal_space X] /-- Urysohns lemma: if `s` and `t` are two disjoint closed sets in a normal topological space `X`, then there exists a continuous function `f : X → ℝ` such that * `f` equals zero on `s`; * `f` equals one on `t`; * `0 ≤ f x ≤ 1` for all `x`. -/ lemma exists_continuous_zero_one_of_closed {s t : set X} (hs : is_closed s) (ht : is_closed t) (hd : disjoint s t) : ∃ f : C(X, ℝ), eq_on f 0 s ∧ eq_on f 1 t ∧ ∀ x, f x ∈ Icc (0 : ℝ) 1 := begin -- The actual proof is in the code above. Here we just repack it into the expected format. set c : urysohns.CU X := ⟨s, tᶜ, hs, ht.is_open_compl, λ _, disjoint_left.1 hd⟩, exact ⟨⟨c.lim, c.continuous_lim⟩, c.lim_of_mem_C, λ x hx, c.lim_of_nmem_U _ (λ h, h hx), c.lim_mem_Icc⟩ end
2cdae5815ffbc046d0158ca2e3f1d913d92c9901
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/ring/ulift.lean
d09849d02ccc1af98a4654dc5c33dc916a9baa71
[ "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,820
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.group.ulift import algebra.ring.equiv /-! # `ulift` instances for ring This file defines instances for ring, semiring and related structures on `ulift` types. (Recall `ulift α` is just a "copy" of a type `α` in a higher universe.) We also provide `ulift.ring_equiv : ulift R ≃+* R`. -/ universes u v variables {α : Type u} {x y : ulift.{v} α} namespace ulift instance mul_zero_class [mul_zero_class α] : mul_zero_class (ulift α) := by refine_struct { zero := (0 : ulift α), mul := (*), .. }; tactic.pi_instance_derive_field instance distrib [distrib α] : distrib (ulift α) := by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance non_unital_non_assoc_semiring [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul, }; tactic.pi_instance_derive_field instance non_assoc_semiring [non_assoc_semiring α] : non_assoc_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul }; tactic.pi_instance_derive_field instance non_unital_semiring [non_unital_semiring α] : non_unital_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul, }; tactic.pi_instance_derive_field instance semiring [semiring α] : semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul, npow := monoid.npow }; tactic.pi_instance_derive_field /-- The ring equivalence between `ulift α` and `α`. -/ def ring_equiv [non_unital_non_assoc_semiring α] : ulift α ≃+* α := { to_fun := ulift.down, inv_fun := ulift.up, map_mul' := λ x y, rfl, map_add' := λ x y, rfl, left_inv := by tidy, right_inv := by tidy, } instance non_unital_comm_semiring [non_unital_comm_semiring α] : non_unital_comm_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), nsmul := add_monoid.nsmul }; tactic.pi_instance_derive_field instance comm_semiring [comm_semiring α] : comm_semiring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), nsmul := add_monoid.nsmul, npow := monoid.npow }; tactic.pi_instance_derive_field instance non_unital_non_assoc_ring [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance non_unital_ring [non_unital_ring α] : non_unital_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance non_assoc_ring [non_assoc_ring α] : non_assoc_ring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance ring [ring α] : ring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, npow := monoid.npow, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance non_unital_comm_ring [non_unital_comm_ring α] : non_unital_comm_ring (ulift α) := by refine_struct { zero := (0 : ulift α), add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance comm_ring [comm_ring α] : comm_ring (ulift α) := by refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, npow := monoid.npow, zsmul := sub_neg_monoid.zsmul }; tactic.pi_instance_derive_field instance field [field α] : field (ulift α) := begin refine_struct { zero := (0 : ulift α), one := 1, add := (+), mul := (*), sub := has_sub.sub, neg := has_neg.neg, nsmul := add_monoid.nsmul, npow := monoid.npow, zsmul := sub_neg_monoid.zsmul, inv := has_inv.inv, div := has_div.div, zpow := λ n a, ulift.up (a.down ^ n), exists_pair_ne := ulift.nontrivial.1 }; tactic.pi_instance_derive_field, -- `mul_inv_cancel` requires special attention: it leaves the goal `∀ {a}, a ≠ 0 → a * a⁻¹ = 1`. cases a, tauto end end ulift
2e1250ed5f11c1e01f0f960660102f4b6525cdcf
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebraic_geometry/EllipticCurve.lean
0e9a84eddac20a945c7e685b38b5124f64add560
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,041
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import algebra.group_power import data.rat.basic import tactic.norm_num /-! # The category of elliptic curves (over a field or a PID) We give a working definition of elliptic curves which is mathematically accurate in many cases, and also good for computation. ## Mathematical background Let `S` be a scheme. The actual category of elliptic curves over `S` is a large category, whose objects are schemes `E` equipped with a map `E → S`, a section `S → E`, and some axioms (the map is smooth and proper and the fibres are geometrically connected group varieties of dimension 1). In the special case where `S` is `Spec R` for some commutative ring `R` whose Picard group is trivial (this includes all fields, all principal ideal domains, and many other commutative rings) then it can be shown (using rather a lot of algebro-geometric machinery) that every elliptic curve is, up to isomorphism, a projective plane cubic defined by the equation `y^2+a₁xy+a₃y=x^3+a₂x^2+a₄x+a₆`, with `aᵢ : R`, and such that the discriminant of the aᵢ is a unit in `R`. Some more details of the construction can be found on pages 66-69 of [N. Katz and B. Mazur, *Arithmetic moduli of elliptic curves*][katz_mazur] or pages 53-56 of [P. Deligne, *Courbes elliptiques: formulaire d'après J. Tate*][deligne_formulaire]. ## Warning The definition in this file makes sense for all commutative rings `R`, but it only gives a type which can be beefed up to a category which is equivalent to the category of elliptic curves over `Spec R` in the case that `R` has trivial Picard group or, slightly more generally, when the 12-torsion of Pic(R) is trivial. The issue is that for a general ring R, there might be elliptic curves over Spec(R) in the sense of algebraic geometry which are not globally defined by a cubic equation valid over the entire base. ## TODO Define the R-points (or even A-points if A is an R-algebra). Care will be needed at infinity if R is not a field. Define the group law on the R-points. (hard) prove associativity. -/ /-- The discriminant of the plane cubic `Y^2+a1*X*Y+a3*Y=X^3+a2*X^2+a4*X+a6`. If `R` is a field then this polynomial vanishes iff the cubic curve cut out by this equation is singular. -/ def EllipticCurve.disc_aux {R : Type*} [comm_ring R] (a1 a2 a3 a4 a6 : R) : R := -432*a6^2 + ((288*a2 + 72*a1^2)*a4 + (-216*a3^2 + (144*a1*a2 + 36*a1^3)*a3 + (-64*a2^3 - 48*a1^2*a2^2 - 12*a1^4*a2 - a1^6)))*a6 + (-64*a4^3 + (-96*a1*a3 + (16*a2^2 + 8*a1^2*a2 + a1^4))*a4^2 + ((72*a2 - 30*a1^2)*a3^2 + (16*a1*a2^2 + 8*a1^3*a2 + a1^5)*a3)*a4 + (-27*a3^4 + (36*a1*a2 + a1^3)*a3^3 + (-16*a2^3 - 8*a1^2*a2^2 - a1^4*a2)*a3^2)) -- If Pic(R)[12]=0 then this definition is mathematically correct /-- The category of elliptic curves over `R` (note that this definition is only mathematically correct for certain rings, for example if `R` is a field or a PID). -/ structure EllipticCurve (R : Type*) [comm_ring R] := (a1 a2 a3 a4 a6 : R) (disc_unit : units R) (disc_unit_eq : (disc_unit : R) = EllipticCurve.disc_aux a1 a2 a3 a4 a6) namespace EllipticCurve instance : inhabited (EllipticCurve ℚ) := ⟨⟨0,0,1,-1,0, ⟨37, 37⁻¹, by norm_num, by norm_num⟩, show (37 : ℚ) = _ + _, by norm_num⟩⟩ variables {R : Type*} [comm_ring R] (E : EllipticCurve R) /-- The discriminant of an elliptic curve. Sometimes only defined up to sign in the literature; we choose the sign used by the LMFDB. See [the LMFDB page on discriminants](https://www.lmfdb.org/knowledge/show/ec.discriminant) for more discussion. -/ def disc : R := disc_aux E.a1 E.a2 E.a3 E.a4 E.a6 lemma disc_is_unit : is_unit E.disc := begin convert units.is_unit E.disc_unit, exact E.disc_unit_eq.symm end /-- The j-invariant of an elliptic curve. -/ def j := (-48*E.a4 + (-24*E.a1*E.a3 + (16*E.a2^2 + 8*E.a1^2*E.a2 + E.a1^4)))^3 * (E.disc_unit⁻¹ : units R) end EllipticCurve
ffbe274c8606b89e72751ebb51e8ed94ad32354a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/free_comm_ring.lean
7a3211dfad72a595aab2830917b92eecab7f0bf9
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,162
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Johan Commelin -/ import data.mv_polynomial.equiv import data.mv_polynomial.comm_ring import logic.equiv.functor import ring_theory.free_ring /-! # Free commutative rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The theory of the free commutative ring generated by a type `α`. It is isomorphic to the polynomial ring over ℤ with variables in `α` ## Main definitions * `free_comm_ring α` : the free commutative ring on a type α * `lift (f : α → R)` : the ring hom `free_comm_ring α →+* R` induced by functoriality from `f`. * `map (f : α → β)` : the ring hom `free_comm_ring α →*+ free_comm_ring β` induced by functoriality from f. ## Main results `free_comm_ring` has functorial properties (it is an adjoint to the forgetful functor). In this file we have: * `of : α → free_comm_ring α` * `lift (f : α → R) : free_comm_ring α →+* R` * `map (f : α → β) : free_comm_ring α →+* free_comm_ring β` * `free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ` : `free_comm_ring α` is isomorphic to a polynomial ring. ## Implementation notes `free_comm_ring α` is implemented not using `mv_polynomial` but directly as the free abelian group on `multiset α`, the type of monomials in this free commutative ring. ## Tags free commutative ring, free ring -/ noncomputable theory open_locale classical polynomial universes u v variables (α : Type u) /-- `free_comm_ring α` is the free commutative ring on the type `α`. -/ @[derive [comm_ring, inhabited]] def free_comm_ring (α : Type u) : Type u := free_abelian_group $ multiplicative $ multiset α namespace free_comm_ring variables {α} /-- The canonical map from `α` to the free commutative ring on `α`. -/ def of (x : α) : free_comm_ring α := free_abelian_group.of $ multiplicative.of_add ({x} : multiset α) lemma of_injective : function.injective (of : α → free_comm_ring α) := free_abelian_group.of_injective.comp (λ x y, (multiset.coe_eq_coe.trans list.singleton_perm_singleton).mp) @[elab_as_eliminator] protected lemma induction_on {C : free_comm_ring α → Prop} (z : free_comm_ring α) (hn1 : C (-1)) (hb : ∀ b, C (of b)) (ha : ∀ x y, C x → C y → C (x + y)) (hm : ∀ x y, C x → C y → C (x * y)) : C z := have hn : ∀ x, C x → C (-x), from λ x ih, neg_one_mul x ▸ hm _ _ hn1 ih, have h1 : C 1, from neg_neg (1 : free_comm_ring α) ▸ hn _ hn1, free_abelian_group.induction_on z (add_left_neg (1 : free_comm_ring α) ▸ ha _ _ hn1 h1) (λ m, multiset.induction_on m h1 $ λ a m ih, hm _ _ (hb a) ih) (λ m ih, hn _ ih) ha section lift variables {R : Type v} [comm_ring R] (f : α → R) /-- A helper to implement `lift`. This is essentially `free_comm_monoid.lift`, but this does not currently exist. -/ private def lift_to_multiset : (α → R) ≃ (multiplicative (multiset α) →* R) := { to_fun := λ f, { to_fun := λ s, (s.to_add.map f).prod, map_mul' := λ x y, calc _ = multiset.prod ((multiset.map f x) + (multiset.map f y)) : by {congr' 1, exact multiset.map_add _ _ _} ... = _ : multiset.prod_add _ _, map_one' := rfl}, inv_fun := λ F x, F (multiplicative.of_add ({x} : multiset α)), left_inv := λ f, funext $ λ x, show (multiset.map f {x}).prod = _, by simp, right_inv := λ F, monoid_hom.ext $ λ x, let F' := F.to_additive'', x' := x.to_add in show (multiset.map (λ a, F' {a}) x').sum = F' x', begin rw [←multiset.map_map, ←add_monoid_hom.map_multiset_sum], exact F.congr_arg (multiset.sum_map_singleton x'), end } /-- Lift a map `α → R` to a additive group homomorphism `free_comm_ring α → R`. For a version producing a bundled homomorphism, see `lift_hom`. -/ def lift : (α → R) ≃ (free_comm_ring α →+* R) := equiv.trans lift_to_multiset free_abelian_group.lift_monoid @[simp] lemma lift_of (x : α) : lift f (of x) = f x := (free_abelian_group.lift.of _ _).trans $ mul_one _ @[simp] lemma lift_comp_of (f : free_comm_ring α →+* R) : lift (f ∘ of) = f := ring_hom.ext $ λ x, free_comm_ring.induction_on x (by rw [ring_hom.map_neg, ring_hom.map_one, f.map_neg, f.map_one]) (lift_of _) (λ x y ihx ihy, by rw [ring_hom.map_add, f.map_add, ihx, ihy]) (λ x y ihx ihy, by rw [ring_hom.map_mul, f.map_mul, ihx, ihy]) @[ext] lemma hom_ext ⦃f g : free_comm_ring α →+* R⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := lift.symm.injective (funext h) end lift variables {β : Type v} (f : α → β) /-- A map `f : α → β` produces a ring homomorphism `free_comm_ring α →+* free_comm_ring β`. -/ def map : free_comm_ring α →+* free_comm_ring β := lift $ of ∘ f @[simp] lemma map_of (x : α) : map f (of x) = of (f x) := lift_of _ _ /-- `is_supported x s` means that all monomials showing up in `x` have variables in `s`. -/ def is_supported (x : free_comm_ring α) (s : set α) : Prop := x ∈ subring.closure (of '' s) section is_supported variables {x y : free_comm_ring α} {s t : set α} theorem is_supported_upwards (hs : is_supported x s) (hst : s ⊆ t) : is_supported x t := subring.closure_mono (set.monotone_image hst) hs theorem is_supported_add (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x + y) s := subring.add_mem _ hxs hys theorem is_supported_neg (hxs : is_supported x s) : is_supported (-x) s := subring.neg_mem _ hxs theorem is_supported_sub (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x - y) s := subring.sub_mem _ hxs hys theorem is_supported_mul (hxs : is_supported x s) (hys : is_supported y s) : is_supported (x * y) s := subring.mul_mem _ hxs hys theorem is_supported_zero : is_supported 0 s := subring.zero_mem _ theorem is_supported_one : is_supported 1 s := subring.one_mem _ theorem is_supported_int {i : ℤ} {s : set α} : is_supported ↑i s := int.induction_on i is_supported_zero (λ i hi, by rw [int.cast_add, int.cast_one]; exact is_supported_add hi is_supported_one) (λ i hi, by rw [int.cast_sub, int.cast_one]; exact is_supported_sub hi is_supported_one) end is_supported /-- The restriction map from `free_comm_ring α` to `free_comm_ring s` where `s : set α`, defined by sending all variables not in `s` to zero. -/ def restriction (s : set α) [decidable_pred (∈ s)] : free_comm_ring α →+* free_comm_ring s := lift (λ p, if H : p ∈ s then of (⟨p, H⟩ : s) else 0) section restriction variables (s : set α) [decidable_pred (∈ s)] (x y : free_comm_ring α) @[simp] lemma restriction_of (p) : restriction s (of p) = if H : p ∈ s then of ⟨p, H⟩ else 0 := lift_of _ _ end restriction theorem is_supported_of {p} {s : set α} : is_supported (of p) s ↔ p ∈ s := suffices is_supported (of p) s → p ∈ s, from ⟨this, λ hps, subring.subset_closure ⟨p, hps, rfl⟩⟩, assume hps : is_supported (of p) s, begin haveI := classical.dec_pred s, have : ∀ x, is_supported x s → ∃ (n : ℤ), lift (λ a, if a ∈ s then (0 : ℤ[X]) else polynomial.X) x = n, { intros x hx, refine subring.in_closure.rec_on hx _ _ _ _, { use 1, rw [ring_hom.map_one], norm_cast }, { use -1, rw [ring_hom.map_neg, ring_hom.map_one, int.cast_neg, int.cast_one] }, { rintros _ ⟨z, hzs, rfl⟩ _ _, use 0, rw [ring_hom.map_mul, lift_of, if_pos hzs, zero_mul], norm_cast }, { rintros x y ⟨q, hq⟩ ⟨r, hr⟩, refine ⟨q+r, _⟩, rw [ring_hom.map_add, hq, hr], norm_cast } }, specialize this (of p) hps, rw [lift_of] at this, split_ifs at this, { exact h }, exfalso, apply ne.symm int.zero_ne_one, rcases this with ⟨w, H⟩, rw ←polynomial.C_eq_int_cast at H, have : polynomial.X.coeff 1 = (polynomial.C ↑w).coeff 1, by rw H, rwa [polynomial.coeff_C, if_neg (one_ne_zero : 1 ≠ 0), polynomial.coeff_X, if_pos rfl] at this end theorem map_subtype_val_restriction {x} (s : set α) [decidable_pred (∈ s)] (hxs : is_supported x s) : map (subtype.val : s → α) (restriction s x) = x := begin refine subring.in_closure.rec_on hxs _ _ _ _, { rw ring_hom.map_one, refl }, { rw [ring_hom.map_neg, ring_hom.map_neg, ring_hom.map_one], refl }, { rintros _ ⟨p, hps, rfl⟩ n ih, rw [ring_hom.map_mul, restriction_of, dif_pos hps, ring_hom.map_mul, map_of, ih] }, { intros x y ihx ihy, rw [ring_hom.map_add, ring_hom.map_add, ihx, ihy] } end theorem exists_finite_support (x : free_comm_ring α) : ∃ s : set α, set.finite s ∧ is_supported x s := free_comm_ring.induction_on x ⟨∅, set.finite_empty, is_supported_neg is_supported_one⟩ (λ p, ⟨{p}, set.finite_singleton p, is_supported_of.2 $ set.mem_singleton _⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_add (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) (λ x y ⟨s, hfs, hxs⟩ ⟨t, hft, hxt⟩, ⟨s ∪ t, hfs.union hft, is_supported_mul (is_supported_upwards hxs $ set.subset_union_left s t) (is_supported_upwards hxt $ set.subset_union_right s t)⟩) theorem exists_finset_support (x : free_comm_ring α) : ∃ s : finset α, is_supported x ↑s := let ⟨s, hfs, hxs⟩ := exists_finite_support x in ⟨hfs.to_finset, by rwa set.finite.coe_to_finset⟩ end free_comm_ring namespace free_ring open function variable (α) /-- The canonical ring homomorphism from the free ring generated by `α` to the free commutative ring generated by `α`. -/ def to_free_comm_ring {α} : free_ring α →+* free_comm_ring α := free_ring.lift free_comm_ring.of instance : has_coe (free_ring α) (free_comm_ring α) := ⟨to_free_comm_ring⟩ /-- The natural map `free_ring α → free_comm_ring α`, as a `ring_hom`. -/ def coe_ring_hom : free_ring α →+* free_comm_ring α := to_free_comm_ring @[simp, norm_cast] protected lemma coe_zero : ↑(0 : free_ring α) = (0 : free_comm_ring α) := rfl @[simp, norm_cast] protected lemma coe_one : ↑(1 : free_ring α) = (1 : free_comm_ring α) := rfl variable {α} @[simp] protected lemma coe_of (a : α) : ↑(free_ring.of a) = free_comm_ring.of a := free_ring.lift_of _ _ @[simp, norm_cast] protected lemma coe_neg (x : free_ring α) : ↑(-x) = -(x : free_comm_ring α) := (free_ring.lift _).map_neg _ @[simp, norm_cast] protected lemma coe_add (x y : free_ring α) : ↑(x + y) = (x : free_comm_ring α) + y := (free_ring.lift _).map_add _ _ @[simp, norm_cast] protected lemma coe_sub (x y : free_ring α) : ↑(x - y) = (x : free_comm_ring α) - y := (free_ring.lift _).map_sub _ _ @[simp, norm_cast] protected lemma coe_mul (x y : free_ring α) : ↑(x * y) = (x : free_comm_ring α) * y := (free_ring.lift _).map_mul _ _ variable (α) protected lemma coe_surjective : surjective (coe : free_ring α → free_comm_ring α) := λ x, begin apply free_comm_ring.induction_on x, { use -1, refl }, { intro x, use free_ring.of x, refl }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x + y, exact (free_ring.lift _).map_add _ _ }, { rintros _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, use x * y, exact (free_ring.lift _).map_mul _ _ } end lemma coe_eq : (coe : free_ring α → free_comm_ring α) = @functor.map free_abelian_group _ _ _ (λ (l : list α), (l : multiset α)) := funext $ λ x, free_abelian_group.lift.unique _ _ $ λ L, by { simp_rw [free_abelian_group.lift.of, (∘)], exact free_monoid.rec_on L rfl (λ hd tl ih, by { rw [(free_monoid.lift _).map_mul, free_monoid.lift_eval_of, ih], refl }) } /-- If α has size at most 1 then the natural map from the free ring on `α` to the free commutative ring on `α` is an isomorphism of rings. -/ def subsingleton_equiv_free_comm_ring [subsingleton α] : free_ring α ≃+* free_comm_ring α := ring_equiv.of_bijective (coe_ring_hom _) begin have : (coe_ring_hom _ : free_ring α → free_comm_ring α) = (functor.map_equiv free_abelian_group (multiset.subsingleton_equiv α)) := coe_eq α, rw this, apply equiv.bijective, end instance [subsingleton α] : comm_ring (free_ring α) := { mul_comm := λ x y, by { rw [← (subsingleton_equiv_free_comm_ring α).symm_apply_apply (y * x), ((subsingleton_equiv_free_comm_ring α)).map_mul, mul_comm, ← ((subsingleton_equiv_free_comm_ring α)).map_mul, (subsingleton_equiv_free_comm_ring α).symm_apply_apply], }, .. free_ring.ring α } end free_ring /-- The free commutative ring on `α` is isomorphic to the polynomial ring over ℤ with variables in `α` -/ def free_comm_ring_equiv_mv_polynomial_int : free_comm_ring α ≃+* mv_polynomial α ℤ := ring_equiv.of_hom_inv (free_comm_ring.lift $ (λ a, mv_polynomial.X a : α → mv_polynomial α ℤ)) (mv_polynomial.eval₂_hom (int.cast_ring_hom (free_comm_ring α)) free_comm_ring.of) (by { ext, simp }) (by ext; simp) /-- The free commutative ring on the empty type is isomorphic to `ℤ`. -/ def free_comm_ring_pempty_equiv_int : free_comm_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (free_comm_ring_equiv_mv_polynomial_int _) (mv_polynomial.is_empty_ring_equiv _ pempty) /-- The free commutative ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_comm_ring_punit_equiv_polynomial_int : free_comm_ring punit.{u+1} ≃+* ℤ[X] := (free_comm_ring_equiv_mv_polynomial_int _).trans (mv_polynomial.punit_alg_equiv ℤ).to_ring_equiv open free_ring /-- The free ring on the empty type is isomorphic to `ℤ`. -/ def free_ring_pempty_equiv_int : free_ring pempty.{u+1} ≃+* ℤ := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_pempty_equiv_int /-- The free ring on a type with one term is isomorphic to `ℤ[X]`. -/ def free_ring_punit_equiv_polynomial_int : free_ring punit.{u+1} ≃+* ℤ[X] := ring_equiv.trans (subsingleton_equiv_free_comm_ring _) free_comm_ring_punit_equiv_polynomial_int
6830a8e7887d38d5fb5acd69a0a036c6f577e3ca
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/list/sigma.lean
404b7e0ebc98c13c9be9179050d58bf670b2961f
[ "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
23,985
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Sean Leather Functions on lists of sigma types. -/ import data.list.perm data.sigma universes u v namespace list variables {α : Type u} {β : α → Type v} /- keys -/ /-- List of keys from a list of key-value pairs -/ def keys : list (sigma β) → list α := map sigma.fst @[simp] theorem keys_nil : @keys α β [] = [] := rfl @[simp] theorem keys_cons {s} {l : list (sigma β)} : (s :: l).keys = s.1 :: l.keys := rfl theorem mem_keys_of_mem {s : sigma β} {l : list (sigma β)} : s ∈ l → s.1 ∈ l.keys := mem_map_of_mem sigma.fst theorem exists_of_mem_keys {a} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a), sigma.mk a b ∈ l := let ⟨⟨a', b'⟩, m, e⟩ := exists_of_mem_map h in eq.rec_on e (exists.intro b' m) theorem mem_keys {a} {l : list (sigma β)} : a ∈ l.keys ↔ ∃ (b : β a), sigma.mk a b ∈ l := ⟨exists_of_mem_keys, λ ⟨b, h⟩, mem_keys_of_mem h⟩ theorem not_mem_keys {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ b : β a, sigma.mk a b ∉ l := (not_iff_not_of_iff mem_keys).trans not_exists theorem not_eq_key {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ s : sigma β, s ∈ l → a ≠ s.1 := iff.intro (λ h₁ s h₂ e, absurd (mem_keys_of_mem h₂) (by rwa e at h₁)) (λ f h₁, let ⟨b, h₂⟩ := exists_of_mem_keys h₁ in f _ h₂ rfl) /- nodupkeys -/ def nodupkeys (l : list (sigma β)) : Prop := l.keys.nodup theorem nodupkeys_iff_pairwise {l} : nodupkeys l ↔ pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := pairwise_map _ @[simp] theorem nodupkeys_nil : @nodupkeys α β [] := pairwise.nil @[simp] theorem nodupkeys_cons {s : sigma β} {l : list (sigma β)} : nodupkeys (s::l) ↔ s.1 ∉ l.keys ∧ nodupkeys l := by simp [keys, nodupkeys] theorem nodupkeys.eq_of_fst_eq {l : list (sigma β)} (nd : nodupkeys l) {s s' : sigma β} (h : s ∈ l) (h' : s' ∈ l) : s.1 = s'.1 → s = s' := @forall_of_forall_of_pairwise _ (λ s s' : sigma β, s.1 = s'.1 → s = s') (λ s s' H h, (H h.symm).symm) _ (λ x h _, rfl) ((nodupkeys_iff_pairwise.1 nd).imp (λ s s' h h', (h h').elim)) _ h _ h' theorem nodupkeys.eq_of_mk_mem {a : α} {b b' : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) (h' : sigma.mk a b' ∈ l) : b = b' := by cases nd.eq_of_fst_eq h h' rfl; refl theorem nodupkeys_singleton (s : sigma β) : nodupkeys [s] := nodup_singleton _ theorem nodupkeys_of_sublist {l₁ l₂ : list (sigma β)} (h : l₁ <+ l₂) : nodupkeys l₂ → nodupkeys l₁ := nodup_of_sublist (map_sublist_map _ h) theorem nodup_of_nodupkeys {l : list (sigma β)} : nodupkeys l → nodup l := nodup_of_nodup_map _ theorem perm_nodupkeys {l₁ l₂ : list (sigma β)} (h : l₁ ~ l₂) : nodupkeys l₁ ↔ nodupkeys l₂ := perm_nodup $ perm_map _ h theorem nodupkeys_join {L : list (list (sigma β))} : nodupkeys (join L) ↔ (∀ l ∈ L, nodupkeys l) ∧ pairwise disjoint (L.map keys) := begin rw [nodupkeys_iff_pairwise, pairwise_join, pairwise_map], refine and_congr (ball_congr $ λ l h, by simp [nodupkeys_iff_pairwise]) _, apply iff_of_eq, congr', ext l₁ l₂, simp [keys, disjoint_iff_ne] end theorem nodup_enum_map_fst (l : list α) : (l.enum.map prod.fst).nodup := by simp [list.nodup_range] variables [decidable_eq α] /- lookup -/ /-- `lookup a l` is the first value in `l` corresponding to the key `a`, or `none` if no such element exists. -/ def lookup (a : α) : list (sigma β) → option (β a) | [] := none | (⟨a', b⟩ :: l) := if h : a' = a then some (eq.rec_on h b) else lookup l @[simp] theorem lookup_nil (a : α) : lookup a [] = @none (β a) := rfl @[simp] theorem lookup_cons_eq (l) (a : α) (b : β a) : lookup a (⟨a, b⟩::l) = some b := dif_pos rfl @[simp] theorem lookup_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup a (s::l) = lookup a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_is_some {a : α} : ∀ {l : list (sigma β)}, (lookup a l).is_some ↔ a ∈ l.keys | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, lookup_is_some] }, end theorem lookup_eq_none {a : α} {l : list (sigma β)} : lookup a l = none ↔ a ∉ l.keys := begin have := not_congr (@lookup_is_some _ _ _ a l), simp at this, refine iff.trans _ this, cases lookup a l; exact dec_trivial end theorem of_mem_lookup {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup a l → sigma.mk a b ∈ l | (⟨a', b'⟩ :: l) H := begin by_cases h : a = a', { subst a', simp at H, simp [H] }, { simp [h] at H, exact or.inr (of_mem_lookup H) } end theorem mem_lookup {a} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) (h : sigma.mk a b ∈ l) : b ∈ lookup a l := begin cases option.is_some_iff_exists.mp (lookup_is_some.mpr (mem_keys_of_mem h)) with b' h', cases nd.eq_of_mk_mem h (of_mem_lookup h'), exact h' end theorem map_lookup_eq_find (a : α) : ∀ l : list (sigma β), (lookup a l).map (sigma.mk a) = find (λ s, a = s.1) l | [] := rfl | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, map_lookup_eq_find] } end theorem mem_lookup_iff {a : α} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) : b ∈ lookup a l ↔ sigma.mk a b ∈ l := ⟨of_mem_lookup, mem_lookup nd⟩ theorem perm_lookup (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup a l₁ = lookup a l₂ := by ext b; simp [mem_lookup_iff, nd₁, nd₂]; exact mem_of_perm p lemma mem_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodup) (nd₁ : l₁.nodup) (h : ∀ x, x ∈ l₀ ↔ x ∈ l₁) : l₀ ~ l₁ := begin induction l₀ with x xs generalizing l₁; cases l₁ with x ys, { constructor }, iterate 2 { specialize h x, simp at h, cases h }, simp at nd₀ nd₁, rename x y, classical, cases nd₀, cases nd₁, by_cases h' : x = y, { subst y, constructor, apply l₀_ih ‹ _ › ‹ nodup ys ›, intro a, specialize h a, simp at h, by_cases h' : a = x, { subst a, rw ← not_iff_not, split; intro; assumption }, { simp [h'] at h, exact h } }, { transitivity x :: y :: ys.erase x, { constructor, apply l₀_ih ‹ _ ›, { simp, split, { intro, apply nd₁_left, apply mem_of_mem_erase a }, apply nodup_erase_of_nodup; assumption }, { intro a, specialize h a, simp at h, by_cases h' : a = x, { subst a, rw ← not_iff_not, split; intro, simp [mem_erase_of_nodup,*], assumption }, { simp [h'] at h, simp [h], apply or_congr, refl, simp [mem_erase_of_ne,*] } } }, transitivity y :: x :: ys.erase x, { constructor }, { constructor, symmetry, apply perm_erase, specialize h x, simp [h'] at h, exact h } } end lemma lookup_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodupkeys) (nd₁ : l₁.nodupkeys) (h : ∀ x y, y ∈ l₀.lookup x ↔ y ∈ l₁.lookup x) : l₀ ~ l₁ := mem_ext (nodup_of_nodupkeys nd₀) (nodup_of_nodupkeys nd₁) (λ ⟨a,b⟩, by rw [← mem_lookup_iff, ← mem_lookup_iff, h]; assumption) /- lookup_all -/ /-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/ def lookup_all (a : α) : list (sigma β) → list (β a) | [] := [] | (⟨a', b⟩ :: l) := if h : a' = a then eq.rec_on h b :: lookup_all l else lookup_all l @[simp] theorem lookup_all_nil (a : α) : lookup_all a [] = @nil (β a) := rfl @[simp] theorem lookup_all_cons_eq (l) (a : α) (b : β a) : lookup_all a (⟨a, b⟩::l) = b :: lookup_all a l := dif_pos rfl @[simp] theorem lookup_all_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup_all a (s::l) = lookup_all a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_all_eq_nil {a : α} : ∀ {l : list (sigma β)}, lookup_all a l = [] ↔ ∀ b : β a, sigma.mk a b ∉ l | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp, exact λ H, H b (or.inl rfl) }, { simp [h, lookup_all_eq_nil] }, end theorem head_lookup_all (a : α) : ∀ l : list (sigma β), head' (lookup_all a l) = lookup a l | [] := by simp | (⟨a', b⟩ :: l) := by by_cases h : a = a'; [{subst h, simp}, simp *] theorem mem_lookup_all {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup_all a l ↔ sigma.mk a b ∈ l | [] := by simp | (⟨a', b'⟩ :: l) := by by_cases h : a = a'; [{subst h, simp *}, simp *] theorem lookup_all_sublist (a : α) : ∀ l : list (sigma β), (lookup_all a l).map (sigma.mk a) <+ l | [] := by simp | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst h, simp, exact (lookup_all_sublist l).cons2 _ _ _ }, { simp [h], exact (lookup_all_sublist l).cons _ _ _ } end theorem lookup_all_length_le_one (a : α) {l : list (sigma β)} (h : l.nodupkeys) : length (lookup_all a l) ≤ 1 := by have := nodup_of_sublist (map_sublist_map _ $ lookup_all_sublist a l) h; rw map_map at this; rwa [← nodup_repeat, ← map_const _ a] theorem lookup_all_eq_lookup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : lookup_all a l = (lookup a l).to_list := begin rw ← head_lookup_all, have := lookup_all_length_le_one a h, revert this, rcases lookup_all a l with _|⟨b, _|⟨c, l⟩⟩; intro; try {refl}, exact absurd this dec_trivial end theorem lookup_all_nodup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : (lookup_all a l).nodup := by rw lookup_all_eq_lookup a h; apply option.to_list_nodup theorem perm_lookup_all (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup_all a l₁ = lookup_all a l₂ := by simp [lookup_all_eq_lookup, nd₁, nd₂, perm_lookup a nd₁ nd₂ p] /- kreplace -/ def kreplace (a : α) (b : β a) : list (sigma β) → list (sigma β) := lookmap $ λ s, if h : a = s.1 then some ⟨a, b⟩ else none theorem kreplace_of_forall_not (a : α) (b : β a) {l : list (sigma β)} (H : ∀ b : β a, sigma.mk a b ∉ l) : kreplace a b l = l := lookmap_of_forall_not _ $ begin rintro ⟨a', b'⟩ h, dsimp, split_ifs, { subst a', exact H _ h }, {refl} end theorem kreplace_self {a : α} {b : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) : kreplace a b l = l := begin refine (lookmap_congr _).trans (lookmap_id' (option.guard (λ s, a = s.1)) _ _), { rintro ⟨a', b'⟩ h', dsimp [option.guard], split_ifs, { subst a', exact ⟨rfl, heq_of_eq $ nd.eq_of_mk_mem h h'⟩ }, { refl } }, { rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, dsimp [option.guard], split_ifs, { subst a₁, rintro ⟨⟩, simp }, { rintro ⟨⟩ } }, end theorem keys_kreplace (a : α) (b : β a) : ∀ l : list (sigma β), (kreplace a b l).keys = l.keys := lookmap_map_eq _ _ $ by rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩; dsimp; split_ifs; simp [h] {contextual := tt} theorem kreplace_nodupkeys (a : α) (b : β a) {l : list (sigma β)} : (kreplace a b l).nodupkeys ↔ l.nodupkeys := by simp [nodupkeys, keys_kreplace] theorem perm_kreplace {a : α} {b : β a} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kreplace a b l₁ ~ kreplace a b l₂ := perm_lookmap _ $ begin refine (nodupkeys_iff_pairwise.1 nd).imp _, intros x y h z h₁ w h₂, split_ifs at h₁ h₂; cases h₁; cases h₂, exact (h (h_2.symm.trans h_1)).elim end /- kerase -/ /-- Remove the first pair with the key `a`. -/ def kerase (a : α) : list (sigma β) → list (sigma β) := erasep $ λ s, a = s.1 @[simp] theorem kerase_nil {a} : @kerase _ β _ a [] = [] := rfl @[simp] theorem kerase_cons_eq {a} {s : sigma β} {l : list (sigma β)} (h : a = s.1) : kerase a (s :: l) = l := by simp [kerase, h] @[simp] theorem kerase_cons_ne {a} {s : sigma β} {l : list (sigma β)} (h : a ≠ s.1) : kerase a (s :: l) = s :: kerase a l := by simp [kerase, h] @[simp] theorem kerase_of_not_mem_keys {a} {l : list (sigma β)} (h : a ∉ l.keys) : kerase a l = l := by induction l with _ _ ih; [refl, { simp [not_or_distrib] at h, simp [h.1, ih h.2] }] theorem kerase_sublist (a : α) (l : list (sigma β)) : kerase a l <+ l := erasep_sublist _ theorem kerase_keys_subset (a) (l : list (sigma β)) : (kerase a l).keys ⊆ l.keys := subset_of_sublist (map_sublist_map _ (kerase_sublist a l)) theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : list (sigma β)} : a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys := @kerase_keys_subset _ _ _ _ _ _ theorem exists_of_kerase {a : α} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a) (l₁ l₂ : list (sigma β)), a ∉ l₁.keys ∧ l = l₁ ++ ⟨a, b⟩ :: l₂ ∧ kerase a l = l₁ ++ l₂ := begin induction l, case list.nil { cases h }, case list.cons : hd tl ih { by_cases e : a = hd.1, { subst e, exact ⟨hd.2, [], tl, by simp, by cases hd; refl, by simp⟩ }, { simp at h, cases h, case or.inl : h { exact absurd h e }, case or.inr : h { rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩, exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁, by rw h₂; refl, by simp [e, h₃]⟩ } } } end @[simp] theorem mem_keys_kerase_of_ne {a₁ a₂} {l : list (sigma β)} (h : a₁ ≠ a₂) : a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys := iff.intro mem_keys_of_mem_keys_kerase $ λ p, if q : a₂ ∈ l.keys then match l, kerase a₂ l, exists_of_kerase q, p with | _, _, ⟨_, _, _, _, rfl, rfl⟩, p := by simpa [keys, h] using p end else by simp [q, p] theorem keys_kerase {a} {l : list (sigma β)} : (kerase a l).keys = l.keys.erase a := by rw [keys, kerase, ←erasep_map sigma.fst l, erase_eq_erasep] theorem kerase_kerase {a a'} {l : list (sigma β)} : (kerase a' l).kerase a = (kerase a l).kerase a' := begin by_cases a = a', { subst a' }, induction l with x xs, { refl }, { by_cases a' = x.1, { subst a', simp [kerase_cons_ne h,kerase_cons_eq rfl] }, by_cases h' : a = x.1, { subst a, simp [kerase_cons_eq rfl,kerase_cons_ne (ne.symm h)] }, { simp [kerase_cons_ne,*] } } end theorem kerase_nodupkeys (a : α) {l : list (sigma β)} : nodupkeys l → (kerase a l).nodupkeys := nodupkeys_of_sublist $ kerase_sublist _ _ theorem perm_kerase {a : α} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ := perm_erasep _ $ (nodupkeys_iff_pairwise.1 nd).imp $ by rintro x y h rfl; exact h @[simp] theorem not_mem_keys_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : a ∉ (kerase a l).keys := begin induction l, case list.nil { simp }, case list.cons : hd tl ih { simp at nd, by_cases h : a = hd.1, { subst h, simp [nd.1] }, { simp [h, ih nd.2] } } end @[simp] theorem lookup_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : lookup a (kerase a l) = none := lookup_eq_none.mpr (not_mem_keys_kerase a nd) @[simp] theorem lookup_kerase_ne {a a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kerase a' l) = lookup a l := begin induction l, case list.nil { refl }, case list.cons : hd tl ih { cases hd with ah bh, by_cases h₁ : a = ah; by_cases h₂ : a' = ah, { substs h₁ h₂, cases ne.irrefl h }, { subst h₁, simp [h₂] }, { subst h₂, simp [h] }, { simp [h₁, h₂, ih] } } end theorem kerase_append_left {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂ | [] _ h := by cases h | (s :: l₁) l₂ h₁ := if h₂ : a = s.1 then by simp [h₂] else by simp at h₁; cases h₁; [exact absurd h₁ h₂, simp [h₂, kerase_append_left h₁]] theorem kerase_append_right {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂ | [] _ h := rfl | (_ :: l₁) l₂ h := by simp [not_or_distrib] at h; simp [h.1, kerase_append_right h.2] theorem kerase_comm (a₁ a₂) (l : list (sigma β)) : kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) := if h : a₁ = a₂ then by simp [h] else if ha₁ : a₁ ∈ l.keys then if ha₂ : a₂ ∈ l.keys then match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with | _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, a₂_in_l₁_app_l₂ := if h' : a₂ ∈ l₁.keys then by simp [kerase_append_left h', kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)] else by simp [kerase_append_right h', kerase_append_right a₁_nin_l₁, @kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (ne.symm h)] end else by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂] else by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁] /- kinsert -/ /-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/ def kinsert (a : α) (b : β a) (l : list (sigma β)) : list (sigma β) := ⟨a, b⟩ :: kerase a l @[simp] theorem kinsert_def {a} {b : β a} {l : list (sigma β)} : kinsert a b l = ⟨a, b⟩ :: kerase a l := rfl @[simp] theorem mem_keys_kinsert {a a'} {b' : β a'} {l : list (sigma β)} : a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys := by by_cases h : a = a'; simp [h] theorem kinsert_nodupkeys (a) (b : β a) {l : list (sigma β)} (nd : l.nodupkeys) : (kinsert a b l).nodupkeys := nodupkeys_cons.mpr ⟨not_mem_keys_kerase a nd, kerase_nodupkeys a nd⟩ theorem perm_kinsert {a} {b : β a} {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (p : l₁ ~ l₂) : kinsert a b l₁ ~ kinsert a b l₂ := perm.skip ⟨a, b⟩ $ perm_kerase nd₁ p @[simp] theorem lookup_kinsert {a} {b : β a} (l : list (sigma β)) : lookup a (kinsert a b l) = some b := by simp only [kinsert, lookup_cons_eq] @[simp] theorem lookup_kinsert_ne {a a'} {b' : β a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kinsert a' b' l) = lookup a l := by simp [h, lookup_cons_ne _ ⟨a', b'⟩ h] /- kextract -/ def kextract (a : α) : list (sigma β) → option (β a) × list (sigma β) | [] := (none, []) | (s::l) := if h : s.1 = a then (some (eq.rec_on h s.2), l) else let (b', l') := kextract l in (b', s :: l') @[simp] theorem kextract_eq_lookup_kerase (a : α) : ∀ l : list (sigma β), kextract a l = (lookup a l, kerase a l) | [] := rfl | (⟨a', b⟩::l) := begin simp [kextract], dsimp, split_ifs, { subst a', simp [kerase] }, { simp [kextract, ne.symm h, kextract_eq_lookup_kerase l, kerase] } end /- erase_dupkeys -/ def erase_dupkeys : list (sigma β) → list (sigma β) := list.foldr (λ ⟨x,y⟩, kinsert x y) [] lemma erase_dupkeys_cons {x : α} {y : β x} (l : list (sigma β)) : erase_dupkeys (⟨x,y⟩ :: l) = kinsert x y (erase_dupkeys l) := rfl lemma nodupkeys_erase_dupkeys (l : list (sigma β)) : nodupkeys (erase_dupkeys l) := begin dsimp [erase_dupkeys], generalize hl : nil = l', have : nodupkeys l', { rw ← hl, apply nodup_nil }, clear hl, induction l with x xs, { apply this }, { cases x, simp [erase_dupkeys], split, { simp [keys_kerase], apply mem_erase_of_nodup l_ih }, apply kerase_nodupkeys _ l_ih, } end lemma lookup_erase_dupkeys (a : α) (l : list (sigma β)) : lookup a (erase_dupkeys l) = lookup a l := begin induction l, refl, cases l_hd with a' b, by_cases a = a', { subst a', rw [erase_dupkeys_cons,lookup_kinsert,lookup_cons_eq] }, { rw [erase_dupkeys_cons,lookup_kinsert_ne h,l_ih,lookup_cons_ne], exact h }, end /- kunion -/ /-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the first matching pair in l₂ is erased. -/ def kunion : list (sigma β) → list (sigma β) → list (sigma β) | [] l₂ := l₂ | (s :: l₁) l₂ := s :: kunion l₁ (kerase s.1 l₂) @[simp] theorem nil_kunion {l : list (sigma β)} : kunion [] l = l := rfl @[simp] theorem kunion_nil : ∀ {l : list (sigma β)}, kunion l [] = l | [] := rfl | (_ :: l) := by rw [kunion, kerase_nil, kunion_nil] @[simp] theorem kunion_cons {s} {l₁ l₂ : list (sigma β)} : kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) := rfl @[simp] theorem mem_keys_kunion {a} {l₁ l₂ : list (sigma β)} : a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s l₁ ih { by_cases h : a = s.1; [simp [h], simp [h, ih]] } end @[simp] theorem kunion_kerase {a} : ∀ {l₁ l₂ : list (sigma β)}, kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂) | [] _ := rfl | (s :: _) l := by by_cases h : a = s.1; simp [h, kerase_comm a s.1 l, kunion_kerase] theorem kunion_nodupkeys {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) : (kunion l₁ l₂).nodupkeys := begin induction l₁ generalizing l₂, case list.nil { simp only [nil_kunion, nd₂] }, case list.cons : s l₁ ih { simp at nd₁, simp [not_or_distrib, nd₁.1, nd₂, ih nd₁.2 (kerase_nodupkeys s.1 nd₂)] } end theorem perm_kunion_left {l₁ l₂ : list (sigma β)} (p : l₁ ~ l₂) (l) : kunion l₁ l ~ kunion l₂ l := begin induction p generalizing l, case list.perm.nil { refl }, case list.perm.skip : hd tl₁ tl₂ p ih { simp [ih (kerase hd.1 l), perm.skip] }, case list.perm.swap : s₁ s₂ l { simp [kerase_comm, perm.swap] }, case list.perm.trans : l₁ l₂ l₃ p₁₂ p₂₃ ih₁₂ ih₂₃ { exact perm.trans (ih₁₂ l) (ih₂₃ l) } end theorem perm_kunion_right : ∀ l {l₁ l₂ : list (sigma β)}, l₁.nodupkeys → l₁ ~ l₂ → kunion l l₁ ~ kunion l l₂ | [] _ _ _ p := p | (s :: l) l₁ l₂ nd₁ p := by simp [perm.skip s (perm_kunion_right l (kerase_nodupkeys s.1 nd₁) (perm_kerase nd₁ p))] theorem perm_kunion {l₁ l₂ l₃ l₄ : list (sigma β)} (nd₃ : l₃.nodupkeys) (p₁₂ : l₁ ~ l₂) (p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ := perm.trans (perm_kunion_left p₁₂ l₃) (perm_kunion_right l₂ nd₃ p₃₄) @[simp] theorem lookup_kunion_left {a} {l₁ l₂ : list (sigma β)} (h : a ∈ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₁ := begin induction l₁ with s _ ih generalizing l₂; simp at h; cases h; cases s with a', { subst h, simp }, { rw kunion_cons, by_cases h' : a = a', { subst h', simp }, { simp [h', ih h] } } end @[simp] theorem lookup_kunion_right {a} {l₁ l₂ : list (sigma β)} (h : a ∉ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : _ _ ih { simp [not_or_distrib] at h, simp [h.1, ih h.2] } end @[simp] theorem mem_lookup_kunion {a} {b : β a} {l₁ l₂ : list (sigma β)} : b ∈ lookup a (kunion l₁ l₂) ↔ b ∈ lookup a l₁ ∨ a ∉ l₁.keys ∧ b ∈ lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s _ ih { cases s with a', by_cases h₁ : a = a', { subst h₁, simp }, { let h₂ := @ih (kerase a' l₂), simp [h₁] at h₂, simp [h₁, h₂] } } end theorem mem_lookup_kunion_middle {a} {b : β a} {l₁ l₂ l₃ : list (sigma β)} (h₁ : b ∈ lookup a (kunion l₁ l₃)) (h₂ : a ∉ keys l₂) : b ∈ lookup a (kunion (kunion l₁ l₂) l₃) := match mem_lookup_kunion.mp h₁ with | or.inl h := mem_lookup_kunion.mpr (or.inl (mem_lookup_kunion.mpr (or.inl h))) | or.inr h := mem_lookup_kunion.mpr $ or.inr ⟨mt mem_keys_kunion.mp (not_or_distrib.mpr ⟨h.1, h₂⟩), h.2⟩ end end list
ad0cce8529aa891259d2b4ad8573f156e10e08ff
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/scripts/lakefile.lean
9552d46561408214e709fbcc4feff114da83513b
[ "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
407
lean
import Lake open Lake DSL package scripts /-- Display a greeting USAGE: lake run greet [name] Greet the entity with the given name. Otherwise, greet the whole world. -/ @[default_script] script greet (args) do if h : 0 < args.length then IO.println s!"Hello, {args[0]'h}!" else IO.println "Hello, world!" return 0 @[default_script] script dismiss do IO.println "Goodbye!" return 0
0e1d447f8240581f1d8ddb4c69889a0ca7b1da5f
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/combinatorics/simple_graph/basic.lean
4c4736d82a20bb94c6ca93d4ffd94f7a9c523e72
[ "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
46,687
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov, Hunter Monroe -/ import data.rel import data.set.finite import data.sym.sym2 /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `simple_graph.neighbor_set` is the `set` of vertices adjacent to a given vertex * `simple_graph.common_neighbors` is the intersection of the neighbor sets of two given vertices * `simple_graph.neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite * `simple_graph.incidence_set` is the `set` of edges containing a given vertex * `simple_graph.incidence_finset` is the `finset` of edges containing a given vertex, if `incidence_set` is finite * `simple_graph.dart` is an ordered pair of adjacent vertices, thought of as being an orientated edge. These are also known as "half-edges" or "bonds." * `simple_graph.hom`, `simple_graph.embedding`, and `simple_graph.iso` for graph homomorphisms, graph embeddings, and graph isomorphisms. Note that a graph embedding is a stronger notion than an injective graph homomorphism, since its image is an induced subgraph. * `boolean_algebra` instance: Under the subgraph relation, `simple_graph` forms a `boolean_algebra`. In other words, this is the lattice of spanning subgraphs of the complete graph. ## Notations * `→g`, `↪g`, and `≃g` for graph homomorphisms, graph embeddings, and graph isomorphisms, respectively. ## Implementation notes * A locally finite graph is one with instances `Π v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. * Morphisms of graphs are abbreviations for `rel_hom`, `rel_embedding`, and `rel_iso`. To make use of pre-existing simp lemmas, definitions involving morphisms are abbreviations as well. ## Naming Conventions * If the vertex type of a graph is finite, we refer to its cardinality as `card_verts`. ## Todo * Upgrade `simple_graph.boolean_algebra` to a `complete_boolean_algebra`. * This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. -/ open finset universes u v w /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent vertices; see `simple_graph.edge_set` for the corresponding edge set. -/ @[ext] structure simple_graph (V : Type u) := (adj : V → V → Prop) (symm : symmetric adj . obviously) (loopless : irreflexive adj . obviously) noncomputable instance {V : Type u} [fintype V] : fintype (simple_graph V) := by { classical, exact fintype.of_injective simple_graph.adj simple_graph.ext } /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V := { adj := λ a b, (a ≠ b) ∧ (r a b ∨ r b a), symm := λ a b ⟨hn, hr⟩, ⟨hn.symm, hr.symm⟩, loopless := λ a ⟨hn, _⟩, hn rfl } @[simp] lemma simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v w : V) : (simple_graph.from_rel r).adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) := iff.rfl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. In `mathlib`, this is usually referred to as `⊤`. -/ def complete_graph (V : Type u) : simple_graph V := { adj := ne } /-- The graph with no edges on a given vertex type `V`. `mathlib` prefers the notation `⊥`. -/ def empty_graph (V : Type u) : simple_graph V := { adj := λ i j, false } /-- Two vertices are adjacent in the complete bipartite graph on two vertex types if and only if they are not from the same side. Bipartite graphs in general may be regarded as being subgraphs of one of these. TODO also introduce complete multi-partite graphs, where the vertex type is a sigma type of an indexed family of vertex types -/ @[simps] def complete_bipartite_graph (V W : Type*) : simple_graph (V ⊕ W) := { adj := λ v w, (v.is_left ∧ w.is_right) ∨ (v.is_right ∧ w.is_left), symm := begin intros v w, cases v; cases w; simp, end, loopless := begin intro v, cases v; simp, end } namespace simple_graph variables {V : Type u} {W : Type v} {X : Type w} (G : simple_graph V) (G' : simple_graph W) {a b c u v w : V} {e : sym2 V} @[simp] protected lemma irrefl {v : V} : ¬G.adj v v := G.loopless v lemma adj_comm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.symm x, λ x, G.symm x⟩ @[symm] lemma adj_symm (h : G.adj u v) : G.adj v u := G.symm h lemma adj.symm {G : simple_graph V} {u v : V} (h : G.adj u v) : G.adj v u := G.symm h lemma ne_of_adj (h : G.adj a b) : a ≠ b := by { rintro rfl, exact G.irrefl h } protected lemma adj.ne {G : simple_graph V} {a b : V} (h : G.adj a b) : a ≠ b := G.ne_of_adj h protected lemma adj.ne' {G : simple_graph V} {a b : V} (h : G.adj a b) : b ≠ a := h.ne.symm lemma ne_of_adj_of_not_adj {v w x : V} (h : G.adj v x) (hn : ¬ G.adj w x) : v ≠ w := λ h', hn (h' ▸ h) section order /-- The relation that one `simple_graph` is a subgraph of another. Note that this should be spelled `≤`. -/ def is_subgraph (x y : simple_graph V) : Prop := ∀ ⦃v w : V⦄, x.adj v w → y.adj v w instance : has_le (simple_graph V) := ⟨is_subgraph⟩ @[simp] lemma is_subgraph_eq_le : (is_subgraph : simple_graph V → simple_graph V → Prop) = (≤) := rfl /-- The supremum of two graphs `x ⊔ y` has edges where either `x` or `y` have edges. -/ instance : has_sup (simple_graph V) := ⟨λ x y, { adj := x.adj ⊔ y.adj, symm := λ v w h, by rwa [pi.sup_apply, pi.sup_apply, x.adj_comm, y.adj_comm] }⟩ @[simp] lemma sup_adj (x y : simple_graph V) (v w : V) : (x ⊔ y).adj v w ↔ x.adj v w ∨ y.adj v w := iff.rfl /-- The infimum of two graphs `x ⊓ y` has edges where both `x` and `y` have edges. -/ instance : has_inf (simple_graph V) := ⟨λ x y, { adj := x.adj ⊓ y.adj, symm := λ v w h, by rwa [pi.inf_apply, pi.inf_apply, x.adj_comm, y.adj_comm] }⟩ @[simp] lemma inf_adj (x y : simple_graph V) (v w : V) : (x ⊓ y).adj v w ↔ x.adj v w ∧ y.adj v w := iff.rfl /-- We define `Gᶜ` to be the `simple_graph V` such that no two adjacent vertices in `G` are adjacent in the complement, and every nonadjacent pair of vertices is adjacent (still ensuring that vertices are not adjacent to themselves). -/ instance : has_compl (simple_graph V) := ⟨λ G, { adj := λ v w, v ≠ w ∧ ¬G.adj v w, symm := λ v w ⟨hne, _⟩, ⟨hne.symm, by rwa adj_comm⟩, loopless := λ v ⟨hne, _⟩, (hne rfl).elim }⟩ @[simp] lemma compl_adj (G : simple_graph V) (v w : V) : Gᶜ.adj v w ↔ v ≠ w ∧ ¬G.adj v w := iff.rfl /-- The difference of two graphs `x \ y` has the edges of `x` with the edges of `y` removed. -/ instance : has_sdiff (simple_graph V) := ⟨λ x y, { adj := x.adj \ y.adj, symm := λ v w h, by change x.adj w v ∧ ¬ y.adj w v; rwa [x.adj_comm, y.adj_comm] }⟩ @[simp] lemma sdiff_adj (x y : simple_graph V) (v w : V) : (x \ y).adj v w ↔ (x.adj v w ∧ ¬ y.adj v w) := iff.rfl instance : boolean_algebra (simple_graph V) := { le := (≤), sup := (⊔), inf := (⊓), compl := has_compl.compl, sdiff := (\), top := complete_graph V, bot := empty_graph V, le_top := λ x v w h, x.ne_of_adj h, bot_le := λ x v w h, h.elim, sup_le := λ x y z hxy hyz v w h, h.cases_on (λ h, hxy h) (λ h, hyz h), sdiff_eq := λ x y, by { ext v w, refine ⟨λ h, ⟨h.1, ⟨_, h.2⟩⟩, λ h, ⟨h.1, h.2.2⟩⟩, rintro rfl, exact x.irrefl h.1 }, le_sup_left := λ x y v w h, or.inl h, le_sup_right := λ x y v w h, or.inr h, le_inf := λ x y z hxy hyz v w h, ⟨hxy h, hyz h⟩, le_sup_inf := λ a b c v w h, or.dcases_on h.2 or.inl $ or.dcases_on h.1 (λ h _, or.inl h) $ λ hb hc, or.inr ⟨hb, hc⟩, inf_compl_le_bot := λ a v w h, false.elim $ h.2.2 h.1, top_le_sup_compl := λ a v w ne, by { by_cases a.adj v w, exact or.inl h, exact or.inr ⟨ne, h⟩ }, inf_le_left := λ x y v w h, h.1, inf_le_right := λ x y v w h, h.2, .. partial_order.lift adj ext } @[simp] lemma top_adj (v w : V) : (⊤ : simple_graph V).adj v w ↔ v ≠ w := iff.rfl @[simp] lemma bot_adj (v w : V) : (⊥ : simple_graph V).adj v w ↔ false := iff.rfl @[simp] lemma complete_graph_eq_top (V : Type u) : complete_graph V = ⊤ := rfl @[simp] lemma empty_graph_eq_bot (V : Type u) : empty_graph V = ⊥ := rfl @[simps] instance (V : Type u) : inhabited (simple_graph V) := ⟨⊥⟩ section decidable variables (V) (H : simple_graph V) [decidable_rel G.adj] [decidable_rel H.adj] instance bot.adj_decidable : decidable_rel (⊥ : simple_graph V).adj := λ v w, decidable.false instance sup.adj_decidable : decidable_rel (G ⊔ H).adj := λ v w, or.decidable instance inf.adj_decidable : decidable_rel (G ⊓ H).adj := λ v w, and.decidable instance sdiff.adj_decidable : decidable_rel (G \ H).adj := λ v w, and.decidable variable [decidable_eq V] instance top.adj_decidable : decidable_rel (⊤ : simple_graph V).adj := λ v w, not.decidable instance compl.adj_decidable : decidable_rel Gᶜ.adj := λ v w, and.decidable end decidable end order /-- `G.support` is the set of vertices that form edges in `G`. -/ def support : set V := rel.dom G.adj lemma mem_support {v : V} : v ∈ G.support ↔ ∃ w, G.adj v w := iff.rfl lemma support_mono {G G' : simple_graph V} (h : G ≤ G') : G.support ⊆ G'.support := rel.dom_mono h /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set (v : V) : set V := set_of (G.adj v) instance neighbor_set.mem_decidable (v : V) [decidable_rel G.adj] : decidable_pred (∈ G.neighbor_set v) := by { unfold neighbor_set, apply_instance } /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. The way `edge_set` is defined is such that `mem_edge_set` is proved by `refl`. (That is, `⟦(v, w)⟧ ∈ G.edge_set` is definitionally equal to `G.adj v w`.) -/ def edge_set : set (sym2 V) := sym2.from_rel G.symm @[simp] lemma mem_edge_set : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w := iff.rfl /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ lemma adj_iff_exists_edge {v w : V} : G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e := begin refine ⟨λ _, ⟨G.ne_of_adj ‹_›, ⟦(v,w)⟧, _⟩, _⟩, { simpa }, { rintro ⟨hne, e, he, hv⟩, rw sym2.mem_and_mem_iff hne at hv, subst e, rwa mem_edge_set at he } end lemma adj_iff_exists_edge_coe : G.adj a b ↔ ∃ (e : G.edge_set), ↑e = ⟦(a, b)⟧ := by simp only [mem_edge_set, exists_prop, set_coe.exists, exists_eq_right, subtype.coe_mk] lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v := begin erw [← sym2.other_spec h, sym2.eq_swap] at he, exact G.ne_of_adj he, end instance decidable_mem_edge_set [decidable_rel G.adj] : decidable_pred (∈ G.edge_set) := sym2.from_rel.decidable_pred _ instance edges_fintype [decidable_eq V] [fintype V] [decidable_rel G.adj] : fintype G.edge_set := subtype.fintype _ /-! ## Darts -/ /-- A `dart` is an oriented edge, implemented as an ordered pair of adjacent vertices. This terminology comes from combinatorial maps, and they are also known as "half-edges" or "bonds." -/ @[ext, derive decidable_eq] structure dart extends V × V := (is_adj : G.adj fst snd) section darts variables {G} /-- The first vertex for the dart. -/ abbreviation dart.fst (d : G.dart) : V := d.fst /-- The second vertex for the dart. -/ abbreviation dart.snd (d : G.dart) : V := d.snd lemma dart.to_prod_injective : function.injective (dart.to_prod : G.dart → V × V) := dart.ext instance dart.fintype [fintype V] [decidable_rel G.adj] : fintype G.dart := fintype.of_equiv (Σ v, G.neighbor_set v) { to_fun := λ s, ⟨(s.fst, s.snd), s.snd.property⟩, inv_fun := λ d, ⟨d.fst, d.snd, d.is_adj⟩, left_inv := λ s, by ext; simp, right_inv := λ d, by ext; simp } /-- The edge associated to the dart. -/ def dart.edge (d : G.dart) : sym2 V := ⟦d.to_prod⟧ @[simp] lemma dart.edge_mk {p : V × V} (h : G.adj p.1 p.2) : (dart.mk p h).edge = ⟦p⟧ := rfl @[simp] lemma dart.edge_mem (d : G.dart) : d.edge ∈ G.edge_set := d.is_adj /-- The dart with reversed orientation from a given dart. -/ @[simps] def dart.symm (d : G.dart) : G.dart := ⟨d.to_prod.swap, G.symm d.is_adj⟩ @[simp] lemma dart.symm_mk {p : V × V} (h : G.adj p.1 p.2) : (dart.mk p h).symm = dart.mk p.swap h.symm := rfl @[simp] lemma dart.edge_symm (d : G.dart) : d.symm.edge = d.edge := sym2.mk_prod_swap_eq @[simp] lemma dart.edge_comp_symm : dart.edge ∘ dart.symm = (dart.edge : G.dart → sym2 V) := funext dart.edge_symm @[simp] lemma dart.symm_symm (d : G.dart) : d.symm.symm = d := dart.ext _ _ $ prod.swap_swap _ @[simp] lemma dart.symm_involutive : function.involutive (dart.symm : G.dart → G.dart) := dart.symm_symm lemma dart.symm_ne (d : G.dart) : d.symm ≠ d := ne_of_apply_ne (prod.snd ∘ dart.to_prod) d.is_adj.ne lemma dart_edge_eq_iff : Π (d₁ d₂ : G.dart), d₁.edge = d₂.edge ↔ d₁ = d₂ ∨ d₁ = d₂.symm := by { rintros ⟨p, hp⟩ ⟨q, hq⟩, simp [sym2.mk_eq_mk_iff] } lemma dart_edge_eq_mk_iff : Π {d : G.dart} {p : V × V}, d.edge = ⟦p⟧ ↔ d.to_prod = p ∨ d.to_prod = p.swap := by { rintro ⟨p, h⟩, apply sym2.mk_eq_mk_iff } lemma dart_edge_eq_mk_iff' : Π {d : G.dart} {u v : V}, d.edge = ⟦(u, v)⟧ ↔ d.fst = u ∧ d.snd = v ∨ d.fst = v ∧ d.snd = u := by { rintro ⟨⟨a, b⟩, h⟩ u v, rw dart_edge_eq_mk_iff, simp } variables (G) /-- Two darts are said to be adjacent if they could be consecutive darts in a walk -- that is, the first dart's second vertex is equal to the second dart's first vertex. -/ def dart_adj (d d' : G.dart) : Prop := d.snd = d'.fst /-- For a given vertex `v`, this is the bijective map from the neighbor set at `v` to the darts `d` with `d.fst = v`. --/ @[simps] def dart_of_neighbor_set (v : V) (w : G.neighbor_set v) : G.dart := ⟨(v, w), w.property⟩ lemma dart_of_neighbor_set_injective (v : V) : function.injective (G.dart_of_neighbor_set v) := λ e₁ e₂ h, subtype.ext $ by { injection h with h', convert congr_arg prod.snd h' } instance nonempty_dart_top [nontrivial V] : nonempty (⊤ : simple_graph V).dart := by { obtain ⟨v, w, h⟩ := exists_pair_ne V, exact ⟨⟨(v, w), h⟩⟩ } end darts /-! ### Incidence set -/ /-- Set of edges incident to a given vertex, aka incidence set. -/ def incidence_set (v : V) : set (sym2 V) := {e ∈ G.edge_set | v ∈ e} lemma incidence_set_subset (v : V) : G.incidence_set v ⊆ G.edge_set := λ _ h, h.1 lemma mk_mem_incidence_set_iff : ⟦(b, c)⟧ ∈ G.incidence_set a ↔ G.adj b c ∧ (a = b ∨ a = c) := and_congr_right' sym2.mem_iff lemma mk_mem_incidence_set_left_iff : ⟦(a, b)⟧ ∈ G.incidence_set a ↔ G.adj a b := and_iff_left $ sym2.mem_mk_left _ _ lemma mk_mem_incidence_set_right_iff : ⟦(a, b)⟧ ∈ G.incidence_set b ↔ G.adj a b := and_iff_left $ sym2.mem_mk_right _ _ lemma edge_mem_incidence_set_iff {e : G.edge_set} : ↑e ∈ G.incidence_set a ↔ a ∈ (e : sym2 V) := and_iff_right e.2 lemma incidence_set_inter_incidence_set_subset (h : a ≠ b) : G.incidence_set a ∩ G.incidence_set b ⊆ {⟦(a, b)⟧} := λ e he, (sym2.mem_and_mem_iff h).1 ⟨he.1.2, he.2.2⟩ lemma incidence_set_inter_incidence_set_of_adj (h : G.adj a b) : G.incidence_set a ∩ G.incidence_set b = {⟦(a, b)⟧} := begin refine (G.incidence_set_inter_incidence_set_subset $ h.ne).antisymm _, rintro _ (rfl : _ = ⟦(a, b)⟧), exact ⟨G.mk_mem_incidence_set_left_iff.2 h, G.mk_mem_incidence_set_right_iff.2 h⟩, end lemma adj_of_mem_incidence_set (h : a ≠ b) (ha : e ∈ G.incidence_set a) (hb : e ∈ G.incidence_set b) : G.adj a b := by rwa [←mk_mem_incidence_set_left_iff, ←set.mem_singleton_iff.1 $ G.incidence_set_inter_incidence_set_subset h ⟨ha, hb⟩] lemma incidence_set_inter_incidence_set_of_not_adj (h : ¬ G.adj a b) (hn : a ≠ b) : G.incidence_set a ∩ G.incidence_set b = ∅ := begin simp_rw [set.eq_empty_iff_forall_not_mem, set.mem_inter_eq, not_and], intros u ha hb, exact h (G.adj_of_mem_incidence_set hn ha hb), end instance decidable_mem_incidence_set [decidable_eq V] [decidable_rel G.adj] (v : V) : decidable_pred (∈ G.incidence_set v) := λ e, and.decidable /-- The `edge_set` of the graph as a `finset`. -/ @[reducible] def edge_finset [fintype G.edge_set] : finset (sym2 V) := set.to_finset G.edge_set @[simp] lemma mem_edge_finset [fintype G.edge_set] (e : sym2 V) : e ∈ G.edge_finset ↔ e ∈ G.edge_set := set.mem_to_finset lemma edge_finset_card [fintype G.edge_set] : G.edge_finset.card = fintype.card G.edge_set := set.to_finset_card _ @[simp] lemma edge_set_univ_card [fintype G.edge_set] : (univ : finset G.edge_set).card = G.edge_finset.card := fintype.card_of_subtype G.edge_finset (mem_edge_finset _) @[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := iff.rfl @[simp] lemma mem_incidence_set (v w : V) : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ G.adj v w := by simp [incidence_set] lemma mem_incidence_iff_neighbor {v w : V} : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ w ∈ G.neighbor_set v := by simp only [mem_incidence_set, mem_neighbor_set] lemma adj_incidence_set_inter {v : V} {e : sym2 V} (he : e ∈ G.edge_set) (h : v ∈ e) : G.incidence_set v ∩ G.incidence_set h.other = {e} := begin ext e', simp only [incidence_set, set.mem_sep_eq, set.mem_inter_eq, set.mem_singleton_iff], refine ⟨λ h', _, _⟩, { rw ←sym2.other_spec h, exact (sym2.mem_and_mem_iff (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩ }, { rintro rfl, exact ⟨⟨he, h⟩, he, sym2.other_mem _⟩ } end lemma compl_neighbor_set_disjoint (G : simple_graph V) (v : V) : disjoint (G.neighbor_set v) (Gᶜ.neighbor_set v) := begin rw set.disjoint_iff, rintro w ⟨h, h'⟩, rw [mem_neighbor_set, compl_adj] at h', exact h'.2 h, end lemma neighbor_set_union_compl_neighbor_set_eq (G : simple_graph V) (v : V) : G.neighbor_set v ∪ Gᶜ.neighbor_set v = {v}ᶜ := begin ext w, have h := @ne_of_adj _ G, simp_rw [set.mem_union, mem_neighbor_set, compl_adj, set.mem_compl_eq, set.mem_singleton_iff], tauto, end -- TODO find out why TC inference has `h` failing a defeq check for `to_finset` lemma card_neighbor_set_union_compl_neighbor_set [fintype V] (G : simple_graph V) (v : V) [h : fintype (G.neighbor_set v ∪ Gᶜ.neighbor_set v : set V)] : (@set.to_finset _ (G.neighbor_set v ∪ Gᶜ.neighbor_set v) h).card = fintype.card V - 1 := begin classical, simp_rw [neighbor_set_union_compl_neighbor_set_eq, set.to_finset_compl, finset.card_compl, set.to_finset_card, set.card_singleton], end lemma neighbor_set_compl (G : simple_graph V) (v : V) : Gᶜ.neighbor_set v = (G.neighbor_set v)ᶜ \ {v} := by { ext w, simp [and_comm, eq_comm] } /-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the intersection of the neighbor sets of `v` and `w`. -/ def common_neighbors (v w : V) : set V := G.neighbor_set v ∩ G.neighbor_set w lemma common_neighbors_eq (v w : V) : G.common_neighbors v w = G.neighbor_set v ∩ G.neighbor_set w := rfl lemma mem_common_neighbors {u v w : V} : u ∈ G.common_neighbors v w ↔ G.adj v u ∧ G.adj w u := iff.rfl lemma common_neighbors_symm (v w : V) : G.common_neighbors v w = G.common_neighbors w v := set.inter_comm _ _ lemma not_mem_common_neighbors_left (v w : V) : v ∉ G.common_neighbors v w := λ h, ne_of_adj G h.1 rfl lemma not_mem_common_neighbors_right (v w : V) : w ∉ G.common_neighbors v w := λ h, ne_of_adj G h.2 rfl lemma common_neighbors_subset_neighbor_set_left (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set v := set.inter_subset_left _ _ lemma common_neighbors_subset_neighbor_set_right (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set w := set.inter_subset_right _ _ instance decidable_mem_common_neighbors [decidable_rel G.adj] (v w : V) : decidable_pred (∈ G.common_neighbors v w) := λ a, and.decidable lemma common_neighbors_top_eq {v w : V} : (⊤ : simple_graph V).common_neighbors v w = set.univ \ {v, w} := by { ext u, simp [common_neighbors, eq_comm, not_or_distrib.symm] } section incidence variable [decidable_eq V] /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def other_vertex_of_incident {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : V := h.2.other' lemma edge_other_incident_set {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : e ∈ G.incidence_set (G.other_vertex_of_incident h) := by { use h.1, simp [other_vertex_of_incident, sym2.other_mem'] } lemma incidence_other_prop {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : G.other_vertex_of_incident h ∈ G.neighbor_set v := by { cases h with he hv, rwa [←sym2.other_spec' hv, mem_edge_set] at he } @[simp] lemma incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighbor_set v) : G.other_vertex_of_incident (G.mem_incidence_iff_neighbor.mpr h) = w := sym2.congr_right.mp (sym2.other_spec' (G.mem_incidence_iff_neighbor.mpr h).right) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ @[simps] def incidence_set_equiv_neighbor_set (v : V) : G.incidence_set v ≃ G.neighbor_set v := { to_fun := λ e, ⟨G.other_vertex_of_incident e.2, G.incidence_other_prop e.2⟩, inv_fun := λ w, ⟨⟦(v, w.1)⟧, G.mem_incidence_iff_neighbor.mpr w.2⟩, left_inv := λ x, by simp [other_vertex_of_incident], right_inv := λ ⟨w, hw⟩, by simp } end incidence /-! ## Edge deletion -/ /-- Given a set of vertex pairs, remove all of the corresponding edges from the graph's edge set, if present. See also: `simple_graph.subgraph.delete_edges`. -/ def delete_edges (s : set (sym2 V)) : simple_graph V := { adj := G.adj \ sym2.to_rel s, symm := λ a b, by simp [adj_comm, sym2.eq_swap] } @[simp] lemma delete_edges_adj (s : set (sym2 V)) (v w : V) : (G.delete_edges s).adj v w ↔ G.adj v w ∧ ¬ ⟦(v, w)⟧ ∈ s := iff.rfl lemma sdiff_eq_delete_edges (G G' : simple_graph V) : G \ G' = G.delete_edges G'.edge_set := by { ext, simp } lemma compl_eq_delete_edges : Gᶜ = (⊤ : simple_graph V).delete_edges G.edge_set := by { ext, simp } @[simp] lemma delete_edges_delete_edges (s s' : set (sym2 V)) : (G.delete_edges s).delete_edges s' = G.delete_edges (s ∪ s') := by { ext, simp [and_assoc, not_or_distrib] } @[simp] lemma delete_edges_empty_eq : G.delete_edges ∅ = G := by { ext, simp } @[simp] lemma delete_edges_univ_eq : G.delete_edges set.univ = ⊥ := by { ext, simp } lemma delete_edges_le (s : set (sym2 V)) : G.delete_edges s ≤ G := by { intro, simp { contextual := tt } } lemma delete_edges_le_of_le {s s' : set (sym2 V)} (h : s ⊆ s') : G.delete_edges s' ≤ G.delete_edges s := λ v w, begin simp only [delete_edges_adj, and_imp, true_and] { contextual := tt }, exact λ ha hn hs, hn (h hs), end lemma delete_edges_eq_inter_edge_set (s : set (sym2 V)) : G.delete_edges s = G.delete_edges (s ∩ G.edge_set) := by { ext, simp [imp_false] { contextual := tt } } /-! ## Map and comap -/ /-- Given an injective function, there is an covariant induced map on graphs by pushing forward the adjacency relation. This is injective (see `simple_graph.map_injective`). -/ protected def map (f : V ↪ W) (G : simple_graph V) : simple_graph W := { adj := relation.map G.adj f f } @[simp] lemma map_adj (f : V ↪ W) (G : simple_graph V) (u v : W) : (G.map f).adj u v ↔ ∃ (u' v' : V), G.adj u' v' ∧ f u' = u ∧ f v' = v := iff.rfl lemma map_monotone (f : V ↪ W) : monotone (simple_graph.map f) := by { rintros G G' h _ _ ⟨u, v, ha, rfl, rfl⟩, exact ⟨_, _, h ha, rfl, rfl⟩ } /-- Given a function, there is a contravariant induced map on graphs by pulling back the adjacency relation. This is one of the ways of creating induced graphs. See `simple_graph.induce` for a wrapper. This is surjective when `f` is injective (see `simple_graph.comap_surjective`).-/ @[simps] protected def comap (f : V → W) (G : simple_graph W) : simple_graph V := { adj := λ u v, G.adj (f u) (f v) } lemma comap_monotone (f : V ↪ W) : monotone (simple_graph.comap f) := by { intros G G' h _ _ ha, exact h ha } @[simp] lemma comap_map_eq (f : V ↪ W) (G : simple_graph V) : (G.map f).comap f = G := by { ext, simp } lemma left_inverse_comap_map (f : V ↪ W) : function.left_inverse (simple_graph.comap f) (simple_graph.map f) := comap_map_eq f lemma map_injective (f : V ↪ W) : function.injective (simple_graph.map f) := (left_inverse_comap_map f).injective lemma comap_surjective (f : V ↪ W) : function.surjective (simple_graph.comap f) := (left_inverse_comap_map f).surjective lemma map_le_iff_le_comap (f : V ↪ W) (G : simple_graph V) (G' : simple_graph W) : G.map f ≤ G' ↔ G ≤ G'.comap f := ⟨λ h u v ha, h ⟨_, _, ha, rfl, rfl⟩, by { rintros h _ _ ⟨u, v, ha, rfl, rfl⟩, exact h ha, }⟩ lemma map_comap_le (f : V ↪ W) (G : simple_graph W) : (G.comap f).map f ≤ G := by { rw map_le_iff_le_comap, exact le_refl _ } /-! ## Induced graphs -/ /- Given a set `s` of vertices, we can restrict a graph to those vertices by restricting its adjacency relation. This gives a map between `simple_graph V` and `simple_graph s`. There is also a notion of induced subgraphs (see `simple_graph.subgraph.induce`). -/ /-- Restrict a graph to the vertices in the set `s`, deleting all edges incident to vertices outside the set. This is a wrapper around `simple_graph.comap`. -/ @[reducible] def induce (s : set V) (G : simple_graph V) : simple_graph s := G.comap (function.embedding.subtype _) /-- Given a graph on a set of vertices, we can make it be a `simple_graph V` by adding in the remaining vertices without adding in any additional edges. This is a wrapper around `simple_graph.map`. -/ @[reducible] def spanning_coe {s : set V} (G : simple_graph s) : simple_graph V := G.map (function.embedding.subtype _) lemma induce_spanning_coe {s : set V} {G : simple_graph s} : G.spanning_coe.induce s = G := comap_map_eq _ _ lemma spanning_coe_induce_le (s : set V) : (G.induce s).spanning_coe ≤ G := map_comap_le _ _ section finite_at /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ variables (v) [fintype (G.neighbor_set v)] /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset : finset V := (G.neighbor_set v).to_finset lemma neighbor_finset_def : G.neighbor_finset v = (G.neighbor_set v).to_finset := rfl @[simp] lemma mem_neighbor_finset (w : V) : w ∈ G.neighbor_finset v ↔ G.adj v w := set.mem_to_finset /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighbor_finset v).card @[simp] lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v := (set.to_finset_card _).symm lemma degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.adj v w := by simp only [degree, card_pos, finset.nonempty, mem_neighbor_finset] lemma degree_compl [fintype (Gᶜ.neighbor_set v)] [fintype V] : Gᶜ.degree v = fintype.card V - 1 - G.degree v := begin classical, rw [← card_neighbor_set_union_compl_neighbor_set G v, set.to_finset_union], simp [card_disjoint_union (set.to_finset_disjoint_iff.mpr (compl_neighbor_set_disjoint G v))], end instance incidence_set_fintype [decidable_eq V] : fintype (G.incidence_set v) := fintype.of_equiv (G.neighbor_set v) (G.incidence_set_equiv_neighbor_set v).symm /-- This is the `finset` version of `incidence_set`. -/ def incidence_finset [decidable_eq V] : finset (sym2 V) := (G.incidence_set v).to_finset @[simp] lemma card_incidence_set_eq_degree [decidable_eq V] : fintype.card (G.incidence_set v) = G.degree v := by { rw fintype.card_congr (G.incidence_set_equiv_neighbor_set v), simp } @[simp] lemma card_incidence_finset_eq_degree [decidable_eq V] : (G.incidence_finset v).card = G.degree v := by { rw ← G.card_incidence_set_eq_degree, apply set.to_finset_card } @[simp] lemma mem_incidence_finset [decidable_eq V] (e : sym2 V) : e ∈ G.incidence_finset v ↔ e ∈ G.incidence_set v := set.mem_to_finset lemma incidence_finset_eq_filter [decidable_eq V] [fintype G.edge_set] : G.incidence_finset v = G.edge_finset.filter (has_mem.mem v) := begin ext e, refine sym2.ind (λ x y, _) e, simp [mk_mem_incidence_set_iff], end end finite_at section locally_finite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ @[reducible] def locally_finite := Π (v : V), fintype (G.neighbor_set v) variable [locally_finite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d variables {G} lemma is_regular_of_degree.degree_eq {d : ℕ} (h : G.is_regular_of_degree d) (v : V) : G.degree v = d := h v lemma is_regular_of_degree.compl [fintype V] [decidable_eq V] {G : simple_graph V} [decidable_rel G.adj] {k : ℕ} (h : G.is_regular_of_degree k) : Gᶜ.is_regular_of_degree (fintype.card V - 1 - k) := by { intro v, rw [degree_compl, h v] } end locally_finite section finite variable [fintype V] instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) := @subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _ lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] : G.neighbor_finset v = finset.univ.filter (G.adj v) := by { ext, simp } lemma neighbor_finset_compl [decidable_eq V] [decidable_rel G.adj] (v : V) : Gᶜ.neighbor_finset v = (G.neighbor_finset v)ᶜ \ {v} := by simp only [neighbor_finset, neighbor_set_compl, set.to_finset_diff, set.to_finset_compl, set.to_finset_singleton] @[simp] lemma complete_graph_degree [decidable_eq V] (v : V) : (⊤ : simple_graph V).degree v = fintype.card V - 1 := by erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v), card_univ] lemma bot_degree (v : V) : (⊥ : simple_graph V).degree v = 0 := begin erw [degree, neighbor_finset_eq_filter, filter_false], exact finset.card_empty, end lemma is_regular_of_degree.top [decidable_eq V] : (⊤ : simple_graph V).is_regular_of_degree (fintype.card V - 1) := by { intro v, simp } /-- The minimum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_minimal_degree_vertex`, `min_degree_le_degree` and `le_min_degree_of_forall_le_degree`. -/ def min_degree [decidable_rel G.adj] : ℕ := with_top.untop' 0 (univ.image (λ v, G.degree v)).min /-- There exists a vertex of minimal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_minimal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.min_degree = G.degree v := begin obtain ⟨t, ht : _ = _⟩ := min_of_nonempty (univ_nonempty.image (λ v, G.degree v)), obtain ⟨v, _, rfl⟩ := mem_image.mp (mem_of_min ht), refine ⟨v, by simp [min_degree, ht]⟩, end /-- The minimum degree in the graph is at most the degree of any particular vertex. -/ lemma min_degree_le_degree [decidable_rel G.adj] (v : V) : G.min_degree ≤ G.degree v := begin obtain ⟨t, ht⟩ := finset.min_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.min_le_of_mem (mem_image_of_mem _ (mem_univ v)) ht, rwa [min_degree, ht] end /-- In a nonempty graph, if `k` is at most the degree of every vertex, it is at most the minimum degree. Note the assumption that the graph is nonempty is necessary as long as `G.min_degree` is defined to be a natural. -/ lemma le_min_degree_of_forall_le_degree [decidable_rel G.adj] [nonempty V] (k : ℕ) (h : ∀ v, k ≤ G.degree v) : k ≤ G.min_degree := by { rcases G.exists_minimal_degree_vertex with ⟨v, hv⟩, rw hv, apply h } /-- The maximum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_maximal_degree_vertex`, `degree_le_max_degree` and `max_degree_le_of_forall_degree_le`. -/ def max_degree [decidable_rel G.adj] : ℕ := option.get_or_else (univ.image (λ v, G.degree v)).max 0 /-- There exists a vertex of maximal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_maximal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.max_degree = G.degree v := begin obtain ⟨t, ht⟩ := max_of_nonempty (univ_nonempty.image (λ v, G.degree v)), have ht₂ := mem_of_max ht, simp only [mem_image, mem_univ, exists_prop_of_true] at ht₂, rcases ht₂ with ⟨v, rfl⟩, refine ⟨v, _⟩, rw [max_degree, ht], refl end /-- The maximum degree in the graph is at least the degree of any particular vertex. -/ lemma degree_le_max_degree [decidable_rel G.adj] (v : V) : G.degree v ≤ G.max_degree := begin obtain ⟨t, ht : _ = _⟩ := finset.max_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.le_max_of_mem (mem_image_of_mem _ (mem_univ v)) ht, rwa [max_degree, ht], end /-- In a graph, if `k` is at least the degree of every vertex, then it is at least the maximum degree. -/ lemma max_degree_le_of_forall_degree_le [decidable_rel G.adj] (k : ℕ) (h : ∀ v, G.degree v ≤ k) : G.max_degree ≤ k := begin by_cases hV : (univ : finset V).nonempty, { haveI : nonempty V := univ_nonempty_iff.mp hV, obtain ⟨v, hv⟩ := G.exists_maximal_degree_vertex, rw hv, apply h }, { rw not_nonempty_iff_eq_empty at hV, rw [max_degree, hV, image_empty], exact zero_le k }, end lemma degree_lt_card_verts [decidable_rel G.adj] (v : V) : G.degree v < fintype.card V := begin classical, apply finset.card_lt_card, rw finset.ssubset_iff, exact ⟨v, by simp, finset.subset_univ _⟩, end /-- The maximum degree of a nonempty graph is less than the number of vertices. Note that the assumption that `V` is nonempty is necessary, as otherwise this would assert the existence of a natural number less than zero. -/ lemma max_degree_lt_card_verts [decidable_rel G.adj] [nonempty V] : G.max_degree < fintype.card V := begin cases G.exists_maximal_degree_vertex with v hv, rw hv, apply G.degree_lt_card_verts v, end lemma card_common_neighbors_le_degree_left [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree v := begin rw [←card_neighbor_set_eq_degree], exact set.card_le_of_subset (set.inter_subset_left _ _), end lemma card_common_neighbors_le_degree_right [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree w := by simp_rw [common_neighbors_symm _ v w, card_common_neighbors_le_degree_left] lemma card_common_neighbors_lt_card_verts [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) < fintype.card V := nat.lt_of_le_of_lt (G.card_common_neighbors_le_degree_left _ _) (G.degree_lt_card_verts v) /-- If the condition `G.adj v w` fails, then `card_common_neighbors_le_degree` is the best we can do in general. -/ lemma adj.card_common_neighbors_lt_degree {G : simple_graph V} [decidable_rel G.adj] {v w : V} (h : G.adj v w) : fintype.card (G.common_neighbors v w) < G.degree v := begin classical, erw [←set.to_finset_card], apply finset.card_lt_card, rw finset.ssubset_iff, use w, split, { rw set.mem_to_finset, apply not_mem_common_neighbors_right }, { rw finset.insert_subset, split, { simpa, }, { rw [neighbor_finset, set.to_finset_mono], exact G.common_neighbors_subset_neighbor_set_left _ _ } } end lemma card_common_neighbors_top [decidable_eq V] {v w : V} (h : v ≠ w) : fintype.card ((⊤ : simple_graph V).common_neighbors v w) = fintype.card V - 2 := begin simp only [common_neighbors_top_eq, ← set.to_finset_card, set.to_finset_diff], rw finset.card_sdiff, { simp [finset.card_univ, h], }, { simp only [set.to_finset_mono, set.subset_univ] }, end end finite section maps /-- A graph homomorphism is a map on vertex sets that respects adjacency relations. The notation `G →g G'` represents the type of graph homomorphisms. -/ abbreviation hom := rel_hom G.adj G'.adj /-- A graph embedding is an embedding `f` such that for vertices `v w : V`, `G.adj f(v) f(w) ↔ G.adj v w `. Its image is an induced subgraph of G'. The notation `G ↪g G'` represents the type of graph embeddings. -/ abbreviation embedding := rel_embedding G.adj G'.adj /-- A graph isomorphism is an bijective map on vertex sets that respects adjacency relations. The notation `G ≃g G'` represents the type of graph isomorphisms. -/ abbreviation iso := rel_iso G.adj G'.adj infix ` →g ` : 50 := hom infix ` ↪g ` : 50 := embedding infix ` ≃g ` : 50 := iso namespace hom variables {G G'} (f : G →g G') /-- The identity homomorphism from a graph to itself. -/ abbreviation id : G →g G := rel_hom.id _ lemma map_adj {v w : V} (h : G.adj v w) : G'.adj (f v) (f w) := f.map_rel' h lemma map_mem_edge_set {e : sym2 V} (h : e ∈ G.edge_set) : e.map f ∈ G'.edge_set := quotient.ind (λ e h, sym2.from_rel_prop.mpr (f.map_rel' h)) e h lemma apply_mem_neighbor_set {v w : V} (h : w ∈ G.neighbor_set v) : f w ∈ G'.neighbor_set (f v) := map_adj f h /-- The map between edge sets induced by a homomorphism. The underlying map on edges is given by `sym2.map`. -/ @[simps] def map_edge_set (e : G.edge_set) : G'.edge_set := ⟨sym2.map f e, f.map_mem_edge_set e.property⟩ /-- The map between neighbor sets induced by a homomorphism. -/ @[simps] def map_neighbor_set (v : V) (w : G.neighbor_set v) : G'.neighbor_set (f v) := ⟨f w, f.apply_mem_neighbor_set w.property⟩ /-- The map between darts induced by a homomorphism. -/ def map_dart (d : G.dart) : G'.dart := ⟨d.1.map f f, f.map_adj d.2⟩ @[simp] lemma map_dart_apply (d : G.dart) : f.map_dart d = ⟨d.1.map f f, f.map_adj d.2⟩ := rfl /-- The induced map for spanning subgraphs, which is the identity on vertices. -/ @[simps] def map_spanning_subgraphs {G G' : simple_graph V} (h : G ≤ G') : G →g G' := { to_fun := λ x, x, map_rel' := h } lemma map_edge_set.injective (hinj : function.injective f) : function.injective f.map_edge_set := begin rintros ⟨e₁, h₁⟩ ⟨e₂, h₂⟩, dsimp [hom.map_edge_set], repeat { rw subtype.mk_eq_mk }, apply sym2.map.injective hinj, end /-- Every graph homomomorphism from a complete graph is injective. -/ lemma injective_of_top_hom (f : (⊤ : simple_graph V) →g G') : function.injective f := begin intros v w h, contrapose! h, exact G'.ne_of_adj (map_adj _ ((top_adj _ _).mpr h)), end /-- There is a homomorphism to a graph from a comapped graph. When the function is injective, this is an embedding (see `simple_graph.embedding.comap`). -/ @[simps] protected def comap (f : V → W) (G : simple_graph W) : G.comap f →g G := { to_fun := f, map_rel' := by simp } variable {G'' : simple_graph X} /-- Composition of graph homomorphisms. -/ abbreviation comp (f' : G' →g G'') (f : G →g G') : G →g G'' := f'.comp f @[simp] lemma coe_comp (f' : G' →g G'') (f : G →g G') : ⇑(f'.comp f) = f' ∘ f := rfl end hom namespace embedding variables {G G'} (f : G ↪g G') /-- The identity embedding from a graph to itself. -/ abbreviation refl : G ↪g G := rel_embedding.refl _ /-- An embedding of graphs gives rise to a homomorphism of graphs. -/ abbreviation to_hom : G →g G' := f.to_rel_hom lemma map_adj_iff {v w : V} : G'.adj (f v) (f w) ↔ G.adj v w := f.map_rel_iff lemma map_mem_edge_set_iff {e : sym2 V} : e.map f ∈ G'.edge_set ↔ e ∈ G.edge_set := quotient.ind (λ ⟨v, w⟩, f.map_adj_iff) e lemma apply_mem_neighbor_set_iff {v w : V} : f w ∈ G'.neighbor_set (f v) ↔ w ∈ G.neighbor_set v := map_adj_iff f /-- A graph embedding induces an embedding of edge sets. -/ @[simps] def map_edge_set : G.edge_set ↪ G'.edge_set := { to_fun := hom.map_edge_set f, inj' := hom.map_edge_set.injective f f.inj' } /-- A graph embedding induces an embedding of neighbor sets. -/ @[simps] def map_neighbor_set (v : V) : G.neighbor_set v ↪ G'.neighbor_set (f v) := { to_fun := λ w, ⟨f w, f.apply_mem_neighbor_set_iff.mpr w.2⟩, inj' := begin rintros ⟨w₁, h₁⟩ ⟨w₂, h₂⟩ h, rw subtype.mk_eq_mk at h ⊢, exact f.inj' h, end } /-- Given an injective function, there is an embedding from the comapped graph into the original graph. -/ @[simps] protected def comap (f : V ↪ W) (G : simple_graph W) : G.comap f ↪g G := { map_rel_iff' := by simp, ..f } /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ @[simps] protected def map (f : V ↪ W) (G : simple_graph V) : G ↪g G.map f := { map_rel_iff' := by simp, ..f } /-- Induced graphs embed in the original graph. Note that if `G.induce s = ⊤` (i.e., if `s` is a clique) then this gives the embedding of a complete graph. -/ @[reducible] protected def induce (s : set V) : G.induce s ↪g G := simple_graph.embedding.comap (function.embedding.subtype _) G /-- Graphs on a set of vertices embed in their `spanning_coe`. -/ @[reducible] protected def spanning_coe {s : set V} (G : simple_graph s) : G ↪g G.spanning_coe := simple_graph.embedding.map (function.embedding.subtype _) G /-- Embeddings of types induce embeddings of complete graphs on those types. -/ protected def complete_graph {α β : Type*} (f : α ↪ β) : (⊤ : simple_graph α) ↪g (⊤ : simple_graph β) := { map_rel_iff' := by simp, ..f } variables {G'' : simple_graph X} /-- Composition of graph embeddings. -/ abbreviation comp (f' : G' ↪g G'') (f : G ↪g G') : G ↪g G'' := f.trans f' @[simp] lemma coe_comp (f' : G' ↪g G'') (f : G ↪g G') : ⇑(f'.comp f) = f' ∘ f := rfl end embedding namespace iso variables {G G'} (f : G ≃g G') /-- The identity isomorphism of a graph with itself. -/ abbreviation refl : G ≃g G := rel_iso.refl _ /-- An isomorphism of graphs gives rise to an embedding of graphs. -/ abbreviation to_embedding : G ↪g G' := f.to_rel_embedding /-- An isomorphism of graphs gives rise to a homomorphism of graphs. -/ abbreviation to_hom : G →g G' := f.to_embedding.to_hom /-- The inverse of a graph isomorphism. --/ abbreviation symm : G' ≃g G := f.symm lemma map_adj_iff {v w : V} : G'.adj (f v) (f w) ↔ G.adj v w := f.map_rel_iff lemma map_mem_edge_set_iff {e : sym2 V} : e.map f ∈ G'.edge_set ↔ e ∈ G.edge_set := quotient.ind (λ ⟨v, w⟩, f.map_adj_iff) e lemma apply_mem_neighbor_set_iff {v w : V} : f w ∈ G'.neighbor_set (f v) ↔ w ∈ G.neighbor_set v := map_adj_iff f /-- An isomorphism of graphs induces an equivalence of edge sets. -/ @[simps] def map_edge_set : G.edge_set ≃ G'.edge_set := { to_fun := hom.map_edge_set f, inv_fun := hom.map_edge_set f.symm, left_inv := begin rintro ⟨e, h⟩, simp only [hom.map_edge_set, sym2.map_map, rel_iso.coe_coe_fn, rel_embedding.coe_coe_fn, subtype.mk_eq_mk, subtype.coe_mk, coe_coe], apply congr_fun, convert sym2.map_id, exact funext (λ _, rel_iso.symm_apply_apply _ _), end, right_inv := begin rintro ⟨e, h⟩, simp only [hom.map_edge_set, sym2.map_map, rel_iso.coe_coe_fn, rel_embedding.coe_coe_fn, subtype.mk_eq_mk, subtype.coe_mk, coe_coe], apply congr_fun, convert sym2.map_id, exact funext (λ _, rel_iso.apply_symm_apply _ _), end } /-- A graph isomorphism induces an equivalence of neighbor sets. -/ @[simps] def map_neighbor_set (v : V) : G.neighbor_set v ≃ G'.neighbor_set (f v) := { to_fun := λ w, ⟨f w, f.apply_mem_neighbor_set_iff.mpr w.2⟩, inv_fun := λ w, ⟨f.symm w, begin convert f.symm.apply_mem_neighbor_set_iff.mpr w.2, simp only [rel_iso.symm_apply_apply], end⟩, left_inv := λ w, by simp, right_inv := λ w, by simp } lemma card_eq_of_iso [fintype V] [fintype W] (f : G ≃g G') : fintype.card V = fintype.card W := by convert (fintype.of_equiv_card f.to_equiv).symm /-- Given a bijection, there is an embedding from the comapped graph into the original graph. -/ @[simps] protected def comap (f : V ≃ W) (G : simple_graph W) : G.comap f.to_embedding ≃g G := { map_rel_iff' := by simp, ..f } /-- Given an injective function, there is an embedding from a graph into the mapped graph. -/ @[simps] protected def map (f : V ≃ W) (G : simple_graph V) : G ≃g G.map f.to_embedding := { map_rel_iff' := by simp, ..f } /-- Equivalences of types induce isomorphisms of complete graphs on those types. -/ protected def complete_graph {α β : Type*} (f : α ≃ β) : (⊤ : simple_graph α) ≃g (⊤ : simple_graph β) := { map_rel_iff' := by simp, ..f } lemma to_embedding_complete_graph {α β : Type*} (f : α ≃ β) : (iso.complete_graph f).to_embedding = embedding.complete_graph f.to_embedding := rfl variables {G'' : simple_graph X} /-- Composition of graph isomorphisms. -/ abbreviation comp (f' : G' ≃g G'') (f : G ≃g G') : G ≃g G'' := f.trans f' @[simp] lemma coe_comp (f' : G' ≃g G'') (f : G ≃g G') : ⇑(f'.comp f) = f' ∘ f := rfl end iso end maps end simple_graph
50eace267a5bdef4910e730cbab8ac4ece3f066c
70f8755415fa7a17f87402cde4651e9f4db1b5bb
/src/mvqpf/comp.lean
308416525ffa5dde27bd31243f1e5e199e3655b5
[ "Apache-2.0" ]
permissive
shingarov/qpf
ab935dc2298db12c87ac011a2e4d2c27e0bdef4b
debe2eacb8cf46b21aba2eaf3f2e20940da0263b
refs/heads/master
1,653,705,576,607
1,570,136,035,000
1,570,136,035,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,854
lean
import mvpfunctor.basic import mvqpf.basic universes u namespace mvqpf variables {n m : ℕ} (F : typevec.{u} n → Type*) [mvfunctor F] [q : mvqpf F] (G : fin' n → typevec.{u} m → Type u) [∀ i, mvfunctor $ G i] [q' : ∀ i, mvqpf $ G i] def comp (v : typevec.{u} m) : Type* := F $ λ i : fin' n, G i v namespace comp open mvfunctor mvpfunctor variables {F G} {α β : typevec.{u} m} (f : α ⟹ β) protected def mk (x : F $ λ i, G i α) : (comp F G) α := x protected def get (x : (comp F G) α) : F $ λ i, G i α := x @[simp] protected lemma mk_get (x : (comp F G) α) : comp.mk (comp.get x) = x := rfl @[simp] protected lemma get_mk (x : F $ λ i, G i α) : comp.get (comp.mk x) = x := rfl protected def map' : (λ (i : fin' n), G i α) ⟹ λ (i : fin' n), G i β := λ i, map f protected def map : (comp F G) α → (comp F G) β := (map (λ i, map f) : F (λ i, G i α) → F (λ i, G i β)) instance : mvfunctor (comp F G) := { map := λ α β, comp.map } lemma map_mk (x : F $ λ i, G i α) : f <$$> comp.mk x = comp.mk ((λ i (x : G i α), f <$$> x) <$$> x) := rfl lemma get_map (x : comp F G α) : comp.get (f <$$> x) = (λ i (x : G i α), f <$$> x) <$$> comp.get x := rfl include q q' instance : mvqpf (comp F G) := { P := mvpfunctor.comp (P F) (λ i, P $ G i), abs := λ α, comp.mk ∘ map (λ i, abs) ∘ abs ∘ mvpfunctor.comp.get, repr' := λ α, mvpfunctor.comp.mk ∘ repr ∘ map (λ i, (repr : G i α → (λ (i : fin' n), apply (P (G i)) α) i)) ∘ comp.get, abs_repr' := by { intros, simp [(∘), mvfunctor.map_map, (⊚), abs_repr] }, abs_map := by { intros, simp [(∘)], rw [← abs_map], simp [id_map, (⊚), map_mk, mvpfunctor.comp.get_map, abs_map, mvfunctor.map_map, abs_repr] } } end comp end mvqpf
beb14d3005df7d3326fd9a449a31edac78749ded
e4a7c8ab8b68ca0e53d2c21397320ea590fa01c6
/src/data/polya/field/default.lean
6f4863487e395f14b34c8afcaee75f764420951b
[]
no_license
lean-forward/field
3ff5dc5f43de40f35481b375f8c871cd0a07c766
7e2127ad485aec25e58a1b9c82a6bb74a599467a
refs/heads/master
1,590,947,010,909
1,563,811,881,000
1,563,811,881,000
190,415,651
1
0
null
1,563,643,371,000
1,559,746,688,000
Lean
UTF-8
Lean
false
false
12
lean
import .main
c5c89b4a895e61dcc5315cd18641d9df5ead965c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/pfunctor/multivariate/M.lean
b74d0ef8d645af8924ec83530feb47b072fdfb04
[ "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
11,596
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import data.pfunctor.multivariate.basic import data.pfunctor.univariate.M /-! # The M construction as a multivariate polynomial functor. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. M types are potentially infinite tree-like structures. They are defined as the greatest fixpoint of a polynomial functor. ## Main definitions * `M.mk` - constructor * `M.dest` - destructor * `M.corec` - corecursor: useful for formulating infinite, productive computations * `M.bisim` - bisimulation: proof technique to show the equality of infinite objects ## Implementation notes Dual view of M-types: * `Mp`: polynomial functor * `M`: greatest fixed point of a polynomial functor Specifically, we define the polynomial functor `Mp` as: * A := a possibly infinite tree-like structure without information in the nodes * B := given the tree-like structure `t`, `B t` is a valid path from the root of `t` to any given node. As a result `Mp.obj α` is made of a dataless tree and a function from its valid paths to values of `α` The difference with the polynomial functor of an initial algebra is that `A` is a possibly infinite tree. ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universe u open_locale mvfunctor namespace mvpfunctor open typevec variables {n : ℕ} (P : mvpfunctor.{u} (n+1)) /-- A path from the root of a tree to one of its node -/ inductive M.path : P.last.M → fin2 n → Type u | root (x : P.last.M) (a : P.A) (f : P.last.B a → P.last.M) (h : pfunctor.M.dest x = ⟨a, f⟩) (i : fin2 n) (c : P.drop.B a i) : M.path x i | child (x : P.last.M) (a : P.A) (f : P.last.B a → P.last.M) (h : pfunctor.M.dest x = ⟨a, f⟩) (j : P.last.B a) (i : fin2 n) (c : M.path (f j) i) : M.path x i instance M.path.inhabited (x : P.last.M) {i} [inhabited (P.drop.B x.head i)] : inhabited (M.path P x i) := ⟨ M.path.root _ (pfunctor.M.head x) (pfunctor.M.children x) (pfunctor.M.cases_on' x $ by intros; simp [pfunctor.M.dest_mk]; ext; rw pfunctor.M.children_mk; refl) _ default ⟩ /-- Polynomial functor of the M-type of `P`. `A` is a data-less possibly infinite tree whereas, for a given `a : A`, `B a` is a valid path in tree `a` so that `Wp.obj α` is made of a tree and a function from its valid paths to the values it contains -/ def Mp : mvpfunctor n := { A := P.last.M, B := M.path P } /-- `n`-ary M-type for `P` -/ def M (α : typevec n) : Type* := P.Mp.obj α instance mvfunctor_M : mvfunctor P.M := by delta M; apply_instance instance inhabited_M {α : typevec _} [I : inhabited P.A] [Π (i : fin2 n), inhabited (α i)] : inhabited (P.M α) := @obj.inhabited _ (Mp P) _ (@pfunctor.M.inhabited P.last I) _ /-- construct through corecursion the shape of an M-type without its contents -/ def M.corec_shape {β : Type u} (g₀ : β → P.A) (g₂ : Π b : β, P.last.B (g₀ b) → β) : β → P.last.M := pfunctor.M.corec (λ b, ⟨g₀ b, g₂ b⟩) /-- Proof of type equality as an arrow -/ def cast_dropB {a a' : P.A} (h : a = a') : P.drop.B a ⟹ P.drop.B a' := λ i b, eq.rec_on h b /-- Proof of type equality as a function -/ def cast_lastB {a a' : P.A} (h : a = a') : P.last.B a → P.last.B a' := λ b, eq.rec_on h b /-- Using corecursion, construct the contents of an M-type -/ def M.corec_contents {α : typevec.{u} n} {β : Type u} (g₀ : β → P.A) (g₁ : Π b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : Π b : β, P.last.B (g₀ b) → β) : Π x b, x = M.corec_shape P g₀ g₂ b → M.path P x ⟹ α | ._ b h ._ (M.path.root x a f h' i c) := have a = g₀ b, by { rw [h, M.corec_shape, pfunctor.M.dest_corec] at h', cases h', refl }, g₁ b i (P.cast_dropB this i c) | ._ b h ._ (M.path.child x a f h' j i c) := have h₀ : a = g₀ b, by { rw [h, M.corec_shape, pfunctor.M.dest_corec] at h', cases h', refl }, have h₁ : f j = M.corec_shape P g₀ g₂ (g₂ b (cast_lastB P h₀ j)), by { rw [h, M.corec_shape, pfunctor.M.dest_corec] at h', cases h', refl }, M.corec_contents (f j) (g₂ b (P.cast_lastB h₀ j)) h₁ i c /-- Corecursor for M-type of `P` -/ def M.corec' {α : typevec n} {β : Type u} (g₀ : β → P.A) (g₁ : Π b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : Π b : β, P.last.B (g₀ b) → β) : β → P.M α := λ b, ⟨M.corec_shape P g₀ g₂ b, M.corec_contents P g₀ g₁ g₂ _ _ rfl⟩ /-- Corecursor for M-type of `P` -/ def M.corec {α : typevec n} {β : Type u} (g : β → P.obj (α.append1 β)) : β → P.M α := M.corec' P (λ b, (g b).fst) (λ b, drop_fun (g b).snd) (λ b, last_fun (g b).snd) /-- Implementation of destructor for M-type of `P` -/ def M.path_dest_left {α : typevec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : pfunctor.M.dest x = ⟨a, f⟩) (f' : M.path P x ⟹ α) : P.drop.B a ⟹ α := λ i c, f' i (M.path.root x a f h i c) /-- Implementation of destructor for M-type of `P` -/ def M.path_dest_right {α : typevec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : pfunctor.M.dest x = ⟨a, f⟩) (f' : M.path P x ⟹ α) : Π j : P.last.B a, M.path P (f j) ⟹ α := λ j i c, f' i (M.path.child x a f h j i c) /-- Destructor for M-type of `P` -/ def M.dest' {α : typevec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : pfunctor.M.dest x = ⟨a, f⟩) (f' : M.path P x ⟹ α) : P.obj (α.append1 (P.M α)) := ⟨a, split_fun (M.path_dest_left P h f') (λ x, ⟨f x, M.path_dest_right P h f' x⟩)⟩ /-- Destructor for M-types -/ def M.dest {α : typevec n} (x : P.M α) : P.obj (α ::: P.M α) := M.dest' P (sigma.eta $ pfunctor.M.dest x.fst).symm x.snd /-- Constructor for M-types -/ def M.mk {α : typevec n} : P.obj (α.append1 (P.M α)) → P.M α := M.corec _ (λ i, append_fun id (M.dest P) <$$> i) theorem M.dest'_eq_dest' {α : typevec n} {x : P.last.M} {a₁ : P.A} {f₁ : P.last.B a₁ → P.last.M} (h₁ : pfunctor.M.dest x = ⟨a₁, f₁⟩) {a₂ : P.A} {f₂ : P.last.B a₂ → P.last.M} (h₂ : pfunctor.M.dest x = ⟨a₂, f₂⟩) (f' : M.path P x ⟹ α) : M.dest' P h₁ f' = M.dest' P h₂ f' := by cases h₁.symm.trans h₂; refl theorem M.dest_eq_dest' {α : typevec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : pfunctor.M.dest x = ⟨a, f⟩) (f' : M.path P x ⟹ α) : M.dest P ⟨x, f'⟩ = M.dest' P h f' := M.dest'_eq_dest' _ _ _ _ theorem M.dest_corec' {α : typevec.{u} n} {β : Type u} (g₀ : β → P.A) (g₁ : Π b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : Π b : β, P.last.B (g₀ b) → β) (x : β) : M.dest P (M.corec' P g₀ g₁ g₂ x) = ⟨g₀ x, split_fun (g₁ x) (M.corec' P g₀ g₁ g₂ ∘ (g₂ x))⟩ := rfl theorem M.dest_corec {α : typevec n} {β : Type u} (g : β → P.obj (α.append1 β)) (x : β) : M.dest P (M.corec P g x) = append_fun id (M.corec P g) <$$> g x := begin transitivity, apply M.dest_corec', cases g x with a f, dsimp, rw mvpfunctor.map_eq, congr, conv { to_rhs, rw [←split_drop_fun_last_fun f, append_fun_comp_split_fun] }, refl end lemma M.bisim_lemma {α : typevec n} {a₁ : (Mp P).A} {f₁ : (Mp P).B a₁ ⟹ α} {a' : P.A} {f' : (P.B a').drop ⟹ α} {f₁' : (P.B a').last → M P α} (e₁ : M.dest P ⟨a₁, f₁⟩ = ⟨a', split_fun f' f₁'⟩) : ∃ g₁' (e₁' : pfunctor.M.dest a₁ = ⟨a', g₁'⟩), f' = M.path_dest_left P e₁' f₁ ∧ f₁' = λ (x : (last P).B a'), ⟨g₁' x, M.path_dest_right P e₁' f₁ x⟩ := begin generalize_hyp ef : @split_fun n _ (append1 α (M P α)) f' f₁' = ff at e₁, cases e₁' : pfunctor.M.dest a₁ with a₁' g₁', rw M.dest_eq_dest' _ e₁' at e₁, cases e₁, exact ⟨_, e₁', split_fun_inj ef⟩, end theorem M.bisim {α : typevec n} (R : P.M α → P.M α → Prop) (h : ∀ x y, R x y → ∃ a f f₁ f₂, M.dest P x = ⟨a, split_fun f f₁⟩ ∧ M.dest P y = ⟨a, split_fun f f₂⟩ ∧ ∀ i, R (f₁ i) (f₂ i)) (x y) (r : R x y) : x = y := begin cases x with a₁ f₁, cases y with a₂ f₂, dsimp [Mp] at *, have : a₁ = a₂, { refine pfunctor.M.bisim (λ a₁ a₂, ∃ x y, R x y ∧ x.1 = a₁ ∧ y.1 = a₂) _ _ _ ⟨⟨a₁, f₁⟩, ⟨a₂, f₂⟩, r, rfl, rfl⟩, rintro _ _ ⟨⟨a₁, f₁⟩, ⟨a₂, f₂⟩, r, rfl, rfl⟩, rcases h _ _ r with ⟨a', f', f₁', f₂', e₁, e₂, h'⟩, rcases M.bisim_lemma P e₁ with ⟨g₁', e₁', rfl, rfl⟩, rcases M.bisim_lemma P e₂ with ⟨g₂', e₂', _, rfl⟩, rw [e₁', e₂'], exact ⟨_, _, _, rfl, rfl, λ b, ⟨_, _, h' b, rfl, rfl⟩⟩ }, subst this, congr' with i p, induction p with x a f h' i c x a f h' i c p IH generalizing f₁ f₂; try { rcases h _ _ r with ⟨a', f', f₁', f₂', e₁, e₂, h''⟩, rcases M.bisim_lemma P e₁ with ⟨g₁', e₁', rfl, rfl⟩, rcases M.bisim_lemma P e₂ with ⟨g₂', e₂', e₃, rfl⟩, cases h'.symm.trans e₁', cases h'.symm.trans e₂' }, { exact (congr_fun (congr_fun e₃ i) c : _) }, { exact IH _ _ (h'' _) } end theorem M.bisim₀ {α : typevec n} (R : P.M α → P.M α → Prop) (h₀ : equivalence R) (h : ∀ x y, R x y → (id ::: quot.mk R) <$$> M.dest _ x = (id ::: quot.mk R) <$$> M.dest _ y) (x y) (r : R x y) : x = y := begin apply M.bisim P R _ _ _ r, clear r x y, introv Hr, specialize h _ _ Hr, clear Hr, rcases M.dest P x with ⟨ax,fx⟩, rcases M.dest P y with ⟨ay,fy⟩, intro h, rw [map_eq,map_eq] at h, injection h with h₀ h₁, subst ay, simp at h₁, clear h, have Hdrop : drop_fun fx = drop_fun fy, { replace h₁ := congr_arg drop_fun h₁, simpa using h₁, }, existsi [ax,drop_fun fx,last_fun fx,last_fun fy], rw [split_drop_fun_last_fun,Hdrop,split_drop_fun_last_fun], simp, intro i, replace h₁ := congr_fun (congr_fun h₁ fin2.fz) i, simp [(⊚),append_fun,split_fun] at h₁, replace h₁ := quot.exact _ h₁, rw h₀.eqv_gen_iff at h₁, exact h₁, end theorem M.bisim' {α : typevec n} (R : P.M α → P.M α → Prop) (h : ∀ x y, R x y → (id ::: quot.mk R) <$$> M.dest _ x = (id ::: quot.mk R) <$$> M.dest _ y) (x y) (r : R x y) : x = y := begin have := M.bisim₀ P (eqv_gen R) _ _, { solve_by_elim [eqv_gen.rel] }, { apply eqv_gen.is_equivalence }, { clear r x y, introv Hr, have : ∀ x y, R x y → eqv_gen R x y := @eqv_gen.rel _ R, induction Hr, { rw ← quot.factor_mk_eq R (eqv_gen R) this, rwa [append_fun_comp_id,← mvfunctor.map_map,← mvfunctor.map_map,h] }, all_goals { cc } } end theorem M.dest_map {α β : typevec n} (g : α ⟹ β) (x : P.M α) : M.dest P (g <$$> x) = append_fun g (λ x, g <$$> x) <$$> M.dest P x := begin cases x with a f, rw map_eq, conv { to_rhs, rw [M.dest, M.dest', map_eq, append_fun_comp_split_fun] }, reflexivity end theorem M.map_dest {α β : typevec n} (g : α ::: P.M α ⟹ β ::: P.M β) (x : P.M α) (h : ∀ x : P.M α, last_fun g x = (drop_fun g <$$> x : P.M β) ): g <$$> M.dest P x = M.dest P (drop_fun g <$$> x) := begin rw M.dest_map, congr, apply eq_of_drop_last_eq; simp, ext1, apply h end end mvpfunctor
4b2209e38216e973d8c89407d9bde01b78f613a2
8711b4976859218c98ea2129103249d693a4178b
/src/modal_logic/axioms.lean
c2b2e8a0984e42882c5a4aa02863ce7ad4526770
[]
no_license
kendfrey/modal_logic
e2433c122ff7012aa743739283ceaa3451e41e79
c07b5524de478cb57d796d0617b28990c7c77770
refs/heads/master
1,679,147,393,521
1,615,255,686,000
1,615,255,686,000
345,164,286
0
0
null
null
null
null
UTF-8
Lean
false
false
7,095
lean
import modal_logic.classes class is_dense (α : Type*) (r : α → α → Prop) : Prop := (dense : ∀ a b, r a b → ∃ c, r a c ∧ r c b) instance is_refl.is_dense {α r} [is_refl α r] : is_dense α r := ⟨λ a b h, ⟨a, refl a, h⟩⟩ class is_serial (α : Type*) (r : α → α → Prop) : Prop := (serial : ∀ a, ∃ b, r a b) instance is_refl.is_serial {α r} [is_refl α r] : is_serial α r := ⟨λ a, ⟨a, refl a⟩⟩ class is_euclidean (α : Type*) (r : α → α → Prop) : Prop := (euc : ∀ a b c, r a b → r a c → r b c) instance is_per.is_euclidean {α r} [is_per α r] : is_euclidean α r := ⟨λ a b c h h', trans (symm h) h'⟩ class is_semieuclidean (α : Type*) (r : α → α → Prop) := (semieuc : ∀ a b c, r a b → r a c → r b c ∨ r c b) instance is_euclidean.is_semieuclidean {α r} [is_euclidean α r] : is_semieuclidean α r := ⟨λ a b c h h', or.inl (is_euclidean.euc a b c h h')⟩ class is_founded (α : Type*) (r : α → α → Prop) : Prop := (founded : ∀ a, ∃ b, r a b ∧ ∀ c, r b c → b = c) class is_convergent (α : Type*) (r : α → α → Prop) : Prop := (conv : ∀ a b c, r a b → r a c → ∃ d, r b d ∧ r c d) class is_discrete (α : Type*) (r : α → α → Prop) : Prop := (disc : ∀ a b, r a b → a = b) class is_functional (α : Type*) (r : α → α → Prop) : Prop := (func : ∀ a b c, r a b → r a c → b = c) class is_function (α : Type*) (r : α → α → Prop) extends is_serial α r, is_functional α r : Prop instance is_discrete.is_functional {α r} [is_discrete α r] : is_functional α r := ⟨λ a b c h h', eq.trans (is_discrete.disc a b h).symm (is_discrete.disc a c h')⟩ class is_right_refl (α : Type*) (r : α → α → Prop) : Prop := (refl : ∀ a b, r a b → r b b) instance is_refl.is_right_refl {α r} [is_refl α r] : is_right_refl α r := ⟨λ a b h, refl b⟩ namespace modal_logic variables [_modal_model : modal_frame] (w : World) (p q : MProp) lemma em : w ⊩ p ∨ ¬p := em _ @[simp] lemma not_sat : (¬(w ⊩ p)) = (w ⊩ ¬p) := rfl lemma not_lam : (¬(λ w, p w)) = (λ w, ¬p w) := rfl @[simp] lemma not_not : (¬¬p) = p := by ext; simp only [not, iff, sat, not_not] @[simp] lemma not_imp : (¬(p ⇒ q)) = (p ∧ ¬q) := by ext; simp only [not, imp, and, iff, sat, not_imp] @[simp] lemma not_and : (¬(p ∧ q)) = (¬p ∨ ¬q) := by ext; simp only [not, and, or, iff, sat, not_and_distrib] @[simp] lemma not_or : (¬(p ∨ q)) = (¬p ∧ ¬q) := by ext; simp only [not, and, or, iff, sat, not_or_distrib] @[simp] lemma not_poss : (¬◇p) = □¬p := by ext; simp only [not, nec, poss, iff, sat, not_exists, _root_.not_and] @[simp] lemma not_nec : (¬□p) = ◇¬p := by ext; simp only [not, nec, poss, iff, sat, not_forall, exists_prop] @[simp] lemma nec_and : □(p ∧ q) = (□p ∧ □q) := by ext; simp only [nec, and, iff, sat, forall_and_distrib] @[simp] lemma poss_or : ◇(p ∨ q) = (◇p ∨ ◇q) := by ext; simp only [poss, or, iff, sat, ← exists_prop, exists_or_distrib] lemma and_comm : (p ∧ q) = (q ∧ p) := by ext; simp only [and, iff, sat, and_comm] lemma or_comm : (p ∨ q) = (q ∨ p) := by ext; simp only [or, iff, sat, or_comm] lemma or_eq_not_imp_left : (p ∨ q) = (¬p ⇒ q) := by ext; simp only [imp, not, or, iff, sat, or_iff_not_imp_left] lemma or_eq_not_imp_right : (p ∨ q) = (¬q ⇒ p) := by ext; simp only [imp, not, or, iff, sat, or_iff_not_imp_right] lemma nec_imp_nec_of_nec_imp : w ⊩ □(p ⇒ q) ⇒ □p ⇒ □q := λ h h' v h_v, h v h_v (h' v h_v) lemma of_nec [is_refl World (≺)] : w ⊩ □p ⇒ p := λ h, h w (refl w) lemma nec_nec_of_nec [is_trans World (≺)] : w ⊩ □p ⇒ □□p := λ h v h_v u h_u, h u (trans h_v h_u) lemma nec_of_nec_nec [is_dense World (≺)] : w ⊩ □□p ⇒ □p := λ h v h_v, let ⟨u, h_u, h_u'⟩ := is_dense.dense w v h_v in h u h_u v h_u' lemma poss_of_nec [is_serial World (≺)] : w ⊩ □p ⇒ ◇p := λ h, let ⟨v, h_v⟩ := is_serial.serial w in ⟨v, h_v, h v h_v⟩ lemma nec_poss [is_symm World (≺)] : w ⊩ p ⇒ □◇p := λ h v h_v, ⟨w, symm h_v, h⟩ lemma nec_poss_of_poss [is_euclidean World (≺)] : w ⊩ ◇p ⇒ □◇p := λ ⟨u, h_u, h⟩ v h_v, ⟨u, is_euclidean.euc w v u h_v h_u, h⟩ lemma nec_of_nec_nec_imp [is_trans World (≺)] (wf : well_founded (λ w v : World, v ≺ w)) : w ⊩ □(□p ⇒ p) ⇒ □p := by apply well_founded.induction wf w; exact λ v ih h u h_u, h u h_u (ih u h_u (λ t h_t, h t (trans h_u h_t))) lemma of_nec_nec_imp_nec_imp [is_preorder World (≺)] (wf : well_founded (λ w v : World, w ≠ v ∧ v ≺ w)) : w ⊩ □(□(p ⇒ □p) ⇒ p) ⇒ p := begin have : is_antisymm World (≺), { constructor, intros v u h_u h_v, rcases well_founded.has_min wf {v, u} ⟨v, set.mem_insert _ _⟩ with ⟨t, h_t, h⟩, simp only [set.mem_insert_iff, set.mem_singleton_iff, _root_.not_and, not_imp_not] at h h_t, rcases h_t with rfl | rfl, { exact (h u (or.inr rfl) h_u).symm, }, { exact h v (or.inl rfl) h_v, }, }, intros h, by_contra h_w_p, obtain ⟨v, h_v, h_v_p, h'⟩ : ∃ v, w ≺ v ∧ ¬(v ⊩ p) ∧ ∀ u, u ≠ v → v ≺ u → u ⊩ p, { rcases well_founded.has_min wf { v | w ≺ v ∧ ¬(v ⊩ p) } ⟨w, refl w, h_w_p⟩ with ⟨v, ⟨h_v, h_v'⟩, h'⟩, simp only [set.mem_set_of_eq, and_imp, not_imp_not] at h', exact ⟨v, h_v, h_v', λ u h_u h_u', h' u (trans h_v h_u') h_u h_u'⟩, }, refine h_v_p (h v h_v _), intros u h_u h_u_p t h_t, by_cases h'' : u = t, { exact h'' ▸ h_u_p, }, { exactI h' t (λ h''', (h'' (antisymm h_t (h'''.symm ▸ h_u)))) (trans h_u h_t), }, end lemma nec_nec_imp_or_nec_nec_imp [is_semieuclidean World (≺)] : w ⊩ □(□p ⇒ q) ∨ □(□q ⇒ p) := begin simp only [or_eq_not_imp_left, not_imp, not_nec], rintros ⟨v, h_v, h, h'⟩ u h_u h'', rcases is_semieuclidean.semieuc w v u h_v h_u with h_u' | h_v', { exact h u h_u', }, { exact false.rec _ (h' (h'' v h_v')), }, end lemma poss_nec_of_nec_poss [is_trans World (≺)] [is_founded World (≺)] : w ⊩ □◇p ⇒ ◇□p := λ h, let ⟨v, h_v, h_v'⟩ := is_founded.founded w in ⟨v, h_v, λ u h_u, let ⟨t, h_t, h'⟩ := h v h_v in h_v' u h_u ▸ (h_v' t h_t).symm ▸ h'⟩ lemma nec_poss_of_poss_nec [is_convergent World (≺)] : w ⊩ ◇□p ⇒ □◇p := λ ⟨u, h_u, h⟩ v h_v, let ⟨t, h_t, h_t'⟩ := is_convergent.conv w v u h_v h_u in ⟨t, h_t, h t h_t'⟩ lemma nec_of [is_discrete World (≺)] : w ⊩ p ⇒ □p := λ h u h_u, is_discrete.disc w u h_u ▸ h lemma nec_of_poss [is_functional World (≺)] : w ⊩ ◇p ⇒ □p := λ ⟨v, h_v, h⟩ u h_u, is_functional.func w v u h_v h_u ▸ h lemma nec_eq_poss [is_function World (≺)] : ◇p = □p := by ext; exact ⟨nec_of_poss w p, poss_of_nec w p⟩ lemma nec_nec_imp [is_right_refl World (≺)] : w ⊩ □(□p ⇒ p) := λ v h_v h, h v (is_right_refl.refl w v h_v) end modal_logic
f2db94ec0f4dfb4b4571930eb28c4f9244baec30
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/module/hom.lean
1bc931a85ecceea941c7292978311a3c3060bcb5
[ "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
1,815
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.module.pi /-! # Bundled hom instances for module and multiplicative actions This file defines instances for module, mul_action and related structures on bundled `_hom` types. These are analogous to the instances in `algebra.module.pi`, but for bundled instead of unbundled functions. -/ variables {R S A B : Type*} namespace add_monoid_hom section variables [monoid R] [monoid S] [add_monoid A] [add_comm_monoid B] variables [distrib_mul_action R B] [distrib_mul_action S B] instance : distrib_mul_action R (A →+ B) := { smul := λ r f, { to_fun := r • f, map_zero' := by simp, map_add' := λ x y, by simp [smul_add] }, one_smul := λ f, by simp, mul_smul := λ r s f, by simp [mul_smul], smul_add := λ r f g, ext $ λ x, by simp [smul_add], smul_zero := λ r, ext $ λ x, by simp [smul_zero] } @[simp] lemma coe_smul (r : R) (f : A →+ B) : ⇑(r • f) = r • f := rfl lemma smul_apply (r : R) (f : A →+ B) (x : A) : (r • f) x = r • f x := rfl instance [smul_comm_class R S B] : smul_comm_class R S (A →+ B) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ instance [has_smul R S] [is_scalar_tower R S B] : is_scalar_tower R S (A →+ B) := ⟨λ a b f, ext $ λ x, smul_assoc _ _ _⟩ instance [distrib_mul_action Rᵐᵒᵖ B] [is_central_scalar R B] : is_central_scalar R (A →+ B) := ⟨λ a b, ext $ λ x, op_smul_eq_smul _ _⟩ end instance [semiring R] [add_monoid A] [add_comm_monoid B] [module R B] : module R (A →+ B) := { add_smul := λ r s x, ext $ λ y, by simp [add_smul], zero_smul := λ x, ext $ λ y, by simp [zero_smul], ..add_monoid_hom.distrib_mul_action } end add_monoid_hom
6fb1e2bad2b644e58c2f206b43a5cd8f80f89345
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/box_integral/partition/tagged.lean
090be6c7aca9f471620ce5258db26137714b4ffc
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,004
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 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_bUnion_iff lemma subset_Union (h : J ∈ π) : ↑J ⊆ π.Union := subset_bUnion_of_mem h lemma Union_subset : π.Union ⊆ I := bUnion_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 ⟨π₁.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 := 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
ecfa77531cc5e4bde4cf3f2eff2850f963ce531e
a5084ddd747b77e77a324f1808b1a7bd33c0f232
/src/sylow.lean
ac375cddc4f30e64f03d36b2be46d874439834bd
[]
no_license
ChrisHughes24/Sylow
182654894c315c7f6af7eae6d40cdefebdd3e72c
64fba83fc3d9e3a875f2a768f84d9fc0bf1e0eb8
refs/heads/master
1,631,517,565,568
1,628,880,386,000
1,628,880,386,000
137,903,621
2
2
null
1,628,880,387,000
1,529,418,841,000
Lean
UTF-8
Lean
false
false
49,127
lean
import group_theory.order_of_element .Zmod algebra.pi_instances open equiv fintype finset function universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] namespace finset lemma filter_insert_of_pos [decidable_eq α] (s : finset α) {P : α → Prop} [decidable_pred P] (a : α) (h : P a) : (insert a s).filter P = insert a (s.filter P) := ext.2 (λ x, by rw [mem_filter, mem_insert, mem_insert, mem_filter, eq_comm]; exact ⟨λ h₁, by cases h₁.1; simp * at *, λ h₁, by cases h₁; simp * at *⟩) lemma filter_insert_of_neg [decidable_eq α] (s : finset α) {P : α → Prop} [decidable_pred P] (a : α) (h : ¬P a) : (insert a s).filter P = s.filter P := ext.2 (λ x, by rw [mem_filter, mem_insert, mem_filter, eq_comm]; exact ⟨λ h₁, by cases h₁.1; simp * at *, by finish⟩) lemma prod_const [comm_monoid β] (s : finset α) (b : β) [decidable_eq α] : s.prod (λ x, b) = b ^ s.card := finset.induction_on s rfl (by simp [pow_add, mul_comm] {contextual := tt}) lemma sum_const [add_comm_monoid β] (s : finset α) (b : β) [decidable_eq α] : s.sum (λ x, b) = add_monoid.smul s.card b := finset.induction_on s rfl (by simp [add_monoid.add_smul] {contextual := tt}) lemma card_pi {δ : α → Type*} [decidable_eq α] (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ end finset lemma nat.sum_mod [decidable_eq α] (s : finset α) (f : α → ℕ) (n : ℕ) : s.sum f ≡ (s.filter (λ x, f x % n ≠ 0)).sum f [MOD n] := finset.induction_on s rfl begin assume a s has ih, by_cases ha : f a % n ≠ 0, { rw [finset.sum_insert has, finset.filter_insert_of_pos s a ha, finset.sum_insert], exact nat.modeq.modeq_add rfl ih, { finish [finset.mem_filter] } }, { rw [finset.sum_insert has, finset.filter_insert_of_neg s a ha, ← zero_add (finset.sum (finset.filter _ _) _)], rw [ne.def, ← nat.zero_mod n] at ha, exact nat.modeq.modeq_add (not_not.1 ha) ih } end namespace fintype instance quotient_fintype {α : Type*} [fintype α] (s : setoid α) [decidable_eq (quotient s)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset_fintype [fintype α] : fintype (finset α) := ⟨finset.univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ instance set.fintype (α : Type u) [fintype α] [decidable_eq α] : fintype (set α) := pi.fintype def subtype_fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} := set_fintype _ lemma card_eq_one_iff [fintype α] : card α = 1 ↔ (∃ x : α, ∀ y : α, y = x) := by rw [← card_unit, card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm unit.star, λ y, a.bijective.1 (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, unit.star, λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma card_eq_zero_iff [fintype α] : card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [card_congr e]⟩ lemma card_pos_iff [fintype α] : 0 < card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have card α = 0 := card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt card_eq_zero_iff.1 (λ h, h a))⟩ lemma card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : injective f) : card α ≤ card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma card_le_one_iff [fintype α] : card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := card α in have hn : n = card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, card_unit ▸ card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end open finset lemma card_pi {β : α → Type*} [fintype α] [decidable_eq α] [f : Π a, fintype (β a)] : card (Π a, β a) = univ.prod (λ a, card (β a)) := by letI f : fintype (Πa∈univ, β a) := ⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩; exact calc card (Π a, β a) = card (Π a ∈ univ, β a) : card_congr ⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩ ... = univ.prod (λ a, card (β a)) : finset.card_pi _ _ lemma card_fun [fintype α] [decidable_eq α] [fintype β] : card (α → β) = card β ^ card α := by rw [card_pi, prod_const, nat.pow_eq_pow]; refl end fintype namespace set lemma card_eq_of_eq {s t : set α} [fintype s] [fintype t] (h : s = t) : card s = card t := by congr; assumption lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : card_fintype_of_finset' _ (by simp) ... = s.to_finset.card : card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = card s : (card_fintype_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h lemma coe_to_finset' [decidable_eq α] (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext (by simp) lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} lemma coe_ssubset [decidable_eq α] {s t : finset α} : (↑s : set α) ⊂ ↑t ↔ s ⊂ t := show ↑s ⊆ ↑t ∧ ↑s ≠ ↑t ↔ s ⊆ t ∧ ¬t ⊆ s, by split; simp [ssubset_iff_subset_not_subset, set.subset.antisymm_iff] {contextual := tt} lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : card s < card t := begin haveI := classical.prop_decidable, rw [card_fintype_of_finset' _ (λ x, mem_to_finset), card_fintype_of_finset' _ (λ x, mem_to_finset)], rw [← coe_to_finset' s, ← coe_to_finset' t, coe_ssubset] at h, exact finset.card_lt_card h, end def equiv_univ (α : Type u) : α ≃ (set.univ : set α) := { to_fun := λ a, ⟨a, mem_univ _⟩, inv_fun := λ a, a.1, left_inv := λ a, rfl, right_inv := λ ⟨a, ha⟩, rfl } @[simp] lemma card_univ (α : Type u) [fintype α] [fintype.{u} (set.univ : set α)] : fintype.card (set.univ : set α) = fintype.card α := eq.symm (card_congr (equiv_univ α)) lemma eq_of_card_eq_of_subset {s t : set α} [fintype s] [fintype t] (hcard : card s = card t) (hsub : s ⊆ t) : s = t := classical.by_contradiction (λ h, lt_irrefl (card t) (have card s < card t := set.card_lt_card ⟨hsub, h⟩, by rwa hcard at this)) end set local attribute [instance, priority 0] fintype.subtype_fintype set_fintype classical.prop_decidable section should_be_in_group_theory noncomputable instance [fintype G] (H : set G) [is_subgroup H] : fintype (left_cosets H) := fintype.quotient_fintype (left_rel H) lemma card_eq_card_cosets_mul_card_subgroup [fintype G] (H : set G) [is_subgroup H] : card G = card (left_cosets H) * card H := by rw ← card_prod; exact card_congr (is_subgroup.group_equiv_left_cosets_times_subgroup _) lemma order_of_dvd_of_pow_eq_one [fintype G] {a : G} {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 _ (nat.pos_of_ne_zero (order_of_ne_zero _))) ⟨mt nat.dvd_of_mod_eq_zero h₁, by rwa ← pow_eq_mod_order_of⟩) lemma eq_one_of_order_of_eq_one [fintype G] {a : G} (h : order_of a = 1) : a = 1 := by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] } lemma order_eq_card_gpowers [fintype G] {a : G} : order_of a = 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 $ nat.pos_iff_ne_zero.mpr $ order_of_ne_zero 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 card_trivial [fintype (is_subgroup.trivial G)] : fintype.card (is_subgroup.trivial G) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : G), by simp⟩, λ ⟨y, hy⟩, subtype.eq $ is_subgroup.mem_trivial.1 hy⟩ local attribute [instance] left_rel normal_subgroup.to_is_subgroup instance quotient.mk.is_group_hom (H : set G) [normal_subgroup H] : @is_group_hom G (left_cosets H) _ _ quotient.mk := ⟨λ _ _, rfl⟩ instance subtype.val.is_group_hom (H : set G) [is_subgroup H] : is_group_hom (subtype.val : H → G) := ⟨λ _ _, rfl⟩ def normalizer (H : set G) : set G := { g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H } instance (H : set G) [is_subgroup H] : is_subgroup (normalizer H) := { one_mem := by simp [normalizer], mul_mem := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by rw [mul_inv_rev, ← mul_assoc, mul_assoc a, mul_assoc a, ← ha, ← hb], inv_mem := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by rw [ha (a⁻¹ * n * a⁻¹⁻¹)]; simp [mul_assoc] } lemma subset_normalizer (H : set G) [is_subgroup H] : H ⊆ normalizer H := λ g hg n, by rw [is_subgroup.mul_mem_cancel_left _ ((is_subgroup.inv_mem_iff _).2 hg), is_subgroup.mul_mem_cancel_right _ hg] instance (H : set G) [is_subgroup H] : normal_subgroup { x : normalizer H | ↑x ∈ H } := { one_mem := show (1 : G) ∈ H, from is_submonoid.one_mem _, mul_mem := λ a b ha hb, show (a * b : G) ∈ H, from is_submonoid.mul_mem ha hb, inv_mem := λ a ha, show (a⁻¹ : G) ∈ H, from is_subgroup.inv_mem ha, normal := λ a ha ⟨m, hm⟩, (hm a).1 ha } lemma conj_inj_left {x : G} : injective (λ (n : G), x * n * x⁻¹) := λ a b h, (mul_left_inj x).1 $ (mul_right_inj (x⁻¹)).1 h lemma mem_normalizer_fintype {H : set G} [fintype H] {x : G} : (∀ n, n ∈ H → x * n * x⁻¹ ∈ H) → x ∈ normalizer H := λ h n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' H = H := set.eq_of_card_eq_of_subset (set.card_image_of_injective _ conj_inj_left) (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' H := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_inj_left hy.2 ▸ hy.1⟩ noncomputable lemma preimage_quotient_mk_equiv_subgroup_times_set (H : set G) [is_subgroup H] (s : set (left_cosets H)) : quotient.mk ⁻¹' s ≃ (H × s) := have h : ∀ {x : left_cosets H} {a : G}, x ∈ s → a ∈ H → ⟦quotient.out x * a⟧ = ⟦quotient.out x⟧ := λ x a hx ha, quotient.sound (show (quotient.out x * a)⁻¹ * quotient.out x ∈ H, from (is_subgroup.inv_mem_iff _).1 $ by rwa [mul_inv_rev, inv_inv, ← mul_assoc, inv_mul_self, one_mul]), { to_fun := λ ⟨a, ha⟩, ⟨⟨(quotient.out ⟦a⟧)⁻¹ * a, @quotient.exact _ (left_rel H) _ _ $ by simp⟩, ⟨⟦a⟧, ha⟩⟩, inv_fun := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, ⟨(quotient.out x) * a, show _ ∈ s, by simpa [h hx ha]⟩, left_inv := λ ⟨a, ha⟩, by simp, right_inv := λ ⟨⟨a, ha⟩, ⟨x, hx⟩⟩, by simp [h hx ha] } end should_be_in_group_theory class is_group_action (f : G → α → α) : Prop := (one : ∀ a : α, f (1 : G) a = a) (mul : ∀ (x y : G) (a : α), f (x * y) a = f x (f y a)) namespace group_action variables (f : G → α → α) [is_group_action f] @[simp] lemma one_apply (a : α) : f 1 a = a := is_group_action.one f a lemma mul_apply (x y : G) (a : α) : f (x * y) a = f x (f y a) := is_group_action.mul _ _ _ _ lemma bijective (g : G) : bijective (f g) := bijective_iff_has_inverse.2 ⟨f (g⁻¹), λ a, by rw [← mul_apply f, inv_mul_self, one_apply f], λ a, by rw [← mul_apply f, mul_inv_self, one_apply f]⟩ def orbit (a : α) := set.range (λ x : G, f x a) lemma mem_orbit_iff {f : G → α → α} [is_group_action f] {a b : α} : b ∈ orbit f a ↔ ∃ x : G, f x a = b := by finish [orbit] @[simp] lemma mem_orbit (a : α) (x : G) : f x a ∈ orbit f a := ⟨x, rfl⟩ @[simp] lemma mem_orbit_self (a : α) : a ∈ orbit f a := ⟨1, show f 1 a = a, by simp [one_apply f]⟩ lemma orbit_eq {f : G → α → α} [is_group_action f] {a b : α} : a ∈ orbit f b → orbit f a = orbit f b := λ ⟨x, (hx : f x b = a)⟩, set.ext (λ c, ⟨λ ⟨y, (hy : f y a = c)⟩, ⟨y * x, show f (y * x) b = c, by rwa [mul_apply f, hx]⟩, λ ⟨y, (hy : f y b = c)⟩, ⟨y * x⁻¹, show f (y * x⁻¹) a = c, by conv {to_rhs, rw [← hy, ← mul_one y, ← inv_mul_self x, ← mul_assoc, mul_apply f, hx]}⟩⟩) instance orbit_fintype (a : α) [decidable_eq α] [fintype G] : fintype (orbit f a) := set.fintype_range _ def stabilizer (a : α) : set G := {x : G | f x a = a} lemma mem_stabilizer_iff {f : G → α → α} [is_group_action f] {a : α} {x : G} : x ∈ stabilizer f a ↔ f x a = a := iff.rfl instance (a : α) : is_subgroup (stabilizer f a) := { one_mem := one_apply _ _, mul_mem := λ x y (hx : f x a = a) (hy : f y a = a), show f (x * y) a = a, by rw mul_apply f; simp *, inv_mem := λ x (hx : f x a = a), show f x⁻¹ a = a, by rw [← hx, ← mul_apply f, inv_mul_self, one_apply f, hx] } noncomputable lemma orbit_equiv_left_cosets (a : α) : orbit f a ≃ left_cosets (stabilizer f a) := by letI := left_rel (stabilizer f a); exact equiv.symm (@equiv.of_bijective _ _ (λ x : left_cosets (stabilizer f a), quotient.lift_on x (λ x, (⟨f x a, mem_orbit _ _ _⟩ : orbit f a)) (λ g h (H : _ = _), subtype.eq $ (group_action.bijective f (g⁻¹)).1 $ show f g⁻¹ (f g a) = f g⁻¹ (f h a), by rw [← mul_apply f, ← mul_apply f, H, inv_mul_self, one_apply f])) ⟨λ g h, quotient.induction_on₂ g h (λ g h H, quotient.sound $ have H : f g a = f h a := subtype.mk.inj H, show f (g⁻¹ * h) a = a, by rw [mul_apply f, ← H, ← mul_apply f, inv_mul_self, one_apply f]), λ ⟨b, ⟨g, hgb⟩⟩, ⟨⟦g⟧, subtype.eq hgb⟩⟩) def fixed_points : set α := {a : α | ∀ x, x ∈ stabilizer f a} lemma mem_fixed_points {f : G → α → α} [is_group_action f] {a : α} : a ∈ fixed_points f ↔ ∀ x : G, f x a = a := iff.rfl lemma mem_fixed_points' {f : G → α → α} [is_group_action f] {a : α} : a ∈ fixed_points f ↔ (∀ b, b ∈ orbit f a → b = a) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, mem_stabilizer_iff.2 (h _ (mem_orbit _ _ _))⟩ lemma card_orbit_of_mem_fixed_points {f : G → α → α} [is_group_action f] {a : α} [fintype (orbit f a)] : a ∈ fixed_points f ↔ card (orbit f a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _ _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc f x a = z : subtype.mk.inj (hz₁ ⟨f x a, mem_orbit _ _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _ _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points f)] {p n : ℕ} (hp : nat.prime p) (h : card G = p ^ n) : card α ≡ card (fixed_points f) [MOD p] := have hcard : ∀ s : set α, card ↥{x : α | orbit f x = s} % p ≠ 0 ↔ card ↥{x : α | orbit f x = s} = 1 := λ s, ⟨λ hs, begin have h : ∃ y, orbit f y = s := by_contradiction (λ h, begin rw not_exists at h, have : {x | orbit f x = s} = ∅ := set.eq_empty_iff_forall_not_mem.2 h, rw [set.card_eq_of_eq this, set.empty_card', nat.zero_mod] at hs, contradiction end), cases h with y hy, have hseq : {x | orbit f x = s} = orbit f y := set.ext (λ z, ⟨λ h : orbit f z = s, hy.symm ▸ h ▸ mem_orbit_self _ _, λ h, show orbit f z = s, by rwa orbit_eq h⟩), rw [card_eq_card_cosets_mul_card_subgroup (stabilizer f y), ← card_congr (orbit_equiv_left_cosets f y)] at h, have : ∃ k ≤ n, card (orbit f y) = p ^ k := (nat.dvd_prime_pow hp).1 (h ▸ dvd_mul_right _ _), rcases this with ⟨k, hk₁, hk₂⟩, rw [set.card_eq_of_eq hseq, hk₂] at hs ⊢, have : ¬p ∣ p ^ k := mt nat.mod_eq_zero_of_dvd hs, cases k, { refl }, { simpa [nat.pow_succ] using this } end, λ hs, hs.symm ▸ (nat.mod_eq_of_lt hp.gt_one).symm ▸ λ h, nat.no_confusion h⟩, have h : (finset.univ.filter (λ a, card {x | orbit f x = a} % p ≠ 0)).sum (λ a : set α, card {x | orbit f x = a}) = card (fixed_points f), from calc _ = (finset.univ.filter (λ a, card {x | orbit f x = a} % p ≠ 0)).sum (λ a : set α, 1) : finset.sum_congr rfl (λ s hs, (hcard s).1 (finset.mem_filter.1 hs).2) ... = card {a : set α | card ↥{x : α | orbit f x = a} % p ≠ 0} : begin rw [finset.sum_const, nat.smul_eq_mul, mul_one], refine eq.symm (set.card_fintype_of_finset' _ _), simp [finset.mem_filter], end ... = card (fixed_points f) : fintype.card_congr (@equiv.of_bijective _ _ (show fixed_points f → {a : set α // card ↥{x : α | orbit f x = a} % p ≠ 0}, from λ x, ⟨orbit f x.1, begin rw [hcard, fintype.card_eq_one_iff], exact ⟨⟨x, rfl⟩, λ ⟨y, hy⟩, have hy : y ∈ orbit f x := (show orbit f y = orbit f x, from hy) ▸ mem_orbit_self _ _, subtype.eq (mem_fixed_points'.1 x.2 _ hy)⟩ end⟩) ⟨λ x y hxy, have hxy : orbit f x.1 = orbit f y.1 := subtype.mk.inj hxy, have hxo : x.1 ∈ orbit f y.1 := hxy ▸ mem_orbit_self _ _, subtype.eq (mem_fixed_points'.1 y.2 _ hxo), λ ⟨s, hs⟩, begin rw [hcard, fintype.card_eq_one_iff] at hs, rcases hs with ⟨⟨x, hx₁⟩, hx₂⟩, exact ⟨⟨x, mem_fixed_points'.2 (λ y hy, subtype.mk.inj (hx₂ ⟨y, by have := orbit_eq hy; simpa [this, hx₁] using hx₁⟩))⟩, by simpa using hx₁⟩ end⟩).symm, calc card α % p = finset.sum finset.univ (λ a : set α, card {x // orbit f x = a}) % p : by rw [card_congr (equiv_fib (orbit f)), fintype.card_sigma] ... = _ : nat.sum_mod _ _ _ ... = fintype.card ↥(fixed_points f) % p : by rw ← h; congr end group_action namespace sylow open group_action def mk_vector_prod_eq_one (n : ℕ) [Zmod.pos n] (v : Zmod n → G) : Zmod (n+1) → G := λ m, if h : m.1 < n then v m.1 else ((list.range n).map (λ m : ℕ, v (m : Zmod n))).prod⁻¹ lemma mk_vector_prod_eq_one_injective {p : ℕ} [h0 : Zmod.pos p] : injective (@mk_vector_prod_eq_one G _ p _) := λ x y hxy, funext (λ ⟨a, ha⟩, begin have : dite _ _ _ = dite _ _ _ := congr_fun hxy a, rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_of_lt ha), dif_pos ha, dif_pos ha] at this, rwa Zmod.mk_eq_cast end) /-- set of elements of G^n such that the product of the list of elements of the vector is one -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) [Zmod.pos n] : set (Zmod n → G) := {v | ((list.range n).map (λ m : ℕ, v (↑m : Zmod n))).prod = 1 } lemma mem_vectors_prod_eq_one_iff {n : ℕ} [Zmod.pos n] (v : Zmod (n + 1) → G) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ mk_vector_prod_eq_one n '' (set.univ : set (Zmod n → G)) := have prod_lemma : ((list.range (n + 1)).map (λ m : ℕ, v (m : Zmod (n + 1)))).prod = list.prod (list.map (λ (m : ℕ), v ↑m) (list.range n)) * v ↑n := by rw [list.range_concat, list.map_append, list.prod_append, list.map_singleton, list.prod_cons, list.prod_nil, mul_one], ⟨λ h : list.prod (list.map (λ (m : ℕ), v ↑m) (list.range (n + 1))) = 1, have h₁ : list.map (λ (m : ℕ), v ((m : Zmod n).val : Zmod (n+1))) (list.range n) = list.map (λ (m : ℕ), v m) (list.range n) := list.map_congr (λ m hm, have hm' : m < n := list.mem_range.1 hm, by simp [Zmod.cast_val, nat.mod_eq_of_lt hm']), ⟨λ m, v m.val, set.mem_univ _, funext (λ i, show dite _ _ _ = _, begin split_ifs, { refine congr_arg _ (fin.eq_of_veq _), simp [Zmod.cast_val, nat.mod_eq_of_lt h_1, nat.mod_eq_of_lt (nat.lt_succ_of_lt h_1)] }, { have hi : i = n := fin.eq_of_veq begin rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_self _)], exact le_antisymm (nat.le_of_lt_succ i.2) (le_of_not_gt h_1), end, rw [h₁, hi, inv_eq_iff_mul_eq_one, ← prod_lemma, h] } end)⟩, λ ⟨w, hw⟩, have h : list.map (λ m : ℕ, w m) (list.range n) = list.map (λ m : ℕ, v m) (list.range n) := list.map_congr (λ k hk, have hk' : k < n := list.mem_range.1 hk, hw.2 ▸ (show _ = dite _ _ _, by rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_of_lt hk'), dif_pos hk'])), begin show list.prod (list.map (λ (m : ℕ), v ↑m) (list.range (n + 1))) = 1, rw [prod_lemma, ← h, ← hw.2], show _ * dite _ _ _ = (1 : G), rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_self _), dif_neg (lt_irrefl _), mul_inv_self], end⟩ def rotate (α : Type v) (n : ℕ) (i : multiplicative (Zmod n)) (v : multiplicative (Zmod n) → α) (m : multiplicative (Zmod n)) := v (m * i) instance rotate.is_group_action (n : ℕ) [Zmod.pos n] : is_group_action (rotate α n) := { mul := λ x y v, funext (λ i, show v (i * (x * y)) = v (i * x * y), by rw mul_assoc), one := λ v, funext (λ i, show v (i * 1) = v i, by rw mul_one) } lemma fixed_points_rotate_eq_const {n : ℕ} [h0 : Zmod.pos n] {v : multiplicative (Zmod n) → G} (h : v ∈ fixed_points (rotate G n)) (i j : multiplicative (Zmod n)) : v i = v j := calc v i = v (j * i) : mul_comm i j ▸ (congr_fun ((mem_fixed_points'.1 h _) (mem_orbit (rotate G n) v j)) i).symm ... = v j : congr_fun ((mem_fixed_points'.1 h _) (mem_orbit (rotate G n) v i)) j lemma map_succ_range : ∀ n : ℕ, list.range (nat.succ n) = 0 :: (list.range n).map nat.succ | 0 := rfl | (n+1) := by rw [list.range_concat, list.range_concat, list.map_append, ← list.cons_append, ← map_succ_range, list.range_concat, list.map_singleton] open nat lemma list.prod_const [monoid α] : ∀ {l : list α} {a : α}, (∀ b ∈ l, b = a) → l.prod = a ^ l.length | [] := λ _ _, rfl | (b::l) := λ a ha, have h : ∀ b ∈ l, b = a := λ b hb, ha b (list.mem_cons_of_mem _ hb), have hb : b = a := ha b (list.mem_cons_self _ _), by simp [_root_.pow_add, list.prod_const h, hb] lemma rotate_on_vectors_prod_eq_one {n : ℕ} [h0 : Zmod.pos n] {v : Zmod n → G} (hv : v ∈ vectors_prod_eq_one G n) (i : Zmod n) : (rotate G n) (i : Zmod n) v ∈ vectors_prod_eq_one G n := begin cases i with i hi, rw Zmod.mk_eq_cast, clear hi, induction i with i ih, { show list.prod (list.map (λ (m : ℕ), v (m + 0)) (list.range n)) = 1, simpa }, { show list.prod (list.map (λ (m : ℕ), v (m + (i + 1))) (list.range n)) = 1, replace ih : list.prod (list.map (λ (m : ℕ), v (m + i)) (list.range n)) = 1 := ih, resetI, cases n, { simp [list.range, list.range_core] }, { rw [list.range_concat, list.map_append, list.prod_append, list.map_singleton, list.prod_cons, list.prod_nil, mul_one] at ⊢ ih, have h : list.map (λ m : ℕ, v (↑m + (i + 1))) (list.range n) = list.map (λ m : ℕ, v (m + i)) (list.map (λ m : ℕ, m + 1) (list.range n)), { simp [list.map_map, comp] }, resetI, cases n, { refine eq.trans _ ih, simp [list.range, list.range_core]; congr }, { have h : list.map (λ m : ℕ, v (↑m + (i + 1))) (list.range n) = list.map (λ m : ℕ, v (m + i)) (list.map succ (list.range n)), { simp [list.map_map, comp] }, have h₁ : (succ n : Zmod (succ (succ n))) + (↑i + 1) = i, { rw [add_left_comm, ← nat.cast_one, ← nat.cast_add, Zmod.cast_self_eq_zero, add_zero] }, have h₂ : (n : Zmod (succ (succ n))) + i + 1 = succ n + i := by simp [succ_eq_add_one], rw [map_succ_range, list.map_cons, list.prod_cons, ← h, nat.cast_zero, zero_add] at ih, have := eq_inv_mul_of_mul_eq ih, rw [list.range_concat, list.map_append, list.map_singleton, list.prod_append, list.prod_cons, list.prod_nil, mul_one, ← add_assoc, h₁, h₂, this], simp } } } end def rotate_vectors_prod_eq_one (G : Type u) [group G] (n : ℕ) [Zmod.pos n] (i : multiplicative (Zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨rotate _ n i v.1, rotate_on_vectors_prod_eq_one v.2 _⟩ instance (n : ℕ) [Zmod.pos n] : is_group_action (rotate_vectors_prod_eq_one G n) := { one := λ ⟨a, ha⟩, subtype.eq (is_group_action.one (rotate G n) _), mul := λ x y ⟨a, ha⟩, subtype.eq (is_group_action.mul (rotate G n) _ _ _) } lemma mem_fixed_points_rotate_vectors_prod_eq_one {n : ℕ} [Zmod.pos n] : ∀ {v : vectors_prod_eq_one G n}, v ∈ fixed_points (rotate_vectors_prod_eq_one G n) ↔ (v : Zmod n → G) ∈ fixed_points (rotate G n) := λ ⟨v, hv⟩, ⟨λ h x, subtype.mk.inj (h x), λ h x, subtype.eq (h x)⟩ lemma fixed_points_rotate_pow_n [fintype G] {n : ℕ} (hn : nat.prime (succ n)) [h0 : Zmod.pos n] : ∀ {v : vectors_prod_eq_one G (succ n)} (hv : v ∈ fixed_points (rotate_vectors_prod_eq_one G (succ n))), (v : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := λ ⟨v, hv₁⟩ hv, let ⟨w, hw⟩ := (mem_vectors_prod_eq_one_iff _).1 hv₁ in have hv' : (v : Zmod (succ n) → G) ∈ fixed_points (rotate G (succ n)) := λ i, subtype.mk.inj (mem_stabilizer_iff.1 (hv i)), begin have h₁ : dite _ _ _ = (v : Zmod (succ n) → G) _ := congr_fun hw.2 ⟨n, nat.lt_succ_self n⟩, rw dif_neg (lt_irrefl _) at h₁, have h₂ : ∀ b, b < n → w b = (v : Zmod (succ n) → G) b := λ b hb, begin have : dite _ _ _ = _ := congr_fun hw.2 b, rwa [Zmod.cast_val_of_lt (lt_succ_of_lt hb), dif_pos hb] at this, end, have hb : ∀ (b : G), b ∈ list.map (λ (m : ℕ), w ↑m) (list.range n) → b = w 0 := λ b hb, let ⟨i, hi⟩ := list.mem_map.1 hb in by rw [← hi.2, h₂ _ (list.mem_range.1 hi.1), fixed_points_rotate_eq_const hv' _ 1]; exact (h₂ 0 h0.pos).symm, refine (@mul_left_inj _ _ (w 0 ^ (-n : ℤ)) _ _).1 _, rw [@list.prod_const _ _ _ (w 0) hb, list.length_map, list.length_range, ← gpow_coe_nat, ← gpow_neg] at h₁, conv { to_rhs, rw [h₁, fixed_points_rotate_eq_const hv' _ 1] }, rw [← nat.cast_zero, h₂ 0 h0.pos, nat.cast_zero, subtype.coe_mk, ← gpow_coe_nat, ← _root_.gpow_add, int.coe_nat_add], simp, refl, end lemma one_mem_fixed_points_rotate [fintype G] {n : ℕ} [h0 : Zmod.pos n] : (1 : Zmod n → G) ∈ fixed_points (rotate G n) := mem_fixed_points'.2 (λ y hy, funext (λ j, let ⟨i, hi⟩ := mem_orbit_iff.1 hy in have hj : (1 : G) = y j := congr_fun hi j, hj ▸ rfl)) lemma one_mem_vectors_prod_eq_one (n : ℕ) [Zmod.pos n] : (1 : Zmod n → G) ∈ vectors_prod_eq_one G n := show list.prod (list.map (λ (m : ℕ), (1 : G)) (list.range n)) = 1, from have h : ∀ b : G, b ∈ list.map (λ (m : ℕ), (1 : G)) (list.range n) → b = 1 := λ b hb, let ⟨_, h⟩ := list.mem_map.1 hb in h.2.symm, by simp [list.prod_const h] lemma exists_prime_order_of_dvd_card [fintype G] {p : ℕ} (hp : nat.prime p) (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n := p - 1 in have hn : p = n + 1 := nat.succ_sub hp.pos, have hnp : nat.prime (n + 1) := hn ▸ hp, have hn0 : Zmod.pos n := ⟨nat.lt_of_succ_lt_succ hnp.gt_one⟩, have hlt : ¬(n : Zmod (n + 1)).val < n := not_lt_of_ge (by rw [Zmod.cast_val, nat.mod_eq_of_lt (nat.lt_succ_self _)]; exact le_refl _), have hcard1 : card (vectors_prod_eq_one G (n + 1)) = card (Zmod n → G) := by rw [← set.card_univ (Zmod n → G), set.ext (@mem_vectors_prod_eq_one_iff _ _ _ hn0), set.card_image_of_injective _ mk_vector_prod_eq_one_injective], have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ n := by conv { rw hcard1, to_rhs, rw ← card_fin n }; exact fintype.card_fun, have fintype (multiplicative (Zmod (succ n))) := fin.fintype _, have Zmod.pos (succ n) := ⟨succ_pos _⟩, have hZmod : @fintype.card (multiplicative (Zmod (succ n))) (fin.fintype _) = (n+1) ^ 1 := (nat.pow_one (n + 1)).symm ▸ card_fin _, by exactI have hmodeq : _ = _ := @card_modeq_card_fixed_points _ _ _ (rotate_vectors_prod_eq_one G (succ n)) _ _ _ _ _ 1 hnp hZmod, have hdvdcard : (n + 1) ∣ card (vectors_prod_eq_one G (n + 1)) := calc (n + 1) = p : hn.symm ... ∣ card G ^ 1 : by rwa nat.pow_one ... ∣ card G ^ n : nat.pow_dvd_pow _ hn0.pos ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : (n + 1) ∣ card (fixed_points (rotate_vectors_prod_eq_one G (succ n))) := nat.dvd_of_mod_eq_zero (hmodeq ▸ (nat.mod_eq_zero_of_dvd hdvdcard)), have hcard_pos : 0 < card (fixed_points (rotate_vectors_prod_eq_one G (succ n))) := fintype.card_pos_iff.2 ⟨⟨⟨(1 : Zmod (succ n) → G), one_mem_vectors_prod_eq_one _⟩, λ x, subtype.eq (one_mem_fixed_points_rotate x)⟩⟩, have hle : 1 < card (fixed_points (rotate_vectors_prod_eq_one G (succ n))) := calc 1 < n + 1 : hnp.gt_one ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨x, hx₁⟩, hx₂⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt hle)) in let ⟨⟨y, hy₁⟩, hy₂⟩ := classical.not_forall.1 hx₂ in have hxy : (x : Zmod (succ n) → G) 0 ≠ 1 ∨ (y : Zmod (succ n) → G) 0 ≠ 1 := or_iff_not_imp_left.2 (λ hx1 hy1, hy₂ $ subtype.eq $ subtype.eq $ funext $ λ i, show (x : Zmod (succ n) → G) i = (y : Zmod (succ n) → G) i, by rw [fixed_points_rotate_eq_const ((mem_fixed_points_rotate_vectors_prod_eq_one).1 hx₁) _ (0 : Zmod (succ n)), fixed_points_rotate_eq_const ((mem_fixed_points_rotate_vectors_prod_eq_one).1 hy₁) _ (0 : Zmod (succ n)), not_not.1 hx1, hy1]), have hxp : (x : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := @fixed_points_rotate_pow_n _ _ _ _ hnp hn0 _ hx₁, have hyp : (y : Zmod (succ n) → G) 0 ^ (n + 1) = 1 := @fixed_points_rotate_pow_n _ _ _ _ hnp hn0 _ hy₁, begin rw hn, cases hxy with hx hy, { existsi (x : Zmod (succ n) → G) 0, exact or.resolve_left (hnp.2 _ (order_of_dvd_of_pow_eq_one hxp)) (λ h, hx (eq_one_of_order_of_eq_one h)) }, { existsi (y : Zmod (succ n) → G) 0, exact or.resolve_left (hnp.2 _ (order_of_dvd_of_pow_eq_one hyp)) (λ h, hy (eq_one_of_order_of_eq_one h)) } end local attribute [instance] left_rel set_fintype open is_subgroup is_submonoid is_group_hom def mul_left_cosets (L₁ L₂ : set G) [is_subgroup L₂] [is_subgroup L₁] (x : L₂) (y : left_cosets L₁) : left_cosets L₁ := quotient.lift_on y (λ y, ⟦(x : G) * y⟧) (λ a b (hab : _ ∈ L₁), quotient.sound (show _ ∈ L₁, by rwa [mul_inv_rev, ← mul_assoc, mul_assoc (a⁻¹), inv_mul_self, mul_one])) instance mul_left_cosets.is_group_action (L₁ L₂ : set G) [is_subgroup L₂] [is_subgroup L₁] : is_group_action (mul_left_cosets L₁ L₂) := { one := λ a, quotient.induction_on a (λ a, quotient.sound (show (1 : G) * a ≈ a, by simp)), mul := λ x y a, quotient.induction_on a (λ a, quotient.sound (by rw ← mul_assoc; refl)) } lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : set G} [is_subgroup H] [fintype H] {x : G} : ⟦x⟧ ∈ fixed_points (mul_left_cosets H H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : left_cosets H}, y ∈ orbit (mul_left_cosets H H) ⟦x⟧ → y = ⟦x⟧ := λ _, (mem_fixed_points'.1 hx _), (inv_mem_iff _).1 (mem_normalizer_fintype (λ n hn, have (n⁻¹ * x)⁻¹ * x ∈ H := quotient.exact (ha (mem_orbit (mul_left_cosets H H) _ ⟨n⁻¹, inv_mem hn⟩)), by simpa only [mul_inv_rev, inv_inv] using this)), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), mem_fixed_points'.2 $ λ y, quotient.induction_on y $ λ y hy, quotient.sound (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient.exact hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_right H (inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ lemma fixed_points_mul_left_cosets_equiv_cosets (H : set G) [is_subgroup H] [fintype H] : fixed_points (mul_left_cosets H H) ≃ left_cosets {x : normalizer H | ↑x ∈ H} := { to_fun := λ a, quotient.hrec_on a.1 (λ a ha, @quotient.mk _ (left_rel {x : normalizer H | ↑x ∈ H}) ⟨a, mem_fixed_points_mul_left_cosets_iff_mem_normalizer.1 ha⟩) (λ x y hxy, hfunext (by rw quotient.sound hxy) (λ hx hy _, heq_of_eq (@quotient.sound _ (left_rel {x : normalizer H | ↑x ∈ H}) _ _ (by exact hxy)))) a.2, inv_fun := λ x, ⟨@quotient.lift_on _ _ (left_rel {x : normalizer H | ↑x ∈ H}) x (λ x, show (↥(fixed_points (mul_left_cosets H H)) : Type u), from ⟨⟦x⟧, mem_fixed_points_mul_left_cosets_iff_mem_normalizer.2 x.2⟩) (λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x⁻¹ * y ∈ H), subtype.eq (quotient.sound hxy)), (@quotient.induction_on _ (left_rel {x : normalizer H | ↑x ∈ H}) _ x (by intro x; cases x with x hx; exact mem_fixed_points_mul_left_cosets_iff_mem_normalizer.2 hx))⟩, left_inv := λ ⟨x, hx⟩, by revert hx; exact quotient.induction_on x (by intros; refl), right_inv := λ x, @quotient.induction_on _ (left_rel {x : normalizer H | ↑x ∈ H}) _ x (by intro x; cases x; refl) } lemma exists_subgroup_card_pow_prime [fintype G] {p : ℕ} : ∀ {n : ℕ} (hp : nat.prime p) (hdvd : p ^ n ∣ card G), ∃ H : set G, is_subgroup H ∧ card H = p ^ n | 0 := λ _ _, ⟨trivial G, by apply_instance, by simp [-set.set_coe_eq_subtype]⟩ | (n+1) := λ hp hdvd, let ⟨H, ⟨hH1, hH2⟩⟩ := exists_subgroup_card_pow_prime hp (dvd.trans (pow_dvd_pow _ (le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in by exactI have hcard : card (left_cosets H) = s * p := (nat.mul_right_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, is_submonoid.one_mem H⟩⟩)).1 (by rwa [← card_eq_card_cosets_mul_card_subgroup, hH2, hs, nat.pow_succ, mul_assoc, mul_comm p]), have hm : s * p % p = card (left_cosets {x : normalizer H | ↑x ∈ H}) % p := card_congr (fixed_points_mul_left_cosets_equiv_cosets H) ▸ hcard ▸ card_modeq_card_fixed_points _ hp hH2, have hm' : p ∣ card (left_cosets {x : normalizer H | ↑x ∈ H}) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := exists_prime_order_of_dvd_card hp hm' in have hxcard : card (gpowers x) = p := by rwa ← order_eq_card_gpowers, let S : set ↥(normalizer H) := set.preimage (@quotient.mk _ (left_rel {x : ↥(normalizer H) | ↑x ∈ H})) (@gpowers (left_cosets {x : ↥(normalizer H) | ↑x ∈ H}) _ x) in have is_subgroup S := @is_group_hom.preimage _ (left_cosets {x : ↥(normalizer H) | ↑x ∈ H}) _ _ _ _ _ _, have fS : fintype S := by apply_instance, let hequiv : {x : ↥(normalizer H) | ↑x ∈ H} ≃ H := { to_fun := λ ⟨x, hx⟩, ⟨x, hx⟩, inv_fun := λ ⟨x, hx⟩, ⟨⟨x, subset_normalizer _ hx⟩, hx⟩, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨_, _⟩, rfl } in ⟨subtype.val '' S, by apply_instance, by dsimp only [S]; rw [set.card_image_of_injective _ subtype.val_injective, nat.pow_succ, @card_congr _ _ fS _ (preimage_quotient_mk_equiv_subgroup_times_set _ _), card_prod, hxcard, ← hH2, card_congr hequiv]⟩ def conjugate_set (x : G) (H : set G) : set G := (λ n, x⁻¹ * n * x) ⁻¹' H lemma conjugate_set_eq_image (H : set G) (x : G) : conjugate_set x H = (λ n, x * n * x⁻¹) '' H := eq.symm (congr_fun (set.image_eq_preimage_of_inverse (λ _, by simp [mul_assoc]) (λ _, by simp [mul_assoc])) _) lemma conjugate_set_eq_preimage (H : set G) (x : G) : conjugate_set x H = (λ n, x⁻¹ * n * x) ⁻¹' H := rfl instance conjugate_set.is_group_action : is_group_action (@conjugate_set G _) := { one := λ H, by simp [conjugate_set_eq_image, set.image], mul := λ x y H, by simp [mul_inv_rev, mul_assoc, comp, conjugate_set_eq_preimage, set.preimage] } @[simp] lemma conjugate_set_normal_subgroup (H : set G) [normal_subgroup H] (x : G) : conjugate_set x H = H := set.ext (λ n, ⟨λ h : _ ∈ H, by have := normal_subgroup.normal _ h x; simpa [mul_assoc] using this, λ h, show _ ∈ H, by have := normal_subgroup.normal _ h (x⁻¹); by simpa using this⟩) instance is_group_action.subgroup (H : set G) [is_subgroup H] (f : G → α → α) [is_group_action f] : is_group_action (λ x : H, f x) := { one := λ a, is_group_action.one f a, mul := λ ⟨x, hx⟩ ⟨y, hy⟩ a, is_group_action.mul f x y a } instance is_group_hom_conj (x : G) : is_group_hom (λ (n : G), x * n * x⁻¹) := ⟨by simp [mul_assoc]⟩ instance is_subgroup_conj (x : G) (H : set G) [is_subgroup H] : is_subgroup (conjugate_set x H) := by rw conjugate_set_eq_image; apply_instance /-- `dlogn p a` gives the maximum value of `n` such that `p ^ n ∣ a` -/ def dlogn (p : ℕ) : ℕ → ℕ | 0 := 0 | (a+1) := if h : p > 1 then have (a + 1) / p < a + 1, from div_lt_self dec_trivial h, if p ∣ (a + 1) then dlogn ((a + 1) / p) + 1 else 0 else 0 lemma dlogn_dvd {p : ℕ} : ∀ a, p > 1 → p ^ dlogn p a ∣ a | 0 := λ _, dvd_zero _ | (a+1) := λ h, have (a + 1) / p < a + 1, from div_lt_self dec_trivial h, begin rw [dlogn, if_pos h], split_ifs with hd, { rw nat.pow_succ, conv { to_rhs, rw ← nat.div_mul_cancel hd }, exact mul_dvd_mul (dlogn_dvd _ h) (dvd_refl _) }, { simp } end lemma not_dvd_of_gt_dlogn {p : ℕ} : ∀ {a m}, a > 0 → p > 1 → m > dlogn p a → ¬p ^ m ∣ a | 0 := λ m h, (lt_irrefl _ h).elim | (a+1) := λ m h hp hm , have (a + 1) / p < a + 1, from div_lt_self dec_trivial hp, begin rw [dlogn, if_pos hp] at hm, split_ifs at hm with hd, { have hmsub : succ (m - 1) = m := succ_sub (show 1 ≤ m, from (lt_of_le_of_lt (nat.zero_le _) hm)) ▸ (succ_sub_one m).symm, have := @not_dvd_of_gt_dlogn ((a + 1) / p) (m - 1) (pos_of_mul_pos_left (by rw nat.mul_div_cancel' hd; exact nat.succ_pos _) (nat.zero_le p)) hp (lt_of_succ_lt_succ (hmsub.symm ▸ hm)), rwa [← nat.mul_dvd_mul_iff_right (lt_trans dec_trivial hp), nat.div_mul_cancel hd, ← nat.pow_succ, hmsub] at this }, { assume h, exact hd (calc p = p ^ 1 : (nat.pow_one _).symm ... ∣ p ^ m : nat.pow_dvd_pow p hm ... ∣ a + 1 : h) } end lemma pow_dvd_of_dvd_mul {p : ℕ} : ∀ {m n k : ℕ} (hp : prime p) (hd : p ^ m ∣ n * k) (hk : ¬p ∣ k), p ^ m ∣ n | 0 := by simp | (m+1) := λ n k hp hd hk, have hpnk : p ∣ n * k := calc p = p ^ 1 : by rw nat.pow_one ... ∣ p ^ (m + 1) : nat.pow_dvd_pow _ (succ_pos _) ... ∣ n * k : by assumption, have hpn : p ∣ n := or.resolve_right (hp.dvd_mul.1 hpnk) hk, have p ^ m ∣ (n / p) * k := dvd_of_mul_dvd_mul_right hp.pos $ by rwa [mul_right_comm, nat.div_mul_cancel hpn, ← nat.pow_succ], by rw [nat.pow_succ, ← nat.div_mul_cancel hpn]; exact mul_dvd_mul_right (pow_dvd_of_dvd_mul hp this hk) _ lemma eq_dlogn_of_dvd_of_succ_not_dvd {a p n : ℕ} (hp : 1 < p) (h₁ : p ^ n ∣ a) (h₂ : ¬p ^ succ n ∣ a) : n = dlogn p a := have ha : 0 < a := nat.pos_of_ne_zero (λ h, by simpa [h] using h₂), le_antisymm (le_of_not_gt $ λ h, not_dvd_of_gt_dlogn ha hp h h₁) (le_of_not_gt $ λ h, h₂ $ calc p ^ succ n ∣ p ^ dlogn p a : nat.pow_dvd_pow _ h ... ∣ _ : dlogn_dvd _ hp) lemma dlogn_eq_of_not_dvd {a b p : ℕ} (hp : prime p) (hpb : ¬p ∣ b) : dlogn p a = dlogn p (a * b) := if ha : a = 0 then by simp [ha, dlogn] else eq_dlogn_of_dvd_of_succ_not_dvd hp.gt_one (dvd.trans (dlogn_dvd _ hp.gt_one) (dvd_mul_right _ _)) (λ h, not_dvd_of_gt_dlogn (nat.pos_of_ne_zero ha) hp.gt_one (lt_succ_self _) (pow_dvd_of_dvd_mul hp h hpb)) lemma not_dvd_div_dlogn {p a : ℕ} (ha : a > 0) (hp : p > 1) : ¬p ∣ a / (p ^ dlogn p a) := by rw [← nat.mul_dvd_mul_iff_left (nat.pos_pow_of_pos (dlogn p a) (lt_trans dec_trivial hp)), nat.mul_div_cancel' (dlogn_dvd _ hp), ← nat.pow_succ]; exact not_dvd_of_gt_dlogn ha hp (lt_succ_self _) class is_sylow [fintype G] (H : set G) {p : ℕ} (hp : prime p) extends is_subgroup H : Prop := (card_eq : card H = p ^ dlogn p (card G)) instance is_subgroup_in_subgroup (H K : set G) [is_subgroup H] [is_subgroup K] : is_subgroup {x : K | (x : G) ∈ H} := { one_mem := show _ ∈ H, from one_mem _, mul_mem := λ x y hx hy, show x.1 * y.1 ∈ H, from mul_mem hx hy, inv_mem := λ x hx, show x.1⁻¹ ∈ H, from inv_mem hx } lemma exists_sylow_subgroup (G : Type u) [group G] [fintype G] {p : ℕ} (hp : prime p) : ∃ H : set G, is_sylow H hp := let ⟨H, ⟨hH₁, hH₂⟩⟩ := exists_subgroup_card_pow_prime hp (dlogn_dvd (card G) hp.gt_one) in by exactI ⟨H, by split; assumption⟩ lemma card_sylow [fintype G] (H : set G) [f : fintype H] {p : ℕ} (hp : prime p) [is_sylow H hp] : card H = p ^ dlogn p (card G) := by rw ← is_sylow.card_eq H hp; congr lemma is_sylow_in_subgroup [fintype G] (H K : set G) {p : ℕ} (hp : prime p) [is_sylow H hp] (hsub : H ⊆ K) [is_subgroup K] : is_sylow {x : K | (x : G) ∈ H} hp := { card_eq := have h₁ : H = subtype.val '' {x : K | (x : G) ∈ H}, from set.ext $ λ x, ⟨λ h, ⟨⟨x, hsub h⟩, ⟨h, rfl⟩⟩, λ ⟨y, hy⟩, hy.2 ▸ hy.1⟩, have h₂ : card K * (card G / card K) = card G := nat.mul_div_cancel' ((card_eq_card_cosets_mul_card_subgroup K).symm ▸ dvd_mul_left _ _), have h₃ : ∀ {f : fintype {x : K | (x : G) ∈ H}}, @fintype.card {x : K | (x : G) ∈ H} f = card H := λ f, by exactI calc @fintype.card {x : K | (x : G) ∈ H} f = card (subtype.val '' {x : K | (x : G) ∈ H}) : by exact (set.card_image_of_injective _ subtype.val_injective).symm ... = card H : set.card_eq_of_eq h₁.symm, calc _ = _ : h₃ ... = p ^ dlogn p (card G) : card_sylow H hp ... = p ^ dlogn p (card K) : congr_arg _ (h₂ ▸ eq.symm begin refine dlogn_eq_of_not_dvd hp (λ h, _), have h₄ := mul_dvd_mul_left (card K) h, rw [h₂, card_eq_card_cosets_mul_card_subgroup {x : K | (x : G) ∈ H}, h₃, card_sylow H hp, mul_assoc, ← nat.pow_succ] at h₄, exact not_dvd_of_gt_dlogn (fintype.card_pos_iff.2 ⟨(1 : G)⟩) hp.gt_one (lt_succ_self _) (dvd_of_mul_left_dvd h₄), end), ..sylow.is_subgroup_in_subgroup H K } lemma sylow_conjugate [fintype G] {p : ℕ} (hp : prime p) (H K : set G) [is_sylow H hp] [is_sylow K hp] : ∃ g : G, H = conjugate_set g K := have hs : card (left_cosets K) = card G / (p ^ dlogn p (card G)) := (nat.mul_right_inj (pos_pow_of_pos (dlogn p (card G)) hp.pos)).1 $ by rw [← card_sylow K hp, ← card_eq_card_cosets_mul_card_subgroup, card_sylow K hp, nat.div_mul_cancel (dlogn_dvd _ hp.gt_one)], have hmodeq : card G / (p ^ dlogn p (card G)) ≡ card (fixed_points (mul_left_cosets K H)) [MOD p] := hs ▸ card_modeq_card_fixed_points (mul_left_cosets K H) hp (card_sylow H hp), have hfixed : 0 < card (fixed_points (mul_left_cosets K H)) := nat.pos_of_ne_zero (λ h, (not_dvd_div_dlogn (fintype.card_pos_iff.2 ⟨(1 : G)⟩) hp.gt_one) $ by rwa [h, nat.modeq.modeq_zero_iff] at hmodeq), let ⟨⟨x, hx⟩⟩ := fintype.card_pos_iff.1 hfixed in begin haveI : is_subgroup K := by apply_instance, revert hx, refine quotient.induction_on x (λ x hx, ⟨x, set.eq_of_card_eq_of_subset _ _⟩), { rw [conjugate_set_eq_image, set.card_image_of_injective _ conj_inj_left, card_sylow K hp, card_sylow H hp] }, { assume y hy, have : (y⁻¹ * x)⁻¹ * x ∈ K := quotient.exact (mem_fixed_points'.1 hx ⟦y⁻¹ * x⟧ ⟨⟨y⁻¹, inv_mem hy⟩, rfl⟩), simp [conjugate_set_eq_preimage, set.preimage, mul_inv_rev, *, mul_assoc] at * } end def conj_on_sylow [fintype G] {p : ℕ} (hp : nat.prime p) : Π (x : G) (H : {H : set G // is_sylow H hp}), {H : set G // is_sylow H hp} := λ x ⟨H, hH⟩, ⟨conjugate_set x H, by exactI have h : is_subgroup (conjugate_set x H) := @sylow.is_subgroup_conj _ _ _ _ _, { card_eq := by exactI by rw [← card_sylow H hp, conjugate_set_eq_image, set.card_image_of_injective _ conj_inj_left], ..h }⟩ instance conj_on_sylow.is_group_action [fintype G] {p : ℕ} (hp : prime p) : is_group_action (@conj_on_sylow G _ _ _ hp) := { one := λ ⟨H, hH⟩, by simp [conj_on_sylow, conjugate_set_eq_preimage, set.preimage], mul := λ x y ⟨H, hH⟩, by simp! [mul_inv_rev, mul_assoc, comp, conjugate_set_eq_image, (set.image_comp _ _ _).symm, conj_on_sylow] } lemma card_sylow_dvd [fintype G] {p : ℕ} (hp : prime p) : card {H : set G // is_sylow H hp} ∣ card G := let ⟨H, hH⟩ := exists_sylow_subgroup G hp in have h : orbit (conj_on_sylow hp) ⟨H, hH⟩ = set.univ := set.eq_univ_iff_forall.2 (λ S, mem_orbit_iff.2 $ let ⟨x, (hx : S.val = _)⟩ := @sylow_conjugate _ _ _ _ hp S.1 H S.2 hH in ⟨x, subtype.eq (hx.symm ▸ rfl)⟩), have is_subgroup (stabilizer (conj_on_sylow hp) ⟨H, hH⟩) := group_action.is_subgroup _ _, by exactI have orbit_equiv : card (orbit (conj_on_sylow hp) ⟨H, hH⟩) = fintype.card (left_cosets (stabilizer (conj_on_sylow hp) ⟨H, hH⟩)) := card_congr (orbit_equiv_left_cosets (conj_on_sylow hp) (⟨H, hH⟩ : {H : set G // is_sylow H hp})), by exactI begin rw [h, ← card_congr (set.equiv_univ _)] at orbit_equiv, rw [orbit_equiv, card_congr (@group_equiv_left_cosets_times_subgroup _ _ (stabilizer (conj_on_sylow hp) ⟨H, hH⟩) (by apply_instance)), card_prod], exact dvd_mul_right _ _ end lemma card_sylow_modeq_one [fintype G] {p : ℕ} (hp : prime p) : card {H : set G // is_sylow H hp} ≡ 1 [MOD p] := let ⟨H, hH⟩ := exists_sylow_subgroup G hp in by exactI eq.trans (card_modeq_card_fixed_points (λ x : H, conj_on_sylow hp (x : G)) hp (card_sylow H hp)) begin refine congr_fun (show (%) _ = (%) 1, from congr_arg _ (fintype.card_eq_one_iff.2 _)) p, refine ⟨(⟨(⟨H, hH⟩ : {H // is_sylow H hp}), λ ⟨x, hx⟩, subtype.eq $ set.ext (λ i, by simp [conj_on_sylow, conjugate_set_eq_preimage, mul_mem_cancel_left _ hx, mul_mem_cancel_right _ (inv_mem hx)])⟩ : subtype (fixed_points (λ (x : ↥H), conj_on_sylow hp ↑x))), _⟩, refine λ L, subtype.eq (subtype.eq _), rcases L with ⟨⟨L, hL₁⟩, hL₂⟩, have Hsub : H ⊆ normalizer L, { assume x hx n, conv {to_rhs, rw ← subtype.mk.inj (hL₂ ⟨x, hx⟩)}, simp [conjugate_set, mul_assoc] }, suffices : ∀ x, x ∈ {x : normalizer L | (x : G) ∈ L} ↔ x ∈ {x : normalizer L | (x : G) ∈ H}, { exact set.ext (λ x, ⟨λ h, (this ⟨x, subset_normalizer _ h⟩).1 h, λ h, (this ⟨x, Hsub h⟩).2 h⟩) }, assume x, haveI := is_sylow_in_subgroup L (normalizer L) hp (subset_normalizer L), haveI := is_sylow_in_subgroup H (normalizer L) hp Hsub, cases sylow_conjugate hp {x : normalizer L | (x : G) ∈ H} {x | (x : G) ∈ L} with x hx, simp [hx] end end sylow
de51a487f0497dafe867af5bb139e644c35ee3cd
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/set_attr1.lean
c98dd54b5bcf2d8c64da0f4b50097836f4c4e5a6
[ "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
240
lean
open tactic constant f : nat → nat constant foo : ∀ n, f n = n + 1 constant zadd : ∀ n, 0 + n = n definition ex1 (n : nat) : 0 + f n = n + 1 := by do set_basic_attribute `simp `foo ff, set_basic_attribute `simp `zadd ff, simp
86f25736ad98fff57ea940728ef95090ff399097
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/big_operators/default.lean
1453249964cf8ef354641727bc673ca6160fb3f1
[ "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
411
lean
-- Import this file to pull in everything about "big operators". -- When preparing a contribution to mathlib, it is best to minimize the imports you use. import algebra.big_operators.order import algebra.big_operators.intervals import algebra.big_operators.ring import algebra.big_operators.pi import algebra.big_operators.finsupp import algebra.big_operators.nat_antidiagonal import algebra.big_operators.enat
84923de60feab1047ae08cfea186884a1f1d85df
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/mv_polynomial/equiv.lean
ea8e300d883d71136288c857c8af7d7b5efde087
[ "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
12,928
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, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.rename import data.equiv.fin import data.polynomial.algebra_map /-! # Equivalences between polynomial rings This file establishes a number of equivalences between polynomial rings, based on equivalences between the underlying types. ## Notation As in other polynomial files, we typically use the notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ## Tags equivalence, isomorphism, morphism, ring hom, hom -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section equiv variables (R) [comm_semiring R] /-- The ring isomorphism between multivariable polynomials in a single variable and polynomials over the ground ring. -/ @[simps] def punit_alg_equiv : mv_polynomial punit R ≃ₐ[R] polynomial R := { to_fun := eval₂ polynomial.C (λu:punit, polynomial.X), inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star), left_inv := begin let f : polynomial R →+* mv_polynomial punit R := (polynomial.eval₂_ring_hom mv_polynomial.C (X punit.star)), let g : mv_polynomial punit R →+* polynomial R := (eval₂_hom polynomial.C (λu:punit, polynomial.X)), show ∀ p, f.comp g p = p, apply is_id, { assume a, dsimp, rw [eval₂_C, polynomial.eval₂_C] }, { rintros ⟨⟩, dsimp, rw [eval₂_X, polynomial.eval₂_X] } end, right_inv := assume p, polynomial.induction_on p (assume a, by rw [polynomial.eval₂_C, mv_polynomial.eval₂_C]) (assume p q hp hq, by rw [polynomial.eval₂_add, mv_polynomial.eval₂_add, hp, hq]) (assume p n hp, by rw [polynomial.eval₂_mul, polynomial.eval₂_pow, polynomial.eval₂_X, polynomial.eval₂_C, eval₂_mul, eval₂_C, eval₂_pow, eval₂_X]), map_mul' := λ _ _, eval₂_mul _ _, map_add' := λ _ _, eval₂_add _ _, commutes' := λ _, eval₂_C _ _ _} section map variables {R} (σ) /-- If `e : A ≃+* B` is an isomorphism of rings, then so is `map e`. -/ @[simps apply] def map_equiv [comm_semiring S₁] [comm_semiring S₂] (e : S₁ ≃+* S₂) : mv_polynomial σ S₁ ≃+* mv_polynomial σ S₂ := { to_fun := map (e : S₁ →+* S₂), inv_fun := map (e.symm : S₂ →+* S₁), left_inv := λ p, have (e.symm : S₂ →+* S₁).comp ↑e = ring_hom.id _ := ring_hom.ext e.symm_apply_apply, by rw [map_map, this, map_id], right_inv := assume p, have (e : S₁ →+* S₂).comp ↑e.symm = ring_hom.id _ := ring_hom.ext e.apply_symm_apply, by rw [map_map, this, map_id], ..map (e : S₁ →+* S₂) } @[simp] lemma map_equiv_refl : map_equiv σ (ring_equiv.refl R) = ring_equiv.refl _ := ring_equiv.ext map_id @[simp] lemma map_equiv_symm [comm_semiring S₁] [comm_semiring S₂] (e : S₁ ≃+* S₂) : (map_equiv σ e).symm = map_equiv σ e.symm := rfl @[simp] lemma map_equiv_trans [comm_semiring S₁] [comm_semiring S₂] [comm_semiring S₃] (e : S₁ ≃+* S₂) (f : S₂ ≃+* S₃) : (map_equiv σ e).trans (map_equiv σ f) = map_equiv σ (e.trans f) := ring_equiv.ext (map_map e f) variables {A₁ A₂ A₃ : Type*} [comm_semiring A₁] [comm_semiring A₂] [comm_semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] /-- If `e : A ≃ₐ[R] B` is an isomorphism of `R`-algebras, then so is `map e`. -/ def map_alg_equiv (e : A₁ ≃ₐ[R] A₂) : mv_polynomial σ A₁ ≃ₐ[R] mv_polynomial σ A₂ := { commutes' := λ r, begin dsimp, have h₁ : algebra_map R (mv_polynomial σ A₁) r = C (algebra_map R A₁ r) := rfl, have h₂ : algebra_map R (mv_polynomial σ A₂) r = C (algebra_map R A₂ r) := rfl, rw [h₁, h₂, map, eval₂_hom_C, ring_hom.comp_apply, ring_equiv.coe_to_ring_hom, alg_equiv.coe_ring_equiv, alg_equiv.commutes], end, ..(map_equiv σ ↑e) } @[simp] lemma map_alg_equiv_apply (e : A₁ ≃ₐ[R] A₂) (x : mv_polynomial σ A₁) : map_alg_equiv σ e x = map ↑e x := rfl @[simp] lemma map_alg_equiv_refl : map_alg_equiv σ (alg_equiv.refl : A₁ ≃ₐ[R] A₁) = alg_equiv.refl := alg_equiv.ext map_id @[simp] lemma map_alg_equiv_symm (e : A₁ ≃ₐ[R] A₂) : (map_alg_equiv σ e).symm = map_alg_equiv σ e.symm := rfl @[simp] lemma map_alg_equiv_trans (e : A₁ ≃ₐ[R] A₂) (f : A₂ ≃ₐ[R] A₃) : (map_alg_equiv σ e).trans (map_alg_equiv σ f) = map_alg_equiv σ (e.trans f) := alg_equiv.ext (map_map e f) end map section variables (S₁ S₂ S₃) /-- The function from multivariable polynomials in a sum of two types, to multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. See `sum_ring_equiv` for the ring isomorphism. -/ def sum_to_iter : mv_polynomial (S₁ ⊕ S₂) R →+* mv_polynomial S₁ (mv_polynomial S₂ R) := eval₂_hom (C.comp C) (λbc, sum.rec_on bc X (C ∘ X)) @[simp] lemma sum_to_iter_C (a : R) : sum_to_iter R S₁ S₂ (C a) = C (C a) := eval₂_C _ _ a @[simp] lemma sum_to_iter_Xl (b : S₁) : sum_to_iter R S₁ S₂ (X (sum.inl b)) = X b := eval₂_X _ _ (sum.inl b) @[simp] lemma sum_to_iter_Xr (c : S₂) : sum_to_iter R S₁ S₂ (X (sum.inr c)) = C (X c) := eval₂_X _ _ (sum.inr c) /-- The function from multivariable polynomials in one type, with coefficents in multivariable polynomials in another type, to multivariable polynomials in the sum of the two types. See `sum_ring_equiv` for the ring isomorphism. -/ def iter_to_sum : mv_polynomial S₁ (mv_polynomial S₂ R) →+* mv_polynomial (S₁ ⊕ S₂) R := eval₂_hom (eval₂_hom C (X ∘ sum.inr)) (X ∘ sum.inl) lemma iter_to_sum_C_C (a : R) : iter_to_sum R S₁ S₂ (C (C a)) = C a := eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _) lemma iter_to_sum_X (b : S₁) : iter_to_sum R S₁ S₂ (X b) = X (sum.inl b) := eval₂_X _ _ _ lemma iter_to_sum_C_X (c : S₂) : iter_to_sum R S₁ S₂ (C (X c)) = X (sum.inr c) := eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _) variable (σ) /-- The algebra isomorphism between multivariable polynomials in no variables and the ground ring. -/ @[simps] def is_empty_alg_equiv [he : is_empty σ] : mv_polynomial σ R ≃ₐ[R] R := alg_equiv.of_alg_hom (aeval (is_empty.elim he)) (algebra.of_id _ _) (by { ext, simp [algebra.of_id_apply, algebra_map_eq] }) (by { ext i m, exact is_empty.elim' he i }) /-- The ring isomorphism between multivariable polynomials in no variables and the ground ring. -/ @[simps] def is_empty_ring_equiv [he : is_empty σ] : mv_polynomial σ R ≃+* R := (is_empty_alg_equiv R σ).to_ring_equiv variable {σ} /-- A helper function for `sum_ring_equiv`. -/ @[simps] def mv_polynomial_equiv_mv_polynomial [comm_semiring S₃] (f : mv_polynomial S₁ R →+* mv_polynomial S₂ S₃) (g : mv_polynomial S₂ S₃ →+* mv_polynomial S₁ R) (hfgC : ∀a, f (g (C a)) = C a) (hfgX : ∀n, f (g (X n)) = X n) (hgfC : ∀a, g (f (C a)) = C a) (hgfX : ∀n, g (f (X n)) = X n) : mv_polynomial S₁ R ≃+* mv_polynomial S₂ S₃ := { to_fun := f, inv_fun := g, left_inv := is_id (ring_hom.comp _ _) hgfC hgfX, right_inv := is_id (ring_hom.comp _ _) hfgC hfgX, map_mul' := f.map_mul, map_add' := f.map_add } /-- The ring isomorphism between multivariable polynomials in a sum of two types, and multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. -/ def sum_ring_equiv : mv_polynomial (S₁ ⊕ S₂) R ≃+* mv_polynomial S₁ (mv_polynomial S₂ R) := begin apply @mv_polynomial_equiv_mv_polynomial R (S₁ ⊕ S₂) _ _ _ _ (sum_to_iter R S₁ S₂) (iter_to_sum R S₁ S₂), { assume p, convert hom_eq_hom ((sum_to_iter R S₁ S₂).comp ((iter_to_sum R S₁ S₂).comp C)) C _ _ p, { assume a, dsimp, rw [iter_to_sum_C_C R S₁ S₂, sum_to_iter_C R S₁ S₂] }, { assume c, dsimp, rw [iter_to_sum_C_X R S₁ S₂, sum_to_iter_Xr R S₁ S₂] } }, { assume b, rw [iter_to_sum_X R S₁ S₂, sum_to_iter_Xl R S₁ S₂] }, { assume a, rw [sum_to_iter_C R S₁ S₂, iter_to_sum_C_C R S₁ S₂] }, { assume n, cases n with b c, { rw [sum_to_iter_Xl, iter_to_sum_X] }, { rw [sum_to_iter_Xr, iter_to_sum_C_X] } }, end /-- The algebra isomorphism between multivariable polynomials in a sum of two types, and multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. -/ def sum_alg_equiv : mv_polynomial (S₁ ⊕ S₂) R ≃ₐ[R] mv_polynomial S₁ (mv_polynomial S₂ R) := { commutes' := begin intro r, have A : algebra_map R (mv_polynomial S₁ (mv_polynomial S₂ R)) r = (C (C r) : _), by refl, have B : algebra_map R (mv_polynomial (S₁ ⊕ S₂) R) r = C r, by refl, simp only [sum_ring_equiv, sum_to_iter_C, mv_polynomial_equiv_mv_polynomial_apply, ring_equiv.to_fun_eq_coe, A, B], end, ..sum_ring_equiv R S₁ S₂ } section -- this speeds up typeclass search in the lemma below local attribute [instance, priority 2000] is_scalar_tower.right /-- The algebra isomorphism between multivariable polynomials in `option S₁` and polynomials with coefficients in `mv_polynomial S₁ R`. -/ def option_equiv_left : mv_polynomial (option S₁) R ≃ₐ[R] polynomial (mv_polynomial S₁ R) := (rename_equiv R $ (equiv.option_equiv_sum_punit.{0} S₁).trans (equiv.sum_comm _ _)) .trans $ (sum_alg_equiv R _ _).trans $ (punit_alg_equiv (mv_polynomial S₁ R)).restrict_scalars R end /-- The algebra isomorphism between multivariable polynomials in `option S₁` and multivariable polynomials with coefficients in polynomials. -/ def option_equiv_right : mv_polynomial (option S₁) R ≃ₐ[R] mv_polynomial S₁ (polynomial R) := (rename_equiv R $ equiv.option_equiv_sum_punit.{0} S₁).trans $ (sum_alg_equiv R S₁ unit).trans $ map_alg_equiv _ (punit_alg_equiv R) /-- The algebra isomorphism between multivariable polynomials in `fin (n + 1)` and polynomials over multivariable polynomials in `fin n`. -/ def fin_succ_equiv (n : ℕ) : mv_polynomial (fin (n + 1)) R ≃ₐ[R] polynomial (mv_polynomial (fin n) R) := (rename_equiv R (fin_succ_equiv n)).trans (option_equiv_left R (fin n)) lemma fin_succ_equiv_eq (n : ℕ) : (fin_succ_equiv R n : mv_polynomial (fin (n + 1)) R →+* polynomial (mv_polynomial (fin n) R)) = eval₂_hom (polynomial.C.comp (C : R →+* mv_polynomial (fin n) R)) (λ i : fin (n+1), fin.cases polynomial.X (λ k, polynomial.C (X k)) i) := begin apply ring_hom_ext, { intro r, dsimp [ring_equiv.coe_to_ring_hom, fin_succ_equiv, option_equiv_left, sum_alg_equiv, sum_ring_equiv], simp only [sum_to_iter_C, eval₂_C, rename_C, ring_hom.coe_comp] }, { intro i, dsimp [fin_succ_equiv, option_equiv_left, sum_alg_equiv, sum_ring_equiv], refine fin.cases _ (λ _, _) i, { simp only [fin.cases_zero, sum.swap, rename_X, equiv.option_equiv_sum_punit_none, equiv.sum_comm_apply, rename_equiv_apply, comp_app, sum_to_iter_Xl, equiv.coe_trans, fin_succ_equiv_zero, eval₂_X], }, { simp only [equiv.option_equiv_sum_punit_some, sum.swap, fin.cases_succ, rename_X, equiv.sum_comm_apply, sum_to_iter_Xr, comp_app, eval₂_C, equiv.coe_trans, fin_succ_equiv_succ, eval₂_X]} } end @[simp] lemma fin_succ_equiv_apply (n : ℕ) (p : mv_polynomial (fin (n + 1)) R) : fin_succ_equiv R n p = eval₂_hom (polynomial.C.comp (C : R →+* mv_polynomial (fin n) R)) (λ i : fin (n+1), fin.cases polynomial.X (λ k, polynomial.C (X k)) i) p := by { rw ← fin_succ_equiv_eq, refl } lemma fin_succ_equiv_comp_C_eq_C {R : Type u} [comm_semiring R] (n : ℕ) : (↑(mv_polynomial.fin_succ_equiv R n).symm : polynomial (mv_polynomial (fin n) R) →+* _).comp ((polynomial.C).comp (mv_polynomial.C)) = (mv_polynomial.C : R →+* mv_polynomial (fin n.succ) R) := begin refine ring_hom.ext (λ x, _), rw ring_hom.comp_apply, refine (mv_polynomial.fin_succ_equiv R n).injective (trans ((mv_polynomial.fin_succ_equiv R n).apply_symm_apply _) _), simp only [mv_polynomial.fin_succ_equiv_apply, mv_polynomial.eval₂_hom_C], end end end equiv end mv_polynomial
bddcb6a33038e2b9adf1db2beae45865069f0e7e
fe208a542cea7b2d6d7ff79f94d535f6d11d814a
/src/Dedekind_cuts/kenny_lau_effort.lean
8a110f140d282cc2554b5cdc2b2e4bc2fb34ddf2
[]
no_license
ImperialCollegeLondon/M1F_room_342_questions
c4b98b14113fe900a7f388762269305faff73e63
63de9a6ab9c27a433039dd5530bc9b10b1d227f7
refs/heads/master
1,585,807,312,561
1,545,232,972,000
1,545,232,972,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,298
lean
import algebra.archimedean data.set.intervals order.conditionally_complete_lattice namespace set protected def dite (c : Prop) {α : Type*} (pos : c → set α) (neg : ¬c → set α) : set α := { x | (∃ hc, x ∈ pos hc) ∨ (∃ hnc, x ∈ neg hnc) } protected def ite (c : Prop) {α : Type*} (pos neg : set α) : set α := set.dite c (λ _, pos) (λ _, neg) protected theorem dif_pos {c : Prop} (hc : c) {α : Type*} {pos neg} : (set.dite c pos neg : set α) = pos hc := ext $ λ z, ⟨λ hz, or.cases_on hz Exists.snd $ λ ⟨hnc, _⟩, absurd hc hnc, λ hz, or.inl ⟨hc, hz⟩⟩ protected theorem dif_neg {c : Prop} (hnc : ¬c) {α : Type*} {pos neg} : (set.dite c pos neg : set α) = neg hnc := ext $ λ z, ⟨λ hz, or.cases_on hz (λ ⟨hc, _⟩, absurd hc hnc) Exists.snd, λ hz, or.inr ⟨hnc, hz⟩⟩ protected theorem if_pos {c : Prop} (hc : c) {α : Type*} {t e} : (set.ite c t e : set α) = t := set.dif_pos hc protected theorem if_neg {c : Prop} (hnc : ¬c) {α : Type*} {t e} : (set.ite c t e : set α) = e := set.dif_neg hnc end set open set lattice structure real : Type := (carrier : set ℚ) (exists_carrier : ∃ x, x ∈ carrier) (exists_not_carrier : ∃ x, x ∉ carrier) (mem_of_mem_of_le : ∀ q ∈ carrier, ∀ p ≤ q, p ∈ carrier) (exists_lt_of_mem : ∀ q ∈ carrier, ∃ M ∈ carrier, q < M) notation `ℝ` := real namespace real @[extensionality] theorem ext : ∀ {c₁ c₂ : ℝ}, c₁.carrier = c₂.carrier → c₁ = c₂ | ⟨_, _, _, _, _⟩ ⟨_, _, _, _, _⟩ rfl := rfl protected def dite (c : Prop) (pos : c → ℝ) (neg : ¬c → ℝ) : ℝ := { carrier := set.dite c (λ hc, (pos hc).1) (λ hnc, (neg hnc).1), exists_carrier := classical.by_cases (λ hc : c, by rw set.dif_pos hc; exact (pos hc).2) (λ hnc : ¬c, by rw set.dif_neg hnc; exact (neg hnc).2), exists_not_carrier := classical.by_cases (λ hc : c, by rw set.dif_pos hc; exact (pos hc).3) (λ hnc : ¬c, by rw set.dif_neg hnc; exact (neg hnc).3), mem_of_mem_of_le := classical.by_cases (λ hc : c, by rw set.dif_pos hc; exact (pos hc).4) (λ hnc : ¬c, by rw set.dif_neg hnc; exact (neg hnc).4), exists_lt_of_mem := classical.by_cases (λ hc : c, by rw set.dif_pos hc; exact (pos hc).5) (λ hnc : ¬c, by rw set.dif_neg hnc; exact (neg hnc).5) } protected def ite (c : Prop) (pos neg : ℝ) : ℝ := real.dite c (λ _, pos) (λ _, neg) protected theorem dif_pos {c : Prop} (hc : c) {pos neg} : real.dite c pos neg = pos hc := ext $ set.dif_pos hc protected theorem dif_neg {c : Prop} (hnc : ¬c) {pos neg} : real.dite c pos neg = neg hnc := ext $ set.dif_neg hnc protected theorem if_pos {c : Prop} (hc : c) {t e} : real.ite c t e = t := real.dif_pos hc protected theorem if_neg {c : Prop} (hnc : ¬c) {t e} : real.ite c t e = e := real.dif_neg hnc def of_rat (r : ℚ) : ℝ := ⟨Iio r, ⟨r-1, sub_one_lt r⟩, ⟨r, lt_irrefl r⟩, λ q hqr p hpq, lt_of_le_of_lt hpq hqr, λ q hqr, ⟨q/2+r/2, calc q/2+r/2 < r/2+r/2 : add_lt_add_right (div_lt_div_of_lt_of_pos hqr two_pos) _ ... = r : add_halves r, calc q = q/2+q/2 : (add_halves q).symm ... < q/2+r/2 : add_lt_add_left (div_lt_div_of_lt_of_pos hqr two_pos) _⟩⟩ instance : has_mem ℚ ℝ := ⟨λ r c, r ∈ c.carrier⟩ theorem lt_of_mem_of_not_mem (c : ℝ) {p q : ℚ} (H1 : p ∈ c) (H2 : q ∉ c) : p < q := lt_of_not_ge $ mt (c.4 _ H1 _) H2 protected theorem le_total (c₁ c₂ : ℝ) : c₁.1 ⊆ c₂.1 ∨ c₂.1 ⊆ c₁.1 := classical.or_iff_not_imp_left.2 $ λ hc q hq2, let ⟨r, hr1, hr2⟩ := not_subset.1 hc in c₁.4 r hr1 _ $ le_of_lt $ lt_of_mem_of_not_mem c₂ hq2 hr2 protected def max (r₁ r₂ : ℝ) : ℝ := real.ite (r₁.1 ⊆ r₂.1) r₂ r₁ protected def min (r₁ r₂ : ℝ) : ℝ := real.ite (r₁.1 ⊆ r₂.1) r₁ r₂ protected def Sup (S : set ℝ) : ℝ := real.dite ((∃ r, r ∈ S) ∧ (∃ M : ℝ, ∀ r ∈ S, carrier r ⊆ M.1)) (λ hc, { carrier := ⋃ r ∈ S, carrier r, exists_carrier := let ⟨⟨r, hrs⟩, _⟩ := hc, ⟨q, hqr⟩ := r.2 in ⟨q, mem_bUnion hrs hqr⟩, exists_not_carrier := let ⟨_, M, HM⟩ := hc, ⟨q, hqM⟩ := M.3 in ⟨q, mt (λ H, bUnion_subset HM H) hqM⟩, mem_of_mem_of_le := λ q hq p hpq, let ⟨r, hrs, hqr⟩ := mem_bUnion_iff.1 hq in mem_bUnion hrs (r.4 q hqr _ hpq), exists_lt_of_mem := λ q hq, let ⟨r, hrs, hqr⟩ := mem_bUnion_iff.1 hq, ⟨M, HMr, hqM⟩ := r.5 q hqr in ⟨M, mem_bUnion hrs HMr, hqM⟩ }) (λ _, of_rat 0) protected def Inf (S : set ℝ) : ℝ := real.Sup $ { m | ∀ r ∈ S, m.1 ⊆ carrier r } instance conditionally_complete_linear_order : conditionally_complete_linear_order ℝ := { le_total := real.le_total, sup := real.max, le_sup_left := λ r₁ r₂, show r₁.1 ⊆ (real.ite (r₁.1 ⊆ r₂.1) r₂ r₁).1, from classical.by_cases (λ h : r₁.1 ⊆ r₂.1, by rwa real.if_pos h) (λ h, by rw real.if_neg h), le_sup_right := λ r₁ r₂, show r₂.1 ⊆ (real.ite (r₁.1 ⊆ r₂.1) r₂ r₁).1, from classical.by_cases (λ h : r₁.1 ⊆ r₂.1, by rw real.if_pos h) (λ h, by rwa real.if_neg h; exact (real.le_total r₁ r₂).resolve_left h), sup_le := λ r₁ r₂ r hr1 hr2, show (real.ite (r₁.1 ⊆ r₂.1) r₂ r₁).1 ⊆ r.1, from classical.by_cases (λ h : r₁.1 ⊆ r₂.1, by rwa real.if_pos h) (λ h, by rwa real.if_neg h), inf := real.min, inf_le_left := λ r₁ r₂, show (real.ite (r₁.1 ⊆ r₂.1) r₁ r₂).1 ⊆ r₁.1, from classical.by_cases (λ h : r₁.1 ⊆ r₂.1, by rw real.if_pos h) (λ h, by rw real.if_neg h; exact (real.le_total r₁ r₂).resolve_left h), inf_le_right := λ r₁ r₂, show (real.ite (r₁.1 ⊆ r₂.1) r₁ r₂).1 ⊆ r₂.1, from classical.by_cases (λ h : r₁.1 ⊆ r₂.1, by rwa real.if_pos h) (λ h, by rw real.if_neg h), le_inf := λ r r₁ r₂ hr1 hr2, show r.1 ⊆ (real.ite (r₁.1 ⊆ r₂.1) r₁ r₂).1, from classical.by_cases (λ h : r₁.1 ⊆ r₂.1, by rwa real.if_pos h) (λ h, by rwa real.if_neg h), Sup := real.Sup, le_cSup := λ S r hS hrS, show r.1 ⊆ set.dite _ _ _, by rw set.dif_pos; [exact subset_bUnion_of_mem hrS, exact ⟨⟨r, hrS⟩, hS⟩], cSup_le := λ S r HS hr, show set.dite _ _ _ ⊆ r.1, by rw set.dif_pos; [exact bUnion_subset hr, exact ⟨exists_mem_of_ne_empty HS, r, hr⟩], cInf_le := λ S r HS hrS, show set.dite _ _ _ ⊆ _, by rw set.dif_pos; [exact bUnion_subset (λ m hm, hm r hrS), exact ⟨HS, r, λ m hm, hm r hrS⟩], le_cInf := λ S r HS hr, let ⟨s, hs⟩ := exists_mem_of_ne_empty HS in show r.1 ⊆ set.dite _ _ _, by rw set.dif_pos; [exact subset_bUnion_of_mem hr, exact ⟨⟨r, hr⟩, s, λ m hm, hm s hs⟩], Inf := real.Inf, .. partial_order.lift _ $ λ _ _, real.ext} theorem of_rat_lt_iff (q : ℚ) (r : ℝ) : of_rat q < r ↔ q ∈ r := ⟨λ hqr, let ⟨p, hpr, hpq⟩ := not_subset.1 hqr.2 in mem_of_mem_of_le _ p hpr _ (le_of_not_lt hpq), λ hqr, ⟨λ p hpq, mem_of_mem_of_le _ q hqr _ (le_of_lt hpq), λ hrq, lt_irrefl q $ hrq hqr⟩⟩ theorem le_of_rat_iff (q : ℚ) (r : ℝ) : r ≤ of_rat q ↔ q ∉ r := ⟨λ hrq, mt (of_rat_lt_iff _ _).2 (not_lt_of_le hrq), λ hqr, le_of_not_lt $ mt (of_rat_lt_iff _ _).1 hqr⟩ def of_rat_embed : ((≤) : ℚ → ℚ → Prop) ≼o ((≤) : ℝ → ℝ → Prop) := { to_fun := of_rat, inj := λ q₁ q₂ hq, le_antisymm (le_of_not_lt $ λ hq21 : q₂ ∈ of_rat q₁, lt_irrefl q₂ $ by rwa hq at hq21) (le_of_not_lt $ λ hq12 : q₁ ∈ of_rat q₂, lt_irrefl q₁ $ by rwa ← hq at hq12), ord := λ q₁ q₂, ⟨λ hq12, le_of_not_lt $ λ hq21, not_lt_of_le hq12 ((of_rat_lt_iff _ _).1 hq21), λ hq21, le_of_not_lt $ λ hq12, not_lt_of_le hq21 ((of_rat_lt_iff _ _).2 hq12)⟩ } theorem of_rat_le_of_rat (q₁ q₂) : of_rat q₁ ≤ of_rat q₂ ↔ q₁ ≤ q₂ := (@order_embedding.ord _ _ _ _ of_rat_embed q₁ q₂).symm theorem of_rat_lt_of_rat (q₁ q₂) : of_rat q₁ < of_rat q₂ ↔ q₁ < q₂ := of_rat_lt_iff _ _ theorem exists_rat_btwn_add (q : ℚ) (r) (hq : 0 < q) : ∃ m, of_rat m < r ∧ r < of_rat (m + q) := suffices ∀ (q:ℚ) (r:ℝ) (hq:q>0), ∃ m, m ∈ r ∧ m+q ∉ r, from let ⟨m, hmr, hmqr⟩ := this (q/2) r (half_pos hq) in ⟨m, (of_rat_lt_iff _ _).2 hmr, lt_of_le_of_lt ((le_of_rat_iff _ _).2 hmqr) ((of_rat_lt_of_rat _ _).2 (add_lt_add_left (half_lt_self hq) _))⟩, λ q r hq, let ⟨lo, hlo⟩ := r.2, ⟨hi, hhi⟩ := r.3 in have ∀ n : ℕ, ∃ m, m ∈ r ∧ m + (hi - lo) / 2^n ∉ r, from λ n, nat.rec_on n ⟨lo, hlo, by rwa [pow_zero, div_one, add_sub_cancel'_right]⟩ $ λ n ⟨m, hmr, hmnr⟩, classical.by_cases (assume h : m + (hi - lo) / 2 ^ n.succ ∈ r, ⟨_, h, by rwa [add_assoc, pow_succ', ← div_div_eq_div_mul, add_halves]⟩) (λ h, ⟨m, hmr, h⟩), let ⟨n, hn⟩ := pow_unbounded_of_gt_one ((hi - lo) / q) two_gt_one, ⟨m, hmr, hmnr⟩ := this n in ⟨m, hmr, mt (λ hmqr, r.4 _ hmqr (m + (hi-lo)/2^n) $ add_le_add_left (mul_div_cancel' q (ne_of_gt (pow_pos two_pos n)) ▸ div_mul_div_cancel (hi-lo) (ne_of_gt (pow_pos two_pos n)) (ne_of_gt hq) ▸ mul_le_mul_of_nonneg_right (le_of_lt hn) (div_nonneg (le_of_lt hq) (pow_pos two_pos n))) m) hmnr⟩ protected theorem exists_rat_btwn {r₁ r₂ : ℝ} (H : r₁ < r₂) : ∃ q, r₁ < of_rat q ∧ of_rat q < r₂ := let ⟨q, hq2, hq1⟩ := not_subset.1 H.2, ⟨q', hq2', hqq'⟩ := r₂.5 q hq2 in ⟨q', lt_of_le_of_lt ((le_of_rat_iff _ _).2 hq1) ((of_rat_lt_of_rat _ _).2 hqq'), (of_rat_lt_iff _ _).2 hq2'⟩ protected def add (r₁ r₂ : ℝ) : ℝ := { carrier := (λ p:ℚ×ℚ, p.1+p.2) '' r₁.1.prod r₂.1, exists_carrier := let ⟨q₁, hq₁⟩ := r₁.2, ⟨q₂, hq₂⟩ := r₂.2 in ⟨q₁+q₂, @mem_image_of_mem _ _ (λ p:ℚ×ℚ, p.1+p.2) (q₁, q₂) (r₁.1.prod r₂.1) ⟨hq₁, hq₂⟩⟩, exists_not_carrier := let ⟨q₁, hq₁⟩ := r₁.3, ⟨q₂, hq₂⟩ := r₂.3 in ⟨q₁+q₂, λ ⟨⟨p₁,p₂⟩,⟨⟨hp₁,hp₂⟩,hp⟩⟩, absurd hp $ ne_of_lt $ add_lt_add (lt_of_mem_of_not_mem r₁ hp₁ hq₁) (lt_of_mem_of_not_mem r₂ hp₂ hq₂)⟩, mem_of_mem_of_le := λ q ⟨⟨p₁,p₂⟩,⟨⟨hp₁,hp₂⟩,hp⟩⟩ p hpq, ⟨(p₁,p₂-(q-p)), ⟨hp₁, r₂.4 p₂ hp₂ _ (sub_le_self _ $ sub_nonneg_of_le hpq)⟩, by simp only [add_sub, (show p₁ + p₂ = q, from hp), sub_sub_cancel]⟩, exists_lt_of_mem := λ q ⟨⟨p₁,p₂⟩,⟨⟨hp₁,hp₂⟩,hp⟩⟩, let ⟨M₁,HM₁,hpM₁⟩ := r₁.5 p₁ hp₁, ⟨M₂,HM₂,hpM₂⟩ := r₂.5 p₂ hp₂ in ⟨M₁+M₂, @mem_image_of_mem _ _ (λ p:ℚ×ℚ, p.1+p.2) (M₁, M₂) (r₁.1.prod r₂.1) ⟨HM₁, HM₂⟩, hp ▸ add_lt_add hpM₁ hpM₂⟩ } theorem rat_dense {r₁ r₂ : ℝ} (h : ∀ q, of_rat q < r₁ ↔ of_rat q < r₂) : r₁ = r₂ := ext $ set.ext $ λ q, (of_rat_lt_iff _ _).symm.trans $ (h q).trans $ of_rat_lt_iff _ _ theorem of_rat_lt_add_iff (q) (r₁ r₂) : of_rat q < real.add r₁ r₂ ↔ ∃ q₁ ∈ r₁, ∃ q₂ ∈ r₂, q₁ + q₂ = q := (of_rat_lt_iff _ _).trans ⟨λ ⟨⟨x,y⟩,⟨hx,hy⟩,hxy⟩, ⟨x,hx,y,hy,hxy⟩, λ ⟨x,hx,y,hy,hxy⟩, ⟨⟨x,y⟩,⟨hx,hy⟩,hxy⟩⟩ protected def neg (r : ℝ) : ℝ := { carrier := { q | r < of_rat (-q) }, exists_carrier := let ⟨q, hqr⟩ := r.3 in ⟨-(q+1), show r < of_rat (- -(q+1)), from lt_of_not_ge $ mt (by rw _root_.neg_neg; exact λ hq1r, (of_rat_lt_iff _ _).1 (lt_of_lt_of_le ((of_rat_lt_of_rat _ _).2 (lt_add_one q)) hq1r)) hqr⟩, exists_not_carrier := let ⟨q, hqr⟩ := r.2 in ⟨-q, show ¬ r < of_rat (- -q), from (neg_neg q).symm ▸ not_lt_of_lt ((of_rat_lt_iff _ _).2 hqr)⟩, mem_of_mem_of_le := λ q hrq p hpq, lt_of_lt_of_le hrq $ (of_rat_le_of_rat _ _).2 (neg_le_neg hpq), exists_lt_of_mem := λ q hrq, let ⟨x, hrx, hxq⟩ := real.exists_rat_btwn hrq in ⟨-x, show r < of_rat (- -x), from (neg_neg x).symm ▸ hrx, lt_neg_of_lt_neg $ (of_rat_lt_of_rat _ _).1 hxq⟩ } instance : add_comm_group ℝ := { add := real.add, zero := of_rat 0, neg := real.neg, add_assoc := λ _ _ _, ext $ le_antisymm (image_subset_iff.2 $ λ ⟨xy,z⟩ ⟨⟨⟨x,y⟩,⟨hx,hy⟩,hxy⟩,hz⟩, ⟨(x,y+z),⟨hx,⟨(y,z),⟨hy,hz⟩,rfl⟩⟩, by simp only at hxy; exact hxy ▸ (add_assoc _ _ _).symm⟩) (image_subset_iff.2 $ λ ⟨x,yz⟩ ⟨hx,⟨⟨y,z⟩,⟨hy,hz⟩,hyz⟩⟩, ⟨(x+y,z),⟨⟨(x,y),⟨hx,hy⟩,rfl⟩,hz⟩, by simp only at hyz; exact hyz ▸ add_assoc _ _ _⟩), zero_add := λ r, rat_dense $ λ q, (of_rat_lt_add_iff _ _ _).trans ⟨λ ⟨q₁,hq₁,q₂,hq₂,hq⟩, hq ▸ (of_rat_lt_iff _ _).2 (r.4 q₂ hq₂ _ $ add_le_of_nonpos_of_le (le_of_lt hq₁) (le_refl _)), λ hqr, let ⟨M, HMr, hqM⟩ := r.5 q ((of_rat_lt_iff _ _).1 hqr) in ⟨q-M, sub_neg_of_lt hqM, M, HMr, sub_add_cancel _ _⟩⟩, add_zero := λ r, rat_dense $ λ q, (of_rat_lt_add_iff _ _ _).trans ⟨λ ⟨q₁,hq₁,q₂,hq₂,hq⟩, hq ▸ (of_rat_lt_iff _ _).2 (r.4 q₁ hq₁ _ $ add_le_of_le_of_nonpos (le_refl _) (le_of_lt hq₂)), λ hqr, let ⟨M, HMr, hqM⟩ := r.5 q ((of_rat_lt_iff _ _).1 hqr) in ⟨M, HMr, q-M, sub_neg_of_lt hqM, add_sub_cancel'_right _ _⟩⟩, add_left_neg := λ r, rat_dense $ λ q, (of_rat_lt_add_iff _ _ _).trans ⟨λ ⟨q₁,hq₁,q₂,hq₂,hq⟩, hq ▸ (of_rat_lt_iff _ _).2 (show q₁ + q₂ < 0, from add_comm q₂ q₁ ▸ (sub_neg_eq_add q₂ q₁) ▸ sub_neg_of_lt ((of_rat_lt_of_rat _ _).1 $ lt_trans ((of_rat_lt_iff _ _).2 hq₂) hq₁)), λ hq, let ⟨m, hmr, hrmq⟩ := exists_rat_btwn_add (-q) r (neg_pos.2 ((of_rat_lt_of_rat _ _).1 hq)) in ⟨-(m-q), show r < of_rat (- -(m-q)), from (neg_neg (m-q)).symm ▸ hrmq, m, ((of_rat_lt_iff _ _).1 hmr), by rw [neg_sub, sub_add_cancel]⟩⟩, add_comm := λ _ _, ext $ le_antisymm (image_subset_iff.2 $ λ ⟨x,y⟩ ⟨hx,hy⟩, ⟨(y,x), ⟨hy,hx⟩, add_comm y x⟩) (image_subset_iff.2 $ λ ⟨x,y⟩ ⟨hx,hy⟩, ⟨(y,x), ⟨hy,hx⟩, add_comm y x⟩), .. real.conditionally_complete_linear_order } def sign (r : ℝ) : ℝ := real.ite (r < of_rat 0) (of_rat (-1)) (real.ite (of_rat 0 < r) (of_rat 1) (of_rat 0)) protected def abs (r : ℝ) : ℝ := r ⊔ -r end real
2c1318b5d5bfe335f230573e8afd128a55fb647e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monad/default.lean
cb2cbf4da4faafeec6c4519c75a3bf4a0f007b16
[]
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
191
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monad.limits import Mathlib.category_theory.monad.types import Mathlib.PostPort namespace Mathlib
b7a48b0e9d68e83e59723b652d0bdd64e3adaeb8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/opens.lean
588a57d588d3624dd3ae11e21f4892a514e7bce2
[ "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
8,934
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn -/ import topology.bases import topology.homeomorph import topology.continuous_function.basic /-! # Open sets ## Summary We define the subtype of open sets in a topological space. ## Main Definitions - `opens α` is the type of open subsets of a topological space `α`. - `open_nhds_of x` is the type of open subsets of a topological space `α` containing `x : α`. -/ open filter set variables {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] namespace topological_space variable (α) /-- The type of open subsets of a topological space. -/ def opens := {s : set α // is_open s} variable {α} namespace opens instance : has_coe (opens α) (set α) := { coe := subtype.val } lemma val_eq_coe (U : opens α) : U.1 = ↑U := rfl /-- the coercion `opens α → set α` applied to a pair is the same as taking the first component -/ lemma coe_mk {α : Type*} [topological_space α] {U : set α} {hU : is_open U} : ↑(⟨U, hU⟩ : opens α) = U := rfl instance : has_subset (opens α) := { subset := λ U V, (U : set α) ⊆ V } instance : has_mem α (opens α) := { mem := λ a U, a ∈ (U : set α) } @[simp] lemma subset_coe {U V : opens α} : ((U : set α) ⊆ (V : set α)) = (U ⊆ V) := rfl @[simp] lemma mem_coe {x : α} {U : opens α} : (x ∈ (U : set α)) = (x ∈ U) := rfl @[ext] lemma ext {U V : opens α} (h : (U : set α) = V) : U = V := subtype.ext_iff.mpr h @[ext] lemma ext_iff {U V : opens α} : (U : set α) = V ↔ U = V := ⟨opens.ext, congr_arg coe⟩ instance : partial_order (opens α) := subtype.partial_order _ /-- The interior of a set, as an element of `opens`. -/ def interior (s : set α) : opens α := ⟨interior s, is_open_interior⟩ lemma gc : galois_connection (coe : opens α → set α) interior := λ U s, ⟨λ h, interior_maximal h U.property, λ h, le_trans h interior_subset⟩ open order_dual (of_dual to_dual) /-- The galois insertion between sets and opens, but ordered by reverse inclusion. -/ def gi : galois_insertion (to_dual ∘ @interior α _ ∘ of_dual) (to_dual ∘ subtype.val ∘ of_dual) := { choice := λ s hs, ⟨s, interior_eq_iff_open.mp $ le_antisymm interior_subset hs⟩, gc := gc.dual, le_l_u := λ _, interior_subset, choice_eq := λ s hs, le_antisymm interior_subset hs } @[simp] lemma gi_choice_val {s : order_dual (set α)} {hs} : (gi.choice s hs).val = s := rfl instance : complete_lattice (opens α) := complete_lattice.copy (@order_dual.complete_lattice _ (galois_insertion.lift_complete_lattice (@gi α _))) /- le -/ (λ U V, U ⊆ V) rfl /- top -/ ⟨set.univ, is_open_univ⟩ (subtype.ext_iff_val.mpr interior_univ.symm) /- bot -/ ⟨∅, is_open_empty⟩ rfl /- sup -/ (λ U V, ⟨↑U ∪ ↑V, is_open.union U.2 V.2⟩) rfl /- inf -/ (λ U V, ⟨↑U ∩ ↑V, is_open.inter U.2 V.2⟩) begin funext, apply subtype.ext_iff_val.mpr, exact (is_open.inter U.2 V.2).interior_eq.symm, end /- Sup -/ _ rfl /- Inf -/ _ rfl lemma le_def {U V : opens α} : U ≤ V ↔ (U : set α) ≤ (V : set α) := by refl @[simp] lemma mk_inf_mk {U V : set α} {hU : is_open U} {hV : is_open V} : (⟨U, hU⟩ ⊓ ⟨V, hV⟩ : opens α) = ⟨U ⊓ V, is_open.inter hU hV⟩ := rfl @[simp,norm_cast] lemma coe_inf {U V : opens α} : ((U ⊓ V : opens α) : set α) = (U : set α) ⊓ (V : set α) := rfl @[simp] lemma coe_bot : ((⊥ : opens α) : set α) = ∅ := rfl @[simp] lemma coe_top : ((⊤ : opens α) : set α) = set.univ := rfl instance : has_inter (opens α) := ⟨λ U V, U ⊓ V⟩ instance : has_union (opens α) := ⟨λ U V, U ⊔ V⟩ instance : has_emptyc (opens α) := ⟨⊥⟩ instance : inhabited (opens α) := ⟨∅⟩ @[simp] lemma inter_eq (U V : opens α) : U ∩ V = U ⊓ V := rfl @[simp] lemma union_eq (U V : opens α) : U ∪ V = U ⊔ V := rfl @[simp] lemma empty_eq : (∅ : opens α) = ⊥ := rfl @[simp] lemma Sup_s {Us : set (opens α)} : ↑(Sup Us) = ⋃₀ ((coe : _ → set α) '' Us) := by { rw [(@gc α _).l_Sup, set.sUnion_image], refl } lemma supr_def {ι} (s : ι → opens α) : (⨆ i, s i) = ⟨⋃ i, s i, is_open_Union $ λ i, (s i).2⟩ := by { ext, simp only [supr, opens.Sup_s, sUnion_image, bUnion_range], refl } @[simp] lemma supr_mk {ι} (s : ι → set α) (h : Π i, is_open (s i)) : (⨆ i, ⟨s i, h i⟩ : opens α) = ⟨⋃ i, s i, is_open_Union h⟩ := by { rw supr_def, simp } @[simp] lemma supr_s {ι} (s : ι → opens α) : ((⨆ i, s i : opens α) : set α) = ⋃ i, s i := by simp [supr_def] @[simp] theorem mem_supr {ι} {x : α} {s : ι → opens α} : x ∈ supr s ↔ ∃ i, x ∈ s i := by { rw [←mem_coe], simp, } @[simp] lemma mem_Sup {Us : set (opens α)} {x : α} : x ∈ Sup Us ↔ ∃ u ∈ Us, x ∈ u := by simp_rw [Sup_eq_supr, mem_supr] lemma open_embedding_of_le {U V : opens α} (i : U ≤ V) : open_embedding (set.inclusion i) := { inj := set.inclusion_injective i, induced := (@induced_compose _ _ _ _ (set.inclusion i) coe).symm, open_range := begin rw set.range_inclusion i, exact U.property.preimage continuous_subtype_val end, } lemma not_nonempty_iff_eq_bot (U : opens α) : ¬ set.nonempty (U : set α) ↔ U = ⊥ := by rw [← subtype.coe_injective.eq_iff, opens.coe_bot, ← set.not_nonempty_iff_eq_empty] lemma ne_bot_iff_nonempty (U : opens α) : U ≠ ⊥ ↔ set.nonempty (U : set α) := by rw [ne.def, ← opens.not_nonempty_iff_eq_bot, not_not] /-- A set of `opens α` is a basis if the set of corresponding sets is a topological basis. -/ def is_basis (B : set (opens α)) : Prop := is_topological_basis ((coe : _ → set α) '' B) lemma is_basis_iff_nbhd {B : set (opens α)} : is_basis B ↔ ∀ {U : opens α} {x}, x ∈ U → ∃ U' ∈ B, x ∈ U' ∧ U' ⊆ U := begin split; intro h, { rintros ⟨sU, hU⟩ x hx, rcases h.mem_nhds_iff.mp (is_open.mem_nhds hU hx) with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩, refine ⟨V, H₁, _⟩, cases V, dsimp at H₂, subst H₂, exact hsV }, { refine is_topological_basis_of_open_of_nhds _ _, { rintros sU ⟨U, ⟨H₁, H₂⟩⟩, subst H₂, exact U.property }, { intros x sU hx hsU, rcases @h (⟨sU, hsU⟩ : opens α) x hx with ⟨V, hV, H⟩, exact ⟨V, ⟨V, hV, rfl⟩, H⟩ } } end lemma is_basis_iff_cover {B : set (opens α)} : is_basis B ↔ ∀ U : opens α, ∃ Us ⊆ B, U = Sup Us := begin split, { intros hB U, refine ⟨{V : opens α | V ∈ B ∧ V ⊆ U}, λ U hU, hU.left, _⟩, apply ext, rw [Sup_s, hB.open_eq_sUnion' U.prop], simp_rw [sUnion_image, sUnion_eq_bUnion, Union, supr_and, supr_image], refl }, { intro h, rw is_basis_iff_nbhd, intros U x hx, rcases h U with ⟨Us, hUs, rfl⟩, rcases mem_Sup.1 hx with ⟨U, Us, xU⟩, exact ⟨U, hUs Us, xU, le_Sup Us⟩ } end /-- The preimage of an open set, as an open set. -/ def comap (f : C(α, β)) : opens β →o opens α := { to_fun := λ V, ⟨f ⁻¹' V, V.2.preimage f.continuous⟩, monotone' := λ V₁ V₂ hle, monotone_preimage hle } @[simp] lemma comap_id : comap (continuous_map.id : C(α, α)) = order_hom.id := by { ext, refl } lemma comap_mono (f : C(α, β)) {V W : opens β} (hVW : V ⊆ W) : comap f V ⊆ comap f W := (comap f).monotone hVW @[simp] lemma coe_comap (f : C(α, β)) (U : opens β) : ↑(comap f U) = f ⁻¹' U := rfl @[simp] lemma comap_val (f : C(α, β)) (U : opens β) : (comap f U).1 = f ⁻¹' U := rfl protected lemma comap_comp (g : C(β, γ)) (f : C(α, β)) : comap (g.comp f) = (comap f).comp (comap g) := rfl protected lemma comap_comap (g : C(β, γ)) (f : C(α, β)) (U : opens γ) : comap f (comap g U) = comap (g.comp f) U := rfl /-- A homeomorphism induces an equivalence on open sets, by taking comaps. -/ @[simp] protected def equiv (f : α ≃ₜ β) : opens α ≃ opens β := { to_fun := opens.comap f.symm.to_continuous_map, inv_fun := opens.comap f.to_continuous_map, left_inv := by { intro U, ext1, exact f.to_equiv.preimage_symm_preimage _ }, right_inv := by { intro U, ext1, exact f.to_equiv.symm_preimage_preimage _ } } /-- A homeomorphism induces an order isomorphism on open sets, by taking comaps. -/ @[simp] protected def order_iso (f : α ≃ₜ β) : opens α ≃o opens β := { to_equiv := opens.equiv f, map_rel_iff' := λ U V, f.symm.surjective.preimage_subset_preimage_iff } end opens /-- The open neighborhoods of a point. See also `opens` or `nhds`. -/ def open_nhds_of (x : α) : Type* := { s : set α // is_open s ∧ x ∈ s } instance open_nhds_of.inhabited {α : Type*} [topological_space α] (x : α) : inhabited (open_nhds_of x) := ⟨⟨set.univ, is_open_univ, set.mem_univ _⟩⟩ end topological_space
5abe12cae26680b7840b0dcba1953faeb1243534
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/linear_algebra/dimension.lean
ba58cb8edad738d5a82c21f2a5345f164006c5f7
[ "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
16,743
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Johannes Hölzl, Sander Dahmen -/ import linear_algebra.basis import set_theory.ordinal /-! # Dimension of modules and vector spaces ## Main definitions * The dimension of a vector space is defined as `vector_space.dim : cardinal`. ## Main statements * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. * `dim_quotient_add_dim`: if V' is a submodule of V, then dim (V/V') + dim V' = dim V. * `dim_range_add_dim_ker`: the rank-nullity theorem. -/ noncomputable theory universes u u' u'' v v' w w' variables {K : Type u} {V V₂ V₃ V₄ : Type v} variables {ι : Type w} {ι' : Type w'} {η : Type u''} {φ : η → Type u'} -- TODO: relax these universe constraints open_locale classical section vector_space variables [field K] [add_comm_group V] [vector_space K V] include K open submodule function set variables (K V) /-- the dimension of a vector space, defined as a term of type `cardinal` -/ def vector_space.dim : cardinal := cardinal.min (nonempty_subtype.2 (@exists_is_basis K V _ _ _)) (λ b, cardinal.mk b.1) variables {K V} open vector_space section set_option class.instance_max_depth 50 theorem is_basis.le_span (zero_ne_one : (0 : K) ≠ 1) {v : ι → V} {J : set V} (hv : is_basis K v) (hJ : span K J = ⊤) : cardinal.mk (range v) ≤ cardinal.mk J := begin cases le_or_lt cardinal.omega (cardinal.mk J) with oJ oJ, { have := cardinal.mk_range_eq_of_inj (linear_independent.injective zero_ne_one hv.1), let S : J → set ι := λ j, (is_basis.repr hv j).support.to_set, let S' : J → set V := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span K J ≤ comap hv.repr (finsupp.supported K K (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : hv.repr (v i) ∈ (finsupp.supported K K (⋃ j, S j)) := this trivial, rw [hv.repr_eq_single, finsupp.mem_supported, finsupp.support_single_ne_zero zero_ne_one.symm] at this, rw ← hi, apply mem_Union.2, rcases mem_Union.1 (this (mem_singleton _)) with ⟨j, hj⟩, use j, rw mem_image, use i, exact ⟨hj, rfl⟩ }, refine le_of_not_lt (λ IJ, _), suffices : cardinal.mk (⋃ j, S' j) < cardinal.mk (range v), { exact not_le_of_lt this ⟨set.embedding_of_subset hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, cardinal.omega) _)) _, { exact λ j, le_of_lt (cardinal.lt_omega_iff_finite.2 $ finite_image _ (finset.finite_to_set _)) }, { rwa [cardinal.sum_const, cardinal.mul_eq_max oJ (le_refl _), max_eq_left oJ] } }, { rcases exists_finite_card_le_of_finite_of_linear_independent_of_span (cardinal.lt_omega_iff_finite.1 oJ) hv.1.to_subtype_range _ with ⟨fI, hi⟩, { rwa [← cardinal.nat_cast_le, cardinal.finset_card, finset.coe_to_finset, cardinal.finset_card, finset.coe_to_finset] at hi, }, { rw hJ, apply set.subset_univ } }, end end /-- dimension theorem -/ theorem mk_eq_mk_of_basis {v : ι → V} {v' : ι' → V} (hv : is_basis K v) (hv' : is_basis K v') : cardinal.lift.{w w'} (cardinal.mk ι) = cardinal.lift.{w' w} (cardinal.mk ι') := begin rw ←cardinal.lift_inj.{(max w w') v}, rw [cardinal.lift_lift, cardinal.lift_lift], apply le_antisymm, { convert cardinal.lift_le.{v (max w w')}.2 (hv.le_span zero_ne_one hv'.2), { rw cardinal.lift_max.{w v w'}, apply (cardinal.mk_range_eq_of_inj (hv.injective zero_ne_one)).symm, }, { rw cardinal.lift_max.{w' v w}, apply (cardinal.mk_range_eq_of_inj (hv'.injective zero_ne_one)).symm, }, }, { convert cardinal.lift_le.{v (max w w')}.2 (hv'.le_span zero_ne_one hv.2), { rw cardinal.lift_max.{w' v w}, apply (cardinal.mk_range_eq_of_inj (hv'.injective zero_ne_one)).symm, }, { rw cardinal.lift_max.{w v w'}, apply (cardinal.mk_range_eq_of_inj (hv.injective zero_ne_one)).symm, }, } end theorem is_basis.mk_range_eq_dim {v : ι → V} (h : is_basis K v) : cardinal.mk (range v) = dim K V := begin have := show ∃ v', dim K V = _, from cardinal.min_eq _ _, rcases this with ⟨v', e⟩, rw e, apply cardinal.lift_inj.1, rw cardinal.mk_range_eq_of_inj (h.injective zero_ne_one), convert @mk_eq_mk_of_basis _ _ _ _ _ _ _ _ _ h v'.property end theorem is_basis.mk_eq_dim {v : ι → V} (h : is_basis K v) : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (dim K V) := by rw [←h.mk_range_eq_dim, cardinal.mk_range_eq_of_inj (h.injective zero_ne_one)] variables [add_comm_group V₂] [vector_space K V₂] /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : V ≃ₗ[K] V₂) : dim K V = dim K V₂ := by letI := classical.dec_eq V; letI := classical.dec_eq V₂; exact let ⟨b, hb⟩ := exists_is_basis K V in cardinal.lift_inj.1 $ hb.mk_eq_dim.symm.trans (f.is_basis hb).mk_eq_dim @[simp] lemma dim_bot : dim K (⊥ : submodule K V) = 0 := by letI := classical.dec_eq V; rw [← cardinal.lift_inj, ← (@is_basis_empty_bot pempty K V _ _ _ not_nonempty_pempty).mk_eq_dim, cardinal.mk_pempty] @[simp] lemma dim_top : dim K (⊤ : submodule K V) = dim K V := linear_equiv.dim_eq (linear_equiv.of_top _ rfl) lemma dim_of_field (K : Type*) [field K] : dim K K = 1 := by rw [←cardinal.lift_inj, ← (@is_basis_singleton_one punit K _ _).mk_eq_dim, cardinal.mk_punit] lemma dim_span {v : ι → V} (hv : linear_independent K v) : dim K ↥(span K (range v)) = cardinal.mk (range v) := by rw [←cardinal.lift_inj, ← (is_basis_span hv).mk_eq_dim, cardinal.mk_range_eq_of_inj (@linear_independent.injective ι K V v _ _ _ zero_ne_one hv)] lemma dim_span_set {s : set V} (hs : linear_independent K (λ x, x : s → V)) : dim K ↥(span K s) = cardinal.mk s := by rw [← @set_of_mem_eq _ s, ← subtype.val_range]; exact dim_span hs lemma dim_span_le (s : set V) : dim K (span K s) ≤ cardinal.mk s := begin classical, rcases exists_linear_independent linear_independent_empty (set.empty_subset s) with ⟨b, hb, _, hsb, hlib⟩, have hsab : span K s = span K b, from span_eq_of_le _ hsb (span_le.2 (λ x hx, subset_span (hb hx))), convert cardinal.mk_le_mk_of_subset hb, rw [hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : dim K (span K (↑s : set V)) < cardinal.omega := calc dim K (span K (↑s : set V)) ≤ cardinal.mk (↑s : set V) : dim_span_le ↑s ... = s.card : by rw ←cardinal.finset_card ... < cardinal.omega : cardinal.nat_lt_omega _ theorem dim_prod : dim K (V × V₂) = dim K V + dim K V₂ := begin letI := classical.dec_eq V, letI := classical.dec_eq V₂, rcases exists_is_basis K V with ⟨b, hb⟩, rcases exists_is_basis K V₂ with ⟨c, hc⟩, rw [← cardinal.lift_inj, ← @is_basis.mk_eq_dim K (V × V₂) _ _ _ _ _ (is_basis_inl_union_inr hb hc), cardinal.lift_add, cardinal.lift_mk, ← hb.mk_eq_dim, ← hc.mk_eq_dim, cardinal.lift_mk, cardinal.lift_mk, cardinal.add_def (ulift b) (ulift c)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr (@equiv.ulift b) (@equiv.ulift c)).symm ⟩), end theorem dim_quotient_add_dim (p : submodule K V) : dim K p.quotient + dim K p = dim K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq theorem dim_quotient_le (p : submodule K V) : dim K p.quotient ≤ dim K V := by { rw ← dim_quotient_add_dim p, exact cardinal.le_add_right _ _ } /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₂) : dim K f.range + dim K f.ker = dim K V := begin haveI := λ (p : submodule K V), classical.dec_eq p.quotient, rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_range_le (f : V →ₗ[K] V₂) : dim K f.range ≤ dim K V := by rw ← dim_range_add_dim_ker f; exact le_add_right (le_refl _) lemma dim_map_le (f : V →ₗ V₂) (p : submodule K V) : dim K (p.map f) ≤ dim K p := begin have h := dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_range_of_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K f.range = dim K V₂ := begin refine linear_equiv.dim_eq (linear_equiv.of_bijective (submodule.subtype _) _ _), exact linear_map.ker_eq_bot.2 subtype.val_injective, rwa [range_subtype, linear_map.range_eq_top] end lemma dim_eq_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K V = dim K V₂ + dim K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] lemma dim_le_surjective (f : V →ₗ[K] V₂) (h : surjective f) : dim K V₂ ≤ dim K V := by rw [dim_eq_surjective f h]; refine le_add_right (le_refl _) lemma dim_eq_injective (f : V →ₗ[K] V₂) (h : injective f) : dim K V = dim K f.range := by rw [← dim_range_add_dim_ker f, linear_map.ker_eq_bot.2 h]; simp [dim_bot] lemma dim_submodule_le (s : submodule K V) : dim K s ≤ dim K V := by { rw ← dim_quotient_add_dim s, exact cardinal.le_add_left _ _ } lemma dim_le_injective (f : V →ₗ[K] V₂) (h : injective f) : dim K V ≤ dim K V₂ := by { rw [dim_eq_injective f h], exact dim_submodule_le _ } lemma dim_le_of_submodule (s t : submodule K V) (h : s ≤ t) : dim K s ≤ dim K t := dim_le_injective (of_le h) $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext.1 eq section variables [add_comm_group V₃] [vector_space K V₃] variables [add_comm_group V₄] [vector_space K V₄] set_option class.instance_max_depth 70 open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₃ →ₗ[K] V) (eb : V₄ →ₗ[K] V) (cd : V₂ →ₗ[K] V₃) (ce : V₂ →ₗ[K] V₄) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : dim K V + dim K V₂ = dim K V₃ + dim K V₄ := have hf : surjective (coprod db eb), begin refine (range_eq_top.1 $ top_unique $ _), rwa [← map_top, ← prod_top, map_coprod_prod] end, begin conv {to_rhs, rw [← dim_prod, dim_eq_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, fapply linear_equiv.of_bijective, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, prod_apply, mem_ker, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, prod_apply, mem_ker, mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : dim K (s ⊔ t : submodule K V) + dim K (s ⊓ t : submodule K V) = dim K s + dim K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_refl _ end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, have : b₁ = b₂ := congr_arg subtype.val eq, subst this, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : dim K (s ⊔ t : submodule K V) ≤ dim K s + dim K t := by rw [← dim_sup_add_dim_inf_eq]; exact le_add_right (le_refl _) end section fintype variable [fintype η] variables [∀i, add_comm_group (φ i)] [∀i, vector_space K (φ i)] open linear_map lemma dim_pi : vector_space.dim K (Πi, φ i) = cardinal.sum (λi, vector_space.dim K (φ i)) := begin choose b hb using assume i, exists_is_basis K (φ i), have : is_basis K (λ (ji : Σ j, b j), std_basis K (λ j, φ j) ji.fst ji.snd.val), by apply pi.is_basis_std_basis _ hb, rw [←cardinal.lift_inj, ← this.mk_eq_dim], simp [λ i, (hb i).mk_range_eq_dim.symm, cardinal.sum_mk] end lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [vector_space K V] : vector_space.dim K (η → V) = fintype.card η * vector_space.dim K V := by rw [dim_pi, cardinal.sum_const, cardinal.fintype_card] lemma dim_fun_eq_lift_mul : vector_space.dim K (η → V) = (fintype.card η : cardinal.{max u'' v}) * cardinal.lift.{v u''} (vector_space.dim K V) := by rw [dim_pi, cardinal.sum_const_eq_lift_mul, cardinal.fintype_card, cardinal.lift_nat_cast] lemma dim_fun' : vector_space.dim K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_of_field K, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : dim K (fin n → K) = n := by simp [dim_fun'] end fintype lemma exists_mem_ne_zero_of_ne_bot {s : submodule K V} (h : s ≠ ⊥) : ∃ b : V, b ∈ s ∧ b ≠ 0 := begin classical, by_contradiction hex, have : ∀x∈s, (x:V) = 0, { simpa only [not_exists, not_and, not_not, ne.def] using hex }, exact (h $ bot_unique $ assume s hs, (submodule.mem_bot K).2 $ this s hs) end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : vector_space.dim K s > 0) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [(>), eq, dim_bot] at h; exact lt_irrefl _ h lemma exists_is_basis_fintype (h : dim K V < cardinal.omega) : ∃ s : (set V), (is_basis K (subtype.val : s → V)) ∧ nonempty (fintype s) := begin cases exists_is_basis K V with s hs, rw [←cardinal.lift_lt, ← is_basis.mk_eq_dim hs, cardinal.lift_lt, cardinal.lt_omega_iff_fintype] at h, exact ⟨s, hs, h⟩ end section rank /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V₂) : cardinal := dim K f.range lemma rank_le_domain (f : V →ₗ[K] V₂) : rank f ≤ dim K V := by rw [← dim_range_add_dim_ker f]; exact le_add_right (le_refl _) lemma rank_le_range (f : V →ₗ[K] V₂) : rank f ≤ dim K V₂ := dim_submodule_le _ lemma rank_add_le (f g : V →ₗ[K] V₂) : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ dim K (f.range ⊔ g.range : submodule K V₂) : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V₂), from mem_sup.2 ⟨_, mem_image_of_mem _ (mem_univ _), _, mem_image_of_mem _ (mem_univ _), rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ @[simp] lemma rank_zero : rank (0 : V →ₗ[K] V₂) = 0 := by rw [rank, linear_map.range_zero, dim_bot] lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V₂) : rank (s.sum f) ≤ s.sum (λ d, rank (f d)) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left' h)) variables [add_comm_group V₃] [vector_space K V₃] lemma rank_comp_le1 (g : V →ₗ[K] V₂) (f : V₂ →ₗ[K] V₃) : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact image_subset _ (subset_univ _) end lemma rank_comp_le2 (g : V →ₗ[K] V₂) (f : V₂ →ₗ V₃) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end rank end vector_space section unconstrained_universes variables {E : Type v'} variables [field K] [add_comm_group V] [vector_space K V] [add_comm_group E] [vector_space K E] open vector_space /-- Version of linear_equiv.dim_eq without universe constraints. -/ theorem linear_equiv.dim_eq_lift (f : V ≃ₗ[K] E) : cardinal.lift.{v v'} (dim K V) = cardinal.lift.{v' v} (dim K E) := begin cases exists_is_basis K V with b hb, rw [← cardinal.lift_inj.1 hb.mk_eq_dim, ← (f.is_basis hb).mk_eq_dim, cardinal.lift_mk], end end unconstrained_universes
57e8137edcbc463495a352c8121dadfce3ef09f8
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/complex/is_R_or_C.lean
688308b1da06e06e0d116eb9e6efec7788953176
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
30,621
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import analysis.normed_space.basic import analysis.complex.basic /-! # `is_R_or_C`: a typeclass for ℝ or ℂ This file defines the typeclass `is_R_or_C` intended to have only two instances: ℝ and ℂ. It is meant for definitions and theorems which hold for both the real and the complex case, and in particular when the real case follows directly from the complex case by setting `re` to `id`, `im` to zero and so on. Its API follows closely that of ℂ. Possible applications include defining inner products and Hilbert spaces for both the real and complex case. One would produce the definitions and proof for an arbitrary field of this typeclass, which basically amounts to doing the complex case, and the two cases then fall out immediately from the two instances of the class. ## Implementation notes The coercion from reals into an `is_R_or_C` field is done by registering `algebra_map ℝ K` as a `has_coe_t`. For this to work, we must proceed carefully to avoid problems involving circular coercions in the case `K=ℝ`; in particular, we cannot use the plain `has_coe` and must set priorities carefully. This problem was already solved for `ℕ`, and we copy the solution detailed in `data/nat/cast`. See also Note [coercion into rings] for more details. In addition, several lemmas need to be set at priority 900 to make sure that they do not override their counterparts in `complex.lean` (which causes linter errors). -/ open_locale big_operators section local notation `𝓚` := algebra_map ℝ _ /-- This typeclass captures properties shared by ℝ and ℂ, with an API that closely matches that of ℂ. -/ class is_R_or_C (K : Type*) extends nondiscrete_normed_field K, normed_algebra ℝ K, complete_space K := (re : K →+ ℝ) (im : K →+ ℝ) (conj : K →+* K) (I : K) -- Meant to be set to 0 for K=ℝ (I_re_ax : re I = 0) (I_mul_I_ax : I = 0 ∨ I * I = -1) (re_add_im_ax : ∀ (z : K), 𝓚 (re z) + 𝓚 (im z) * I = z) (of_real_re_ax : ∀ r : ℝ, re (𝓚 r) = r) (of_real_im_ax : ∀ r : ℝ, im (𝓚 r) = 0) (mul_re_ax : ∀ z w : K, re (z * w) = re z * re w - im z * im w) (mul_im_ax : ∀ z w : K, im (z * w) = re z * im w + im z * re w) (conj_re_ax : ∀ z : K, re (conj z) = re z) (conj_im_ax : ∀ z : K, im (conj z) = -(im z)) (conj_I_ax : conj I = -I) (norm_sq_eq_def_ax : ∀ (z : K), ∥z∥^2 = (re z) * (re z) + (im z) * (im z)) (mul_im_I_ax : ∀ (z : K), (im z) * im I = im z) (inv_def_ax : ∀ (z : K), z⁻¹ = conj z * 𝓚 ((∥z∥^2)⁻¹)) (div_I_ax : ∀ (z : K), z / I = -(z * I)) end namespace is_R_or_C variables {K : Type*} [is_R_or_C K] local postfix `†`:100 := @is_R_or_C.conj K _ /- The priority must be set at 900 to ensure that coercions are tried in the right order. See Note [coercion into rings], or `data/nat/cast.lean` for more details. -/ @[priority 900] noncomputable instance algebra_map_coe : has_coe_t ℝ K := ⟨algebra_map ℝ K⟩ lemma of_real_alg (x : ℝ) : (x : K) = x • (1 : K) := algebra.algebra_map_eq_smul_one x lemma algebra_map_eq_of_real : ⇑(algebra_map ℝ K) = coe := rfl @[simp] lemma re_add_im (z : K) : ((re z) : K) + (im z) * I = z := is_R_or_C.re_add_im_ax z @[simp, norm_cast] lemma of_real_re : ∀ r : ℝ, re (r : K) = r := is_R_or_C.of_real_re_ax @[simp, norm_cast] lemma of_real_im : ∀ r : ℝ, im (r : K) = 0 := is_R_or_C.of_real_im_ax @[simp] lemma mul_re : ∀ z w : K, re (z * w) = re z * re w - im z * im w := is_R_or_C.mul_re_ax @[simp] lemma mul_im : ∀ z w : K, im (z * w) = re z * im w + im z * re w := is_R_or_C.mul_im_ax theorem inv_def (z : K) : z⁻¹ = conj z * ((∥z∥^2)⁻¹:ℝ) := is_R_or_C.inv_def_ax z theorem ext_iff : ∀ {z w : K}, z = w ↔ re z = re w ∧ im z = im w := λ z w, { mp := by { rintro rfl, cc }, mpr := by { rintro ⟨h₁,h₂⟩, rw [←re_add_im z, ←re_add_im w, h₁, h₂] } } theorem ext : ∀ {z w : K}, re z = re w → im z = im w → z = w := by { simp_rw ext_iff, cc } @[simp, norm_cast, priority 900] lemma of_real_zero : ((0 : ℝ) : K) = 0 := by rw [of_real_alg, zero_smul] @[simp] lemma zero_re' : re (0 : K) = (0 : ℝ) := re.map_zero @[simp, norm_cast, priority 900] lemma of_real_one : ((1 : ℝ) : K) = 1 := by rw [of_real_alg, one_smul] @[simp] lemma one_re : re (1 : K) = 1 := by rw [←of_real_one, of_real_re] @[simp] lemma one_im : im (1 : K) = 0 := by rw [←of_real_one, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_inj {z w : ℝ} : (z : K) = (w : K) ↔ z = w := { mp := λ h, by { convert congr_arg re h; simp only [of_real_re] }, mpr := λ h, by rw h } @[simp] lemma bit0_re (z : K) : re (bit0 z) = bit0 (re z) := by simp [bit0] @[simp] lemma bit1_re (z : K) : re (bit1 z) = bit1 (re z) := by simp only [bit1, add_monoid_hom.map_add, bit0_re, add_right_inj, one_re] @[simp] lemma bit0_im (z : K) : im (bit0 z) = bit0 (im z) := by simp [bit0] @[simp] lemma bit1_im (z : K) : im (bit1 z) = bit0 (im z) := by simp only [bit1, add_right_eq_self, add_monoid_hom.map_add, bit0_im, one_im] @[simp, priority 900] theorem of_real_eq_zero {z : ℝ} : (z : K) = 0 ↔ z = 0 := by rw [←of_real_zero]; exact of_real_inj @[simp, norm_cast, priority 900] lemma of_real_add ⦃r s : ℝ⦄ : ((r + s : ℝ) : K) = r + s := by { apply (@is_R_or_C.ext_iff K _ ((r + s : ℝ) : K) (r + s)).mpr, simp } @[simp, norm_cast, priority 900] lemma of_real_bit0 (r : ℝ) : ((bit0 r : ℝ) : K) = bit0 (r : K) := ext_iff.2 $ by simp [bit0] @[simp, norm_cast, priority 900] lemma of_real_bit1 (r : ℝ) : ((bit1 r : ℝ) : K) = bit1 (r : K) := ext_iff.2 $ by simp [bit1] /- Note: This can be proven by `norm_num` once K is proven to be of characteristic zero below. -/ lemma two_ne_zero : (2 : K) ≠ 0 := begin intro h, rw [(show (2 : K) = ((2 : ℝ) : K), by norm_num), ←of_real_zero, of_real_inj] at h, linarith, end @[simp, norm_cast, priority 900] lemma of_real_neg (r : ℝ) : ((-r : ℝ) : K) = -r := ext_iff.2 $ by simp @[simp, norm_cast, priority 900] lemma of_real_mul (r s : ℝ) : ((r * s : ℝ) : K) = r * s := ext_iff.2 $ by simp lemma of_real_mul_re (r : ℝ) (z : K) : re (↑r * z) = r * re z := by simp only [mul_re, of_real_im, zero_mul, of_real_re, sub_zero] lemma smul_re (r : ℝ) (z : K) : re (↑r * z) = r * (re z) := by simp only [of_real_im, zero_mul, of_real_re, sub_zero, mul_re] lemma smul_im (r : ℝ) (z : K) : im (↑r * z) = r * (im z) := by simp only [add_zero, of_real_im, zero_mul, of_real_re, mul_im] lemma smul_re' : ∀ (r : ℝ) (z : K), re (r • z) = r * (re z) := λ r z, by { rw algebra.smul_def, apply smul_re } lemma smul_im' : ∀ (r : ℝ) (z : K), im (r • z) = r * (im z) := λ r z, by { rw algebra.smul_def, apply smul_im } /-- The real part in a `is_R_or_C` field, as a linear map. -/ noncomputable def re_lm : K →ₗ[ℝ] ℝ := { map_smul' := smul_re', .. re } @[simp] lemma re_lm_coe : (re_lm : K → ℝ) = re := rfl /-! ### The imaginary unit, `I` -/ /-- The imaginary unit. -/ @[simp] lemma I_re : re (I : K) = 0 := I_re_ax @[simp] lemma I_im (z : K) : im z * im (I : K) = im z := mul_im_I_ax z @[simp] lemma I_im' (z : K) : im (I : K) * im z = im z := by rw [mul_comm, I_im _] lemma I_mul_I : (I : K) = 0 ∨ (I : K) * I = -1 := I_mul_I_ax @[simp] lemma conj_re (z : K) : re (conj z) = re z := is_R_or_C.conj_re_ax z @[simp] lemma conj_im (z : K) : im (conj z) = -(im z) := is_R_or_C.conj_im_ax z @[simp] lemma conj_of_real (r : ℝ) : conj (r : K) = (r : K) := by { rw ext_iff, simp only [of_real_im, conj_im, eq_self_iff_true, conj_re, and_self, neg_zero] } @[simp] lemma conj_bit0 (z : K) : conj (bit0 z) = bit0 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_bit1 (z : K) : conj (bit1 z) = bit1 (conj z) := by simp [bit0, ext_iff] @[simp] lemma conj_neg_I : conj (-I) = (I : K) := by simp [ext_iff] @[simp] lemma conj_conj (z : K) : conj (conj z) = z := by simp [ext_iff] lemma conj_involutive : @function.involutive K is_R_or_C.conj := conj_conj lemma conj_bijective : @function.bijective K K is_R_or_C.conj := conj_involutive.bijective lemma conj_inj (z w : K) : conj z = conj w ↔ z = w := conj_bijective.1.eq_iff lemma conj_eq_zero {z : K} : conj z = 0 ↔ z = 0 := ring_hom.map_eq_zero conj lemma eq_conj_iff_real {z : K} : conj z = z ↔ ∃ r : ℝ, z = (r : K) := begin split, { intro h, suffices : im z = 0, { use (re z), rw ← add_zero (coe _), convert (re_add_im z).symm, simp [this] }, contrapose! h, rw ← re_add_im z, simp only [conj_of_real, ring_hom.map_add, ring_hom.map_mul, conj_I_ax], rw [add_left_cancel_iff, ext_iff], simpa [neg_eq_iff_add_eq_zero, add_self_eq_zero] }, { rintros ⟨r, rfl⟩, apply conj_of_real } end variables (K) /-- Conjugation as a ring equivalence. This is used to convert the inner product into a sesquilinear product. -/ def conj_to_ring_equiv : K ≃+* Kᵒᵖ := { to_fun := opposite.op ∘ conj, inv_fun := conj ∘ opposite.unop, left_inv := λ x, by simp only [conj_conj, function.comp_app, opposite.unop_op], right_inv := λ x, by simp only [conj_conj, opposite.op_unop, function.comp_app], map_mul' := λ x y, by simp [mul_comm], map_add' := λ x y, by simp } variables {K} @[simp] lemma ring_equiv_apply {x : K} : (conj_to_ring_equiv K x).unop = x† := rfl lemma eq_conj_iff_re {z : K} : conj z = z ↔ ((re z) : K) = z := eq_conj_iff_real.trans ⟨by rintro ⟨r, rfl⟩; simp, λ h, ⟨_, h.symm⟩⟩ /-- The norm squared function. -/ def norm_sq : monoid_with_zero_hom K ℝ := { to_fun := λ z, re z * re z + im z * im z, map_zero' := by simp, map_one' := by simp, map_mul' := λ z w, by { simp, ring } } lemma norm_sq_eq_def {z : K} : ∥z∥^2 = (re z) * (re z) + (im z) * (im z) := norm_sq_eq_def_ax z lemma norm_sq_eq_def' (z : K) : norm_sq z = ∥z∥^2 := by { rw norm_sq_eq_def, refl } @[simp] lemma norm_sq_of_real (r : ℝ) : ∥(r : K)∥^2 = r * r := by simp [norm_sq_eq_def] lemma norm_sq_zero : norm_sq (0 : K) = 0 := norm_sq.map_zero lemma norm_sq_one : norm_sq (1 : K) = 1 := norm_sq.map_one lemma norm_sq_nonneg (z : K) : 0 ≤ norm_sq z := add_nonneg (mul_self_nonneg _) (mul_self_nonneg _) @[simp] lemma norm_sq_eq_zero {z : K} : norm_sq z = 0 ↔ z = 0 := by { rw [norm_sq_eq_def'], simp [pow_two] } @[simp] lemma norm_sq_pos {z : K} : 0 < norm_sq z ↔ z ≠ 0 := by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg] @[simp] lemma norm_sq_neg (z : K) : norm_sq (-z) = norm_sq z := by simp [norm_sq_eq_def'] @[simp] lemma norm_sq_conj (z : K) : norm_sq (conj z) = norm_sq z := by simp [norm_sq] @[simp] lemma norm_sq_mul (z w : K) : norm_sq (z * w) = norm_sq z * norm_sq w := norm_sq.map_mul z w lemma norm_sq_add (z w : K) : norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (re (z * conj w)) := by simp [norm_sq, pow_two]; ring lemma re_sq_le_norm_sq (z : K) : re z * re z ≤ norm_sq z := le_add_of_nonneg_right (mul_self_nonneg _) lemma im_sq_le_norm_sq (z : K) : im z * im z ≤ norm_sq z := le_add_of_nonneg_left (mul_self_nonneg _) theorem mul_conj (z : K) : z * conj z = ((norm_sq z) : K) := by simp [ext_iff, norm_sq, mul_comm, sub_eq_neg_add, add_comm] theorem add_conj (z : K) : z + conj z = 2 * (re z) := by simp [ext_iff, two_mul] /-- The pseudo-coercion `of_real` as a `ring_hom`. -/ noncomputable def of_real_hom : ℝ →+* K := algebra_map ℝ K /-- The coercion from reals as a `ring_hom`. -/ noncomputable def coe_hom : ℝ →+* K := ⟨coe, of_real_one, of_real_mul, of_real_zero, of_real_add⟩ @[simp, norm_cast, priority 900] lemma of_real_sub (r s : ℝ) : ((r - s : ℝ) : K) = r - s := ext_iff.2 $ by simp @[simp, norm_cast, priority 900] lemma of_real_pow (r : ℝ) (n : ℕ) : ((r ^ n : ℝ) : K) = r ^ n := by induction n; simp [*, of_real_mul, pow_succ] theorem sub_conj (z : K) : z - conj z = (2 * im z) * I := by simp [ext_iff, two_mul, sub_eq_add_neg, add_mul, mul_im_I_ax] lemma norm_sq_sub (z w : K) : norm_sq (z - w) = norm_sq z + norm_sq w - 2 * re (z * conj w) := by simp [-mul_re, norm_sq_add, add_comm, add_left_comm, sub_eq_add_neg] lemma sqrt_norm_sq_eq_norm {z : K} : real.sqrt (norm_sq z) = ∥z∥ := begin have h₂ : ∥z∥ = real.sqrt (∥z∥^2) := (real.sqrt_sqr (norm_nonneg z)).symm, rw [h₂], exact congr_arg real.sqrt (norm_sq_eq_def' z) end /-! ### Inversion -/ @[simp] lemma inv_re (z : K) : re (z⁻¹) = re z / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp] lemma inv_im (z : K) : im (z⁻¹) = im (-z) / norm_sq z := by simp [inv_def, norm_sq_eq_def, norm_sq, division_def] @[simp, norm_cast, priority 900] lemma of_real_inv (r : ℝ) : ((r⁻¹ : ℝ) : K) = r⁻¹ := begin rw ext_iff, by_cases r = 0, { simp [h] }, { simp; field_simp [h, norm_sq] }, end protected lemma inv_zero : (0⁻¹ : K) = 0 := by rw [← of_real_zero, ← of_real_inv, inv_zero] protected theorem mul_inv_cancel {z : K} (h : z ≠ 0) : z * z⁻¹ = 1 := by rw [inv_def, ←mul_assoc, mul_conj, ←of_real_mul, ←norm_sq_eq_def', mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one] lemma div_re (z w : K) : re (z / w) = re z * re w / norm_sq w + im z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg] lemma div_im (z w : K) : im (z / w) = im z * re w / norm_sq w - re z * im w / norm_sq w := by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm] @[simp, norm_cast, priority 900] lemma of_real_div (r s : ℝ) : ((r / s : ℝ) : K) = r / s := (@is_R_or_C.coe_hom K _).map_div r s lemma div_re_of_real {z : K} {r : ℝ} : re (z / r) = re z / r := begin by_cases h : r = 0, { simp [h, of_real_zero] }, { change r ≠ 0 at h, rw [div_eq_mul_inv, ←of_real_inv, div_eq_mul_inv], simp [norm_sq, div_mul_eq_div_mul_one_div, div_self h] } end @[simp, norm_cast, priority 900] lemma of_real_fpow (r : ℝ) (n : ℤ) : ((r ^ n : ℝ) : K) = r ^ n := (@is_R_or_C.coe_hom K _).map_fpow r n lemma I_mul_I_of_nonzero : (I : K) ≠ 0 → (I : K) * I = -1 := by { have := I_mul_I_ax, tauto } @[simp] lemma div_I (z : K) : z / I = -(z * I) := begin by_cases h : (I : K) = 0, { simp [h] }, { field_simp [h], simp [mul_assoc, I_mul_I_of_nonzero h] } end @[simp] lemma inv_I : (I : K)⁻¹ = -I := by { by_cases h : (I : K) = 0; field_simp [h] } @[simp] lemma norm_sq_inv (z : K) : norm_sq z⁻¹ = (norm_sq z)⁻¹ := (@norm_sq K _).map_inv' z @[simp] lemma norm_sq_div (z w : K) : norm_sq (z / w) = norm_sq z / norm_sq w := (@norm_sq K _).map_div z w lemma norm_conj {z : K} : ∥conj z∥ = ∥z∥ := by simp only [←sqrt_norm_sq_eq_norm, norm_sq_conj] lemma conj_inv {z : K} : conj (z⁻¹) = (conj z)⁻¹ := by simp only [inv_def, norm_conj, ring_hom.map_mul, conj_of_real] lemma conj_div {z w : K} : conj (z / w) = (conj z) / (conj w) := by rw [div_eq_inv_mul, div_eq_inv_mul, ring_hom.map_mul]; simp only [conj_inv] /-! ### Cast lemmas -/ @[simp, norm_cast, priority 900] theorem of_real_nat_cast (n : ℕ) : ((n : ℝ) : K) = n := of_real_hom.map_nat_cast n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : re (n : K) = n := by rw [← of_real_nat_cast, of_real_re] @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : im (n : K) = 0 := by rw [← of_real_nat_cast, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_int_cast (n : ℤ) : ((n : ℝ) : K) = n := of_real_hom.map_int_cast n @[simp, norm_cast] lemma int_cast_re (n : ℤ) : re (n : K) = n := by rw [← of_real_int_cast, of_real_re] @[simp, norm_cast] lemma int_cast_im (n : ℤ) : im (n : K) = 0 := by rw [← of_real_int_cast, of_real_im] @[simp, norm_cast, priority 900] theorem of_real_rat_cast (n : ℚ) : ((n : ℝ) : K) = n := (@is_R_or_C.of_real_hom K _).map_rat_cast n @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : re (q : K) = q := by rw [← of_real_rat_cast, of_real_re] @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : im (q : K) = 0 := by rw [← of_real_rat_cast, of_real_im] /-! ### Characteristic zero -/ -- TODO: I think this can be instance, because it is a `Prop` /-- ℝ and ℂ are both of characteristic zero. Note: This is not registered as an instance to avoid having multiple instances on ℝ and ℂ. -/ lemma char_zero_R_or_C : char_zero K := char_zero_of_inj_zero $ λ n h, by rwa [← of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h theorem re_eq_add_conj (z : K) : ↑(re z) = (z + conj z) / 2 := begin haveI : char_zero K := char_zero_R_or_C, rw [add_conj, mul_div_cancel_left ((re z):K) two_ne_zero'], end /-! ### Absolute value -/ /-- The complex absolute value function, defined as the square root of the norm squared. -/ @[pp_nodot] noncomputable def abs (z : K) : ℝ := (norm_sq z).sqrt local notation `abs'` := _root_.abs local notation `absK` := @abs K _ @[simp, norm_cast] lemma abs_of_real (r : ℝ) : absK r = abs' r := by simp [abs, norm_sq, norm_sq_of_real, real.sqrt_mul_self_eq_abs] lemma norm_eq_abs (z : K) : ∥z∥ = absK z := by simp [abs, norm_sq_eq_def'] lemma abs_of_nonneg {r : ℝ} (h : 0 ≤ r) : absK r = r := (abs_of_real _).trans (abs_of_nonneg h) lemma abs_of_nat (n : ℕ) : absK n = n := by { rw [← of_real_nat_cast], exact abs_of_nonneg (nat.cast_nonneg n) } lemma mul_self_abs (z : K) : abs z * abs z = norm_sq z := real.mul_self_sqrt (norm_sq_nonneg _) @[simp] lemma abs_zero : absK 0 = 0 := by simp [abs] @[simp] lemma abs_one : absK 1 = 1 := by simp [abs] @[simp] lemma abs_two : absK 2 = 2 := calc absK 2 = absK (2 : ℝ) : by rw [of_real_bit0, of_real_one] ... = (2 : ℝ) : abs_of_nonneg (by norm_num) lemma abs_nonneg (z : K) : 0 ≤ absK z := real.sqrt_nonneg _ @[simp] lemma abs_eq_zero {z : K} : absK z = 0 ↔ z = 0 := (real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero lemma abs_ne_zero {z : K} : abs z ≠ 0 ↔ z ≠ 0 := not_congr abs_eq_zero @[simp] lemma abs_conj (z : K) : abs (conj z) = abs z := by simp [abs] @[simp] lemma abs_mul (z w : K) : abs (z * w) = abs z * abs w := by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl lemma abs_re_le_abs (z : K) : abs' (re z) ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (re z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply re_sq_le_norm_sq lemma abs_im_le_abs (z : K) : abs' (im z) ≤ abs z := by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (im z)) (abs_nonneg _), abs_mul_abs_self, mul_self_abs]; apply im_sq_le_norm_sq lemma re_le_abs (z : K) : re z ≤ abs z := (abs_le.1 (abs_re_le_abs _)).2 lemma im_le_abs (z : K) : im z ≤ abs z := (abs_le.1 (abs_im_le_abs _)).2 lemma im_eq_zero_of_le {a : K} (h : abs a ≤ re a) : im a = 0 := begin rw ← zero_eq_mul_self, have : re a * re a = re a * re a + im a * im a, { convert is_R_or_C.mul_self_abs a; linarith [re_le_abs a] }, linarith end lemma re_eq_self_of_le {a : K} (h : abs a ≤ re a) : (re a : K) = a := by { rw ← re_add_im a, simp [im_eq_zero_of_le h] } lemma abs_add (z w : K) : abs (z + w) ≤ abs z + abs w := (mul_self_le_mul_self_iff (abs_nonneg _) (add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $ begin rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs, add_right_comm, norm_sq_add, add_le_add_iff_left, mul_assoc, mul_le_mul_left (@zero_lt_two ℝ _ _)], simpa [-mul_re] using re_le_abs (z * conj w) end instance : is_absolute_value absK := { abv_nonneg := abs_nonneg, abv_eq_zero := λ _, abs_eq_zero, abv_add := abs_add, abv_mul := abs_mul } open is_absolute_value @[simp] lemma abs_abs (z : K) : abs' (abs z) = abs z := _root_.abs_of_nonneg (abs_nonneg _) @[simp] lemma abs_pos {z : K} : 0 < abs z ↔ z ≠ 0 := abv_pos abs @[simp] lemma abs_neg : ∀ z : K, abs (-z) = abs z := abv_neg abs lemma abs_sub : ∀ z w : K, abs (z - w) = abs (w - z) := abv_sub abs lemma abs_sub_le : ∀ a b c : K, abs (a - c) ≤ abs (a - b) + abs (b - c) := abv_sub_le abs @[simp] theorem abs_inv : ∀ z : K, abs z⁻¹ = (abs z)⁻¹ := abv_inv abs @[simp] theorem abs_div : ∀ z w : K, abs (z / w) = abs z / abs w := abv_div abs lemma abs_abs_sub_le_abs_sub : ∀ z w : K, abs' (abs z - abs w) ≤ abs (z - w) := abs_abv_sub_le_abv_sub abs lemma abs_re_div_abs_le_one (z : K) : abs' (re z / abs z) ≤ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] } end lemma abs_im_div_abs_le_one (z : K) : abs' (im z / abs z) ≤ 1 := begin by_cases hz : z = 0, { simp [hz, zero_le_one] }, { simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] } end @[simp, norm_cast] lemma abs_cast_nat (n : ℕ) : abs (n : K) = n := by rw [← of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)] lemma norm_sq_eq_abs (x : K) : norm_sq x = abs x ^ 2 := by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)] lemma re_eq_abs_of_mul_conj (x : K) : re (x * (conj x)) = abs (x * (conj x)) := by rw [mul_conj, of_real_re, abs_of_real, norm_sq_eq_abs, pow_two, _root_.abs_mul, abs_abs] lemma abs_sqr_re_add_conj (x : K) : (abs (x + x†))^2 = (re (x + x†))^2 := by simp [pow_two, ←norm_sq_eq_abs, norm_sq] lemma abs_sqr_re_add_conj' (x : K) : (abs (x† + x))^2 = (re (x† + x))^2 := by simp [pow_two, ←norm_sq_eq_abs, norm_sq] lemma conj_mul_eq_norm_sq_left (x : K) : x† * x = ((norm_sq x) : K) := begin rw ext_iff, refine ⟨by simp [of_real_re, mul_re, conj_re, conj_im, norm_sq],_⟩, simp [of_real_im, mul_im, conj_im, conj_re, mul_comm], end /-- The real part in a `is_R_or_C` field, as a continuous linear map. -/ noncomputable def re_clm : K →L[ℝ] ℝ := re_lm.mk_continuous 1 $ by { simp only [norm_eq_abs, re_lm_coe, one_mul], exact abs_re_le_abs } @[simp] lemma norm_re_clm : ∥(re_clm : K →L[ℝ] ℝ)∥ = 1 := begin apply le_antisymm (linear_map.mk_continuous_norm_le _ zero_le_one _), convert continuous_linear_map.ratio_le_op_norm _ (1 : K), simp, end @[simp, norm_cast] lemma re_clm_coe : ((re_clm : K →L[ℝ] ℝ) : K →ₗ[ℝ] ℝ) = re_lm := rfl @[simp] lemma re_clm_apply : ((re_clm : K →L[ℝ] ℝ) : K → ℝ) = re := rfl /-! ### Cauchy sequences -/ theorem is_cau_seq_re (f : cau_seq K abs) : is_cau_seq abs' (λ n, re (f n)) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij) theorem is_cau_seq_im (f : cau_seq K abs) : is_cau_seq abs' (λ n, im (f n)) := λ ε ε0, (f.cauchy ε0).imp $ λ i H j ij, lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij) /-- The real part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_re (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_re f⟩ /-- The imaginary part of a K Cauchy sequence, as a real Cauchy sequence. -/ noncomputable def cau_seq_im (f : cau_seq K abs) : cau_seq ℝ abs' := ⟨_, is_cau_seq_im f⟩ lemma is_cau_seq_abs {f : ℕ → K} (hf : is_cau_seq abs f) : is_cau_seq abs' (abs ∘ f) := λ ε ε0, let ⟨i, hi⟩ := hf ε ε0 in ⟨i, λ j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)⟩ @[simp, norm_cast, priority 900] lemma of_real_prod {α : Type*} (s : finset α) (f : α → ℝ) : ((∏ i in s, f i : ℝ) : K) = ∏ i in s, (f i : K) := ring_hom.map_prod _ _ _ @[simp, norm_cast, priority 900] lemma of_real_sum {α : Type*} (s : finset α) (f : α → ℝ) : ((∑ i in s, f i : ℝ) : K) = ∑ i in s, (f i : K) := ring_hom.map_sum _ _ _ @[simp, norm_cast] lemma of_real_finsupp_sum {α M : Type*} [has_zero M] (f : α →₀ M) (g : α → M → ℝ) : ((f.sum (λ a b, g a b) : ℝ) : K) = f.sum (λ a b, ((g a b) : K)) := ring_hom.map_finsupp_sum _ f g @[simp, norm_cast] lemma of_real_finsupp_prod {α M : Type*} [has_zero M] (f : α →₀ M) (g : α → M → ℝ) : ((f.prod (λ a b, g a b) : ℝ) : K) = f.prod (λ a b, ((g a b) : K)) := ring_hom.map_finsupp_prod _ f g end is_R_or_C namespace finite_dimensional variables {K : Type*} [is_R_or_C K] open_locale classical open is_R_or_C /-- This instance generates a type-class problem with a metavariable `?m` that should satisfy `is_R_or_C ?m`. Since this can only be satisfied by `ℝ` or `ℂ`, this does not cause problems. -/ library_note "is_R_or_C instance" /-- An `is_R_or_C` field is finite-dimensional over `ℝ`, since it is spanned by `{1, I}`. -/ @[nolint dangerous_instance] instance is_R_or_C_to_real : finite_dimensional ℝ K := finite_dimensional.iff_fg.mpr ⟨{1, I}, begin rw eq_top_iff, intros a _, rw [finset.coe_insert, finset.coe_singleton, submodule.mem_span_insert], refine ⟨re a, (im a) • I, _, _⟩, { rw submodule.mem_span_singleton, use im a }, simp [re_add_im a, algebra.smul_def, algebra_map_eq_of_real] end⟩ /-- Over an `is_R_or_C` field, we can register the properness of finite-dimensional normed spaces as an instance. -/ @[priority 900, nolint dangerous_instance] instance proper_is_R_or_C -- note [is_R_or_C instance] {E : Type*} [normed_group E] [normed_space K E] [finite_dimensional K E] : proper_space E := begin letI : normed_space ℝ E := restrict_scalars.normed_space ℝ K E, letI : is_scalar_tower ℝ K E := restrict_scalars.is_scalar_tower _ _ _, letI : finite_dimensional ℝ E := finite_dimensional.trans ℝ K E, apply_instance end end finite_dimensional section instances noncomputable instance real.is_R_or_C : is_R_or_C ℝ := { re := add_monoid_hom.id ℝ, im := 0, conj := ring_hom.id ℝ, I := 0, I_re_ax := by simp only [add_monoid_hom.map_zero], I_mul_I_ax := or.intro_left _ rfl, re_add_im_ax := λ z, by unfold_coes; simp [add_zero, id.def, mul_zero], of_real_re_ax := λ r, by simp only [add_monoid_hom.id_apply, algebra.id.map_eq_self], of_real_im_ax := λ r, by simp only [add_monoid_hom.zero_apply], mul_re_ax := λ z w, by simp only [sub_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_ax := λ z w, by simp only [add_zero, zero_mul, mul_zero, add_monoid_hom.zero_apply], conj_re_ax := λ z, by simp only [ring_hom.id_apply], conj_im_ax := λ z, by simp only [neg_zero, add_monoid_hom.zero_apply], conj_I_ax := by simp only [ring_hom.map_zero, neg_zero], norm_sq_eq_def_ax := λ z, by simp only [pow_two, norm, ←abs_mul, abs_mul_self z, add_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply], mul_im_I_ax := λ z, by simp only [mul_zero, add_monoid_hom.zero_apply], inv_def_ax := begin intro z, unfold_coes, have H : z ≠ 0 → 1 / z = z / (z * z) := λ h, calc 1 / z = 1 * (1 / z) : (one_mul (1 / z)).symm ... = (z / z) * (1 / z) : congr_arg (λ x, x * (1 / z)) (div_self h).symm ... = z / (z * z) : by field_simp, rcases lt_trichotomy z 0 with hlt|heq|hgt, { field_simp [norm, abs, max_eq_right_of_lt (show z < -z, by linarith), pow_two, mul_inv', ←H (ne_of_lt hlt)] }, { simp [heq] }, { field_simp [norm, abs, max_eq_left_of_lt (show -z < z, by linarith), pow_two, mul_inv', ←H (ne_of_gt hgt)] }, end, div_I_ax := λ z, by simp only [div_zero, mul_zero, neg_zero]} noncomputable instance complex.is_R_or_C : is_R_or_C ℂ := { re := ⟨complex.re, complex.zero_re, complex.add_re⟩, im := ⟨complex.im, complex.zero_im, complex.add_im⟩, conj := complex.conj, I := complex.I, I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re], I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true], re_add_im_ax := λ z, by simp only [add_monoid_hom.coe_mk, complex.re_add_im, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_re_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re, complex.coe_algebra_map, complex.of_real_eq_coe], of_real_im_ax := λ r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im, complex.coe_algebra_map, complex.of_real_eq_coe], mul_re_ax := λ z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk], mul_im_ax := λ z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im], conj_re_ax := λ z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re], conj_im_ax := λ z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk], conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk], norm_sq_eq_def_ax := λ z, by simp only [←complex.norm_sq_eq_abs, ←complex.norm_sq_apply, add_monoid_hom.coe_mk, complex.norm_eq_abs], mul_im_I_ax := λ z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im], inv_def_ax := λ z, by simp only [complex.inv_def, complex.norm_sq_eq_abs, complex.coe_algebra_map, complex.of_real_eq_coe, complex.norm_eq_abs], div_I_ax := complex.div_I } end instances namespace is_R_or_C section cleanup_lemmas local notation `reR` := @is_R_or_C.re ℝ _ local notation `imR` := @is_R_or_C.im ℝ _ local notation `conjR` := @is_R_or_C.conj ℝ _ local notation `IR` := @is_R_or_C.I ℝ _ local notation `absR` := @is_R_or_C.abs ℝ _ local notation `norm_sqR` := @is_R_or_C.norm_sq ℝ _ local notation `reC` := @is_R_or_C.re ℂ _ local notation `imC` := @is_R_or_C.im ℂ _ local notation `conjC` := @is_R_or_C.conj ℂ _ local notation `IC` := @is_R_or_C.I ℂ _ local notation `absC` := @is_R_or_C.abs ℂ _ local notation `norm_sqC` := @is_R_or_C.norm_sq ℂ _ @[simp] lemma re_to_real {x : ℝ} : reR x = x := rfl @[simp] lemma im_to_real {x : ℝ} : imR x = 0 := rfl @[simp] lemma conj_to_real {x : ℝ} : conjR x = x := rfl @[simp] lemma I_to_real : IR = 0 := rfl @[simp] lemma norm_sq_to_real {x : ℝ} : norm_sqR x = x*x := by simp [is_R_or_C.norm_sq] @[simp] lemma abs_to_real {x : ℝ} : absR x = _root_.abs x := by simp [is_R_or_C.abs, abs, real.sqrt_mul_self_eq_abs] @[simp] lemma coe_real_eq_id : @coe ℝ ℝ _ = id := rfl @[simp] lemma re_to_complex {x : ℂ} : reC x = x.re := rfl @[simp] lemma im_to_complex {x : ℂ} : imC x = x.im := rfl @[simp] lemma conj_to_complex {x : ℂ} : conjC x = x.conj := rfl @[simp] lemma I_to_complex : IC = complex.I := rfl @[simp] lemma norm_sq_to_complex {x : ℂ} : norm_sqC x = complex.norm_sq x := by simp [is_R_or_C.norm_sq, complex.norm_sq] @[simp] lemma abs_to_complex {x : ℂ} : absC x = complex.abs x := by simp [is_R_or_C.abs, complex.abs] end cleanup_lemmas end is_R_or_C
d17edae745fd0e828d5f0eb4ce0eb938ac3aa2d5
076f5040b63237c6dd928c6401329ed5adcb0e44
/instructor-notes/2019.10.29.props_and_proofs/2019.10.31.props_and_proofs.lean
9cd4823fe726af24f78ce16cfd65a2a0635f93d4
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
11,779
lean
/- (1) Boo! Happy Halloween! (2) You gotta love the ℕs! (3) Notes from Tue in IN (4) Weather warning. (3) No exam on Tuesday. -/ /- Review: We define day to be a type. -/ inductive day : Type /- Type is the type of *computational* types. Constructors define the values of the type. -/ | mon | tue | wed | thu | fri | sat | sun /- Now we can define variables of this type. -/ open day def d : day := tue /- NEW IDEA: another syntax for defintions Definition now given by a "PROOF SCRIPT" -/ def d' : day := begin exact sat, end /- *************************************** Propositions as Types, Proofs as Values *************************************** -/ /- We define emily's_from_cville to be a new kind of type: a logical type as opposed to a computational type. We understand this *type* to represent a proposition. Now the question, is what does it mean to have a proof of such a proposition? Informally, we might say that we'll take a driver's license, passport, or utility bill as a proof. We can formalize this idea by defining drivers_license, passport, and proof to be *values* of this type! We have a proof of a proposition if we can produce a value of its type! -/ inductive emily's_from_cville : Prop /- Constructors define the values, which we now accept as "proofs" of the proposition Proofs in Lean are values of *logical* types. -/ | drivers_license | passport | utility_bill open emily's_from_cville -- Proofs represented formally as *values* def a_proof : emily's_from_cville := passport theorem a_proof' : emily's_from_cville := utility_bill theorem a_proof'' : emily's_from_cville := begin exact utility_bill, end /- Note the use of def in the first example and theorem in the second. There is no practical difference. We use "theorem" to inform the reader that we intend to produce a proof of a proposition. -/ /- **************************************** Predicates as parameterized propositions **************************************** -/ /- Here's aother data (computational) type. -/ inductive person : Type | mari | jose | jane | bill open person inductive mari_is_from_cville : Prop | yes_she_is #check mari_is_from_cville open mari_is_from_cville theorem mari_proof : mari_is_from_cville := yes_she_is /- We can generalize from a specific proposition, such as *emily* is from charlottesville to one that allows us to assert that any given person is from charlottesville. We do this by adding a parameter. The result is what we call a predicate. We can say that a predicate is a proposition with a parameter. When applied to an argument of the right type, the result is again a proposition. Ex: inductive is_from_cville : person → Prop The constructors of the parameterized type define the set of proofs that can be produced for each of the corresponding propositions. -/ inductive is_from_cville : person → Prop | proof_for : ∀ (p : person), p = mari → is_from_cville p #check is_from_cville #check is_from_cville mari #check is_from_cville jose #check is_from_cville jane #check is_from_cville bill open is_from_cville #check proof_for /- Think of a proof of a "∀" proposition as being like a function. A constructor is a proof. In particular, proof_for can be understood as a proof of the ∀ claim. So we can treat proof_for as a function that takes a person as an argument and that returns a proposition, obtained by applying the predicate on the right of the comma to the given argument. -/ #check proof_for mari #check proof_for jose #check proof_for bill theorem mifc : is_from_cville mari := begin apply proof_for _ _, apply eq.refl mari, end theorem bifc : is_from_cville bill := begin apply proof_for, _ end /- What we're seeing here is what we call the elimination principle for proofs of ∀ propositions. We can treat such a proof as a function and apply it to a particular object of the quantified type to get a proof for the stated proposition *about that particular object*. Here' we get back proofs of proposition such as mari = mari → is_from_cvill mari and bill = mari → is_from_cville bill. Each of these is a proof of an implication, of the form P → Q, which we can also treat as a kind of function: if we can produce a proof of a premise, then we can apply the proof-of-implication/function to it to get a proof of the conclusion. In this case, we will be able to construct and thereby obtain a proof of mari = mari, but there is no proof of bill = mari, so we will be able to construct a proof of the proposition, (is_from_cville mari) but not one of (is_from_cville bill). -/ /- Understand that the constructors of a type are to be understood as the "axioms," or fundamental rules of reasoning, for a given type. They tell us exactly how we can produce values (or proofs) of a given type (or proposition, understood as a type). -/ /- As an example, suppose we to prove the proposition that mari is from cville. Formally we'd state this as the proposition (is_from_cville mari). To prove it, we need to construct a proof. To do that, we have to use the only available "reasoning rule", which is given by the one constructor for this type, namely: proof_for : ∀ (p : person), p = mari → is_from_cville p What this says is that for any person, p, *if* you have a proof that (p = mari) then you can derive a proof of (is_from_cville mari). In plain English, the proof would thus go like this: "To produce a proof of (is_from_cville mari) we first apply the `proof_for' rule to mari to conclude that (mari = mari) → is_from_cville mari. To prove the conclusion, it will suffice to produce a proof of (mari = mari). But this follows from the reflexivity of the equality relation. QED." Now look at what happens if we try to prove jane is from cville. We apply proof_for to jane, yielding the proposition, (jane = mari) → is_from_cville jane. The conclusion is what we want, but to reach it, we have to produce a proof of (jane = mari), and there is no way to do that because jane and mari are different people. So we are stuck, with no way to build the proof we require. -/ /- ****************************************** Predicates define properties and relations ****************************************** -/ /- The is_from_cville predicate defines the "property" of being from Charlottesville. Only mari has this property according to our definitions, because only for mari is there a proof. A predicate of one argument defines proofs for none, some, or all values of its argument type and thereby identifies those with the given property. A predicate of two arguments similarly defines a *relation*: a set of pairs of values that have a given property. The equality relation is a very good example. We accept as an axiom that there is a proof for every proposition of the form, a = a, no matter what type of thing a is, and that there are no other proofs of equalities. (Slight footnote here.) This idea is formalized in Lean with a predicate called that takes two arguments (of any given type -- it's polymorphic), for which there's a proof only if both are the same. Convention infix notation uses the = operator. -/ #check eq 4 4 #check eq 4 5 #check 4 = 5 #check eq "Hi" "Hi" /- Each of these terms is a proposition/type. There are proofs for those that are true! The proofs are constructed by a constructor called refl defined for the eq type. We refer to it as eq.refl. It takes *one* argument, a, and yields a proof/value of type a = a. It's thus impossible to create a proof of a = b unless a and b are really equal to each other! -/ #check (eq.refl 3) #check (eq.refl "Hi") #check (eq.refl mari) /- The term, (proof_for mari (eq.refl mari)), is accepted as a value of type (is_from_cville mari), i.e., as a proof that mari is from charlottesville. Can we construct a proof -/ theorem mari_is_from_cville' : is_from_cville mari := begin apply proof_for mari _, exact (eq.refl mari), _ end -- YAY! theorem mari_is_from_cville'' : is_from_cville mari := begin apply proof_for _ _, -- lean infer first arg! --exact mari, exact (eq.refl mari), end theorem bill_is_from_cville : is_from_cville bill := begin apply proof_for _ _, -- lean infer first arg! --exact mari, exact (eq.refl mari), -- no way end /- End of lecture -/ /- Some comments about function definitions. Consider the following simple definition. -/ def evenb (n : ℕ) : bool := n % 2 = 0 #eval evenb 3 #eval evenb 4 #check evenb def evenb' : ℕ → bool := λ n, n % 2 = 0 def evenb'' : Π (n : ℕ), bool := λ n, n % 2 = 0 #eval evenb'' 5 def evenb''' : ∀ (n : ℕ), bool := λ n, n % 2 = 0 #eval evenb''' 6 /- Predicates are often used to represent properties of objects, here, a property of people, namely the property of a person being from Cville. -/ inductive is_zero : ℕ → Prop | zmk: ∀ (n : ℕ), n = 0 → is_zero n open is_zero theorem zero_is_zero_0 : is_zero 0 := zmk 0 (eq.refl 0) /- Even: inductively defined proofs -/ inductive is_even : ℕ → Prop | pf_zero_is_even : (is_even 0) | pf_even_plus_two_is_even : ∀ (n : ℕ), is_even n → is_even (nat.succ (nat.succ n)) open is_even theorem zero_is_even : is_even 0 := pf_zero_is_even theorem zero_is_even' : is_even 0 := begin exact pf_zero_is_even end /- Inductive -/ theorem two_is_even : is_even 2 := pf_even_plus_two_is_even 0 zero_is_even theorem four_is_even : is_even 4 := pf_even_plus_two_is_even 2 two_is_even theorem ten_is_even : is_even 1000 := begin repeat { apply pf_even_plus_two_is_even }, exact pf_zero_is_even, end #print ten_is_even theorem two_is_even' : is_even 2 := begin apply pf_even_plus_two_is_even 0 zero_is_even, end theorem two_is_even'' : is_even 2 := begin apply pf_even_plus_two_is_even 0 _, exact zero_is_even, end theorem two_is_even''' : is_even 2 := begin apply pf_even_plus_two_is_even _ _, exact zero_is_even, end theorem two_is_even'''' : is_even 2 := begin apply pf_even_plus_two_is_even, exact zero_is_even, end theorem four_is_even' : is_even 4 := pf_even_plus_two_is_even 2 two_is_even theorem four_is_even'' : is_even 4 := begin apply pf_even_plus_two_is_even 2 two_is_even, end theorem four_is_even''' : is_even 4 := begin apply pf_even_plus_two_is_even, apply two_is_even, end theorem four_is_even'''' : is_even 4 := begin apply pf_even_plus_two_is_even, apply pf_even_plus_two_is_even, apply zero_is_even, end theorem ten_is_even' : is_even 10 := begin apply pf_even_plus_two_is_even, apply pf_even_plus_two_is_even, apply pf_even_plus_two_is_even, apply pf_even_plus_two_is_even, apply pf_even_plus_two_is_even, exact zero_is_even, end #print ten_is_even' -- Here's some automation in Lean theorem ten_is_even'' : is_even 10 := begin repeat {apply pf_even_plus_two_is_even}, exact zero_is_even, end inductive successor_of : ℕ → ℕ → Prop | mk : ∀ (n : ℕ), successor_of (nat.succ n) n theorem five_succ_four : successor_of 5 4 := successor_of.mk 4 inductive equal_to_nat : ℕ → ℕ → Prop | refl : ∀ (n : ℕ), equal_to_nat n n theorem five_equals_five : equal_to_nat 5 5 := equal_to_nat.refl 5 theorem five_equals_five' : equal_to_nat 5 5 := begin apply equal_to_nat.refl _, end inductive equal_to_nat' (n : ℕ) : ℕ → Prop | refl : ∀ (n : ℕ), equal_to_nat' n #check equal_to_nat #check equal_to_nat' theorem five_eq_five'' : equal_to_nat' 5 5 := equal_to_nat'.refl 5 5 inductive equal_to {α : Type} : α → α → Prop | refl : ∀ (a : α), equal_to a a
dcb210ee5f70cde4bd6c99f3ed0057cbc28ff14a
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/algebra/subalgebra.lean
fbd699600ce67896248310a3038cf956ed143353
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,558
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.algebra.operations import data.set.Union_lift /-! # Subalgebras over Commutative Semiring In this file we define `subalgebra`s and the usual operations on them (`map`, `comap'`). More lemmas about `adjoin` can be found in `ring_theory.adjoin`. -/ universes u u' v w open_locale tensor_product big_operators set_option old_structure_cmd true /-- A subalgebra is a sub(semi)ring that includes the range of `algebra_map`. -/ structure subalgebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] extends subsemiring A : Type v := (algebra_map_mem' : ∀ r, algebra_map R A r ∈ carrier) (zero_mem' := (algebra_map R A).map_zero ▸ algebra_map_mem' 0) (one_mem' := (algebra_map R A).map_one ▸ algebra_map_mem' 1) /-- Reinterpret a `subalgebra` as a `subsemiring`. -/ add_decl_doc subalgebra.to_subsemiring namespace subalgebra variables {R' : Type u'} {R : Type u} {A : Type v} {B : Type w} {C : Type w} variables [comm_semiring R] variables [semiring A] [algebra R A] [semiring B] [algebra R B] [semiring C] [algebra R C] include R instance : set_like (subalgebra R A) A := ⟨subalgebra.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {s : subalgebra R A} {x : A} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h @[simp] lemma mem_to_subsemiring {S : subalgebra R A} {x} : x ∈ S.to_subsemiring ↔ x ∈ S := iff.rfl @[simp] lemma coe_to_subsemiring (S : subalgebra R A) : (↑S.to_subsemiring : set A) = S := rfl /-- Copy of a subalgebra with a new `carrier` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (S : subalgebra R A) (s : set A) (hs : s = ↑S) : subalgebra R A := { carrier := s, add_mem' := hs.symm ▸ S.add_mem', mul_mem' := hs.symm ▸ S.mul_mem', algebra_map_mem' := hs.symm ▸ S.algebra_map_mem' } @[simp] lemma coe_copy (S : subalgebra R A) (s : set A) (hs : s = ↑S) : (S.copy s hs : set A) = s := rfl lemma copy_eq (S : subalgebra R A) (s : set A) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs variables (S : subalgebra R A) theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S := S.algebra_map_mem' r theorem srange_le : (algebra_map R A).srange ≤ S.to_subsemiring := λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r theorem range_subset : set.range (algebra_map R A) ⊆ S := λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r theorem range_le : set.range (algebra_map R A) ≤ S := S.range_subset theorem one_mem : (1 : A) ∈ S := S.to_subsemiring.one_mem theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S := S.to_subsemiring.mul_mem hx hy theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S := (algebra.smul_def r x).symm ▸ S.mul_mem (S.algebra_map_mem r) hx theorem pow_mem {x : A} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S := S.to_subsemiring.pow_mem hx n theorem zero_mem : (0 : A) ∈ S := S.to_subsemiring.zero_mem theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S := S.to_subsemiring.add_mem hx hy theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S := neg_one_smul R x ▸ S.smul_mem hx _ theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S := by simpa only [sub_eq_add_neg] using S.add_mem hx (S.neg_mem hy) theorem nsmul_mem {x : A} (hx : x ∈ S) (n : ℕ) : n • x ∈ S := S.to_subsemiring.nsmul_mem hx n theorem zsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : ∀ (n : ℤ), n • x ∈ S | (n : ℕ) := by { rw [coe_nat_zsmul], exact S.nsmul_mem hx n } | -[1+ n] := by { rw [zsmul_neg_succ_of_nat], exact S.neg_mem (S.nsmul_mem hx _) } theorem coe_nat_mem (n : ℕ) : (n : A) ∈ S := S.to_subsemiring.coe_nat_mem n theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) (n : ℤ) : (n : A) ∈ S := int.cases_on n (λ i, S.coe_nat_mem i) (λ i, S.neg_mem $ S.coe_nat_mem $ i + 1) theorem list_prod_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.prod ∈ S := S.to_subsemiring.list_prod_mem h theorem list_sum_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.sum ∈ S := S.to_subsemiring.list_sum_mem h theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.prod ∈ S := S.to_subsemiring.multiset_prod_mem m h theorem multiset_sum_mem {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.sum ∈ S := S.to_subsemiring.multiset_sum_mem m h theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) {ι : Type w} {t : finset ι} {f : ι → A} (h : ∀ x ∈ t, f x ∈ S) : ∏ x in t, f x ∈ S := S.to_subsemiring.prod_mem h theorem sum_mem {ι : Type w} {t : finset ι} {f : ι → A} (h : ∀ x ∈ t, f x ∈ S) : ∑ x in t, f x ∈ S := S.to_subsemiring.sum_mem h /-- The projection from a subalgebra of `A` to an additive submonoid of `A`. -/ def to_add_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : add_submonoid A := S.to_subsemiring.to_add_submonoid /-- The projection from a subalgebra of `A` to a submonoid of `A`. -/ def to_submonoid {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : submonoid A := S.to_subsemiring.to_submonoid /-- A subalgebra over a ring is also a `subring`. -/ def to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : subring A := { neg_mem' := λ _, S.neg_mem, .. S.to_subsemiring } @[simp] lemma mem_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {S : subalgebra R A} {x} : x ∈ S.to_subring ↔ x ∈ S := iff.rfl @[simp] lemma coe_to_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : (↑S.to_subring : set A) = S := rfl instance : inhabited S := ⟨(0 : S.to_subsemiring)⟩ section /-! `subalgebra`s inherit structure from their `subsemiring` / `semiring` coercions. -/ instance to_semiring {R A} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : semiring S := S.to_subsemiring.to_semiring instance to_comm_semiring {R A} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) : comm_semiring S := S.to_subsemiring.to_comm_semiring instance to_ring {R A} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : ring S := S.to_subring.to_ring instance to_comm_ring {R A} [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := S.to_subring.to_comm_ring instance to_ordered_semiring {R A} [comm_semiring R] [ordered_semiring A] [algebra R A] (S : subalgebra R A) : ordered_semiring S := S.to_subsemiring.to_ordered_semiring instance to_ordered_comm_semiring {R A} [comm_semiring R] [ordered_comm_semiring A] [algebra R A] (S : subalgebra R A) : ordered_comm_semiring S := S.to_subsemiring.to_ordered_comm_semiring instance to_ordered_ring {R A} [comm_ring R] [ordered_ring A] [algebra R A] (S : subalgebra R A) : ordered_ring S := S.to_subring.to_ordered_ring instance to_ordered_comm_ring {R A} [comm_ring R] [ordered_comm_ring A] [algebra R A] (S : subalgebra R A) : ordered_comm_ring S := S.to_subring.to_ordered_comm_ring instance to_linear_ordered_semiring {R A} [comm_semiring R] [linear_ordered_semiring A] [algebra R A] (S : subalgebra R A) : linear_ordered_semiring S := S.to_subsemiring.to_linear_ordered_semiring /-! There is no `linear_ordered_comm_semiring`. -/ instance to_linear_ordered_ring {R A} [comm_ring R] [linear_ordered_ring A] [algebra R A] (S : subalgebra R A) : linear_ordered_ring S := S.to_subring.to_linear_ordered_ring instance to_linear_ordered_comm_ring {R A} [comm_ring R] [linear_ordered_comm_ring A] [algebra R A] (S : subalgebra R A) : linear_ordered_comm_ring S := S.to_subring.to_linear_ordered_comm_ring end /-- Convert a `subalgebra` to `submodule` -/ def to_submodule : submodule R A := { carrier := S, zero_mem' := (0:S).2, add_mem' := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul_mem' := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } @[simp] lemma mem_to_submodule {x} : x ∈ S.to_submodule ↔ x ∈ S := iff.rfl @[simp] lemma coe_to_submodule (S : subalgebra R A) : (↑S.to_submodule : set A) = S := rfl theorem to_submodule_injective : function.injective (to_submodule : subalgebra R A → submodule R A) := λ S T h, ext $ λ x, by rw [← mem_to_submodule, ← mem_to_submodule, h] theorem to_submodule_inj {S U : subalgebra R A} : S.to_submodule = U.to_submodule ↔ S = U := to_submodule_injective.eq_iff section /-! `subalgebra`s inherit structure from their `submodule` coercions. -/ instance module' [semiring R'] [has_scalar R' R] [module R' A] [is_scalar_tower R' R A] : module R' S := S.to_submodule.module' instance : module R S := S.module' instance [semiring R'] [has_scalar R' R] [module R' A] [is_scalar_tower R' R A] : is_scalar_tower R' R S := S.to_submodule.is_scalar_tower instance algebra' [comm_semiring R'] [has_scalar R' R] [algebra R' A] [is_scalar_tower R' R A] : algebra R' S := { commutes' := λ c x, subtype.eq $ algebra.commutes _ _, smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _, .. (algebra_map R' A).cod_srestrict S.to_subsemiring $ λ x, begin rw [algebra.algebra_map_eq_smul_one, ←smul_one_smul R x (1 : A), ←algebra.algebra_map_eq_smul_one], exact algebra_map_mem S _, end } instance : algebra R S := S.algebra' end instance nontrivial [nontrivial A] : nontrivial S := S.to_subsemiring.nontrivial instance no_zero_smul_divisors_bot [no_zero_smul_divisors R A] : no_zero_smul_divisors R S := ⟨λ c x h, have c = 0 ∨ (x : A) = 0, from eq_zero_or_eq_zero_of_smul_eq_zero (congr_arg coe h), this.imp_right (@subtype.ext_iff _ _ x 0).mpr⟩ @[simp, norm_cast] lemma coe_add (x y : S) : (↑(x + y) : A) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_mul (x y : S) : (↑(x * y) : A) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : S) : A) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : S) : A) = 1 := rfl @[simp, norm_cast] lemma coe_neg {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {S : subalgebra R A} (x : S) : (↑(-x) : A) = -↑x := rfl @[simp, norm_cast] lemma coe_sub {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {S : subalgebra R A} (x y : S) : (↑(x - y) : A) = ↑x - ↑y := rfl @[simp, norm_cast] lemma coe_smul [semiring R'] [has_scalar R' R] [module R' A] [is_scalar_tower R' R A] (r : R') (x : S) : (↑(r • x) : A) = r • ↑x := rfl @[simp, norm_cast] lemma coe_algebra_map [comm_semiring R'] [has_scalar R' R] [algebra R' A] [is_scalar_tower R' R A] (r : R') : ↑(algebra_map R' S r) = algebra_map R' A r := rfl @[simp, norm_cast] lemma coe_pow (x : S) (n : ℕ) : (↑(x^n) : A) = (↑x)^n := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end @[simp, norm_cast] lemma coe_eq_zero {x : S} : (x : A) = 0 ↔ x = 0 := (subtype.ext_iff.symm : (x : A) = (0 : S) ↔ x = 0) @[simp, norm_cast] lemma coe_eq_one {x : S} : (x : A) = 1 ↔ x = 1 := (subtype.ext_iff.symm : (x : A) = (1 : S) ↔ x = 1) -- todo: standardize on the names these morphisms -- compare with submodule.subtype /-- Embedding of a subalgebra into the algebra. -/ def val : S →ₐ[R] A := by refine_struct { to_fun := (coe : S → A) }; intros; refl @[simp] lemma coe_val : (S.val : S → A) = coe := rfl lemma val_apply (x : S) : S.val x = (x : A) := rfl @[simp] lemma to_subsemiring_subtype : S.to_subsemiring.subtype = (S.val : S →+* A) := rfl @[simp] lemma to_subring_subtype {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : S.to_subring.subtype = (S.val : S →+* A) := rfl /-- As submodules, subalgebras are idempotent. -/ @[simp] theorem mul_self : S.to_submodule * S.to_submodule = S.to_submodule := begin apply le_antisymm, { rw submodule.mul_le, intros y hy z hz, exact mul_mem S hy hz }, { intros x hx1, rw ← mul_one x, exact submodule.mul_mem_mul hx1 (one_mem S) } end /-- Linear equivalence between `S : submodule R A` and `S`. Though these types are equal, we define it as a `linear_equiv` to avoid type equalities. -/ def to_submodule_equiv (S : subalgebra R A) : S.to_submodule ≃ₗ[R] S := linear_equiv.of_eq _ _ rfl /-- Transport a subalgebra via an algebra homomorphism. -/ def map (S : subalgebra R A) (f : A →ₐ[R] B) : subalgebra R B := { algebra_map_mem' := λ r, f.commutes r ▸ set.mem_image_of_mem _ (S.algebra_map_mem r), .. S.to_subsemiring.map (f : A →+* B) } lemma map_mono {S₁ S₂ : subalgebra R A} {f : A →ₐ[R] B} : S₁ ≤ S₂ → S₁.map f ≤ S₂.map f := set.image_subset f lemma map_injective {S₁ S₂ : subalgebra R A} (f : A →ₐ[R] B) (hf : function.injective f) (ih : S₁.map f = S₂.map f) : S₁ = S₂ := ext $ set.ext_iff.1 $ set.image_injective.2 hf $ set.ext $ set_like.ext_iff.mp ih @[simp] lemma map_id (S : subalgebra R A) : S.map (alg_hom.id R A) = S := set_like.coe_injective $ set.image_id _ lemma map_map (S : subalgebra R A) (g : B →ₐ[R] C) (f : A →ₐ[R] B) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma mem_map {S : subalgebra R A} {f : A →ₐ[R] B} {y : B} : y ∈ map S f ↔ ∃ x ∈ S, f x = y := subsemiring.mem_map /-- Preimage of a subalgebra under an algebra homomorphism. -/ def comap' (S : subalgebra R B) (f : A →ₐ[R] B) : subalgebra R A := { algebra_map_mem' := λ r, show f (algebra_map R A r) ∈ S, from (f.commutes r).symm ▸ S.algebra_map_mem r, .. S.to_subsemiring.comap (f : A →+* B) } theorem map_le {S : subalgebra R A} {f : A →ₐ[R] B} {U : subalgebra R B} : map S f ≤ U ↔ S ≤ comap' U f := set.image_subset_iff lemma gc_map_comap (f : A →ₐ[R] B) : galois_connection (λ S, map S f) (λ S, comap' S f) := λ S U, map_le @[simp] lemma mem_comap (S : subalgebra R B) (f : A →ₐ[R] B) (x : A) : x ∈ S.comap' f ↔ f x ∈ S := iff.rfl @[simp, norm_cast] lemma coe_comap (S : subalgebra R B) (f : A →ₐ[R] B) : (S.comap' f : set A) = f ⁻¹' (S : set B) := rfl instance no_zero_divisors {R A : Type*} [comm_ring R] [semiring A] [no_zero_divisors A] [algebra R A] (S : subalgebra R A) : no_zero_divisors S := S.to_subsemiring.no_zero_divisors instance is_domain {R A : Type*} [comm_ring R] [ring A] [is_domain A] [algebra R A] (S : subalgebra R A) : is_domain S := subring.is_domain S.to_subring end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) /-- Range of an `alg_hom` as a subalgebra. -/ protected def range (φ : A →ₐ[R] B) : subalgebra R B := { algebra_map_mem' := λ r, ⟨algebra_map R A r, φ.commutes r⟩, .. φ.to_ring_hom.srange } @[simp] lemma mem_range (φ : A →ₐ[R] B) {y : B} : y ∈ φ.range ↔ ∃ x, φ x = y := ring_hom.mem_srange theorem mem_range_self (φ : A →ₐ[R] B) (x : A) : φ x ∈ φ.range := φ.mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (φ : A →ₐ[R] B) : (φ.range : set B) = set.range φ := by { ext, rw [set_like.mem_coe, mem_range], refl } /-- Restrict the codomain of an algebra homomorphism. -/ def cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : A →ₐ[R] S := { commutes' := λ r, subtype.eq $ f.commutes r, .. ring_hom.cod_srestrict (f : A →+* B) S.to_subsemiring hf } @[simp] lemma val_comp_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : S.val.comp (f.cod_restrict S hf) = f := alg_hom.ext $ λ _, rfl @[simp] lemma coe_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) (x : A) : ↑(f.cod_restrict S hf x) = f x := rfl theorem injective_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : function.injective (f.cod_restrict S hf) ↔ function.injective f := ⟨λ H x y hxy, H $ subtype.eq hxy, λ H x y hxy, H (congr_arg subtype.val hxy : _)⟩ /-- Restrict the codomain of a alg_hom `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict (f : A →ₐ[R] B) : A →ₐ[R] f.range := f.cod_restrict f.range f.mem_range_self /-- The equalizer of two R-algebra homomorphisms -/ def equalizer (ϕ ψ : A →ₐ[R] B) : subalgebra R A := { carrier := {a | ϕ a = ψ a}, add_mem' := λ x y hx hy, by { change ϕ x = ψ x at hx, change ϕ y = ψ y at hy, change ϕ (x + y) = ψ (x + y), rw [alg_hom.map_add, alg_hom.map_add, hx, hy] }, mul_mem' := λ x y hx hy, by { change ϕ x = ψ x at hx, change ϕ y = ψ y at hy, change ϕ (x * y) = ψ (x * y), rw [alg_hom.map_mul, alg_hom.map_mul, hx, hy] }, algebra_map_mem' := λ x, by { change ϕ (algebra_map R A x) = ψ (algebra_map R A x), rw [alg_hom.commutes, alg_hom.commutes] } } @[simp] lemma mem_equalizer (ϕ ψ : A →ₐ[R] B) (x : A) : x ∈ ϕ.equalizer ψ ↔ ϕ x = ψ x := iff.rfl /-- The range of a morphism of algebras is a fintype, if the domain is a fintype. Note that this instance can cause a diamond with `subtype.fintype` if `B` is also a fintype. -/ instance fintype_range [fintype A] [decidable_eq B] (φ : A →ₐ[R] B) : fintype φ.range := set.fintype_range φ end alg_hom namespace alg_equiv variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] /-- Restrict an algebra homomorphism with a left inverse to an algebra isomorphism to its range. This is a computable alternative to `alg_equiv.of_injective`. -/ def of_left_inverse {g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) : A ≃ₐ[R] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.val, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := f.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.range_restrict } @[simp] lemma of_left_inverse_apply {g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : A) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply {g : B → A} {f : A →ₐ[R] B} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl /-- Restrict an injective algebra homomorphism to an algebra isomorphism -/ noncomputable def of_injective (f : A →ₐ[R] B) (hf : function.injective f) : A ≃ₐ[R] f.range := of_left_inverse (classical.some_spec hf.has_left_inverse) @[simp] lemma of_injective_apply (f : A →ₐ[R] B) (hf : function.injective f) (x : A) : ↑(of_injective f hf x) = f x := rfl /-- Restrict an algebra homomorphism between fields to an algebra isomorphism -/ noncomputable def of_injective_field {E F : Type*} [division_ring E] [semiring F] [nontrivial F] [algebra R E] [algebra R F] (f : E →ₐ[R] F) : E ≃ₐ[R] f.range := of_injective f f.to_ring_hom.injective end alg_equiv namespace algebra variables (R : Type u) {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] /-- The minimal subalgebra that includes `s`. -/ def adjoin (s : set A) : subalgebra R A := { algebra_map_mem' := λ r, subsemiring.subset_closure $ or.inl ⟨r, rfl⟩, .. subsemiring.closure (set.range (algebra_map R A) ∪ s) } variables {R} protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H, λ H, show subsemiring.closure (set.range (algebra_map R A) ∪ s) ≤ S.to_subsemiring, from subsemiring.closure_le.2 $ set.union_subset S.range_subset H⟩ /-- Galois insertion between `adjoin` and `coe`. -/ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, (adjoin R s).copy s $ le_antisymm (algebra.gc.le_u_l s) hs, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := λ _ _, subalgebra.copy_eq _ _ _ } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi @[simp] lemma coe_top : (↑(⊤ : subalgebra R A) : set A) = set.univ := rfl @[simp] lemma mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := set.mem_univ x @[simp] lemma top_to_submodule : (⊤ : subalgebra R A).to_submodule = ⊤ := rfl @[simp] lemma top_to_subsemiring : (⊤ : subalgebra R A).to_subsemiring = ⊤ := rfl @[simp, norm_cast] lemma coe_inf (S T : subalgebra R A) : (↑(S ⊓ T) : set A) = S ∩ T := rfl @[simp] lemma mem_inf {S T : subalgebra R A} {x : A} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl @[simp] lemma inf_to_submodule (S T : subalgebra R A) : (S ⊓ T).to_submodule = S.to_submodule ⊓ T.to_submodule := rfl @[simp] lemma inf_to_subsemiring (S T : subalgebra R A) : (S ⊓ T).to_subsemiring = S.to_subsemiring ⊓ T.to_subsemiring := rfl @[simp, norm_cast] lemma coe_Inf (S : set (subalgebra R A)) : (↑(Inf S) : set A) = ⋂ s ∈ S, ↑s := Inf_image lemma mem_Inf {S : set (subalgebra R A)} {x : A} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := by simp only [← set_like.mem_coe, coe_Inf, set.mem_bInter_iff] @[simp] lemma Inf_to_submodule (S : set (subalgebra R A)) : (Inf S).to_submodule = Inf (subalgebra.to_submodule '' S) := set_like.coe_injective $ by simp @[simp] lemma Inf_to_subsemiring (S : set (subalgebra R A)) : (Inf S).to_subsemiring = Inf (subalgebra.to_subsemiring '' S) := set_like.coe_injective $ by simp @[simp, norm_cast] lemma coe_infi {ι : Sort*} {S : ι → subalgebra R A} : (↑(⨅ i, S i) : set A) = ⋂ i, S i := by simp [infi] lemma mem_infi {ι : Sort*} {S : ι → subalgebra R A} {x : A} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp] lemma infi_to_submodule {ι : Sort*} (S : ι → subalgebra R A) : (⨅ i, S i).to_submodule = ⨅ i, (S i).to_submodule := set_like.coe_injective $ by simp instance : inhabited (subalgebra R A) := ⟨⊥⟩ theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) := suffices (of_id R A).range = (⊥ : subalgebra R A), by { rw [← this, ←set_like.mem_coe, alg_hom.coe_range], refl }, le_bot_iff.mp (λ x hx, subalgebra.range_le _ ((of_id R A).coe_range ▸ hx)) theorem to_submodule_bot : (⊥ : subalgebra R A).to_submodule = R ∙ 1 := by { ext x, simp [mem_bot, -set.singleton_one, submodule.mem_span_singleton, algebra.smul_def] } @[simp] theorem coe_bot : ((⊥ : subalgebra R A) : set A) = set.range (algebra_map R A) := by simp [set.ext_iff, algebra.mem_bot] theorem eq_top_iff {S : subalgebra R A} : S = ⊤ ↔ ∀ x : A, x ∈ S := ⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩ @[simp] theorem map_top (f : A →ₐ[R] B) : subalgebra.map (⊤ : subalgebra R A) f = f.range := subalgebra.ext $ λ x, ⟨λ ⟨y, _, hy⟩, ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨y, algebra.mem_top, hy⟩⟩ @[simp] theorem map_bot (f : A →ₐ[R] B) : subalgebra.map (⊥ : subalgebra R A) f = ⊥ := eq_bot_iff.2 $ λ x ⟨y, hy, hfy⟩, let ⟨r, hr⟩ := mem_bot.1 hy in subalgebra.range_le _ ⟨r, by rwa [← f.commutes, hr]⟩ @[simp] theorem comap_top (f : A →ₐ[R] B) : subalgebra.comap' (⊤ : subalgebra R B) f = ⊤ := eq_top_iff.2 $ λ x, mem_top /-- `alg_hom` to `⊤ : subalgebra R A`. -/ def to_top : A →ₐ[R] (⊤ : subalgebra R A) := (alg_hom.id R A).cod_restrict ⊤ (λ _, mem_top) theorem surjective_algebra_map_iff : function.surjective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ := ⟨λ h, eq_bot_iff.2 $ λ y _, let ⟨x, hx⟩ := h y in hx ▸ subalgebra.algebra_map_mem _ _, λ h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y ∈ _)⟩ theorem bijective_algebra_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A] [algebra R A] : function.bijective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ := ⟨λ h, surjective_algebra_map_iff.1 h.2, λ h, ⟨(algebra_map R A).injective, surjective_algebra_map_iff.2 h⟩⟩ /-- The bottom subalgebra is isomorphic to the base ring. -/ noncomputable def bot_equiv_of_injective (h : function.injective (algebra_map R A)) : (⊥ : subalgebra R A) ≃ₐ[R] R := alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _) ⟨λ x y hxy, h (congr_arg subtype.val hxy : _), λ ⟨y, hy⟩, let ⟨x, hx⟩ := algebra.mem_bot.1 hy in ⟨x, subtype.eq hx⟩⟩ /-- The bottom subalgebra is isomorphic to the field. -/ noncomputable def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] : (⊥ : subalgebra F R) ≃ₐ[F] F := bot_equiv_of_injective (ring_hom.injective _) /-- The top subalgebra is isomorphic to the field. -/ noncomputable def top_equiv : (⊤ : subalgebra R A) ≃ₐ[R] A := (alg_equiv.of_bijective to_top ⟨λ _ _, subtype.mk.inj, λ x, ⟨x.val, by { ext, refl }⟩⟩ : A ≃ₐ[R] (⊤ : subalgebra R A)).symm end algebra namespace subalgebra open algebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] variables (S : subalgebra R A) -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_subsingleton [subsingleton A] : subsingleton (subalgebra R A) := ⟨λ B C, ext (λ x, by { simp only [subsingleton.elim x 0, zero_mem] })⟩ /-- For performance reasons this is not an instance. If you need this instance, add ``` local attribute [instance] alg_hom.subsingleton subalgebra.subsingleton_of_subsingleton ``` in the section that needs it. -/ -- TODO[gh-6025]: make this an instance once safe to do so lemma _root_.alg_hom.subsingleton [subsingleton (subalgebra R A)] : subsingleton (A →ₐ[R] B) := ⟨λ f g, alg_hom.ext $ λ a, have a ∈ (⊥ : subalgebra R A) := subsingleton.elim (⊤ : subalgebra R A) ⊥ ▸ mem_top, let ⟨x, hx⟩ := set.mem_range.mp (mem_bot.mp this) in hx ▸ (f.commutes _).trans (g.commutes _).symm⟩ -- TODO[gh-6025]: make this an instance once safe to do so lemma _root_.alg_equiv.subsingleton_left [subsingleton (subalgebra R A)] : subsingleton (A ≃ₐ[R] B) := begin haveI : subsingleton (A →ₐ[R] B) := alg_hom.subsingleton, exact ⟨λ f g, alg_equiv.ext (λ x, alg_hom.ext_iff.mp (subsingleton.elim f.to_alg_hom g.to_alg_hom) x)⟩, end -- TODO[gh-6025]: make this an instance once safe to do so lemma _root_.alg_equiv.subsingleton_right [subsingleton (subalgebra R B)] : subsingleton (A ≃ₐ[R] B) := begin haveI : subsingleton (B ≃ₐ[R] A) := alg_equiv.subsingleton_left, exact ⟨λ f g, eq.trans (alg_equiv.symm_symm _).symm (by rw [subsingleton.elim f.symm g.symm, alg_equiv.symm_symm])⟩ end lemma range_val : S.val.range = S := ext $ set.ext_iff.1 $ S.val.coe_range.trans subtype.range_val instance : unique (subalgebra R R) := { uniq := begin intro S, refine le_antisymm (λ r hr, _) bot_le, simp only [set.mem_range, mem_bot, id.map_eq_self, exists_apply_eq_apply, default], end .. algebra.subalgebra.inhabited } /-- The map `S → T` when `S` is a subalgebra contained in the subalgebra `T`. This is the subalgebra version of `submodule.of_le`, or `subring.inclusion` -/ def inclusion {S T : subalgebra R A} (h : S ≤ T) : S →ₐ[R] T := { to_fun := set.inclusion h, map_one' := rfl, map_add' := λ _ _, rfl, map_mul' := λ _ _, rfl, map_zero' := rfl, commutes' := λ _, rfl } lemma inclusion_injective {S T : subalgebra R A} (h : S ≤ T) : function.injective (inclusion h) := λ _ _, subtype.ext ∘ subtype.mk.inj @[simp] lemma inclusion_self {S : subalgebra R A}: inclusion (le_refl S) = alg_hom.id R S := alg_hom.ext $ λ x, subtype.ext rfl @[simp] lemma inclusion_right {S T : subalgebra R A} (h : S ≤ T) (x : T) (m : (x : A) ∈ S) : inclusion h ⟨x, m⟩ = x := subtype.ext rfl @[simp] lemma inclusion_inclusion {S T U : subalgebra R A} (hst : S ≤ T) (htu : T ≤ U) (x : S) : inclusion htu (inclusion hst x) = inclusion (le_trans hst htu) x := subtype.ext rfl @[simp] lemma coe_inclusion {S T : subalgebra R A} (h : S ≤ T) (s : S) : (inclusion h s : A) = s := rfl /-- Two subalgebras that are equal are also equivalent as algebras. This is the `subalgebra` version of `linear_equiv.of_eq` and `equiv.set.of_eq`. -/ @[simps apply] def equiv_of_eq (S T : subalgebra R A) (h : S = T) : S ≃ₐ[R] T := { to_fun := λ x, ⟨x, h ▸ x.2⟩, inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩, map_mul' := λ _ _, rfl, commutes' := λ _, rfl, .. linear_equiv.of_eq _ _ (congr_arg to_submodule h) } @[simp] lemma equiv_of_eq_symm (S T : subalgebra R A) (h : S = T) : (equiv_of_eq S T h).symm = equiv_of_eq T S h.symm := rfl @[simp] lemma equiv_of_eq_rfl (S : subalgebra R A) : equiv_of_eq S S rfl = alg_equiv.refl := by { ext, refl } @[simp] lemma equiv_of_eq_trans (S T U : subalgebra R A) (hST : S = T) (hTU : T = U) : (equiv_of_eq S T hST).trans (equiv_of_eq T U hTU) = equiv_of_eq S U (trans hST hTU) := rfl section prod variables (S₁ : subalgebra R B) /-- The product of two subalgebras is a subalgebra. -/ def prod : subalgebra R (A × B) := { carrier := set.prod S S₁, algebra_map_mem' := λ r, ⟨algebra_map_mem _ _, algebra_map_mem _ _⟩, .. S.to_subsemiring.prod S₁.to_subsemiring } @[simp] lemma coe_prod : (prod S S₁ : set (A × B)) = set.prod S S₁ := rfl lemma prod_to_submodule : (S.prod S₁).to_submodule = S.to_submodule.prod S₁.to_submodule := rfl @[simp] lemma mem_prod {S : subalgebra R A} {S₁ : subalgebra R B} {x : A × B} : x ∈ prod S S₁ ↔ x.1 ∈ S ∧ x.2 ∈ S₁ := set.mem_prod @[simp] lemma prod_top : (prod ⊤ ⊤ : subalgebra R (A × B)) = ⊤ := by ext; simp lemma prod_mono {S T : subalgebra R A} {S₁ T₁ : subalgebra R B} : S ≤ T → S₁ ≤ T₁ → prod S S₁ ≤ prod T T₁ := set.prod_mono @[simp] lemma prod_inf_prod {S T : subalgebra R A} {S₁ T₁ : subalgebra R B} : S.prod S₁ ⊓ T.prod T₁ = (S ⊓ T).prod (S₁ ⊓ T₁) := set_like.coe_injective set.prod_inter_prod end prod section supr_lift variables {ι : Type*} lemma coe_supr_of_directed [nonempty ι] {S : ι → subalgebra R A} (dir : directed (≤) S) : ↑(supr S) = ⋃ i, (S i : set A) := let K : subalgebra R A := { carrier := ⋃ i, (S i), mul_mem' := λ x y hx hy, let ⟨i, hi⟩ := set.mem_Union.1 hx in let ⟨j, hj⟩ := set.mem_Union.1 hy in let ⟨k, hik, hjk⟩ := dir i j in set.mem_Union.2 ⟨k, subalgebra.mul_mem (S k) (hik hi) (hjk hj)⟩ , add_mem' := λ x y hx hy, let ⟨i, hi⟩ := set.mem_Union.1 hx in let ⟨j, hj⟩ := set.mem_Union.1 hy in let ⟨k, hik, hjk⟩ := dir i j in set.mem_Union.2 ⟨k, subalgebra.add_mem (S k) (hik hi) (hjk hj)⟩, algebra_map_mem' := λ r, let i := @nonempty.some ι infer_instance in set.mem_Union.2 ⟨i, subalgebra.algebra_map_mem _ _⟩ } in have supr S = K, from le_antisymm (supr_le (λ i, set.subset_Union (λ i, ↑(S i)) i)) (set_like.coe_subset_coe.1 (set.Union_subset (λ i, set_like.coe_subset_coe.2 (le_supr _ _)))), this.symm ▸ rfl /-- Define an algebra homomorphism on a directed supremum of subalgebras by defining it on each subalgebra, and proving that it agrees on the intersection of subalgebras. -/ noncomputable def supr_lift [nonempty ι] (K : ι → subalgebra R A) (dir : directed (≤) K) (f : Π i, K i →ₐ[R] B) (hf : ∀ (i j : ι) (h : K i ≤ K j), f i = (f j).comp (inclusion h)) (T : subalgebra R A) (hT : T = supr K) : ↥T →ₐ[R] B := by subst hT; exact { to_fun := set.Union_lift (λ i, ↑(K i)) (λ i x, f i x) (λ i j x hxi hxj, let ⟨k, hik, hjk⟩ := dir i j in begin rw [hf i k hik, hf j k hjk], refl end) ↑(supr K) (by rw coe_supr_of_directed dir; refl), map_one' := set.Union_lift_const _ (λ _, 1) (λ _, rfl) _ (by simp), map_zero' := set.Union_lift_const _ (λ _, 0) (λ _, rfl) _ (by simp), map_mul' := set.Union_lift_binary (coe_supr_of_directed dir) dir _ (λ _, (*)) (λ _ _ _, rfl) _ (by simp), map_add' := set.Union_lift_binary (coe_supr_of_directed dir) dir _ (λ _, (+)) (λ _ _ _, rfl) _ (by simp), commutes' := λ r, set.Union_lift_const _ (λ _, algebra_map _ _ r) (λ _, rfl) _ (λ i, by erw [alg_hom.commutes (f i)]) } variables [nonempty ι] {K : ι → subalgebra R A} {dir : directed (≤) K} {f : Π i, K i →ₐ[R] B} {hf : ∀ (i j : ι) (h : K i ≤ K j), f i = (f j).comp (inclusion h)} {T : subalgebra R A} {hT : T = supr K} @[simp] lemma supr_lift_inclusion {i : ι} (x : K i) (h : K i ≤ T) : supr_lift K dir f hf T hT (inclusion h x) = f i x := by subst T; exact set.Union_lift_inclusion _ _ @[simp] lemma supr_lift_comp_inclusion {i : ι} (h : K i ≤ T) : (supr_lift K dir f hf T hT).comp (inclusion h) = f i := by ext; simp @[simp] lemma supr_lift_mk {i : ι} (x : K i) (hx : (x : A) ∈ T) : supr_lift K dir f hf T hT ⟨x, hx⟩ = f i x := by subst hT; exact set.Union_lift_mk x hx lemma supr_lift_of_mem {i : ι} (x : T) (hx : (x : A) ∈ K i) : supr_lift K dir f hf T hT x = f i ⟨x, hx⟩ := by subst hT; exact set.Union_lift_of_mem x hx end supr_lift /-! ## Actions by `subalgebra`s These are just copies of the definitions about `subsemiring` starting from `subring.mul_action`. -/ section actions variables {α β : Type*} /-- The action by a subalgebra is the action by the underlying ring. -/ instance [mul_action A α] (S : subalgebra R A) : mul_action S α := S.to_subsemiring.mul_action lemma smul_def [mul_action A α] {S : subalgebra R A} (g : S) (m : α) : g • m = (g : A) • m := rfl instance smul_comm_class_left [mul_action A β] [has_scalar α β] [smul_comm_class A α β] (S : subalgebra R A) : smul_comm_class S α β := S.to_subsemiring.smul_comm_class_left instance smul_comm_class_right [has_scalar α β] [mul_action A β] [smul_comm_class α A β] (S : subalgebra R A) : smul_comm_class α S β := S.to_subsemiring.smul_comm_class_right /-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/ instance is_scalar_tower_left [has_scalar α β] [mul_action A α] [mul_action A β] [is_scalar_tower A α β] (S : subalgebra R A) : is_scalar_tower S α β := S.to_subsemiring.is_scalar_tower instance [mul_action A α] [has_faithful_scalar A α] (S : subalgebra R A) : has_faithful_scalar S α := S.to_subsemiring.has_faithful_scalar /-- The action by a subalgebra is the action by the underlying algebra. -/ instance [add_monoid α] [distrib_mul_action A α] (S : subalgebra R A) : distrib_mul_action S α := S.to_subsemiring.distrib_mul_action /-- The action by a subalgebra is the action by the underlying algebra. -/ instance module_left [add_comm_monoid α] [module A α] (S : subalgebra R A) : module S α := S.to_subsemiring.module /-- The action by a subalgebra is the action by the underlying algebra. -/ instance to_algebra {R A : Type*} [comm_semiring R] [comm_semiring A] [semiring α] [algebra R A] [algebra A α] (S : subalgebra R A) : algebra S α := algebra.of_subsemiring S.to_subsemiring lemma algebra_map_eq {R A : Type*} [comm_semiring R] [comm_semiring A] [semiring α] [algebra R A] [algebra A α] (S : subalgebra R A) : algebra_map S α = (algebra_map A α).comp S.val := rfl @[simp] lemma srange_algebra_map {R A : Type*} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) : (algebra_map S A).srange = S.to_subsemiring := by rw [algebra_map_eq, algebra.id.map_eq_id, ring_hom.id_comp, ← to_subsemiring_subtype, subsemiring.srange_subtype] @[simp] lemma range_algebra_map {R A : Type*} [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : (algebra_map S A).range = S.to_subring := by rw [algebra_map_eq, algebra.id.map_eq_id, ring_hom.id_comp, ← to_subring_subtype, subring.range_subtype] instance no_zero_smul_divisors_top [no_zero_divisors A] (S : subalgebra R A) : no_zero_smul_divisors S A := ⟨λ c x h, have (c : A) = 0 ∨ x = 0, from eq_zero_or_eq_zero_of_mul_eq_zero h, this.imp_left (@subtype.ext_iff _ _ c 0).mpr⟩ end actions section pointwise variables {R' : Type*} [semiring R'] [mul_semiring_action R' A] [smul_comm_class R' R A] /-- The action on a subalgebra corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action R' (subalgebra R A) := { smul := λ a S, S.map (mul_semiring_action.to_alg_hom _ _ a), one_smul := λ S, (congr_arg (λ f, S.map f) (alg_hom.ext $ by exact one_smul R')).trans S.map_id, mul_smul := λ a₁ a₂ S, (congr_arg (λ f, S.map f) (alg_hom.ext $ by exact mul_smul _ _)).trans (S.map_map _ _).symm } localized "attribute [instance] subalgebra.pointwise_mul_action" in pointwise open_locale pointwise @[simp] lemma coe_pointwise_smul (m : R') (S : subalgebra R A) : ↑(m • S) = m • (S : set A) := rfl @[simp] lemma pointwise_smul_to_subsemiring (m : R') (S : subalgebra R A) : (m • S).to_subsemiring = m • S.to_subsemiring := rfl @[simp] lemma pointwise_smul_to_submodule (m : R') (S : subalgebra R A) : (m • S).to_submodule = m • S.to_submodule := rfl @[simp] lemma pointwise_smul_to_subring {R' R A : Type*} [semiring R'] [comm_ring R] [ring A] [mul_semiring_action R' A] [algebra R A] [smul_comm_class R' R A] (m : R') (S : subalgebra R A) : (m • S).to_subring = m • S.to_subring := rfl lemma smul_mem_pointwise_smul (m : R') (r : A) (S : subalgebra R A) : r ∈ S → m • r ∈ m • S := (set.smul_mem_smul_set : _ → _ ∈ m • (S : set A)) end pointwise end subalgebra section nat variables {R : Type*} [semiring R] /-- A subsemiring is a `ℕ`-subalgebra. -/ def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra ℕ R := { algebra_map_mem' := λ i, S.coe_nat_mem i, .. S } @[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} : x ∈ subalgebra_of_subsemiring S ↔ x ∈ S := iff.rfl end nat section int variables {R : Type*} [ring R] /-- A subring is a `ℤ`-subalgebra. -/ def subalgebra_of_subring (S : subring R) : subalgebra ℤ R := { algebra_map_mem' := λ i, int.induction_on i S.zero_mem (λ i ih, S.add_mem ih S.one_mem) (λ i ih, show ((-i - 1 : ℤ) : R) ∈ S, by { rw [int.cast_sub, int.cast_one], exact S.sub_mem ih S.one_mem }), .. S } variables {S : Type*} [semiring S] @[simp] lemma mem_subalgebra_of_subring {x : R} {S : subring R} : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl end int
b6858c37bb274a6523518f7da65d8afb8dabce3b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/digits_auto.lean
22a7a6140fb75f5d4c2e8b9d106766e5c9b68608
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
11,929
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.int.modeq import Mathlib.tactic.interval_cases import Mathlib.tactic.linarith.default import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. A basic `norm_digits` tactic is also provided for proving goals of the form `nat.digits a b = l` where `a` and `b` are numerals. -/ namespace nat /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_0 : ℕ → List ℕ := sorry /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_1 (n : ℕ) : List ℕ := list.repeat 1 n /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux (b : ℕ) (h : bit0 1 ≤ b) : ℕ → List ℕ := sorry @[simp] theorem digits_aux_zero (b : ℕ) (h : bit0 1 ≤ b) : digits_aux b h 0 = [] := rfl theorem digits_aux_def (b : ℕ) (h : bit0 1 ≤ b) (n : ℕ) (w : 0 < n) : digits_aux b h n = n % b :: digits_aux b h (n / b) := sorry /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `of_digits b L = L.foldr (λ x y, x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = list.repeat 1 n`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `nat.to_digits` in core, which is used for printing numerals. In particular, `nat.to_digits b 0 = [0]`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → List ℕ := sorry @[simp] theorem digits_zero (b : ℕ) : digits b 0 = [] := nat.cases_on b (Eq.refl (digits 0 0)) fun (b : ℕ) => nat.cases_on b (Eq.refl (digits 1 0)) fun (b : ℕ) => Eq.refl (digits (Nat.succ (Nat.succ b)) 0) @[simp] theorem digits_zero_zero : digits 0 0 = [] := rfl @[simp] theorem digits_zero_succ (n : ℕ) : digits 0 (Nat.succ n) = [n + 1] := rfl theorem digits_zero_succ' {n : ℕ} (w : 0 < n) : digits 0 n = [n] := nat.cases_on n (fun (w : 0 < 0) => idRhs (digits 0 0 = [0]) (absurd w (of_as_true trivial))) (fun (n : ℕ) (w : 0 < Nat.succ n) => idRhs (digits 0 (n + 1) = digits 0 (n + 1)) rfl) w @[simp] theorem digits_one (n : ℕ) : digits 1 n = list.repeat 1 n := rfl @[simp] theorem digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl @[simp] theorem digits_add_two_add_one (b : ℕ) (n : ℕ) : digits (b + bit0 1) (n + 1) = (n + 1) % (b + bit0 1) :: digits (b + bit0 1) ((n + 1) / (b + bit0 1)) := rfl theorem digits_def' {b : ℕ} (h : bit0 1 ≤ b) {n : ℕ} (w : 0 < n) : digits b n = n % b :: digits b (n / b) := sorry @[simp] theorem digits_of_lt (b : ℕ) (x : ℕ) (w₁ : 0 < x) (w₂ : x < b) : digits b x = [x] := sorry theorem digits_add (b : ℕ) (h : bit0 1 ≤ b) (x : ℕ) (y : ℕ) (w : x < b) (w' : 0 < x ∨ 0 < y) : digits b (x + b * y) = x :: digits b y := sorry /-- `of_digits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. def of_digits {α : Type u_1} [semiring α] (b : α) : List ℕ → α := sorry theorem of_digits_eq_foldr {α : Type u_1} [semiring α] (b : α) (L : List ℕ) : of_digits b L = list.foldr (fun (x : ℕ) (y : α) => ↑x + b * y) 0 L := sorry @[simp] theorem of_digits_singleton {b : ℕ} {n : ℕ} : of_digits b [n] = n := sorry @[simp] theorem of_digits_one_cons {α : Type u_1} [semiring α] (h : ℕ) (L : List ℕ) : of_digits 1 (h :: L) = ↑h + of_digits 1 L := sorry theorem of_digits_append {b : ℕ} {l1 : List ℕ} {l2 : List ℕ} : of_digits b (l1 ++ l2) = of_digits b l1 + b ^ list.length l1 * of_digits b l2 := sorry theorem coe_of_digits (α : Type u_1) [semiring α] (b : ℕ) (L : List ℕ) : ↑(of_digits b L) = of_digits (↑b) L := sorry theorem coe_int_of_digits (b : ℕ) (L : List ℕ) : ↑(of_digits b L) = of_digits (↑b) L := sorry theorem digits_zero_of_eq_zero {b : ℕ} (h : 1 ≤ b) {L : List ℕ} (w : of_digits b L = 0) (l : ℕ) (H : l ∈ L) : l = 0 := sorry theorem digits_of_digits (b : ℕ) (h : bit0 1 ≤ b) (L : List ℕ) (w₁ : ∀ (l : ℕ), l ∈ L → l < b) (w₂ : ∀ (h : L ≠ []), list.last L h ≠ 0) : digits b (of_digits b L) = L := sorry theorem of_digits_digits (b : ℕ) (n : ℕ) : of_digits b (digits b n) = n := sorry theorem of_digits_one (L : List ℕ) : of_digits 1 L = list.sum L := sorry /-! ### Properties This section contains various lemmas of properties relating to `digits` and `of_digits`. -/ theorem digits_eq_nil_iff_eq_zero {b : ℕ} {n : ℕ} : digits b n = [] ↔ n = 0 := sorry theorem digits_ne_nil_iff_ne_zero {b : ℕ} {n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero theorem digits_last {b : ℕ} {m : ℕ} (h : bit0 1 ≤ b) (hm : 0 < m) (p : digits b m ≠ []) (q : digits b (m / b) ≠ []) : list.last (digits b m) p = list.last (digits b (m / b)) q := sorry theorem last_digit_ne_zero (b : ℕ) {m : ℕ} (hm : m ≠ 0) : list.last (digits b m) (iff.mpr digits_ne_nil_iff_ne_zero hm) ≠ 0 := sorry /-- The digits in the base b+2 expansion of n are all less than b+2 -/ theorem digits_lt_base' {b : ℕ} {m : ℕ} {d : ℕ} : d ∈ digits (b + bit0 1) m → d < b + bit0 1 := sorry /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ theorem digits_lt_base {b : ℕ} {m : ℕ} {d : ℕ} (hb : bit0 1 ≤ b) (hd : d ∈ digits b m) : d < b := sorry /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ theorem of_digits_lt_base_pow_length' {b : ℕ} {l : List ℕ} (hl : ∀ (x : ℕ), x ∈ l → x < b + bit0 1) : of_digits (b + bit0 1) l < (b + bit0 1) ^ list.length l := sorry /-- an n-digit number in base b is less than b^n if b ≥ 2 -/ theorem of_digits_lt_base_pow_length {b : ℕ} {l : List ℕ} (hb : bit0 1 ≤ b) (hl : ∀ (x : ℕ), x ∈ l → x < b) : of_digits b l < b ^ list.length l := sorry /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ theorem lt_base_pow_length_digits' {b : ℕ} {m : ℕ} : m < (b + bit0 1) ^ list.length (digits (b + bit0 1) m) := sorry /-- Any number m is less than b^(number of digits in the base b representation of m) -/ theorem lt_base_pow_length_digits {b : ℕ} {m : ℕ} (hb : bit0 1 ≤ b) : m < b ^ list.length (digits b m) := sorry theorem of_digits_digits_append_digits {b : ℕ} {m : ℕ} {n : ℕ} : of_digits b (digits b n ++ digits b m) = n + b ^ list.length (digits b n) * m := sorry theorem digits_len_le_digits_len_succ (b : ℕ) (n : ℕ) : list.length (digits b n) ≤ list.length (digits b (n + 1)) := sorry theorem le_digits_len_le (b : ℕ) (n : ℕ) (m : ℕ) (h : n ≤ m) : list.length (digits b n) ≤ list.length (digits b m) := monotone_of_monotone_nat (digits_len_le_digits_len_succ b) h theorem pow_length_le_mul_of_digits {b : ℕ} {l : List ℕ} (hl : l ≠ []) (hl2 : list.last l hl ≠ 0) : (b + bit0 1) ^ list.length l ≤ (b + bit0 1) * of_digits (b + bit0 1) l := sorry /-- Any non-zero natural number `m` is greater than (b+2)^((number of digits in the base (b+2) representation of m) - 1) -/ theorem base_pow_length_digits_le' (b : ℕ) (m : ℕ) (hm : m ≠ 0) : (b + bit0 1) ^ list.length (digits (b + bit0 1) m) ≤ (b + bit0 1) * m := sorry /-- Any non-zero natural number `m` is greater than b^((number of digits in the base b representation of m) - 1) -/ theorem base_pow_length_digits_le (b : ℕ) (m : ℕ) (hb : bit0 1 ≤ b) : m ≠ 0 → b ^ list.length (digits b m) ≤ b * m := sorry /-! ### Modular Arithmetic -/ -- This is really a theorem about polynomials. theorem dvd_of_digits_sub_of_digits {α : Type u_1} [comm_ring α] {a : α} {b : α} {k : α} (h : k ∣ a - b) (L : List ℕ) : k ∣ of_digits a L - of_digits b L := sorry theorem of_digits_modeq' (b : ℕ) (b' : ℕ) (k : ℕ) (h : modeq k b b') (L : List ℕ) : modeq k (of_digits b L) (of_digits b' L) := sorry theorem of_digits_modeq (b : ℕ) (k : ℕ) (L : List ℕ) : modeq k (of_digits b L) (of_digits (b % k) L) := of_digits_modeq' b (b % k) k (modeq.symm (modeq.mod_modeq b k)) L theorem of_digits_mod (b : ℕ) (k : ℕ) (L : List ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_modeq b k L theorem of_digits_zmodeq' (b : ℤ) (b' : ℤ) (k : ℕ) (h : int.modeq (↑k) b b') (L : List ℕ) : int.modeq (↑k) (of_digits b L) (of_digits b' L) := sorry theorem of_digits_zmodeq (b : ℤ) (k : ℕ) (L : List ℕ) : int.modeq (↑k) (of_digits b L) (of_digits (b % ↑k) L) := of_digits_zmodeq' b (b % ↑k) k (int.modeq.symm (int.modeq.mod_modeq b ↑k)) L theorem of_digits_zmod (b : ℤ) (k : ℕ) (L : List ℕ) : of_digits b L % ↑k = of_digits (b % ↑k) L % ↑k := of_digits_zmodeq b k L theorem modeq_digits_sum (b : ℕ) (b' : ℕ) (h : b' % b = 1) (n : ℕ) : modeq b n (list.sum (digits b' n)) := sorry theorem modeq_three_digits_sum (n : ℕ) : modeq (bit1 1) n (list.sum (digits (bit0 (bit1 (bit0 1))) n)) := sorry theorem modeq_nine_digits_sum (n : ℕ) : modeq (bit1 (bit0 (bit0 1))) n (list.sum (digits (bit0 (bit1 (bit0 1))) n)) := sorry theorem zmodeq_of_digits_digits (b : ℕ) (b' : ℕ) (c : ℤ) (h : int.modeq (↑b) (↑b') c) (n : ℕ) : int.modeq (↑b) (↑n) (of_digits c (digits b' n)) := sorry theorem of_digits_neg_one (L : List ℕ) : of_digits (-1) L = list.alternating_sum (list.map (fun (n : ℕ) => ↑n) L) := sorry theorem modeq_eleven_digits_sum (n : ℕ) : int.modeq (bit1 (bit1 (bit0 1))) (↑n) (list.alternating_sum (list.map (fun (n : ℕ) => ↑n) (digits (bit0 (bit1 (bit0 1))) n))) := sorry /-! ## Divisibility -/ theorem dvd_iff_dvd_digits_sum (b : ℕ) (b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ list.sum (digits b' n) := sorry theorem three_dvd_iff (n : ℕ) : bit1 1 ∣ n ↔ bit1 1 ∣ list.sum (digits (bit0 (bit1 (bit0 1))) n) := sorry theorem nine_dvd_iff (n : ℕ) : bit1 (bit0 (bit0 1)) ∣ n ↔ bit1 (bit0 (bit0 1)) ∣ list.sum (digits (bit0 (bit1 (bit0 1))) n) := sorry theorem dvd_iff_dvd_of_digits (b : ℕ) (b' : ℕ) (c : ℤ) (h : ↑b ∣ ↑b' - c) (n : ℕ) : b ∣ n ↔ ↑b ∣ of_digits c (digits b' n) := sorry theorem eleven_dvd_iff (n : ℕ) : bit1 (bit1 (bit0 1)) ∣ n ↔ bit1 (bit1 (bit0 1)) ∣ list.alternating_sum (list.map (fun (n : ℕ) => ↑n) (digits (bit0 (bit1 (bit0 1))) n)) := sorry /-! ### `norm_digits` tactic -/ namespace norm_digits theorem digits_succ (b : ℕ) (n : ℕ) (m : ℕ) (r : ℕ) (l : List ℕ) (e : r + b * m = n) (hr : r < b) (h : digits b m = l ∧ bit0 1 ≤ b ∧ 0 < m) : digits b n = r :: l ∧ bit0 1 ≤ b ∧ 0 < n := sorry theorem digits_one (b : ℕ) (n : ℕ) (n0 : 0 < n) (nb : n < b) : digits b n = [n] ∧ bit0 1 ≤ b ∧ 0 < n := sorry end Mathlib
f9cdaff50fbe9dd6b23b59862bf4ea10cd507462
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/aggregateProjectPullUpConstants.lean
de47cd949ccd87bd7e54b15603d52e3d1f390a2b
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,738
lean
/- ⟦ Γ ⊢ (SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_job)) (combineGroupByProj PLAIN(uvariable (right⋅emp_empno)) (combineGroupByProj PLAIN(uvariable (right⋅emp_sal)) (SUM(uvariable (right⋅emp_sal)))))) FROM1 (table rel_emp) WHERE (equal (uvariable (right⋅emp_empno)) (constantExpr integer_10)) GROUP BY (combine (right⋅emp_job) (combine (right⋅emp_empno) (right⋅emp_sal)))) : _ ⟧ ⟦ Γ ⊢ (SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_job)) (combineGroupByProj PLAIN(uvariable (e2p (constantExpr integer_10))) (combineGroupByProj PLAIN(uvariable (right⋅emp_sal)) (SUM(uvariable (right⋅emp_sal)))))) FROM1 (table rel_emp) WHERE (equal (uvariable (right⋅emp_empno)) (constantExpr integer_10)) GROUP BY (combine (right⋅emp_job) (right⋅emp_sal))) : _ ⟧ -/ import ..extra_constants import ..sql import ..u_semiring import ..cosette_tactics open SQL open Proj open Pred open Expr variable i : const datatypes.int theorem rule : forall (Γ scm_emp : Schema) (rel_emp : relation scm_emp) (emp_empno : Column datatypes.int scm_emp) (emp_ename : Column datatypes.int scm_emp) (emp_job : Column datatypes.int scm_emp) (emp_mgr : Column datatypes.int scm_emp) (emp_hiredate : Column datatypes.int scm_emp) (emp_comm : Column datatypes.int scm_emp) (emp_sal : Column datatypes.int scm_emp) (emp_deptno : Column datatypes.int scm_emp) (emp_slacker : Column datatypes.int scm_emp), denoteSQL (SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_job)) (combineGroupByProj PLAIN(uvariable (right⋅emp_empno)) (combineGroupByProj PLAIN(uvariable (right⋅emp_sal)) SUM(uvariable (right⋅emp_sal))))) FROM1 (table rel_emp WHERE (Pred.equal (uvariable (right⋅emp_empno)) (constantExpr i))) GROUP BY (combine (right⋅emp_job) (combine (right⋅emp_empno) (right⋅emp_sal))) : SQL Γ _) = denoteSQL (SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_job)) (combineGroupByProj PLAIN(uvariable (e2p (constantExpr i))) (combineGroupByProj PLAIN(uvariable (right⋅emp_sal)) SUM(uvariable (right⋅emp_sal))))) FROM1 (table rel_emp WHERE (Pred.equal (uvariable (right⋅emp_empno)) (constantExpr i))) GROUP BY (combine (right⋅emp_job) (right⋅emp_sal)) : SQL Γ _) := begin intros, unfold_all_denotations, funext, simp, sorry end
91d8c5d35f1f65f2d9ed3ff2c0f619d2a61bce00
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/list_auto.lean
f7f62f97bd17ee348285d5aca8fa64bba03dc484
[]
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
6,147
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.constructions import Mathlib.topology.algebra.group import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Topology on lists and vectors -/ protected instance list.topological_space {α : Type u_1} [topological_space α] : topological_space (List α) := topological_space.mk_of_nhds (traverse nhds) theorem nhds_list {α : Type u_1} [topological_space α] (as : List α) : nhds as = traverse nhds as := sorry @[simp] theorem nhds_nil {α : Type u_1} [topological_space α] : nhds [] = pure [] := eq.mpr (id (Eq._oldrec (Eq.refl (nhds [] = pure [])) (nhds_list []))) (eq.mpr (id (Eq._oldrec (Eq.refl (traverse nhds [] = pure [])) (list.traverse_nil nhds))) (Eq.refl (pure []))) theorem nhds_cons {α : Type u_1} [topological_space α] (a : α) (l : List α) : nhds (a :: l) = List.cons <$> nhds a <*> nhds l := sorry theorem list.tendsto_cons {α : Type u_1} [topological_space α] {a : α} {l : List α} : filter.tendsto (fun (p : α × List α) => prod.fst p :: prod.snd p) (filter.prod (nhds a) (nhds l)) (nhds (a :: l)) := sorry theorem filter.tendsto.cons {β : Type u_2} [topological_space β] {α : Type u_1} {f : α → β} {g : α → List β} {a : filter α} {b : β} {l : List β} (hf : filter.tendsto f a (nhds b)) (hg : filter.tendsto g a (nhds l)) : filter.tendsto (fun (a : α) => f a :: g a) a (nhds (b :: l)) := filter.tendsto.comp list.tendsto_cons (filter.tendsto.prod_mk hf hg) namespace list theorem tendsto_cons_iff {α : Type u_1} [topological_space α] {β : Type u_2} {f : List α → β} {b : filter β} {a : α} {l : List α} : filter.tendsto f (nhds (a :: l)) b ↔ filter.tendsto (fun (p : α × List α) => f (prod.fst p :: prod.snd p)) (filter.prod (nhds a) (nhds l)) b := sorry theorem continuous_cons {α : Type u_1} [topological_space α] : continuous fun (x : α × List α) => prod.fst x :: prod.snd x := sorry theorem tendsto_nhds {α : Type u_1} [topological_space α] {β : Type u_2} {f : List α → β} {r : List α → filter β} (h_nil : filter.tendsto f (pure []) (r [])) (h_cons : ∀ (l : List α) (a : α), filter.tendsto f (nhds l) (r l) → filter.tendsto (fun (p : α × List α) => f (prod.fst p :: prod.snd p)) (filter.prod (nhds a) (nhds l)) (r (a :: l))) (l : List α) : filter.tendsto f (nhds l) (r l) := sorry theorem continuous_at_length {α : Type u_1} [topological_space α] (l : List α) : continuous_at length l := sorry theorem tendsto_insert_nth' {α : Type u_1} [topological_space α] {a : α} {n : ℕ} {l : List α} : filter.tendsto (fun (p : α × List α) => insert_nth n (prod.fst p) (prod.snd p)) (filter.prod (nhds a) (nhds l)) (nhds (insert_nth n a l)) := sorry theorem tendsto_insert_nth {α : Type u_1} [topological_space α] {β : Type u_2} {n : ℕ} {a : α} {l : List α} {f : β → α} {g : β → List α} {b : filter β} (hf : filter.tendsto f b (nhds a)) (hg : filter.tendsto g b (nhds l)) : filter.tendsto (fun (b : β) => insert_nth n (f b) (g b)) b (nhds (insert_nth n a l)) := filter.tendsto.comp tendsto_insert_nth' (filter.tendsto.prod_mk hf hg) theorem continuous_insert_nth {α : Type u_1} [topological_space α] {n : ℕ} : continuous fun (p : α × List α) => insert_nth n (prod.fst p) (prod.snd p) := sorry theorem tendsto_remove_nth {α : Type u_1} [topological_space α] {n : ℕ} {l : List α} : filter.tendsto (fun (l : List α) => remove_nth l n) (nhds l) (nhds (remove_nth l n)) := sorry theorem continuous_remove_nth {α : Type u_1} [topological_space α] {n : ℕ} : continuous fun (l : List α) => remove_nth l n := iff.mpr continuous_iff_continuous_at fun (a : List α) => tendsto_remove_nth theorem tendsto_sum {α : Type u_1} [topological_space α] [add_monoid α] [has_continuous_add α] {l : List α} : filter.tendsto sum (nhds l) (nhds (sum l)) := sorry theorem continuous_sum {α : Type u_1} [topological_space α] [add_monoid α] [has_continuous_add α] : continuous sum := iff.mpr continuous_iff_continuous_at fun (l : List α) => tendsto_sum end list namespace vector protected instance topological_space {α : Type u_1} [topological_space α] (n : ℕ) : topological_space (vector α n) := eq.mpr sorry subtype.topological_space theorem tendsto_cons {α : Type u_1} [topological_space α] {n : ℕ} {a : α} {l : vector α n} : filter.tendsto (fun (p : α × vector α n) => prod.fst p::ᵥprod.snd p) (filter.prod (nhds a) (nhds l)) (nhds (a::ᵥl)) := sorry theorem tendsto_insert_nth {α : Type u_1} [topological_space α] {n : ℕ} {i : fin (n + 1)} {a : α} {l : vector α n} : filter.tendsto (fun (p : α × vector α n) => insert_nth (prod.fst p) i (prod.snd p)) (filter.prod (nhds a) (nhds l)) (nhds (insert_nth a i l)) := sorry theorem continuous_insert_nth' {α : Type u_1} [topological_space α] {n : ℕ} {i : fin (n + 1)} : continuous fun (p : α × vector α n) => insert_nth (prod.fst p) i (prod.snd p) := sorry theorem continuous_insert_nth {α : Type u_1} {β : Type u_2} [topological_space α] [topological_space β] {n : ℕ} {i : fin (n + 1)} {f : β → α} {g : β → vector α n} (hf : continuous f) (hg : continuous g) : continuous fun (b : β) => insert_nth (f b) i (g b) := continuous.comp continuous_insert_nth' (continuous.prod_mk hf hg) theorem continuous_at_remove_nth {α : Type u_1} [topological_space α] {n : ℕ} {i : fin (n + 1)} {l : vector α (n + 1)} : continuous_at (remove_nth i) l := sorry -- ∀{l:vector α (n+1)}, tendsto (remove_nth i) (𝓝 l) (𝓝 (remove_nth i l)) --| ⟨l, hl⟩ := theorem continuous_remove_nth {α : Type u_1} [topological_space α] {n : ℕ} {i : fin (n + 1)} : continuous (remove_nth i) := sorry end Mathlib
73b36e1594a2848952bacfddffd895b73b56e915
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/hint_auto.lean
1a00aa63f8df7684d1f3e130e33e7b7ce404e8af
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,009
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.solve_by_elim import Mathlib.tactic.interactive import Mathlib.PostPort namespace Mathlib namespace tactic namespace hint /-- An attribute marking a `tactic unit` or `tactic string` which should be used by the `hint` tactic. -/ /-- `add_hint_tactic t` runs the tactic `t` whenever `hint` is invoked. The typical use case is `add_hint_tactic "foo"` for some interactive tactic `foo`. -/ end hint /-- Report a list of tactics that can make progress against the current goal, and for each such tactic, the number of remaining goals afterwards. -/ namespace interactive /-- Report a list of tactics that can make progress against the current goal. -/ /-- `hint` lists possible tactics which will make progress (that is, not fail) against the current goal. end Mathlib
6f5cb7172de60891898f511407a3367b3febca00
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/order/filter/bases.lean
5d68676054e7615a425f9d94b40fba19eb206a23
[ "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
36,171
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import order.filter.basic import data.set.countable /-! # Filter bases A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. Compared to filters, filter bases do not require that any set containing an element of `B` belongs to `B`. A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs to `B.filter` if and only if it contains an element of `B`. Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`, the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p` (ie. `s '' set_of p`) defines a filter basis `h.filter_basis`. If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop` and `s : ι → set α` as above) means that a set belongs to `l` if and only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and `l = h.filter_basis.filter`. The point of this definition is that checking statements involving elements of `l` often reduces to checking them on the basis elements. We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual destruction of `h.mem_iff.mpr ht` using `cases` or `let`. This file also introduces more restricted classes of bases, involving monotonicity or countability. In particular, for `l : filter α`, `l.is_countably_generated` means there is a countable set of sets which generates `s`. This is reformulated in term of bases, and consequences are derived. ## Main statements * `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f` in terms of a basis; * `basis_sets` : all sets of a filter form a basis; * `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`, `has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`, `l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively; * `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms of bases. * `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate `tendsto f l l'` in terms of bases. * `is_countably_generated_iff_exists_antimono_basis` : proves a filter is countably generated if and only if it admis a basis parametrized by a decreasing sequence of sets indexed by `ℕ`. * `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous". ## Implementation notes As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases: * `has_basis l s`, `s : set (set α)`; * `has_basis l s`, `s : ι → set α`; * `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`. We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis of this form. The other two can be emulated using `s = id` or `p = λ _, true`. With this approach sometimes one needs to `simp` the statement provided by the `has_basis` machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help with the case `p = λ _, true`. -/ open set filter open_locale filter classical variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} {ι' : Type*} /-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure filter_basis (α : Type*) := (sets : set (set α)) (nonempty : sets.nonempty) (inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype /-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩ -- For illustration purposes, the filter basis defining (at_top : filter ℕ) instance : inhabited (filter_basis ℕ) := ⟨{ sets := range Ici, nonempty := ⟨Ici 0, mem_range_self 0⟩, inter_sets := begin rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, refine ⟨Ici (max n m), mem_range_self _, _⟩, rintros p p_in, split ; rw mem_Ici at *, exact le_of_max_le_left p_in, exact le_of_max_le_right p_in, end }⟩ /-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/ protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop := (nonempty : ∃ i, p i) (inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j) namespace filter namespace is_basis /-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/ protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α := { sets := s '' set_of p, nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, mem_image_of_mem s hi⟩, inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩, rcases h.inter hi hj with ⟨k, hk, hk'⟩, exact ⟨_, mem_image_of_mem s hk, hk'⟩ } } variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s) lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U := iff.rfl end is_basis end filter namespace filter_basis /-- The filter associated to a filter basis. -/ protected def filter (B : filter_basis α) : filter α := { sets := {s | ∃ t ∈ B, t ⊆ s}, univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩, sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩, inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩, let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in ⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ } lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U := iff.rfl lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:= λ U_in, ⟨U, U_in, subset.refl _⟩ lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s := begin have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)), { rintros ⟨U, U_in⟩ ⟨V, V_in⟩, rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩, use [W, W_in], finish }, ext U, simp [mem_filter_iff, mem_infi this] end protected lemma generate (B : filter_basis α) : generate B.sets = B.filter := begin apply le_antisymm, { intros U U_in, rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩, exact generate_sets.superset (generate_sets.basic V_in) h }, { rw sets_iff_generate, apply mem_filter_of_mem } end end filter_basis namespace filter namespace is_basis variables {p : ι → Prop} {s : ι → set α} /-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/ protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter protected lemma mem_filter_iff (h : is_basis p s) {U : set α} : U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U := begin erw [h.filter_basis.mem_filter_iff], simp only [mem_filter_basis_iff h, exists_prop], split, { rintros ⟨_, ⟨i, pi, rfl⟩, h⟩, tauto }, { tauto } end lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} := by erw h.filter_basis.generate ; refl end is_basis /-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/ protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t) section same_type variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι} {p' : ι' → Prop} {s' : ι' → set α} {i' : ι'} lemma has_basis_generate (s : set (set α)) : (generate s).has_basis (λ t, finite t ∧ t ⊆ s) (λ t, ⋂₀ t) := ⟨begin intro U, rw mem_generate_iff, apply exists_congr, tauto end⟩ /-- The smallest filter basis containing a given collection of sets. -/ def filter_basis.of_sets (s : set (set α)) : filter_basis α := { sets := sInter '' { t | finite t ∧ t ⊆ s}, nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩, inter_sets := begin rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩, exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩, by rw sInter_union⟩, end } /-- Definition of `has_basis` unfolded with implicit set argument. -/ lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := hl.mem_iff' t lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i := let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, pi⟩ protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s := ⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩ lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := (hl.mem_iff).2 ⟨i, hi, ht⟩ lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l := hl.mem_of_superset hi $ subset.refl _ /-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/ noncomputable def has_basis.index (h : l.has_basis p s) (t : set α) (ht : t ∈ l) : {i : ι // p i} := ⟨(h.mem_iff.1 ht).some, (h.mem_iff.1 ht).some_spec.fst⟩ lemma has_basis.property_index (h : l.has_basis p s) (ht : t ∈ l) : p (h.index t ht) := (h.index t ht).2 lemma has_basis.set_index_mem (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l := h.mem_of_mem $ h.property_index _ lemma has_basis.set_index_subset (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t := (h.mem_iff.1 ht).some_spec.snd lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s := { nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, hi⟩, inter := λ i j hi hj, by simpa [h.mem_iff] using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) } lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l := by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] } lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } := by rw [← h.is_basis.filter_eq_generate, h.filter_eq] lemma generate_eq_generate_inter (s : set (set α)) : generate s = generate (sInter '' { t | finite t ∧ t ⊆ s}) := by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s := by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' := begin constructor, intro t, rw hl.mem_iff, split, { rintros ⟨i, pi, hi⟩, rcases h i pi with ⟨i', pi', hi'⟩, use [i', pi'], tauto }, { rintros ⟨i', pi', hi'⟩, rcases h' i' pi' with ⟨i, pi, hi⟩, use [i, pi], tauto }, end lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} : (∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x := by simpa using hl.mem_iff lemma has_basis.frequently_iff (hl : l.has_basis p s) {q : α → Prop} : (∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x := by simp [filter.frequently, hl.eventually_iff] lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) : (∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) := ⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩, λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩ lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) : (∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) := ⟨λ H i hi, H (s i) $ hl.mem_of_mem hi, λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩ lemma has_basis.ne_bot_iff (hl : l.has_basis p s) : ne_bot l ↔ (∀ {i}, p i → (s i).nonempty) := forall_sets_nonempty_iff_ne_bot.symm.trans $ hl.forall_iff $ λ _ _, nonempty.mono lemma has_basis.eq_bot_iff (hl : l.has_basis p s) : l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ := not_iff_not.1 $ hl.ne_bot_iff.trans $ by simp only [not_exists, not_and, ← ne_empty_iff_nonempty] lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id := ⟨λ t, exists_sets_subset_iff.symm⟩ lemma has_basis_self {l : filter α} {P : set α → Prop} : has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t, (t ∈ l ↔ ∃ r ∈ l, P r ∧ r ⊆ t) := by simp only [has_basis_iff, exists_prop, id, and_assoc] /-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that `p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/ lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop} (hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) : l.has_basis (λ i, p i ∧ q i) s := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩, rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩, rcases hq i hpi with ⟨j, hpj, hqj, hji⟩, exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩ end /-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}` is a basis of `l`. -/ lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) : l.has_basis (λ i, p i ∧ s i ⊆ V) s := h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem_sets hV (h.mem_of_mem hi))).imp $ λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩ lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id) {V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id := by simpa only [and_assoc] using h.restrict_subset hV theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l := ⟨λ h i' hi', h $ hl'.mem_of_mem hi', λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_sets_of_superset (h _ hi') hs⟩ theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t := by simp only [le_def, hl.mem_iff] theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' := by simp only [hl'.ge_iff, hl.mem_iff] lemma has_basis.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s') (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' := begin apply le_antisymm, { rw hl.le_basis_iff hl', simpa using h' }, { rw hl'.le_basis_iff hl, simpa using h }, end lemma has_basis.inf (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := ⟨begin intro t, simp only [mem_inf_sets, exists_prop, hl.mem_iff, hl'.mem_iff], split, { rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, H⟩, use [(i, i'), ⟨hi, hi'⟩, subset.trans (inter_subset_inter ht ht') H] }, { rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩, use [s i, i, hi, subset.refl _, s' i', i', hi', subset.refl _, H] } end⟩ lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) := ⟨λ U, by simp⟩ lemma has_basis.sup (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊔ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) := ⟨begin intros t, simp only [mem_sup_sets, hl.mem_iff, hl'.mem_iff, prod.exists, union_subset_iff, exists_prop, and_assoc, exists_and_distrib_left], simp only [← and_assoc, exists_and_distrib_right, and_comm] end⟩ lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) : (l ⊓ 𝓟 s').has_basis p (λ i, s i ∩ s') := ⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq, mem_inter_iff, and_imp]⟩ lemma has_basis.inf_basis_ne_bot_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃i'⦄ (hi' : p' i'), (s i ∩ s' i').nonempty := (hl.inf hl').ne_bot_iff.trans $ by simp [@forall_swap _ ι'] lemma has_basis.inf_ne_bot_iff (hl : l.has_basis p s) : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃s'⦄ (hs' : s' ∈ l'), (s i ∩ s').nonempty := hl.inf_basis_ne_bot_iff l'.basis_sets lemma has_basis.inf_principal_ne_bot_iff (hl : l.has_basis p s) {t : set α} : ne_bot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄ (hi : p i), (s i ∩ t).nonempty := (hl.inf_principal t).ne_bot_iff lemma inf_ne_bot_iff : ne_bot (l ⊓ l') ↔ ∀ ⦃s : set α⦄ (hs : s ∈ l) ⦃s'⦄ (hs' : s' ∈ l'), (s ∩ s').nonempty := l.basis_sets.inf_ne_bot_iff lemma inf_principal_ne_bot_iff {s : set α} : ne_bot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).nonempty := l.basis_sets.inf_principal_ne_bot_iff lemma inf_eq_bot_iff {f g : filter α} : f ⊓ g = ⊥ ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := not_iff_not.1 $ inf_ne_bot_iff.trans $ by simp [← ne_empty_iff_nonempty] protected lemma disjoint_iff {f g : filter α} : disjoint f g ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ := disjoint_iff.trans inf_eq_bot_iff lemma mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ := begin refine not_iff_not.1 (inf_principal_ne_bot_iff.trans _).symm, exact ⟨λ h hs, by simpa [empty_not_nonempty] using h s hs, λ hs t ht, inter_compl_nonempty_iff.2 $ λ hts, hs $ mem_sets_of_superset ht hts⟩, end lemma mem_iff_disjoint_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ disjoint f (𝓟 sᶜ) := mem_iff_inf_principal_compl.trans disjoint_iff.symm lemma le_iff_forall_disjoint_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, disjoint f (𝓟 Vᶜ) := forall_congr $ λ _, forall_congr $ λ _, mem_iff_disjoint_principal_compl lemma le_iff_forall_inf_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ := forall_congr $ λ _, forall_congr $ λ _, mem_iff_inf_principal_compl lemma inf_ne_bot_iff_frequently_left {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x := by simpa only [inf_ne_bot_iff, frequently_iff, exists_prop, and_comm] lemma inf_ne_bot_iff_frequently_right {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x := by { rw inf_comm, exact inf_ne_bot_iff_frequently_left } lemma has_basis.eq_binfi (h : l.has_basis p s) : l = ⨅ i (_ : p i), 𝓟 (s i) := eq_binfi_of_mem_sets_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal_sets] lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) : l = ⨅ i, 𝓟 (s i) := by simpa only [infi_true] using h.eq_binfi lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] : (⨅ i, 𝓟 (s i)).has_basis (λ _, true) s := ⟨begin refine λ t, (mem_infi (h.mono_comp _ _) t).trans $ by simp only [exists_prop, true_and, mem_principal_sets], exact λ _ _, principal_mono.2 end⟩ /-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis of `⨅ i, 𝓟 (s i)`. -/ lemma has_basis_infi_principal_finite (s : ι → set α) : (⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, finite t) (λ t, ⋂ i ∈ t, s i) := begin refine ⟨λ U, (mem_infi_finite _).trans _⟩, simp only [infi_principal_finset, mem_Union, mem_principal_sets, exists_prop, exists_finite_iff_finset, finset.set_bInter_coe] end lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S) (ne : S.nonempty) : (⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s := ⟨begin refine λ t, (mem_binfi _ ne).trans $ by simp only [mem_principal_sets], rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢, apply h.mono_comp _ _, exact λ _ _, principal_mono.2 end⟩ lemma has_basis_binfi_principal' (h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) : (⨅ i (h : p i), 𝓟 (s i)).has_basis p s := filter.has_basis_binfi_principal h ne lemma has_basis.map (f : α → β) (hl : l.has_basis p s) : (l.map f).has_basis p (λ i, f '' (s i)) := ⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩ lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) : (l.comap f).has_basis p (λ i, f ⁻¹' (s i)) := ⟨begin intro t, simp only [mem_comap_sets, exists_prop, hl.mem_iff], split, { rintros ⟨t', ⟨i, hi, ht'⟩, H⟩, exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ } end⟩ lemma comap_has_basis (f : α → β) (l : filter β) : has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) := ⟨λ t, mem_comap_sets⟩ lemma has_basis.prod_self (hl : l.has_basis p s) : (l ×ᶠ l).has_basis p (λ i, (s i).prod (s i)) := ⟨begin intro t, apply mem_prod_iff.trans, split, { rintros ⟨t₁, ht₁, t₂, ht₂, H⟩, rcases hl.mem_iff.1 (inter_mem_sets ht₁ ht₂) with ⟨i, hi, ht⟩, exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ }, { rintros ⟨i, hi, H⟩, exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ } end⟩ lemma mem_prod_self_iff {s} : s ∈ l ×ᶠ l ↔ ∃ t ∈ l, set.prod t t ⊆ s := l.basis_sets.prod_self.mem_iff lemma has_basis.sInter_sets (h : has_basis l p s) : ⋂₀ l.sets = ⋂ i ∈ set_of p, s i := begin ext x, suffices : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i, by simpa only [mem_Inter, mem_set_of_eq, mem_sInter], simp_rw h.mem_iff, split, { intros h i hi, exact h (s i) ⟨i, hi, subset.refl _⟩ }, { rintros h _ ⟨i, hi, sub⟩, exact sub (h i hi) }, end variables [preorder ι] (l p s) /-- `is_antimono_basis p s` means the image of `s` bounded by `p` is a filter basis such that `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure is_antimono_basis extends is_basis p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) /-- We say that a filter `l` has a antimono basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/ structure has_antimono_basis [preorder ι] (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i) (mono : monotone p) end same_type section two_types variables {la : filter α} {pa : ι → Prop} {sa : ι → set α} {lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β} lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) : tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl } lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := by simp only [tendsto, hlb.ge_iff, mem_map, filter.eventually] lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := by simp [hlb.tendsto_right_iff, hla.eventually_iff] lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) : ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t := hla.tendsto_left_iff.1 H lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) : ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i := hlb.tendsto_right_iff.1 H lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib := (hla.tendsto_iff hlb).1 H lemma has_basis.prod (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := (hla.comap prod.fst).inf (hlb.comap prod.snd) lemma has_basis.prod' {la : filter α} {lb : filter β} {ι : Type*} {p : ι → Prop} {sa : ι → set α} {sb : ι → set β} (hla : la.has_basis p sa) (hlb : lb.has_basis p sb) (h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) : (la ×ᶠ lb).has_basis p (λ i, (sa i).prod (sb i)) := ⟨begin intros t, rw mem_prod_iff, split, { rintros ⟨u, u_in, v, v_in, huv⟩, rcases hla.mem_iff.mp u_in with ⟨i, hi, si⟩, rcases hlb.mem_iff.mp v_in with ⟨j, hj, sj⟩, rcases h_dir hi hj with ⟨k, hk, ki, kj⟩, use [k, hk], calc (sa k).prod (sb k) ⊆ (sa i).prod (sb j) : set.prod_mono ki kj ... ⊆ u.prod v : set.prod_mono si sj ... ⊆ t : huv, }, { rintro ⟨i, hi, h⟩, exact ⟨sa i, hla.mem_of_mem hi, sb i, hlb.mem_of_mem hi, h⟩ }, end⟩ end two_types /-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/ def is_countably_generated (f : filter α) : Prop := ∃ s : set (set α), countable s ∧ f = generate s /-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/ structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop := (countable : countable $ set_of p) /-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`, if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set defined by `p` is countable. -/ structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (countable : countable $ set_of p) /-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure countable_filter_basis (α : Type*) extends filter_basis α := (countable : countable sets) -- For illustration purposes, the countable filter basis defining (at_top : filter ℕ) instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) := ⟨{ countable := countable_range (λ n, Ici n), ..(default $ filter_basis ℕ),}⟩ lemma antimono_seq_of_seq (s : ℕ → set α) : ∃ t : ℕ → set α, (∀ i j, i ≤ j → t j ⊆ t i) ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) := begin use λ n, ⋂ m ≤ n, s m, split, { exact λ i j hij, bInter_mono' (Iic_subset_Iic.2 hij) (λ n hn, subset.refl _) }, apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, refine (bInter_mem_sets (finite_le_nat _)).2 (λ j hji, _), rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl }, end lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : countable B) (Bne : B.nonempty) (f : ι → α) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin rw countable_iff_exists_surjective_to_subtype Bne at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_refl _ }, { intros a, rcases gsurj a with ⟨i, rfl⟩, apply infi_le } end lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : countable B) (f : ι → α) {i₀ : ι} (h : f i₀ = ⊤) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin cases B.eq_empty_or_nonempty with hB Bnonempty, { rw [hB, infi_emptyset], use λ n, i₀, simp [h] }, { exact countable_binfi_eq_infi_seq Bcbl Bnonempty f } end lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : countable B) : ∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) := countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ namespace is_countably_generated /-- A set generating a countably generated filter. -/ def generating_set {f : filter α} (h : is_countably_generated f) := classical.some h lemma countable_generating_set {f : filter α} (h : is_countably_generated f) : countable h.generating_set := (classical.some_spec h).1 lemma eq_generate {f : filter α} (h : is_countably_generated f) : f = generate h.generating_set := (classical.some_spec h).2 /-- A countable filter basis for a countably generated filter. -/ def countable_filter_basis {l : filter α} (h : is_countably_generated l) : countable_filter_basis α := { countable := (countable_set_of_finite_subset h.countable_generating_set).image _, ..filter_basis.of_sets (h.generating_set) } lemma filter_basis_filter {l : filter α} (h : is_countably_generated l) : h.countable_filter_basis.to_filter_basis.filter = l := begin conv_rhs { rw h.eq_generate }, apply of_sets_filter_eq_generate, end lemma has_countable_basis {l : filter α} (h : is_countably_generated l) : l.has_countable_basis (λ t, finite t ∧ t ⊆ h.generating_set) (λ t, ⋂₀ t) := ⟨by convert has_basis_generate _ ; exact h.eq_generate, countable_set_of_finite_subset h.countable_generating_set⟩ lemma exists_countable_infi_principal {f : filter α} (h : f.is_countably_generated) : ∃ s : set (set α), countable s ∧ f = ⨅ t ∈ s, 𝓟 t := begin let B := h.countable_filter_basis, use [B.sets, B.countable], rw ← h.filter_basis_filter, rw B.to_filter_basis.eq_infi_principal, rw infi_subtype'' end lemma exists_seq {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i) := begin rcases cblb.exists_countable_infi_principal with ⟨B, Bcbl, rfl⟩, exact countable_binfi_principal_eq_seq_infi Bcbl, end /-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which forms a basis of `f`-/ lemma exists_antimono_subbasis {f : filter α} (cblb : f.is_countably_generated) {p : ι → Prop} {s : ι → set α} (hs : f.has_basis p s) : ∃ x : ℕ → ι, (∀ i, p (x i)) ∧ f.has_antimono_basis (λ _, true) (λ i, s (x i)) := begin rcases cblb.exists_seq with ⟨x', hx'⟩, have : ∀ i, x' i ∈ f := λ i, hx'.symm ▸ (infi_le (λ i, 𝓟 (x' i)) i) (mem_principal_self _), let x : ℕ → {i : ι // p i} := λ n, nat.rec_on n (hs.index _ $ this 0) (λ n xn, (hs.index _ $ inter_mem_sets (this $ n + 1) (hs.mem_of_mem xn.coe_prop))), have x_mono : ∀ n : ℕ, s (x n.succ) ⊆ s (x n) := λ n, subset.trans (hs.set_index_subset _) (inter_subset_right _ _), replace x_mono : ∀ ⦃i j⦄, i ≤ j → s (x j) ≤ s (x i), { refine @monotone_of_monotone_nat (order_dual $ set α) _ _ _, exact x_mono }, have x_subset : ∀ i, s (x i) ⊆ x' i, { rintro (_|i), exacts [hs.set_index_subset _, subset.trans (hs.set_index_subset _) (inter_subset_left _ _)] }, refine ⟨λ i, x i, λ i, (x i).2, _⟩, have : (⨅ i, 𝓟 (s (x i))).has_antimono_basis (λ _, true) (λ i, s (x i)) := ⟨has_basis_infi_principal (directed_of_sup x_mono), λ i j _ _ hij, x_mono hij, monotone_const⟩, convert this, exact le_antisymm (le_infi $ λ i, le_principal_iff.2 $ by cases i; apply hs.set_index_mem) (hx'.symm ▸ le_infi (λ i, le_principal_iff.2 $ this.to_has_basis.mem_iff.2 ⟨i, trivial, x_subset i⟩)) end /-- A countably generated filter admits a basis formed by a monotonically decreasing sequence of sets. -/ lemma exists_antimono_basis {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x := let ⟨x, hxf, hx⟩ := cblb.exists_antimono_subbasis f.basis_sets in ⟨x, hx⟩ end is_countably_generated lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α} (h : f.has_countable_basis p s) : f.is_countably_generated := ⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩ lemma is_countably_generated_seq (x : ℕ → set α) : is_countably_generated (⨅ i, 𝓟 $ x i) := begin rcases antimono_seq_of_seq x with ⟨y, am, h⟩, rw h, use [range y, countable_range _], rw (has_basis_infi_principal _).eq_generate, { simp [range] }, { exact directed_of_sup am }, { use 0 }, end lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) : f.is_countably_generated := let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq lemma is_countably_generated_binfi_principal {B : set $ set α} (h : countable B) : is_countably_generated (⨅ (s ∈ B), 𝓟 s) := is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h) lemma is_countably_generated_iff_exists_antimono_basis {f : filter α} : is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x := begin split, { exact λ h, h.exists_antimono_basis }, { rintros ⟨x, h⟩, rw h.to_has_basis.eq_infi, exact is_countably_generated_seq x }, end lemma is_countably_generated_principal (s : set α) : is_countably_generated (𝓟 s) := begin rw show 𝓟 s = ⨅ i : ℕ, 𝓟 s, by simp, apply is_countably_generated_seq end namespace is_countably_generated lemma inf {f g : filter α} (hf : is_countably_generated f) (hg : is_countably_generated g) : is_countably_generated (f ⊓ g) := begin rw is_countably_generated_iff_exists_antimono_basis at hf hg, rcases hf with ⟨s, hs⟩, rcases hg with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.inf ht.to_has_basis, set.countable_encodable _⟩ end lemma inf_principal {f : filter α} (h : is_countably_generated f) (s : set α) : is_countably_generated (f ⊓ 𝓟 s) := h.inf (filter.is_countably_generated_principal s) lemma exists_antimono_seq' {f : filter α} (cblb : f.is_countably_generated) : ∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) := let ⟨x, hx⟩ := is_countably_generated_iff_exists_antimono_basis.mp cblb in ⟨x, λ i j, hx.decreasing trivial trivial, λ s, by simp [hx.to_has_basis.mem_iff]⟩ protected lemma comap {l : filter β} (h : l.is_countably_generated) (f : α → β) : (comap f l).is_countably_generated := let ⟨x, hx_mono⟩ := h.exists_antimono_basis in is_countably_generated_of_seq ⟨_, (hx_mono.to_has_basis.comap _).eq_infi⟩ end is_countably_generated end filter
d9aed529004c836e0d26f56ad26ee7529af55cba
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/path_category.lean
6623c1350a54dbf0279af922dbef37db4a0d36c1
[ "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
2,534
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.eq_to_hom import combinatorics.quiver.path /-! # The category paths on a quiver. -/ universes v₁ v₂ u₁ u₂ namespace category_theory section /-- A type synonym for the category of paths in a quiver. -/ def paths (V : Type u₁) : Type u₁ := V instance (V : Type u₁) [inhabited V] : inhabited (paths V) := ⟨(default : V)⟩ variables (V : Type u₁) [quiver.{v₁+1} V] namespace paths instance category_paths : category.{max u₁ v₁} (paths V) := { hom := λ (X Y : V), quiver.path X Y, id := λ X, quiver.path.nil, comp := λ X Y Z f g, quiver.path.comp f g, } variables {V} /-- The inclusion of a quiver `V` into its path category, as a prefunctor. -/ @[simps] def of : prefunctor V (paths V) := { obj := λ X, X, map := λ X Y f, f.to_path, } local attribute [ext] functor.ext /-- Two functors out of a path category are equal when they agree on singleton paths. -/ @[ext] lemma ext_functor {C} [category C] {F G : paths V ⥤ C} (h_obj : F.obj = G.obj) (h : ∀ (a b : V) (e : a ⟶ b), F.map e.to_path = eq_to_hom (congr_fun h_obj a) ≫ G.map e.to_path ≫ eq_to_hom (congr_fun h_obj.symm b)) : F = G := begin ext X Y f, { induction f with Y' Z' g e ih, { erw [F.map_id, G.map_id, category.id_comp, eq_to_hom_trans, eq_to_hom_refl], }, { erw [F.map_comp g e.to_path, G.map_comp g e.to_path, ih, h], simp only [category.id_comp, eq_to_hom_refl, eq_to_hom_trans_assoc, category.assoc], }, }, { intro X, rw h_obj, } end end paths variables (W : Type u₂) [quiver.{v₂+1} W] -- A restatement of `prefunctor.map_path_comp` using `f ≫ g` instead of `f.comp g`. @[simp] lemma prefunctor.map_path_comp' (F : prefunctor V W) {X Y Z : paths V} (f : X ⟶ Y) (g : Y ⟶ Z) : F.map_path (f ≫ g) = (F.map_path f).comp (F.map_path g) := prefunctor.map_path_comp _ _ _ end section variables {C : Type u₁} [category.{v₁} C] open quiver /-- A path in a category can be composed to a single morphism. -/ @[simp] def compose_path {X : C} : Π {Y : C} (p : path X Y), X ⟶ Y | _ path.nil := 𝟙 X | _ (path.cons p e) := compose_path p ≫ e @[simp] lemma compose_path_comp {X Y Z : C} (f : path X Y) (g : path Y Z) : compose_path (f.comp g) = compose_path f ≫ compose_path g := begin induction g with Y' Z' g e ih, { simp, }, { simp [ih], }, end end end category_theory
e07c822a5b0019720d423337f35bbb3815466425
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/hott/delta_issue2.hlean
47b6fbe4b56848958133465373db7d9319c88b24
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
704
hlean
open nat eq theorem add_assoc₁ : Π (a b c : ℕ), (a + b) + c = a + (b + c) | a b 0 := eq.refl (nat.rec a (λ x, succ) b) | a b (succ n) := calc (a + b) + (succ n) = succ ((a + b) + n) : rfl ... = succ (a + (b + n)) : ap succ (add_assoc₁ a b n) ... = a + (succ (b + n)) : rfl ... = a + (b + (succ n)) : rfl theorem add_assoc₂ : Π (a b c : ℕ), (a + b) + c = a + (b + c) | a b 0 := eq.refl (nat.rec a (λ x, succ) b) | a b (succ n) := ap succ (add_assoc₂ a b n) theorem add_assoc₃ : Π (a b c : ℕ), (a + b) + c = a + (b + c) | a b nat.zero := eq.refl (nat.add a b) | a b (succ n) := ap succ (add_assoc₃ a b n)
be902b37908232647ea50394ac90116d3ad28ebb
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/macroStack.lean
aab0b96cfd7f67dbaf105a9c88c7f5887d0c57b2
[ "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
307
lean
-- def f1 := if h:x then 1 else 0 set_option pp.macroStack true def f2 := if h:(x > 0) then 1 else 0 def x := <- get macro "foo!" x:term:max : term => `(let x := "hello"; $x + x) macro "bla!" x:term:max : term => `(fun (x : Nat) => if foo! ($x + x) < 1 then true else false) def f (x : Nat) := bla! x
6371150e4a2f271421d21c0d049857fa805e4305
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/real/golden_ratio.lean
dbb1e6f021a0c702227979519552311991c79e82
[ "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
5,572
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Alexey Soloyev, Junyan Xu -/ import data.real.irrational import data.nat.fib import data.fin.vec_notation import tactic.ring_exp import algebra.linear_recurrence /-! # The golden ratio and its conjugate This file defines the golden ratio `φ := (1 + √5)/2` and its conjugate `ψ := (1 - √5)/2`, which are the two real roots of `X² - X - 1`. Along with various computational facts about them, we prove their irrationality, and we link them to the Fibonacci sequence by proving Binet's formula. -/ noncomputable theory /-- The golden ratio `φ := (1 + √5)/2`. -/ @[reducible] def golden_ratio := (1 + real.sqrt 5)/2 /-- The conjugate of the golden ratio `ψ := (1 - √5)/2`. -/ @[reducible] def golden_conj := (1 - real.sqrt 5)/2 localized "notation `φ` := golden_ratio" in real localized "notation `ψ` := golden_conj" in real /-- The inverse of the golden ratio is the opposite of its conjugate. -/ lemma inv_gold : φ⁻¹ = -ψ := begin have : 1 + real.sqrt 5 ≠ 0, from ne_of_gt (add_pos (by norm_num) $ real.sqrt_pos.mpr (by norm_num)), field_simp [sub_mul, mul_add], norm_num end /-- The opposite of the golden ratio is the inverse of its conjugate. -/ lemma inv_gold_conj : ψ⁻¹ = -φ := begin rw [inv_eq_iff, ← neg_inv, neg_eq_iff_neg_eq], exact inv_gold.symm, end @[simp] lemma gold_mul_gold_conj : φ * ψ = -1 := by {field_simp, rw ← sq_sub_sq, norm_num} @[simp] lemma gold_conj_mul_gold : ψ * φ = -1 := by {rw mul_comm, exact gold_mul_gold_conj} @[simp] lemma gold_add_gold_conj : φ + ψ = 1 := by {rw [golden_ratio, golden_conj], ring} lemma one_sub_gold_conj : 1 - φ = ψ := by linarith [gold_add_gold_conj] lemma one_sub_gold : 1 - ψ = φ := by linarith [gold_add_gold_conj] @[simp] lemma gold_sub_gold_conj : φ - ψ = real.sqrt 5 := by {rw [golden_ratio, golden_conj], ring} @[simp] lemma gold_sq : φ^2 = φ + 1 := begin rw [golden_ratio, ←sub_eq_zero], ring_exp, rw real.sq_sqrt; norm_num, end @[simp] lemma gold_conj_sq : ψ^2 = ψ + 1 := begin rw [golden_conj, ←sub_eq_zero], ring_exp, rw real.sq_sqrt; norm_num, end lemma gold_pos : 0 < φ := mul_pos (by apply add_pos; norm_num) $ inv_pos.2 zero_lt_two lemma gold_ne_zero : φ ≠ 0 := ne_of_gt gold_pos lemma one_lt_gold : 1 < φ := begin refine lt_of_mul_lt_mul_left _ (le_of_lt gold_pos), simp [← sq, gold_pos, zero_lt_one] end lemma gold_conj_neg : ψ < 0 := by linarith [one_sub_gold_conj, one_lt_gold] lemma gold_conj_ne_zero : ψ ≠ 0 := ne_of_lt gold_conj_neg lemma neg_one_lt_gold_conj : -1 < ψ := begin rw [neg_lt, ← inv_gold], exact inv_lt_one one_lt_gold, end /-! ## Irrationality -/ /-- The golden ratio is irrational. -/ theorem gold_irrational : irrational φ := begin have := nat.prime.irrational_sqrt (show nat.prime 5, by norm_num), have := this.rat_add 1, have := this.rat_mul (show (0.5 : ℚ) ≠ 0, by norm_num), convert this, field_simp end /-- The conjugate of the golden ratio is irrational. -/ theorem gold_conj_irrational : irrational ψ := begin have := nat.prime.irrational_sqrt (show nat.prime 5, by norm_num), have := this.rat_sub 1, have := this.rat_mul (show (0.5 : ℚ) ≠ 0, by norm_num), convert this, field_simp end /-! ## Links with Fibonacci sequence -/ section fibrec variables {α : Type*} [comm_semiring α] /-- The recurrence relation satisfied by the Fibonacci sequence. -/ def fib_rec : linear_recurrence α := { order := 2, coeffs := ![1, 1]} section poly open polynomial /-- The characteristic polynomial of `fib_rec` is `X² - (X + 1)`. -/ lemma fib_rec_char_poly_eq {β : Type*} [comm_ring β] : fib_rec.char_poly = X^2 - (X + (1 : polynomial β)) := begin rw [fib_rec, linear_recurrence.char_poly], simp [finset.sum_fin_eq_sum_range, finset.sum_range_succ', monomial_eq_smul_X] end end poly /-- As expected, the Fibonacci sequence is a solution of `fib_rec`. -/ lemma fib_is_sol_fib_rec : fib_rec.is_solution (λ x, x.fib : ℕ → α) := begin rw fib_rec, intros n, simp only, rw [nat.fib_add_two, add_comm], simp [finset.sum_fin_eq_sum_range, finset.sum_range_succ'], end /-- The geometric sequence `λ n, φ^n` is a solution of `fib_rec`. -/ lemma geom_gold_is_sol_fib_rec : fib_rec.is_solution (pow φ) := begin rw [fib_rec.geom_sol_iff_root_char_poly, fib_rec_char_poly_eq], simp [sub_eq_zero] end /-- The geometric sequence `λ n, ψ^n` is a solution of `fib_rec`. -/ lemma geom_gold_conj_is_sol_fib_rec : fib_rec.is_solution (pow ψ) := begin rw [fib_rec.geom_sol_iff_root_char_poly, fib_rec_char_poly_eq], simp [sub_eq_zero] end end fibrec /-- Binet's formula as a function equality. -/ theorem real.coe_fib_eq' : (λ n, nat.fib n : ℕ → ℝ) = λ n, (φ^n - ψ^n) / real.sqrt 5 := begin rw fib_rec.sol_eq_of_eq_init, { intros i hi, fin_cases hi, { simp }, { simp only [golden_ratio, golden_conj], ring_exp, rw mul_inv_cancel; norm_num } }, { exact fib_is_sol_fib_rec }, { ring_nf, exact (@fib_rec ℝ _).sol_space.sub_mem (submodule.smul_mem fib_rec.sol_space (real.sqrt 5)⁻¹ geom_gold_is_sol_fib_rec) (submodule.smul_mem fib_rec.sol_space (real.sqrt 5)⁻¹ geom_gold_conj_is_sol_fib_rec) } end /-- Binet's formula as a dependent equality. -/ theorem real.coe_fib_eq : ∀ n, (nat.fib n : ℝ) = (φ^n - ψ^n) / real.sqrt 5 := by rw [← function.funext_iff, real.coe_fib_eq']