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
5f66f145dd85fd38f1e090d9a757869b0507eb5f
367134ba5a65885e863bdc4507601606690974c1
/src/data/nat/upto.lean
bc1abd3632f9a0415b06873cc5b9db48ff6b8cbf
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
2,375
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import data.nat.basic /-! # `nat.upto` `nat.upto p`, with `p` a predicate on `ℕ`, is a subtype of elements `n : ℕ` such that no value (strictly) below `n` satisfies `p`. This type has the property that `>` is well-founded when `∃ i, p i`, which allows us to implement searches on `ℕ`, starting at `0` and with an unknown upper-bound. It is similar to the well founded relation constructed to define `nat.find` with the difference that, in `nat.upto p`, `p` does not need to be decidable. In fact, `nat.find` could be slightly altered to factor decidability out of its well founded relation and would then fulfill the same purpose as this file. -/ namespace nat /-- The subtype of natural numbers `i` which have the property that no `j` less than `i` satisfies `p`. This is an initial segment of the natural numbers, up to and including the first value satisfying `p`. We will be particularly interested in the case where there exists a value satisfying `p`, because in this case the `>` relation is well-founded. -/ @[reducible] def upto (p : ℕ → Prop) : Type := {i : ℕ // ∀ j < i, ¬ p j} namespace upto variable {p : ℕ → Prop} /-- Lift the "greater than" relation on natural numbers to `nat.upto`. -/ protected def gt (p) (x y : upto p) : Prop := x.1 > y.1 instance : has_lt (upto p) := ⟨λ x y, x.1 < y.1⟩ /-- The "greater than" relation on `upto p` is well founded if (and only if) there exists a value satisfying `p`. -/ protected lemma wf : (∃ x, p x) → well_founded (upto.gt p) | ⟨x, h⟩ := begin suffices : upto.gt p = measure (λ y : nat.upto p, x - y.val), { rw this, apply measure_wf }, ext ⟨a, ha⟩ ⟨b, _⟩, dsimp [measure, inv_image, upto.gt], rw nat.sub_lt_sub_left_iff, exact le_of_not_lt (λ h', ha _ h' h), end /-- Zero is always a member of `nat.upto p` because it has no predecessors. -/ def zero : nat.upto p := ⟨0, λ j h, false.elim (nat.not_lt_zero _ h)⟩ /-- The successor of `n` is in `nat.upto p` provided that `n` doesn't satisfy `p`. -/ def succ (x : nat.upto p) (h : ¬ p x.val) : nat.upto p := ⟨x.val.succ, λ j h', begin rcases nat.lt_succ_iff_lt_or_eq.1 h' with h' | rfl; [exact x.2 _ h', exact h] end⟩ end upto end nat
2f30b8d76aca246f31dfd05d54a5fed447a32063
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/library/data/nat/basic.lean
1b0d870399de09918bb1a16d5efe0bbc8340c847
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,395
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.nat.basic Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad Basic operations on the natural numbers. -/ import logic.connectives data.num algebra.binary algebra.ring open binary eq.ops namespace nat /- a variant of add, defined by recursion on the first argument -/ definition addl (x y : ℕ) : ℕ := nat.rec y (λ n r, succ r) x infix `⊕`:65 := addl theorem addl.succ_right (n m : ℕ) : n ⊕ succ m = succ (n ⊕ m) := nat.induction_on n rfl (λ n₁ ih, calc succ n₁ ⊕ succ m = succ (n₁ ⊕ succ m) : rfl ... = succ (succ (n₁ ⊕ m)) : ih ... = succ (succ n₁ ⊕ m) : rfl) theorem add_eq_addl (x : ℕ) : ∀y, x + y = x ⊕ y := nat.induction_on x (λ y, nat.induction_on y rfl (λ y₁ ih, calc zero + succ y₁ = succ (zero + y₁) : rfl ... = succ (zero ⊕ y₁) : {ih} ... = zero ⊕ (succ y₁) : rfl)) (λ x₁ ih₁ y, nat.induction_on y (calc succ x₁ + zero = succ (x₁ + zero) : rfl ... = succ (x₁ ⊕ zero) : {ih₁ zero} ... = succ x₁ ⊕ zero : rfl) (λ y₁ ih₂, calc succ x₁ + succ y₁ = succ (succ x₁ + y₁) : rfl ... = succ (succ x₁ ⊕ y₁) : {ih₂} ... = succ x₁ ⊕ succ y₁ : addl.succ_right)) /- successor and predecessor -/ theorem succ_ne_zero (n : ℕ) : succ n ≠ 0 := assume H, nat.no_confusion H -- add_rewrite succ_ne_zero theorem pred_zero : pred 0 = 0 := rfl theorem pred_succ (n : ℕ) : pred (succ n) = n := rfl theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) := nat.induction_on n (or.inl rfl) (take m IH, or.inr (show succ m = succ (pred (succ m)), from congr_arg succ !pred_succ⁻¹)) theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k := exists.intro _ (or_resolve_right !eq_zero_or_eq_succ_pred H) theorem succ.inj {n m : ℕ} (H : succ n = succ m) : n = m := nat.no_confusion H (λe, e) theorem succ.ne_self {n : ℕ} : succ n ≠ n := nat.induction_on n (take H : 1 = 0, have ne : 1 ≠ 0, from !succ_ne_zero, absurd H ne) (take k IH H, IH (succ.inj H)) theorem discriminate {B : Prop} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B := have H : n = n → B, from nat.cases_on n H1 H2, H rfl theorem two_step_induction_on {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a := have stronger : P a ∧ P (succ a), from nat.induction_on a (and.intro H1 H2) (take k IH, have IH1 : P k, from and.elim_left IH, have IH2 : P (succ k), from and.elim_right IH, and.intro IH2 (H3 k IH1 IH2)), and.elim_left stronger theorem sub_induction {P : ℕ → ℕ → Prop} (n m : ℕ) (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : P n m := have general : ∀m, P n m, from nat.induction_on n (take m : ℕ, H1 m) (take k : ℕ, assume IH : ∀m, P k m, take m : ℕ, nat.cases_on m (H2 k) (take l, (H3 k l (IH l)))), general m /- addition -/ theorem add_zero (n : ℕ) : n + 0 = n := rfl theorem add_succ (n m : ℕ) : n + succ m = succ (n + m) := rfl theorem zero_add (n : ℕ) : 0 + n = n := nat.induction_on n !add_zero (take m IH, show 0 + succ m = succ m, from calc 0 + succ m = succ (0 + m) : add_succ ... = succ m : IH) theorem add.succ_left (n m : ℕ) : (succ n) + m = succ (n + m) := nat.induction_on m (!add_zero ▸ !add_zero) (take k IH, calc succ n + succ k = succ (succ n + k) : add_succ ... = succ (succ (n + k)) : IH ... = succ (n + succ k) : add_succ) theorem add.comm (n m : ℕ) : n + m = m + n := nat.induction_on m (!add_zero ⬝ !zero_add⁻¹) (take k IH, calc n + succ k = succ (n+k) : add_succ ... = succ (k + n) : IH ... = succ k + n : add.succ_left) theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := !add.succ_left ⬝ !add_succ⁻¹ theorem add.assoc (n m k : ℕ) : (n + m) + k = n + (m + k) := nat.induction_on k (!add_zero ▸ !add_zero) (take l IH, calc (n + m) + succ l = succ ((n + m) + l) : add_succ ... = succ (n + (m + l)) : IH ... = n + succ (m + l) : add_succ ... = n + (m + succ l) : add_succ) theorem add.left_comm (n m k : ℕ) : n + (m + k) = m + (n + k) := left_comm add.comm add.assoc n m k theorem add.right_comm (n m k : ℕ) : n + m + k = n + k + m := right_comm add.comm add.assoc n m k theorem add.cancel_left {n m k : ℕ} : n + m = n + k → m = k := nat.induction_on n (take H : 0 + m = 0 + k, !zero_add⁻¹ ⬝ H ⬝ !zero_add) (take (n : ℕ) (IH : n + m = n + k → m = k) (H : succ n + m = succ n + k), have H2 : succ (n + m) = succ (n + k), from calc succ (n + m) = succ n + m : add.succ_left ... = succ n + k : H ... = succ (n + k) : add.succ_left, have H3 : n + m = n + k, from succ.inj H2, IH H3) theorem add.cancel_right {n m k : ℕ} (H : n + m = k + m) : n = k := have H2 : m + n = m + k, from !add.comm ⬝ H ⬝ !add.comm, add.cancel_left H2 theorem eq_zero_of_add_eq_zero_right {n m : ℕ} : n + m = 0 → n = 0 := nat.induction_on n (take (H : 0 + m = 0), rfl) (take k IH, assume H : succ k + m = 0, absurd (show succ (k + m) = 0, from calc succ (k + m) = succ k + m : add.succ_left ... = 0 : H) !succ_ne_zero) theorem eq_zero_of_add_eq_zero_left {n m : ℕ} (H : n + m = 0) : m = 0 := eq_zero_of_add_eq_zero_right (!add.comm ⬝ H) theorem add.eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 := and.intro (eq_zero_of_add_eq_zero_right H) (eq_zero_of_add_eq_zero_left H) theorem add_one (n : ℕ) : n + 1 = succ n := !add_zero ▸ !add_succ theorem one_add (n : ℕ) : 1 + n = succ n := !zero_add ▸ !add.succ_left /- multiplication -/ theorem mul_zero (n : ℕ) : n * 0 = 0 := rfl theorem mul_succ (n m : ℕ) : n * succ m = n * m + n := rfl -- commutativity, distributivity, associativity, identity theorem zero_mul (n : ℕ) : 0 * n = 0 := nat.induction_on n !mul_zero (take m IH, !mul_succ ⬝ !add_zero ⬝ IH) theorem succ_mul (n m : ℕ) : (succ n) * m = (n * m) + m := nat.induction_on m (!mul_zero ⬝ !mul_zero⁻¹ ⬝ !add_zero⁻¹) (take k IH, calc succ n * succ k = succ n * k + succ n : mul_succ ... = n * k + k + succ n : IH ... = n * k + (k + succ n) : add.assoc ... = n * k + (succ n + k) : add.comm ... = n * k + (n + succ k) : succ_add_eq_succ_add ... = n * k + n + succ k : add.assoc ... = n * succ k + succ k : mul_succ) theorem mul.comm (n m : ℕ) : n * m = m * n := nat.induction_on m (!mul_zero ⬝ !zero_mul⁻¹) (take k IH, calc n * succ k = n * k + n : mul_succ ... = k * n + n : IH ... = (succ k) * n : succ_mul) theorem mul.right_distrib (n m k : ℕ) : (n + m) * k = n * k + m * k := nat.induction_on k (calc (n + m) * 0 = 0 : mul_zero ... = 0 + 0 : add_zero ... = n * 0 + 0 : mul_zero ... = n * 0 + m * 0 : mul_zero) (take l IH, calc (n + m) * succ l = (n + m) * l + (n + m) : mul_succ ... = n * l + m * l + (n + m) : IH ... = n * l + m * l + n + m : add.assoc ... = n * l + n + m * l + m : add.right_comm ... = n * l + n + (m * l + m) : add.assoc ... = n * succ l + (m * l + m) : mul_succ ... = n * succ l + m * succ l : mul_succ) theorem mul.left_distrib (n m k : ℕ) : n * (m + k) = n * m + n * k := calc n * (m + k) = (m + k) * n : mul.comm ... = m * n + k * n : mul.right_distrib ... = n * m + k * n : mul.comm ... = n * m + n * k : mul.comm theorem mul.assoc (n m k : ℕ) : (n * m) * k = n * (m * k) := nat.induction_on k (calc (n * m) * 0 = n * (m * 0) : mul_zero) (take l IH, calc (n * m) * succ l = (n * m) * l + n * m : mul_succ ... = n * (m * l) + n * m : IH ... = n * (m * l + m) : mul.left_distrib ... = n * (m * succ l) : mul_succ) theorem mul_one (n : ℕ) : n * 1 = n := calc n * 1 = n * 0 + n : mul_succ ... = 0 + n : mul_zero ... = n : zero_add theorem one_mul (n : ℕ) : 1 * n = n := calc 1 * n = n * 1 : mul.comm ... = n : mul_one theorem eq_zero_or_eq_zero_of_mul_eq_zero {n m : ℕ} : n * m = 0 → n = 0 ∨ m = 0 := nat.cases_on n (assume H, or.inl rfl) (take n', nat.cases_on m (assume H, or.inr rfl) (take m', assume H : succ n' * succ m' = 0, absurd ((calc 0 = succ n' * succ m' : H ... = succ n' * m' + succ n' : mul_succ ... = succ (succ n' * m' + n') : add_succ)⁻¹) !succ_ne_zero)) section open [classes] algebra protected definition comm_semiring [instance] [reducible] : algebra.comm_semiring nat := ⦃algebra.comm_semiring, add := add, add_assoc := add.assoc, zero := zero, zero_add := zero_add, add_zero := add_zero, add_comm := add.comm, mul := mul, mul_assoc := mul.assoc, one := succ zero, one_mul := one_mul, mul_one := mul_one, left_distrib := mul.left_distrib, right_distrib := mul.right_distrib, zero_mul := zero_mul, mul_zero := mul_zero, mul_comm := mul.comm⦄ end section port_algebra theorem mul.left_comm : ∀a b c : ℕ, a * (b * c) = b * (a * c) := algebra.mul.left_comm theorem mul.right_comm : ∀a b c : ℕ, (a * b) * c = (a * c) * b := algebra.mul.right_comm definition dvd (a b : ℕ) : Prop := algebra.dvd a b notation (a | b) := dvd a b theorem dvd.intro : ∀{a b c : ℕ} (H : a * c = b), (a | b) := @algebra.dvd.intro _ _ theorem dvd.intro_left : ∀{a b c : ℕ} (H : c * a = b), (a | b) := @algebra.dvd.intro_left _ _ theorem exists_eq_mul_right_of_dvd : ∀{a b : ℕ} (H : (a | b)), ∃c, b = a * c := @algebra.exists_eq_mul_right_of_dvd _ _ theorem dvd.elim : ∀{P : Prop} {a b : ℕ} (H₁ : (a | b)) (H₂ : ∀c, b = a * c → P), P := @algebra.dvd.elim _ _ theorem exists_eq_mul_left_of_dvd : ∀{a b : ℕ} (H : (a | b)), ∃c, b = c * a := @algebra.exists_eq_mul_left_of_dvd _ _ theorem dvd.elim_left : ∀{P : Prop} {a b : ℕ} (H₁ : (a | b)) (H₂ : ∀c, b = c * a → P), P := @algebra.dvd.elim_left _ _ theorem dvd.refl : ∀a : ℕ, (a | a) := algebra.dvd.refl theorem dvd.trans : ∀{a b c : ℕ} (H₁ : (a | b)) (H₂ : (b | c)), (a | c) := @algebra.dvd.trans _ _ theorem eq_zero_of_zero_dvd : ∀{a : ℕ} (H : (0 | a)), a = 0 := @algebra.eq_zero_of_zero_dvd _ _ theorem dvd_zero : ∀a : ℕ, (a | 0) := algebra.dvd_zero theorem one_dvd : ∀a : ℕ, (1 | a) := algebra.one_dvd theorem dvd_mul_right : ∀a b : ℕ, (a | a * b) := algebra.dvd_mul_right theorem dvd_mul_left : ∀a b : ℕ, (a | b * a) := algebra.dvd_mul_left theorem dvd_mul_of_dvd_left : ∀{a b : ℕ} (H : (a | b)) (c : ℕ), (a | b * c) := @algebra.dvd_mul_of_dvd_left _ _ theorem dvd_mul_of_dvd_right : ∀{a b : ℕ} (H : (a | b)) (c : ℕ), (a | c * b) := @algebra.dvd_mul_of_dvd_right _ _ theorem mul_dvd_mul : ∀{a b c d : ℕ}, (a | b) → (c | d) → (a * c | b * d) := @algebra.mul_dvd_mul _ _ theorem dvd_of_mul_right_dvd : ∀{a b c : ℕ}, (a * b | c) → (a | c) := @algebra.dvd_of_mul_right_dvd _ _ theorem dvd_of_mul_left_dvd : ∀{a b c : ℕ}, (a * b | c) → (b | c) := @algebra.dvd_of_mul_left_dvd _ _ theorem dvd_add : ∀{a b c : ℕ}, (a | b) → (a | c) → (a | b + c) := @algebra.dvd_add _ _ end port_algebra end nat
101a3b5f6b82bade00ba1c30b1928fbb1c45c375
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/namespaceHyg.lean
55ec3afdbfa4a21e3d9767ec377aab83bf812100
[ "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
60
lean
macro "classical" : command => `(open Classical) classical
0ce16620c8a89b0b58419ae68038ce7ebb427e0b
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/topological_spaces/distrib.lean
11e3203c81def34f87810e3fef2986b380241078
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
4,385
lean
import for_mathlib import category_theory.colimit_lemmas import .category import .colimits import .homeomorphism import .inter_union import .subspace noncomputable theory /- The distributivity law in Top: X × Y ⊔ X × Z ≅ X × (Y ⊔ Z). -/ open set open category_theory universe u namespace homotopy_theory.topological_spaces open homotopy_theory.topological_spaces.Top local notation `Top` := Top.{u} namespace distrib_private section parameters {X Y Z : Top} def YZ := Y ⊔ Z def inY : Y ⟶ Y ⊔ Z := i₀ def inZ : Z ⟶ Y ⊔ Z := i₁ -- TODO: These annotations shouldn't really be necessary def Y' : set (Y ⊔ Z) := set.range inY def Z' : set (Y ⊔ Z) := set.range inZ def Y_Y' : homeomorphism Y (Top.mk_ob Y') := homeomorphism_to_image_of_embedding (embedding_inl : embedding inY) def Z_Z' : homeomorphism Z (Top.mk_ob Z') := homeomorphism_to_image_of_embedding (embedding_inr : embedding inZ) def XYZ := Top.prod X (Y ⊔ Z) def XY := {p : XYZ | p.2 ∈ Y'} def XZ := {p : XYZ | p.2 ∈ Z'} -- Verify closedness conditions for intersection-union pushout. -- TODO: Move to mathlib? def selector : YZ → bool | (sum.inl _) := ff | (sum.inr _) := tt lemma continuous_selector : continuous selector := continuous_sum_rec (@continuous_const _ _ _ _ ff) (@continuous_const _ _ _ _ tt) def Y'_closed : is_closed Y' := begin convert continuous_iff_is_closed.mp continuous_selector {ff} trivial, ext p, cases p, { change (∃ y, sum.inl y = sum.inl p) ↔ ff ∈ {ff}, simp }, { change (∃ y, sum.inl y = sum.inr p) ↔ tt ∈ {ff}, simp } end def Z'_closed : is_closed Z' := begin convert continuous_iff_is_closed.mp continuous_selector {tt} trivial, ext p, cases p, { change (∃ z, sum.inr z = sum.inl p) ↔ ff ∈ {tt}, simp }, { change (∃ z, sum.inr z = sum.inr p) ↔ tt ∈ {tt}, simp } end def XY_closed : is_closed XY := continuous_iff_is_closed.mp continuous_snd _ Y'_closed def XZ_closed : is_closed XZ := continuous_iff_is_closed.mp continuous_snd _ Z'_closed -- TODO: Eliminate duplication with pair.l2 def XxA_XA {B : Top} (A : set B) : homeomorphism (Top.prod X (Top.mk_ob A)) (Top.mk_ob {p : Top.prod X B | p.2 ∈ A}) := { hom := Top.mk_hom (λ p, ⟨(p.1, p.2.val), p.2.property⟩) (by continuity!), inv := Top.mk_hom (λ p, (p.val.1, ⟨p.val.2, p.property⟩)) (by continuity!), hom_inv_id' := by ext p; rcases p with ⟨x, ⟨b, hb⟩⟩; refl, inv_hom_id' := by ext p; rcases p with ⟨⟨x, b⟩, hb⟩; refl } def XxY_XY' : homeomorphism (Top.prod X Y) (Top.mk_ob XY) := Y_Y'.prod_congr_right.trans (XxA_XA Y') def XxZ_XZ' : homeomorphism (Top.prod X Z) (Top.mk_ob XZ) := Z_Z'.prod_congr_right.trans (XxA_XA Z') def po := Is_pushout_inter_of_cover XY XZ XY_closed XZ_closed begin rw ←univ_subset_iff, intros p _, rcases p with ⟨x, y|z⟩, { exact or.inl ⟨y, rfl⟩ }, { exact or.inr ⟨z, rfl⟩ } end def not_XY_and_XZ : XY ∩ XZ → pempty := λ q, false.elim $ let ⟨p, ⟨y, py⟩, ⟨z, pz⟩⟩ := q in by change sum.inl y = p.2 at py; change sum.inr z = p.2 at pz; cc def po' := Is_pushout_of_isomorphic po (Top.empty_induced (Top.prod X Y)) (Top.empty_induced (Top.prod X Z)) (initial_object.unique Top.empty_is_initial_object (Top.is_initial_object_of_to_empty (Top.mk_ob (XY ∩ XZ : set _)) not_XY_and_XZ)) XxY_XY' XxZ_XZ' (Top.empty_is_initial_object.uniqueness _ _) (Top.empty_is_initial_object.uniqueness _ _) def XxY_XYZ : Top.prod X Y ⟶ Top.prod X (Y ⊔ Z) := Top.mk_hom (λ p, (p.1, inY p.2)) (by continuity!) def XxZ_XYZ : Top.prod X Z ⟶ Top.prod X (Y ⊔ Z) := Top.mk_hom (λ p, (p.1, inZ p.2)) (by continuity!) def coprod : Is_coproduct XxY_XYZ XxZ_XYZ := Is_coproduct_of_Is_pushout_of_Is_initial po' Top.empty_is_initial_object end end distrib_private def Top.prod.distrib {X Y Z : Top} : homeomorphism (Top.prod X Y ⊔ Top.prod X Z) (Top.prod X (Y ⊔ Z)) := isomorphic_coprod_of_Is_coproduct distrib_private.coprod -- TODO: The above construction lost computational control of the -- inverse morphism. We know it must be given by sending (x, inl y) to -- inl (x, y) and similarly for Z. We could replace the inverse -- morphism in prod.distrib; or possibly it would have been easier -- from the start to just show that this formula defines a continuous -- inverse. end homotopy_theory.topological_spaces
4139d9ccdd5d539dd10f551398366dd0ac653246
037dba89703a79cd4a4aec5e959818147f97635d
/src/2021/sets/sheet4.lean
0717654a66e6d925515287bc02ab1223b542a212
[]
no_license
ImperialCollegeLondon/M40001_lean
3a6a09298da395ab51bc220a535035d45bbe919b
62a76fa92654c855af2b2fc2bef8e60acd16ccec
refs/heads/master
1,666,750,403,259
1,665,771,117,000
1,665,771,117,000
209,141,835
115
12
null
1,640,270,596,000
1,568,749,174,000
Lean
UTF-8
Lean
false
false
1,688
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Kevin Buzzard -/ import tactic -- imports all the Lean tactics /-! # Sets in Lean, example sheet 4 : exists (`∃`) In this sheet we learn how to manipulate `∃` in Lean. We will see statements of the form `∃ x, x ∈ A`. We will need to learn two new tactics -- one for making progress when the goal is `⊢ ∃ x, x ∈ A`, and one for making progress when we have a hypothesis `h : ∃ x, x ∈ A`. Now we have `∃` and `∀`, and `∈` and `∉`, we can finally get going with some harder levels. ## New tactics you will need to know `cases` or `rcases` -- to get the `x` from a hypothesis `h : ∃ x, ...` `use` -- to make progress on goals of the form `⊢ ∃ x, ...` ### The `cases` tactic We've seen this tactic before to take apart `h : P ∧ Q`. We can also use it to take apart `h : ∃ t : X, F t`: if `h` is such a hypothesis then `cases h with x hx,` will give us `x : X` and `hx : F x` ### The `use` tactic If we have a goal `⊢ ∃ x : X, F x` and a term `a : X` which we know will work, then `use a` will change the goal to `F a`. By the way, `use` tries `refl` so it might magically close goals early -/ open set variables (X : Type) -- Everything will be a subset of `X` (A B C D E : set X) -- A,B,C,D,E are subsets of `X` (x y z : X) -- x,y,z are elements of `X` or, more precisely, terms of type `X` example : x ∈ A → ∃ t, t ∈ A := begin sorry end example : (∀ x, x ∈ A) ↔ ¬ (∃ x, x ∉ A) := begin sorry end example : (∃ x, x ∈ A) ↔ ¬ (∀ x, x ∉ A) := begin sorry end
541ef2302cc8bf6d80df18f9dadae72a34778358
947b78d97130d56365ae2ec264df196ce769371a
/src/Lean/Compiler/NeverExtractAttr.lean
b5ee879daf91642a6683ffc81dc636d7cc034afe
[ "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
976
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.Environment import Lean.Attributes namespace Lean def mkNeverExtractAttr : IO TagAttribute := registerTagAttribute `neverExtract "instruct the compiler that function applications using the tagged declaration should not be extracted when they are closed terms, nor common subexpression should be performed. This is useful for declarations that have implicit effects." @[init mkNeverExtractAttr] constant neverExtractAttr : TagAttribute := arbitrary _ private partial def hasNeverExtractAttributeAux (env : Environment) : Name → Bool | n => neverExtractAttr.hasTag env n || (n.isInternal && hasNeverExtractAttributeAux n.getPrefix) @[export lean_has_never_extract_attribute] def hasNeverExtractAttribute (env : Environment) (n : Name) : Bool := hasNeverExtractAttributeAux env n end Lean
b72fba91d4eae1b0102084486ace2b81adbb95cf
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/funMatchIssue.lean
36bf0213141309be5a5f679e5ab5f6a422ffb534
[ "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
282
lean
inductive T : Type 1 := | mkT : (forall {a : Type}, a -> a) -> T open T -- Works def makeT (f : forall {a : Type}, a -> a) : T := mkT f def makeT' : (forall {a : Type}, a -> a) -> T := fun x => let f := @x mkT f def makeT'' : (forall {a : Type}, a -> a) -> T | f => mkT f
1e9e40f0071ee1db3859eabdc54e051cfec7acbc
3d2a7f1582fe5bae4d0bdc2fe86e997521239a65
/spatial-reasoning/spatial-reasoning-problem-14.lean
c4a9a38fdfaf9b101302e1abee72d171e64c8d9a
[]
no_license
own-pt/common-sense-lean
e4fa643ae010459de3d1bf673be7cbc7062563c9
f672210aecb4172f5bae265e43e6867397e13b1c
refs/heads/master
1,622,065,660,261
1,589,487,533,000
1,589,487,533,000
254,167,782
3
2
null
1,589,487,535,000
1,586,370,214,000
Lean
UTF-8
Lean
false
false
183
lean
/- Spatial Reasoning Problem 14 -/ /- It can be found at: SpatialQs.txt -/ /- (14) John is outside a circle and then crosses the border of the circle. Is he inside the circle? -/
1c73dd01db77875ccfbb4d22c6dce23d11487d5c
bc0ebfde190bc1da50a425e63b8f44a50746ca42
/src/misc_mathlib.lean
69900a4d18668d4538efffba079a63cc775b43ba
[ "Apache-2.0" ]
permissive
Pazzaz/erdos-szekeres
d93996420d10aaa8c603379abdea3391295e8be2
b6e53035340946602b9e4cc346314e541a5f3774
refs/heads/master
1,680,656,743,365
1,618,681,128,000
1,618,681,128,000
358,942,643
0
0
null
null
null
null
UTF-8
Lean
false
false
7,166
lean
import data.list import tactic import data.finset theorem sublist_take_mp_sublist {X : Type*} (A S: list X) (n : ℕ) (h: S <+ A.take n) : S <+ A := list.sublist.trans h (list.sublist_of_prefix (A.take_prefix n)) theorem nth_le_mem_take_succ {X : Type*} (A : list X) (n : ℕ) (h : n < A.length) : A.nth_le n h ∈ A.take n.succ := begin rw list.nth_le_take A h (lt_add_one n), exact list.nth_le_mem (list.take n.succ A) n _, end theorem sublist_concat_is_sublist {X : Type*} {l1 l2 : list X} {e : X} (n : ℕ) (h_sub : l1 <+ l2.take n) (h_in : e ∈ l2.drop n) : l1.concat e <+ l2 := begin rw [list.concat_eq_append, ←list.take_append_drop n l2], exact list.sublist.append h_sub (list.singleton_sublist.mpr h_in), end theorem sublist_of_take_concat_sublist_of_take {X : Type*} {A B: list X} {n₁ n₂ : ℕ} (h₁ : n₂ < A.length) (h₂ : n₁ ≤ n₂) (h₃ : B <+ A.take n₁) : B.concat (A.nth_le n₂ h₁) <+ A.take n₂.succ := begin have le_add_of_sub_eq_id : ∀ {a b : ℕ} (h : a ≤ b), a + (b - a) = b := by omega, have succ_bring_in2 : ∀ {a b : ℕ} (h : a ≤ b), (b + 1) - a = (b - a) + 1 := by omega, have le_comp : n₁ + (n₂ - n₁) < A.length, { rw le_add_of_sub_eq_id h₂, exact h₁, }, have comp_nth_le : A.nth_le n₂ h₁ = A.nth_le (n₁ + (n₂ - n₁)) le_comp, { congr, exact (le_add_of_sub_eq_id h₂).symm, }, apply sublist_concat_is_sublist n₁, { rw [list.take_take, min_eq_left (le_trans h₂ (nat.le_succ n₂))], exact h₃, }, { rw [←(le_add_of_sub_eq_id (le_trans h₂ (nat.le_succ n₂))), list.drop_take n₁, comp_nth_le, list.nth_le_drop, succ_bring_in2 h₂], exact nth_le_mem_take_succ (A.drop n₁) (n₂ - n₁) _, } end theorem list_chain_concat {X : Type*} {R : X → X → Prop} {l : list X} (a : X) (h1 : list.chain' R l) (h2 : ∀ (x : X), x ∈ l.last' → R x a) : list.chain' R (l.concat a) := begin rw list.concat_eq_append, apply list.chain'.append h1 (list.chain'_singleton a), intros _ x_in _ y_in, rw option.mem_unique y_in rfl, exact h2 x x_in, end theorem pair_from_pairwise_to_pair_from_map {X Y: Type*} {A : list X} {f : X → Y} {r1 : X → X → Prop} [ant : anti_symmetric r1] {r2 : Y → Y → Prop} [rfx : reflexive r2] (h1 : A.pairwise r1) (h2 : (A.map f).pairwise r2) {x y : X} (h3 : x ∈ A) (h4 : y ∈ A) (h5 : r1 x y) : r2 (f x) (f y) := begin induction A, { finish }, { have A_tl_pair := list.pairwise_of_pairwise_cons h1, have A_tl_map_pair := list.pairwise_of_pairwise_cons h2, have hypp := A_ih A_tl_pair A_tl_map_pair, cases h3, { cases h4, { rw [h3, h4], exact rfx (f A_hd), }, { rw list.map_cons at h2, rw h3, exact list.rel_of_pairwise_cons h2 (list.mem_map_of_mem f h4), } }, { cases h4, { have thinger := list.rel_of_pairwise_cons h1 h3, rw ←h4 at thinger, rw ant h5 thinger, exact rfx (f y), }, { exact hypp h3 h4, } }, } end theorem prod_ne_iff_right_or_left_ne {X Y : Type*} (a b : X × Y) : a.1 ≠ b.1 ∨ a.2 ≠ b.2 ↔ a ≠ b := begin cases a, cases b, simpa [not_and, prod.mk.inj_iff, ne.def] using imp_iff_not_or.symm, end theorem nat_mul_sub_right_lt {a b : ℕ} (h1 : a ≠ 0) (h2 : b ≠ 0) : a*(b-1) < a*b := (mul_lt_mul_left (pos_iff_ne_zero.mpr h1)).mpr (nat.pred_lt h2) theorem nat_mul_sub_left_lt {a b : ℕ} (h1 : a ≠ 0) (h2 : b ≠ 0) : (a-1)*b < a*b := (mul_lt_mul_right (pos_iff_ne_zero.mpr h2)).mpr (nat.pred_lt h1) theorem nat_mul_sub_left_le (a b : ℕ) : (a-1)*b ≤ a*b := begin by_cases h : 0 < b, { exact (mul_le_mul_right h).mpr (nat.sub_le a 1), }, { rw [not_lt, nonpos_iff_eq_zero] at h, rw [h, mul_zero, mul_zero], } end theorem cons_sub_not_eq {X : Type*} {A B : list X} {a b : X} (h1 : a ≠ b) (h2 : a :: A <+ b :: B) : a :: A <+ B := begin cases h2 with _ _ _ e _ _ _ _, { exact e }, { exact absurd rfl h1 }, end theorem drop_while_imp_mem {X: Type*} [decidable_eq X] (A : list X) (f : X → Prop) [decidable_pred f] : A.drop_while f = A.drop_while (λ x, x ∈ A → f x) := begin induction A, { exact rfl, }, { dsimp [list.drop_while], have thing : (A_hd ∈ (A_hd :: A_tl) → f A_hd) = f A_hd, by simp, have step2 : ∀ x, (x ∈ A_hd :: A_tl → f x) = ((x = A_hd ∨ x ∈ A_tl) → f x), { tauto, }, simp only [thing], simp only [step2], split_ifs, { rw A_ih, congr, ext, split, { intros dkdkkd huehue, cases huehue, { rw ←huehue at h, exact h, }, { exact dkdkkd huehue, }, }, { intros juju x_inn, exact juju (or.inr x_inn), }, }, { exact ⟨rfl, rfl⟩, } }, end theorem sublist_map_exists {X Y : Type*} {A : list X} {B : list Y} {f : X → Y} (h : B <+ A.map f) : ∃ C, C <+ A ∧ C.map f = B := begin induction A generalizing B, { refine ⟨list.nil, list.nil.nil_sublist, _⟩, rw list.eq_nil_of_sublist_nil h, exact rfl, }, { rw list.map_cons at h, by_cases hhh : B = list.nil, { rw hhh, exact ⟨list.nil, (A_hd :: A_tl).nil_sublist, rfl⟩, }, { obtain ⟨b, B', hhh2⟩ := list.exists_cons_of_ne_nil hhh, rw hhh2 at *, by_cases heads_eq : b = f A_hd, { rw [heads_eq] at h, obtain ⟨C',C'_le,C'_map⟩ := A_ih (list.cons_sublist_cons_iff.mp h), refine ⟨A_hd :: C',_,_⟩, exact list.cons_sublist_cons_iff.mpr C'_le, rw [list.map_cons, C'_map, heads_eq], }, { obtain ⟨C,C_le,C_map⟩ := A_ih (cons_sub_not_eq heads_eq h), exact ⟨C, list.sublist.cons C A_tl A_hd C_le, C_map⟩, }, } } end @[simp] theorem take_while_false_mem {X : Type*} {A : list X} (f : X → Prop) [decidable_pred f] (h: ∀ x ∈ A, ¬(f x)) : list.take_while f A = list.nil := begin induction A, { exact rfl }, { dsimp [list.take_while], rw [A_ih _, if_neg (h A_hd (list.mem_cons_self A_hd A_tl))], finish, } end @[simp] theorem drop_while_false_mem {X : Type*} {A : list X} (f : X → Prop) [decidable_pred f] (h: ∀ x ∈ A, ¬(f x)) : list.drop_while f A = A := begin nth_rewrite 1 ←(list.take_while_append_drop f A), rw [take_while_false_mem f h, list.nil_append], end theorem finset_sort_idempotent {X: Type*} [linear_order X] {A : list X} (h1 : A.sorted (≤)) (h2 : A.nodup) : A.to_finset.sort (≤) = A := begin induction A, tauto, dsimp [finset.sort], have rw_nodup := list.erase_dup_eq_self.mpr h2, rw [ rw_nodup, list.merge_sort_eq_insertion_sort, list.insertion_sort_cons_eq_take_drop, list.sorted.insertion_sort_eq (list.sorted_of_sorted_cons h1)], dsimp [list.sorted] at h1, have drop_simple : list.drop_while (λ b, ¬A_hd ≤ b) A_tl = A_tl, { apply drop_while_false_mem _ _, intros _ aa_mem, rw not_not, exact list.rel_of_pairwise_cons h1 aa_mem, }, have take_simple: list.take_while (λ b, ¬A_hd ≤ b) A_tl = [], { apply @list.append_right_cancel _ _ _(list.drop_while (λ (b : X), ¬A_hd ≤ b) A_tl), rw [list.take_while_append_drop _ A_tl, drop_simple, list.nil_append], }, rw [take_simple, drop_simple, list.nil_append], end
eafec261cd833501294627d200d7632223fff33d
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/partial1.lean
c6602bb05a5f80343dbdf76938e1019a9bc08cfa
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
538
lean
new_frontend partial def reverse {α} (as : List α) : List α := let rec loop : List α → List α → List α | [], r => r | a::as, r => loop as (a::r); loop as [] #eval reverse [3, 2, 1] #eval reverse [1, 2, 3, 4] #print reverse #print reverse.loop #print reverse.loop._unsafe_rec partial def appendRev {α} (extra : List α) (as : List α) : List α := let rec loop (as acc : List α) : List α := match as, acc with | [], r => extra ++ r | a::as, r => loop as (a::r); loop as [] #eval appendRev [3, 4] [1, 2, 0]
9e48e81c6bdbc9fe2dbb135739fee1cefc0852d9
f313d4982feee650661f61ed73f0cb6635326350
/Mathlib/Mem.lean
7e7b47692c4ae158ede4f6e1b20b223b7a92becf
[ "Apache-2.0" ]
permissive
shingtaklam1324/mathlib4
38c6e172eec1385944db5a70a3b5545c924980ee
50610c343b7065e8eec056d641f859ceed608e69
refs/heads/master
1,683,032,333,313
1,621,942,699,000
1,621,942,699,000
371,130,608
0
0
Apache-2.0
1,622,053,166,000
1,622,053,166,000
null
UTF-8
Lean
false
false
150
lean
class Mem (α : outParam $ Type u) (γ : Type v) where mem : α → γ → Prop infix:50 " ∈ " => Mem.mem notation:50 x " ∉ " s => ¬ x ∈ s
5b02c5a7630a84b3bda4442b6f3ae32d45a1b5a6
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/limits/kan_extension.lean
815218caa1dabf595143dfc1a6cac4cda349a4e2
[ "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
9,110
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Adam Topaz -/ import category_theory.punit import category_theory.structured_arrow import category_theory.limits.functor_category import category_theory.limits.shapes.terminal /-! # Kan extensions This file defines the right and left Kan extensions of a functor. They exist under the assumption that the target category has enough limits resp. colimits. The main definitions are `Ran ι` and `Lan ι`, where `ι : S ⥤ L` is a functor. Namely, `Ran ι` is the right Kan extension, while `Lan ι` is the left Kan extension, both as functors `(S ⥤ D) ⥤ (L ⥤ D)`. To access the right resp. left adjunction associated to these, use `Ran.adjunction` resp. `Lan.adjunction`. # Projects A lot of boilerplate could be generalized by defining and working with pseudofunctors. -/ noncomputable theory namespace category_theory open limits universes v u₁ u₂ u₃ variables {S : Type v} {L : Type u₂} {D : Type u₃} variables [category.{v} S] [category.{v} L] [category.{v} D] variables (ι : S ⥤ L) namespace Ran local attribute [simp] structured_arrow.proj /-- The diagram indexed by `Ran.index ι x` used to define `Ran`. -/ abbreviation diagram (F : S ⥤ D) (x : L) : structured_arrow x ι ⥤ D := structured_arrow.proj x ι ⋙ F variable {ι} /-- A cone over `Ran.diagram ι F x` used to define `Ran`. -/ @[simp] def cone {F : S ⥤ D} {G : L ⥤ D} (x : L) (f : ι ⋙ G ⟶ F) : cone (diagram ι F x) := { X := G.obj x, π := { app := λ i, G.map i.hom ≫ f.app i.right, naturality' := begin rintro ⟨⟨il⟩, ir, i⟩ ⟨⟨jl⟩, jr, j⟩ ⟨⟨⟨fl⟩⟩, fr, ff⟩, dsimp at *, simp only [category.id_comp, category.assoc] at *, rw [ff], have := f.naturality, tidy, end } } variable (ι) /-- An auxiliary definition used to define `Ran`. -/ @[simps] def loc (F : S ⥤ D) [∀ x, has_limit (diagram ι F x)] : L ⥤ D := { obj := λ x, limit (diagram ι F x), map := λ x y f, limit.pre (diagram _ _ _) (structured_arrow.map f : structured_arrow _ ι ⥤ _), map_id' := begin intro l, ext j, simp only [category.id_comp, limit.pre_π], congr' 1, simp, end, map_comp' := begin intros x y z f g, ext j, erw [limit.pre_pre, limit.pre_π, limit.pre_π], congr' 1, tidy, end } /-- An auxiliary definition used to define `Ran` and `Ran.adjunction`. -/ @[simps] def equiv (F : S ⥤ D) [∀ x, has_limit (diagram ι F x)] (G : L ⥤ D) : (G ⟶ loc ι F) ≃ (((whiskering_left _ _ _).obj ι).obj G ⟶ F) := { to_fun := λ f, { app := λ x, f.app _ ≫ limit.π (diagram ι F (ι.obj x)) (structured_arrow.mk (𝟙 _)), naturality' := begin intros x y ff, dsimp only [whiskering_left], simp only [functor.comp_map, nat_trans.naturality_assoc, loc_map, category.assoc], congr' 1, erw limit.pre_π, change _ = _ ≫ (diagram ι F (ι.obj x)).map (structured_arrow.hom_mk _ _), rw limit.w, tidy, end }, inv_fun := λ f, { app := λ x, limit.lift (diagram ι F x) (cone _ f), naturality' := begin intros x y ff, ext j, erw [limit.lift_pre, limit.lift_π, category.assoc, limit.lift_π (cone _ f) j], tidy, end }, left_inv := begin intro x, ext k j, dsimp only [cone], rw limit.lift_π, simp only [nat_trans.naturality_assoc, loc_map], erw limit.pre_π, congr, cases j, tidy, end, right_inv := by tidy } end Ran /-- The right Kan extension of a functor. -/ @[simps] def Ran [∀ X, has_limits_of_shape (structured_arrow X ι) D] : (S ⥤ D) ⥤ L ⥤ D := adjunction.right_adjoint_of_equiv (λ F G, (Ran.equiv ι G F).symm) (by tidy) namespace Ran variable (D) /-- The adjunction associated to `Ran`. -/ def adjunction [∀ X, has_limits_of_shape (structured_arrow X ι) D] : (whiskering_left _ _ D).obj ι ⊣ Ran ι := adjunction.adjunction_of_equiv_right _ _ lemma reflective [full ι] [faithful ι] [∀ X, has_limits_of_shape (structured_arrow X ι) D] : is_iso (adjunction D ι).counit := begin apply nat_iso.is_iso_of_is_iso_app _, intros F, apply nat_iso.is_iso_of_is_iso_app _, intros X, dsimp [adjunction], simp only [category.id_comp], exact is_iso.of_iso ((limit.is_limit _).cone_point_unique_up_to_iso (limit_of_diagram_initial structured_arrow.mk_id_initial _)), end end Ran namespace Lan local attribute [simp] costructured_arrow.proj /-- The diagram indexed by `Ran.index ι x` used to define `Ran`. -/ abbreviation diagram (F : S ⥤ D) (x : L) : costructured_arrow ι x ⥤ D := costructured_arrow.proj ι x ⋙ F variable {ι} /-- A cocone over `Lan.diagram ι F x` used to define `Lan`. -/ @[simp] def cocone {F : S ⥤ D} {G : L ⥤ D} (x : L) (f : F ⟶ ι ⋙ G) : cocone (diagram ι F x) := { X := G.obj x, ι := { app := λ i, f.app i.left ≫ G.map i.hom, naturality' := begin rintro ⟨ir, ⟨il⟩, i⟩ ⟨jl, ⟨jr⟩, j⟩ ⟨fl, ⟨⟨fl⟩⟩, ff⟩, dsimp at *, simp only [functor.comp_map, category.comp_id, nat_trans.naturality_assoc], rw [← G.map_comp, ff], tidy, end } } variable (ι) /-- An auxiliary definition used to define `Lan`. -/ @[simps] def loc (F : S ⥤ D) [I : ∀ x, has_colimit (diagram ι F x)] : L ⥤ D := { obj := λ x, colimit (diagram ι F x), map := λ x y f, colimit.pre (diagram _ _ _) (costructured_arrow.map f : costructured_arrow ι _ ⥤ _), map_id' := begin intro l, ext j, erw [colimit.ι_pre, category.comp_id], congr' 1, simp, end, map_comp' := begin intros x y z f g, ext j, let ff : costructured_arrow ι _ ⥤ _ := costructured_arrow.map f, let gg : costructured_arrow ι _ ⥤ _ := costructured_arrow.map g, let dd := diagram ι F z, -- I don't know why lean can't deduce the following three instances... haveI : has_colimit (ff ⋙ gg ⋙ dd) := I _, haveI : has_colimit ((ff ⋙ gg) ⋙ dd) := I _, haveI : has_colimit (gg ⋙ dd) := I _, change _ = colimit.ι ((ff ⋙ gg) ⋙ dd) j ≫ _ ≫ _, erw [colimit.pre_pre dd gg ff, colimit.ι_pre, colimit.ι_pre], congr' 1, simp, end } /-- An auxiliary definition used to define `Lan` and `Lan.adjunction`. -/ @[simps] def equiv (F : S ⥤ D) [I : ∀ x, has_colimit (diagram ι F x)] (G : L ⥤ D) : (loc ι F ⟶ G) ≃ (F ⟶ ((whiskering_left _ _ _).obj ι).obj G) := { to_fun := λ f, { app := λ x, by apply colimit.ι (diagram ι F (ι.obj x)) (costructured_arrow.mk (𝟙 _)) ≫ f.app _, -- sigh naturality' := begin intros x y ff, dsimp only [whiskering_left], simp only [functor.comp_map, category.assoc], rw [← f.naturality (ι.map ff), ← category.assoc, ← category.assoc], let fff : costructured_arrow ι _ ⥤ _ := costructured_arrow.map (ι.map ff), -- same issue :-( haveI : has_colimit (fff ⋙ diagram ι F (ι.obj y)) := I _, erw colimit.ι_pre (diagram ι F (ι.obj y)) fff (costructured_arrow.mk (𝟙 _)), let xx : costructured_arrow ι (ι.obj y) := costructured_arrow.mk (ι.map ff), let yy : costructured_arrow ι (ι.obj y) := costructured_arrow.mk (𝟙 _), let fff : xx ⟶ yy := costructured_arrow.hom_mk ff (by {simp only [costructured_arrow.mk_hom_eq_self], erw category.comp_id}), erw colimit.w (diagram ι F (ι.obj y)) fff, congr, simp, end }, inv_fun := λ f, { app := λ x, colimit.desc (diagram ι F x) (cocone _ f), naturality' := begin intros x y ff, ext j, erw [colimit.pre_desc, ← category.assoc, colimit.ι_desc, colimit.ι_desc], tidy, end }, left_inv := begin intro x, ext k j, rw colimit.ι_desc, dsimp only [cocone], rw [category.assoc, ← x.naturality j.hom, ← category.assoc], congr' 1, change colimit.ι _ _ ≫ colimit.pre (diagram ι F k) (costructured_arrow.map _) = _, rw colimit.ι_pre, congr, cases j, tidy, end, right_inv := by tidy } end Lan /-- The left Kan extension of a functor. -/ @[simps] def Lan [∀ X, has_colimits_of_shape (costructured_arrow ι X) D] : (S ⥤ D) ⥤ L ⥤ D := adjunction.left_adjoint_of_equiv (λ F G, Lan.equiv ι F G) (by tidy) namespace Lan variable (D) /-- The adjunction associated to `Lan`. -/ def adjunction [∀ X, has_colimits_of_shape (costructured_arrow ι X) D] : Lan ι ⊣ (whiskering_left _ _ D).obj ι := adjunction.adjunction_of_equiv_left _ _ lemma coreflective [full ι] [faithful ι] [∀ X, has_colimits_of_shape (costructured_arrow ι X) D] : is_iso (adjunction D ι).unit := begin apply nat_iso.is_iso_of_is_iso_app _, intros F, apply nat_iso.is_iso_of_is_iso_app _, intros X, dsimp [adjunction], simp only [category.comp_id], exact is_iso.of_iso ((colimit.is_colimit _).cocone_point_unique_up_to_iso (colimit_of_diagram_terminal costructured_arrow.mk_id_terminal _)).symm, end end Lan end category_theory
32f19e9b9d8b047f15e77e0368fe1d4800055b18
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/analysis/special_functions/trigonometric.lean
c9475e41137e5720a74a8eb5d67ba53537812f33
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
74,223
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 -/ import analysis.special_functions.exp_log /-! # Trigonometric functions ## Main definitions This file contains the following definitions: * π, arcsin, arccos, arctan * argument of a complex number * logarithm on complex numbers ## Main statements Many basic inequalities on trigonometric functions are established. The continuity and differentiability of the usual trigonometric functions are proved, and their derivatives are computed. ## Tags log, sin, cos, tan, arcsin, arccos, arctan, angle, argument -/ noncomputable theory open_locale classical namespace complex /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := begin simp only [cos, div_eq_mul_inv], convert ((((has_deriv_at_id x).neg.mul_const I).cexp.sub ((has_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [sub_mul, mul_assoc, mul_assoc, I_mul_I, neg_one_mul, neg_neg, mul_one, one_mul, mul_assoc, I_mul_I, mul_neg_one, sub_neg_eq_add, add_comm] end lemma differentiable_sin : differentiable ℂ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin {x : ℂ} : differentiable_at ℂ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := begin simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul], convert (((has_deriv_at_id x).mul_const I).cexp.add ((has_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], ring end lemma differentiable_cos : differentiable ℂ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x lemma deriv_cos {x : ℂ} : deriv cos x = -sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) := funext $ λ x, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `cosh x`. -/ lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := begin simp only [cosh, div_eq_mul_inv], convert ((has_deriv_at_exp x).sub (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, neg_neg] end lemma differentiable_sinh : differentiable ℂ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh {x : ℂ} : differentiable_at ℂ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `sinh x`. -/ lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := begin simp only [sinh, div_eq_mul_inv], convert ((has_deriv_at_exp x).add (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, mul_neg_one, sub_eq_add_neg] end lemma differentiable_cosh : differentiable ℂ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh {x : ℂ} : differentiable_at ℂ cos x := differentiable_cos x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous end complex section /-! Register lemmas for the derivatives of the composition of `complex.cos`, `complex.sin`, `complex.cosh` and `complex.sinh` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} /-! `complex.cos`-/ lemma has_deriv_at.ccos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') x := (complex.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.ccos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cos (f x)) (- complex.sin (f x) * f') s x := (complex.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.ccos (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cos (f x)) s x := hf.has_deriv_within_at.ccos.differentiable_within_at @[simp] lemma differentiable_at.ccos (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cos (f x)) x := hc.has_deriv_at.ccos.differentiable_at lemma differentiable_on.ccos (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cos (f x)) s := λx h, (hc x h).ccos @[simp] lemma differentiable.ccos (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cos (f x)) := λx, (hc x).ccos lemma deriv_within_ccos (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cos (f x)) s x = - complex.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccos.deriv_within hxs @[simp] lemma deriv_ccos (hc : differentiable_at ℂ f x) : deriv (λx, complex.cos (f x)) x = - complex.sin (f x) * (deriv f x) := hc.has_deriv_at.ccos.deriv /-! `complex.sin`-/ lemma has_deriv_at.csin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') x := (complex.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.csin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sin (f x)) (complex.cos (f x) * f') s x := (complex.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.csin (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sin (f x)) s x := hf.has_deriv_within_at.csin.differentiable_within_at @[simp] lemma differentiable_at.csin (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sin (f x)) x := hc.has_deriv_at.csin.differentiable_at lemma differentiable_on.csin (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sin (f x)) s := λx h, (hc x h).csin @[simp] lemma differentiable.csin (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sin (f x)) := λx, (hc x).csin lemma deriv_within_csin (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sin (f x)) s x = complex.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csin.deriv_within hxs @[simp] lemma deriv_csin (hc : differentiable_at ℂ f x) : deriv (λx, complex.sin (f x)) x = complex.cos (f x) * (deriv f x) := hc.has_deriv_at.csin.deriv /-! `complex.cosh`-/ lemma has_deriv_at.ccosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') x := (complex.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.ccosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.cosh (f x)) (complex.sinh (f x) * f') s x := (complex.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.ccosh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.cosh (f x)) s x := hf.has_deriv_within_at.ccosh.differentiable_within_at @[simp] lemma differentiable_at.ccosh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.cosh (f x)) x := hc.has_deriv_at.ccosh.differentiable_at lemma differentiable_on.ccosh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.cosh (f x)) s := λx h, (hc x h).ccosh @[simp] lemma differentiable.ccosh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.cosh (f x)) := λx, (hc x).ccosh lemma deriv_within_ccosh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.cosh (f x)) s x = complex.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.ccosh.deriv_within hxs @[simp] lemma deriv_ccosh (hc : differentiable_at ℂ f x) : deriv (λx, complex.cosh (f x)) x = complex.sinh (f x) * (deriv f x) := hc.has_deriv_at.ccosh.deriv /-! `complex.sinh`-/ lemma has_deriv_at.csinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') x := (complex.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.csinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, complex.sinh (f x)) (complex.cosh (f x) * f') s x := (complex.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.csinh (hf : differentiable_within_at ℂ f s x) : differentiable_within_at ℂ (λ x, complex.sinh (f x)) s x := hf.has_deriv_within_at.csinh.differentiable_within_at @[simp] lemma differentiable_at.csinh (hc : differentiable_at ℂ f x) : differentiable_at ℂ (λx, complex.sinh (f x)) x := hc.has_deriv_at.csinh.differentiable_at lemma differentiable_on.csinh (hc : differentiable_on ℂ f s) : differentiable_on ℂ (λx, complex.sinh (f x)) s := λx h, (hc x h).csinh @[simp] lemma differentiable.csinh (hc : differentiable ℂ f) : differentiable ℂ (λx, complex.sinh (f x)) := λx, (hc x).csinh lemma deriv_within_csinh (hf : differentiable_within_at ℂ f s x) (hxs : unique_diff_within_at ℂ s x) : deriv_within (λx, complex.sinh (f x)) s x = complex.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.csinh.deriv_within hxs @[simp] lemma deriv_csinh (hc : differentiable_at ℂ f x) : deriv (λx, complex.sinh (f x)) x = complex.cosh (f x) * (deriv f x) := hc.has_deriv_at.csinh.deriv end namespace real variables {x y z : ℝ} lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sin x) lemma differentiable_sin : differentiable ℝ sin := λx, (has_deriv_at_sin x).differentiable_at lemma differentiable_at_sin : differentiable_at ℝ sin x := differentiable_sin x @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (has_deriv_at_real_of_complex (complex.has_deriv_at_cos x) : _) lemma differentiable_cos : differentiable ℝ cos := λx, (has_deriv_at_cos x).differentiable_at lemma differentiable_at_cos : differentiable_at ℝ cos x := differentiable_cos x lemma deriv_cos : deriv cos x = - sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) := funext $ λ _, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sinh x) lemma differentiable_sinh : differentiable ℝ sinh := λx, (has_deriv_at_sinh x).differentiable_at lemma differentiable_at_sinh : differentiable_at ℝ sinh x := differentiable_sinh x @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_cosh x) lemma differentiable_cosh : differentiable ℝ cosh := λx, (has_deriv_at_cosh x).differentiable_at lemma differentiable_at_cosh : differentiable_at ℝ cosh x := differentiable_cosh x @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous /-- `sinh` is strictly monotone. -/ lemma sinh_strict_mono : strict_mono sinh := strict_mono_of_deriv_pos differentiable_sinh (by { rw [real.deriv_sinh], exact cosh_pos }) end real section /-! Register lemmas for the derivatives of the composition of `real.exp`, `real.cos`, `real.sin`, `real.cosh` and `real.sinh` with a differentiable function, for standalone use and use with `simp`. -/ variables {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} /-! `real.cos`-/ lemma has_deriv_at.cos (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cos (f x)) (- real.sin (f x) * f') x := (real.has_deriv_at_cos (f x)).comp x hf lemma has_deriv_within_at.cos (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cos (f x)) (- real.sin (f x) * f') s x := (real.has_deriv_at_cos (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.cos (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cos (f x)) s x := hf.has_deriv_within_at.cos.differentiable_within_at @[simp] lemma differentiable_at.cos (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cos (f x)) x := hc.has_deriv_at.cos.differentiable_at lemma differentiable_on.cos (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cos (f x)) s := λx h, (hc x h).cos @[simp] lemma differentiable.cos (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cos (f x)) := λx, (hc x).cos lemma deriv_within_cos (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cos (f x)) s x = - real.sin (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cos.deriv_within hxs @[simp] lemma deriv_cos (hc : differentiable_at ℝ f x) : deriv (λx, real.cos (f x)) x = - real.sin (f x) * (deriv f x) := hc.has_deriv_at.cos.deriv /-! `real.sin`-/ lemma has_deriv_at.sin (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sin (f x)) (real.cos (f x) * f') x := (real.has_deriv_at_sin (f x)).comp x hf lemma has_deriv_within_at.sin (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sin (f x)) (real.cos (f x) * f') s x := (real.has_deriv_at_sin (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.sin (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sin (f x)) s x := hf.has_deriv_within_at.sin.differentiable_within_at @[simp] lemma differentiable_at.sin (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sin (f x)) x := hc.has_deriv_at.sin.differentiable_at lemma differentiable_on.sin (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sin (f x)) s := λx h, (hc x h).sin @[simp] lemma differentiable.sin (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sin (f x)) := λx, (hc x).sin lemma deriv_within_sin (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sin (f x)) s x = real.cos (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sin.deriv_within hxs @[simp] lemma deriv_sin (hc : differentiable_at ℝ f x) : deriv (λx, real.sin (f x)) x = real.cos (f x) * (deriv f x) := hc.has_deriv_at.sin.deriv /-! `real.cosh`-/ lemma has_deriv_at.cosh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') x := (real.has_deriv_at_cosh (f x)).comp x hf lemma has_deriv_within_at.cosh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.cosh (f x)) (real.sinh (f x) * f') s x := (real.has_deriv_at_cosh (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.cosh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.cosh (f x)) s x := hf.has_deriv_within_at.cosh.differentiable_within_at @[simp] lemma differentiable_at.cosh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.cosh (f x)) x := hc.has_deriv_at.cosh.differentiable_at lemma differentiable_on.cosh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.cosh (f x)) s := λx h, (hc x h).cosh @[simp] lemma differentiable.cosh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.cosh (f x)) := λx, (hc x).cosh lemma deriv_within_cosh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.cosh (f x)) s x = real.sinh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.cosh.deriv_within hxs @[simp] lemma deriv_cosh (hc : differentiable_at ℝ f x) : deriv (λx, real.cosh (f x)) x = real.sinh (f x) * (deriv f x) := hc.has_deriv_at.cosh.deriv /-! `real.sinh`-/ lemma has_deriv_at.sinh (hf : has_deriv_at f f' x) : has_deriv_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') x := (real.has_deriv_at_sinh (f x)).comp x hf lemma has_deriv_within_at.sinh (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, real.sinh (f x)) (real.cosh (f x) * f') s x := (real.has_deriv_at_sinh (f x)).comp_has_deriv_within_at x hf lemma differentiable_within_at.sinh (hf : differentiable_within_at ℝ f s x) : differentiable_within_at ℝ (λ x, real.sinh (f x)) s x := hf.has_deriv_within_at.sinh.differentiable_within_at @[simp] lemma differentiable_at.sinh (hc : differentiable_at ℝ f x) : differentiable_at ℝ (λx, real.sinh (f x)) x := hc.has_deriv_at.sinh.differentiable_at lemma differentiable_on.sinh (hc : differentiable_on ℝ f s) : differentiable_on ℝ (λx, real.sinh (f x)) s := λx h, (hc x h).sinh @[simp] lemma differentiable.sinh (hc : differentiable ℝ f) : differentiable ℝ (λx, real.sinh (f x)) := λx, (hc x).sinh lemma deriv_within_sinh (hf : differentiable_within_at ℝ f s x) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, real.sinh (f x)) s x = real.cosh (f x) * (deriv_within f s x) := hf.has_deriv_within_at.sinh.deriv_within hxs @[simp] lemma deriv_sinh (hc : differentiable_at ℝ f x) : deriv (λx, real.sinh (f x)) x = real.cosh (f x) * (deriv f x) := hc.has_deriv_at.sinh.deriv end namespace real lemma exists_cos_eq_zero : 0 ∈ cos '' set.Icc (1:ℝ) 2 := intermediate_value_Icc' (by norm_num) continuous_cos.continuous_on ⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩ /-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/ noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero localized "notation `π` := real.pi" in real @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.2 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_mem_Ioo {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_mem_Icc {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_mem_Ioo hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_mem_Ioo (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_mem_Icc (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sub_eq_add_neg, sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff, ← sin_sq_add_cos_sq x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_mem_Ioo (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos]) ... < cos x : cos_pos_of_mem_Ioo (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_right_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq : set.Icc (-1:ℝ) 1 ⊆ sin '' set.Icc (-(π / 2)) (π / 2) := by convert intermediate_value_Icc (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two] lemma exists_cos_eq : (set.Icc (-1) 1 : set ℝ) ⊆ cos '' set.Icc 0 π := by convert intermediate_value_Icc' real.pi_pos.le real.continuous_cos.continuous_on; simp only [real.cos_pi, real.cos_zero] lemma range_cos : set.range cos = (set.Icc (-1) 1 : set ℝ) := begin ext, split, { rintros ⟨y, rfl⟩, exact ⟨y.neg_one_le_cos, y.cos_le_one⟩ }, { rintros h, rcases real.exists_cos_eq h with ⟨y, -, hy⟩, exact ⟨y, hy⟩ } end lemma range_sin : set.range sin = (set.Icc (-1) 1 : set ℝ) := begin ext, split, { rintros ⟨y, rfl⟩, exact ⟨y.neg_one_le_sin, y.sin_le_one⟩ }, { rintros h, rcases real.exists_sin_eq h with ⟨y, -, hy⟩, exact ⟨y, hy⟩ } end lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases le_or_gt x 1 with h' h', { have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.2, rw [sub_le_iff_le_add', hx] at this, apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)), apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h }, exact lt_of_le_of_lt (sin_le_one x) h' end /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x := begin have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.1, rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left, apply add_lt_of_lt_sub_left, rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12, by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num), apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h end section cos_div_pow_two variable (x : ℝ) /-- the series `sqrt_two_add_series x n` is `sqrt(2 + sqrt(2 + ... ))` with `n` square roots, starting with `x`. We define it here because `cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2` -/ @[simp] noncomputable def sqrt_two_add_series (x : ℝ) : ℕ → ℝ | 0 := x | (n+1) := sqrt (2 + sqrt_two_add_series n) lemma sqrt_two_add_series_zero : sqrt_two_add_series x 0 = x := by simp lemma sqrt_two_add_series_one : sqrt_two_add_series 0 1 = sqrt 2 := by simp lemma sqrt_two_add_series_two : sqrt_two_add_series 0 2 = sqrt (2 + sqrt 2) := by simp lemma sqrt_two_add_series_zero_nonneg : ∀(n : ℕ), 0 ≤ sqrt_two_add_series 0 n | 0 := le_refl 0 | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_nonneg {x : ℝ} (h : 0 ≤ x) : ∀(n : ℕ), 0 ≤ sqrt_two_add_series x n | 0 := h | (n+1) := sqrt_nonneg _ lemma sqrt_two_add_series_lt_two : ∀(n : ℕ), sqrt_two_add_series 0 n < 2 | 0 := by norm_num | (n+1) := begin refine lt_of_lt_of_le _ (le_of_eq $ sqrt_sqr $ le_of_lt two_pos), rw [sqrt_two_add_series, sqrt_lt], apply add_lt_of_lt_sub_left, apply lt_of_lt_of_le (sqrt_two_add_series_lt_two n), norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num end lemma sqrt_two_add_series_succ (x : ℝ) : ∀(n : ℕ), sqrt_two_add_series x (n+1) = sqrt_two_add_series (sqrt (2 + x)) n | 0 := rfl | (n+1) := by rw [sqrt_two_add_series, sqrt_two_add_series_succ, sqrt_two_add_series] lemma sqrt_two_add_series_monotone_left {x y : ℝ} (h : x ≤ y) : ∀(n : ℕ), sqrt_two_add_series x n ≤ sqrt_two_add_series y n | 0 := h | (n+1) := begin rw [sqrt_two_add_series, sqrt_two_add_series], apply sqrt_le_sqrt, apply add_le_add_left, apply sqrt_two_add_series_monotone_left end @[simp] lemma cos_pi_over_two_pow : ∀(n : ℕ), cos (pi / 2 ^ (n+1)) = sqrt_two_add_series 0 n / 2 | 0 := by simp | (n+1) := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_two_add_series, sqrt_eq_iff_sqr_eq, mul_pow, cos_square, ←mul_div_assoc, nat.add_succ, pow_succ, mul_div_mul_left, cos_pi_over_two_pow, add_mul], congr, norm_num, rw [mul_comm, pow_two, mul_assoc, ←mul_div_assoc, mul_div_cancel_left, ←mul_div_assoc, mul_div_cancel_left], norm_num, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, norm_num, apply le_of_lt, apply cos_pos_of_mem_Ioo, { transitivity (0 : ℝ), rw neg_lt_zero, apply pi_div_two_pos, apply div_pos pi_pos, apply pow_pos, norm_num }, apply div_lt_div' (le_refl pi) _ pi_pos _, refine lt_of_le_of_lt (le_of_eq (pow_one _).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_lt_succ, apply nat.succ_pos, all_goals {norm_num} end lemma sin_square_pi_over_two_pow (n : ℕ) : sin (pi / 2 ^ (n+1)) ^ 2 = 1 - (sqrt_two_add_series 0 n / 2) ^ 2 := by rw [sin_square, cos_pi_over_two_pow] lemma sin_square_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) ^ 2 = 1 / 2 - sqrt_two_add_series 0 n / 4 := begin rw [sin_square_pi_over_two_pow, sqrt_two_add_series, div_pow, sqr_sqrt, add_div, ←sub_sub], congr, norm_num, norm_num, apply add_nonneg, norm_num, apply sqrt_two_add_series_zero_nonneg, end @[simp] lemma sin_pi_over_two_pow_succ (n : ℕ) : sin (pi / 2 ^ (n+2)) = sqrt (2 - sqrt_two_add_series 0 n) / 2 := begin symmetry, rw [div_eq_iff_mul_eq], symmetry, rw [sqrt_eq_iff_sqr_eq, mul_pow, sin_square_pi_over_two_pow_succ, sub_mul], { congr, norm_num, rw [mul_comm], convert mul_div_cancel' _ _, norm_num, norm_num }, { rw [sub_nonneg], apply le_of_lt, apply sqrt_two_add_series_lt_two }, apply le_of_lt, apply mul_pos, apply sin_pos_of_pos_of_lt_pi, { apply div_pos pi_pos, apply pow_pos, norm_num }, refine lt_of_lt_of_le _ (le_of_eq (div_one _)), rw [div_lt_div_left], refine lt_of_le_of_lt (le_of_eq (pow_zero 2).symm) _, apply pow_lt_pow, norm_num, apply nat.succ_pos, apply pi_pos, apply pow_pos, all_goals {norm_num} end lemma cos_pi_div_four : cos (pi / 4) = sqrt 2 / 2 := by { transitivity cos (pi / 2 ^ 2), congr, norm_num, simp } lemma sin_pi_div_four : sin (pi / 4) = sqrt 2 / 2 := by { transitivity sin (pi / 2 ^ 2), congr, norm_num, simp } lemma cos_pi_div_eight : cos (pi / 8) = sqrt (2 + sqrt 2) / 2 := by { transitivity cos (pi / 2 ^ 3), congr, norm_num, simp } lemma sin_pi_div_eight : sin (pi / 8) = sqrt (2 - sqrt 2) / 2 := by { transitivity sin (pi / 2 ^ 3), congr, norm_num, simp } lemma cos_pi_div_sixteen : cos (pi / 16) = sqrt (2 + sqrt (2 + sqrt 2)) / 2 := by { transitivity cos (pi / 2 ^ 4), congr, norm_num, simp } lemma sin_pi_div_sixteen : sin (pi / 16) = sqrt (2 - sqrt (2 + sqrt 2)) / 2 := by { transitivity sin (pi / 2 ^ 4), congr, norm_num, simp } lemma cos_pi_div_thirty_two : cos (pi / 32) = sqrt (2 + sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity cos (pi / 2 ^ 5), congr, norm_num, simp } lemma sin_pi_div_thirty_two : sin (pi / 32) = sqrt (2 - sqrt (2 + sqrt (2 + sqrt 2))) / 2 := by { transitivity sin (pi / 2 ^ 5), congr, norm_num, simp } end cos_div_pow_two /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (add_subgroup.gmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance : inhabited angle := ⟨0⟩ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) : ↑((n : ℝ) * x) = n •ℕ (↑x : angle) := by simpa using add_monoid_hom.map_nsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp, norm_cast] lemma coe_int_mul_eq_gsmul (x : ℝ) (n : ℤ) : ↑((n : ℝ) * x : ℝ) = n •ℤ (↑x : angle) := by simpa using add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, show (-1 : ℤ) •ℤ (2 * π) = _, by rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, add_subgroup.gmultiples_eq_closure, add_subgroup.mem_closure_singleton, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _), ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq (@two_ne_zero ℝ _), eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, coe_int_mul_eq_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_right_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ (@two_ne_zero ℝ _), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ (@two_ne_zero ℝ _), cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, change n •ℤ _ = _ at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.2 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq ⟨hx₁, hx₂⟩)).2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [sub_eq_add_neg, arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_mem_Icc (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 @[simp] lemma tan_pi_div_four : tan (π / 4) = 1 := begin rw [tan_eq_sin_div_cos, cos_pi_div_four, sin_pi_div_four], have h : (sqrt 2) / 2 > 0 := by cancel_denoms, exact div_self (ne_of_gt h), end lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_mem_Ioo (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith)) (cos_pos_of_mem_Ioo (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow, pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← mul_right_inj' (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.right_inverse.surjective tan_arctan lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_one : arctan 1 = π / 4 := begin refine tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan 1) (arctan_lt_pi_div_two 1) _ _ _; linarith [pi_pos, tan_arctan 1, tan_pi_div_four], end @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex open_locale real /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_nonneg _))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow, ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [sub_eq_add_neg, real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := begin by_cases h : x = 0, { simp only [h, zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] }, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right _ (mt abs_eq_zero.1 h)] end lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_mem_Icc hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; try {simp [add_left_comm]}; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) lemma log_of_real_re (x : ℝ) : (log (x : ℂ)).re = real.log x := by simp [log_re] @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma exp_pi_mul_I : exp (π * I) = -1 := by { rw exp_mul_I, simp, } 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 (by norm_num), zero_mul, add_eq_zero_iff_eq_neg, neg_eq_neg_one_mul (exp (-θ * I)), ← div_eq_iff (exp_ne_zero (-θ * I)), ← exp_sub], field_simp, ring }, rw [cos, h, ← exp_pi_mul_I, exp_eq_exp_iff_exists_int], split; simp; intros; use x, { field_simp, ring at a, rwa [mul_right_comm 2 I θ, mul_right_comm (2*(x:ℂ)+1) I (π:ℂ), mul_left_inj' I_ne_zero, mul_comm 2 θ] at a }, { field_simp at a, ring, rw [mul_right_comm 2 I θ, mul_right_comm (2*(x:ℂ)+1) I (π:ℂ), mul_left_inj' I_ne_zero, mul_comm 2 θ, a] }, end theorem cos_ne_zero_iff {θ : ℂ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 := by rw [← not_exists, not_iff_not, cos_eq_zero_iff] lemma has_deriv_at_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : has_deriv_at tan (1 / (cos x)^2) x := begin convert has_deriv_at.div (has_deriv_at_sin x) (has_deriv_at_cos x) (cos_ne_zero_iff.mpr h), rw ← sin_sq_add_cos_sq x, ring, end lemma differentiable_at_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : differentiable_at ℂ tan x := (has_deriv_at_tan h).differentiable_at @[simp] lemma deriv_tan {x : ℂ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : deriv tan x = 1 / (cos x)^2 := (has_deriv_at_tan h).deriv lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) := (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} := by { rw continuous_on_iff_continuous_restrict, convert continuous_tan } end complex namespace real open_locale real theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * π / 2 := begin rw [← complex.of_real_eq_zero, complex.of_real_cos θ], convert @complex.cos_eq_zero_iff θ, norm_cast, end theorem cos_ne_zero_iff {θ : ℝ} : cos θ ≠ 0 ↔ ∀ k : ℤ, θ ≠ (2 * k + 1) * π / 2 := by rw [← not_exists, not_iff_not, cos_eq_zero_iff] lemma has_deriv_at_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : has_deriv_at tan (1 / (cos x)^2) x := begin convert has_deriv_at_real_of_complex (complex.has_deriv_at_tan (by { convert h, norm_cast } )), rw ← complex.of_real_re (1/((cos x)^2)), simp, end lemma differentiable_at_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : differentiable_at ℝ tan x := (has_deriv_at_tan h).differentiable_at @[simp] lemma deriv_tan {x : ℝ} (h : ∀ k : ℤ, x ≠ (2 * k + 1) * π / 2) : deriv tan x = 1 / (cos x)^2 := (has_deriv_at_tan h).deriv lemma continuous_tan : continuous (λ x : {x | cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma continuous_on_tan : continuous_on tan {x | cos x ≠ 0} := by { rw continuous_on_iff_continuous_restrict, convert continuous_tan } lemma has_deriv_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ set.Ioo (-(π/2):ℝ) (π/2)) : has_deriv_at tan (1 / (cos x)^2) x := has_deriv_at_tan (cos_ne_zero_iff.mp (ne_of_gt (cos_pos_of_mem_Ioo h.1 h.2))) lemma differentiable_at_tan_of_mem_Ioo {x : ℝ} (h : x ∈ set.Ioo (-(π/2):ℝ) (π/2)) : differentiable_at ℝ tan x := (has_deriv_at_tan_of_mem_Ioo h).differentiable_at lemma deriv_tan_of_mem_Ioo {x : ℝ} (h : x ∈ set.Ioo (-(π/2):ℝ) (π/2)) : deriv tan x = 1 / (cos x)^2 := (has_deriv_at_tan_of_mem_Ioo h).deriv end real
2b2178b96df19d2551f1b84af72b54c04e5ab035
ddf69e0b8ad10bfd251aa1fb492bd92f064768ec
/src/data/int/basic.lean
a45414ee4f2854c9c64e9f937125019c2e74feae
[ "Apache-2.0" ]
permissive
MaboroshiChan/mathlib
db1c1982df384a2604b19a5e1f5c6464c7c76de1
7f74e6b35f6bac86b9218250e83441ac3e17264c
refs/heads/master
1,671,993,587,476
1,601,911,102,000
1,601,911,102,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
47,928
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The integers, with addition, multiplication, and subtraction. -/ import data.nat.basic import algebra.order_functions open nat namespace int instance : inhabited ℤ := ⟨int.zero⟩ instance : nontrivial ℤ := ⟨⟨0, 1, int.zero_ne_one⟩⟩ instance : comm_ring int := { add := int.add, add_assoc := int.add_assoc, zero := int.zero, zero_add := int.zero_add, add_zero := int.add_zero, neg := int.neg, add_left_neg := int.add_left_neg, add_comm := int.add_comm, mul := int.mul, mul_assoc := int.mul_assoc, one := int.one, one_mul := int.one_mul, mul_one := int.mul_one, left_distrib := int.distrib_left, right_distrib := int.distrib_right, mul_comm := int.mul_comm } /- Extra instances to short-circuit type class resolution -/ -- instance : has_sub int := by apply_instance -- This is in core instance : add_comm_monoid int := by apply_instance instance : add_monoid int := by apply_instance instance : monoid int := by apply_instance instance : comm_monoid int := by apply_instance instance : comm_semigroup int := by apply_instance instance : semigroup int := by apply_instance instance : add_comm_semigroup int := by apply_instance instance : add_semigroup int := by apply_instance instance : comm_semiring int := by apply_instance instance : semiring int := by apply_instance instance : ring int := by apply_instance instance : distrib int := by apply_instance instance : decidable_linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, mul_pos := @int.mul_pos, zero_lt_one := int.zero_lt_one, .. int.comm_ring, .. int.decidable_linear_order, .. int.nontrivial } instance : decidable_linear_ordered_add_comm_group int := by apply_instance theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] @[simp] lemma default_eq_zero : default ℤ = 0 := rfl meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩ meta instance : has_reflect ℤ := by tactic.mk_has_reflect_instance attribute [simp] int.coe_nat_add int.coe_nat_mul int.coe_nat_zero int.coe_nat_one int.coe_nat_succ attribute [simp] int.of_nat_eq_coe int.bodd @[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl @[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl @[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl @[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl @[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl @[simp, norm_cast] theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n @[simp, norm_cast] theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n @[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := by rw [← int.coe_nat_zero, coe_nat_lt] @[simp] theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := by rw [← int.coe_nat_zero, coe_nat_inj'] theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := not_congr coe_nat_eq_zero @[simp] lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _) lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n := ⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h), λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩ lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n) @[simp, norm_cast] theorem coe_nat_abs (n : ℕ) : abs (n : ℤ) = n := abs_of_nonneg (coe_nat_nonneg n) /- succ and pred -/ /-- Immediate successor of an integer: `succ n = n + 1` -/ def succ (a : ℤ) := a + 1 /-- Immediate predecessor of an integer: `pred n = n - 1` -/ def pred (a : ℤ) := a - 1 theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _ theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _ theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _ theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a := by rw [neg_succ, succ_pred] theorem neg_pred (a : ℤ) : -pred a = succ (-a) := by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg] theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a := by rw [neg_pred, pred_succ] theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n theorem lt_succ_self (a : ℤ) : a < succ a := lt_add_of_pos_right _ zero_lt_one theorem pred_self_lt (a : ℤ) : pred a < a := sub_lt_self _ zero_lt_one theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b := @add_le_add_iff_right _ _ a b 1 lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 := le_of_lt (int.lt_add_one_iff.mpr h) theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b := sub_lt_iff_lt_add.trans lt_add_one_iff theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b := le_sub_iff_add_le @[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop} (i : ℤ) (hz : p 0) (hp : ∀i : ℕ, p i → p (i + 1)) (hn : ∀i : ℕ, p (-i) → p (-i - 1)) : p i := begin induction i, { induction i, { exact hz }, { exact hp _ i_ih } }, { have : ∀n:ℕ, p (- n), { intro n, induction n, { simp [hz] }, { convert hn _ n_ih using 1, simp [sub_eq_neg_add] } }, exact this (i + 1) } end protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ) : C b → (∀ k, b ≤ k → C k → C (k + 1)) → (∀ k ≤ b, C k → C (k - 1)) → C z := λ H0 Hs Hp, begin rw ←sub_add_cancel z b, induction (z - b), { induction a with n ih, { rwa [of_nat_zero, zero_add] }, rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc], exact Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih }, { induction a with n ih, { rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub], exact Hp _ (le_refl _) H0 }, { rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub], exact Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) (le_refl _))) ih } } end /- nat abs -/ attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b := begin have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b), { refine (λ a b : ℕ, sub_nat_nat_elim a b.succ (λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ _ rfl); intros i n e, { subst e, rw [add_comm _ i, add_assoc], exact nat.le_add_right i (b.succ + b).succ }, { apply succ_le_succ, rw [← succ.inj e, ← add_assoc, add_comm], apply nat.le_add_right } }, cases a; cases b with b b; simp [nat_abs, nat.succ_add]; try {refl}; [skip, rw add_comm a b]; apply this end theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n := by cases n; refl theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) := by cases a; cases b; simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs] @[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a := by rw [← int.coe_nat_mul, nat_abs_mul_self] theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 := by simp [neg_succ_of_nat_eq, sub_eq_neg_add] lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 := λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h @[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 := ⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩ lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) : a.nat_abs < b.nat_abs := begin lift b to ℕ using le_trans w₁ (le_of_lt w₂), lift a to ℕ using w₁, simpa using w₂, end /- / -/ @[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl @[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) : -[1+m] / b = -(m / b + 1) := match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end @[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b) | (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl | (m : ℕ) (n+1:ℕ) := rfl | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := (neg_neg _).symm | -[1+ m] 0 := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl end protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b := match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _ end protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 := nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb) theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 := match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _ end -- Will be generalized to Euclidean domains. protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl local attribute [simp] -- Will be generalized to Euclidean domains. protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0 | 0 := rfl | (n+1:ℕ) := rfl | -[1+ n] := rfl @[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a | 0 := rfl | (n+1:ℕ) := congr_arg of_nat (nat.div_one _) | -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _) theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 := match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2 end theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < abs b) : a / b = 0 := match b, abs b, abs_eq_nat_abs b, H2 with | (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2 | -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2 end protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) : (a + b * c) / c = a / c + b := have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from λ k n a, match a with | (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos | -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ = n - (m / k.succ + 1 : ℕ), begin cases lt_or_ge m (n*k.succ) with h h, { rw [← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.div_lt_iff_lt_mul _ _ k.succ_pos).2 h)], apply congr_arg of_nat, rw [mul_comm, nat.mul_sub_div], rwa mul_comm }, { change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) = ↑n - ((m / nat.succ k : ℕ) + 1), rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ), ← int.coe_nat_sub h, ← int.coe_nat_sub ((nat.le_div_iff_mul_le _ _ k.succ_pos).2 h), ← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'], { apply congr_arg neg_succ_of_nat, rw [mul_comm, nat.sub_mul_div], rwa mul_comm } } end end, have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from λ a b c H, match c, eq_succ_of_zero_lt H, b with | ._, ⟨k, rfl⟩, (n : ℕ) := this | ._, ⟨k, rfl⟩, -[1+ n] := show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from eq_sub_of_add_eq $ by rw [← this, sub_add_cancel] end, match lt_trichotomy c 0 with | or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg]; apply this (neg_pos_of_neg hlt) | or.inr (or.inl heq) := absurd heq H | or.inr (or.inr hgt) := this hgt end protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) : (a + b * c) / b = a / b + c := by rw [mul_comm, int.add_mul_div_right _ _ H] @[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a := by have := int.add_mul_div_right 0 a H; rwa [zero_add, int.zero_div, zero_add] at this @[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b := by rw [mul_comm, int.mul_div_cancel _ H] @[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 := by have := int.mul_div_cancel 1 H; rwa one_mul at this /- mod -/ theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl @[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) : -[1+m] % b = b - 1 - m % b := by rw [sub_sub, add_comm]; exact match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end @[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b | (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _) @[simp] theorem mod_abs (a b : ℤ) : a % (abs b) = a % b := abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _) local attribute [simp] -- Will be generalized to Euclidean domains. theorem zero_mod (b : ℤ) : 0 % b = 0 := congr_arg of_nat $ nat.zero_mod _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_zero : ∀ (a : ℤ), a % 0 = a | (m : ℕ) := congr_arg of_nat $ nat.mod_zero _ | -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _ local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_one : ∀ (a : ℤ), a % 1 = 0 | (m : ℕ) := congr_arg of_nat $ nat.mod_one _ | -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a := match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with | ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 := congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2) end theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b | (m : ℕ) n H := coe_zero_le _ | -[1+ m] n H := sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H) theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b := match a, b, eq_succ_of_zero_lt H with | (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _)) | -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _) end theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < abs b := by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos_of_ne_zero H) theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] := begin rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)], apply eq_neg_of_eq_neg, rw [neg_sub, sub_sub_self, add_right_comm], exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm end theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a | (m : ℕ) 0 := congr_arg of_nat (nat.mod_add_div _ _) | (m : ℕ) (n+1:ℕ) := congr_arg of_nat (nat.mod_add_div _ _) | 0 -[1+ n] := rfl | (m+1:ℕ) -[1+ n] := show (_ + -(n+1) * -((m + 1) / (n + 1) : ℕ) : ℤ) = _, by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _) | -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl | -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ | -[1+ m] -[1+ n] := mod_add_div_aux m n.succ theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) := eq_sub_of_add_eq (mod_add_div _ _) @[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c := if cz : c = 0 then by rw [cz, mul_zero, add_zero] else by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz, mul_add, mul_comm, add_sub_add_right_eq_sub] @[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b := by rw [mul_comm, add_mul_mod_self] @[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b := by have := add_mul_mod_self_left a b 1; rwa mul_one at this @[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a := by rw [add_comm, add_mod_self] @[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n := by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm; rwa [add_right_comm, mod_add_div] at this @[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k := by rw [add_comm, mod_add_mod, add_comm] lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n := by rw [add_mod_mod, mod_add_mod] theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := by rw [← mod_add_mod, ← mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm] theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔ m % n = k % n := ⟨λ H, by have := add_mod_eq_add_mod_right (-i) H; rwa [add_neg_cancel_right, add_neg_cancel_right] at this, add_mod_eq_add_mod_right _⟩ theorem mod_add_cancel_left {m n k i : ℤ} : (i + m) % n = (i + k) % n ↔ m % n = k % n := by rw [add_comm, add_comm i, mod_add_cancel_right] theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔ m % n = k % n := mod_add_cancel_right _ theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 := (mod_sub_cancel_right k).symm.trans $ by simp @[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 := by rw [← zero_add (a * b), add_mul_mod_self, zero_mod] @[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 := by rw [mul_comm, mul_mod_left] lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n := begin conv_lhs { rw [←mod_add_div a n, ←mod_add_div b n, right_distrib, left_distrib, left_distrib, mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, mul_comm _ (n * (b / n)), mul_assoc, add_mul_mod_self_left] } end local attribute [simp] -- Will be generalized to Euclidean domains. theorem mod_self {a : ℤ} : a % a = 0 := by have := mul_mod_left 1 a; rwa one_mul at this @[simp] theorem mod_mod_of_dvd (n : int) {m k : int} (h : m ∣ k) : n % k % m = n % m := begin conv { to_rhs, rw ←mod_add_div n k }, rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left] end @[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b := by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]} lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n := begin apply (mod_add_cancel_right b).mp, rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod] end /- properties of / and % -/ @[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c := suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with | ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _ | ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ := by rw [← neg_mul_eq_mul_neg, int.div_neg, int.div_neg]; apply congr_arg has_neg.neg; apply this end, λ m k b, match b, k with | (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos) | -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero] | -[1+ n], k+1 := congr_arg neg_succ_of_nat $ show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin apply nat.div_eq_of_lt_le, { refine le_trans _ (nat.le_add_right _ _), rw [← nat.mul_div_mul _ _ m.succ_pos], apply nat.div_mul_le_self }, { change m.succ * n.succ ≤ _, rw [mul_left_comm], apply nat.mul_le_mul_left, apply (nat.div_lt_iff_lt_mul _ _ k.succ_pos).1, apply nat.lt_succ_self } end end @[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (c : ℤ) (H : 0 < b) : a * b / (c * b) = a / c := by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H] @[simp] theorem mul_mod_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b % (a * c) = a * (b % c) := by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc] theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b := by rw [add_mul, one_mul, mul_comm]; apply lt_add_of_sub_left_lt; rw [← mod_def]; apply mod_lt_of_pos _ H theorem abs_div_le_abs : ∀ (a b : ℤ), abs (a / b) ≤ abs a := suffices ∀ (a : ℤ) (n : ℕ), abs (a / n) ≤ abs a, from λ a b, match b, eq_coe_or_neg b with | ._, ⟨n, or.inl rfl⟩ := this _ _ | ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this end, λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact coe_nat_le_coe_nat_of_le (match a, n with | (m : ℕ), n := nat.div_le_self _ _ | -[1+ m], 0 := nat.zero_le _ | -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _) end) theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a := by have := le_trans (le_abs_self _) (abs_div_le_abs a b); rwa [abs_of_nonneg Ha] at this theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a := by have := mod_add_div a b; rwa [H, zero_add] at this theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a := by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H] lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 := have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial, have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial, match (n % 2), h, h₁ with | (0 : ℕ) := λ _ _, or.inl rfl | (1 : ℕ) := λ _ _, or.inr rfl | (k + 2 : ℕ) := λ h _, absurd h dec_trivial | -[1+ a] := λ _ h₁, absurd h₁ dec_trivial end /- dvd -/ @[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n := ⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim (λm0, by simp [m0] at ae; simp [ae, m0]) (λm0l, by { cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_left ℤ _ m a (by simp [ae.symm]) (by simpa using m0l)) with k e, subst a, exact ⟨k, int.coe_nat_inj ae⟩ }), λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩ theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n := by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd] theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b := begin rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs], rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'], apply nat.dvd_antisymm end theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b := ⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩ theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0 | a ._ ⟨c, rfl⟩ := mul_mod_right _ _ theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ /-- If `a % b = c` then `b` divides `a - c`. -/ lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c := begin have hx : a % b % b = c % b, { rw h }, rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx, exact dvd_of_mod_eq_zero hx end theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b := (nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd_iff_dvd, ← e]) theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b := (nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg_iff_dvd, ← e]) instance decidable_dvd : @decidable_rel ℤ (∣) := assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b := by rw [mul_comm, int.div_mul_cancel H] protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c) | ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz] theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a | a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az]; apply dvd_mul_right protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, int.mul_div_cancel' H1] protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) : a / b = c := by rw [H2, int.mul_div_cancel_left _ H1] protected theorem eq_div_of_mul_eq_right {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) : b = c / a := eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2] protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) : a / b = c := int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2]) theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b) | ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz] lemma add_div_of_dvd {a b c : ℤ} : c ∣ a → c ∣ b → (a + b) / c = a / c + b / c := begin intros h1 h2, by_cases h3 : c = 0, { rw [h3, zero_dvd_iff] at *, rw [h1, h2, h3], refl }, { apply mul_right_cancel' h3, rw add_mul, repeat {rw [int.div_mul_cancel]}; try {apply dvd_add}; assumption } end theorem div_sign : ∀ a b, a / sign b = a * sign b | a (n+1:ℕ) := by unfold sign; simp | a 0 := by simp [sign] | a -[1+ n] := by simp [sign] @[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b | a 0 := by simp | 0 b := by simp | (m+1:ℕ) (n+1:ℕ) := rfl | (m+1:ℕ) -[1+ n] := rfl | -[1+ m] (n+1:ℕ) := rfl | -[1+ m] -[1+ n] := rfl protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / (abs a) := if az : a = 0 then by simp [az] else (int.div_eq_of_eq_mul_left (mt eq_zero_of_abs_eq_zero az) (sign_mul_abs _).symm).symm theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i | (n+1:ℕ) := mul_one _ | 0 := mul_zero _ | -[1+ n] := mul_neg_one _ theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b := match a, b, eq_succ_of_zero_lt bpos, H with | (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $ nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H | -[1+ m], ._, ⟨n, rfl⟩, _ := le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _) end theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 := match a, eq_coe_of_zero_le H, H' with | ._, ⟨n, rfl⟩, H' := congr_arg coe $ nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H' end theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 := eq_one_of_dvd_one H ⟨b, H'.symm⟩ theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (by rw [mul_comm, H']) lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z | (int.of_nat _) haz := int.coe_nat_dvd.2 haz | -[1+k] haz := begin change ↑a ∣ -(k+1 : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, exact haz end lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs | (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz) | -[1+k] haz := have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz, int.coe_nat_dvd.1 haz' lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) : ↑(p ^ m) ∣ k := begin induction k, { apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1 hdiv }, { change -[1+k] with -(↑(k+1) : ℤ), apply dvd_neg_of_dvd, apply int.coe_nat_dvd.2, apply pow_dvd_of_le_of_pow_dvd hmn, apply int.coe_nat_dvd.1, apply dvd_of_dvd_neg, exact hdiv } end lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m := by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk /- / and ordering -/ protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a := le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b := le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b := lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3) protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b := le_trans (mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1)) protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c := le_of_lt_add_one $ lt_of_mul_lt_mul_right (lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1) protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩ protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c := int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H') protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b := lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H') protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c := lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2) protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c := ⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩ protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) : a ≤ c * b := by rw [← int.div_mul_cancel H2]; exact mul_le_mul_of_nonneg_right H3 H1 protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) : a < c / b := lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3) protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) : a < b / c ↔ a * c < b := ⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩ theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b := int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul) theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0) (H4 : d ≠ 0) (H5 : a * d = b * c) : a / b = c / d := int.div_eq_of_eq_mul_right H3 $ by rw [← int.mul_div_assoc _ H2]; exact (int.div_eq_of_eq_mul_left H4 H5.symm).symm theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c) (h : b * a = c * d) : a = c / b * d := begin cases hbc with k hk, subst hk, rw [int.mul_div_cancel_left _ hb], rw mul_assoc at h, apply mul_left_cancel' hb h end /-- If an integer with larger absolute value divides an integer, it is zero. -/ lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) : b = 0 := begin rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w, rw ←nat_abs_eq_zero, exact eq_zero_of_dvd_of_lt w h end lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 := eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂) /-- If two integers are congruent to a sufficiently large modulus, they are equal. -/ lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c) (h2 : nat_abs (a - c) < nat_abs b) : a = c := eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2) theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) : of_nat m + -[1+n] = -[1+ n - m] := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = (n - m).succ, apply succ_sub, apply le_of_lt_succ h, simp [*, sub_nat_nat] end theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ} (h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) := begin change sub_nat_nat _ _ = _, have h' : n.succ - m = 0, apply sub_eq_zero_of_le h, simp [*, sub_nat_nat] end @[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl /- to_nat -/ theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0 | (n : ℕ) := (max_eq_left (coe_zero_le n)).symm | -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm @[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl @[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl @[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a := by rw [to_nat_eq_max, max_eq_left h] @[simp] lemma to_nat_sub_of_le (a b : ℤ) (h : b ≤ a) : (to_nat (a + -b) : ℤ) = a + - b := int.to_nat_of_nonneg (sub_nonneg_of_le h) @[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl @[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl theorem le_to_nat (a : ℤ) : a ≤ to_nat a := by rw [to_nat_eq_max]; apply le_max_left @[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n := by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff]; exact and_iff_left (coe_zero_le _) @[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a := le_iff_le_iff_lt_iff_lt.1 to_nat_le theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b := by rw to_nat_le; exact le_trans h (le_to_nat b) theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b := ⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end, λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩ theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b := (to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : (a + b).to_nat = a.to_nat + b.to_nat := begin lift a to ℕ using ha, lift b to ℕ using hb, norm_cast, end lemma to_nat_add_one {a : ℤ} (h : 0 ≤ a) : (a + 1).to_nat = a.to_nat + 1 := to_nat_add h (zero_le_one) def to_nat' : ℤ → option ℕ | (n : ℕ) := some n | -[1+ n] := none theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n | (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm | -[1+ m] n := by split; intro h; cases h lemma to_nat_zero_of_neg : ∀ {z : ℤ}, z < 0 → z.to_nat = 0 | (-[1+n]) _ := rfl | (int.of_nat n) h := (not_le_of_gt h $ int.of_nat_nonneg n).elim /- units -/ @[simp] theorem units_nat_abs (u : units ℤ) : nat_abs u = 1 := units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹, by rw [← nat_abs_mul, units.mul_inv]; refl, by rw [← nat_abs_mul, units.inv_mul]; refl⟩ theorem units_eq_one_or (u : units ℤ) : u = 1 ∨ u = -1 := by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u lemma units_inv_eq_self (u : units ℤ) : u⁻¹ = u := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) /- bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl @[simp] lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma div2_bit (b n) : div2 (bit b n) = n := begin rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add], cases b, all_goals {exact dec_trivial} end @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, nat.sub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, nat.add_sub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, nat.sub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ /- Least upper bound property for integers -/ section classical open_locale classical theorem exists_least_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → b ≤ z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, P z → lb ≤ z) := let ⟨b, Hb⟩ := Hbdd in have EX : ∃ n : ℕ, P (b + n), from let ⟨elt, Helt⟩ := Hinh in match elt, le.dest (Hb _ Helt), Helt with | ._, ⟨n, rfl⟩, Hn := ⟨n, Hn⟩ end, ⟨b + (nat.find EX : ℤ), nat.find_spec EX, λ z h, match z, le.dest (Hb _ h), h with | ._, ⟨n, rfl⟩, h := add_le_add_left (int.coe_nat_le.2 $ nat.find_min' _ h) _ end⟩ theorem exists_greatest_of_bdd {P : ℤ → Prop} (Hbdd : ∃ b : ℤ, ∀ z : ℤ, P z → z ≤ b) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, P z → z ≤ ub) := have Hbdd' : ∃ (b : ℤ), ∀ (z : ℤ), P (-z) → b ≤ z, from let ⟨b, Hb⟩ := Hbdd in ⟨-b, λ z h, neg_le.1 (Hb _ h)⟩, have Hinh' : ∃ z : ℤ, P (-z), from let ⟨elt, Helt⟩ := Hinh in ⟨-elt, by rw [neg_neg]; exact Helt⟩, let ⟨lb, Plb, al⟩ := exists_least_of_bdd Hbdd' Hinh' in ⟨-lb, Plb, λ z h, le_neg.1 $ al _ $ by rwa neg_neg⟩ end classical end int
2a5f632600dac8e162d9cf622166e61277193bfc
d8820d2c92be8052d13f9c8f8c483a6e15c5f566
/src/M40002/M40002_C5.lean
47800f312a010829baa4dbc61a7548834f8cac62
[]
no_license
JasonKYi/M4000x_LEAN_formalisation
4a19b84f6d0fe2e214485b8532e21cd34996c4b1
6e99793f2fcbe88596e27644f430e46aa2a464df
refs/heads/master
1,599,755,414,708
1,589,494,604,000
1,589,494,604,000
221,759,483
8
1
null
1,589,494,605,000
1,573,755,201,000
Lean
UTF-8
Lean
false
false
25,465
lean
-- M40002 (Analysis I) Chapter 5. Continuity import M40002.M40002_C4 import data.polynomial namespace M40002 -- Definition of limits of functions (f(x) → b as x → a) def func_converges_to (f : ℝ → ℝ) (a b : ℝ) := ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, abs (x - a) < δ → abs (f x - b) < ε -- Definition of continuity at a point def func_continuous_at (f : ℝ → ℝ) (a : ℝ) := func_converges_to f a (f a) -- Definition of a continuous function def func_continuous (f : ℝ → ℝ) := ∀ a : ℝ, func_continuous_at f a -- Defintion composition of functions and sequences for sequential continuity def func_seq_comp (f : ℝ → ℝ) (s : ℕ → ℝ) (n : ℕ) := f (s n) -- The definition for limits can have an alternative restriction of 0 < abs (x - a) theorem func_continuous_at_to_pos (f : ℝ → ℝ) (a : ℝ) : func_continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, 0 < abs (x - a) ∧ abs (x - a) < δ → abs (f x - f a) < ε := begin split, {intros hconv ε hε, rcases hconv ε hε with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, use δ, use hδ₁, intros x hx, from hδ₂ x hx.right }, {intros hconv ε hε, rcases hconv ε hε with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, use δ, use hδ₁, intros x hx, cases lt_or_le 0 (abs (x - a)), from hδ₂ x ⟨h, hx⟩, have : x = a := by {suffices : abs (x - a) = 0, from eq_of_abs_sub_eq_zero this, cases lt_or_eq_of_le h, rw ←not_le at h_1, exfalso, apply h_1, from abs_nonneg (x - a), assumption }, rw this, simp, assumption } end -- Sequential continuity lemma seq_contin_conv_lem {s : ℕ → ℝ} {a : ℝ} (h : ∀ n : ℕ, abs (s n - a) < 1 / (n + 1)) : s ⇒ a := begin intros ε hε, cases exists_nat_gt (1 / ε) with N₀ hN₀, let N : ℕ := max N₀ 1, have hN : 1 / ε < (N : ℝ) := by {apply lt_of_lt_of_le hN₀, norm_cast, apply le_max_left }, use N, intros n hn, apply lt_trans (h n), rw one_div_lt _ hε, {apply lt_trans hN, norm_cast, linarith}, {norm_cast, linarith} end theorem lambda_rw (n : ℕ) (f : ℕ → ℝ) : (λ x : ℕ, f x) n = f n := by {rw eq_self_iff_true, trivial} theorem seq_contin {f : ℝ → ℝ} {a b : ℝ} : (func_converges_to f a b) ↔ ∀ s : ℕ → ℝ, s ⇒ a → func_seq_comp f s ⇒ b := begin split, {intros h s hs ε hε, rcases h ε hε with ⟨δ, ⟨hδ, hr⟩⟩, cases hs δ hδ with N hN, use N, intros n hn, have : abs (s n - a) < δ := hN n hn, from hr (s n) this }, {intros h, cases classical.em (func_converges_to f a b) with ha ha, from ha, unfold func_converges_to at ha, push_neg at ha, rcases ha with ⟨ε, ⟨hε, hδ⟩⟩, have hα : ∀ n : ℕ, 1 / ((n : ℝ) + 1) > 0 := by {intro n, simp, norm_cast, from nat.zero_lt_one_add n}, have hβ : ∀ n : ℕ, ∃ (x : ℝ), abs (x - a) < (1 / (n + 1)) ∧ ε ≤ abs (f x - b) := λ n, hδ (1 / (n + 1)) (hα n), let s : ℕ → ℝ := λ n : ℕ, classical.some (hβ n), have h₀ : s = λ n : ℕ, classical.some (hβ n) := rfl, have hsn : ∀ n : ℕ, abs (s n - a) < 1 / ((n : ℝ) + 1) ∧ ε ≤ abs (func_seq_comp f s n - b) := by {intro n, rw [h₀, lambda_rw n s], from classical.some_spec (hβ n) }, have h₁ : s ⇒ a := by {have : ∀ n : ℕ, abs (s n - a) < 1 / ((n : ℝ) + 1) := by {intro n, from (hsn n).left}, from seq_contin_conv_lem this }, have h₂ : ¬ (func_seq_comp f s ⇒ b) := by {unfold converges_to, push_neg, use ε, split, from hε, intro N, use N, split, from nat.le_refl N, from (hsn N).right }, exfalso; from h₂ (h s h₁) } end -- Algebra of limits for functions def func_add_func (f g : ℝ → ℝ) := λ r : ℝ, f r + g r instance : has_add (ℝ → ℝ) := ⟨func_add_func⟩ theorem func_add_func_conv (f g : ℝ → ℝ) (a b₁ b₂) : func_converges_to f a b₁ ∧ func_converges_to g a b₂ → func_converges_to (f + g) a (b₁ + b₂) := begin rintro ⟨ha, hb⟩, rw seq_contin, intros s hs, have : func_seq_comp (f + g) s = seq_add_seq (func_seq_comp f s) (func_seq_comp g s) := rfl, rw this, apply add_lim_conv, from ⟨seq_contin.mp ha s hs, seq_contin.mp hb s hs⟩ end theorem func_add_func_contin (f g : ℝ → ℝ) : func_continuous f ∧ func_continuous g → func_continuous (f + g) := begin rintros ⟨ha, hb⟩ a, apply func_add_func_conv, from ⟨ha a, hb a⟩ end def func_mul_func (f g : ℝ → ℝ) := λ r : ℝ, f r * g r notation f ` × ` g := func_mul_func f g theorem func_mul_func_conv (f g : ℝ → ℝ) (a b₁ b₂) : func_converges_to f a b₁ ∧ func_converges_to g a b₂ → func_converges_to (f × g) a (b₁ * b₂) := begin rintro ⟨ha, hb⟩, rw seq_contin, intros s hs, have : func_seq_comp (f × g) s = seq_mul_seq (func_seq_comp f s) (func_seq_comp g s) := rfl, rw this, apply mul_lim_conv, from seq_contin.mp ha s hs, from seq_contin.mp hb s hs, end theorem func_mul_func_contin (f g : ℝ → ℝ) : func_continuous f ∧ func_continuous g → func_continuous (f × g) := begin rintros ⟨ha, hb⟩ a, apply func_mul_func_conv, from ⟨ha a, hb a⟩ end noncomputable def func_div_func (f g : ℝ → ℝ) := λ r : ℝ, (f r) / (g r) noncomputable instance func_div : has_div (ℝ → ℝ) := ⟨func_div_func⟩ theorem func_div_func_conv (f g : ℝ → ℝ) (a b₁ b₂) (h : b₂ ≠ 0) : func_converges_to f a b₁ ∧ func_converges_to g a b₂ → func_converges_to (f / g) a (b₁ / b₂) := begin rintro ⟨ha, hb⟩, rw seq_contin, intros s hs, have : func_seq_comp (f / g) s = seq_div_seq (func_seq_comp f s) (func_seq_comp g s) := rfl, rw this, apply div_lim_conv, from seq_contin.mp ha s hs, from seq_contin.mp hb s hs, norm_cast, assumption end theorem func_comp_func_conv (f g : ℝ → ℝ) (a b c : ℝ) : func_converges_to f a b ∧ func_converges_to g b c → func_converges_to (g ∘ f) a c := begin repeat {rw seq_contin}, rintro ⟨ha, hb⟩, intros s hs, have : func_seq_comp (g ∘ f) s = func_seq_comp g (func_seq_comp f s) := rfl, rw this, apply hb (func_seq_comp f s), from ha s hs end theorem func_comp_func_contin (f g : ℝ → ℝ) : func_continuous f ∧ func_continuous g → func_continuous (g ∘ f) := begin repeat {unfold func_continuous}, rintros ⟨ha, hb⟩ a, apply func_comp_func_conv, swap, from f a, from ⟨ha a, hb (f a)⟩ end -- All polynomials and rational functions are continuous lemma constant_contin (c : ℝ) : func_continuous (λ x : ℝ, c) := begin intros a ε hε, simp, use ε, from ⟨hε, λ x, λ hx, hε⟩ end lemma x_contin : func_continuous (λ x : ℝ, x) := begin intros a ε hε, simp, use ε, from ⟨hε, λ x, λ hx, hx⟩ end lemma xn_contin (n : ℕ) : func_continuous (λ x : ℝ, x ^ n) := begin induction n with k hk, {simp, from constant_contin (1 : ℝ)}, {have : (λ (x : ℝ), x ^ nat.succ k) = func_mul_func (λ x : ℝ, x) (λ x : ℝ, x ^ k) := rfl, rw this, apply func_mul_func_contin, from ⟨x_contin, hk⟩ } end theorem poly_contin {f : polynomial ℝ} : func_continuous (λ x, f.eval x) := begin apply polynomial.induction_on f, {intro a, simp, from constant_contin a }, {intros p q hp hq, simp, apply func_add_func_contin (λ x : ℝ, polynomial.eval x p) (λ x : ℝ, polynomial.eval x q), from ⟨hp, hq⟩ }, simp, intros n a hcon, apply func_mul_func_contin, from ⟨constant_contin a, xn_contin (n + 1)⟩ end -- Intermediate Value Theorem theorem intermediate_value {f : ℝ → ℝ} {a b : ℝ} (h₀ : a ≤ b) (h₁ : func_continuous f) : ∀ y : ℝ, f a ≤ y ∧ y ≤ f b → ∃ c : ℝ, a ≤ c ∧ c ≤ b ∧ f c = y := begin rintros y ⟨hy₁, hy₂⟩, cases eq_or_lt_of_le hy₁ with heq hlt₀, {use a, split, linarith, rw heq, from ⟨h₀, refl y⟩ }, {cases eq_or_lt_of_le hy₂ with heq hlt₁, {use b, split, linarith, rw heq, from ⟨le_refl b, refl (f b)⟩ }, clear hy₁ hy₂, let S : set ℝ := {d : ℝ | a ≤ d ∧ d ≤ b ∧ f d < y}, have hbdd : bounded_above S := by {use b, intros s hs, rw set.mem_set_of_eq at hs, from hs.right.left }, have hnempty : S ≠ ∅ := by {dsimp, rw set.not_eq_empty_iff_exists, use a, rw set.mem_set_of_eq, from ⟨le_refl a, h₀, hlt₀⟩ }, cases completeness S hbdd hnempty with M hM, use M, split, apply hM.left a, rw set.mem_set_of_eq, from ⟨le_refl a, h₀, hlt₀⟩, split, unfold sup at hM, have hα : upper_bound S b := by {intros s hs, rw set.mem_set_of_eq at hs, from hs.right.left }, cases le_or_lt M b with hβ hγ, from hβ, exfalso; from (hM.right b hγ) hα, rw le_antisymm_iff, split, {apply classical.by_contradiction, push_neg, intro h, have : ∃ ε : ℝ, ε = f M - y ∧ 0 < ε := by {use f M - y, split, refl, linarith }, cases this with ε hε, rcases h₁ M ε hε.right with ⟨δ, ⟨hδ, hhδ⟩⟩, rw hε.left at hhδ, have : ∀ (x : ℝ), abs (x - M) < δ → - (f M - y) < f x - f M ∧ f x - f M < f M - y := by {intros x hx, apply abs_lt.mp, from hhδ x hx}, simp at this, replace this : ∀ (x : ℝ), abs (x - M) < δ → x ∉ S := by {intros x hx hS, rw set.mem_set_of_eq at hS, apply asymm (hS.right.right), from (this x hx).left }, replace this : upper_bound S (M - δ) := by {intros s hs, cases lt_or_le s (M - δ), {from le_of_lt h_1}, {cases lt_or_eq_of_le h_1, swap, linarith, have hkt : abs (s - M) < δ := by {rw abs_lt, split, linarith, rw sub_lt_iff_lt_add, apply lt_of_le_of_lt (hM.left s hs), linarith }, exfalso, from (this s hkt) hs } }, have hfa : M - δ < M := by {linarith}, from (hM.right (M - δ) hfa) this }, {have hα : upper_bound S b := by {intros s hs, rw set.mem_set_of_eq at hs, from hs.right.left }, have hβ : M ≤ b := by {rw ←not_lt, intro hγ, from hM.right b hγ hα}, cases lt_or_eq_of_le hβ, swap, rw h, from le_of_lt hlt₁, apply classical.by_contradiction, push_neg, intro h, have : ∃ ε : ℝ, ε = y - f M ∧ 0 < ε := by {use y - f M, split, refl, linarith }, cases this with ε hε, rcases h₁ M ε hε.right with ⟨δ, ⟨hδ, hhδ⟩⟩, rw hε.left at hhδ, have : abs (M + (δ / 2) - M) < δ := by {simp, rw abs_of_pos (half_pos hδ), linarith }, replace this : abs (M + min (δ / 2) ((b - M) / 2) - M) < δ := by {apply lt_of_le_of_lt _ this, rw add_comm, simp, have hpos : 0 < min (δ / 2) ((b + -M) / 2) := by {simp, split, from half_pos hδ, linarith }, rw [abs_of_pos hpos, abs_of_pos (half_pos hδ)], from min_le_left (δ / 2) ((b - M) / 2), }, replace this : abs (f (M + min (δ / 2) ((b - M) / 2)) - f M) < y - f M := by {from hhδ (M + min (δ / 2) ((b - M) / 2)) this}, rw abs_lt at this, cases this with h₃ h₄, simp at h₄, have h₅ : M < M + min (δ / 2) ((b + -M) / 2) := by {simp, split, from half_pos hδ, linarith }, have h₆ : M + min (δ / 2) ((b + -M) / 2) ∈ S := by {rw set.mem_set_of_eq, split, apply le_of_lt (lt_of_le_of_lt _ h₅), have : a ∈ S := by {rw set.mem_set_of_eq, from ⟨le_refl a, h₀, hlt₀⟩}, from hM.left a this, split, cases le_or_lt (δ / 2) ((b + -M) / 2), rw min_eq_left h_1, suffices : (δ / 2) < b + -M, linarith, apply lt_of_le_of_lt h_1, linarith, rw min_eq_right (le_of_lt h_1), linarith, from h₄ }, have h₇ : ¬ upper_bound S M := by {unfold upper_bound, push_neg, use (M + min (δ / 2) ((b + -M) / 2)), from ⟨h₆, h₅⟩ }, from h₇ hM.left } } end def func_bounded_above {S : set ℝ} (f : S → ℝ) := bounded_above {t : ℝ | ∀ x : S, t = f x} def func_bounded_below {S : set ℝ} (f : S → ℝ) := bounded_below {t : ℝ | ∀ x : S, t = f x} -- TODO Extreme value theorem def closed_interval (a b : ℝ) := {x : ℝ | a ≤ x ∧ x ≤ b} lemma mem_of_closed_interval {a b x : ℝ} : x ∈ closed_interval a b ↔ a ≤ x ∧ x ≤ b := by {unfold closed_interval, rw set.mem_set_of_eq} lemma abs_le_closed_interval {x y δ : ℝ} : y ∈ closed_interval (x - δ) (x + δ) ↔ abs (y - x) ≤ δ := begin unfold closed_interval, rw [set.mem_set_of_eq, abs_le], split, repeat {rintro ⟨hα, hβ⟩, split, repeat {linarith}} end def open_interval (a b : ℝ) := {x : ℝ | a < x ∧ x < b} lemma mem_of_open_interval {a b x : ℝ} : x ∈ open_interval a b ↔ a < x ∧ x < b := by {unfold open_interval, rw set.mem_set_of_eq} lemma abs_lt_open_interval {x y δ : ℝ} : y ∈ open_interval (x - δ) (x + δ) ↔ abs (y - x) < δ := begin unfold open_interval, rw [set.mem_set_of_eq, abs_lt], split, repeat {rintro ⟨hα, hβ⟩, split, repeat {linarith}} end -- Defining open and closed sets def is_open (S : set ℝ) := ∀ x ∈ S, ∃ δ > 0, open_interval (x - δ) (x + δ) ⊆ S def is_closed (S : set ℝ) := ∀ a : ℕ → ℝ, seq_in a S → (∃ l : ℝ, a ⇒ l) → ∃ l ∈ S, a ⇒ l def is_compact (S : set ℝ) := is_closed S ∧ bounded S -- An open interval is open theorem open_interval_is_open (a b : ℝ) : is_open (open_interval a b) := begin unfold open_interval, intros x hx, have hδ : 0 < min (x - a) (b - x) := by {apply lt_min_iff.mpr, rw set.mem_set_of_eq at hx, cases hx with ha hb, split, repeat {linarith}, }, use min (x - a) (b - x), use hδ, unfold open_interval, intros y hy, rw set.mem_set_of_eq at hy, rw set.mem_set_of_eq, cases hy with hy₁ hy₂, split, {apply lt_of_le_of_lt _ hy₁, have : min (x - a) (b - x) ≤ x - a := min_le_left (x - a) (b - x), linarith }, {apply lt_of_lt_of_le hy₂, have : min (x - a) (b - x) ≤ b - x := min_le_right (x - a) (b - x), linarith } end -- A closed interval is compact theorem closed_interval_is_compact (a b : ℝ) : is_compact (closed_interval a b) := begin split, {unfold is_closed, rintros s ha ⟨l, hl⟩, use l, have h : l ∈ closed_interval a b := by{unfold closed_interval, rw set.mem_set_of_eq, split, {let c : ℕ → ℝ := λ n : ℕ, a, have : c ⇒ a := cons_conv, apply le_lim c s a l, repeat {assumption}, intro n, show a ≤ s n, suffices : s n ∈ closed_interval a b, unfold closed_interval at this, rw set.mem_set_of_eq at this, from this.left, from ha n }, {let c : ℕ → ℝ := λ n : ℕ, b, have : c ⇒ b := cons_conv, apply le_lim s c l b, repeat {assumption}, intro n, show s n ≤ b, suffices : s n ∈ closed_interval a b, unfold closed_interval at this, rw set.mem_set_of_eq at this, from this.right, from ha n } }, use h, assumption }, {split, {use b, intro s, unfold closed_interval, rw set.mem_set_of_eq, intro h, from h.right }, {use a, intro s, unfold closed_interval, rw set.mem_set_of_eq, intro h, from h.left } } end -- The union of open sets is also open theorem two_union_open_is_open {S T : set ℝ} (h₁ : is_open S) (h₂ : is_open T) : is_open (S ∪ T) := begin intros x hx, rw (set.mem_union x S T) at hx, cases hx, {rcases (h₁ x hx) with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, use δ, use hδ₁, intros a ha, left, from hδ₂ ha }, {rcases (h₂ x hx) with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, use δ, use hδ₁, intros a ha, right, from hδ₂ ha } end -- The empty set is open theorem empty_open : is_open ∅ := begin intros x hx, exfalso, from hx end -- The union of a collection of open sets is also open theorem union_open_is_open {I : Type} {S : I → set ℝ} (h₁ : ∀ i : I, is_open (S i)) : is_open ⋃ i : I, S i := begin intros x hx, rw set.mem_Union at hx, cases hx with i hi, have h₂ : is_open (S i) := h₁ i, unfold is_open at h₂, have h₃ : S i ⊆ ⋃ (i : I), S i := set.subset_Union S i, rcases h₂ x hi with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, use δ, use hδ₁, from set.subset.trans hδ₂ h₃ end lemma element_of_Inter {S : ℕ → set ℝ} {n i : ℕ} : ∀ x ∈ ⋂ i ∈ finset.range n, S i, i ∈ finset.range n → x ∈ S i := by {intros x hx hi, rw set.mem_Inter at hx, finish} lemma comp_open_to_closed {S : set ℝ} : is_open S → is_closed (-S) := begin intro hopen, rintros a x ⟨l, hl⟩, use l, have : l ∈ -S := by {intro hS, rcases hopen l hS with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, cases hl δ hδ₁ with N hN, apply x N, suffices : a N ∈ open_interval (l - δ) (l + δ), from hδ₂ this, rw abs_lt_open_interval, apply hN N (le_refl N) }, use this, assumption end lemma lt_ε_ge_zero {N : ℕ} {ε : ℝ} (h : 0 < ε) : 1 / ε < N → 1 / (N : ℝ) < ε := by {intro hα, have hβ : 0 < N, cases lt_or_le 0 N, assumption, exfalso, apply not_le.mpr h, suffices : 1 / ε ≤ 0, simp only [one_div_eq_inv, inv_nonpos] at this, assumption, apply le_of_lt, apply lt_of_lt_of_le hα, norm_cast, assumption, rw [div_lt_iff, mul_comm], rwa div_lt_iff at hα, assumption, norm_cast, assumption } lemma comp_closed_to_open {S : set ℝ} : is_closed S → is_open (-S) := begin intros hclosed x hx, apply classical.by_contradiction, push_neg, intro hnopen, have : ∀ n : ℕ, ∃ s ∈ open_interval (x - (1 / (n + 1))) (x + (1 / (n + 1))), s ∈ S := by {intros n, apply classical.by_contradiction, push_neg, intro h, suffices : open_interval (x - (1 / (n + 1))) (x + (1 / (n + 1))) ⊆ -S, from hnopen (1 / (n + 1)) nat.one_div_pos_of_nat this, intros s hs, from h s hs }, simp only [classical.skolem] at this, rcases this with ⟨t, ht₁, ht₂⟩, have ht : t ⇒ x := by {intros ε hε, cases exists_nat_gt (1 / ε) with N hN, use N, intros n hn, rw ←abs_lt_open_interval, suffices : open_interval (x - 1 / (n + 1)) (x + 1 / (n + 1)) ⊆ open_interval (x - ε) (x + ε), apply this, from ht₁ n, unfold open_interval, simp only [set.set_of_subset_set_of], rintros a ⟨hα, hβ⟩, split, apply lt_trans _ hα, swap, apply lt_trans hβ, all_goals { simp only [neg_lt_neg_iff, add_lt_add_iff_left, sub_eq_add_neg], apply lt_trans _ ((lt_ε_ge_zero hε) hN), have hγ : 0 < (N : ℝ), norm_cast, cases lt_or_le 0 N, assumption, exfalso, apply not_le.mpr hε, suffices : 1 / ε ≤ 0, simp only [one_div_eq_inv, inv_nonpos] at this, assumption, apply le_of_lt, apply lt_of_lt_of_le hN, norm_cast, assumption, have : 0 < (n : ℝ) + 1, norm_cast, norm_cast at hγ, apply lt_trans hγ, apply lt_of_le_of_lt hn, linarith, rw (one_div_lt_one_div this hγ), norm_cast, linarith } }, unfold is_closed at hclosed, have hseqin : seq_in t S := by {intro n, from ht₂ n}, have hcontra : ∃ (l : ℝ) (H : l ∈ S), t ⇒ l := by {apply hclosed t hseqin, use x, assumption}, rcases hcontra with ⟨l, ⟨hl₁, hl₂⟩⟩, have hleqx : l = x := unique_lim t l x hl₂ ht, apply hx, rwa ←hleqx end theorem comp_open_iff_closed {S : set ℝ} : is_open S ↔ is_closed (-S) := begin split, from comp_open_to_closed, have h₁ : (- -S) = S := by {simp}, have h₂ : (- - -S) = -S :=by {simp}, rw [←h₁, h₂], from comp_closed_to_open end -- A function f : ℝ → ℝ is continuous iff. ∀ U ⊆ R, f⁻¹(U) is open theorem contin_open_pre_image {f : ℝ → ℝ} : func_continuous f ↔ ∀ U : set ℝ, is_open U → is_open {x : ℝ | f x ∈ U} := begin split, {intros h₁ U hU x hx, have hf : f x ∈ U := by {rw set.mem_set_of_eq at hx, assumption}, rcases hU (f x) hf with ⟨ε, ⟨hε, hrang⟩⟩, rcases h₁ x ε hε with ⟨δ, ⟨hδ, hcontin⟩⟩, use δ, use hδ, intros y hy, rw set.mem_set_of_eq, rw abs_lt_open_interval at hy, suffices : f y ∈ open_interval (f x - ε) (f x + ε), from hrang this, rw abs_lt_open_interval, from hcontin y hy }, {intros hU y ε hε, let U : set ℝ := open_interval (f y - ε) (f y + ε), have : f y ∈ U := by {rw abs_lt_open_interval, simpa}, rcases hU U (open_interval_is_open (f y - ε) (f y + ε)) y this with ⟨δ, ⟨hδ, hrang⟩⟩, use δ, use hδ, intros x hx, rw ←abs_lt_open_interval at hx, rw ←abs_lt_open_interval, suffices : x ∈ {x : ℝ | f x ∈ U}, rw set.mem_set_of_eq at this, assumption, from hrang hx } end -- a n → l iff ∀ U ⊆ ℝ, U an open set, l ∈ U ⇒ ∃ N ∈ ℕ, ∀ n ≥ N, a n ∈ U (Unseen 2 Term 2) lemma seq_converge_imples_all_open {a : ℕ → ℝ} {l : ℝ} : a ⇒ l → ∀ U : set ℝ, is_open U ∧ l ∈ U → ∃ N : ℕ, ∀ n : ℕ, N ≤ n → (a n) ∈ U := begin rintros hconv U ⟨hU, hlU⟩, rcases hU l hlU with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, cases hconv δ hδ₁ with N hN, use N, intros n hn, suffices : a n ∈ open_interval (l - δ) (l + δ), from hδ₂ this, rw abs_lt_open_interval, from hN n hn end lemma all_open_imples_seq_converge {a : ℕ → ℝ} {l : ℝ} : (∀ U : set ℝ, is_open U ∧ l ∈ U → ∃ N : ℕ, ∀ n : ℕ, N ≤ n → (a n) ∈ U) → a ⇒ l := begin intros hU ε hε, let U : set ℝ := open_interval (l - ε) (l + ε), have hopen : is_open U := by {apply open_interval_is_open}, have hlU : l ∈ open_interval (l - ε) (l + ε) := by {unfold open_interval, rw set.mem_set_of_eq, split, all_goals {linarith}, }, cases hU U ⟨hopen, hlU⟩ with N hN, use N, intros n hn, rw ←abs_lt_open_interval, from hN n hn end theorem seq_converge_iff_all_open {a : ℕ → ℝ} {l : ℝ} : a ⇒ l ↔ ∀ U : set ℝ, is_open U ∧ l ∈ U → ∃ N : ℕ, ∀ n : ℕ, N ≤ n → (a n) ∈ U := by {split, all_goals {try {from seq_converge_imples_all_open <|> from all_open_imples_seq_converge}}} -- Uniform continuity and convergence def unif_contin (f : ℝ → ℝ) := ∀ ε > 0, ∃ δ > 0, ∀ x y : ℝ, abs (x - y) < δ → abs (f x - f y) < ε -- Uniformly continuous implies continuous (hence is stronger) theorem unif_contin_implies_contin {f : ℝ → ℝ} : unif_contin f → func_continuous f := begin intros h₁ a ε hε, rcases h₁ ε hε with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, use δ, use hδ₁, intro x, from hδ₂ x a end -- Uniformly continuous functions will map a Cauchy sequence to another Cauchy sequence theorem unif_contin_map_cauchy {f : ℝ → ℝ} {a : ℕ → ℝ} (h : unif_contin f) : cauchy a → cauchy (λ n : ℕ, f (a n)) := begin intros hcauchy ε hε, rcases h ε hε with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, cases hcauchy δ hδ₁ with N hN, use N, intros n m hnm, show abs (f (a n) - f (a m)) < ε, convert hδ₂ (a n) (a m) _, from hN n m hnm end def func_pointwise_converge_to (f : ℕ → ℝ → ℝ) (g : ℝ → ℝ) := ∀ x : ℝ, ∀ ε > 0, ∃ N : ℕ, ∀ n : ℕ, N ≤ n → abs (f n x - g x) < ε def func_converge_uniform (f : ℕ → ℝ → ℝ) (g : ℝ → ℝ) := ∀ ε > 0, ∃ N : ℕ, ∀ x : ℝ, ∀ n : ℕ, N ≤ n → abs (f n x - g x) < ε -- function.swap swaps -- f: ℕ → ℝ → ℝ = fₙ(x) -- If a sequence of uniformly continuous functions fₙ converges to f, then f is uniformly continuous theorem unif_contin_lim_unif_contin (f : ℕ → ℝ → ℝ) (g : ℝ → ℝ) (h : ∀ n : ℕ, unif_contin (f n)) : func_converge_uniform f g → unif_contin g := begin intros h₁ ε hε, have hε₂: 0 < ε / 3 := by linarith, cases h₁ (ε / 3) hε₂ with N hN, rcases h N (ε / 3) hε₂ with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, use δ, use hδ₁, intros x y hxy, suffices : abs (g x -f N x) + abs (f N x - f N y) + abs (f N y - g y) < ε, {apply lt_of_le_of_lt _ this, convert le_trans (abs_add (g x - f N y) (f N y - g y)) _, simp, apply add_le_add_right', convert abs_add (g x - f N x) (f N x - f N y), simp }, have : ε = ε / 3 + ε / 3 + ε / 3 := by {linarith}, rw this, repeat {apply add_lt_add}, {rw abs_sub, from hN x N (le_refl N)}, {from hδ₂ x y hxy}, {from hN y N (le_refl N)} end -- A similar but weaker proposition than the above: If a sequence of continuous functions fₙ converges to f, then f is continuous theorem contin_lim_contin (f : ℕ → ℝ → ℝ) (g : ℝ → ℝ) (h : ∀ n : ℕ, func_continuous (f n)) : func_converge_uniform f g → func_continuous g := begin intros h₁ y ε hε, have hε₂ : 0 < ε / 3 := by linarith, cases h₁ (ε / 3) hε₂ with N hN, rcases h N y (ε / 3) hε₂ with ⟨δ, ⟨hδ₁, hδ₂⟩⟩, use δ, use hδ₁, intros x hxy, suffices : abs (g x -f N x) + abs (f N x - f N y) + abs (f N y - g y) < ε, {apply lt_of_le_of_lt _ this, convert le_trans (abs_add (g x - f N y) (f N y - g y)) _, simp, apply add_le_add_right', convert abs_add (g x - f N x) (f N x - f N y), simp }, have : ε = ε / 3 + ε / 3 + ε / 3 := by {linarith}, rw this, repeat {apply add_lt_add}, {rw abs_sub, from hN x N (le_refl N)}, {from hδ₂ x hxy}, {from hN y N (le_refl N)} end -- TODO: define sum of functions and prove Weierstrass M-test end M40002
adec776d696ade0760ec7ac2e50e5ce3ba02a08a
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/analysis/complex/basic.lean
fa49725857ba0279fa37463ec95ad4bc1e9e94fd
[ "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
7,339
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.times_cont_diff import analysis.normed_space.finite_dimension /-! # Normed space structure on `ℂ`. This file gathers basic facts on complex numbers of an analytic nature. ## Main results This file registers `ℂ` as a normed field, expresses basic properties of the norm, and gives tools on the real vector space structure of `ℂ`. Notably, in the namespace `complex`, it defines functions: * `continuous_linear_map.re` * `continuous_linear_map.im` * `continuous_linear_map.of_real` They are bundled versions of the real part, the imaginary part, and the embedding of `ℝ` in `ℂ`, as continuous `ℝ`-linear maps. `has_deriv_at.real_of_complex` expresses that, if a function on `ℂ` is differentiable (over `ℂ`), then its restriction to `ℝ` is differentiable over `ℝ`, with derivative the real part of the complex derivative. -/ noncomputable theory namespace complex instance : has_norm ℂ := ⟨abs⟩ instance : normed_group ℂ := normed_group.of_core ℂ { norm_eq_zero_iff := λ z, abs_eq_zero, triangle := abs_add, norm_neg := abs_neg } instance : normed_field ℂ := { norm := abs, dist_eq := λ _ _, rfl, norm_mul' := abs_mul, .. complex.field } instance : nondiscrete_normed_field ℂ := { non_trivial := ⟨2, by simp [norm]; norm_num⟩ } instance normed_algebra_over_reals : normed_algebra ℝ ℂ := { norm_algebra_map_eq := abs_of_real, ..complex.algebra_over_reals } @[simp] lemma norm_eq_abs (z : ℂ) : ∥z∥ = abs z := rfl lemma dist_eq (z w : ℂ) : dist z w = abs (z - w) := rfl @[simp] lemma norm_real (r : ℝ) : ∥(r : ℂ)∥ = ∥r∥ := abs_of_real _ @[simp] lemma norm_rat (r : ℚ) : ∥(r : ℂ)∥ = _root_.abs (r : ℝ) := suffices ∥((r : ℝ) : ℂ)∥ = _root_.abs r, by simpa, by rw [norm_real, real.norm_eq_abs] @[simp] lemma norm_nat (n : ℕ) : ∥(n : ℂ)∥ = n := abs_of_nat _ @[simp] lemma norm_int {n : ℤ} : ∥(n : ℂ)∥ = _root_.abs n := suffices ∥((n : ℝ) : ℂ)∥ = _root_.abs n, by simpa, by rw [norm_real, real.norm_eq_abs] lemma norm_int_of_nonneg {n : ℤ} (hn : 0 ≤ n) : ∥(n : ℂ)∥ = n := by rw [norm_int, _root_.abs_of_nonneg]; exact int.cast_nonneg.2 hn /-- A complex normed vector space is also a real normed vector space. -/ @[priority 900] instance normed_space.restrict_scalars_real (E : Type*) [normed_group E] [normed_space ℂ E] : normed_space ℝ E := normed_space.restrict_scalars ℝ ℂ E open continuous_linear_map /-- The space of continuous linear maps over `ℝ`, from a real vector space to a complex vector space, is a normed vector space over `ℂ`. -/ instance continuous_linear_map.real_smul_complex (E : Type*) [normed_group E] [normed_space ℝ E] (F : Type*) [normed_group F] [normed_space ℂ F] : normed_space ℂ (E →L[ℝ] F) := continuous_linear_map.normed_space_extend_scalars /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def continuous_linear_map.re : ℂ →L[ℝ] ℝ := linear_map.re.to_continuous_linear_map @[simp] lemma continuous_linear_map.re_coe : (coe (continuous_linear_map.re) : ℂ →ₗ[ℝ] ℝ) = linear_map.re := rfl @[simp] lemma continuous_linear_map.re_apply (z : ℂ) : (continuous_linear_map.re : ℂ → ℝ) z = z.re := rfl @[simp] lemma continuous_linear_map.re_norm : ∥continuous_linear_map.re∥ = 1 := le_antisymm (op_norm_le_bound _ zero_le_one $ λ z, by simp [real.norm_eq_abs, abs_re_le_abs]) $ calc 1 = ∥continuous_linear_map.re 1∥ : by simp ... ≤ ∥continuous_linear_map.re∥ : unit_le_op_norm _ _ (by simp) /-- Continuous linear map version of the real part function, from `ℂ` to `ℝ`. -/ def continuous_linear_map.im : ℂ →L[ℝ] ℝ := linear_map.im.to_continuous_linear_map @[simp] lemma continuous_linear_map.im_coe : (coe (continuous_linear_map.im) : ℂ →ₗ[ℝ] ℝ) = linear_map.im := rfl @[simp] lemma continuous_linear_map.im_apply (z : ℂ) : (continuous_linear_map.im : ℂ → ℝ) z = z.im := rfl @[simp] lemma continuous_linear_map.im_norm : ∥continuous_linear_map.im∥ = 1 := le_antisymm (op_norm_le_bound _ zero_le_one $ λ z, by simp [real.norm_eq_abs, abs_im_le_abs]) $ calc 1 = ∥continuous_linear_map.im I∥ : by simp ... ≤ ∥continuous_linear_map.im∥ : unit_le_op_norm _ _ (by simp) /-- Linear isometry version of the canonical embedding of `ℝ` in `ℂ`. -/ def linear_isometry.of_real : ℝ →ₗᵢ[ℝ] ℂ := ⟨linear_map.of_real, λ x, by simp⟩ /-- Continuous linear map version of the canonical embedding of `ℝ` in `ℂ`. -/ def continuous_linear_map.of_real : ℝ →L[ℝ] ℂ := linear_isometry.of_real.to_continuous_linear_map lemma isometry_of_real : isometry (coe : ℝ → ℂ) := linear_isometry.of_real.isometry lemma continuous_of_real : continuous (coe : ℝ → ℂ) := isometry_of_real.continuous @[simp] lemma continuous_linear_map.of_real_coe : (coe (continuous_linear_map.of_real) : ℝ →ₗ[ℝ] ℂ) = linear_map.of_real := rfl @[simp] lemma continuous_linear_map.of_real_apply (x : ℝ) : (continuous_linear_map.of_real : ℝ → ℂ) x = x := rfl @[simp] lemma continuous_linear_map.of_real_norm : ∥continuous_linear_map.of_real∥ = 1 := linear_isometry.of_real.norm_to_continuous_linear_map end complex section real_deriv_of_complex /-! ### Differentiability of the restriction to `ℝ` of complex functions -/ open complex variables {e : ℂ → ℂ} {e' : ℂ} {z : ℝ} /-- If a complex function is differentiable at a real point, then the induced real function is also differentiable at this point, with a derivative equal to the real part of the complex derivative. -/ theorem has_deriv_at.real_of_complex (h : has_deriv_at e e' z) : has_deriv_at (λx:ℝ, (e x).re) e'.re z := begin have A : has_fderiv_at continuous_linear_map.of_real continuous_linear_map.of_real z := continuous_linear_map.of_real.has_fderiv_at, have B : has_fderiv_at e ((continuous_linear_map.smul_right 1 e' : ℂ →L[ℂ] ℂ).restrict_scalars ℝ) (continuous_linear_map.of_real z) := (has_deriv_at_iff_has_fderiv_at.1 h).restrict_scalars ℝ, have C : has_fderiv_at continuous_linear_map.re continuous_linear_map.re (e (continuous_linear_map.of_real z)) := continuous_linear_map.re.has_fderiv_at, simpa using has_fderiv_at_iff_has_deriv_at.1 (C.comp z (B.comp z A)), end theorem times_cont_diff_at.real_of_complex {n : with_top ℕ} (h : times_cont_diff_at ℂ n e z) : times_cont_diff_at ℝ n (λ x : ℝ, (e x).re) z := begin have A : times_cont_diff_at ℝ n continuous_linear_map.of_real z, from continuous_linear_map.of_real.times_cont_diff.times_cont_diff_at, have B : times_cont_diff_at ℝ n e z := h.restrict_scalars ℝ, have C : times_cont_diff_at ℝ n continuous_linear_map.re (e z), from continuous_linear_map.re.times_cont_diff.times_cont_diff_at, exact C.comp z (B.comp z A) end theorem times_cont_diff.real_of_complex {n : with_top ℕ} (h : times_cont_diff ℂ n e) : times_cont_diff ℝ n (λ x : ℝ, (e x).re) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, h.times_cont_diff_at.real_of_complex end real_deriv_of_complex
1f6c347bed6ef1b77acc3098131373c5ce632e15
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/sheaves/sheaf_condition/sites.lean
d6692f330c357aa459dcf62c7f5a8bd32b57306e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,118
lean
/- Copyright (c) 2021 Justus Springer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Justus Springer -/ import category_theory.sites.spaces import topology.sheaves.sheaf import category_theory.sites.dense_subsite /-! # Coverings and sieves; from sheaves on sites and sheaves on spaces > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we connect coverings in a topological space to sieves in the associated Grothendieck topology, in preparation of connecting the sheaf condition on sites to the various sheaf conditions on spaces. We also specialize results about sheaves on sites to sheaves on spaces; we show that the inclusion functor from a topological basis to `topological_space.opens` is cover_dense, that open maps induce cover_preserving functors, and that open embeddings induce compatible_preserving functors. -/ noncomputable theory universes w v u open category_theory topological_space namespace Top.presheaf variables {X : Top.{w}} /-- Given a presieve `R` on `U`, we obtain a covering family of open sets in `X`, by taking as index type the type of dependent pairs `(V, f)`, where `f : V ⟶ U` is in `R`. -/ def covering_of_presieve (U : opens X) (R : presieve U) : (Σ V, {f : V ⟶ U // R f}) → opens X := λ f, f.1 @[simp] lemma covering_of_presieve_apply (U : opens X) (R : presieve U) (f : Σ V, {f : V ⟶ U // R f}) : covering_of_presieve U R f = f.1 := rfl namespace covering_of_presieve variables (U : opens X) (R : presieve U) /-- If `R` is a presieve in the grothendieck topology on `opens X`, the covering family associated to `R` really is _covering_, i.e. the union of all open sets equals `U`. -/ lemma supr_eq_of_mem_grothendieck (hR : sieve.generate R ∈ opens.grothendieck_topology X U) : supr (covering_of_presieve U R) = U := begin apply le_antisymm, { refine supr_le _, intro f, exact f.2.1.le, }, intros x hxU, rw [opens.mem_supr], obtain ⟨V, iVU, ⟨W, iVW, iWU, hiWU, -⟩, hxV⟩ := hR x hxU, exact ⟨⟨W, ⟨iWU, hiWU⟩⟩, iVW.le hxV⟩, end end covering_of_presieve /-- Given a family of opens `U : ι → opens X` and any open `Y : opens X`, we obtain a presieve on `Y` by declaring that a morphism `f : V ⟶ Y` is a member of the presieve if and only if there exists an index `i : ι` such that `V = U i`. -/ def presieve_of_covering_aux {ι : Type v} (U : ι → opens X) (Y : opens X) : presieve Y := λ V f, ∃ i, V = U i /-- Take `Y` to be `supr U` and obtain a presieve over `supr U`. -/ def presieve_of_covering {ι : Type v} (U : ι → opens X) : presieve (supr U) := presieve_of_covering_aux U (supr U) /-- Given a presieve `R` on `Y`, if we take its associated family of opens via `covering_of_presieve` (which may not cover `Y` if `R` is not covering), and take the presieve on `Y` associated to the family of opens via `presieve_of_covering_aux`, then we get back the original presieve `R`. -/ @[simp] lemma covering_presieve_eq_self {Y : opens X} (R : presieve Y) : presieve_of_covering_aux (covering_of_presieve Y R) Y = R := by { ext Z f, exact ⟨λ ⟨⟨_,_,h⟩,rfl⟩, by convert h, λ h, ⟨⟨Z,f,h⟩,rfl⟩⟩ } namespace presieve_of_covering variables {ι : Type v} (U : ι → opens X) /-- The sieve generated by `presieve_of_covering U` is a member of the grothendieck topology. -/ lemma mem_grothendieck_topology : sieve.generate (presieve_of_covering U) ∈ opens.grothendieck_topology X (supr U) := begin intros x hx, obtain ⟨i, hxi⟩ := opens.mem_supr.mp hx, exact ⟨U i, opens.le_supr U i, ⟨U i, 𝟙 _, opens.le_supr U i, ⟨i, rfl⟩, category.id_comp _⟩, hxi⟩, end /-- An index `i : ι` can be turned into a dependent pair `(V, f)`, where `V` is an open set and `f : V ⟶ supr U` is a member of `presieve_of_covering U f`. -/ def hom_of_index (i : ι) : Σ V, {f : V ⟶ supr U // presieve_of_covering U f} := ⟨U i, opens.le_supr U i, i, rfl⟩ /-- By using the axiom of choice, a dependent pair `(V, f)` where `f : V ⟶ supr U` is a member of `presieve_of_covering U f` can be turned into an index `i : ι`, such that `V = U i`. -/ def index_of_hom (f : Σ V, {f : V ⟶ supr U // presieve_of_covering U f}) : ι := f.2.2.some lemma index_of_hom_spec (f : Σ V, {f : V ⟶ supr U // presieve_of_covering U f}) : f.1 = U (index_of_hom U f) := f.2.2.some_spec end presieve_of_covering end Top.presheaf namespace Top.opens variables {X : Top} {ι : Type*} lemma cover_dense_iff_is_basis [category ι] (B : ι ⥤ opens X) : cover_dense (opens.grothendieck_topology X) B ↔ opens.is_basis (set.range B.obj) := begin rw opens.is_basis_iff_nbhd, split, intros hd U x hx, rcases hd.1 U x hx with ⟨V,f,⟨i,f₁,f₂,hc⟩,hV⟩, exact ⟨B.obj i, ⟨i,rfl⟩, f₁.le hV, f₂.le⟩, intro hb, split, intros U x hx, rcases hb hx with ⟨_,⟨i,rfl⟩,hx,hi⟩, exact ⟨B.obj i, ⟨⟨hi⟩⟩, ⟨⟨i, 𝟙 _, ⟨⟨hi⟩⟩, rfl⟩⟩, hx⟩, end lemma cover_dense_induced_functor {B : ι → opens X} (h : opens.is_basis (set.range B)) : cover_dense (opens.grothendieck_topology X) (induced_functor B) := (cover_dense_iff_is_basis _).2 h end Top.opens section open_embedding open Top.presheaf opposite variables {C : Type u} [category.{v} C] variables {X Y : Top.{w}} {f : X ⟶ Y} {F : Y.presheaf C} lemma open_embedding.compatible_preserving (hf : open_embedding f) : compatible_preserving (opens.grothendieck_topology Y) hf.is_open_map.functor := begin haveI : mono f := (Top.mono_iff_injective f).mpr hf.inj, apply compatible_preserving_of_downwards_closed, intros U V i, refine ⟨(opens.map f).obj V, eq_to_iso $ opens.ext $ set.image_preimage_eq_of_subset $ λ x h, _⟩, obtain ⟨_, _, rfl⟩ := i.le h, exact ⟨_, rfl⟩ end lemma is_open_map.cover_preserving (hf : is_open_map f) : cover_preserving (opens.grothendieck_topology X) (opens.grothendieck_topology Y) hf.functor := begin constructor, rintros U S hU _ ⟨x, hx, rfl⟩, obtain ⟨V, i, hV, hxV⟩ := hU x hx, exact ⟨_, hf.functor.map i, ⟨_, i, 𝟙 _, hV, rfl⟩, set.mem_image_of_mem f hxV⟩ end lemma Top.presheaf.is_sheaf_of_open_embedding (h : open_embedding f) (hF : F.is_sheaf) : is_sheaf (h.is_open_map.functor.op ⋙ F) := pullback_is_sheaf_of_cover_preserving h.compatible_preserving h.is_open_map.cover_preserving ⟨_, hF⟩ end open_embedding namespace Top.sheaf open Top opposite variables {C : Type u} [category.{v} C] variables {X : Top.{w}} {ι : Type*} {B : ι → opens X} variables (F : X.presheaf C) (F' : sheaf C X) (h : opens.is_basis (set.range B)) /-- The empty component of a sheaf is terminal -/ def is_terminal_of_empty (F : sheaf C X) : limits.is_terminal (F.val.obj (op ⊥)) := F.is_terminal_of_bot_cover ⊥ (by tidy) /-- A variant of `is_terminal_of_empty` that is easier to `apply`. -/ def is_terminal_of_eq_empty (F : X.sheaf C) {U : opens X} (h : U = ⊥) : limits.is_terminal (F.val.obj (op U)) := by convert F.is_terminal_of_empty /-- If a family `B` of open sets forms a basis of the topology on `X`, and if `F'` is a sheaf on `X`, then a homomorphism between a presheaf `F` on `X` and `F'` is equivalent to a homomorphism between their restrictions to the indexing type `ι` of `B`, with the induced category structure on `ι`. -/ def restrict_hom_equiv_hom : ((induced_functor B).op ⋙ F ⟶ (induced_functor B).op ⋙ F'.1) ≃ (F ⟶ F'.1) := @cover_dense.restrict_hom_equiv_hom _ _ _ _ _ _ _ _ (opens.cover_dense_induced_functor h) _ F F' @[simp] lemma extend_hom_app (α : ((induced_functor B).op ⋙ F ⟶ (induced_functor B).op ⋙ F'.1)) (i : ι) : (restrict_hom_equiv_hom F F' h α).app (op (B i)) = α.app (op i) := by { nth_rewrite 1 ← (restrict_hom_equiv_hom F F' h).left_inv α, refl } include h lemma hom_ext {α β : F ⟶ F'.1} (he : ∀ i, α.app (op (B i)) = β.app (op (B i))) : α = β := by { apply (restrict_hom_equiv_hom F F' h).symm.injective, ext i, exact he i.unop } end Top.sheaf
e9bf69c26bff21a13001426642f5e9abb92433bb
90edd5cdcf93124fe15627f7304069fdce3442dd
/src/Lean/Aesop/Config.lean
99440c544295a424c9c4894c2e3cceb4dea23f27
[ "Apache-2.0" ]
permissive
JLimperg/lean4-aesop
8a9d9cd3ee484a8e67fda2dd9822d76708098712
5c4b9a3e05c32f69a4357c3047c274f4b94f9c71
refs/heads/master
1,689,415,944,104
1,627,383,284,000
1,627,383,284,000
377,536,770
0
0
null
null
null
null
UTF-8
Lean
false
false
14,725
lean
/- Copyright (c) 2021 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg, Asta Halkjær From -/ import Lean.Aesop.RuleBuilder open Lean open Lean.Meta (SimpEntry getSimpLemmas) namespace Lean.Aesop namespace Parser.Attribute declare_syntax_cat aesop_prio syntax "-"? num "%"? : aesop_prio declare_syntax_cat' aesop_kind force_leading_unreserved_tokens syntax (aesop_prio)? : aesop_kind syntax &"safe" (aesop_prio)? : aesop_kind syntax &"unsafe" (aesop_prio)? : aesop_kind syntax &"norm" (aesop_prio)? : aesop_kind declare_syntax_cat' aesop_builder force_leading_unreserved_tokens syntax &"apply" : aesop_builder syntax &"simp" : aesop_builder syntax &"unfold" : aesop_builder syntax &"tactic" : aesop_builder declare_syntax_cat' aesop_clause force_leading_unreserved_tokens syntax "(" &"builder" aesop_builder ")" : aesop_clause syntax (name := aesop) &"aesop" aesop_kind aesop_clause* : attr end Parser.Attribute variable [Monad m] [MonadError m] inductive Prio | successProbability (p : Percent) | penalty (i : Int) deriving Inhabited, BEq namespace Prio instance : ToString Prio where toString | successProbability p => p.toHumanString | penalty i => toString i protected def parse : Syntax → Except String Prio | `(aesop_prio|- $n:numLit %) => throw "percentage cannot be negative" | `(aesop_prio|- $n:numLit) => return penalty $ - n.toNat | `(aesop_prio|$n:numLit) => return penalty $ n.toNat | `(aesop_prio|$n:numLit %) => do let (some p) ← Percent.ofNat n.toNat | throw "percentage must be between 0 and 100." return successProbability p | _ => unreachable! end Prio def parsePrioForUnsafeRule : Option Syntax → Except String Percent | none => throw "unsafe rule must be given a success probability." | some p => do let (Prio.successProbability p) ← Prio.parse p | throw "unsafe rule must be given a success probability ('x%'), not an integer penalty" return p def parsePrioForSafeRule : Option Syntax → Except String Int | none => return defaultSafePenalty | some p => do let (Prio.penalty p) ← Prio.parse p | throw "safe rule must be given an integer penalty, not a success probability" return p def parsePrioForNormRule : Option Syntax → Except String Int | none => return defaultNormPenalty | some p => do let (Prio.penalty p) ← Prio.parse p | throw "norm rule must be given an integer penalty, not a success probability" return p inductive RuleKind | norm (penalty : Int) | safe (penalty : Int) | «unsafe» (successProbability : Percent) deriving Inhabited, BEq namespace RuleKind instance : ToString RuleKind where toString | norm p => s!"norm {p}" | safe p => s!"safe {p}" | «unsafe» p => s!"unsafe {p.toHumanString}" protected def parse : Syntax → m RuleKind | `(aesop_kind|safe $[$prio:aesop_prio]?) => go (parsePrioForSafeRule prio) safe | `(aesop_kind|unsafe $[$prio:aesop_prio]?) => go (parsePrioForUnsafeRule prio) «unsafe» | `(aesop_kind|$[$prio:aesop_prio]?) => go (parsePrioForUnsafeRule prio) «unsafe» | `(aesop_kind|norm $[$prio:aesop_prio]?) => go (parsePrioForNormRule prio) norm | _ => unreachable! where go {α} (prio : Except String α) (cont : α → RuleKind) : m RuleKind := match prio with | Except.ok prio => return cont prio | Except.error e => throwError "aesop: {e}" end RuleKind inductive RegularBuilderClause | apply | tactic deriving Inhabited, BEq namespace RegularBuilderClause instance : ToString RegularBuilderClause where toString | apply => "(builder apply)" | tactic => "(builder tactic)" def toRuleBuilder : RegularBuilderClause → RuleBuilder RegularRuleBuilderResult | apply => RuleBuilder.apply | tactic => RuleBuilder.tactic end RegularBuilderClause inductive BuilderClause | regular (c : RegularBuilderClause) | simpLemma | simpUnfold deriving Inhabited, BEq namespace BuilderClause instance : ToString BuilderClause where toString | regular c => toString c | simpLemma => "(builder simp)" | simpUnfold => "(builder unfold)" open RegularBuilderClause in protected def parseBuilder : Syntax → BuilderClause | `(aesop_builder|apply) => regular apply | `(aesop_builder|tactic) => regular tactic | `(aesop_builder|simp) => simpLemma | `(aesop_builder|unfold) => simpUnfold | _ => unreachable! def toRuleBuilder : BuilderClause → RuleBuilder NormRuleBuilderResult | regular c => λ goal i => NormRuleBuilderResult.regular <$> c.toRuleBuilder goal i | simpLemma => RuleBuilder.normSimpLemmas | simpUnfold => RuleBuilder.normSimpUnfold end BuilderClause inductive Clause | builder (c : BuilderClause) deriving Inhabited, BEq namespace Clause instance : ToString Clause where toString | builder c => toString c protected def parse : Syntax → m Clause | `(aesop_clause|(builder $b:aesop_builder)) => builder <$> BuilderClause.parseBuilder b | _ => unreachable! end Clause structure NormRuleConfig where penalty : Option Int builder : Option BuilderClause deriving Inhabited, BEq namespace NormRuleConfig instance : ToString NormRuleConfig where toString conf := " ".joinSep [ match conf.penalty with | none => "" | some p => toString p, match conf.builder with | none => "" | some b => toString b ] protected def addClause (conf : NormRuleConfig) : Clause → m NormRuleConfig | Clause.builder b => if conf.builder.isSome then throwError "aesop: duplicate builder clause." else pure { conf with builder := b } protected def addClauses (clauses : Array Clause) (conf : NormRuleConfig) : m NormRuleConfig := clauses.foldlM NormRuleConfig.addClause conf open NormRuleBuilderResult in protected def applyToRuleIdent (i : RuleIdent) (conf : NormRuleConfig) : MetaM RuleSetMember := do let builderResult ← match conf.builder with | none => RuleBuilder.normRuleDefault i | some builderClause => builderClause.toRuleBuilder i match builderResult with | regular res => let penalty := conf.penalty.getD 1 return RuleSetMember'.normRule { name := `norm ++ res.builderName ++ i.ruleName indexingMode := res.indexingMode extra := { penalty := penalty } tac := res.tac } | simpEntries es => return RuleSetMember'.normSimpEntries es end NormRuleConfig structure SafeRuleConfig where penalty : Option Int builder : Option RegularBuilderClause deriving Inhabited namespace SafeRuleConfig instance : ToString SafeRuleConfig where toString conf := " ".joinSep [ match conf.penalty with | none => "" | some p => toString p, match conf.builder with | none => "" | some b => toString (BuilderClause.regular b) ] protected def addClause (conf : SafeRuleConfig) : Clause → m SafeRuleConfig | Clause.builder BuilderClause.simpLemma => throwError "aesop: 'simp' builder cannot be used with safe rules." | Clause.builder BuilderClause.simpUnfold => throwError "aesop: 'unfold' builder cannot be used with safe rules." | Clause.builder (BuilderClause.regular b) => if conf.builder.isSome then throwError "aesop: duplicate builder clause." else pure { conf with builder := b } protected def addClauses (clauses : Array Clause) (conf : SafeRuleConfig) : m SafeRuleConfig := clauses.foldlM SafeRuleConfig.addClause conf protected def applyToRuleIdent (i : RuleIdent) (conf : SafeRuleConfig) : MetaM RuleSetMember := do let builderResult ← match conf.builder with | none => RuleBuilder.safeRuleDefault i | some builderClause => builderClause.toRuleBuilder i let penalty := conf.penalty.getD 0 return RuleSetMember'.safeRule { name := `safe ++ builderResult.builderName ++ i.ruleName indexingMode := builderResult.indexingMode, extra := { penalty := penalty, safety := Safety.safe } -- TODO support almost_safe rules tac := builderResult.tac } end SafeRuleConfig structure UnsafeRuleConfig where successProbability : Percent builder : Option RegularBuilderClause deriving Inhabited namespace UnsafeRuleConfig instance : ToString UnsafeRuleConfig where toString conf := " ".joinSep [ conf.successProbability.toHumanString, match conf.builder with | none => "" | some b => toString (BuilderClause.regular b) ] protected def addClause (conf : UnsafeRuleConfig) : Clause → m UnsafeRuleConfig | Clause.builder BuilderClause.simpLemma => throwError "aesop: 'simp' builder cannot be used with unsafe rules." | Clause.builder BuilderClause.simpUnfold => throwError "aesop: 'unfold' builder cannot be used with unsafe rules." | Clause.builder (BuilderClause.regular b) => if conf.builder.isSome then throwError "aesop: duplicate builder clause." else pure { conf with builder := b } protected def addClauses (clauses : Array Clause) (conf : UnsafeRuleConfig) : m UnsafeRuleConfig := clauses.foldlM UnsafeRuleConfig.addClause conf protected def applyToRuleIdent (i : RuleIdent) (conf : UnsafeRuleConfig) : MetaM RuleSetMember := do let builderResult ← match conf.builder with | none => RuleBuilder.unsafeRuleDefault i | some builderClause => builderClause.toRuleBuilder i return RuleSetMember'.unsafeRule { name := `unsafe ++ builderResult.builderName ++ i.ruleName indexingMode := builderResult.indexingMode, extra := { successProbability := conf.successProbability }, tac := builderResult.tac } end UnsafeRuleConfig inductive RuleConfig | norm (conf : NormRuleConfig) | safe (conf : SafeRuleConfig) | «unsafe» (conf : UnsafeRuleConfig) deriving Inhabited namespace RuleConfig instance : ToString RuleConfig where toString c := "aesop " ++ match c with | norm conf => " ".joinSep ["norm", toString conf] | safe conf => " ".joinSep ["safe", toString conf] | «unsafe» conf => " ".joinSep ["unsafe", toString conf] protected def ofKindAndClauses : RuleKind → Array Clause → m RuleConfig | RuleKind.norm penalty, cs => do let conf : NormRuleConfig := { penalty := penalty, builder := none } norm <$> conf.addClauses cs | RuleKind.safe penalty, cs => do let conf : SafeRuleConfig := { penalty := penalty, builder := none } safe <$> conf.addClauses cs | RuleKind.unsafe prob, cs => do let conf : UnsafeRuleConfig := { successProbability := prob, builder := none } «unsafe» <$> conf.addClauses cs protected def parse : Syntax → m RuleConfig | `(attr|aesop $kind:aesop_kind $[$clauses:aesop_clause]*) => do let kind ← RuleKind.parse kind let clauses ← clauses.mapM Clause.parse RuleConfig.ofKindAndClauses kind clauses | _ => unreachable! protected def applyToRuleIdent (i : RuleIdent) : RuleConfig → MetaM RuleSetMember | norm conf => conf.applyToRuleIdent i | safe conf => conf.applyToRuleIdent i | «unsafe» conf => conf.applyToRuleIdent i end RuleConfig builtin_initialize extension : ScopedEnvExtension (RuleSetMember' RuleTacDescr) RuleSetMember RuleSet ← registerScopedEnvExtension { name := `aesopExt mkInitial := return {} ofOLeanEntry := λ rs r => runMetaMAsImportM r.ofDescr toOLeanEntry := λ r => r.toDescr.getD (panic! "aesop attribute extension: trying to serialise a rule set member without a description") addEntry := λ rs r => rs.add r } def getAttrRuleSet : CoreM RuleSet := do extension.getState (← getEnv) builtin_initialize registerBuiltinAttribute { name := `aesop descr := "Register a declaration as an Aesop rule." add := λ decl stx attrKind => do let config ← RuleConfig.parse stx let rule ← runMetaMAsCoreM $ config.applyToRuleIdent (RuleIdent.const decl) extension.add rule attrKind erase := λ _ => throwError "aesop attribute currently cannot be removed" } def getRuleSet : MetaM RuleSet := do let defaultSimpLemmas ← getSimpLemmas let rs ← getAttrRuleSet return { rs with normSimpLemmas := defaultSimpLemmas.merge rs.normSimpLemmas } namespace Parser.Tactic declare_syntax_cat aesop_rule syntax ident (aesop_prio)? (aesop_clause)* : aesop_rule declare_syntax_cat aesop_tactic_clause syntax ruleList := "[" aesop_rule,+,? "]" syntax "(" &"unsafe" ruleList ")" : aesop_tactic_clause syntax "(" &"safe" ruleList ")" : aesop_tactic_clause syntax "(" &"norm" ruleList ")" : aesop_tactic_clause syntax (name := aesop) &"aesop " (aesop_tactic_clause)* : tactic end Parser.Tactic structure AdditionalRule where ruleIdent : RuleIdent config : RuleConfig deriving Inhabited namespace AdditionalRule protected def parse (prioParser : Option Syntax → Except String α) (ruleKind : α → RuleKind) : Syntax → MetaM AdditionalRule | `(aesop_rule|$i:ident $[$prio:aesop_prio]? $clauses:aesop_clause*) => do let prio ← match prioParser prio with | Except.ok p => p | Except.error e => throwError "aesop: at rule {i}: {e}" let clauses ← clauses.mapM Clause.parse let config ← RuleConfig.ofKindAndClauses (ruleKind prio) clauses return { ruleIdent := (← RuleIdent.ofName i.getId), config := config } | _ => unreachable! protected def toRuleSetMember (r : AdditionalRule) : MetaM RuleSetMember := r.config.applyToRuleIdent r.ruleIdent end AdditionalRule def parseAdditionalRuleClause : Syntax → MetaM (Array AdditionalRule) | `(aesop_tactic_clause|(unsafe [$rules:aesop_rule,*])) => (rules : Array Syntax).mapM (AdditionalRule.parse parsePrioForUnsafeRule RuleKind.unsafe) | `(aesop_tactic_clause|(safe [$rules:aesop_rule,*])) => (rules : Array Syntax).mapM (AdditionalRule.parse parsePrioForSafeRule RuleKind.safe) | `(aesop_tactic_clause|(norm [$rules:aesop_rule,*])) => (rules : Array Syntax).mapM (AdditionalRule.parse parsePrioForNormRule RuleKind.norm) | _ => unreachable! structure TacticConfig where additionalRules : Array AdditionalRule deriving Inhabited namespace TacticConfig -- NOTE: Must be called with the MVar context of the main goal. protected def parse : Syntax → MetaM TacticConfig | `(tactic|aesop $[$clauses:aesop_tactic_clause]*) => do let rs ← clauses.concatMapM parseAdditionalRuleClause return { additionalRules := rs } | _ => unreachable! def additionalRuleSetMembers (c : TacticConfig) : MetaM (Array RuleSetMember) := c.additionalRules.mapM (·.toRuleSetMember) end TacticConfig end Lean.Aesop
e046043d96295bddbba09f23b67b964a4f4efe65
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/ptst.lean
f6b91b05fa9e1718d18d333ab4fdccb22fbb1560
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
77
lean
open prod nat -- Test tuple notation #check ((3:nat), false, (1:int), true)
2511715fa6d08c2f0e7c2d973c6629e3e29387f3
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/data/fin/ops.lean
68b58636654fa81c4065e96b457a709ead651e64
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
3,359
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.nat init.data.fin.basic namespace fin open nat variable {n : nat} def of_nat {n : nat} (a : nat) : fin (succ n) := ⟨a % succ n, nat.mod_lt _ (nat.zero_lt_succ _)⟩ private lemma mlt {n b : nat} : ∀ {a}, n > a → b % n < n | 0 h := nat.mod_lt _ h | (a+1) h := have n > 0, from lt.trans (nat.zero_lt_succ _) h, nat.mod_lt _ this protected def add : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a + b) % n, mlt h⟩ protected def mul : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨(a * b) % n, mlt h⟩ private lemma sublt {a b n : nat} (h : a < n) : a - b < n := lt_of_le_of_lt (nat.sub_le a b) h protected def sub : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a - b, sublt h⟩ private lemma modlt {a b n : nat} (h₁ : a < n) (h₂ : b < n) : a % b < n := begin cases b with b, {simp [mod_zero], assumption}, {assert h : a % (succ b) < succ b, apply nat.mod_lt _ (nat.zero_lt_succ _), exact lt.trans h h₂} end protected def mod : fin n → fin n → fin n | ⟨a, h₁⟩ ⟨b, h₂⟩ := ⟨a % b, modlt h₁ h₂⟩ private lemma divlt {a b n : nat} (h : a < n) : a / b < n := lt_of_le_of_lt (nat.div_le_self a b) h protected def div : fin n → fin n → fin n | ⟨a, h⟩ ⟨b, _⟩ := ⟨a / b, divlt h⟩ protected def lt : fin n → fin n → Prop | ⟨a, _⟩ ⟨b, _⟩ := a < b protected def le : fin n → fin n → Prop | ⟨a, _⟩ ⟨b, _⟩ := a ≤ b instance : has_zero (fin (succ n)) := ⟨of_nat 0⟩ instance : has_one (fin (succ n)) := ⟨of_nat 1⟩ instance : has_add (fin n) := ⟨fin.add⟩ instance : has_sub (fin n) := ⟨fin.sub⟩ instance : has_mul (fin n) := ⟨fin.mul⟩ instance : has_mod (fin n) := ⟨fin.mod⟩ instance : has_div (fin n) := ⟨fin.div⟩ instance : has_lt (fin n) := ⟨fin.lt⟩ instance : has_le (fin n) := ⟨fin.le⟩ instance decidable_lt : ∀ (a b : fin n), decidable (a < b) | ⟨a, _⟩ ⟨b, _⟩ := by apply nat.decidable_lt instance decidable_le : ∀ (a b : fin n), decidable (a ≤ b) | ⟨a, _⟩ ⟨b, _⟩ := by apply nat.decidable_le lemma add_def (a b : fin n) : (a + b).val = (a.val + b.val) % n := show (fin.add a b).val = (a.val + b.val) % n, from by cases a; cases b; simp [fin.add] lemma mul_def (a b : fin n) : (a * b).val = (a.val * b.val) % n := show (fin.mul a b).val = (a.val * b.val) % n, from by cases a; cases b; simp [fin.mul] lemma sub_def (a b : fin n) : (a - b).val = a.val - b.val := show (fin.sub a b).val = a.val - b.val, from by cases a; cases b; simp [fin.sub] lemma mod_def (a b : fin n) : (a % b).val = a.val % b.val := show (fin.mod a b).val = a.val % b.val, from by cases a; cases b; simp [fin.mod] lemma div_def (a b : fin n) : (a / b).val = a.val / b.val := show (fin.div a b).val = a.val / b.val, from by cases a; cases b; simp [fin.div] lemma lt_def (a b : fin n) : (a < b) = (a.val < b.val) := show (fin.lt a b) = (a.val < b.val), from by cases a; cases b; simp [fin.lt] lemma le_def (a b : fin n) : (a ≤ b) = (a.val ≤ b.val) := show (fin.le a b) = (a.val ≤ b.val), from by cases a; cases b; simp [fin.le] end fin
d60d51ffe34d9df4faaab0c67d5065cd707f6538
367134ba5a65885e863bdc4507601606690974c1
/src/number_theory/pythagorean_triples.lean
b1c6851e86406c73f5ac33da9701b5f807b5bfd3
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
26,046
lean
/- Copyright (c) 2020 Paul van Wamelen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Paul van Wamelen. -/ import algebra.field import ring_theory.int.basic import algebra.group_with_zero.power import tactic.ring import tactic.ring_exp import tactic.field_simp /-! # Pythagorean Triples The main result is the classification of Pythagorean triples. The final result is for general Pythagorean triples. It follows from the more interesting relatively prime case. We use the "rational parametrization of the circle" method for the proof. The parametrization maps the point `(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where `m / n` is the slope. In order to identify numerators and denominators we now need results showing that these are coprime. This is easy except for the prime 2. In order to deal with that we have to analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up the bulk of the proof below. -/ noncomputable theory open_locale classical /-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/ def pythagorean_triple (x y z : ℤ) : Prop := x * x + y * y = z * z /-- Pythagorean triples are interchangable, i.e `x * x + y * y = y * y + x * x = z * z`. This comes from additive commutativity. -/ lemma pythagorean_triple_comm {x y z : ℤ} : (pythagorean_triple x y z) ↔ (pythagorean_triple y x z) := by { delta pythagorean_triple, rw add_comm } /-- The zeroth Pythagorean triple is all zeros. -/ lemma pythagorean_triple.zero : pythagorean_triple 0 0 0 := by simp only [pythagorean_triple, zero_mul, zero_add] namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma eq : x * x + y * y = z * z := h @[symm] lemma symm : pythagorean_triple y x z := by rwa [pythagorean_triple_comm] /-- A triple is still a triple if you multiply `x`, `y` and `z` by a constant `k`. -/ lemma mul (k : ℤ) : pythagorean_triple (k * x) (k * y) (k * z) := begin by_cases hk : k = 0, { simp only [pythagorean_triple, hk, zero_mul, zero_add], }, { calc (k * x) * (k * x) + (k * y) * (k * y) = k ^ 2 * (x * x + y * y) : by ring ... = k ^ 2 * (z * z) : by rw h.eq ... = (k * z) * (k * z) : by ring } end omit h /-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if `(x, y, z)` is also a triple. -/ lemma mul_iff (k : ℤ) (hk : k ≠ 0) : pythagorean_triple (k * x) (k * y) (k * z) ↔ pythagorean_triple x y z := begin refine ⟨_, λ h, h.mul k⟩, simp only [pythagorean_triple], intro h, rw ← mul_left_inj' (mul_ne_zero hk hk), convert h using 1; ring, end include h /-- A Pythagorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that either * `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or * `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/ @[nolint unused_arguments] def is_classified := ∃ (k m n : ℤ), ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ int.gcd m n = 1 /-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime. Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either * `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or * `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`. -/ @[nolint unused_arguments] def is_primitive_classified := ∃ (m n : ℤ), ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) lemma mul_is_classified (k : ℤ) (hc : h.is_classified) : (h.mul k).is_classified := begin obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc, { use [k * l, m, n], apply and.intro _ co, left, split; ring }, { use [k * l, m, n], apply and.intro _ co, right, split; ring }, end lemma even_odd_of_coprime (hc : int.gcd x y = 1) : (x % 2 = 0 ∧ y % 2 = 1) ∨ (x % 2 = 1 ∧ y % 2 = 0) := begin cases int.mod_two_eq_zero_or_one x with hx hx; cases int.mod_two_eq_zero_or_one y with hy hy, { -- x even, y even exfalso, apply nat.not_coprime_of_dvd_of_dvd (dec_trivial : 1 < 2) _ _ hc, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hx }, { apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hy } }, { left, exact ⟨hx, hy⟩ }, -- x even, y odd { right, exact ⟨hx, hy⟩ }, -- x odd, y even { -- x odd, y odd exfalso, obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0* 2 + 1 ∧ y = y0 * 2 + 1, { cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hx) with x0 hx2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hy) with y0 hy2, rw sub_eq_iff_eq_add at hx2 hy2, exact ⟨x0, y0, hx2, hy2⟩ }, have hz : (z * z) % 4 = 2, { rw show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2, by { rw ← h.eq, ring }, simp only [int.add_mod, int.mul_mod_right, int.mod_mod, zero_add], refl }, have : ∀ (k : ℤ), 0 ≤ k → k < 4 → k * k % 4 ≠ 2 := dec_trivial, have h4 : (4 : ℤ) ≠ 0 := dec_trivial, apply this (z % 4) (int.mod_nonneg z h4) (int.mod_lt z h4), rwa [← int.mul_mod] }, end lemma gcd_dvd : (int.gcd x y : ℤ) ∣ z := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hz, dvd_zero], }, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul], rw [← int.pow_dvd_pow_iff (dec_trivial : 0 < 2), pow_two z, ← h.eq], rw (by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = k ^ 2 * (x0 * x0 + y0 * y0)), exact dvd_mul_right _ _ end lemma normalize : pythagorean_triple (x / int.gcd x y) (y / int.gcd x y) (z / int.gcd x y) := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, have hz : z = 0, { simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h }, simp only [hx, hy, hz, int.zero_div], exact zero }, rcases h.gcd_dvd with ⟨z0, rfl⟩, obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ : ∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k := int.exists_gcd_one' (nat.pos_of_ne_zero h0), have hk : (k : ℤ) ≠ 0, { norm_cast, rwa pos_iff_ne_zero at k0 }, rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul] at h ⊢, rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h, rwa [int.mul_div_cancel _ hk, int.mul_div_cancel _ hk, int.mul_div_cancel_left _ hk], end lemma is_classified_of_is_primitive_classified (hp : h.is_primitive_classified) : h.is_classified := begin obtain ⟨m, n, H⟩ := hp, use [1, m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩; { apply and.intro _ co, rw one_mul, rw one_mul, tauto } end lemma is_classified_of_normalize_is_primitive_classified (hc : h.normalize.is_primitive_classified) : h.is_classified := begin convert h.normalize.mul_is_classified (int.gcd x y) (is_classified_of_is_primitive_classified h.normalize hc); rw int.mul_div_cancel', { exact int.gcd_dvd_left x y }, { exact int.gcd_dvd_right x y }, { exact h.gcd_dvd } end lemma ne_zero_of_coprime (hc : int.gcd x y = 1) : z ≠ 0 := begin suffices : 0 < z * z, { rintro rfl, norm_num at this }, rw [← h.eq, ← pow_two, ← pow_two], have hc' : int.gcd x y ≠ 0, { rw hc, exact one_ne_zero }, cases int.ne_zero_of_gcd hc' with hxz hyz, { apply lt_add_of_pos_of_le (pow_two_pos_of_ne_zero x hxz) (pow_two_nonneg y) }, { apply lt_add_of_le_of_pos (pow_two_nonneg x) (pow_two_pos_of_ne_zero y hyz) } end lemma is_primitive_classified_of_coprime_of_zero_left (hc : int.gcd x y = 1) (hx : x = 0) : h.is_primitive_classified := begin subst x, change nat.gcd 0 (int.nat_abs y) = 1 at hc, rw [nat.gcd_zero_left (int.nat_abs y)] at hc, cases int.nat_abs_eq y with hy hy, { use [1, 0], rw [hy, hc, int.gcd_zero_right], norm_num }, { use [0, 1], rw [hy, hc, int.gcd_zero_left], norm_num } end lemma coprime_of_coprime (hc : int.gcd x y = 1) : int.gcd y z = 1 := begin by_contradiction H, obtain ⟨p, hp, hpy, hpz⟩ := nat.prime.not_coprime_iff_dvd.mp H, apply hp.not_dvd_one, rw [← hc], apply nat.dvd_gcd (int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp _ _) hpy, rw [pow_two, eq_sub_of_add_eq h], rw [← int.coe_nat_dvd_left] at hpy hpz, exact dvd_sub (dvd_mul_of_dvd_left (hpz) _) (dvd_mul_of_dvd_left (hpy) _), end end pythagorean_triple section circle_equiv_gen /-! ### A parametrization of the unit circle For the classification of pythogorean triples, we will use a parametrization of the unit circle. -/ variables {K : Type*} [field K] /-- A parameterization of the unit circle that is useful for classifying Pythagorean triples. (To be applied in the case where `K = ℚ`.) -/ def circle_equiv_gen (hk : ∀ x : K, 1 + x^2 ≠ 0) : K ≃ {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := { to_fun := λ x, ⟨⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩, by { field_simp [hk x, div_pow], ring }, begin simp only [ne.def, div_eq_iff (hk x), ←neg_mul_eq_neg_mul, one_mul, neg_add, sub_eq_add_neg, add_left_inj], simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1, end⟩, inv_fun := λ p, (p : K × K).1 / ((p : K × K).2 + 1), left_inv := λ x, begin have h2 : (1 + 1 : K) = 2 := rfl, have h3 : (2 : K) ≠ 0, { convert hk 1, rw [one_pow 2, h2] }, field_simp [hk x, h2, add_assoc, add_comm, add_sub_cancel'_right, mul_comm], end, right_inv := λ ⟨⟨x, y⟩, hxy, hy⟩, begin change x ^ 2 + y ^ 2 = 1 at hxy, have h2 : y + 1 ≠ 0, { apply mt eq_neg_of_add_eq_zero, exact hy }, have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1), { rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm], ring }, have h4 : (2 : K) ≠ 0, { convert hk 1, rw one_pow 2, refl }, simp only [prod.mk.inj_iff, subtype.mk_eq_mk], split, { field_simp [h3], ring }, { field_simp [h3], rw [← add_neg_eq_iff_eq_add.mpr hxy.symm], ring } end } @[simp] lemma circle_equiv_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (x : K) : (circle_equiv_gen hk x : K × K) = ⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩ := rfl @[simp] lemma circle_equiv_symm_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (v : {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1}) : (circle_equiv_gen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) := rfl end circle_equiv_gen private lemma coprime_pow_two_sub_pow_two_add_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have h2m : (p : ℤ) ∣ 2 * m ^ 2, { convert dvd_add hp2 hp1, ring }, have h2n : (p : ℤ) ∣ 2 * n ^ 2, { convert dvd_sub hp2 hp1, ring }, have hmc : p = 2 ∨ p ∣ int.nat_abs m := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m, have hnc : p = 2 ∨ p ∣ int.nat_abs n := prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n, by_cases h2 : p = 2, { have h3 : (m ^ 2 + n ^ 2) % 2 = 1, { norm_num [pow_two, int.add_mod, int.mul_mod, hm, hn] }, have h4 : (m ^ 2 + n ^ 2) % 2 = 0, { apply int.mod_eq_zero_of_dvd, rwa h2 at hp2 }, rw h4 at h3, exact zero_ne_one h3 }, { apply hp.not_dvd_one, rw ← h, exact nat.dvd_gcd (or.resolve_left hmc h2) (or.resolve_left hnc h2), } end private lemma coprime_pow_two_sub_pow_two_add_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0): int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm], apply coprime_pow_two_sub_pow_two_add_of_even_odd _ hn hm, rwa [int.gcd_comm], end private lemma coprime_pow_two_sub_mul_of_even_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 0) (hn : n % 2 = 1) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin by_contradiction H, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H, rw ← int.coe_nat_dvd_left at hp1 hp2, have hnp : ¬ (p : ℤ) ∣ int.gcd m n, { rw h, norm_cast, exact mt nat.dvd_one.mp (nat.prime.ne_one hp) }, cases int.prime.dvd_mul hp hp2 with hp2m hpn, { rw int.nat_abs_mul at hp2m, cases (nat.prime.dvd_mul hp).mp hp2m with hp2 hpm, { have hp2' : p = 2 := (nat.le_of_dvd zero_lt_two hp2).antisymm hp.two_le, revert hp1, rw hp2', apply mt int.mod_eq_zero_of_dvd, norm_num [pow_two, int.sub_mod, int.mul_mod, hm, hn], }, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpm)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : n * n = - (m ^ 2 - n ^ 2) + m * m), apply dvd_add (dvd_neg_of_dvd hp1), exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpm) m }, rw int.gcd_comm at hnp, apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpn)) hnp, apply (or_self _).mp, apply int.prime.dvd_mul' hp, rw (by ring : m * m = (m ^ 2 - n ^ 2) + n * n), apply dvd_add hp1, exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpn) n end private lemma coprime_pow_two_sub_mul_of_odd_even {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 0) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)], rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)], apply coprime_pow_two_sub_mul_of_even_odd _ hn hm, rwa [int.gcd_comm] end private lemma coprime_pow_two_sub_mul {m n : ℤ} (h : int.gcd m n = 1) (hmn : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) : int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 := begin cases hmn with h1 h2, { exact coprime_pow_two_sub_mul_of_even_odd h h1.left h1.right }, { exact coprime_pow_two_sub_mul_of_odd_even h h2.left h2.right } end private lemma coprime_pow_two_sub_pow_two_sum_of_odd_odd {m n : ℤ} (h : int.gcd m n = 1) (hm : m % 2 = 1) (hn : n % 2 = 1) : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 := begin cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hm) with m0 hm2, cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hn) with n0 hn2, rw sub_eq_iff_eq_add at hm2 hn2, subst m, subst n, have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1), by ring_exp, have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)), by ring_exp, have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0, { rw [h2, int.mul_div_cancel_left, int.mul_mod_right], exact dec_trivial }, refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩, have h20 : (2:ℤ) ≠ 0 := dec_trivial, rw [h1, h2, int.mul_div_cancel_left _ h20, int.mul_div_cancel_left _ h20], by_contra h4, obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp h4, apply hp.not_dvd_one, rw ← h, rw ← int.coe_nat_dvd_left at hp1 hp2, apply nat.dvd_gcd, { apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp, convert dvd_add hp1 hp2, ring_exp }, { apply int.prime.dvd_nat_abs_of_coe_dvd_pow_two hp, convert dvd_sub hp2 hp1, ring_exp }, end namespace pythagorean_triple variables {x y z : ℤ} (h : pythagorean_triple x y z) include h lemma is_primitive_classified_aux (hc : x.gcd y = 1) (hzpos : 0 < z) {m n : ℤ} (hm2n2 : 0 < m ^ 2 + n ^ 2) (hv2 : (x : ℚ) / z = 2 * m * n / (m ^ 2 + n ^ 2)) (hw2 : (y : ℚ) / z = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2)) (H : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1) (co : int.gcd m n = 1) (pp : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)): h.is_primitive_classified := begin have hz : z ≠ 0, apply ne_of_gt hzpos, have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2, { apply rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H, rw [hw2], norm_cast }, use [m, n], apply and.intro _ (and.intro co pp), right, refine ⟨_, h2.left⟩, rw [← rat.coe_int_inj _ _, ← div_left_inj' ((mt (rat.coe_int_inj z 0).mp) hz), hv2, h2.right], norm_cast end theorem is_primitive_classified_of_coprime_of_odd_of_pos (hc : int.gcd x y = 1) (hyo : y % 2 = 1) (hzpos : 0 < z) : h.is_primitive_classified := begin by_cases h0 : x = 0, { exact h.is_primitive_classified_of_coprime_of_zero_left hc h0 }, let v := (x : ℚ) / z, let w := (y : ℚ) / z, have hz : z ≠ 0, apply ne_of_gt hzpos, have hq : v ^ 2 + w ^ 2 = 1, { field_simp [hz, pow_two], norm_cast, exact h }, have hvz : v ≠ 0, { field_simp [hz], exact h0 }, have hw1 : w ≠ -1, { contrapose! hvz with hw1, rw [hw1, neg_square, one_pow, add_left_eq_self] at hq, exact pow_eq_zero hq, }, have hQ : ∀ x : ℚ, 1 + x^2 ≠ 0, { intro q, apply ne_of_gt, exact lt_add_of_pos_of_le zero_lt_one (pow_two_nonneg q) }, have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ {p : ℚ × ℚ | p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := ⟨hq, hw1⟩, let q := (circle_equiv_gen hQ).symm ⟨⟨v, w⟩, hp⟩, have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2), { apply prod.mk.inj, have := ((circle_equiv_gen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm, exact congr_arg subtype.val this, }, let m := (q.denom : ℤ), let n := q.num, have hm0 : m ≠ 0, { norm_cast, apply rat.denom_ne_zero q }, have hq2 : q = n / m, { rw [int.cast_coe_nat], exact (rat.cast_id q).symm }, have hm2n2 : 0 < m ^ 2 + n ^ 2, { apply lt_add_of_pos_of_le _ (pow_two_nonneg n), exact lt_of_le_of_ne (pow_two_nonneg m) (ne.symm (pow_ne_zero 2 hm0)) }, have hw2 : w = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2), { rw [ht4.2, hq2], field_simp [hm2n2, (rat.denom_ne_zero q)] }, have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0, { norm_cast, simpa only [int.coe_nat_pow] using ne_of_gt hm2n2 }, have hv2 : v = 2 * m * n / (m ^ 2 + n ^ 2), { apply eq.symm, apply (div_eq_iff hm2n20).mpr, rw [ht4.1], field_simp [hQ q], rw [hq2] {occs := occurrences.pos [2, 3]}, field_simp [rat.denom_ne_zero q], ring }, have hnmcp : int.gcd n m = 1 := q.cop, have hmncp : int.gcd m n = 1, { rw int.gcd_comm, exact hnmcp }, cases int.mod_two_eq_zero_or_one m with hm2 hm2; cases int.mod_two_eq_zero_or_one n with hn2 hn2, { -- m even, n even exfalso, have h1 : 2 ∣ (int.gcd n m : ℤ), { exact int.dvd_gcd (int.dvd_of_mod_eq_zero hn2) (int.dvd_of_mod_eq_zero hm2) }, rw hnmcp at h1, revert h1, norm_num }, { -- m even, n odd apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_left, exact and.intro hm2 hn2 }, { apply coprime_pow_two_sub_pow_two_add_of_even_odd hmncp hm2 hn2 } }, { -- m odd, n even apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp, { apply or.intro_right, exact and.intro hm2 hn2 }, apply coprime_pow_two_sub_pow_two_add_of_odd_even hmncp hm2 hn2 }, { -- m odd, n odd exfalso, have h1 : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2 ∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1, { exact coprime_pow_two_sub_pow_two_sum_of_odd_odd hmncp hm2 hn2 }, have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2, { apply rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2, { show w = _, rw [←rat.mk_eq_div, ←(rat.div_mk_div_cancel_left (by norm_num : (2 : ℤ) ≠ 0))], rw [int.div_mul_cancel h1.1, int.div_mul_cancel h1.2.1, hw2], norm_cast }, { apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp, rw [int.div_mul_cancel h1.1, zero_mul], exact hm2n2 } }, rw [h2.1, h1.2.2.1] at hyo, revert hyo, norm_num } end theorem is_primitive_classified_of_coprime_of_pos (hc : int.gcd x y = 1) (hzpos : 0 < z): h.is_primitive_classified := begin cases h.even_odd_of_coprime hc with h1 h2, { exact (h.is_primitive_classified_of_coprime_of_odd_of_pos hc h1.right hzpos) }, rw int.gcd_comm at hc, obtain ⟨m, n, H⟩ := (h.symm.is_primitive_classified_of_coprime_of_odd_of_pos hc h2.left hzpos), use [m, n], tauto end theorem is_primitive_classified_of_coprime (hc : int.gcd x y = 1) : h.is_primitive_classified := begin by_cases hz : 0 < z, { exact h.is_primitive_classified_of_coprime_of_pos hc hz }, have h' : pythagorean_triple x y (-z), { simpa [pythagorean_triple, neg_mul_neg] using h.eq, }, apply h'.is_primitive_classified_of_coprime_of_pos hc, apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm, exact le_neg.mp (not_lt.mp hz) end theorem classified : h.is_classified := begin by_cases h0 : int.gcd x y = 0, { have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 }, have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 }, use [0, 1, 0], norm_num [hx, hy], }, apply h.is_classified_of_normalize_is_primitive_classified, apply h.normalize.is_primitive_classified_of_coprime, apply int.gcd_div_gcd_div_gcd (nat.pos_of_ne_zero h0), end omit h theorem coprime_classification : pythagorean_triple x y z ∧ int.gcd x y = 1 ↔ ∃ m n, ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2)) ∧ (z = m ^ 2 + n ^ 2 ∨ z = - (m ^ 2 + n ^ 2)) ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) := begin split, { intro h, obtain ⟨m, n, H⟩ := h.left.is_primitive_classified_of_coprime h.right, use [m, n], rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [pow_two, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _, co, pp⟩, have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2, { rw [pow_two, ← h.left.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } }, { delta pythagorean_triple, rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩; { split, { ring }, exact coprime_pow_two_sub_mul co pp } <|> { split, { ring }, rw int.gcd_comm, exact coprime_pow_two_sub_mul co pp } } end /-- by assuming `x` is odd and `z` is positive we get a slightly more precise classification of the pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`-/ theorem coprime_classification' {x y z : ℤ} (h : pythagorean_triple x y z) (h_coprime : int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) : ∃ m n, x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n ∧ z = m ^ 2 + n ^ 2 ∧ int.gcd m n = 1 ∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) ∧ 0 ≤ m := begin obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ := pythagorean_triple.coprime_classification.mp (and.intro h h_coprime), cases le_or_lt 0 m with hm hm, { use [m, n], cases ht1 with h_odd h_even, { apply and.intro h_odd.1, apply and.intro h_odd.2, cases ht2 with h_pos h_neg, { apply and.intro h_pos (and.intro ht3 (and.intro ht4 hm)) }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (pow_two_nonneg m) (pow_two_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity }, { use [-m, -n], cases ht1 with h_odd h_even, { rw [neg_square m], rw [neg_square n], apply and.intro h_odd.1, split, { rw h_odd.2, ring }, cases ht2 with h_pos h_neg, { apply and.intro h_pos, split, { delta int.gcd, rw [int.nat_abs_neg, int.nat_abs_neg], exact ht3 }, { rw [int.neg_mod_two, int.neg_mod_two], apply and.intro ht4, linarith } }, { exfalso, revert h_pos, rw h_neg, exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (pow_two_nonneg m) (pow_two_nonneg n)))) } }, exfalso, rcases h_even with ⟨rfl, -⟩, rw [mul_assoc, int.mul_mod_right] at h_parity, exact zero_ne_one h_parity } end theorem classification : pythagorean_triple x y z ↔ ∃ k m n, ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2))) ∧ (z = k * (m ^ 2 + n ^ 2) ∨ z = - k * (m ^ 2 + n ^ 2)) := begin split, { intro h, obtain ⟨k, m, n, H⟩ := h.classified, use [k, m, n], rcases H with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine ⟨or.inl ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [pow_two, ← h.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this }, { refine ⟨or.inr ⟨rfl, rfl⟩, _⟩, have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2, { rw [pow_two, ← h.eq], ring }, simpa using eq_or_eq_neg_of_pow_two_eq_pow_two _ _ this } }, { rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩; delta pythagorean_triple; ring } end end pythagorean_triple
909448839e4d5084b2a5bf78f64e33919156f331
f94866221d9fc3e2706d042c19de3c569d853531
/src/main.lean
f1c77ae057e8ff5c0a0fc556ddba994c4c440d5f
[]
no_license
arthur-adjedj/proof_Q_denumerable
1040647af48ffa7afe921b73a96c89e1a6896ba3
7a1059ea91cff929bb0c5fa3876c73b72ebee9f7
refs/heads/main
1,692,085,100,716
1,632,130,913,000
1,632,130,913,000
398,863,134
1
0
null
null
null
null
UTF-8
Lean
false
false
6,203
lean
import init.data.nat.basic import tactic.finish import tactic.ext import biject import init.data.int.basic import data.int.basic import data.nat.parity import tactic.hint import data.nat.basic universes u1 u2 u3 u4 def denombrable (α : Sort u1) : Prop := in_bijection ℕ α theorem tf_l {A : Sort u1} {B : Sort u2} {x3 x4 :pprod A B} : x3 = x4 → x3.1 = x4.1 ∧ x3.2 = x4.2 := begin intro a, apply and.intro, apply map_eq (λ x :pprod A B, x.1) a, apply map_eq (λ x :pprod A B, x.2) a, end theorem tf_r {A : Sort u1} {B : Sort u2} {x3 x4 :pprod A B} : x3.1 = x4.1 ∧ x3.2 = x4.2 → x3 = x4 := begin intro eq1, cases eq1 with a b, cases x3, cases x4, finish end theorem tf {A : Sort u1} {B : Sort u2} (x3 x4 :pprod A B) : x3 = x4 ↔ x3.1 = x4.1 ∧ x3.2 = x4.2 := begin split, apply tf_l, apply tf_r end def prod_func {A : Sort u1} {B : Sort u2} {C : Sort u3} {D : Sort u4} (f : A → B) (g : C → D) : pprod A C → pprod B D := λ x : pprod A C , pprod.mk (f (x.fst)) (g x.snd) theorem prod_bij_prod_left {A : Sort u1} {B : Sort u2} {C : Sort u3} {D : Sort u4} (f : A → B) (g : C → D) [bijective f] [bijective g] : bijective (prod_func f g) := begin apply and.intro, intros x1 x2, rw prod_func, simp, intro h, apply iff.elim_right (tf x1 x2), apply and.intro, apply _inst_1.left x1.fst x2.fst ((tf (prod_func f g x1) (prod_func f g x2)).elim_left h).left, apply _inst_2.left x1.snd x2.snd ((tf (prod_func f g x1) (prod_func f g x2)).elim_left h).right, intro y, let x1 := (_inst_1.elim_right y.1).some, let x2 := (_inst_2.elim_right y.2).some, use pprod.mk x1 x2, rw prod_func, simp, apply tf_r, simp, change x1 with (_inst_1.elim_right y.1).some, change x2 with (_inst_2.elim_right y.2).some, split, apply Exists.some_spec (_inst_1.elim_right y.1), apply Exists.some_spec (_inst_2.elim_right y.2) end def nat_plus := { n : ℕ // ¬ n = 0} lemma nat_succ_not_zero (n : ℕ) : ¬ n.succ = 0 := begin apply not.intro, trivial end def succ_plus (n : ℕ ) : nat_plus := ⟨ n.succ,nat_succ_not_zero n⟩ lemma not_zero_le (n : ℕ) : ¬ n = 0 ↔ 0 < n := begin split, apply nat.cases_on n, trivial, intro m, simp, apply nat.cases_on n, simp, intro m, simp, trivial end lemma bon (n : nat_plus) : n.val.pred.succ = n.val := begin apply n.cases_on, intros k p, simp, apply nat.succ_pred_eq_of_pos ((not_zero_le k).elim_left p) end theorem Nplus_denumbrable : denombrable nat_plus := begin rw [denombrable,in_bijection], use succ_plus, split, intros x1 x2, rw [succ_plus,succ_plus], intro hyp, apply subtype.mk.inj, simp, apply nat.succ.inj (subtype.mk_eq_mk.elim_left hyp), exact (λ n : ℕ , true), trivial, trivial, intro y, use y.val.pred, rw succ_plus, rw eq.symm (subtype.coe_eta y y.property), rw subtype.mk.inj_eq, simp, apply bon y end def abs_nat : ℤ → ℕ |(int.of_nat k) := k |(int.neg_succ_of_nat k) := k @[simp] def nat_abs : ℤ → ℕ | (int.of_nat m) := m | -[1+ m] := m.succ constant h : Prop constant dh : decidable h constants a b : α lemma if_works {α : Sort u1} {p : Prop} [decidable p] {a b: α} : p → (ite p a b = a) := begin intro h, simp, intro nh, trivial end lemma if_not_works {α : Sort u1} {p : Prop} [decidable p] {a b: α} : ¬ p → (ite p a b = b) := begin intro h, rw eq.symm (ite_not p b a), apply if_works, exact h end lemma whatever_decidable : decidable (∀ (n : ℕ), 0 ≤ (n : ℤ )) := begin simp, apply decidable.true end def f : ℕ → ℤ := λ n: ℕ , (-1) ^n *(n/2) def g : ℤ → ℕ := λ z : ℤ, if z ≤ 0 then (0-2*(nat_abs z)) else 1+2*(nat_abs z) lemma leq_two_z_o (n : ℕ) : n<2 → n=0 ∨ n=1 := begin cases n, tauto, intro, fconstructor, hint end lemma is_le_one_is_zero : ∀ n : ℕ, n<1 → n=0 := begin intro n, cases n, simp, intro h, have p : ¬ n.succ < 1 := dec_trivial, apply absurd h p end lemma even_succ_not_zero (n : ℕ) (h : even n.succ) : ¬(n.succ / 2 = 0) := begin apply not.intro, have wut : 0 < 2 := by simp, rw nat.div_eq_zero_iff wut, simp at *, cases h, norm_cast at *, intro x, safe, rw eq.symm (nat.one_mul 2) at x, rw nat.mul_assoc at x, have lol : 1 * (2 * h_w) = (2 * h_w) := by simp, rw lol at x, rw nat.mul_comm 1 2 at x, have triv : 0 ≤ 2 := by simp, have hmm := @lt_of_mul_lt_mul_left nat nat.linear_ordered_semiring h_w 1 2 x triv, have hw_z : h_w= 0 := by apply is_le_one_is_zero h_w hmm, rw hw_z at h_h, simp at h_h, have triv : ¬ n.succ = 0 := by trivial, apply absurd h_h triv end theorem comp_fg_is_id : comp g f = id := begin rw comp, change g with λ (z : ℤ), ite (z ≤ 0) (0 - 2 * nat_abs z) (1+2 * nat_abs z), change f with λ (n : ℕ), (-1) ^ n * (↑n / 2), simp, rw function.funext_iff, intro n, simp, by_cases even n, rw nat.neg_one_pow_of_even h, simp, cases n, simp, have p : ¬(n.succ / 2 ≤ 0) := by simp;exact even_succ_not_zero n h, simp at p, split_ifs, simp at h_1, norm_cast at *, rw nat.succ_eq_add_one n at p, simp at h_1, apply absurd h_1 p, simp, cases n, simp, apply or.intro_right, finish, norm_cast at *, simp, cases n, simp, end /- theorem Z_denumbrable : denombrable ℤ := begin rw denombrable, rw in_bijection, use f, rw [bijective,and_comm], split, intro x, use g x, change g with λ (z : ℤ), ite (z ≤ 0) (1 - 2 * nat_abs z) (2 * nat_abs z), change f with λ (n : ℕ), (-1) ^ n * (↑n / 2), cases x, simp, apply if_works int.coe_nat_nonneg, end -/
63433c18f2c159c73f2c107ea33bc30fde81258f
aa5a655c05e5359a70646b7154e7cac59f0b4132
/tests/lean/run/concatElim.lean
f5ccc730c778afdedc692bf2aaa107400a04f63c
[ "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
2,992
lean
universes u def concat {α} : List α → α → List α | [], a => [a] | x::xs, a => x :: concat xs a def last {α} : (xs : List α) → xs ≠ [] → α | [], h => absurd rfl h | [a], h => a | _::a::as, h => last (a::as) (fun h => by injection h) def dropLast {α} : List α → List α | [] => [] | [a] => [] | a::as => a :: dropLast as variable {α} theorem concatEq (xs : List α) (h : xs ≠ []) : concat (dropLast xs) (last xs h) = xs := by match xs, h with | [], h => apply False.elim apply h rfl | [x], h => rfl | x₁::x₂::xs, h => have x₂::xs ≠ [] by intro h; injection h have ih := concatEq (x₂::xs) this show x₁ :: concat (dropLast (x₂::xs)) (last (x₂::xs) this) = x₁ :: x₂ :: xs rewrite ih rfl theorem lengthCons {α} (x : α) (xs : List α) : (x::xs).length = xs.length + 1 := let rec aux (a : α) (xs : List α) : (n : Nat) → (a::xs).lengthAux n = xs.lengthAux n + 1 := match xs with | [] => fun _ => rfl | x::xs => fun n => aux a xs (n+1) aux x xs 0 theorem eqNilOfLengthZero {α} : (xs : List α) → xs.length = 0 → xs = [] | [], h => rfl | x::xs, h => by rw [lengthCons] at h; injection h theorem dropLastLen {α} (xs : List α) : (n : Nat) → xs.length = n+1 → (dropLast xs).length = n := by match xs with | [] => intro _ h; injection h | [a] => intro n h have 1 = n + 1 from h have 0 = n by injection this; assumption subst this rfl | x₁::x₂::xs => intro n h cases n with | zero => rw [lengthCons, lengthCons] at h injection h with h injection h | succ n => have (x₁ :: x₂ :: xs).length = xs.length + 2 by rw [lengthCons, lengthCons] have xs.length = n by rw [this] at h; injection h with h; injection h with h; assumption have ih : (dropLast (x₂::xs)).length = xs.length from dropLastLen (x₂::xs) xs.length (lengthCons _ _) show (x₁ :: dropLast (x₂ :: xs)).length = n+1 rw [lengthCons, ih, this] @[inline] def concatElim {α} (motive : List α → Sort u) (base : Unit → motive []) (ind : (xs : List α) → (a : α) → motive xs → motive (concat xs a)) (xs : List α) : motive xs := let rec @[specialize] aux : (n : Nat) → (xs : List α) → xs.length = n → motive xs | 0, xs, h => by have aux := eqNilOfLengthZero _ h subst aux apply base () | n+1, xs, h => by have notNil : xs ≠ [] by intro h1; subst h1; injection h let ih := aux n (dropLast xs) (dropLastLen _ _ h) let aux := ind (dropLast xs) (last xs notNil) ih rw [concatEq] at aux exact aux aux xs.length xs rfl -- The generated code is tail recursive def test (xs : List Nat) : IO Unit := concatElim (motive := fun _ => IO Unit) (fun _ => pure ()) (fun xs x r => do IO.println s!"step xs: {xs} x: {x}"; r) xs #eval test [1, 2, 3, 4]
1f05422a4eb37c5f750fac42f68a73db152da722
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/euclidean_domain.lean
83e3caea25d8affe6484642f7131b46912210be0
[ "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
2,587
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes -/ import ring_theory.coprime import ring_theory.ideal.basic /-! # Lemmas about Euclidean domains Various about Euclidean domains are proved; all of them seem to be true more generally for principal ideal domains, so these lemmas should probably be reproved in more generality and this file perhaps removed? ## Tags euclidean domain -/ noncomputable theory open_locale classical open euclidean_domain set ideal -- TODO -- this should surely be proved for PIDs instead? theorem span_gcd {α} [euclidean_domain α] (x y : α) : span ({gcd x y} : set α) = span ({x, y} : set α) := begin apply le_antisymm, { refine span_le.2 (λ x, _), simp only [set.mem_singleton_iff, set_like.mem_coe, mem_span_pair], rintro rfl, exact ⟨gcd_a x y, gcd_b x y, by simp [gcd_eq_gcd_ab, mul_comm]⟩ }, { assume z , simp [mem_span_singleton, euclidean_domain.gcd_dvd_left, mem_span_pair, @eq_comm _ _ z] {contextual := tt}, assume a b h, exact dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left _ _) _) (dvd_mul_of_dvd_right (gcd_dvd_right _ _) _) } end -- this should be proved for PIDs? theorem gcd_is_unit_iff {α} [euclidean_domain α] {x y : α} : is_unit (gcd x y) ↔ is_coprime x y := ⟨λ h, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 h in ⟨b * gcd_a x y, b * gcd_b x y, by rw [← hb, gcd_eq_gcd_ab, mul_comm x, mul_comm y, mul_add, mul_assoc, mul_assoc]⟩, λ ⟨a, b, h⟩, is_unit_iff_dvd_one.2 $ h ▸ dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left x y) _) (dvd_mul_of_dvd_right (gcd_dvd_right x y) _)⟩ -- this should be proved for UFDs surely? theorem is_coprime_of_dvd {α} [euclidean_domain α] {x y : α} (z : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits α, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, euclidean_domain.gcd_eq_zero_iff] end -- this should be proved for UFDs surely? theorem dvd_or_coprime {α} [euclidean_domain α] (x y : α) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), apply is_coprime_of_dvd, { unfreezingI { rintro ⟨rfl, rfl⟩ }, simpa using h }, { unfreezingI { rintro z nu nz ⟨w, rfl⟩ dy }, refine h' (dvd.trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end
349d7b287aad74d80f8d9f4a936d4313e088b755
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/finsupp/default.lean
1864bbe881fa990b31ff6321cc653c554f86b699
[]
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
288
lean
/- Copyright (c) 2020 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.finsupp.basic import Mathlib.PostPort namespace Mathlib
f3121de21b8bbf8013052d720334f4a68503d27c
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/group_theory/quotient_group.lean
6d968723f6ab41d2308b257cf3c4c38be0a9210b
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
7,555
lean
/- Copyright (c) 2018 Kevin Buzzard and Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Patrick Massot. This file is to a certain extent based on `quotient_module.lean` by Johannes Hölzl. -/ import group_theory.coset universes u v namespace quotient_group variables {G : Type u} [group G] (N : subgroup G) [nN : N.normal] {H : Type v} [group H] include nN @[to_additive quotient_add_group.add_group] instance : group (quotient N) := { one := (1 : G), mul := quotient.map₂' (*) (λ a₁ b₁ hab₁ a₂ b₂ hab₂, ((N.mul_mem_cancel_right (N.inv_mem hab₂)).1 (by rw [mul_inv_rev, mul_inv_rev, ← mul_assoc (a₂⁻¹ * a₁⁻¹), mul_assoc _ b₂, ← mul_assoc b₂, mul_inv_self, one_mul, mul_assoc (a₂⁻¹)]; exact nN.conj_mem _ hab₁ _))), mul_assoc := λ a b c, quotient.induction_on₃' a b c (λ a b c, congr_arg mk (mul_assoc a b c)), one_mul := λ a, quotient.induction_on' a (λ a, congr_arg mk (one_mul a)), mul_one := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_one a)), inv := λ a, quotient.lift_on' a (λ a, ((a⁻¹ : G) : quotient N)) (λ a b hab, quotient.sound' begin show a⁻¹⁻¹ * b⁻¹ ∈ N, rw ← mul_inv_rev, exact N.inv_mem (nN.mem_comm hab) end), mul_left_inv := λ a, quotient.induction_on' a (λ a, congr_arg mk (mul_left_inv a)) } /-- The group homomorphism from `G` to `G/N`. -/ @[to_additive quotient_add_group.mk' "The additive group homomorphism from `G` to `G/N`."] def mk' : G →* quotient N := monoid_hom.mk' (quotient_group.mk) (λ _ _, rfl) @[simp, to_additive quotient_add_group.ker_mk] lemma ker_mk : monoid_hom.ker (quotient_group.mk' N : G →* quotient_group.quotient N) = N := begin ext g, rw [monoid_hom.mem_ker, eq_comm], show (((1 : G) : quotient_group.quotient N)) = g ↔ _, rw [quotient_group.eq, one_inv, one_mul], end -- for commutative groups we don't need normality assumption omit nN @[to_additive quotient_add_group.add_comm_group] instance {G : Type*} [comm_group G] (N : subgroup G) : comm_group (quotient N) := { mul_comm := λ a b, quotient.induction_on₂' a b (λ a b, congr_arg mk (mul_comm a b)), ..@quotient_group.group _ _ N N.normal_of_comm } include nN @[simp, to_additive quotient_add_group.coe_zero] lemma coe_one : ((1 : G) : quotient N) = 1 := rfl @[simp, to_additive quotient_add_group.coe_add] lemma coe_mul (a b : G) : ((a * b : G) : quotient N) = a * b := rfl @[simp, to_additive quotient_add_group.coe_neg] lemma coe_inv (a : G) : ((a⁻¹ : G) : quotient N) = a⁻¹ := rfl @[simp] lemma coe_pow (a : G) (n : ℕ) : ((a ^ n : G) : quotient N) = a ^ n := (mk' N).map_pow a n @[simp] lemma coe_gpow (a : G) (n : ℤ) : ((a ^ n : G) : quotient N) = a ^ n := (mk' N).map_gpow a n local notation ` Q ` := quotient N /-- A group homomorphism `φ : G →* H` with `N ⊆ ker(φ)` descends (i.e. `lift`s) to a group homomorphism `G/N →* H`. -/ @[to_additive quotient_add_group.lift "An `add_group` homomorphism `φ : G →+ H` with `N ⊆ ker(φ)` descends (i.e. `lift`s) to a group homomorphism `G/N →* H`."] def lift (φ : G →* H) (HN : ∀x∈N, φ x = 1) : Q →* H := monoid_hom.mk' (λ q : Q, q.lift_on' φ $ assume a b (hab : a⁻¹ * b ∈ N), (calc φ a = φ a * 1 : (mul_one _).symm ... = φ a * φ (a⁻¹ * b) : HN (a⁻¹ * b) hab ▸ rfl ... = φ (a * (a⁻¹ * b)) : (is_mul_hom.map_mul φ a (a⁻¹ * b)).symm ... = φ b : by rw mul_inv_cancel_left)) (λ q r, quotient.induction_on₂' q r $ is_mul_hom.map_mul φ) @[simp, to_additive quotient_add_group.lift_mk] lemma lift_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (g : Q) = φ g := rfl @[simp, to_additive quotient_add_group.lift_mk'] lemma lift_mk' {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (mk g : Q) = φ g := rfl @[simp, to_additive quotient_add_group.lift_quot_mk] lemma lift_quot_mk {φ : G →* H} (HN : ∀x∈N, φ x = 1) (g : G) : lift N φ HN (quot.mk _ g : Q) = φ g := rfl /-- A group homomorphism `f : G →* H` induces a map `G/N →* H/M` if `N ⊆ f⁻¹(M)`. -/ @[to_additive quotient_add_group.map "An `add_group` homomorphism `f : G →+ H` induces a map `G/N →+ H/M` if `N ⊆ f⁻¹(M)`."] def map (M : subgroup H) [M.normal] (f : G →* H) (h : N ≤ M.comap f) : quotient N →* quotient M := begin refine quotient_group.lift N ((mk' M).comp f) _, assume x hx, refine quotient_group.eq.2 _, rw [mul_one, subgroup.inv_mem_iff], exact h hx, end omit nN variables (φ : G →* H) open function monoid_hom /-- The induced map from the quotient by the kernel to the codomain. -/ @[to_additive quotient_add_group.ker_lift "The induced map from the quotient by the kernel to the codomain."] def ker_lift : quotient (ker φ) →* H := lift _ φ $ λ g, φ.mem_ker.mp @[simp, to_additive quotient_add_group.ker_lift_mk] lemma ker_lift_mk (g : G) : (ker_lift φ) g = φ g := lift_mk _ _ _ @[simp, to_additive quotient_add_group.ker_lift_mk'] lemma ker_lift_mk' (g : G) : (ker_lift φ) (mk g) = φ g := lift_mk' _ _ _ @[to_additive quotient_add_group.injective_ker_lift] lemma ker_lift_injective : injective (ker_lift φ) := assume a b, quotient.induction_on₂' a b $ assume a b (h : φ a = φ b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [mem_ker, is_mul_hom.map_mul φ, ← h, is_group_hom.map_inv φ, inv_mul_self] -- Note that ker φ isn't definitionally ker (to_range φ) -- so there is a bit of annoying code duplication here /-- The induced map from the quotient by the kernel to the range. -/ @[to_additive quotient_add_group.range_ker_lift "The induced map from the quotient by the kernel to the range."] def range_ker_lift : quotient (ker φ) →* φ.range := lift _ (to_range φ) $ λ g hg, (mem_ker _).mp $ by rwa to_range_ker @[to_additive quotient_add_group.range_ker_lift_injective] lemma range_ker_lift_injective : injective (range_ker_lift φ) := assume a b, quotient.induction_on₂' a b $ assume a b (h : to_range φ a = to_range φ b), quotient.sound' $ show a⁻¹ * b ∈ ker φ, by rw [←to_range_ker, mem_ker, is_mul_hom.map_mul (to_range φ), ← h, is_group_hom.map_inv (to_range φ), inv_mul_self] @[to_additive quotient_add_group.range_ker_lift_surjective] lemma range_ker_lift_surjective : surjective (range_ker_lift φ) := begin rintro ⟨_, g, rfl⟩, use mk g, refl, end /-- The first isomorphism theorem (a definition): the canonical isomorphism between `G/(ker φ)` to `range φ`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_range "The first isomorphism theorem (a definition): the canonical isomorphism between `G/(ker φ)` to `range φ`."] noncomputable def quotient_ker_equiv_range : (quotient (ker φ)) ≃* range φ := mul_equiv.of_bijective (range_ker_lift φ) ⟨range_ker_lift_injective φ, range_ker_lift_surjective φ⟩ /-- The canonical isomorphism `G/(ker φ) ≃* H` induced by a surjection `φ : G →* H`. -/ @[to_additive quotient_add_group.quotient_ker_equiv_of_surjective "The canonical isomorphism `G/(ker φ) ≃+ H` induced by a surjection `φ : G →+ H`."] noncomputable def quotient_ker_equiv_of_surjective (hφ : function.surjective φ) : (quotient (ker φ)) ≃* H := mul_equiv.of_bijective (ker_lift φ) ⟨ker_lift_injective φ, λ h, begin rcases hφ h with ⟨g, rfl⟩, use mk g, refl end⟩ end quotient_group
66f45cd66bc5089b4a208a664bd376d3f06f0de4
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/affine_space/slope.lean
18267ebaf02d16d3e742732027504aa75265129f
[ "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
4,527
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import algebra.order.module import linear_algebra.affine_space.affine_map import tactic.field_simp /-! # Slope of a function In this file we define the slope of a function `f : k → PE` taking values in an affine space over `k` and prove some basic theorems about `slope`. The `slope` function naturally appears in the Mean Value Theorem, and in the proof of the fact that a function with nonnegative second derivative on an interval is convex on this interval. ## Tags affine space, slope -/ open affine_map variables {k E PE : Type*} [field k] [add_comm_group E] [module k E] [add_torsor E PE] include E /-- `slope f a b = (b - a)⁻¹ • (f b -ᵥ f a)` is the slope of a function `f` on the interval `[a, b]`. Note that `slope f a a = 0`, not the derivative of `f` at `a`. -/ def slope (f : k → PE) (a b : k) : E := (b - a)⁻¹ • (f b -ᵥ f a) lemma slope_fun_def (f : k → PE) : slope f = λ a b, (b - a)⁻¹ • (f b -ᵥ f a) := rfl omit E lemma slope_def_field (f : k → k) (a b : k) : slope f a b = (f b - f a) / (b - a) := div_eq_inv_mul.symm @[simp] lemma slope_same (f : k → PE) (a : k) : (slope f a a : E) = 0 := by rw [slope, sub_self, inv_zero, zero_smul] include E lemma slope_def_module (f : k → E) (a b : k) : slope f a b = (b - a)⁻¹ • (f b - f a) := rfl @[simp] lemma sub_smul_slope (f : k → PE) (a b : k) : (b - a) • slope f a b = f b -ᵥ f a := begin rcases eq_or_ne a b with rfl | hne, { rw [sub_self, zero_smul, vsub_self] }, { rw [slope, smul_inv_smul₀ (sub_ne_zero.2 hne.symm)] } end lemma sub_smul_slope_vadd (f : k → PE) (a b : k) : (b - a) • slope f a b +ᵥ f a = f b := by rw [sub_smul_slope, vsub_vadd] @[simp] lemma slope_vadd_const (f : k → E) (c : PE) : slope (λ x, f x +ᵥ c) = slope f := begin ext a b, simp only [slope, vadd_vsub_vadd_cancel_right, vsub_eq_sub] end @[simp] lemma slope_sub_smul (f : k → E) {a b : k} (h : a ≠ b): slope (λ x, (x - a) • f x) a b = f b := by simp [slope, inv_smul_smul₀ (sub_ne_zero.2 h.symm)] lemma eq_of_slope_eq_zero {f : k → PE} {a b : k} (h : slope f a b = (0:E)) : f a = f b := by rw [← sub_smul_slope_vadd f a b, h, smul_zero, zero_vadd] lemma slope_comm (f : k → PE) (a b : k) : slope f a b = slope f b a := by rw [slope, slope, ← neg_vsub_eq_vsub_rev, smul_neg, ← neg_smul, neg_inv, neg_sub] /-- `slope f a c` is a linear combination of `slope f a b` and `slope f b c`. This version explicitly provides coefficients. If `a ≠ c`, then the sum of the coefficients is `1`, so it is actually an affine combination, see `line_map_slope_slope_sub_div_sub`. -/ lemma sub_div_sub_smul_slope_add_sub_div_sub_smul_slope (f : k → PE) (a b c : k) : ((b - a) / (c - a)) • slope f a b + ((c - b) / (c - a)) • slope f b c = slope f a c := begin by_cases hab : a = b, { subst hab, rw [sub_self, zero_div, zero_smul, zero_add], by_cases hac : a = c, { simp [hac] }, { rw [div_self (sub_ne_zero.2 $ ne.symm hac), one_smul] } }, by_cases hbc : b = c, { subst hbc, simp [sub_ne_zero.2 (ne.symm hab)] }, rw [add_comm], simp_rw [slope, div_eq_inv_mul, mul_smul, ← smul_add, smul_inv_smul₀ (sub_ne_zero.2 $ ne.symm hab), smul_inv_smul₀ (sub_ne_zero.2 $ ne.symm hbc), vsub_add_vsub_cancel], end /-- `slope f a c` is an affine combination of `slope f a b` and `slope f b c`. This version uses `line_map` to express this property. -/ lemma line_map_slope_slope_sub_div_sub (f : k → PE) (a b c : k) (h : a ≠ c) : line_map (slope f a b) (slope f b c) ((c - b) / (c - a)) = slope f a c := by field_simp [sub_ne_zero.2 h.symm, ← sub_div_sub_smul_slope_add_sub_div_sub_smul_slope f a b c, line_map_apply_module] /-- `slope f a b` is an affine combination of `slope f a (line_map a b r)` and `slope f (line_map a b r) b`. We use `line_map` to express this property. -/ lemma line_map_slope_line_map_slope_line_map (f : k → PE) (a b r : k) : line_map (slope f (line_map a b r) b) (slope f a (line_map a b r)) r = slope f a b := begin obtain (rfl|hab) : a = b ∨ a ≠ b := classical.em _, { simp }, rw [slope_comm _ a, slope_comm _ a, slope_comm _ _ b], convert line_map_slope_slope_sub_div_sub f b (line_map a b r) a hab.symm using 2, rw [line_map_apply_ring, eq_div_iff (sub_ne_zero.2 hab), sub_mul, one_mul, mul_sub, ← sub_sub, sub_sub_cancel] end
d9c44209e7b00623b10a575944980b4594517ca4
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/char_p/basic.lean
616531f3aceefc393db17ed7ad80d4ddf44392e1
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,781
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Joey van Langen, Casper Putz -/ import algebra.iterate_hom import data.int.modeq import data.nat.choose import group_theory.order_of_element /-! # Characteristic of semirings -/ universes u v variables (R : Type u) /-- The generator of the kernel of the unique homomorphism ℕ → R for a semiring R -/ class char_p [add_monoid R] [has_one R] (p : ℕ) : Prop := (cast_eq_zero_iff [] : ∀ x:ℕ, (x:R) = 0 ↔ p ∣ x) theorem char_p.cast_eq_zero [add_monoid R] [has_one R] (p : ℕ) [char_p R p] : (p:R) = 0 := (char_p.cast_eq_zero_iff R p p).2 (dvd_refl p) @[simp] lemma char_p.cast_card_eq_zero [add_group R] [has_one R] [fintype R] : (fintype.card R : R) = 0 := by rw [← nsmul_one, card_nsmul_eq_zero] lemma char_p.int_cast_eq_zero_iff [add_group R] [has_one R] (p : ℕ) [char_p R p] (a : ℤ) : (a : R) = 0 ↔ (p:ℤ) ∣ a := begin rcases lt_trichotomy a 0 with h|rfl|h, { rw [← neg_eq_zero, ← int.cast_neg, ← dvd_neg], lift -a to ℕ using neg_nonneg.mpr (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] }, { simp only [int.cast_zero, eq_self_iff_true, dvd_zero] }, { lift a to ℕ using (le_of_lt h) with b, rw [int.cast_coe_nat, char_p.cast_eq_zero_iff R p, int.coe_nat_dvd] } end lemma char_p.int_coe_eq_int_coe_iff [add_group R] [has_one R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = (b : R) ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq_iff_dvd] theorem char_p.eq [add_monoid R] [has_one R] {p q : ℕ} (c1 : char_p R p) (c2 : char_p R q) : p = q := nat.dvd_antisymm ((char_p.cast_eq_zero_iff R p q).1 (char_p.cast_eq_zero _ _)) ((char_p.cast_eq_zero_iff R q p).1 (char_p.cast_eq_zero _ _)) instance char_p.of_char_zero [add_monoid R] [has_one R] [char_zero R] : char_p R 0 := ⟨λ x, by rw [zero_dvd_iff, ← nat.cast_zero, nat.cast_inj]⟩ theorem char_p.exists [non_assoc_semiring R] : ∃ p, char_p R p := by letI := classical.dec_eq R; exact classical.by_cases (assume H : ∀ p:ℕ, (p:R) = 0 → p = 0, ⟨0, ⟨λ x, by rw [zero_dvd_iff]; exact ⟨H x, by rintro rfl; refl⟩⟩⟩) (λ H, ⟨nat.find (not_forall.1 H), ⟨λ x, ⟨λ H1, nat.dvd_of_mod_eq_zero (by_contradiction $ λ H2, nat.find_min (not_forall.1 H) (nat.mod_lt x $ nat.pos_of_ne_zero $ not_of_not_imp $ nat.find_spec (not_forall.1 H)) (not_imp_of_and_not ⟨by rwa [← nat.mod_add_div x (nat.find (not_forall.1 H)), nat.cast_add, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul, add_zero] at H1, H2⟩)), λ H1, by rw [← nat.mul_div_cancel' H1, nat.cast_mul, of_not_not (not_not_of_not_imp $ nat.find_spec (not_forall.1 H)), zero_mul]⟩⟩⟩) theorem char_p.exists_unique [non_assoc_semiring R] : ∃! p, char_p R p := let ⟨c, H⟩ := char_p.exists R in ⟨c, H, λ y H2, char_p.eq R H2 H⟩ theorem char_p.congr {R : Type u} [add_monoid R] [has_one R] {p : ℕ} (q : ℕ) [hq : char_p R q] (h : q = p) : char_p R p := h ▸ hq /-- Noncomputable function that outputs the unique characteristic of a semiring. -/ noncomputable def ring_char [non_assoc_semiring R] : ℕ := classical.some (char_p.exists_unique R) namespace ring_char variables [non_assoc_semiring R] theorem spec : ∀ x:ℕ, (x:R) = 0 ↔ ring_char R ∣ x := by letI := (classical.some_spec (char_p.exists_unique R)).1; unfold ring_char; exact char_p.cast_eq_zero_iff R (ring_char R) theorem eq {p : ℕ} (C : char_p R p) : p = ring_char R := (classical.some_spec (char_p.exists_unique R)).2 p C instance char_p : char_p R (ring_char R) := ⟨spec R⟩ variables {R} theorem of_eq {p : ℕ} (h : ring_char R = p) : char_p R p := char_p.congr (ring_char R) h theorem eq_iff {p : ℕ} : ring_char R = p ↔ char_p R p := ⟨of_eq, eq.symm ∘ eq R⟩ theorem dvd {x : ℕ} (hx : (x : R) = 0) : ring_char R ∣ x := (spec R x).1 hx @[simp] lemma eq_zero [char_zero R] : ring_char R = 0 := (eq R (char_p.of_char_zero R)).symm end ring_char theorem add_pow_char_of_commute [semiring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x + y)^p = x^p + y^p := begin rw [commute.add_pow h, finset.sum_range_succ_comm, nat.sub_self, pow_zero, nat.choose_self], rw [nat.cast_one, mul_one, mul_one], congr' 1, convert finset.sum_eq_single 0 _ _, { simp only [mul_one, one_mul, nat.choose_zero_right, nat.sub_zero, nat.cast_one, pow_zero] }, { intros b h1 h2, suffices : (p.choose b : R) = 0, { rw this, simp }, rw char_p.cast_eq_zero_iff R p, refine nat.prime.dvd_choose_self (pos_iff_ne_zero.mpr h2) _ (fact.out _), rwa ← finset.mem_range }, { intro h1, contrapose! h1, rw finset.mem_range, exact nat.prime.pos (fact.out _) } end theorem add_pow_char_pow_of_commute [semiring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := begin induction n, { simp, }, rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih], apply add_pow_char_of_commute, apply commute.pow_pow h, end theorem sub_pow_char_of_commute [ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) (h : commute x y) : (x - y)^p = x^p - y^p := begin rw [eq_sub_iff_add_eq, ← add_pow_char_of_commute _ _ _ (commute.sub_left h rfl)], simp, repeat {apply_instance}, end theorem sub_pow_char_pow_of_commute [ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) (h : commute x y) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := begin induction n, { simp, }, rw [pow_succ', pow_mul, pow_mul, pow_mul, n_ih], apply sub_pow_char_of_commute, apply commute.pow_pow h, end theorem add_pow_char [comm_semiring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) : (x + y)^p = x^p + y^p := add_pow_char_of_commute _ _ _ (commute.all _ _) theorem add_pow_char_pow [comm_semiring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x + y) ^ (p ^ n) = x ^ (p ^ n) + y ^ (p ^ n) := add_pow_char_pow_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] (x y : R) : (x - y)^p = x^p - y^p := sub_pow_char_of_commute _ _ _ (commute.all _ _) theorem sub_pow_char_pow [comm_ring R] {p : ℕ} [fact p.prime] [char_p R p] {n : ℕ} (x y : R) : (x - y) ^ (p ^ n) = x ^ (p ^ n) - y ^ (p ^ n) := sub_pow_char_pow_of_commute _ _ _ (commute.all _ _) lemma eq_iff_modeq_int [ring R] (p : ℕ) [char_p R p] (a b : ℤ) : (a : R) = b ↔ a ≡ b [ZMOD p] := by rw [eq_comm, ←sub_eq_zero, ←int.cast_sub, char_p.int_cast_eq_zero_iff R p, int.modeq_iff_dvd] lemma char_p.neg_one_ne_one [ring R] (p : ℕ) [char_p R p] [fact (2 < p)] : (-1 : R) ≠ (1 : R) := begin suffices : (2 : R) ≠ 0, { symmetry, rw [ne.def, ← sub_eq_zero, sub_neg_eq_add], exact this }, assume h, rw [show (2 : R) = (2 : ℕ), by norm_cast] at h, have := (char_p.cast_eq_zero_iff R p 2).mp h, have := nat.le_of_dvd dec_trivial this, rw fact_iff at *, linarith, end lemma ring_hom.char_p_iff_char_p {K L : Type*} [field K] [field L] (f : K →+* L) (p : ℕ) : char_p K p ↔ char_p L p := begin split; { introI _c, constructor, intro n, rw [← @char_p.cast_eq_zero_iff _ _ _ p _c n, ← f.injective.eq_iff, f.map_nat_cast, f.map_zero] } end section frobenius section comm_semiring variables [comm_semiring R] {S : Type v} [comm_semiring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) /-- The frobenius map that sends x to x^p -/ def frobenius : R →+* R := { to_fun := λ x, x^p, map_one' := one_pow p, map_mul' := λ x y, mul_pow x y p, map_zero' := zero_pow (lt_trans zero_lt_one (fact.out (nat.prime p)).one_lt), map_add' := add_pow_char R } variable {R} theorem frobenius_def : frobenius R p x = x ^ p := rfl theorem iterate_frobenius (n : ℕ) : (frobenius R p)^[n] x = x ^ p ^ n := begin induction n, {simp}, rw [function.iterate_succ', pow_succ', pow_mul, function.comp_apply, frobenius_def, n_ih] end theorem frobenius_mul : frobenius R p (x * y) = frobenius R p x * frobenius R p y := (frobenius R p).map_mul x y theorem frobenius_one : frobenius R p 1 = 1 := one_pow _ theorem monoid_hom.map_frobenius : f (frobenius R p x) = frobenius S p (f x) := f.map_pow x p theorem ring_hom.map_frobenius : g (frobenius R p x) = frobenius S p (g x) := g.map_pow x p theorem monoid_hom.map_iterate_frobenius (n : ℕ) : f (frobenius R p^[n] x) = (frobenius S p^[n] (f x)) := function.semiconj.iterate_right (f.map_frobenius p) n x theorem ring_hom.map_iterate_frobenius (n : ℕ) : g (frobenius R p^[n] x) = (frobenius S p^[n] (g x)) := g.to_monoid_hom.map_iterate_frobenius p x n theorem monoid_hom.iterate_map_frobenius (f : R →* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ theorem ring_hom.iterate_map_frobenius (f : R →+* R) (p : ℕ) [fact p.prime] [char_p R p] (n : ℕ) : f^[n] (frobenius R p x) = frobenius R p (f^[n] x) := f.iterate_map_pow _ _ _ variable (R) theorem frobenius_zero : frobenius R p 0 = 0 := (frobenius R p).map_zero theorem frobenius_add : frobenius R p (x + y) = frobenius R p x + frobenius R p y := (frobenius R p).map_add x y theorem frobenius_nat_cast (n : ℕ) : frobenius R p n = n := (frobenius R p).map_nat_cast n end comm_semiring section comm_ring variables [comm_ring R] {S : Type v} [comm_ring S] (f : R →* S) (g : R →+* S) (p : ℕ) [fact p.prime] [char_p R p] [char_p S p] (x y : R) theorem frobenius_neg : frobenius R p (-x) = -frobenius R p x := (frobenius R p).map_neg x theorem frobenius_sub : frobenius R p (x - y) = frobenius R p x - frobenius R p y := (frobenius R p).map_sub x y end comm_ring end frobenius theorem frobenius_inj [comm_ring R] [no_zero_divisors R] (p : ℕ) [fact p.prime] [char_p R p] : function.injective (frobenius R p) := λ x h H, by { rw ← sub_eq_zero at H ⊢, rw ← frobenius_sub at H, exact pow_eq_zero H } namespace char_p section variables [ring R] lemma char_p_to_char_zero [char_p R 0] : char_zero R := char_zero_of_inj_zero $ λ n h0, eq_zero_of_zero_dvd ((cast_eq_zero_iff R 0 n).mp h0) lemma cast_eq_mod (p : ℕ) [char_p R p] (k : ℕ) : (k : R) = (k % p : ℕ) := calc (k : R) = ↑(k % p + p * (k / p)) : by rw [nat.mod_add_div] ... = ↑(k % p) : by simp[cast_eq_zero] theorem char_ne_zero_of_fintype (p : ℕ) [hc : char_p R p] [fintype R] : p ≠ 0 := assume h : p = 0, have char_zero R := @char_p_to_char_zero R _ (h ▸ hc), absurd (@nat.cast_injective R _ _ this) (not_injective_infinite_fintype coe) end section semiring open nat variables [non_assoc_semiring R] theorem char_ne_one [nontrivial R] (p : ℕ) [hc : char_p R p] : p ≠ 1 := assume hp : p = 1, have ( 1 : R) = 0, by simpa using (cast_eq_zero_iff R p 1).mpr (hp ▸ dvd_refl p), absurd this one_ne_zero section no_zero_divisors variable [no_zero_divisors R] theorem char_is_prime_of_two_le (p : ℕ) [hc : char_p R p] (hp : 2 ≤ p) : nat.prime p := suffices ∀d ∣ p, d = 1 ∨ d = p, from ⟨hp, this⟩, assume (d : ℕ) (hdvd : ∃ e, p = d * e), let ⟨e, hmul⟩ := hdvd in have (p : R) = 0, from (cast_eq_zero_iff R p p).mpr (dvd_refl p), have (d : R) * e = 0, from (@cast_mul R _ d e) ▸ (hmul ▸ this), or.elim (eq_zero_or_eq_zero_of_mul_eq_zero this) (assume hd : (d : R) = 0, have p ∣ d, from (cast_eq_zero_iff R p d).mp hd, show d = 1 ∨ d = p, from or.inr (dvd_antisymm ⟨e, hmul⟩ this)) (assume he : (e : R) = 0, have p ∣ e, from (cast_eq_zero_iff R p e).mp he, have e ∣ p, from dvd_of_mul_left_eq d (eq.symm hmul), have e = p, from dvd_antisymm ‹e ∣ p› ‹p ∣ e›, have h₀ : p > 0, from gt_of_ge_of_gt hp (nat.zero_lt_succ 1), have d * p = 1 * p, by rw ‹e = p› at hmul; rw [one_mul]; exact eq.symm hmul, show d = 1 ∨ d = p, from or.inl (eq_of_mul_eq_mul_right h₀ this)) section nontrivial variables [nontrivial R] theorem char_is_prime_or_zero (p : ℕ) [hc : char_p R p] : nat.prime p ∨ p = 0 := match p, hc with | 0, _ := or.inr rfl | 1, hc := absurd (eq.refl (1 : ℕ)) (@char_ne_one R _ _ (1 : ℕ) hc) | (m+2), hc := or.inl (@char_is_prime_of_two_le R _ _ (m+2) hc (nat.le_add_left 2 m)) end lemma char_is_prime_of_pos (p : ℕ) [h : fact (0 < p)] [char_p R p] : fact p.prime := ⟨(char_p.char_is_prime_or_zero R _).resolve_right (pos_iff_ne_zero.1 h.1)⟩ end nontrivial end no_zero_divisors end semiring section ring variables (R) [ring R] [no_zero_divisors R] [nontrivial R] [fintype R] theorem char_is_prime (p : ℕ) [char_p R p] : p.prime := or.resolve_right (char_is_prime_or_zero R p) (char_ne_zero_of_fintype R p) end ring section char_one variables {R} [non_assoc_semiring R] @[priority 100] -- see Note [lower instance priority] instance [char_p R 1] : subsingleton R := subsingleton.intro $ suffices ∀ (r : R), r = 0, from assume a b, show a = b, by rw [this a, this b], assume r, calc r = 1 * r : by rw one_mul ... = (1 : ℕ) * r : by rw nat.cast_one ... = 0 * r : by rw char_p.cast_eq_zero ... = 0 : by rw zero_mul lemma false_of_nontrivial_of_char_one [nontrivial R] [char_p R 1] : false := false_of_nontrivial_of_subsingleton R lemma ring_char_ne_one [nontrivial R] : ring_char R ≠ 1 := by { intros h, apply @zero_ne_one R, symmetry, rw [←nat.cast_one, ring_char.spec, h], } lemma nontrivial_of_char_ne_one {v : ℕ} (hv : v ≠ 1) [hr : char_p R v] : nontrivial R := ⟨⟨(1 : ℕ), 0, λ h, hv $ by rwa [char_p.cast_eq_zero_iff _ v, nat.dvd_one] at h; assumption ⟩⟩ end char_one end char_p section variables (R) [comm_ring R] [fintype R] (n : ℕ) lemma char_p_of_ne_zero (hn : fintype.card R = n) (hR : ∀ i < n, (i : R) = 0 → i = 0) : char_p R n := { cast_eq_zero_iff := begin have H : (n : R) = 0, by { rw [← hn, char_p.cast_card_eq_zero] }, intro k, split, { intro h, rw [← nat.mod_add_div k n, nat.cast_add, nat.cast_mul, H, zero_mul, add_zero] at h, rw nat.dvd_iff_mod_eq_zero, apply hR _ (nat.mod_lt _ _) h, rw [← hn, fintype.card_pos_iff], exact ⟨0⟩, }, { rintro ⟨k, rfl⟩, rw [nat.cast_mul, H, zero_mul] } end } lemma char_p_of_prime_pow_injective (p : ℕ) [hp : fact p.prime] (n : ℕ) (hn : fintype.card R = p ^ n) (hR : ∀ i ≤ n, (p ^ i : R) = 0 → i = n) : char_p R (p ^ n) := begin obtain ⟨c, hc⟩ := char_p.exists R, resetI, have hcpn : c ∣ p ^ n, { rw [← char_p.cast_eq_zero_iff R c, ← hn, char_p.cast_card_eq_zero], }, obtain ⟨i, hi, hc⟩ : ∃ i ≤ n, c = p ^ i, by rwa nat.dvd_prime_pow hp.1 at hcpn, obtain rfl : i = n, { apply hR i hi, rw [← nat.cast_pow, ← hc, char_p.cast_eq_zero] }, rwa ← hc end end section prod variables (S : Type v) [semiring R] [semiring S] (p q : ℕ) [char_p R p] /-- The characteristic of the product of rings is the least common multiple of the characteristics of the two rings. -/ instance [char_p S q] : char_p (R × S) (nat.lcm p q) := { cast_eq_zero_iff := by simp [prod.ext_iff, char_p.cast_eq_zero_iff R p, char_p.cast_eq_zero_iff S q, nat.lcm_dvd_iff] } /-- The characteristic of the product of two rings of the same characteristic is the same as the characteristic of the rings -/ instance prod.char_p [char_p S p] : char_p (R × S) p := by convert nat.lcm.char_p R S p p; simp end prod
6ba4871440d55fa2982f784b911b7ff80351386d
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/list/sorted.lean
112222f229238202cc732fae52381bcd4667fdd8
[ "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
5,767
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.list.comb data.list.perm namespace list variable {A : Type} variable (R : A → A → Prop) inductive locally_sorted : list A → Prop := | base0 : locally_sorted [] | base : ∀ a, locally_sorted [a] | step : ∀ {a b l}, R a b → locally_sorted (b::l) → locally_sorted (a::b::l) inductive hd_rel (a : A) : list A → Prop := | base : hd_rel a [] | step : ∀ {b} (l), R a b → hd_rel a (b::l) inductive sorted : list A → Prop := | base : sorted [] | step : ∀ {a : A} {l : list A}, hd_rel R a l → sorted l → sorted (a::l) variable {R} lemma hd_rel_inv : ∀ {a b l}, hd_rel R a (b::l) → R a b := begin intros a b l h, cases h, assumption end lemma sorted_inv : ∀ {a l}, sorted R (a::l) → hd_rel R a l ∧ sorted R l := begin intros a l h, cases h, split, repeat assumption end lemma sorted.rect_on {P : list A → Type} : ∀ {l}, sorted R l → P [] → (∀ a l, sorted R l → P l → hd_rel R a l → P (a::l)) → P l | [] s h₁ h₂ := h₁ | (a::l) s h₁ h₂ := have hd_rel R a l, from and.left (sorted_inv s), have sorted R l, from and.right (sorted_inv s), have P l, from sorted.rect_on this h₁ h₂, h₂ a l `sorted R l` `P l` `hd_rel R a l` lemma sorted_singleton (a : A) : sorted R [a] := sorted.step !hd_rel.base !sorted.base lemma sorted_of_locally_sorted : ∀ {l}, locally_sorted R l → sorted R l | [] h := !sorted.base | [a] h := !sorted_singleton | (a::b::l) (locally_sorted.step h₁ h₂) := have sorted R (b::l), from sorted_of_locally_sorted h₂, sorted.step (hd_rel.step _ h₁) this lemma locally_sorted_of_sorted : ∀ {l}, sorted R l → locally_sorted R l | [] h := !locally_sorted.base0 | [a] h := !locally_sorted.base | (a::b::l) (sorted.step (hd_rel.step _ h₁) h₂) := have locally_sorted R (b::l), from locally_sorted_of_sorted h₂, locally_sorted.step h₁ this lemma strongly_sorted_eq_sorted : @locally_sorted = @sorted := funext (λ A, funext (λ R, funext (λ l, propext (iff.intro sorted_of_locally_sorted locally_sorted_of_sorted)))) variable (R) inductive strongly_sorted : list A → Prop := | base : strongly_sorted [] | step : ∀ {a l}, all l (R a) → strongly_sorted l → strongly_sorted (a::l) variable {R} lemma sorted_of_strongly_sorted : ∀ {l}, strongly_sorted R l → sorted R l | [] h := !sorted.base | [a] h := !sorted_singleton | (a::b::l) (strongly_sorted.step h₁ h₂) := have hd_rel R a (b::l), from hd_rel.step _ (of_all_cons h₁), have sorted R (b::l), from sorted_of_strongly_sorted h₂, sorted.step `hd_rel R a (b::l)` `sorted R (b::l)` lemma sorted_extends (trans : transitive R) : ∀ {a l}, sorted R (a::l) → all l (R a) | a [] h := !all_nil | a (b::l) h := have hd_rel R a (b::l), from and.left (sorted_inv h), have R a b, from hd_rel_inv this, have all l (R b), from sorted_extends (and.right (sorted_inv h)), all_of_forall (take x, suppose x ∈ b::l, or.elim (eq_or_mem_of_mem_cons this) (suppose x = b, by+ subst x; assumption) (suppose x ∈ l, have R b x, from of_mem_of_all this `all l (R b)`, trans `R a b` `R b x`)) theorem strongly_sorted_of_sorted_of_transitive (trans : transitive R) : ∀ {l}, sorted R l → strongly_sorted R l | [] h := !strongly_sorted.base | (a::l) h := have sorted R l, from and.right (sorted_inv h), have strongly_sorted R l, from strongly_sorted_of_sorted_of_transitive this, have all l (R a), from sorted_extends trans h, strongly_sorted.step `all l (R a)` `strongly_sorted R l` open perm lemma eq_of_sorted_of_perm (tr : transitive R) (anti : anti_symmetric R) : ∀ {l₁ l₂ : list A}, l₁ ~ l₂ → sorted R l₁ → sorted R l₂ → l₁ = l₂ | [] [] h₁ h₂ h₃ := rfl | (a₁::l₁) [] h₁ h₂ h₃ := absurd (perm.symm h₁) !not_perm_nil_cons | [] (a₂::l₂) h₁ h₂ h₃ := absurd h₁ !not_perm_nil_cons | (a::l₁) l₂ h₁ h₂ h₃ := have aux : ∀ {t}, l₂ = a::t → a::l₁ = l₂, from take t, suppose l₂ = a::t, have l₁ ~ t, by rewrite [this at h₁]; apply perm_cons_inv h₁, have sorted R l₁, from and.right (sorted_inv h₂), have sorted R t, by rewrite [`l₂ = a::t` at h₃]; exact and.right (sorted_inv h₃), assert l₁ = t, from eq_of_sorted_of_perm `l₁ ~ t` `sorted R l₁` `sorted R t`, show a :: l₁ = l₂, by rewrite [`l₂ = a::t`, this], have a ∈ l₂, from mem_perm h₁ !mem_cons, obtain s t (e₁ : l₂ = s ++ (a::t)), from mem_split this, begin cases s with b s, { have l₂ = a::t, by exact e₁, exact aux this }, { have e₁ : l₂ = b::(s++(a::t)), by exact e₁, have b ∈ l₂, by rewrite e₁; apply mem_cons, have hall₂ : all (s++(a::t)) (R b), begin rewrite [e₁ at h₃], apply sorted_extends tr h₃ end, have a ∈ s++(a::t), from mem_append_right _ !mem_cons, have R b a, from of_mem_of_all this hall₂, have b ∈ a::l₁, from mem_perm (perm.symm h₁) `b ∈ l₂`, have hall₁ : all l₁ (R a), from sorted_extends tr h₂, apply or.elim (eq_or_mem_of_mem_cons `b ∈ a::l₁`), suppose b = a, by rewrite this at e₁; exact aux e₁, suppose b ∈ l₁, have R a b, from of_mem_of_all this hall₁, assert b = a, from anti `R b a` `R a b`, by rewrite this at e₁; exact aux e₁ } end end list
bfa81a0cad879b0846d13a68d8c492fd8c7d340b
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20170116_POPL/super/usage.lean
ad38ae15f614326a883e3934bb9a3408b942f6b5
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
1,773
lean
import tools.super -- The super tactic takes two lists of lemmas as arguments: -- super [normal lemmas] with [sos lemmas] -- The sos lemmas ("set of support") are only used in a restricted way: we do -- not perform inferences between sos lemmas, just with other clauses. (For -- performance reasons.) -- If the formula is valid in first-order logic (without extra lemmas), then -- just `super` is enough: example (a b c : Prop) : (a → b → c) ↔ (¬(¬c ∧ a) ∨ ¬b) := by super example (p : ℕ → Prop) (r : Prop) : (∃ x, p x → r) ↔ (∀ x, p x) → r := by super -- You can see what clauses super infers by enabling the trace.super option: set_option trace.super true example (p q : ℕ → Prop) : p 3 → (∀x, p x → q x^.succ) → q (nat.succ 3) := by super -- (Can we make this work with 4 instead of (nat.succ 3) as well?) -- External lemmas can be included by their full name after super: example {α a} {s t : list α} : a ∉ s → a ∈ s ++ t → a ∈ t := by super list.mem_append_iff -- (You can also try putting `with` here.) -- super makes it very easy to obtain slight variations of lemmas in the library: example {α a} {s t : list α} : a ∉ s → a ∉ t → a ∉ s ++ t := by super list.mem_append_iff example {α a} {s t : list α} : a ∈ s ∨ a ∈ t ∨ a ∉ t ++ s := by super list.mem_append_iff example {α a b} {t : list α} : a = b ∨ a ∈ t ∨ a ∉ t ++ [b] ++ t := by super list.mem_append_iff -- because super attempts to produce constructive proofs, it can also -- work in other types than Prop: universe variables u v example {α : Type u} [comm_semigroup α] {P : list α → Type.{v}} (h : ∀x y zs, P (x::y::zs) → P (y::x::zs)) : ∀x y z, P [x*y, z] → P [z, y*x] := by super with mul_comm
a3731214571b9bec62b0df92965896e81d2f0b21
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/noncomp_hott.hlean
0a59b906be96e170119d03ba4db9f9ca98edd86e
[ "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
35
hlean
noncomputable definition foo := 10
7a5cc9ac9daf38c9c3a3ba495c51dc02abc603c9
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/infoTree.lean
bf034bebdde739c159f635ed41ab157ef97aa8c4
[ "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
769
lean
import Lean open Lean.Elab elab "enableInfo!" : command => enableInfoTree elab "showInfoTrees!" : command => do let trees ← getInfoTrees trees.forM fun tree => do logInfo f!"{← tree.format}" structure A where val : Nat → Nat structure B where pair : A × A enableInfo! def f (x : Nat) : Nat × Nat := let y := ⟨x, x⟩ id y def h : (x y : Nat) → (b : Bool) → x + 0 = x := fun x y b => by simp def f2 : (x y : Nat) → (b : Bool) → Nat := fun x y b => let (z, w) := (x + y, x - y) let z1 := z + w z + z1 def f3 (s : Nat × Array (Array Nat)) : Array Nat := s.2[1].push s.1 def f4 (arg : B) : Nat := arg.pair.fst.val 0 def f5 (x : Nat) : B := { pair := ({ val := id }, { val := id }) } showInfoTrees!
6dec208bfe35c040676453ef0ee36d13edf09b0d
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/group.lean
4b3b08138f8981a2f294a1c2421eec87ae689249
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
1,735
lean
import algebra.group data.equiv.basic import group_theory.subgroup import group_theory.quotient_group import for_mathlib.equiv variables {G : Type*} [group G] open quotient_group -- this one lemma is not PR'ed yet. def group_equiv.quot_eq_of_eq {G1 : set G} [normal_subgroup G1] {G2 : set G} [normal_subgroup G2] (h : G1 = G2) : group_equiv (quotient G1) (quotient G2) := { to_fun := λ q, quotient.lift_on' q (quotient_group.mk : G → quotient G2) $ λ a b hab, quotient.sound' begin change a⁻¹ * b ∈ G1 at hab, rwa h at hab end, inv_fun := λ q, quotient.lift_on' q (quotient_group.mk : G → quotient G1) $ λ a b hab, quotient.sound' begin change a⁻¹ * b ∈ G2 at hab, rwa ←h at hab, end, left_inv := λ x, by induction x; refl, right_inv := λ x, by induction x; refl, hom := ⟨λ a b, begin let f : G → quotient G2 := quotient_group.mk, have h2 := quotient_group.is_group_hom_quotient_lift G1 f, have h3 := h2 (λ x hx, by rwa [←is_group_hom.mem_ker f, quotient_group.ker_mk G2, ←h]), have h4 := h3.map_mul, exact h4 a b, end⟩ } variables {M : Type*} [monoid M] lemma units.ext_inv (a b : units M) (h : a.inv = b.inv) : a = b := inv_inj $ units.ext h -- is this true for non-commutative monoids? -- KL: No, s := nat.pred, t := nat.succ, u := id /-- produces a unit s from a proof that s divides a unit -/ def units.unit_of_mul_left_eq_unit {M : Type*} [comm_monoid M] {s t : M} {u : units M} (h : s * t = u) : units M := { val := s, inv := t * (u⁻¹ : units M), val_inv := by {show s * (t * (u⁻¹ : units M)) = 1, rw [←mul_assoc, h], simp}, inv_val := by {show t * (u⁻¹ : units M) * s = 1, rw [mul_comm, ←mul_assoc, h], simp} }
3f7861bc0c065ab423212ed779c2c95ce11f0f2b
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Coe.lean
e2d31c3f628a7835ad80d87ba80d70e2f0896aa0
[ "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
1,292
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.WHNF import Lean.Meta.Transform namespace Lean.Meta /-- Return true iff `declName` is one of the auxiliary definitions/projections used to implement coercions. -/ def isCoeDecl (declName : Name) : Bool := declName == ``Coe.coe || declName == ``CoeTC.coe || declName == ``CoeHead.coe || declName == ``CoeTail.coe || declName == ``CoeHTCT.coe || declName == ``CoeDep.coe || declName == ``CoeT.coe || declName == ``CoeFun.coe || declName == ``CoeSort.coe || declName == ``Lean.Internal.liftCoeM || declName == ``Lean.Internal.coeM /-- Expand coercions occurring in `e` -/ partial def expandCoe (e : Expr) : MetaM Expr := withReducibleAndInstances do return (← transform e (pre := step)) where step (e : Expr) : MetaM TransformStep := do let f := e.getAppFn if !f.isConst then return TransformStep.visit e else let declName := f.constName! if isCoeDecl declName then match (← unfoldDefinition? e) with | none => return TransformStep.visit e | some e => step e.headBeta else return TransformStep.visit e end Lean.Meta
ea2f85eee9c9889afdd9ebede59e70129861ef35
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/tensor_product.lean
2ab4f3342304bc69c194dfd844ef57afbc01e335
[]
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
19,420
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.linear_algebra.tensor_product import Mathlib.algebra.algebra.basic import Mathlib.PostPort universes u v₁ v₂ v₃ v₄ namespace Mathlib /-! # The tensor product of R-algebras We construct the R-algebra structure on `A ⊗[R] B`, when `A` and `B` are both `R`-algebras, and provide the structure isomorphisms * `R ⊗[R] A ≃ₐ[R] A` * `A ⊗[R] R ≃ₐ[R] A` * `A ⊗[R] B ≃ₐ[R] B ⊗[R] A` The code for * `((A ⊗[R] B) ⊗[R] C) ≃ₐ[R] (A ⊗[R] (B ⊗[R] C))` is written and compiles, but takes longer than the `-T100000` time limit, so is currently commented out. -/ namespace algebra namespace tensor_product /-- (Implementation detail) The multiplication map on `A ⊗[R] B`, for a fixed pure tensor in the first argument, as an `R`-linear map. -/ def mul_aux {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a₁ : A) (b₁ : B) : linear_map R (tensor_product R A B) (tensor_product R A B) := tensor_product.lift (linear_map.mk (fun (a₂ : A) => linear_map.mk (fun (b₂ : B) => tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) sorry sorry) sorry sorry) @[simp] theorem mul_aux_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a₁ : A) (a₂ : A) (b₁ : B) (b₂ : B) : coe_fn (mul_aux a₁ b₁) (tensor_product.tmul R a₂ b₂) = tensor_product.tmul R (a₁ * a₂) (b₁ * b₂) := rfl /-- (Implementation detail) The multiplication map on `A ⊗[R] B`, as an `R`-bilinear map. -/ def mul {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] : linear_map R (tensor_product R A B) (linear_map R (tensor_product R A B) (tensor_product R A B)) := tensor_product.lift (linear_map.mk (fun (a₁ : A) => linear_map.mk (fun (b₁ : B) => mul_aux a₁ b₁) sorry sorry) sorry sorry) @[simp] theorem mul_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a₁ : A) (a₂ : A) (b₁ : B) (b₂ : B) : coe_fn (coe_fn mul (tensor_product.tmul R a₁ b₁)) (tensor_product.tmul R a₂ b₂) = tensor_product.tmul R (a₁ * a₂) (b₁ * b₂) := rfl theorem mul_assoc' {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (mul : linear_map R (tensor_product R A B) (linear_map R (tensor_product R A B) (tensor_product R A B))) (h : ∀ (a₁ a₂ a₃ : A) (b₁ b₂ b₃ : B), coe_fn (coe_fn mul (coe_fn (coe_fn mul (tensor_product.tmul R a₁ b₁)) (tensor_product.tmul R a₂ b₂))) (tensor_product.tmul R a₃ b₃) = coe_fn (coe_fn mul (tensor_product.tmul R a₁ b₁)) (coe_fn (coe_fn mul (tensor_product.tmul R a₂ b₂)) (tensor_product.tmul R a₃ b₃))) (x : tensor_product R A B) (y : tensor_product R A B) (z : tensor_product R A B) : coe_fn (coe_fn mul (coe_fn (coe_fn mul x) y)) z = coe_fn (coe_fn mul x) (coe_fn (coe_fn mul y) z) := sorry theorem mul_assoc {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (x : tensor_product R A B) (y : tensor_product R A B) (z : tensor_product R A B) : coe_fn (coe_fn mul (coe_fn (coe_fn mul x) y)) z = coe_fn (coe_fn mul x) (coe_fn (coe_fn mul y) z) := sorry theorem one_mul {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (x : tensor_product R A B) : coe_fn (coe_fn mul (tensor_product.tmul R 1 1)) x = x := sorry theorem mul_one {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (x : tensor_product R A B) : coe_fn (coe_fn mul x) (tensor_product.tmul R 1 1) = x := sorry protected instance tensor_product.semiring {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] : semiring (tensor_product R A B) := semiring.mk Add.add sorry 0 sorry sorry sorry (fun (a b : tensor_product R A B) => coe_fn (coe_fn mul a) b) mul_assoc (tensor_product.tmul R 1 1) one_mul mul_one sorry sorry sorry sorry theorem one_def {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] : 1 = tensor_product.tmul R 1 1 := rfl @[simp] theorem tmul_mul_tmul {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a₁ : A) (a₂ : A) (b₁ : B) (b₂ : B) : tensor_product.tmul R a₁ b₁ * tensor_product.tmul R a₂ b₂ = tensor_product.tmul R (a₁ * a₂) (b₁ * b₂) := rfl @[simp] theorem tmul_pow {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a : A) (b : B) (k : ℕ) : tensor_product.tmul R a b ^ k = tensor_product.tmul R (a ^ k) (b ^ k) := sorry /-- The algebra map `R →+* (A ⊗[R] B)` giving `A ⊗[R] B` the structure of an `R`-algebra. -/ def tensor_algebra_map {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] : R →+* tensor_product R A B := ring_hom.mk (fun (r : R) => tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) sorry sorry sorry sorry protected instance tensor_product.algebra {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] : algebra R (tensor_product R A B) := mk (ring_hom.mk (ring_hom.to_fun tensor_algebra_map) sorry sorry sorry sorry) sorry sorry @[simp] theorem algebra_map_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (r : R) : coe_fn (algebra_map R (tensor_product R A B)) r = tensor_product.tmul R (coe_fn (algebra_map R A) r) 1 := rfl theorem ext {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {g : alg_hom R (tensor_product R A B) C} {h : alg_hom R (tensor_product R A B) C} (H : ∀ (a : A) (b : B), coe_fn g (tensor_product.tmul R a b) = coe_fn h (tensor_product.tmul R a b)) : g = h := sorry /-- The algebra morphism `A →ₐ[R] A ⊗[R] B` sending `a` to `a ⊗ₜ 1`. -/ def include_left {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] : alg_hom R A (tensor_product R A B) := alg_hom.mk (fun (a : A) => tensor_product.tmul R a 1) sorry sorry sorry sorry sorry @[simp] theorem include_left_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (a : A) : coe_fn include_left a = tensor_product.tmul R a 1 := rfl /-- The algebra morphism `B →ₐ[R] A ⊗[R] B` sending `b` to `1 ⊗ₜ b`. -/ def include_right {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] : alg_hom R B (tensor_product R A B) := alg_hom.mk (fun (b : B) => tensor_product.tmul R 1 b) sorry sorry sorry sorry sorry @[simp] theorem include_right_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] (b : B) : coe_fn include_right b = tensor_product.tmul R 1 b := rfl protected instance tensor_product.ring {R : Type u} [comm_ring R] {A : Type v₁} [ring A] [algebra R A] {B : Type v₂} [ring B] [algebra R B] : ring (tensor_product R A B) := ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry protected instance tensor_product.comm_ring {R : Type u} [comm_ring R] {A : Type v₁} [comm_ring A] [algebra R A] {B : Type v₂} [comm_ring B] [algebra R B] : comm_ring (tensor_product R A B) := comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry sorry /-- Verify that typeclass search finds the ring structure on `A ⊗[ℤ] B` when `A` and `B` are merely rings, by treating both as `ℤ`-algebras. -/ /-- Verify that typeclass search finds the comm_ring structure on `A ⊗[ℤ] B` when `A` and `B` are merely comm_rings, by treating both as `ℤ`-algebras. -/ /-! We now build the structure maps for the symmetric monoidal category of `R`-algebras. -/ /-- Build an algebra morphism from a linear map out of a tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_hom_of_linear_map_tensor_product {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] (f : linear_map R (tensor_product R A B) C) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B), coe_fn f (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) = coe_fn f (tensor_product.tmul R a₁ b₁) * coe_fn f (tensor_product.tmul R a₂ b₂)) (w₂ : ∀ (r : R), coe_fn f (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) = coe_fn (algebra_map R C) r) : alg_hom R (tensor_product R A B) C := alg_hom.mk (linear_map.to_fun f) sorry sorry sorry sorry sorry @[simp] theorem alg_hom_of_linear_map_tensor_product_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] (f : linear_map R (tensor_product R A B) C) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B), coe_fn f (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) = coe_fn f (tensor_product.tmul R a₁ b₁) * coe_fn f (tensor_product.tmul R a₂ b₂)) (w₂ : ∀ (r : R), coe_fn f (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) = coe_fn (algebra_map R C) r) (x : tensor_product R A B) : coe_fn (alg_hom_of_linear_map_tensor_product f w₁ w₂) x = coe_fn f x := rfl /-- Build an algebra equivalence from a linear equivalence out of a tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_equiv_of_linear_equiv_tensor_product {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] (f : linear_equiv R (tensor_product R A B) C) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B), coe_fn f (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) = coe_fn f (tensor_product.tmul R a₁ b₁) * coe_fn f (tensor_product.tmul R a₂ b₂)) (w₂ : ∀ (r : R), coe_fn f (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) = coe_fn (algebra_map R C) r) : alg_equiv R (tensor_product R A B) C := alg_equiv.mk (alg_hom.to_fun (alg_hom_of_linear_map_tensor_product (↑f) w₁ w₂)) (linear_equiv.inv_fun f) sorry sorry sorry sorry sorry @[simp] theorem alg_equiv_of_linear_equiv_tensor_product_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] (f : linear_equiv R (tensor_product R A B) C) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B), coe_fn f (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) = coe_fn f (tensor_product.tmul R a₁ b₁) * coe_fn f (tensor_product.tmul R a₂ b₂)) (w₂ : ∀ (r : R), coe_fn f (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) = coe_fn (algebra_map R C) r) (x : tensor_product R A B) : coe_fn (alg_equiv_of_linear_equiv_tensor_product f w₁ w₂) x = coe_fn f x := rfl /-- Build an algebra equivalence from a linear equivalence out of a triple tensor product, and evidence of multiplicativity on pure tensors. -/ def alg_equiv_of_linear_equiv_triple_tensor_product {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D] [algebra R D] (f : linear_equiv R (tensor_product R (tensor_product R A B) C) D) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B) (c₁ c₂ : C), coe_fn f (tensor_product.tmul R (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) (c₁ * c₂)) = coe_fn f (tensor_product.tmul R (tensor_product.tmul R a₁ b₁) c₁) * coe_fn f (tensor_product.tmul R (tensor_product.tmul R a₂ b₂) c₂)) (w₂ : ∀ (r : R), coe_fn f (tensor_product.tmul R (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) 1) = coe_fn (algebra_map R D) r) : alg_equiv R (tensor_product R (tensor_product R A B) C) D := alg_equiv.mk (⇑f) (linear_equiv.inv_fun f) sorry sorry sorry sorry sorry @[simp] theorem alg_equiv_of_linear_equiv_triple_tensor_product_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D] [algebra R D] (f : linear_equiv R (tensor_product R (tensor_product R A B) C) D) (w₁ : ∀ (a₁ a₂ : A) (b₁ b₂ : B) (c₁ c₂ : C), coe_fn f (tensor_product.tmul R (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) (c₁ * c₂)) = coe_fn f (tensor_product.tmul R (tensor_product.tmul R a₁ b₁) c₁) * coe_fn f (tensor_product.tmul R (tensor_product.tmul R a₂ b₂) c₂)) (w₂ : ∀ (r : R), coe_fn f (tensor_product.tmul R (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) 1) = coe_fn (algebra_map R D) r) (x : tensor_product R (tensor_product R A B) C) : coe_fn (alg_equiv_of_linear_equiv_triple_tensor_product f w₁ w₂) x = coe_fn f x := rfl /-- The base ring is a left identity for the tensor product of algebra, up to algebra isomorphism. -/ protected def lid (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A] : alg_equiv R (tensor_product R R A) A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.lid R A) sorry sorry @[simp] theorem lid_tmul (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A] (r : R) (a : A) : coe_fn (tensor_product.lid R A) (tensor_product.tmul R r a) = r • a := sorry /-- The base ring is a right identity for the tensor product of algebra, up to algebra isomorphism. -/ protected def rid (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A] : alg_equiv R (tensor_product R A R) A := alg_equiv_of_linear_equiv_tensor_product (tensor_product.rid R A) sorry sorry @[simp] theorem rid_tmul (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A] (r : R) (a : A) : coe_fn (tensor_product.rid R A) (tensor_product.tmul R a r) = r • a := sorry /-- The tensor product of R-algebras is commutative, up to algebra isomorphism. -/ protected def comm (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A] (B : Type v₂) [semiring B] [algebra R B] : alg_equiv R (tensor_product R A B) (tensor_product R B A) := alg_equiv_of_linear_equiv_tensor_product (tensor_product.comm R A B) sorry sorry @[simp] theorem comm_tmul (R : Type u) [comm_semiring R] (A : Type v₁) [semiring A] [algebra R A] (B : Type v₂) [semiring B] [algebra R B] (a : A) (b : B) : coe_fn (tensor_product.comm R A B) (tensor_product.tmul R a b) = tensor_product.tmul R b a := sorry theorem assoc_aux_1 {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] (a₁ : A) (a₂ : A) (b₁ : B) (b₂ : B) (c₁ : C) (c₂ : C) : coe_fn (tensor_product.assoc R A B C) (tensor_product.tmul R (tensor_product.tmul R (a₁ * a₂) (b₁ * b₂)) (c₁ * c₂)) = coe_fn (tensor_product.assoc R A B C) (tensor_product.tmul R (tensor_product.tmul R a₁ b₁) c₁) * coe_fn (tensor_product.assoc R A B C) (tensor_product.tmul R (tensor_product.tmul R a₂ b₂) c₂) := rfl theorem assoc_aux_2 {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] (r : R) : coe_fn (tensor_product.assoc R A B C) (tensor_product.tmul R (tensor_product.tmul R (coe_fn (algebra_map R A) r) 1) 1) = coe_fn (algebra_map R (tensor_product R A (tensor_product R B C))) r := rfl -- variables (R A B C) -- -- local attribute [elab_simple] alg_equiv_of_linear_equiv_triple_tensor_product -- /-- The associator for tensor product of R-algebras, as an algebra isomorphism. -/ -- -- FIXME This is _really_ slow to compile. :-( -- protected def assoc : ((A ⊗[R] B) ⊗[R] C) ≃ₐ[R] (A ⊗[R] (B ⊗[R] C)) := -- alg_equiv_of_linear_equiv_triple_tensor_product -- (tensor_product.assoc R A B C) -- assoc_aux_1 assoc_aux_2 -- variables {R A B C} -- @[simp] theorem assoc_tmul (a : A) (b : B) (c : C) : -- ((tensor_product.assoc R A B C) : (A ⊗[R] B) ⊗[R] C → A ⊗[R] (B ⊗[R] C)) ((a ⊗ₜ b) ⊗ₜ c) = a ⊗ₜ (b ⊗ₜ c) := -- rfl /-- The tensor product of a pair of algebra morphisms. -/ def map {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D] [algebra R D] (f : alg_hom R A B) (g : alg_hom R C D) : alg_hom R (tensor_product R A C) (tensor_product R B D) := alg_hom_of_linear_map_tensor_product (tensor_product.map (alg_hom.to_linear_map f) (alg_hom.to_linear_map g)) sorry sorry @[simp] theorem map_tmul {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D] [algebra R D] (f : alg_hom R A B) (g : alg_hom R C D) (a : A) (c : C) : coe_fn (map f g) (tensor_product.tmul R a c) = tensor_product.tmul R (coe_fn f a) (coe_fn g c) := rfl /-- Construct an isomorphism between tensor products of R-algebras from isomorphisms between the tensor factors. -/ def congr {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D] [algebra R D] (f : alg_equiv R A B) (g : alg_equiv R C D) : alg_equiv R (tensor_product R A C) (tensor_product R B D) := alg_equiv.of_alg_hom (map ↑f ↑g) (map ↑(alg_equiv.symm f) ↑(alg_equiv.symm g)) sorry sorry @[simp] theorem congr_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D] [algebra R D] (f : alg_equiv R A B) (g : alg_equiv R C D) (x : tensor_product R A C) : coe_fn (congr f g) x = coe_fn (map ↑f ↑g) x := rfl @[simp] theorem congr_symm_apply {R : Type u} [comm_semiring R] {A : Type v₁} [semiring A] [algebra R A] {B : Type v₂} [semiring B] [algebra R B] {C : Type v₃} [semiring C] [algebra R C] {D : Type v₄} [semiring D] [algebra R D] (f : alg_equiv R A B) (g : alg_equiv R C D) (x : tensor_product R B D) : coe_fn (alg_equiv.symm (congr f g)) x = coe_fn (map ↑(alg_equiv.symm f) ↑(alg_equiv.symm g)) x := rfl
27159ceb6a4e8e65577ed42aebc7627c78dbb63d
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/list/min_max.lean
aa32f329369938b46e0035302060ac8cf11f3bad
[ "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,681
lean
/- Copyright (c) 2019 Minchao Wu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Minchao Wu, Chris Hughes -/ import data.list.basic /-! # Minimum and maximum of lists ## Main definitions The main definitions are `argmax`, `argmin`, `minimum` and `maximum` for lists. `argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmax f []` = none` `minimum l` returns an `with_top α`, the smallest element of `l` for nonempty lists, and `⊤` for `[]` -/ namespace list variables {α : Type*} {β : Type*} [linear_order β] /-- Auxiliary definition to define `argmax` -/ def argmax₂ (f : α → β) (a : option α) (b : α) : option α := option.cases_on a (some b) (λ c, if f b ≤ f c then some c else some b) /-- `argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmax f []` = none` -/ def argmax (f : α → β) (l : list α) : option α := l.foldl (argmax₂ f) none /-- `argmin f l` returns `some a`, where `a` of `l` that minimises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmin f []` = none` -/ def argmin (f : α → β) (l : list α) := @argmax _ (order_dual β) _ f l @[simp] lemma argmax_two_self (f : α → β) (a : α) : argmax₂ f (some a) a = a := if_pos (le_refl _) @[simp] lemma argmax_nil (f : α → β) : argmax f [] = none := rfl @[simp] lemma argmin_nil (f : α → β) : argmin f [] = none := rfl @[simp] lemma argmax_singleton {f : α → β} {a : α} : argmax f [a] = some a := rfl @[simp] lemma argmin_singleton {f : α → β} {a : α} : argmin f [a] = a := rfl @[simp] lemma foldl_argmax₂_eq_none {f : α → β} {l : list α} {o : option α} : l.foldl (argmax₂ f) o = none ↔ l = [] ∧ o = none := list.reverse_rec_on l (by simp) $ (assume tl hd, by simp [argmax₂]; cases foldl (argmax₂ f) o tl; simp; try {split_ifs}; simp) private theorem le_of_foldl_argmax₂ {f : α → β} {l} : Π {a m : α} {o : option α}, a ∈ l → m ∈ foldl (argmax₂ f) o l → f a ≤ f m := list.reverse_rec_on l (λ _ _ _ h, absurd h $ not_mem_nil _) begin intros tl _ ih _ _ _ h ho, rw [foldl_append, foldl_cons, foldl_nil, argmax₂] at ho, cases hf : foldl (argmax₂ f) o tl, { rw [hf] at ho, rw [foldl_argmax₂_eq_none] at hf, simp [hf.1, hf.2, *] at * }, rw [hf, option.mem_def] at ho, dsimp only at ho, cases mem_append.1 h with h h, { refine le_trans (ih h hf) _, have := @le_of_lt _ _ (f val) (f m), split_ifs at ho; simp * at * }, { split_ifs at ho; simp * at * } end private theorem foldl_argmax₂_mem (f : α → β) (l) : Π (a m : α), m ∈ foldl (argmax₂ f) (some a) l → m ∈ a :: l := list.reverse_rec_on l (by simp [eq_comm]) begin assume tl hd ih a m, simp only [foldl_append, foldl_cons, foldl_nil, argmax₂], cases hf : foldl (argmax₂ f) (some a) tl, { simp {contextual := tt} }, { dsimp only, split_ifs, { finish [ih _ _ hf] }, { simp {contextual := tt} } } end theorem argmax_mem {f : α → β} : Π {l : list α} {m : α}, m ∈ argmax f l → m ∈ l | [] m := by simp | (hd::tl) m := by simpa [argmax, argmax₂] using foldl_argmax₂_mem f tl hd m theorem argmin_mem {f : α → β} : Π {l : list α} {m : α}, m ∈ argmin f l → m ∈ l := @argmax_mem _ (order_dual β) _ _ @[simp] theorem argmax_eq_none {f : α → β} {l : list α} : l.argmax f = none ↔ l = [] := by simp [argmax] @[simp] theorem argmin_eq_none {f : α → β} {l : list α} : l.argmin f = none ↔ l = [] := @argmax_eq_none _ (order_dual β) _ _ _ theorem le_argmax_of_mem {f : α → β} {a m : α} {l : list α} : a ∈ l → m ∈ argmax f l → f a ≤ f m := le_of_foldl_argmax₂ theorem argmin_le_of_mem {f : α → β} {a m : α} {l : list α} : a ∈ l → m ∈ argmin f l → f m ≤ f a:= @le_argmax_of_mem _ (order_dual β) _ _ _ _ _ theorem argmax_concat (f : α → β) (a : α) (l : list α) : argmax f (l ++ [a]) = option.cases_on (argmax f l) (some a) (λ c, if f a ≤ f c then some c else some a) := by rw [argmax, argmax]; simp [argmax₂] theorem argmin_concat (f : α → β) (a : α) (l : list α) : argmin f (l ++ [a]) = option.cases_on (argmin f l) (some a) (λ c, if f c ≤ f a then some c else some a) := @argmax_concat _ (order_dual β) _ _ _ _ theorem argmax_cons (f : α → β) (a : α) (l : list α) : argmax f (a :: l) = option.cases_on (argmax f l) (some a) (λ c, if f c ≤ f a then some a else some c) := list.reverse_rec_on l rfl $ assume hd tl ih, begin rw [← cons_append, argmax_concat, ih, argmax_concat], cases h : argmax f hd with m, { simp [h] }, { simp [h], dsimp, by_cases ham : f m ≤ f a, { rw if_pos ham, dsimp, by_cases htlm : f tl ≤ f m, { rw if_pos htlm, dsimp, rw [if_pos (le_trans htlm ham), if_pos ham] }, { rw if_neg htlm } }, { rw if_neg ham, dsimp, by_cases htlm : f tl ≤ f m, { rw if_pos htlm, dsimp, rw if_neg ham }, { rw if_neg htlm, dsimp, rw [if_neg (not_le_of_gt (lt_trans (lt_of_not_ge ham) (lt_of_not_ge htlm)))] } } } end theorem argmin_cons (f : α → β) (a : α) (l : list α) : argmin f (a :: l) = option.cases_on (argmin f l) (some a) (λ c, if f a ≤ f c then some a else some c) := @argmax_cons _ (order_dual β) _ _ _ _ theorem index_of_argmax [decidable_eq α] {f : α → β} : Π {l : list α} {m : α}, m ∈ argmax f l → ∀ {a}, a ∈ l → f m ≤ f a → l.index_of m ≤ l.index_of a | [] m _ _ _ _ := by simp | (hd::tl) m hm a ha ham := begin simp only [index_of_cons, argmax_cons, option.mem_def] at ⊢ hm, cases h : argmax f tl, { rw h at hm, simp * at * }, { rw h at hm, dsimp only at hm, cases ha with hahd hatl, { clear index_of_argmax, subst hahd, split_ifs at hm, { subst hm }, { subst hm, contradiction } }, { have := index_of_argmax h hatl, clear index_of_argmax, split_ifs at *; refl <|> exact nat.zero_le _ <|> simp [*, nat.succ_le_succ_iff, -not_le] at * } } end theorem index_of_argmin [decidable_eq α] {f : α → β} : Π {l : list α} {m : α}, m ∈ argmin f l → ∀ {a}, a ∈ l → f a ≤ f m → l.index_of m ≤ l.index_of a := @index_of_argmax _ (order_dual β) _ _ _ theorem mem_argmax_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : m ∈ argmax f l ↔ m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧ (∀ a ∈ l, f m ≤ f a → l.index_of m ≤ l.index_of a) := ⟨λ hm, ⟨argmax_mem hm, λ a ha, le_argmax_of_mem ha hm, λ _, index_of_argmax hm⟩, begin rintros ⟨hml, ham, hma⟩, cases harg : argmax f l with n, { simp * at * }, { have := le_antisymm (hma n (argmax_mem harg) (le_argmax_of_mem hml harg)) (index_of_argmax harg hml (ham _ (argmax_mem harg))), rw [(index_of_inj hml (argmax_mem harg)).1 this, option.mem_def] } end⟩ theorem argmax_eq_some_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : argmax f l = some m ↔ m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧ (∀ a ∈ l, f m ≤ f a → l.index_of m ≤ l.index_of a) := mem_argmax_iff theorem mem_argmin_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : m ∈ argmin f l ↔ m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧ (∀ a ∈ l, f a ≤ f m → l.index_of m ≤ l.index_of a) := @mem_argmax_iff _ (order_dual β) _ _ _ _ _ theorem argmin_eq_some_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : argmin f l = some m ↔ m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧ (∀ a ∈ l, f a ≤ f m → l.index_of m ≤ l.index_of a) := mem_argmin_iff variable [linear_order α] /-- `maximum l` returns an `with_bot α`, the largest element of `l` for nonempty lists, and `⊥` for `[]` -/ def maximum (l : list α) : with_bot α := argmax id l /-- `minimum l` returns an `with_top α`, the smallest element of `l` for nonempty lists, and `⊤` for `[]` -/ def minimum (l : list α) : with_top α := argmin id l @[simp] lemma maximum_nil : maximum ([] : list α) = ⊥ := rfl @[simp] lemma minimum_nil : minimum ([] : list α) = ⊤ := rfl @[simp] lemma maximum_singleton (a : α) : maximum [a] = a := rfl @[simp] lemma minimum_singleton (a : α) : minimum [a] = a := rfl theorem maximum_mem {l : list α} {m : α} : (maximum l : with_top α) = m → m ∈ l := argmax_mem theorem minimum_mem {l : list α} {m : α} : (minimum l : with_bot α) = m → m ∈ l := argmin_mem @[simp] theorem maximum_eq_none {l : list α} : l.maximum = none ↔ l = [] := argmax_eq_none @[simp] theorem minimum_eq_none {l : list α} : l.minimum = none ↔ l = [] := argmin_eq_none theorem le_maximum_of_mem {a m : α} {l : list α} : a ∈ l → (maximum l : with_bot α) = m → a ≤ m := le_argmax_of_mem theorem minimum_le_of_mem {a m : α} {l : list α} : a ∈ l → (minimum l : with_top α) = m → m ≤ a := argmin_le_of_mem theorem le_maximum_of_mem' {a : α} {l : list α} (ha : a ∈ l) : (a : with_bot α) ≤ maximum l := option.cases_on (maximum l) (λ _ h, absurd ha ((h rfl).symm ▸ not_mem_nil _)) (λ m hm _, with_bot.coe_le_coe.2 $ hm _ rfl) (λ m, @le_maximum_of_mem _ _ _ m _ ha) (@maximum_eq_none _ _ l).1 theorem le_minimum_of_mem' {a : α} {l : list α} (ha : a ∈ l) : minimum l ≤ (a : with_top α) := @le_maximum_of_mem' (order_dual α) _ _ _ ha theorem maximum_concat (a : α) (l : list α) : maximum (l ++ [a]) = max (maximum l) a := begin rw max_comm, simp only [maximum, argmax_concat, id], cases h : argmax id l, { rw [max_eq_left], refl, exact bot_le }, change (coe : α → with_bot α) with some, rw [max_comm], simp [max] end theorem minimum_concat (a : α) (l : list α) : minimum (l ++ [a]) = min (minimum l) a := @maximum_concat (order_dual α) _ _ _ theorem maximum_cons (a : α) (l : list α) : maximum (a :: l) = max a (maximum l) := list.reverse_rec_on l (by simp [@max_eq_left (with_bot α) _ _ _ bot_le]) (λ tl hd ih, by rw [← cons_append, maximum_concat, ih, maximum_concat, max_assoc]) theorem minimum_cons (a : α) (l : list α) : minimum (a :: l) = min a (minimum l) := @maximum_cons (order_dual α) _ _ _ theorem maximum_eq_coe_iff {m : α} {l : list α} : maximum l = m ↔ m ∈ l ∧ (∀ a ∈ l, a ≤ m) := begin unfold_coes, simp only [maximum, argmax_eq_some_iff, id], split, { simp only [true_and, forall_true_iff] {contextual := tt} }, { simp only [true_and, forall_true_iff] {contextual := tt}, intros h a hal hma, rw [le_antisymm hma (h.2 a hal)] } end theorem minimum_eq_coe_iff {m : α} {l : list α} : minimum l = m ↔ m ∈ l ∧ (∀ a ∈ l, m ≤ a) := @maximum_eq_coe_iff (order_dual α) _ _ _ section fold variables {M : Type*} [canonically_linear_ordered_add_monoid M] /-! Note: since there is no typeclass for both `linear_order` and `has_top`, nor a typeclass dual to `canonically_linear_ordered_add_monoid α` we cannot express these lemmas generally for `minimum`; instead we are limited to doing so on `order_dual α`. -/ lemma maximum_eq_coe_foldr_max_of_ne_nil (l : list M) (h : l ≠ []) : l.maximum = (l.foldr max ⊥ : M) := begin induction l with hd tl IH, { contradiction }, { rw [maximum_cons, foldr, with_bot.coe_max], by_cases h : tl = [], { simp [h, -with_top.coe_zero] }, { simp [IH h] } } end lemma minimum_eq_coe_foldr_min_of_ne_nil (l : list (order_dual M)) (h : l ≠ []) : l.minimum = (l.foldr min ⊤ : order_dual M) := maximum_eq_coe_foldr_max_of_ne_nil l h lemma maximum_nat_eq_coe_foldr_max_of_ne_nil (l : list ℕ) (h : l ≠ []) : l.maximum = (l.foldr max 0 : ℕ) := maximum_eq_coe_foldr_max_of_ne_nil l h lemma max_le_of_forall_le (l : list M) (n : M) (h : ∀ (x ∈ l), x ≤ n) : l.foldr max ⊥ ≤ n := begin induction l with y l IH, { simp }, { specialize IH (λ x hx, h x (mem_cons_of_mem _ hx)), have hy : y ≤ n := h y (mem_cons_self _ _), simpa [hy] using IH } end lemma le_min_of_le_forall (l : list (order_dual M)) (n : (order_dual M)) (h : ∀ (x ∈ l), n ≤ x) : n ≤ l.foldr min ⊤ := max_le_of_forall_le l n h lemma max_nat_le_of_forall_le (l : list ℕ) (n : ℕ) (h : ∀ (x ∈ l), x ≤ n) : l.foldr max 0 ≤ n := max_le_of_forall_le l n h end fold end list
e244d99c7459495606eeca7f28c942780b439b4a
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch6/ex0402.lean
e619da20b25e79a483ae28a44a141627b5551284
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
222
lean
variable {α : Type*} def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix @[simp] theorem list.is_prefix_refl (l : list α) : l <+: l := ⟨[], by simp⟩
72299bb1a77f4a6ad84f26dea801eb21becdc5a1
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/mvar3.lean
75acd1888f38d784969103f8148f009a6e60bf6b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
3,068
lean
import Lean.MetavarContext open Lean def mkLambdaTest (mctx : MetavarContext) (ngen : NameGenerator) (lctx : LocalContext) (xs : Array Expr) (e : Expr) : Except MetavarContext.MkBinding.Exception (MetavarContext × NameGenerator × Expr) := match MetavarContext.mkLambda xs e false true lctx { mctx := mctx, ngen := ngen } with | EStateM.Result.ok e s => Except.ok (s.mctx, s.ngen, e) | EStateM.Result.error e s => Except.error e def check (b : Bool) : IO Unit := unless b do throw $ IO.userError "error" def f := mkConst `f def g := mkConst `g def a := mkConst `a def b := mkConst `b def c := mkConst `c def b0 := mkBVar 0 def b1 := mkBVar 1 def b2 := mkBVar 2 def u := mkLevelParam `u def typeE := mkSort levelOne def natE := mkConst `Nat def boolE := mkConst `Bool def vecE := mkConst `Vec [levelZero] instance : Coe Name FVarId where coe n := { name := n } instance : Coe Name MVarId where coe n := { name := n } def α := mkFVar `α def x := mkFVar `x def y := mkFVar `y def z := mkFVar `z def w := mkFVar `w def m1 := mkMVar `m1 def m2 := mkMVar `m2 def m3 := mkMVar `m3 def bi := BinderInfo.default def arrow (d b : Expr) := mkForall `_ bi d b def lctx1 : LocalContext := {} def lctx2 := lctx1.mkLocalDecl `α `α typeE def lctx3 := lctx2.mkLocalDecl `x `x m1 def lctx4 := lctx3.mkLocalDecl `y `y (arrow natE m2) def mctx1 : MetavarContext := {} def mctx2 := mctx1.addExprMVarDecl `m1 `m1 lctx2 #[] typeE def mctx3 := mctx2.addExprMVarDecl `m2 `m2 lctx3 #[] natE def mctx4 := mctx3.addExprMVarDecl `m3 `m3 lctx3 #[] natE def mctx4' := mctx3.addExprMVarDecl `m3 `m3 lctx3 #[] natE MetavarKind.syntheticOpaque def R1 := match mkLambdaTest mctx4 {namePrefix := `n} lctx4 #[α, x, y] $ mkAppN f #[m3, x] with | Except.ok s => s | Except.error e => panic! (toString e) def e1 := R1.2.2 def mctx5 := R1.1 def sortNames (xs : List Name) : List Name := (xs.toArray.qsort Name.lt).toList instance : ToString MVarId where toString m := toString m.name def sortNamePairs {α} [Inhabited α] (xs : List (MVarId × α)) : List (MVarId × α) := (xs.toArray.qsort (fun a b => Name.lt a.1.name b.1.name)).toList #eval toString $ sortNames $ mctx5.decls.toList.map (·.1.name) #eval toString $ sortNamePairs $ mctx5.eAssignment.toList #eval e1 #eval check (!e1.hasFVar) def R2 := match mkLambdaTest mctx4' {namePrefix := `n} lctx4 #[α, x, y] $ mkAppN f #[m3, y] with | Except.ok s => s | Except.error e => panic! (toString e) def e2 := R2.2.2 def mctx6 := R2.1 #eval toString $ sortNames $ mctx6.decls.toList.map (·.1.name) #eval toString $ sortNamePairs $ mctx6.eAssignment.toList -- ?n.2 was delayed assigned because ?m.3 is synthetic #eval toString $ sortNames $ mctx6.dAssignment.toList.map (·.1.name) #eval e2 #print "assigning ?m1 and ?n.1" def R3 := let mctx := mctx6.assignExpr `m3 x; let mctx := mctx.assignExpr (Name.mkNum `n 1) (mkLambda `_ bi typeE natE); -- ?n.2 is instantiated because we have the delayed assignment `?n.2 α x := ?m1` (mctx.instantiateMVars e2) def e3 := R3.1 def mctx7 := R3.2 #eval e3
7f2e50990b63c6605975b5a44c11b93382373fd0
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/function/conditional_expectation.lean
5157a106cbe4d300bcf1baa59da5168d8d62157e
[ "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
86,989
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 -/ import analysis.inner_product_space.projection import measure_theory.function.l2_space import measure_theory.decomposition.radon_nikodym /-! # Conditional expectation We build the conditional expectation of a function `f` with value in a Banach space with respect to a measure `μ` (defined on a measurable space structure `m0`) and a measurable space structure `m` with `hm : m ≤ m0` (a sub-sigma-algebra). This is an `m`-measurable function `μ[f|hm]` which is integrable and verifies `∫ x in s, μ[f|hm] x ∂μ = ∫ x in s, f x ∂μ` for any `m`-measurable sets `s`. It is unique as an element of `L¹`. The construction is done in four steps: * Define the conditional expectation of an `L²` function, as an element of `L²`. This is the orthogonal projection on the subspace of almost everywhere `m`-measurable functions. * Show that the conditional expectation of the indicator of a measurable set with finite measure is integrable and define a map `set α → (E →L[ℝ] (α →₁[μ] E))` which to a set associates a linear map. That linear map sends `x ∈ E` to the conditional expectation of the indicator of the set with value `x`. * Extend that map to `condexp_L1_clm : (α →₁[μ] E) →L[ℝ] (α →₁[μ] E)`. This is done using the same construction as the Bochner integral (see the file `measure_theory/integral/set_to_L1`). * Define the conditional expectation of a function `f : α → E`, which is an integrable function `α → E` equal to 0 if `f` is not integrable, and equal to an `m`-measurable representative of `condexp_L1_clm` applied to `[f]`, the equivalence class of `f` in `L¹`. ## Main results The conditional expectation and its properties * `condexp (hm : m ≤ m0) (μ : measure α) (f : α → E)`: conditional expectation of `f` with respect to `m`. * `integrable_condexp` : `condexp` is integrable. * `measurable_condexp` : `condexp` is `m`-measurable. * `set_integral_condexp (hf : integrable f μ) (hs : measurable_set[m] s)` : the conditional expectation verifies `∫ x in s, condexp hm μ f x ∂μ = ∫ x in s, f x ∂μ` for any `m`-measurable set `s`. While `condexp` is function-valued, we also define `condexp_L1` with value in `L1` and a continuous linear map `condexp_L1_clm` from `L1` to `L1`. `condexp` should be used in most cases. Uniqueness of the conditional expectation * `Lp.ae_eq_of_forall_set_integral_eq'`: two `Lp` functions verifying the equality of integrals defining the conditional expectation are equal everywhere. * `ae_eq_of_forall_set_integral_eq_of_sigma_finite'`: two functions verifying the equality of integrals defining the conditional expectation are equal everywhere. Requires `[sigma_finite (μ.trim hm)]`. * `ae_eq_condexp_of_forall_set_integral_eq`: an a.e. `m`-measurable function which verifies the equality of integrals is a.e. equal to `condexp`. ## Notations For a measure `μ` defined on a measurable space structure `m0`, another measurable space structure `m` with `hm : m ≤ m0` (a sub-sigma-algebra) and a function `f`, we define the notation * `μ[f|hm] = condexp hm μ f`. ## Implementation notes Most of the results in this file are valid for a second countable, borel, real normed space `F`. However, some lemmas also use `𝕜 : is_R_or_C`: * `condexp_L2` is defined only for an `inner_product_space` for now, and we use `𝕜` for its field. * results about scalar multiplication are stated not only for `ℝ` but also for `𝕜` if we happen to have `normed_space 𝕜 F` and `is_scalar_tower ℝ 𝕜 F'`. ## Tags conditional expectation, conditional expected value -/ noncomputable theory open topological_space measure_theory.Lp filter continuous_linear_map open_locale nnreal ennreal topological_space big_operators measure_theory namespace measure_theory /-- A function `f` verifies `ae_measurable' m f μ` if it is `μ`-a.e. equal to an `m`-measurable function. This is similar to `ae_measurable`, but the `measurable_space` structures used for the measurability statement and for the measure are different. -/ def ae_measurable' {α β} [measurable_space β] (m : measurable_space α) {m0 : measurable_space α} (f : α → β) (μ : measure α) : Prop := ∃ g : α → β, @measurable α β m _ g ∧ f =ᵐ[μ] g namespace ae_measurable' variables {α β 𝕜 : Type*} {m m0 : measurable_space α} {μ : measure α} [measurable_space β] [measurable_space 𝕜] {f g : α → β} lemma congr (hf : ae_measurable' m f μ) (hfg : f =ᵐ[μ] g) : ae_measurable' m g μ := by { obtain ⟨f', hf'_meas, hff'⟩ := hf, exact ⟨f', hf'_meas, hfg.symm.trans hff'⟩, } lemma add [has_add β] [has_measurable_add₂ β] (hf : ae_measurable' m f μ) (hg : ae_measurable' m g μ) : ae_measurable' m (f+g) μ := begin rcases hf with ⟨f', h_f'_meas, hff'⟩, rcases hg with ⟨g', h_g'_meas, hgg'⟩, exact ⟨f' + g', @measurable.add _ _ _ _ m _ f' g' h_f'_meas h_g'_meas, hff'.add hgg'⟩, end lemma neg [has_neg β] [has_measurable_neg β] {f : α → β} (hfm : ae_measurable' m f μ) : ae_measurable' m (-f) μ := begin rcases hfm with ⟨f', hf'_meas, hf_ae⟩, refine ⟨-f', @measurable.neg _ _ _ _ _ m _ hf'_meas, hf_ae.mono (λ x hx, _)⟩, simp_rw pi.neg_apply, rw hx, end lemma sub [has_sub β] [has_measurable_sub₂ β] {f g : α → β} (hfm : ae_measurable' m f μ) (hgm : ae_measurable' m g μ) : ae_measurable' m (f - g) μ := begin rcases hfm with ⟨f', hf'_meas, hf_ae⟩, rcases hgm with ⟨g', hg'_meas, hg_ae⟩, refine ⟨f'-g', @measurable.sub _ _ _ _ m _ _ _ hf'_meas hg'_meas, hf_ae.mp (hg_ae.mono (λ x hx1 hx2, _))⟩, simp_rw pi.sub_apply, rw [hx1, hx2], end lemma const_smul [has_scalar 𝕜 β] [has_measurable_smul 𝕜 β] (c : 𝕜) (hf : ae_measurable' m f μ) : ae_measurable' m (c • f) μ := begin rcases hf with ⟨f', h_f'_meas, hff'⟩, refine ⟨c • f', @measurable.const_smul _ _ _ _ _ _ m _ f' h_f'_meas c, _⟩, exact eventually_eq.fun_comp hff' (λ x, c • x), end lemma const_inner [is_R_or_C 𝕜] [borel_space 𝕜] [inner_product_space 𝕜 β] [second_countable_topology β] [opens_measurable_space β] {f : α → β} (hfm : ae_measurable' m f μ) (c : β) : ae_measurable' m (λ x, (inner c (f x) : 𝕜)) μ := begin rcases hfm with ⟨f', hf'_meas, hf_ae⟩, refine ⟨λ x, (inner c (f' x) : 𝕜), @measurable.inner _ _ _ _ _ m _ _ _ _ _ _ _ (@measurable_const _ _ _ m _) hf'_meas, hf_ae.mono (λ x hx, _)⟩, dsimp only, rw hx, end /-- A m-measurable function almost everywhere equal to `f`. -/ def mk (f : α → β) (hfm : ae_measurable' m f μ) : α → β := hfm.some lemma measurable_mk {f : α → β} (hfm : ae_measurable' m f μ) : measurable[m] (hfm.mk f) := hfm.some_spec.1 lemma ae_eq_mk {f : α → β} (hfm : ae_measurable' m f μ) : f =ᵐ[μ] hfm.mk f := hfm.some_spec.2 lemma measurable_comp {γ} [measurable_space γ] {f : α → β} {g : β → γ} (hg : measurable g) (hf : ae_measurable' m f μ) : ae_measurable' m (g ∘ f) μ := ⟨λ x, g (hf.mk _ x), @measurable.comp _ _ _ m _ _ _ _ hg hf.measurable_mk, hf.ae_eq_mk.mono (λ x hx, by rw [function.comp_apply, hx])⟩ end ae_measurable' lemma ae_measurable'_of_ae_measurable'_trim {α β} {m m0 m0' : measurable_space α} [measurable_space β] (hm0 : m0 ≤ m0') {μ : measure α} {f : α → β} (hf : ae_measurable' m f (μ.trim hm0)) : ae_measurable' m f μ := by { obtain ⟨g, hg_meas, hfg⟩ := hf, exact ⟨g, hg_meas, ae_eq_of_ae_eq_trim hfg⟩, } lemma measurable.ae_measurable' {α β} {m m0 : measurable_space α} [measurable_space β] {μ : measure α} {f : α → β} (hf : measurable[m] f) : ae_measurable' m f μ := ⟨f, hf, ae_eq_refl _⟩ lemma ae_eq_trim_iff_of_ae_measurable' {α β} [add_group β] [measurable_space β] [measurable_singleton_class β] [has_measurable_sub₂ β] {m m0 : measurable_space α} {μ : measure α} {f g : α → β} (hm : m ≤ m0) (hfm : ae_measurable' m f μ) (hgm : ae_measurable' m g μ) : hfm.mk f =ᵐ[μ.trim hm] hgm.mk g ↔ f =ᵐ[μ] g := (ae_eq_trim_iff hm hfm.measurable_mk hgm.measurable_mk).trans ⟨λ h, hfm.ae_eq_mk.trans (h.trans hgm.ae_eq_mk.symm), λ h, hfm.ae_eq_mk.symm.trans (h.trans hgm.ae_eq_mk)⟩ variables {α β γ E E' F F' G G' H 𝕜 : Type*} {p : ℝ≥0∞} [is_R_or_C 𝕜] [measurable_space 𝕜] -- 𝕜 for ℝ or ℂ, together with a measurable_space [measurable_space β] -- β for a generic measurable space -- E for an inner product space [inner_product_space 𝕜 E] [measurable_space E] [borel_space E] [second_countable_topology E] -- E' for an inner product space on which we compute integrals [inner_product_space 𝕜 E'] [measurable_space E'] [borel_space E'] [second_countable_topology E'] [complete_space E'] [normed_space ℝ E'] -- F for a Lp submodule [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] [second_countable_topology F] -- F' for integrals on a Lp submodule [normed_group F'] [normed_space 𝕜 F'] [measurable_space F'] [borel_space F'] [second_countable_topology F'] [normed_space ℝ F'] [complete_space F'] -- G for a Lp add_subgroup [normed_group G] [measurable_space G] [borel_space G] [second_countable_topology G] -- G' for integrals on a Lp add_subgroup [normed_group G'] [measurable_space G'] [borel_space G'] [second_countable_topology G'] [normed_space ℝ G'] [complete_space G'] -- H for measurable space and normed group (hypotheses of mem_ℒp) [measurable_space H] [normed_group H] section Lp_meas /-! ## The subset `Lp_meas` of `Lp` functions a.e. measurable with respect to a sub-sigma-algebra -/ variables (F) /-- `Lp_meas_subgroup F m p μ` is the subspace of `Lp F p μ` containing functions `f` verifying `ae_measurable' m f μ`, i.e. functions which are `μ`-a.e. equal to an `m`-measurable function. -/ def Lp_meas_subgroup (m : measurable_space α) [measurable_space α] (p : ℝ≥0∞) (μ : measure α) : add_subgroup (Lp F p μ) := { carrier := {f : (Lp F p μ) | ae_measurable' m f μ} , zero_mem' := ⟨(0 : α → F), @measurable_zero _ α _ m _, Lp.coe_fn_zero _ _ _⟩, add_mem' := λ f g hf hg, (hf.add hg).congr (Lp.coe_fn_add f g).symm, neg_mem' := λ f hf, ae_measurable'.congr hf.neg (Lp.coe_fn_neg f).symm, } variables (𝕜) /-- `Lp_meas F 𝕜 m p μ` is the subspace of `Lp F p μ` containing functions `f` verifying `ae_measurable' m f μ`, i.e. functions which are `μ`-a.e. equal to an `m`-measurable function. -/ def Lp_meas [opens_measurable_space 𝕜] (m : measurable_space α) [measurable_space α] (p : ℝ≥0∞) (μ : measure α) : submodule 𝕜 (Lp F p μ) := { carrier := {f : (Lp F p μ) | ae_measurable' m f μ} , zero_mem' := ⟨(0 : α → F), @measurable_zero _ α _ m _, Lp.coe_fn_zero _ _ _⟩, add_mem' := λ f g hf hg, (hf.add hg).congr (Lp.coe_fn_add f g).symm, smul_mem' := λ c f hf, (hf.const_smul c).congr (Lp.coe_fn_smul c f).symm, } variables {F 𝕜} variables [opens_measurable_space 𝕜] lemma mem_Lp_meas_subgroup_iff_ae_measurable' {m m0 : measurable_space α} {μ : measure α} {f : Lp F p μ} : f ∈ Lp_meas_subgroup F m p μ ↔ ae_measurable' m f μ := by rw [← add_subgroup.mem_carrier, Lp_meas_subgroup, set.mem_set_of_eq] lemma mem_Lp_meas_iff_ae_measurable' {m m0 : measurable_space α} {μ : measure α} {f : Lp F p μ} : f ∈ Lp_meas F 𝕜 m p μ ↔ ae_measurable' m f μ := by rw [← set_like.mem_coe, ← submodule.mem_carrier, Lp_meas, set.mem_set_of_eq] lemma Lp_meas.ae_measurable' {m m0 : measurable_space α} {μ : measure α} (f : Lp_meas F 𝕜 m p μ) : ae_measurable' m f μ := mem_Lp_meas_iff_ae_measurable'.mp f.mem lemma mem_Lp_meas_self {m0 : measurable_space α} (μ : measure α) (f : Lp F p μ) : f ∈ Lp_meas F 𝕜 m0 p μ := mem_Lp_meas_iff_ae_measurable'.mpr (Lp.ae_measurable f) lemma Lp_meas_subgroup_coe {m m0 : measurable_space α} {μ : measure α} {f : Lp_meas_subgroup F m p μ} : ⇑f = (f : Lp F p μ) := coe_fn_coe_base f lemma Lp_meas_coe {m m0 : measurable_space α} {μ : measure α} {f : Lp_meas F 𝕜 m p μ} : ⇑f = (f : Lp F p μ) := coe_fn_coe_base f lemma mem_Lp_meas_indicator_const_Lp {m m0 : measurable_space α} (hm : m ≤ m0) {μ : measure α} {s : set α} (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) {c : F} : indicator_const_Lp p (hm s hs) hμs c ∈ Lp_meas F 𝕜 m p μ := ⟨s.indicator (λ x : α, c), @measurable.indicator α _ m _ _ s (λ x, c) (@measurable_const _ α _ m _) hs, indicator_const_Lp_coe_fn⟩ section complete_subspace /-! ## The subspace `Lp_meas` is complete. We define an `isometric` between `Lp_meas_subgroup` and the `Lp` space corresponding to the measure `μ.trim hm`. As a consequence, the completeness of `Lp` implies completeness of `Lp_meas_subgroup` (and `Lp_meas`). -/ variables {ι : Type*} {m m0 : measurable_space α} {μ : measure α} /-- If `f` belongs to `Lp_meas_subgroup F m p μ`, then the measurable function it is almost everywhere equal to (given by `ae_measurable.mk`) belongs to `ℒp` for the measure `μ.trim hm`. -/ lemma mem_ℒp_trim_of_mem_Lp_meas_subgroup (hm : m ≤ m0) (f : Lp F p μ) (hf_meas : f ∈ Lp_meas_subgroup F m p μ) : mem_ℒp (mem_Lp_meas_subgroup_iff_ae_measurable'.mp hf_meas).some p (μ.trim hm) := begin have hf : ae_measurable' m f μ, from (mem_Lp_meas_subgroup_iff_ae_measurable'.mp hf_meas), let g := hf.some, obtain ⟨hg, hfg⟩ := hf.some_spec, change mem_ℒp g p (μ.trim hm), refine ⟨hg.ae_measurable, _⟩, have h_snorm_fg : snorm g p (μ.trim hm) = snorm f p μ, by { rw snorm_trim hm hg, exact snorm_congr_ae hfg.symm, }, rw h_snorm_fg, exact Lp.snorm_lt_top f, end /-- If `f` belongs to `Lp` for the measure `μ.trim hm`, then it belongs to the subgroup `Lp_meas_subgroup F m p μ`. -/ lemma mem_Lp_meas_subgroup_to_Lp_of_trim (hm : m ≤ m0) (f : Lp F p (μ.trim hm)) : (mem_ℒp_of_mem_ℒp_trim hm (Lp.mem_ℒp f)).to_Lp f ∈ Lp_meas_subgroup F m p μ := begin let hf_mem_ℒp := mem_ℒp_of_mem_ℒp_trim hm (Lp.mem_ℒp f), rw mem_Lp_meas_subgroup_iff_ae_measurable', refine ae_measurable'.congr _ (mem_ℒp.coe_fn_to_Lp hf_mem_ℒp).symm, refine ae_measurable'_of_ae_measurable'_trim hm _, exact (Lp.ae_measurable f), end variables (F p μ) /-- Map from `Lp_meas_subgroup` to `Lp F p (μ.trim hm)`. -/ def Lp_meas_subgroup_to_Lp_trim (hm : m ≤ m0) (f : Lp_meas_subgroup F m p μ) : Lp F p (μ.trim hm) := mem_ℒp.to_Lp (mem_Lp_meas_subgroup_iff_ae_measurable'.mp f.mem).some (mem_ℒp_trim_of_mem_Lp_meas_subgroup hm f f.mem) variables (𝕜) /-- Map from `Lp_meas` to `Lp F p (μ.trim hm)`. -/ def Lp_meas_to_Lp_trim (hm : m ≤ m0) (f : Lp_meas F 𝕜 m p μ) : Lp F p (μ.trim hm) := mem_ℒp.to_Lp (mem_Lp_meas_iff_ae_measurable'.mp f.mem).some (mem_ℒp_trim_of_mem_Lp_meas_subgroup hm f f.mem) variables {𝕜} /-- Map from `Lp F p (μ.trim hm)` to `Lp_meas_subgroup`, inverse of `Lp_meas_subgroup_to_Lp_trim`. -/ def Lp_trim_to_Lp_meas_subgroup (hm : m ≤ m0) (f : Lp F p (μ.trim hm)) : Lp_meas_subgroup F m p μ := ⟨(mem_ℒp_of_mem_ℒp_trim hm (Lp.mem_ℒp f)).to_Lp f, mem_Lp_meas_subgroup_to_Lp_of_trim hm f⟩ variables (𝕜) /-- Map from `Lp F p (μ.trim hm)` to `Lp_meas`, inverse of `Lp_meas_to_Lp_trim`. -/ def Lp_trim_to_Lp_meas (hm : m ≤ m0) (f : Lp F p (μ.trim hm)) : Lp_meas F 𝕜 m p μ := ⟨(mem_ℒp_of_mem_ℒp_trim hm (Lp.mem_ℒp f)).to_Lp f, mem_Lp_meas_subgroup_to_Lp_of_trim hm f⟩ variables {F 𝕜 p μ} lemma Lp_meas_subgroup_to_Lp_trim_ae_eq (hm : m ≤ m0) (f : Lp_meas_subgroup F m p μ) : Lp_meas_subgroup_to_Lp_trim F p μ hm f =ᵐ[μ] f := (ae_eq_of_ae_eq_trim (mem_ℒp.coe_fn_to_Lp (mem_ℒp_trim_of_mem_Lp_meas_subgroup hm ↑f f.mem))).trans (mem_Lp_meas_subgroup_iff_ae_measurable'.mp f.mem).some_spec.2.symm lemma Lp_trim_to_Lp_meas_subgroup_ae_eq (hm : m ≤ m0) (f : Lp F p (μ.trim hm)) : Lp_trim_to_Lp_meas_subgroup F p μ hm f =ᵐ[μ] f := mem_ℒp.coe_fn_to_Lp _ lemma Lp_meas_to_Lp_trim_ae_eq (hm : m ≤ m0) (f : Lp_meas F 𝕜 m p μ) : Lp_meas_to_Lp_trim F 𝕜 p μ hm f =ᵐ[μ] f := (ae_eq_of_ae_eq_trim (mem_ℒp.coe_fn_to_Lp (mem_ℒp_trim_of_mem_Lp_meas_subgroup hm ↑f f.mem))).trans (mem_Lp_meas_subgroup_iff_ae_measurable'.mp f.mem).some_spec.2.symm lemma Lp_trim_to_Lp_meas_ae_eq (hm : m ≤ m0) (f : Lp F p (μ.trim hm)) : Lp_trim_to_Lp_meas F 𝕜 p μ hm f =ᵐ[μ] f := mem_ℒp.coe_fn_to_Lp _ /-- `Lp_trim_to_Lp_meas_subgroup` is a right inverse of `Lp_meas_subgroup_to_Lp_trim`. -/ lemma Lp_meas_subgroup_to_Lp_trim_right_inv (hm : m ≤ m0) : function.right_inverse (Lp_trim_to_Lp_meas_subgroup F p μ hm) (Lp_meas_subgroup_to_Lp_trim F p μ hm) := begin intro f, ext1, refine ae_eq_trim_of_measurable hm (Lp.measurable _) (Lp.measurable _) _, exact (Lp_meas_subgroup_to_Lp_trim_ae_eq hm _).trans (Lp_trim_to_Lp_meas_subgroup_ae_eq hm _), end /-- `Lp_trim_to_Lp_meas_subgroup` is a left inverse of `Lp_meas_subgroup_to_Lp_trim`. -/ lemma Lp_meas_subgroup_to_Lp_trim_left_inv (hm : m ≤ m0) : function.left_inverse (Lp_trim_to_Lp_meas_subgroup F p μ hm) (Lp_meas_subgroup_to_Lp_trim F p μ hm) := begin intro f, ext1, ext1, rw ← Lp_meas_subgroup_coe, exact (Lp_trim_to_Lp_meas_subgroup_ae_eq hm _).trans (Lp_meas_subgroup_to_Lp_trim_ae_eq hm _), end lemma Lp_meas_subgroup_to_Lp_trim_add (hm : m ≤ m0) (f g : Lp_meas_subgroup F m p μ) : Lp_meas_subgroup_to_Lp_trim F p μ hm (f + g) = Lp_meas_subgroup_to_Lp_trim F p μ hm f + Lp_meas_subgroup_to_Lp_trim F p μ hm g := begin ext1, refine eventually_eq.trans _ (Lp.coe_fn_add _ _).symm, refine ae_eq_trim_of_measurable hm (Lp.measurable _) _ _, { exact @measurable.add _ _ _ _ m _ _ _ (Lp.measurable _) (Lp.measurable _), }, refine (Lp_meas_subgroup_to_Lp_trim_ae_eq hm _).trans _, refine eventually_eq.trans _ (eventually_eq.add (Lp_meas_subgroup_to_Lp_trim_ae_eq hm f).symm (Lp_meas_subgroup_to_Lp_trim_ae_eq hm g).symm), refine (Lp.coe_fn_add _ _).trans _, simp_rw Lp_meas_subgroup_coe, exact eventually_of_forall (λ x, by refl), end lemma Lp_meas_subgroup_to_Lp_trim_neg (hm : m ≤ m0) (f : Lp_meas_subgroup F m p μ) : Lp_meas_subgroup_to_Lp_trim F p μ hm (-f) = -Lp_meas_subgroup_to_Lp_trim F p μ hm f := begin ext1, refine eventually_eq.trans _ (Lp.coe_fn_neg _).symm, refine ae_eq_trim_of_measurable hm (Lp.measurable _) _ _, { exact @measurable.neg _ _ _ _ _ m _ (Lp.measurable _), }, refine (Lp_meas_subgroup_to_Lp_trim_ae_eq hm _).trans _, refine eventually_eq.trans _ (eventually_eq.neg (Lp_meas_subgroup_to_Lp_trim_ae_eq hm f).symm), refine (Lp.coe_fn_neg _).trans _, simp_rw Lp_meas_subgroup_coe, exact eventually_of_forall (λ x, by refl), end lemma Lp_meas_subgroup_to_Lp_trim_sub (hm : m ≤ m0) (f g : Lp_meas_subgroup F m p μ) : Lp_meas_subgroup_to_Lp_trim F p μ hm (f - g) = Lp_meas_subgroup_to_Lp_trim F p μ hm f - Lp_meas_subgroup_to_Lp_trim F p μ hm g := by rw [sub_eq_add_neg, sub_eq_add_neg, Lp_meas_subgroup_to_Lp_trim_add, Lp_meas_subgroup_to_Lp_trim_neg] lemma Lp_meas_to_Lp_trim_smul (hm : m ≤ m0) (c : 𝕜) (f : Lp_meas F 𝕜 m p μ) : Lp_meas_to_Lp_trim F 𝕜 p μ hm (c • f) = c • Lp_meas_to_Lp_trim F 𝕜 p μ hm f := begin ext1, refine eventually_eq.trans _ (Lp.coe_fn_smul _ _).symm, refine ae_eq_trim_of_measurable hm (Lp.measurable _) _ _, { exact @measurable.const_smul _ _ α _ _ _ m _ _ (Lp.measurable _) c, }, refine (Lp_meas_to_Lp_trim_ae_eq hm _).trans _, refine (Lp.coe_fn_smul _ _).trans _, refine (Lp_meas_to_Lp_trim_ae_eq hm f).mono (λ x hx, _), rw [pi.smul_apply, pi.smul_apply, hx], refl, end /-- `Lp_meas_subgroup_to_Lp_trim` preserves the norm. -/ lemma Lp_meas_subgroup_to_Lp_trim_norm_map [hp : fact (1 ≤ p)] (hm : m ≤ m0) (f : Lp_meas_subgroup F m p μ) : ∥Lp_meas_subgroup_to_Lp_trim F p μ hm f∥ = ∥f∥ := begin rw [Lp.norm_def, snorm_trim hm (Lp.measurable _)], swap, { apply_instance, }, rw [snorm_congr_ae (Lp_meas_subgroup_to_Lp_trim_ae_eq hm _), Lp_meas_subgroup_coe, ← Lp.norm_def], congr, end lemma isometry_Lp_meas_subgroup_to_Lp_trim [hp : fact (1 ≤ p)] (hm : m ≤ m0) : isometry (Lp_meas_subgroup_to_Lp_trim F p μ hm) := begin rw isometry_emetric_iff_metric, intros f g, rw [dist_eq_norm, ← Lp_meas_subgroup_to_Lp_trim_sub, Lp_meas_subgroup_to_Lp_trim_norm_map, dist_eq_norm], end variables (F p μ) /-- `Lp_meas_subgroup` and `Lp F p (μ.trim hm)` are isometric. -/ def Lp_meas_subgroup_to_Lp_trim_iso [hp : fact (1 ≤ p)] (hm : m ≤ m0) : Lp_meas_subgroup F m p μ ≃ᵢ Lp F p (μ.trim hm) := { to_fun := Lp_meas_subgroup_to_Lp_trim F p μ hm, inv_fun := Lp_trim_to_Lp_meas_subgroup F p μ hm, left_inv := Lp_meas_subgroup_to_Lp_trim_left_inv hm, right_inv := Lp_meas_subgroup_to_Lp_trim_right_inv hm, isometry_to_fun := isometry_Lp_meas_subgroup_to_Lp_trim hm, } variables (𝕜) /-- `Lp_meas_subgroup` and `Lp_meas` are isometric. -/ def Lp_meas_subgroup_to_Lp_meas_iso [hp : fact (1 ≤ p)] : Lp_meas_subgroup F m p μ ≃ᵢ Lp_meas F 𝕜 m p μ := isometric.refl (Lp_meas_subgroup F m p μ) /-- `Lp_meas` and `Lp F p (μ.trim hm)` are isometric, with a linear equivalence. -/ def Lp_meas_to_Lp_trim_lie [hp : fact (1 ≤ p)] (hm : m ≤ m0) : Lp_meas F 𝕜 m p μ ≃ₗᵢ[𝕜] Lp F p (μ.trim hm) := { to_fun := Lp_meas_to_Lp_trim F 𝕜 p μ hm, inv_fun := Lp_trim_to_Lp_meas F 𝕜 p μ hm, left_inv := Lp_meas_subgroup_to_Lp_trim_left_inv hm, right_inv := Lp_meas_subgroup_to_Lp_trim_right_inv hm, map_add' := Lp_meas_subgroup_to_Lp_trim_add hm, map_smul' := Lp_meas_to_Lp_trim_smul hm, norm_map' := Lp_meas_subgroup_to_Lp_trim_norm_map hm, } variables {F 𝕜 p μ} instance [hm : fact (m ≤ m0)] [complete_space F] [hp : fact (1 ≤ p)] : complete_space (Lp_meas_subgroup F m p μ) := by { rw (Lp_meas_subgroup_to_Lp_trim_iso F p μ hm.elim).complete_space_iff, apply_instance, } instance [hm : fact (m ≤ m0)] [complete_space F] [hp : fact (1 ≤ p)] : complete_space (Lp_meas F 𝕜 m p μ) := by { rw (Lp_meas_subgroup_to_Lp_meas_iso F 𝕜 p μ).symm.complete_space_iff, apply_instance, } lemma is_complete_ae_measurable' [hp : fact (1 ≤ p)] [complete_space F] (hm : m ≤ m0) : is_complete {f : Lp F p μ | ae_measurable' m f μ} := begin rw ← complete_space_coe_iff_is_complete, haveI : fact (m ≤ m0) := ⟨hm⟩, change complete_space (Lp_meas_subgroup F m p μ), apply_instance, end lemma is_closed_ae_measurable' [hp : fact (1 ≤ p)] [complete_space F] (hm : m ≤ m0) : is_closed {f : Lp F p μ | ae_measurable' m f μ} := is_complete.is_closed (is_complete_ae_measurable' hm) end complete_subspace section strongly_measurable variables {m m0 : measurable_space α} {μ : measure α} /-- We do not get `ae_fin_strongly_measurable f (μ.trim hm)`, since we don't have `f =ᵐ[μ.trim hm] Lp_meas_to_Lp_trim F 𝕜 p μ hm f` but only the weaker `f =ᵐ[μ] Lp_meas_to_Lp_trim F 𝕜 p μ hm f`. -/ lemma Lp_meas.ae_fin_strongly_measurable' (hm : m ≤ m0) (f : Lp_meas F 𝕜 m p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : ∃ g, fin_strongly_measurable g (μ.trim hm) ∧ f =ᵐ[μ] g := ⟨Lp_meas_subgroup_to_Lp_trim F p μ hm f, Lp.fin_strongly_measurable _ hp_ne_zero hp_ne_top, (Lp_meas_subgroup_to_Lp_trim_ae_eq hm f).symm⟩ end strongly_measurable end Lp_meas section uniqueness_of_conditional_expectation /-! ## Uniqueness of the conditional expectation -/ variables {m m0 : measurable_space α} {μ : measure α} [borel_space 𝕜] lemma Lp_meas.ae_eq_zero_of_forall_set_integral_eq_zero (hm : m ≤ m0) (f : Lp_meas E' 𝕜 m p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on f s μ) (hf_zero : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) : f =ᵐ[μ] 0 := begin obtain ⟨g, hg_sm, hfg⟩ := Lp_meas.ae_fin_strongly_measurable' hm f hp_ne_zero hp_ne_top, refine hfg.trans _, refine ae_eq_zero_of_forall_set_integral_eq_of_fin_strongly_measurable_trim hm _ _ hg_sm, { intros s hs hμs, have hfg_restrict : f =ᵐ[μ.restrict s] g, from ae_restrict_of_ae hfg, rw [integrable_on, integrable_congr hfg_restrict.symm], exact hf_int_finite s hs hμs, }, { intros s hs hμs, have hfg_restrict : f =ᵐ[μ.restrict s] g, from ae_restrict_of_ae hfg, rw integral_congr_ae hfg_restrict.symm, exact hf_zero s hs hμs, }, end include 𝕜 lemma Lp.ae_eq_zero_of_forall_set_integral_eq_zero' (hm : m ≤ m0) (f : Lp E' p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on f s μ) (hf_zero : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) (hf_meas : ae_measurable' m f μ) : f =ᵐ[μ] 0 := begin let f_meas : Lp_meas E' 𝕜 m p μ := ⟨f, hf_meas⟩, have hf_f_meas : f =ᵐ[μ] f_meas, by simp only [coe_fn_coe_base', subtype.coe_mk], refine hf_f_meas.trans _, refine Lp_meas.ae_eq_zero_of_forall_set_integral_eq_zero hm f_meas hp_ne_zero hp_ne_top _ _, { intros s hs hμs, have hfg_restrict : f =ᵐ[μ.restrict s] f_meas, from ae_restrict_of_ae hf_f_meas, rw [integrable_on, integrable_congr hfg_restrict.symm], exact hf_int_finite s hs hμs, }, { intros s hs hμs, have hfg_restrict : f =ᵐ[μ.restrict s] f_meas, from ae_restrict_of_ae hf_f_meas, rw integral_congr_ae hfg_restrict.symm, exact hf_zero s hs hμs, }, end /-- **Uniqueness of the conditional expectation** -/ lemma Lp.ae_eq_of_forall_set_integral_eq' (hm : m ≤ m0) (f g : Lp E' p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on f s μ) (hg_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on g s μ) (hfg : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) (hf_meas : ae_measurable' m f μ) (hg_meas : ae_measurable' m g μ) : f =ᵐ[μ] g := begin suffices h_sub : ⇑(f-g) =ᵐ[μ] 0, by { rw ← sub_ae_eq_zero, exact (Lp.coe_fn_sub f g).symm.trans h_sub, }, have hfg' : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, (f - g) x ∂μ = 0, { intros s hs hμs, rw integral_congr_ae (ae_restrict_of_ae (Lp.coe_fn_sub f g)), rw integral_sub' (hf_int_finite s hs hμs) (hg_int_finite s hs hμs), exact sub_eq_zero.mpr (hfg s hs hμs), }, have hfg_int : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on ⇑(f-g) s μ, { intros s hs hμs, rw [integrable_on, integrable_congr (ae_restrict_of_ae (Lp.coe_fn_sub f g))], exact (hf_int_finite s hs hμs).sub (hg_int_finite s hs hμs), }, have hfg_meas : ae_measurable' m ⇑(f - g) μ, from ae_measurable'.congr (hf_meas.sub hg_meas) (Lp.coe_fn_sub f g).symm, exact Lp.ae_eq_zero_of_forall_set_integral_eq_zero' hm (f-g) hp_ne_zero hp_ne_top hfg_int hfg' hfg_meas, end omit 𝕜 lemma ae_eq_of_forall_set_integral_eq_of_sigma_finite' (hm : m ≤ m0) [sigma_finite (μ.trim hm)] {f g : α → F'} (hf_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on f s μ) (hg_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on g s μ) (hfg_eq : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) (hfm : ae_measurable' m f μ) (hgm : ae_measurable' m g μ) : f =ᵐ[μ] g := begin rw ← ae_eq_trim_iff_of_ae_measurable' hm hfm hgm, have hf_mk_int_finite : ∀ s, measurable_set[m] s → μ.trim hm s < ∞ → @integrable_on _ _ m _ _ (hfm.mk f) s (μ.trim hm), { intros s hs hμs, rw trim_measurable_set_eq hm hs at hμs, rw [integrable_on, restrict_trim hm _ hs], refine integrable.trim hm _ hfm.measurable_mk, exact integrable.congr (hf_int_finite s hs hμs) (ae_restrict_of_ae hfm.ae_eq_mk), }, have hg_mk_int_finite : ∀ s, measurable_set[m] s → μ.trim hm s < ∞ → @integrable_on _ _ m _ _ (hgm.mk g) s (μ.trim hm), { intros s hs hμs, rw trim_measurable_set_eq hm hs at hμs, rw [integrable_on, restrict_trim hm _ hs], refine integrable.trim hm _ hgm.measurable_mk, exact integrable.congr (hg_int_finite s hs hμs) (ae_restrict_of_ae hgm.ae_eq_mk), }, have hfg_mk_eq : ∀ s : set α, measurable_set[m] s → μ.trim hm s < ∞ → ∫ x in s, (hfm.mk f x) ∂(μ.trim hm) = ∫ x in s, (hgm.mk g x) ∂(μ.trim hm), { intros s hs hμs, rw trim_measurable_set_eq hm hs at hμs, rw [restrict_trim hm _ hs, ← integral_trim hm hfm.measurable_mk, ← integral_trim hm hgm.measurable_mk, integral_congr_ae (ae_restrict_of_ae hfm.ae_eq_mk.symm), integral_congr_ae (ae_restrict_of_ae hgm.ae_eq_mk.symm)], exact hfg_eq s hs hμs, }, exact ae_eq_of_forall_set_integral_eq_of_sigma_finite hf_mk_int_finite hg_mk_int_finite hfg_mk_eq, end end uniqueness_of_conditional_expectation section integral_norm_le variables {m m0 : measurable_space α} {μ : measure α} {s : set α} /-- Let `m` be a sub-σ-algebra of `m0`, `f` a `m0`-measurable function and `g` a `m`-measurable function, such that their integrals coincide on `m`-measurable sets with finite measure. Then `∫ x in s, ∥g x∥ ∂μ ≤ ∫ x in s, ∥f x∥ ∂μ` on all `m`-measurable sets with finite measure. -/ lemma integral_norm_le_of_forall_fin_meas_integral_eq (hm : m ≤ m0) {f g : α → ℝ} (hf : measurable f) (hfi : integrable_on f s μ) (hg : measurable[m] g) (hgi : integrable_on g s μ) (hgf : ∀ t, measurable_set[m] t → μ t < ∞ → ∫ x in t, g x ∂μ = ∫ x in t, f x ∂μ) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫ x in s, ∥g x∥ ∂μ ≤ ∫ x in s, ∥f x∥ ∂μ := begin rw [integral_norm_eq_pos_sub_neg (hg.mono hm le_rfl) hgi, integral_norm_eq_pos_sub_neg hf hfi], have h_meas_nonneg_g : measurable_set[m] {x | 0 ≤ g x}, from @measurable_set_le _ α _ _ _ m _ _ _ _ g (@measurable_const _ α _ m _) hg, have h_meas_nonneg_f : measurable_set {x | 0 ≤ f x}, from measurable_set_le measurable_const hf, have h_meas_nonpos_g : measurable_set[m] {x | g x ≤ 0}, from @measurable_set_le _ α _ _ _ m _ _ _ g _ hg (@measurable_const _ α _ m _), have h_meas_nonpos_f : measurable_set {x | f x ≤ 0}, from measurable_set_le hf measurable_const, refine sub_le_sub _ _, { rw [measure.restrict_restrict (hm _ h_meas_nonneg_g), measure.restrict_restrict h_meas_nonneg_f, hgf _ (@measurable_set.inter α m _ _ h_meas_nonneg_g hs) ((measure_mono (set.inter_subset_right _ _)).trans_lt (lt_top_iff_ne_top.mpr hμs)), ← measure.restrict_restrict (hm _ h_meas_nonneg_g), ← measure.restrict_restrict h_meas_nonneg_f], exact set_integral_le_nonneg (hm _ h_meas_nonneg_g) hf hfi, }, { rw [measure.restrict_restrict (hm _ h_meas_nonpos_g), measure.restrict_restrict h_meas_nonpos_f, hgf _ (@measurable_set.inter α m _ _ h_meas_nonpos_g hs) ((measure_mono (set.inter_subset_right _ _)).trans_lt (lt_top_iff_ne_top.mpr hμs)), ← measure.restrict_restrict (hm _ h_meas_nonpos_g), ← measure.restrict_restrict h_meas_nonpos_f], exact set_integral_nonpos_le (hm _ h_meas_nonpos_g) hf hfi, }, end /-- Let `m` be a sub-σ-algebra of `m0`, `f` a `m0`-measurable function and `g` a `m`-measurable function, such that their integrals coincide on `m`-measurable sets with finite measure. Then `∫⁻ x in s, ∥g x∥₊ ∂μ ≤ ∫⁻ x in s, ∥f x∥₊ ∂μ` on all `m`-measurable sets with finite measure. -/ lemma lintegral_nnnorm_le_of_forall_fin_meas_integral_eq (hm : m ≤ m0) {f g : α → ℝ} (hf : measurable f) (hfi : integrable_on f s μ) (hg : measurable[m] g) (hgi : integrable_on g s μ) (hgf : ∀ t, measurable_set[m] t → μ t < ∞ → ∫ x in t, g x ∂μ = ∫ x in t, f x ∂μ) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫⁻ x in s, ∥g x∥₊ ∂μ ≤ ∫⁻ x in s, ∥f x∥₊ ∂μ := begin rw [← of_real_integral_norm_eq_lintegral_nnnorm hfi, ← of_real_integral_norm_eq_lintegral_nnnorm hgi, ennreal.of_real_le_of_real_iff], { exact integral_norm_le_of_forall_fin_meas_integral_eq hm hf hfi hg hgi hgf hs hμs, }, { exact integral_nonneg (λ x, norm_nonneg _), }, end end integral_norm_le /-! ## Conditional expectation in L2 We define a conditional expectation in `L2`: it is the orthogonal projection on the subspace `Lp_meas`. -/ section condexp_L2 local attribute [instance] fact_one_le_two_ennreal variables [complete_space E] [borel_space 𝕜] {m m0 : measurable_space α} {μ : measure α} {s t : set α} local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y local notation `⟪`x`, `y`⟫₂` := @inner 𝕜 (α →₂[μ] E) _ x y variables (𝕜) /-- Conditional expectation of a function in L2 with respect to a sigma-algebra -/ def condexp_L2 (hm : m ≤ m0) : (α →₂[μ] E) →L[𝕜] (Lp_meas E 𝕜 m 2 μ) := @orthogonal_projection 𝕜 (α →₂[μ] E) _ _ (Lp_meas E 𝕜 m 2 μ) (by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact infer_instance, }) variables {𝕜} lemma ae_measurable'_condexp_L2 (hm : m ≤ m0) (f : α →₂[μ] E) : ae_measurable' m (condexp_L2 𝕜 hm f) μ := Lp_meas.ae_measurable' _ lemma integrable_on_condexp_L2_of_measure_ne_top (hm : m ≤ m0) (hμs : μ s ≠ ∞) (f : α →₂[μ] E) : integrable_on (condexp_L2 𝕜 hm f) s μ := integrable_on_Lp_of_measure_ne_top ((condexp_L2 𝕜 hm f) : α →₂[μ] E) fact_one_le_two_ennreal.elim hμs lemma integrable_condexp_L2_of_is_finite_measure (hm : m ≤ m0) [is_finite_measure μ] {f : α →₂[μ] E} : integrable (condexp_L2 𝕜 hm f) μ := integrable_on_univ.mp $ integrable_on_condexp_L2_of_measure_ne_top hm (measure_ne_top _ _) f lemma norm_condexp_L2_le_one (hm : m ≤ m0) : ∥@condexp_L2 α E 𝕜 _ _ _ _ _ _ _ _ _ _ μ hm∥ ≤ 1 := by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact orthogonal_projection_norm_le _, } lemma norm_condexp_L2_le (hm : m ≤ m0) (f : α →₂[μ] E) : ∥condexp_L2 𝕜 hm f∥ ≤ ∥f∥ := ((@condexp_L2 _ E 𝕜 _ _ _ _ _ _ _ _ _ _ μ hm).le_op_norm f).trans (mul_le_of_le_one_left (norm_nonneg _) (norm_condexp_L2_le_one hm)) lemma snorm_condexp_L2_le (hm : m ≤ m0) (f : α →₂[μ] E) : snorm (condexp_L2 𝕜 hm f) 2 μ ≤ snorm f 2 μ := begin rw [Lp_meas_coe, ← ennreal.to_real_le_to_real (Lp.snorm_ne_top _) (Lp.snorm_ne_top _), ← Lp.norm_def, ← Lp.norm_def, submodule.norm_coe], exact norm_condexp_L2_le hm f, end lemma norm_condexp_L2_coe_le (hm : m ≤ m0) (f : α →₂[μ] E) : ∥(condexp_L2 𝕜 hm f : α →₂[μ] E)∥ ≤ ∥f∥ := begin rw [Lp.norm_def, Lp.norm_def, ← Lp_meas_coe], refine (ennreal.to_real_le_to_real _ (Lp.snorm_ne_top _)).mpr (snorm_condexp_L2_le hm f), exact Lp.snorm_ne_top _, end lemma inner_condexp_L2_left_eq_right (hm : m ≤ m0) {f g : α →₂[μ] E} : ⟪(condexp_L2 𝕜 hm f : α →₂[μ] E), g⟫₂ = ⟪f, (condexp_L2 𝕜 hm g : α →₂[μ] E)⟫₂ := by { haveI : fact (m ≤ m0) := ⟨hm⟩, exact inner_orthogonal_projection_left_eq_right _ f g, } lemma condexp_L2_indicator_of_measurable (hm : m ≤ m0) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) (c : E) : (condexp_L2 𝕜 hm (indicator_const_Lp 2 (hm s hs) hμs c) : α →₂[μ] E) = indicator_const_Lp 2 (hm s hs) hμs c := begin rw condexp_L2, haveI : fact (m ≤ m0) := ⟨hm⟩, have h_mem : indicator_const_Lp 2 (hm s hs) hμs c ∈ Lp_meas E 𝕜 m 2 μ, from mem_Lp_meas_indicator_const_Lp hm hs hμs, let ind := (⟨indicator_const_Lp 2 (hm s hs) hμs c, h_mem⟩ : Lp_meas E 𝕜 m 2 μ), have h_coe_ind : (ind : α →₂[μ] E) = indicator_const_Lp 2 (hm s hs) hμs c, by refl, have h_orth_mem := orthogonal_projection_mem_subspace_eq_self ind, rw [← h_coe_ind, h_orth_mem], end lemma inner_condexp_L2_eq_inner_fun (hm : m ≤ m0) (f g : α →₂[μ] E) (hg : ae_measurable' m g μ) : ⟪(condexp_L2 𝕜 hm f : α →₂[μ] E), g⟫₂ = ⟪f, g⟫₂ := begin symmetry, rw [← sub_eq_zero, ← inner_sub_left, condexp_L2], simp only [mem_Lp_meas_iff_ae_measurable'.mpr hg, orthogonal_projection_inner_eq_zero], end section real variables {hm : m ≤ m0} lemma integral_condexp_L2_eq_of_fin_meas_real (f : Lp 𝕜 2 μ) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫ x in s, condexp_L2 𝕜 hm f x ∂μ = ∫ x in s, f x ∂μ := begin rw ← L2.inner_indicator_const_Lp_one (hm s hs) hμs, have h_eq_inner : ∫ x in s, condexp_L2 𝕜 hm f x ∂μ = inner (indicator_const_Lp 2 (hm s hs) hμs (1 : 𝕜)) (condexp_L2 𝕜 hm f), { rw L2.inner_indicator_const_Lp_one (hm s hs) hμs, congr, }, rw [h_eq_inner, ← inner_condexp_L2_left_eq_right, condexp_L2_indicator_of_measurable hm hs hμs], end lemma lintegral_nnnorm_condexp_L2_le (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) (f : Lp ℝ 2 μ) : ∫⁻ x in s, ∥condexp_L2 ℝ hm f x∥₊ ∂μ ≤ ∫⁻ x in s, ∥f x∥₊ ∂μ := begin let h_meas := Lp_meas.ae_measurable' (condexp_L2 ℝ hm f), let g := h_meas.some, have hg_meas : measurable[m] g, from h_meas.some_spec.1, have hg_eq : g =ᵐ[μ] condexp_L2 ℝ hm f, from h_meas.some_spec.2.symm, have hg_eq_restrict : g =ᵐ[μ.restrict s] condexp_L2 ℝ hm f, from ae_restrict_of_ae hg_eq, have hg_nnnorm_eq : (λ x, (∥g x∥₊ : ℝ≥0∞)) =ᵐ[μ.restrict s] (λ x, (∥condexp_L2 ℝ hm f x∥₊ : ℝ≥0∞)), { refine hg_eq_restrict.mono (λ x hx, _), dsimp only, rw hx, }, rw lintegral_congr_ae hg_nnnorm_eq.symm, refine lintegral_nnnorm_le_of_forall_fin_meas_integral_eq hm (Lp.measurable f) _ _ _ _ hs hμs, { exact integrable_on_Lp_of_measure_ne_top f fact_one_le_two_ennreal.elim hμs, }, { exact hg_meas, }, { rw [integrable_on, integrable_congr hg_eq_restrict], exact integrable_on_condexp_L2_of_measure_ne_top hm hμs f, }, { intros t ht hμt, rw ← integral_condexp_L2_eq_of_fin_meas_real f ht hμt.ne, exact set_integral_congr_ae (hm t ht) (hg_eq.mono (λ x hx _, hx)), }, end lemma condexp_L2_ae_eq_zero_of_ae_eq_zero (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) {f : Lp ℝ 2 μ} (hf : f =ᵐ[μ.restrict s] 0) : condexp_L2 ℝ hm f =ᵐ[μ.restrict s] 0 := begin suffices h_nnnorm_eq_zero : ∫⁻ x in s, ∥condexp_L2 ℝ hm f x∥₊ ∂μ = 0, { rw lintegral_eq_zero_iff at h_nnnorm_eq_zero, refine h_nnnorm_eq_zero.mono (λ x hx, _), dsimp only at hx, rw pi.zero_apply at hx ⊢, { rwa [ennreal.coe_eq_zero, nnnorm_eq_zero] at hx, }, { refine measurable.coe_nnreal_ennreal (measurable.nnnorm _), rw Lp_meas_coe, exact Lp.measurable _, }, }, refine le_antisymm _ (zero_le _), refine (lintegral_nnnorm_condexp_L2_le hs hμs f).trans (le_of_eq _), rw lintegral_eq_zero_iff, { refine hf.mono (λ x hx, _), dsimp only, rw hx, simp, }, { exact (Lp.measurable _).nnnorm.coe_nnreal_ennreal, }, end lemma lintegral_nnnorm_condexp_L2_indicator_le_real (hs : measurable_set s) (hμs : μ s ≠ ∞) (ht : measurable_set[m] t) (hμt : μ t ≠ ∞) : ∫⁻ a in t, ∥condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a∥₊ ∂μ ≤ μ (s ∩ t) := begin refine (lintegral_nnnorm_condexp_L2_le ht hμt _).trans (le_of_eq _), have h_eq : ∫⁻ x in t, ∥(indicator_const_Lp 2 hs hμs (1 : ℝ)) x∥₊ ∂μ = ∫⁻ x in t, s.indicator (λ x, (1 : ℝ≥0∞)) x ∂μ, { refine lintegral_congr_ae (ae_restrict_of_ae _), refine (@indicator_const_Lp_coe_fn _ _ _ 2 _ _ _ _ hs hμs (1 : ℝ) _ _).mono (λ x hx, _), rw hx, simp_rw set.indicator_apply, split_ifs; simp, }, rw [h_eq, lintegral_indicator _ hs, lintegral_const, measure.restrict_restrict hs], simp only [one_mul, set.univ_inter, measurable_set.univ, measure.restrict_apply], end end real /-- `condexp_L2` commutes with taking inner products with constants. See the lemma `condexp_L2_comp_continuous_linear_map` for a more general result about commuting with continuous linear maps. -/ lemma condexp_L2_const_inner (hm : m ≤ m0) (f : Lp E 2 μ) (c : E) : condexp_L2 𝕜 hm (((Lp.mem_ℒp f).const_inner c).to_Lp (λ a, ⟪c, f a⟫)) =ᵐ[μ] λ a, ⟪c, condexp_L2 𝕜 hm f a⟫ := begin rw Lp_meas_coe, have h_mem_Lp : mem_ℒp (λ a, ⟪c, condexp_L2 𝕜 hm f a⟫) 2 μ, { refine mem_ℒp.const_inner _ _, rw Lp_meas_coe, exact Lp.mem_ℒp _, }, have h_eq : h_mem_Lp.to_Lp _ =ᵐ[μ] λ a, ⟪c, condexp_L2 𝕜 hm f a⟫, from h_mem_Lp.coe_fn_to_Lp, refine eventually_eq.trans _ h_eq, refine Lp.ae_eq_of_forall_set_integral_eq' hm _ _ ennreal.zero_lt_two.ne.symm ennreal.coe_ne_top (λ s hs hμs, integrable_on_condexp_L2_of_measure_ne_top hm hμs.ne _) _ _ _ _, { intros s hs hμs, rw [integrable_on, integrable_congr (ae_restrict_of_ae h_eq)], exact (integrable_on_condexp_L2_of_measure_ne_top hm hμs.ne _).const_inner _, }, { intros s hs hμs, rw [← Lp_meas_coe, integral_condexp_L2_eq_of_fin_meas_real _ hs hμs.ne, integral_congr_ae (ae_restrict_of_ae h_eq), Lp_meas_coe, ← L2.inner_indicator_const_Lp_eq_set_integral_inner ↑(condexp_L2 𝕜 hm f) (hm s hs) c hμs.ne, ← inner_condexp_L2_left_eq_right, condexp_L2_indicator_of_measurable, L2.inner_indicator_const_Lp_eq_set_integral_inner f (hm s hs) c hμs.ne, set_integral_congr_ae (hm s hs) ((mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).const_inner c)).mono (λ x hx hxs, hx))], }, { rw ← Lp_meas_coe, exact Lp_meas.ae_measurable' _, }, { refine ae_measurable'.congr _ h_eq.symm, exact (Lp_meas.ae_measurable' _).const_inner _, }, end /-- `condexp_L2` verifies the equality of integrals defining the conditional expectation. -/ lemma integral_condexp_L2_eq [is_scalar_tower ℝ 𝕜 E'] (hm : m ≤ m0) (f : Lp E' 2 μ) (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫ x in s, condexp_L2 𝕜 hm f x ∂μ = ∫ x in s, f x ∂μ := begin rw [← sub_eq_zero, Lp_meas_coe, ← integral_sub' (integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs) (integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs)], refine integral_eq_zero_of_forall_integral_inner_eq_zero _ _ _, { rw integrable_congr (ae_restrict_of_ae (Lp.coe_fn_sub ↑(condexp_L2 𝕜 hm f) f).symm), exact integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs, }, intro c, simp_rw [pi.sub_apply, inner_sub_right], rw integral_sub ((integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs).const_inner c) ((integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs).const_inner c), have h_ae_eq_f := mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).const_inner c), rw [← Lp_meas_coe, sub_eq_zero, ← set_integral_congr_ae (hm s hs) ((condexp_L2_const_inner hm f c).mono (λ x hx _, hx)), ← set_integral_congr_ae (hm s hs) (h_ae_eq_f.mono (λ x hx _, hx))], exact integral_condexp_L2_eq_of_fin_meas_real _ hs hμs, end variables {E'' 𝕜' : Type*} [is_R_or_C 𝕜'] [measurable_space 𝕜'] [borel_space 𝕜'] [measurable_space E''] [inner_product_space 𝕜' E''] [borel_space E''] [second_countable_topology E''] [complete_space E''] [normed_space ℝ E''] [is_scalar_tower ℝ 𝕜 E'] [is_scalar_tower ℝ 𝕜' E''] variables (𝕜 𝕜') lemma condexp_L2_comp_continuous_linear_map (hm : m ≤ m0) (T : E' →L[ℝ] E'') (f : α →₂[μ] E') : (condexp_L2 𝕜' hm (T.comp_Lp f) : α →₂[μ] E'') =ᵐ[μ] T.comp_Lp (condexp_L2 𝕜 hm f : α →₂[μ] E') := begin refine Lp.ae_eq_of_forall_set_integral_eq' hm _ _ ennreal.zero_lt_two.ne.symm ennreal.coe_ne_top (λ s hs hμs, integrable_on_condexp_L2_of_measure_ne_top hm hμs.ne _) (λ s hs hμs, integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs.ne) _ _ _, { intros s hs hμs, rw [T.set_integral_comp_Lp _ (hm s hs), T.integral_comp_comm (integrable_on_Lp_of_measure_ne_top _ fact_one_le_two_ennreal.elim hμs.ne), ← Lp_meas_coe, ← Lp_meas_coe, integral_condexp_L2_eq hm f hs hμs.ne, integral_condexp_L2_eq hm (T.comp_Lp f) hs hμs.ne, T.set_integral_comp_Lp _ (hm s hs), T.integral_comp_comm (integrable_on_Lp_of_measure_ne_top f fact_one_le_two_ennreal.elim hμs.ne)], }, { rw ← Lp_meas_coe, exact Lp_meas.ae_measurable' _, }, { have h_coe := T.coe_fn_comp_Lp (condexp_L2 𝕜 hm f : α →₂[μ] E'), rw ← eventually_eq at h_coe, refine ae_measurable'.congr _ h_coe.symm, exact (Lp_meas.ae_measurable' (condexp_L2 𝕜 hm f)).measurable_comp T.measurable, }, end variables {𝕜 𝕜'} section condexp_L2_indicator variables (𝕜) lemma condexp_L2_indicator_ae_eq_smul (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') : condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) =ᵐ[μ] λ a, (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a) • x := begin rw indicator_const_Lp_eq_to_span_singleton_comp_Lp hs hμs x, have h_comp := condexp_L2_comp_continuous_linear_map ℝ 𝕜 hm (to_span_singleton ℝ x) (indicator_const_Lp 2 hs hμs (1 : ℝ)), rw ← Lp_meas_coe at h_comp, refine h_comp.trans _, exact (to_span_singleton ℝ x).coe_fn_comp_Lp _, end lemma condexp_L2_indicator_eq_to_span_singleton_comp (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') : (condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) : α →₂[μ] E') = (to_span_singleton ℝ x).comp_Lp (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ))) := begin ext1, rw ← Lp_meas_coe, refine (condexp_L2_indicator_ae_eq_smul 𝕜 hm hs hμs x).trans _, have h_comp := (to_span_singleton ℝ x).coe_fn_comp_Lp (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) : α →₂[μ] ℝ), rw ← eventually_eq at h_comp, refine eventually_eq.trans _ h_comp.symm, refine eventually_of_forall (λ y, _), refl, end variables {𝕜} lemma set_lintegral_nnnorm_condexp_L2_indicator_le (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') {t : set α} (ht : @measurable_set _ m t) (hμt : μ t ≠ ∞) : ∫⁻ a in t, ∥condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) a∥₊ ∂μ ≤ μ (s ∩ t) * ∥x∥₊ := calc ∫⁻ a in t, ∥condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) a∥₊ ∂μ = ∫⁻ a in t, ∥(condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a) • x∥₊ ∂μ : set_lintegral_congr_fun (hm t ht) ((condexp_L2_indicator_ae_eq_smul 𝕜 hm hs hμs x).mono (λ a ha hat, by rw ha)) ... = ∫⁻ a in t, ∥condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a∥₊ ∂μ * ∥x∥₊ : begin simp_rw [nnnorm_smul, ennreal.coe_mul], rw [lintegral_mul_const, Lp_meas_coe], exact (Lp.measurable _).nnnorm.coe_nnreal_ennreal, end ... ≤ μ (s ∩ t) * ∥x∥₊ : ennreal.mul_le_mul (lintegral_nnnorm_condexp_L2_indicator_le_real hs hμs ht hμt) le_rfl lemma lintegral_nnnorm_condexp_L2_indicator_le (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') [sigma_finite (μ.trim hm)] : ∫⁻ a, ∥condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x) a∥₊ ∂μ ≤ μ s * ∥x∥₊ := begin refine lintegral_le_of_forall_fin_meas_le' hm (μ s * ∥x∥₊) _ (λ t ht hμt, _), { rw Lp_meas_coe, exact (Lp.ae_measurable _).nnnorm.coe_nnreal_ennreal, }, refine (set_lintegral_nnnorm_condexp_L2_indicator_le hm hs hμs x ht hμt).trans _, refine ennreal.mul_le_mul _ le_rfl, exact measure_mono (set.inter_subset_left _ _), end /-- If the measure `μ.trim hm` is sigma-finite, then the conditional expectation of a measurable set with finite measure is integrable. -/ lemma integrable_condexp_L2_indicator (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : E') : integrable (condexp_L2 𝕜 hm (indicator_const_Lp 2 hs hμs x)) μ := begin refine integrable_of_forall_fin_meas_le' hm (μ s * ∥x∥₊) (ennreal.mul_lt_top hμs ennreal.coe_ne_top) _ _, { rw Lp_meas_coe, exact Lp.ae_measurable _, }, { refine λ t ht hμt, (set_lintegral_nnnorm_condexp_L2_indicator_le hm hs hμs x ht hμt).trans _, exact ennreal.mul_le_mul (measure_mono (set.inter_subset_left _ _)) le_rfl, }, end end condexp_L2_indicator section condexp_ind_smul variables [normed_space ℝ G] {hm : m ≤ m0} /-- Conditional expectation of the indicator of a measurable set with finite measure, in L2. -/ def condexp_ind_smul (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : Lp G 2 μ := (to_span_singleton ℝ x).comp_LpL 2 μ (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ))) lemma ae_measurable'_condexp_ind_smul (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : ae_measurable' m (condexp_ind_smul hm hs hμs x) μ := begin have h : ae_measurable' m (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ))) μ, from ae_measurable'_condexp_L2 _ _, rw condexp_ind_smul, suffices : ae_measurable' m ((to_span_singleton ℝ x) ∘ (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)))) μ, { refine ae_measurable'.congr this _, refine eventually_eq.trans _ (coe_fn_comp_LpL _ _).symm, rw Lp_meas_coe, }, exact ae_measurable'.measurable_comp (to_span_singleton ℝ x).measurable h, end lemma condexp_ind_smul_add (hs : measurable_set s) (hμs : μ s ≠ ∞) (x y : G) : condexp_ind_smul hm hs hμs (x + y) = condexp_ind_smul hm hs hμs x + condexp_ind_smul hm hs hμs y := by { simp_rw [condexp_ind_smul], rw [to_span_singleton_add, add_comp_LpL, add_apply], } lemma condexp_ind_smul_smul (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : ℝ) (x : G) : condexp_ind_smul hm hs hμs (c • x) = c • condexp_ind_smul hm hs hμs x := by { simp_rw [condexp_ind_smul], rw [to_span_singleton_smul, smul_comp_LpL, smul_apply], } lemma condexp_ind_smul_smul' [normed_space ℝ F] [smul_comm_class ℝ 𝕜 F] (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : 𝕜) (x : F) : condexp_ind_smul hm hs hμs (c • x) = c • condexp_ind_smul hm hs hμs x := by rw [condexp_ind_smul, condexp_ind_smul, to_span_singleton_smul', (to_span_singleton ℝ x).smul_comp_LpL_apply c ↑(condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)))] lemma condexp_ind_smul_ae_eq_smul (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : condexp_ind_smul hm hs hμs x =ᵐ[μ] λ a, (condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a) • x := (to_span_singleton ℝ x).coe_fn_comp_LpL _ lemma set_lintegral_nnnorm_condexp_ind_smul_le (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) {t : set α} (ht : @measurable_set _ m t) (hμt : μ t ≠ ∞) : ∫⁻ a in t, ∥condexp_ind_smul hm hs hμs x a∥₊ ∂μ ≤ μ (s ∩ t) * ∥x∥₊ := calc ∫⁻ a in t, ∥condexp_ind_smul hm hs hμs x a∥₊ ∂μ = ∫⁻ a in t, ∥condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a • x∥₊ ∂μ : set_lintegral_congr_fun (hm t ht) ((condexp_ind_smul_ae_eq_smul hm hs hμs x).mono (λ a ha hat, by rw ha )) ... = ∫⁻ a in t, ∥condexp_L2 ℝ hm (indicator_const_Lp 2 hs hμs (1 : ℝ)) a∥₊ ∂μ * ∥x∥₊ : begin simp_rw [nnnorm_smul, ennreal.coe_mul], rw [lintegral_mul_const, Lp_meas_coe], exact (Lp.measurable _).nnnorm.coe_nnreal_ennreal, end ... ≤ μ (s ∩ t) * ∥x∥₊ : ennreal.mul_le_mul (lintegral_nnnorm_condexp_L2_indicator_le_real hs hμs ht hμt) le_rfl lemma lintegral_nnnorm_condexp_ind_smul_le (hm : m ≤ m0) (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) [sigma_finite (μ.trim hm)] : ∫⁻ a, ∥condexp_ind_smul hm hs hμs x a∥₊ ∂μ ≤ μ s * ∥x∥₊ := begin refine lintegral_le_of_forall_fin_meas_le' hm (μ s * ∥x∥₊) _ (λ t ht hμt, _), { exact (Lp.ae_measurable _).nnnorm.coe_nnreal_ennreal, }, refine (set_lintegral_nnnorm_condexp_ind_smul_le hm hs hμs x ht hμt).trans _, refine ennreal.mul_le_mul _ le_rfl, exact measure_mono (set.inter_subset_left _ _), end /-- If the measure `μ.trim hm` is sigma-finite, then the conditional expectation of a measurable set with finite measure is integrable. -/ lemma integrable_condexp_ind_smul (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : integrable (condexp_ind_smul hm hs hμs x) μ := begin refine integrable_of_forall_fin_meas_le' hm (μ s * ∥x∥₊) (ennreal.mul_lt_top hμs ennreal.coe_ne_top) _ _, { exact Lp.ae_measurable _, }, { refine λ t ht hμt, (set_lintegral_nnnorm_condexp_ind_smul_le hm hs hμs x ht hμt).trans _, exact ennreal.mul_le_mul (measure_mono (set.inter_subset_left _ _)) le_rfl, }, end lemma condexp_ind_smul_empty {x : G} : condexp_ind_smul hm measurable_set.empty ((@measure_empty _ _ μ).le.trans_lt ennreal.coe_lt_top).ne x = 0 := begin rw [condexp_ind_smul, indicator_const_empty], simp only [coe_fn_coe_base, submodule.coe_zero, continuous_linear_map.map_zero], end lemma set_integral_condexp_ind_smul (hs : measurable_set[m] s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (x : G') : ∫ a in s, (condexp_ind_smul hm ht hμt x) a ∂μ = (μ (t ∩ s)).to_real • x := calc ∫ a in s, (condexp_ind_smul hm ht hμt x) a ∂μ = (∫ a in s, (condexp_L2 ℝ hm (indicator_const_Lp 2 ht hμt (1 : ℝ)) a • x) ∂μ) : set_integral_congr_ae (hm s hs) ((condexp_ind_smul_ae_eq_smul hm ht hμt x).mono (λ x hx hxs, hx)) ... = (∫ a in s, condexp_L2 ℝ hm (indicator_const_Lp 2 ht hμt (1 : ℝ)) a ∂μ) • x : by rw integral_smul_const _ x ... = (∫ a in s, indicator_const_Lp 2 ht hμt (1 : ℝ) a ∂μ) • x : by rw @integral_condexp_L2_eq α _ ℝ _ _ _ _ _ _ _ _ _ _ _ _ _ _ hm (indicator_const_Lp 2 ht hμt (1 : ℝ)) hs hμs ... = (μ (t ∩ s)).to_real • x : by rw [set_integral_indicator_const_Lp (hm s hs), smul_assoc, one_smul] end condexp_ind_smul end condexp_L2 section condexp_ind /-! ## Conditional expectation of an indicator as a condinuous linear map. The goal of this section is to build `condexp_ind (hm : m ≤ m0) (μ : measure α) (s : set s) : G →L[ℝ] α →₁[μ] G`, which takes `x : G` to the conditional expectation of the indicator of the set `s` with value `x`, seen as an element of `α →₁[μ] G`. -/ local attribute [instance] fact_one_le_two_ennreal variables {m m0 : measurable_space α} {μ : measure α} [borel_space 𝕜] [is_scalar_tower ℝ 𝕜 E'] {s t : set α} [normed_space ℝ G] section condexp_ind_L1_fin /-- Conditional expectation of the indicator of a measurable set with finite measure, as a function in L1. -/ def condexp_ind_L1_fin (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : α →₁[μ] G := (integrable_condexp_ind_smul hm hs hμs x).to_L1 _ lemma condexp_ind_L1_fin_ae_eq_condexp_ind_smul (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : condexp_ind_L1_fin hm hs hμs x =ᵐ[μ] condexp_ind_smul hm hs hμs x := (integrable_condexp_ind_smul hm hs hμs x).coe_fn_to_L1 variables {hm : m ≤ m0} [sigma_finite (μ.trim hm)] lemma condexp_ind_L1_fin_add (hs : measurable_set s) (hμs : μ s ≠ ∞) (x y : G) : condexp_ind_L1_fin hm hs hμs (x + y) = condexp_ind_L1_fin hm hs hμs x + condexp_ind_L1_fin hm hs hμs y := begin ext1, refine (mem_ℒp.coe_fn_to_Lp _).trans _, refine eventually_eq.trans _ (Lp.coe_fn_add _ _).symm, refine eventually_eq.trans _ (eventually_eq.add (mem_ℒp.coe_fn_to_Lp _).symm (mem_ℒp.coe_fn_to_Lp _).symm), rw condexp_ind_smul_add, refine (Lp.coe_fn_add _ _).trans (eventually_of_forall (λ a, _)), refl, end lemma condexp_ind_L1_fin_smul (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : ℝ) (x : G) : condexp_ind_L1_fin hm hs hμs (c • x) = c • condexp_ind_L1_fin hm hs hμs x := begin ext1, refine (mem_ℒp.coe_fn_to_Lp _).trans _, refine eventually_eq.trans _ (Lp.coe_fn_smul _ _).symm, rw condexp_ind_smul_smul hs hμs c x, refine (Lp.coe_fn_smul _ _).trans _, refine (condexp_ind_L1_fin_ae_eq_condexp_ind_smul hm hs hμs x).mono (λ y hy, _), rw [pi.smul_apply, pi.smul_apply, hy], end lemma condexp_ind_L1_fin_smul' [normed_space ℝ F] [smul_comm_class ℝ 𝕜 F] (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : 𝕜) (x : F) : condexp_ind_L1_fin hm hs hμs (c • x) = c • condexp_ind_L1_fin hm hs hμs x := begin ext1, refine (mem_ℒp.coe_fn_to_Lp _).trans _, refine eventually_eq.trans _ (Lp.coe_fn_smul _ _).symm, rw condexp_ind_smul_smul' hs hμs c x, refine (Lp.coe_fn_smul _ _).trans _, refine (condexp_ind_L1_fin_ae_eq_condexp_ind_smul hm hs hμs x).mono (λ y hy, _), rw [pi.smul_apply, pi.smul_apply, hy], end lemma norm_condexp_ind_L1_fin_le (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : ∥condexp_ind_L1_fin hm hs hμs x∥ ≤ (μ s).to_real * ∥x∥ := begin have : 0 ≤ ∫ (a : α), ∥condexp_ind_L1_fin hm hs hμs x a∥ ∂μ, from integral_nonneg (λ a, norm_nonneg _), rw [L1.norm_eq_integral_norm, ← ennreal.to_real_of_real (norm_nonneg x), ← ennreal.to_real_mul, ← ennreal.to_real_of_real this, ennreal.to_real_le_to_real ennreal.of_real_ne_top (ennreal.mul_ne_top hμs ennreal.of_real_ne_top), of_real_integral_norm_eq_lintegral_nnnorm], swap, { rw [← mem_ℒp_one_iff_integrable], exact Lp.mem_ℒp _, }, have h_eq : ∫⁻ a, ∥condexp_ind_L1_fin hm hs hμs x a∥₊ ∂μ = ∫⁻ a, nnnorm (condexp_ind_smul hm hs hμs x a) ∂μ, { refine lintegral_congr_ae _, refine (condexp_ind_L1_fin_ae_eq_condexp_ind_smul hm hs hμs x).mono (λ z hz, _), dsimp only, rw hz, }, rw [h_eq, of_real_norm_eq_coe_nnnorm], exact lintegral_nnnorm_condexp_ind_smul_le hm hs hμs x, end lemma condexp_ind_L1_fin_disjoint_union (hs : measurable_set s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (hst : s ∩ t = ∅) (x : G) : condexp_ind_L1_fin hm (hs.union ht) ((measure_union_le s t).trans_lt (lt_top_iff_ne_top.mpr (ennreal.add_ne_top.mpr ⟨hμs, hμt⟩))).ne x = condexp_ind_L1_fin hm hs hμs x + condexp_ind_L1_fin hm ht hμt x := begin ext1, have hμst := ((measure_union_le s t).trans_lt (lt_top_iff_ne_top.mpr (ennreal.add_ne_top.mpr ⟨hμs, hμt⟩))).ne, refine (condexp_ind_L1_fin_ae_eq_condexp_ind_smul hm (hs.union ht) hμst x).trans _, refine eventually_eq.trans _ (Lp.coe_fn_add _ _).symm, have hs_eq := condexp_ind_L1_fin_ae_eq_condexp_ind_smul hm hs hμs x, have ht_eq := condexp_ind_L1_fin_ae_eq_condexp_ind_smul hm ht hμt x, refine eventually_eq.trans _ (eventually_eq.add hs_eq.symm ht_eq.symm), rw condexp_ind_smul, rw indicator_const_Lp_disjoint_union hs ht hμs hμt hst (1 : ℝ), rw (condexp_L2 ℝ hm).map_add, push_cast, rw ((to_span_singleton ℝ x).comp_LpL 2 μ).map_add, refine (Lp.coe_fn_add _ _).trans _, refine eventually_of_forall (λ y, _), refl, end end condexp_ind_L1_fin open_locale classical section condexp_ind_L1 /-- Conditional expectation of the indicator of a set, as a function in L1. Its value for sets which are not both measurable and of finite measure is not used: we set it to 0. -/ def condexp_ind_L1 {m m0 : measurable_space α} (hm : m ≤ m0) (μ : measure α) (s : set α) [sigma_finite (μ.trim hm)] (x : G) : α →₁[μ] G := if hs : measurable_set s ∧ μ s ≠ ∞ then condexp_ind_L1_fin hm hs.1 hs.2 x else 0 variables {hm : m ≤ m0} [sigma_finite (μ.trim hm)] lemma condexp_ind_L1_of_measurable_set_of_measure_ne_top (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : condexp_ind_L1 hm μ s x = condexp_ind_L1_fin hm hs hμs x := by simp only [condexp_ind_L1, and.intro hs hμs, dif_pos, ne.def, not_false_iff, and_self] lemma condexp_ind_L1_of_measure_eq_top (hμs : μ s = ∞) (x : G) : condexp_ind_L1 hm μ s x = 0 := by simp only [condexp_ind_L1, hμs, eq_self_iff_true, not_true, ne.def, dif_neg, not_false_iff, and_false] lemma condexp_ind_L1_of_not_measurable_set (hs : ¬ measurable_set s) (x : G) : condexp_ind_L1 hm μ s x = 0 := by simp only [condexp_ind_L1, hs, dif_neg, not_false_iff, false_and] lemma condexp_ind_L1_add (x y : G) : condexp_ind_L1 hm μ s (x + y) = condexp_ind_L1 hm μ s x + condexp_ind_L1 hm μ s y := begin by_cases hs : measurable_set s, swap, {simp_rw condexp_ind_L1_of_not_measurable_set hs, rw zero_add, }, by_cases hμs : μ s = ∞, { simp_rw condexp_ind_L1_of_measure_eq_top hμs, rw zero_add, }, { simp_rw condexp_ind_L1_of_measurable_set_of_measure_ne_top hs hμs, exact condexp_ind_L1_fin_add hs hμs x y, }, end lemma condexp_ind_L1_smul (c : ℝ) (x : G) : condexp_ind_L1 hm μ s (c • x) = c • condexp_ind_L1 hm μ s x := begin by_cases hs : measurable_set s, swap, {simp_rw condexp_ind_L1_of_not_measurable_set hs, rw smul_zero, }, by_cases hμs : μ s = ∞, { simp_rw condexp_ind_L1_of_measure_eq_top hμs, rw smul_zero, }, { simp_rw condexp_ind_L1_of_measurable_set_of_measure_ne_top hs hμs, exact condexp_ind_L1_fin_smul hs hμs c x, }, end lemma condexp_ind_L1_smul' [normed_space ℝ F] [smul_comm_class ℝ 𝕜 F] (c : 𝕜) (x : F) : condexp_ind_L1 hm μ s (c • x) = c • condexp_ind_L1 hm μ s x := begin by_cases hs : measurable_set s, swap, {simp_rw condexp_ind_L1_of_not_measurable_set hs, rw smul_zero, }, by_cases hμs : μ s = ∞, { simp_rw condexp_ind_L1_of_measure_eq_top hμs, rw smul_zero, }, { simp_rw condexp_ind_L1_of_measurable_set_of_measure_ne_top hs hμs, exact condexp_ind_L1_fin_smul' hs hμs c x, }, end lemma norm_condexp_ind_L1_le (x : G) : ∥condexp_ind_L1 hm μ s x∥ ≤ (μ s).to_real * ∥x∥ := begin by_cases hs : measurable_set s, swap, {simp_rw condexp_ind_L1_of_not_measurable_set hs, rw Lp.norm_zero, exact mul_nonneg ennreal.to_real_nonneg (norm_nonneg _), }, by_cases hμs : μ s = ∞, { rw [condexp_ind_L1_of_measure_eq_top hμs x, Lp.norm_zero], exact mul_nonneg ennreal.to_real_nonneg (norm_nonneg _), }, { rw condexp_ind_L1_of_measurable_set_of_measure_ne_top hs hμs x, exact norm_condexp_ind_L1_fin_le hs hμs x, }, end lemma continuous_condexp_ind_L1 : continuous (λ x : G, condexp_ind_L1 hm μ s x) := continuous_of_linear_of_bound condexp_ind_L1_add condexp_ind_L1_smul norm_condexp_ind_L1_le lemma condexp_ind_L1_disjoint_union (hs : measurable_set s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (hst : s ∩ t = ∅) (x : G) : condexp_ind_L1 hm μ (s ∪ t) x = condexp_ind_L1 hm μ s x + condexp_ind_L1 hm μ t x := begin have hμst : μ (s ∪ t) ≠ ∞, from ((measure_union_le s t).trans_lt (lt_top_iff_ne_top.mpr (ennreal.add_ne_top.mpr ⟨hμs, hμt⟩))).ne, rw [condexp_ind_L1_of_measurable_set_of_measure_ne_top hs hμs x, condexp_ind_L1_of_measurable_set_of_measure_ne_top ht hμt x, condexp_ind_L1_of_measurable_set_of_measure_ne_top (hs.union ht) hμst x], exact condexp_ind_L1_fin_disjoint_union hs ht hμs hμt hst x, end end condexp_ind_L1 /-- Conditional expectation of the indicator of a set, as a linear map from `G` to L1. -/ def condexp_ind {m m0 : measurable_space α} (hm : m ≤ m0) (μ : measure α) [sigma_finite (μ.trim hm)] (s : set α) : G →L[ℝ] α →₁[μ] G := { to_fun := condexp_ind_L1 hm μ s, map_add' := condexp_ind_L1_add, map_smul' := condexp_ind_L1_smul, cont := continuous_condexp_ind_L1, } lemma condexp_ind_ae_eq_condexp_ind_smul (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : condexp_ind hm μ s x =ᵐ[μ] condexp_ind_smul hm hs hμs x := begin refine eventually_eq.trans _ (condexp_ind_L1_fin_ae_eq_condexp_ind_smul hm hs hμs x), simp [condexp_ind, condexp_ind_L1, hs, hμs], end variables {hm : m ≤ m0} [sigma_finite (μ.trim hm)] lemma ae_measurable'_condexp_ind (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : G) : ae_measurable' m (condexp_ind hm μ s x) μ := ae_measurable'.congr (ae_measurable'_condexp_ind_smul hm hs hμs x) (condexp_ind_ae_eq_condexp_ind_smul hm hs hμs x).symm @[simp] lemma condexp_ind_empty : condexp_ind hm μ ∅ = (0 : G →L[ℝ] α →₁[μ] G) := begin ext1, ext1, refine (condexp_ind_ae_eq_condexp_ind_smul hm measurable_set.empty (by simp) x).trans _, rw condexp_ind_smul_empty, refine (Lp.coe_fn_zero G 2 μ).trans _, refine eventually_eq.trans _ (Lp.coe_fn_zero G 1 μ).symm, refl, end lemma condexp_ind_smul' [normed_space ℝ F] [smul_comm_class ℝ 𝕜 F] (c : 𝕜) (x : F) : condexp_ind hm μ s (c • x) = c • condexp_ind hm μ s x := condexp_ind_L1_smul' c x lemma norm_condexp_ind_apply_le (x : G) : ∥condexp_ind hm μ s x∥ ≤ (μ s).to_real * ∥x∥ := norm_condexp_ind_L1_le x lemma norm_condexp_ind_le : ∥(condexp_ind hm μ s : G →L[ℝ] α →₁[μ] G)∥ ≤ (μ s).to_real := continuous_linear_map.op_norm_le_bound _ ennreal.to_real_nonneg norm_condexp_ind_apply_le lemma condexp_ind_disjoint_union_apply (hs : measurable_set s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (hst : s ∩ t = ∅) (x : G) : condexp_ind hm μ (s ∪ t) x = condexp_ind hm μ s x + condexp_ind hm μ t x := condexp_ind_L1_disjoint_union hs ht hμs hμt hst x lemma condexp_ind_disjoint_union (hs : measurable_set s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (hst : s ∩ t = ∅) : (condexp_ind hm μ (s ∪ t) : G →L[ℝ] α →₁[μ] G) = condexp_ind hm μ s + condexp_ind hm μ t := by { ext1, push_cast, exact condexp_ind_disjoint_union_apply hs ht hμs hμt hst x, } variables (G) lemma dominated_fin_meas_additive_condexp_ind (hm : m ≤ m0) (μ : measure α) [sigma_finite (μ.trim hm)] : dominated_fin_meas_additive μ (condexp_ind hm μ : set α → G →L[ℝ] α →₁[μ] G) 1 := ⟨λ s t, condexp_ind_disjoint_union, λ s, norm_condexp_ind_le.trans (one_mul _).symm.le⟩ variables {G} lemma set_integral_condexp_ind (hs : measurable_set[m] s) (ht : measurable_set t) (hμs : μ s ≠ ∞) (hμt : μ t ≠ ∞) (x : G') : ∫ a in s, condexp_ind hm μ t x a ∂μ = (μ (t ∩ s)).to_real • x := calc ∫ a in s, condexp_ind hm μ t x a ∂μ = ∫ a in s, condexp_ind_smul hm ht hμt x a ∂μ : set_integral_congr_ae (hm s hs) ((condexp_ind_ae_eq_condexp_ind_smul hm ht hμt x).mono (λ x hx hxs, hx)) ... = (μ (t ∩ s)).to_real • x : set_integral_condexp_ind_smul hs ht hμs hμt x lemma condexp_ind_of_measurable (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) (c : G) : condexp_ind hm μ s c = indicator_const_Lp 1 (hm s hs) hμs c := begin ext1, refine eventually_eq.trans _ indicator_const_Lp_coe_fn.symm, refine (condexp_ind_ae_eq_condexp_ind_smul hm (hm s hs) hμs c).trans _, refine (condexp_ind_smul_ae_eq_smul hm (hm s hs) hμs c).trans _, rw [Lp_meas_coe, condexp_L2_indicator_of_measurable hm hs hμs (1 : ℝ)], refine (@indicator_const_Lp_coe_fn α _ _ 2 μ _ _ s (hm s hs) hμs (1 : ℝ) _ _).mono (λ x hx, _), dsimp only, rw hx, by_cases hx_mem : x ∈ s; simp [hx_mem], end end condexp_ind section condexp_L1 local attribute [instance] fact_one_le_one_ennreal variables {m m0 : measurable_space α} {μ : measure α} [borel_space 𝕜] [is_scalar_tower ℝ 𝕜 F'] {hm : m ≤ m0} [sigma_finite (μ.trim hm)] {f g : α → F'} {s : set α} /-- Conditional expectation of a function as a linear map from `α →₁[μ] F'` to itself. -/ def condexp_L1_clm (hm : m ≤ m0) (μ : measure α) [sigma_finite (μ.trim hm)] : (α →₁[μ] F') →L[ℝ] α →₁[μ] F' := L1.set_to_L1 (dominated_fin_meas_additive_condexp_ind F' hm μ) lemma condexp_L1_clm_smul (c : 𝕜) (f : α →₁[μ] F') : condexp_L1_clm hm μ (c • f) = c • condexp_L1_clm hm μ f := L1.set_to_L1_smul (dominated_fin_meas_additive_condexp_ind F' hm μ) (λ c s x, condexp_ind_smul' c x) c f lemma condexp_L1_clm_indicator_const_Lp (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : F') : (condexp_L1_clm hm μ) (indicator_const_Lp 1 hs hμs x) = condexp_ind hm μ s x := L1.set_to_L1_indicator_const_Lp (dominated_fin_meas_additive_condexp_ind F' hm μ) hs hμs x lemma condexp_L1_clm_indicator_const (hs : measurable_set s) (hμs : μ s ≠ ∞) (x : F') : (condexp_L1_clm hm μ) ↑(simple_func.indicator_const 1 hs hμs x) = condexp_ind hm μ s x := by { rw Lp.simple_func.coe_indicator_const, exact condexp_L1_clm_indicator_const_Lp hs hμs x, } /-- Auxiliary lemma used in the proof of `set_integral_condexp_L1_clm`. -/ lemma set_integral_condexp_L1_clm_of_measure_ne_top (f : α →₁[μ] F') (hs : measurable_set[m] s) (hμs : μ s ≠ ∞) : ∫ x in s, condexp_L1_clm hm μ f x ∂μ = ∫ x in s, f x ∂μ := begin refine Lp.induction ennreal.one_ne_top (λ f : α →₁[μ] F', ∫ x in s, condexp_L1_clm hm μ f x ∂μ = ∫ x in s, f x ∂μ) _ _ (is_closed_eq _ _) f, { intros x t ht hμt, simp_rw condexp_L1_clm_indicator_const ht hμt.ne x, rw [Lp.simple_func.coe_indicator_const, set_integral_indicator_const_Lp (hm _ hs)], exact set_integral_condexp_ind hs ht hμs hμt.ne x, }, { intros f g hf_Lp hg_Lp hfg_disj hf hg, simp_rw (condexp_L1_clm hm μ).map_add, rw set_integral_congr_ae (hm s hs) ((Lp.coe_fn_add (condexp_L1_clm hm μ (hf_Lp.to_Lp f)) (condexp_L1_clm hm μ (hg_Lp.to_Lp g))).mono (λ x hx hxs, hx)), rw set_integral_congr_ae (hm s hs) ((Lp.coe_fn_add (hf_Lp.to_Lp f) (hg_Lp.to_Lp g)).mono (λ x hx hxs, hx)), simp_rw pi.add_apply, rw [integral_add (L1.integrable_coe_fn _).integrable_on (L1.integrable_coe_fn _).integrable_on, integral_add (L1.integrable_coe_fn _).integrable_on (L1.integrable_coe_fn _).integrable_on, hf, hg], }, { exact (continuous_set_integral s).comp (condexp_L1_clm hm μ).continuous, }, { exact continuous_set_integral s, }, end /-- The integral of the conditional expectation `condexp_L1_clm` over an `m`-measurable set is equal to the integral of `f` on that set. See also `set_integral_condexp`, the similar statement for `condexp`. -/ lemma set_integral_condexp_L1_clm (f : α →₁[μ] F') (hs : measurable_set[m] s) : ∫ x in s, condexp_L1_clm hm μ f x ∂μ = ∫ x in s, f x ∂μ := begin let S := spanning_sets (μ.trim hm), have hS_meas : ∀ i, measurable_set[m] (S i) := measurable_spanning_sets (μ.trim hm), have hS_meas0 : ∀ i, measurable_set (S i) := λ i, hm _ (hS_meas i), have hs_eq : s = ⋃ i, S i ∩ s, { simp_rw set.inter_comm, rw [← set.inter_Union, (Union_spanning_sets (μ.trim hm)), set.inter_univ], }, have hS_finite : ∀ i, μ (S i ∩ s) < ∞, { refine λ i, (measure_mono (set.inter_subset_left _ _)).trans_lt _, have hS_finite_trim := measure_spanning_sets_lt_top (μ.trim hm) i, rwa trim_measurable_set_eq hm (hS_meas i) at hS_finite_trim, }, have h_mono : monotone (λ i, (S i) ∩ s), { intros i j hij x, simp_rw set.mem_inter_iff, exact λ h, ⟨monotone_spanning_sets (μ.trim hm) hij h.1, h.2⟩, }, have h_eq_forall : (λ i, ∫ x in (S i) ∩ s, condexp_L1_clm hm μ f x ∂μ) = λ i, ∫ x in (S i) ∩ s, f x ∂μ, from funext (λ i, set_integral_condexp_L1_clm_of_measure_ne_top f (@measurable_set.inter α m _ _ (hS_meas i) hs) (hS_finite i).ne), have h_right : tendsto (λ i, ∫ x in (S i) ∩ s, f x ∂μ) at_top (𝓝 (∫ x in s, f x ∂μ)), { have h := tendsto_set_integral_of_monotone (λ i, (hS_meas0 i).inter (hm s hs)) h_mono (L1.integrable_coe_fn f).integrable_on, rwa ← hs_eq at h, }, have h_left : tendsto (λ i, ∫ x in (S i) ∩ s, condexp_L1_clm hm μ f x ∂μ) at_top (𝓝 (∫ x in s, condexp_L1_clm hm μ f x ∂μ)), { have h := tendsto_set_integral_of_monotone (λ i, (hS_meas0 i).inter (hm s hs)) h_mono (L1.integrable_coe_fn (condexp_L1_clm hm μ f)).integrable_on, rwa ← hs_eq at h, }, rw h_eq_forall at h_left, exact tendsto_nhds_unique h_left h_right, end lemma ae_measurable'_condexp_L1_clm (f : α →₁[μ] F') : ae_measurable' m (condexp_L1_clm hm μ f) μ := begin refine Lp.induction ennreal.one_ne_top (λ f : α →₁[μ] F', ae_measurable' m (condexp_L1_clm hm μ f) μ) _ _ _ f, { intros c s hs hμs, rw condexp_L1_clm_indicator_const hs hμs.ne c, exact ae_measurable'_condexp_ind hs hμs.ne c, }, { intros f g hf hg h_disj hfm hgm, rw (condexp_L1_clm hm μ).map_add, refine ae_measurable'.congr _ (coe_fn_add _ _).symm, exact ae_measurable'.add hfm hgm, }, { have : {f : Lp F' 1 μ | ae_measurable' m (condexp_L1_clm hm μ f) μ} = (condexp_L1_clm hm μ) ⁻¹' {f | ae_measurable' m f μ}, by refl, rw this, refine is_closed.preimage (condexp_L1_clm hm μ).continuous _, exact is_closed_ae_measurable' hm, }, end lemma Lp_meas_to_Lp_trim_lie_symm_indicator [normed_space ℝ F] {μ : measure α} (hs : measurable_set[m] s) (hμs : μ.trim hm s ≠ ∞) (c : F) : ((Lp_meas_to_Lp_trim_lie F ℝ 1 μ hm).symm (indicator_const_Lp 1 hs hμs c) : α →₁[μ] F) = indicator_const_Lp 1 (hm s hs) ((le_trim hm).trans_lt hμs.lt_top).ne c := begin ext1, rw ← Lp_meas_coe, change Lp_trim_to_Lp_meas F ℝ 1 μ hm (indicator_const_Lp 1 hs hμs c) =ᵐ[μ] (indicator_const_Lp 1 _ _ c : α → F), refine (Lp_trim_to_Lp_meas_ae_eq hm _).trans _, exact (ae_eq_of_ae_eq_trim indicator_const_Lp_coe_fn).trans indicator_const_Lp_coe_fn.symm, end lemma condexp_L1_clm_Lp_meas (f : Lp_meas F' ℝ m 1 μ) : condexp_L1_clm hm μ (f : α →₁[μ] F') = ↑f := begin let g := Lp_meas_to_Lp_trim_lie F' ℝ 1 μ hm f, have hfg : f = (Lp_meas_to_Lp_trim_lie F' ℝ 1 μ hm).symm g, by simp only [linear_isometry_equiv.symm_apply_apply], rw hfg, refine @Lp.induction α F' m _ _ _ _ 1 (μ.trim hm) _ ennreal.coe_ne_top (λ g : α →₁[μ.trim hm] F', condexp_L1_clm hm μ ((Lp_meas_to_Lp_trim_lie F' ℝ 1 μ hm).symm g : α →₁[μ] F') = ↑((Lp_meas_to_Lp_trim_lie F' ℝ 1 μ hm).symm g)) _ _ _ g, { intros c s hs hμs, rw [Lp.simple_func.coe_indicator_const, Lp_meas_to_Lp_trim_lie_symm_indicator hs hμs.ne c, condexp_L1_clm_indicator_const_Lp], exact condexp_ind_of_measurable hs ((le_trim hm).trans_lt hμs).ne c, }, { intros f g hf hg hfg_disj hf_eq hg_eq, rw linear_isometry_equiv.map_add, push_cast, rw [map_add, hf_eq, hg_eq], }, { refine is_closed_eq _ _, { refine (condexp_L1_clm hm μ).continuous.comp (continuous_induced_dom.comp _), exact linear_isometry_equiv.continuous _, }, { refine continuous_induced_dom.comp _, exact linear_isometry_equiv.continuous _, }, }, end lemma condexp_L1_clm_of_ae_measurable' (f : α →₁[μ] F') (hfm : ae_measurable' m f μ) : condexp_L1_clm hm μ f = f := condexp_L1_clm_Lp_meas (⟨f, hfm⟩ : Lp_meas F' ℝ m 1 μ) /-- Conditional expectation of a function, in L1. Its value is 0 if the function is not integrable. The function-valued `condexp` should be used instead in most cases. -/ def condexp_L1 (hm : m ≤ m0) (μ : measure α) [sigma_finite (μ.trim hm)] (f : α → F') : α →₁[μ] F' := set_to_fun (dominated_fin_meas_additive_condexp_ind F' hm μ) f lemma condexp_L1_undef (hf : ¬ integrable f μ) : condexp_L1 hm μ f = 0 := set_to_fun_undef (dominated_fin_meas_additive_condexp_ind F' hm μ) hf lemma condexp_L1_eq (hf : integrable f μ) : condexp_L1 hm μ f = condexp_L1_clm hm μ (hf.to_L1 f) := set_to_fun_eq (dominated_fin_meas_additive_condexp_ind F' hm μ) hf lemma condexp_L1_zero : condexp_L1 hm μ (0 : α → F') = 0 := begin refine (condexp_L1_eq (integrable_zero _ _ _)).trans _, change (condexp_L1_clm hm μ) (integrable.to_L1 0 _) = 0, rw [integrable.to_L1_zero, continuous_linear_map.map_zero], end lemma ae_measurable'_condexp_L1 {f : α → F'} : ae_measurable' m (condexp_L1 hm μ f) μ := begin by_cases hf : integrable f μ, { rw condexp_L1_eq hf, exact ae_measurable'_condexp_L1_clm _, }, { rw condexp_L1_undef hf, refine ae_measurable'.congr _ (coe_fn_zero _ _ _).symm, exact measurable.ae_measurable' (@measurable_zero _ _ _ m _), }, end lemma integrable_condexp_L1 (f : α → F') : integrable (condexp_L1 hm μ f) μ := L1.integrable_coe_fn _ /-- The integral of the conditional expectation `condexp_L1` over an `m`-measurable set is equal to the integral of `f` on that set. See also `set_integral_condexp`, the similar statement for `condexp`. -/ lemma set_integral_condexp_L1 (hf : integrable f μ) (hs : measurable_set[m] s) : ∫ x in s, condexp_L1 hm μ f x ∂μ = ∫ x in s, f x ∂μ := begin simp_rw condexp_L1_eq hf, rw set_integral_condexp_L1_clm (hf.to_L1 f) hs, exact set_integral_congr_ae (hm s hs) ((hf.coe_fn_to_L1).mono (λ x hx hxs, hx)), end lemma condexp_L1_add (hf : integrable f μ) (hg : integrable g μ) : condexp_L1 hm μ (f + g) = condexp_L1 hm μ f + condexp_L1 hm μ g := calc condexp_L1 hm μ (f + g) = condexp_L1_clm hm μ ((hf.add hg).to_L1 (f + g)) : condexp_L1_eq (hf.add hg) ... = condexp_L1_clm hm μ (hf.to_L1 f + hg.to_L1 g) : by rw integrable.to_L1_add _ _ hf hg ... = condexp_L1_clm hm μ (hf.to_L1 f) + condexp_L1_clm hm μ (hg.to_L1 g) : (condexp_L1_clm hm μ).map_add _ _ ... = condexp_L1 hm μ f + condexp_L1 hm μ g : by rw [condexp_L1_eq hf, condexp_L1_eq hg] lemma condexp_L1_neg (f : α → F') : condexp_L1 hm μ (-f) = - condexp_L1 hm μ f := begin by_cases hf : integrable f μ, { calc condexp_L1 hm μ (-f) = condexp_L1_clm hm μ (hf.neg.to_L1 (-f)) : condexp_L1_eq hf.neg ... = condexp_L1_clm hm μ (- hf.to_L1 f) : by rw integrable.to_L1_neg _ hf ... = - condexp_L1_clm hm μ (hf.to_L1 f) : (condexp_L1_clm hm μ).map_neg _ ... = - condexp_L1 hm μ f : by rw condexp_L1_eq hf, }, { rw [condexp_L1_undef hf, condexp_L1_undef (mt integrable_neg_iff.mp hf), neg_zero], }, end lemma condexp_L1_smul (c : 𝕜) (f : α → F') : condexp_L1 hm μ (c • f) = c • condexp_L1 hm μ f := begin by_cases hf : integrable f μ, { calc condexp_L1 hm μ (c • f) = condexp_L1_clm hm μ ((hf.smul c).to_L1 (c • f)) : condexp_L1_eq (hf.smul c) ... = condexp_L1_clm hm μ (c • hf.to_L1 f) : by rw integrable.to_L1_smul' _ hf c ... = c • condexp_L1_clm hm μ (hf.to_L1 f) : condexp_L1_clm_smul c (hf.to_L1 f) ... = c • condexp_L1 hm μ f : by rw condexp_L1_eq hf, }, { by_cases hc : c = 0, { rw [hc, zero_smul, zero_smul, condexp_L1_zero], }, rw [condexp_L1_undef hf, condexp_L1_undef (mt (integrable_smul_iff hc f).mp hf), smul_zero], }, end lemma condexp_L1_sub (hf : integrable f μ) (hg : integrable g μ) : condexp_L1 hm μ (f - g) = condexp_L1 hm μ f - condexp_L1 hm μ g := by rw [sub_eq_add_neg, sub_eq_add_neg, condexp_L1_add hf hg.neg, condexp_L1_neg g] lemma condexp_L1_of_ae_measurable' (hfm : ae_measurable' m f μ) (hfi : integrable f μ) : condexp_L1 hm μ f =ᵐ[μ] f := begin rw condexp_L1_eq hfi, refine eventually_eq.trans _ (integrable.coe_fn_to_L1 hfi), rw condexp_L1_clm_of_ae_measurable', exact ae_measurable'.congr hfm (integrable.coe_fn_to_L1 hfi).symm, end end condexp_L1 section condexp /-! ### Conditional expectation of a function -/ open_locale classical local attribute [instance] fact_one_le_one_ennreal variables {𝕜} {m m0 : measurable_space α} {μ : measure α} [borel_space 𝕜] [is_scalar_tower ℝ 𝕜 F'] {hm : m ≤ m0} [sigma_finite (μ.trim hm)] {f g : α → F'} {s : set α} /-- Conditional expectation of a function. Its value is 0 if the function is not integrable. -/ @[irreducible] def condexp (hm : m ≤ m0) (μ : measure α) [sigma_finite (μ.trim hm)] (f : α → F') : α → F' := if (measurable[m] f ∧ integrable f μ) then f else ae_measurable'_condexp_L1.mk (condexp_L1 hm μ f) localized "notation μ `[` f `|` hm `]` := measure_theory.condexp hm μ f" in measure_theory lemma condexp_of_measurable {f : α → F'} (hf : measurable[m] f) (hfi : integrable f μ) : μ[f|hm] = f := by rw [condexp, if_pos (⟨hf, hfi⟩ : measurable[m] f ∧ integrable f μ)] lemma condexp_const (c : F') [is_finite_measure μ] : μ[(λ x : α, c)|hm] = λ _, c := condexp_of_measurable (@measurable_const _ _ _ m _) (integrable_const c) lemma condexp_ae_eq_condexp_L1 (f : α → F') : μ[f|hm] =ᵐ[μ] condexp_L1 hm μ f := begin unfold condexp, by_cases hfm : measurable[m] f, { by_cases hfi : integrable f μ, { rw if_pos (⟨hfm, hfi⟩ : measurable[m] f ∧ integrable f μ), exact (condexp_L1_of_ae_measurable' (measurable.ae_measurable' hfm) hfi).symm, }, { simp only [hfi, if_false, and_false], exact (ae_measurable'.ae_eq_mk ae_measurable'_condexp_L1).symm, }, }, simp only [hfm, if_false, false_and], exact (ae_measurable'.ae_eq_mk ae_measurable'_condexp_L1).symm, end lemma condexp_ae_eq_condexp_L1_clm (hf : integrable f μ) : μ[f|hm] =ᵐ[μ] condexp_L1_clm hm μ (hf.to_L1 f) := begin refine (condexp_ae_eq_condexp_L1 f).trans (eventually_of_forall (λ x, _)), rw condexp_L1_eq hf, end lemma condexp_undef (hf : ¬ integrable f μ) : μ[f|hm] =ᵐ[μ] 0 := begin refine (condexp_ae_eq_condexp_L1 f).trans (eventually_eq.trans _ (coe_fn_zero _ 1 _)), rw condexp_L1_undef hf, end @[simp] lemma condexp_zero : μ[(0 : α → F')|hm] = 0 := condexp_of_measurable (@measurable_zero _ _ _ m _) (integrable_zero _ _ _) lemma measurable_condexp : measurable[m] (μ[f|hm]) := begin unfold condexp, by_cases hfm : measurable[m] f, { by_cases hfi : integrable f μ, { rwa if_pos (⟨hfm, hfi⟩ : measurable[m] f ∧ integrable f μ), }, { simp only [hfi, if_false, and_false], exact ae_measurable'.measurable_mk _, }, }, simp only [hfm, if_false, false_and], exact ae_measurable'.measurable_mk _, end lemma integrable_condexp : integrable (μ[f|hm]) μ := (integrable_condexp_L1 f).congr (condexp_ae_eq_condexp_L1 f).symm /-- The integral of the conditional expectation `μ[f|hm]` over an `m`-measurable set is equal to the integral of `f` on that set. -/ lemma set_integral_condexp (hf : integrable f μ) (hs : measurable_set[m] s) : ∫ x in s, μ[f|hm] x ∂μ = ∫ x in s, f x ∂μ := begin rw set_integral_congr_ae (hm s hs) ((condexp_ae_eq_condexp_L1 f).mono (λ x hx _, hx)), exact set_integral_condexp_L1 hf hs, end lemma integral_condexp (hf : integrable f μ) : ∫ x, μ[f|hm] x ∂μ = ∫ x, f x ∂μ := begin suffices : ∫ x in set.univ, μ[f|hm] x ∂μ = ∫ x in set.univ, f x ∂μ, by { simp_rw integral_univ at this, exact this, }, exact set_integral_condexp hf (@measurable_set.univ _ m), end /-- **Uniqueness of the conditional expectation** If a function is a.e. `m`-measurable, verifies an integrability condition and has same integral as `f` on all `m`-measurable sets, then it is a.e. equal to `μ[f|hm]`. -/ lemma ae_eq_condexp_of_forall_set_integral_eq (hm : m ≤ m0) [sigma_finite (μ.trim hm)] {f g : α → F'} (hf : integrable f μ) (hg_int_finite : ∀ s, measurable_set[m] s → μ s < ∞ → integrable_on g s μ) (hg_eq : ∀ s : set α, measurable_set[m] s → μ s < ∞ → ∫ x in s, g x ∂μ = ∫ x in s, f x ∂μ) (hgm : ae_measurable' m g μ) : g =ᵐ[μ] μ[f|hm] := begin refine ae_eq_of_forall_set_integral_eq_of_sigma_finite' hm hg_int_finite (λ s hs hμs, integrable_condexp.integrable_on) (λ s hs hμs, _) hgm (measurable.ae_measurable' measurable_condexp), rw [hg_eq s hs hμs, set_integral_condexp hf hs], end lemma condexp_add (hf : integrable f μ) (hg : integrable g μ) : μ[f + g | hm] =ᵐ[μ] μ[f|hm] + μ[g|hm] := begin refine (condexp_ae_eq_condexp_L1 _).trans _, rw condexp_L1_add hf hg, exact (coe_fn_add _ _).trans ((condexp_ae_eq_condexp_L1 _).symm.add (condexp_ae_eq_condexp_L1 _).symm), end lemma condexp_smul (c : 𝕜) (f : α → F') : μ[c • f | hm] =ᵐ[μ] c • μ[f|hm] := begin by_cases hf : integrable f μ, { refine (condexp_ae_eq_condexp_L1 _).trans _, rw condexp_L1_smul c f, refine (@condexp_ae_eq_condexp_L1 _ _ _ _ _ _ _ _ m _ _ hm _ f).mp _, refine (coe_fn_smul c (condexp_L1 hm μ f)).mono (λ x hx1 hx2, _), rw [hx1, pi.smul_apply, pi.smul_apply, hx2], }, { by_cases hc : c = 0, { rw [hc, zero_smul, zero_smul, condexp_zero], }, refine (condexp_undef (mt (integrable_smul_iff hc f).mp hf)).trans _, refine (@condexp_undef _ _ _ _ _ _ _ _ _ _ _ hm _ _ hf).mono (λ x hx, _), rw [pi.zero_apply, pi.smul_apply, hx, pi.zero_apply, smul_zero], }, end lemma condexp_neg (f : α → F') : μ[-f|hm] =ᵐ[μ] - μ[f|hm] := by letI : module ℝ (α → F') := @pi.module α (λ _, F') ℝ _ _ (λ _, infer_instance); calc μ[-f|hm] = μ[(-1 : ℝ) • f|hm] : by rw neg_one_smul ℝ f ... =ᵐ[μ] (-1 : ℝ) • μ[f|hm] : condexp_smul (-1) f ... = -μ[f|hm] : neg_one_smul ℝ (μ[f|hm]) lemma condexp_sub (hf : integrable f μ) (hg : integrable g μ) : μ[f - g | hm] =ᵐ[μ] μ[f|hm] - μ[g|hm] := begin simp_rw sub_eq_add_neg, exact (condexp_add hf hg.neg).trans (eventually_eq.rfl.add (condexp_neg g)), end section real lemma rn_deriv_ae_eq_condexp {f : α → ℝ} (hf : integrable f μ) : signed_measure.rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm) =ᵐ[μ] μ[f | hm] := begin refine ae_eq_condexp_of_forall_set_integral_eq hm hf _ _ _, { exact λ _ _ _, (integrable_of_integrable_trim hm (signed_measure.integrable_rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm))).integrable_on }, { intros s hs hlt, conv_rhs { rw [← hf.with_densityᵥ_trim_eq_integral hm hs, ← signed_measure.with_densityᵥ_rn_deriv_eq ((μ.with_densityᵥ f).trim hm) (μ.trim hm) (hf.with_densityᵥ_trim_absolutely_continuous hm)], }, rw [with_densityᵥ_apply (signed_measure.integrable_rn_deriv ((μ.with_densityᵥ f).trim hm) (μ.trim hm)) hs, ← set_integral_trim hm _ hs], exact signed_measure.measurable_rn_deriv _ _ }, { exact measurable.ae_measurable' (signed_measure.measurable_rn_deriv _ _) }, end end real end condexp end measure_theory
652677f468b85abf2c7779cc4ff716eaa05f56ca
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/constructions.lean
b4ae819f0d3a4891ede1e1cc7aefb6c547b1fdaf
[ "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
50,102
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps import order.filter.pi import data.fin.tuple /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) := t.induced ulift.down lemma quotient.preimage_mem_nhds [topological_space α] [s : setoid α] {V : set $ quotient s} {a : α} (hs : V ∈ 𝓝 (quotient.mk a)) : quotient.mk ⁻¹' V ∈ 𝓝 a := preimage_nhds_coinduced hs /-- The image of a dense set under `quotient.mk` is a dense set. -/ lemma dense.quotient [setoid α] [topological_space α] {s : set α} (H : dense s) : dense (quotient.mk '' s) := (surjective_quotient_mk α).dense_range.dense_image continuous_coinduced_rng H /-- The composition of `quotient.mk` and a function with dense range has dense range. -/ lemma dense_range.quotient [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) : dense_range (quotient.mk ∘ f) := (surjective_quotient_mk α).dense_range.comp hf continuous_coinduced_rng instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t := mem_nhds_induced coe a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap coe (𝓝 (a : α)) := nhds_induced coe a end topα /-- The topology whose open sets are the empty set and the sets with finite complements. -/ def cofinite_topology (α : Type*) : topological_space α := { is_open := λ s, s.nonempty → set.finite sᶜ, is_open_univ := by simp, is_open_inter := λ s t, begin classical, rintros hs ht ⟨x, hxs, hxt⟩, haveI := set.finite.fintype (hs ⟨x, hxs⟩), haveI := set.finite.fintype (ht ⟨x, hxt⟩), rw compl_inter, exact set.finite.intro (sᶜ.fintype_union tᶜ), end, is_open_sUnion := begin rintros s h ⟨x, t, hts, hzt⟩, rw set.compl_sUnion, apply set.finite.sInter _ (h t hts ⟨x, hzt⟩), simp [hts] end } lemma nhds_cofinite {α : Type*} (a : α) : @nhds α (cofinite_topology α) a = pure a ⊔ cofinite := begin ext U, rw mem_nhds_iff, split, { rintro ⟨V, hVU, V_op, haV⟩, exact mem_sup.mpr ⟨hVU haV, mem_of_superset (V_op ⟨_, haV⟩) hVU⟩ }, { rintros ⟨hU : a ∈ U, hU' : (Uᶜ).finite⟩, exact ⟨U, subset.rfl, λ h, hU', hU⟩ } end lemma mem_nhds_cofinite {α : Type*} {a : α} {s : set α} : s ∈ @nhds α (cofinite_topology α) a ↔ a ∈ s ∧ sᶜ.finite := by simp [nhds_cofinite] end constructions section prod variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] @[continuity] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p := continuous_fst.continuous_at lemma continuous.fst {f : α → β × γ} (hf : continuous f) : continuous (λ a : α, (f a).1) := continuous_fst.comp hf lemma continuous_at.fst {f : α → β × γ} {x : α} (hf : continuous_at f x) : continuous_at (λ a : α, (f a).1) x := continuous_at_fst.comp hf @[continuity] lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p := continuous_snd.continuous_at lemma continuous.snd {f : α → β × γ} (hf : continuous f) : continuous (λ a : α, (f a).2) := continuous_snd.comp hf lemma continuous_at.snd {f : α → β × γ} {x : α} (hf : continuous_at f x) : continuous_at (λ a : α, (f a).2) x := continuous_at_snd.comp hf @[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) @[continuity] lemma continuous.prod.mk (a : α) : continuous (prod.mk a : β → α × β) := continuous_const.prod_mk continuous_id' lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous (λ x : γ × δ, (f x.1, g x.2)) := (hf.comp continuous_fst).prod_mk (hg.comp continuous_snd) /-- A version of `continuous_inf_dom_left` for binary functions -/ lemma continuous_inf_dom_left₂ {α β γ} {f : α → β → γ} {ta1 ta2 : topological_space α} {tb1 tb2 : topological_space β} {tc1 : topological_space γ} (h : by haveI := ta1; haveI := tb1; exact continuous (λ p : α × β, f p.1 p.2)) : by haveI := ta1 ⊓ ta2; haveI := tb1 ⊓ tb2; exact continuous (λ p : α × β, f p.1 p.2) := begin have ha := @continuous_inf_dom_left _ _ id ta1 ta2 ta1 (@continuous_id _ (id _)), have hb := @continuous_inf_dom_left _ _ id tb1 tb2 tb1 (@continuous_id _ (id _)), have h_continuous_id := @continuous.prod_map _ _ _ _ ta1 tb1 (ta1 ⊓ ta2) (tb1 ⊓ tb2) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ h h_continuous_id, end /-- A version of `continuous_inf_dom_right` for binary functions -/ lemma continuous_inf_dom_right₂ {α β γ} {f : α → β → γ} {ta1 ta2 : topological_space α} {tb1 tb2 : topological_space β} {tc1 : topological_space γ} (h : by haveI := ta2; haveI := tb2; exact continuous (λ p : α × β, f p.1 p.2)) : by haveI := ta1 ⊓ ta2; haveI := tb1 ⊓ tb2; exact continuous (λ p : α × β, f p.1 p.2) := begin have ha := @continuous_inf_dom_right _ _ id ta1 ta2 ta2 (@continuous_id _ (id _)), have hb := @continuous_inf_dom_right _ _ id tb1 tb2 tb2 (@continuous_id _ (id _)), have h_continuous_id := @continuous.prod_map _ _ _ _ ta2 tb2 (ta1 ⊓ ta2) (tb1 ⊓ tb2) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ h h_continuous_id, end /-- A version of `continuous_Inf_dom` for binary functions -/ lemma continuous_Inf_dom₂ {α β γ} {f : α → β → γ} {tas : set (topological_space α)} {tbs : set (topological_space β)} {ta : topological_space α} {tb : topological_space β} {tc : topological_space γ} (ha : ta ∈ tas) (hb : tb ∈ tbs) (hf : continuous (λ p : α × β, f p.1 p.2)): by haveI := Inf tas; haveI := Inf tbs; exact @continuous _ _ _ tc (λ p : α × β, f p.1 p.2) := begin let t : topological_space (α × β) := prod.topological_space, have ha := continuous_Inf_dom ha continuous_id, have hb := continuous_Inf_dom hb continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ ta tb (Inf tas) (Inf tbs) _ _ ha hb, exact @continuous.comp _ _ _ (id _) (id _) _ _ _ hf h_continuous_id, end lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 := continuous_at_fst h lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 := continuous_at_snd h lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x) {pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) : ∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl_nhds b).and (hb.prod_inr_nhds a) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous_snd.prod_mk continuous_fst lemma continuous_uncurry_left {f : α → β → γ} (a : α) (h : continuous (function.uncurry f)) : continuous (f a) := show continuous (function.uncurry f ∘ (λ b, (a, b))), from h.comp (by continuity) lemma continuous_uncurry_right {f : α → β → γ} (b : β) (h : continuous (function.uncurry f)) : continuous (λ a, f a b) := show continuous (function.uncurry f ∘ (λ a, (a, b))), from h.comp (by continuity) lemma continuous_curry {g : α × β → γ} (a : α) (h : continuous g) : continuous (function.curry g a) := show continuous (g ∘ (λ b, (a, b))), from h.comp (by continuity) lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (s ×ˢ t) := is_open.inter (hs.preimage continuous_fst) (ht.preimage continuous_snd) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), u ×ˢ v ⊆ s := by rw [nhds_prod_eq, mem_prod_iff] lemma mem_nhds_prod_iff' {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u : set α) (v : set β), is_open u ∧ a ∈ u ∧ is_open v ∧ b ∈ v ∧ u ×ˢ v ⊆ s := begin rw mem_nhds_prod_iff, split, { rintros ⟨u, Hu, v, Hv, h⟩, rcases mem_nhds_iff.1 Hu with ⟨u', u'u, u'_open, Hu'⟩, rcases mem_nhds_iff.1 Hv with ⟨v', v'v, v'_open, Hv'⟩, exact ⟨u', v', u'_open, Hu', v'_open, Hv', (set.prod_mono u'u v'v).trans h⟩ }, { rintros ⟨u, v, u_open, au, v_open, bv, huv⟩, exact ⟨u, u_open.mem_nhds au, v, v_open.mem_nhds bv, huv⟩ } end lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa) (hb : (𝓝 b).has_basis pb sb) : (𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := by { rw nhds_prod_eq, exact ha.prod hb } lemma filter.has_basis.prod_nhds' {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {ab : α × β} (ha : (𝓝 ab.1).has_basis pa sa) (hb : (𝓝 ab.2).has_basis pb sb) : (𝓝 ab).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := by { cases ab, exact ha.prod_nhds hb } instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_iff {s : set α} {t : set β} {a : α} {b : β} : s ×ˢ t ∈ 𝓝 (a, b) ↔ s ∈ 𝓝 a ∧ t ∈ 𝓝 b := by rw [nhds_prod_eq, prod_mem_prod_iff] lemma prod_is_open.mem_nhds {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : s ×ˢ t ∈ 𝓝 (a, b) := prod_mem_nhds_iff.2 ⟨ha, hb⟩ lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by { rw [nhds_prod_eq] at h, exact h.curry } lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f p.fst) (hg : continuous_at g p.snd) : continuous_at (λ p : α × β, (f p.1, g p.2)) p := (hf.comp continuous_at_fst).prod (hg.comp continuous_at_snd) lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) := have hf : continuous_at f (x, y).fst, from hf, have hg : continuous_at g (x, y).snd, from hg, hf.prod_map hg lemma prod_generate_from_generate_from_eq {α β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = u ×ˢ v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = u ×ˢ v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open.prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, u ×ˢ v) = prod.fst ⁻¹' u, from calc (⋃v∈t, u ×ˢ v) = u ×ˢ (univ : set β) : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : set.prod_univ, show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, u ×ˢ v) = prod.snd ⁻¹' v, from calc (⋃u∈s, u ×ˢ v) = (univ : set α) ×ˢ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : set.univ_prod, show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = s ×ˢ t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α × β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ u ×ˢ v ⊆ s) := begin rw [is_open_iff_nhds], simp_rw [le_principal_iff, prod.forall, ((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop], simp only [and_assoc, and.left_comm] end /-- A product of induced topologies is induced by the product map -/ lemma prod_induced_induced {α γ : Type*} (f : α → β) (g : γ → δ) : @prod.topological_space α γ (induced f ‹_›) (induced g ‹_›) = induced (λ p, (f p.1, g p.2)) prod.topological_space := begin set fxg := (λ p : α × γ, (f p.1, g p.2)), have key1 : f ∘ (prod.fst : α × γ → α) = (prod.fst : β × δ → β) ∘ fxg, from rfl, have key2 : g ∘ (prod.snd : α × γ → γ) = (prod.snd : β × δ → δ) ∘ fxg, from rfl, unfold prod.topological_space, conv_lhs { rw [induced_compose, induced_compose, key1, key2], congr, rw ← induced_compose, skip, rw ← induced_compose, }, rw induced_inf end lemma continuous_uncurry_of_discrete_topology_left [discrete_topology α] {f : α → β → γ} (h : ∀ a, continuous (f a)) : continuous (function.uncurry f) := continuous_iff_continuous_at.2 $ λ ⟨a, b⟩, by simp only [continuous_at, nhds_prod_eq, nhds_discrete α, pure_prod, tendsto_map'_iff, (∘), function.uncurry, (h a).tendsto] /-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) : ∃ U : set α, is_open U ∧ x ∈ U ∧ U ×ˢ U ⊆ s := by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx /-- `prod.fst` maps neighborhood of `x : α × β` within the section `prod.snd ⁻¹' {x.2}` to `𝓝 x.1`. -/ lemma map_fst_nhds_within (x : α × β) : map prod.fst (𝓝[prod.snd ⁻¹' {x.2}] x) = 𝓝 x.1 := begin refine le_antisymm (continuous_at_fst.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_of_superset hu (λ z hz, H _ hz _ (mem_of_mem_nhds hv) rfl) end @[simp] lemma map_fst_nhds (x : α × β) : map prod.fst (𝓝 x) = 𝓝 x.1 := le_antisymm continuous_at_fst $ (map_fst_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_fst_nhds x).ge /-- `prod.snd` maps neighborhood of `x : α × β` within the section `prod.fst ⁻¹' {x.1}` to `𝓝 x.2`. -/ lemma map_snd_nhds_within (x : α × β) : map prod.snd (𝓝[prod.fst ⁻¹' {x.1}] x) = 𝓝 x.2 := begin refine le_antisymm (continuous_at_snd.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_of_superset hv (λ z hz, H _ (mem_of_mem_nhds hu) _ hz rfl) end @[simp] lemma map_snd_nhds (x : α × β) : map prod.snd (𝓝 x) = 𝓝 x.2 := le_antisymm continuous_at_snd $ (map_snd_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_snd_nhds x).ge /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (s ×ˢ t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (s ×ˢ t : set _).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (s ×ˢ t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H, exact H.1.prod H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (s ×ˢ t) = closure s ×ˢ closure t := set.ext $ assume ⟨a, b⟩, have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (s ×ˢ t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot lemma interior_prod_eq (s : set α) (t : set β) : interior (s ×ˢ t) = interior s ×ˢ interior t := set.ext $ λ ⟨a, b⟩, by simp only [mem_interior_iff_mem_nhds, mem_prod, prod_mem_nhds_iff] lemma frontier_prod_eq (s : set α) (t : set β) : frontier (s ×ˢ t) = closure s ×ˢ frontier t ∪ frontier s ×ˢ closure t := by simp only [frontier, closure_prod_eq, interior_prod_eq, prod_diff_prod] @[simp] lemma frontier_prod_univ_eq (s : set α) : frontier (s ×ˢ (univ : set β)) = frontier s ×ˢ (univ : set β) := by simp [frontier_prod_eq] @[simp] lemma frontier_univ_prod_eq (s : set β) : frontier ((univ : set α) ×ˢ s) = (univ : set α) ×ˢ (frontier s) := by simp [frontier_prod_eq] lemma map_mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (s ×ˢ t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from map_mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ×ˢ s₂) := closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] /-- The product of two dense sets is a dense set. -/ lemma dense.prod {s : set α} {t : set β} (hs : dense s) (ht : dense t) : dense (s ×ˢ t) := λ x, by { rw closure_prod_eq, exact ⟨hs x.1, ht x.2⟩ } /-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/ lemma dense_range.prod_map {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) := by simpa only [dense_range, prod_range_range_eq] using hf.prod hg lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum open sum variables [topological_space α] [topological_space β] [topological_space γ] @[continuity] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng @[continuity] lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng @[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := begin apply continuous_sup_dom; rw continuous_def at hf hg ⊢; assumption end lemma is_open_sum_iff {s : set (α ⊕ β)} : is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) := iff.rfl lemma is_open_map_sum {f : α ⊕ β → γ} (h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) : is_open_map f := begin intros u hu, rw is_open_sum_iff at hu, cases hu with hu₁ hu₂, have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u), { ext (_|_); simp }, rw [this, set.image_union, set.image_image, set.image_image], exact is_open.union (h₁ _ hu₁) (h₂ _ hu₂) end lemma embedding_inl : embedding (@inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_left }, { intros u hu, existsi (inl '' u), change (is_open (inl ⁻¹' (@inl α β '' u)) ∧ is_open (inr ⁻¹' (@inl α β '' u))) ∧ inl ⁻¹' (inl '' u) = u, have : inl ⁻¹' (@inl α β '' u) = u := preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this, have : inr ⁻¹' (@inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, inl.inj_iff.mp } lemma embedding_inr : embedding (@inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_right }, { intros u hu, existsi (inr '' u), change (is_open (inl ⁻¹' (@inr α β '' u)) ∧ is_open (inr ⁻¹' (@inr α β '' u))) ∧ inr ⁻¹' (inr '' u) = u, have : inl ⁻¹' (@inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this, have : inr ⁻¹' (@inr α β '' u) = u := preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, inr.inj_iff.mp } lemma is_open_range_inl : is_open (range (inl : α → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma is_open_range_inr : is_open (range (inr : β → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) := { open_range := is_open_range_inl, .. embedding_inl } lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) := { open_range := is_open_range_inr, .. embedding_inr } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_coe : embedding (coe : subtype p → α) := ⟨⟨rfl⟩, subtype.coe_injective⟩ lemma closed_embedding_subtype_coe (h : is_closed {a | p a}) : closed_embedding (coe : subtype p → α) := ⟨embedding_subtype_coe, by rwa [subtype.range_coe_subtype]⟩ @[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma continuous.subtype_coe {f : β → subtype p} (hf : continuous f) : continuous (λ x, (f x : α)) := continuous_subtype_coe.comp hf lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) : open_embedding (coe : s → α) := { induced := rfl, inj := subtype.coe_injective, open_range := (subtype.range_coe : range coe = s).symm ▸ hs } lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) : is_open_map (coe : s → α) := hs.open_embedding_subtype_coe.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_coe lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) : closed_embedding (coe : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.coe_injective, closed_range := (subtype.range_coe : range coe = s).symm ▸ hs } @[continuity] lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_coe lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} : continuous_at (coe : subtype p → α) a := continuous_iff_continuous_at.mp continuous_subtype_coe _ lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_of_mem $ by simpa only [subtype.coe_mk, subtype.range_coe] using h lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α)) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_mem_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map coe (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from assume i, (closed_embedding_subtype_coe (h_is_closed _)).is_closed_map _ (hs.preimage (f_cont i)), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from locally_finite.is_closed_Union (h_lf.subset $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) := closure_induced end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ @[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng @[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h lemma continuous_quotient_lift_on' {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (λ x, quotient.lift_on' x f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} @[continuity] lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i @[continuity] lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom @[continuity] lemma continuous_apply_apply {κ : Type*} {ρ : κ → ι → Type*} [∀ j i, topological_space (ρ j i)] (j : κ) (i : ι) : continuous (λ p : (Π j, Π i, ρ j i), p j i) := (continuous_apply i).comp (continuous_apply j) lemma continuous_at_apply [∀i, topological_space (π i)] (i : ι) (x : Π i, π i) : continuous_at (λ p : Π i, π i, p i) x := (continuous_apply i).continuous_at lemma filter.tendsto.apply [∀i, topological_space (π i)] {l : filter α} {f : α → Π i, π i} {x : Π i, π i} (h : tendsto f l (𝓝 x)) (i : ι) : tendsto (λ a, f a i) l (𝓝 $ x i) := (continuous_at_apply i _).tendsto.comp h lemma continuous_pi_iff [topological_space α] [∀ i, topological_space (π i)] {f : α → Π i, π i} : continuous f ↔ ∀ i, continuous (λ y, f y i) := iff.intro (λ h i, (continuous_apply i).comp h) continuous_pi lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = pi (λ i, 𝓝 (a i)) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma tendsto_pi_nhds [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} : tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) := by rw [nhds_pi, filter.tendsto_pi] lemma continuous_at_pi [∀ i, topological_space (π i)] [topological_space α] {f : α → Π i, π i} {x : α} : continuous_at f x ↔ ∀ i, continuous_at (λ y, f y i) x := tendsto_pi_nhds lemma filter.tendsto.update [∀i, topological_space (π i)] [decidable_eq ι] {l : filter α} {f : α → Π i, π i} {x : Π i, π i} (hf : tendsto f l (𝓝 x)) (i : ι) {g : α → π i} {xi : π i} (hg : tendsto g l (𝓝 xi)) : tendsto (λ a, function.update (f a) i (g a)) l (𝓝 $ function.update x i xi) := tendsto_pi_nhds.2 $ λ j, by { rcases em (j = i) with rfl|hj; simp [*, hf.apply] } lemma continuous_at.update [∀i, topological_space (π i)] [topological_space α] [decidable_eq ι] {f : α → Π i, π i} {a : α} (hf : continuous_at f a) (i : ι) {g : α → π i} (hg : continuous_at g a) : continuous_at (λ a, function.update (f a) i (g a)) a := hf.update i hg lemma continuous.update [∀i, topological_space (π i)] [topological_space α] [decidable_eq ι] {f : α → Π i, π i} (hf : continuous f) (i : ι) {g : α → π i} (hg : continuous g) : continuous (λ a, function.update (f a) i (g a)) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.update i hg.continuous_at /-- `function.update f i x` is continuous in `(f, x)`. -/ @[continuity] lemma continuous_update [∀i, topological_space (π i)] [decidable_eq ι] (i : ι) : continuous (λ f : (Π j, π j) × π i, function.update f.1 i f.2) := continuous_fst.update i continuous_snd lemma filter.tendsto.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : α → π i} {l : filter α} {x : π i} (hf : tendsto f l (𝓝 x)) {g : α → Π j : fin n, π (i.succ_above j)} {y : Π j, π (i.succ_above j)} (hg : tendsto g l (𝓝 y)) : tendsto (λ a, i.insert_nth (f a) (g a)) l (𝓝 $ i.insert_nth x y) := tendsto_pi_nhds.2 (λ j, fin.succ_above_cases i (by simpa) (by simpa using tendsto_pi_nhds.1 hg) j) lemma continuous_at.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] [topological_space α] (i : fin (n + 1)) {f : α → π i} {a : α} (hf : continuous_at f a) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous_at g a) : continuous_at (λ a, i.insert_nth (f a) (g a)) a := hf.fin_insert_nth i hg lemma continuous.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] [topological_space α] (i : fin (n + 1)) {f : α → π i} (hf : continuous f) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous g) : continuous (λ a, i.insert_nth (f a) (g a)) := continuous_iff_continuous_at.2 $ λ a, hf.continuous_at.fin_insert_nth i hg.continuous_at lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, (hs _ ha).preimage (continuous_apply _)) lemma is_closed_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hs : ∀a∈i, is_closed (s a)) : is_closed (pi i s) := by rw [pi_def]; exact (is_closed_Inter $ λ a, is_closed_Inter $ λ ha, (hs _ ha).preimage (continuous_apply _)) lemma mem_nhds_of_pi_mem_nhds {ι : Type*} {α : ι → Type*} [Π (i : ι), topological_space (α i)] {I : set ι} {s : Π i, set (α i)} (a : Π i, α i) (hs : I.pi s ∈ 𝓝 a) {i : ι} (hi : i ∈ I) : s i ∈ 𝓝 (a i) := by { rw nhds_pi at hs, exact mem_of_pi_mem_pi hs hi } lemma set_pi_mem_nhds [Π a, topological_space (π a)] {i : set ι} {s : Π a, set (π a)} {x : Π a, π a} (hi : finite i) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) : pi i s ∈ 𝓝 x := by { rw [pi_def, bInter_mem hi], exact λ a ha, (continuous_apply a).continuous_at (hs a ha) } lemma set_pi_mem_nhds_iff {α : ι → Type*} [Π (i : ι), topological_space (α i)] {I : set ι} (hI : I.finite) {s : Π i, set (α i)} (a : Π i, α i) : I.pi s ∈ 𝓝 a ↔ ∀ (i : ι), i ∈ I → s i ∈ 𝓝 (a i) := by { rw [nhds_pi, pi_mem_pi_iff hI], apply_instance } lemma interior_pi_set {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} (hI : I.finite) {s : Π i, set (α i)} : interior (pi I s) = I.pi (λ i, interior (s i)) := by { ext a, simp only [set.mem_pi, mem_interior_iff_mem_nhds, set_pi_mem_nhds_iff hI] } lemma exists_finset_piecewise_mem_of_mem_nhds [decidable_eq ι] [Π i, topological_space (π i)] {s : set (Π a, π a)} {x : Π a, π a} (hs : s ∈ 𝓝 x) (y : Π a, π a) : ∃ I : finset ι, I.piecewise x y ∈ s := begin simp only [nhds_pi, filter.mem_pi'] at hs, rcases hs with ⟨I, t, htx, hts⟩, refine ⟨I, hts $ λ i hi, _⟩, simpa [finset.mem_coe.1 hi] using mem_of_mem_nhds (htx i) end lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, s_eq ▸ by ext f; simp [set.pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, set.pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, set.pi] at * }, simpa [pi_if, hf] } } end /-- Suppose `π i` is a family of topological spaces indexed by `i : ι`, and `X` is a type endowed with a family of maps `f i : X → π i` for every `i : ι`, hence inducing a map `g : X → Π i, π i`. This lemma shows that infimum of the topologies on `X` induced by the `f i` as `i : ι` varies is simply the topology on `X` induced by `g : X → Π i, π i` where `Π i, π i` is endowed with the usual product topology. -/ lemma inducing_infi_to_pi {X : Type*} [∀ i, topological_space (π i)] (f : Π i, X → π i) : @inducing X (Π i, π i) (⨅ i, induced (f i) infer_instance) _ (λ x i, f i x) := begin constructor, erw induced_infi, congr' 1, funext, erw induced_compose, end variables [fintype ι] [∀ i, topological_space (π i)] [∀ i, discrete_topology (π i)] /-- A finite product of discrete spaces is discrete. -/ instance Pi.discrete_topology : discrete_topology (Π i, π i) := singletons_open_iff_discrete.mp (λ x, begin rw show {x} = ⋂ i, {y : Π i, π i | y i = x i}, { ext, simp only [function.funext_iff, set.mem_singleton_iff, set.mem_Inter, set.mem_set_of_eq] }, exact is_open_Inter (λ i, (continuous_apply i).is_open_preimage {x i} (is_open_discrete {x i})) end) end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] @[continuity] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := by simp only [← is_open_compl_iff, is_open_sigma_iff, preimage_compl] lemma is_open_sigma_fst_preimage (s : set ι) : is_open (sigma.fst ⁻¹' s : set (Σ a, σ a)) := begin rw is_open_sigma_iff, intros a, by_cases h : a ∈ s, { convert is_open_univ, ext x, simp only [h, set.mem_preimage, set.mem_univ] }, { convert is_open_empty, ext x, simp only [h, set.mem_empty_eq, set.mem_preimage] } end lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, rcases eq_or_ne i j with (rfl|hne), { rwa set.preimage_image_eq _ sigma_mk_injective }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := is_open_map_sigma_mk.is_open_range lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, rcases eq_or_ne i j with (rfl|hne), { rwa set.preimage_image_eq _ sigma_mk_injective }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity] lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) @[continuity] lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, rw [← Union_image_preimage_sigma_mk_eq_self s, image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma section ulift @[continuity] lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom @[continuity] lemma continuous_ulift_up [topological_space α] : continuous (ulift.up : α → ulift.{v u} α) := continuous_induced_rng continuous_id end ulift lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure t : closure_minimal h.image_subset is_closed_closure lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (s ×ˢ t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
14fb35f3a9efe0f9376c7010bf731a48281a1d14
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/playground/sleep_save.lean
fb2724d6dea1f556d7459c3f66bd176b38b018c8
[ "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
795
lean
macro "expensive_tactic" : tactic => `(sleep 5000) example (h₁ : x = y) (h₂ : y = z) : z = x := by expensive_tactic save have : y = x := h₁.symm have : z = y := h₂.symm trace "hello world" apply this.trans exact ‹y = x› example (h₁ : p ∨ q) (h₂ : p → x = 0) (h₃ : q → y = 0) : x * y = 0 := by expensive_tactic save match h₁ with | .inr h => expensive_tactic save have : y = 0 := h₃ h simp [*] | .inl h => stop done example (h₁ : p ∨ q) (h₂ : p → x = 0) (h₃ : q → y = 0) : x * y = 0 := by expensive_tactic save cases h₁ with | inr h => expensive_tactic save have : y = 0 := h₃ h simp [*] | inl h => stop expensive_tactic save have : x = 0 := h₂ h simp [*] done
3088dd5d7b5b0801f4036b31869a71c0d32e1140
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/elab_error_msgs.lean
023a0a85aa604020c1f8718d971c2f6f4dfcc3af
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
352
lean
lemma ex1 (a b : Prop) : a ∧ b ∧ b → b ∧ a := and.rec (λ ha hb hb, ha) @[elab_as_eliminator] def bogus_elim {A : Type} {C : A → A → Prop} {a b : A} (h : C a a) : C a b := sorry lemma ex2 (a b : Prop) : a ∧ b := bogus_elim trivial lemma ex1 (a b : Prop) : a ∧ b ∧ b → b ∧ a := λ h, and.rec (λ ha hb, ha + hb) h
ffd80f17e86932b303e239133d32f616a2923717
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/ring_theory/multiplicity.lean
89215f1d5e37d71b0fdc4b5120066d5bc365ae11
[ "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
15,332
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Chris Hughes -/ import algebra.associated data.int.gcd data.nat.enat import tactic.converter.interactive import tactic.norm_cast variables {α : Type*} open nat roption theorem nat.find_le {p q : ℕ → Prop} [decidable_pred p] [decidable_pred q] (h : ∀ n, q n → p n) (hp : ∃ n, p n) (hq : ∃ n, q n) : nat.find hp ≤ nat.find hq := nat.find_min' _ ((h _) (nat.find_spec hq)) /-- `multiplicity a b` returns the largest natural number `n` such that `a ^ n ∣ b`, as an `enat` or natural with infinity. If `∀ n, a ^ n ∣ b`, then it returns `⊤`-/ def multiplicity [comm_semiring α] [decidable_rel ((∣) : α → α → Prop)] (a b : α) : enat := ⟨∃ n : ℕ, ¬a ^ (n + 1) ∣ b, λ h, nat.find h⟩ namespace multiplicity section comm_semiring variables [comm_semiring α] @[reducible] def finite (a b : α) : Prop := ∃ n : ℕ, ¬a ^ (n + 1) ∣ b lemma finite_iff_dom [decidable_rel ((∣) : α → α → Prop)] {a b : α} : finite a b ↔ (multiplicity a b).dom := iff.rfl lemma finite_def {a b : α} : finite a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b := iff.rfl @[move_cast] theorem int.coe_nat_multiplicity (a b : ℕ) : multiplicity a b = multiplicity (a : ℤ) (b : ℤ) := begin apply roption.ext', { repeat {rw [← finite_iff_dom, finite_def]}, norm_cast, simp }, { intros h1 h2, apply _root_.le_antisymm; { apply nat.find_le, norm_cast, simp }} end lemma not_finite_iff_forall {a b : α} : (¬ finite a b) ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (one_dvd _) (by simpa [finite, classical.not_not] using h), by simp [finite, multiplicity, classical.not_not]; tauto⟩ lemma not_unit_of_finite {a b : α} (h : finite a b) : ¬is_unit a := let ⟨n, hn⟩ := h in mt (is_unit_iff_forall_dvd.1 ∘ is_unit_pow (n + 1)) $ λ h, hn (h b) lemma ne_zero_of_finite {a b : α} (h : finite a b) : b ≠ 0 := let ⟨n, hn⟩ := h in λ hb, by simpa [hb] using hn lemma finite_of_finite_mul_left {a b c : α} : finite a (b * c) → finite a c := λ ⟨n, hn⟩, ⟨n, λ h, hn (dvd.trans h (by simp [_root_.mul_pow]))⟩ lemma finite_of_finite_mul_right {a b c : α} : finite a (b * c) → finite a b := by rw mul_comm; exact finite_of_finite_mul_left variable [decidable_rel ((∣) : α → α → Prop)] lemma pow_dvd_of_le_multiplicity {a b : α} {k : ℕ} : (k : enat) ≤ multiplicity a b → a ^ k ∣ b := nat.cases_on k (λ _, one_dvd _) (λ k ⟨h₁, h₂⟩, by_contradiction (λ hk, (nat.find_min _ (lt_of_succ_le (h₂ ⟨k, hk⟩)) hk))) lemma pow_multiplicity_dvd {a b : α} (h : finite a b) : a ^ get (multiplicity a b) h ∣ b := pow_dvd_of_le_multiplicity (by rw enat.coe_get) lemma is_greatest {a b : α} {m : ℕ} (hm : multiplicity a b < m) : ¬a ^ m ∣ b := λ h, have finite a b, from enat.dom_of_le_some (le_of_lt hm), by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_lt_coe] at hm; exact nat.find_spec this (dvd.trans (pow_dvd_pow _ hm) h) lemma is_greatest' {a b : α} {m : ℕ} (h : finite a b) (hm : get (multiplicity a b) h < m) : ¬a ^ m ∣ b := is_greatest (by rwa [← enat.coe_lt_coe, enat.coe_get] at hm) lemma unique {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) : (k : enat) = multiplicity a b := le_antisymm (le_of_not_gt (λ hk', is_greatest hk' hk)) $ have finite a b, from ⟨k, hsucc⟩, by rw [← enat.coe_get (finite_iff_dom.1 this), enat.coe_le_coe]; exact nat.find_min' _ hsucc lemma unique' {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬ a ^ (k + 1) ∣ b) : k = get (multiplicity a b) ⟨k, hsucc⟩ := by rw [← enat.coe_inj, enat.coe_get, unique hk hsucc] lemma le_multiplicity_of_pow_dvd {a b : α} {k : ℕ} (hk : a ^ k ∣ b) : (k : enat) ≤ multiplicity a b := le_of_not_gt $ λ hk', is_greatest hk' hk lemma pow_dvd_iff_le_multiplicity {a b : α} {k : ℕ} : a ^ k ∣ b ↔ (k : enat) ≤ multiplicity a b := ⟨le_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicity⟩ lemma eq_some_iff {a b : α} {n : ℕ} : multiplicity a b = (n : enat) ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := ⟨λ h, let ⟨h₁, h₂⟩ := eq_some_iff.1 h in h₂ ▸ ⟨pow_multiplicity_dvd _, is_greatest (by conv_lhs {rw ← enat.coe_get h₁ }; rw [enat.coe_lt_coe]; exact lt_succ_self _)⟩, λ h, eq_some_iff.2 ⟨⟨n, h.2⟩, eq.symm $ unique' h.1 h.2⟩⟩ lemma eq_top_iff {a b : α} : multiplicity a b = ⊤ ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (one_dvd _) (λ n, by_contradiction (not_exists.1 (eq_none_iff'.1 h) n : _)), λ h, eq_none_iff.2 (λ n ⟨⟨_, h₁⟩, _⟩, h₁ (h _))⟩ @[simp] protected lemma zero (a : α) : multiplicity a 0 = ⊤ := roption.eq_none_iff.2 (λ n ⟨⟨k, hk⟩, _⟩, hk (dvd_zero _)) lemma one_right {a : α} (ha : ¬is_unit a) : multiplicity a 1 = 0 := eq_some_iff.2 ⟨dvd_refl _, mt is_unit_iff_dvd_one.2 $ by simpa⟩ @[simp] lemma get_one_right {a : α} (ha : finite a 1) : get (multiplicity a 1) ha = 0 := get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨dvd_refl _, by simpa [is_unit_iff_dvd_one.symm] using not_unit_of_finite ha⟩) @[simp] lemma one_left (b : α) : multiplicity 1 b = ⊤ := by simp [eq_top_iff] @[simp] lemma multiplicity_unit {a : α} (b : α) (ha : is_unit a) : multiplicity a b = ⊤ := eq_top_iff.2 (λ _, is_unit_iff_forall_dvd.1 (is_unit_pow _ ha) _) lemma multiplicity_eq_zero_of_not_dvd {a b : α} (ha : ¬a ∣ b) : multiplicity a b = 0 := eq_some_iff.2 (by simpa) lemma eq_top_iff_not_finite {a b : α} : multiplicity a b = ⊤ ↔ ¬ finite a b := roption.eq_none_iff' local attribute [instance, priority 0] classical.prop_decidable lemma multiplicity_le_multiplicity_iff {a b c d : α} : multiplicity a b ≤ multiplicity c d ↔ (∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d) := ⟨λ h n hab, (pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h)), λ h, if hab : finite a b then by rw [← enat.coe_get (finite_iff_dom.1 hab)]; exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _)) else have ∀ n : ℕ, c ^ n ∣ d, from λ n, h n (not_finite_iff_forall.1 hab _), by rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2 (not_finite_iff_forall.2 this)]⟩ lemma min_le_multiplicity_add {p a b : α} : min (multiplicity p a) (multiplicity p b) ≤ multiplicity p (a + b) := (le_total (multiplicity p a) (multiplicity p b)).elim (λ h, by rw [min_eq_left h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn)) (λ h, by rw [min_eq_right h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn) lemma dvd_of_multiplicity_pos {a b : α} (h : (0 : enat) < multiplicity a b) : a ∣ b := by rw [← _root_.pow_one a]; exact pow_dvd_of_le_multiplicity (enat.pos_iff_one_le.1 h) lemma finite_nat_iff {a b : ℕ} : finite a b ↔ (a ≠ 1 ∧ 0 < b) := begin rw [← not_iff_not, not_finite_iff_forall, not_and_distrib, ne.def, not_not, not_lt, nat.le_zero_iff], exact ⟨λ h, or_iff_not_imp_right.2 (λ hb, have ha : a ≠ 0, from λ ha, by simpa [ha] using h 1, by_contradiction (λ ha1 : a ≠ 1, have ha_gt_one : 1 < a, from have ∀ a : ℕ, a ≤ 1 → a ≠ 0 → a ≠ 1 → false, from dec_trivial, lt_of_not_ge (λ ha', this a ha' ha ha1), not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero hb) (h b)) (by simp only [nat.pow_eq_pow]; exact lt_pow_self ha_gt_one b))), λ h, by cases h; simp *⟩ end lemma finite_int_iff_nat_abs_finite {a b : ℤ} : finite a b ↔ finite a.nat_abs b.nat_abs := begin rw [finite_def, finite_def], conv in (a ^ _ ∣ b) { rw [← int.nat_abs_dvd_abs_iff, int.nat_abs_pow, ← pow_eq_pow] } end lemma finite_int_iff {a b : ℤ} : finite a b ↔ (a.nat_abs ≠ 1 ∧ b ≠ 0) := begin have := int.nat_abs_eq a, have := @int.nat_abs_ne_zero_of_ne_zero b, rw [finite_int_iff_nat_abs_finite, finite_nat_iff, nat.pos_iff_ne_zero'], split; finish end instance decidable_nat : decidable_rel (λ a b : ℕ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_nat_iff.symm instance decidable_int : decidable_rel (λ a b : ℤ, (multiplicity a b).dom) := λ a b, decidable_of_iff _ finite_int_iff.symm end comm_semiring section comm_ring variables [comm_ring α] [decidable_rel ((∣) : α → α → Prop)] local attribute [instance, priority 0] classical.prop_decidable @[simp] protected lemma neg (a b : α) : multiplicity a (-b) = multiplicity a b := roption.ext' (by simp only [multiplicity]; conv in (_ ∣ - _) {rw dvd_neg}) (λ h₁ h₂, enat.coe_inj.1 (by rw [enat.coe_get]; exact eq.symm (unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _)) (mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _)))))) end comm_ring section integral_domain variables [integral_domain α] [decidable_rel ((∣) : α → α → Prop)] @[simp] lemma multiplicity_self {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) : multiplicity a a = 1 := eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, ha (is_unit_iff_dvd_one.2 ⟨b, (domain.mul_left_inj ha0).1 $ by clear _fun_match; simpa [_root_.pow_succ, mul_assoc] using hb⟩)⟩ @[simp] lemma get_multiplicity_self {a : α} (ha : finite a a) : get (multiplicity a a) ha = 1 := roption.get_eq_iff_eq_some.2 (eq_some_iff.2 ⟨by simp, λ ⟨b, hb⟩, by rw [← mul_one a, _root_.pow_add, _root_.pow_one, mul_assoc, mul_assoc, domain.mul_left_inj (ne_zero_of_finite ha)] at hb; exact mt is_unit_iff_dvd_one.2 (not_unit_of_finite ha) ⟨b, by clear _fun_match; simp * at *⟩⟩) lemma finite_mul_aux {p : α} (hp : prime p) : ∀ {n m : ℕ} {a b : α}, ¬p ^ (n + 1) ∣ a → ¬p ^ (m + 1) ∣ b → ¬p ^ (n + m + 1) ∣ a * b | n m := λ a b ha hb ⟨s, hs⟩, have p ∣ a * b, from ⟨p ^ (n + m) * s, by simp [hs, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩, (hp.2.2 a b this).elim (λ ⟨x, hx⟩, have hn0 : 0 < n, from nat.pos_of_ne_zero (λ hn0, by clear _fun_match _fun_match; simpa [hx, hn0] using ha), have wf : (n - 1) < n, from nat.sub_lt_self hn0 dec_trivial, have hpx : ¬ p ^ (n - 1 + 1) ∣ x, from λ ⟨y, hy⟩, ha (hx.symm ▸ ⟨y, (domain.mul_left_inj hp.1).1 $ by rw [nat.sub_add_cancel hn0] at hy; simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), have 1 ≤ n + m, from le_trans hn0 (le_add_right n m), finite_mul_aux hpx hb ⟨s, (domain.mul_left_inj hp.1).1 begin rw [← nat.sub_add_comm hn0, nat.sub_add_cancel this], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at * end⟩) (λ ⟨x, hx⟩, have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, by clear _fun_match _fun_match; simpa [hx, hm0] using hb), have wf : (m - 1) < m, from nat.sub_lt_self hm0 dec_trivial, have hpx : ¬ p ^ (m - 1 + 1) ∣ x, from λ ⟨y, hy⟩, hb (hx.symm ▸ ⟨y, (domain.mul_left_inj hp.1).1 $ by rw [nat.sub_add_cancel hm0] at hy; simp [hy, _root_.pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), finite_mul_aux ha hpx ⟨s, (domain.mul_left_inj hp.1).1 begin rw [add_assoc, nat.sub_add_cancel hm0], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add] at * end⟩) lemma finite_mul {p a b : α} (hp : prime p) : finite p a → finite p b → finite p (a * b) := λ ⟨n, hn⟩ ⟨m, hm⟩, ⟨n + m, finite_mul_aux hp hn hm⟩ lemma finite_mul_iff {p a b : α} (hp : prime p) : finite p (a * b) ↔ finite p a ∧ finite p b := ⟨λ h, ⟨finite_of_finite_mul_right h, finite_of_finite_mul_left h⟩, λ h, finite_mul hp h.1 h.2⟩ lemma finite_pow {p a : α} (hp : prime p) : Π {k : ℕ} (ha : finite p a), finite p (a ^ k) | 0 ha := ⟨0, by simp [mt is_unit_iff_dvd_one.2 hp.2.1]⟩ | (k+1) ha := by rw [_root_.pow_succ]; exact finite_mul hp ha (finite_pow ha) protected lemma mul' {p a b : α} (hp : prime p) (h : (multiplicity p (a * b)).dom) : get (multiplicity p (a * b)) h = get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2 := have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ∣ a, from pow_multiplicity_dvd _, have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ∣ b, from pow_multiplicity_dvd _, have hpoweq : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) = p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 * p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2, by simp [_root_.pow_add], have hdiv : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ∣ a * b, by rw [hpoweq]; apply mul_dvd_mul; assumption, have hsucc : ¬p ^ ((get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) + 1) ∣ a * b, from λ h, not_or (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _)) (succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp (by convert hdiva) (by convert hdivb) h), by rw [← enat.coe_inj, enat.coe_get, eq_some_iff]; exact ⟨hdiv, hsucc⟩ local attribute [instance, priority 0] classical.prop_decidable protected lemma mul {p a b : α} (hp : prime p) : multiplicity p (a * b) = multiplicity p a + multiplicity p b := if h : finite p a ∧ finite p b then by rw [← enat.coe_get (finite_iff_dom.1 h.1), ← enat.coe_get (finite_iff_dom.1 h.2), ← enat.coe_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)), ← enat.coe_add, enat.coe_inj, multiplicity.mul' hp]; refl else begin rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)], cases not_and_distrib.1 h with h h; simp [eq_top_iff_not_finite.2 h] end protected lemma pow' {p a : α} (hp : prime p) (ha : finite p a) : ∀ {k : ℕ}, get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha | 0 := by dsimp [_root_.pow_zero]; simp [one_right hp.2.1]; refl | (k+1) := by dsimp only [_root_.pow_succ]; erw [multiplicity.mul' hp, pow', add_mul, one_mul, add_comm] lemma pow {p a : α} (hp : prime p) : ∀ {k : ℕ}, multiplicity p (a ^ k) = add_monoid.smul k (multiplicity p a) | 0 := by simp [one_right hp.2.1] | (succ k) := by simp [_root_.pow_succ, succ_smul, pow, multiplicity.mul hp] end integral_domain end multiplicity section nat open multiplicity lemma multiplicity_eq_zero_of_coprime {p a b : ℕ} (hp : p ≠ 1) (hle : multiplicity p a ≤ multiplicity p b) (hab : nat.coprime a b) : multiplicity p a = 0 := begin rw [multiplicity_le_multiplicity_iff] at hle, rw [← le_zero_iff_eq, ← not_lt, enat.pos_iff_one_le, ← enat.coe_one, ← pow_dvd_iff_le_multiplicity], assume h, have := nat.dvd_gcd h (hle _ h), rw [coprime.gcd_eq_one hab, nat.dvd_one, _root_.pow_one] at this, exact hp this end end nat
e8a261d37953a4dd4dadae0d2ab93657bf117eaa
efce24474b28579aba3272fdb77177dc2b11d7aa
/src/homotopy_theory/formal/i_category/cylinder_object.lean
385cc263df18ccfb25e02a69c5d7a05969692f1a
[ "Apache-2.0" ]
permissive
rwbarton/lean-homotopy-theory
cff499f24268d60e1c546e7c86c33f58c62888ed
39e1b4ea1ed1b0eca2f68bc64162dde6a6396dee
refs/heads/lean-3.4.2
1,622,711,883,224
1,598,550,958,000
1,598,550,958,000
136,023,667
12
6
Apache-2.0
1,573,187,573,000
1,528,116,262,000
Lean
UTF-8
Lean
false
false
2,139
lean
import .homotopy_equivalences import .lemmas universes v u open category_theory open category_theory.category local notation f ` ∘ `:80 g:80 := g ≫ f /- We show that IA is a cylinder object for A, in the sense that A ⊔ A → IA → A is a factorization of the fold map into a cofibration followed by a homotopy equivalence. -/ namespace homotopy_theory.cofibrations section C open category_theory.has_initial_object open homotopy_theory.cylinder open I_category parameters {C : Type u} [category.{v} C] [has_initial_object.{v} C] [has_coproducts.{v} C] [I_category.{v} C] lemma cof_ii (a : C) : is_cof (ii.{v} @> a) := begin let po := (Is_pushout_of_isomorphic (Is_pushout.refl (! (∂I.obj a))) _ _ (coprod_initial_right ∅).symm (iso.refl _) (initial_object.unique Ii_initial has_initial_object.initial_object.is_initial_object) _ _), convert relative_cylinder' (! a) (all_objects_cofibrant.cofibrant.{v} a) _ _ po, any_goals { apply coprod.uniqueness; apply initial.uniqueness }, symmetry, convert ←(po.induced_commutes₀ _ _ _), convert id_comp _, simp end lemma i₀p {a : C} : i.{v} 0 @> a ∘ p @> a ≃ 𝟙 (I.obj a) := let ⟨J, hJ₁, hJ₂⟩ := hep_cof (ii.{v} @> a) (cof_ii a) 0 (I.obj a) (i 0 @> a ∘ p @> a) (I_of_coprod_is_coproduct.induced (i 0 @> a ∘ p @> a) (𝟙 (I.obj a))) $ begin apply coprod.uniqueness; erw i_nat_assoc; simp, rw ←assoc, dsimp, simp end in ⟨⟨J ∘ T @> a, begin erw [←assoc, cylinder_has_interchange.Ti], have : J ∘ I &> (i 0 @> a) = J ∘ I &> (ii @> a ∘ i₀), by simp [ii], rw this, rw [I.map_comp, assoc, hJ₂], simp end, begin erw [←assoc, cylinder_has_interchange.Ti], have : J ∘ I &> (i 1 @> a) = J ∘ I &> (ii @> a ∘ i₁), by simp [ii], rw this, rw [I.map_comp, assoc, hJ₂], simp end⟩⟩ lemma heq_p {a : C} : homotopy_equivalence.{v} (p @> a) := homotopy_equivalence_iff.mpr ⟨i 0 @> a, i₀p, by simp; refl⟩ lemma pii {a : C} : p.{v} @> a ∘ ii @> a = coprod.fold a := by apply coprod.uniqueness; simp end C end homotopy_theory.cofibrations
5f173285e3cf73473a54ec31a899551e451f854e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finset/fold.lean
9ebaefe51cdc6c1d5eeb8939ed027d943b07018e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
9,128
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.order.monoid.with_top import data.finset.image import data.multiset.fold /-! # The fold operation for a commutative associative operation over a finset. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace finset open multiset variables {α β γ : Type*} /-! ### fold -/ section fold variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op] local notation (name := op) a ` * ` b := op a b include hc ha /-- `fold op b f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_cons (h : a ∉ s) : (cons a s h).fold op b f = f a * s.fold op b f := by { dunfold fold, rw [cons_val, multiset.map_cons, fold_cons_left], } @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, multiset.map_cons, fold_cons_left] @[simp] theorem fold_singleton : ({a} : finset α).fold op b f = f a * b := rfl @[simp] theorem fold_map {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr rfl H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] lemma fold_const [decidable (s = ∅)] (c : β) (h : op c (op b c) = op b c) : finset.fold op b (λ _, c) s = if s = ∅ then b else op b c := begin classical, unfreezingI { induction s using finset.induction_on with x s hx IH }, { simp }, { simp only [finset.fold_insert hx, IH, if_false, finset.insert_ne_empty], split_ifs, { rw hc.comm }, { exact h } } end theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_disj_union {s₁ s₂ : finset α} {b₁ b₂ : β} (h) : (s₁.disj_union s₂ h).fold op (b₁ * b₂) f = s₁.fold op b₁ f * s₂.fold op b₂ f := (congr_arg _ $ multiset.map_add _ _ _).trans (multiset.fold_add _ _ _ _ _) theorem fold_disj_Union {ι : Type*} {s : finset ι} {t : ι → finset α} {b : ι → β} {b₀ : β} (h) : (s.disj_Union t h).fold op (s.fold op b₀ b) f = s.fold op b₀ (λ i, (t i).fold op (b i) f) := (congr_arg _ $ multiset.map_bind _ _ _).trans (multiset.fold_bind _ _ _ _ _) theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← multiset.map_add, union_val, inter_val, union_add_inter, multiset.map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := begin by_cases (a ∈ s), { rw [← insert_erase h], simp [← ha.assoc, hi.idempotent] }, { apply fold_insert h }, end theorem fold_image_idem [decidable_eq α] {g : γ → α} {s : finset γ} [hi : is_idempotent β op] : (image g s).fold op b f = s.fold op b (f ∘ g) := begin induction s using finset.cons_induction with x xs hx ih, { rw [fold_empty, image_empty, fold_empty] }, { haveI := classical.dec_eq γ, rw [fold_cons, cons_eq_insert, image_insert, fold_insert_idem, ih], } end /-- A stronger version of `finset.fold_ite`, but relies on an explicit proof of idempotency on the seed element, rather than relying on typeclass idempotency over the whole type. -/ lemma fold_ite' {g : α → β} (hb : op b b = b) (p : α → Prop) [decidable_pred p] : finset.fold op b (λ i, ite (p i) (f i) (g i)) s = op (finset.fold op b f (s.filter p)) (finset.fold op b g (s.filter (λ i, ¬ p i))) := begin classical, induction s using finset.induction_on with x s hx IH, { simp [hb] }, { simp only [finset.filter_congr_decidable, finset.fold_insert hx], split_ifs with h h, { have : x ∉ finset.filter p s, { simp [hx] }, simp [finset.filter_insert, h, finset.fold_insert this, ha.assoc, IH] }, { have : x ∉ finset.filter (λ i, ¬ p i) s, { simp [hx] }, simp [finset.filter_insert, h, finset.fold_insert this, IH, ←ha.assoc, hc.comm] } } end /-- A weaker version of `finset.fold_ite'`, relying on typeclass idempotency over the whole type, instead of solely on the seed element. However, this is easier to use because it does not generate side goals. -/ lemma fold_ite [is_idempotent β op] {g : α → β} (p : α → Prop) [decidable_pred p] : finset.fold op b (λ i, ite (p i) (f i) (g i)) s = op (finset.fold op b f (s.filter p)) (finset.fold op b g (s.filter (λ i, ¬ p i))) := fold_ite' (is_idempotent.idempotent _) _ lemma fold_op_rel_iff_and {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∧ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∧ ∀ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← and_assoc, and_comm (r c (f a)), and_assoc], apply and_congr iff.rfl, split, { rintro ⟨h₁, h₂⟩, intros b hb, rw finset.mem_insert at hb, rcases hb with rfl|hb; solve_by_elim }, { intro h, split, { exact h a (finset.mem_insert_self _ _), }, { intros b hb, apply h b, rw finset.mem_insert, right, exact hb } } end lemma fold_op_rel_iff_or {r : β → β → Prop} (hr : ∀ {x y z}, r x (op y z) ↔ (r x y ∨ r x z)) {c : β} : r c (s.fold op b f) ↔ (r c b ∨ ∃ x∈s, r c (f x)) := begin classical, apply finset.induction_on s, { simp }, clear s, intros a s ha IH, rw [finset.fold_insert ha, hr, IH, ← or_assoc, or_comm (r c (f a)), or_assoc], apply or_congr iff.rfl, split, { rintro (h₁|⟨x, hx, h₂⟩), { use a, simp [h₁] }, { refine ⟨x, by simp [hx], h₂⟩ } }, { rintro ⟨x, hx, h⟩, rw mem_insert at hx, cases hx, { left, rwa hx at h }, { right, exact ⟨x, hx, h⟩ } } end omit hc ha @[simp] lemma fold_union_empty_singleton [decidable_eq α] (s : finset α) : finset.fold (∪) ∅ singleton s = s := begin apply finset.induction_on s, { simp only [fold_empty], }, { intros a s has ih, rw [fold_insert has, ih, insert_eq], } end lemma fold_sup_bot_singleton [decidable_eq α] (s : finset α) : finset.fold (⊔) ⊥ singleton s = s := fold_union_empty_singleton s section order variables [linear_order β] (c : β) lemma le_fold_min : c ≤ s.fold min b f ↔ (c ≤ b ∧ ∀ x∈s, c ≤ f x) := fold_op_rel_iff_and $ λ x y z, le_min_iff lemma fold_min_le : s.fold min b f ≤ c ↔ (b ≤ c ∨ ∃ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ ≤ _ ↔ _, exact min_le_iff end lemma lt_fold_min : c < s.fold min b f ↔ (c < b ∧ ∀ x∈s, c < f x) := fold_op_rel_iff_and $ λ x y z, lt_min_iff lemma fold_min_lt : s.fold min b f < c ↔ (b < c ∨ ∃ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_or, intros x y z, show _ < _ ↔ _, exact min_lt_iff end lemma fold_max_le : s.fold max b f ≤ c ↔ (b ≤ c ∧ ∀ x∈s, f x ≤ c) := begin show _ ≥ _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ ≤ _ ↔ _, exact max_le_iff end lemma le_fold_max : c ≤ s.fold max b f ↔ (c ≤ b ∨ ∃ x∈s, c ≤ f x) := fold_op_rel_iff_or $ λ x y z, le_max_iff lemma fold_max_lt : s.fold max b f < c ↔ (b < c ∧ ∀ x∈s, f x < c) := begin show _ > _ ↔ _, apply fold_op_rel_iff_and, intros x y z, show _ < _ ↔ _, exact max_lt_iff end lemma lt_fold_max : c < s.fold max b f ↔ (c < b ∨ ∃ x∈s, c < f x) := fold_op_rel_iff_or $ λ x y z, lt_max_iff lemma fold_max_add [has_add β] [covariant_class β β (function.swap (+)) (≤)] (n : with_bot β) (s : finset α) : s.fold max ⊥ (λ (x : α), ↑(f x) + n) = s.fold max ⊥ (coe ∘ f) + n := by { classical, apply s.induction_on; simp [max_add_add_right] {contextual := tt} } end order end fold end finset
64a0c2f82d077950bd791f5ad8019a1da386f3cf
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/lean/string_imp2.lean
77821577c6909abdfe8e01216435e44f917bde5f
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
2,556
lean
def f (s : String) : String := s ++ " " ++ s def g (s : String) : String := s.push ' ' ++ s.push '-' def h (s : String) : String := let it₁ := s.mkIterator in let it₂ := it₁.next in it₁.remainingToString ++ "-" ++ it₂.remainingToString #exit -- Disabled until we implement new VM def r (s : String) : String := let it₁ := s.mkIterator.toEnd in let it₂ := it₁.prev in it₁.prevToString ++ "-" ++ it₂.prevToString def s (s : String) : String := let it₁ := s.mkIterator.toEnd in let it₂ := it₁.prev in (it₁.insert "abc").toString ++ (it₂.insert "de").toString #eval "hello" ++ "hello" #eval f "hello" #eval (f "αβ").length #eval "hello".toList #eval "αβ".toList #eval "".toList #eval "αβγ".toList #eval "αβγ".mkIterator.1 #eval "αβγ".mkIterator.next.1 #eval "αβγ".mkIterator.next.next.1 #eval "αβγ".mkIterator.next.2 #eval "αβ".1 #eval "αβ".push 'a' #eval g "α" #eval "".mkIterator.curr #eval ("αβγ".mkIterator.setCurr 'a').toString #eval (("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').toString #eval ((("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').next.setCurr 'c').toString #eval ((("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').prev.setCurr 'c').toString #eval ("abc".mkIterator.setCurr '0').toString #eval (("abc".mkIterator.setCurr '0').next.setCurr '1').toString #eval ((("abc".mkIterator.setCurr '0').next.setCurr '1').next.setCurr '2').toString #eval ((("abc".mkIterator.setCurr '0').next.setCurr '1').prev.setCurr '2').toString #eval ("abc".mkIterator.setCurr (Char.ofNat 955)).toString #eval h "abc" #eval "abc".mkIterator.remainingToString #eval ("a".push (Char.ofNat 0)) ++ "bb" #eval (("a".push (Char.ofNat 0)) ++ "αb").length #eval r "abc" #eval "abc".mkIterator.toEnd.prevToString #eval "".mkIterator.hasNext #eval "a".mkIterator.hasNext #eval "a".mkIterator.next.hasNext #eval "".mkIterator.hasPrev #eval "a".mkIterator.next.hasPrev #eval "αβ".mkIterator.next.hasPrev #eval "αβ".mkIterator.next.prev.hasPrev #eval ("αβ".mkIterator.toEnd.insert "abc").toString #eval ("αβ".mkIterator.next.insert "abc").toString #eval s "αβ" #eval ("abcdef".mkIterator.next.remove 2).toString #eval ("abcdef".mkIterator.next.next.remove 2).toString #eval ("abcdef".mkIterator.next.remove 3).toString #eval (("abcdef".mkIterator.next.next.next.remove 100).prev.setCurr 'a').toString #eval ("abcdef".mkIterator.next.next.next.remove 100).hasNext #eval ("abcdef".mkIterator.next.next.next.remove 100).prev.hasNext #eval toBool $ "abc" = "abc" #eval toBool $ "abc" = "abd"
38495593c0d4b8723610703370d61560cb482e68
c2d3fec70c4d83c328c648449c5f2b1c48e8c05c
/propositional.lean
f5ee24978f4e6c0bdfb176e176967315d757dbf9
[]
no_license
agro1986/lean-proofs
d603364212d46c30601da94660f4f0133a47d793
a11b42ec47dbb347b66547d7e72e5154e13b6e85
refs/heads/master
1,598,977,963,373
1,572,882,333,000
1,572,882,333,000
219,005,217
0
0
null
null
null
null
UTF-8
Lean
false
false
1,602
lean
variables p q r s: Prop -- commutativity of ∧ and ∨ theorem and_switch (h: p ∧ q): q ∧ p := and.intro h.right h.left example: p ∧ q ↔ q ∧ p := iff.intro (and_switch p q) (and_switch q p) theorem or_switch (h: p ∨ q): q ∨ p := or.elim h (assume p, or.inr p) (assume q, or.inl q) example: p ∨ q ↔ q ∨ p := iff.intro (or_switch p q) (or_switch q p) -- associativity of ∧ and ∨ example: p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := iff.intro (assume h: p ∧ (q ∨ r), have hp: p, from h.left, or.elim h.right (assume hq: q, have hpq: p ∧ q, from and.intro hp hq, or.inl hpq) (assume hr: r, have hpr: p ∧ r, from and.intro hp hr, or.inr hpr)) (assume h: (p ∧ q) ∨ (p ∧ r), or.elim h (assume hpq: p ∧ q, have hp: p, from hpq.left, have hqr: q ∨ r, from or.inl hpq.right, and.intro hp hqr) (assume hpr: p ∧ r, have hp: p, from hpr.left, have hqr: q ∨ r, from or.inr hpr.right, and.intro hp hqr)) example: (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := iff.intro (assume h: (p ∧ q) ∧ r, have hpq: p ∧ q, from h.left, have hp: p, from hpq.left, have hq: q, from hpq.right, have hr: r, from h.right, ⟨hp, ⟨hq, hr⟩⟩) (assume h: p ∧ (q ∧ r), have hp: p, from h.left, have hqr: q ∧ r, from h.right, have hq: q, from hqr.left, have hr: r, from hqr.right, ⟨⟨hp, hq⟩, hr⟩)
9c08ea74b6bf8fcbb860c3586cc045d35f758a43
46125763b4dbf50619e8846a1371029346f4c3db
/src/order/complete_boolean_algebra.lean
347f77593dc8dd6e3c02cc565c8fe97c7dfe113e
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
4,647
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 Theory of complete Boolean algebras. -/ import order.complete_lattice order.boolean_algebra data.set.basic set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} namespace lattice section prio set_option default_priority 100 -- see Note [default priority] /-- A complete distributive lattice is a bit stronger than the name might suggest; perhaps completely distributive lattice is more descriptive, as this class includes a requirement that the lattice join distribute over *arbitrary* infima, and similarly for the dual. -/ class complete_distrib_lattice α extends complete_lattice α := (infi_sup_le_sup_Inf : ∀a s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s) (inf_Sup_le_supr_inf : ∀a s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b)) end prio section complete_distrib_lattice variables [complete_distrib_lattice α] {a b : α} {s t : set α} theorem sup_Inf_eq : a ⊔ Inf s = (⨅ b ∈ s, a ⊔ b) := le_antisymm (le_infi $ assume i, le_infi $ assume h, sup_le_sup (le_refl _) (Inf_le h)) (complete_distrib_lattice.infi_sup_le_sup_Inf _ _) theorem Inf_sup_eq : Inf s ⊔ b = (⨅ a ∈ s, a ⊔ b) := by simpa [sup_comm] using @sup_Inf_eq α _ b s theorem inf_Sup_eq : a ⊓ Sup s = (⨆ b ∈ s, a ⊓ b) := le_antisymm (complete_distrib_lattice.inf_Sup_le_supr_inf _ _) (supr_le $ assume i, supr_le $ assume h, inf_le_inf (le_refl _) (le_Sup h)) theorem Sup_inf_eq : Sup s ⊓ b = (⨆ a ∈ s, a ⊓ b) := by simpa [inf_comm] using @inf_Sup_eq α _ b s theorem Inf_sup_Inf : Inf s ⊔ Inf t = (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) := begin apply le_antisymm, { finish }, { have : ∀ a ∈ s, (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ a ⊔ Inf t, { assume a ha, have : (⨅p ∈ set.prod s t, ((p : α × α).1 : α) ⊔ p.2) ≤ (⨅p ∈ prod.mk a '' t, (p : α × α).1 ⊔ p.2), { apply infi_le_infi_of_subset, rintros ⟨x, y⟩, simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq, exists_imp_distrib], assume x' x't ax x'y, rw [← x'y, ← ax], simp [ha, x't] }, rw [infi_image] at this, simp only [] at this, rwa ← sup_Inf_eq at this }, calc (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ (⨅a∈s, a ⊔ Inf t) : by simp; exact this ... = Inf s ⊔ Inf t : Inf_sup_eq.symm } end theorem Sup_inf_Sup : Sup s ⊓ Sup t = (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2) := begin apply le_antisymm, { have : ∀ a ∈ s, a ⊓ Sup t ≤ (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2), { assume a ha, have : (⨆p ∈ prod.mk a '' t, (p : α × α).1 ⊓ p.2) ≤ (⨆p ∈ set.prod s t, ((p : α × α).1 : α) ⊓ p.2), { apply supr_le_supr_of_subset, rintros ⟨x, y⟩, simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq, exists_imp_distrib], assume x' x't ax x'y, rw [← x'y, ← ax], simp [ha, x't] }, rw [supr_image] at this, simp only [] at this, rwa ← inf_Sup_eq at this }, calc Sup s ⊓ Sup t = (⨆a∈s, a ⊓ Sup t) : Sup_inf_eq ... ≤ (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2) : by simp; exact this }, { finish } end end complete_distrib_lattice @[priority 100] -- see Note [lower instance priority] instance [d : complete_distrib_lattice α] : bounded_distrib_lattice α := { le_sup_inf := λ x y z, by rw [← Inf_pair, ← Inf_pair, sup_Inf_eq, ← Inf_image, set.image_pair], ..d } section prio set_option default_priority 100 -- see Note [default priority] /-- A complete boolean algebra is a completely distributive boolean algebra. -/ class complete_boolean_algebra α extends boolean_algebra α, complete_distrib_lattice α end prio section complete_boolean_algebra variables [complete_boolean_algebra α] {a b : α} {s : set α} {f : ι → α} theorem neg_infi : - infi f = (⨆i, - f i) := le_antisymm (neg_le_of_neg_le $ le_infi $ assume i, neg_le_of_neg_le $ le_supr (λi, - f i) i) (supr_le $ assume i, neg_le_neg $ infi_le _ _) theorem neg_supr : - supr f = (⨅i, - f i) := neg_eq_neg_of_eq (by simp [neg_infi]) theorem neg_Inf : - Inf s = (⨆i∈s, - i) := by simp [Inf_eq_infi, neg_infi] theorem neg_Sup : - Sup s = (⨅i∈s, - i) := by simp [Sup_eq_supr, neg_supr] end complete_boolean_algebra end lattice
7689c06965945ce8546aa02458694b2012dd64aa
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/jacobson.lean
c4f252cd949d89537e8db70a06391d636e06c717
[ "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
34,288
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Devon Tuma -/ import ring_theory.localization.away import ring_theory.ideal.over import ring_theory.jacobson_ideal /-! # Jacobson Rings The following conditions are equivalent for a ring `R`: 1. Every radical ideal `I` is equal to its Jacobson radical 2. Every radical ideal `I` can be written as an intersection of maximal ideals 3. Every prime ideal `I` is equal to its Jacobson radical Any ring satisfying any of these equivalent conditions is said to be Jacobson. Some particular examples of Jacobson rings are also proven. `is_jacobson_quotient` says that the quotient of a Jacobson ring is Jacobson. `is_jacobson_localization` says the localization of a Jacobson ring to a single element is Jacobson. `is_jacobson_polynomial_iff_is_jacobson` says polynomials over a Jacobson ring form a Jacobson ring. ## Main definitions Let `R` be a commutative ring. Jacobson Rings are defined using the first of the above conditions * `is_jacobson R` is the proposition that `R` is a Jacobson ring. It is a class, implemented as the predicate that for any ideal, `I.is_radical` implies `I.jacobson = I`. ## Main statements * `is_jacobson_iff_prime_eq` is the equivalence between conditions 1 and 3 above. * `is_jacobson_iff_Inf_maximal` is the equivalence between conditions 1 and 2 above. * `is_jacobson_of_surjective` says that if `R` is a Jacobson ring and `f : R →+* S` is surjective, then `S` is also a Jacobson ring * `is_jacobson_mv_polynomial` says that multi-variate polynomials over a Jacobson ring are Jacobson. ## Tags Jacobson, Jacobson Ring -/ namespace ideal open polynomial open_locale polynomial section is_jacobson variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R} /-- A ring is a Jacobson ring if for every radical ideal `I`, the Jacobson radical of `I` is equal to `I`. See `is_jacobson_iff_prime_eq` and `is_jacobson_iff_Inf_maximal` for equivalent definitions. -/ class is_jacobson (R : Type*) [comm_ring R] : Prop := (out' : ∀ (I : ideal R), I.is_radical → I.jacobson = I) theorem is_jacobson_iff {R} [comm_ring R] : is_jacobson R ↔ ∀ (I : ideal R), I.is_radical → I.jacobson = I := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem is_jacobson.out {R} [comm_ring R] : is_jacobson R → ∀ {I : ideal R}, I.is_radical → I.jacobson = I := is_jacobson_iff.1 /-- A ring is a Jacobson ring if and only if for all prime ideals `P`, the Jacobson radical of `P` is equal to `P`. -/ lemma is_jacobson_iff_prime_eq : is_jacobson R ↔ ∀ P : ideal R, is_prime P → P.jacobson = P := begin refine is_jacobson_iff.trans ⟨λ h I hI, h I hI.is_radical, _⟩, refine λ h I hI, le_antisymm (λ x hx, _) (λ x hx, mem_Inf.mpr (λ _ hJ, hJ.left hx)), rw [← hI.radical, radical_eq_Inf I, mem_Inf], intros P hP, rw set.mem_set_of_eq at hP, erw mem_Inf at hx, erw [← h P hP.right, mem_Inf], exact λ J hJ, hx ⟨le_trans hP.left hJ.left, hJ.right⟩ end /-- A ring `R` is Jacobson if and only if for every prime ideal `I`, `I` can be written as the infimum of some collection of maximal ideals. Allowing ⊤ in the set `M` of maximal ideals is equivalent, but makes some proofs cleaner. -/ lemma is_jacobson_iff_Inf_maximal : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ J ∈ M, is_maximal J ∨ J = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal.1 (H.out h.is_radical), λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal.2 (H hP))⟩ lemma is_jacobson_iff_Inf_maximal' : is_jacobson R ↔ ∀ {I : ideal R}, I.is_prime → ∃ M : set (ideal R), (∀ (J ∈ M) (K : ideal R), J < K → K = ⊤) ∧ I = Inf M := ⟨λ H I h, eq_jacobson_iff_Inf_maximal'.1 (H.out h.is_radical), λ H, is_jacobson_iff_prime_eq.2 (λ P hP, eq_jacobson_iff_Inf_maximal'.2 (H hP))⟩ lemma radical_eq_jacobson [H : is_jacobson R] (I : ideal R) : I.radical = I.jacobson := le_antisymm (le_Inf (λ J ⟨hJ, hJ_max⟩, (is_prime.radical_le_iff hJ_max.is_prime).mpr hJ)) (H.out (radical_is_radical I) ▸ jacobson_mono le_radical) /-- Fields have only two ideals, and the condition holds for both of them. -/ @[priority 100] instance is_jacobson_field {K : Type*} [field K] : is_jacobson K := ⟨λ I hI, or.rec_on (eq_bot_or_top I) (λ h, le_antisymm (Inf_le ⟨le_rfl, h.symm ▸ bot_is_maximal⟩) (h.symm ▸ bot_le)) (λ h, by rw [h, jacobson_eq_top_iff])⟩ theorem is_jacobson_of_surjective [H : is_jacobson R] : (∃ (f : R →+* S), function.surjective f) → is_jacobson S := begin rintros ⟨f, hf⟩, rw is_jacobson_iff_Inf_maximal, intros p hp, use map f '' {J : ideal R | comap f p ≤ J ∧ J.is_maximal }, use λ j ⟨J, hJ, hmap⟩, hmap ▸ (map_eq_top_or_is_maximal_of_surjective f hf hJ.right).symm, have : p = map f (comap f p).jacobson := (is_jacobson.out' _ $ hp.is_radical.comap f).symm ▸ (map_comap_of_surjective f hf p).symm, exact this.trans (map_Inf hf (λ J ⟨hJ, _⟩, le_trans (ideal.ker_le_comap f) hJ)), end @[priority 100] instance is_jacobson_quotient [is_jacobson R] : is_jacobson (R ⧸ I) := is_jacobson_of_surjective ⟨quotient.mk I, (by rintro ⟨x⟩; use x; refl)⟩ lemma is_jacobson_iso (e : R ≃+* S) : is_jacobson R ↔ is_jacobson S := ⟨λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e : R →+* S), e.surjective⟩, λ h, @is_jacobson_of_surjective _ _ _ _ h ⟨(e.symm : S →+* R), e.symm.surjective⟩⟩ lemma is_jacobson_of_is_integral [algebra R S] (hRS : algebra.is_integral R S) (hR : is_jacobson R) : is_jacobson S := begin rw is_jacobson_iff_prime_eq, introsI P hP, by_cases hP_top : comap (algebra_map R S) P = ⊤, { simp [comap_eq_top_iff.1 hP_top] }, { haveI : nontrivial (R ⧸ comap (algebra_map R S) P) := quotient.nontrivial hP_top, rw jacobson_eq_iff_jacobson_quotient_eq_bot, refine eq_bot_of_comap_eq_bot (is_integral_quotient_of_is_integral hRS) _, rw [eq_bot_iff, ← jacobson_eq_iff_jacobson_quotient_eq_bot.1 ((is_jacobson_iff_prime_eq.1 hR) (comap (algebra_map R S) P) (comap_is_prime _ _)), comap_jacobson], refine Inf_le_Inf (λ J hJ, _), simp only [true_and, set.mem_image, bot_le, set.mem_set_of_eq], haveI : J.is_maximal, { simpa using hJ }, exact exists_ideal_over_maximal_of_is_integral (is_integral_quotient_of_is_integral hRS) J (comap_bot_le_of_injective _ algebra_map_quotient_injective) } end lemma is_jacobson_of_is_integral' (f : R →+* S) (hf : f.is_integral) (hR : is_jacobson R) : is_jacobson S := @is_jacobson_of_is_integral _ _ _ _ f.to_algebra hf hR end is_jacobson section localization open is_localization submonoid variables {R S : Type*} [comm_ring R] [comm_ring S] {I : ideal R} variables (y : R) [algebra R S] [is_localization.away y S] lemma disjoint_powers_iff_not_mem (hI : I.is_radical) : disjoint ((submonoid.powers y) : set R) ↑I ↔ y ∉ I.1 := begin refine ⟨λ h, set.disjoint_left.1 h (mem_powers _), λ h, disjoint_iff.mpr (eq_bot_iff.mpr _)⟩, rintros x ⟨⟨n, rfl⟩, hx'⟩, exact h (hI $ mem_radical_of_pow_mem $ le_radical hx') end variables (S) /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its comap. See `le_rel_iso_of_maximal` for the more general relation isomorphism -/ lemma is_maximal_iff_is_maximal_disjoint [H : is_jacobson R] (J : ideal S) : J.is_maximal ↔ (comap (algebra_map R S) J).is_maximal ∧ y ∉ ideal.comap (algebra_map R S) J := begin split, { refine λ h, ⟨_, λ hy, h.ne_top (ideal.eq_top_of_is_unit_mem _ hy (map_units _ ⟨y, submonoid.mem_powers _⟩))⟩, have hJ : J.is_prime := is_maximal.is_prime h, rw is_prime_iff_is_prime_disjoint (submonoid.powers y) at hJ, have : y ∉ (comap (algebra_map R S) J).1 := set.disjoint_left.1 hJ.right (submonoid.mem_powers _), erw [← H.out hJ.left.is_radical, mem_Inf] at this, push_neg at this, rcases this with ⟨I, hI, hI'⟩, convert hI.right, by_cases hJ : J = map (algebra_map R S) I, { rw [hJ, comap_map_of_is_prime_disjoint (powers y) S I (is_maximal.is_prime hI.right)], rwa disjoint_powers_iff_not_mem y hI.right.is_prime.is_radical }, { have hI_p : (map (algebra_map R S) I).is_prime, { refine is_prime_of_is_prime_disjoint (powers y) _ I hI.right.is_prime _, rwa disjoint_powers_iff_not_mem y hI.right.is_prime.is_radical }, have : J ≤ map (algebra_map R S) I := (map_comap (submonoid.powers y) S J) ▸ (map_mono hI.left), exact absurd (h.1.2 _ (lt_of_le_of_ne this hJ)) hI_p.1 } }, { refine λ h, ⟨⟨λ hJ, h.1.ne_top (eq_top_iff.2 _), λ I hI, _⟩⟩, { rwa [eq_top_iff, ← (is_localization.order_embedding (powers y) S).le_iff_le] at hJ }, { have := congr_arg (map (algebra_map R S)) (h.1.1.2 _ ⟨comap_mono (le_of_lt hI), _⟩), rwa [map_comap (powers y) S I, map_top] at this, refine λ hI', hI.right _, rw [← map_comap (powers y) S I, ← map_comap (powers y) S J], exact map_mono hI' } } end variables {S} /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y`. This lemma gives the correspondence in the particular case of an ideal and its map. See `le_rel_iso_of_maximal` for the more general statement, and the reverse of this implication -/ lemma is_maximal_of_is_maximal_disjoint [is_jacobson R] (I : ideal R) (hI : I.is_maximal) (hy : y ∉ I) : (map (algebra_map R S) I).is_maximal := begin rw [is_maximal_iff_is_maximal_disjoint S y, comap_map_of_is_prime_disjoint (powers y) S I (is_maximal.is_prime hI) ((disjoint_powers_iff_not_mem y hI.is_prime.is_radical).2 hy)], exact ⟨hI, hy⟩ end /-- If `R` is a Jacobson ring, then maximal ideals in the localization at `y` correspond to maximal ideals in the original ring `R` that don't contain `y` -/ def order_iso_of_maximal [is_jacobson R] : {p : ideal S // p.is_maximal} ≃o {p : ideal R // p.is_maximal ∧ y ∉ p} := { to_fun := λ p, ⟨ideal.comap (algebra_map R S) p.1, (is_maximal_iff_is_maximal_disjoint S y p.1).1 p.2⟩, inv_fun := λ p, ⟨ideal.map (algebra_map R S) p.1, is_maximal_of_is_maximal_disjoint y p.1 p.2.1 p.2.2⟩, left_inv := λ J, subtype.eq (map_comap (powers y) S J), right_inv := λ I, subtype.eq (comap_map_of_is_prime_disjoint _ _ I.1 (is_maximal.is_prime I.2.1) ((disjoint_powers_iff_not_mem y I.2.1.is_prime.is_radical).2 I.2.2)), map_rel_iff' := λ I I', ⟨λ h, (show I.val ≤ I'.val, from (map_comap (powers y) S I.val) ▸ (map_comap (powers y) S I'.val) ▸ (ideal.map_mono h)), λ h x hx, h hx⟩ } include y /-- If `S` is the localization of the Jacobson ring `R` at the submonoid generated by `y : R`, then `S` is Jacobson. -/ lemma is_jacobson_localization [H : is_jacobson R] : is_jacobson S := begin rw is_jacobson_iff_prime_eq, refine λ P' hP', le_antisymm _ le_jacobson, obtain ⟨hP', hPM⟩ := (is_localization.is_prime_iff_is_prime_disjoint (powers y) S P').mp hP', have hP := H.out hP'.is_radical, refine (is_localization.map_comap (powers y) S P'.jacobson).ge.trans ((map_mono _).trans (is_localization.map_comap (powers y) S P').le), have : Inf { I : ideal R | comap (algebra_map R S) P' ≤ I ∧ I.is_maximal ∧ y ∉ I } ≤ comap (algebra_map R S) P', { intros x hx, have hxy : x * y ∈ (comap (algebra_map R S) P').jacobson, { rw [ideal.jacobson, mem_Inf], intros J hJ, by_cases y ∈ J, { exact J.mul_mem_left x h }, { exact J.mul_mem_right y ((mem_Inf.1 hx) ⟨hJ.left, ⟨hJ.right, h⟩⟩) } }, rw hP at hxy, cases hP'.mem_or_mem hxy with hxy hxy, { exact hxy }, { exact (hPM.le_bot ⟨submonoid.mem_powers _, hxy⟩).elim } }, refine le_trans _ this, rw [ideal.jacobson, comap_Inf', Inf_eq_infi], refine infi_le_infi_of_subset (λ I hI, ⟨map (algebra_map R S) I, ⟨_, _⟩⟩), { exact ⟨le_trans (le_of_eq ((is_localization.map_comap (powers y) S P').symm)) (map_mono hI.1), is_maximal_of_is_maximal_disjoint y _ hI.2.1 hI.2.2⟩ }, { exact is_localization.comap_map_of_is_prime_disjoint _ S I (is_maximal.is_prime hI.2.1) ((disjoint_powers_iff_not_mem y hI.2.1.is_prime.is_radical).2 hI.2.2) } end end localization namespace polynomial open polynomial section comm_ring variables {R S : Type*} [comm_ring R] [comm_ring S] [is_domain S] variables {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] /-- If `I` is a prime ideal of `R[X]` and `pX ∈ I` is a non-constant polynomial, then the map `R →+* R[x]/I` descends to an integral map when localizing at `pX.leading_coeff`. In particular `X` is integral because it satisfies `pX`, and constants are trivially integral, so integrality of the entire extension follows by closure under addition and multiplication. -/ lemma is_integral_is_localization_polynomial_quotient (P : ideal R[X]) (pX : R[X]) (hpX : pX ∈ P) [algebra (R ⧸ P.comap (C : R →+* _)) Rₘ] [is_localization.away (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff Rₘ] [algebra (R[X] ⧸ P) Sₘ] [is_localization ((submonoid.powers (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff).map (quotient_map P C le_rfl) : submonoid (R[X] ⧸ P)) Sₘ] : (is_localization.map Sₘ (quotient_map P C le_rfl) ((submonoid.powers (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff).le_comap_map) : Rₘ →+* _) .is_integral := begin let P' : ideal R := P.comap C, let M : submonoid (R ⧸ P') := submonoid.powers (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff, let M' : submonoid (R[X] ⧸ P) := (submonoid.powers (pX.map (quotient.mk (P.comap (C : R →+* R[X])))).leading_coeff).map (quotient_map P C le_rfl), let φ : R ⧸ P' →+* R[X] ⧸ P := quotient_map P C le_rfl, let φ' : Rₘ →+* Sₘ := is_localization.map Sₘ φ M.le_comap_map, have hφ' : φ.comp (quotient.mk P') = (quotient.mk P).comp C := rfl, intro p, obtain ⟨⟨p', ⟨q, hq⟩⟩, hp⟩ := is_localization.surj M' p, suffices : φ'.is_integral_elem (algebra_map _ _ p'), { obtain ⟨q', hq', rfl⟩ := hq, obtain ⟨q'', hq''⟩ := is_unit_iff_exists_inv'.1 (is_localization.map_units Rₘ (⟨q', hq'⟩ : M)), refine φ'.is_integral_of_is_integral_mul_unit p (algebra_map _ _ (φ q')) q'' _ (hp.symm ▸ this), convert trans (trans (φ'.map_mul _ _).symm (congr_arg φ' hq'')) φ'.map_one using 2, rw [← φ'.comp_apply, is_localization.map_comp, ring_hom.comp_apply, subtype.coe_mk] }, refine is_integral_of_mem_closure'' (((algebra_map _ Sₘ).comp (quotient.mk P)) '' (insert X {p | p.degree ≤ 0})) _ _ _, { rintros x ⟨p, hp, rfl⟩, refine hp.rec_on (λ hy, _) (λ hy, _), { refine hy.symm ▸ (φ.is_integral_elem_localization_at_leading_coeff ((quotient.mk P) X) (pX.map (quotient.mk P')) _ M ⟨1, pow_one _⟩), rwa [eval₂_map, hφ', ← hom_eval₂, quotient.eq_zero_iff_mem, eval₂_C_X] }, { rw [set.mem_set_of_eq, degree_le_zero_iff] at hy, refine hy.symm ▸ ⟨X - C (algebra_map _ _ ((quotient.mk P') (p.coeff 0))), monic_X_sub_C _, _⟩, simp only [eval₂_sub, eval₂_C, eval₂_X], rw [sub_eq_zero, ← φ'.comp_apply, is_localization.map_comp], refl } }, { obtain ⟨p, rfl⟩ := quotient.mk_surjective p', refine polynomial.induction_on p (λ r, subring.subset_closure $ set.mem_image_of_mem _ (or.inr degree_C_le)) (λ _ _ h1 h2, _) (λ n _ hr, _), { convert subring.add_mem _ h1 h2, rw [ring_hom.map_add, ring_hom.map_add] }, { rw [pow_succ X n, mul_comm X, ← mul_assoc, ring_hom.map_mul, ring_hom.map_mul], exact subring.mul_mem _ hr (subring.subset_closure (set.mem_image_of_mem _ (or.inl rfl))) } }, end /-- If `f : R → S` descends to an integral map in the localization at `x`, and `R` is a Jacobson ring, then the intersection of all maximal ideals in `S` is trivial -/ lemma jacobson_bot_of_integral_localization {R : Type*} [comm_ring R] [is_domain R] [is_jacobson R] (Rₘ Sₘ : Type*) [comm_ring Rₘ] [comm_ring Sₘ] (φ : R →+* S) (hφ : function.injective φ) (x : R) (hx : x ≠ 0) [algebra R Rₘ] [is_localization.away x Rₘ] [algebra S Sₘ] [is_localization ((submonoid.powers x).map φ : submonoid S) Sₘ] (hφ' : ring_hom.is_integral (is_localization.map Sₘ φ (submonoid.powers x).le_comap_map : Rₘ →+* Sₘ)) : (⊥ : ideal S).jacobson = (⊥ : ideal S) := begin have hM : ((submonoid.powers x).map φ : submonoid S) ≤ non_zero_divisors S := map_le_non_zero_divisors_of_injective φ hφ (powers_le_non_zero_divisors_of_no_zero_divisors hx), letI : is_domain Sₘ := is_localization.is_domain_of_le_non_zero_divisors _ hM, let φ' : Rₘ →+* Sₘ := is_localization.map _ φ (submonoid.powers x).le_comap_map, suffices : ∀ I : ideal Sₘ, I.is_maximal → (I.comap (algebra_map S Sₘ)).is_maximal, { have hϕ' : comap (algebra_map S Sₘ) (⊥ : ideal Sₘ) = (⊥ : ideal S), { rw [← ring_hom.ker_eq_comap_bot, ← ring_hom.injective_iff_ker_eq_bot], exact is_localization.injective Sₘ hM }, have hSₘ : is_jacobson Sₘ := is_jacobson_of_is_integral' φ' hφ' (is_jacobson_localization x), refine eq_bot_iff.mpr (le_trans _ (le_of_eq hϕ')), rw [← hSₘ.out is_radical_bot_of_no_zero_divisors, comap_jacobson], exact Inf_le_Inf (λ j hj, ⟨bot_le, let ⟨J, hJ⟩ := hj in hJ.2 ▸ this J hJ.1.2⟩) }, introsI I hI, -- Remainder of the proof is pulling and pushing ideals around the square and the quotient square haveI : (I.comap (algebra_map S Sₘ)).is_prime := comap_is_prime _ I, haveI : (I.comap φ').is_prime := comap_is_prime φ' I, haveI : (⊥ : ideal (S ⧸ I.comap (algebra_map S Sₘ))).is_prime := bot_prime, have hcomm: φ'.comp (algebra_map R Rₘ) = (algebra_map S Sₘ).comp φ := is_localization.map_comp _, let f := quotient_map (I.comap (algebra_map S Sₘ)) φ le_rfl, let g := quotient_map I (algebra_map S Sₘ) le_rfl, have := is_maximal_comap_of_is_integral_of_is_maximal' φ' hφ' I hI, have := ((is_maximal_iff_is_maximal_disjoint Rₘ x _).1 this).left, have : ((I.comap (algebra_map S Sₘ)).comap φ).is_maximal, { rwa [comap_comap, hcomm, ← comap_comap] at this }, rw ← bot_quotient_is_maximal_iff at this ⊢, refine is_maximal_of_is_integral_of_is_maximal_comap' f _ ⊥ ((eq_bot_iff.2 (comap_bot_le_of_injective f quotient_map_injective)).symm ▸ this), exact f.is_integral_tower_bot_of_is_integral g quotient_map_injective ((comp_quotient_map_eq_of_comp_eq hcomm I).symm ▸ (ring_hom.is_integral_trans _ _ (ring_hom.is_integral_of_surjective _ (is_localization.surjective_quotient_map_of_maximal_of_localization (submonoid.powers x) Rₘ (by rwa [comap_comap, hcomm, ← bot_quotient_is_maximal_iff]))) (ring_hom.is_integral_quotient_of_is_integral _ hφ'))), end /-- Used to bootstrap the proof of `is_jacobson_polynomial_iff_is_jacobson`. That theorem is more general and should be used instead of this one. -/ private lemma is_jacobson_polynomial_of_domain (R : Type*) [comm_ring R] [is_domain R] [hR : is_jacobson R] (P : ideal R[X]) [is_prime P] (hP : ∀ (x : R), C x ∈ P → x = 0) : P.jacobson = P := begin by_cases Pb : P = ⊥, { exact Pb.symm ▸ jacobson_bot_polynomial_of_jacobson_bot (hR.out is_radical_bot_of_no_zero_divisors) }, { rw jacobson_eq_iff_jacobson_quotient_eq_bot, haveI : (P.comap (C : R →+* R[X])).is_prime := comap_is_prime C P, obtain ⟨p, pP, p0⟩ := exists_nonzero_mem_of_ne_bot Pb hP, let x := (polynomial.map (quotient.mk (comap (C : R →+* _) P)) p).leading_coeff, have hx : x ≠ 0 := by rwa [ne.def, leading_coeff_eq_zero], refine jacobson_bot_of_integral_localization (localization.away x) (localization ((submonoid.powers x).map (P.quotient_map C le_rfl) : submonoid (R[X] ⧸ P))) (quotient_map P C le_rfl) quotient_map_injective x hx _, -- `convert` is noticeably faster than `exact` here: convert is_integral_is_localization_polynomial_quotient P p pP } end lemma is_jacobson_polynomial_of_is_jacobson (hR : is_jacobson R) : is_jacobson R[X] := begin refine is_jacobson_iff_prime_eq.mpr (λ I, _), introI hI, let R' : subring (R[X] ⧸ I) := ((quotient.mk I).comp C).range, let i : R →+* R' := ((quotient.mk I).comp C).range_restrict, have hi : function.surjective (i : R → R') := ((quotient.mk I).comp C).range_restrict_surjective, have hi' : (polynomial.map_ring_hom i : R[X] →+* R'[X]).ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), replace hf := congr_arg (λ (g : polynomial (((quotient.mk I).comp C).range)), g.coeff n) hf, change (polynomial.map ((quotient.mk I).comp C).range_restrict f).coeff n = 0 at hf, rw [coeff_map, subtype.ext_iff] at hf, rwa [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], }, haveI := map_is_prime_of_surjective (show function.surjective (map_ring_hom i), from map_surjective i hi) hi', suffices : (I.map (polynomial.map_ring_hom i)).jacobson = (I.map (polynomial.map_ring_hom i)), { replace this := congr_arg (comap (polynomial.map_ring_hom i)) this, rw [← map_jacobson_of_surjective _ hi', comap_map_of_surjective _ _, comap_map_of_surjective _ _] at this, refine le_antisymm (le_trans (le_sup_of_le_left le_rfl) (le_trans (le_of_eq this) (sup_le le_rfl hi'))) le_jacobson, all_goals {exact polynomial.map_surjective i hi} }, exact @is_jacobson_polynomial_of_domain R' _ _ (is_jacobson_of_surjective ⟨i, hi⟩) (map (map_ring_hom i) I) _ (eq_zero_of_polynomial_mem_map_range I), end theorem is_jacobson_polynomial_iff_is_jacobson : is_jacobson R[X] ↔ is_jacobson R := begin refine ⟨_, is_jacobson_polynomial_of_is_jacobson⟩, introI H, exact is_jacobson_of_surjective ⟨eval₂_ring_hom (ring_hom.id _) 1, λ x, ⟨C x, by simp only [coe_eval₂_ring_hom, ring_hom.id_apply, eval₂_C]⟩⟩, end instance [is_jacobson R] : is_jacobson R[X] := is_jacobson_polynomial_iff_is_jacobson.mpr ‹is_jacobson R› end comm_ring section variables {R : Type*} [comm_ring R] [is_jacobson R] variables (P : ideal R[X]) [hP : P.is_maximal] include P hP lemma is_maximal_comap_C_of_is_maximal [nontrivial R] (hP' : ∀ (x : R), C x ∈ P → x = 0) : is_maximal (comap (C : R →+* R[X]) P : ideal R) := begin haveI hp'_prime : (P.comap (C : R →+* R[X]) : ideal R).is_prime := comap_is_prime C P, obtain ⟨m, hm⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_of_maximal P polynomial_not_is_field), have : (m : R[X]) ≠ 0, rwa [ne.def, submodule.coe_eq_zero], let φ : R ⧸ P.comap (C : R →+* R[X]) →+* R[X] ⧸ P := quotient_map P (C : R →+* R[X]) le_rfl, let M : submonoid (R ⧸ P.comap C) := submonoid.powers ((m : R[X]).map (quotient.mk (P.comap (C : R →+* R[X]) : ideal R))).leading_coeff, rw ← bot_quotient_is_maximal_iff, have hp0 : ((m : R[X]).map (quotient.mk (P.comap (C : R →+* R[X]) : ideal R))).leading_coeff ≠ 0 := λ hp0', this $ map_injective (quotient.mk (P.comap (C : R →+* R[X]) : ideal R)) ((injective_iff_map_eq_zero (quotient.mk (P.comap (C : R →+* R[X]) : ideal R))).2 (λ x hx, by rwa [quotient.eq_zero_iff_mem, (by rwa eq_bot_iff : (P.comap C : ideal R) = ⊥)] at hx)) (by simpa only [leading_coeff_eq_zero, polynomial.map_zero] using hp0'), have hM : (0 : R ⧸ P.comap C) ∉ M := λ ⟨n, hn⟩, hp0 (pow_eq_zero hn), suffices : (⊥ : ideal (localization M)).is_maximal, { rw ← is_localization.comap_map_of_is_prime_disjoint M (localization M) ⊥ bot_prime (disjoint_iff_inf_le.mpr $ λ x hx, hM (hx.2 ▸ hx.1)), refine ((is_maximal_iff_is_maximal_disjoint (localization M) _ _).mp (by rwa map_bot)).1, swap, exact localization.is_localization }, let M' : submonoid (R[X] ⧸ P) := M.map φ, have hM' : (0 : R[X] ⧸ P) ∉ M' := λ ⟨z, hz⟩, hM (quotient_map_injective (trans hz.2 φ.map_zero.symm) ▸ hz.1), haveI : is_domain (localization M') := is_localization.is_domain_localization (le_non_zero_divisors_of_no_zero_divisors hM'), suffices : (⊥ : ideal (localization M')).is_maximal, { rw le_antisymm bot_le (comap_bot_le_of_injective _ (is_localization.map_injective_of_injective M (localization M) (localization M') quotient_map_injective )), refine is_maximal_comap_of_is_integral_of_is_maximal' _ _ ⊥ this, apply is_integral_is_localization_polynomial_quotient P _ (submodule.coe_mem m) }, rw (map_bot.symm : (⊥ : ideal (localization M')) = map (algebra_map (R[X] ⧸ P) (localization M')) ⊥), let bot_maximal := ((bot_quotient_is_maximal_iff _).mpr hP), refine map.is_maximal (algebra_map _ _) (is_field.localization_map_bijective hM' _) bot_maximal, rwa [← quotient.maximal_ideal_iff_is_field_quotient, ← bot_quotient_is_maximal_iff], end /-- Used to bootstrap the more general `quotient_mk_comp_C_is_integral_of_jacobson` -/ private lemma quotient_mk_comp_C_is_integral_of_jacobson' [nontrivial R] (hR : is_jacobson R) (hP' : ∀ (x : R), C x ∈ P → x = 0) : ((quotient.mk P).comp C : R →+* R[X] ⧸ P).is_integral := begin refine (is_integral_quotient_map_iff _).mp _, let P' : ideal R := P.comap C, obtain ⟨pX, hpX, hp0⟩ := exists_nonzero_mem_of_ne_bot (ne_of_lt (bot_lt_of_maximal P polynomial_not_is_field)).symm hP', let M : submonoid (R ⧸ P') := submonoid.powers (pX.map (quotient.mk P')).leading_coeff, let φ : R ⧸ P' →+* R[X] ⧸ P := quotient_map P C le_rfl, haveI hp'_prime : P'.is_prime := comap_is_prime C P, have hM : (0 : R ⧸ P') ∉ M := λ ⟨n, hn⟩, hp0 $ leading_coeff_eq_zero.mp (pow_eq_zero hn), let M' : submonoid (R[X] ⧸ P) := M.map (quotient_map P C le_rfl), refine ((quotient_map P C le_rfl).is_integral_tower_bot_of_is_integral (algebra_map _ (localization M')) _ _), { refine is_localization.injective (localization M') (show M' ≤ _, from le_non_zero_divisors_of_no_zero_divisors (λ hM', hM _)), exact (let ⟨z, zM, z0⟩ := hM' in (quotient_map_injective (trans z0 φ.map_zero.symm)) ▸ zM) }, { rw ← is_localization.map_comp M.le_comap_map, refine ring_hom.is_integral_trans (algebra_map (R ⧸ P') (localization M)) (is_localization.map (localization M') _ M.le_comap_map) _ _, { exact (algebra_map (R ⧸ P') (localization M)).is_integral_of_surjective (is_field.localization_map_bijective hM ((quotient.maximal_ideal_iff_is_field_quotient _).mp (is_maximal_comap_C_of_is_maximal P hP'))).2 }, { -- `convert` here is faster than `exact`, and this proof is near the time limit. convert is_integral_is_localization_polynomial_quotient P pX hpX } } end /-- If `R` is a Jacobson ring, and `P` is a maximal ideal of `R[X]`, then `R → R[X]/P` is an integral map. -/ lemma quotient_mk_comp_C_is_integral_of_jacobson : ((quotient.mk P).comp C : R →+* R[X] ⧸ P).is_integral := begin let P' : ideal R := P.comap C, haveI : P'.is_prime := comap_is_prime C P, let f : R[X] →+* polynomial (R ⧸ P') := polynomial.map_ring_hom (quotient.mk P'), have hf : function.surjective f := map_surjective (quotient.mk P') quotient.mk_surjective, have hPJ : P = (P.map f).comap f, { rw comap_map_of_surjective _ hf, refine le_antisymm (le_sup_of_le_left le_rfl) (sup_le le_rfl _), refine λ p hp, polynomial_mem_ideal_of_coeff_mem_ideal P p (λ n, quotient.eq_zero_iff_mem.mp _), simpa only [coeff_map, coe_map_ring_hom] using (polynomial.ext_iff.mp hp) n }, refine ring_hom.is_integral_tower_bot_of_is_integral _ _ (injective_quotient_le_comap_map P) _, rw ← quotient_mk_maps_eq, refine ring_hom.is_integral_trans _ _ ((quotient.mk P').is_integral_of_surjective quotient.mk_surjective) _, apply quotient_mk_comp_C_is_integral_of_jacobson' _ _ (λ x hx, _), any_goals { exact ideal.is_jacobson_quotient }, { exact or.rec_on (map_eq_top_or_is_maximal_of_surjective f hf hP) (λ h, absurd (trans (h ▸ hPJ : P = comap f ⊤) comap_top : P = ⊤) hP.ne_top) id }, { apply_instance, }, { obtain ⟨z, rfl⟩ := quotient.mk_surjective x, rwa [quotient.eq_zero_iff_mem, mem_comap, hPJ, mem_comap, coe_map_ring_hom, map_C] } end lemma is_maximal_comap_C_of_is_jacobson : (P.comap (C : R →+* R[X])).is_maximal := begin rw [← @mk_ker _ _ P, ring_hom.ker_eq_comap_bot, comap_comap], exact is_maximal_comap_of_is_integral_of_is_maximal' _ (quotient_mk_comp_C_is_integral_of_jacobson P) ⊥ ((bot_quotient_is_maximal_iff _).mpr hP), end omit P hP lemma comp_C_integral_of_surjective_of_jacobson {S : Type*} [field S] (f : R[X] →+* S) (hf : function.surjective f) : (f.comp C).is_integral := begin haveI : (f.ker).is_maximal := ring_hom.ker_is_maximal_of_surjective f hf, let g : R[X] ⧸ f.ker →+* S := ideal.quotient.lift f.ker f (λ _ h, h), have hfg : (g.comp (quotient.mk f.ker)) = f := ring_hom_ext' rfl rfl, rw [← hfg, ring_hom.comp_assoc], refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f.ker) (g.is_integral_of_surjective _), --(quotient.lift_surjective f.ker f _ hf)), rw [← hfg] at hf, exact function.surjective.of_comp hf, end end end polynomial open mv_polynomial ring_hom namespace mv_polynomial lemma is_jacobson_mv_polynomial_fin {R : Type*} [comm_ring R] [H : is_jacobson R] : ∀ (n : ℕ), is_jacobson (mv_polynomial (fin n) R) | 0 := ((is_jacobson_iso ((rename_equiv R (equiv.equiv_pempty (fin 0))).to_ring_equiv.trans (is_empty_ring_equiv R pempty))).mpr H) | (n+1) := (is_jacobson_iso (fin_succ_equiv R n).to_ring_equiv).2 (polynomial.is_jacobson_polynomial_iff_is_jacobson.2 (is_jacobson_mv_polynomial_fin n)) /-- General form of the nullstellensatz for Jacobson rings, since in a Jacobson ring we have `Inf {P maximal | P ≥ I} = Inf {P prime | P ≥ I} = I.radical`. Fields are always Jacobson, and in that special case this is (most of) the classical Nullstellensatz, since `I(V(I))` is the intersection of maximal ideals containing `I`, which is then `I.radical` -/ instance is_jacobson {R : Type*} [comm_ring R] {ι : Type*} [finite ι] [is_jacobson R] : is_jacobson (mv_polynomial ι R) := begin casesI nonempty_fintype ι, haveI := classical.dec_eq ι, let e := fintype.equiv_fin ι, rw is_jacobson_iso (rename_equiv R e).to_ring_equiv, exact is_jacobson_mv_polynomial_fin _ end variables {n : ℕ} lemma quotient_mk_comp_C_is_integral_of_jacobson {R : Type*} [comm_ring R] [is_jacobson R] (P : ideal (mv_polynomial (fin n) R)) [P.is_maximal] : ((quotient.mk P).comp mv_polynomial.C : R →+* mv_polynomial _ R ⧸ P).is_integral := begin unfreezingI {induction n with n IH}, { refine ring_hom.is_integral_of_surjective _ (function.surjective.comp quotient.mk_surjective _), exact C_surjective (fin 0) }, { rw [← fin_succ_equiv_comp_C_eq_C, ← ring_hom.comp_assoc, ← ring_hom.comp_assoc, ← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc (polynomial.C), ← quotient_map_comp_mk le_rfl, ring_hom.comp_assoc, ring_hom.comp_assoc, ← quotient_map_comp_mk le_rfl, ← ring_hom.comp_assoc (quotient.mk _)], refine ring_hom.is_integral_trans _ _ _ _, { refine ring_hom.is_integral_trans _ _ (is_integral_of_surjective _ quotient.mk_surjective) _, refine ring_hom.is_integral_trans _ _ _ _, { apply (is_integral_quotient_map_iff _).mpr (IH _), apply polynomial.is_maximal_comap_C_of_is_jacobson _, { exact mv_polynomial.is_jacobson_mv_polynomial_fin n }, { apply comap_is_maximal_of_surjective, exact (fin_succ_equiv R n).symm.surjective } }, { refine (is_integral_quotient_map_iff _).mpr _, rw ← quotient_map_comp_mk le_rfl, refine ring_hom.is_integral_trans _ _ _ ((is_integral_quotient_map_iff _).mpr _), { exact ring_hom.is_integral_of_surjective _ quotient.mk_surjective }, { apply polynomial.quotient_mk_comp_C_is_integral_of_jacobson _, { exact mv_polynomial.is_jacobson_mv_polynomial_fin n }, { exact comap_is_maximal_of_surjective _ (fin_succ_equiv R n).symm.surjective } } } }, { refine (is_integral_quotient_map_iff _).mpr _, refine ring_hom.is_integral_trans _ _ _ (is_integral_of_surjective _ quotient.mk_surjective), exact ring_hom.is_integral_of_surjective _ (fin_succ_equiv R n).symm.surjective } } end lemma comp_C_integral_of_surjective_of_jacobson {R : Type*} [comm_ring R] [is_jacobson R] {σ : Type*} [finite σ] {S : Type*} [field S] (f : mv_polynomial σ R →+* S) (hf : function.surjective f) : (f.comp C).is_integral := begin casesI nonempty_fintype σ, have e := (fintype.equiv_fin σ).symm, let f' : mv_polynomial (fin _) R →+* S := f.comp (rename_equiv R e).to_ring_equiv.to_ring_hom, have hf' : function.surjective f' := ((function.surjective.comp hf (rename_equiv R e).surjective)), have : (f'.comp C).is_integral, { haveI : (f'.ker).is_maximal := ker_is_maximal_of_surjective f' hf', let g : mv_polynomial _ R ⧸ f'.ker →+* S := ideal.quotient.lift f'.ker f' (λ _ h, h), have hfg : (g.comp (quotient.mk f'.ker)) = f' := ring_hom_ext (λ r, rfl) (λ i, rfl), rw [← hfg, ring_hom.comp_assoc], refine ring_hom.is_integral_trans _ g (quotient_mk_comp_C_is_integral_of_jacobson f'.ker) (g.is_integral_of_surjective _), rw ← hfg at hf', exact function.surjective.of_comp hf' }, rw ring_hom.comp_assoc at this, convert this, refine ring_hom.ext (λ x, _), exact ((rename_equiv R e).commutes' x).symm, end end mv_polynomial end ideal
31dd0d376ee0e910de881d6c45499bf0b6407c27
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/topology/separation.lean
d05aa19ea7532ed0ef315e5a49faf51c7cfda027
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,717
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 Separation properties of topological spaces. -/ import topology.subset_properties open set filter open_locale topological_space local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- A T₀ space, also known as a Kolmogorov space, is a topological space where for every pair `x ≠ y`, there is an open set containing one but not the other. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U))) theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [ha : nonempty α] : ∃ x:α, is_open ({x}:set α) := have H : ∀ (T : finset α), T ≠ ∅ → ∃ x ∈ T, ∃ u, is_open u ∧ {x} = {y | y ∈ T} ∩ u := begin classical, intro T, apply finset.case_strong_induction_on T, { intro h, exact (h rfl).elim }, { intros x S hxS ih h, by_cases hs : S = ∅, { existsi [x, finset.mem_insert_self x S, univ, is_open_univ], rw [hs, inter_univ], refl }, { rcases ih S (finset.subset.refl S) hs with ⟨y, hy, V, hv1, hv2⟩, by_cases hxV : x ∈ V, { cases t0_space.t0 x y (λ hxy, hxS $ by rwa hxy) with U hu, rcases hu with ⟨hu1, ⟨hu2, hu3⟩ | ⟨hu2, hu3⟩⟩, { existsi [x, finset.mem_insert_self x S, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hzx, rw set.mem_singleton_iff at hzx, rw hzx, exact ⟨finset.mem_insert_self x S, ⟨hu2, hxV⟩⟩ }, { intro hz, rw set.mem_singleton_iff, rcases hz with ⟨hz1, hz2, hz3⟩, cases finset.mem_insert.1 hz1 with hz4 hz4, { exact hz4 }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V, { exact ⟨hz4, hz3⟩ }, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, rw h1 at hz2, exact (hu3 hz2).elim } } }, { existsi [y, finset.mem_insert_of_mem hy, U ∩ V, is_open_inter hu1 hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, refine ⟨finset.mem_insert_of_mem hy, hu2, _⟩, have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 }, { intro hz, rw set.mem_singleton_iff, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hu3 hz2.1).elim }, { have h1 : z ∈ {y : α | y ∈ S} ∩ V := ⟨hz3, hz2.2⟩, rw ← hv2 at h1, rw set.mem_singleton_iff at h1, exact h1 } } } }, { existsi [y, finset.mem_insert_of_mem hy, V, hv1], apply set.ext, intro z, split, { intro hz, rw set.mem_singleton_iff at hz, rw hz, split, { exact finset.mem_insert_of_mem hy }, { have h1 : y ∈ {y} := set.mem_singleton y, rw hv2 at h1, exact h1.2 } }, { intro hz, rw hv2, cases hz with hz1 hz2, cases finset.mem_insert.1 hz1 with hz3 hz3, { rw hz3 at hz2, exact (hxV hz2).elim }, { exact ⟨hz3, hz2⟩ } } } } } end, begin apply nonempty.elim ha, intro x, specialize H finset.univ (finset.ne_empty_of_mem $ finset.mem_univ x), rcases H with ⟨y, hyf, U, hu1, hu2⟩, existsi y, have h1 : {y : α | y ∈ finset.univ} = (univ : set α), { exact set.eq_univ_of_forall (λ x : α, by rw mem_set_of_eq; exact finset.mem_univ x) }, rw h1 at hu2, rw set.univ_inter at hu2, rw hu2, exact hu1 end /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} := compl_singleton_eq x ▸ is_open_compl_iff.2 (t1_space.t1 x) @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, ⟨{z | z ≠ y}, is_open_ne, or.inl ⟨h, not_not_intro rfl⟩⟩⟩ lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : - {x} ∈ 𝓝 y := mem_nhds_sets is_closed_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := closure_eq_of_is_closed is_closed_singleton /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := ⟨λ x, is_open_iff_forall_mem_open.2 $ λ y hxy, let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in ⟨u, λ z hz1 hz2, (ext_iff.1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩ lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : 𝓝 x ⊓ 𝓝 y ≠ ⊥) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in absurd huv $ (inf_ne_bot_iff.1 h (mem_nhds_sets hu hx) (mem_nhds_sets hv hy)).ne_empty lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, 𝓝 x ⊓ 𝓝 y ≠ ⊥ → x = y := ⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot, assume h, ⟨assume x y xy, have 𝓝 x ⊓ 𝓝 y = ⊥ := classical.by_contradiction (mt h xy), let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this, ⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu', ⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in ⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint.mono uu' vv' u'v'⟩⟩⟩ lemma t2_iff_ultrafilter : t2_space α ↔ ∀ f {x y : α}, is_ultrafilter f → f ≤ 𝓝 x → f ≤ 𝓝 y → x = y := t2_iff_nhds.trans ⟨assume h f x y u fx fy, h $ ne_bot_of_le_ne_bot u.1 (le_inf fx fy), assume h x y xy, let ⟨f, hf, uf⟩ := exists_ultrafilter xy in h f uf (le_trans hf inf_le_left) (le_trans hf inf_le_right)⟩ @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : l ≠ ⊥) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot (map_ne_bot hl) $ le_inf ha hb section lim variables [nonempty α] [t2_space α] {f : filter α} lemma lim_eq {a : α} (hf : f ≠ ⊥) (h : f ≤ 𝓝 a) : lim f = a := eq_of_nhds_ne_bot $ ne_bot_of_le_ne_bot hf $ le_inf (lim_spec ⟨_, h⟩) h @[simp] lemma lim_nhds_eq {a : α} : lim (𝓝 a) = a := lim_eq nhds_ne_bot (le_refl _) @[simp] lemma lim_nhds_eq_of_closure {a : α} {s : set α} (h : a ∈ closure s) : lim (𝓝 a ⊓ principal s) = a := lim_eq begin rw [closure_eq_nhds] at h, exact h end inf_le_left end lim @[priority 100] -- see Note [lower instance priority] instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, mem_insert _ _, mem_insert _ _, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } private lemma separated_by_f {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] [t2_space β] (f : α → β) (hf : tα ≤ tβ.induced f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, hf _ ⟨u, uo, rfl⟩, hf _ ⟨v, vo, rfl⟩, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_f subtype.val (le_refl _) (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_f prod.fst inf_le_left h₁) (λ h₂, separated_by_f prod.snd inf_le_right h₂)⟩ instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [Πa, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_f (λz, z i) (infi_le _ i) hi⟩ lemma is_closed_diagonal [t2_space α] : is_closed {p:α×α | p.1 = p.2} := is_closed_iff_nhds.mpr $ assume ⟨a₁, a₂⟩ h, eq_of_nhds_ne_bot $ assume : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h $ let ⟨t₁, ht₁, t₂, ht₂, (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this in begin change t₁ ∈ 𝓝 a₁ at ht₁, change t₂ ∈ 𝓝 a₂ at ht₂, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end variables [topological_space β] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ - {p:α×α | p.1 = p.2} ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : compact s) (ht : compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal hst lemma closed_of_compact [t2_space α] (s : set α) (hs : compact s) : is_closed s := is_open_compl_iff.mpr $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ -s, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : -w ∈ 𝓝 x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k - w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) end separation section regularity section prio set_option default_priority 100 -- see Note [default priority] /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥) end prio lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃t∈(𝓝 a), t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ -s' ⊆ t ∧ 𝓝 a ⊓ principal t = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨-t, mem_sets_of_eq_bot $ by rwa [compl_compl], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ variable (α) @[priority 100] -- see Note [lower instance priority] instance regular_space.t2_space [regular_space α] : t2_space α := ⟨λ x y hxy, let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton (mt mem_singleton_iff.1 hxy), ⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs, ⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in ⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys, eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩ end regularity section normality section prio set_option default_priority 100 -- see Note [default priority] /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v) end prio theorem normal_separation [normal_space α] (s t : set α) (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := normal_space.normal s t H1 H2 H3 @[priority 100] -- see Note [lower instance priority] instance normal_space.regular_space [normal_space α] : regular_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation s {x} hs is_closed_singleton (λ _ ⟨hx, hy⟩, hxs $ set.mem_of_eq_of_mem (set.eq_of_mem_singleton hy).symm hx) in ⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2 ⟨v, mem_nhds_sets hv (set.singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, set.inter_comm u v ▸ huv⟩⟩ } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated hs.compact ht.compact st.eq_bot end end normality
642a7e055cb93e8aec981156814039a0e668bca3
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/multiset/pi.lean
f47ac224b1f7b60cef754b04a60d7b06a2648c68
[ "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,888
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.multiset.nodup /-! # The cartesian product of multisets -/ namespace multiset section pi variables {α : Type*} open function /-- Given `δ : α → Type*`, `pi.empty δ` is the trivial dependent function out of the empty multiset. -/ def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . variables [decidable_eq α] {δ : α → Type*} /-- Given `δ : α → Type*`, a multiset `m` and a term `a`, as well as a term `b : δ a` and a function `f` such that `f a' : δ a'` for all `a'` in `m`, `pi.cons m a b f` is a function `g` such that `g a'' : δ a''` for all `a''` in `a ::ₘ m`. -/ def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a ::ₘ m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a ::ₘ m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a ::ₘ m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' ::ₘ m) a b (pi.cons m a' b' f) == pi.cons (a ::ₘ m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = {pi.empty δ} := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a ::ₘ m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma pi_cons_injective {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a ::ₘ s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, split, { assume b hb, from nodup_map (pi_cons_injective has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') }, { apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _), from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) } end lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin refine multiset.induction_on m (λ f, _) (λ a m ih f, _), { simpa using show f = pi.empty δ, by funext a ha; exact ha.elim }, simp only [mem_bind, exists_prop, mem_cons, pi_cons, mem_map], split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', rw [ih] at hf', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha), (ih _).2 (λ a' h', hf _ _), _⟩, funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } end end pi end multiset
54d481b82678a3ffd238287355c2ebbee5fccd5e
798dd332c1ad790518589a09bc82459fb12e5156
/analysis/normed_space.lean
9ff8669af12d5bcd54833a5ee429794f5204f6b7
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,813
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Normed spaces. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.pi_instances import linear_algebra.prod_module import analysis.nnreal variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter local notation f `→_{`:50 a `}`:0 b := tendsto f (nhds a) (nhds b) lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (nhds 0) := begin apply tendsto_of_tendsto_of_tendsto_of_le_of_le (tendsto_const_nhds) g0; simp [*]; exact filter.univ_mem_sets end class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) section normed_group variables [normed_group α] [normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := normed_group.dist_eq _ _ @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by { rw[dist_eq_norm], simp } lemma norm_triangle (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := calc ∥g + h∥ = ∥g - (-h)∥ : by simp ... = dist g (-h) : by simp[dist_eq_norm] ... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle ... = ∥g∥ + ∥h∥ : by simp[dist_eq_norm] @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_eq_zero } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 (by simp) lemma norm_pos_iff (g : α) : ∥ g ∥ > 0 ↔ g ≠ 0 := begin split ; intro h ; rw[←dist_zero_right] at *, { exact dist_pos.1 h }, { exact dist_pos.2 h } end lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := calc ∥-g∥ = ∥0 - g∥ : by simp ... = dist 0 g : (dist_eq_norm 0 g).symm ... = dist g 0 : dist_comm _ _ ... = ∥g - 0∥ : (dist_eq_norm g 0) ... = ∥g∥ : by simp lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := abs_le.2 $ and.intro (suffices -∥g - h∥ ≤ -(∥h∥ - ∥g∥), by simpa, neg_le_neg $ sub_right_le_of_le_add $ calc ∥h∥ = ∥h - g + g∥ : by simp ... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _ ... = ∥-(g - h)∥ + ∥g∥ : by simp ... = ∥g - h∥ + ∥g∥ : by { rw [norm_neg (g-h)] }) (sub_right_le_of_le_add $ calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h section nnnorm def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩ @[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _ lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] @[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 := nnreal.eq norm_zero lemma nnnorm_triangle (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := by simpa [nnreal.coe_le] using norm_triangle g h @[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) := (nnreal.coe_le _ _).2 $ dist_norm_norm_le g h end nnnorm instance prod.normed_group [normed_group β] : normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_left] end lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_right] end instance fintype.normed_group {π : α → Type*} [fintype α] [∀i, normed_group (π i)] : normed_group (Πb, π b) := { norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume x y, congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ } lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (nhds b) ↔ tendsto (λ e, ∥ f e - b ∥) a (nhds 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma lim_norm (x : α) : ((λ g, ∥g - x∥) : α → ℝ) →_{x} 0 := tendsto_iff_norm_tendsto_zero.1 (continuous_iff_tendsto.1 continuous_id x) lemma lim_norm_zero : ((λ g, ∥g∥) : α → ℝ) →_{0} 0 := by simpa using lim_norm (0:α) lemma continuous_norm : continuous ((λ g, ∥g∥) : α → ℝ) := begin rw continuous_iff_tendsto, intro x, rw tendsto_iff_dist_tendsto_zero, exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x) end instance normed_top_monoid : topological_add_monoid α := ⟨continuous_iff_tendsto.2 $ λ ⟨x₁, x₂⟩, tendsto_iff_norm_tendsto_zero.2 begin refine squeeze_zero (by simp) _ (by simpa using tendsto_add (lim_norm (x₁, x₂)) (lim_norm (x₁, x₂))), exact λ ⟨e₁, e₂⟩, calc ∥(e₁ + e₂) - (x₁ + x₂)∥ = ∥(e₁ - x₁) + (e₂ - x₂)∥ : by simp ... ≤ ∥e₁ - x₁∥ + ∥e₂ - x₂∥ : norm_triangle _ _ ... ≤ max (∥e₁ - x₁∥) (∥e₂ - x₂∥) + max (∥e₁ - x₁∥) (∥e₂ - x₂∥) : add_le_add (le_max_left _ _) (le_max_right _ _) end⟩ instance normed_top_group : topological_add_group α := ⟨continuous_iff_tendsto.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 begin have : ∀ (e : α), ∥-e - -x∥ = ∥e - x∥, { intro, simpa using norm_neg (e - x) }, rw funext this, exact lim_norm x, end⟩ end normed_group section normed_ring class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } lemma norm_mul {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := normed_ring.norm_mul _ _ instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul (x.1) (y.1)) (norm_mul (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] } ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.normed_group } end normed_ring section normed_field class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) = norm a * norm b) instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul], ..i } instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul := abs_mul } lemma real.norm_eq_abs (r : ℝ): norm r = abs r := rfl end normed_field section normed_space class normed_space (α : out_param $ Type*) (β : Type*) [out_param $ normed_field α] extends has_norm β , vector_space α β, metric_space β := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_smul : ∀ a b, norm (a • b) = has_norm.norm a * norm b) variables [normed_field α] instance normed_space.to_normed_group [i : normed_space α β] : normed_group β := by refine { add := (+), dist_eq := normed_space.dist_eq, zero := 0, neg := λ x, -x, ..i, .. }; simp lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := normed_space.norm_smul _ _ lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x variables {E : Type*} {F : Type*} [normed_space α E] [normed_space α F] lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} : (tendsto f e (nhds s)) → (tendsto g e (nhds b)) → tendsto (λ x, (f x) • (g x)) e (nhds (s • b)) := begin intros limf limg, rw tendsto_iff_norm_tendsto_zero, have ineq := λ x : γ, calc ∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc] ... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b) ... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] }, apply squeeze_zero, { intro t, exact norm_nonneg _ }, { exact ineq }, { clear ineq, have limf': tendsto (λ x, ∥f x - s∥) e (nhds 0) := tendsto_iff_norm_tendsto_zero.1 limf, have limg' : tendsto (λ x, ∥g x∥) e (nhds ∥b∥) := filter.tendsto.comp limg (continuous_iff_tendsto.1 continuous_norm _), have lim1 : tendsto (λ x, ∥f x - s∥ * ∥g x∥) e (nhds 0), by simpa using tendsto_mul limf' limg', have limg3 := tendsto_iff_norm_tendsto_zero.1 limg, have lim2 : tendsto (λ x, ∥s∥ * ∥g x - b∥) e (nhds 0), by simpa using tendsto_mul tendsto_const_nhds limg3, rw [show (0:ℝ) = 0 + 0, by simp], exact tendsto_add lim1 lim2 } end instance : normed_space α (E × F) := { norm_smul := begin intros s x, cases x with x₁ x₂, exact calc ∥s • (x₁, x₂)∥ = ∥ (s • x₁, s• x₂)∥ : rfl ... = max (∥s • x₁∥) (∥ s• x₂∥) : rfl ... = max (∥s∥ * ∥x₁∥) (∥s∥ * ∥x₂∥) : by simp[norm_smul s x₁, norm_smul s x₂] ... = ∥s∥ * max (∥x₁∥) (∥x₂∥) : by simp[mul_max_of_nonneg] end, add_smul := by simp[add_smul], -- I have no idea why by simp[smul_add] is not enough for the next goal smul_add := assume r x y, show (r•(x+y).fst, r•(x+y).snd) = (r•x.fst+r•y.fst, r•x.snd+r•y.snd), by simp[smul_add], ..prod.normed_group, ..prod.vector_space } instance fintype.normed_space {ι : Type*} {E : ι → Type*} [fintype ι] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm := λf, ((finset.univ.sup (λb, nnnorm (f b)) : nnreal) : ℝ), dist_eq := assume f g, congr_arg coe $ congr_arg (finset.sup finset.univ) $ by funext i; exact nndist_eq_nnnorm _ _, norm_smul := λ a f, show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) = nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul], ..metric_space_pi } end normed_space
8f3e9f22b105ac20ee1be6b741727b44278625d5
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/data/unit/insts.lean
6f7cf442e4dea2cbaee1348b96da232d9fb4f297
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
582
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import data.unit.decl data.unit.thms logic.decidable logic.inhabited open decidable namespace unit protected theorem subsingleton [instance] : subsingleton unit := subsingleton.intro (λ a b, equal a b) protected definition is_inhabited [instance] : inhabited unit := inhabited.mk ⋆ protected definition has_decidable_eq [instance] : decidable_eq unit := take (a b : unit), inl (equal a b) end unit
34ed4aac3369873202141164a07550c928f392b9
c9b68131de1dfe4e7f0ea5749b11e67a774bc839
/src/memory.lean
a150075d17565eae21b5542e9c8e538e5f55ddd1
[]
no_license
congge666/formal-proofs
2013f158f310abcfc07c156bb2a5113fb78f7831
b5f6964d0220c8f89668357f2c08e44861128fe3
refs/heads/master
1,691,374,567,671
1,632,704,604,000
1,632,706,366,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,971
lean
/- The organization of information in the memory. -/ import memory_aux constraints noncomputable theory open_locale classical open_locale big_operators open_locale disable_subsingleton_simps /- the data -/ variables {F : Type*} variable {T : ℕ} -- the number of steps in the execution variables {pc inst dst_addr dst op0_addr op0 op1_addr op1 : fin T → F} variables {mem_star : F → option F} variables {n : ℕ} variables {a v a' v' p : fin (n + 1) → F} variables {embed_inst embed_dst embed_op0 embed_op1 : fin T → fin (n + 1)} variables {embed_mem : mem_dom mem_star → fin (n + 1)} variables {alpha z : F} /- the assumptions and constraints -/ variables [field F] [fintype F] variable h_continuity : ∀ i : fin n, (a' i.succ - a' i.cast_succ) * (a' i.succ - a' i.cast_succ - 1) = 0 variable h_single_valued : ∀ i : fin n, (v' i.succ - v' i.cast_succ) * (a' i.succ - a' i.cast_succ - 1) = 0 variable h_initial : (z - (a' 0 + alpha * v' 0)) * p 0 = z - (a 0 + alpha * v 0) variable h_cumulative : ∀ i : fin n, (z - (a' i.succ + alpha * v' i.succ)) * p i.succ = (z - (a i.succ + alpha * v i.succ)) * p i.cast_succ variable h_final : p (fin.last n) * ∏ a : mem_dom mem_star, (z - (a.val + alpha * mem_val a)) = z^(fintype.card (mem_dom mem_star)) variable h_embed_pc : ∀ i, a (embed_inst i) = pc i variable h_embed_inst : ∀ i, v (embed_inst i) = inst i variable h_embed_dst_addr : ∀ i, a (embed_dst i) = dst_addr i variable h_embed_dst : ∀ i, v (embed_dst i) = dst i variable h_embed_op0_addr : ∀ i, a (embed_op0 i) = op0_addr i variable h_embed_op0 : ∀ i, v (embed_op0 i) = op0 i variable h_embed_op1_addr : ∀ i, a (embed_op1 i) = op1_addr i variable h_embed_op1 : ∀ i, v (embed_op1 i) = op1 i variable h_embed_dom : ∀ i, a (embed_mem i) = 0 variable h_embed_val : ∀ i, v (embed_mem i) = 0 variable h_embed_mem_inj : function.injective embed_mem variable h_embed_mem_disj_inst : ∀ i j, embed_mem i ≠ embed_inst j variable h_embed_mem_disj_dst : ∀ i j, embed_mem i ≠ embed_dst j variable h_embed_mem_disj_op0 : ∀ i j, embed_mem i ≠ embed_op0 j variable h_embed_mem_disj_op1 : ∀ i j, embed_mem i ≠ embed_op1 j /- The memory. -/ def mem (a' v' : fin (n + 1) → F) : F → F := λ addr, if h : ∃ i, a' i = addr then v' (classical.some h) else 0 /- Recovering the real a and v arrays from mem_star and the trace version in which those values have been replaced by (0, 0) pairs. -/ def real_a (mem_star : F → option F) (a : fin (n + 1) → F) (embed_mem : mem_dom mem_star → fin (n + 1)) : fin (n + 1) → F := λ i, if h : ∃ addr, embed_mem addr = i then (classical.some h).val else a i def real_v (mem_star : F → option F) (v : fin (n + 1) → F) (embed_mem : mem_dom mem_star → fin (n + 1)) : fin (n + 1) → F := λ i, if h : ∃ addr, embed_mem addr = i then mem_val (classical.some h) else v i /- Requires messing around with finite products. Needs the fact that `embed_mem` is injective. -/ section include h_embed_mem_inj h_embed_dom h_embed_val lemma real_prod_eq : let ra := real_a mem_star a embed_mem, rv := real_v mem_star v embed_mem in (∏ i, (z - (ra i + alpha * rv i))) * z^(fintype.card (mem_dom mem_star)) = (∏ i, (z - (a i + alpha * v i))) * ∏ a : mem_dom mem_star, (z - (a.val + alpha * mem_val a)) := begin dsimp, let s := finset.image embed_mem finset.univ, rw [←finset.prod_sdiff (finset.subset_univ s), ←finset.prod_sdiff (finset.subset_univ s), mul_right_comm _ _ (z ^ _)], congr' 2, { apply finset.prod_congr rfl, intro i, rw finset.mem_sdiff, rintros ⟨_, nsi⟩, simp [-not_exists, finset.mem_image] at nsi, rw [real_a, real_v], dsimp, rw [dif_neg nsi, dif_neg nsi] }, { rw [finset.prod_image (λ x _ y _ h, @h_embed_mem_inj x y h), fintype.card, ←finset.prod_const], apply finset.prod_congr rfl, intros i _, dsimp, rw [h_embed_dom, h_embed_val, zero_add, mul_zero, sub_zero] }, rw [finset.prod_image (λ x _ y _ h, @h_embed_mem_inj x y h)], apply finset.prod_congr rfl, intros i _, dsimp, have h : ∃ addr, embed_mem addr = embed_mem i := ⟨i, rfl⟩, have h' : classical.some h = i := h_embed_mem_inj (classical.some_spec h), rw [real_a, real_v], dsimp, rw [dif_pos h, dif_pos h, mem_val], congr; exact h' end end /- Moving from `a`, `v` to `real_a`, `real_v` preserves the pairs we care about. -/ section include h_embed_pc h_embed_mem_disj_inst lemma real_a_embed_inst (i : fin T) : real_a mem_star a embed_mem (embed_inst i) = pc i := begin rw [real_a], dsimp, rw [dif_neg, h_embed_pc], apply not_exists_of_forall_not, intro j, apply h_embed_mem_disj_inst end end section include h_embed_inst h_embed_mem_disj_inst lemma real_v_embed_inst (i : fin T) : real_v mem_star v embed_mem (embed_inst i) = inst i := begin rw [real_v], dsimp, rw [dif_neg, h_embed_inst], apply not_exists_of_forall_not, intro j, apply h_embed_mem_disj_inst end end -- because these are so uniform, we can use the same proofs lemma real_a_embed_dst (i : fin T) : real_a mem_star a embed_mem (embed_dst i) = dst_addr i := real_a_embed_inst h_embed_dst_addr h_embed_mem_disj_dst i lemma real_v_embed_dst (i : fin T) : real_v mem_star v embed_mem (embed_dst i) = dst i := real_v_embed_inst h_embed_dst h_embed_mem_disj_dst i lemma real_a_embed_op0 (i : fin T) : real_a mem_star a embed_mem (embed_op0 i) = op0_addr i := real_a_embed_inst h_embed_op0_addr h_embed_mem_disj_op0 i lemma real_v_embed_op0 (i : fin T) : real_v mem_star v embed_mem (embed_op0 i) = op0 i := real_v_embed_inst h_embed_op0 h_embed_mem_disj_op0 i lemma real_a_embed_op1 (i : fin T) : real_a mem_star a embed_mem (embed_op1 i) = op1_addr i := real_a_embed_inst h_embed_op1_addr h_embed_mem_disj_op1 i lemma real_v_embed_op1 (i : fin T) : real_v mem_star v embed_mem (embed_op1 i) = op1 i := real_v_embed_inst h_embed_op1 h_embed_mem_disj_op1 i section variable h_z_ne_zero : z ≠ 0 include h_initial h_cumulative h_final h_embed_mem_inj h_embed_dom h_embed_val h_z_ne_zero lemma real_permutation_prod_eq : let ra := real_a mem_star a embed_mem, rv := real_v mem_star v embed_mem in (∏ i, (z - (ra i + alpha * rv i))) = (∏ i, (z - (a' i + alpha * v' i))) := begin let ra := real_a mem_star a embed_mem, let rv := real_v mem_star v embed_mem, suffices : (∏ i, (z - (ra i + alpha * rv i))) * z^(fintype.card (mem_dom mem_star)) = (∏ i, (z - (a' i + alpha * v' i))) * z^(fintype.card (mem_dom mem_star)), from mul_right_cancel' (pow_ne_zero _ h_z_ne_zero) this, have := real_prod_eq h_embed_dom h_embed_val h_embed_mem_inj , dsimp [-subtype.val_eq_coe] at this, rw this, rw [←fin.range_last, ←fin.succ_last, permutation_aux h_initial h_cumulative, mul_assoc, h_final] end variable hprob₁ : alpha ∉ bad_set_1 (real_a mem_star a embed_mem) (real_v mem_star v embed_mem) a' v' variable hprob₂ : z ∉ bad_set_2 (real_a mem_star a embed_mem) (real_v mem_star v embed_mem) a' v' alpha lemma real_perm : ∀ i, ∃ j, real_v mem_star v embed_mem i = v' j ∧ real_a mem_star a embed_mem i = a' j := let ra := real_a mem_star a embed_mem, rv := real_v mem_star v embed_mem in have h : ∏ (i : fin (n + 1)), (z - (ra i + alpha * rv i)) = ∏ (i : fin (n + 1)), (z - (a' i + alpha * v' i)) := real_permutation_prod_eq h_initial h_cumulative h_final h_embed_dom h_embed_val h_embed_mem_inj h_z_ne_zero, permutation hprob₁ hprob₂ h lemma real_perm' : ∀ i, ∃ j, v' i = real_v mem_star v embed_mem j ∧ a' i = real_a mem_star a embed_mem j := let ra := real_a mem_star a embed_mem, rv := real_v mem_star v embed_mem in have h : ∏ (i : fin (n + 1)), (z - (ra i + alpha * rv i)) = ∏ (i : fin (n + 1)), (z - (a' i + alpha * v' i)) := real_permutation_prod_eq h_initial h_cumulative h_final h_embed_dom h_embed_val h_embed_mem_inj h_z_ne_zero, permutation' hprob₁ hprob₂ h variable h_char_lt : n < ring_char F include h_continuity h_single_valued hprob₁ hprob₂ h_char_lt lemma real_a_single_valued : let ra := real_a mem_star a embed_mem, rv := real_v mem_star v embed_mem in ∀ i i', ra i = ra i' → rv i = rv i' := begin dsimp, intros i i' aieq, let ra := real_a mem_star a embed_mem, let rv := real_v mem_star v embed_mem, have h : ∏ (i : fin (n + 1)), (z - (ra i + alpha * rv i)) = ∏ (i : fin (n + 1)), (z - (a' i + alpha * v' i)) := real_permutation_prod_eq h_initial h_cumulative h_final h_embed_dom h_embed_val h_embed_mem_inj h_z_ne_zero, have perm := permutation hprob₁ hprob₂ h, rcases perm i with ⟨j, veq, aeq⟩, rcases perm i' with ⟨j', veq', aeq'⟩, rw [veq, veq'], apply a'_single_valued h_continuity h_single_valued h_char_lt, rw [←aeq, ←aeq', aieq] end lemma mem_unique (i : fin (n + 1)) : mem a' v' (real_a mem_star a embed_mem i) = real_v mem_star v embed_mem i := begin have perm := real_perm h_initial h_cumulative h_final h_embed_dom h_embed_val h_embed_mem_inj h_z_ne_zero hprob₁ hprob₂, rcases perm i with ⟨i', v'eq, a'eq⟩, have h : ∃ i', a' i' = real_a mem_star a embed_mem i := ⟨i', a'eq.symm⟩, rw [mem], dsimp, rw [dif_pos h], rw v'eq, apply a'_single_valued h_continuity h_single_valued h_char_lt, exact (classical.some_spec h).trans a'eq end section include h_embed_pc h_embed_inst h_embed_mem_disj_inst theorem mem_pc (i : fin T) : mem a' v' (pc i) = inst i := begin rw [←@real_a_embed_inst _ T pc mem_star _ a embed_inst embed_mem _ _ h_embed_pc h_embed_mem_disj_inst], rw [←@real_v_embed_inst _ T inst mem_star _ v embed_inst embed_mem _ _ h_embed_inst h_embed_mem_disj_inst], apply mem_unique h_continuity h_single_valued h_initial h_cumulative h_final h_embed_dom h_embed_val h_embed_mem_inj h_z_ne_zero hprob₁ hprob₂ h_char_lt end end theorem mem_dst_addr (i : fin T) : mem a' v' (dst_addr i) = dst i := mem_pc h_continuity h_single_valued h_initial h_cumulative h_final h_embed_dst_addr h_embed_dst h_embed_dom h_embed_val h_embed_mem_inj h_embed_mem_disj_dst h_z_ne_zero hprob₁ hprob₂ h_char_lt i theorem mem_op0_addr (i : fin T) : mem a' v' (op0_addr i) = op0 i := mem_pc h_continuity h_single_valued h_initial h_cumulative h_final h_embed_op0_addr h_embed_op0 h_embed_dom h_embed_val h_embed_mem_inj h_embed_mem_disj_op0 h_z_ne_zero hprob₁ hprob₂ h_char_lt i theorem mem_op1_addr (i : fin T) : mem a' v' (op1_addr i) = op1 i := mem_pc h_continuity h_single_valued h_initial h_cumulative h_final h_embed_op1_addr h_embed_op1 h_embed_dom h_embed_val h_embed_mem_inj h_embed_mem_disj_op1 h_z_ne_zero hprob₁ hprob₂ h_char_lt i theorem mem_extends : option.fn_extends (mem a' v') mem_star := begin intro addr, cases h : (mem_star addr) with val; simp only [option.agrees], have h' : (option.is_some (mem_star addr) : Prop), by { rw h, simp }, let aelt : mem_dom mem_star := ⟨addr, h'⟩, have h₀ : ∃ i, embed_mem i = embed_mem aelt := ⟨aelt, rfl⟩, have h₁ : classical.some h₀ = aelt, { apply h_embed_mem_inj, apply classical.some_spec h₀ }, have h₂ : real_a mem_star a embed_mem (embed_mem aelt) = addr, { rw real_a, dsimp, rw [dif_pos h₀, h₁], refl }, have h₃ : real_v mem_star v embed_mem (embed_mem aelt) = val, { rw real_v, dsimp, rw [dif_pos h₀, h₁], apply option.some_inj.mp, rw [←h, mem_val, option.some_get] }, rw [←h₂, ←h₃], symmetry, dsimp [aelt], exact mem_unique h_continuity h_single_valued h_initial h_cumulative h_final h_embed_dom h_embed_val h_embed_mem_inj h_z_ne_zero hprob₁ hprob₂ h_char_lt (embed_mem ⟨addr, h'⟩) end end
6718e568cbf54b93a1818aa3657798e8e6e1998c
d72901cc240bd78b8b0384565e4f4dee8abd3a86
/src/topology/metric_space/gromov_hausdorff.lean
0dbc1521a14bf85b20d38c8937904f4571c695aa
[ "Apache-2.0" ]
permissive
leon-volq/mathlib
513b24765349bb5187df9d898b92beadf96124d9
0cc93a137e9b2e243f8ae1f808fa7225ce0fe143
refs/heads/master
1,676,294,376,990
1,610,838,688,000
1,610,838,688,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,682
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.closeds import set_theory.cardinal import topology.metric_space.gromov_hausdorff_realized import topology.metric_space.completion /-! # Gromov-Hausdorff distance This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduce the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance between all possible isometric embeddings of `X` and `Y` in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. ## Main results We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ noncomputable theory open_locale classical topological_space universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function nat Kuratowski_embedding open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section GH_space /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to `GH_space`. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop := λx y, nonempty (x.val ≃ᵢ y.val) /-- This is indeed an equivalence relation -/ private lemma is_equivalence_isometry_rel : equivalence isometry_rel := ⟨λx, ⟨isometric.refl _⟩, λx y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩ /-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/ instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ definition GH_space : Type := quotient (isometry_rel.setoid) /-- Map any nonempty compact type to `GH_space` -/ definition to_GH_space (α : Type u) [metric_space α] [compact_space α] [nonempty α] : GH_space := ⟦nonempty_compacts.Kuratowski_embedding α⟧ instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp⟩⟩ /-- A metric space representative of any abstract point in `GH_space` -/ definition GH_space.rep (p : GH_space) : Type := (quot.out p).val lemma eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [nonempty α] {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space α ↔ ∃Ψ : α → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val := begin simp only [to_GH_space, quotient.eq], split, { assume h, rcases setoid.symm h with ⟨e⟩, have f := (Kuratowski_embedding.isometry α).isometric_on_range.trans e, use λx, f x, split, { apply isometry_subtype_coe.comp f.isometry }, { rw [range_comp, f.range_coe, set.image_univ, subtype.range_coe] } }, { rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩, have f := ((Kuratowski_embedding.isometry α).isometric_on_range.symm.trans isomΨ.isometric_on_range).symm, have E : (range Ψ ≃ᵢ (nonempty_compacts.Kuratowski_embedding α).val) = (p.val ≃ᵢ range (Kuratowski_embedding α)), by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl }, have g := cast E f, exact ⟨g⟩ } end lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val := begin refine eq_to_GH_space_iff.2 ⟨((λx, x) : p.val → ℓ_infty_ℝ), _, subtype.range_coe⟩, apply isometry_subtype_coe end section local attribute [reducible] GH_space.rep instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) := by apply_instance instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) := by apply_instance instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) := by apply_instance end lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p := begin change to_GH_space (quot.out p).val = p, rw ← eq_to_GH_space, exact quot.out_eq p end /-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric. -/ lemma to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type u} [metric_space β] [compact_space β] [nonempty β] : to_GH_space α = to_GH_space β ↔ nonempty (α ≃ᵢ β) := ⟨begin simp only [to_GH_space, quotient.eq], assume h, rcases h with ⟨e⟩, have I : ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val) = ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have e' := cast I e, have f := (Kuratowski_embedding.isometry α).isometric_on_range, have g := (Kuratowski_embedding.isometry β).isometric_on_range.symm, have h := (f.trans e').trans g, exact ⟨h⟩ end, begin rintros ⟨e⟩, simp only [to_GH_space, quotient.eq], have f := (Kuratowski_embedding.isometry α).isometric_on_range.symm, have g := (Kuratowski_embedding.isometry β).isometric_on_range, have h := (f.trans e).trans g, have I : ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))) = ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have h' := cast I h, exact ⟨h'⟩ end⟩ /-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/ instance : has_dist (GH_space) := { dist := λx y, Inf $ (λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) } /-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/ def GH_dist (α : Type u) (β : Type v) [metric_space α] [nonempty α] [compact_space α] [metric_space β] [nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β) lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) := by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep] /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] {γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) : GH_dist α β ≤ Hausdorff_dist (range Φ) (range Ψ) := begin /- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not separable in general. We restrict to the union of the images of `α` and `β` in `γ`, which is separable and therefore embeddable in `ℓ^∞(ℝ)`. -/ rcases exists_mem_of_nonempty α with ⟨xα, _⟩, let s : set γ := (range Φ) ∪ (range Ψ), let Φ' : α → subtype s := λy, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩, let Ψ' : β → subtype s := λy, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩, have IΦ' : isometry Φ' := λx y, ha x y, have IΨ' : isometry Ψ' := λx y, hb x y, have : is_compact s, from (compact_range ha.continuous).union (compact_range hb.continuous), letI : metric_space (subtype s) := by apply_instance, haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹is_compact s›⟩, haveI : nonempty (subtype s) := ⟨Φ' xα⟩, have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl }, have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl }, have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'), { rw [ΦΦ', ΨΨ', range_comp, range_comp], exact Hausdorff_dist_image (isometry_subtype_coe) }, rw this, -- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding let F := Kuratowski_embedding (subtype s), have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _), rw ← this, -- Let `A` and `B` be the images of `α` and `β` under this embedding. They are in `ℓ^∞(ℝ)`, and -- their Hausdorff distance is the same as in the original space. let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨(range_nonempty _).image _, (compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _, (compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩, have Aα : ⟦A⟧ = to_GH_space α, { rw eq_to_GH_space_iff, exact ⟨λx, F (Φ' x), ⟨(Kuratowski_embedding.isometry _).comp IΦ', by rw range_comp⟩⟩ }, have Bβ : ⟦B⟧ = to_GH_space β, { rw eq_to_GH_space_iff, exact ⟨λx, F (Ψ' x), ⟨(Kuratowski_embedding.isometry _).comp IΨ', by rw range_comp⟩⟩ }, refine cInf_le ⟨0, begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _, apply (mem_image _ _ _).2, existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), simp [Aα, Bβ] end /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ lemma Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) = GH_dist α β := begin inhabit α, inhabit β, /- we only need to check the inequality `≤`, as the other one follows from the previous lemma. As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance in the optimal coupling is smaller than the Hausdorff distance of any coupling. First, we check this for couplings which already have small Hausdorff distance: in this case, the induced "distance" on `α ⊕ β` belongs to the candidates family introduced in the definition of the optimal coupling, and the conclusion follows from the optimality of the optimal coupling within this family. -/ have A : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β → Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β) → Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq bound, rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩, rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩, have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β), { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : ∃y ∈ range Ψ, dist (Φ xα) y < diam (univ : set α) + 1 + diam (univ : set β), { rw Ψrange, have : Φ xα ∈ p.val := Φrange ▸ mem_range_self _, exact exists_dist_lt_of_Hausdorff_dist_lt this bound (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) }, rcases this with ⟨y, hy, dy⟩, rcases mem_range.1 hy with ⟨z, hzy⟩, rw ← hzy at dy, have DΦ : diam (range Φ) = diam (univ : set α) := Φisom.diam_range, have DΨ : diam (range Ψ) = diam (univ : set β) := Ψisom.diam_range, calc diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xα) (Ψ z) + diam (range Ψ) : diam_union (mem_range_self _) (mem_range_self _) ... ≤ diam (univ : set α) + (diam (univ : set α) + 1 + diam (univ : set β)) + diam (univ : set β) : by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) } ... = 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by ring }, let f : α ⊕ β → ℓ_infty_ℝ := λx, match x with | inl y := Φ y | inr z := Ψ z end, let F : (α ⊕ β) × (α ⊕ β) → ℝ := λp, dist (f p.1) (f p.2), -- check that the induced "distance" is a candidate have Fgood : F ∈ candidates α β, { simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero, and_self, set.mem_set_of_eq], repeat {split}, { exact λx y, calc F (inl x, inl y) = dist (Φ x) (Φ y) : rfl ... = dist x y : Φisom.dist_eq x y }, { exact λx y, calc F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl ... = dist x y : Ψisom.dist_eq x y }, { exact λx y, dist_comm _ _ }, { exact λx y z, dist_triangle _ _ _ }, { exact λx y, calc F (x, y) ≤ diam (range Φ ∪ range Ψ) : begin have A : ∀z : α ⊕ β, f z ∈ range Φ ∪ range Ψ, { assume z, cases z, { apply mem_union_left, apply mem_range_self }, { apply mem_union_right, apply mem_range_self } }, refine dist_le_diam_of_mem _ (A _) (A _), rw [Φrange, Ψrange], exact (p.2.2.union q.2.2).bounded, end ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : I } }, let Fb := candidates_b_of_candidates F Fgood, have : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD Fb := Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood), refine le_trans this (le_of_forall_le_of_dense (λr hr, _)), have I1 : ∀x : α, (⨅ y, Fb (inl x, inr y)) ≤ r, { assume x, have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Ψ, by rwa [← Ψrange] at zq, rcases mem_range.1 this with ⟨y, hy⟩, calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux1 0) y ... = dist (Φ x) (Ψ y) : rfl ... = dist (f (inl x)) z : by rw hy ... ≤ r : le_of_lt hz }, have I2 : ∀y : β, (⨅ x, Fb (inl x, inr y)) ≤ r, { assume y, have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Φ, by rwa [← Φrange] at zq, rcases mem_range.1 this with ⟨x, hx⟩, calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux2 0) x ... = dist (Φ x) (Ψ y) : rfl ... = dist z (f (inr y)) : by rw hx ... ≤ r : le_of_lt hz }, simp [HD, csupr_le I1, csupr_le I2] }, /- Get the same inequality for any coupling. If the coupling is quite good, the desired inequality has been proved above. If it is bad, then the inequality is obvious. -/ have B : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β → Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq, by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β), { exact A p q hp hq h }, { calc Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD (candidates_b_dist α β) : Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b) ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : HD_candidates_b_dist_le ... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } }, refine le_antisymm _ _, { apply le_cInf, { refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ }, { rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩, exact B p q hp hq } }, { exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl α β) (isometry_optimal_GH_injr α β) } end /-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [nonempty α] (β : Type v) [metric_space β] [compact_space β] [nonempty β] : ∃Φ : α → ℓ_infty_ℝ, ∃Ψ : β → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧ GH_dist α β = Hausdorff_dist (range Φ) (range Ψ) := begin let F := Kuratowski_embedding (optimal_GH_coupling α β), let Φ := F ∘ optimal_GH_injl α β, let Ψ := F ∘ optimal_GH_injr α β, refine ⟨Φ, Ψ, _, _, _⟩, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl α β) }, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr α β) }, { rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr α β), image_univ, ← Hausdorff_dist_optimal], exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm }, end -- without the next two lines, `{ exact hΦ.is_closed }` in the next -- proof is very slow, as the `t2_space` instance is very hard to find local attribute [instance, priority 10] order_topology.t2_space local attribute [instance, priority 10] order_closed_topology.to_t2_space /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ instance GH_space_metric_space : metric_space GH_space := { dist_self := λx, begin rcases exists_rep x with ⟨y, hy⟩, refine le_antisymm _ _, { apply cInf_le, { exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩}, { simp, existsi [y, y], simpa } }, { apply le_cInf, { exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ }, { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } }, end, dist_comm := λx y, begin have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) = ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) := by { congr, funext, simp, rw Hausdorff_dist_comm }, simp only [dist, A, image_comp, image_swap_prod], end, eq_of_dist_eq_zero := λx y hxy, begin /- To show that two spaces at zero distance are isometric, we argue that the distance is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance, i.e., they coincide. Therefore, the original spaces are isometric. -/ rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩, rw [← dist_GH_dist, hxy] at DΦΨ, have : range Φ = range Ψ, { have hΦ : is_compact (range Φ) := compact_range Φisom.continuous, have hΨ : is_compact (range Ψ) := compact_range Ψisom.continuous, apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm), { exact hΦ.is_closed }, { exact hΨ.is_closed }, { exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) hΦ.bounded hΨ.bounded } }, have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this, have eΨ := cast T Ψisom.isometric_on_range.symm, have e := Φisom.isometric_on_range.trans eΨ, rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], exact ⟨e⟩ end, dist_triangle := λx y z, begin /- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space `γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff distance in `γ` to conclude. -/ let X := x.rep, let Y := y.rep, let Z := z.rep, let γ1 := optimal_GH_coupling X Y, let γ2 := optimal_GH_coupling Y Z, let Φ : Y → γ1 := optimal_GH_injr X Y, have hΦ : isometry Φ := isometry_optimal_GH_injr X Y, let Ψ : Y → γ2 := optimal_GH_injl Y Z, have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z, let γ := glue_space hΦ hΨ, letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ, have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ, calc dist x z = dist (to_GH_space X) (to_GH_space Z) : by rw [x.to_GH_space_rep, z.to_GH_space_rep] ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : GH_dist_le_Hausdorff_dist ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)) ((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z)) ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) + Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : begin refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) _ _), { exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)))).bounded }, { exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injr X Y)))).bounded } end ... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y))) ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y))) + Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z))) ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) : by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj] ... = Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) + Hausdorff_dist (range (optimal_GH_injl Y Z)) (range (optimal_GH_injr Y Z)) : by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ), Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)] ... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) : by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist] ... = dist x y + dist y z: by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep] end } end GH_space --section end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/ definition topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α] (p : nonempty_compacts α) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val open topological_space namespace Gromov_Hausdorff section nonempty_compacts variables {α : Type u} [metric_space α] theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts α) : dist p.to_GH_space q.to_GH_space ≤ dist p q := begin have ha : isometry (coe : p.val → α) := isometry_subtype_coe, have hb : isometry (coe : q.val → α) := isometry_subtype_coe, have A : dist p q = Hausdorff_dist p.val q.val := rfl, have I : p.val = range (coe : p.val → α), by simp, have J : q.val = range (coe : q.val → α), by simp, rw [I, J] at A, rw A, exact GH_dist_le_Hausdorff_dist ha hb end lemma to_GH_space_lipschitz : lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) := lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist lemma to_GH_space_continuous : continuous (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) := to_GH_space_lipschitz.continuous end nonempty_compacts section /- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/ variables {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] -- we want to ignore these instances in the following theorem local attribute [instance, priority 10] sum.topological_space sum.uniform_space /-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. -/ theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε₁ ε₂ ε₃ : ℝ} (hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε₁) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε₃) (H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε₂) : GH_dist α β ≤ ε₁ + ε₂ / 2 + ε₃ := begin refine le_of_forall_pos_le_add (λδ δ0, _), rcases exists_mem_of_nonempty α with ⟨xα, _⟩, rcases hs xα with ⟨xs, hxs, Dxs⟩, have sne : s.nonempty := ⟨xs, hxs⟩, letI : nonempty s := sne.to_subtype, have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩), have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε₂/2 + δ) := λp q, calc abs (dist p q - dist (Φ p) (Φ q)) ≤ ε₂ : H p q ... ≤ 2 * (ε₂/2 + δ) : by linarith, -- glue `α` and `β` along the almost matching subsets letI : metric_space (α ⊕ β) := glue_metric_approx (λ x:s, (x:α)) (λx, Φ x) (ε₂/2 + δ) (by linarith) this, let Fl := @sum.inl α β, let Fr := @sum.inr α β, have Il : isometry Fl := isometry_emetric_iff_metric.2 (λx y, rfl), have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λx y, rfl), /- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances of `α` and `s` (in the coupling or, equivalently in the original space), of `s` and `Φ s`, and of `Φ s` and `β` (in the coupling or, equivalently, in the original space). The first term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive constant where positivity is used to ensure that the coupling is really a metric space and not a premetric space on `α ⊕ β`). -/ have : GH_dist α β ≤ Hausdorff_dist (range Fl) (range Fr) := GH_dist_le_Hausdorff_dist Il Ir, have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s) + Hausdorff_dist (Fl '' s) (range Fr), { have B : bounded (range Fl) := (compact_range Il.continuous).bounded, exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) }, have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) + Hausdorff_dist (Fr '' (range Φ)) (range Fr), { have B : bounded (range Fr) := (compact_range Ir.continuous).bounded, exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded ((range_nonempty _).image _) (range_nonempty _) (bounded.subset (image_subset_range _ _) B) B) }, have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁, { rw [← image_univ, Hausdorff_dist_image Il], have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs, refine Hausdorff_dist_le_of_mem_dist this (λx hx, hs x) (λx hx, ⟨x, mem_univ _, by simpa⟩) }, have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ, { refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩, rw ← xx', use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)], exact le_of_eq (glue_dist_glued_points (λ x:s, (x:α)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) }, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩, rcases mem_range.1 y_in_s' with ⟨x, xy⟩, use [Fl x, mem_image_of_mem _ x.2], rw [← yx', ← xy, dist_comm], exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε₂/2 + δ) x) } }, have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃, { rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir], rcases exists_mem_of_nonempty β with ⟨xβ, _⟩, rcases hs' xβ with ⟨xs', Dxs'⟩, have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs', refine Hausdorff_dist_le_of_mem_dist this (λx hx, ⟨x, mem_univ _, by simpa⟩) (λx _, _), rcases hs' x with ⟨y, Dy⟩, exact ⟨Φ y, mem_range_self _, Dy⟩ }, linarith end end --section /-- The Gromov-Hausdorff space is second countable. -/ instance second_countable : second_countable_topology GH_space := begin refine second_countable_of_countable_discretization (λδ δpos, _), let ε := (2/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, have : ∀p:GH_space, ∃s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) := λp, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos, -- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space -- `p.rep` representing `p`) choose s hs using this, have : ∀p:GH_space, ∀t:set (p.rep), finite t → ∃n:ℕ, ∃e:equiv t (fin n), true, { assume p t ht, letI : fintype t := finite.fintype ht, rcases fintype.exists_equiv_fin t with ⟨n, hn⟩, rcases hn with ⟨e⟩, exact ⟨n, e, trivial⟩ }, choose N e hne using this, -- cardinality of the nice finite subset `s p` of `p.rep`, called `N p` let N := λp:GH_space, N p (s p) (hs p).1, -- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p` let E := λp:GH_space, e p (s p) (hs p).1, -- A function `F` associating to `p : GH_space` the data of all distances between points -- in the `ε`-dense set `s p`. let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) := λp, ⟨N p, λa b, floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))⟩, refine ⟨_, by apply_instance, F, λp q hpq, _⟩, /- As the target space of F is countable, it suffices to show that two points `p` and `q` with `F p = F q` are at distance `≤ δ`. For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`) to `q.rep` (representing `q`) which is almost an isometry on `s p`, and with image `s q`. For this, we compose the identification of `s p` with `fin (N p)` and the inverse of the identification of `s q` with `fin (N q)`. Together with the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then composing with the canonical inclusion we get `Φ`. -/ have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λx, Ψ x, -- Use the almost isometry `Φ` to show that `p.rep` and `q.rep` -- are within controlled Gromov-Hausdorff distance. have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε, { refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_of_lt hy⟩ }, show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).is_lt, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_of_lt hy }, show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y), by simp only [F, (E p).symm_apply_apply], have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y), by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl }, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by simp only [F, (E q).symm_apply_apply], have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, rw [Ap, Aq] at this, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ : by { simp [ε], ring } end /-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the interesting direction that these conditions imply compactness. -/ lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ} (ulim : tendsto u at_top (𝓝 0)) (hdiam : ∀p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C) (hcov : ∀p ∈ t, ∀n:ℕ, ∃s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) : totally_bounded t := begin /- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`, up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/ refine metric.totally_bounded_of_finite_discretization (λδ δpos, _), let ε := (1/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, -- choose `n` for which `u n < ε` rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩, have u_le_ε : u n ≤ ε, { have := hn n (le_refl _), simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this, exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) }, -- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n` have : ∀p:GH_space, ∃s : set (p.rep), ∃N ≤ K n, ∃E : equiv s (fin N), p ∈ t → univ ⊆ ⋃x∈s, ball x (u n), { assume p, by_cases hp : p ∉ t, { have : nonempty (equiv (∅ : set (p.rep)) (fin 0)), { rw ← fintype.card_eq, simp }, use [∅, 0, bot_le, choice (this)] }, { rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩, rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩, rw [hN, cardinal.nat_cast_le] at scard, have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin], cases quotient.exact this with E, use [s, N, scard, E], simp [hp, scover] } }, choose s N hN E hs using this, -- Define a function `F` taking values in a finite type and associating to `p` enough data -- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`. let M := (floor (ε⁻¹ * max C 0)).to_nat, let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) := λp, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩, λa b, ⟨min M (floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))).to_nat, lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩, refine ⟨_, by apply_instance, (λp, F p), _⟩, -- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq, have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λx, Ψ x, have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε, { -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense -- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows -- from `GH_dist_le_of_approx_subsets` refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ }, show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_trans (le_of_lt hy) u_le_ε }, show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp [Ψ] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)), by { simp [Ψ] }, -- Express `dist x y` in terms of `F p` have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 : by { congr; apply (fin.ext_iff _ _).2; refl } ... = min M (floor (ε⁻¹ * dist x y)).to_nat : by simp only [F, (E p).symm_apply_apply] ... = (floor (ε⁻¹ * dist x y)).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (x : p.rep) y ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam p pt end, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 : by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] } ... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : by simp only [F, (E q).symm_apply_apply] ... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (Ψ x : q.rep) (Ψ y) ≤ C, refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam q qt end, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), { rw [Ap, Aq] at this, have D : 0 ≤ floor (ε⁻¹ * dist x y) := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] }, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ/2 : by { simp [ε], ring } ... < δ : half_lt_self δpos end section complete /- We will show that a sequence `u n` of compact metric spaces satisfying `dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space. We need to exhibit the limiting compact metric space. For this, start from a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)` for all `n`, in a common metric space. Formally, this is done as follows. Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space `Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive limit of the `Y n`, and finally let `Z` be the completion of `Z0`. The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty compact metric space we are looking for. -/ variables (X : ℕ → Type) [∀n, metric_space (X n)] [∀n, compact_space (X n)] [∀n, nonempty (X n)] /-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding of a type `A` in another metric space. -/ structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 := (space : Type) (metric : metric_space space) (embed : A → space) (isom : isometry embed) /-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each `X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/ def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n { space := X 0, metric := by apply_instance, embed := id, isom := λx y, rfl } (λn a, by letI : metric_space a.space := a.metric; exact { space := glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)), metric := metric.metric_space_glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)), embed := (to_glue_r a.isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injr (X n) (X n.succ)), isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X n.succ)) }) /-- The Gromov-Hausdorff space is complete. -/ instance : complete_space (GH_space) := begin have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num }, -- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other refine metric.complete_of_convergent_controlled_sequences (λn, (1/2)^n) this (λu hu, _), -- `X n` is a representative of `u n` let X := λn, (u n).rep, -- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n` let Y := aux_gluing X, letI : ∀n, metric_space (Y n).space := λn, (Y n).metric, have E : ∀ n : ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space := λ n, by { simp [Y, aux_gluing], refl }, let c := λn, cast (E n), have ic : ∀n, isometry (c n) := λn x y, rfl, -- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction let f : Πn, (Y n).space → (Y n.succ).space := λn, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))), have I : ∀n, isometry (f n), { assume n, apply isometry.comp, { assume x y, refl }, { apply to_glue_l_isometry } }, -- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z` let Z0 := metric.inductive_limit I, let Z := uniform_space.completion Z0, let Φ := to_inductive_limit I, let coeZ := (coe : Z0 → Z), -- let `X2 n` be the image of `X n` in the space `Z` let X2 := λn, range (coeZ ∘ (Φ n) ∘ (Y n).embed), have isom : ∀n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed), { assume n, apply isometry.comp completion.coe_isometry _, apply isometry.comp _ (Y n).isom, apply to_inductive_limit_isometry }, -- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between -- `u n` and `u (n+1)`, therefore bounded by `1/2^n` have D2 : ∀n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n, { assume n, have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injl (X n) (X n.succ))), { change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injl (X n) (X n.succ))), simp only [X2, Φ], rw [← to_inductive_limit_commute I], simp only [f], rw ← to_glue_commute }, rw range_comp at X2n, have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injr (X n) (X n.succ))), by refl, rw range_comp at X2nsucc, rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist], { exact hu n n n.succ (le_refl n) (le_succ n) }, { apply isometry.comp completion.coe_isometry _, apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)), apply to_inductive_limit_isometry } }, -- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which -- is a metric space let X3 : ℕ → nonempty_compacts Z := λn, ⟨X2 n, ⟨range_nonempty _, compact_range (isom n).continuous ⟩⟩, -- `X3 n` is a Cauchy sequence by construction, as the successive distances are -- bounded by `(1/2)^n` have : cauchy_seq X3, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _), rw one_mul, exact le_of_lt (D2 n) }, -- therefore, it converges to a limit `L` rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩, -- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L` have M : tendsto (λn, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) := tendsto.comp (to_GH_space_continuous.tendsto _) hL, -- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`. have : ∀n, (X3 n).to_GH_space = u n, { assume n, rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], constructor, convert (isom n).isometric_on_range.symm, }, -- Finally, we have proved the convergence of `u n` exact ⟨L.to_GH_space, by simpa [this] using M⟩ end end complete--section end Gromov_Hausdorff --namespace
3bf3f8f138fc1db9b338f94d8f16618d41133b93
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/computability/halting.lean
f2332cfc0a39e8242be1443764e6a0084503377b
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,733
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro More partial recursive functions using a universal program; Rice's theorem and the halting problem. -/ import computability.partrec_code open encodable denumerable namespace nat.partrec open computable roption theorem merge' {f g} (hf : nat.partrec f) (hg : nat.partrec g) : ∃ h, nat.partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).dom ↔ (f a).dom ∨ (g a).dom) := begin rcases code.exists_code.1 hf with ⟨cf, rfl⟩, rcases code.exists_code.1 hg with ⟨cg, rfl⟩, have : nat.partrec (λ n, (nat.rfind_opt (λ k, cf.evaln k n <|> cg.evaln k n))) := partrec.nat_iff.1 (partrec.rfind_opt $ primrec.option_orelse.to_comp.comp (code.evaln_prim.to_comp.comp $ (snd.pair (const cf)).pair fst) (code.evaln_prim.to_comp.comp $ (snd.pair (const cg)).pair fst)), refine ⟨_, this, λ n, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw nat.rfind_opt_dom, simp [dom_iff_mem, code.evaln_complete] at h, rcases h with ⟨x, k, e⟩ | ⟨x, k, e⟩, { refine ⟨k, x, _⟩, simp [e] }, { refine ⟨k, _⟩, cases cf.evaln k n with y, { exact ⟨x, by simp [e]⟩ }, { exact ⟨y, by simp⟩ } } }, { intros x h, rcases nat.rfind_opt_spec h with ⟨k, e⟩, revert e, simp; cases e' : cf.evaln k n with y; simp; intro, { exact or.inr (code.evaln_sound e) }, { subst y, exact or.inl (code.evaln_sound e') } } end end nat.partrec namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable roption nat.partrec (code) nat.partrec.code theorem merge' {f g : α →. σ} (hf : partrec f) (hg : partrec g) : ∃ k : α →. σ, partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).dom ↔ (f a).dom ∨ (g a).dom) := let ⟨k, hk, H⟩ := nat.partrec.merge' (bind_decode2_iff.1 hf) (bind_decode2_iff.1 hg) in begin let k' := λ a, (k (encode a)).bind (λ n, decode σ n), refine ⟨k', ((nat_iff.2 hk).comp computable.encode).bind (computable.decode.of_option.comp snd).to₂, λ a, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, simp [k'], have hk : (k (encode a)).dom := (H _).2.2 (by simpa [encodek2] using h), existsi hk, cases (H _).1 _ ⟨hk, rfl⟩ with h h; { simp at h, rcases h with ⟨a', ha', y, hy, e⟩, simp [e.symm, encodek] } }, { intros x h', simp [k'] at h', rcases h' with ⟨n, hn, hx⟩, have := (H _).1 _ hn, simp [mem_decode2] at this, cases this with h h; { rcases h with ⟨a', ⟨ha₁, ha₂⟩, y, hy, rfl⟩, rw encodek at hx ha₁, simp at hx ha₁, substs y a', simp [hy] } }, end theorem merge {f g : α →. σ} (hf : partrec f) (hg : partrec g) (H : ∀ a (x ∈ f a) (y ∈ g a), x = y) : ∃ k : α →. σ, partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg in ⟨k, hk, λ a x, ⟨(K _).1 _, λ h, begin have : (k a).dom := (K _).2.2 (h.imp Exists.fst Exists.fst), refine ⟨this, _⟩, cases h with h h; cases (K _).1 _ ⟨this, rfl⟩ with h' h', { exact mem_unique h' h }, { exact (H _ _ h _ h').symm }, { exact H _ _ h' _ h }, { exact mem_unique h' h } end⟩⟩ theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} (hc : computable c) (hf : partrec f) (hg : partrec g) : partrec (λ a, cond (c a) (f a) (g a)) := let ⟨cf, ef⟩ := exists_code.1 hf, ⟨cg, eg⟩ := exists_code.1 hg in ((eval_part.comp (computable.cond hc (const cf) (const cg)) computable.id).bind ((@computable.decode σ _).comp snd).of_option.to₂).of_eq $ λ a, by cases c a; simp [ef, eg, encodek] theorem sum_cases {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : computable f) (hg : partrec₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (sum_cases hf (const tt).to₂ (const ff).to₂) (sum_cases_left hf (option_some_iff.2 hg).to₂ (const option.none).to₂) (sum_cases_right hf (const option.none).to₂ (option_some_iff.2 hh).to₂)) .of_eq $ λ a, by cases f a; simp end partrec def computable_pred {α} [primcodable α] (p : α → Prop) := ∃ [D : decidable_pred p], by exactI computable (λ a, to_bool (p a)) /- recursively enumerable predicate -/ def re_pred {α} [primcodable α] (p : α → Prop) := partrec (λ a, roption.assert (p a) (λ _, roption.some ())) theorem computable_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : computable_pred p) (H : ∀ a, p a ↔ q a) : computable_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp namespace computable_pred variables {α : Type*} {σ : Type*} variables [primcodable α] [primcodable σ] open nat.partrec (code) nat.partrec.code computable theorem rice (C : set (ℕ →. ℕ)) (h : computable_pred (λ c, eval c ∈ C)) {f g} (hf : nat.partrec f) (hg : nat.partrec g) (fC : f ∈ C) : g ∈ C := begin cases h with _ h, resetI, rcases fixed_point₂ (partrec.cond (h.comp fst) ((partrec.nat_iff.2 hg).comp snd).to₂ ((partrec.nat_iff.2 hf).comp snd).to₂).to₂ with ⟨c, e⟩, simp at e, by_cases eval c ∈ C, { simp [h] at e, rwa ← e }, { simp at h, simp [h] at e, rw e at h, contradiction } end theorem rice₂ (C : set code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : computable_pred (λ c, c ∈ C) ↔ C = ∅ ∨ C = set.univ := by haveI := classical.dec; exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C, from λ f, ⟨set.mem_image_of_mem _, λ ⟨g, hg, e⟩, (H _ _ e).1 hg⟩, ⟨λ h, or_iff_not_imp_left.2 $ λ C0, set.eq_univ_of_forall $ λ cg, let ⟨cf, fC⟩ := set.ne_empty_iff_exists_mem.1 C0 in (hC _).2 $ rice (eval '' C) (h.of_eq hC) (partrec.nat_iff.1 $ eval_part.comp (const cf) computable.id) (partrec.nat_iff.1 $ eval_part.comp (const cg) computable.id) ((hC _).1 fC), λ h, by rcases h with rfl | rfl; simp [computable_pred]; exact ⟨by apply_instance, computable.const _⟩⟩ theorem halting_problem (n) : ¬ computable_pred (λ c, (eval c n).dom) | h := rice {f | (f n).dom} h nat.partrec.zero nat.partrec.none trivial end computable_pred namespace nat open vector roption /-- A simplified basis for `partrec`. -/ inductive partrec' : ∀ {n}, (vector ℕ n →. ℕ) → Prop | prim {n f} : @primrec' n f → @partrec' n f | comp {m n f} (g : fin n → vector ℕ m →. ℕ) : partrec' f → (∀ i, partrec' (g i)) → partrec' (λ v, m_of_fn (λ i, g i v) >>= f) | rfind {n} {f : vector ℕ (n+1) → ℕ} : @partrec' (n+1) f → partrec' (λ v, rfind (λ n, some (f (n :: v) = 0))) end nat namespace nat.partrec' open vector partrec computable nat (partrec') nat.partrec' theorem to_part {n f} (pf : @partrec' n f) : partrec f := begin induction pf, case nat.partrec'.prim : n f hf { exact hf.to_prim.to_comp }, case nat.partrec'.comp : m n f g _ _ hf hg { exact (vector_m_of_fn (λ i, hg i)).bind (hf.comp snd) }, case nat.partrec'.rfind : n f _ hf { have := ((primrec.eq.comp primrec.id (primrec.const 0)).to_comp.comp (hf.comp (vector_cons.comp snd fst))).to₂.part, exact this.rfind }, end theorem of_eq {n} {f g : vector ℕ n →. ℕ} (hf : partrec' f) (H : ∀ i, f i = g i) : partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : vector ℕ n → ℕ} (hf : primrec f) : @partrec' n f := prim (nat.primrec'.of_prim hf) theorem head {n : ℕ} : @partrec' n.succ (@head ℕ n) := prim nat.primrec'.head theorem tail {n f} (hf : @partrec' n f) : @partrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @prim _ _ $ nat.primrec'.nth i.succ)).of_eq $ λ v, by simp; rw [← of_fn_nth v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).bind (λ a, g (a :: v))) := (@comp n (n+1) g (λ i, fin.cases f (λ i v, some (v.nth i)) i) hg (λ i, begin refine fin.cases _ (λ i, _) i; simp *, exact prim (nat.primrec'.nth _) end)).of_eq $ λ v, by simp [m_of_fn, roption.bind_assoc, pure] protected theorem map {n f} {g : vector ℕ (n+1) → ℕ} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).map (λ a, g (a :: v))) := by simp [(roption.bind_some_eq_map _ _).symm]; exact hf.bind hg def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, partrec' (λ v, (f v).nth i) theorem vec.prim {n m f} (hf : @nat.primrec'.vec n m f) : vec f := λ i, prim $ hf i protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m} {f : vector ℕ n → ℕ} {g} (hf : @partrec' n f) (hg : @vec n m g) : vec (λ v, f v :: g v) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := vec.prim nat.primrec'.idv theorem comp' {n m f g} (hf : @partrec' m f) (hg : @vec n m g) : partrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : vector ℕ n → ℕ} (hf : @partrec' 1 (λ v, f v.head)) (hg : @partrec' n g) : @partrec' n (λ v, f (g v)) := by simpa using hf.comp' (partrec'.cons hg partrec'.nil) theorem rfind_opt {n} {f : vector ℕ (n+1) → ℕ} (hf : @partrec' (n+1) f) : @partrec' n (λ v, nat.rfind_opt (λ a, of_nat (option ℕ) (f (a :: v)))) := ((rfind $ (of_prim (primrec.nat_sub.comp (primrec.const 1) primrec.vector_head)) .comp₁ (λ n, roption.some (1 - n)) hf) .bind ((prim nat.primrec'.pred).comp₁ nat.pred hf)).of_eq $ λ v, roption.ext $ λ b, begin simp [nat.rfind_opt, -nat.mem_rfind], refine exists_congr (λ a, (and_congr (iff_of_eq _) iff.rfl).trans (and_congr_right (λ h, _))), { congr; funext n, simp, cases f (n :: v); simp [nat.succ_ne_zero]; refl }, { have := nat.rfind_spec h, simp at this, cases f (a :: v) with c, {cases this}, rw [← option.some_inj, eq_comm], refl } end open nat.partrec.code theorem of_part : ∀ {n f}, partrec f → @partrec' n f := suffices ∀ f, nat.partrec f → @partrec' 1 (λ v, f v.head), from λ n f hf, begin let g, swap, exact (comp₁ g (this g hf) (prim nat.primrec'.encode)).of_eq (λ i, by dsimp [g]; simp [encodek, roption.map_id']), end, λ f hf, begin rcases exists_code.1 hf with ⟨c, rfl⟩, simpa [eval_eq_rfind_opt] using (rfind_opt $ of_prim $ primrec.encode_iff.2 $ evaln_prim.comp $ (primrec.vector_head.pair (primrec.const c)).pair $ primrec.vector_head.comp primrec.vector_tail) end theorem part_iff {n f} : @partrec' n f ↔ partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : @partrec' 1 (λ v, f v.head) ↔ partrec f := part_iff.trans ⟨ λ h, (h.comp $ (primrec.vector_of_fn $ λ i, primrec.id).to_comp).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : @partrec' 2 (λ v, f v.head v.tail.head) ↔ partrec₂ f := part_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ computable f := ⟨λ h, by simpa using vector_of_fn (λ i, to_part (h i)), λ h i, of_part $ vector_nth.comp h (const i)⟩ end nat.partrec'
ece5d25ee85d78f03eecdbfde0e46a9020215915
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/monoidal/opposite.lean
fcb952d416984d0f37b1d3099b6d56a2144614a2
[ "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,217
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.coherence /-! # Monoidal opposites We write `Cᵐᵒᵖ` for the monoidal opposite of a monoidal category `C`. -/ universes v₁ v₂ u₁ u₂ variables {C : Type u₁} namespace category_theory open category_theory.monoidal_category /-- A type synonym for the monoidal opposite. Use the notation `Cᴹᵒᵖ`. -/ @[nolint has_nonempty_instance] def monoidal_opposite (C : Type u₁) := C namespace monoidal_opposite notation C `ᴹᵒᵖ`:std.prec.max_plus := monoidal_opposite C /-- Think of an object of `C` as an object of `Cᴹᵒᵖ`. -/ @[pp_nodot] def mop (X : C) : Cᴹᵒᵖ := X /-- Think of an object of `Cᴹᵒᵖ` as an object of `C`. -/ @[pp_nodot] def unmop (X : Cᴹᵒᵖ) : C := X lemma op_injective : function.injective (mop : C → Cᴹᵒᵖ) := λ _ _, id lemma unop_injective : function.injective (unmop : Cᴹᵒᵖ → C) := λ _ _, id @[simp] lemma op_inj_iff (x y : C) : mop x = mop y ↔ x = y := iff.rfl @[simp] lemma unop_inj_iff (x y : Cᴹᵒᵖ) : unmop x = unmop y ↔ x = y := iff.rfl attribute [irreducible] monoidal_opposite @[simp] lemma mop_unmop (X : Cᴹᵒᵖ) : mop (unmop X) = X := rfl @[simp] lemma unmop_mop (X : C) : unmop (mop X) = X := rfl instance monoidal_opposite_category [I : category.{v₁} C] : category Cᴹᵒᵖ := { hom := λ X Y, unmop X ⟶ unmop Y, id := λ X, 𝟙 (unmop X), comp := λ X Y Z f g, f ≫ g, } end monoidal_opposite end category_theory open category_theory open category_theory.monoidal_opposite variables [category.{v₁} C] /-- The monoidal opposite of a morphism `f : X ⟶ Y` is just `f`, thought of as `mop X ⟶ mop Y`. -/ def quiver.hom.mop {X Y : C} (f : X ⟶ Y) : @quiver.hom Cᴹᵒᵖ _ (mop X) (mop Y) := f /-- We can think of a morphism `f : mop X ⟶ mop Y` as a morphism `X ⟶ Y`. -/ def quiver.hom.unmop {X Y : Cᴹᵒᵖ} (f : X ⟶ Y) : unmop X ⟶ unmop Y := f namespace category_theory lemma mop_inj {X Y : C} : function.injective (quiver.hom.mop : (X ⟶ Y) → (mop X ⟶ mop Y)) := λ _ _ H, congr_arg quiver.hom.unmop H lemma unmop_inj {X Y : Cᴹᵒᵖ} : function.injective (quiver.hom.unmop : (X ⟶ Y) → (unmop X ⟶ unmop Y)) := λ _ _ H, congr_arg quiver.hom.mop H @[simp] lemma unmop_mop {X Y : C} {f : X ⟶ Y} : f.mop.unmop = f := rfl @[simp] lemma mop_unmop {X Y : Cᴹᵒᵖ} {f : X ⟶ Y} : f.unmop.mop = f := rfl @[simp] lemma mop_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).mop = f.mop ≫ g.mop := rfl @[simp] lemma mop_id {X : C} : (𝟙 X).mop = 𝟙 (mop X) := rfl @[simp] lemma unmop_comp {X Y Z : Cᴹᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unmop = f.unmop ≫ g.unmop := rfl @[simp] lemma unmop_id {X : Cᴹᵒᵖ} : (𝟙 X).unmop = 𝟙 (unmop X) := rfl @[simp] lemma unmop_id_mop {X : C} : (𝟙 (mop X)).unmop = 𝟙 X := rfl @[simp] lemma mop_id_unmop {X : Cᴹᵒᵖ} : (𝟙 (unmop X)).mop = 𝟙 X := rfl namespace iso variables {X Y : C} /-- An isomorphism in `C` gives an isomorphism in `Cᴹᵒᵖ`. -/ @[simps] def mop (f : X ≅ Y) : mop X ≅ mop Y := { hom := f.hom.mop, inv := f.inv.mop, hom_inv_id' := unmop_inj f.hom_inv_id, inv_hom_id' := unmop_inj f.inv_hom_id } end iso variables [monoidal_category.{v₁} C] open opposite monoidal_category instance monoidal_category_op : monoidal_category Cᵒᵖ := { tensor_obj := λ X Y, op (unop X ⊗ unop Y), tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (f.unop ⊗ g.unop).op, tensor_unit := op (𝟙_ C), associator := λ X Y Z, (α_ (unop X) (unop Y) (unop Z)).symm.op, left_unitor := λ X, (λ_ (unop X)).symm.op, right_unitor := λ X, (ρ_ (unop X)).symm.op, associator_naturality' := by { intros, apply quiver.hom.unop_inj, simp, }, left_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, }, right_unitor_naturality' := by { intros, apply quiver.hom.unop_inj, simp, }, triangle' := by { intros, apply quiver.hom.unop_inj, coherence, }, pentagon' := by { intros, apply quiver.hom.unop_inj, coherence, }, } lemma op_tensor_obj (X Y : Cᵒᵖ) : X ⊗ Y = op (unop X ⊗ unop Y) := rfl lemma op_tensor_unit : (𝟙_ Cᵒᵖ) = op (𝟙_ C) := rfl instance monoidal_category_mop : monoidal_category Cᴹᵒᵖ := { tensor_obj := λ X Y, mop (unmop Y ⊗ unmop X), tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (g.unmop ⊗ f.unmop).mop, tensor_unit := mop (𝟙_ C), associator := λ X Y Z, (α_ (unmop Z) (unmop Y) (unmop X)).symm.mop, left_unitor := λ X, (ρ_ (unmop X)).mop, right_unitor := λ X, (λ_ (unmop X)).mop, associator_naturality' := by { intros, apply unmop_inj, simp, }, left_unitor_naturality' := by { intros, apply unmop_inj, simp, }, right_unitor_naturality' := by { intros, apply unmop_inj, simp, }, triangle' := by { intros, apply unmop_inj, coherence, }, pentagon' := by { intros, apply unmop_inj, coherence, }, } lemma mop_tensor_obj (X Y : Cᴹᵒᵖ) : X ⊗ Y = mop (unmop Y ⊗ unmop X) := rfl lemma mop_tensor_unit : (𝟙_ Cᴹᵒᵖ) = mop (𝟙_ C) := rfl end category_theory
23eed55ef89df68776add5f3c2a52a464e361522
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monad/default_auto.lean
5b5af04ffd45a63304447b7e4257ef125b636b8e
[]
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
202
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 end Mathlib
f4ef3829de0de2b3b3014b02fbadaa4d4a172c80
9b9a16fa2cb737daee6b2785474678b6fa91d6d4
/src/ring_theory/algebra.lean
1e34dd1e140417e3e0465566e8d7cc530dfabef1
[ "Apache-2.0" ]
permissive
johoelzl/mathlib
253f46daa30b644d011e8e119025b01ad69735c4
592e3c7a2dfbd5826919b4605559d35d4d75938f
refs/heads/master
1,625,657,216,488
1,551,374,946,000
1,551,374,946,000
98,915,829
0
0
Apache-2.0
1,522,917,267,000
1,501,524,499,000
Lean
UTF-8
Lean
false
false
18,606
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Algebra over Commutative Ring (under category) -/ import data.polynomial data.multivariate_polynomial import linear_algebra.tensor_product import ring_theory.subring universes u v w u₁ v₁ open lattice local infix ` ⊗ `:100 := tensor_product /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg ⥤ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ class algebra (R : Type u) (A : Type v) [comm_ring R] [ring A] extends module R A := (to_fun : R → A) [hom : is_ring_hom to_fun] (commutes' : ∀ r x, x * to_fun r = to_fun r * x) (smul_def' : ∀ r x, r • x = to_fun r * x) attribute [instance] algebra.hom def algebra_map {R : Type u} (A : Type v) [comm_ring R] [ring A] [algebra R A] (x : R) : A := algebra.to_fun A x namespace algebra variables {R : Type u} {S : Type v} {A : Type w} variables [comm_ring R] [comm_ring S] [ring A] [algebra R A] /-- The codomain of an algebra. -/ instance : module R A := infer_instance instance : has_scalar R A := infer_instance instance {F : Type u} {K : Type v} [discrete_field F] [ring K] [algebra F K] : vector_space F K := @vector_space.mk F _ _ _ algebra.module include R instance : is_ring_hom (algebra_map A : R → A) := algebra.hom _ A variables (A) @[simp] lemma map_add (r s : R) : algebra_map A (r + s) = algebra_map A r + algebra_map A s := is_ring_hom.map_add _ @[simp] lemma map_neg (r : R) : algebra_map A (-r) = -algebra_map A r := is_ring_hom.map_neg _ @[simp] lemma map_sub (r s : R) : algebra_map A (r - s) = algebra_map A r - algebra_map A s := is_ring_hom.map_sub _ @[simp] lemma map_mul (r s : R) : algebra_map A (r * s) = algebra_map A r * algebra_map A s := is_ring_hom.map_mul _ variables (R) @[simp] lemma map_zero : algebra_map A (0 : R) = 0 := is_ring_hom.map_zero _ @[simp] lemma map_one : algebra_map A (1 : R) = 1 := is_ring_hom.map_one _ variables {R A} /-- Creating an algebra from a morphism in CRing. -/ def of_ring_hom (i : R → S) (hom : is_ring_hom i) : algebra R S := { smul := λ c x, i c * x, smul_zero := λ x, mul_zero (i x), smul_add := λ r x y, mul_add (i r) x y, add_smul := λ r s x, show i (r + s) * x = _, by rw [hom.3, add_mul], mul_smul := λ r s x, show i (r * s) * x = _, by rw [hom.2, mul_assoc], one_smul := λ x, show i 1 * x = _, by rw [hom.1, one_mul], zero_smul := λ x, show i 0 * x = _, by rw [@@is_ring_hom.map_zero _ _ i hom, zero_mul], to_fun := i, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c x, rfl } theorem smul_def (r : R) (x : A) : r • x = algebra_map A r * x := algebra.smul_def' r x theorem commutes (r : R) (x : A) : x * algebra_map A r = algebra_map A r * x := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map A r * y) = algebra_map A r * (x * y) := by rw [← mul_assoc, commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := by rw [smul_def, smul_def, mul_assoc] /-- R[X] is the generator of the category R-Alg. -/ instance polynomial (R : Type u) [comm_ring R] [decidable_eq R] : algebra R (polynomial R) := { to_fun := polynomial.C, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (polynomial.C_mul' c p).symm, .. polynomial.module } /-- The algebra of multivariate polynomials. -/ instance mv_polynomial (R : Type u) [comm_ring R] [decidable_eq R] (ι : Type v) [decidable_eq ι] : algebra R (mv_polynomial ι R) := { to_fun := mv_polynomial.C, commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (mv_polynomial.C_mul' c p).symm, .. mv_polynomial.module } /-- Creating an algebra from a subring. This is the dual of ring extension. -/ instance of_subring (S : set R) [is_subring S] : algebra S R := of_ring_hom subtype.val ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩ variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A →ₗ A →ₗ A := linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm]) set_option class.instance_max_depth 37 def lmul_left (r : A) : A →ₗ A := lmul R A r def lmul_right (r : A) : A →ₗ A := (lmul R A).flip r variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl end algebra /-- Defining the homomorphism in the category R-Alg. -/ structure alg_hom {R : Type u} (A : Type v) (B : Type w) [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] := (to_fun : A → B) [hom : is_ring_hom to_fun] (commutes' : ∀ r : R, to_fun (algebra_map A r) = algebra_map B r) infixr ` →ₐ `:25 := alg_hom notation A ` →ₐ[`:25 R `] ` B := @alg_hom R A B _ _ _ _ _ namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} variables [comm_ring R] [ring A] [ring B] [ring C] [ring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] include R instance : has_coe_to_fun (A →ₐ[R] B) := ⟨λ _, A → B, to_fun⟩ variables (φ : A →ₐ[R] B) instance : is_ring_hom ⇑φ := hom φ @[extensionality] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := by cases φ₁; cases φ₂; congr' 1; ext; apply H theorem commutes (r : R) : φ (algebra_map A r) = algebra_map B r := φ.commutes' r @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := is_ring_hom.map_add _ @[simp] lemma map_zero : φ 0 = 0 := is_ring_hom.map_zero _ @[simp] lemma map_neg (x) : φ (-x) = -φ x := is_ring_hom.map_neg _ @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := is_ring_hom.map_sub _ @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := is_ring_hom.map_mul _ @[simp] lemma map_one : φ 1 = 1 := is_ring_hom.map_one _ /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ B := { to_fun := φ, add := φ.map_add, smul := λ c x, by rw [algebra.smul_def, φ.map_mul, φ.commutes c, algebra.smul_def] } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ := ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H variables (R A) protected def id : A →ₐ[R] A := { to_fun := id, commutes' := λ _, rfl } variables {R A} @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ C := { to_fun := φ₁ ∘ φ₂, commutes' := λ r, by rw [function.comp_apply, φ₂.commutes, φ₁.commutes] } @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl end alg_hom namespace algebra variables (R : Type u) (S : Type v) (A : Type w) variables [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] include R S A def comap : Type w := A def comap.to_comap : A → comap R S A := id def comap.of_comap : comap R S A → A := id omit R S A instance comap.ring : ring (comap R S A) := _inst_3 instance comap.comm_ring (R : Type u) (S : Type v) (A : Type w) [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] : comm_ring (comap R S A) := _inst_8 instance comap.module : module S (comap R S A) := _inst_5.to_module instance comap.has_scalar : has_scalar S (comap R S A) := _inst_5.to_module.to_has_scalar /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ instance comap.algebra : algebra R (comap R S A) := { smul := λ r x, (algebra_map S r • x : A), smul_add := λ _ _ _, smul_add _ _ _, add_smul := λ _ _ _, by simp only [algebra.map_add]; from add_smul _ _ _, mul_smul := λ _ _ _, by simp only [algebra.map_mul]; from mul_smul _ _ _, one_smul := λ _, by simp only [algebra.map_one]; from one_smul _ _, zero_smul := λ _, by simp only [algebra.map_zero]; from zero_smul _ _, smul_zero := λ _, smul_zero _, to_fun := (algebra_map A : S → A) ∘ algebra_map S, hom := by letI : is_ring_hom (algebra_map A) := _inst_5.hom; apply_instance, commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _ } def to_comap : S →ₐ[R] comap R S A := { to_fun := (algebra_map A : S → A), hom := _inst_5.hom, commutes' := λ r, rfl } theorem to_comap_apply (x) : to_comap R S A x = (algebra_map A : S → A) x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_ring R] [comm_ring S] [ring A] [ring B] variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B) include R /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { to_fun := φ, hom := alg_hom.is_ring_hom _, commutes' := λ r, φ.commutes (algebra_map S r) } end alg_hom namespace polynomial variables (R : Type u) (A : Type v) variables [comm_ring R] [comm_ring A] [algebra R A] variables [decidable_eq R] (x : A) /-- A → Hom[R-Alg](R[X],A) -/ def aeval : polynomial R →ₐ[R] A := { to_fun := eval₂ (algebra_map A) x, hom := ⟨eval₂_one _ x, λ _ _, eval₂_mul _ x, λ _ _, eval₂_add _ x⟩, commutes' := λ r, eval₂_C _ _ } theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map A) x p := rfl instance aeval.is_ring_hom : is_ring_hom (aeval R A x) := alg_hom.hom _ theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, is_ring_hom.map_mul φ, eval₂_mul (algebra_map A : R → A), eval₂_X, ih] } end end polynomial namespace mv_polynomial variables (R : Type u) (A : Type v) variables [comm_ring R] [comm_ring A] [algebra R A] variables [decidable_eq R] [decidable_eq A] (σ : set A) /-- (ι → A) → Hom[R-Alg](R[ι],A) -/ def aeval : mv_polynomial σ R →ₐ[R] A := { to_fun := eval₂ (algebra_map A) subtype.val, hom := ⟨eval₂_one _ _, λ _ _, eval₂_mul _ _, λ _ _, eval₂_add _ _⟩, commutes' := λ r, eval₂_C _ _ _ } theorem aeval_def (p : mv_polynomial σ R) : aeval R A σ p = eval₂ (algebra_map A) subtype.val p := rfl instance aeval.is_ring_hom : is_ring_hom (aeval R A σ) := alg_hom.hom _ variables (ι : Type w) [decidable_eq ι] theorem eval_unique (φ : mv_polynomial ι R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map A) (φ ∘ X) p := begin apply mv_polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [is_ring_hom.map_add φ, ih1, ih2, eval₂_add] }, { intros p j ih, rw [is_ring_hom.map_mul φ, eval₂_mul, eval₂_X, ih] } end end mv_polynomial structure subalgebra (R : Type u) (A : Type v) [comm_ring R] [ring A] [algebra R A] : Type v := (carrier : set A) [subring : is_subring carrier] (range_le : set.range (algebra_map A : R → A) ≤ carrier) attribute [instance] subalgebra.subring namespace subalgebra variables {R : Type u} {A : Type v} variables [comm_ring R] [ring A] [algebra R A] include R instance : has_coe (subalgebra R A) (set A) := ⟨λ S, S.carrier⟩ instance : has_mem A (subalgebra R A) := ⟨λ x S, x ∈ S.carrier⟩ variables {A} theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s := iff.rfl @[extensionality] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := by cases S; cases T; congr; ext x; exact h x variables (S : subalgebra R A) instance : is_subring (S : set A) := S.subring instance : ring S := @@subtype.ring _ S.is_subring instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring instance algebra : algebra R S := { smul := λ (c:R) x, ⟨c • x.1, by rw algebra.smul_def; exact @@is_submonoid.mul_mem _ S.2.2 (S.3 ⟨c, rfl⟩) x.2⟩, smul_add := λ c x y, subtype.eq $ by apply _inst_3.1.1.2, add_smul := λ c x y, subtype.eq $ by apply _inst_3.1.1.3, mul_smul := λ c x y, subtype.eq $ by apply _inst_3.1.1.4, one_smul := λ x, subtype.eq $ by apply _inst_3.1.1.5, zero_smul := λ x, subtype.eq $ by apply _inst_3.1.1.6, smul_zero := λ x, subtype.eq $ by apply _inst_3.1.1.7, to_fun := λ r, ⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, hom := ⟨subtype.eq $ algebra.map_one R A, λ x y, subtype.eq $ algebra.map_mul A x y, λ x y, subtype.eq $ algebra.map_add A x y⟩, commutes' := λ c x, subtype.eq $ by apply _inst_3.4, smul_def' := λ c x, subtype.eq $ by apply _inst_3.5 } instance to_algebra (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : algebra S A := algebra.of_subring _ def val : S →ₐ[R] A := { to_fun := subtype.val, hom := ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩, commutes' := λ r, rfl } def to_submodule : submodule R A := { carrier := S.carrier, zero := (0:S).2, add := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } instance to_submodule.is_subring : is_subring (S.to_submodule : set A) := S.2 instance : partial_order (subalgebra R A) := { le := λ S T, S.carrier ≤ T.carrier, le_refl := λ _, le_refl _, le_trans := λ _ _ _, le_trans, le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ } def comap {R : Type u} {S : Type v} {A : Type w} [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] (iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) := { carrier := (iSB : set A), subring := iSB.is_subring, range_le := λ a ⟨r, hr⟩, hr ▸ iSB.range_le ⟨_, rfl⟩ } def under {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] {i : algebra R A} (S : subalgebra R A) (T : subalgebra S A) : subalgebra R A := { carrier := T, range_le := (λ a ⟨r, hr⟩, hr ▸ T.range_le ⟨⟨algebra_map A r, S.range_le ⟨r, rfl⟩⟩, rfl⟩) } end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [ring A] [ring B] [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) protected def range : subalgebra R B := { carrier := set.range φ, subring := { one_mem := ⟨1, φ.map_one⟩, mul_mem := λ y₁ y₂ ⟨x₁, hx₁⟩ ⟨x₂, hx₂⟩, ⟨x₁ * x₂, hx₁ ▸ hx₂ ▸ φ.map_mul x₁ x₂⟩ }, range_le := λ y ⟨r, hr⟩, ⟨algebra_map A r, hr ▸ φ.commutes r⟩ } end alg_hom namespace algebra variables {R : Type u} (A : Type v) variables [comm_ring R] [ring A] [algebra R A] include R variables (R) instance id : algebra R R := algebra.of_ring_hom id $ by apply_instance def of_id : R →ₐ A := { to_fun := algebra_map A, commutes' := λ _, rfl } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map A r := rfl variables (R) {A} def adjoin (s : set A) : subalgebra R A := { carrier := ring.closure (set.range (algebra_map A : R → A) ∪ s), range_le := le_trans (set.subset_union_left _ _) ring.subset_closure } variables {R} protected def gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) ring.subset_closure) H, λ H, ring.closure_subset $ set.union_subset S.range_le H⟩ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, adjoin R s, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map A : R → A) := suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl, le_antisymm bot_le $ subalgebra.range_le _ theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := ring.mem_closure $ or.inr trivial def to_top : A →ₐ[R] (⊤ : subalgebra R A) := { to_fun := λ x, ⟨x, mem_top⟩, hom := ⟨rfl, λ _ _, rfl, λ _ _, rfl⟩, commutes' := λ _, rfl } end algebra section int variables (R : Type*) [comm_ring R] /-- CRing ⥤ ℤ-Alg -/ def alg_hom_int {R : Type u} [comm_ring R] [algebra ℤ R] {S : Type v} [comm_ring S] [algebra ℤ S] (f : R → S) [is_ring_hom f] : R →ₐ[ℤ] S := { to_fun := f, hom := by apply_instance, commutes' := λ i, int.induction_on i (by rw [algebra.map_zero, algebra.map_zero, is_ring_hom.map_zero f]) (λ i ih, by rw [algebra.map_add, algebra.map_add, algebra.map_one, algebra.map_one]; rw [is_ring_hom.map_add f, is_ring_hom.map_one f, ih]) (λ i ih, by rw [algebra.map_sub, algebra.map_sub, algebra.map_one, algebra.map_one]; rw [is_ring_hom.map_sub f, is_ring_hom.map_one f, ih]) } /-- CRing ⥤ ℤ-Alg -/ instance algebra_int : algebra ℤ R := algebra.of_ring_hom coe $ by constructor; intros; simp variables {R} /-- CRing ⥤ ℤ-Alg -/ def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R := { carrier := S, range_le := λ x ⟨i, h⟩, h ▸ int.induction_on i (by rw algebra.map_zero; exact is_add_submonoid.zero_mem _) (λ i hi, by rw [algebra.map_add, algebra.map_one]; exact is_add_submonoid.add_mem hi (is_submonoid.one_mem _)) (λ i hi, by rw [algebra.map_sub, algebra.map_one]; exact is_add_subgroup.sub_mem _ _ _ hi (is_submonoid.one_mem _)) } @[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl end int
6be97ac2197fb6dbcd1731da5db1fea2b1b24ad1
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/quadratic_discriminant.lean
c409916124bd78b96e7c206e1d416915feb065b5
[ "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
6,906
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.ordered_field import tactic.linarith tactic.ring /-! # Quadratic discriminants and roots of a quadratic This file defines the discriminant of a quadratic and gives the solution to a quadratic equation. ## Main definition The discriminant of a quadratic `a*x*x + b*x + c` is `b*b - 4*a*c`. ## Main statements • Roots of a quadratic can be written as `(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is the square root of the discriminant. • If the discriminant has no square root, then the corresponding quadratic has no root. • If a quadratic is always non-negative, then its discriminant is non-positive. ## Tags polynomial, quadratic, discriminant, root -/ variables {α : Type*} section lemmas variables [linear_ordered_field α] {a b c : α} lemma exists_le_mul_self : ∀ a : α, ∃ x : α, a ≤ x * x := begin classical, -- TODO: otherwise linarith performance sucks assume a, cases le_total 1 a with ha ha, { use a, exact le_mul_of_ge_one_left (by linarith) ha }, { use 1, linarith } end lemma exists_lt_mul_self : ∀ a : α, ∃ x : α, a < x * x := begin classical, -- todo: otherwise linarith performance sucks assume a, rcases (exists_le_mul_self a) with ⟨x, hx⟩, cases le_total 0 x with hx' hx', { use (x + 1), have : (x+1)*(x+1) = x*x + 2*x + 1, {ring}, exact lt_of_le_of_lt hx (by rw this; linarith) }, { use (x - 1), have : (x-1)*(x-1) = x*x - 2*x + 1, {ring}, exact lt_of_le_of_lt hx (by rw this; linarith) } end end lemmas variables [linear_ordered_field α] {a b c x : α} /-- Discriminant of a quadratic -/ def discrim [ring α] (a b c : α) : α := b^2 - 4 * a * c /-- A quadratic has roots if and only if its discriminant equals some square. -/ lemma quadratic_eq_zero_iff_discrim_eq_square (ha : a ≠ 0) : ∀ x : α, a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b)^2 := by classical; exact -- TODO: otherwise linarith performance sucks assume x, iff.intro (assume h, calc discrim a b c = 4*a*(a*x*x + b*x + c) + b*b - 4*a*c : by rw [h, discrim]; ring ... = (2*a*x + b)^2 : by ring) (assume h, have ha : 2*2*a ≠ 0 := mul_ne_zero (mul_ne_zero two_ne_zero two_ne_zero) ha, eq_of_mul_eq_mul_left_of_ne_zero ha $ calc 2 * 2 * a * (a * x * x + b * x + c) = (2*a*x + b)^2 - (b^2 - 4*a*c) : by ring ... = 0 : by { rw [← h, discrim], ring } ... = 2*2*a*0 : by ring) /-- Roots of a quadratic -/ lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : α} (h : discrim a b c = s * s) : ∀ x : α, a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := assume x, begin classical, -- TODO: otherwise linarith performance sucks rw [quadratic_eq_zero_iff_discrim_eq_square ha, h, pow_two, mul_self_eq_mul_self_iff], have ne : 2 * a ≠ 0 := mul_ne_zero two_ne_zero ha, have : x = 2 * a * x / (2 * a) := (mul_div_cancel_left x ne).symm, have h₁ : 2 * a * ((-b + s) / (2 * a)) = -b + s := mul_div_cancel' _ ne, have h₂ : 2 * a * ((-b - s) / (2 * a)) = -b - s := mul_div_cancel' _ ne, split, { intro h', rcases h', { left, rw h', simpa [add_comm] }, { right, rw h', simpa [add_comm, sub_eq_add_neg] } }, { intro h', rcases h', { left, rw [h', h₁], ring }, { right, rw [h', h₂], ring } } end /-- A quadratic has roots if its discriminant has square roots -/ lemma exist_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) : ∃ x, a * x * x + b * x + c = 0 := begin rcases h with ⟨s, hs⟩, use (-b + s) / (2 * a), rw quadratic_eq_zero_iff ha hs, simp end /-- Root of a quadratic when its discriminant equals zero -/ lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) : ∀ x : α, a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) := assume x, begin classical, -- TODO: otherwise linarith performance sucks have : discrim a b c = 0 * 0 := eq.trans h (by ring), rw quadratic_eq_zero_iff ha this, simp end /-- A quadratic has no root if its discriminant has no square root. -/ lemma quadratic_ne_zero_of_discrim_ne_square (ha : a ≠ 0) (h : ∀ s : α, discrim a b c ≠ s * s) : ∀ (x : α), a * x * x + b * x + c ≠ 0 := begin assume x h', rw [quadratic_eq_zero_iff_discrim_eq_square ha, pow_two] at h', have := h _, contradiction end /-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/ lemma discriminant_le_zero {a b c : α} (h : ∀ x : α, 0 ≤ a*x*x + b*x + c) : discrim a b c ≤ 0 := by classical; exact -- TODO: otherwise linarith performance sucks have hc : 0 ≤ c, by { have := h 0, linarith }, begin rw [discrim, pow_two], cases lt_trichotomy a 0 with ha ha, -- if a < 0 cases classical.em (b = 0) with hb hb, { rw hb at *, rcases exists_lt_mul_self (-c/a) with ⟨x, hx⟩, have := mul_lt_mul_of_neg_left hx ha, rw [mul_div_cancel' _ (ne_of_lt ha), ← mul_assoc] at this, have h₂ := h x, linarith }, { cases classical.em (c = 0) with hc' hc', { rw hc' at *, have : -(a*-b*-b + b*-b + 0) = (1-a)*(b*b), {ring}, have h := h (-b), rw [← neg_nonpos, this] at h, have : b * b ≤ 0 := nonpos_of_mul_nonpos_left h (by linarith), linarith }, { have h := h (-c/b), have : a*(-c/b)*(-c/b) + b*(-c/b) + c = a*((c/b)*(c/b)), { rw mul_div_cancel' _ hb, ring }, rw this at h, have : 0 ≤ a := nonneg_of_mul_nonneg_right h (mul_self_pos $ div_ne_zero hc' hb), linarith [ha] } }, cases ha with ha ha, -- if a = 0 cases classical.em (b = 0) with hb hb, { rw [ha, hb], linarith }, { have := h ((-c-1)/b), rw [ha, mul_div_cancel' _ hb] at this, linarith }, -- if a > 0 have := calc 4*a* (a*(-(b/a)*(1/2))*(-(b/a)*(1/2)) + b*(-(b/a)*(1/2)) + c) = (a*(b/a)) * (a*(b/a)) - 2*(a*(b/a))*b + 4*a*c : by ring ... = -(b*b - 4*a*c) : by { simp only [mul_div_cancel' b (ne_of_gt ha)], ring }, have ha' : 0 ≤ 4*a, {linarith}, have h := (mul_nonneg ha' (h (-(b/a) * (1/2)))), rw this at h, rwa ← neg_nonneg end /-- If a polynomial of degree 2 is always positive, then its discriminant is negative, at least when the coefficient of the quadratic term is nonzero. -/ lemma discriminant_lt_zero {a b c : α} (ha : a ≠ 0) (h : ∀ x : α, 0 < a*x*x + b*x + c) : discrim a b c < 0 := begin classical, -- TODO: otherwise linarith performance sucks have : ∀ x : α, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x), refine lt_of_le_of_ne (discriminant_le_zero this) _, assume h', have := h (-b / (2 * a)), have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0, { rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] }, linarith end
7bd0b39a8489866b94916b6548be4e8175c4da3a
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/tactic/replacer.lean
34b8100493c2318abf44207cbcbb23ac87ad1cc6
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
4,773
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro A mechanism for defining tactics for use in auto params, whose meaning is defined incrementally through attributes. -/ import tactic.basic data.string.defs data.list.defs meta.expr namespace tactic meta def replacer_core {α : Type} [reflected α] (ntac : name) (eval : ∀ β [reflected β], expr → tactic β) : list name → tactic α | [] := fail ("no implementation defined for " ++ to_string ntac) | (n::ns) := do d ← get_decl n, let t := d.type, tac ← do { mk_const n >>= eval (tactic α) } <|> do { tac ← mk_const n >>= eval (tactic α → tactic α), return (tac (replacer_core ns)) } <|> do { tac ← mk_const n >>= eval (option (tactic α) → tactic α), return (tac (guard (ns ≠ []) >> some (replacer_core ns))) }, tac meta def replacer (ntac : name) {α : Type} [reflected α] (F : Type → Type) (eF : ∀ β, reflected β → reflected (F β)) (R : ∀ β, F β → β) : tactic α := attribute.get_instances ntac >>= replacer_core ntac (λ β eβ e, R β <$> @eval_expr' (F β) (eF β eβ) e) meta def mk_replacer₁ : expr → nat → expr × expr | (expr.pi n bi d b) i := let (e₁, e₂) := mk_replacer₁ b (i+1) in (expr.pi n bi d e₁, (`(expr.pi n bi d) : expr) e₂) | _ i := (expr.var i, expr.var 0) meta def mk_replacer₂ (ntac : name) (v : expr × expr) : expr → nat → option expr | (expr.pi n bi d b) i := do b' ← mk_replacer₂ b (i+1), some (expr.lam n bi d b') | `(tactic %%β) i := some $ (expr.const ``replacer []).mk_app [ reflect ntac, β, reflect β, expr.lam `γ binder_info.default `(Type) v.1, expr.lam `γ binder_info.default `(Type) $ expr.lam `eγ binder_info.inst_implicit ((`(@reflected Type) : expr) β) v.2, expr.lam `γ binder_info.default `(Type) $ expr.lam `f binder_info.default v.1 $ (list.range i).foldr (λ i e', e' (expr.var (i+2))) (expr.var 0) ] | _ i := none meta def mk_replacer (ntac : name) (e : expr) : tactic expr := mk_replacer₂ ntac (mk_replacer₁ e 0) e 0 meta def valid_types : expr → list expr | (expr.pi n bi d b) := expr.pi n bi d <$> valid_types b | `(tactic %%β) := [`(tactic.{0} %%β), `(tactic.{0} %%β → tactic.{0} %%β), `(option (tactic.{0} %%β) → tactic.{0} %%β)] | _ := [] meta def replacer_attr (ntac : name) : user_attribute := { name := ntac, descr := "Replaces the definition of `" ++ to_string ntac ++ "`. This should be " ++ "applied to a definition with the type `tactic unit`, which will be " ++ "called whenever `" ++ to_string ntac ++ "` is called. The definition " ++ "can optionally have an argument of type `tactic unit` or " ++ "`option (tactic unit)` which refers to the previous definition, if any.", after_set := some $ λ n _ _, do d ← get_decl n, base ← get_decl ntac, guardb ((valid_types base.type).any (=ₐ d.type)) <|> fail format!"incorrect type for @[{ntac}]" } /-- Define a new replaceable tactic. -/ meta def def_replacer (ntac : name) (ty : expr) : tactic unit := let nattr := ntac <.> "attr" in do add_meta_definition nattr [] `(user_attribute) `(replacer_attr %%(reflect ntac)), set_basic_attribute `user_attribute nattr tt, v ← mk_replacer ntac ty, add_meta_definition ntac [] ty v, add_doc_string ntac $ "The `" ++ to_string ntac ++ "` tactic is a \"replaceable\" " ++ "tactic, which means that its meaning is defined by tactics that " ++ "are defined later with the `@[" ++ to_string ntac ++ "]` attribute. " ++ "It is intended for use with `auto_param`s for structure fields." open interactive lean.parser /-- Define a new replaceable tactic. -/ @[user_command] meta def def_replacer_cmd (meta_info : decl_meta_info) (_ : parse $ tk "def_replacer") : lean.parser unit := do ntac ← ident, ty ← optional (tk ":" *> types.texpr), match ty with | (some p) := do t ← to_expr p, def_replacer ntac t | none := def_replacer ntac `(tactic unit) end meta def unprime : name → tactic name | nn@(name.mk_string s n) := let s' := s.over_list (list.take_while (≠ ''')) in if s'.length < s.length then pure (name.mk_string s' n) else fail format!"expecting primed name: {nn}" | n := fail format!"invalid name: {n}" @[user_attribute] meta def replaceable_attr : user_attribute := { name := `replaceable, descr := "make definition replaceable in dependent modules", after_set := some $ λ n' _ _, do { n ← unprime n', d ← get_decl n', «def_replacer» n d.type, (replacer_attr n).set n' () tt } } end tactic
8e3b4ba7c69b54e710b3283d2cb3df661bd5813b
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/hw8/hw8_turn_in/associativity_and_precedence.lean
b3d9b016a494c4043144ccc0189307133d31b638
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
2,945
lean
import .propositional_logic_syntax_and_semantics open pExp #check 2 + 3 + 4 #check (2 + 3) + 4 #check 2 + (3 + 4) /- Motivation: Can't overlad →. First attempt at a solution: overload > to mean pImp, as follows. notation e1 > e2 := pImp e1 e2 Problem: > is a reserved notation in Lean. We can overload it but we cannot change either is precedence or its associativity. The notation is thus non-standard and confusing. -/ def P := pVar (var.mk 0) def Q := pVar (var.mk 1) def R := pVar (var.mk 2) -- associativity is wrong #check P >> Q >> R #check P >> (Q >> R) #check (P >> Q) >> R -- associativity is wrong #check P ∧ Q >> Q >> R #check (P ∧ Q) >> (Q >> R) #check P ∧ (Q >> Q) >> R -- precedence is wrong, too #check P ∨ Q >> Q >> R #check (P ∨ Q) >> (Q >> R) #check P ∨ (Q >> Q) >> R #check P ∧ Q >> Q >> R #check (P ∧ Q) >> (Q >> R) #check P ∧ (Q >> Q) >> R #check P >> Q ↔ Q >> P #check (P >> Q) ↔ (Q >> P) /- Solution: Define our own infix operator with appropriate precedence (also called) binding strength. First, let's see where the other reserved operators that we're using (such as ∧ and ∨) get their binding strengths: from one of Lean's libraries. Here's what appears there (some details omitted). /- /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` == `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:100 reserve infixr ` ^ `:80 reserve infixr ` ∘ `:90 -- input with \comp reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 -/ -/ -- Here's our new notation infixr ` >> ` : 30 := pImp -- associativity is correct #check P >> Q >> R #check P >> (Q >> R) #check (P >> Q) >> R -- precedence is correct #check P ∧ Q >> Q >> R #check (P ∧ Q) >> (Q >> R) #check P ∧ (Q >> Q) >> R #check P ∨ Q >> Q >> R #check P ∨ Q >> (Q >> R) #check P ∨ (Q >> (Q >> R)) --uh oh, another bug! /- What is wrong? How to fix it? -/ #check (P ∨ Q) >> (Q >> R) #check (P ∨ Q) >> Q >> R axioms X Y Z : Prop #check X ∨ Y → Y → Z #check X ∨ Y → (Y → Z) #check (P ∨ Q) >> Q >> R #check P ∨ (Q >> Q) >> R #check P ∧ Q >> Q >> R #check (P ∧ Q) >> (Q >> R) #check P ∧ (Q >> Q) >> R #check P >> Q ↔ Q >> P #check (P >> Q) ↔ (Q >> P)
6fbe5e25a2d747f7fb7847a49183d8e1521f5c3a
f68ef9a599ec5575db7b285d4960e63c5d464ccc
/Exercises/Lista 2/capitulo-04-LucasMoschen.lean
f222f8079b9b7a84447428fb118e97ce22e50bad
[]
no_license
lucasmoschen/discrete-mathematics
a38d5970cc571b0b9d202bf6a43efeb8ed6f66e3
0f1945cc5eb094814c926cd6ae4a8b4c5c579a1e
refs/heads/master
1,677,111,757,003
1,611,500,097,000
1,611,500,097,000
205,903,359
1
0
null
null
null
null
UTF-8
Lean
false
false
1,306
lean
variables A B C D : Prop example : A ∧ (A → B) → B := assume : A ∧ (A → B), show B, from (and.right this) (and.left this) example : A → ¬ (¬ A ∧ B) := assume h: A, assume h₁ : ¬A ∧ B, show false, from (and.left h₁) h example : ¬ (A ∧ B) → (A → ¬ B) := assume h: ¬ (A ∧ B), assume h₁ : A, assume h₂ : B, show false, from h (and.intro h₁ h₂) example (h₁ : A ∨ B) (h₂ : A → C) (h₃ : B → D) : C ∨ D := show C ∨ D, from or.elim h₁ (assume h: A, show C ∨ D, from or.inl (h₂ h)) (assume h: B, show C ∨ D, from or.inr (h₃ h)) theorem or_resolve_left (h1 : A ∨ B) (h2 : ¬ A) : B := or.elim h1 (assume h3 : A, show B, from false.elim (h2 h3)) (assume h3 : B, show B, from h3) example (h : ¬ A ∧ ¬ B) : ¬ (A ∨ B) := assume h₁ : A ∨ B, show false, from or.elim h₁ (assume h₂ : A, show false, from (and.left h) h₂) (assume h₂ : B, show false, from (and.right h) h₂) open classical example : ¬ (A ↔ ¬ A) := assume h1 : A ↔ ¬ A, have h2: ¬A, from assume h4: A, have h5: ¬ A, from iff.elim_left h1 h4, show false, from h5 h4, have h3: A, from by_contradiction (assume h: ¬A, have h6: A, from iff.elim_right h1 h, show false, from h h6), show false, from h2 h3
df25909008834d13c231864a221b0872409e9e52
4727251e0cd73359b15b664c3170e5d754078599
/src/data/psigma/order.lean
28fcd68846249a1929517da2831ade841eb65191
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,743
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Minchao Wu -/ import data.sigma.lex import order.synonym /-! # Lexicographic order on a sigma type This file defines the lexicographic order on `Σₗ' i, α i`. `a` is less than `b` if its summand is strictly less than the summand of `b` or they are in the same summand and `a` is less than `b` there. ## Notation * `Σₗ' i, α i`: Sigma type equipped with the lexicographic order. A type synonym of `Σ' i, α i`. ## See also Related files are: * `data.finset.colex`: Colexicographic order on finite sets. * `data.list.lex`: Lexicographic order on lists. * `data.sigma.order`: Lexicographic order on `Σₗ i, α i`. Basically a twin of this file. * `order.lexicographic`: Lexicographic order on `α × β`. ## TODO Define the disjoint order on `Σ' i, α i`, where `x ≤ y` only if `x.fst = y.fst`. Prove that a sigma type is a `no_max_order`, `no_min_order`, `densely_ordered` when its summands are. -/ variables {ι : Type*} {α : ι → Type*} namespace psigma notation `Σₗ'` binders `, ` r:(scoped p, _root_.lex (psigma p)) := r /-- The lexicographical `≤` on a sigma type. -/ instance lex.has_le [has_lt ι] [Π i, has_le (α i)] : has_le (Σₗ' i, α i) := { le := lex (<) (λ i, (≤)) } /-- The lexicographical `<` on a sigma type. -/ instance lex.has_lt [has_lt ι] [Π i, has_lt (α i)] : has_lt (Σₗ' i, α i) := { lt := lex (<) (λ i, (<)) } instance lex.preorder [preorder ι] [Π i, preorder (α i)] : preorder (Σₗ' i, α i) := { le_refl := λ ⟨i, a⟩, lex.right _ le_rfl, le_trans := begin rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ ⟨a₃, b₃⟩ ⟨h₁l, h₁r⟩ ⟨h₂l, h₂r⟩, { left, apply lt_trans, repeat { assumption } }, { left, assumption }, { left, assumption }, { right, apply le_trans, repeat { assumption } } end, lt_iff_le_not_le := begin refine λ a b, ⟨λ hab, ⟨hab.mono_right (λ i a b, le_of_lt), _⟩, _⟩, { rintro (⟨j, i, b, a, hji⟩ | ⟨i, b, a, hba⟩); obtain (⟨_, _, _, _, hij⟩ | ⟨_, _, _, hab⟩) := hab, { exact hij.not_lt hji }, { exact lt_irrefl _ hji }, { exact lt_irrefl _ hij }, { exact hab.not_le hba } }, { rintro ⟨⟨i, j, a, b, hij⟩ |⟨i, a, b, hab⟩, hba⟩, { exact lex.left _ _ hij }, { exact lex.right _ (hab.lt_of_not_le $ λ h, hba $ lex.right _ h) } } end, .. lex.has_le, .. lex.has_lt } /-- Dictionary / lexicographic partial_order for dependent pairs. -/ instance lex.partial_order [partial_order ι] [Π i, partial_order (α i)] : partial_order (Σₗ' i, α i) := { le_antisymm := begin rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ (⟨_, _, _, _, hlt₁⟩ | ⟨_, _, _, hlt₁⟩) (⟨_, _, _, _, hlt₂⟩ | ⟨_, _, _, hlt₂⟩), { exact (lt_irrefl a₁ $ hlt₁.trans hlt₂).elim }, { exact (lt_irrefl a₁ hlt₁).elim }, { exact (lt_irrefl a₁ hlt₂).elim }, { rw hlt₁.antisymm hlt₂ } end .. lex.preorder } /-- Dictionary / lexicographic linear_order for pairs. -/ instance lex.linear_order [linear_order ι] [Π i, linear_order (α i)] : linear_order (Σₗ' i, α i) := { le_total := begin rintro ⟨i, a⟩ ⟨j, b⟩, obtain hij | rfl | hji := lt_trichotomy i j, { exact or.inl (lex.left _ _ hij) }, { obtain hab | hba := le_total a b, { exact or.inl (lex.right _ hab) }, { exact or.inr (lex.right _ hba) } }, { exact or.inr (lex.left _ _ hji) } end, decidable_eq := psigma.decidable_eq, decidable_le := lex.decidable _ _, decidable_lt := lex.decidable _ _, .. lex.partial_order } end psigma
24a6fb2c15a786d3fd41ac367bfdee87c7ebae13
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/doc/demo/nnf.lean
518b40f50dff8db7b795c5d1cfbb12627feae584
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
509
lean
rewrite_set NNF add_rewrite not_not_eq not_true not_false not_neq not_and not_or not_iff not_implies not_forall not_exists forall_and_distribute exists_and_distributer exists_and_distributel : NNF variable p : Nat → Nat → Bool variable f : Nat → Nat variable g : Nat → Nat → Nat (* local t1 = parse_lean('¬ ∀ x, (∃ y, p x y ∨ p (f x) (f y)) ∨ f 0 = 1') local t2, pr = simplify(t1, "NNF") print(t1) print("====>") print(t2) -- print(pr) get_environment():type_check(pr) *)
b637c5a889bf053c7d17689719efbb5f564c327c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/perfection_auto.lean
7570085f3e46cf9de16687c9caf3806552be09f7
[]
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
24,840
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.char_p.default import Mathlib.algebra.ring.pi import Mathlib.analysis.special_functions.pow import Mathlib.field_theory.perfect_closure import Mathlib.ring_theory.localization import Mathlib.ring_theory.subring import Mathlib.ring_theory.valuation.integers import Mathlib.PostPort universes u₁ u₂ l u₃ u₄ namespace Mathlib /-! # Ring Perfection and Tilt In this file we define the perfection of a ring of characteristic p, and the tilt of a field given a valuation to `ℝ≥0`. ## TODO Define the valuation on the tilt, and define a characteristic predicate for the tilt. -/ /-- The perfection of a monoid `M`, defined to be the projective limit of `M` using the `p`-th power maps `M → M` indexed by the natural numbers, implemented as `{ f : ℕ → M | ∀ n, f (n + 1) ^ p = f n }`. -/ def monoid.perfection (M : Type u₁) [comm_monoid M] (p : ℕ) : submonoid (ℕ → M) := submonoid.mk (set_of fun (f : ℕ → M) => ∀ (n : ℕ), f (n + 1) ^ p = f n) sorry sorry /-- The perfection of a ring `R` with characteristic `p`, defined to be the projective limit of `R` using the Frobenius maps `R → R` indexed by the natural numbers, implemented as `{ f : ℕ → R | ∀ n, f (n + 1) ^ p = f n }`. -/ def ring.perfection (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] : subsemiring (ℕ → R) := subsemiring.mk (submonoid.carrier (monoid.perfection R p)) sorry sorry sorry sorry namespace perfection /-- The `n`-th coefficient of an element of the perfection. -/ def coeff (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] (n : ℕ) : ↥(ring.perfection R p) →+* R := ring_hom.mk (fun (f : ↥(ring.perfection R p)) => subtype.val f n) sorry sorry sorry sorry theorem ext {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] {f : ↥(ring.perfection R p)} {g : ↥(ring.perfection R p)} (h : ∀ (n : ℕ), coe_fn (coeff R p n) f = coe_fn (coeff R p n) g) : f = g := subtype.eq (funext h) /-- The `p`-th root of an element of the perfection. -/ def pth_root (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] : ↥(ring.perfection R p) →+* ↥(ring.perfection R p) := ring_hom.mk (fun (f : ↥(ring.perfection R p)) => { val := fun (n : ℕ) => coe_fn (coeff R p (n + 1)) f, property := sorry }) sorry sorry sorry sorry @[simp] theorem coeff_mk {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ℕ → R) (hf : f ∈ ring.perfection R p) (n : ℕ) : coe_fn (coeff R p n) { val := f, property := hf } = f n := rfl theorem coeff_pth_root {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff R p n) (coe_fn (pth_root R p) f) = coe_fn (coeff R p (n + 1)) f := rfl theorem coeff_pow_p {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff R p (n + 1)) (f ^ p) = coe_fn (coeff R p n) f := sorry theorem coeff_pow_p' {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff R p (n + 1)) f ^ p = coe_fn (coeff R p n) f := subtype.property f n theorem coeff_frobenius {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff R p (n + 1)) (coe_fn (frobenius (↥(ring.perfection R p)) p) f) = coe_fn (coeff R p n) f := sorry theorem coeff_iterate_frobenius {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) (m : ℕ) : coe_fn (coeff R p (n + m)) (nat.iterate (⇑(frobenius (↥(ring.perfection R p)) p)) m f) = coe_fn (coeff R p n) f := sorry theorem coeff_iterate_frobenius' {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] (f : ↥(ring.perfection R p)) (n : ℕ) (m : ℕ) (hmn : m ≤ n) : coe_fn (coeff R p n) (nat.iterate (⇑(frobenius (↥(ring.perfection R p)) p)) m f) = coe_fn (coeff R p (n - m)) f := Eq.symm (Eq.trans (Eq.symm (coeff_iterate_frobenius f (n - m) m)) (Eq.symm (nat.sub_add_cancel hmn) ▸ rfl)) theorem pth_root_frobenius {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] : ring_hom.comp (pth_root R p) (frobenius (↥(ring.perfection R p)) p) = ring_hom.id ↥(ring.perfection R p) := sorry theorem frobenius_pth_root {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] : ring_hom.comp (frobenius (↥(ring.perfection R p)) p) (pth_root R p) = ring_hom.id ↥(ring.perfection R p) := sorry theorem coeff_add_ne_zero {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] {f : ↥(ring.perfection R p)} {n : ℕ} (hfn : coe_fn (coeff R p n) f ≠ 0) (k : ℕ) : coe_fn (coeff R p (n + k)) f ≠ 0 := sorry theorem coeff_ne_zero_of_le {R : Type u₁} [comm_semiring R] {p : ℕ} [hp : fact (nat.prime p)] [char_p R p] {f : ↥(ring.perfection R p)} {m : ℕ} {n : ℕ} (hfm : coe_fn (coeff R p m) f ≠ 0) (hmn : m ≤ n) : coe_fn (coeff R p n) f ≠ 0 := sorry protected instance perfect_ring (R : Type u₁) [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] : perfect_ring (↥(ring.perfection R p)) p := perfect_ring.mk ⇑(pth_root R p) sorry sorry protected instance ring (p : ℕ) [hp : fact (nat.prime p)] (R : Type u₁) [comm_ring R] [char_p R p] : ring ↥(ring.perfection R p) := subring.to_ring (subsemiring.to_subring (ring.perfection R p) sorry) protected instance comm_ring (p : ℕ) [hp : fact (nat.prime p)] (R : Type u₁) [comm_ring R] [char_p R p] : comm_ring ↥(ring.perfection R p) := subring.to_comm_ring (subsemiring.to_subring (ring.perfection R p) sorry) /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* perfection S p`. -/ @[simp] theorem lift_symm_apply (p : ℕ) [hp : fact (nat.prime p)] (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] (hmn : R →+* ↥(ring.perfection S p)) : coe_fn (equiv.symm (lift p R S)) hmn = ring_hom.comp (coeff S p 0) hmn := Eq.refl (coe_fn (equiv.symm (lift p R S)) hmn) theorem hom_ext (p : ℕ) [hp : fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {f : R →+* ↥(ring.perfection S p)} {g : R →+* ↥(ring.perfection S p)} (hfg : ∀ (x : R), coe_fn (coeff S p 0) (coe_fn f x) = coe_fn (coeff S p 0) (coe_fn g x)) : f = g := equiv.injective (equiv.symm (lift p R S)) (ring_hom.ext hfg) /-- A ring homomorphism `R →+* S` induces `perfection R p →+* perfection S p` -/ @[simp] theorem map_apply_coe {R : Type u₁} [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] {S : Type u₂} [comm_semiring S] [char_p S p] (φ : R →+* S) (f : ↥(ring.perfection R p)) (n : ℕ) : coe (coe_fn (map p φ) f) n = coe_fn φ (coe_fn (coeff R p n) f) := Eq.refl (coe (coe_fn (map p φ) f) n) theorem coeff_map {R : Type u₁} [comm_semiring R] (p : ℕ) [hp : fact (nat.prime p)] [char_p R p] {S : Type u₂} [comm_semiring S] [char_p S p] (φ : R →+* S) (f : ↥(ring.perfection R p)) (n : ℕ) : coe_fn (coeff S p n) (coe_fn (map p φ) f) = coe_fn φ (coe_fn (coeff R p n) f) := rfl end perfection /-- A perfection map to a ring of characteristic `p` is a map that is isomorphic to its perfection. -/ structure perfection_map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₂} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* R) where injective : ∀ {x y : P}, (∀ (n : ℕ), coe_fn π (nat.iterate (⇑(pth_root P p)) n x) = coe_fn π (nat.iterate (⇑(pth_root P p)) n y)) → x = y surjective : ∀ (f : ℕ → R), (∀ (n : ℕ), f (n + 1) ^ p = f n) → ∃ (x : P), ∀ (n : ℕ), coe_fn π (nat.iterate (⇑(pth_root P p)) n x) = f n namespace perfection_map /-- Create a `perfection_map` from an isomorphism to the perfection. -/ theorem mk' {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {f : P →+* R} (g : P ≃+* ↥(ring.perfection R p)) (hfg : coe_fn (perfection.lift p P R) f = ↑g) : perfection_map p f := sorry /-- The canonical perfection map from the perfection of a ring. -/ theorem of (p : ℕ) [fact (nat.prime p)] (R : Type u₁) [comm_semiring R] [char_p R p] : perfection_map p (perfection.coeff R p 0) := mk' (ring_equiv.refl ↥(ring.perfection R p)) (iff.mpr (equiv.apply_eq_iff_eq_symm_apply (perfection.lift p (↥(ring.perfection R p)) R)) rfl) /-- For a perfect ring, it itself is the perfection. -/ theorem id (p : ℕ) [fact (nat.prime p)] (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] : perfection_map p (ring_hom.id R) := sorry /-- A perfection map induces an isomorphism to the prefection. -/ def equiv {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) : P ≃+* ↥(ring.perfection R p) := ring_equiv.of_bijective (coe_fn (perfection.lift p P R) π) sorry theorem equiv_apply {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) (x : P) : coe_fn (equiv m) x = coe_fn (coe_fn (perfection.lift p P R) π) x := rfl theorem comp_equiv {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) (x : P) : coe_fn (perfection.coeff R p 0) (coe_fn (equiv m) x) = coe_fn π x := rfl theorem comp_equiv' {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) : ring_hom.comp (perfection.coeff R p 0) ↑(equiv m) = π := ring_hom.ext fun (x : P) => rfl theorem comp_symm_equiv {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) (f : ↥(ring.perfection R p)) : coe_fn π (coe_fn (ring_equiv.symm (equiv m)) f) = coe_fn (perfection.coeff R p 0) f := Eq.trans (Eq.symm (comp_equiv m (coe_fn (ring_equiv.symm (equiv m)) f))) (congr_arg (⇑(perfection.coeff R p 0)) (ring_equiv.apply_symm_apply (equiv m) f)) theorem comp_symm_equiv' {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {π : P →+* R} (m : perfection_map p π) : ring_hom.comp π ↑(ring_equiv.symm (equiv m)) = perfection.coeff R p 0 := ring_hom.ext (comp_symm_equiv m) /-- Given rings `R` and `S` of characteristic `p`, with `R` being perfect, any homomorphism `R →+* S` can be lifted to a homomorphism `R →+* P`, where `P` is any perfection of `S`. -/ @[simp] theorem lift_apply (p : ℕ) [fact (nat.prime p)] (R : Type u₁) [comm_semiring R] [char_p R p] [perfect_ring R p] (S : Type u₂) [comm_semiring S] [char_p S p] (P : Type u₃) [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) (f : R →+* S) : coe_fn (lift p R S P π m) f = ring_hom.comp (↑(ring_equiv.symm (equiv m))) (coe_fn (perfection.lift p R S) f) := Eq.refl (coe_fn (lift p R S P π m) f) theorem hom_ext {p : ℕ} [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] [perfect_ring R p] {S : Type u₂} [comm_semiring S] [char_p S p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] (π : P →+* S) (m : perfection_map p π) {f : R →+* P} {g : R →+* P} (hfg : ∀ (x : R), coe_fn π (coe_fn f x) = coe_fn π (coe_fn g x)) : f = g := equiv.injective (equiv.symm (lift p R S P π m)) (ring_hom.ext hfg) /-- A ring homomorphism `R →+* S` induces `P →+* Q`, a map of the respective perfections -/ def map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {S : Type u₂} [comm_semiring S] [char_p S p] {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : P →+* Q := coe_fn (lift p P S Q σ n) (ring_hom.comp φ π) theorem comp_map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {S : Type u₂} [comm_semiring S] [char_p S p] {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) : ring_hom.comp σ (map p m n φ) = ring_hom.comp φ π := equiv.symm_apply_apply (lift p P S Q σ n) (ring_hom.comp φ π) theorem map_map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {P : Type u₃} [comm_semiring P] [char_p P p] [perfect_ring P p] {S : Type u₂} [comm_semiring S] [char_p S p] {Q : Type u₄} [comm_semiring Q] [char_p Q p] [perfect_ring Q p] {π : P →+* R} (m : perfection_map p π) {σ : Q →+* S} (n : perfection_map p σ) (φ : R →+* S) (x : P) : coe_fn σ (coe_fn (map p m n φ) x) = coe_fn φ (coe_fn π x) := iff.mp ring_hom.ext_iff (comp_map p m n φ) x -- Why is this slow? theorem map_eq_map (p : ℕ) [fact (nat.prime p)] {R : Type u₁} [comm_semiring R] [char_p R p] {S : Type u₂} [comm_semiring S] [char_p S p] (φ : R →+* S) : map p (of p R) (of p S) φ = perfection.map p φ := sorry end perfection_map /-- `O/(p)` for `O`, ring of integers of `K`. -/ def mod_p (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) := ideal.quotient (ideal.span (singleton ↑p)) namespace mod_p protected instance comm_ring (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) : comm_ring (mod_p K v O hv p) := ideal.quotient.comm_ring (ideal.span (singleton ↑p)) protected instance char_p (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : char_p (mod_p K v O hv p) p := char_p.quotient O p (mt (valuation.integers.one_of_is_unit hv) (Eq.symm (ring_hom.map_nat_cast (algebra_map O K) p) ▸ hvp)) protected instance nontrivial (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : nontrivial (mod_p K v O hv p) := char_p.nontrivial_of_char_ne_one (nat.prime.ne_one hp) /-- For a field `K` with valuation `v : K → ℝ≥0` and ring of integers `O`, a function `O/(p) → ℝ≥0` that sends `0` to `0` and `x + (p)` to `v(x)` as long as `x ∉ (p)`. -/ def pre_val (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) (x : mod_p K v O hv p) : nnreal := ite (x = 0) 0 (coe_fn v (coe_fn (algebra_map O K) (quotient.out' x))) theorem pre_val_mk {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} {x : O} (hx : coe_fn (ideal.quotient.mk (ideal.span (singleton ↑p))) x ≠ 0) : pre_val K v O hv p (coe_fn (ideal.quotient.mk (ideal.span (singleton ↑p))) x) = coe_fn v (coe_fn (algebra_map O K) x) := sorry theorem pre_val_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} : pre_val K v O hv p 0 = 0 := if_pos rfl theorem pre_val_mul {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} {x : mod_p K v O hv p} {y : mod_p K v O hv p} (hxy0 : x * y ≠ 0) : pre_val K v O hv p (x * y) = pre_val K v O hv p x * pre_val K v O hv p y := sorry theorem pre_val_add {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} (x : mod_p K v O hv p) (y : mod_p K v O hv p) : pre_val K v O hv p (x + y) ≤ max (pre_val K v O hv p x) (pre_val K v O hv p y) := sorry theorem v_p_lt_pre_val {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} {x : mod_p K v O hv p} : coe_fn v ↑p < pre_val K v O hv p x ↔ x ≠ 0 := sorry theorem pre_val_eq_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} {x : mod_p K v O hv p} : pre_val K v O hv p x = 0 ↔ x = 0 := sorry theorem v_p_lt_val {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] (hv : valuation.integers v O) {p : ℕ} {x : O} : coe_fn v ↑p < coe_fn v (coe_fn (algebra_map O K) x) ↔ coe_fn (ideal.quotient.mk (ideal.span (singleton ↑p))) x ≠ 0 := sorry theorem mul_ne_zero_of_pow_p_ne_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] {x : mod_p K v O hv p} {y : mod_p K v O hv p} (hx : x ^ p ≠ 0) (hy : y ^ p ≠ 0) : x * y ≠ 0 := sorry end mod_p /-- Perfection of `O/(p)` where `O` is the ring of integers of `K`. -/ def pre_tilt (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : subsemiring (ℕ → mod_p K v O hv p) := ring.perfection (mod_p K v O hv p) p namespace pre_tilt protected instance comm_ring (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : comm_ring ↥(pre_tilt K v O hv p) := perfection.comm_ring p (mod_p K v O hv p) /-- The valuation `Perfection(O/(p)) → ℝ≥0` as a function. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ def val_aux (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] (f : ↥(pre_tilt K v O hv p)) : nnreal := dite (∃ (n : ℕ), coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0) (fun (h : ∃ (n : ℕ), coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0) => mod_p.pre_val K v O hv p (coe_fn (perfection.coeff (mod_p K v O hv p) p (nat.find h)) f) ^ p ^ nat.find h) fun (h : ¬∃ (n : ℕ), coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0) => 0 theorem coeff_nat_find_add_ne_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] {f : ↥(pre_tilt K v O hv p)} {h : ∃ (n : ℕ), coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0} (k : ℕ) : coe_fn (perfection.coeff (mod_p K v O hv p) p (nat.find h + k)) f ≠ 0 := perfection.coeff_add_ne_zero (nat.find_spec h) k theorem val_aux_eq {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] {f : ↥(pre_tilt K v O hv p)} {n : ℕ} (hfn : coe_fn (perfection.coeff (mod_p K v O hv p) p n) f ≠ 0) : val_aux K v O hv p f = mod_p.pre_val K v O hv p (coe_fn (perfection.coeff (mod_p K v O hv p) p n) f) ^ p ^ n := sorry theorem val_aux_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : val_aux K v O hv p 0 = 0 := sorry theorem val_aux_one {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : val_aux K v O hv p 1 = 1 := sorry theorem val_aux_mul {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] (f : ↥(pre_tilt K v O hv p)) (g : ↥(pre_tilt K v O hv p)) : val_aux K v O hv p (f * g) = val_aux K v O hv p f * val_aux K v O hv p g := sorry theorem val_aux_add {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] (f : ↥(pre_tilt K v O hv p)) (g : ↥(pre_tilt K v O hv p)) : val_aux K v O hv p (f + g) ≤ max (val_aux K v O hv p f) (val_aux K v O hv p g) := sorry /-- The valuation `Perfection(O/(p)) → ℝ≥0`. Given `f ∈ Perfection(O/(p))`, if `f = 0` then output `0`; otherwise output `pre_val(f(n))^(p^n)` for any `n` such that `f(n) ≠ 0`. -/ def val (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : valuation (↥(pre_tilt K v O hv p)) nnreal := valuation.mk (val_aux K v O hv p) val_aux_zero val_aux_one val_aux_mul val_aux_add theorem map_eq_zero {K : Type u₁} [field K] {v : valuation K nnreal} {O : Type u₂} [comm_ring O] [algebra O K] {hv : valuation.integers v O} {p : ℕ} [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] {f : ↥(pre_tilt K v O hv p)} : coe_fn (val K v O hv p) f = 0 ↔ f = 0 := sorry protected instance integral_domain (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : integral_domain ↥(pre_tilt K v O hv p) := integral_domain.mk comm_ring.add sorry comm_ring.zero sorry sorry comm_ring.neg comm_ring.sub sorry sorry comm_ring.mul sorry comm_ring.one sorry sorry sorry sorry sorry sorry sorry end pre_tilt /-- The tilt of a field, as defined in Perfectoid Spaces by Peter Scholze, as in [scholze2011perfectoid]. Given a field `K` with valuation `K → ℝ≥0` and ring of integers `O`, this is implemented as the fraction field of the perfection of `O/(p)`. -/ def tilt (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] := fraction_ring ↥(pre_tilt K v O hv p) namespace tilt protected instance field (K : Type u₁) [field K] (v : valuation K nnreal) (O : Type u₂) [comm_ring O] [algebra O K] (hv : valuation.integers v O) (p : ℕ) [hp : fact (nat.prime p)] [hvp : fact (coe_fn v ↑p ≠ 1)] : field (tilt K v O hv p) := fraction_ring.field end Mathlib
c97fc0e641ab3828f15fdb5e9a7df0b8f635bf5b
0851884047bb567d19e188e8f1ad959c5ae9c5ce
/src/Euclid/axioms.lean
0af862667e98b7ff09b37cf9762ba9aad7a1c235
[ "Apache-2.0" ]
permissive
yz5216/xena-UROP-2018
00d3f71a831324966d40d302544ed2cbbec3fd0f
5e9da9dc64dc51897677f8b73ab9f94061a8d977
refs/heads/master
1,584,922,436,989
1,531,487,250,000
1,531,487,250,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,415
lean
class Euclidean_plane (point : Type) := -- Equidistance of 4 Points (eqd : point → point → point → point → Prop) -- Between A B C means B is on the line segment AC (B : point → point → point → Prop) (eqd_refl : ∀ a b : point, eqd a b b a) (eqd_trans : ∀ a b p q r s, eqd a b p q → eqd a b r s → eqd p q r s) (id_eqd : ∀ a b c, eqd a b c c → a = b) (seg_cons : ∀ a b c q, ∃ x, B q a x → eqd a x b c) (five_seg : ∀ a b c d a' b' c' d', a ≠ b → B a b c → B a' b' c' → eqd a b a' b' → eqd b c b' c' → eqd a d a' d' → eqd b d b' d' → eqd c d c' d') (btw_same : ∀ a b, B a b a → a = b) (inner_pasch : ∀ a b c p q, B a p c → B b q c → ∃ x, B p x b → B q x a) (two_dimensions : ∃ a b c, ¬B a b c → ¬B b c a → ¬B c a b) (not_three_dimensions : ∀ a b c p₁ p₂, p₁ ≠ p₂ → eqd a p₁ a p₂ → eqd b p₁ b p₂ → eqd c p₁ c p₂ → (B a b c ∨ B b c a ∨ B c a b)) (euclids : ∀ a b c d t, B a d t → B b d c → a ≠ d → ∃ x y, B a b x → B a c y → B y t x) (cont : ∀ X Y : set point, (∃ a, ∀ x y, x ∈ X → y ∈ Y → B a x y) → (∃ b, ∀ x y, x ∈ X → y ∈ Y → B x b y)) (refl_btw : ∀ a b, B a b b) (btw_itself : ∀ a b, a = b → B a b a) (btw_symm : ∀ a b c , B a b c → B c b a) (in_trans : ∀ a b c d, B a b d → B b c d → B a b c) (out_trans : ∀ a b c d, B a b c → B b c d → b ≠ c → B a b d) (in_conn : ∀ a b c d, B a b d → B a c d → (B a b c ∨ B a c b)) (out_conn : ∀ a b c d, B a b c → B a b d → a ≠ b → (B a c d ∨ B a d c)) (eq_dist : ∀ a b c, a = b → eqd a c b c) (unique_tri : ∀ a b c d c' d' x, eqd a c a c' → eqd b c b c' → B a d b → B a d' b → B c d x → B c' d' x → d ≠ x → d' ≠ x → c = c') (existence_triangle : ∀ a b a' b' c' p, eqd a b a' b' → ∃ c x, eqd a c a' c' → eqd b c b' c' → B c x p → (B a b x ∨ B b x a ∨ B x a b)) (dens_btw : ∀ x z, x ≠ z → ∃ y, x ≠ y → z ≠ y → B x y z) (add_dist : ∀ x y z x' y' z', B x y z → B x' y' z' → eqd x y x' y' → eqd y z y' z' → eqd x z x' z') (sub_dist : ∀ x y z x' y' z', B x y z → B x' y' z' → eqd x z x' z' → eqd y z y' z' → eqd x y x' y') open Euclidean_plane variables {point : Type} [Euclidean_plane point] example (a b : point) : eqd a a b b := sub_dist a a b b b a (btw_symm b a a (refl_btw b a)) (btw_symm a b b (refl_btw a b)) (eqd_refl a b) (eqd_refl a b) theorem dist_reflex (a b : point) : eqd a b a b := eqd_trans b a a b a b (eqd_refl b a) (eqd_refl b a) theorem dist_symm (a b c d : point) : eqd a b c d → eqd c d a b := assume h : eqd a b c d, eqd_trans a b c d a b h (dist_reflex a b) theorem dist_trans (a b c d e f: point) : eqd a b c d → eqd c d e f → eqd a b e f := assume h h1, eqd_trans c d a b e f (dist_symm a b c d h) h1 -- a "setoid" is just a silly computer science name for a type with an equiv reln instance point_setoid : setoid (point × point) := { r := λ ⟨a,b⟩ ⟨c,d⟩, eqd a b c d, iseqv := ⟨λ ⟨a,b⟩,dist_reflex a b,λ ⟨a,b⟩ ⟨c,d⟩,dist_symm a b c d,λ ⟨a,b⟩ ⟨c,d⟩ ⟨e,f⟩,dist_trans a b c d e f⟩ } -- this type denotes the equiv classes. You may never need it but it's -- a good test to see if you've got the definitions right! definition distance_values (point : Type) [Euclidean_plane point] := quotient (@point_setoid point _)
eded654cea0bdca70ec678a1333a620e597bea0c
bb31430994044506fa42fd667e2d556327e18dfe
/src/set_theory/ordinal/natural_ops.lean
526bc5ea3d49ce01dcd65050a181a3bf13a470e8
[ "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
12,041
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import set_theory.ordinal.arithmetic /-! # Natural operations on ordinals The goal of this file is to define natural addition and multiplication on ordinals, also known as the Hessenberg sum and product, and provide a basic API. The natural addition of two ordinals `a ♯ b` is recursively defined as the least ordinal greater than `a' ♯ b` and `a ♯ b'` for `a' < a` and `b' < b`. The natural multiplication `a ⨳ b` is likewise recursively defined as the least ordinal such that `a ⨳ b ♯ a' ⨳ b'` is greater than `a' ⨳ b ♯ a ⨳ b'` for any `a' < a` and `b' < b`. These operations form a rich algebraic structure: they're commutative, associative, preserve order, have the usual `0` and `1` from ordinals, and distribute over one another. Moreover, these operations are the addition and multiplication of ordinals when viewed as combinatorial `game`s. This makes them particularly useful for game theory. Finally, both operations admit simple, intuitive descriptions in terms of the Cantor normal form. The natural addition of two ordinals corresponds to adding their Cantor normal forms as if they were polynomials in `ω`. Likewise, their natural multiplication corresponds to multiplying the Cantor normal forms as polynomials. # Implementation notes Given the rich algebraic structure of these two operations, we choose to create a type synonym `nat_ordinal`, where we provide the appropriate instances. However, to avoid casting back and forth between both types, we attempt to prove and state most results on `ordinal`. # Todo - Define natural multiplication and provide a basic API. - Prove the characterizations of natural addition and multiplication in terms of the Cantor normal form. -/ universes u v open function order noncomputable theory /-- A type synonym for ordinals with natural addition and multiplication. -/ @[derive [has_zero, inhabited, has_one, linear_order, succ_order, has_well_founded]] def nat_ordinal : Type* := ordinal /-- The identity function between `ordinal` and `nat_ordinal`. -/ @[pattern] def ordinal.to_nat_ordinal : ordinal ≃o nat_ordinal := order_iso.refl _ /-- The identity function between `nat_ordinal` and `ordinal`. -/ @[pattern] def nat_ordinal.to_ordinal : nat_ordinal ≃o ordinal := order_iso.refl _ open ordinal namespace nat_ordinal variables {a b c : nat_ordinal.{u}} @[simp] theorem to_ordinal_symm_eq : nat_ordinal.to_ordinal.symm = ordinal.to_nat_ordinal := rfl @[simp] theorem to_ordinal_to_nat_ordinal (a : nat_ordinal) : a.to_ordinal.to_nat_ordinal = a := rfl theorem lt_wf : @well_founded nat_ordinal (<) := ordinal.lt_wf instance : well_founded_lt nat_ordinal := ordinal.well_founded_lt instance : is_well_order nat_ordinal (<) := ordinal.has_lt.lt.is_well_order @[simp] theorem to_ordinal_zero : to_ordinal 0 = 0 := rfl @[simp] theorem to_ordinal_one : to_ordinal 1 = 1 := rfl @[simp] theorem to_ordinal_eq_zero (a) : to_ordinal a = 0 ↔ a = 0 := iff.rfl @[simp] theorem to_ordinal_eq_one (a) : to_ordinal a = 1 ↔ a = 1 := iff.rfl @[simp] theorem to_ordinal_max : (max a b).to_ordinal = max a.to_ordinal b.to_ordinal := rfl @[simp] theorem to_ordinal_min : (min a b).to_ordinal = min a.to_ordinal b.to_ordinal := rfl theorem succ_def (a : nat_ordinal) : succ a = (a.to_ordinal + 1).to_nat_ordinal := rfl /-- A recursor for `nat_ordinal`. Use as `induction x using nat_ordinal.rec`. -/ protected def rec {β : nat_ordinal → Sort*} (h : Π a, β (to_nat_ordinal a)) : Π a, β a := λ a, h a.to_ordinal /-- `ordinal.induction` but for `nat_ordinal`. -/ theorem induction {p : nat_ordinal → Prop} : ∀ i (h : ∀ j, (∀ k, k < j → p k) → p j), p i := ordinal.induction end nat_ordinal namespace ordinal variables {a b c : ordinal.{u}} @[simp] theorem to_nat_ordinal_symm_eq : to_nat_ordinal.symm = nat_ordinal.to_ordinal := rfl @[simp] theorem to_nat_ordinal_to_ordinal (a : ordinal) : a.to_nat_ordinal.to_ordinal = a := rfl @[simp] theorem to_nat_ordinal_zero : to_nat_ordinal 0 = 0 := rfl @[simp] theorem to_nat_ordinal_one : to_nat_ordinal 1 = 1 := rfl @[simp] theorem to_nat_ordinal_eq_zero (a) : to_nat_ordinal a = 0 ↔ a = 0 := iff.rfl @[simp] theorem to_nat_ordinal_eq_one (a) : to_nat_ordinal a = 1 ↔ a = 1 := iff.rfl @[simp] theorem to_nat_ordinal_max : to_nat_ordinal (max a b) = max a.to_nat_ordinal b.to_nat_ordinal := rfl @[simp] theorem to_nat_ordinal_min : (linear_order.min a b).to_nat_ordinal = linear_order.min a.to_nat_ordinal b.to_nat_ordinal := rfl /-- Natural addition on ordinals `a ♯ b`, also known as the Hessenberg sum, is recursively defined as the least ordinal greater than `a' ♯ b` and `a ♯ b'` for all `a' < a` and `b' < b`. In contrast to normal ordinal addition, it is commutative. Natural addition can equivalently be characterized as the ordinal resulting from adding up corresponding coefficients in the Cantor normal forms of `a` and `b`. -/ noncomputable def nadd : ordinal → ordinal → ordinal | a b := max (blsub.{u u} a $ λ a' h, nadd a' b) (blsub.{u u} b $ λ b' h, nadd a b') using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } localized "infix (name := ordinal.nadd) ` ♯ `:65 := ordinal.nadd" in natural_ops theorem nadd_def (a b : ordinal) : a ♯ b = max (blsub.{u u} a $ λ a' h, a' ♯ b) (blsub.{u u} b $ λ b' h, a ♯ b') := by rw nadd theorem lt_nadd_iff : a < b ♯ c ↔ (∃ b' < b, a ≤ b' ♯ c) ∨ ∃ c' < c, a ≤ b ♯ c' := by { rw nadd_def, simp [lt_blsub_iff] } theorem nadd_le_iff : b ♯ c ≤ a ↔ (∀ b' < b, b' ♯ c < a) ∧ ∀ c' < c, b ♯ c' < a := by { rw nadd_def, simp [blsub_le_iff] } theorem nadd_lt_nadd_left (h : b < c) (a) : a ♯ b < a ♯ c := lt_nadd_iff.2 (or.inr ⟨b, h, le_rfl⟩) theorem nadd_lt_nadd_right (h : b < c) (a) : b ♯ a < c ♯ a := lt_nadd_iff.2 (or.inl ⟨b, h, le_rfl⟩) theorem nadd_le_nadd_left (h : b ≤ c) (a) : a ♯ b ≤ a ♯ c := begin rcases lt_or_eq_of_le h with h | rfl, { exact (nadd_lt_nadd_left h a).le }, { exact le_rfl } end theorem nadd_le_nadd_right (h : b ≤ c) (a) : b ♯ a ≤ c ♯ a := begin rcases lt_or_eq_of_le h with h | rfl, { exact (nadd_lt_nadd_right h a).le }, { exact le_rfl } end variables (a b) theorem nadd_comm : ∀ a b, a ♯ b = b ♯ a | a b := begin rw [nadd_def, nadd_def, max_comm], congr; ext c hc; apply nadd_comm end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } theorem blsub_nadd_of_mono {f : Π c < a ♯ b, ordinal.{max u v}} (hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : blsub _ f = max (blsub.{u v} a (λ a' ha', f (a' ♯ b) $ nadd_lt_nadd_right ha' b)) (blsub.{u v} b (λ b' hb', f (a ♯ b') $ nadd_lt_nadd_left hb' a)) := begin apply (blsub_le_iff.2 (λ i h, _)).antisymm (max_le _ _), { rcases lt_nadd_iff.1 h with ⟨a', ha', hi⟩ | ⟨b', hb', hi⟩, { exact lt_max_of_lt_left ((hf h (nadd_lt_nadd_right ha' b) hi).trans_lt (lt_blsub _ _ _)) }, { exact lt_max_of_lt_right ((hf h (nadd_lt_nadd_left hb' a) hi).trans_lt (lt_blsub _ _ _)) } }, all_goals { apply blsub_le_of_brange_subset.{u u v}, rintro c ⟨d, hd, rfl⟩, apply mem_brange_self } end theorem nadd_assoc : ∀ a b c, a ♯ b ♯ c = a ♯ (b ♯ c) | a b c := begin rw [nadd_def a (b ♯ c), nadd_def, blsub_nadd_of_mono, blsub_nadd_of_mono, max_assoc], { congr; ext d hd; apply nadd_assoc }, { exact λ i j _ _ h, nadd_le_nadd_left h a }, { exact λ i j _ _ h, nadd_le_nadd_right h c } end using_well_founded { dec_tac := `[solve_by_elim [psigma.lex.left, psigma.lex.right]] } @[simp] theorem nadd_zero : a ♯ 0 = a := begin induction a using ordinal.induction with a IH, rw [nadd_def, blsub_zero, max_zero_right], convert blsub_id a, ext b hb, exact IH _ hb end @[simp] theorem zero_nadd : 0 ♯ a = a := by rw [nadd_comm, nadd_zero] @[simp] theorem nadd_one : a ♯ 1 = succ a := begin induction a using ordinal.induction with a IH, rw [nadd_def, blsub_one, nadd_zero, max_eq_right_iff, blsub_le_iff], intros i hi, rwa [IH i hi, succ_lt_succ_iff] end @[simp] theorem one_nadd : 1 ♯ a = succ a := by rw [nadd_comm, nadd_one] theorem nadd_succ : a ♯ succ b = succ (a ♯ b) := by rw [←nadd_one (a ♯ b), nadd_assoc, nadd_one] theorem succ_nadd : succ a ♯ b = succ (a ♯ b) := by rw [←one_nadd (a ♯ b), ←nadd_assoc, one_nadd] @[simp] theorem nadd_nat (n : ℕ) : a ♯ n = a + n := begin induction n with n hn, { simp }, { rw [nat.cast_succ, add_one_eq_succ, nadd_succ, add_succ, hn] } end @[simp] theorem nat_nadd (n : ℕ) : ↑n ♯ a = a + n := by rw [nadd_comm, nadd_nat] theorem add_le_nadd : a + b ≤ a ♯ b := begin apply b.limit_rec_on, { simp }, { intros c h, rwa [add_succ, nadd_succ, succ_le_succ_iff] }, { intros c hc H, rw [←is_normal.blsub_eq.{u u} (add_is_normal a) hc, blsub_le_iff], exact λ i hi, (H i hi).trans_lt (nadd_lt_nadd_left hi a) } end end ordinal open ordinal namespace nat_ordinal instance : has_add nat_ordinal := ⟨nadd⟩ instance add_covariant_class_lt : covariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (<) := ⟨λ a b c h, nadd_lt_nadd_left h a⟩ instance add_covariant_class_le : covariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (≤) := ⟨λ a b c h, nadd_le_nadd_left h a⟩ instance add_contravariant_class_le : contravariant_class nat_ordinal.{u} nat_ordinal.{u} (+) (≤) := ⟨λ a b c h, by { by_contra' h', exact h.not_lt (add_lt_add_left h' a) }⟩ instance : ordered_cancel_add_comm_monoid nat_ordinal := { add := (+), add_assoc := nadd_assoc, add_le_add_left := λ a b, add_le_add_left, le_of_add_le_add_left := λ a b c, le_of_add_le_add_left, zero := 0, zero_add := zero_nadd, add_zero := nadd_zero, add_comm := nadd_comm, ..nat_ordinal.linear_order } instance : add_monoid_with_one nat_ordinal := add_monoid_with_one.unary @[simp] theorem add_one_eq_succ : ∀ a : nat_ordinal, a + 1 = succ a := nadd_one @[simp] theorem to_ordinal_cast_nat (n : ℕ) : to_ordinal n = n := begin induction n with n hn, { refl }, { change nadd (to_ordinal n) 1 = n + 1, rw hn, apply nadd_one } end end nat_ordinal open nat_ordinal open_locale natural_ops namespace ordinal @[simp] theorem to_nat_ordinal_cast_nat (n : ℕ) : to_nat_ordinal n = n := by { rw ←to_ordinal_cast_nat n, refl } theorem lt_of_nadd_lt_nadd_left : ∀ {a b c}, a ♯ b < a ♯ c → b < c := @lt_of_add_lt_add_left nat_ordinal _ _ _ theorem lt_of_nadd_lt_nadd_right : ∀ {a b c}, b ♯ a < c ♯ a → b < c := @_root_.lt_of_add_lt_add_right nat_ordinal _ _ _ theorem le_of_nadd_le_nadd_left : ∀ {a b c}, a ♯ b ≤ a ♯ c → b ≤ c := @le_of_add_le_add_left nat_ordinal _ _ _ theorem le_of_nadd_le_nadd_right : ∀ {a b c}, b ♯ a ≤ c ♯ a → b ≤ c := @le_of_add_le_add_right nat_ordinal _ _ _ theorem nadd_lt_nadd_iff_left : ∀ a {b c}, a ♯ b < a ♯ c ↔ b < c := @add_lt_add_iff_left nat_ordinal _ _ _ _ theorem nadd_lt_nadd_iff_right : ∀ a {b c}, b ♯ a < c ♯ a ↔ b < c := @add_lt_add_iff_right nat_ordinal _ _ _ _ theorem nadd_le_nadd_iff_left : ∀ a {b c}, a ♯ b ≤ a ♯ c ↔ b ≤ c := @add_le_add_iff_left nat_ordinal _ _ _ _ theorem nadd_le_nadd_iff_right : ∀ a {b c}, b ♯ a ≤ c ♯ a ↔ b ≤ c := @_root_.add_le_add_iff_right nat_ordinal _ _ _ _ theorem nadd_left_cancel : ∀ {a b c}, a ♯ b = a ♯ c → b = c := @_root_.add_left_cancel nat_ordinal _ _ theorem nadd_right_cancel : ∀ {a b c}, a ♯ b = c ♯ b → a = c := @_root_.add_right_cancel nat_ordinal _ _ theorem nadd_left_cancel_iff : ∀ {a b c}, a ♯ b = a ♯ c ↔ b = c := @add_left_cancel_iff nat_ordinal _ _ theorem nadd_right_cancel_iff : ∀ {a b c}, b ♯ a = c ♯ a ↔ b = c := @add_right_cancel_iff nat_ordinal _ _ end ordinal
fcd7ee8d87b3e89e61f24e870b0750d2ae1eb472
40ad357bbd0d327dd1e3e7f7beb868bd4e5b0a9d
/src/temporal_logic/scheduling.lean
e8cf088bb93919bdaadba03bafaf099a3ed5a530
[]
no_license
unitb/temporal-logic
9966424f015976d5997a9ffa30cbd77cc3a9cb1c
accec04d1b09ca841be065511c9e206b725b16e9
refs/heads/master
1,633,868,382,769
1,541,072,223,000
1,541,072,223,000
114,790,987
5
3
null
null
null
null
UTF-8
Lean
false
false
19,351
lean
import .lemmas import .spec import data.set.basic import util.data.minimum import util.data.ordering import util.data.order import util.function import util.logic import tactic.norm_num open temporal function predicate nat set local infix ` ≃ `:75 := v_eq local prefix `♯ `:0 := cast (by simp) universes u v namespace temporal namespace scheduling section scheduling local attribute [instance, priority 0] classical.prop_decidable local attribute [-simp] add_comm parameter {evt : Type u} parameter Γ : cpred parameter r : tvar (set evt) parameter Hr : Γ ⊢ ◻-(r ≃ (∅ : set evt)) -- parameter [nonempty evt] abbreviation SCHED (s : tvar evt) := ◻(s ∊ r) ⋀ ∀∀ (e : evt), ◻◇(↑e ∊ r) ⟶ ◻◇(s ≃ ↑e ⋀ ↑e ∊ r) section implementation parameters (f : ℕ → evt) (Hinj : surjective f) parameter p : tvar (ℕ → evt) parameter cur : tvar ℕ /- consider making select into a state variable instead of a definition -/ variable select : tvar evt infixl ` |+| `:80 := lifted₂ has_add.add infixl ` |-| `:80 := lifted₂ has_sub.sub noncomputable def next_p (p : ℕ → evt) (r' : set evt) (i : ℕ) : ordering → evt | ordering.gt := p i | ordering.eq := p (↓ i : ℕ, p i ∈ r') | ordering.lt := if (↓ i : ℕ, p i ∈ r') ≤ i then p (i + 1) else p i noncomputable def next' (r' : set evt) : ℕ × (ℕ → evt) → ℕ × (ℕ → evt) | (cur,p) := let min := ↓ i : ℕ, p i ∈ r', cur' := max min $ cur+1, p' : ℕ → evt := λ i : ℕ, next_p p r' i (cmp i cur') in (cur',p') section noncomputable def next : tvar $ ℕ × (ℕ → evt) → ℕ × (ℕ → evt) := ⟪ ℕ, next' ⟫ (⊙r) end @[simp] lemma next_def (cur cur' : ℕ) (p p' : ℕ → evt) (σ : ℕ) : (cur', p') = (σ ⊨ next) (cur, p) ↔ cur' = max (↓ (i : ℕ), p i ∈ succ σ ⊨ r) (cur + 1) ∧ ∀ i, p' i = next_p p (succ σ ⊨ r) i (cmp i cur') := by { repeat { simp [next,next'] <|> unfold_coes }, apply and_congr_right, intro, split, { introv h, subst cur', simp [h], }, { intro, apply funext, intro, subst cur', solve_by_elim } } section parameter f @[predicate] noncomputable def cur₀ : tvar ℕ := [| r , ↓ i : ℕ, f i ∈ r |] -- noncomputable abbreviation select₀ : tvar evt := -- [| r , f (↓ i : ℕ, f i ∈ r) |] -- noncomputable def nxt_select : tvar (evt → evt) := -- [| p , λ (p' : ℕ → ℕ) (r' : set evt) (e : evt), -- inv q $ ↓ i : ℕ, inv q i ∈ r' |] (⊙q) (⊙r) end noncomputable def Spec := ⦃cur,p⦄ ≃ ⦃cur₀,f⦄ ⋀ ◻(⊙⦃cur,p⦄ ≃ next ⦃cur,p⦄) parameter Hq : Γ ⊢ Spec @[predicate] def select : tvar evt := p cur -- noncomputable def select_Spec := -- select ≃ select₀ ⋀ ◻(⊙select ≃ nxt_select select) -- variables Hs : Γ ⊢ select_Spec select section q_injective lemma next_rec (P : ℕ → Prop) (cur cur') (p p' : ℕ → evt) (r' : set evt) {i : ℕ} {e : evt} (h : p i = e) (Hcur' : cur' = max (↓ (i : ℕ), p i ∈ r') (cur + 1)) (Hq' : ∀ (i : ℕ), p' i = next_p p r' i (cmp i cur')) (Hcase_lt : (i < ↓ (i : ℕ), p i ∈ r') ∨ (↓ (i : ℕ), p i ∈ r') < i ∧ ¬i ≤ cur' → next_p p r' i (cmp i cur') = e → P i) (Hcase_eq : (i = ↓ (i : ℕ), p i ∈ r') → next_p p r' cur' (cmp cur' cur') = e → P cur') (Hcase_gt : (↓ (i : ℕ), p i ∈ r') < i → next_p p r' (i - 1) (cmp (i - 1) cur') = e → P (i - 1)) : (∃ j, p' j = e ∧ P j) := begin ordering_cases cmp i (↓ i, p i ∈ r'), { existsi i, rw Hq', suffices : cmp i cur' = ordering.lt, { rw [this,next_p,if_neg,h] at *, { existsi [rfl], apply_assumption, left, solve_by_elim, refl, }, all_goals { apply not_le_of_gt h_1 }, }, rw [cmp,cmp_using_eq_lt,Hcur'], apply lt_max_of_lt_left _ h_1, }, { existsi cur', rw Hq', have : cmp cur' cur' = ordering.eq, { rw [cmp_eq_eq], }, rw and_iff_imp, intro, solve_by_elim, rw [this,next_p], cc }, by_cases h_cur : i ≤ cur', { existsi i - 1, rw Hq', have h_i_gt_0 : 0 < i, { apply lt_of_le_of_lt, apply nat.zero_le, assumption, }, have : cmp (i - 1) cur' = ordering.lt, { rw [cmp,cmp_using_eq_lt], apply lt_of_lt_of_le _ h_cur, show i - 1 < i, { apply nat.sub_lt, assumption, norm_num }, }, rw and_iff_imp, intro, solve_by_elim, rw [this,next_p,if_pos,nat.sub_add_cancel,h], assumption, rw ← add_le_to_le_sub, repeat { assumption }, }, { existsi i, rw Hq', have : cmp i cur' = ordering.gt, { rw [cmp,cmp_using_eq_gt], apply lt_of_not_ge h_cur }, rw and_iff_imp, intro, apply_assumption, right, tauto, solve_by_elim, rw [this,next_p,h] at *, } end include Hq Hinj /- TODO: split into lemmas -/ lemma q_injective : Γ ⊢ ◻(⟨ surjective ⟩ ! p) := begin [temporal] cases Hq with Hq Hq', t_induction!, { explicit' with Hq { cases_matching* _ ∧ _, subst p, solve_by_elim, } }, { henceforth at Hq', explicit' with ih Hq' { simp_intros e, cases ih e with i h, cases Hq' with Hcur' Hq', ordering_cases cmp i (↓ i, p i ∈ r'), { existsi i, rw Hq', suffices : cmp i cur' = ordering.lt, { rw [this,next_p,if_neg,h], apply not_le_of_gt h_1, }, rw [cmp,cmp_using_eq_lt,Hcur'], apply lt_max_of_lt_left _ h_1, }, { existsi cur', rw Hq', have : cmp cur' cur' = ordering.eq, { rw [cmp_eq_eq], }, rw [this,next_p], cc }, by_cases h_cur : i ≤ cur', { existsi i - 1, rw Hq', have h_i_gt_0 : 0 < i, { apply lt_of_le_of_lt, apply nat.zero_le, assumption, }, have : cmp (i - 1) cur' = ordering.lt, { rw [cmp,cmp_using_eq_lt], apply lt_of_lt_of_le _ h_cur, show i - 1 < i, { apply nat.sub_lt, assumption, norm_num }, }, rw [this,next_p,if_pos,nat.sub_add_cancel,h], assumption, rw ← add_le_to_le_sub, repeat { assumption }, }, { existsi i, rw Hq', have : cmp i cur' = ordering.gt, { rw [cmp,cmp_using_eq_gt], apply lt_of_not_ge h_cur }, rw [this,next_p,h], } } }, end end q_injective section -- include Hq -- lemma select_eq_inv_q_cur' -- : Γ ⊢ select_Spec select' := -- begin [temporal] -- cases Hq with Hq₀ Hq, -- split, -- explicit' { cc }, -- henceforth! at ⊢ Hq, -- explicit' [nxt_select] -- { cases Hq with Hcur Hq, -- rw [inv_eq _ _ _], -- rw [Hq,← Hcur], -- ordering_cases cmp (↓ (i : ℕ), inv q i ∈ r') (q (inv q (↓ (i : ℕ), inv q i ∈ r'))) -- ; simp [next_p], -- ite_cases, -- { exfalso, apply h_1, clear h_1, -- rw Hcur, rw le_max_iff_le_or_le, left, -- } } -- { verbose := tt } -- end -- include Hs Hinj -- lemma select_eq_inv_q_cur -- : Γ ⊢ ◻[| q cur select, select = inv q cur |] := -- begin [temporal] -- have Hinj_q := temporal.scheduling.q_injective, -- have Hinj_q' := henceforth_next _ _ Hinj_q, -- cases Hq with Hq₀ Hq, -- cases Hs with Hs₀ Hs, -- t_induction! using Hq Hs Hinj_q' Hinj_q, -- explicit' { cc }, -- explicit' [nxt_select] -- { cases Hq, -- rw inv_eq _ _ Hinj_q', -- rw [Hq_right], -- ordering_cases (cmp (↓ (i : ℕ), inv q i ∈ r') (q select')) -- ; simp [next_p], -- ite_cases, -- { exfalso, apply h_1, clear h_1, -- rw le_max_iff_le_or_le, left, -- apply le_of_eq, clear_except Hs, }, -- { }, -- { }, -- { } } -- end -- end open set -- invariant -- inv q' cur' = (↓ i, inv q' i ∈ r) -- inv q' cur' ≤ (↓ i, inv q' i ∈ r) -- inv q' cur' ≥ (↓ i, inv q' i ∈ r) section include Hr Hq Hinj lemma valid_indices_ne_empty : Γ ⊢ ◻([| p, λ r : set evt, { i : ℕ | p i ∈ r } ≠ ∅ |] (⊙r)) := begin [temporal] have Hsur := temporal.scheduling.q_injective, replace Hr := henceforth_next _ _ Hr, henceforth! at Hr Hsur ⊢, explicit' with Hr Hsur { rw not_eq_empty_iff_exists at *, cases Hr with i Hr, existsi inv p i, change _ ∈ r', rw [inv_is_right_inverse_of_surjective Hsur], assumption, } end end noncomputable def rank (e : evt) : tvar ℕ := [| p, ↓ i, p i = e |] include Hr Hq Hinj lemma sched_inv : Γ ⊢ ◻(select ∊ r) := begin [temporal] have Hq_inj := temporal.scheduling.q_injective, have hJ := temporal.scheduling.valid_indices_ne_empty, cases Hq with Hq₀ Hq, have Hq_inj' := henceforth_next _ _ Hq_inj, t_induction!, henceforth! at Hr Hq_inj, { explicit' [select,cur₀] with Hq₀ Hr Hq_inj { change cur ∈ { i | p i ∈ r }, rw [Hq₀.left,Hq₀.right], apply minimum_mem, intro, apply Hr, rw eq_empty_iff_forall_not_mem at *, intro x, specialize a (inv p x), -- apply Hr, intro, apply a, show f (inv p x) ∈ r, cases Hq₀, subst p, rw [inv_is_right_inverse_of_surjective Hq_inj], assumption } }, henceforth! at Hr Hq_inj' Hq_inj Hq hJ, explicit' with Hq hJ { cases Hq with Hq Hq', rw Hq', have : cmp cur' cur' = ordering.eq, { rw cmp_eq_eq }, rw [this,next_p], change (↓ (i : ℕ), p i ∈ r') ∈ { i | p i ∈ r' }, apply minimum_mem, assumption }, end lemma cur_lt_cur' : Γ ⊢ ◻(cur ≺ ⊙cur) := begin [temporal] cases Hq with Hq₀ Hq, henceforth! at Hq ⊢, explicit' with Hq { simp [Hq], apply lt_max_of_lt_right, apply lt_add_one, } end section sched_queue_safety variables (q₀ : ℕ) (e : evt) (Hprev : Γ ⊢ rank e |+| (rank e |-| cur) ≃ ↑q₀) (H₂ : Γ ⊢ ⊙(-(⟨λ (i : ℕ), (i ⊨ rank e) + ((i ⊨ rank e) - (i ⊨ cur))⟩ ≺≺ q₀) ⋀ -(select ≃ e))) (Hdec : Γ ⊢ cur ≺ ⊙cur) (Hsurj : Γ ⊢ ⊙( ⟨ surjective ⟩ ! p )) (this : Γ ⊢ ⊙rank e ≼ rank e ⋁ ⊙(cur ≃ rank e)) omit Hq include Hdec Hprev Hsurj H₂ this lemma non_dec_po : Γ ⊢ ⊙(rank e |+| (rank e |-| cur) ≃ ↑q₀) := begin [temporal] explicit' [next,next',select,rank] with Hprev this H₂ Hdec Hsurj { subst q₀, cases this with this this, cases lt_or_eq_of_le this, { exfalso, apply H₂.left, change _ + _ < _ + _, apply lt_of_lt_of_le, { apply add_lt_add_right h, }, apply add_le_add_left, transitivity, { apply nat.sub_le_sub_left, apply le_of_lt Hdec, }, { apply nat.sub_le_sub_right this, } }, { simp [h], let rank := (↓ (i : ℕ), p i = e), have : rank - cur' ≤ rank - cur, { apply nat.sub_le_sub_left, apply le_of_lt Hdec }, cases lt_or_eq_of_le this, { exfalso, apply H₂.left, change _ + _ < _ + _, simp [h,h_1], }, assumption }, replace H₂ := H₂.right, rw this at H₂, have H₀ : { i : ℕ | p' i = e } ≠ ∅, { apply ne_empty_of_mem _, exact (inv p' e), change p' (inv p' e) = e, apply inv_is_right_inverse_of_surjective Hsurj, }, have H₃ := minimum_mem H₀, cases H₂ H₃, }, end end sched_queue_safety lemma subsumes_requested (e : evt) : Γ ⊢ ◻( select ≃ ↑e ⋀ ↑e ∊ r ≡ select ≃ ↑e ) := begin [temporal] have Hr' := temporal.scheduling.sched_inv, henceforth! at ⊢ Hr', explicit' [select] with Hr' { split, { simp, intros, assumption }, { intros, cc, } }, end -- include Hinj /-- TODO: Pull out lemmas -/ lemma sched_queue_safety (q₀ : ℕ) (e : evt) : Γ ⊢ ◻(rank e |+| (rank e |-| cur) ≃ ↑q₀ ⟶ ◻(rank e |+| (rank e |-| cur) ≃ ↑q₀) ⋁ ◇(rank e |+| (rank e |-| cur) ≺≺ ↑q₀ ⋁ select ≃ ↑e)) := begin [temporal] have hJ := temporal.scheduling.q_injective, have Hinc := temporal.scheduling.cur_lt_cur', have p_not_empty := temporal.scheduling.valid_indices_ne_empty, have p'_not_empty := henceforth_next _ _ p_not_empty, cases Hq with Hq Hq', henceforth!, intro H, rw [p_or_comm,← p_not_p_imp], intros H₁, simp [p_not_p_or,p_not_p_and] at H₁, t_induction, { assumption }, { henceforth!, intro Hprev, have H₂ := henceforth_next _ _ H₁, have hJ' := henceforth_next _ _ hJ, henceforth at Hinc Hq' H₁ H₂ hJ hJ' p_not_empty p'_not_empty, apply temporal.scheduling.non_dec_po _ _ Hprev H₂ Hinc hJ', explicit' [next,next',select,rank] with Hq' hJ hJ' H₂ { cases Hq' with Hcur Hq, replace Hq := congr_fun Hq, simp only at Hq, rw [or_comm,or_iff_not_imp], intro Hncur, have p_not_empty : { i : ℕ | p i = e } ≠ ∅, { rw ne_empty_iff_exists_mem, apply hJ e, }, have p'_not_empty : { i : ℕ | p' i = e } ≠ ∅, { rw ne_empty_iff_exists_mem, apply hJ' e, }, apply (le_minimum_iff_forall_le p_not_empty (↓ (i : ℕ), p' i = e)).2, assume j (Hj : p j = e), apply (minimum_le_iff_exists_le p'_not_empty j).2, rw ← Hcur at Hq, apply next_rec _ cur cur' p p' r' Hj Hcur Hq, { intros, refl }, { intros h h', rw ← Hq at h', cases H₂.right h', }, { intros, apply nat.sub_le, } }, }, end /- TODO: split into lemmas -/ lemma sched_queue_liveness (q₀ : ℕ) (e : evt) : Γ ⊢ ⊙(↑e ∊ r) ⋀ rank e |+| (rank e |-| cur) ≃ ↑q₀ ~> rank e |+| (rank e |-| cur) ≺≺ ↑q₀ ⋁ select ≃ ↑e ⋀ ↑e ∊ r := begin [temporal] { have Hq_inj := temporal.scheduling.q_injective, have Hinc := temporal.scheduling.cur_lt_cur', cases Hq with Hq₀ Hq, henceforth! at ⊢ Hq Hq_inj Hinc, have Hq_inj' : ⊙(⟨surjective⟩ ! p) := holds_next _ _ Hq_inj, simp, intros hreq hq₀, apply next_entails_eventually, explicit' [select,next,next',rank] with Hq hreq hq₀ Hinc Hq_inj { cases Hq with Hq Hq' Hq_inj, replace Hq' := congr_fun Hq', simp at Hq', rw ← Hq at Hq', let rank := ↓ i, p i = e, have Hrank : p rank = e := _, let P := λ k, k + (k - cur') < q₀ ∨ k = cur', have rec := temporal.scheduling.next_rec P cur cur' p p' r' Hrank Hq Hq' _ _ _, { cases rec with k Hk, cases Hk with Hpk Hk, cases Hk with Hk Hk, { left, change _ + _ < _, apply @lt_of_le_of_lt _ _ _ (k + (k - cur')), have h : (↓ (i : ℕ), p' i = e) ≤ k, apply minimum_le, exact Hpk, apply add_le_add, assumption, apply nat.sub_le_sub_right, assumption, assumption, }, { right, cc }, }, { simp [P,rank], intros h₀ h₁, rw ← Hq' (↓ (i : ℕ), p i = e) at h₁, clear P, cases h₀, { right, clear hq₀ Hq', have : cur + 1 ≤ (↓ (i : ℕ), p i ∈ r'), admit, rw max_eq_left this at Hq, clear this, admit }, { left, rw ← hq₀, have : ((↓ (i : ℕ), p i = e) ≥ cur'), { apply le_of_lt h₀.right }, monotonicity Hinc }, }, { intros, rw ← Hq' at a_1, right, refl, }, { intros, rw ← Hq' at a_1, left, rw ← hq₀, apply lt_of_lt_of_le, apply add_lt_add_right, apply nat.sub_lt, apply lt_of_le_of_lt (nat.zero_le _) a, norm_num, apply nat.sub_le_sub, apply nat.sub_le, apply le_of_lt Hinc, }, { have h : { i | p i = e } ≠ ∅, { rw ne_empty_iff_exists_mem, apply Hq_inj, }, apply minimum_mem h, } } }, end lemma sched_fairness (e : evt) : Γ ⊢ ◻◇(↑e ∊ r) ⟶ ◻◇(select ≃ ↑e ⋀ ↑e ∊ r) := begin [temporal] suffices : ◻◇⊙(↑e ∊ r) ⟶ ◻◇(temporal.scheduling.select ≃ ↑e ⋀ ↑e ∊ r), { intro h, apply this, rw [← next_eventually_comm], apply henceforth_next _ _ h, }, apply inf_often_induction' (temporal.scheduling.rank e |+| (temporal.scheduling.rank e |-| cur)) ; intro q₀, { rw temporal.scheduling.subsumes_requested e, apply temporal.scheduling.sched_queue_safety q₀ e, }, { apply temporal.scheduling.sched_queue_liveness } end def correct_sched : Γ ⊢ SCHED select := begin [temporal] split, { apply temporal.scheduling.sched_inv, }, { intro, apply temporal.scheduling.sched_fairness }, end end end implementation -- class schedulable (α : Sort u) := -- (f : α → ℕ) -- (inj : injective f) open encodable example (w σ₀ : tvar ℕ) : ⇑(to_fun_var (λ (w : tvar ℕ), w ≃ σ₀)) w = w ≃ σ₀ := begin -- rw [v_eq,to_fun_var_lift₂], -- dsimp, -- dsimp, -- unfold_coes, -- dsimp with lifted_fn, -- unfold_coes, simp! only with lifted_fn predicate, end lemma scheduler [encodable evt] (Hr : Γ ⊢ ◻-(r ≃ (∅ : set evt))) : Γ ⊢ (∃∃ s, SCHED s) := begin [temporal] let f' : (evt → ℕ) := @encode evt _, let f : tvar (evt → ℕ) := f', have Hnemp : ∃∃ x : evt, True, { admit }, nonempty evt, let g' : (ℕ → evt) := inv (@encode evt _), let g : tvar (ℕ → evt) := g', let σ₀ := ⦃cur₀ r g',g⦄, select_witness w : w ≃ σ₀ ⋀ ◻(⊙w ≃ temporal.scheduling.next w), have := fwd_witness σ₀ (next r) Γ, cases this with cur Hcur, cases cur with cur q, existsi select p cur, note Hsur : surjective (inv f'), { apply surjective_of_has_right_inverse, existsi f', apply inv_is_left_inverse_of_injective, apply schedulable.inj }, type_check @temporal.scheduling.correct_sched, apply temporal.scheduling.correct_sched (inv f') Hsur _, simp [Spec,σ₀] at ⊢ Hcur, exact Hcur, end end scheduling section spec variables Γ : cpred variables {α : Type v} (m : mch α) local notation `evt` := m.evt variable [encodable evt] local notation `cs` := m.cs local notation `fs` := m.fs local notation `p` := m.init local notation `A` := m.A lemma sch_intro (v : tvar α) : Γ ⊢ m.spec v ⟶ (∃∃ sch, m.spec_sch v sch) := begin [temporal] intro h, let r : tvar (set (option evt)) := ⟪ ℕ, λ s s', { e | m.effect e s s' } ⟫ v ⊙v, have hr : ◻-(r ≃ (∅ : set (option evt))), { simp [mch.spec] at h, casesm* _ ⋀ _, select Hact : ◻(p_exists _), henceforth! at Hact ⊢, explicit' [r] with Hact { erw [← not_eq_empty_iff_exists] at Hact, exact Hact }, }, have h' := temporal.scheduling.scheduler Γ r hr, cases h' with sch h', existsi sch, simp at ⊢ h, casesm* _ ⋀ _, split!* ; try { solve_by_elim }, { select h' : ◻(p_exists _), select hJ : ◻(_ ∊ _), henceforth! at hJ h' ⊢, existsi sch with hh, { explicit' [r] with hh hJ h' { subst sch, tauto } } }, { introv, intros h₀ h₁, rename a_3 h₂, replace h₂ := h₂ x h₀ h₁, replace a_1 := a_1 x, persistent, have H₀ : ↑x ∊ r ≡ cs x ! v ⋀ fs x ! v ⋀ ⟦ v | A x ⟧, { explicit' [r] { simp [mch.effect,and_assoc] }, }, have H₁ : sch ≃ ↑x ⋀ ↑x ∊ r ≡ cs x ! v ⋀ fs x ! v ⋀ (sch ≃ ↑x ⋀ ⟦ v | A x ⟧), { explicit' [r,mch.effect,and_assoc] { apply eq.to_iff, ac_refl }, }, rw [H₁,H₀] at a_1, solve_by_elim, } end end spec end scheduling export scheduling (schedulable sch_intro) end temporal
341d94c18c1cc016a9b675d795c0c12abd60a4f4
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_ematch5.lean
5a8e8c45bc3cc608b1f2e8bc9884a5978c47fcc6
[ "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
248
lean
constant subt : nat → nat → Prop lemma subt_trans [forward] {a b c : nat} : subt a b → subt b c → subt a c := sorry set_option blast.strategy "ematch" example (a b c d : nat) : subt a b → subt b c → subt c d → subt a d := by blast
bec4ac5fea3824ccc2611e9da7d442116d85237a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/calculus/iterated_deriv.lean
57637f6b3ffd904beb184e0d756398636eab0aff
[ "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
14,346
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.deriv import analysis.calculus.cont_diff /-! # One-dimensional iterated derivatives We define the `n`-th derivative of a function `f : 𝕜 → F` as a function `iterated_deriv n f : 𝕜 → F`, as well as a version on domains `iterated_deriv_within n f s : 𝕜 → F`, and prove their basic properties. ## Main definitions and results Let `𝕜` be a nontrivially normed field, and `F` a normed vector space over `𝕜`. Let `f : 𝕜 → F`. * `iterated_deriv n f` is the `n`-th derivative of `f`, seen as a function from `𝕜` to `F`. It is defined as the `n`-th Fréchet derivative (which is a multilinear map) applied to the vector `(1, ..., 1)`, to take advantage of all the existing framework, but we show that it coincides with the naive iterative definition. * `iterated_deriv_eq_iterate` states that the `n`-th derivative of `f` is obtained by starting from `f` and differentiating it `n` times. * `iterated_deriv_within n f s` is the `n`-th derivative of `f` within the domain `s`. It only behaves well when `s` has the unique derivative property. * `iterated_deriv_within_eq_iterate` states that the `n`-th derivative of `f` in the domain `s` is obtained by starting from `f` and differentiating it `n` times within `s`. This only holds when `s` has the unique derivative property. ## Implementation details The results are deduced from the corresponding results for the more general (multilinear) iterated Fréchet derivative. For this, we write `iterated_deriv n f` as the composition of `iterated_fderiv 𝕜 n f` and a continuous linear equiv. As continuous linear equivs respect differentiability and commute with differentiation, this makes it possible to prove readily that the derivative of the `n`-th derivative is the `n+1`-th derivative in `iterated_deriv_within_succ`, by translating the corresponding result `iterated_fderiv_within_succ_apply_left` for the iterated Fréchet derivative. -/ noncomputable theory open_locale classical topological_space big_operators open filter asymptotics set variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] /-- The `n`-th iterated derivative of a function from `𝕜` to `F`, as a function from `𝕜` to `F`. -/ def iterated_deriv (n : ℕ) (f : 𝕜 → F) (x : 𝕜) : F := (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) /-- The `n`-th iterated derivative of a function from `𝕜` to `F` within a set `s`, as a function from `𝕜` to `F`. -/ def iterated_deriv_within (n : ℕ) (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) : F := (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) variables {n : ℕ} {f : 𝕜 → F} {s : set 𝕜} {x : 𝕜} lemma iterated_deriv_within_univ : iterated_deriv_within n f univ = iterated_deriv n f := by { ext x, rw [iterated_deriv_within, iterated_deriv, iterated_fderiv_within_univ] } /-! ### Properties of the iterated derivative within a set -/ lemma iterated_deriv_within_eq_iterated_fderiv_within : iterated_deriv_within n f s x = (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_within_eq_equiv_comp : iterated_deriv_within n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv_within 𝕜 n f s) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_within_eq_equiv_comp : iterated_fderiv_within 𝕜 n f s = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv_within n f s) := by rw [iterated_deriv_within_eq_equiv_comp, ← function.comp.assoc, linear_isometry_equiv.self_comp_symm, function.left_id] /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_within_apply_eq_iterated_deriv_within_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv_within 𝕜 n f s x : ((fin n) → 𝕜) → F) m = (∏ i, m i) • iterated_deriv_within n f s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, ← continuous_multilinear_map.map_smul_univ], simp end @[simp] lemma iterated_deriv_within_zero : iterated_deriv_within 0 f s = f := by { ext x, simp [iterated_deriv_within] } @[simp] lemma iterated_deriv_within_one (hs : unique_diff_on 𝕜 s) {x : 𝕜} (hx : x ∈ s): iterated_deriv_within 1 f s x = deriv_within f s x := by { simp [iterated_deriv_within, iterated_fderiv_within_one_apply hs hx], refl } /-- If the first `n` derivatives within a set of a function are continuous, and its first `n-1` derivatives are differentiable, then the function is `C^n`. This is not an equivalence in general, but this is an equivalence when the set has unique derivatives, see `cont_diff_on_iff_continuous_on_differentiable_on_deriv`. -/ lemma cont_diff_on_of_continuous_on_differentiable_on_deriv {n : ℕ∞} (Hcont : ∀ (m : ℕ), (m : ℕ∞) ≤ n → continuous_on (λ x, iterated_deriv_within m f s x) s) (Hdiff : ∀ (m : ℕ), (m : ℕ∞) < n → differentiable_on 𝕜 (λ x, iterated_deriv_within m f s x) s) : cont_diff_on 𝕜 n f s := begin apply cont_diff_on_of_continuous_on_differentiable_on, { simpa [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff] }, { simpa [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_on_iff] } end /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma cont_diff_on_of_differentiable_on_deriv {n : ℕ∞} (h : ∀(m : ℕ), (m : ℕ∞) ≤ n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) : cont_diff_on 𝕜 n f s := begin apply cont_diff_on_of_differentiable_on, simpa only [iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_on_iff] end /-- On a set with unique derivatives, a `C^n` function has derivatives up to `n` which are continuous. -/ lemma cont_diff_on.continuous_on_iterated_deriv_within {n : ℕ∞} {m : ℕ} (h : cont_diff_on 𝕜 n f s) (hmn : (m : ℕ∞) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_deriv_within m f s) s := by simpa only [iterated_deriv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff] using h.continuous_on_iterated_fderiv_within hmn hs /-- On a set with unique derivatives, a `C^n` function has derivatives less than `n` which are differentiable. -/ lemma cont_diff_on.differentiable_on_iterated_deriv_within {n : ℕ∞} {m : ℕ} (h : cont_diff_on 𝕜 n f s) (hmn : (m : ℕ∞) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_deriv_within m f s) s := by simpa only [iterated_deriv_within_eq_equiv_comp, linear_isometry_equiv.comp_differentiable_on_iff] using h.differentiable_on_iterated_fderiv_within hmn hs /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative on sets with unique derivatives. -/ lemma cont_diff_on_iff_continuous_on_differentiable_on_deriv {n : ℕ∞} (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 n f s ↔ (∀m:ℕ, (m : ℕ∞) ≤ n → continuous_on (iterated_deriv_within m f s) s) ∧ (∀m:ℕ, (m : ℕ∞) < n → differentiable_on 𝕜 (iterated_deriv_within m f s) s) := by simp only [cont_diff_on_iff_continuous_on_differentiable_on hs, iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_continuous_on_iff, linear_isometry_equiv.comp_differentiable_on_iff] /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_within_succ {x : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : iterated_deriv_within (n + 1) f s x = deriv_within (iterated_deriv_within n f s) s x := begin rw [iterated_deriv_within_eq_iterated_fderiv_within, iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_eq_equiv_comp, linear_isometry_equiv.comp_fderiv_within _ hxs, deriv_within], change ((continuous_multilinear_map.mk_pi_field 𝕜 (fin n) ((fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1)) : (fin n → 𝕜 ) → F) (λ (i : fin n), 1) = (fderiv_within 𝕜 (iterated_deriv_within n f s) s x : 𝕜 → F) 1, simp end /-- The `n`-th iterated derivative within a set with unique derivatives can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_within_eq_iterate {x : 𝕜} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within n f s x = ((λ (g : 𝕜 → F), deriv_within g s)^[n]) f x := begin induction n with n IH generalizing x, { simp }, { rw [iterated_deriv_within_succ (hs x hx), function.iterate_succ'], exact deriv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx) } end /-- The `n+1`-th iterated derivative within a set with unique derivatives can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_within_succ' {x : 𝕜} (hxs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_deriv_within (n + 1) f s x = (iterated_deriv_within n (deriv_within f s) s) x := by { rw [iterated_deriv_within_eq_iterate hxs hx, iterated_deriv_within_eq_iterate hxs hx], refl } /-! ### Properties of the iterated derivative on the whole space -/ lemma iterated_deriv_eq_iterated_fderiv : iterated_deriv n f x = (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) (λ(i : fin n), 1) := rfl /-- Write the iterated derivative as the composition of a continuous linear equiv and the iterated Fréchet derivative -/ lemma iterated_deriv_eq_equiv_comp : iterated_deriv n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F).symm ∘ (iterated_fderiv 𝕜 n f) := by { ext x, refl } /-- Write the iterated Fréchet derivative as the composition of a continuous linear equiv and the iterated derivative. -/ lemma iterated_fderiv_eq_equiv_comp : iterated_fderiv 𝕜 n f = (continuous_multilinear_map.pi_field_equiv 𝕜 (fin n) F) ∘ (iterated_deriv n f) := by rw [iterated_deriv_eq_equiv_comp, ← function.comp.assoc, linear_isometry_equiv.self_comp_symm, function.left_id] /-- The `n`-th Fréchet derivative applied to a vector `(m 0, ..., m (n-1))` is the derivative multiplied by the product of the `m i`s. -/ lemma iterated_fderiv_apply_eq_iterated_deriv_mul_prod {m : (fin n) → 𝕜} : (iterated_fderiv 𝕜 n f x : ((fin n) → 𝕜) → F) m = (∏ i, m i) • iterated_deriv n f x := by { rw [iterated_deriv_eq_iterated_fderiv, ← continuous_multilinear_map.map_smul_univ], simp } @[simp] lemma iterated_deriv_zero : iterated_deriv 0 f = f := by { ext x, simp [iterated_deriv] } @[simp] lemma iterated_deriv_one : iterated_deriv 1 f = deriv f := by { ext x, simp [iterated_deriv], refl } /-- The property of being `C^n`, initially defined in terms of the Fréchet derivative, can be reformulated in terms of the one-dimensional derivative. -/ lemma cont_diff_iff_iterated_deriv {n : ℕ∞} : cont_diff 𝕜 n f ↔ (∀m:ℕ, (m : ℕ∞) ≤ n → continuous (iterated_deriv m f)) ∧ (∀m:ℕ, (m : ℕ∞) < n → differentiable 𝕜 (iterated_deriv m f)) := by simp only [cont_diff_iff_continuous_differentiable, iterated_fderiv_eq_equiv_comp, linear_isometry_equiv.comp_continuous_iff, linear_isometry_equiv.comp_differentiable_iff] /-- To check that a function is `n` times continuously differentiable, it suffices to check that its first `n` derivatives are differentiable. This is slightly too strong as the condition we require on the `n`-th derivative is differentiability instead of continuity, but it has the advantage of avoiding the discussion of continuity in the proof (and for `n = ∞` this is optimal). -/ lemma cont_diff_of_differentiable_iterated_deriv {n : ℕ∞} (h : ∀(m : ℕ), (m : ℕ∞) ≤ n → differentiable 𝕜 (iterated_deriv m f)) : cont_diff 𝕜 n f := cont_diff_iff_iterated_deriv.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ lemma cont_diff.continuous_iterated_deriv {n : ℕ∞} (m : ℕ) (h : cont_diff 𝕜 n f) (hmn : (m : ℕ∞) ≤ n) : continuous (iterated_deriv m f) := (cont_diff_iff_iterated_deriv.1 h).1 m hmn lemma cont_diff.differentiable_iterated_deriv {n : ℕ∞} (m : ℕ) (h : cont_diff 𝕜 n f) (hmn : (m : ℕ∞) < n) : differentiable 𝕜 (iterated_deriv m f) := (cont_diff_iff_iterated_deriv.1 h).2 m hmn /-- The `n+1`-th iterated derivative can be obtained by differentiating the `n`-th iterated derivative. -/ lemma iterated_deriv_succ : iterated_deriv (n + 1) f = deriv (iterated_deriv n f) := begin ext x, rw [← iterated_deriv_within_univ, ← iterated_deriv_within_univ, ← deriv_within_univ], exact iterated_deriv_within_succ unique_diff_within_at_univ, end /-- The `n`-th iterated derivative can be obtained by iterating `n` times the differentiation operation. -/ lemma iterated_deriv_eq_iterate : iterated_deriv n f = (deriv^[n]) f := begin ext x, rw [← iterated_deriv_within_univ], convert iterated_deriv_within_eq_iterate unique_diff_on_univ (mem_univ x), simp [deriv_within_univ] end /-- The `n+1`-th iterated derivative can be obtained by taking the `n`-th derivative of the derivative. -/ lemma iterated_deriv_succ' : iterated_deriv (n + 1) f = iterated_deriv n (deriv f) := by { rw [iterated_deriv_eq_iterate, iterated_deriv_eq_iterate], refl }
9032350100a7e4b01f066f77b75d1a60baca4c2f
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/nat/sqrt.lean
98ca8aa9232a1328ae6172a4037d12844fd19638
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
7,106
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Very simple (sqrt n) function that returns s s.t. s*s ≤ n ≤ s*s + s + s -/ import data.nat.order data.nat.sub namespace nat open decidable -- This is the simplest possible function that just performs a linear search definition sqrt_aux : nat → nat → nat | 0 n := 0 | (succ s) n := if (succ s)*(succ s) ≤ n then succ s else sqrt_aux s n theorem sqrt_aux_succ_of_pos {s n} : (succ s)*(succ s) ≤ n → sqrt_aux (succ s) n = (succ s) := assume h, if_pos h theorem sqrt_aux_succ_of_neg {s n} : ¬ (succ s)*(succ s) ≤ n → sqrt_aux (succ s) n = sqrt_aux s n := assume h, if_neg h theorem sqrt_aux_of_le : ∀ {s n : nat}, s * s ≤ n → sqrt_aux s n = s := sorry /- | 0 n h := rfl | (succ s) n h := by rewrite [sqrt_aux_succ_of_pos h] -/ theorem sqrt_aux_le : ∀ (s n), sqrt_aux s n ≤ s := sorry /- | 0 n := !zero_le | (succ s) n := or.elim (em ((succ s)*(succ s) ≤ n)) (λ h, begin unfold sqrt_aux, rewrite [if_pos h] end) (λ h, have sqrt_aux s n ≤ succ s, from le.step (sqrt_aux_le s n), begin unfold sqrt_aux, rewrite [if_neg h], eassumption end) -/ definition sqrt (n : nat) : nat := sqrt_aux n n theorem sqrt_aux_lower : ∀ {s n : nat}, s ≤ n → sqrt_aux s n * sqrt_aux s n ≤ n := sorry /- | 0 n h := h | (succ s) n h := by_cases (λ h₁ : (succ s)*(succ s) ≤ n, by rewrite [sqrt_aux_succ_of_pos h₁]; exact h₁) (λ h₂ : ¬ (succ s)*(succ s) ≤ n, have aux : s ≤ n, from le_of_succ_le h, by rewrite [sqrt_aux_succ_of_neg h₂]; exact (sqrt_aux_lower aux)) -/ theorem sqrt_lower (n : nat) : sqrt n * sqrt n ≤ n := sqrt_aux_lower (le.refl n) theorem sqrt_aux_upper : ∀ {s n : nat}, n ≤ s*s + s + s → n ≤ sqrt_aux s n * sqrt_aux s n + sqrt_aux s n + sqrt_aux s n := sorry /- | 0 n h := h | (succ s) n h := by_cases (λ h₁ : (succ s)*(succ s) ≤ n, by rewrite [sqrt_aux_succ_of_pos h₁]; exact h) (λ h₂ : ¬ (succ s)*(succ s) ≤ n, have h₃ : n < (succ s) * (succ s), from lt_of_not_ge h₂, have h₄ : n ≤ s * s + s + s, by rewrite [succ_mul_succ_eq at h₃]; exact le_of_lt_succ h₃, by rewrite [sqrt_aux_succ_of_neg h₂]; exact (sqrt_aux_upper h₄)) -/ theorem sqrt_upper (n : nat) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := have aux : n ≤ n*n + n + n, from le_add_of_le_right (le_add_of_le_left (le.refl n)), sqrt_aux_upper aux private theorem le_squared : ∀ (n : nat), n ≤ n*n := sorry /- | 0 := !le.refl | (succ n) := have aux₁ : 1 ≤ succ n, from succ_le_succ !zero_le, have aux₂ : 1 * succ n ≤ succ n * succ n, from nat.mul_le_mul aux₁ !le.refl, by rewrite [one_mul at aux₂]; exact aux₂ -/ private theorem lt_squared : ∀ {n : nat}, n > 1 → n < n * n := sorry /- | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | (succ (succ n)) h := have 1 < succ (succ n), from dec_trivial, have succ (succ n) * 1 < succ (succ n) * succ (succ n), from mul_lt_mul_of_pos_left this dec_trivial, by rewrite [mul_one at this]; exact this -/ theorem sqrt_le (n : nat) : sqrt n ≤ n := calc sqrt n ≤ sqrt n * sqrt n : le_squared (sqrt n) ... ≤ n : sqrt_lower n theorem eq_zero_of_sqrt_eq_zero {n : nat} : sqrt n = 0 → n = 0 := sorry /- suppose sqrt n = 0, have n ≤ sqrt n * sqrt n + sqrt n + sqrt n, from !sqrt_upper, have n ≤ 0, by rewrite [*`sqrt n = 0` at this]; exact this, eq_zero_of_le_zero this -/ theorem le_three_of_sqrt_eq_one {n : nat} : sqrt n = 1 → n ≤ 3 := sorry /- suppose sqrt n = 1, have n ≤ sqrt n * sqrt n + sqrt n + sqrt n, from !sqrt_upper, show n ≤ 3, by rewrite [*`sqrt n = 1` at this]; exact this -/ theorem sqrt_lt : ∀ {n : nat}, n > 1 → sqrt n < n := sorry /- | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | 2 h := dec_trivial | 3 h := dec_trivial | (n+4) h := have sqrt (n+4) > 1, from by_contradiction (suppose ¬ sqrt (n+4) > 1, have sqrt (n+4) ≤ 1, from le_of_not_gt this, or.elim (eq_or_lt_of_le this) (suppose sqrt (n+4) = 1, have n+4 ≤ 3, from le_three_of_sqrt_eq_one this, absurd this dec_trivial) (suppose sqrt (n+4) < 1, have sqrt (n+4) = 0, from eq_zero_of_le_zero (le_of_lt_succ this), have n + 4 = 0, from eq_zero_of_sqrt_eq_zero this, absurd this dec_trivial)), calc sqrt (n+4) < sqrt (n+4) * sqrt (n+4) : lt_squared this ... ≤ n+4 : !sqrt_lower -/ theorem sqrt_pos_of_pos {n : nat} : n > 0 → sqrt n > 0 := sorry /- suppose n > 0, have sqrt n ≠ 0, from suppose sqrt n = 0, have n = 0, from eq_zero_of_sqrt_eq_zero this, by subst n; exact absurd `0 > 0` !lt.irrefl, pos_of_ne_zero this -/ theorem sqrt_aux_offset_eq {n k : nat} (h₁ : k ≤ n + n) : ∀ {s}, s ≥ n → sqrt_aux s (n*n + k) = n := sorry /- | 0 h₂ := have neqz : n = 0, from eq_zero_of_le_zero h₂, by rewrite neqz | (succ s) h₂ := by_cases (λ hl : (succ s)*(succ s) ≤ n*n + k, have l₁ : n*n + k ≤ n*n + n + n, from by rewrite [add.assoc]; exact (add_le_add_left h₁ (n*n)), have l₂ : n*n + k < n*n + n + n + 1, from lt_succ_of_le l₁, have l₃ : n*n + k < (succ n)*(succ n), by rewrite [-succ_mul_succ_eq at l₂]; exact l₂, have l₄ : (succ s)*(succ s) < (succ n)*(succ n), from lt_of_le_of_lt hl l₃, have ng : ¬ succ s > (succ n), from assume g : succ s > succ n, have g₁ : (succ s)*(succ s) > (succ n)*(succ n), from mul_lt_mul_of_le_of_le g g, absurd (lt.trans g₁ l₄) !lt.irrefl, have sslesn : succ s ≤ succ n, from le_of_not_gt ng, have ssnesn : succ s ≠ succ n, from assume sseqsn : succ s = succ n, by rewrite [sseqsn at l₄]; exact (absurd l₄ !lt.irrefl), have sslen : s < n, from lt_of_succ_lt_succ (lt_of_le_of_ne sslesn ssnesn), have sseqn : succ s = n, from le.antisymm sslen h₂, by rewrite [sqrt_aux_succ_of_pos hl]; exact sseqn) (λ hg : ¬ (succ s)*(succ s) ≤ n*n + k, or.elim (eq_or_lt_of_le h₂) (λ neqss : n = succ s, have p : n*n ≤ n*n + k, from !le_add_right, have n : ¬ n*n ≤ n*n + k, by rewrite [-neqss at hg]; exact hg, absurd p n) (λ sgen : succ s > n, by rewrite [sqrt_aux_succ_of_neg hg]; exact (sqrt_aux_offset_eq (le_of_lt_succ sgen)))) -/ theorem sqrt_offset_eq {n k : nat} : k ≤ n + n → sqrt (n*n + k) = n := assume h, have h₁ : n ≤ n*n + k, from le.trans (le_squared n) (le_add_right (n * n) k), sqrt_aux_offset_eq h h₁ theorem sqrt_eq (n : nat) : sqrt (n*n) = n := sqrt_offset_eq (zero_le (n + n)) theorem mul_square_cancel {a b : nat} : a*a = b*b → a = b := sorry /- assume h, have aux : sqrt (a*a) = sqrt (b*b), by rewrite h, by rewrite [*sqrt_eq at aux]; exact aux -/ end nat
ea55de95e165d60b221dd58371fab71c8be30795
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/ordering/lemmas_auto.lean
314d44834dbf7ecd85e9cb092d54edd7396caae6
[]
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,499
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.data.ordering.basic import Mathlib.Lean3Lib.init.meta.default import Mathlib.Lean3Lib.init.algebra.classes import Mathlib.Lean3Lib.init.ite_simp universes u namespace Mathlib namespace ordering @[simp] theorem ite_eq_lt_distrib (c : Prop) [Decidable c] (a : ordering) (b : ordering) : ite c a b = lt = ite c (a = lt) (b = lt) := sorry @[simp] theorem ite_eq_eq_distrib (c : Prop) [Decidable c] (a : ordering) (b : ordering) : ite c a b = eq = ite c (a = eq) (b = eq) := sorry @[simp] theorem ite_eq_gt_distrib (c : Prop) [Decidable c] (a : ordering) (b : ordering) : ite c a b = gt = ite c (a = gt) (b = gt) := sorry /- ------------------------------------------------------------------ -/ end ordering @[simp] theorem cmp_using_eq_lt {α : Type u} {lt : α → α → Prop} [DecidableRel lt] (a : α) (b : α) : cmp_using lt a b = ordering.lt = lt a b := sorry @[simp] theorem cmp_using_eq_gt {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_order α lt] (a : α) (b : α) : cmp_using lt a b = ordering.gt = lt b a := sorry @[simp] theorem cmp_using_eq_eq {α : Type u} {lt : α → α → Prop} [DecidableRel lt] (a : α) (b : α) : cmp_using lt a b = ordering.eq = (¬lt a b ∧ ¬lt b a) := sorry end Mathlib
4ff2e338de4d4030b77ffdef2d5bcbb5741568b0
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Data/RBMap.lean
22221ec697e8bd4264b14adb1c0f9142f10bf244
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
15,405
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ namespace Lean universe u v w w' inductive Rbcolor where | red | black inductive RBNode (α : Type u) (β : α → Type v) where | leaf : RBNode α β | node (color : Rbcolor) (lchild : RBNode α β) (key : α) (val : β key) (rchild : RBNode α β) : RBNode α β namespace RBNode variable {α : Type u} {β : α → Type v} {σ : Type w} open Rbcolor Nat def depth (f : Nat → Nat → Nat) : RBNode α β → Nat | leaf => 0 | node _ l _ _ r => succ (f (depth f l) (depth f r)) protected def min : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ leaf k v _ => some ⟨k, v⟩ | node _ l _ _ _ => RBNode.min l protected def max : RBNode α β → Option (Sigma (fun k => β k)) | leaf => none | node _ _ k v leaf => some ⟨k, v⟩ | node _ _ _ _ r => RBNode.max r @[specialize] def fold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ | b, leaf => b | b, node _ l k v r => fold f (f (fold f b l) k v) r @[specialize] def forM [Monad m] (f : (k : α) → β k → m Unit) : RBNode α β → m Unit | leaf => pure () | node _ l k v r => do forM f l; f k v; forM f r @[specialize] def foldM [Monad m] (f : σ → (k : α) → β k → m σ) : (init : σ) → RBNode α β → m σ | b, leaf => pure b | b, node _ l k v r => do let b ← foldM f b l let b ← f b k v foldM f b r @[inline] protected def forIn [Monad m] (as : RBNode α β) (init : σ) (f : (k : α) → β k → σ → m (ForInStep σ)) : m σ := do let rec @[specialize] visit : RBNode α β → σ → m (ForInStep σ) | leaf, b => return ForInStep.yield b | node _ l k v r, b => do match (← visit l b) with | r@(ForInStep.done _) => return r | ForInStep.yield b => match (← f k v b) with | r@(ForInStep.done _) => return r | ForInStep.yield b => visit r b match (← visit as init) with | ForInStep.done b => pure b | ForInStep.yield b => pure b @[specialize] def revFold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ | b, leaf => b | b, node _ l k v r => revFold f (f (revFold f b r) k v) l @[specialize] def all (p : (k : α) → β k → Bool) : RBNode α β → Bool | leaf => true | node _ l k v r => p k v && all p l && all p r @[specialize] def any (p : (k : α) → β k → Bool) : RBNode α β → Bool | leaf => false | node _ l k v r => p k v || any p l || any p r def singleton (k : α) (v : β k) : RBNode α β := node red leaf k v leaf -- the first half of Okasaki's `balance`, concerning red-red sequences in the left child @[inline] def balance1 : RBNode α β → (a : α) → β a → RBNode α β → RBNode α β | node red (node red a kx vx b) ky vy c, kz, vz, d | node red a kx vx (node red b ky vy c), kz, vz, d => node red (node black a kx vx b) ky vy (node black c kz vz d) | a, kx, vx, b => node black a kx vx b -- the second half, concerning red-red sequences in the right child @[inline] def balance2 : RBNode α β → (a : α) → β a → RBNode α β → RBNode α β | a, kx, vx, node red (node red b ky vy c) kz vz d | a, kx, vx, node red b ky vy (node red c kz vz d) => node red (node black a kx vx b) ky vy (node black c kz vz d) | a, kx, vx, b => node black a kx vx b def isRed : RBNode α β → Bool | node red .. => true | _ => false def isBlack : RBNode α β → Bool | node black .. => true | _ => false section Insert variable (cmp : α → α → Ordering) @[specialize] def ins : RBNode α β → (k : α) → β k → RBNode α β | leaf, kx, vx => node red leaf kx vx leaf | node red a ky vy b, kx, vx => match cmp kx ky with | Ordering.lt => node red (ins a kx vx) ky vy b | Ordering.gt => node red a ky vy (ins b kx vx) | Ordering.eq => node red a kx vx b | node black a ky vy b, kx, vx => match cmp kx ky with | Ordering.lt => balance1 (ins a kx vx) ky vy b | Ordering.gt => balance2 a ky vy (ins b kx vx) | Ordering.eq => node black a kx vx b def setBlack : RBNode α β → RBNode α β | node _ l k v r => node black l k v r | e => e @[specialize] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β := if isRed t then setBlack (ins cmp t k v) else ins cmp t k v end Insert def setRed : RBNode α β → RBNode α β | node _ a k v b => node red a k v b | e => e def balLeft : RBNode α β → (k : α) → β k → RBNode α β → RBNode α β | node red a kx vx b, k, v, r => node red (node black a kx vx b) k v r | l, k, v, node black a ky vy b => balance2 l k v (node red a ky vy b) | l, k, v, node red (node black a ky vy b) kz vz c => node red (node black l k v a) ky vy (balance2 b kz vz (setRed c)) | l, k, v, r => node red l k v r -- unreachable def balRight (l : RBNode α β) (k : α) (v : β k) (r : RBNode α β) : RBNode α β := match r with | (node red b ky vy c) => node red l k v (node black b ky vy c) | _ => match l with | node black a kx vx b => balance1 (node red a kx vx b) k v r | node red a kx vx (node black b ky vy c) => node red (balance1 (setRed a) kx vx b) ky vy (node black c k v r) | _ => node red l k v r -- unreachable /-- The number of nodes in the tree. -/ @[local simp] def size : RBNode α β → Nat | leaf => 0 | node _ x _ _ y => x.size + y.size + 1 def appendTrees : RBNode α β → RBNode α β → RBNode α β | leaf, x => x | x, leaf => x | node red a kx vx b, node red c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node red a kx vx b') kz vz (node red c' ky vy d) | bc => node red a kx vx (node red bc ky vy d) | node black a kx vx b, node black c ky vy d => match appendTrees b c with | node red b' kz vz c' => node red (node black a kx vx b') kz vz (node black c' ky vy d) | bc => balLeft a kx vx (node black bc ky vy d) | a, node red b kx vx c => node red (appendTrees a b) kx vx c | node red a kx vx b, c => node red a kx vx (appendTrees b c) termination_by _ x y => x.size + y.size section Erase variable (cmp : α → α → Ordering) @[specialize] def del (x : α) : RBNode α β → RBNode α β | leaf => leaf | node _ a y v b => match cmp x y with | Ordering.lt => if a.isBlack then balLeft (del x a) y v b else node red (del x a) y v b | Ordering.gt => if b.isBlack then balRight a y v (del x b) else node red a y v (del x b) | Ordering.eq => appendTrees a b @[specialize] def erase (x : α) (t : RBNode α β) : RBNode α β := let t := del cmp x t; t.setBlack end Erase section Membership variable (cmp : α → α → Ordering) @[specialize] def findCore : RBNode α β → (k : α) → Option (Sigma (fun k => β k)) | leaf, _ => none | node _ a ky vy b, x => match cmp x ky with | Ordering.lt => findCore a x | Ordering.gt => findCore b x | Ordering.eq => some ⟨ky, vy⟩ @[specialize] def find {β : Type v} : RBNode α (fun _ => β) → α → Option β | leaf, _ => none | node _ a ky vy b, x => match cmp x ky with | Ordering.lt => find a x | Ordering.gt => find b x | Ordering.eq => some vy @[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, _, lb => lb | node _ a ky vy b, x, lb => match cmp x ky with | Ordering.lt => lowerBound a x lb | Ordering.gt => lowerBound b x (some ⟨ky, vy⟩) | Ordering.eq => some ⟨ky, vy⟩ end Membership inductive WellFormed (cmp : α → α → Ordering) : RBNode α β → Prop where | leafWff : WellFormed cmp leaf | insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed cmp n → n' = insert cmp n k v → WellFormed cmp n' | eraseWff {n n' : RBNode α β} {k : α} : WellFormed cmp n → n' = erase cmp k n → WellFormed cmp n' section Map @[specialize] def mapM {α : Type v} {β γ : α → Type v} {M : Type v → Type v} [Applicative M] (f : (a : α) → β a → M (γ a)) : RBNode α β → M (RBNode α γ) | leaf => pure leaf | node color lchild key val rchild => pure (node color · key · ·) <*> lchild.mapM f <*> f _ val <*> rchild.mapM f @[specialize] def map {α : Type u} {β γ : α → Type v} (f : (a : α) → β a → γ a) : RBNode α β → RBNode α γ | leaf => leaf | node color lchild key val rchild => node color (lchild.map f) key (f key val) (rchild.map f) end Map def toArray (n : RBNode α β) : Array (Sigma β) := n.fold (init := ∅) fun acc k v => acc.push ⟨k,v⟩ instance : EmptyCollection (RBNode α β) := ⟨leaf⟩ end RBNode open Lean.RBNode /- TODO(Leo): define dRBMap -/ def RBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Type (max u v) := {t : RBNode α (fun _ => β) // t.WellFormed cmp } @[inline] def mkRBMap (α : Type u) (β : Type v) (cmp : α → α → Ordering) : RBMap α β cmp := ⟨leaf, WellFormed.leafWff⟩ @[inline] def RBMap.empty {α : Type u} {β : Type v} {cmp : α → α → Ordering} : RBMap α β cmp := mkRBMap .. instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : EmptyCollection (RBMap α β cmp) := ⟨RBMap.empty⟩ instance (α : Type u) (β : Type v) (cmp : α → α → Ordering) : Inhabited (RBMap α β cmp) := ⟨∅⟩ namespace RBMap variable {α : Type u} {β : Type v} {σ : Type w} {cmp : α → α → Ordering} def depth (f : Nat → Nat → Nat) (t : RBMap α β cmp) : Nat := t.val.depth f @[inline] def fold (f : σ → α → β → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.fold f b @[inline] def revFold (f : σ → α → β → σ) : (init : σ) → RBMap α β cmp → σ | b, ⟨t, _⟩ => t.revFold f b @[inline] def foldM [Monad m] (f : σ → α → β → m σ) : (init : σ) → RBMap α β cmp → m σ | b, ⟨t, _⟩ => t.foldM f b @[inline] def forM [Monad m] (f : α → β → m PUnit) (t : RBMap α β cmp) : m PUnit := t.foldM (fun _ k v => f k v) ⟨⟩ @[inline] protected def forIn [Monad m] (t : RBMap α β cmp) (init : σ) (f : (α × β) → σ → m (ForInStep σ)) : m σ := t.val.forIn init (fun a b acc => f (a, b) acc) instance : ForIn m (RBMap α β cmp) (α × β) where forIn := RBMap.forIn @[inline] def isEmpty : RBMap α β cmp → Bool | ⟨leaf, _⟩ => true | _ => false @[specialize] def toList : RBMap α β cmp → List (α × β) | ⟨t, _⟩ => t.revFold (fun ps k v => (k, v)::ps) [] /-- Returns the kv pair `(a,b)` such that `a ≤ k` for all keys in the RBMap. -/ @[inline] protected def min : RBMap α β cmp → Option (α × β) | ⟨t, _⟩ => match t.min with | some ⟨k, v⟩ => some (k, v) | none => none /-- Returns the kv pair `(a,b)` such that `a ≥ k` for all keys in the RBMap. -/ @[inline] protected def max : RBMap α β cmp → Option (α × β) | ⟨t, _⟩ => match t.max with | some ⟨k, v⟩ => some (k, v) | none => none instance [Repr α] [Repr β] : Repr (RBMap α β cmp) where reprPrec m prec := Repr.addAppParen ("Lean.rbmapOf " ++ repr m.toList) prec @[inline] def insert : RBMap α β cmp → α → β → RBMap α β cmp | ⟨t, w⟩, k, v => ⟨t.insert cmp k v, WellFormed.insertWff w rfl⟩ @[inline] def erase : RBMap α β cmp → α → RBMap α β cmp | ⟨t, w⟩, k => ⟨t.erase cmp k, WellFormed.eraseWff w rfl⟩ @[specialize] def ofList : List (α × β) → RBMap α β cmp | [] => mkRBMap .. | ⟨k,v⟩::xs => (ofList xs).insert k v @[inline] def findCore? : RBMap α β cmp → α → Option (Sigma (fun (_ : α) => β)) | ⟨t, _⟩, x => t.findCore cmp x @[inline] def find? : RBMap α β cmp → α → Option β | ⟨t, _⟩, x => t.find cmp x @[inline] def findD (t : RBMap α β cmp) (k : α) (v₀ : β) : β := (t.find? k).getD v₀ /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ @[inline] def lowerBound : RBMap α β cmp → α → Option (Sigma (fun (_ : α) => β)) | ⟨t, _⟩, x => t.lowerBound cmp x none /-- Returns true if the given key `a` is in the RBMap. -/ @[inline] def contains (t : RBMap α β cmp) (a : α) : Bool := (t.find? a).isSome @[inline] def fromList (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := l.foldl (fun r p => r.insert p.1 p.2) (mkRBMap α β cmp) @[inline] def fromArray (l : Array (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := l.foldl (fun r p => r.insert p.1 p.2) (mkRBMap α β cmp) /-- Returns true if the given predicate is true for all items in the RBMap. -/ @[inline] def all : RBMap α β cmp → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.all p /-- Returns true if the given predicate is true for any item in the RBMap. -/ @[inline] def any : RBMap α β cmp → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.any p /-- The number of items in the RBMap. -/ def size (m : RBMap α β cmp) : Nat := m.fold (fun sz _ _ => sz+1) 0 def maxDepth (t : RBMap α β cmp) : Nat := t.val.depth Nat.max @[inline] def min! [Inhabited α] [Inhabited β] (t : RBMap α β cmp) : α × β := match t.min with | some p => p | none => panic! "map is empty" @[inline] def max! [Inhabited α] [Inhabited β] (t : RBMap α β cmp) : α × β := match t.max with | some p => p | none => panic! "map is empty" /-- Attempts to find the value with key `k : α` in `t` and panics if there is no such key. -/ @[inline] def find! [Inhabited β] (t : RBMap α β cmp) (k : α) : β := match t.find? k with | some b => b | none => panic! "key is not in the map" /-- Merges the maps `t₁` and `t₂`, if a key `a : α` exists in both, then use `mergeFn a b₁ b₂` to produce the new merged value. -/ def mergeBy (mergeFn : α → β → β → β) (t₁ t₂ : RBMap α β cmp) : RBMap α β cmp := t₂.fold (init := t₁) fun t₁ a b₂ => t₁.insert a <| match t₁.find? a with | some b₁ => mergeFn a b₁ b₂ | none => b₂ /-- Intersects the maps `t₁` and `t₂` using `mergeFn a b₁ b₂` to produce the new value. -/ def intersectBy {γ : Type v₁} {δ : Type v₂} (mergeFn : α → β → γ → δ) (t₁ : RBMap α β cmp) (t₂ : RBMap α γ cmp) : RBMap α δ cmp := t₁.fold (init := ∅) fun acc a b₁ => match t₂.find? a with | some b₂ => acc.insert a <| mergeFn a b₁ b₂ | none => acc end RBMap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (cmp : α → α → Ordering) : RBMap α β cmp := RBMap.fromList l cmp
4ca428fc43eea25a826bccd438324881976747bd
737dc4b96c97368cb66b925eeea3ab633ec3d702
/tests/lean/run/multiTargetCasesInductionIssue.lean
fa1f6147f563abbd22238ec10b617e01536c7f9b
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,657
lean
def Vec (α : Type u) (n : Nat) : Type u := { a : List α // a.length = n } def Vec.nil : Vec α 0 := ⟨[], rfl⟩ def Vec.cons (a : α) (as : Vec α n) : Vec α (n+1) := ⟨a :: as.val, by simp [as.property]⟩ set_option pp.analyze false def Vec.casesOn (motive : (n : Nat) → Vec α n → Sort v) (n : Nat) (as : Vec α n) (nil : motive 0 Vec.nil) (cons : (n : Nat) → (a : α) → (as : Vec α n) → (ih : motive n as) → motive (n+1) (Vec.cons a as)) : motive n as := let rec go (n : Nat) (as : List α) (h : as.length = n) : motive n ⟨as, h⟩ := match n, as, h with | 0, [], _ => nil | n+1, a::as, h => have : as.length = n := by injection h; assumption have ih : motive n ⟨as, this⟩ := go n as this cons n a ⟨as, this⟩ ih match as with | ⟨as, h⟩ => go n as h example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by induction n+2, Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n a as ih => traceState constructor #print "-----" example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by cases n+2, Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n a as ih => traceState constructor #print "-----" example (n : Nat) (a : α) (as : Vec α n) : Vec.cons a (Vec.cons a as) = Vec.cons a (Vec.cons a as) := by cases h₁ : n+2, h₂ : Vec.cons a (Vec.cons a as) using Vec.casesOn case nil => constructor case cons n' a' as' ih => traceState constructor
2744b3ed2949983dd5e69f81809cdde8569f7079
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Meta/Tactic/Apply.lean
539bb1d9aa8ca69cb85fb8ad03df0539b2af1dcf
[ "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
4,287
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.FindMVar import Lean.Meta.ExprDefEq import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Tactic.Util namespace Lean.Meta /- Compute the number of expected arguments and whether the result type is of the form (?m ...) where ?m is an unassigned metavariable. -/ private def getExpectedNumArgsAux (e : Expr) : MetaM (Nat × Bool) := withDefault <| forallTelescopeReducing e fun xs body => pure (xs.size, body.getAppFn.isMVar) private def getExpectedNumArgs (e : Expr) : MetaM Nat := do let (numArgs, _) ← getExpectedNumArgsAux e pure numArgs private def throwApplyError {α} (mvarId : MVarId) (eType : Expr) (targetType : Expr) : MetaM α := throwTacticEx `apply mvarId m!"failed to unify{indentExpr eType}\nwith{indentExpr targetType}" def synthAppInstances (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := newMVars.size.forM fun i => do if binderInfos[i].isInstImplicit then let mvar := newMVars[i] let mvarType ← inferType mvar let mvarVal ← synthInstance mvarType unless (← isDefEq mvar mvarVal) do throwTacticEx tacticName mvarId "failed to assign synthesized instance" def appendParentTag (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do let parentTag ← getMVarTag mvarId if newMVars.size == 1 then -- if there is only one subgoal, we inherit the parent tag setMVarTag newMVars[0].mvarId! parentTag else unless parentTag.isAnonymous do newMVars.size.forM fun i => do let newMVarId := newMVars[i].mvarId! unless (← isExprMVarAssigned newMVarId) do unless binderInfos[i].isInstImplicit do let currTag ← getMVarTag newMVarId setMVarTag newMVarId (appendTag parentTag currTag) def postprocessAppMVars (tacticName : Name) (mvarId : MVarId) (newMVars : Array Expr) (binderInfos : Array BinderInfo) : MetaM Unit := do synthAppInstances tacticName mvarId newMVars binderInfos -- TODO: default and auto params appendParentTag mvarId newMVars binderInfos private def dependsOnOthers (mvar : Expr) (otherMVars : Array Expr) : MetaM Bool := otherMVars.anyM fun otherMVar => do if mvar == otherMVar then pure false else let otherMVarType ← inferType otherMVar return (otherMVarType.findMVar? fun mvarId => mvarId == mvar.mvarId!).isSome private def reorderNonDependentFirst (newMVars : Array Expr) : MetaM (List MVarId) := do let (nonDeps, deps) ← newMVars.foldlM (init := (#[], #[])) fun (nonDeps, deps) mvar => do let currMVarId := mvar.mvarId! if (← dependsOnOthers mvar newMVars) then pure (nonDeps, deps.push currMVarId) else pure (nonDeps.push currMVarId, deps) return nonDeps.toList ++ deps.toList inductive ApplyNewGoals where | nonDependentFirst | nonDependentOnly | all def apply (mvarId : MVarId) (e : Expr) : MetaM (List MVarId) := withMVarContext mvarId do checkNotAssigned mvarId `apply let targetType ← getMVarType mvarId let eType ← inferType e let mut (numArgs, hasMVarHead) ← getExpectedNumArgsAux eType if hasMVarHead then let targetTypeNumArgs ← getExpectedNumArgs targetType numArgs := numArgs - targetTypeNumArgs let (newMVars, binderInfos, eType) ← forallMetaTelescopeReducing eType (some numArgs) unless (← isDefEq eType targetType) do throwApplyError mvarId eType targetType postprocessAppMVars `apply mvarId newMVars binderInfos let e ← instantiateMVars e assignExprMVar mvarId (mkAppN e newMVars) let newMVars ← newMVars.filterM fun mvar => not <$> isExprMVarAssigned mvar.mvarId! let otherMVarIds ← getMVarsNoDelayed e -- TODO: add option `ApplyNewGoals` and implement other orders let newMVarIds ← reorderNonDependentFirst newMVars let otherMVarIds := otherMVarIds.filter fun mvarId => !newMVarIds.contains mvarId let result := newMVarIds ++ otherMVarIds.toList result.forM headBetaMVarType return result end Lean.Meta
cf8f606251d1453fefa207469f56e74ade9da060
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/algebra/monoid.lean
f62e5682e9756b2d5d8dd1fb7c71a0c1579a657e
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,122
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.continuous_on import group_theory.submonoid.operations import algebra.group.prod import algebra.pointwise /-! # Theory of topological monoids In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many applications the underlying type is a monoid (multiplicative or additive), we do not require this in the definitions. -/ open classical set filter topological_space open_locale classical topological_space big_operators variables {α β M N : Type*} /-- Basic hypothesis to talk about a topological additive monoid or a topological additive semigroup. A topological additive monoid over `α`, for example, is obtained by requiring both the instances `add_monoid α` and `has_continuous_add α`. -/ class has_continuous_add (M : Type*) [topological_space M] [has_add M] : Prop := (continuous_add : continuous (λ p : M × M, p.1 + p.2)) /-- Basic hypothesis to talk about a topological monoid or a topological semigroup. A topological monoid over `α`, for example, is obtained by requiring both the instances `monoid α` and `has_continuous_mul α`. -/ @[to_additive] class has_continuous_mul (M : Type*) [topological_space M] [has_mul M] : Prop := (continuous_mul : continuous (λ p : M × M, p.1 * p.2)) section has_continuous_mul variables [topological_space M] [has_mul M] [has_continuous_mul M] @[to_additive] lemma continuous_mul : continuous (λp:M×M, p.1 * p.2) := has_continuous_mul.continuous_mul @[continuity, to_additive] lemma continuous.mul [topological_space α] {f : α → M} {g : α → M} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := continuous_mul.comp (hf.prod_mk hg : _) -- should `to_additive` be doing this? attribute [continuity] continuous.add @[to_additive] lemma continuous_mul_left (a : M) : continuous (λ b:M, a * b) := continuous_const.mul continuous_id @[to_additive] lemma continuous_mul_right (a : M) : continuous (λ b:M, b * a) := continuous_id.mul continuous_const @[to_additive] lemma continuous_on.mul [topological_space α] {f : α → M} {g : α → M} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, f x * g x) s := (continuous_mul.comp_continuous_on (hf.prod hg) : _) @[to_additive] lemma tendsto_mul {a b : M} : tendsto (λp:M×M, p.fst * p.snd) (𝓝 (a, b)) (𝓝 (a * b)) := continuous_iff_continuous_at.mp has_continuous_mul.continuous_mul (a, b) @[to_additive] lemma filter.tendsto.mul {f : α → M} {g : α → M} {x : filter α} {a b : M} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, f x * g x) x (𝓝 (a * b)) := tendsto_mul.comp (hf.prod_mk_nhds hg) @[to_additive] lemma filter.tendsto.const_mul (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), b * f k) l (𝓝 (b * c)) := tendsto_const_nhds.mul h @[to_additive] lemma filter.tendsto.mul_const (b : M) {c : M} {f : α → M} {l : filter α} (h : tendsto (λ (k:α), f k) l (𝓝 c)) : tendsto (λ (k:α), f k * b) l (𝓝 (c * b)) := h.mul tendsto_const_nhds @[to_additive] lemma continuous_at.mul [topological_space α] {f : α → M} {g : α → M} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, f x * g x) x := hf.mul hg @[to_additive] lemma continuous_within_at.mul [topological_space α] {f : α → M} {g : α → M} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, f x * g x) s x := hf.mul hg @[to_additive] instance [topological_space N] [has_mul N] [has_continuous_mul N] : has_continuous_mul (M × N) := ⟨((continuous_fst.comp continuous_fst).mul (continuous_fst.comp continuous_snd)).prod_mk ((continuous_snd.comp continuous_fst).mul (continuous_snd.comp continuous_snd))⟩ @[to_additive] instance pi.has_continuous_mul {C : β → Type*} [∀ b, topological_space (C b)] [∀ b, has_mul (C b)] [∀ b, has_continuous_mul (C b)] : has_continuous_mul (Π b, C b) := { continuous_mul := continuous_pi (λ i, continuous.mul ((continuous_apply i).comp continuous_fst) ((continuous_apply i).comp continuous_snd)) } @[priority 100, to_additive] instance has_continuous_mul_of_discrete_topology [topological_space N] [has_mul N] [discrete_topology N] : has_continuous_mul N := ⟨continuous_of_discrete_topology⟩ open_locale filter open function @[to_additive] lemma has_continuous_mul.of_nhds_one {M : Type*} [monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) $ 𝓝 1) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) (hright : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x*x₀) (𝓝 1)) : has_continuous_mul M := ⟨begin rw continuous_iff_continuous_at, rintros ⟨x₀, y₀⟩, have key : (λ p : M × M, x₀ * p.1 * (p.2 * y₀)) = ((λ x, x₀*x) ∘ (λ x, x*y₀)) ∘ (uncurry (*)), { ext p, simp [uncurry, mul_assoc] }, have key₂ : (λ x, x₀*x) ∘ (λ x, y₀*x) = λ x, (x₀ *y₀)*x, { ext x, simp }, calc map (uncurry (*)) (𝓝 (x₀, y₀)) = map (uncurry (*)) (𝓝 x₀ ×ᶠ 𝓝 y₀) : by rw nhds_prod_eq ... = map (λ (p : M × M), x₀ * p.1 * (p.2 * y₀)) ((𝓝 1) ×ᶠ (𝓝 1)) : by rw [uncurry, hleft x₀, hright y₀, prod_map_map_eq, filter.map_map] ... = map ((λ x, x₀ * x) ∘ λ x, x * y₀) (map (uncurry (*)) (𝓝 1 ×ᶠ 𝓝 1)) : by { rw [key, ← filter.map_map], } ... ≤ map ((λ (x : M), x₀ * x) ∘ λ x, x * y₀) (𝓝 1) : map_mono hmul ... = 𝓝 (x₀*y₀) : by rw [← filter.map_map, ← hright, hleft y₀, filter.map_map, key₂, ← hleft] end⟩ @[to_additive] lemma has_continuous_mul_of_comm_of_nhds_one (M : Type*) [comm_monoid M] [topological_space M] (hmul : tendsto (uncurry ((*) : M → M → M)) (𝓝 1 ×ᶠ 𝓝 1) (𝓝 1)) (hleft : ∀ x₀ : M, 𝓝 x₀ = map (λ x, x₀*x) (𝓝 1)) : has_continuous_mul M := begin apply has_continuous_mul.of_nhds_one hmul hleft, intros x₀, simp_rw [mul_comm, hleft x₀] end end has_continuous_mul section has_continuous_mul variables [topological_space M] [monoid M] [has_continuous_mul M] @[to_additive] lemma submonoid.top_closure_mul_self_subset (s : submonoid M) : (closure (s : set M)) * closure (s : set M) ⊆ closure (s : set M) := calc (closure (s : set M)) * closure (s : set M) = (λ p : M × M, p.1 * p.2) '' (closure ((s : set M).prod s)) : by simp [closure_prod_eq] ... ⊆ closure ((λ p : M × M, p.1 * p.2) '' ((s : set M).prod s)) : image_closure_subset_closure_image continuous_mul ... = closure s : by simp [s.coe_mul_self_eq] @[to_additive] lemma submonoid.top_closure_mul_self_eq (s : submonoid M) : (closure (s : set M)) * closure (s : set M) = closure (s : set M) := subset.antisymm s.top_closure_mul_self_subset (λ x hx, ⟨x, 1, hx, subset_closure s.one_mem, mul_one _⟩) /-- The (topological-space) closure of a submonoid of a space `M` with `has_continuous_mul` is itself a submonoid. -/ @[to_additive "The (topological-space) closure of an additive submonoid of a space `M` with `has_continuous_add` is itself an additive submonoid."] def submonoid.topological_closure (s : submonoid M) : submonoid M := { carrier := closure (s : set M), one_mem' := subset_closure s.one_mem, mul_mem' := λ a b ha hb, s.top_closure_mul_self_subset ⟨a, b, ha, hb, rfl⟩ } @[to_additive] instance submonoid.topological_closure_has_continuous_mul (s : submonoid M) : has_continuous_mul (s.topological_closure) := { continuous_mul := begin apply continuous_induced_rng, change continuous (λ p : s.topological_closure × s.topological_closure, (p.1 : M) * (p.2 : M)), continuity, end } lemma submonoid.submonoid_topological_closure (s : submonoid M) : s ≤ s.topological_closure := subset_closure lemma submonoid.is_closed_topological_closure (s : submonoid M) : is_closed (s.topological_closure : set M) := by convert is_closed_closure lemma submonoid.topological_closure_minimal (s : submonoid M) {t : submonoid M} (h : s ≤ t) (ht : is_closed (t : set M)) : s.topological_closure ≤ t := closure_minimal h ht @[to_additive exists_open_nhds_zero_half] lemma exists_open_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ ∀ (v ∈ V) (w ∈ V), v * w ∈ s := have ((λa:M×M, a.1 * a.2) ⁻¹' s) ∈ 𝓝 ((1, 1) : M × M), from tendsto_mul (by simpa only [one_mul] using hs), by simpa only [prod_subset_iff] using exists_nhds_square this @[to_additive exists_nhds_zero_half] lemma exists_nhds_one_split {s : set M} (hs : s ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ (v ∈ V) (w ∈ V), v * w ∈ s := let ⟨V, Vo, V1, hV⟩ := exists_open_nhds_one_split hs in ⟨V, mem_nhds_sets Vo V1, hV⟩ @[to_additive exists_nhds_zero_quarter] lemma exists_nhds_one_split4 {u : set M} (hu : u ∈ 𝓝 (1 : M)) : ∃ V ∈ 𝓝 (1 : M), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_one_split hu with ⟨W, W1, h⟩, rcases exists_nhds_one_split W1 with ⟨V, V1, h'⟩, use [V, V1], intros v w s t v_in w_in s_in t_in, simpa only [mul_assoc] using h _ (h' v v_in w w_in) _ (h' s s_in t t_in) end /-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1` such that `VV ⊆ U`. -/ @[to_additive "Given a open neighborhood `U` of `0` there is a open neighborhood `V` of `0` such that `V + V ⊆ U`."] lemma exists_open_nhds_one_mul_subset {U : set M} (hU : U ∈ 𝓝 (1 : M)) : ∃ V : set M, is_open V ∧ (1 : M) ∈ V ∧ V * V ⊆ U := begin rcases exists_open_nhds_one_split hU with ⟨V, Vo, V1, hV⟩, use [V, Vo, V1], rintros _ ⟨x, y, hx, hy, rfl⟩, exact hV _ hx _ hy end @[to_additive] lemma tendsto_list_prod {f : β → α → M} {x : filter α} {a : β → M} : ∀l:list β, (∀c∈l, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (l.map (λc, f c b)).prod) x (𝓝 ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp only [list.map_cons, list.prod_cons], exact (h f (list.mem_cons_self _ _)).mul (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive] lemma continuous_list_prod [topological_space α] {f : β → α → M} (l : list β) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c a)).prod) := continuous_iff_continuous_at.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_continuous_at.1 (h c hc) x -- @[to_additive continuous_smul] @[continuity] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : M, a ^ n) | 0 := by simpa using continuous_const | (k+1) := show continuous (λ (a : M), a * a ^ k), from continuous_id.mul (continuous_pow _) @[continuity] lemma continuous.pow {f : α → M} [topological_space α] (h : continuous f) (n : ℕ) : continuous (λ b, (f b) ^ n) := continuous.comp (continuous_pow n) h end has_continuous_mul section variables [topological_space M] [comm_monoid M] @[to_additive] lemma submonoid.mem_nhds_one (S : submonoid M) (oS : is_open (S : set M)) : (S : set M) ∈ 𝓝 (1 : M) := mem_nhds_sets oS S.one_mem variable [has_continuous_mul M] @[to_additive] lemma tendsto_multiset_prod {f : β → α → M} {x : filter α} {a : β → M} (s : multiset β) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (𝓝 ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive] lemma tendsto_finset_prod {f : β → α → M} {x : filter α} {a : β → M} (s : finset β) : (∀c∈s, tendsto (f c) x (𝓝 (a c))) → tendsto (λb, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := tendsto_multiset_prod _ @[to_additive, continuity] lemma continuous_multiset_prod [topological_space α] {f : β → α → M} (s : multiset β) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } attribute [continuity] continuous_multiset_sum @[continuity, to_additive] lemma continuous_finset_prod [topological_space α] {f : β → α → M} (s : finset β) : (∀c∈s, continuous (f c)) → continuous (λa, ∏ c in s, f c a) := continuous_multiset_prod _ -- should `to_additive` be doing this? attribute [continuity] continuous_finset_sum end instance additive.has_continuous_add {M} [h : topological_space M] [has_mul M] [has_continuous_mul M] : @has_continuous_add (additive M) h _ := { continuous_add := @continuous_mul M _ _ _ } instance multiplicative.has_continuous_mul {M} [h : topological_space M] [has_add M] [has_continuous_add M] : @has_continuous_mul (multiplicative M) h _ := { continuous_mul := @continuous_add M _ _ _ }
53acf7364ffdea2b3547f6f4f05ed23f84479a37
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/int.lean
786f3f7d5fe07ea264f3a5fde8a934f999cd9890
[ "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,522
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 analysis.normed.field.basic /-! # The integers as normed ring This file contains basic facts about the integers as normed ring. Recall that `‖n‖` denotes the norm of `n` as real number. This norm is always nonnegative, so we can bundle the norm together with this fact, to obtain a term of type `nnreal` (the nonnegative real numbers). The resulting nonnegative real number is denoted by `‖n‖₊`. -/ open_locale big_operators namespace int lemma nnnorm_coe_units (e : ℤˣ) : ‖(e : ℤ)‖₊ = 1 := begin obtain (rfl|rfl) := int.units_eq_one_or e; simp only [units.coe_neg_one, units.coe_one, nnnorm_neg, nnnorm_one], end lemma norm_coe_units (e : ℤˣ) : ‖(e : ℤ)‖ = 1 := by rw [← coe_nnnorm, int.nnnorm_coe_units, nnreal.coe_one] @[simp] lemma nnnorm_coe_nat (n : ℕ) : ‖(n : ℤ)‖₊ = n := real.nnnorm_coe_nat _ @[simp] lemma norm_coe_nat (n : ℕ) : ‖(n : ℤ)‖ = n := real.norm_coe_nat _ @[simp] lemma to_nat_add_to_nat_neg_eq_nnnorm (n : ℤ) : ↑(n.to_nat) + ↑((-n).to_nat) = ‖n‖₊ := by rw [← nat.cast_add, to_nat_add_to_nat_neg_eq_nat_abs, nnreal.coe_nat_abs] @[simp] lemma to_nat_add_to_nat_neg_eq_norm (n : ℤ) : ↑(n.to_nat) + ↑((-n).to_nat) = ‖n‖ := by simpa only [nnreal.coe_nat_cast, nnreal.coe_add] using congr_arg (coe : _ → ℝ) (to_nat_add_to_nat_neg_eq_nnnorm n) end int
73fa391622e85ab3b5b4f3f78722bcf6c3387a97
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/ring_theory/coprime.lean
5701c20d9d0f9df26c3c4c956cacded9b9bf8cd6
[ "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
13,669
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Ken Lee, Chris Hughes -/ import algebra.big_operators.basic import data.fintype.basic import data.int.gcd import data.set.pairwise import tactic.ring /-! # Coprime elements of a ring ## Main definitions * `is_coprime x y`: that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. -/ open_locale classical big_operators universes u v section comm_semiring variables {R : Type u} [comm_semiring R] (x y z : R) /-- The proposition that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. -/ @[simp] def is_coprime : Prop := ∃ a b, a * x + b * y = 1 theorem nat.is_coprime_iff_coprime {m n : ℕ} : is_coprime (m : ℤ) n ↔ nat.coprime m n := ⟨λ ⟨a, b, H⟩, nat.eq_one_of_dvd_one $ int.coe_nat_dvd.1 $ by { rw [int.coe_nat_one, ← H], exact dvd_add (dvd_mul_of_dvd_right (int.coe_nat_dvd.2 $ nat.gcd_dvd_left m n) _) (dvd_mul_of_dvd_right (int.coe_nat_dvd.2 $ nat.gcd_dvd_right m n) _) }, λ H, ⟨nat.gcd_a m n, nat.gcd_b m n, by rw [mul_comm _ (m : ℤ), mul_comm _ (n : ℤ), ← nat.gcd_eq_gcd_ab, show _ = _, from H, int.coe_nat_one]⟩⟩ variables {x y z} theorem is_coprime.symm (H : is_coprime x y) : is_coprime y x := let ⟨a, b, H⟩ := H in ⟨b, a, by rw [add_comm, H]⟩ theorem is_coprime_comm : is_coprime x y ↔ is_coprime y x := ⟨is_coprime.symm, is_coprime.symm⟩ theorem is_coprime_self : is_coprime x x ↔ is_unit x := ⟨λ ⟨a, b, h⟩, is_unit_of_mul_eq_one x (a + b) $ by rwa [mul_comm, add_mul], λ h, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 h in ⟨b, 0, by rwa [zero_mul, add_zero]⟩⟩ theorem is_coprime_zero_left : is_coprime 0 x ↔ is_unit x := ⟨λ ⟨a, b, H⟩, is_unit_of_mul_eq_one x b $ by rwa [mul_zero, zero_add, mul_comm] at H, λ H, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 H in ⟨1, b, by rwa [one_mul, zero_add]⟩⟩ theorem is_coprime_zero_right : is_coprime x 0 ↔ is_unit x := is_coprime_comm.trans is_coprime_zero_left lemma not_coprime_zero_zero [nontrivial R] : ¬ is_coprime (0 : R) 0 := mt is_coprime_zero_right.mp not_is_unit_zero theorem is_coprime_one_left : is_coprime 1 x := ⟨1, 0, by rw [one_mul, zero_mul, add_zero]⟩ theorem is_coprime_one_right : is_coprime x 1 := ⟨0, 1, by rw [one_mul, zero_mul, zero_add]⟩ theorem is_coprime.dvd_of_dvd_mul_right (H1 : is_coprime x z) (H2 : x ∣ y * z) : x ∣ y := let ⟨a, b, H⟩ := H1 in by { rw [← mul_one y, ← H, mul_add, ← mul_assoc, mul_left_comm], exact dvd_add (dvd_mul_left _ _) (H2.mul_left _) } theorem is_coprime.dvd_of_dvd_mul_left (H1 : is_coprime x y) (H2 : x ∣ y * z) : x ∣ z := let ⟨a, b, H⟩ := H1 in by { rw [← one_mul z, ← H, add_mul, mul_right_comm, mul_assoc b], exact dvd_add (dvd_mul_left _ _) (H2.mul_left _) } theorem is_coprime.mul_left (H1 : is_coprime x z) (H2 : is_coprime y z) : is_coprime (x * y) z := let ⟨a, b, h1⟩ := H1, ⟨c, d, h2⟩ := H2 in ⟨a * c, a * x * d + b * c * y + b * d * z, calc a * c * (x * y) + (a * x * d + b * c * y + b * d * z) * z = (a * x + b * z) * (c * y + d * z) : by ring ... = 1 : by rw [h1, h2, mul_one]⟩ theorem is_coprime.mul_right (H1 : is_coprime x y) (H2 : is_coprime x z) : is_coprime x (y * z) := by { rw is_coprime_comm at H1 H2 ⊢, exact H1.mul_left H2 } variables {I : Type v} {s : I → R} {t : finset I} theorem is_coprime.prod_left : (∀ i ∈ t, is_coprime (s i) x) → is_coprime (∏ i in t, s i) x := finset.induction_on t (λ _, is_coprime_one_left) $ λ b t hbt ih H, by { rw finset.prod_insert hbt, rw finset.forall_mem_insert at H, exact H.1.mul_left (ih H.2) } theorem is_coprime.prod_right : (∀ i ∈ t, is_coprime x (s i)) → is_coprime x (∏ i in t, s i) := by simpa only [is_coprime_comm] using is_coprime.prod_left theorem is_coprime.mul_dvd (H : is_coprime x y) (H1 : x ∣ z) (H2 : y ∣ z) : x * y ∣ z := begin obtain ⟨a, b, h⟩ := H, rw [← mul_one z, ← h, mul_add], apply dvd_add, { rw [mul_comm z, mul_assoc], exact (mul_dvd_mul_left _ H2).mul_left _ }, { rw [mul_comm b, ← mul_assoc], exact (mul_dvd_mul_right H1 _).mul_right _ } end theorem finset.prod_dvd_of_coprime : ∀ (Hs : set.pairwise_on (↑t : set I) (is_coprime on s)) (Hs1 : ∀ i ∈ t, s i ∣ z), ∏ x in t, s x ∣ z := finset.induction_on t (λ _ _, one_dvd z) begin intros a r har ih Hs Hs1, rw finset.prod_insert har, have aux1 : a ∈ (↑(insert a r) : set I) := finset.mem_insert_self a r, refine (is_coprime.prod_right $ λ i hir, Hs a aux1 i _ (by { rintro rfl, exact har hir })).mul_dvd (Hs1 a aux1) (ih (Hs.mono _) $ λ i hi, Hs1 i (finset.mem_insert_of_mem hi)), { exact finset.mem_insert_of_mem hir }, { simp only [finset.coe_insert, set.subset_insert] } end theorem fintype.prod_dvd_of_coprime [fintype I] (Hs : pairwise (is_coprime on s)) (Hs1 : ∀ i, s i ∣ z) : ∏ x, s x ∣ z := finset.prod_dvd_of_coprime (Hs.pairwise_on _) (λ i _, Hs1 i) theorem is_coprime.of_mul_left_left (H : is_coprime (x * y) z) : is_coprime x z := let ⟨a, b, h⟩ := H in ⟨a * y, b, by rwa [mul_right_comm, mul_assoc]⟩ theorem is_coprime.of_mul_left_right (H : is_coprime (x * y) z) : is_coprime y z := by { rw mul_comm at H, exact H.of_mul_left_left } theorem is_coprime.of_mul_right_left (H : is_coprime x (y * z)) : is_coprime x y := by { rw is_coprime_comm at H ⊢, exact H.of_mul_left_left } theorem is_coprime.of_mul_right_right (H : is_coprime x (y * z)) : is_coprime x z := by { rw mul_comm at H, exact H.of_mul_right_left } theorem is_coprime.mul_left_iff : is_coprime (x * y) z ↔ is_coprime x z ∧ is_coprime y z := ⟨λ H, ⟨H.of_mul_left_left, H.of_mul_left_right⟩, λ ⟨H1, H2⟩, H1.mul_left H2⟩ theorem is_coprime.mul_right_iff : is_coprime x (y * z) ↔ is_coprime x y ∧ is_coprime x z := by rw [is_coprime_comm, is_coprime.mul_left_iff, is_coprime_comm, @is_coprime_comm _ _ z] theorem is_coprime.prod_left_iff : is_coprime (∏ i in t, s i) x ↔ ∀ i ∈ t, is_coprime (s i) x := finset.induction_on t (iff_of_true is_coprime_one_left $ λ _, false.elim) $ λ b t hbt ih, by rw [finset.prod_insert hbt, is_coprime.mul_left_iff, ih, finset.forall_mem_insert] theorem is_coprime.prod_right_iff : is_coprime x (∏ i in t, s i) ↔ ∀ i ∈ t, is_coprime x (s i) := by simpa only [is_coprime_comm] using is_coprime.prod_left_iff theorem is_coprime.of_prod_left (H1 : is_coprime (∏ i in t, s i) x) (i : I) (hit : i ∈ t) : is_coprime (s i) x := is_coprime.prod_left_iff.1 H1 i hit theorem is_coprime.of_prod_right (H1 : is_coprime x (∏ i in t, s i)) (i : I) (hit : i ∈ t) : is_coprime x (s i) := is_coprime.prod_right_iff.1 H1 i hit variables {m n : ℕ} theorem is_coprime.pow_left (H : is_coprime x y) : is_coprime (x ^ m) y := by { rw [← finset.card_range m, ← finset.prod_const], exact is_coprime.prod_left (λ _ _, H) } theorem is_coprime.pow_right (H : is_coprime x y) : is_coprime x (y ^ n) := by { rw [← finset.card_range n, ← finset.prod_const], exact is_coprime.prod_right (λ _ _, H) } theorem is_coprime.pow (H : is_coprime x y) : is_coprime (x ^ m) (y ^ n) := H.pow_left.pow_right theorem is_coprime.pow_left_iff (hm : 0 < m) : is_coprime (x ^ m) y ↔ is_coprime x y := begin refine ⟨λ h, _, is_coprime.pow_left⟩, rw [← finset.card_range m, ← finset.prod_const] at h, exact h.of_prod_left 0 (finset.mem_range.mpr hm), end theorem is_coprime.pow_right_iff (hm : 0 < m) : is_coprime x (y ^ m) ↔ is_coprime x y := is_coprime_comm.trans $ (is_coprime.pow_left_iff hm).trans $ is_coprime_comm theorem is_coprime.pow_iff (hm : 0 < m) (hn : 0 < n) : is_coprime (x ^ m) (y ^ n) ↔ is_coprime x y := (is_coprime.pow_left_iff hm).trans $ is_coprime.pow_right_iff hn theorem is_coprime.of_coprime_of_dvd_left (h : is_coprime y z) (hdvd : x ∣ y) : is_coprime x z := begin obtain ⟨d, rfl⟩ := hdvd, exact is_coprime.of_mul_left_left h end theorem is_coprime.of_coprime_of_dvd_right (h : is_coprime z y) (hdvd : x ∣ y) : is_coprime z x := (h.symm.of_coprime_of_dvd_left hdvd).symm theorem is_coprime.is_unit_of_dvd (H : is_coprime x y) (d : x ∣ y) : is_unit x := let ⟨k, hk⟩ := d in is_coprime_self.1 $ is_coprime.of_mul_right_left $ show is_coprime x (x * k), from hk ▸ H theorem is_coprime.is_unit_of_dvd' {a b x : R} (h : is_coprime a b) (ha : x ∣ a) (hb : x ∣ b) : is_unit x := (h.of_coprime_of_dvd_left ha).is_unit_of_dvd hb theorem is_coprime.map (H : is_coprime x y) {S : Type v} [comm_semiring S] (f : R →+* S) : is_coprime (f x) (f y) := let ⟨a, b, h⟩ := H in ⟨f a, f b, by rw [← f.map_mul, ← f.map_mul, ← f.map_add, h, f.map_one]⟩ variables {x y z} lemma is_coprime.of_add_mul_left_left (h : is_coprime (x + y * z) y) : is_coprime x y := let ⟨a, b, H⟩ := h in ⟨a, a * z + b, by simpa only [add_mul, mul_add, add_assoc, add_comm, add_left_comm, mul_assoc, mul_comm, mul_left_comm] using H⟩ lemma is_coprime.of_add_mul_right_left (h : is_coprime (x + z * y) y) : is_coprime x y := by { rw mul_comm at h, exact h.of_add_mul_left_left } lemma is_coprime.of_add_mul_left_right (h : is_coprime x (y + x * z)) : is_coprime x y := by { rw is_coprime_comm at h ⊢, exact h.of_add_mul_left_left } lemma is_coprime.of_add_mul_right_right (h : is_coprime x (y + z * x)) : is_coprime x y := by { rw mul_comm at h, exact h.of_add_mul_left_right } lemma is_coprime.of_mul_add_left_left (h : is_coprime (y * z + x) y) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_left_left } lemma is_coprime.of_mul_add_right_left (h : is_coprime (z * y + x) y) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_right_left } lemma is_coprime.of_mul_add_left_right (h : is_coprime x (x * z + y)) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_left_right } lemma is_coprime.of_mul_add_right_right (h : is_coprime x (z * x + y)) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_right_right } end comm_semiring namespace is_coprime section comm_ring variables {R : Type u} [comm_ring R] lemma add_mul_left_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (x + y * z) y := @of_add_mul_left_left R _ _ _ (-z) $ by simpa only [mul_neg_eq_neg_mul_symm, add_neg_cancel_right] using h lemma add_mul_right_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (x + z * y) y := by { rw mul_comm, exact h.add_mul_left_left z } lemma add_mul_left_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (y + x * z) := by { rw is_coprime_comm, exact h.symm.add_mul_left_left z } lemma add_mul_right_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (y + z * x) := by { rw is_coprime_comm, exact h.symm.add_mul_right_left z } lemma mul_add_left_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (y * z + x) y := by { rw add_comm, exact h.add_mul_left_left z } lemma mul_add_right_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (z * y + x) y := by { rw add_comm, exact h.add_mul_right_left z } lemma mul_add_left_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (x * z + y) := by { rw add_comm, exact h.add_mul_left_right z } lemma mul_add_right_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (z * x + y) := by { rw add_comm, exact h.add_mul_right_right z } lemma add_mul_left_left_iff {x y z : R} : is_coprime (x + y * z) y ↔ is_coprime x y := ⟨of_add_mul_left_left, λ h, h.add_mul_left_left z⟩ lemma add_mul_right_left_iff {x y z : R} : is_coprime (x + z * y) y ↔ is_coprime x y := ⟨of_add_mul_right_left, λ h, h.add_mul_right_left z⟩ lemma add_mul_left_right_iff {x y z : R} : is_coprime x (y + x * z) ↔ is_coprime x y := ⟨of_add_mul_left_right, λ h, h.add_mul_left_right z⟩ lemma add_mul_right_right_iff {x y z : R} : is_coprime x (y + z * x) ↔ is_coprime x y := ⟨of_add_mul_right_right, λ h, h.add_mul_right_right z⟩ lemma mul_add_left_left_iff {x y z : R} : is_coprime (y * z + x) y ↔ is_coprime x y := ⟨of_mul_add_left_left, λ h, h.mul_add_left_left z⟩ lemma mul_add_right_left_iff {x y z : R} : is_coprime (z * y + x) y ↔ is_coprime x y := ⟨of_mul_add_right_left, λ h, h.mul_add_right_left z⟩ lemma mul_add_left_right_iff {x y z : R} : is_coprime x (x * z + y) ↔ is_coprime x y := ⟨of_mul_add_left_right, λ h, h.mul_add_left_right z⟩ lemma mul_add_right_right_iff {x y z : R} : is_coprime x (z * x + y) ↔ is_coprime x y := ⟨of_mul_add_right_right, λ h, h.mul_add_right_right z⟩ lemma neg_left {x y : R} (h : is_coprime x y) : is_coprime (-x) y := begin obtain ⟨a, b, h⟩ := h, use [-a, b], rwa neg_mul_neg, end lemma neg_left_iff (x y : R) : is_coprime (-x) y ↔ is_coprime x y := ⟨λ h, neg_neg x ▸ h.neg_left, neg_left⟩ lemma neg_right {x y : R} (h : is_coprime x y) : is_coprime x (-y) := h.symm.neg_left.symm lemma neg_right_iff (x y : R) : is_coprime x (-y) ↔ is_coprime x y := ⟨λ h, neg_neg y ▸ h.neg_right, neg_right⟩ lemma neg_neg {x y : R} (h : is_coprime x y) : is_coprime (-x) (-y) := h.neg_left.neg_right lemma neg_neg_iff (x y : R) : is_coprime (-x) (-y) ↔ is_coprime x y := (neg_left_iff _ _).trans (neg_right_iff _ _) end comm_ring end is_coprime
bd59cdfe19d178e60cc6f9a2ca0e64e5665ada8b
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/expandAbbrevAtIsClass.lean
575c3921315236dfc39d8c4e5aa9f41aa6c6e860
[ "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
193
lean
def one (α : Type u) [OfNat α (natLit! 1)] : α := 1 abbrev HasOne (α : Type u) := OfNat α (natLit! 1) def one' (α : Type u) [HasOne α] : α := 1 example : HasOne Nat := inferInstance
bd49a080b3652b54b0b596d118d3092ff58a9983
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/dynamics/periodic_pts.lean
353804e7661ea24df3c0467e62730b3c2138c21a
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
24,673
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import algebra.hom.iterate import data.list.cycle import data.pnat.basic import data.nat.prime import dynamics.fixed_points.basic import group_theory.group_action.group /-! # Periodic points > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A point `x : α` is a periodic point of `f : α → α` of period `n` if `f^[n] x = x`. ## Main definitions * `is_periodic_pt f n x` : `x` is a periodic point of `f` of period `n`, i.e. `f^[n] x = x`. We do not require `n > 0` in the definition. * `pts_of_period f n` : the set `{x | is_periodic_pt f n x}`. Note that `n` is not required to be the minimal period of `x`. * `periodic_pts f` : the set of all periodic points of `f`. * `minimal_period f x` : the minimal period of a point `x` under an endomorphism `f` or zero if `x` is not a periodic point of `f`. * `orbit f x`: the cycle `[x, f x, f (f x), ...]` for a periodic point. ## Main statements We provide “dot syntax”-style operations on terms of the form `h : is_periodic_pt f n x` including arithmetic operations on `n` and `h.map (hg : semiconj_by g f f')`. We also prove that `f` is bijective on each set `pts_of_period f n` and on `periodic_pts f`. Finally, we prove that `x` is a periodic point of `f` of period `n` if and only if `minimal_period f x | n`. ## References * https://en.wikipedia.org/wiki/Periodic_point -/ open set namespace function variables {α : Type*} {β : Type*} {f fa : α → α} {fb : β → β} {x y : α} {m n : ℕ} /-- A point `x` is a periodic point of `f : α → α` of period `n` if `f^[n] x = x`. Note that we do not require `0 < n` in this definition. Many theorems about periodic points need this assumption. -/ def is_periodic_pt (f : α → α) (n : ℕ) (x : α) := is_fixed_pt (f^[n]) x /-- A fixed point of `f` is a periodic point of `f` of any prescribed period. -/ lemma is_fixed_pt.is_periodic_pt (hf : is_fixed_pt f x) (n : ℕ) : is_periodic_pt f n x := hf.iterate n /-- For the identity map, all points are periodic. -/ lemma is_periodic_id (n : ℕ) (x : α) : is_periodic_pt id n x := (is_fixed_pt_id x).is_periodic_pt n /-- Any point is a periodic point of period `0`. -/ lemma is_periodic_pt_zero (f : α → α) (x : α) : is_periodic_pt f 0 x := is_fixed_pt_id x namespace is_periodic_pt instance [decidable_eq α] {f : α → α} {n : ℕ} {x : α} : decidable (is_periodic_pt f n x) := is_fixed_pt.decidable protected lemma is_fixed_pt (hf : is_periodic_pt f n x) : is_fixed_pt (f^[n]) x := hf protected lemma map (hx : is_periodic_pt fa n x) {g : α → β} (hg : semiconj g fa fb) : is_periodic_pt fb n (g x) := hx.map (hg.iterate_right n) lemma apply_iterate (hx : is_periodic_pt f n x) (m : ℕ) : is_periodic_pt f n (f^[m] x) := hx.map $ commute.iterate_self f m protected lemma apply (hx : is_periodic_pt f n x) : is_periodic_pt f n (f x) := hx.apply_iterate 1 protected lemma add (hn : is_periodic_pt f n x) (hm : is_periodic_pt f m x) : is_periodic_pt f (n + m) x := by { rw [is_periodic_pt, iterate_add], exact hn.comp hm } lemma left_of_add (hn : is_periodic_pt f (n + m) x) (hm : is_periodic_pt f m x) : is_periodic_pt f n x := by { rw [is_periodic_pt, iterate_add] at hn, exact hn.left_of_comp hm } lemma right_of_add (hn : is_periodic_pt f (n + m) x) (hm : is_periodic_pt f n x) : is_periodic_pt f m x := by { rw add_comm at hn, exact hn.left_of_add hm } protected lemma sub (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (m - n) x := begin cases le_total n m with h h, { refine left_of_add _ hn, rwa [tsub_add_cancel_of_le h] }, { rw [tsub_eq_zero_iff_le.mpr h], apply is_periodic_pt_zero } end protected lemma mul_const (hm : is_periodic_pt f m x) (n : ℕ) : is_periodic_pt f (m * n) x := by simp only [is_periodic_pt, iterate_mul, hm.is_fixed_pt.iterate n] protected lemma const_mul (hm : is_periodic_pt f m x) (n : ℕ) : is_periodic_pt f (n * m) x := by simp only [mul_comm n, hm.mul_const n] lemma trans_dvd (hm : is_periodic_pt f m x) {n : ℕ} (hn : m ∣ n) : is_periodic_pt f n x := let ⟨k, hk⟩ := hn in hk.symm ▸ hm.mul_const k protected lemma iterate (hf : is_periodic_pt f n x) (m : ℕ) : is_periodic_pt (f^[m]) n x := begin rw [is_periodic_pt, ← iterate_mul, mul_comm, iterate_mul], exact hf.is_fixed_pt.iterate m end lemma comp {g : α → α} (hco : commute f g) (hf : is_periodic_pt f n x) (hg : is_periodic_pt g n x) : is_periodic_pt (f ∘ g) n x := by { rw [is_periodic_pt, hco.comp_iterate], exact hf.comp hg } lemma comp_lcm {g : α → α} (hco : commute f g) (hf : is_periodic_pt f m x) (hg : is_periodic_pt g n x) : is_periodic_pt (f ∘ g) (nat.lcm m n) x := (hf.trans_dvd $ nat.dvd_lcm_left _ _).comp hco (hg.trans_dvd $ nat.dvd_lcm_right _ _) lemma left_of_comp {g : α → α} (hco : commute f g) (hfg : is_periodic_pt (f ∘ g) n x) (hg : is_periodic_pt g n x) : is_periodic_pt f n x := begin rw [is_periodic_pt, hco.comp_iterate] at hfg, exact hfg.left_of_comp hg end lemma iterate_mod_apply (h : is_periodic_pt f n x) (m : ℕ) : f^[m % n] x = (f^[m] x) := by conv_rhs { rw [← nat.mod_add_div m n, iterate_add_apply, (h.mul_const _).eq] } protected lemma mod (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (m % n) x := (hn.iterate_mod_apply m).trans hm protected lemma gcd (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) : is_periodic_pt f (m.gcd n) x := begin revert hm hn, refine nat.gcd.induction m n (λ n h0 hn, _) (λ m n hm ih hm hn, _), { rwa [nat.gcd_zero_left], }, { rw [nat.gcd_rec], exact ih (hn.mod hm) hm } end /-- If `f` sends two periodic points `x` and `y` of the same positive period to the same point, then `x = y`. For a similar statement about points of different periods see `eq_of_apply_eq`. -/ lemma eq_of_apply_eq_same (hx : is_periodic_pt f n x) (hy : is_periodic_pt f n y) (hn : 0 < n) (h : f x = f y) : x = y := by rw [← hx.eq, ← hy.eq, ← iterate_pred_comp_of_pos f hn, comp_app, h] /-- If `f` sends two periodic points `x` and `y` of positive periods to the same point, then `x = y`. -/ lemma eq_of_apply_eq (hx : is_periodic_pt f m x) (hy : is_periodic_pt f n y) (hm : 0 < m) (hn : 0 < n) (h : f x = f y) : x = y := (hx.mul_const n).eq_of_apply_eq_same (hy.const_mul m) (mul_pos hm hn) h end is_periodic_pt /-- The set of periodic points of a given (possibly non-minimal) period. -/ def pts_of_period (f : α → α) (n : ℕ) : set α := {x : α | is_periodic_pt f n x} @[simp] lemma mem_pts_of_period : x ∈ pts_of_period f n ↔ is_periodic_pt f n x := iff.rfl lemma semiconj.maps_to_pts_of_period {g : α → β} (h : semiconj g fa fb) (n : ℕ) : maps_to g (pts_of_period fa n) (pts_of_period fb n) := (h.iterate_right n).maps_to_fixed_pts lemma bij_on_pts_of_period (f : α → α) {n : ℕ} (hn : 0 < n) : bij_on f (pts_of_period f n) (pts_of_period f n) := ⟨(commute.refl f).maps_to_pts_of_period n, λ x hx y hy hxy, hx.eq_of_apply_eq_same hy hn hxy, λ x hx, ⟨f^[n.pred] x, hx.apply_iterate _, by rw [← comp_app f, comp_iterate_pred_of_pos f hn, hx.eq]⟩⟩ lemma directed_pts_of_period_pnat (f : α → α) : directed (⊆) (λ n : ℕ+, pts_of_period f n) := λ m n, ⟨m * n, λ x hx, hx.mul_const n, λ x hx, hx.const_mul m⟩ /-- The set of periodic points of a map `f : α → α`. -/ def periodic_pts (f : α → α) : set α := {x : α | ∃ n > 0, is_periodic_pt f n x} lemma mk_mem_periodic_pts (hn : 0 < n) (hx : is_periodic_pt f n x) : x ∈ periodic_pts f := ⟨n, hn, hx⟩ lemma mem_periodic_pts : x ∈ periodic_pts f ↔ ∃ n > 0, is_periodic_pt f n x := iff.rfl lemma is_periodic_pt_of_mem_periodic_pts_of_is_periodic_pt_iterate (hx : x ∈ periodic_pts f) (hm : is_periodic_pt f m (f^[n] x)) : is_periodic_pt f m x := begin rcases hx with ⟨r, hr, hr'⟩, convert (hm.apply_iterate ((n / r + 1) * r - n)).eq, suffices : n ≤ (n / r + 1) * r, { rw [←iterate_add_apply, nat.sub_add_cancel this, iterate_mul, (hr'.iterate _).eq] }, rw [add_mul, one_mul], exact (nat.lt_div_mul_add hr).le end variable (f) lemma bUnion_pts_of_period : (⋃ n > 0, pts_of_period f n) = periodic_pts f := set.ext $ λ x, by simp [mem_periodic_pts] lemma Union_pnat_pts_of_period : (⋃ n : ℕ+, pts_of_period f n) = periodic_pts f := supr_subtype.trans $ bUnion_pts_of_period f lemma bij_on_periodic_pts : bij_on f (periodic_pts f) (periodic_pts f) := Union_pnat_pts_of_period f ▸ bij_on_Union_of_directed (directed_pts_of_period_pnat f) (λ i, bij_on_pts_of_period f i.pos) variable {f} lemma semiconj.maps_to_periodic_pts {g : α → β} (h : semiconj g fa fb) : maps_to g (periodic_pts fa) (periodic_pts fb) := λ x ⟨n, hn, hx⟩, ⟨n, hn, hx.map h⟩ open_locale classical noncomputable theory /-- Minimal period of a point `x` under an endomorphism `f`. If `x` is not a periodic point of `f`, then `minimal_period f x = 0`. -/ def minimal_period (f : α → α) (x : α) := if h : x ∈ periodic_pts f then nat.find h else 0 lemma is_periodic_pt_minimal_period (f : α → α) (x : α) : is_periodic_pt f (minimal_period f x) x := begin delta minimal_period, split_ifs with hx, { exact (nat.find_spec hx).snd }, { exact is_periodic_pt_zero f x } end @[simp] lemma iterate_minimal_period : f^[minimal_period f x] x = x := is_periodic_pt_minimal_period f x @[simp] lemma iterate_add_minimal_period_eq : f^[n + minimal_period f x] x = (f^[n] x) := by { rw iterate_add_apply, congr, exact is_periodic_pt_minimal_period f x } @[simp] lemma iterate_mod_minimal_period_eq : f^[n % minimal_period f x] x = (f^[n] x) := (is_periodic_pt_minimal_period f x).iterate_mod_apply n lemma minimal_period_pos_of_mem_periodic_pts (hx : x ∈ periodic_pts f) : 0 < minimal_period f x := by simp only [minimal_period, dif_pos hx, (nat.find_spec hx).fst.lt] lemma minimal_period_eq_zero_of_nmem_periodic_pts (hx : x ∉ periodic_pts f) : minimal_period f x = 0 := by simp only [minimal_period, dif_neg hx] lemma is_periodic_pt.minimal_period_pos (hn : 0 < n) (hx : is_periodic_pt f n x) : 0 < minimal_period f x := minimal_period_pos_of_mem_periodic_pts $ mk_mem_periodic_pts hn hx lemma minimal_period_pos_iff_mem_periodic_pts : 0 < minimal_period f x ↔ x ∈ periodic_pts f := ⟨not_imp_not.1 $ λ h, by simp only [minimal_period, dif_neg h, lt_irrefl 0, not_false_iff], minimal_period_pos_of_mem_periodic_pts⟩ lemma minimal_period_eq_zero_iff_nmem_periodic_pts : minimal_period f x = 0 ↔ x ∉ periodic_pts f := by rw [←minimal_period_pos_iff_mem_periodic_pts, not_lt, nonpos_iff_eq_zero] lemma is_periodic_pt.minimal_period_le (hn : 0 < n) (hx : is_periodic_pt f n x) : minimal_period f x ≤ n := begin rw [minimal_period, dif_pos (mk_mem_periodic_pts hn hx)], exact nat.find_min' (mk_mem_periodic_pts hn hx) ⟨hn, hx⟩ end lemma minimal_period_apply_iterate (hx : x ∈ periodic_pts f) (n : ℕ) : minimal_period f (f^[n] x) = minimal_period f x := begin apply (is_periodic_pt.minimal_period_le (minimal_period_pos_of_mem_periodic_pts hx) _).antisymm ((is_periodic_pt_of_mem_periodic_pts_of_is_periodic_pt_iterate hx (is_periodic_pt_minimal_period f _)).minimal_period_le (minimal_period_pos_of_mem_periodic_pts _)), { exact (is_periodic_pt_minimal_period f x).apply_iterate n, }, { rcases hx with ⟨m, hm, hx⟩, exact ⟨m, hm, hx.apply_iterate n⟩ } end lemma minimal_period_apply (hx : x ∈ periodic_pts f) : minimal_period f (f x) = minimal_period f x := minimal_period_apply_iterate hx 1 lemma le_of_lt_minimal_period_of_iterate_eq {m n : ℕ} (hm : m < minimal_period f x) (hmn : f^[m] x = (f^[n] x)) : m ≤ n := begin by_contra' hmn', rw [←nat.add_sub_of_le hmn'.le, add_comm, iterate_add_apply] at hmn, exact ((is_periodic_pt.minimal_period_le (tsub_pos_of_lt hmn') (is_periodic_pt_of_mem_periodic_pts_of_is_periodic_pt_iterate (minimal_period_pos_iff_mem_periodic_pts.1 ((zero_le m).trans_lt hm)) hmn)).trans (nat.sub_le m n)).not_lt hm end lemma eq_of_lt_minimal_period_of_iterate_eq {m n : ℕ} (hm : m < minimal_period f x) (hn : n < minimal_period f x) (hmn : f^[m] x = (f^[n] x)) : m = n := (le_of_lt_minimal_period_of_iterate_eq hm hmn).antisymm (le_of_lt_minimal_period_of_iterate_eq hn hmn.symm) lemma eq_iff_lt_minimal_period_of_iterate_eq {m n : ℕ} (hm : m < minimal_period f x) (hn : n < minimal_period f x) : f^[m] x = (f^[n] x) ↔ m = n := ⟨eq_of_lt_minimal_period_of_iterate_eq hm hn, congr_arg _⟩ lemma minimal_period_id : minimal_period id x = 1 := ((is_periodic_id _ _ ).minimal_period_le nat.one_pos).antisymm (nat.succ_le_of_lt ((is_periodic_id _ _ ).minimal_period_pos nat.one_pos)) lemma is_fixed_point_iff_minimal_period_eq_one : minimal_period f x = 1 ↔ is_fixed_pt f x := begin refine ⟨λ h, _, λ h, _⟩, { rw ← iterate_one f, refine function.is_periodic_pt.is_fixed_pt _, rw ← h, exact is_periodic_pt_minimal_period f x }, { exact ((h.is_periodic_pt 1).minimal_period_le nat.one_pos).antisymm (nat.succ_le_of_lt ((h.is_periodic_pt 1).minimal_period_pos nat.one_pos)) } end lemma is_periodic_pt.eq_zero_of_lt_minimal_period (hx : is_periodic_pt f n x) (hn : n < minimal_period f x) : n = 0 := eq.symm $ (eq_or_lt_of_le $ n.zero_le).resolve_right $ λ hn0, not_lt.2 (hx.minimal_period_le hn0) hn lemma not_is_periodic_pt_of_pos_of_lt_minimal_period : ∀ {n : ℕ} (n0 : n ≠ 0) (hn : n < minimal_period f x), ¬ is_periodic_pt f n x | 0 n0 _ := (n0 rfl).elim | (n + 1) _ hn := λ hp, nat.succ_ne_zero _ (hp.eq_zero_of_lt_minimal_period hn) lemma is_periodic_pt.minimal_period_dvd (hx : is_periodic_pt f n x) : minimal_period f x ∣ n := (eq_or_lt_of_le $ n.zero_le).elim (λ hn0, hn0 ▸ dvd_zero _) $ λ hn0, nat.dvd_iff_mod_eq_zero.2 $ (hx.mod $ is_periodic_pt_minimal_period f x).eq_zero_of_lt_minimal_period $ nat.mod_lt _ $ hx.minimal_period_pos hn0 lemma is_periodic_pt_iff_minimal_period_dvd : is_periodic_pt f n x ↔ minimal_period f x ∣ n := ⟨is_periodic_pt.minimal_period_dvd, λ h, (is_periodic_pt_minimal_period f x).trans_dvd h⟩ open nat lemma minimal_period_eq_minimal_period_iff {g : β → β} {y : β} : minimal_period f x = minimal_period g y ↔ ∀ n, is_periodic_pt f n x ↔ is_periodic_pt g n y := by simp_rw [is_periodic_pt_iff_minimal_period_dvd, dvd_right_iff_eq] lemma minimal_period_eq_prime {p : ℕ} [hp : fact p.prime] (hper : is_periodic_pt f p x) (hfix : ¬ is_fixed_pt f x) : minimal_period f x = p := (hp.out.eq_one_or_self_of_dvd _ (hper.minimal_period_dvd)).resolve_left (mt is_fixed_point_iff_minimal_period_eq_one.1 hfix) lemma minimal_period_eq_prime_pow {p k : ℕ} [hp : fact p.prime] (hk : ¬ is_periodic_pt f (p ^ k) x) (hk1 : is_periodic_pt f (p ^ (k + 1)) x) : minimal_period f x = p ^ (k + 1) := begin apply nat.eq_prime_pow_of_dvd_least_prime_pow hp.out; rwa ← is_periodic_pt_iff_minimal_period_dvd end lemma commute.minimal_period_of_comp_dvd_lcm {g : α → α} (h : function.commute f g) : minimal_period (f ∘ g) x ∣ nat.lcm (minimal_period f x) (minimal_period g x) := begin rw [← is_periodic_pt_iff_minimal_period_dvd], exact (is_periodic_pt_minimal_period f x).comp_lcm h (is_periodic_pt_minimal_period g x) end lemma commute.minimal_period_of_comp_dvd_mul {g : α → α} (h : function.commute f g) : minimal_period (f ∘ g) x ∣ (minimal_period f x) * (minimal_period g x) := dvd_trans h.minimal_period_of_comp_dvd_lcm (lcm_dvd_mul _ _) lemma commute.minimal_period_of_comp_eq_mul_of_coprime {g : α → α} (h : function.commute f g) (hco : coprime (minimal_period f x) (minimal_period g x)) : minimal_period (f ∘ g) x = (minimal_period f x) * (minimal_period g x) := begin apply dvd_antisymm (h.minimal_period_of_comp_dvd_mul), suffices : ∀ {f g : α → α}, commute f g → coprime (minimal_period f x) (minimal_period g x) → minimal_period f x ∣ minimal_period (f ∘ g) x, from hco.mul_dvd_of_dvd_of_dvd (this h hco) (h.comp_eq.symm ▸ this h.symm hco.symm), clear hco h f g, intros f g h hco, refine hco.dvd_of_dvd_mul_left (is_periodic_pt.left_of_comp h _ _).minimal_period_dvd, { exact (is_periodic_pt_minimal_period _ _).const_mul _ }, { exact (is_periodic_pt_minimal_period _ _).mul_const _ } end private lemma minimal_period_iterate_eq_div_gcd_aux (h : 0 < gcd (minimal_period f x) n) : minimal_period (f ^[n]) x = minimal_period f x / nat.gcd (minimal_period f x) n := begin apply nat.dvd_antisymm, { apply is_periodic_pt.minimal_period_dvd, rw [is_periodic_pt, is_fixed_pt, ← iterate_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (gcd_dvd_right _ _), mul_comm, iterate_mul], exact (is_periodic_pt_minimal_period f x).iterate _ }, { apply coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd h), apply dvd_of_mul_dvd_mul_right h, rw [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc, nat.div_mul_cancel (gcd_dvd_right _ _), mul_comm], apply is_periodic_pt.minimal_period_dvd, rw [is_periodic_pt, is_fixed_pt, iterate_mul], exact is_periodic_pt_minimal_period _ _ } end lemma minimal_period_iterate_eq_div_gcd (h : n ≠ 0) : minimal_period (f ^[n]) x = minimal_period f x / nat.gcd (minimal_period f x) n := minimal_period_iterate_eq_div_gcd_aux $ gcd_pos_of_pos_right _ (nat.pos_of_ne_zero h) lemma minimal_period_iterate_eq_div_gcd' (h : x ∈ periodic_pts f) : minimal_period (f ^[n]) x = minimal_period f x / nat.gcd (minimal_period f x) n := minimal_period_iterate_eq_div_gcd_aux $ gcd_pos_of_pos_left n (minimal_period_pos_iff_mem_periodic_pts.mpr h) /-- The orbit of a periodic point `x` of `f` is the cycle `[x, f x, f (f x), ...]`. Its length is the minimal period of `x`. If `x` is not a periodic point, then this is the empty (aka nil) cycle. -/ def periodic_orbit (f : α → α) (x : α) : cycle α := (list.range (minimal_period f x)).map (λ n, f^[n] x) /-- The definition of a periodic orbit, in terms of `list.map`. -/ lemma periodic_orbit_def (f : α → α) (x : α) : periodic_orbit f x = (list.range (minimal_period f x)).map (λ n, f^[n] x) := rfl /-- The definition of a periodic orbit, in terms of `cycle.map`. -/ lemma periodic_orbit_eq_cycle_map (f : α → α) (x : α) : periodic_orbit f x = (list.range (minimal_period f x) : cycle ℕ).map (λ n, f^[n] x) := rfl @[simp] lemma periodic_orbit_length : (periodic_orbit f x).length = minimal_period f x := by rw [periodic_orbit, cycle.length_coe, list.length_map, list.length_range] @[simp] lemma periodic_orbit_eq_nil_iff_not_periodic_pt : periodic_orbit f x = cycle.nil ↔ x ∉ periodic_pts f := by { simp [periodic_orbit], exact minimal_period_eq_zero_iff_nmem_periodic_pts } lemma periodic_orbit_eq_nil_of_not_periodic_pt (h : x ∉ periodic_pts f) : periodic_orbit f x = cycle.nil := periodic_orbit_eq_nil_iff_not_periodic_pt.2 h @[simp] lemma mem_periodic_orbit_iff (hx : x ∈ periodic_pts f) : y ∈ periodic_orbit f x ↔ ∃ n, f^[n] x = y := begin simp only [periodic_orbit, cycle.mem_coe_iff, list.mem_map, list.mem_range], use λ ⟨a, ha, ha'⟩, ⟨a, ha'⟩, rintro ⟨n, rfl⟩, use [n % minimal_period f x, mod_lt _ (minimal_period_pos_of_mem_periodic_pts hx)], rw iterate_mod_minimal_period_eq end @[simp] lemma iterate_mem_periodic_orbit (hx : x ∈ periodic_pts f) (n : ℕ) : f^[n] x ∈ periodic_orbit f x := (mem_periodic_orbit_iff hx).2 ⟨n, rfl⟩ @[simp] lemma self_mem_periodic_orbit (hx : x ∈ periodic_pts f) : x ∈ periodic_orbit f x := iterate_mem_periodic_orbit hx 0 lemma nodup_periodic_orbit : (periodic_orbit f x).nodup := begin rw [periodic_orbit, cycle.nodup_coe_iff, list.nodup_map_iff_inj_on (list.nodup_range _)], intros m hm n hn hmn, rw list.mem_range at hm hn, rwa eq_iff_lt_minimal_period_of_iterate_eq hm hn at hmn end lemma periodic_orbit_apply_iterate_eq (hx : x ∈ periodic_pts f) (n : ℕ) : periodic_orbit f (f^[n] x) = periodic_orbit f x := eq.symm $ cycle.coe_eq_coe.2 $ ⟨n, begin apply list.ext_le _ (λ m _ _, _), { simp [minimal_period_apply_iterate hx] }, { rw list.nth_le_rotate _ n m, simp [iterate_add_apply] } end⟩ lemma periodic_orbit_apply_eq (hx : x ∈ periodic_pts f) : periodic_orbit f (f x) = periodic_orbit f x := periodic_orbit_apply_iterate_eq hx 1 theorem periodic_orbit_chain (r : α → α → Prop) {f : α → α} {x : α} : (periodic_orbit f x).chain r ↔ ∀ n < minimal_period f x, r (f^[n] x) (f^[n+1] x) := begin by_cases hx : x ∈ periodic_pts f, { have hx' := minimal_period_pos_of_mem_periodic_pts hx, have hM := nat.sub_add_cancel (succ_le_iff.2 hx'), rw [periodic_orbit, ←cycle.map_coe, cycle.chain_map, ←hM, cycle.chain_range_succ], refine ⟨_, λ H, ⟨_, λ m hm, H _ (hm.trans (nat.lt_succ_self _))⟩⟩, { rintro ⟨hr, H⟩ n hn, cases eq_or_lt_of_le (lt_succ_iff.1 hn) with hM' hM', { rwa [hM', hM, iterate_minimal_period] }, { exact H _ hM' } }, { rw iterate_zero_apply, nth_rewrite 2 ←@iterate_minimal_period α f x, nth_rewrite 1 ←hM, exact H _ (nat.lt_succ_self _) } }, { rw [periodic_orbit_eq_nil_of_not_periodic_pt hx, minimal_period_eq_zero_of_nmem_periodic_pts hx], simp } end theorem periodic_orbit_chain' (r : α → α → Prop) {f : α → α} {x : α} (hx : x ∈ periodic_pts f) : (periodic_orbit f x).chain r ↔ ∀ n, r (f^[n] x) (f^[n+1] x) := begin rw periodic_orbit_chain r, refine ⟨λ H n, _, λ H n _, H n⟩, rw [iterate_succ_apply, ←iterate_mod_minimal_period_eq], nth_rewrite 1 ←iterate_mod_minimal_period_eq, rw [←iterate_succ_apply, minimal_period_apply hx], exact H _ (mod_lt _ (minimal_period_pos_of_mem_periodic_pts hx)) end end function namespace function variables {α β : Type*} {f : α → α} {g : β → β} {x : α × β} {a : α} {b : β} {m n : ℕ} @[simp] lemma iterate_prod_map (f : α → α) (g : β → β) (n : ℕ) : (prod.map f g)^[n] = prod.map (f^[n]) (g^[n]) := by induction n; simp [*, prod.map_comp_map] @[simp] lemma is_fixed_pt_prod_map (x : α × β) : is_fixed_pt (prod.map f g) x ↔ is_fixed_pt f x.1 ∧ is_fixed_pt g x.2 := prod.ext_iff @[simp] lemma is_periodic_pt_prod_map (x : α × β) : is_periodic_pt (prod.map f g) n x ↔ is_periodic_pt f n x.1 ∧ is_periodic_pt g n x.2 := by simp [is_periodic_pt] lemma minimal_period_prod_map (f : α → α) (g : β → β) (x : α × β) : minimal_period (prod.map f g) x = (minimal_period f x.1).lcm (minimal_period g x.2) := eq_of_forall_dvd $ by cases x; simp [←is_periodic_pt_iff_minimal_period_dvd, nat.lcm_dvd_iff] lemma minimal_period_fst_dvd : minimal_period f x.1 ∣ minimal_period (prod.map f g) x := by { rw minimal_period_prod_map, exact nat.dvd_lcm_left _ _ } lemma minimal_period_snd_dvd : minimal_period g x.2 ∣ minimal_period (prod.map f g) x := by { rw minimal_period_prod_map, exact nat.dvd_lcm_right _ _ } end function namespace mul_action open function variables {α β : Type*} [group α] [mul_action α β] {a : α} {b : β} @[to_additive] lemma pow_smul_eq_iff_minimal_period_dvd {n : ℕ} : a ^ n • b = b ↔ function.minimal_period ((•) a) b ∣ n := by rw [←is_periodic_pt_iff_minimal_period_dvd, is_periodic_pt, is_fixed_pt, smul_iterate] @[to_additive] lemma zpow_smul_eq_iff_minimal_period_dvd {n : ℤ} : a ^ n • b = b ↔ (function.minimal_period ((•) a) b : ℤ) ∣ n := begin cases n, { rw [int.of_nat_eq_coe, zpow_coe_nat, int.coe_nat_dvd, pow_smul_eq_iff_minimal_period_dvd] }, { rw [int.neg_succ_of_nat_coe, zpow_neg, zpow_coe_nat, inv_smul_eq_iff, eq_comm, dvd_neg, int.coe_nat_dvd, pow_smul_eq_iff_minimal_period_dvd] }, end variables (a b) @[simp, to_additive] lemma pow_smul_mod_minimal_period (n : ℕ) : a ^ (n % function.minimal_period ((•) a) b) • b = a ^ n • b := by conv_rhs { rw [← nat.mod_add_div n (minimal_period ((•) a) b), pow_add, mul_smul, pow_smul_eq_iff_minimal_period_dvd.mpr (dvd_mul_right _ _)] } @[simp, to_additive] lemma zpow_smul_mod_minimal_period (n : ℤ) : a ^ (n % (function.minimal_period ((•) a) b : ℤ)) • b = a ^ n • b := by conv_rhs { rw [← int.mod_add_div n (minimal_period ((•) a) b), zpow_add, mul_smul, zpow_smul_eq_iff_minimal_period_dvd.mpr (dvd_mul_right _ _)] } end mul_action
acbfac4a77dcd79b846720a366eaddcb01c66f07
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/list/perm.lean
1d73362be795d7e162959b77aaccdfa2f0df620a
[ "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
54,298
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import data.list.erase_dup import data.list.lattice import data.list.permutation import data.list.zip import logic.relation /-! # List Permutations This file introduces the `list.perm` relation, which is true if two lists are permutations of one another. ## Notation The notation `~` is used for permutation equivalence. -/ open_locale nat universes uu vv namespace list variables {α : Type uu} {β : Type vv} /-- `perm l₁ l₂` or `l₁ ~ l₂` asserts that `l₁` and `l₂` are permutations of each other. This is defined by induction using pairwise swaps. -/ inductive perm : list α → list α → Prop | nil : perm [] [] | cons : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ open perm (swap) infix ` ~ `:50 := perm @[refl] protected theorem perm.refl : ∀ (l : list α), l ~ l | [] := perm.nil | (x::xs) := (perm.refl xs).cons x @[symm] protected theorem perm.symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p perm.nil (λ x l₁ l₂ p₁ r₁, r₁.cons x) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₂.trans r₁) theorem perm_comm {l₁ l₂ : list α} : l₁ ~ l₂ ↔ l₂ ~ l₁ := ⟨perm.symm, perm.symm⟩ theorem perm.swap' (x y : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : y::x::l₁ ~ x::y::l₂ := (swap _ _ _).trans ((p.cons _).cons _) attribute [trans] perm.trans theorem perm.eqv (α) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) instance is_setoid (α) : setoid (list α) := setoid.mk (@perm α) (perm.eqv α) theorem perm.subset {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ ⊆ l₂ := λ a, perm.rec_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim i (λ ax, by simp [ax]) (λ al₁, or.inr (r₁ al₁))) (λ x y l ayxl, or.elim ayxl (λ ay, by simp [ay]) (λ axl, or.elim axl (λ ax, by simp [ax]) (λ al, or.inr (or.inr al)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem perm.mem_iff {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ := iff.intro (λ m, h.subset m) (λ m, h.symm.subset m) theorem perm.append_right {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : l₁++t₁ ~ l₂++t₁ := perm.rec_on p (perm.refl ([] ++ t₁)) (λ x l₁ l₂ p₁ r₁, r₁.cons x) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, r₁.trans r₂) theorem perm.append_left {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → l++t₁ ~ l++t₂ | [] p := p | (x::xs) p := (perm.append_left xs p).cons x theorem perm.append {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁++t₁ ~ l₂++t₂ := (p₁.append_right t₁).trans (p₂.append_left l₂) theorem perm.append_cons (a : α) {h₁ h₂ t₁ t₂ : list α} (p₁ : h₁ ~ h₂) (p₂ : t₁ ~ t₂) : h₁ ++ a::t₁ ~ h₂ ++ a::t₂ := p₁.append (p₂.cons a) @[simp] theorem perm_middle {a : α} : ∀ {l₁ l₂ : list α}, l₁++a::l₂ ~ a::(l₁++l₂) | [] l₂ := perm.refl _ | (b::l₁) l₂ := ((@perm_middle l₁ l₂).cons _).trans (swap a b _) @[simp] theorem perm_append_singleton (a : α) (l : list α) : l ++ [a] ~ a::l := perm_middle.trans $ by rw [append_nil] theorem perm_append_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁) | [] l₂ := by simp | (a::t) l₂ := (perm_append_comm.cons _).trans perm_middle.symm theorem concat_perm (l : list α) (a : α) : concat l a ~ a :: l := by simp theorem perm.length_eq {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ := perm.rec_on p rfl (λ x l₁ l₂ p r, by simp[r]) (λ x y l, by simp) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem perm.eq_nil {l : list α} (p : l ~ []) : l = [] := eq_nil_of_length_eq_zero p.length_eq theorem perm.nil_eq {l : list α} (p : [] ~ l) : [] = l := p.symm.eq_nil.symm @[simp] theorem perm_nil {l₁ : list α} : l₁ ~ [] ↔ l₁ = [] := ⟨λ p, p.eq_nil, λ e, e ▸ perm.refl _⟩ @[simp] theorem nil_perm {l₁ : list α} : [] ~ l₁ ↔ l₁ = [] := perm_comm.trans perm_nil theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ x::l | p := by injection p.symm.eq_nil @[simp] theorem reverse_perm : ∀ (l : list α), reverse l ~ l | [] := perm.nil | (a::l) := by { rw reverse_cons, exact (perm_append_singleton _ _).trans ((reverse_perm l).cons a) } theorem perm_cons_append_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) := (p.cons a).trans perm_middle.symm @[simp] theorem perm_repeat {a : α} {n : ℕ} {l : list α} : l ~ repeat a n ↔ l = repeat a n := ⟨λ p, (eq_repeat.2 ⟨p.length_eq.trans $ length_repeat _ _, λ b m, eq_of_mem_repeat $ p.subset m⟩), λ h, h ▸ perm.refl _⟩ @[simp] theorem repeat_perm {a : α} {n : ℕ} {l : list α} : repeat a n ~ l ↔ repeat a n = l := (perm_comm.trans perm_repeat).trans eq_comm @[simp] theorem perm_singleton {a : α} {l : list α} : l ~ [a] ↔ l = [a] := @perm_repeat α a 1 l @[simp] theorem singleton_perm {a : α} {l : list α} : [a] ~ l ↔ [a] = l := @repeat_perm α a 1 l theorem perm.eq_singleton {a : α} {l : list α} (p : l ~ [a]) : l = [a] := perm_singleton.1 p theorem perm.singleton_eq {a : α} {l : list α} (p : [a] ~ l) : [a] = l := p.symm.eq_singleton.symm theorem singleton_perm_singleton {a b : α} : [a] ~ [b] ↔ a = b := by simp theorem perm_cons_erase [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) : l ~ a :: l.erase a := let ⟨l₁, l₂, _, e₁, e₂⟩ := exists_erase_eq h in e₂.symm ▸ e₁.symm ▸ perm_middle @[elab_as_eliminator] theorem perm_induction_on {P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l, from assume l, list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ @[congr] theorem perm.filter_map (f : α → option β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : filter_map f l₁ ~ filter_map f l₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp only [filter_map], cases f x with a; simp [filter_map, IH, perm.cons] }, { simp only [filter_map], cases f x with a; cases f y with b; simp [filter_map, swap] }, { exact IH₁.trans IH₂ } end @[congr] theorem perm.map (f : α → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) : map f l₁ ~ map f l₂ := filter_map_eq_map f ▸ p.filter_map _ theorem perm.pmap {p : α → Prop} (f : Π a, p a → β) {l₁ l₂ : list α} (p : l₁ ~ l₂) {H₁ H₂} : pmap f l₁ H₁ ~ pmap f l₂ H₂ := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂, { simp }, { simp [IH, perm.cons] }, { simp [swap] }, { refine IH₁.trans IH₂, exact λ a m, H₂ a (p₂.subset m) } end theorem perm.filter (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : filter p l₁ ~ filter p l₂ := by rw ← filter_map_eq_filter; apply s.filter_map _ theorem exists_perm_sublist {l₁ l₂ l₂' : list α} (s : l₁ <+ l₂) (p : l₂ ~ l₂') : ∃ l₁' ~ l₁, l₁' <+ l₂' := begin induction p with x l₂ l₂' p IH x y l₂ l₂ m₂ r₂ p₁ p₂ IH₁ IH₂ generalizing l₁ s, { exact ⟨[], eq_nil_of_sublist_nil s ▸ perm.refl _, nil_sublist _⟩ }, { cases s with _ _ _ s l₁ _ _ s, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨l₁', p', s'.cons _ _ _⟩ }, { exact let ⟨l₁', p', s'⟩ := IH s in ⟨x::l₁', p'.cons x, s'.cons2 _ _ _⟩ } }, { cases s with _ _ _ s l₁ _ _ s; cases s with _ _ _ s l₁ _ _ s, { exact ⟨l₁, perm.refl _, (s.cons _ _ _).cons _ _ _⟩ }, { exact ⟨x::l₁, perm.refl _, (s.cons _ _ _).cons2 _ _ _⟩ }, { exact ⟨y::l₁, perm.refl _, (s.cons2 _ _ _).cons _ _ _⟩ }, { exact ⟨x::y::l₁, perm.swap _ _ _, (s.cons2 _ _ _).cons2 _ _ _⟩ } }, { exact let ⟨m₁, pm, sm⟩ := IH₁ s, ⟨r₁, pr, sr⟩ := IH₂ sm in ⟨r₁, pr.trans pm, sr⟩ } end theorem perm.sizeof_eq_sizeof [has_sizeof α] {l₁ l₂ : list α} (h : l₁ ~ l₂) : l₁.sizeof = l₂.sizeof := begin induction h with hd l₁ l₂ h₁₂ h_sz₁₂ a b l l₁ l₂ l₃ h₁₂ h₂₃ h_sz₁₂ h_sz₂₃, { refl }, { simp only [list.sizeof, h_sz₁₂] }, { simp only [list.sizeof, add_left_comm] }, { simp only [h_sz₁₂, h_sz₂₃] } end section rel open relator variables {γ : Type*} {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} local infixr ` ∘r ` : 80 := relation.comp lemma perm_comp_perm : (perm ∘r perm : list α → list α → Prop) = perm := begin funext a c, apply propext, split, { exact assume ⟨b, hab, hba⟩, perm.trans hab hba }, { exact assume h, ⟨a, perm.refl a, h⟩ } end lemma perm_comp_forall₂ {l u v} (hlu : perm l u) (huv : forall₂ r u v) : (forall₂ r ∘r perm) l v := begin induction hlu generalizing v, case perm.nil { cases huv, exact ⟨[], forall₂.nil, perm.nil⟩ }, case perm.cons : a l u hlu ih { cases huv with _ b _ v hab huv', rcases ih huv' with ⟨l₂, h₁₂, h₂₃⟩, exact ⟨b::l₂, forall₂.cons hab h₁₂, h₂₃.cons _⟩ }, case perm.swap : a₁ a₂ l₁ l₂ h₂₃ { cases h₂₃ with _ b₁ _ l₂ h₁ hr_₂₃, cases hr_₂₃ with _ b₂ _ l₂ h₂ h₁₂, exact ⟨b₂::b₁::l₂, forall₂.cons h₂ (forall₂.cons h₁ h₁₂), perm.swap _ _ _⟩ }, case perm.trans : la₁ la₂ la₃ _ _ ih₁ ih₂ { rcases ih₂ huv with ⟨lb₂, hab₂, h₂₃⟩, rcases ih₁ hab₂ with ⟨lb₁, hab₁, h₁₂⟩, exact ⟨lb₁, hab₁, perm.trans h₁₂ h₂₃⟩ } end lemma forall₂_comp_perm_eq_perm_comp_forall₂ : forall₂ r ∘r perm = perm ∘r forall₂ r := begin funext l₁ l₃, apply propext, split, { assume h, rcases h with ⟨l₂, h₁₂, h₂₃⟩, have : forall₂ (flip r) l₂ l₁, from h₁₂.flip , rcases perm_comp_forall₂ h₂₃.symm this with ⟨l', h₁, h₂⟩, exact ⟨l', h₂.symm, h₁.flip⟩ }, { exact assume ⟨l₂, h₁₂, h₂₃⟩, perm_comp_forall₂ h₁₂ h₂₃ } end lemma rel_perm_imp (hr : right_unique r) : (forall₂ r ⇒ forall₂ r ⇒ implies) perm perm := assume a b h₁ c d h₂ h, have (flip (forall₂ r) ∘r (perm ∘r forall₂ r)) b d, from ⟨a, h₁, c, h, h₂⟩, have ((flip (forall₂ r) ∘r forall₂ r) ∘r perm) b d, by rwa [← forall₂_comp_perm_eq_perm_comp_forall₂, ← relation.comp_assoc] at this, let ⟨b', ⟨c', hbc, hcb⟩, hbd⟩ := this in have b' = b, from right_unique_forall₂' hr hcb hbc, this ▸ hbd lemma rel_perm (hr : bi_unique r) : (forall₂ r ⇒ forall₂ r ⇒ (↔)) perm perm := assume a b hab c d hcd, iff.intro (rel_perm_imp hr.2 hab hcd) (rel_perm_imp hr.left.flip hab.flip hcd.flip) end rel section subperm /-- `subperm l₁ l₂`, denoted `l₁ <+~ l₂`, means that `l₁` is a sublist of a permutation of `l₂`. This is an analogue of `l₁ ⊆ l₂` which respects multiplicities of elements, and is used for the `≤` relation on multisets. -/ def subperm (l₁ l₂ : list α) : Prop := ∃ l ~ l₁, l <+ l₂ infix ` <+~ `:50 := subperm theorem nil_subperm {l : list α} : [] <+~ l := ⟨[], perm.nil, by simp⟩ theorem perm.subperm_left {l l₁ l₂ : list α} (p : l₁ ~ l₂) : l <+~ l₁ ↔ l <+~ l₂ := suffices ∀ {l₁ l₂ : list α}, l₁ ~ l₂ → l <+~ l₁ → l <+~ l₂, from ⟨this p, this p.symm⟩, λ l₁ l₂ p ⟨u, pu, su⟩, let ⟨v, pv, sv⟩ := exists_perm_sublist su p in ⟨v, pv.trans pu, sv⟩ theorem perm.subperm_right {l₁ l₂ l : list α} (p : l₁ ~ l₂) : l₁ <+~ l ↔ l₂ <+~ l := ⟨λ ⟨u, pu, su⟩, ⟨u, pu.trans p, su⟩, λ ⟨u, pu, su⟩, ⟨u, pu.trans p.symm, su⟩⟩ theorem sublist.subperm {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁ <+~ l₂ := ⟨l₁, perm.refl _, s⟩ theorem perm.subperm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁ <+~ l₂ := ⟨l₂, p.symm, sublist.refl _⟩ @[refl] theorem subperm.refl (l : list α) : l <+~ l := (perm.refl _).subperm @[trans] theorem subperm.trans {l₁ l₂ l₃ : list α} : l₁ <+~ l₂ → l₂ <+~ l₃ → l₁ <+~ l₃ | s ⟨l₂', p₂, s₂⟩ := let ⟨l₁', p₁, s₁⟩ := p₂.subperm_left.2 s in ⟨l₁', p₁, s₁.trans s₂⟩ theorem subperm.length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ ≤ length l₂ | ⟨l, p, s⟩ := p.length_eq ▸ length_le_of_sublist s theorem subperm.perm_of_length_le {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₂ ≤ length l₁ → l₁ ~ l₂ | ⟨l, p, s⟩ h := suffices l = l₂, from this ▸ p.symm, eq_of_sublist_of_length_le s $ p.symm.length_eq ▸ h theorem subperm.antisymm {l₁ l₂ : list α} (h₁ : l₁ <+~ l₂) (h₂ : l₂ <+~ l₁) : l₁ ~ l₂ := h₁.perm_of_length_le h₂.length_le theorem subperm.subset {l₁ l₂ : list α} : l₁ <+~ l₂ → l₁ ⊆ l₂ | ⟨l, p, s⟩ := subset.trans p.symm.subset s.subset lemma subperm.filter (p : α → Prop) [decidable_pred p] ⦃l l' : list α⦄ (h : l <+~ l') : filter p l <+~ filter p l' := begin obtain ⟨xs, hp, h⟩ := h, exact ⟨_, hp.filter p, h.filter p⟩ end end subperm theorem sublist.exists_perm_append : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → ∃ l, l₂ ~ l₁ ++ l | ._ ._ sublist.slnil := ⟨nil, perm.refl _⟩ | ._ ._ (sublist.cons l₁ l₂ a s) := let ⟨l, p⟩ := sublist.exists_perm_append s in ⟨a::l, (p.cons a).trans perm_middle.symm⟩ | ._ ._ (sublist.cons2 l₁ l₂ a s) := let ⟨l, p⟩ := sublist.exists_perm_append s in ⟨l, p.cons a⟩ theorem perm.countp_eq (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} (s : l₁ ~ l₂) : countp p l₁ = countp p l₂ := by rw [countp_eq_length_filter, countp_eq_length_filter]; exact (s.filter _).length_eq theorem subperm.countp_le (p : α → Prop) [decidable_pred p] {l₁ l₂ : list α} : l₁ <+~ l₂ → countp p l₁ ≤ countp p l₂ | ⟨l, p', s⟩ := p'.countp_eq p ▸ s.countp_le p theorem perm.count_eq [decidable_eq α] {l₁ l₂ : list α} (p : l₁ ~ l₂) (a) : count a l₁ = count a l₂ := p.countp_eq _ theorem subperm.count_le [decidable_eq α] {l₁ l₂ : list α} (s : l₁ <+~ l₂) (a) : count a l₁ ≤ count a l₂ := s.countp_le _ theorem perm.foldl_eq' {f : β → α → β} {l₁ l₂ : list α} (p : l₁ ~ l₂) : (∀ (x ∈ l₁) (y ∈ l₁) z, f (f z x) y = f (f z y) x) → ∀ b, foldl f b l₁ = foldl f b l₂ := perm_induction_on p (λ H b, rfl) (λ x t₁ t₂ p r H b, r (λ x hx y hy, H _ (or.inr hx) _ (or.inr hy)) _) (λ x y t₁ t₂ p r H b, begin simp only [foldl], rw [H x (or.inr $ or.inl rfl) y (or.inl rfl)], exact r (λ x hx y hy, H _ (or.inr $ or.inr hx) _ (or.inr $ or.inr hy)) _ end) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ H b, eq.trans (r₁ H b) (r₂ (λ x hx y hy, H _ (p₁.symm.subset hx) _ (p₁.symm.subset hy)) b)) theorem perm.foldl_eq {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) : ∀ b, foldl f b l₁ = foldl f b l₂ := p.foldl_eq' $ λ x hx y hy z, rcomm z x y theorem perm.foldr_eq {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) : ∀ b, foldr f b l₁ = foldr f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, by simp; rw [r b]) (λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b]) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) lemma perm.rec_heq {β : list α → Sort*} {f : Πa l, β l → β (a::l)} {b : β []} {l l' : list α} (hl : perm l l') (f_congr : ∀{a l l' b b'}, perm l l' → b == b' → f a l b == f a l' b') (f_swap : ∀{a a' l b}, f a (a'::l) (f a' l b) == f a' (a::l) (f a l b)) : @list.rec α β b f l == @list.rec α β b f l' := begin induction hl, case list.perm.nil { refl }, case list.perm.cons : a l l' h ih { exact f_congr h ih }, case list.perm.swap : a a' l { exact f_swap }, case list.perm.trans : l₁ l₂ l₃ h₁ h₂ ih₁ ih₂ { exact heq.trans ih₁ ih₂ } end section variables {op : α → α → α} [is_associative α op] [is_commutative α op] local notation a * b := op a b local notation l <*> a := foldl op a l lemma perm.fold_op_eq {l₁ l₂ : list α} {a : α} (h : l₁ ~ l₂) : l₁ <*> a = l₂ <*> a := h.foldl_eq (right_comm _ is_commutative.comm is_associative.assoc) _ end section comm_monoid /-- If elements of a list commute with each other, then their product does not depend on the order of elements-/ @[to_additive] lemma perm.prod_eq' [monoid α] {l₁ l₂ : list α} (h : l₁ ~ l₂) (hc : l₁.pairwise (λ x y, x * y = y * x)) : l₁.prod = l₂.prod := h.foldl_eq' (forall_of_forall_of_pairwise (λ x y h z, (h z).symm) (λ x hx z, rfl) $ hc.imp $ λ x y h z, by simp only [mul_assoc, h]) _ variable [comm_monoid α] @[to_additive] lemma perm.prod_eq {l₁ l₂ : list α} (h : perm l₁ l₂) : prod l₁ = prod l₂ := h.fold_op_eq @[to_additive] lemma prod_reverse (l : list α) : prod l.reverse = prod l := (reverse_perm l).prod_eq end comm_monoid theorem perm_inv_core {a : α} {l₁ l₂ r₁ r₂ : list α} : l₁++a::r₁ ~ l₂++a::r₂ → l₁++r₁ ~ l₂++r₂ := begin generalize e₁ : l₁++a::r₁ = s₁, generalize e₂ : l₂++a::r₂ = s₂, intro p, revert l₁ l₂ r₁ r₂ e₁ e₂, refine perm_induction_on p _ (λ x t₁ t₂ p IH, _) (λ x y t₁ t₂ p IH, _) (λ t₁ t₂ t₃ p₁ p₂ IH₁ IH₂, _); intros l₁ l₂ r₁ r₂ e₁ e₂, { apply (not_mem_nil a).elim, rw ← e₁, simp }, { cases l₁ with y l₁; cases l₂ with z l₂; dsimp at e₁ e₂; injections; subst x, { substs t₁ t₂, exact p }, { substs z t₁ t₂, exact p.trans perm_middle }, { substs y t₁ t₂, exact perm_middle.symm.trans p }, { substs z t₁ t₂, exact (IH rfl rfl).cons y } }, { rcases l₁ with _|⟨y, _|⟨z, l₁⟩⟩; rcases l₂ with _|⟨u, _|⟨v, l₂⟩⟩; dsimp at e₁ e₂; injections; substs x y, { substs r₁ r₂, exact p.cons a }, { substs r₁ r₂, exact p.cons u }, { substs r₁ v t₂, exact (p.trans perm_middle).cons u }, { substs r₁ r₂, exact p.cons y }, { substs r₁ r₂ y u, exact p.cons a }, { substs r₁ u v t₂, exact ((p.trans perm_middle).cons y).trans (swap _ _ _) }, { substs r₂ z t₁, exact (perm_middle.symm.trans p).cons y }, { substs r₂ y z t₁, exact (swap _ _ _).trans ((perm_middle.symm.trans p).cons u) }, { substs u v t₁ t₂, exact (IH rfl rfl).swap' _ _ } }, { substs t₁ t₃, have : a ∈ t₂ := p₁.subset (by simp), rcases mem_split this with ⟨l₂, r₂, e₂⟩, subst t₂, exact (IH₁ rfl rfl).trans (IH₂ rfl rfl) } end theorem perm.cons_inv {a : α} {l₁ l₂ : list α} : a::l₁ ~ a::l₂ → l₁ ~ l₂ := @perm_inv_core _ _ [] [] _ _ @[simp] theorem perm_cons (a : α) {l₁ l₂ : list α} : a::l₁ ~ a::l₂ ↔ l₁ ~ l₂ := ⟨perm.cons_inv, perm.cons a⟩ theorem perm_append_left_iff {l₁ l₂ : list α} : ∀ l, l++l₁ ~ l++l₂ ↔ l₁ ~ l₂ | [] := iff.rfl | (a::l) := (perm_cons a).trans (perm_append_left_iff l) theorem perm_append_right_iff {l₁ l₂ : list α} (l) : l₁++l ~ l₂++l ↔ l₁ ~ l₂ := ⟨λ p, (perm_append_left_iff _).1 $ perm_append_comm.trans $ p.trans perm_append_comm, perm.append_right _⟩ theorem perm_option_to_list {o₁ o₂ : option α} : o₁.to_list ~ o₂.to_list ↔ o₁ = o₂ := begin refine ⟨λ p, _, λ e, e ▸ perm.refl _⟩, cases o₁ with a; cases o₂ with b, {refl}, { cases p.length_eq }, { cases p.length_eq }, { exact option.mem_to_list.1 (p.symm.subset $ by simp) } end theorem subperm_cons (a : α) {l₁ l₂ : list α} : a::l₁ <+~ a::l₂ ↔ l₁ <+~ l₂ := ⟨λ ⟨l, p, s⟩, begin cases s with _ _ _ s' u _ _ s', { exact (p.subperm_left.2 $ (sublist_cons _ _).subperm).trans s'.subperm }, { exact ⟨u, p.cons_inv, s'⟩ } end, λ ⟨l, p, s⟩, ⟨a::l, p.cons a, s.cons2 _ _ _⟩⟩ theorem cons_subperm_of_mem {a : α} {l₁ l₂ : list α} (d₁ : nodup l₁) (h₁ : a ∉ l₁) (h₂ : a ∈ l₂) (s : l₁ <+~ l₂) : a :: l₁ <+~ l₂ := begin rcases s with ⟨l, p, s⟩, induction s generalizing l₁, case list.sublist.slnil { cases h₂ }, case list.sublist.cons : r₁ r₂ b s' ih { simp at h₂, cases h₂ with e m, { subst b, exact ⟨a::r₁, p.cons a, s'.cons2 _ _ _⟩ }, { rcases ih m d₁ h₁ p with ⟨t, p', s'⟩, exact ⟨t, p', s'.cons _ _ _⟩ } }, case list.sublist.cons2 : r₁ r₂ b s' ih { have bm : b ∈ l₁ := (p.subset $ mem_cons_self _ _), have am : a ∈ r₂ := h₂.resolve_left (λ e, h₁ $ e.symm ▸ bm), rcases mem_split bm with ⟨t₁, t₂, rfl⟩, have st : t₁ ++ t₂ <+ t₁ ++ b :: t₂ := by simp, rcases ih am (nodup_of_sublist st d₁) (mt (λ x, st.subset x) h₁) (perm.cons_inv $ p.trans perm_middle) with ⟨t, p', s'⟩, exact ⟨b::t, (p'.cons b).trans $ (swap _ _ _).trans (perm_middle.symm.cons a), s'.cons2 _ _ _⟩ } end theorem subperm_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+~ l++l₂ ↔ l₁ <+~ l₂ | [] := iff.rfl | (a::l) := (subperm_cons a).trans (subperm_append_left l) theorem subperm_append_right {l₁ l₂ : list α} (l) : l₁++l <+~ l₂++l ↔ l₁ <+~ l₂ := (perm_append_comm.subperm_left.trans perm_append_comm.subperm_right).trans (subperm_append_left l) theorem subperm.exists_of_length_lt {l₁ l₂ : list α} : l₁ <+~ l₂ → length l₁ < length l₂ → ∃ a, a :: l₁ <+~ l₂ | ⟨l, p, s⟩ h := suffices length l < length l₂ → ∃ (a : α), a :: l <+~ l₂, from (this $ p.symm.length_eq ▸ h).imp (λ a, (p.cons a).subperm_right.1), begin clear subperm.exists_of_length_lt p h l₁, rename l₂ u, induction s with l₁ l₂ a s IH _ _ b s IH; intro h, { cases h }, { cases lt_or_eq_of_le (nat.le_of_lt_succ h : length l₁ ≤ length l₂) with h h, { exact (IH h).imp (λ a s, s.trans (sublist_cons _ _).subperm) }, { exact ⟨a, eq_of_sublist_of_length_eq s h ▸ subperm.refl _⟩ } }, { exact (IH $ nat.lt_of_succ_lt_succ h).imp (λ a s, (swap _ _ _).subperm_right.1 $ (subperm_cons _).2 s) } end theorem subperm_of_subset_nodup {l₁ l₂ : list α} (d : nodup l₁) (H : l₁ ⊆ l₂) : l₁ <+~ l₂ := begin induction d with a l₁' h d IH, { exact ⟨nil, perm.nil, nil_sublist _⟩ }, { cases forall_mem_cons.1 H with H₁ H₂, simp at h, exact cons_subperm_of_mem d h H₁ (IH H₂) } end theorem perm_ext {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) : l₁ ~ l₂ ↔ ∀a, a ∈ l₁ ↔ a ∈ l₂ := ⟨λ p a, p.mem_iff, λ H, subperm.antisymm (subperm_of_subset_nodup d₁ (λ a, (H a).1)) (subperm_of_subset_nodup d₂ (λ a, (H a).2))⟩ theorem nodup.sublist_ext {l₁ l₂ l : list α} (d : nodup l) (s₁ : l₁ <+ l) (s₂ : l₂ <+ l) : l₁ ~ l₂ ↔ l₁ = l₂ := ⟨λ h, begin induction s₂ with l₂ l a s₂ IH l₂ l a s₂ IH generalizing l₁, { exact h.eq_nil }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { exact IH d.2 s₁ h }, { apply d.1.elim, exact subperm.subset ⟨_, h.symm, s₂⟩ (mem_cons_self _ _) } }, { simp at d, cases s₁ with _ _ _ s₁ l₁ _ _ s₁, { apply d.1.elim, exact subperm.subset ⟨_, h, s₁⟩ (mem_cons_self _ _) }, { rw IH d.2 s₁ h.cons_inv } } end, λ h, by rw h⟩ section variable [decidable_eq α] -- attribute [congr] theorem perm.erase (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁.erase a ~ l₂.erase a := if h₁ : a ∈ l₁ then have h₂ : a ∈ l₂, from p.subset h₁, perm.cons_inv $ (perm_cons_erase h₁).symm.trans $ p.trans (perm_cons_erase h₂) else have h₂ : a ∉ l₂, from mt p.mem_iff.2 h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p theorem subperm_cons_erase (a : α) (l : list α) : l <+~ a :: l.erase a := begin by_cases h : a ∈ l, { exact (perm_cons_erase h).subperm }, { rw [erase_of_not_mem h], exact (sublist_cons _ _).subperm } end theorem erase_subperm (a : α) (l : list α) : l.erase a <+~ l := (erase_sublist _ _).subperm theorem subperm.erase {l₁ l₂ : list α} (a : α) (h : l₁ <+~ l₂) : l₁.erase a <+~ l₂.erase a := let ⟨l, hp, hs⟩ := h in ⟨l.erase a, hp.erase _, hs.erase _⟩ theorem perm.diff_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.diff t ~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, perm.erase] theorem perm.diff_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l.diff t₁ = l.diff t₂ := by induction h generalizing l; simp [*, perm.erase, erase_comm] <|> exact (ih_1 _).trans (ih_2 _) theorem perm.diff {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.diff t₁ ~ l₂.diff t₂ := ht.diff_left l₂ ▸ hl.diff_right _ theorem subperm.diff_right {l₁ l₂ : list α} (h : l₁ <+~ l₂) (t : list α) : l₁.diff t <+~ l₂.diff t := by induction t generalizing l₁ l₂ h; simp [*, subperm.erase] theorem erase_cons_subperm_cons_erase (a b : α) (l : list α) : (a :: l).erase b <+~ a :: l.erase b := begin by_cases h : a = b, { subst b, rw [erase_cons_head], apply subperm_cons_erase }, { rw [erase_cons_tail _ h] } end theorem subperm_cons_diff {a : α} : ∀ {l₁ l₂ : list α}, (a :: l₁).diff l₂ <+~ a :: l₁.diff l₂ | l₁ [] := ⟨a::l₁, by simp⟩ | l₁ (b::l₂) := begin simp only [diff_cons], refine ((erase_cons_subperm_cons_erase a b l₁).diff_right l₂).trans _, apply subperm_cons_diff end theorem subset_cons_diff {a : α} {l₁ l₂ : list α} : (a :: l₁).diff l₂ ⊆ a :: l₁.diff l₂ := subperm_cons_diff.subset theorem perm.bag_inter_right {l₁ l₂ : list α} (t : list α) (h : l₁ ~ l₂) : l₁.bag_inter t ~ l₂.bag_inter t := begin induction h with x _ _ _ _ x y _ _ _ _ _ _ ih_1 ih_2 generalizing t, {simp}, { by_cases x ∈ t; simp [*, perm.cons] }, { by_cases x = y, {simp [h]}, by_cases xt : x ∈ t; by_cases yt : y ∈ t, { simp [xt, yt, mem_erase_of_ne h, mem_erase_of_ne (ne.symm h), erase_comm, swap] }, { simp [xt, yt, mt mem_of_mem_erase, perm.cons] }, { simp [xt, yt, mt mem_of_mem_erase, perm.cons] }, { simp [xt, yt] } }, { exact (ih_1 _).trans (ih_2 _) } end theorem perm.bag_inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l.bag_inter t₁ = l.bag_inter t₂ := begin induction l with a l IH generalizing t₁ t₂ p, {simp}, by_cases a ∈ t₁, { simp [h, p.subset h, IH (p.erase _)] }, { simp [h, mt p.mem_iff.2 h, IH p] } end theorem perm.bag_inter {l₁ l₂ t₁ t₂ : list α} (hl : l₁ ~ l₂) (ht : t₁ ~ t₂) : l₁.bag_inter t₁ ~ l₂.bag_inter t₂ := ht.bag_inter_left l₂ ▸ hl.bag_inter_right _ theorem cons_perm_iff_perm_erase {a : α} {l₁ l₂ : list α} : a::l₁ ~ l₂ ↔ a ∈ l₂ ∧ l₁ ~ l₂.erase a := ⟨λ h, have a ∈ l₂, from h.subset (mem_cons_self a l₁), ⟨this, (h.trans $ perm_cons_erase this).cons_inv⟩, λ ⟨m, h⟩, (h.cons a).trans (perm_cons_erase m).symm⟩ theorem perm_iff_count {l₁ l₂ : list α} : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ := ⟨perm.count_eq, λ H, begin induction l₁ with a l₁ IH generalizing l₂, { cases l₂ with b l₂, {refl}, specialize H b, simp at H, contradiction }, { have : a ∈ l₂ := count_pos.1 (by rw ← H; simp; apply nat.succ_pos), refine ((IH $ λ b, _).cons a).trans (perm_cons_erase this).symm, specialize H b, rw (perm_cons_erase this).count_eq at H, by_cases b = a; simp [h] at H ⊢; assumption } end⟩ lemma subperm.cons_right {α : Type*} {l l' : list α} (x : α) (h : l <+~ l') : l <+~ x :: l' := h.trans (sublist_cons x l').subperm /-- The list version of `add_tsub_cancel_of_le` for multisets. -/ lemma subperm_append_diff_self_of_count_le {l₁ l₂ : list α} (h : ∀ x ∈ l₁, count x l₁ ≤ count x l₂) : l₁ ++ l₂.diff l₁ ~ l₂ := begin induction l₁ with hd tl IH generalizing l₂, { simp }, { have : hd ∈ l₂, { rw ←count_pos, exact lt_of_lt_of_le (count_pos.mpr (mem_cons_self _ _)) (h hd (mem_cons_self _ _)) }, replace this : l₂ ~ hd :: l₂.erase hd := perm_cons_erase this, refine perm.trans _ this.symm, rw [cons_append, diff_cons, perm_cons], refine IH (λ x hx, _), specialize h x (mem_cons_of_mem _ hx), rw (perm_iff_count.mp this) at h, by_cases hx : x = hd, { subst hd, simpa [nat.succ_le_succ_iff] using h }, { simpa [hx] using h } }, end /-- The list version of `multiset.le_iff_count`. -/ lemma subperm_ext_iff {l₁ l₂ : list α} : l₁ <+~ l₂ ↔ ∀ x ∈ l₁, count x l₁ ≤ count x l₂ := begin refine ⟨λ h x hx, subperm.count_le h x, λ h, _⟩, suffices : l₁ <+~ (l₂.diff l₁ ++ l₁), { refine this.trans (perm.subperm _), exact perm_append_comm.trans (subperm_append_diff_self_of_count_le h) }, convert (subperm_append_right _).mpr nil_subperm using 1 end @[simp] lemma subperm_singleton_iff {α} {l : list α} {a : α} : [a] <+~ l ↔ a ∈ l := ⟨λ ⟨s, hla, h⟩, by rwa [perm_singleton.mp hla, singleton_sublist] at h, λ h, ⟨[a], perm.refl _, singleton_sublist.mpr h⟩⟩ lemma subperm.cons_left {l₁ l₂ : list α} (h : l₁ <+~ l₂) (x : α) (hx : count x l₁ < count x l₂) : x :: l₁ <+~ l₂ := begin rw subperm_ext_iff at h ⊢, intros y hy, by_cases hy' : y = x, { subst x, simpa using nat.succ_le_of_lt hx }, { rw count_cons_of_ne hy', refine h y _, simpa [hy'] using hy } end instance decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) | [] [] := is_true $ perm.refl _ | [] (b::l₂) := is_false $ λ h, by have := h.nil_eq; contradiction | (a::l₁) l₂ := by haveI := decidable_perm l₁ (l₂.erase a); exact decidable_of_iff' _ cons_perm_iff_perm_erase -- @[congr] theorem perm.erase_dup {l₁ l₂ : list α} (p : l₁ ~ l₂) : erase_dup l₁ ~ erase_dup l₂ := perm_iff_count.2 $ λ a, if h : a ∈ l₁ then by simp [nodup_erase_dup, h, p.subset h] else by simp [h, mt p.mem_iff.2 h] -- attribute [congr] theorem perm.insert (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : insert a l₁ ~ insert a l₂ := if h : a ∈ l₁ then by simpa [h, p.subset h] using p else by simpa [h, mt p.mem_iff.2 h] using p.cons a theorem perm_insert_swap (x y : α) (l : list α) : insert x (insert y l) ~ insert y (insert x l) := begin by_cases xl : x ∈ l; by_cases yl : y ∈ l; simp [xl, yl], by_cases xy : x = y, { simp [xy] }, simp [not_mem_cons_of_ne_of_not_mem xy xl, not_mem_cons_of_ne_of_not_mem (ne.symm xy) yl], constructor end theorem perm_insert_nth {α} (x : α) (l : list α) {n} (h : n ≤ l.length) : insert_nth n x l ~ x :: l := begin induction l generalizing n, { cases n, refl, cases h }, cases n, { simp [insert_nth] }, { simp only [insert_nth, modify_nth_tail], transitivity, { apply perm.cons, apply l_ih, apply nat.le_of_succ_le_succ h }, { apply perm.swap } } end theorem perm.union_right {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : l₁ ∪ t₁ ~ l₂ ∪ t₁ := begin induction h with a _ _ _ ih _ _ _ _ _ _ _ _ ih_1 ih_2; try {simp}, { exact ih.insert a }, { apply perm_insert_swap }, { exact ih_1.trans ih_2 } end theorem perm.union_left (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : l ∪ t₁ ~ l ∪ t₂ := by induction l; simp [*, perm.insert] -- @[congr] theorem perm.union {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∪ t₁ ~ l₂ ∪ t₂ := (p₁.union_right t₁).trans (p₂.union_left l₂) theorem perm.inter_right {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → l₁ ∩ t₁ ~ l₂ ∩ t₁ := perm.filter _ theorem perm.inter_left (l : list α) {t₁ t₂ : list α} (p : t₁ ~ t₂) : l ∩ t₁ = l ∩ t₂ := filter_congr' (λ a _, p.mem_iff) -- @[congr] theorem perm.inter {l₁ l₂ t₁ t₂ : list α} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : l₁ ∩ t₁ ~ l₂ ∩ t₂ := p₂.inter_left l₂ ▸ p₁.inter_right t₁ theorem perm.inter_append {l t₁ t₂ : list α} (h : disjoint t₁ t₂) : l ∩ (t₁ ++ t₂) ~ l ∩ t₁ ++ l ∩ t₂ := begin induction l, case list.nil { simp }, case list.cons : x xs l_ih { by_cases h₁ : x ∈ t₁, { have h₂ : x ∉ t₂ := h h₁, simp * }, by_cases h₂ : x ∈ t₂, { simp only [*, inter_cons_of_not_mem, false_or, mem_append, inter_cons_of_mem, not_false_iff], transitivity, { apply perm.cons _ l_ih, }, change [x] ++ xs ∩ t₁ ++ xs ∩ t₂ ~ xs ∩ t₁ ++ ([x] ++ xs ∩ t₂), rw [← list.append_assoc], solve_by_elim [perm.append_right, perm_append_comm] }, { simp * } }, end end theorem perm.pairwise_iff {R : α → α → Prop} (S : symmetric R) : ∀ {l₁ l₂ : list α} (p : l₁ ~ l₂), pairwise R l₁ ↔ pairwise R l₂ := suffices ∀ {l₁ l₂}, l₁ ~ l₂ → pairwise R l₁ → pairwise R l₂, from λ l₁ l₂ p, ⟨this p, this p.symm⟩, λ l₁ l₂ p d, begin induction d with a l₁ h d IH generalizing l₂, { rw ← p.nil_eq, constructor }, { have : a ∈ l₂ := p.subset (mem_cons_self _ _), rcases mem_split this with ⟨s₂, t₂, rfl⟩, have p' := (p.trans perm_middle).cons_inv, refine (pairwise_middle S).2 (pairwise_cons.2 ⟨λ b m, _, IH _ p'⟩), exact h _ (p'.symm.subset m) } end theorem perm.nodup_iff {l₁ l₂ : list α} : l₁ ~ l₂ → (nodup l₁ ↔ nodup l₂) := perm.pairwise_iff $ @ne.symm α theorem perm.bind_right {l₁ l₂ : list α} (f : α → list β) (p : l₁ ~ l₂) : l₁.bind f ~ l₂.bind f := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact IH.append_left _ }, { simp, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end theorem perm.bind_left (l : list α) {f g : α → list β} (h : ∀ a, f a ~ g a) : l.bind f ~ l.bind g := by induction l with a l IH; simp; exact (h a).append IH theorem bind_append_perm (l : list α) (f g : α → list β) : l.bind f ++ l.bind g ~ l.bind (λ x, f x ++ g x) := begin induction l with a l IH; simp, refine (perm.trans _ (IH.append_left _)).append_left _, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append_right _ end theorem perm.product_right {l₁ l₂ : list α} (t₁ : list β) (p : l₁ ~ l₂) : product l₁ t₁ ~ product l₂ t₁ := p.bind_right _ theorem perm.product_left (l : list α) {t₁ t₂ : list β} (p : t₁ ~ t₂) : product l t₁ ~ product l t₂ := perm.bind_left _ $ λ a, p.map _ @[congr] theorem perm.product {l₁ l₂ : list α} {t₁ t₂ : list β} (p₁ : l₁ ~ l₂) (p₂ : t₁ ~ t₂) : product l₁ t₁ ~ product l₂ t₂ := (p₁.product_right t₁).trans (p₂.product_left l₂) theorem sublists_cons_perm_append (a : α) (l : list α) : sublists (a :: l) ~ sublists l ++ map (cons a) (sublists l) := begin simp only [sublists, sublists_aux_cons_cons, cons_append, perm_cons], refine (perm.cons _ _).trans perm_middle.symm, induction sublists_aux l cons with b l IH; simp, exact (IH.cons _).trans perm_middle.symm end theorem sublists_perm_sublists' : ∀ l : list α, sublists l ~ sublists' l | [] := perm.refl _ | (a::l) := let IH := sublists_perm_sublists' l in by rw sublists'_cons; exact (sublists_cons_perm_append _ _).trans (IH.append (IH.map _)) theorem revzip_sublists (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists → l₁ ++ l₂ ~ l := begin rw revzip, apply list.reverse_rec_on l, { intros l₁ l₂ h, simp at h, simp [h] }, { intros l a IH l₁ l₂ h, rw [sublists_concat, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [skip, {simp}], simp only [prod.mk.inj_iff, mem_map, mem_append, prod.map_mk, prod.exists] at h, rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', l₂, h, rfl, rfl⟩, { rw ← append_assoc, exact (IH _ _ h).append_right _ }, { rw append_assoc, apply (perm_append_comm.append_left _).trans, rw ← append_assoc, exact (IH _ _ h).append_right _ } } end theorem revzip_sublists' (l : list α) : ∀ l₁ l₂, (l₁, l₂) ∈ revzip l.sublists' → l₁ ++ l₂ ~ l := begin rw revzip, induction l with a l IH; intros l₁ l₂ h, { simp at h, simp [h] }, { rw [sublists'_cons, reverse_append, zip_append, ← map_reverse, zip_map_right, zip_map_left] at h; [simp at h, simp], rcases h with ⟨l₁, l₂', h, rfl, rfl⟩ | ⟨l₁', h, rfl⟩, { exact perm_middle.trans ((IH _ _ h).cons _) }, { exact (IH _ _ h).cons _ } } end theorem perm_lookmap (f : α → option α) {l₁ l₂ : list α} (H : pairwise (λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d) l₁) (p : l₁ ~ l₂) : lookmap f l₁ ~ lookmap f l₂ := begin let F := λ a b, ∀ (c ∈ f a) (d ∈ f b), a = b ∧ c = d, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { cases h : f a, { simp [h], exact IH (pairwise_cons.1 H).2 }, { simp [lookmap_cons_some _ _ h, p] } }, { cases h₁ : f a with c; cases h₂ : f b with d, { simp [h₁, h₂], apply swap }, { simp [h₁, lookmap_cons_some _ _ h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, h₂], apply swap }, { simp [lookmap_cons_some _ _ h₁, lookmap_cons_some _ _ h₂], rcases (pairwise_cons.1 H).1 _ (or.inl rfl) _ h₂ _ h₁ with ⟨rfl, rfl⟩, refl } }, { refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)), exact λ a b h c h₁ d h₂, (h d h₂ c h₁).imp eq.symm eq.symm } end theorem perm.erasep (f : α → Prop) [decidable_pred f] {l₁ l₂ : list α} (H : pairwise (λ a b, f a → f b → false) l₁) (p : l₁ ~ l₂) : erasep f l₁ ~ erasep f l₂ := begin let F := λ a b, f a → f b → false, change pairwise F l₁ at H, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { by_cases h : f a, { simp [h, p] }, { simp [h], exact IH (pairwise_cons.1 H).2 } }, { by_cases h₁ : f a; by_cases h₂ : f b; simp [h₁, h₂], { cases (pairwise_cons.1 H).1 _ (or.inl rfl) h₂ h₁ }, { apply swap } }, { refine (IH₁ H).trans (IH₂ ((p₁.pairwise_iff _).1 H)), exact λ a b h h₁ h₂, h h₂ h₁ } end lemma perm.take_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ) (h : xs ~ ys) (h' : ys.nodup) : xs.take n ~ ys.inter (xs.take n) := begin simp only [list.inter] at *, induction h generalizing n, case list.perm.nil : n { simp only [not_mem_nil, filter_false, take_nil] }, case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih n { cases n; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos, perm_cons, take, not_mem_nil, filter_false], cases h' with _ _ h₁ h₂, convert h_ih h₂ n using 1, apply filter_congr', introv h, simp only [(h₁ x h).symm, false_or], }, case list.perm.swap : h_x h_y h_l n { cases h' with _ _ h₁ h₂, cases h₂ with _ _ h₂ h₃, have := h₁ _ (or.inl rfl), cases n; simp only [mem_cons_iff, not_mem_nil, filter_false, take], cases n; simp only [mem_cons_iff, false_or, true_or, filter, *, nat.nat_zero_eq_zero, if_true, not_mem_nil, eq_self_iff_true, or_false, if_false, perm_cons, take], { rw filter_eq_nil.2, intros, solve_by_elim [ne.symm], }, { convert perm.swap _ _ _, rw @filter_congr' _ _ (∈ take n h_l), { clear h₁, induction n generalizing h_l, { simp }, cases h_l; simp only [mem_cons_iff, true_or, eq_self_iff_true, filter_cons_of_pos, true_and, take, not_mem_nil, filter_false, take_nil], cases h₃ with _ _ h₃ h₄, rwa [@filter_congr' _ _ (∈ take n_n h_l_tl), n_ih], { introv h, apply h₂ _ (or.inr h), }, { introv h, simp only [(h₃ x h).symm, false_or], }, }, { introv h, simp only [(h₂ x h).symm, (h₁ x (or.inr h)).symm, false_or], } } }, case list.perm.trans : h_l₁ h_l₂ h_l₃ h₀ h₁ h_ih₀ h_ih₁ n { transitivity, { apply h_ih₀, rwa h₁.nodup_iff }, { apply perm.filter _ h₁, } }, end lemma perm.drop_inter {α} [decidable_eq α] {xs ys : list α} (n : ℕ) (h : xs ~ ys) (h' : ys.nodup) : xs.drop n ~ ys.inter (xs.drop n) := begin by_cases h'' : n ≤ xs.length, { let n' := xs.length - n, have h₀ : n = xs.length - n', { dsimp [n'], rwa tsub_tsub_cancel_of_le, } , have h₁ : n' ≤ xs.length, { apply tsub_le_self }, have h₂ : xs.drop n = (xs.reverse.take n').reverse, { rw [reverse_take _ h₁, h₀, reverse_reverse], }, rw [h₂], apply (reverse_perm _).trans, rw inter_reverse, apply perm.take_inter _ _ h', apply (reverse_perm _).trans; assumption, }, { have : drop n xs = [], { apply eq_nil_of_length_eq_zero, rw [length_drop, tsub_eq_zero_iff_le], apply le_of_not_ge h'' }, simp [this, list.inter], } end lemma perm.slice_inter {α} [decidable_eq α] {xs ys : list α} (n m : ℕ) (h : xs ~ ys) (h' : ys.nodup) : list.slice n m xs ~ ys ∩ (list.slice n m xs) := begin simp only [slice_eq], have : n ≤ n + m := nat.le_add_right _ _, have := h.nodup_iff.2 h', apply perm.trans _ (perm.inter_append _).symm; solve_by_elim [perm.append, perm.drop_inter, perm.take_inter, disjoint_take_drop, h, h'] { max_depth := 7 }, end /- enumerating permutations -/ section permutations theorem perm_of_mem_permutations_aux : ∀ {ts is l : list α}, l ∈ permutations_aux ts is → l ~ ts ++ is := begin refine permutations_aux.rec (by simp) _, introv IH1 IH2 m, rw [permutations_aux_cons, permutations, mem_foldr_permutations_aux2] at m, rcases m with m | ⟨l₁, l₂, m, _, e⟩, { exact (IH1 m).trans perm_middle }, { subst e, have p : l₁ ++ l₂ ~ is, { simp [permutations] at m, cases m with e m, {simp [e]}, exact is.append_nil ▸ IH2 m }, exact ((perm_middle.trans (p.cons _)).append_right _).trans (perm_append_comm.cons _) } end theorem perm_of_mem_permutations {l₁ l₂ : list α} (h : l₁ ∈ permutations l₂) : l₁ ~ l₂ := (eq_or_mem_of_mem_cons h).elim (λ e, e ▸ perm.refl _) (λ m, append_nil l₂ ▸ perm_of_mem_permutations_aux m) theorem length_permutations_aux : ∀ ts is : list α, length (permutations_aux ts is) + is.length! = (length ts + length is)! := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2, have IH2 : length (permutations_aux is nil) + 1 = is.length!, { simpa using IH2 }, simp [-add_comm, nat.factorial, nat.add_succ, mul_comm] at IH1, rw [permutations_aux_cons, length_foldr_permutations_aux2' _ _ _ _ _ (λ l m, (perm_of_mem_permutations m).length_eq), permutations, length, length, IH2, nat.succ_add, nat.factorial_succ, mul_comm (nat.succ _), ← IH1, add_comm (_*_), add_assoc, nat.mul_succ, mul_comm] end theorem length_permutations (l : list α) : length (permutations l) = (length l)! := length_permutations_aux l [] theorem mem_permutations_of_perm_lemma {is l : list α} (H : l ~ [] ++ is → (∃ ts' ~ [], l = ts' ++ is) ∨ l ∈ permutations_aux is []) : l ~ is → l ∈ permutations is := by simpa [permutations, perm_nil] using H theorem mem_permutations_aux_of_perm : ∀ {ts is l : list α}, l ~ is ++ ts → (∃ is' ~ is, l = is' ++ ts) ∨ l ∈ permutations_aux ts is := begin refine permutations_aux.rec (by simp) _, intros t ts is IH1 IH2 l p, rw [permutations_aux_cons, mem_foldr_permutations_aux2], rcases IH1 (p.trans perm_middle) with ⟨is', p', e⟩ | m, { clear p, subst e, rcases mem_split (p'.symm.subset (mem_cons_self _ _)) with ⟨l₁, l₂, e⟩, subst is', have p := (perm_middle.symm.trans p').cons_inv, cases l₂ with a l₂', { exact or.inl ⟨l₁, by simpa using p⟩ }, { exact or.inr (or.inr ⟨l₁, a::l₂', mem_permutations_of_perm_lemma IH2 p, by simp⟩) } }, { exact or.inr (or.inl m) } end @[simp] theorem mem_permutations {s t : list α} : s ∈ permutations t ↔ s ~ t := ⟨perm_of_mem_permutations, mem_permutations_of_perm_lemma mem_permutations_aux_of_perm⟩ theorem perm_permutations'_aux_comm (a b : α) (l : list α) : (permutations'_aux a l).bind (permutations'_aux b) ~ (permutations'_aux b l).bind (permutations'_aux a) := begin induction l with c l ih, {simp [swap]}, simp [permutations'_aux], apply perm.swap', have : ∀ a b, (map (cons c) (permutations'_aux a l)).bind (permutations'_aux b) ~ map (cons b ∘ cons c) (permutations'_aux a l) ++ map (cons c) ((permutations'_aux a l).bind (permutations'_aux b)), { intros, simp only [map_bind, permutations'_aux], refine (bind_append_perm _ (λ x, [_]) _).symm.trans _, rw [← map_eq_bind, ← bind_map] }, refine (((this _ _).append_left _).trans _).trans ((this _ _).append_left _).symm, rw [← append_assoc, ← append_assoc], exact perm_append_comm.append (ih.map _), end theorem perm.permutations' {s t : list α} (p : s ~ t) : permutations' s ~ permutations' t := begin induction p with a s t p IH a b l s t u p₁ p₂ IH₁ IH₂, {simp}, { simp only [permutations'], exact IH.bind_right _ }, { simp only [permutations'], rw [bind_assoc, bind_assoc], apply perm.bind_left, apply perm_permutations'_aux_comm }, { exact IH₁.trans IH₂ } end theorem permutations_perm_permutations' (ts : list α) : ts.permutations ~ ts.permutations' := begin obtain ⟨n, h⟩ : ∃ n, length ts < n := ⟨_, nat.lt_succ_self _⟩, induction n with n IH generalizing ts, {cases h}, refine list.reverse_rec_on ts (λ h, _) (λ ts t _ h, _) h, {simp [permutations]}, rw [← concat_eq_append, length_concat, nat.succ_lt_succ_iff] at h, have IH₂ := (IH ts.reverse (by rwa [length_reverse])).trans (reverse_perm _).permutations', simp only [permutations_append, foldr_permutations_aux2, permutations_aux_nil, permutations_aux_cons, append_nil], refine (perm_append_comm.trans ((IH₂.bind_right _).append ((IH _ h).map _))).trans (perm.trans _ perm_append_comm.permutations'), rw [map_eq_bind, singleton_append, permutations'], convert bind_append_perm _ _ _, funext ys, rw [permutations'_aux_eq_permutations_aux2, permutations_aux2_append] end @[simp] theorem mem_permutations' {s t : list α} : s ∈ permutations' t ↔ s ~ t := (permutations_perm_permutations' _).symm.mem_iff.trans mem_permutations theorem perm.permutations {s t : list α} (h : s ~ t) : permutations s ~ permutations t := (permutations_perm_permutations' _).trans $ h.permutations'.trans (permutations_perm_permutations' _).symm @[simp] theorem perm_permutations_iff {s t : list α} : permutations s ~ permutations t ↔ s ~ t := ⟨λ h, mem_permutations.1 $ h.mem_iff.1 $ mem_permutations.2 (perm.refl _), perm.permutations⟩ @[simp] theorem perm_permutations'_iff {s t : list α} : permutations' s ~ permutations' t ↔ s ~ t := ⟨λ h, mem_permutations'.1 $ h.mem_iff.1 $ mem_permutations'.2 (perm.refl _), perm.permutations'⟩ lemma nth_le_permutations'_aux (s : list α) (x : α) (n : ℕ) (hn : n < length (permutations'_aux x s)) : (permutations'_aux x s).nth_le n hn = s.insert_nth n x := begin induction s with y s IH generalizing n, { simp only [length, permutations'_aux, nat.lt_one_iff] at hn, simp [hn] }, { cases n, { simp }, { simpa using IH _ _ } } end lemma count_permutations'_aux_self [decidable_eq α] (l : list α) (x : α) : count (x :: l) (permutations'_aux x l) = length (take_while ((=) x) l) + 1 := begin induction l with y l IH generalizing x, { simp [take_while], }, { rw [permutations'_aux, count_cons_self], by_cases hx : x = y, { subst hx, simpa [take_while, nat.succ_inj'] using IH _ }, { rw take_while, rw if_neg hx, cases permutations'_aux x l with a as, { simp }, { rw [count_eq_zero_of_not_mem, length, zero_add], simp [hx, ne.symm hx] } } } end @[simp] lemma length_permutations'_aux (s : list α) (x : α) : length (permutations'_aux x s) = length s + 1 := begin induction s with y s IH, { simp }, { simpa using IH } end @[simp] lemma permutations'_aux_nth_le_zero (s : list α) (x : α) (hn : 0 < length (permutations'_aux x s) := by simp) : (permutations'_aux x s).nth_le 0 hn = x :: s := nth_le_permutations'_aux _ _ _ _ lemma injective_permutations'_aux (x : α) : function.injective (permutations'_aux x) := begin intros s t h, apply insert_nth_injective s.length x, have hl : s.length = t.length := by simpa using congr_arg length h, rw [←nth_le_permutations'_aux s x s.length (by simp), ←nth_le_permutations'_aux t x s.length (by simp [hl])], simp [h, hl] end lemma nodup_permutations'_aux_of_not_mem (s : list α) (x : α) (hx : x ∉ s) : nodup (permutations'_aux x s) := begin induction s with y s IH, { simp }, { simp only [not_or_distrib, mem_cons_iff] at hx, simp only [not_and, exists_eq_right_right, mem_map, permutations'_aux, nodup_cons], refine ⟨λ _, ne.symm hx.left, _⟩, rw nodup_map_iff, { exact IH hx.right }, { simp } } end lemma nodup_permutations'_aux_iff {s : list α} {x : α} : nodup (permutations'_aux x s) ↔ x ∉ s := begin refine ⟨λ h, _, nodup_permutations'_aux_of_not_mem _ _⟩, intro H, obtain ⟨k, hk, hk'⟩ := nth_le_of_mem H, rw nodup_iff_nth_le_inj at h, suffices : k = k + 1, { simpa using this }, refine h k (k + 1) _ _ _, { simpa [nat.lt_succ_iff] using hk.le }, { simpa using hk }, rw [nth_le_permutations'_aux, nth_le_permutations'_aux], have hl : length (insert_nth k x s) = length (insert_nth (k + 1) x s), { rw [length_insert_nth _ _ hk.le, length_insert_nth _ _ (nat.succ_le_of_lt hk)] }, refine ext_le hl (λ n hn hn', _), rcases lt_trichotomy n k with H|rfl|H, { rw [nth_le_insert_nth_of_lt _ _ _ _ H (H.trans hk), nth_le_insert_nth_of_lt _ _ _ _ (H.trans (nat.lt_succ_self _))] }, { rw [nth_le_insert_nth_self _ _ _ hk.le, nth_le_insert_nth_of_lt _ _ _ _ (nat.lt_succ_self _) hk, hk'] }, { rcases (nat.succ_le_of_lt H).eq_or_lt with rfl|H', { rw [nth_le_insert_nth_self _ _ _ (nat.succ_le_of_lt hk)], convert hk' using 1, convert nth_le_insert_nth_add_succ _ _ _ 0 _, simpa using hk }, { obtain ⟨m, rfl⟩ := nat.exists_eq_add_of_lt H', rw [length_insert_nth _ _ hk.le, nat.succ_lt_succ_iff, nat.succ_add] at hn, rw nth_le_insert_nth_add_succ, convert nth_le_insert_nth_add_succ s x k m.succ _ using 2, { simp [nat.add_succ, nat.succ_add] }, { simp [add_left_comm, add_comm] }, { simpa [nat.add_succ] using hn }, { simpa [nat.succ_add] using hn } } } end lemma nodup_permutations (s : list α) (hs : nodup s) : nodup s.permutations := begin rw (permutations_perm_permutations' s).nodup_iff, induction hs with x l h h' IH, { simp }, { rw [permutations'], rw nodup_bind, split, { intros ys hy, rw mem_permutations' at hy, rw [nodup_permutations'_aux_iff, hy.mem_iff], exact λ H, h x H rfl }, { refine IH.pairwise_of_forall_ne (λ as ha bs hb H, _), rw disjoint_iff_ne, rintro a ha' b hb' rfl, obtain ⟨n, hn, hn'⟩ := nth_le_of_mem ha', obtain ⟨m, hm, hm'⟩ := nth_le_of_mem hb', rw mem_permutations' at ha hb, have hl : as.length = bs.length := (ha.trans hb.symm).length_eq, simp only [nat.lt_succ_iff, length_permutations'_aux] at hn hm, rw nth_le_permutations'_aux at hn' hm', have hx : nth_le (insert_nth n x as) m (by rwa [length_insert_nth _ _ hn, nat.lt_succ_iff, hl]) = x, { simp [hn', ←hm', hm] }, have hx' : nth_le (insert_nth m x bs) n (by rwa [length_insert_nth _ _ hm, nat.lt_succ_iff, ←hl]) = x, { simp [hm', ←hn', hn] }, rcases lt_trichotomy n m with ht|ht|ht, { suffices : x ∈ bs, { exact h x (hb.subset this) rfl }, rw [←hx', nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hm)], exact nth_le_mem _ _ _ }, { simp only [ht] at hm' hn', rw ←hm' at hn', exact H (insert_nth_injective _ _ hn') }, { suffices : x ∈ as, { exact h x (ha.subset this) rfl }, rw [←hx, nth_le_insert_nth_of_lt _ _ _ _ ht (ht.trans_le hn)], exact nth_le_mem _ _ _ } } } end -- TODO: `nodup s.permutations ↔ nodup s` -- TODO: `count s s.permutations = (zip_with count s s.tails).prod` end permutations end list
abe6ca25b01eac508d295aa9c6b0f932c57e3979
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/omega/int/preterm.lean
3936d85c9df91c7dcc0b85384400e2ffa35b5c37
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
2,814
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Seul Baek -/ /- Linear integer arithmetic terms in pre-normalized form. -/ import tactic.omega.term namespace omega namespace int /-- The shadow syntax for arithmetic terms. All constants are reified to `cst` (e.g., `-5` is reified to `cst -5`) and all other atomic terms are reified to `exp` (e.g., `-5 * (gcd 14 -7)` is reified to `exp -5 \`(gcd 14 -7)`). `exp` accepts a coefficient of type `int` as its first argument because multiplication by constant is allowed by the omega test. -/ meta inductive exprterm : Type | cst : int → exprterm | exp : int → expr → exprterm | add : exprterm → exprterm → exprterm /-- Similar to `exprterm`, except that all exprs are now replaced with de Brujin indices of type `nat`. This is akin to generalizing over the terms represented by the said exprs. -/ @[derive has_reflect, derive inhabited] inductive preterm : Type | cst : int → preterm | var : int → nat → preterm | add : preterm → preterm → preterm localized "notation `&` k := omega.int.preterm.cst k" in omega.int localized "infix ` ** ` : 300 := omega.int.preterm.var" in omega.int localized "notation t `+*` s := omega.int.preterm.add t s" in omega.int namespace preterm /-- Preterm evaluation -/ @[simp] def val (v : nat → int) : preterm → int | (& i) := i | (i ** n) := if i = 1 then v n else if i = -1 then -(v n) else (v n) * i | (t1 +* t2) := t1.val + t2.val /-- Fresh de Brujin index not used by any variable in argument -/ def fresh_index : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_index t2.fresh_index @[simp] def add_one (t : preterm) : preterm := t +* (&1) def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" end preterm open_locale list.func -- get notation for list.func.set /-- Return a term (which is in canonical form by definition) that is equivalent to the input preterm -/ @[simp] def canonize : preterm → term | (& i) := ⟨i, []⟩ | (i ** n) := ⟨0, [] {n ↦ i}⟩ | (t1 +* t2) := term.add (canonize t1) (canonize t2) @[simp] lemma val_canonize {v : nat → int} : ∀ {t : preterm}, (canonize t).val v = t.val v | (& i) := by simp only [preterm.val, add_zero, term.val, canonize, coeffs.val_nil] | (i ** n) := begin simp only [coeffs.val_set, canonize, preterm.val, zero_add, term.val], split_ifs with h1 h2, { simp only [one_mul, h1] }, { simp only [neg_mul_eq_neg_mul_symm, one_mul, h2] }, { rw mul_comm } end | (t +* s) := by simp only [canonize, val_canonize, term.val_add, preterm.val] end int end omega
83dadc76048b45b161d96ff5d3530f18b55c8872
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/record10.lean
e5168c0fcf5e6a50b296d65960b3e37667e296af
[ "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
487
lean
set_option old_structure_cmd true #print prefix semigroup #print "=======================" structure [class] has_two_muls (A : Type) extends has_mul A renaming mul→mul1, private has_mul A renaming mul→mul2 #print prefix has_two_muls #print "=======================" structure [class] another_two_muls (A : Type) extends has_mul A renaming mul→mul1, has_mul A renaming mul→mul2
c785520c0a6f807a3b6f75cf51d202cf7da21680
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/zmod/quotient.lean
3fd7a8587f6841ecfa01145d6d142196578e1b17
[ "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,369
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.zmod.basic import group_theory.quotient_group import ring_theory.int.basic /-! # `zmod n` and quotient groups / rings This file relates `zmod n` to the quotient group `quotient_add_group.quotient (add_subgroup.zmultiples n)` and to the quotient ring `(ideal.span {n}).quotient`. ## Main definitions - `zmod.quotient_zmultiples_nat_equiv_zmod` and `zmod.quotient_zmultiples_equiv_zmod`: `zmod n` is the group quotient of `ℤ` by `n ℤ := add_subgroup.zmultiples (n)`, (where `n : ℕ` and `n : ℤ` respectively) - `zmod.quotient_span_nat_equiv_zmod` and `zmod.quotient_span_equiv_zmod`: `zmod n` is the ring quotient of `ℤ` by `n ℤ : ideal.span {n}` (where `n : ℕ` and `n : ℤ` respectively) - `zmod.lift n f` is the map from `zmod n` induced by `f : ℤ →+ A` that maps `n` to `0`. ## Tags zmod, quotient group, quotient ring, ideal quotient -/ open quotient_add_group open zmod variables (n : ℕ) {A R : Type*} [add_group A] [ring R] namespace int /-- `ℤ` modulo multiples of `n : ℕ` is `zmod n`. -/ def quotient_zmultiples_nat_equiv_zmod : ℤ ⧸ add_subgroup.zmultiples (n : ℤ) ≃+ zmod n := (equiv_quotient_of_eq (zmod.ker_int_cast_add_hom _)).symm.trans $ quotient_ker_equiv_of_right_inverse (int.cast_add_hom (zmod n)) coe int_cast_zmod_cast /-- `ℤ` modulo multiples of `a : ℤ` is `zmod a.nat_abs`. -/ def quotient_zmultiples_equiv_zmod (a : ℤ) : ℤ ⧸ add_subgroup.zmultiples a ≃+ zmod a.nat_abs := (equiv_quotient_of_eq (zmultiples_nat_abs a)).symm.trans (quotient_zmultiples_nat_equiv_zmod a.nat_abs) /-- `ℤ` modulo the ideal generated by `n : ℕ` is `zmod n`. -/ def quotient_span_nat_equiv_zmod : ℤ ⧸ ideal.span {↑n} ≃+* zmod n := (ideal.quot_equiv_of_eq (zmod.ker_int_cast_ring_hom _)).symm.trans $ ring_hom.quotient_ker_equiv_of_right_inverse $ show function.right_inverse coe (int.cast_ring_hom (zmod n)), from int_cast_zmod_cast /-- `ℤ` modulo the ideal generated by `a : ℤ` is `zmod a.nat_abs`. -/ def quotient_span_equiv_zmod (a : ℤ) : ℤ ⧸ ideal.span ({a} : set ℤ) ≃+* zmod a.nat_abs := (ideal.quot_equiv_of_eq (span_nat_abs a)).symm.trans (quotient_span_nat_equiv_zmod a.nat_abs) end int
dd81138b1b3870d821b9b5af2c4fc8a61bf298b3
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/category_theory/functor/epi_mono.lean
cb3bff689fb2a6f8dc52d256876754c5bc4f3fc7
[ "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
8,747
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.epi_mono /-! # Preservation and reflection of monomorphisms and epimorphisms We provide typeclasses that state that a functor preserves or reflects monomorphisms or epimorphisms. -/ open category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ namespace category_theory.functor variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] {E : Type u₃} [category.{v₃} E] /-- A functor preserves monomorphisms if it maps monomorphisms to monomorphisms. -/ class preserves_monomorphisms (F : C ⥤ D) : Prop := (preserves : ∀ {X Y : C} (f : X ⟶ Y) [mono f], mono (F.map f)) instance map_mono (F : C ⥤ D) [preserves_monomorphisms F] {X Y : C} (f : X ⟶ Y) [mono f] : mono (F.map f) := preserves_monomorphisms.preserves f /-- A functor preserves epimorphisms if it maps epimorphisms to epimorphisms. -/ class preserves_epimorphisms (F : C ⥤ D) : Prop := (preserves : ∀ {X Y : C} (f : X ⟶ Y) [epi f], epi (F.map f)) instance map_epi (F : C ⥤ D) [preserves_epimorphisms F] {X Y : C} (f : X ⟶ Y) [epi f] : epi (F.map f) := preserves_epimorphisms.preserves f /-- A functor reflects monomorphisms if morphisms that are mapped to monomorphisms are themselves monomorphisms. -/ class reflects_monomorphisms (F : C ⥤ D) : Prop := (reflects : ∀ {X Y : C} (f : X ⟶ Y), mono (F.map f) → mono f) lemma mono_of_mono_map (F : C ⥤ D) [reflects_monomorphisms F] {X Y : C} {f : X ⟶ Y} (h : mono (F.map f)) : mono f := reflects_monomorphisms.reflects f h /-- A functor reflects epimorphisms if morphisms that are mapped to epimorphisms are themselves epimorphisms. -/ class reflects_epimorphisms (F : C ⥤ D) : Prop := (reflects : ∀ {X Y : C} (f : X ⟶ Y), epi (F.map f) → epi f) lemma epi_of_epi_map (F : C ⥤ D) [reflects_epimorphisms F] {X Y : C} {f : X ⟶ Y} (h : epi (F.map f)) : epi f := reflects_epimorphisms.reflects f h instance preserves_monomorphisms_comp (F : C ⥤ D) (G : D ⥤ E) [preserves_monomorphisms F] [preserves_monomorphisms G] : preserves_monomorphisms (F ⋙ G) := { preserves := λ X Y f h, by { rw comp_map, exactI infer_instance } } instance preserves_epimorphisms_comp (F : C ⥤ D) (G : D ⥤ E) [preserves_epimorphisms F] [preserves_epimorphisms G] : preserves_epimorphisms (F ⋙ G) := { preserves := λ X Y f h, by { rw comp_map, exactI infer_instance } } instance reflects_monomorphisms_comp (F : C ⥤ D) (G : D ⥤ E) [reflects_monomorphisms F] [reflects_monomorphisms G] : reflects_monomorphisms (F ⋙ G) := { reflects := λ X Y f h, (F.mono_of_mono_map (G.mono_of_mono_map h)) } instance reflects_epimorphisms_comp (F : C ⥤ D) (G : D ⥤ E) [reflects_epimorphisms F] [reflects_epimorphisms G] : reflects_epimorphisms (F ⋙ G) := { reflects := λ X Y f h, (F.epi_of_epi_map (G.epi_of_epi_map h)) } lemma preserves_monomorphisms.of_iso {F G : C ⥤ D} [preserves_monomorphisms F] (α : F ≅ G) : preserves_monomorphisms G := { preserves := λ X Y f h, begin haveI : mono (F.map f ≫ (α.app Y).hom) := by exactI mono_comp _ _, convert (mono_comp _ _ : mono ((α.app X).inv ≫ F.map f ≫ (α.app Y).hom)), rw [iso.eq_inv_comp, iso.app_hom, iso.app_hom, nat_trans.naturality] end } lemma preserves_monomorphisms.iso_iff {F G : C ⥤ D} (α : F ≅ G) : preserves_monomorphisms F ↔ preserves_monomorphisms G := ⟨λ h, by exactI preserves_monomorphisms.of_iso α, λ h, by exactI preserves_monomorphisms.of_iso α.symm⟩ lemma preserves_epimorphisms.of_iso {F G : C ⥤ D} [preserves_epimorphisms F] (α : F ≅ G) : preserves_epimorphisms G := { preserves := λ X Y f h, begin haveI : epi (F.map f ≫ (α.app Y).hom) := by exactI epi_comp _ _, convert (epi_comp _ _ : epi ((α.app X).inv ≫ F.map f ≫ (α.app Y).hom)), rw [iso.eq_inv_comp, iso.app_hom, iso.app_hom, nat_trans.naturality] end } lemma preserves_epimorphisms.iso_iff {F G : C ⥤ D} (α : F ≅ G) : preserves_epimorphisms F ↔ preserves_epimorphisms G := ⟨λ h, by exactI preserves_epimorphisms.of_iso α, λ h, by exactI preserves_epimorphisms.of_iso α.symm⟩ lemma reflects_monomorphisms.of_iso {F G : C ⥤ D} [reflects_monomorphisms F] (α : F ≅ G) : reflects_monomorphisms G := { reflects := λ X Y f h, begin apply F.mono_of_mono_map, haveI : mono (G.map f ≫ (α.app Y).inv) := by exactI mono_comp _ _, convert (mono_comp _ _ : mono ((α.app X).hom ≫ G.map f ≫ (α.app Y).inv)), rw [← category.assoc, iso.eq_comp_inv, iso.app_hom, iso.app_hom, nat_trans.naturality] end } lemma reflects_monomorphisms.iso_iff {F G : C ⥤ D} (α : F ≅ G) : reflects_monomorphisms F ↔ reflects_monomorphisms G := ⟨λ h, by exactI reflects_monomorphisms.of_iso α, λ h, by exactI reflects_monomorphisms.of_iso α.symm⟩ lemma reflects_epimorphisms.of_iso {F G : C ⥤ D} [reflects_epimorphisms F] (α : F ≅ G) : reflects_epimorphisms G := { reflects := λ X Y f h, begin apply F.epi_of_epi_map, haveI : epi (G.map f ≫ (α.app Y).inv) := by exactI epi_comp _ _, convert (epi_comp _ _ : epi ((α.app X).hom ≫ G.map f ≫ (α.app Y).inv)), rw [← category.assoc, iso.eq_comp_inv, iso.app_hom, iso.app_hom, nat_trans.naturality] end } lemma reflects_epimorphisms.iso_iff {F G : C ⥤ D} (α : F ≅ G) : reflects_epimorphisms F ↔ reflects_epimorphisms G := ⟨λ h, by exactI reflects_epimorphisms.of_iso α, λ h, by exactI reflects_epimorphisms.of_iso α.symm⟩ lemma preserves_epimorphsisms_of_adjunction {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) : preserves_epimorphisms F := { preserves := λ X Y f hf, ⟨begin introsI Z g h H, replace H := congr_arg (adj.hom_equiv X Z) H, rwa [adj.hom_equiv_naturality_left, adj.hom_equiv_naturality_left, cancel_epi, equiv.apply_eq_iff_eq] at H end⟩ } @[priority 100] instance preserves_epimorphisms_of_is_left_adjoint (F : C ⥤ D) [is_left_adjoint F] : preserves_epimorphisms F := preserves_epimorphsisms_of_adjunction (adjunction.of_left_adjoint F) lemma preserves_monomorphisms_of_adjunction {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) : preserves_monomorphisms G := { preserves := λ X Y f hf, ⟨begin introsI Z g h H, replace H := congr_arg (adj.hom_equiv Z Y).symm H, rwa [adj.hom_equiv_naturality_right_symm, adj.hom_equiv_naturality_right_symm, cancel_mono, equiv.apply_eq_iff_eq] at H end⟩ } @[priority 100] instance preserves_monomorphisms_of_is_right_adjoint (F : C ⥤ D) [is_right_adjoint F] : preserves_monomorphisms F := preserves_monomorphisms_of_adjunction (adjunction.of_right_adjoint F) @[priority 100] instance reflects_monomorphisms_of_faithful (F : C ⥤ D) [faithful F] : reflects_monomorphisms F := { reflects := λ X Y f hf, ⟨λ Z g h hgh, by exactI F.map_injective ((cancel_mono (F.map f)).1 (by rw [← F.map_comp, hgh, F.map_comp]))⟩ } @[priority 100] instance reflects_epimorphisms_of_faithful (F : C ⥤ D) [faithful F] : reflects_epimorphisms F := { reflects := λ X Y f hf, ⟨λ Z g h hgh, by exactI F.map_injective ((cancel_epi (F.map f)).1 (by rw [← F.map_comp, hgh, F.map_comp]))⟩ } section variables (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) /-- If `F` is a fully faithful functor, split epimorphisms are preserved and reflected by `F`. -/ def split_epi_equiv [full F] [faithful F] : split_epi f ≃ split_epi (F.map f) := { to_fun := λ f, f.map F, inv_fun := λ s, begin refine ⟨F.preimage s.section_, _⟩, apply F.map_injective, simp only [map_comp, image_preimage, map_id], apply split_epi.id, end, left_inv := by tidy, right_inv := by tidy, } /-- If `F` is a fully faithful functor, split monomorphisms are preserved and reflected by `F`. -/ def split_mono_equiv [full F] [faithful F] : split_mono f ≃ split_mono (F.map f) := { to_fun := λ f, f.map F, inv_fun := λ s, begin refine ⟨F.preimage s.retraction, _⟩, apply F.map_injective, simp only [map_comp, image_preimage, map_id], apply split_mono.id, end, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma epi_map_iff_epi [hF₁ : preserves_epimorphisms F] [hF₂ : reflects_epimorphisms F] : epi (F.map f) ↔ epi f := begin split, { exact F.epi_of_epi_map, }, { introI h, exact F.map_epi f, }, end @[simp] lemma mono_map_iff_mono [hF₁ : preserves_monomorphisms F] [hF₂ : reflects_monomorphisms F] : mono (F.map f) ↔ mono f := begin split, { exact F.mono_of_mono_map, }, { introI h, exact F.map_mono f, }, end end end category_theory.functor
50804f9b21fc6817eaafa246addbe68d1dde9d80
f3849be5d845a1cb97680f0bbbe03b85518312f0
/old_library/init/datatypes.lean
23ef9cbdae74df805de09da4a750b77e8e4e3343
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,565
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Basic datatypes -/ prelude notation `Prop` := Type 0 notation `Type₂` := Type 2 notation `Type₃` := Type 3 universe variables u v inductive poly_unit : Type u | star : poly_unit inductive unit : Type | star : unit inductive true : Prop | intro : true inductive false : Prop inductive empty : Type inductive eq {A : Type u} (a : A) : A → Prop | refl : eq a inductive heq {A : Type u} (a : A) : Π {B : Type u}, B → Prop | refl : heq a structure prod (A : Type u) (B : Type v) := (fst : A) (snd : B) inductive and (a b : Prop) : Prop | intro : a → b → and definition and.elim_left {a b : Prop} (H : and a b) : a := and.rec (λ Ha Hb, Ha) H definition and.left := @and.elim_left definition and.elim_right {a b : Prop} (H : and a b) : b := and.rec (λ Ha Hb, Hb) H definition and.right := @and.elim_right inductive sum (A : Type u) (B : Type v) | inl {} : A → sum | inr {} : B → sum attribute [reducible] definition sum.intro_left {A : Type u} (B : Type v) (a : A) : sum A B := sum.inl a attribute [reducible] definition sum.intro_right (A : Type u) {B : Type v} (b : B) : sum A B := sum.inr b inductive or (a b : Prop) : Prop | inl {} : a → or | inr {} : b → or definition or.intro_left {a : Prop} (b : Prop) (Ha : a) : or a b := or.inl Ha definition or.intro_right (a : Prop) {b : Prop} (Hb : b) : or a b := or.inr Hb structure sigma {A : Type u} (B : A → Type v) := mk :: (fst : A) (snd : B fst) -- pos_num and num are two auxiliary datatypes used when parsing numerals such as 13, 0, 26. -- The parser will generate the terms (pos (bit1 (bit1 (bit0 one)))), zero, and (pos (bit0 (bit1 (bit1 one)))). -- This representation can be coerced in whatever we want (e.g., naturals, integers, reals, etc). inductive pos_num : Type | one : pos_num | bit1 : pos_num → pos_num | bit0 : pos_num → pos_num namespace pos_num definition succ (a : pos_num) : pos_num := pos_num.rec_on a (bit0 one) (λ n r, bit0 r) (λ n r, bit1 n) end pos_num inductive num : Type | zero : num | pos : pos_num → num namespace num open pos_num definition succ (a : num) : num := num.rec_on a (pos one) (λ p, pos (succ p)) end num inductive bool : Type | ff : bool | tt : bool inductive option (A : Type u) | none {} : option | some : A → option export option (none some) export bool (ff tt) inductive list (T : Type u) | nil {} : list | cons : T → list → list inductive nat | zero : nat | succ : nat → nat /- Declare builtin and reserved notation -/ structure [class] has_zero (A : Type u) := (zero : A) structure [class] has_one (A : Type u) := (one : A) structure [class] has_add (A : Type u) := (add : A → A → A) structure [class] has_mul (A : Type u) := (mul : A → A → A) structure [class] has_inv (A : Type u) := (inv : A → A) structure [class] has_neg (A : Type u) := (neg : A → A) structure [class] has_sub (A : Type u) := (sub : A → A → A) structure [class] has_div (A : Type u) := (div : A → A → A) structure [class] has_dvd (A : Type u) := (dvd : A → A → Prop) structure [class] has_mod (A : Type u) := (mod : A → A → A) structure [class] has_le (A : Type u) := (le : A → A → Prop) structure [class] has_lt (A : Type u) := (lt : A → A → Prop) structure [class] has_append (A : Type u) := (append : A → A → A) structure [class] has_andthen(A : Type u) := (andthen : A → A → A) definition zero {A : Type u} [has_zero A] : A := has_zero.zero A definition one {A : Type u} [has_one A] : A := has_one.one A definition add {A : Type u} [has_add A] : A → A → A := has_add.add definition mul {A : Type u} [has_mul A] : A → A → A := has_mul.mul definition sub {A : Type u} [has_sub A] : A → A → A := has_sub.sub definition div {A : Type u} [has_div A] : A → A → A := has_div.div definition dvd {A : Type u} [has_dvd A] : A → A → Prop := has_dvd.dvd definition mod {A : Type u} [has_mod A] : A → A → A := has_mod.mod definition neg {A : Type u} [has_neg A] : A → A := has_neg.neg definition inv {A : Type u} [has_inv A] : A → A := has_inv.inv definition le {A : Type u} [has_le A] : A → A → Prop := has_le.le definition lt {A : Type u} [has_lt A] : A → A → Prop := has_lt.lt definition append {A : Type u} [has_append A] : A → A → A := has_append.append definition andthen {A : Type u} [has_andthen A] : A → A → A := has_andthen.andthen attribute [reducible] definition ge {A : Type u} [s : has_le A] (a b : A) : Prop := le b a attribute [reducible] definition gt {A : Type u} [s : has_lt A] (a b : A) : Prop := lt b a definition bit0 {A : Type u} [s : has_add A] (a : A) : A := add a a definition bit1 {A : Type u} [s₁ : has_one A] [s₂ : has_add A] (a : A) : A := add (bit0 a) one attribute [pattern] zero one bit0 bit1 add attribute [instance] definition num_has_zero : has_zero num := ⟨num.zero⟩ attribute [instance] definition num_has_one : has_one num := ⟨num.pos pos_num.one⟩ attribute [instance] definition pos_num_has_one : has_one pos_num := ⟨pos_num.one⟩ namespace pos_num definition is_one (a : pos_num) : bool := pos_num.rec_on a tt (λ n r, ff) (λ n r, ff) definition pred (a : pos_num) : pos_num := pos_num.rec_on a one (λ n r, bit0 n) (λ n r, bool.rec_on (is_one n) (bit1 r) one) definition size (a : pos_num) : pos_num := pos_num.rec_on a one (λ n r, succ r) (λ n r, succ r) definition add (a b : pos_num) : pos_num := pos_num.rec_on a succ (λ n f b, pos_num.rec_on b (succ (bit1 n)) (λ m r, succ (bit1 (f m))) (λ m r, bit1 (f m))) (λ n f b, pos_num.rec_on b (bit1 n) (λ m r, bit1 (f m)) (λ m r, bit0 (f m))) b end pos_num attribute [instance] definition pos_num_has_add : has_add pos_num := ⟨pos_num.add⟩ namespace num open pos_num definition add (a b : num) : num := num.rec_on a b (λ pa, num.rec_on b (pos pa) (λ pb, pos (pos_num.add pa pb))) end num attribute [instance] definition num_has_add : has_add num := ⟨num.add⟩ definition std.priority.default : num := 1000 definition std.priority.max : num := 4294967295 namespace nat protected definition prio := num.add std.priority.default 100 protected definition add (a b : nat) : nat := nat.rec a (λ b₁ r, nat.succ r) b definition of_pos_num (p : pos_num) : nat := pos_num.rec (succ zero) (λ n r, nat.add (nat.add r r) (succ zero)) (λ n r, nat.add r r) p definition of_num (n : num) : nat := num.rec zero (λ p, of_pos_num p) n end nat attribute pos_num_has_add pos_num_has_one num_has_zero num_has_one num_has_add [instance, priority nat.prio] attribute [instance, priority nat.prio] definition nat_has_zero : has_zero nat := ⟨nat.zero⟩ attribute [instance, priority nat.prio] definition nat_has_one : has_one nat := ⟨nat.succ (nat.zero)⟩ attribute [instance, priority nat.prio] definition nat_has_add : has_add nat := ⟨nat.add⟩ /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ definition std.prec.max : num := 1024 -- the strength of application, identifiers, (, [, etc. definition std.prec.arrow : num := 25 /- The next definition is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ definition std.prec.max_plus := num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ std.prec.max))))))))) /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and type constructors -/ reserve infixr ` ⊕ `:30 reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:100 reserve infix ` ^ `:80 reserve infixr ` ∘ `:90 -- input with \comp reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 reserve infix ` ' `:75 -- for the image of a set under a function reserve infix ` '- `:75 -- for the preimage of a set under a function /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:67 reserve infixl `; `:1 infix + := add infix * := mul infix - := sub infix / := div infix ∣ := dvd infix % := mod prefix - := neg postfix ⁻¹ := inv infix <= := le infix >= := ge infix ≤ := le infix ≥ := ge infix < := lt infix > := gt infix ++ := append infix ; := andthen /- eq basic support -/ notation a = b := eq a b attribute [pattern] definition rfl {A : Type u} {a : A} : a = a := eq.refl a namespace eq variables {A : Type u} variables {a b c a': A} attribute [elab_as_eliminator] theorem subst {P : A → Prop} (H₁ : a = b) (H₂ : P a) : P b := eq.rec H₂ H₁ theorem trans (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ theorem symm : a = b → b = a := λ h, eq.rec (refl a) h end eq notation H1 ▸ H2 := eq.subst H1 H2 attribute eq.subst [subst] attribute eq.refl [refl] attribute eq.trans [trans] attribute eq.symm [symm] /- sizeof -/ structure [class] has_sizeof (A : Type u) := (sizeof : A → nat) definition sizeof {A : Type u} [s : has_sizeof A] : A → nat := has_sizeof.sizeof /- Declare sizeof instances and lemmas for types declared before has_sizeof. From now on, the inductive compiler will automatically generate sizeof instances and lemmas. -/ /- Every type `A` has a default has_sizeof instance that just returns 0 for every element of `A` -/ attribute [instance] definition default_has_sizeof (A : Type u) : has_sizeof A := ⟨λ a, nat.zero⟩ attribute [simp, defeq, simp.sizeof] definition default_has_sizeof_eq (A : Type u) (a : A) : @sizeof A (default_has_sizeof A) a = 0 := rfl attribute [instance] definition nat_has_sizeof : has_sizeof nat := ⟨λ a, a⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_nat_eq (a : nat) : sizeof a = a := rfl attribute [instance] definition prod_has_sizeof (A : Type u) (B : Type v) [has_sizeof A] [has_sizeof B] : has_sizeof (prod A B) := ⟨λ p, prod.cases_on p (λ a b, 1 + sizeof a + sizeof b)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_prod_eq {A : Type u} {B : Type v} [has_sizeof A] [has_sizeof B] (a : A) (b : B) : sizeof (prod.mk a b) = 1 + sizeof a + sizeof b := rfl attribute [instance] definition sum_has_sizeof (A : Type u) (B : Type v) [has_sizeof A] [has_sizeof B] : has_sizeof (sum A B) := ⟨λ s, sum.cases_on s (λ a, 1 + sizeof a) (λ b, 1 + sizeof b)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_sum_eq_left {A : Type u} {B : Type v} [has_sizeof A] [has_sizeof B] (a : A) : sizeof (@sum.inl A B a) = 1 + sizeof a := rfl attribute [simp, defeq, simp.sizeof] definition sizeof_sum_eq_right {A : Type u} {B : Type v} [has_sizeof A] [has_sizeof B] (b : B) : sizeof (@sum.inr A B b) = 1 + sizeof b := rfl attribute [instance] definition sigma_has_sizeof (A : Type u) (B : A → Type v) [has_sizeof A] [∀ a, has_sizeof (B a)] : has_sizeof (sigma B) := ⟨λ p, sigma.cases_on p (λ a b, 1 + sizeof a + sizeof b)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_sigma_eq {A : Type u} {B : A → Type v} [has_sizeof A] [∀ a, has_sizeof (B a)] (a : A) (b : B a) : sizeof (@sigma.mk A B a b) = 1 + sizeof a + sizeof b := rfl attribute [instance] definition unit_has_sizeof : has_sizeof unit := ⟨λ u, 1⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_unit_eq (u : unit) : sizeof u = 1 := rfl attribute [instance] definition poly_unit_has_sizeof : has_sizeof poly_unit := ⟨λ u, 1⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_poly_unit_eq (u : poly_unit) : sizeof u = 1 := rfl attribute [instance] definition bool_has_sizeof : has_sizeof bool := ⟨λ u, 1⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_bool_eq (b : bool) : sizeof b = 1 := rfl attribute [instance] definition pos_num_has_sizeof : has_sizeof pos_num := ⟨λ p, nat.of_pos_num p⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_pos_num_eq (p : pos_num) : sizeof p = nat.of_pos_num p := rfl attribute [instance] definition num_has_sizeof : has_sizeof num := ⟨λ p, nat.of_num p⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_num_eq (n : num) : sizeof n = nat.of_num n := rfl attribute [instance] definition option_has_sizeof (A : Type u) [has_sizeof A] : has_sizeof (option A) := ⟨λ o, option.cases_on o 1 (λ a, 1 + sizeof a)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_option_none_eq (A : Type u) [has_sizeof A] : sizeof (@none A) = 1 := rfl attribute [simp, defeq, simp.sizeof] definition sizeof_option_some_eq {A : Type u} [has_sizeof A] (a : A) : sizeof (some a) = 1 + sizeof a := rfl attribute [instance] definition list_has_sizeof (A : Type u) [has_sizeof A] : has_sizeof (list A) := ⟨λ l, list.rec_on l 1 (λ a t ih, 1 + sizeof a + ih)⟩ attribute [simp, defeq, simp.sizeof] definition sizeof_list_nil_eq (A : Type u) [has_sizeof A] : sizeof (@list.nil A) = 1 := rfl attribute [simp, defeq, simp.sizeof] definition sizeof_list_cons_eq {A : Type u} [has_sizeof A] (a : A) (l : list A) : sizeof (list.cons a l) = 1 + sizeof a + sizeof l := rfl attribute [simp.sizeof] lemma nat_add_zero (n : nat) : n + 0 = n := rfl
e333775a5040d15f62c397902fe91f0bd397325e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/homology/additive.lean
11f29707270ed3b231cd09ed9d8cb28694ebd7a8
[ "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,617
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 algebra.homology.homology import algebra.homology.single import category_theory.preadditive.additive_functor /-! # Homology is an additive functor When `V` is preadditive, `homological_complex V c` is also preadditive, and `homology_functor` is additive. TODO: similarly for `R`-linear. -/ universes v u open_locale classical noncomputable theory open category_theory category_theory.limits homological_complex variables {ι : Type*} variables {V : Type u} [category.{v} V] [preadditive V] variables {c : complex_shape ι} {C D E : homological_complex V c} variables (f g : C ⟶ D) (h k : D ⟶ E) (i : ι) namespace homological_complex instance : has_zero (C ⟶ D) := ⟨{ f := λ i, 0 }⟩ instance : has_add (C ⟶ D) := ⟨λ f g, { f := λ i, f.f i + g.f i, }⟩ instance : has_neg (C ⟶ D) := ⟨λ f, { f := λ i, -(f.f i), }⟩ instance : has_sub (C ⟶ D) := ⟨λ f g, { f := λ i, f.f i - g.f i, }⟩ @[simp] lemma zero_f_apply (i : ι) : (0 : C ⟶ D).f i = 0 := rfl @[simp] lemma add_f_apply (f g : C ⟶ D) (i : ι) : (f + g).f i = f.f i + g.f i := rfl @[simp] lemma neg_f_apply (f : C ⟶ D) (i : ι) : (-f).f i = -(f.f i) := rfl @[simp] lemma sub_f_apply (f g : C ⟶ D) (i : ι) : (f - g).f i = f.f i - g.f i := rfl /- TODO(jmc/Scott): the instance below doesn't have the correct defeq for `nsmul` and `zsmul`. We should generalize `function.injective.add_comm_group` and friends. For the `R`-linear version, it will be very convenient to have a good definition of `nsmul` and `zsmul` that matches `smul`. -/ instance : add_comm_group (C ⟶ D) := function.injective.add_comm_group hom.f homological_complex.hom_f_injective (by tidy) (by tidy) (by tidy) (by tidy) instance : preadditive (homological_complex V c) := {} /-- The `i`-th component of a chain map, as an additive map from chain maps to morphisms. -/ @[simps] def hom.f_add_monoid_hom {C₁ C₂ : homological_complex V c} (i : ι) : (C₁ ⟶ C₂) →+ (C₁.X i ⟶ C₂.X i) := add_monoid_hom.mk' (λ f, hom.f f i) (λ _ _, rfl) end homological_complex namespace homological_complex instance eval_additive (i : ι) : (eval V c i).additive := {} variables [has_zero_object V] instance cycles_additive [has_equalizers V] : (cycles_functor V c i).additive := {} variables [has_images V] [has_image_maps V] instance boundaries_additive : (boundaries_functor V c i).additive := {} variables [has_equalizers V] [has_cokernels V] instance homology_additive : (homology_functor V c i).additive := { map_add' := λ C D f g, begin dsimp [homology_functor], ext, simp only [homology.π_map, preadditive.comp_add, ←preadditive.add_comp], congr, ext, simp, end } end homological_complex namespace category_theory variables {W : Type*} [category W] [preadditive W] /-- An additive functor induces a functor between homological complexes. This is sometimes called the "prolongation". -/ @[simps] def functor.map_homological_complex (F : V ⥤ W) [F.additive] (c : complex_shape ι) : homological_complex V c ⥤ homological_complex W c := { obj := λ C, { X := λ i, F.obj (C.X i), d := λ i j, F.map (C.d i j), shape' := λ i j w, by rw [C.shape _ _ w, F.map_zero], d_comp_d' := λ i j k _ _, by rw [←F.map_comp, C.d_comp_d, F.map_zero], }, map := λ C D f, { f := λ i, F.map (f.f i), comm' := λ i j h, by { dsimp, rw [←F.map_comp, ←F.map_comp, f.comm], }, }, }. instance functor.map_homogical_complex_additive (F : V ⥤ W) [F.additive] (c : complex_shape ι) : (F.map_homological_complex c).additive := {} /-- A natural transformation between functors induces a natural transformation between those functors applied to homological complexes. -/ @[simps] def nat_trans.map_homological_complex {F G : V ⥤ W} [F.additive] [G.additive] (α : F ⟶ G) (c : complex_shape ι) : F.map_homological_complex c ⟶ G.map_homological_complex c := { app := λ C, { f := λ i, α.app _, }, } @[simp] lemma nat_trans.map_homological_complex_id (c : complex_shape ι) (F : V ⥤ W) [F.additive] : nat_trans.map_homological_complex (𝟙 F) c = 𝟙 (F.map_homological_complex c) := by tidy @[simp] lemma nat_trans.map_homological_complex_comp (c : complex_shape ι) {F G H : V ⥤ W} [F.additive] [G.additive] [H.additive] (α : F ⟶ G) (β : G ⟶ H): nat_trans.map_homological_complex (α ≫ β) c = nat_trans.map_homological_complex α c ≫ nat_trans.map_homological_complex β c := by tidy @[simp, reassoc] lemma nat_trans.map_homological_complex_naturality {c : complex_shape ι} {F G : V ⥤ W} [F.additive] [G.additive] (α : F ⟶ G) {C D : homological_complex V c} (f : C ⟶ D) : (F.map_homological_complex c).map f ≫ (nat_trans.map_homological_complex α c).app D = (nat_trans.map_homological_complex α c).app C ≫ (G.map_homological_complex c).map f := by tidy end category_theory variables [has_zero_object V] {W : Type*} [category W] [preadditive W] [has_zero_object W] namespace homological_complex /-- Turning an object into a complex supported at `j` then applying a functor is the same as applying the functor then forming the complex. -/ def single_map_homological_complex (F : V ⥤ W) [F.additive] (c : complex_shape ι) (j : ι): single V c j ⋙ F.map_homological_complex _ ≅ F ⋙ single W c j := nat_iso.of_components (λ X, { hom := { f := λ i, if h : i = j then eq_to_hom (by simp [h]) else 0, }, inv := { f := λ i, if h : i = j then eq_to_hom (by simp [h]) else 0, }, hom_inv_id' := begin ext i, dsimp, split_ifs with h, { simp [h] }, { rw [zero_comp, if_neg h], exact (zero_of_source_iso_zero _ F.map_zero_object).symm, }, end, inv_hom_id' := begin ext i, dsimp, split_ifs with h, { simp [h] }, { rw [zero_comp, if_neg h], simp, }, end, }) (λ X Y f, begin ext i, dsimp, split_ifs with h; simp [h], end). variables (F : V ⥤ W) [functor.additive F] (c) @[simp] lemma single_map_homological_complex_hom_app_self (j : ι) (X : V) : ((single_map_homological_complex F c j).hom.app X).f j = eq_to_hom (by simp) := by simp [single_map_homological_complex] @[simp] lemma single_map_homological_complex_hom_app_ne {i j : ι} (h : i ≠ j) (X : V) : ((single_map_homological_complex F c j).hom.app X).f i = 0 := by simp [single_map_homological_complex, h] @[simp] lemma single_map_homological_complex_inv_app_self (j : ι) (X : V) : ((single_map_homological_complex F c j).inv.app X).f j = eq_to_hom (by simp) := by simp [single_map_homological_complex] @[simp] lemma single_map_homological_complex_inv_app_ne {i j : ι} (h : i ≠ j) (X : V): ((single_map_homological_complex F c j).inv.app X).f i = 0 := by simp [single_map_homological_complex, h] end homological_complex namespace chain_complex -- TODO: dualize to cochain complexes /-- Turning an object into a chain complex supported at zero then applying a functor is the same as applying the functor then forming the complex. -/ def single₀_map_homological_complex (F : V ⥤ W) [F.additive] : single₀ V ⋙ F.map_homological_complex _ ≅ F ⋙ single₀ W := nat_iso.of_components (λ X, { hom := { f := λ i, match i with | 0 := 𝟙 _ | (i+1) := F.map_zero_object.hom end, }, inv := { f := λ i, match i with | 0 := 𝟙 _ | (i+1) := F.map_zero_object.inv end, }, hom_inv_id' := begin ext (_|i), { unfold_aux, simp, }, { unfold_aux, dsimp, simp only [comp_f, id_f, zero_comp], exact (zero_of_source_iso_zero _ F.map_zero_object).symm, } end, inv_hom_id' := by { ext (_|i); { unfold_aux, dsimp, simp, }, }, }) (λ X Y f, by { ext (_|i); { unfold_aux, dsimp, simp, }, }). @[simp] lemma single₀_map_homological_complex_hom_app_zero (F : V ⥤ W) [F.additive] (X : V) : ((single₀_map_homological_complex F).hom.app X).f 0 = 𝟙 _ := rfl @[simp] lemma single₀_map_homological_complex_hom_app_succ (F : V ⥤ W) [F.additive] (X : V) (n : ℕ) : ((single₀_map_homological_complex F).hom.app X).f (n+1) = 0 := rfl @[simp] lemma single₀_map_homological_complex_inv_app_zero (F : V ⥤ W) [F.additive] (X : V) : ((single₀_map_homological_complex F).inv.app X).f 0 = 𝟙 _ := rfl @[simp] lemma single₀_map_homological_complex_inv_app_succ (F : V ⥤ W) [F.additive] (X : V) (n : ℕ) : ((single₀_map_homological_complex F).inv.app X).f (n+1) = 0 := rfl end chain_complex
2083a341f6d088139204b072e010ced6c8739bbe
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/bench/frontend_test.lean
6506251a5a463429288510635be672b1cf53fa1d
[ "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
61,186
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude notation `Prop` := Sort 0 notation f ` $ `:1 a:0 := f a /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` == `:50 reserve infix ` != `:50 reserve infix ` ~= `:50 reserve infix ` ≅ `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and Type constructors -/ reserve infixr ` ⊕ `:30 reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve infixl ` %ₙ `:70 reserve prefix `-`:100 reserve infixr ` ^ `:80 reserve infixr ` ∘ `:90 reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve prefix `!`:40 reserve infixl ` && `:35 reserve infixl ` || `:30 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 reserve infix ` ⊂ `:50 reserve infix ` ⊃ `:50 reserve infix ` \ `:70 /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:67 /- Control -/ reserve infixr ` <|> `:2 reserve infixr `; ` :3 reserve infixr ` >>= `:55 reserve infixr ` >=> `:55 reserve infixl ` <*> `:60 reserve infixl ` <* ` :60 reserve infixr ` *> ` :60 reserve infixr ` >> ` :60 reserve infixr ` <$> `:100 reserve infixr ` <$ ` :100 reserve infixr ` $> ` :100 reserve infixl ` <&> `:100 universes u v w /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α @[inline] def id {α : Sort u} (a : α) : α := a def inline {α : Sort u} (a : α) : α := a @[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- The kernel definitional equality test (t =?= s) has special support for idDelta applications. It implements the following rules 1) (idDelta t) =?= t 2) t =?= (idDelta t) 3) (idDelta t) =?= s IF (unfoldOf t) =?= s 4) t =?= idDelta s IF t =?= (unfoldOf s) This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel. We use idDelta applications to address performance problems when Type checking theorems generated by the equation Compiler. -/ @[inline] def idDelta {α : Sort u} (a : α) : α := a /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /- `idRhs` is an auxiliary Declaration used in the equation Compiler to address performance issues when proving equational theorems. The equation Compiler uses it as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a inductive PUnit : Sort u | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /- Remark: thunks have an efficient implementation in the runtime. -/ structure Thunk (α : Type u) : Type u := (fn : Unit → α) attribute [extern cpp inline "lean::mk_thunk(#2)"] Thunk.mk @[noinline, extern cpp inline "lean::thunk_pure(#2)"] protected def Thunk.pure {α : Type u} (a : α) : Thunk α := ⟨λ _, a⟩ @[noinline, extern cpp inline "lean::thunk_get_own(#2)"] protected def Thunk.get {α : Type u} (x : @& Thunk α) : α := x.fn () @[noinline, extern cpp inline "lean::thunk_map(#3, #4)"] protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β := ⟨λ _, f x.get⟩ @[noinline, extern cpp inline "lean::thunk_bind(#3, #4)"] protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β := ⟨λ _, (f x.get).get⟩ /- Remark: tasks have an efficient implementation in the runtime. -/ structure Task (α : Type u) : Type u := (fn : Unit → α) attribute [extern cpp inline "lean::mk_task(#2)"] Task.mk @[noinline, extern cpp inline "lean::task_pure(#2)"] protected def Task.pure {α : Type u} (a : α) : Task α := ⟨λ _, a⟩ @[noinline, extern cpp inline "lean::task_get(#2)"] protected def Task.get {α : Type u} (x : @& Task α) : α := x.fn () @[noinline, extern cpp inline "lean::task_map(#3, #4)"] protected def Task.map {α : Type u} {β : Type v} (f : α → β) (x : Task α) : Task β := ⟨λ _, f x.get⟩ @[noinline, extern cpp inline "lean::task_bind(#3, #4)"] protected def Task.bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) : Task β := ⟨λ _, (f x.get).get⟩ inductive True : Prop | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False prefix `¬` := Not inductive Eq {α : Sort u} (a : α) : α → Prop | refl : Eq a @[elabAsEliminator, inline, reducible] def {u1 u2} Eq.ndrec {α : Sort u2} {a : α} {C : α → Sort u1} (m : C a) {b : α} (h : Eq a b) : C b := @Eq.rec α a (λ α _, C α) m b h @[elabAsEliminator, inline, reducible] def {u1 u2} Eq.ndrecOn {α : Sort u2} {a : α} {C : α → Sort u1} {b : α} (h : Eq a b) (m : C a) : C b := @Eq.rec α a (λ α _, C α) m b h /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ initQuot inductive Heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop | refl : Heq a structure Prod (α : Type u) (β : Type v) := (fst : α) (snd : β) /-- Similar to `Prod`, but α and β can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) := (fst : α) (snd : β) structure And (a b : Prop) : Prop := intro :: (left : a) (right : b) structure Iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) /- Eq basic support -/ infix = := Eq @[matchPattern] def rfl {α : Sort u} {a : α} : a = a := Eq.refl a @[elabAsEliminator] theorem Eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b := Eq.ndrec h₂ h₁ infixr ▸ := Eq.subst theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a := h ▸ rfl infix ~= := Heq infix ≅ := Heq @[matchPattern] def Heq.rfl {α : Sort u} {a : α} : a ≅ a := Heq.refl a theorem eqOfHeq {α : Sort u} {a a' : α} (h : a ≅ a') : a = a' := have ∀ (α' : Sort u) (a' : α') (h₁ : @Heq α a α' a') (h₂ : α = α'), (Eq.recOn h₂ a : α') = a', from λ (α' : Sort u) (a' : α') (h₁ : @Heq α a α' a'), Heq.recOn h₁ (λ h₂ : α = α, rfl), show (Eq.ndrecOn (Eq.refl α) a : α) = a', from this α a' h (Eq.refl α) inductive Sum (α : Type u) (β : Type v) | inl {} (val : α) : Sum | inr {} (val : β) : Sum inductive PSum (α : Sort u) (β : Sort v) | inl {} (val : α) : PSum | inr {} (val : β) : PSum inductive Or (a b : Prop) : Prop | inl {} (h : a) : Or | inr {} (h : b) : Or def Or.introLeft {a : Prop} (b : Prop) (ha : a) : Or a b := Or.inl ha def Or.introRight (a : Prop) {b : Prop} (hb : b) : Or a b := Or.inr hb structure Sigma {α : Type u} (β : α → Type v) := mk :: (fst : α) (snd : β fst) structure PSigma {α : Sort u} (β : α → Sort v) := mk :: (fst : α) (snd : β fst) inductive Bool : Type | false : Bool | true : Bool /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) := (val : α) (property : p val) inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro (w : α) (h : p w) : Exists class inductive Decidable (p : Prop) | isFalse (h : ¬p) : Decidable | isTrue (h : p) : Decidable @[reducible] def DecidablePred {α : Sort u} (r : α → Prop) := Π (a : α), Decidable (r a) @[reducible] def DecidableRel {α : Sort u} (r : α → α → Prop) := Π (a b : α), Decidable (r a b) class DecidableEq (α : Sort u) := {decEq : Π a b : α, Decidable (a = b)} export DecidableEq (decEq) @[inline] instance decidableOfDecidableEq {α : Sort u} (a b : α) [DecidableEq α] : Decidable (a = b) := decEq a b inductive Option (α : Type u) | none {} : Option | some (val : α) : Option export Option (none some) export Bool (false true) inductive List (T : Type u) | nil {} : List | cons (hd : T) (tl : List) : List infixr :: := List.cons inductive Nat | zero : Nat | succ (n : Nat) : Nat /- Auxiliary axiom used to implement `sorry`. TODO: add this theorem on-demand. That is, we should only add it if after the first error. -/ unsafe axiom sorryAx (α : Sort u) (synthetic := true) : α /- Declare builtin and reserved notation -/ class HasZero (α : Type u) := (zero : α) class HasOne (α : Type u) := (one : α) class HasAdd (α : Type u) := (add : α → α → α) class HasMul (α : Type u) := (mul : α → α → α) class HasNeg (α : Type u) := (neg : α → α) class HasSub (α : Type u) := (sub : α → α → α) class HasDiv (α : Type u) := (div : α → α → α) class HasDivides (α : Type u) := (Divides : α → α → Prop) class HasMod (α : Type u) := (mod : α → α → α) class HasModn (α : Type u) := (modn : α → Nat → α) class HasLessEq (α : Type u) := (LessEq : α → α → Prop) class HasLess (α : Type u) := (Less : α → α → Prop) class HasBeq (α : Type u) := (beq : α → α → Bool) class HasAppend (α : Type u) := (append : α → α → α) class HasOrelse (α : Type u) := (orelse : α → α → α) class HasAndthen (α : Type u) := (andthen : α → α → α) class HasUnion (α : Type u) := (union : α → α → α) class HasInter (α : Type u) := (inter : α → α → α) class HasSDiff (α : Type u) := (sdiff : α → α → α) class HasEquiv (α : Sort u) := (Equiv : α → α → Prop) class HasSubset (α : Type u) := (Subset : α → α → Prop) class HasSSubset (α : Type u) := (SSubset : α → α → Prop) /- Type classes HasEmptyc and HasInsert are used to implement polymorphic notation for collections. Example: {a, b, c}. -/ class HasEmptyc (α : Type u) := (emptyc : α) class HasInsert (α : outParam $ Type u) (γ : Type v) := (insert : α → γ → γ) /- Type class used to implement the notation { a ∈ c | p a } -/ class HasSep (α : outParam $ Type u) (γ : Type v) := (sep : (α → Prop) → γ → γ) /- Type class for set-like membership -/ class HasMem (α : outParam $ Type u) (γ : Type v) := (mem : α → γ → Prop) class HasPow (α : Type u) (β : Type v) := (pow : α → β → α) export HasAndthen (andthen) export HasPow (pow) infix ∈ := HasMem.mem notation a ` ∉ ` s := ¬ HasMem.mem a s infix + := HasAdd.add infix * := HasMul.mul infix - := HasSub.sub infix / := HasDiv.div infix ∣ := HasDivides.Divides infix % := HasMod.mod infix %ₙ := HasModn.modn prefix - := HasNeg.neg infix <= := HasLessEq.LessEq infix ≤ := HasLessEq.LessEq infix < := HasLess.Less infix == := HasBeq.beq infix ++ := HasAppend.append notation `∅` := HasEmptyc.emptyc _ infix ∪ := HasUnion.union infix ∩ := HasInter.inter infix ⊆ := HasSubset.Subset infix ⊂ := HasSSubset.SSubset infix \ := HasSDiff.sdiff infix ≈ := HasEquiv.Equiv infixr ^ := HasPow.pow infixr /\ := And infixr ∧ := And infixr \/ := Or infixr ∨ := Or infix <-> := Iff infix ↔ := Iff -- notation `exists` binders `, ` r:(scoped P, Exists P) := r -- notation `∃` binders `, ` r:(scoped P, Exists P) := r infixr <|> := HasOrelse.orelse infixr >> := HasAndthen.andthen export HasAppend (append) @[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := HasLessEq.LessEq b a @[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := HasLess.Less b a infix >= := GreaterEq infix ≥ := GreaterEq infix > := Greater @[reducible] def Superset {α : Type u} [HasSubset α] (a b : α) : Prop := HasSubset.Subset b a @[reducible] def SSuperset {α : Type u} [HasSSubset α] (a b : α) : Prop := HasSSubset.SSubset b a infix ⊇ := Superset infix ⊃ := SSuperset @[inline] def bit0 {α : Type u} [s : HasAdd α] (a : α) : α := a + a @[inline] def bit1 {α : Type u} [s₁ : HasOne α] [s₂ : HasAdd α] (a : α) : α := (bit0 a) + 1 attribute [matchPattern] HasZero.zero HasOne.one bit0 bit1 HasAdd.add HasNeg.neg export HasInsert (insert) /- The Empty collection -/ @[inline] def singleton {α : Type u} {γ : Type v} [HasEmptyc γ] [HasInsert α γ] (a : α) : γ := HasInsert.insert a ∅ /- Nat basic instances -/ @[extern cpp "lean::nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a Nat.zero := a | a (Nat.succ b) := Nat.succ (Nat.add a b) /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Nat.add._main instance : HasZero Nat := ⟨Nat.zero⟩ instance : HasOne Nat := ⟨Nat.succ (Nat.zero)⟩ instance : HasAdd Nat := ⟨Nat.add⟩ /- Auxiliary constant used by equation compiler. -/ constant hugeFuel : Nat := 10000 def std.priority.default : Nat := 1000 def std.priority.max : Nat := 0xFFFFFFFF protected def Nat.prio := std.priority.default + 100 /- Global declarations of right binding strength If a Module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ def std.prec.max : Nat := 1024 -- the strength of application, identifiers, (, [, etc. def std.prec.arrow : Nat := 25 /- The next def is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ def std.prec.maxPlus : Nat := std.prec.max + 10 infixr × := Prod -- notation for n-ary tuples /- Some type that is not a scalar value in our runtime. TODO: mark opaque -/ structure NonScalar := (val : Nat) /- sizeof -/ class HasSizeof (α : Sort u) := (sizeof : α → Nat) export HasSizeof (sizeof) /- Declare sizeof instances and theorems for types declared before HasSizeof. From now on, the inductive Compiler will automatically generate sizeof instances and theorems. -/ /- Every Type `α` has a default HasSizeof instance that just returns 0 for every element of `α` -/ protected def default.sizeof (α : Sort u) : α → Nat | a := 0 instance defaultHasSizeof (α : Sort u) : HasSizeof α := ⟨default.sizeof α⟩ protected def Nat.sizeof : Nat → Nat | n := n instance : HasSizeof Nat := ⟨Nat.sizeof⟩ protected def Prod.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Prod α β) → Nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Prod α β) := ⟨Prod.sizeof⟩ protected def Sum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Sum α β) → Nat | (Sum.inl a) := 1 + sizeof a | (Sum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Sum α β) := ⟨Sum.sizeof⟩ protected def PSum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (PSum α β) → Nat | (PSum.inl a) := 1 + sizeof a | (PSum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (PSum α β) := ⟨PSum.sizeof⟩ protected def Sigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : Sigma β → Nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (Sigma β) := ⟨Sigma.sizeof⟩ protected def PSigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : PSigma β → Nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (PSigma β) := ⟨PSigma.sizeof⟩ protected def PUnit.sizeof : PUnit → Nat | u := 1 instance : HasSizeof PUnit := ⟨PUnit.sizeof⟩ protected def Bool.sizeof : Bool → Nat | b := 1 instance : HasSizeof Bool := ⟨Bool.sizeof⟩ protected def Option.sizeof {α : Type u} [HasSizeof α] : Option α → Nat | none := 1 | (some a) := 1 + sizeof a instance (α : Type u) [HasSizeof α] : HasSizeof (Option α) := ⟨Option.sizeof⟩ protected def List.sizeof {α : Type u} [HasSizeof α] : List α → Nat | List.nil := 1 | (List.cons a l) := 1 + sizeof a + List.sizeof l instance (α : Type u) [HasSizeof α] : HasSizeof (List α) := ⟨List.sizeof⟩ protected def Subtype.sizeof {α : Type u} [HasSizeof α] {p : α → Prop} : Subtype p → Nat | ⟨a, _⟩ := sizeof a instance {α : Type u} [HasSizeof α] (p : α → Prop) : HasSizeof (Subtype p) := ⟨Subtype.sizeof⟩ theorem natAddZero (n : Nat) : n + 0 = n := rfl theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl /-- Like `by applyInstance`, but not dependent on the tactic framework. -/ @[reducible] def inferInstance {α : Type u} [i : α] : α := i @[reducible, elabSimple] def inferInstanceAs (α : Type u) [i : α] : α := i /- Boolean operators -/ @[macroInline] def cond {a : Type u} : Bool → a → a → a | true x y := x | false x y := y @[macroInline] def or : Bool → Bool → Bool | true _ := true | false b := b @[macroInline] def and : Bool → Bool → Bool | false _ := false | true b := b @[macroInline] def not : Bool → Bool | true := false | false := true @[macroInline] def xor : Bool → Bool → Bool | true b := not b | false b := b prefix ! := not infix || := or infix && := and @[extern cpp inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[extern cpp inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def bne {α : Type u} [HasBeq α] (a b : α) : Bool := !(a == b) infix != := bne /- Logical connectives an equality -/ def implies (a b : Prop) := a → b theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) def trivial : True := ⟨⟩ @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (λ _, C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := False.elim (h₂ h₁) theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, h₂ (h₁ ha) theorem notFalse : ¬False := id -- proof irrelevance is built in theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl theorem id.def {α : Sort u} (a : α) : id a = a := rfl @[macroInline] def Eq.mp {α β : Sort u} (h₁ : α = β) (h₂ : α) : β := Eq.recOn h₁ h₂ @[macroInline] def Eq.mpr {α β : Sort u} : (α = β) → β → α := λ h₁ h₂, Eq.recOn (Eq.symm h₁) h₂ @[elabAsEliminator] theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b := Eq.subst (Eq.symm h₁) h₂ theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := Eq.subst h₁ (Eq.subst h₂ rfl) theorem congrFun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := Eq.subst h (Eq.refl (f a)) theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : a₁ = a₂) : f a₁ = f a₂ := congr rfl h theorem transRelLeft {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ theorem transRelRight {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁.symm ▸ h₂ theorem ofEqTrue {p : Prop} (h : p = True) : p := h.symm ▸ trivial theorem notOfEqFalse {p : Prop} (h : p = False) : ¬p := assume hp, h ▸ hp @[macroInline] def cast {α β : Sort u} (h : α = β) (a : α) : β := Eq.rec a h theorem castProofIrrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl @[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b) infix ≠ := Ne theorem Ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl section Ne variable {α : Sort u} variables {a b : α} {p : Prop} theorem Ne.intro (h : a = b → False) : a ≠ b := h theorem Ne.elim (h : a ≠ b) : a = b → False := h theorem Ne.irrefl (h : a ≠ a) : False := h rfl theorem Ne.symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁.symm) theorem falseOfNe : a ≠ a → False := Ne.irrefl theorem neFalseOfSelf : p → p ≠ False := assume (hp : p) (Heq : p = False), Heq ▸ hp theorem neTrueOfNot : ¬p → p ≠ True := assume (hnp : ¬p) (Heq : p = True), (Heq ▸ hnp) trivial theorem trueNeFalse : ¬True = False := neFalseOfSelf trivial end Ne theorem eqFalseOfNeTrue : ∀ {b : Bool}, b ≠ true → b = false | true h := False.elim (h rfl) | false h := rfl theorem eqTrueOfNeFalse : ∀ {b : Bool}, b ≠ false → b = true | true h := rfl | false h := False.elim (h rfl) section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} @[elabAsEliminator] theorem {u1 u2} Heq.ndrec {α : Sort u2} {a : α} {C : Π {β : Sort u2}, β → Sort u1} (m : C a) {β : Sort u2} {b : β} (h : a ≅ b) : C b := @Heq.rec α a (λ β b _, C b) m β b h @[elabAsEliminator] theorem {u1 u2} Heq.ndrecOn {α : Sort u2} {a : α} {C : Π {β : Sort u2}, β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : C a) : C b := @Heq.rec α a (λ β b _, C b) m β b h theorem Heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b := Eq.recOn (eqOfHeq h₁) h₂ theorem Heq.subst {p : ∀ T : Sort u, T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b := Heq.ndrecOn h₁ h₂ theorem Heq.symm (h : a ≅ b) : b ≅ a := Heq.ndrecOn h (Heq.refl a) theorem heqOfEq (h : a = a') : a ≅ a' := Eq.subst h (Heq.refl a) theorem Heq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c := Heq.subst h₂ h₁ theorem heqOfHeqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' := Heq.trans h₁ (heqOfEq h₂) theorem heqOfEqOfHeq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b := Heq.trans (heqOfEq h₁) h₂ def typeEqOfHeq (h : a ≅ b) : α = β := Heq.ndrecOn h (Eq.refl α) end theorem eqRecHeq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (Eq.recOn h p : φ a') ≅ p | a _ rfl p := Heq.refl p theorem ofHeqTrue {a : Prop} (h : a ≅ True) : a := ofEqTrue (eqOfHeq h) theorem castHeq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a | α _ rfl a := Heq.refl a variables {a b c d : Prop} theorem And.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := And.rec h₂ h₁ theorem And.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ def And.symm := @And.swap theorem Or.elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := Or.rec h₂ h₃ h₁ theorem Or.swap (h : a ∨ b) : b ∨ a := Or.elim h Or.inr Or.inl def Or.symm := @Or.swap /- xor -/ def Xor (a b : Prop) : Prop := (a ∧ ¬ b) ∨ (b ∧ ¬ a) theorem Iff.elim (h₁ : (a → b) → (b → a) → c) (h₂ : a ↔ b) : c := Iff.rec h₁ h₂ theorem Iff.left : (a ↔ b) → a → b := Iff.mp theorem Iff.right : (a ↔ b) → b → a := Iff.mpr theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := Iff.intro (λ h, And.intro h.mp h.mpr) (λ h, Iff.intro h.left h.right) theorem Iff.refl (a : Prop) : a ↔ a := Iff.intro (assume h, h) (assume h, h) theorem Iff.rfl {a : Prop} : a ↔ a := Iff.refl a theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := Iff.intro (assume ha, Iff.mp h₂ (Iff.mp h₁ ha)) (assume hc, Iff.mpr h₁ (Iff.mpr h₂ hc)) theorem Iff.symm (h : a ↔ b) : b ↔ a := Iff.intro (Iff.right h) (Iff.left h) theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) := Iff.intro Iff.symm Iff.symm theorem Eq.toIff {a b : Prop} (h : a = b) : a ↔ b := Eq.recOn h Iff.rfl theorem neqOfNotIff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from Eq.subst h₂ (Iff.refl a), absurd this h₁ theorem notIffNotOfIff (h₁ : a ↔ b) : ¬a ↔ ¬b := Iff.intro (assume (hna : ¬ a) (hb : b), hna (Iff.right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (Iff.left h₁ ha)) theorem ofIffTrue (h : a ↔ True) : a := Iff.mp (Iff.symm h) trivial theorem notOfIffFalse : (a ↔ False) → ¬a := Iff.mp theorem iffTrueIntro (h : a) : a ↔ True := Iff.intro (λ hl, trivial) (λ hr, h) theorem iffFalseIntro (h : ¬a) : a ↔ False := Iff.intro h (False.rec (λ _, a)) theorem notNotIntro (ha : a) : ¬¬a := assume hna : ¬a, hna ha theorem notTrue : (¬ True) ↔ False := iffFalseIntro (notNotIntro trivial) /- or resolution rulses -/ theorem resolveLeft {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := Or.elim h (λ ha, absurd ha na) id theorem negResolveLeft {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := Or.elim h (λ na, absurd ha na) id theorem resolveRight {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := Or.elim h id (λ hb, absurd hb nb) theorem negResolveRight {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := Or.elim h id (λ nb, absurd hb nb) /- Exists -/ theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : Exists (λ x, p x)) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- Decidable -/ @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn h (λ h₁, false) (λ h₂, true) export Decidable (isTrue isFalse decide) instance beqOfEq {α : Type u} [DecidableEq α] : HasBeq α := ⟨λ a b, decide (a = b)⟩ theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true := Decidable.casesOn h (λ h, False.elim (Iff.mp notTrue h)) (λ _, rfl) theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false := Decidable.casesOn h (λ h, rfl) (λ h, False.elim h) instance : Decidable True := isTrue trivial instance : Decidable False := isFalse notFalse -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite (c : Prop) [h : Decidable c] {α : Sort u} : (c → α) → (¬ c → α) → α := λ t e, Decidable.casesOn h e t /- if-then-else -/ @[macroInline] def ite (c : Prop) [h : Decidable c] {α : Sort u} (t e : α) : α := Decidable.casesOn h (λ hnc, e) (λ hc, t) namespace Decidable variables {p q : Prop} def recOnTrue [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : (Decidable.recOn h h₂ h₁ : Sort u) := Decidable.casesOn h (λ h, False.rec _ (h h₃)) (λ h, h₄) def recOnFalse [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : (Decidable.recOn h h₂ h₁ : Sort u) := Decidable.casesOn h (λ h, h₄) (λ h, False.rec _ (h₃ h)) @[macroInline] def byCases {q : Sort u} [s : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q := match s with | isTrue h := h1 h | isFalse h := h2 h theorem em (p : Prop) [Decidable p] : p ∨ ¬p := byCases Or.inl Or.inr theorem byContradiction [Decidable p] (h : ¬p → False) : p := byCases id (λ np : ¬p, False.elim (h np)) theorem ofNotNot [Decidable p] : ¬ ¬ p → p := λ hnn, byContradiction (λ hn, absurd hn hnn) theorem notNotIff (p) [Decidable p] : (¬ ¬ p) ↔ p := Iff.intro ofNotNot notNotIntro theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := Iff.intro (λ h, match d₁, d₂ with | isTrue h₁, isTrue h₂ := absurd (And.intro h₁ h₂) h | _, isFalse h₂ := Or.inr h₂ | isFalse h₁, _ := Or.inl h₁) (λ h ⟨hp, hq⟩, Or.elim h (λ h, h hp) (λ h, h hq)) end Decidable section variables {p q : Prop} @[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q := if hp : p then isTrue (Iff.mp h hp) else isFalse (Iff.mp (notIffNotOfIff h) hp) @[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q := decidableOfDecidableOfIff hp h.toIff end section variables {p q : Prop} @[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∧ q) := if hp : p then if hq : q then isTrue ⟨hp, hq⟩ else isFalse (assume h : p ∧ q, hq (And.right h)) else isFalse (assume h : p ∧ q, hp (And.left h)) @[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∨ q) := if hp : p then isTrue (Or.inl hp) else if hq : q then isTrue (Or.inr hq) else isFalse (λ h, Or.elim h hp hq) instance [Decidable p] : Decidable (¬p) := if hp : p then isFalse (absurd hp) else isTrue hp @[macroInline] instance implies.Decidable [Decidable p] [Decidable q] : Decidable (p → q) := if hp : p then if hq : q then isTrue (assume h, hq) else isFalse (assume h : p → q, absurd (h hp) hq) else isTrue (assume h, absurd h hp) instance [Decidable p] [Decidable q] : Decidable (p ↔ q) := if hp : p then if hq : q then isTrue ⟨λ_, hq, λ_, hp⟩ else isFalse $ λh, hq (h.1 hp) else if hq : q then isFalse $ λh, hp (h.2 hq) else isTrue $ ⟨λh, absurd h hp, λh, absurd h hq⟩ instance [Decidable p] [Decidable q] : Decidable (Xor p q) := if hp : p then if hq : q then isFalse (λ h, Or.elim h (λ ⟨_, h⟩, h hq : ¬(p ∧ ¬ q)) (λ ⟨_, h⟩, h hp : ¬(q ∧ ¬ p))) else isTrue $ Or.inl ⟨hp, hq⟩ else if hq : q then isTrue $ Or.inr ⟨hq, hp⟩ else isFalse (λ h, Or.elim h (λ ⟨h, _⟩, hp h : ¬(p ∧ ¬ q)) (λ ⟨h, _⟩, hq h : ¬(q ∧ ¬ p))) end @[inline] instance {α : Sort u} [DecidableEq α] (a b : α) : Decidable (a ≠ b) := match decEq a b with | isTrue h := isFalse $ λ h', absurd h h' | isFalse h := isTrue h theorem Bool.falseNeTrue (h : false = true) : False := Bool.noConfusion h instance : DecidableEq Bool := {decEq := λ a b, match a, b with | false, false := isTrue rfl | false, true := isFalse Bool.falseNeTrue | true, false := isFalse (Ne.symm Bool.falseNeTrue) | true, true := isTrue rfl} /- if-then-else expression theorems -/ theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (isTrue hc) := rfl | (isFalse hnc) := absurd hc hnc theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (isTrue hc) := absurd hc hnc | (isFalse hnc) := rfl -- Remark: dite and ite are "defally equal" when we ignore the proofs. theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (isTrue hc) := rfl | (isFalse hnc) := rfl instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) := match dC with | (isTrue hc) := dT | (isFalse hc) := dE instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) := match dC with | (isTrue hc) := dT hc | (isFalse hc) := dE hc /-- Universe lifting operation -/ structure {r s} ULift (α : Type s) : Type (max s r) := up :: (down : α) namespace ULift /- Bijection between α and ULift.{v} α -/ theorem upDown {α : Type u} : ∀ (b : ULift.{v} α), up (down b) = b | (up a) := rfl theorem downUp {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ULift /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u := up :: (down : α) namespace PLift /- Bijection between α and PLift α -/ theorem upDown {α : Sort u} : ∀ (b : PLift α), up (down b) = b | (up a) := rfl theorem downUp {α : Sort u} (a : α) : down (up a) = a := rfl end PLift /- pointed types -/ structure PointedType := (type : Type u) (val : type) /- Inhabited -/ class Inhabited (α : Sort u) := (default : α) constant default (α : Sort u) [Inhabited α] : α := Inhabited.default α @[inline, irreducible] def arbitrary (α : Sort u) [Inhabited α] : α := default α instance Prop.Inhabited : Inhabited Prop := ⟨True⟩ instance Fun.Inhabited (α : Sort u) {β : Sort v} [h : Inhabited β] : Inhabited (α → β) := Inhabited.casesOn h (λ b, ⟨λ a, b⟩) instance Pi.Inhabited (α : Sort u) {β : α → Sort v} [Π x, Inhabited (β x)] : Inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : Inhabited Bool := ⟨false⟩ instance : Inhabited True := ⟨trivial⟩ instance : Inhabited Nat := ⟨0⟩ instance : Inhabited NonScalar := ⟨⟨default _⟩⟩ instance : Inhabited PointedType := ⟨{type := PUnit, val := ⟨⟩}⟩ class inductive Nonempty (α : Sort u) : Prop | intro (val : α) : Nonempty protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p := Nonempty.rec h₂ h₁ instance nonemptyOfInhabited {α : Sort u} [Inhabited α] : Nonempty α := ⟨default α⟩ theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (λ x, p x) → Nonempty α | ⟨w, h⟩ := ⟨w⟩ /- Subsingleton -/ class inductive Subsingleton (α : Sort u) : Prop | intro (h : ∀ a b : α, a = b) : Subsingleton protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : ∀ (a b : α), a = b := Subsingleton.casesOn h (λ p, p) protected def Subsingleton.helim {α β : Sort u} [h : Subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a ≅ b := Eq.recOn h (λ a b : α, heqOfEq (Subsingleton.elim a b)) instance subsingletonProp (p : Prop) : Subsingleton p := ⟨λ a b, proofIrrel a b⟩ instance (p : Prop) : Subsingleton (Decidable p) := Subsingleton.intro (λ d₁, match d₁ with | (isTrue t₁) := (λ d₂, match d₂ with | (isTrue t₂) := Eq.recOn (proofIrrel t₁ t₂) rfl | (isFalse f₂) := absurd t₁ f₂) | (isFalse f₁) := (λ d₂, match d₂ with | (isTrue t₂) := absurd t₂ f₁ | (isFalse f₂) := Eq.recOn (proofIrrel f₁ f₂) rfl)) protected theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : Π (h : p), Subsingleton (h₁ h)] [h₄ : Π (h : ¬p), Subsingleton (h₂ h)] : Subsingleton (Decidable.casesOn h h₂ h₁) := match h with | (isTrue h) := h₃ h | (isFalse h) := h₄ h section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) def Reflexive := ∀ x, r x x def Symmetric := ∀ {x y}, r x y → r y x def Transitive := ∀ {x y z}, r x y → r y z → r x z def Equivalence := Reflexive r ∧ Symmetric r ∧ Transitive r def Total := ∀ x y, r x y ∨ r y x def mkEquivalence (rfl : Reflexive r) (symm : Symmetric r) (trans : Transitive r) : Equivalence r := ⟨rfl, @symm, @trans⟩ def Irreflexive := ∀ x, ¬ r x x def AntiSymmetric := ∀ {x y}, r x y → r y x → x = y def emptyRelation := λ a₁ a₂ : α, False def Subrelation (q r : β → β → Prop) := ∀ {x y}, q x y → r x y def InvImage (f : α → β) : α → α → Prop := λ a₁ a₂, r (f a₁) (f a₂) theorem InvImage.Transitive (f : α → β) (h : Transitive r) : Transitive (InvImage r f) := λ (a₁ a₂ a₃ : α) (h₁ : InvImage r f a₁ a₂) (h₂ : InvImage r f a₂ a₃), h h₁ h₂ theorem InvImage.Irreflexive (f : α → β) (h : Irreflexive r) : Irreflexive (InvImage r f) := λ (a : α) (h₁ : InvImage r f a a), h (f a) h₁ inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → TC a b | trans : ∀ a b c, TC a b → TC b c → TC a c @[elabAsEliminator] theorem {u1 u2} TC.ndrec {α : Sort u} {r : α → α → Prop} {C : α → α → Prop} (m₁ : ∀ (a b : α), r a b → C a b) (m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c) {a b : α} (h : TC r a b) : C a b := @TC.rec α r (λ a b _, C a b) m₁ m₂ a b h @[elabAsEliminator] theorem {u1 u2} TC.ndrecOn {α : Sort u} {r : α → α → Prop} {C : α → α → Prop} {a b : α} (h : TC r a b) (m₁ : ∀ (a b : α), r a b → C a b) (m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c) : C a b := @TC.rec α r (λ a b _, C a b) m₁ m₂ a b h end relation section Binary variables {α : Type u} {β : Type v} variable f : α → α → α def Commutative := ∀ a b, f a b = f b a def Associative := ∀ a b c, f (f a b) c = f a (f b c) def RightCommutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def LeftCommutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) theorem leftComm : Commutative f → Associative f → LeftCommutative f := assume hcomm hassoc, assume a b c, ((Eq.symm (hassoc a b c)).trans (hcomm a b ▸ rfl : f (f a b) c = f (f b a) c)).trans (hassoc b a c) theorem rightComm : Commutative f → Associative f → RightCommutative f := assume hcomm hassoc, assume a b c, ((hassoc a b c).trans (hcomm b c ▸ rfl : f a (f b c) = f a (f c b))).trans (Eq.symm (hassoc a c b)) end Binary /- Subtype -/ namespace Subtype def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (λ x, p x) | ⟨a, h⟩ := ⟨a, h⟩ variables {α : Type u} {p : α → Prop} theorem tagIrrelevant {a : α} (h1 h2 : p a) : mk a h1 = mk a h2 := rfl protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2 | ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := Subtype.eq rfl instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} := ⟨⟨a, h⟩⟩ instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} := {decEq := λ ⟨a, h₁⟩ ⟨b, h₂⟩, if h : a = b then isTrue (Subtype.eq h) else isFalse (λ h', Subtype.noConfusion h' (λ h', absurd h' h))} end Subtype /- Sum -/ infixr ⊕ := Sum section variables {α : Type u} {β : Type v} instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (α ⊕ β) := ⟨Sum.inl (default α)⟩ instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (α ⊕ β) := ⟨Sum.inr (default β)⟩ instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (α ⊕ β) := {decEq := λ a b, match a, b with | (Sum.inl a), (Sum.inl b) := if h : a = b then isTrue (h ▸ rfl) else isFalse (λ h', Sum.noConfusion h' (λ h', absurd h' h)) | (Sum.inr a), (Sum.inr b) := if h : a = b then isTrue (h ▸ rfl) else isFalse (λ h', Sum.noConfusion h' (λ h', absurd h' h)) | (Sum.inr a), (Sum.inl b) := isFalse (λ h, Sum.noConfusion h) | (Sum.inl a), (Sum.inr b) := isFalse (λ h, Sum.noConfusion h)} end /- Product -/ section variables {α : Type u} {β : Type v} instance [Inhabited α] [Inhabited β] : Inhabited (Prod α β) := ⟨(default α, default β)⟩ instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) := {decEq := λ ⟨a, b⟩ ⟨a', b'⟩, match (decEq a a') with | (isTrue e₁) := (match (decEq b b') with | (isTrue e₂) := isTrue (Eq.recOn e₁ (Eq.recOn e₂ rfl)) | (isFalse n₂) := isFalse (assume h, Prod.noConfusion h (λ e₁' e₂', absurd e₂' n₂))) | (isFalse n₁) := isFalse (assume h, Prod.noConfusion h (λ e₁' e₂', absurd e₁' n₁))} instance [HasLess α] [HasLess β] : HasLess (α × β) := ⟨λ s t, s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)⟩ instance prodHasDecidableLt [HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β] [Π a b : α, Decidable (a < b)] [Π a b : β, Decidable (a < b)] : Π s t : α × β, Decidable (s < t) := λ t s, Or.Decidable theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) := rfl end def {u₁ u₂ v₁ v₂} Prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂} (f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂ | (a, b) := (f a, g b) /- Dependent products -/ -- notation `Σ` binders `, ` r:(scoped p, Sigma p) := r -- notation `Σ'` binders `, ` r:(scoped p, PSigma p) := r theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (λ x, p x)) → Exists (λ x, p x) | ⟨x, hx⟩ := ⟨x, hx⟩ section variables {α : Type u} {β : α → Type v} protected theorem Sigma.eq : ∀ {p₁ p₂ : Sigma (λ a : α, β a)} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂ | ⟨a, b⟩ ⟨.(a), .(b)⟩ rfl rfl := rfl end section variables {α : Sort u} {β : α → Sort v} protected theorem PSigma.eq : ∀ {p₁ p₂ : PSigma β} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂ | ⟨a, b⟩ ⟨.(a), .(b)⟩ rfl rfl := rfl end /- Universe polymorphic unit -/ theorem punitEq (a b : PUnit) : a = b := PUnit.recOn a (PUnit.recOn b rfl) theorem punitEqPUnit (a : PUnit) : a = () := punitEq a () instance : Subsingleton PUnit := Subsingleton.intro punitEq instance : Inhabited PUnit := ⟨⟨⟩⟩ instance : DecidableEq PUnit := {decEq := λ a b, isTrue (punitEq a b)} /- Setoid -/ class Setoid (α : Sort u) := (r : α → α → Prop) (iseqv : Equivalence r) instance setoidHasEquiv {α : Sort u} [Setoid α] : HasEquiv α := ⟨Setoid.r⟩ namespace Setoid variables {α : Sort u} [Setoid α] theorem refl (a : α) : a ≈ a := match Setoid.iseqv α with | ⟨hRefl, hSymm, hTrans⟩ := hRefl a theorem symm {a b : α} (hab : a ≈ b) : b ≈ a := match Setoid.iseqv α with | ⟨hRefl, hSymm, hTrans⟩ := hSymm hab theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c := match Setoid.iseqv α with | ⟨hRefl, hSymm, hTrans⟩ := hTrans hab hbc end Setoid /- Propositional extensionality -/ axiom propext {a b : Prop} : (a ↔ b) → a = b theorem eqTrueIntro {a : Prop} (h : a) : a = True := propext (iffTrueIntro h) theorem eqFalseIntro {a : Prop} (h : ¬a) : a = False := propext (iffFalseIntro h) /- Quotients -/ -- Iff can now be used to do substitutions in a calculation theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b := Eq.subst (propext h₁) h₂ namespace Quot axiom sound : Π {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b attribute [elabAsEliminator] lift ind protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : ∀ a b, r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a := rfl protected theorem indBeta {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (p : ∀ a, β (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : β (Quot.mk r a)) = p a := rfl @[reducible, elabAsEliminator, inline] protected def liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : ∀ a b, r a b → f a = f b) : β := lift f c q @[elabAsEliminator] protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (q : Quot r) (h : ∀ a, β (Quot.mk r a)) : β q := ind h q theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (λ a : α, (Quot.mk r a) = q) := Quot.inductionOn q (λ a, ⟨a, rfl⟩) section variable {α : Sort u} variable {r : α → α → Prop} variable {β : Quot r → Sort v} @[reducible, macroInline] protected def indep (f : Π a, β (Quot.mk r a)) (a : α) : PSigma β := ⟨Quot.mk r a, f a⟩ protected theorem indepCoherent (f : Π a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) : ∀ a b, r a b → Quot.indep f a = Quot.indep f b := λ a b e, PSigma.eq (sound e) (h a b e) protected theorem liftIndepPr1 (f : Π a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) (q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := Quot.ind (λ (a : α), Eq.refl (Quot.indep f a).1) q @[reducible, elabAsEliminator, inline] protected def rec (f : Π a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) (q : Quot r) : β q := Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2) @[reducible, elabAsEliminator, inline] protected def recOn (q : Quot r) (f : Π a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) : β q := Quot.rec f h q @[reducible, elabAsEliminator, inline] protected def recOnSubsingleton [h : ∀ a, Subsingleton (β (Quot.mk r a))] (q : Quot r) (f : Π a, β (Quot.mk r a)) : β q := Quot.rec f (λ a b h, Subsingleton.elim _ (f b)) q @[reducible, elabAsEliminator, inline] protected def hrecOn (q : Quot r) (f : Π a, β (Quot.mk r a)) (c : ∀ (a b : α) (p : r a b), f a ≅ f b) : β q := Quot.recOn q f $ λ a b p, eqOfHeq $ have p₁ : (Eq.rec (f a) (sound p) : β (Quot.mk r b)) ≅ f a, from eqRecHeq (sound p) (f a), Heq.trans p₁ (c a b p) end end Quot def Quotient {α : Sort u} (s : Setoid α) := @Quot α Setoid.r namespace Quotient @[inline] protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s := Quot.mk Setoid.r a notation `⟦`:max a `⟧`:0 := Quotient.mk a def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → ⟦a⟧ = ⟦b⟧ := Quot.sound @[reducible, elabAsEliminator] protected def lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : (∀ a b, a ≈ b → f a = f b) → Quotient s → β := Quot.lift f @[elabAsEliminator] protected theorem ind {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} : (∀ a, β ⟦a⟧) → ∀ q, β q := Quot.ind @[reducible, elabAsEliminator, inline] protected def liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : ∀ a b, a ≈ b → f a = f b) : β := Quot.liftOn q f c @[elabAsEliminator] protected theorem inductionOn {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} (q : Quotient s) (h : ∀ a, β ⟦a⟧) : β q := Quot.inductionOn q h theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (λ a : α, ⟦a⟧ = q) := Quot.existsRep q section variable {α : Sort u} variable [s : Setoid α] variable {β : Quotient s → Sort v} @[inline] protected def rec (f : Π a, β ⟦a⟧) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β ⟦b⟧) = f b) (q : Quotient s) : β q := Quot.rec f h q @[reducible, elabAsEliminator, inline] protected def recOn (q : Quotient s) (f : Π a, β ⟦a⟧) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β ⟦b⟧) = f b) : β q := Quot.recOn q f h @[reducible, elabAsEliminator, inline] protected def recOnSubsingleton [h : ∀ a, Subsingleton (β ⟦a⟧)] (q : Quotient s) (f : Π a, β ⟦a⟧) : β q := @Quot.recOnSubsingleton _ _ _ h q f @[reducible, elabAsEliminator, inline] protected def hrecOn (q : Quotient s) (f : Π a, β ⟦a⟧) (c : ∀ (a b : α) (p : a ≈ b), f a ≅ f b) : β q := Quot.hrecOn q f c end section universes uA uB uC variables {α : Sort uA} {β : Sort uB} {φ : Sort uC} variables [s₁ : Setoid α] [s₂ : Setoid β] @[reducible, elabAsEliminator, inline] protected def lift₂ (f : α → β → φ)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ := Quotient.lift (λ (a₁ : α), Quotient.lift (f a₁) (λ (a b : β), c a₁ a a₁ b (Setoid.refl a₁)) q₂) (λ (a b : α) (h : a ≈ b), @Quotient.ind β s₂ (λ (a1 : Quotient s₂), (Quotient.lift (f a) (λ (a1 b : β), c a a1 a b (Setoid.refl a)) a1) = (Quotient.lift (f b) (λ (a b1 : β), c b a b b1 (Setoid.refl b)) a1)) (λ (a' : β), c a a' b a' h (Setoid.refl a')) q₂) q₁ @[reducible, elabAsEliminator, inline] protected def liftOn₂ (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : φ := Quotient.lift₂ f c q₁ q₂ @[elabAsEliminator] protected theorem ind₂ {φ : Quotient s₁ → Quotient s₂ → Prop} (h : ∀ a b, φ ⟦a⟧ ⟦b⟧) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ q₁ q₂ := Quotient.ind (λ a₁, Quotient.ind (λ a₂, h a₁ a₂) q₂) q₁ @[elabAsEliminator] protected theorem inductionOn₂ {φ : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : ∀ a b, φ ⟦a⟧ ⟦b⟧) : φ q₁ q₂ := Quotient.ind (λ a₁, Quotient.ind (λ a₂, h a₁ a₂) q₂) q₁ @[elabAsEliminator] protected theorem inductionOn₃ [s₃ : Setoid φ] {δ : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : ∀ a b c, δ ⟦a⟧ ⟦b⟧ ⟦c⟧) : δ q₁ q₂ q₃ := Quotient.ind (λ a₁, Quotient.ind (λ a₂, Quotient.ind (λ a₃, h a₁ a₂ a₃) q₃) q₂) q₁ end section Exact variable {α : Sort u} private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop := Quotient.liftOn₂ q₁ q₂ (λ a₁ a₂, a₁ ≈ a₂) (λ a₁ a₂ b₁ b₂ a₁b₁ a₂b₂, propext (Iff.intro (λ a₁a₂, Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂)) (λ b₁b₂, Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂))))) private theorem rel.refl [s : Setoid α] : ∀ q : Quotient s, rel q q := λ q, Quot.inductionOn q (λ a, Setoid.refl a) private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ := assume h, Eq.ndrecOn h (rel.refl q₁) theorem exact [s : Setoid α] {a b : α} : ⟦a⟧ = ⟦b⟧ → a ≈ b := assume h, eqImpRel h end Exact section universes uA uB uC variables {α : Sort uA} {β : Sort uB} variables [s₁ : Setoid α] [s₂ : Setoid β] @[reducible, elabAsEliminator] protected def recOnSubsingleton₂ {φ : Quotient s₁ → Quotient s₂ → Sort uC} [h : ∀ a b, Subsingleton (φ ⟦a⟧ ⟦b⟧)] (q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : Π a b, φ ⟦a⟧ ⟦b⟧) : φ q₁ q₂:= @Quotient.recOnSubsingleton _ s₁ (λ q, φ q q₂) (λ a, Quotient.ind (λ b, h a b) q₂) q₁ (λ a, Quotient.recOnSubsingleton q₂ (λ b, f a b)) end end Quotient section variable {α : Type u} variable (r : α → α → Prop) inductive EqvGen : α → α → Prop | rel {} : Π x y, r x y → EqvGen x y | refl {} : Π x, EqvGen x x | symm {} : Π x y, EqvGen x y → EqvGen y x | trans {} : Π x y z, EqvGen x y → EqvGen y z → EqvGen x z theorem EqvGen.isEquivalence : Equivalence (@EqvGen α r) := mkEquivalence _ EqvGen.refl EqvGen.symm EqvGen.trans def EqvGen.Setoid : Setoid α := Setoid.mk _ (EqvGen.isEquivalence r) theorem Quot.exact {a b : α} (H : Quot.mk r a = Quot.mk r b) : EqvGen r a b := @Quotient.exact _ (EqvGen.Setoid r) a b (@congrArg _ _ _ _ (Quot.lift (@Quotient.mk _ (EqvGen.Setoid r)) (λx y h, Quot.sound (EqvGen.rel x y h))) H) theorem Quot.eqvGenSound {r : α → α → Prop} {a b : α} (H : EqvGen r a b) : Quot.mk r a = Quot.mk r b := EqvGen.recOn H (λ x y h, Quot.sound h) (λ x, rfl) (λ x y _ IH, Eq.symm IH) (λ x y z _ _ IH₁ IH₂, Eq.trans IH₁ IH₂) end instance {α : Sort u} {s : Setoid α} [d : ∀ a b : α, Decidable (a ≈ b)] : DecidableEq (Quotient s) := {decEq := λ q₁ q₂ : Quotient s, Quotient.recOnSubsingleton₂ q₁ q₂ (λ a₁ a₂, match (d a₁ a₂) with | (isTrue h₁) := isTrue (Quotient.sound h₁) | (isFalse h₂) := isFalse (λ h, absurd (Quotient.exact h) h₂))} /- Function extensionality -/ namespace Function variables {α : Sort u} {β : α → Sort v} def Equiv (f₁ f₂ : Π x : α, β x) : Prop := ∀ x, f₁ x = f₂ x protected theorem Equiv.refl (f : Π x : α, β x) : Equiv f f := assume x, rfl protected theorem Equiv.symm {f₁ f₂ : Π x: α, β x} : Equiv f₁ f₂ → Equiv f₂ f₁ := λ h x, Eq.symm (h x) protected theorem Equiv.trans {f₁ f₂ f₃ : Π x: α, β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ := λ h₁ h₂ x, Eq.trans (h₁ x) (h₂ x) protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := mkEquivalence (@Function.Equiv α β) (@Equiv.refl α β) (@Equiv.symm α β) (@Equiv.trans α β) end Function section open Quotient variables {α : Sort u} {β : α → Sort v} @[instance] private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (Π x : α, β x) := Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β) private def extfunApp (f : Quotient $ funSetoid α β) : Π x : α, β x := assume x, Quot.liftOn f (λ f : Π x : α, β x, f x) (λ f₁ f₂ h, h x) theorem funext {f₁ f₂ : Π x : α, β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := show extfunApp ⟦f₁⟧ = extfunApp ⟦f₂⟧, from congrArg extfunApp (sound h) end instance Pi.Subsingleton {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (Π a, β a) := ⟨λ f₁ f₂, funext (λ a, Subsingleton.elim (f₁ a) (f₂ a))⟩ /- General operations on functions -/ namespace Function universes u₁ u₂ u₃ u₄ variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁} @[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ := λ x, f (g x) infixr ` ∘ ` := Function.comp @[inline, reducible] def onFun (f : β → β → φ) (g : α → β) : α → α → φ := λ x y, f (g x) (g y) @[inline, reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ) : α → β → ζ := λ x y, op (f x y) (g x y) @[inline, reducible] def const (β : Sort u₂) (a : α) : β → α := λ x, a @[inline, reducible] def swap {φ : α → β → Sort u₃} (f : Π x y, φ x y) : Π y x, φ x y := λ y x, f x y end Function /- Classical reasoning support -/ namespace Classical axiom choice {α : Sort u} : Nonempty α → α noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop) (h : Exists (λ x, p x)) : {x // p x} := choice $ let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩ noncomputable def choose {α : Sort u} {p : α → Prop} (h : Exists (λ x, p x)) : α := (indefiniteDescription p h).val theorem chooseSpec {α : Sort u} {p : α → Prop} (h : Exists (λ 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 : Exists (λ x, U x), from ⟨True, Or.inl rfl⟩, have exV : Exists (λ x, V x), from ⟨False, Or.inl rfl⟩, let u : Prop := choose exU; let v : Prop := choose exV; have uDef : U u, from chooseSpec exU, have vDef : V v, from chooseSpec exV, have notUvOrP : u ≠ v ∨ p, from Or.elim uDef (assume hut : u = True, Or.elim vDef (assume hvf : v = False, have hne : u ≠ v, from hvf.symm ▸ hut.symm ▸ trueNeFalse, Or.inl hne) Or.inr) Or.inr, have pImpliesUv : p → u = v, from assume hp : p, have hpred : U = V, from funext $ assume x : Prop, have hl : (x = True ∨ p) → (x = False ∨ p), from assume a, Or.inr hp, have hr : (x = False ∨ p) → (x = True ∨ p), from assume 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, from hpred ▸ λ exU exV, rfl, show u = v, from h₀ _ _, Or.elim notUvOrP (assume hne : u ≠ v, Or.inr (mt pImpliesUv hne)) Or.inl theorem existsTrueOfNonempty {α : Sort u} : Nonempty α → Exists (λ x : α, True) | ⟨x⟩ := ⟨x, trivial⟩ noncomputable def inhabitedOfNonempty {α : Sort u} (h : Nonempty α) : Inhabited α := ⟨choice h⟩ noncomputable def inhabitedOfExists {α : Sort u} {p : α → Prop} (h : Exists (λ x, p x)) : Inhabited α := inhabitedOfNonempty (Exists.elim h (λ w hw, ⟨w⟩)) /- all propositions are Decidable -/ noncomputable def propDecidable (a : Prop) : Decidable a := choice $ Or.elim (em a) (assume ha, ⟨isTrue ha⟩) (assume hna, ⟨isFalse hna⟩) noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) := ⟨propDecidable a⟩ noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α := {decEq := λ x y, propDecidable (x = y)} noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) := match (propDecidable (Nonempty α)) with | (isTrue hp) := PSum.inl (@Inhabited.default _ (inhabitedOfNonempty hp)) | (isFalse hn) := PSum.inr (λ a, absurd (Nonempty.intro a) hn) noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop) (h : Nonempty α) : {x : α // Exists (λ y : α, p y) → p x} := @dite (Exists (λ x : α, p x)) (propDecidable _) _ (λ hp : Exists (λ x : α, p x), show {x : α // Exists (λ y : α, p y) → p x}, from let xp := indefiniteDescription _ hp; ⟨xp.val, λ h', xp.property⟩) (λ hp, ⟨choice h, λ h, absurd h hp⟩) /- the Hilbert epsilon Function -/ noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α := (strongIndefiniteDescription p h).val theorem epsilonSpecAux {α : Sort u} (h : Nonempty α) (p : α → Prop) : Exists (λ y, p y) → p (@epsilon α h p) := (strongIndefiniteDescription p h).property theorem epsilonSpec {α : Sort u} {p : α → Prop} (hex : Exists (λ y, p y)) : p (@epsilon α (nonemptyOfExists hex) p) := epsilonSpecAux (nonemptyOfExists hex) p hex theorem epsilonSingleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (λ y, y = x) = x := @epsilonSpec α (λ y, y = x) ⟨x, rfl⟩ /- the axiom of choice -/ theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : Π x, β x → Prop} (h : ∀ x, Exists (λ y, r x y)) : Exists (λ (f : Π x, β x), ∀ x, r x (f x)) := ⟨_, λ x, chooseSpec (h x)⟩ theorem skolem {α : Sort u} {b : α → Sort v} {p : Π x, b x → Prop} : (∀ x, Exists (λ y, p x y)) ↔ Exists (λ (f : Π x, b x), ∀ x, p x (f x)) := ⟨axiomOfChoice, λ ⟨f, hw⟩ x, ⟨f x, hw x⟩⟩ theorem propComplete (a : Prop) : a = True ∨ a = False := Or.elim (em a) (λ t, Or.inl (eqTrueIntro t)) (λ f, Or.inr (eqFalseIntro f)) -- this supercedes byCases in Decidable theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q := @Decidable.byCases _ _ (propDecidable _) hpq hnpq -- this supercedes byContradiction in Decidable theorem byContradiction {p : Prop} (h : ¬p → False) : p := @Decidable.byContradiction _ (propDecidable _) h end Classical
a3fe2b5e8da2e26660d1cb5562e9837e6ff1048e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/463.lean
dfc856b4f216a23d697adfd3234593f5042b166a
[ "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
263
lean
structure A := (a b : Nat) structure B extends A := (c : Nat) structure C := (a b c : Nat) structure D := (toA : A) (c : Nat) def foo (s : C) : B := {s with} -- works in lean 4, works in lean 3 def bar (s : D) : B := {s with} -- works in lean 4, fails in lean 3
e393a64f8fdddb15b42a11f3dce5bf13169c043d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/evalTacticBug.lean
24435e9a58a0158d7d64ee36ed6827f99f5da932
[ "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
378
lean
syntax "foo" : tactic macro_rules | `(tactic| foo) => `(tactic| assumption) macro_rules | `(tactic| foo) => `(tactic| apply Nat.pred_lt; assumption) macro_rules | `(tactic| foo) => `(tactic| contradiction) example (i : Nat) (h : i - 1 < i) : i - 1 < i := by foo example (i : Nat) (h : i ≠ 0) : i - 1 < i := by foo example (i : Nat) (h : False) : i - 1 < i := by foo
436e3e76bb737960e17ce36c8f1caf0804db61c7
35960c5b117752aca7e3e7767c0b393e4dbd72a7
/src/occurs.lean
58339bc8f332c984605265a0005ef509d2ac0254
[ "Apache-2.0" ]
permissive
spl/tts
461dc76b83df8db47e4660d0941dc97e6d4fd7d1
b65298fea68ce47c8ed3ba3dbce71c1a20dd3481
refs/heads/master
1,541,049,198,347
1,537,967,023,000
1,537,967,029,000
119,653,145
1
0
null
null
null
null
UTF-8
Lean
false
false
963
lean
import data.equiv.basic namespace tts ------------------------------------------------------------------ /-- An enumeration of the states in which a variable can occur with respect to bindings. `occurs` is isomorphic to `bool` but more descriptive in naming. -/ @[derive decidable_eq] inductive occurs : Type | bound : occurs -- Referenced by a binding | free : occurs -- Not referenced by any binding (unbound) namespace occurs --------------------------------------------------------------- @[simp] def is_free : occurs → bool | bound := ff | free := tt @[simp] def of_free : bool → occurs | ff := bound | tt := free def equiv_bool : occurs ≃ bool := ⟨is_free, of_free, λ o, by cases o; simp, λ b, by cases b; simp⟩ @[reducible] instance : has_coe occurs bool := ⟨is_free⟩ end /- namespace -/ occurs ----------------------------------------------------- end /- namespace -/ tts --------------------------------------------------------
edc18f8cd4862becde36eb9c0cc7a70c4151257e
0c9c1ff8e5013c525bf1d72338b62db639374733
/library/init/data/nat/lemmas.lean
e1fb94474959d99714b64cd4439b834d86155061
[ "Apache-2.0" ]
permissive
semorrison/lean
1f2bb450c3400098666ff6e43aa29b8e1e3cdc3a
85dcb385d5219f2fca8c73b2ebca270fe81337e0
refs/heads/master
1,638,526,143,586
1,634,825,588,000
1,634,825,588,000
258,650,844
0
0
Apache-2.0
1,587,772,955,000
1,587,772,954,000
null
UTF-8
Lean
false
false
49,238
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad -/ prelude import init.data.nat.basic init.data.nat.div init.meta init.algebra.functions universes u namespace nat attribute [pre_smt] nat_zero_eq_zero /-! addition -/ protected lemma add_comm : ∀ n m : ℕ, n + m = m + n | n 0 := eq.symm (nat.zero_add n) | n (m+1) := suffices succ (n + m) = succ (m + n), from eq.symm (succ_add m n) ▸ this, congr_arg succ (add_comm n m) protected lemma add_assoc : ∀ n m k : ℕ, (n + m) + k = n + (m + k) | n m 0 := rfl | n m (succ k) := by rw [add_succ, add_succ, add_assoc]; refl protected lemma add_left_comm : ∀ (n m k : ℕ), n + (m + k) = m + (n + k) := left_comm nat.add nat.add_comm nat.add_assoc protected lemma add_left_cancel : ∀ {n m k : ℕ}, n + m = n + k → m = k | 0 m k := by simp [nat.zero_add] {contextual := tt} | (succ n) m k := λ h, have n+m = n+k, by { simp [succ_add] at h, assumption }, add_left_cancel this protected lemma add_right_cancel {n m k : ℕ} (h : n + m = k + m) : n = k := have m + n = m + k, by rwa [nat.add_comm n m, nat.add_comm k m] at h, nat.add_left_cancel this lemma succ_ne_zero (n : ℕ) : succ n ≠ 0 := assume h, nat.no_confusion h lemma succ_ne_self : ∀ n : ℕ, succ n ≠ n | 0 h := absurd h (nat.succ_ne_zero 0) | (n+1) h := succ_ne_self n (nat.no_confusion h (λ h, h)) protected lemma one_ne_zero : 1 ≠ (0 : ℕ) := assume h, nat.no_confusion h protected lemma zero_ne_one : 0 ≠ (1 : ℕ) := assume h, nat.no_confusion h protected lemma eq_zero_of_add_eq_zero_right : ∀ {n m : ℕ}, n + m = 0 → n = 0 | 0 m := by simp [nat.zero_add] | (n+1) m := λ h, begin exfalso, rw [add_one, succ_add] at h, apply succ_ne_zero _ h end protected lemma eq_zero_of_add_eq_zero_left {n m : ℕ} (h : n + m = 0) : m = 0 := @nat.eq_zero_of_add_eq_zero_right m n (nat.add_comm n m ▸ h) protected theorem add_right_comm : ∀ (n m k : ℕ), n + m + k = n + k + m := right_comm nat.add nat.add_comm nat.add_assoc theorem eq_zero_of_add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0 := ⟨nat.eq_zero_of_add_eq_zero_right H, nat.eq_zero_of_add_eq_zero_left H⟩ /-! multiplication -/ protected lemma mul_zero (n : ℕ) : n * 0 = 0 := rfl lemma mul_succ (n m : ℕ) : n * succ m = n * m + n := rfl protected theorem zero_mul : ∀ (n : ℕ), 0 * n = 0 | 0 := rfl | (succ n) := by rw [mul_succ, zero_mul] private meta def sort_add := `[simp [nat.add_assoc, nat.add_comm, nat.add_left_comm]] lemma succ_mul : ∀ (n m : ℕ), (succ n) * m = (n * m) + m | n 0 := rfl | n (succ m) := begin simp [mul_succ, add_succ, succ_mul n m], sort_add end protected lemma right_distrib : ∀ (n m k : ℕ), (n + m) * k = n * k + m * k | n m 0 := rfl | n m (succ k) := begin simp [mul_succ, right_distrib n m k], sort_add end protected lemma left_distrib : ∀ (n m k : ℕ), n * (m + k) = n * m + n * k | 0 m k := by simp [nat.zero_mul] | (succ n) m k := begin simp [succ_mul, left_distrib n m k], sort_add end protected lemma mul_comm : ∀ (n m : ℕ), n * m = m * n | n 0 := by rw [nat.zero_mul, nat.mul_zero] | n (succ m) := by simp [mul_succ, succ_mul, mul_comm n m] protected lemma mul_assoc : ∀ (n m k : ℕ), (n * m) * k = n * (m * k) | n m 0 := rfl | n m (succ k) := by simp [mul_succ, nat.left_distrib, mul_assoc n m k] protected lemma mul_one : ∀ (n : ℕ), n * 1 = n := nat.zero_add protected lemma one_mul (n : ℕ) : 1 * n = n := by rw [nat.mul_comm, nat.mul_one] theorem succ_add_eq_succ_add (n m : ℕ) : succ n + m = n + succ m := by simp [succ_add, add_succ] theorem eq_zero_of_mul_eq_zero : ∀ {n m : ℕ}, n * m = 0 → n = 0 ∨ m = 0 | 0 m := λ h, or.inl rfl | (succ n) m := begin rw succ_mul, intro h, exact or.inr (nat.eq_zero_of_add_eq_zero_left h) end /-! properties of inequality -/ protected lemma le_of_eq {n m : ℕ} (p : n = m) : n ≤ m := p ▸ less_than_or_equal.refl lemma le_succ_of_le {n m : ℕ} (h : n ≤ m) : n ≤ succ m := nat.le_trans h (le_succ m) lemma le_of_succ_le {n m : ℕ} (h : succ n ≤ m) : n ≤ m := nat.le_trans (le_succ n) h protected lemma le_of_lt {n m : ℕ} (h : n < m) : n ≤ m := le_of_succ_le h lemma lt.step {n m : ℕ} : n < m → n < succ m := less_than_or_equal.step protected lemma eq_zero_or_pos (n : ℕ) : n = 0 ∨ 0 < n := by {cases n, exact or.inl rfl, exact or.inr (succ_pos _)} protected lemma pos_of_ne_zero {n : nat} : n ≠ 0 → 0 < n := or.resolve_left n.eq_zero_or_pos protected lemma lt_trans {n m k : ℕ} (h₁ : n < m) : m < k → n < k := nat.le_trans (less_than_or_equal.step h₁) protected lemma lt_of_le_of_lt {n m k : ℕ} (h₁ : n ≤ m) : m < k → n < k := nat.le_trans (succ_le_succ h₁) lemma lt.base (n : ℕ) : n < succ n := nat.le_refl (succ n) lemma lt_succ_self (n : ℕ) : n < succ n := lt.base n protected lemma le_antisymm {n m : ℕ} (h₁ : n ≤ m) : m ≤ n → n = m := less_than_or_equal.cases_on h₁ (λ a, rfl) (λ a b c, absurd (nat.lt_of_le_of_lt b c) (nat.lt_irrefl n)) protected lemma lt_or_ge : ∀ (a b : ℕ), a < b ∨ b ≤ a | a 0 := or.inr a.zero_le | a (b+1) := match lt_or_ge a b with | or.inl h := or.inl (le_succ_of_le h) | or.inr h := match nat.eq_or_lt_of_le h with | or.inl h1 := or.inl (h1 ▸ lt_succ_self b) | or.inr h1 := or.inr h1 end end protected lemma le_total {m n : ℕ} : m ≤ n ∨ n ≤ m := or.imp_left nat.le_of_lt (nat.lt_or_ge m n) protected lemma lt_of_le_and_ne {m n : ℕ} (h1 : m ≤ n) : m ≠ n → m < n := or.resolve_right (or.swap (nat.eq_or_lt_of_le h1)) protected lemma lt_iff_le_not_le {m n : ℕ} : m < n ↔ (m ≤ n ∧ ¬ n ≤ m) := ⟨λ hmn, ⟨nat.le_of_lt hmn, λ hnm, nat.lt_irrefl _ (nat.lt_of_le_of_lt hnm hmn)⟩, λ ⟨hmn, hnm⟩, nat.lt_of_le_and_ne hmn (λ heq, hnm (heq ▸ nat.le_refl _))⟩ instance : linear_order ℕ := { le := nat.less_than_or_equal, le_refl := @nat.le_refl, le_trans := @nat.le_trans, le_antisymm := @nat.le_antisymm, le_total := @nat.le_total, lt := nat.lt, lt_iff_le_not_le := @nat.lt_iff_le_not_le, decidable_lt := nat.decidable_lt, decidable_le := nat.decidable_le, decidable_eq := nat.decidable_eq } protected lemma eq_zero_of_le_zero {n : nat} (h : n ≤ 0) : n = 0 := le_antisymm h n.zero_le lemma succ_lt_succ {a b : ℕ} : a < b → succ a < succ b := succ_le_succ lemma lt_of_succ_lt {a b : ℕ} : succ a < b → a < b := le_of_succ_le lemma lt_of_succ_lt_succ {a b : ℕ} : succ a < succ b → a < b := le_of_succ_le_succ lemma pred_lt_pred : ∀ {n m : ℕ}, n ≠ 0 → n < m → pred n < pred m | 0 _ h₁ h := absurd rfl h₁ | n 0 h₁ h := absurd h n.not_lt_zero | (succ n) (succ m) _ h := lt_of_succ_lt_succ h lemma lt_of_succ_le {a b : ℕ} (h : succ a ≤ b) : a < b := h lemma succ_le_of_lt {a b : ℕ} (h : a < b) : succ a ≤ b := h protected lemma le_add_right : ∀ (n k : ℕ), n ≤ n + k | n 0 := nat.le_refl n | n (k+1) := le_succ_of_le (le_add_right n k) protected lemma le_add_left (n m : ℕ): n ≤ m + n := nat.add_comm n m ▸ n.le_add_right m lemma le.dest : ∀ {n m : ℕ}, n ≤ m → ∃ k, n + k = m | n _ less_than_or_equal.refl := ⟨0, rfl⟩ | n _ (less_than_or_equal.step h) := match le.dest h with | ⟨w, hw⟩ := ⟨succ w, hw ▸ add_succ n w⟩ end protected lemma le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := h ▸ n.le_add_right k protected lemma add_le_add_left {n m : ℕ} (h : n ≤ m) (k : ℕ) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc, hw] end end protected lemma add_le_add_right {n m : ℕ} (h : n ≤ m) (k : ℕ) : n + k ≤ m + k := begin rw [nat.add_comm n k, nat.add_comm m k], apply nat.add_le_add_left h end protected lemma le_of_add_le_add_left {k n m : ℕ} (h : k + n ≤ k + m) : n ≤ m := match le.dest h with | ⟨w, hw⟩ := @le.intro _ _ w begin rw [nat.add_assoc] at hw, apply nat.add_left_cancel hw end end protected lemma le_of_add_le_add_right {k n m : ℕ} : n + k ≤ m + k → n ≤ m := begin rw [nat.add_comm _ k, nat.add_comm _ k], apply nat.le_of_add_le_add_left end protected lemma add_le_add_iff_le_right (k n m : ℕ) : n + k ≤ m + k ↔ n ≤ m := ⟨ nat.le_of_add_le_add_right , assume h, nat.add_le_add_right h _ ⟩ protected theorem lt_of_add_lt_add_left {k n m : ℕ} (h : k + n < k + m) : n < m := let h' := nat.le_of_lt h in nat.lt_of_le_and_ne (nat.le_of_add_le_add_left h') (λ heq, nat.lt_irrefl (k + m) begin rw heq at h, assumption end) protected lemma lt_of_add_lt_add_right {a b c : ℕ} (h : a + b < c + b) : a < c := nat.lt_of_add_lt_add_left $ show b + a < b + c, by rwa [nat.add_comm b a, nat.add_comm b c] protected lemma add_lt_add_left {n m : ℕ} (h : n < m) (k : ℕ) : k + n < k + m := lt_of_succ_le (add_succ k n ▸ nat.add_le_add_left (succ_le_of_lt h) k) protected lemma add_lt_add_right {n m : ℕ} (h : n < m) (k : ℕ) : n + k < m + k := nat.add_comm k m ▸ nat.add_comm k n ▸ nat.add_lt_add_left h k protected lemma lt_add_of_pos_right {n k : ℕ} (h : 0 < k) : n < n + k := nat.add_lt_add_left h n protected lemma lt_add_of_pos_left {n k : ℕ} (h : 0 < k) : n < k + n := by rw nat.add_comm; exact nat.lt_add_of_pos_right h protected lemma add_lt_add {a b c d : ℕ} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := lt_trans (nat.add_lt_add_right h₁ c) (nat.add_lt_add_left h₂ b) protected lemma add_le_add {a b c d : ℕ} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := le_trans (nat.add_le_add_right h₁ c) (nat.add_le_add_left h₂ b) protected lemma zero_lt_one : 0 < (1:nat) := zero_lt_succ 0 protected lemma mul_le_mul_left {n m : ℕ} (k : ℕ) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ := have k * n + k * l = k * m, by rw [← nat.left_distrib, hl], le.intro this end protected lemma mul_le_mul_right {n m : ℕ} (k : ℕ) (h : n ≤ m) : n * k ≤ m * k := nat.mul_comm k m ▸ nat.mul_comm k n ▸ k.mul_le_mul_left h protected lemma mul_lt_mul_of_pos_left {n m k : ℕ} (h : n < m) (hk : 0 < k) : k * n < k * m := nat.lt_of_lt_of_le (nat.lt_add_of_pos_right hk) (mul_succ k n ▸ nat.mul_le_mul_left k (succ_le_of_lt h)) protected lemma mul_lt_mul_of_pos_right {n m k : ℕ} (h : n < m) (hk : 0 < k) : n * k < m * k := nat.mul_comm k m ▸ nat.mul_comm k n ▸ nat.mul_lt_mul_of_pos_left h hk protected lemma le_of_mul_le_mul_left {a b c : ℕ} (h : c * a ≤ c * b) (hc : 0 < c) : a ≤ b := not_lt.1 (assume h1 : b < a, have h2 : c * b < c * a, from nat.mul_lt_mul_of_pos_left h1 hc, not_le_of_gt h2 h) lemma le_of_lt_succ {m n : nat} : m < succ n → m ≤ n := le_of_succ_le_succ protected theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : 0 < n) (H : n * m = n * k) : m = k := le_antisymm (nat.le_of_mul_le_mul_left (le_of_eq H) Hn) (nat.le_of_mul_le_mul_left (le_of_eq H.symm) Hn) protected lemma mul_pos {a b : ℕ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b := have h : 0 * b < a * b, from nat.mul_lt_mul_of_pos_right ha hb, by rwa nat.zero_mul at h theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n less_than_or_equal.step (λ a, succ_le_succ) theorem le_lt_antisymm {n m : ℕ} (h₁ : n ≤ m) (h₂ : m < n) : false := nat.lt_irrefl n (nat.lt_of_le_of_lt h₁ h₂) theorem lt_le_antisymm {n m : ℕ} (h₁ : n < m) (h₂ : m ≤ n) : false := le_lt_antisymm h₂ h₁ protected theorem lt_asymm {n m : ℕ} (h₁ : n < m) : ¬ m < n := le_lt_antisymm (nat.le_of_lt h₁) protected def lt_ge_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : b ≤ a → C) : C := decidable.by_cases h₁ (λ h, h₂ (or.elim (nat.lt_or_ge a b) (λ a, absurd a h) (λ a, a))) protected def lt_by_cases {a b : ℕ} {C : Sort u} (h₁ : a < b → C) (h₂ : a = b → C) (h₃ : b < a → C) : C := nat.lt_ge_by_cases h₁ (λ h₁, nat.lt_ge_by_cases h₃ (λ h, h₂ (nat.le_antisymm h h₁))) protected theorem lt_trichotomy (a b : ℕ) : a < b ∨ a = b ∨ b < a := nat.lt_by_cases (λ h, or.inl h) (λ h, or.inr (or.inl h)) (λ h, or.inr (or.inr h)) protected theorem eq_or_lt_of_not_lt {a b : ℕ} (hnlt : ¬ a < b) : a = b ∨ b < a := (nat.lt_trichotomy a b).resolve_left hnlt theorem lt_succ_of_lt {a b : nat} (h : a < b) : a < succ b := le_succ_of_le h lemma one_pos : 0 < 1 := nat.zero_lt_one protected lemma mul_le_mul_of_nonneg_left {a b c : ℕ} (h₁ : a ≤ b) : c * a ≤ c * b := begin by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] }, by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 c.zero_le, nat.zero_mul] }, exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_left (lt_of_le_not_le h₁ hba) (lt_of_le_not_le c.zero_le hc0))).left, end protected lemma mul_le_mul_of_nonneg_right {a b c : ℕ} (h₁ : a ≤ b) : a * c ≤ b * c := begin by_cases hba : b ≤ a, { simp [le_antisymm hba h₁] }, by_cases hc0 : c ≤ 0, { simp [le_antisymm hc0 c.zero_le, nat.mul_zero] }, exact (le_not_le_of_lt (nat.mul_lt_mul_of_pos_right (lt_of_le_not_le h₁ hba) (lt_of_le_not_le c.zero_le hc0))).left, end protected lemma mul_lt_mul {a b c d : ℕ} (hac : a < c) (hbd : b ≤ d) (pos_b : 0 < b) : a * b < c * d := calc a * b < c * b : nat.mul_lt_mul_of_pos_right hac pos_b ... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd protected lemma mul_lt_mul' {a b c d : ℕ} (h1 : a ≤ c) (h2 : b < d) (h3 : 0 < c) : a * b < c * d := calc a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right h1 ... < c * d : nat.mul_lt_mul_of_pos_left h2 h3 -- TODO: there are four variations, depending on which variables we assume to be nonneg protected lemma mul_le_mul {a b c d : ℕ} (hac : a ≤ c) (hbd : b ≤ d) : a * b ≤ c * d := calc a * b ≤ c * b : nat.mul_le_mul_of_nonneg_right hac ... ≤ c * d : nat.mul_le_mul_of_nonneg_left hbd /-! bit0/bit1 properties -/ protected lemma bit1_eq_succ_bit0 (n : ℕ) : bit1 n = succ (bit0 n) := rfl protected lemma bit1_succ_eq (n : ℕ) : bit1 (succ n) = succ (succ (bit1 n)) := eq.trans (nat.bit1_eq_succ_bit0 (succ n)) (congr_arg succ (nat.bit0_succ_eq n)) protected lemma bit1_ne_one : ∀ {n : ℕ}, n ≠ 0 → bit1 n ≠ 1 | 0 h h1 := absurd rfl h | (n+1) h h1 := nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero _)) protected lemma bit0_ne_one : ∀ n : ℕ, bit0 n ≠ 1 | 0 h := absurd h (ne.symm nat.one_ne_zero) | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (succ_ne_zero (n + n))) protected lemma add_self_ne_one : ∀ (n : ℕ), n + n ≠ 1 | 0 h := nat.no_confusion h | (n+1) h := have h1 : succ (succ (n + n)) = 1, from succ_add n n ▸ h, nat.no_confusion h1 (λ h2, absurd h2 (nat.succ_ne_zero (n + n))) protected lemma bit1_ne_bit0 : ∀ (n m : ℕ), bit1 n ≠ bit0 m | 0 m h := absurd h (ne.symm (nat.add_self_ne_one m)) | (n+1) 0 h := have h1 : succ (bit0 (succ n)) = 0, from h, absurd h1 (nat.succ_ne_zero _) | (n+1) (m+1) h := have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)), from nat.bit0_succ_eq m ▸ nat.bit1_succ_eq n ▸ h, have h2 : bit1 n = bit0 m, from nat.no_confusion h1 (λ h2', nat.no_confusion h2' (λ h2'', h2'')), absurd h2 (bit1_ne_bit0 n m) protected lemma bit0_ne_bit1 : ∀ (n m : ℕ), bit0 n ≠ bit1 m := λ n m : nat, ne.symm (nat.bit1_ne_bit0 m n) protected lemma bit0_inj : ∀ {n m : ℕ}, bit0 n = bit0 m → n = m | 0 0 h := rfl | 0 (m+1) h := by contradiction | (n+1) 0 h := by contradiction | (n+1) (m+1) h := have succ (succ (n + n)) = succ (succ (m + m)), by { unfold bit0 at h, simp [add_one, add_succ, succ_add] at h, have aux : n + n = m + m := h, rw aux }, have n + n = m + m, by iterate { injection this with this }, have n = m, from bit0_inj this, by rw this protected lemma bit1_inj : ∀ {n m : ℕ}, bit1 n = bit1 m → n = m := λ n m h, have succ (bit0 n) = succ (bit0 m), begin simp [nat.bit1_eq_succ_bit0] at h, rw h end, have bit0 n = bit0 m, by injection this, nat.bit0_inj this protected lemma bit0_ne {n m : ℕ} : n ≠ m → bit0 n ≠ bit0 m := λ h₁ h₂, absurd (nat.bit0_inj h₂) h₁ protected lemma bit1_ne {n m : ℕ} : n ≠ m → bit1 n ≠ bit1 m := λ h₁ h₂, absurd (nat.bit1_inj h₂) h₁ protected lemma zero_ne_bit0 {n : ℕ} : n ≠ 0 → 0 ≠ bit0 n := λ h, ne.symm (nat.bit0_ne_zero h) protected lemma zero_ne_bit1 (n : ℕ) : 0 ≠ bit1 n := ne.symm (nat.bit1_ne_zero n) protected lemma one_ne_bit0 (n : ℕ) : 1 ≠ bit0 n := ne.symm (nat.bit0_ne_one n) protected lemma one_ne_bit1 {n : ℕ} : n ≠ 0 → 1 ≠ bit1 n := λ h, ne.symm (nat.bit1_ne_one h) protected lemma one_lt_bit1 : ∀ {n : nat}, n ≠ 0 → 1 < bit1 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit1_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma one_lt_bit0 : ∀ {n : nat}, n ≠ 0 → 1 < bit0 n | 0 h := by contradiction | (succ n) h := begin rw nat.bit0_succ_eq, apply succ_lt_succ, apply zero_lt_succ end protected lemma bit0_lt {n m : nat} (h : n < m) : bit0 n < bit0 m := nat.add_lt_add h h protected lemma bit1_lt {n m : nat} (h : n < m) : bit1 n < bit1 m := succ_lt_succ (nat.add_lt_add h h) protected lemma bit0_lt_bit1 {n m : nat} (h : n ≤ m) : bit0 n < bit1 m := lt_succ_of_le (nat.add_le_add h h) protected lemma bit1_lt_bit0 : ∀ {n m : nat}, n < m → bit1 n < bit0 m | n 0 h := absurd h n.not_lt_zero | n (succ m) h := have n ≤ m, from le_of_lt_succ h, have succ (n + n) ≤ succ (m + m), from succ_le_succ (nat.add_le_add this this), have succ (n + n) ≤ succ m + m, {rw succ_add, assumption}, show succ (n + n) < succ (succ m + m), from lt_succ_of_le this protected lemma one_le_bit1 (n : ℕ) : 1 ≤ bit1 n := show 1 ≤ succ (bit0 n), from succ_le_succ (bit0 n).zero_le protected lemma one_le_bit0 : ∀ (n : ℕ), n ≠ 0 → 1 ≤ bit0 n | 0 h := absurd rfl h | (n+1) h := suffices 1 ≤ succ (succ (bit0 n)), from eq.symm (nat.bit0_succ_eq n) ▸ this, succ_le_succ (bit0 n).succ.zero_le /-! successor and predecessor -/ @[simp] lemma pred_zero : pred 0 = 0 := rfl @[simp] lemma pred_succ (n : ℕ) : pred (succ n) = n := rfl theorem add_one_ne_zero (n : ℕ) : n + 1 ≠ 0 := succ_ne_zero _ theorem eq_zero_or_eq_succ_pred (n : ℕ) : n = 0 ∨ n = succ (pred n) := by cases n; simp theorem exists_eq_succ_of_ne_zero {n : ℕ} (H : n ≠ 0) : ∃k : ℕ, n = succ k := ⟨_, (eq_zero_or_eq_succ_pred _).resolve_left H⟩ def discriminate {B : Sort u} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B := by induction h : n; [exact H1 h, exact H2 _ h] theorem one_succ_zero : 1 = succ 0 := rfl theorem pred_inj : ∀ {a b : nat}, 0 < a → 0 < b → nat.pred a = nat.pred b → a = b | (succ a) (succ b) ha hb h := have a = b, from h, by rw this | (succ a) 0 ha hb h := absurd hb (lt_irrefl _) | 0 (succ b) ha hb h := absurd ha (lt_irrefl _) | 0 0 ha hb h := rfl /-! subtraction Many lemmas are proven more generally in mathlib `algebra/order/sub` -/ @[simp] protected lemma zero_sub : ∀ a : ℕ, 0 - a = 0 | 0 := rfl | (a+1) := congr_arg pred (zero_sub a) lemma sub_lt_succ (a b : ℕ) : a - b < succ a := lt_succ_of_le (a.sub_le b) protected theorem sub_le_sub_right {n m : ℕ} (h : n ≤ m) : ∀ k, n - k ≤ m - k | 0 := h | (succ z) := pred_le_pred (sub_le_sub_right z) @[simp] protected theorem sub_zero (n : ℕ) : n - 0 = n := rfl theorem sub_succ (n m : ℕ) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : ℕ) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : ℕ), n - n = 0 | 0 := by rw nat.sub_zero | (succ n) := by rw [succ_sub_succ, sub_self n] /- TODO(Leo): remove the following ematch annotations as soon as we have arithmetic theory in the smt_stactic -/ @[ematch_lhs] protected theorem add_sub_add_right : ∀ (n k m : ℕ), (n + k) - (m + k) = n - m | n 0 m := by rw [nat.add_zero, nat.add_zero] | n (succ k) m := by rw [add_succ, add_succ, succ_sub_succ, add_sub_add_right n k m] @[ematch_lhs] protected theorem add_sub_add_left (k n m : ℕ) : (k + n) - (k + m) = n - m := by rw [nat.add_comm k n, nat.add_comm k m, nat.add_sub_add_right] @[ematch_lhs] protected theorem add_sub_cancel (n m : ℕ) : n + m - m = n := suffices n + m - (0 + m) = n, from by rwa [nat.zero_add] at this, by rw [nat.add_sub_add_right, nat.sub_zero] @[ematch_lhs] protected theorem add_sub_cancel_left (n m : ℕ) : n + m - n = m := show n + m - (n + 0) = m, from by rw [nat.add_sub_add_left, nat.sub_zero] protected theorem sub_sub : ∀ (n m k : ℕ), n - m - k = n - (m + k) | n m 0 := by rw [nat.add_zero, nat.sub_zero] | n m (succ k) := by rw [add_succ, nat.sub_succ, nat.sub_succ, sub_sub n m k] protected theorem le_of_le_of_sub_le_sub_right {n m k : ℕ} (h₀ : k ≤ m) (h₁ : n - k ≤ m - k) : n ≤ m := begin revert k m, induction n with n ; intros k m h₀ h₁, { exact m.zero_le }, { cases k with k, { apply h₁ }, cases m with m, { cases not_succ_le_zero _ h₀ }, { simp [succ_sub_succ] at h₁, apply succ_le_succ, apply n_ih _ h₁, apply le_of_succ_le_succ h₀ }, } end protected theorem sub_le_sub_right_iff (n m k : ℕ) (h : k ≤ m) : n - k ≤ m - k ↔ n ≤ m := ⟨ nat.le_of_le_of_sub_le_sub_right h , assume h, nat.sub_le_sub_right h k ⟩ protected theorem sub_self_add (n m : ℕ) : n - (n + m) = 0 := show (n + 0) - (n + m) = 0, from by rw [nat.add_sub_add_left, nat.zero_sub] protected theorem add_le_to_le_sub (x : ℕ) {y k : ℕ} (h : k ≤ y) : x + k ≤ y ↔ x ≤ y - k := by rw [← nat.add_sub_cancel x k, nat.sub_le_sub_right_iff _ _ _ h, nat.add_sub_cancel] protected lemma sub_lt_of_pos_le (a b : ℕ) (h₀ : 0 < a) (h₁ : a ≤ b) : b - a < b := begin apply nat.sub_lt _ h₀, apply lt_of_lt_of_le h₀ h₁ end protected theorem sub_one (n : ℕ) : n - 1 = pred n := rfl theorem succ_sub_one (n : ℕ) : succ n - 1 = n := rfl theorem succ_pred_eq_of_pos : ∀ {n : ℕ}, 0 < n → succ (pred n) = n | 0 h := absurd h (lt_irrefl 0) | (succ k) h := rfl protected theorem sub_eq_zero_of_le {n m : ℕ} (h : n ≤ m) : n - m = 0 := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.sub_self_add]) protected theorem le_of_sub_eq_zero : ∀{n m : ℕ}, n - m = 0 → n ≤ m | n 0 H := begin rw [nat.sub_zero] at H, simp [H] end | 0 (m+1) H := (m + 1).zero_le | (n+1) (m+1) H := nat.add_le_add_right (le_of_sub_eq_zero begin simp [nat.add_sub_add_right] at H, exact H end) _ protected theorem sub_eq_zero_iff_le {n m : ℕ} : n - m = 0 ↔ n ≤ m := ⟨nat.le_of_sub_eq_zero, nat.sub_eq_zero_of_le⟩ protected theorem add_sub_of_le {n m : ℕ} (h : n ≤ m) : n + (m - n) = m := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left]) protected theorem sub_add_cancel {n m : ℕ} (h : m ≤ n) : n - m + m = n := by rw [nat.add_comm, nat.add_sub_of_le h] protected theorem add_sub_assoc {m k : ℕ} (h : k ≤ m) (n : ℕ) : n + m - k = n + (m - k) := exists.elim (nat.le.dest h) (assume l, assume hl : k + l = m, by rw [← hl, nat.add_sub_cancel_left, nat.add_comm k, ← nat.add_assoc, nat.add_sub_cancel]) protected lemma sub_eq_iff_eq_add {a b c : ℕ} (ab : b ≤ a) : a - b = c ↔ a = c + b := ⟨assume c_eq, begin rw [c_eq.symm, nat.sub_add_cancel ab] end, assume a_eq, begin rw [a_eq, nat.add_sub_cancel] end⟩ protected lemma lt_of_sub_eq_succ {m n l : ℕ} (H : m - n = nat.succ l) : n < m := not_le.1 (assume (H' : n ≥ m), begin simp [nat.sub_eq_zero_of_le H'] at H, contradiction end) protected theorem sub_le_sub_left {n m : ℕ} (k) (h : n ≤ m) : k - m ≤ k - n := by induction h; [refl, exact le_trans (pred_le _) h_ih] theorem succ_sub_sub_succ (n m k : ℕ) : succ n - m - succ k = n - m - k := by rw [nat.sub_sub, nat.sub_sub, add_succ, succ_sub_succ] protected theorem sub.right_comm (m n k : ℕ) : m - n - k = m - k - n := by rw [nat.sub_sub, nat.sub_sub, nat.add_comm] theorem succ_sub {m n : ℕ} (h : n ≤ m) : succ m - n = succ (m - n) := exists.elim (nat.le.dest h) (assume k, assume hk : n + k = m, by rw [← hk, nat.add_sub_cancel_left, ← add_succ, nat.add_sub_cancel_left]) protected theorem sub_pos_of_lt {m n : ℕ} (h : m < n) : 0 < n - m := have 0 + m < n - m + m, begin rw [nat.zero_add, nat.sub_add_cancel (le_of_lt h)], exact h end, nat.lt_of_add_lt_add_right this protected theorem sub_sub_self {n m : ℕ} (h : m ≤ n) : n - (n - m) = m := (nat.sub_eq_iff_eq_add (nat.sub_le _ _)).2 (nat.add_sub_of_le h).symm protected theorem sub_add_comm {n m k : ℕ} (h : k ≤ n) : n + m - k = n - k + m := (nat.sub_eq_iff_eq_add (nat.le_trans h (nat.le_add_right _ _))).2 (by rwa [nat.add_right_comm, nat.sub_add_cancel]) theorem sub_one_sub_lt {n i} (h : i < n) : n - 1 - i < n := begin rw nat.sub_sub, apply nat.sub_lt, apply lt_of_lt_of_le (nat.zero_lt_succ _) h, rw nat.add_comm, apply nat.zero_lt_succ end theorem mul_pred_left : ∀ (n m : ℕ), pred n * m = n * m - m | 0 m := by simp [nat.zero_sub, pred_zero, nat.zero_mul] | (succ n) m := by rw [pred_succ, succ_mul, nat.add_sub_cancel] theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n := by rw [nat.mul_comm, mul_pred_left, nat.mul_comm] protected theorem mul_sub_right_distrib : ∀ (n m k : ℕ), (n - m) * k = n * k - m * k | n 0 k := by simp [nat.sub_zero, nat.zero_mul] | n (succ m) k := by rw [nat.sub_succ, mul_pred_left, mul_sub_right_distrib, succ_mul, nat.sub_sub] protected theorem mul_sub_left_distrib (n m k : ℕ) : n * (m - k) = n * m - n * k := by rw [nat.mul_comm, nat.mul_sub_right_distrib, nat.mul_comm m n, nat.mul_comm n k] protected theorem mul_self_sub_mul_self_eq (a b : nat) : a * a - b * b = (a + b) * (a - b) := by rw [nat.mul_sub_left_distrib, nat.right_distrib, nat.right_distrib, nat.mul_comm b a, nat.add_comm (a*a) (a*b), nat.add_sub_add_left] theorem succ_mul_succ_eq (a b : nat) : succ a * succ b = a * b + a + b + 1 := begin rw [← add_one, ← add_one], simp [nat.right_distrib, nat.left_distrib, nat.add_left_comm, nat.mul_one, nat.one_mul, nat.add_assoc], end /-! min -/ protected lemma zero_min (a : ℕ) : min 0 a = 0 := min_eq_left a.zero_le protected lemma min_zero (a : ℕ) : min a 0 = 0 := min_eq_right a.zero_le -- Distribute succ over min theorem min_succ_succ (x y : ℕ) : min (succ x) (succ y) = succ (min x y) := have f : x ≤ y → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ x : if_pos (succ_le_succ p) ... = succ (min x y) : congr_arg succ (eq.symm (if_pos p)), have g : ¬ (x ≤ y) → min (succ x) (succ y) = succ (min x y), from λp, calc min (succ x) (succ y) = succ y : if_neg (λeq, p (pred_le_pred eq)) ... = succ (min x y) : congr_arg succ (eq.symm (if_neg p)), decidable.by_cases f g theorem sub_eq_sub_min (n m : ℕ) : n - m = n - min n m := if h : n ≥ m then by rewrite [min_eq_right h] else by rewrite [nat.sub_eq_zero_of_le (le_of_not_ge h), min_eq_left (le_of_not_ge h), nat.sub_self] @[simp] protected theorem sub_add_min_cancel (n m : ℕ) : n - m + min n m = n := by rw [sub_eq_sub_min, nat.sub_add_cancel (min_le_left n m)] /-! induction principles -/ def two_step_induction {P : ℕ → Sort u} (H1 : P 0) (H2 : P 1) (H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : Π (a : ℕ), P a | 0 := H1 | 1 := H2 | (succ (succ n)) := H3 _ (two_step_induction _) (two_step_induction _) def sub_induction {P : ℕ → ℕ → Sort u} (H1 : ∀m, P 0 m) (H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : Π (n m : ℕ), P n m | 0 m := H1 _ | (succ n) 0 := H2 _ | (succ n) (succ m) := H3 _ _ (sub_induction n m) protected def strong_rec_on {p : nat → Sort u} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := suffices ∀ n m, m < n → p m, from this (succ n) n (lt_succ_self _), begin intros n, induction n with n ih, {intros m h₁, exact absurd h₁ m.not_lt_zero}, {intros m h₁, apply or.by_cases (decidable.lt_or_eq_of_le (le_of_lt_succ h₁)), {intros, apply ih, assumption}, {intros, subst m, apply h _ ih}} end protected lemma strong_induction_on {p : nat → Prop} (n : nat) (h : ∀ n, (∀ m, m < n → p m) → p n) : p n := nat.strong_rec_on n h protected lemma case_strong_induction_on {p : nat → Prop} (a : nat) (hz : p 0) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (succ n)) : p a := nat.strong_induction_on a $ λ n, match n with | 0 := λ _, hz | (n+1) := λ h₁, hi n (λ m h₂, h₁ _ (lt_succ_of_le h₂)) end /-! mod -/ private lemma mod_core_congr {x y f1 f2} (h1 : x ≤ f1) (h2 : x ≤ f2) : nat.mod_core y f1 x = nat.mod_core y f2 x := begin cases y, { cases f1; cases f2; refl }, induction f1 with f1 ih generalizing x f2, { cases h1, cases f2; refl }, cases x, { cases f1; cases f2; refl }, cases f2, { cases h2 }, refine if_congr iff.rfl _ rfl, simp only [succ_sub_succ], exact ih (le_trans (nat.sub_le _ _) (le_of_succ_le_succ h1)) (le_trans (nat.sub_le _ _) (le_of_succ_le_succ h2)) end lemma mod_def (x y : nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := begin cases x, { cases y; refl }, cases y, { refl }, refine if_congr iff.rfl (mod_core_congr _ _) rfl; simp [nat.sub_le] end @[simp] lemma mod_zero (a : nat) : a % 0 = a := begin rw mod_def, have h : ¬ (0 < 0 ∧ 0 ≤ a), simp [lt_irrefl], simp [if_neg, h] end lemma mod_eq_of_lt {a b : nat} (h : a < b) : a % b = a := begin rw mod_def, have h' : ¬(0 < b ∧ b ≤ a), simp [not_le_of_gt h], simp [if_neg, h'] end @[simp] lemma zero_mod (b : nat) : 0 % b = 0 := begin rw mod_def, have h : ¬(0 < b ∧ b ≤ 0), {intro hn, cases hn with l r, exact absurd (lt_of_lt_of_le l r) (lt_irrefl 0)}, simp [if_neg, h] end lemma mod_eq_sub_mod {a b : nat} (h : b ≤ a) : a % b = (a - b) % b := or.elim b.eq_zero_or_pos (λb0, by rw [b0, nat.sub_zero]) (λh₂, by rw [mod_def, if_pos (and.intro h₂ h)]) lemma mod_lt (x : nat) {y : nat} (h : 0 < y) : x % y < y := begin induction x using nat.case_strong_induction_on with x ih, { rw zero_mod, assumption }, { by_cases h₁ : succ x < y, { rwa [mod_eq_of_lt h₁] }, { have h₁ : succ x % y = (succ x - y) % y := mod_eq_sub_mod (not_lt.1 h₁), have : succ x - y ≤ x := le_of_lt_succ (nat.sub_lt (succ_pos x) h), have h₂ : (succ x - y) % y < y := ih _ this, rwa [← h₁] at h₂ } } end @[simp] theorem mod_self (n : nat) : n % n = 0 := by rw [mod_eq_sub_mod (le_refl _), nat.sub_self, zero_mod] @[simp] lemma mod_one (n : ℕ) : n % 1 = 0 := have n % 1 < 1, from (mod_lt n) (succ_pos 0), nat.eq_zero_of_le_zero (le_of_lt_succ this) lemma mod_two_eq_zero_or_one (n : ℕ) : n % 2 = 0 ∨ n % 2 = 1 := match n % 2, @nat.mod_lt n 2 dec_trivial with | 0, _ := or.inl rfl | 1, _ := or.inr rfl | k+2, h := absurd h dec_trivial end theorem mod_le (x y : ℕ) : x % y ≤ x := or.elim (lt_or_le x y) (λxlty, by rw mod_eq_of_lt xlty; refl) (λylex, or.elim y.eq_zero_or_pos (λy0, by rw [y0, mod_zero]; refl) (λypos, le_trans (le_of_lt (mod_lt _ ypos)) ylex)) @[simp] theorem add_mod_right (x z : ℕ) : (x + z) % z = x % z := by rw [mod_eq_sub_mod (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_mod_left (x z : ℕ) : (x + z) % x = z % x := by rw [nat.add_comm, add_mod_right] @[simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := by {induction z with z ih, rw [nat.mul_zero, nat.add_zero], rw [mul_succ, ← nat.add_assoc, add_mod_right, ih]} @[simp] theorem add_mul_mod_self_right (x y z : ℕ) : (x + y * z) % z = x % z := by rw [nat.mul_comm, add_mul_mod_self_left] @[simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 := by rw [← nat.zero_add (m*n), add_mul_mod_self_left, zero_mod] @[simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 := by rw [nat.mul_comm, mul_mod_right] theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) := if y0 : y = 0 then by rw [y0, nat.mul_zero, mod_zero, mod_zero] else if z0 : z = 0 then by rw [z0, nat.zero_mul, nat.zero_mul, nat.zero_mul, mod_zero] else x.strong_induction_on $ λn IH, have y0 : y > 0, from nat.pos_of_ne_zero y0, have z0 : z > 0, from nat.pos_of_ne_zero z0, or.elim (le_or_lt y n) (λyn, by rw [ mod_eq_sub_mod yn, mod_eq_sub_mod (nat.mul_le_mul_left z yn), ← nat.mul_sub_left_distrib]; exact IH _ (nat.sub_lt (lt_of_lt_of_le y0 yn) y0)) (λyn, by rw [mod_eq_of_lt yn, mod_eq_of_lt (nat.mul_lt_mul_of_pos_left yn z0)]) theorem mul_mod_mul_right (z x y : ℕ) : (x * z) % (y * z) = (x % y) * z := by rw [nat.mul_comm x z, nat.mul_comm y z, nat.mul_comm (x % y) z]; apply mul_mod_mul_left theorem cond_to_bool_mod_two (x : ℕ) [d : decidable (x % 2 = 1)] : cond (@to_bool (x % 2 = 1) d) 1 0 = x % 2 := begin by_cases h : x % 2 = 1, { simp! [*] }, { cases mod_two_eq_zero_or_one x; simp! [*, nat.zero_ne_one] } end theorem sub_mul_mod (x k n : ℕ) (h₁ : n*k ≤ x) : (x - n*k) % n = x % n := begin induction k with k, { rw [nat.mul_zero, nat.sub_zero] }, { have h₂ : n * k ≤ x, { rw [mul_succ] at h₁, apply nat.le_trans _ h₁, apply nat.le_add_right _ n }, have h₄ : x - n * k ≥ n, { apply @nat.le_of_add_le_add_right (n*k), rw [nat.sub_add_cancel h₂], simp [mul_succ, nat.add_comm] at h₁, simp [h₁] }, rw [mul_succ, ← nat.sub_sub, ← mod_eq_sub_mod h₄, k_ih h₂] } end /-! div -/ private lemma div_core_congr {x y f1 f2} (h1 : x ≤ f1) (h2 : x ≤ f2) : nat.div_core y f1 x = nat.div_core y f2 x := begin cases y, { cases f1; cases f2; refl }, induction f1 with f1 ih generalizing x f2, { cases h1, cases f2; refl }, cases x, { cases f1; cases f2; refl }, cases f2, { cases h2 }, refine if_congr iff.rfl _ rfl, simp only [succ_sub_succ], refine congr_arg (+1) _, exact ih (le_trans (nat.sub_le _ _) (le_of_succ_le_succ h1)) (le_trans (nat.sub_le _ _) (le_of_succ_le_succ h2)) end lemma div_def (x y : nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := begin cases x, { cases y; refl }, cases y, { refl }, refine if_congr iff.rfl (congr_arg (+1) _) rfl, refine div_core_congr _ _; simp [nat.sub_le] end lemma mod_add_div (m k : ℕ) : m % k + k * (m / k) = m := begin apply nat.strong_induction_on m, clear m, intros m IH, cases decidable.em (0 < k ∧ k ≤ m) with h h', -- 0 < k ∧ k ≤ m { have h' : m - k < m, { apply nat.sub_lt _ h.left, apply lt_of_lt_of_le h.left h.right }, rw [div_def, mod_def, if_pos h, if_pos h], simp [nat.left_distrib, IH _ h', nat.add_comm, nat.add_left_comm], rw [nat.add_comm, ← nat.add_sub_assoc h.right, nat.mul_one, nat.add_sub_cancel_left] }, -- ¬ (0 < k ∧ k ≤ m) { rw [div_def, mod_def, if_neg h', if_neg h', nat.mul_zero, nat.add_zero] }, end @[simp] protected lemma div_one (n : ℕ) : n / 1 = n := have n % 1 + 1 * (n / 1) = n, from mod_add_div _ _, by { rwa [mod_one, nat.zero_add, nat.one_mul] at this } @[simp] protected lemma div_zero (n : ℕ) : n / 0 = 0 := begin rw [div_def], simp [lt_irrefl] end @[simp] protected lemma zero_div (b : ℕ) : 0 / b = 0 := eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt) protected lemma div_le_of_le_mul {m n : ℕ} : ∀ {k}, m ≤ k * n → m / k ≤ n | 0 h := by simp [nat.div_zero, n.zero_le] | (succ k) h := suffices succ k * (m / succ k) ≤ succ k * n, from nat.le_of_mul_le_mul_left this (zero_lt_succ _), calc succ k * (m / succ k) ≤ m % succ k + succ k * (m / succ k) : nat.le_add_left _ _ ... = m : by rw mod_add_div ... ≤ succ k * n : h protected lemma div_le_self : ∀ (m n : ℕ), m / n ≤ m | m 0 := by simp [nat.div_zero, m.zero_le] | m (succ n) := have m ≤ succ n * m, from calc m = 1 * m : by rw nat.one_mul ... ≤ succ n * m : m.mul_le_mul_right (succ_le_succ n.zero_le), nat.div_le_of_le_mul this lemma div_eq_sub_div {a b : nat} (h₁ : 0 < b) (h₂ : b ≤ a) : a / b = (a - b) / b + 1 := begin rw [div_def a, if_pos], split ; assumption end lemma div_eq_of_lt {a b : ℕ} (h₀ : a < b) : a / b = 0 := begin rw [div_def a, if_neg], intro h₁, apply not_le_of_gt h₀ h₁.right end -- this is a Galois connection -- f x ≤ y ↔ x ≤ g y -- with -- f x = x * k -- g y = y / k theorem le_div_iff_mul_le (x y : ℕ) {k : ℕ} (Hk : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin -- Hk is needed because, despite div being made total, y / 0 := 0 -- x * 0 ≤ y ↔ x ≤ y / 0 -- ↔ 0 ≤ y ↔ x ≤ 0 -- ↔ true ↔ x = 0 -- ↔ x = 0 revert x, apply nat.strong_induction_on y _, clear y, intros y IH x, cases lt_or_le y k with h h, -- base case: y < k { rw [div_eq_of_lt h], cases x with x, { simp [nat.zero_mul, y.zero_le] }, { simp [succ_mul, not_succ_le_zero, nat.add_comm], apply lt_of_lt_of_le h, apply nat.le_add_right } }, -- step: k ≤ y { rw [div_eq_sub_div Hk h], cases x with x, { simp [nat.zero_mul, nat.zero_le] }, { have Hlt : y - k < y, { apply nat.sub_lt_of_pos_le ; assumption }, rw [ ← add_one , nat.add_le_add_iff_le_right , IH (y - k) Hlt x , add_one , succ_mul, nat.add_le_to_le_sub _ h ] } } end theorem div_lt_iff_lt_mul (x y : ℕ) {k : ℕ} (Hk : 0 < k) : x / k < y ↔ x < y * k := begin simp [← not_le], apply not_iff_not_of_iff, apply le_div_iff_mul_le _ _ Hk end theorem sub_mul_div (x n p : ℕ) (h₁ : n*p ≤ x) : (x - n*p) / n = x / n - p := begin cases nat.eq_zero_or_pos n with h₀ h₀, { rw [h₀, nat.div_zero, nat.div_zero, nat.zero_sub] }, { induction p with p, { rw [nat.mul_zero, nat.sub_zero, nat.sub_zero] }, { have h₂ : n*p ≤ x, { transitivity, { apply nat.mul_le_mul_left, apply le_succ }, { apply h₁ } }, have h₃ : x - n * p ≥ n, { apply nat.le_of_add_le_add_right, rw [nat.sub_add_cancel h₂, nat.add_comm], rw [mul_succ] at h₁, apply h₁ }, rw [sub_succ, ← p_ih h₂], rw [@div_eq_sub_div (x - n*p) _ h₀ h₃], simp [add_one, pred_succ, mul_succ, nat.sub_sub] } } end theorem div_mul_le_self : ∀ (m n : ℕ), m / n * n ≤ m | m 0 := by simp [m.zero_le, nat.zero_mul] | m (succ n) := (le_div_iff_mul_le _ _ (nat.succ_pos _)).1 (le_refl _) @[simp] theorem add_div_right (x : ℕ) {z : ℕ} (H : 0 < z) : (x + z) / z = succ (x / z) := by rw [div_eq_sub_div H (nat.le_add_left _ _), nat.add_sub_cancel] @[simp] theorem add_div_left (x : ℕ) {z : ℕ} (H : 0 < z) : (z + x) / z = succ (x / z) := by rw [nat.add_comm, add_div_right x H] @[simp] theorem mul_div_right (n : ℕ) {m : ℕ} (H : 0 < m) : m * n / m = n := by {induction n; simp [*, mul_succ, nat.mul_zero] } @[simp] theorem mul_div_left (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m := by rw [nat.mul_comm, mul_div_right _ H] protected theorem div_self {n : ℕ} (H : 0 < n) : n / n = 1 := let t := add_div_right 0 H in by rwa [nat.zero_add, nat.zero_div] at t theorem add_mul_div_left (x z : ℕ) {y : ℕ} (H : 0 < y) : (x + y * z) / y = x / y + z := begin induction z with z ih, { rw [nat.mul_zero, nat.add_zero, nat.add_zero] }, { rw [mul_succ, ← nat.add_assoc, add_div_right _ H, ih], refl } end theorem add_mul_div_right (x y : ℕ) {z : ℕ} (H : 0 < z) : (x + y * z) / z = x / z + y := by rw [nat.mul_comm, add_mul_div_left _ _ H] protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : 0 < n) : m * n / n = m := let t := add_mul_div_right 0 m H in by rwa [nat.zero_add, nat.zero_div, nat.zero_add] at t protected theorem mul_div_cancel_left (m : ℕ) {n : ℕ} (H : 0 < n) : n * m / n = m := by rw [nat.mul_comm, nat.mul_div_cancel _ H] protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : 0 < n) (H2 : m = k * n) : m / n = k := by rw [H2, nat.mul_div_cancel _ H1] protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : 0 < n) (H2 : m = n * k) : m / n = k := by rw [H2, nat.mul_div_cancel_left _ H1] protected theorem div_eq_of_lt_le {m n k : ℕ} (lo : k * n ≤ m) (hi : m < succ k * n) : m / n = k := have npos : 0 < n, from n.eq_zero_or_pos.resolve_left $ λ hn, by rw [hn, nat.mul_zero] at hi lo; exact absurd lo (not_le_of_gt hi), le_antisymm (le_of_lt_succ ((nat.div_lt_iff_lt_mul _ _ npos).2 hi)) ((nat.le_div_iff_mul_le _ _ npos).2 lo) theorem mul_sub_div (x n p : ℕ) (h₁ : x < n*p) : (n * p - succ x) / n = p - succ (x / n) := begin have npos : 0 < n := n.eq_zero_or_pos.resolve_left (λ n0, by rw [n0, nat.zero_mul] at h₁; exact nat.not_lt_zero _ h₁), apply nat.div_eq_of_lt_le, { rw [nat.mul_sub_right_distrib, nat.mul_comm], apply nat.sub_le_sub_left, exact (div_lt_iff_lt_mul _ _ npos).1 (lt_succ_self _) }, { change succ (pred (n * p - x)) ≤ (succ (pred (p - x / n))) * n, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁), succ_pred_eq_of_pos (nat.sub_pos_of_lt _)], { rw [nat.mul_sub_right_distrib, nat.mul_comm], apply nat.sub_le_sub_left, apply div_mul_le_self }, { apply (div_lt_iff_lt_mul _ _ npos).2, rwa nat.mul_comm } } end protected theorem div_div_eq_div_mul (m n k : ℕ) : m / n / k = m / (n * k) := begin cases k.eq_zero_or_pos with k0 kpos, {rw [k0, nat.mul_zero, nat.div_zero, nat.div_zero]}, cases n.eq_zero_or_pos with n0 npos, {rw [n0, nat.zero_mul, nat.div_zero, nat.zero_div]}, apply le_antisymm, { apply (le_div_iff_mul_le _ _ (nat.mul_pos npos kpos)).2, rw [nat.mul_comm n k, ← nat.mul_assoc], apply (le_div_iff_mul_le _ _ npos).1, apply (le_div_iff_mul_le _ _ kpos).1, refl }, { apply (le_div_iff_mul_le _ _ kpos).2, apply (le_div_iff_mul_le _ _ npos).2, rw [nat.mul_assoc, nat.mul_comm n k], apply (le_div_iff_mul_le _ _ (nat.mul_pos kpos npos)).1, refl } end protected theorem mul_div_mul {m : ℕ} (n k : ℕ) (H : 0 < m) : m * n / (m * k) = n / k := by rw [← nat.div_div_eq_div_mul, nat.mul_div_cancel_left _ H] lemma div_lt_self {n m : nat} : 0 < n → 1 < m → n / m < n := begin intros h₁ h₂, have m_pos : 0 < m, { apply lt_trans _ h₂, comp_val }, suffices : 1 * n < m * n, { rw [nat.one_mul, nat.mul_comm] at this, exact iff.mpr (nat.div_lt_iff_lt_mul n n m_pos) this }, exact nat.mul_lt_mul h₂ (le_refl _) h₁ end /-! dvd -/ protected theorem dvd_mul_right (a b : ℕ) : a ∣ a * b := ⟨b, rfl⟩ protected theorem dvd_trans {a b c : ℕ} (h₁ : a ∣ b) (h₂ : b ∣ c) : a ∣ c := match h₁, h₂ with | ⟨d, (h₃ : b = a * d)⟩, ⟨e, (h₄ : c = b * e)⟩ := ⟨d * e, show c = a * (d * e), by simp [h₃, h₄, nat.mul_assoc]⟩ end protected theorem eq_zero_of_zero_dvd {a : ℕ} (h : 0 ∣ a) : a = 0 := exists.elim h (assume c, assume H' : a = 0 * c, eq.trans H' (nat.zero_mul c)) protected theorem dvd_add {a b c : ℕ} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := exists.elim h₁ (λ d hd, exists.elim h₂ (λ e he, ⟨d + e, by simp [nat.left_distrib, hd, he]⟩)) protected theorem dvd_add_iff_right {k m n : ℕ} (h : k ∣ m) : k ∣ n ↔ k ∣ m + n := ⟨nat.dvd_add h, exists.elim h $ λd hd, match m, hd with | ._, rfl := λh₂, exists.elim h₂ $ λe he, ⟨e - d, by rw [nat.mul_sub_left_distrib, ← he, nat.add_sub_cancel_left]⟩ end⟩ protected theorem dvd_add_iff_left {k m n : ℕ} (h : k ∣ n) : k ∣ m ↔ k ∣ m + n := by rw nat.add_comm; exact nat.dvd_add_iff_right h theorem dvd_sub {k m n : ℕ} (H : n ≤ m) (h₁ : k ∣ m) (h₂ : k ∣ n) : k ∣ m - n := (nat.dvd_add_iff_left h₂).2 $ by rw nat.sub_add_cancel H; exact h₁ theorem dvd_mod_iff {k m n : ℕ} (h : k ∣ n) : k ∣ m % n ↔ k ∣ m := let t := @nat.dvd_add_iff_left _ (m % n) _ (nat.dvd_trans h (nat.dvd_mul_right n (m / n))) in by rwa mod_add_div at t theorem le_of_dvd {m n : ℕ} (h : 0 < n) : m ∣ n → m ≤ n := λ⟨k, e⟩, by { revert h, rw e, refine k.cases_on _ _, exact λhn, absurd hn (lt_irrefl _), exact λk _, let t := m.mul_le_mul_left (succ_pos k) in by rwa nat.mul_one at t } theorem dvd_antisymm : Π {m n : ℕ}, m ∣ n → n ∣ m → m = n | m 0 h₁ h₂ := nat.eq_zero_of_zero_dvd h₂ | 0 n h₁ h₂ := (nat.eq_zero_of_zero_dvd h₁).symm | (succ m) (succ n) h₁ h₂ := le_antisymm (le_of_dvd (succ_pos _) h₁) (le_of_dvd (succ_pos _) h₂) theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : 0 < n) : 0 < m := nat.pos_of_ne_zero $ λm0, by rw m0 at H1; rw nat.eq_zero_of_zero_dvd H1 at H2; exact lt_irrefl _ H2 theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := le_antisymm (le_of_dvd dec_trivial H) (pos_of_dvd_of_pos H dec_trivial) theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n := ⟨n / m, by { have t := (mod_add_div n m).symm, rwa [H, nat.zero_add] at t }⟩ theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 := exists.elim H (λ z H1, by rw [H1, mul_mod_right]) theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 := ⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩ instance decidable_dvd : @decidable_rel ℕ (∣) := λm n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m := let t := mod_add_div m n in by rwa [mod_eq_zero_of_dvd H, nat.zero_add] at t protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m := by rw [nat.mul_comm, nat.mul_div_cancel' H] protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) := or.elim k.eq_zero_or_pos (λh, by rw [h, nat.div_zero, nat.div_zero, nat.mul_zero]) (λh, have m * n / k = m * (n / k * k) / k, by rw nat.div_mul_cancel H, by rw[this, ← nat.mul_assoc, nat.mul_div_cancel _ h]) theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : 0 < k) (H : k * m ∣ k * n) : m ∣ n := exists.elim H (λl H1, by rw nat.mul_assoc at H1; exact ⟨_, nat.eq_of_mul_eq_mul_left kpos H1⟩) theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : 0 < k) (H : m * k ∣ n * k) : m ∣ n := by rw [nat.mul_comm m k, nat.mul_comm n k] at H; exact dvd_of_mul_dvd_mul_left kpos H /-! iterate -/ def iterate {α : Sort u} (op : α → α) : ℕ → α → α | 0 a := a | (succ k) a := iterate k (op a) notation f`^[`n`]` := iterate f n /-! find -/ section find parameter {p : ℕ → Prop} private def lbp (m n : ℕ) : Prop := m = n + 1 ∧ ∀ k ≤ n, ¬p k parameters [decidable_pred p] (H : ∃n, p n) private def wf_lbp : well_founded lbp := ⟨let ⟨n, pn⟩ := H in suffices ∀m k, n ≤ k + m → acc lbp k, from λa, this _ _ (nat.le_add_left _ _), λm, nat.rec_on m (λk kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := absurd pn (a _ kn) end⟩) (λm IH k kn, ⟨_, λy r, match y, r with ._, ⟨rfl, a⟩ := IH _ (by rw nat.add_right_comm; exact kn) end⟩)⟩ protected def find_x : {n // p n ∧ ∀m < n, ¬p m} := @well_founded.fix _ (λk, (∀n < k, ¬p n) → {n // p n ∧ ∀m < n, ¬p m}) lbp wf_lbp (λm IH al, if pm : p m then ⟨m, pm, al⟩ else have ∀ n ≤ m, ¬p n, from λn h, or.elim (decidable.lt_or_eq_of_le h) (al n) (λe, by rw e; exact pm), IH _ ⟨rfl, this⟩ (λn h, this n $ nat.le_of_succ_le_succ h)) 0 (λn h, absurd h (nat.not_lt_zero _)) /-- If `p` is a (decidable) predicate on `ℕ` and `hp : ∃ (n : ℕ), p n` is a proof that there exists some natural number satisfying `p`, then `nat.find hp` is the smallest natural number satisfying `p`. Note that `nat.find` is protected, meaning that you can't just write `find`, even if the `nat` namespace is open. The API for `nat.find` is: * `nat.find_spec` is the proof that `nat.find hp` satisfies `p`. * `nat.find_min` is the proof that if `m < nat.find hp` then `m` does not satisfy `p`. * `nat.find_min'` is the proof that if `m` does satisfy `p` then `nat.find hp ≤ m`. -/ protected def find : ℕ := nat.find_x.1 protected theorem find_spec : p nat.find := nat.find_x.2.left protected theorem find_min : ∀ {m : ℕ}, m < nat.find → ¬p m := nat.find_x.2.right protected theorem find_min' {m : ℕ} (h : p m) : nat.find ≤ m := le_of_not_lt (λ l, find_min l h) end find end nat
e02ca922817dd379178383da78d1d5e64884f0d3
d29d82a0af640c937e499f6be79fc552eae0aa13
/src/ring_theory/derivation.lean
67aabe1bbedd4a20f126e38747c1f077135ff3c0
[ "Apache-2.0" ]
permissive
AbdulMajeedkhurasani/mathlib
835f8a5c5cf3075b250b3737172043ab4fa1edf6
79bc7323b164aebd000524ebafd198eb0e17f956
refs/heads/master
1,688,003,895,660
1,627,788,521,000
1,627,788,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,026
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import algebra.lie.of_associative import ring_theory.algebra_tower /-! # Derivations This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an `R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`. ## Notation The notation `⁅D1, D2⁆` is used for the commutator of two derivations. TODO: this file is just a stub to go on with some PRs in the geometry section. It only implements the definition of derivations in commutative algebra. This will soon change: as soon as bimodules will be there in mathlib I will change this file to take into account the non-commutative case. Any development on the theory of derivations is discouraged until the definitive definition of derivation will be implemented. -/ open algebra ring_hom -- to match `linear_map` set_option old_structure_cmd true /-- `D : derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz` equality. TODO: update this when bimodules are defined. -/ @[protect_proj] structure derivation (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A] [algebra R A] (M : Type*) [add_cancel_comm_monoid M] [module A M] [module R M] [is_scalar_tower R A M] extends A →ₗ[R] M := (leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a) /-- The `linear_map` underlying a `derivation`. -/ add_decl_doc derivation.to_linear_map namespace derivation section variables {R : Type*} [comm_semiring R] variables {A : Type*} [comm_semiring A] [algebra R A] variables {M : Type*} [add_cancel_comm_monoid M] [module A M] [module R M] variables [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩ @[simp] lemma to_fun_eq_coe : D.to_fun = ⇑D := rfl instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) := ⟨λ D, D.to_linear_map⟩ @[simp] lemma to_linear_map_eq_coe : D.to_linear_map = D := rfl @[simp] lemma mk_coe (f : A →ₗ[R] M) (h₁ h₂ h₃) : ((⟨f, h₁, h₂, h₃⟩ : derivation R A M) : A → M) = f := rfl @[simp, norm_cast] lemma coe_fn_coe (f : derivation R A M) : ⇑(f : A →ₗ[R] M) = f := rfl lemma coe_injective : @function.injective (derivation R A M) (A → M) coe_fn := λ D1 D2 h, by { cases D1, cases D2, congr', } @[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 := coe_injective $ funext H lemma congr_fun (h : D1 = D2) (a : A) : D1 a = D2 a := congr_fun (congr_arg coe_fn h) a @[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b @[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D @[simp] lemma map_smul : D (r • a) = r • D a := linear_map.map_smul D r a @[simp] lemma leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _ @[simp] lemma map_one_eq_zero : D 1 = 0 := begin have h : D 1 = D (1 * 1) := by rw mul_one, rwa [leibniz D 1 1, one_smul, self_eq_add_right] at h end @[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 := by rw [←mul_one r, ring_hom.map_mul, map_one, ←smul_def, map_smul, map_one_eq_zero, smul_zero] /- Data typeclasses -/ instance : has_zero (derivation R A M) := ⟨{ leibniz' := λ a b, by simp only [add_zero, linear_map.zero_apply, linear_map.to_fun_eq_coe, smul_zero], ..(0 : A →ₗ[R] M) }⟩ @[simp] lemma coe_zero : ⇑(0 : derivation R A M) = 0 := rfl @[simp] lemma coe_zero_linear_map : ↑(0 : derivation R A M) = (0 : A →ₗ[R] M) := rfl lemma zero_apply (a : A) : (0 : derivation R A M) a = 0 := rfl instance : has_add (derivation R A M) := ⟨λ D1 D2, { leibniz' := λ a b, by simp only [leibniz, linear_map.add_apply, linear_map.to_fun_eq_coe, coe_fn_coe, smul_add, add_add_add_comm], ..(D1 + D2 : A →ₗ[R] M) }⟩ @[simp] lemma coe_add (D1 D2 : derivation R A M) : ⇑(D1 + D2) = D1 + D2 := rfl @[simp] lemma coe_add_linear_map (D1 D2 : derivation R A M) : ↑(D1 + D2) = (D1 + D2 : A →ₗ[R] M) := rfl lemma add_apply : (D1 + D2) a = D1 a + D2 a := rfl instance Rscalar : has_scalar R (derivation R A M) := ⟨λ r D, { leibniz' := λ a b, by simp only [linear_map.smul_apply, leibniz, linear_map.to_fun_eq_coe, smul_algebra_smul_comm, coe_fn_coe, smul_add, add_comm], ..(r • D : A →ₗ[R] M) }⟩ @[simp] lemma coe_Rsmul (r : R) (D : derivation R A M) : ⇑(r • D) = r • D := rfl @[simp] lemma coe_Rsmul_linear_map (r : R) (D : derivation R A M) : ↑(r • D) = (r • D : A →ₗ[R] M) := rfl lemma Rsmul_apply (r : R) (D : derivation R A M) : (r • D) a = r • D a := rfl instance has_scalar : has_scalar A (derivation R A M) := ⟨λ a D, { leibniz' := λ b c, by { dsimp, simp only [smul_add, leibniz, smul_comm a, add_comm] }, ..(a • D : A →ₗ[R] M) }⟩ @[simp] lemma coe_smul (a : A) (D : derivation R A M) : ⇑(a • D) = a • D := rfl @[simp] lemma coe_smul_linear_map (a : A) (D : derivation R A M) : ↑(a • D) = (a • D : A →ₗ[R] M) := rfl lemma smul_apply (a : A) (D : derivation R A M) (b : A) : (a • D) b = a • D b := rfl instance : inhabited (derivation R A M) := ⟨0⟩ instance : add_comm_monoid (derivation R A M) := coe_injective.add_comm_monoid _ coe_zero coe_add /-- `coe_fn` as an `add_monoid_hom`. -/ def coe_fn_add_monoid_hom : derivation R A M →+ (A → M) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } @[priority 100] instance derivation.Rmodule : module R (derivation R A M) := function.injective.module R coe_fn_add_monoid_hom coe_injective coe_Rsmul instance : module A (derivation R A M) := function.injective.module A coe_fn_add_monoid_hom coe_injective coe_smul instance : is_scalar_tower R A (derivation R A M) := ⟨λ x y z, ext (λ a, smul_assoc _ _ _)⟩ section push_forward variables {N : Type*} [add_cancel_comm_monoid N] [module A N] [module R N] [is_scalar_tower R A N] variables (f : M →ₗ[A] N) /-- We can push forward derivations using linear maps, i.e., the composition of a derivation with a linear map is a derivation. Furthermore, this operation is linear on the spaces of derivations. -/ def _root_.linear_map.comp_der : derivation R A M →ₗ[R] derivation R A N := { to_fun := λ D, { leibniz' := λ a b, by simp only [coe_fn_coe, function.comp_app, linear_map.coe_comp, linear_map.map_add, leibniz, linear_map.coe_coe_is_scalar_tower, linear_map.map_smul, linear_map.to_fun_eq_coe], .. (f : M →ₗ[R] N).comp (D : A →ₗ[R] M), }, map_add' := λ D₁ D₂, by { ext, exact linear_map.map_add _ _ _, }, map_smul' := λ r D, by { ext, exact linear_map.map_smul _ _ _, }, } @[simp] lemma coe_to_linear_map_comp : (f.comp_der D : A →ₗ[R] N) = (f : M →ₗ[R] N).comp (D : A →ₗ[R] M) := rfl @[simp] lemma coe_comp : (f.comp_der D : A → N) = (f : M →ₗ[R] N).comp (D : A →ₗ[R] M) := rfl end push_forward end section variables {R : Type*} [comm_ring R] variables {A : Type*} [comm_ring A] [algebra R A] section variables {M : Type*} [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M] variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A) @[simp] lemma map_neg : D (-a) = -D a := linear_map.map_neg D a @[simp] lemma map_sub : D (a - b) = D a - D b := linear_map.map_sub D a b instance : has_neg (derivation R A M) := ⟨λ D, { leibniz' := λ a b, by simp only [linear_map.neg_apply, smul_neg, neg_add_rev, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, add_comm], ..(-D : A →ₗ[R] M)}⟩ @[simp] lemma coe_neg (D : derivation R A M) : ⇑(-D) = -D := rfl @[simp] lemma coe_neg_linear_map (D : derivation R A M) : ↑(-D) = (-D : A →ₗ[R] M) := rfl lemma neg_apply : (-D) a = -D a := rfl instance : has_sub (derivation R A M) := ⟨λ D1 D2, { leibniz' := λ a b, by { simp only [linear_map.to_fun_eq_coe, linear_map.sub_apply, leibniz, coe_fn_coe, smul_sub], abel }, ..(D1 - D2 : A →ₗ[R] M)}⟩ @[simp] lemma coe_sub (D1 D2 : derivation R A M) : ⇑(D1 - D2) = D1 - D2 := rfl @[simp] lemma coe_sub_linear_map (D1 D2 : derivation R A M) : ↑(D1 - D2) = (D1 - D2 : A →ₗ[R] M) := rfl lemma sub_apply : (D1 - D2) a = D1 a - D2 a := rfl instance : add_comm_group (derivation R A M) := coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub end section lie_structures /-! # Lie structures -/ variables (D : derivation R A A) {D1 D2 : derivation R A A} (r : R) (a b : A) /-- The commutator of derivations is again a derivation. -/ instance : has_bracket (derivation R A A) (derivation R A A) := ⟨λ D1 D2, { leibniz' := λ a b, by { simp only [ring.lie_def, map_add, id.smul_eq_mul, linear_map.mul_apply, leibniz, linear_map.to_fun_eq_coe, coe_fn_coe, linear_map.sub_apply], ring, }, ..⁅(D1 : module.End R A), (D2 : module.End R A)⁆, }⟩ @[simp] lemma commutator_coe_linear_map : ↑⁅D1, D2⁆ = ⁅(D1 : module.End R A), (D2 : module.End R A)⁆ := rfl lemma commutator_apply : ⁅D1, D2⁆ a = D1 (D2 a) - D2 (D1 a) := rfl instance : lie_ring (derivation R A A) := { add_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, lie_add := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, }, lie_self := λ d, by { ext a, simp only [commutator_apply, add_apply, map_add], ring_nf, }, leibniz_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, sub_apply, map_sub], ring, } } instance : lie_algebra R (derivation R A A) := { lie_smul := λ r d e, by { ext a, simp only [commutator_apply, map_smul, smul_sub, Rsmul_apply]}, ..derivation.Rmodule } end lie_structures end end derivation
d1213893d0040d85e03e9d5e02c67c7831d5542d
9954952c821fe205cf4a343886fef5c7b6f070bf
/lean/intro.lean
1cba65b49c6a18bb3096b3253136f37de0960da4
[]
no_license
gaorongjia/cs-dm
cc81c43a56e4e3861de4779ae63d74378d64f03b
e50adcf6120d985c93075fa36d4f0211589779a3
refs/heads/master
1,584,030,132,304
1,524,251,414,000
1,524,251,414,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,431
lean
/- At this point, we've proposed and validated (using truth tables) a set of fundamental inference rules. Unfortunately, using truth tables doesn't scale well. We thus play an important game, now, where we simply accept the inference rules as valid transformation between sets of premises and conclusions. We view the Ps, Qs, Rs in the rules we validated as "standing for" arbitrary propositions, and we now apply the rules without having to go back and validate the results "semantically" (using truth tables). We thus transition from what we call "semantic entailment" to "syntactic entailment," which finally moves us into the realm of symbolic logic and proof. We now also shift tools, from Dafny, which allows us to write logic, but which largely hides the proofs and their construction, to Lean, which is what we call a proof assistant. Many propositions are too difficult for tools such as Dafny to prove automatically. If we still want the assurances of correctness (of software or even just of pure mathematics) provided by a strongly typed checker, then we have to use a tool in which we manipulate both propositions and proofs explicitly. We are now there. The purpose of this initial unit is to give you an introduction to the fundamental concepts of propositions and proofs when using a proof assistant tool, here the Lean Prover. The key point of this chapter is that different forms of propositions require the use of different proof strategies and have different forms of proofs. These are ideas that are fundmental to discrete mathematical whether or not you are using a proof assistant tool such as Lean. The benefits of using Lean include nearly absolute assurance that you haven't made mistakes: that proofs don't contain errors. This technology is now also at the forefront of important research not only in ultra high assurance software and systems, but even in pure mathematics. Wecome to the cutting edge! -/ /- **** PROPOSITIONS AS TYPES **** -/ /- Here's a typical definition, in this case, of a variable, x, bound to the value, 1, of type, nat. -/ def x: nat := 1 /- In Lean, you can check the type of a term by using the #check command. Hover your mouse over the #check in VSCode to see the result. -/ #check 1 #check x /- Lean tells you that the type of x is nat. It uses the standard mathematical script N (ℕ) for nat. You can use it too by typing "\nat" rather than just "nat" for the type. -/ def x': ℕ := 1 /- You can evaluate an expression in Lean using the #eval command. (There are other ways to do this, as well, which we'll see later.) You hover your mouse over the command to see the result. -/ #eval x /- In Lean, definitions start with the keyword, def, followed by the name of a variable, here x; a colon; then the declared type of the variable, here nat; then :=; and finally an expression of the right type, here simply the literal expression, 1, of type ℕ. Lean type-checks the assignment and gives and error if the term on the right doesn't have the same type declared or inferror for the variable on the left. -/ /- ****** TYPES ARE VALUES, TOO ****** -/ /- In Lean, every term has a type. A type is a term, too, so it, too, has a type. We've seen that the type of x is nat. What is the type of nat? -/ #check nat /- What is the type of Type? -/ #check Type /- What is the type of Type 1? -/ #check Type 1 /- You can guess where it goes from here! -/ /- ****** PROPOSITIONS ****** -/ /- Lean and similar constructive logic proof assistants unify and automate mathematical logic and computing. So propositions are now values, and so are proofs. As such, propositions must have types. Let's write a few simple propositions and check to see what their types are. -/ -- zero equals zero; this is a proposition #check 0=0 -- every natural numbers is non-negative #check ∀ n: nat, n >= 0 -- Get the forall symbol by typing "\forall" -- every natural number has a successor #check ∀ n: ℕ, ∃ m: ℕ, m = n + 1 -- Get the exists symbol by typing "\exists" /- In each case, we see that the type of a proposition is Prop. What's the type of Prop? -/ #check Prop /- Ok, the type of Prop is also Type. So what we have here is a type hierarchy in which the familiar types, such as nat, have the type, Type, but where there's also a type, called Prop, that is also of type, Type, and that, in turn, is the type of all propositions. So let's start again with x := 1. The value of x is 1. The type of the value, 1, is nat. The type of nat is Type. From there the type of each type is just the next bigger "Type n."" We've also seen that a proposition, such as 0=0, is of type, Prop, which in turn has the type, Type. But what about proofs? -/ /- ** PROOFS: PROPOSITIONS ARE TYPES! ** -/ /- So what about proofs? They crazy idea that Lean and similar systems are built on is that propositions can themselves be viewed as types, and proofs as values of these types! In this analogy, a proof is a value of a type, namely of the proposition that it proves, viewed as a type. So just as 1 is a value of type nat, and nat in turn is a value of type, Type, so a proof of 0=0 is a value of type 0=0! The proposition is the type, the proof, if there is one, is a value of such a type. The type of a proposition (itself a type) is Prop. And the type of Prop is Type. To see this clearly, we need to build some proof values. -/ /- Here (following this comment) is another definition, of the variable, zeqz. But whereas before we defined x to be of the type, nat, now we define zeqz to be of the type, 0=0. We're using a proposition as a type! To this variable we then assign a value, which we will understand to be a proof. Proof values are built by what we can view as inference rules. The inference rule, rfl, build a proof that anything is equal to itself -/ def zeqz: 0 = 0 := rfl /- The proof is produced the rfl inference rule. The rfl "proof constructor" (that is what an inference rule is, after all) is polymorphic, uses type inference, takes a single argument, a, and yields a proof of a = a. The value in this case is 0 and the type is nat. What the rule rule says more formally is that, without any premises you can conclude that for any type, A, and for any value, a, of that type, there is a proof of a = a. For example, if you need a proof of 0=0, you use this rule to build it. The rule infers the type to be nat and the value, a, to be 0. The result is a proof of the proposition 0 = 0. The value of zeqz is thus a *proof*, a proof of its type, i.e., of the logical proposition, 0 = 0. Checke the type of zeqz. Its type is the proposition that it is a proof of! -/ #check zeqz /- It helps to draw a picture. Draw a picture that includes "nodes" for all of the values we've used or defined so far, with arrows depicting the "hasType" relation. There are nodes for 1, x, zeqz, nat, Prop, Type, Type 1, Type 2, etc. -/ /- When we're building values that are proofs of propositions, we generally use the keyword, "theorem", instead of "def". They mean exactly the same thing to Lean, but they communicate different intentions to human readers. We add a tick mark to the name of the theorem here only to avoid giving multiple definitions of the same name, which is an error in Lean. -/ theorem zeqz': 0 = 0 := rfl /- We could have defined x := 1 as a theorem. -/ theorem x'': nat := 1 /- While this means exactly the same thing as our original definition of x, it gives us an entirely new view: a value is a proof of its type. 1 is thus a proof of the type nat. Our ability to provide any value for a type gives us a proof of that type. The type checker in Lean of course ensures that we never assign a value to a variable that is not of its declared or inferred type. -/ /- ********** TRUTH ********** -/ /- What does it mean for a proposition to be true in Lean? It means exactly that there is some value of that type. A proposition that is false is a good proposition, and a good type, but it is a type that has no values! It's an "empty" type. The type, 1=0, has no values (no proofs). To prove a proposition (a type) in Lean means that one has produced/exhibited a value of that type: a value that the type checker confirms is of that type. -/ /- ********** NEXT STEPS ************ -/ /- With this background in hand, we can now use what we've learned to start to investigate the world of mathematical logic and proof at a very high level of sophistication and automation! In particular, we now start to explore different *forms of propositions* and corresponding *proof strategies*. The rest of this unit focuses on propositions that claim that two terms are equal, and the proof strategy we see is called "proof by simplification and by the reflexive property of equality". -/ /- ******** PROOFS OF EQUALITY ******* -/ /- An expression, v1=v2, is a proposition that asserts the equality of the terms v1 and v2. The terms are considered equal if and only if one can produce a proof of v1=v2. There is an inference rule defined in Lean that can produce such a proof whenever v1 and v2 are exactly the same terms, such as in 0=0. This rule can also produce a proof whenever v1 and v2 reduce (evaluate) to identical terms. So we can also produce a proof of 0+0=0, for example, because 0+0 reduces to 0, and then you have identical terms on each side of the =. This notion of equality is called "definitional equality"). As you'd expect, it's a binary, reflexive, symmetric, and transitive relation on terms. It is also polymorphic, and so can be used for any two terms of the same type, A, no matter what A is. The Lean inference rule that produces proofs of definitional equality is just rfl. Here (following) are several terms that are definitionally equal even though they're not identical. rfl is happy to build proofs for them. The second example illustrates that terms that look pretty different can still be definitionally equal. On the left we have a nat/string pair. The .1 after the pair is the operator that extracts the first element of the pair, here term 1-1. This term then reduces to 0. The terms on either side of the = reduce to the same term, 0, which allows rfl to complete its work and return a value that is accepted as being of the right type, i.e., as a proof of equality. -/ theorem t0 : 1 - 1 = 5 - 5 := rfl theorem t1 : (1-1, "fidgblof").1 = 0 := rfl /- What you are seeing here is a strategy of proving propositions that assert equalities in two steps: first simplify (evaluate) the expressions on either side of the =, and then certify a proof of equality if and only if the resulting terms are identical. Whether you are using a proof assistant tool such as Lean or just doing paper-and-pencil mathematics, this is a fundamental strategy for proving propositions of a certain kind, namely propositions that assert equalities. -/ /- ***** PROOFS OF CONJUNCTIONS ****** -/ /- Key Point: Propositions of different kinds require the use of different proof strategies. Learning to recognize what kind of proposition you're looking at, and then to pick the right proof strategy, is critical. To illustate this point, we now look at how to produce proofs of conjunctions: propositions of the form, P ∧ Q. The key idea is simple: a proof of P ∧ Q can be constructed if and only if you have (or can produce) both a proof of P and a proof of Q. In that case, you can use the and introduction rule to build the desired proof. Remember the rule: [P, Q] ⊢ P ∧ Q. Now we can write this rule to distinguish propositions, such a P and Q, from proofs. [pfP: P, pfQ: Q] ⊢ (pfP, pfQ): P ∧ Q. In other words, if I have a proof, pfP, of P (a value, pfP, type, P!), and a proof, pfQ, of Q, then I can build a proof, (pfP, pfQ), of P ∧ Q; and the proof of the conjuction is just the ordered pair of the individual proof values! The and introduction rule can be understood as a function that takes two proof values and returns them as an ordered pair, which in Lean proves the conjunction of the corresponding propositions. Whether using a proof assistant or just doing paper and pencil math, the strategy for proving a conjunction of propositions is to split the conjunction into its two component propositions, obtain proofs of them individually, and then combine/take the two proofs as a proof of the overall conjunction. The benefit of using a proof assistant is that aspects are automated, and you're not allowed to make mistakes. -/ /- So that we can play around with this idea, given that we already have a proof of 0=0 (zeqz), we now contruct a proof of 1=1 so that we have two propositions and proofs to play with. -/ theorem oeqo : 1 = 1 := rfl /- To start, we conjecture that 0=0 /\ 1=1. We already have a proof of 0=0, namely zeqz. And we already have a proof of 1=1, namely oeqo. So we should be able to produce a proof of 0=0 /\ 1=1 by using the "and introduction" inference rule. Remember that it says that if a proposition, P, is true (and now by that we mean that we have a proof of it), and if Q is true, then we can deduce (construct a proof!) that P ∧ Q is true. Here's how you do that in Lean. (Note: we get the logical and symbol, ∧, by typing "\and", i.e., backslash-and, followed by a space.) -/ theorem t2: 0=0 ∧ 1=1 := -- proposition and.intro zeqz oeqo -- build proof /- NOTE!!! Whereas we typically define functions to take a single tuples of argument values, and thus write the arguments to functions as tuples (in parenthesis), e.g., inc(0), we write the arguments to proof constructors (inference rules) without parenthesis and without commas between values. So here for example, and below, we write "and.intro zeqz oeqo" rather than and.intro(zeqz, oeqo). Be careful when you get to the exercises to remember this point. -/ /- The preceding code should make it pretty clear that and.intro is, for all intents and purposes, a function that takes proofs of 0=0 and 1=1, respectively, and constructs a proof of 0=0 /\ 1=1. As we've already discussed, such a proof is in essence the ordered pair of the given proof values. As such, we should be able to extract the individual proofs from such a pair, and that is what the and elimination rules do! There are two, one to obtain each element. Thus from a proof of P ∧ Q we can apply the and elimination rules to obtain a proof of P and a proof of Q. Natural deduction, which is the proof system that we're using here, is a set of functions (inference rules) for taking apart (elimination) and putting together (introduction) proofs of propositions to produce proofs of other propositions. This natural deduction proof systems was invented long before autoamted tools, and is one of the fundamental systems for precise logical reasoning. The Lean Prover and similar "proof assistants" automate and use strong, static type checking to make sure that you can never produce an incorrect proof, because you're never allowed to pass arguments of the wrong types to the inference rules, and at the end of the day, you don't have a proof of a complex proposition unless the type checkers accepts it as a value of the type (proposition) it is inteded to prove. Take-away: You're learning the natural deduction style of producing proofs of mathematical conjectures; but unlike the students doing this with paper and pencil and no tool to help, you have the benefit of automation and a highly trustworthy correctness checker. The cost is that now you can't be slooppy. Inded, you have to be very precise about every step. Experienced mathematicians like to skip many steps in writing proofs, when they (think they) know that the details will all work out. The upside is that it's easier to "write the code." The downside is that errors can easily go undetected. Many errors in proofs of important theorems have only been found years after the proofs were reviewed by mathematicians and accepted as true in the community. When lives depend on the correctness of proofs, it can be worth the trouble to make sure they're right. -/ /- ***** PROOFS OF DISJUNCTIONS ***** -/ /- To prove a conjunction, we saw that we need to construct a pair of proofs, one for each conject. To prove a disjunction, P ∨ Q, we just need a proof of P or a proof of Q. We thus have two inference rules to prove P ∨ Q, one takeing a proof of P and returning a proof of P ∨ Q, and one taking a proof of Q and returning a proof of P ∨ Q. We thus have two or introduction rules in the natural deduction proof system, one taking a proof of the left disjunct (P), and one taking a proof of the right (Q). For example, we can prove the proposition, 0=0 ∨ 1=0 using an "or introduction" rule. In general, you have to decide which rule will work. In this case, we won't be able to build a proof of 1=0 (it's not true!), but we can build a proof of 0=0, so we'll do that and then use the left introduction rule to generate a proof of the overall proposition. The or introduction rules in Lean are called or.inl (left) and or.inr (right). Here then we construct a proof just as described above, but now checked by the tool. -/ theorem t3: 0=0 ∨ 1=0 := or.inl zeqz theorem t4: 1=0 ∨ 1=1 := or.inr oeqo /- Once again, we emphasize that whether or not you're using Lean or any other tool or no tool at all, the strategy for proving a disjunction is to prove at least one of its disjucts, and then to take that as enough to prove the overall disjunction. You see that each form of proposition has its own corresponding proof strategy (or at least one; there might be several that work). In the cases we've seen so far, you look at the constructor that was used to build the proposition and from that you select the appropriate inference rule / strategy to use to build the final proof. You then either have, or construct, the proofs that you need to apply that rule to construct the required proof. As a computational object, a proof of a disjunction is like a discriminated union in C or C++: an object containing one of two values along with a label that tells you what kind of value it contains. In this case, the label is given by the introduction rule used to construct the proof object: either or.inl or or.inr. -/ /-******** FUNCTIONS **********-/ /- Next we turn to proofs of propositions in the form of implications, such as P → Q. Up until now, we've read this implication as a proposition that claims that "if P is true then Q must be true." But now we've understood "truth" to mean that there is a proof. So we would view the proposition, P → Q, to be true if there's a proof of P → Q. And we have also seen that we can view propositions as types, and proofs as values. So what we need to conclude that P → Q is true is a proof, i.e., a value of type P → Q. What does such a value look like? Well, what does the type P → Q look like?! We have seen such types before. It looks like a function type: for a function that when given any value of type, P, returns a value of type, Q. And indeed, that's just what we want! We will view P → Q, the proposition, to be true, if and only if we can produce a *function* that, when given any proof of P, gives us back a proof of Q. If there is such a function, it means that if P is true (if you can produce a proof value for P) then Q is true (you can obtain a proof for Q) just by calling the given function. To make this idea clear, it will help to spend a little more time talking about functions and function types. In particular, we'll introduce here a new notation for saying something that you already know how to say well: a way to represent function bodies without having to give them names. These are given the somewhat arcane name, lambda expressions, also written as λ expressions. So let's get started. -/ /- We can define functions in Lean almost as in Dafny. Here are two functions to play with: increment and square. Go back and look at the function.dfy file to see just how similar the syntax is. -/ def inc(n: nat): nat := n + 1 def sqr(n: nat): nat := n * n def comp(n: nat): nat := sqr (inc n) /- Now's a good time to make a point that should make sense: functions are values of function types. Our familiar notation doesn't make function types explicit, but it shouldn't be a stretch for you to accept that the type of inc is nat → nat. Lean provides nice mathematical notation so if you type "\nat" you'll get ℕ. So, that type of inc is best written, ℕ → ℕ. We could thus have declared inc to be a value of type ℕ → ℕ, to which we would then assign a function value. That is a new concept: we need to write formally what we'd say informally as "the function that takes a nat, n, as an argument and that returns the nat, n + 1 as a result." The way we write that in Lean (and in what we call the lambda calculus more generally) is "λ n, n + 1". The greek letter, lambda (λ), says "the following variable is an argument to a function". Then comes a comma followed by the body of the function, usually using the name of the argument. Here then is the way we'd rewrite inc using this new notation. -/ def inc': ℕ → ℕ := λ n: nat, n + 1 /- As you might suspect, from the function value, Lean can infer its type, so you don't have to write it explicitly. But you do have to write the type of n here, as Lean can't figure out if you mean nat or int or some other type that supports a * operator. -/ def sqr' := λ n: nat, n * n /- Given a function defined in this way, you can apply it just as you would apply any other function. -/ def sq3 := sqr' 3 /- Don't believe that sq3 is therefore of type nat? You can check the type of any term in Lean using its #check command. Just hover your mouse over the #check. -/ #check sq3 /- Do you want to evaluate the expression (aka, term) sq3 to see that it evaluates to 9? Hover your mouse over the #eval. -/ #eval sq3 /- To give a proof (value) for a proposition in the form of an implication, we'll need to provide a function value, as discussed. While we could write a named function using def and then give that name as a proof, it is often easier to give a lambda expression directly, as we'll see shortly. -/ /- We can also define recursive functions, such as factorial and fibonacci using Lean's version of Dafny's "match/case" construct (aka, "pattern matching"). Here's how you write it. The first line declares the function name and type. The following lines, each starting with a bar character, define the cases. The first rule matches the case where the argument to fac is 0, and in that case the result is 1. The second case, which is written here a little differently than before, matches any value that is one more than some smaller argument, n, and returns that "one more than n" times the factorial of the samller number, n. Writing it this way allows Lean to prove to itself that the recursion terminates. -/ def fac: ℕ → ℕ | 0 := 1 | (n + 1) := (n + 1) * fac n /- We can now write some test cases for our function ... as little theorems! And we can check that they work by ... proving them! Here once again our proof is by the reflexive property of equality, and lean is automatically reducing (simplifying) the terms (fac 5) and 120 before checking that the results are the same. fac 5 does in fact reduce to 120, so the terms, fac 5, and 120, are definitionally equal, and in this case, rfl constructs a proof of the equality. -/ theorem fac5is120 : fac 5 = 120 := rfl /- ******* PROOFS OF IMPLICATIONS ******* -/ /- So far we've see how to build proofs of equality propositions (using simplification and reflexivity, i.e., rfl), of conjunctions (using and.intro), and of disjuctions (using one of the or introduction rules). What about implications? Suppose we wanted to show, for example, that (1=1 ∧ 0=0() → (0=0 ∧ 1=1). Here the order of the conjuncts is reversed. How to think about this? First, remember that an implication, such as P → Q, doesn't claim that the conclusion, P, is necessarily true. Rather, it only claims that *if the premise is true, then the conclusion is true. Now, by "true", we mean that we have or can construct a proof. An implication is thus read as saying if you assume that the premise, P, is true, in other words if you assume you have a proof of P, then you can then derive a proof of the conclusion, Q. But proofs are just values of (these strange propositional) types, and so a proposition in the form of an implication, such as P → Q is true exactly when we have a way to convert any value (proof) of type P into a value (proof) of type Q. We call such things, that change values into other values, functions! Think about this: the implication, P → Q is true if we can define a function of type, yep, you guessed it, P → Q. Whoa! So now, think about how to write a function that takes an argument of type 1=1 ∧ 0=0 and that returns a result of type 0=0 ∧ 1=1. To make it even clearer, understand that a proof of a conjunction is a pair of proofs, the and elimination rules just give you the values in such pairs, and the and introduction rule just forms such an ordered pair given arguments of the right types. The strategy for writing the function we need is thus: start with (proof of 1=1, proof of 0=0) as a pair proving 1=1 ∧ 0=0; extract each of the component proofs, then construct and return a pair constituting a proof of the conjunction with the component proofs in the opposite order. -/ theorem and_swap: 1=1 ∧ 0=0 → 0=0 ∧ 1=1 := λ premise: 1=1 ∧ 0=0, and.intro (and.elim_right premise) (and.elim_left premise) /- If using lambda is still confusing at this point, just write it as an ordinary function, and then give the function name as the proof. -/ def and_swap_fun(premise: 1=1 ∧ 0=0): 0=0 ∧ 1=1 := and.intro (and.elim_right premise) (and.elim_left premise) theorem and_swap': 1=1 ∧ 0=0 → 0=0 ∧ 1=1 := and_swap_fun -- give named function as proof /- ******* CONCLUSION ******* -/ /- This unit has given an introduction to deductive logic using natural deduction based on introduction and elimination rules that we first saw in the unit on propositional logic. We saw that these rules are semantically valid (based on truth tables), and now we take them as valid ways of deducing the truth of propositions (conclusions) in given contexts, in which we have proofs of sequences of propositions (contexts, assumptions, premises). As mathematicians and computer scientists, we're often the goal of proving some putative (unproven) theorem (aka conjecture). A key question in such a case is what proof strategy to use to produce a proof. The rules of natural deduction can help. First, look at the form of the proposition. Then ask what inference rule could be used to deduce it. Then apply the strategy associated with that rule. If you want to prove an equality, simplify and then apply the axiom that says that identical terms can be considered equal without any other proofs at all. If you want to prove a conjunction, obtain proofs of the conjuncts, then deduce by "and introduction" the desired result. If you want to prove an implication, P → Q, explain how the assumption that you're given a proof of P enables you to construct a proof of Q (or if you're using a tool like Lean, do this in a precise way by writing a function). Proof strategies emerge from the choices of inference rules needed to produce a final result. If you already have proofs of all premises for a rule, just apply the rule. But in many cases, you don't. The twist is to read inference rules not from top to bottom: if I know these things then I can conclude that. Instead, read them backwards: from bottom to top: if I want to prove this, then it will suffice to prove these other things, the premises, because if I have proofs of those things, then I can apply this inference rule to get the final proof that I want. In this way, the problem of proving a complex conjecture is decomposed into simpler problems, to prove each of the premises. You then apply this idea recursively to each premise, selecting a proof strategy appropriate for its form, and working backwards in this way until you get to propositions for which proofs are available with no futher recursion. An example is 0=0. We can get a proof of this using rfl without any futher "backward chaining." Once you've worked all the way back to propositions for which you have "base case" proofs, you then apply the inference rules going forward, to build the desired proof from all of the elementary and intermediates proofs, until, voila, you have what you need. As an example, consider 1=1 ∧ 0=0. It's a conjunction. A conjunction can be proved using and.intro. It, however, requires proofs of the conjuncts. So now we need proofs of 1=1 and of 0=0. Considering each of these "sub-goals" recursively, we can obtains proofs without futher recursion, using rfl. Given those proofs we can combine them going forward using and.intro. And that's how it works. Proving theorems in this way is thus in effect an exercise in what amounts to "top-down structured programming," but what we're building isn't a program that we intend to *run* but a proof that, if it type checks, witnesses the truth of a proposition. -/ theorem t5: 1=1 ∧ 0=0 := and.intro rfl rfl /- ****** GENERALIZING PROPOSITIONS ******* -/ /- In Lean we can declare variables to be of given types without actually defining values for them. You can think of these as "assumptions." So for example, you can say, "assume that P, Q, and R are arbitrary propositions (of type Prop)". -/ variables P Q R: Prop /- If we wanted to, we could also assume that we have proofs of one or more of these propositions by declaring variables to be of these types. Here's one example (which we won't use futher in this code). -/ variable proof_of_P: P /- Now we can write somewhat more interesting propositions, and prove them. Here's an example in which we prove that if P ∧ Q is true then we P is true. The proof is by the provisioning of a function that given a proof of P ∧ Q returns a proof of P by applying and.elim_left to its argument. -/ theorem t6: P ∧ Q → P := λ PandQ: P ∧ Q, and.elim_left PandQ /- Similarly we can prove that P ∧ Q → Q ∧ P -/ theorem t7: P ∧ Q → Q ∧ P := λ PandQ: P ∧ Q, and.intro (and.elim_right PandQ) (and.elim_left PandQ) /- EXERCISES -/ /- (1) Write an implementation of comp (call it comp'), using a lambda expression rather than the usual function definition notation. This problem gives practice writing function bodies as lambda expressions. -/ /- (2) Write three test cases for comp' and generate proofs using the strategy of "simplication and the reflexive property of equality." -/ /- (3) Implement the Fibonacci function, fib, using the usual recursive definition. Test it for n = 0, n = 1, and n = 10, by writing and proving theorems about what it computes (or should compute) in these cases. Hint: Write your cases in the definition of the function for 0, 1, and n+2 (covering the cases from 2 up). Here you get practice writing recursive functions in Lean. The syntax is similar to that of the Haskell language. -/ /- (4) Uncomment then complete this proof of the proposition, "Hello World" = "Hello" + " World" (which we write using the string.append function). Put your anwer in place of the <answer> string. This example introduces Lean's string type, which you might want to use at some point. It also gives you an example showing that rfl works for diverse types. It's polymorphic, as we said. -/ --theorem hw : "Hello World" = string.append "Hello" " World" := <answer> /- (5) Prove P ∧ Q ∧ R → R . Hint: ∧ is right-associative. In other words, P ∧ Q ∧ R means P ∧ (Q ∧ R). A proof of this proposition will thus have a pair inside a pair. -/ /- (6) Prove P → Q → (P ∧ Q). You can read this as saying that if you have a proof of P, then if you (also) have a proof of Q ,then you can produce a proof of P and Q. Hint: → is right associative, so P → Q → (P ∧ Q) means P → (Q → (P ∧ Q)). A proof will be a function that takes a proof of P and returns ... you guessed it, a function that takes a proof of Q and that returns a proof of P ∧ Q. The body of the outer lambda will thus use a lambda. -/ /- EXTRA KUDOS! Prove (P ∨ Q) → (P → R) → (Q → R) -> R. This looks scary, but think about it in the context of material you've already learned about. It say that if you have a proof of (P ∨ Q), then if you also have a proof of (P → R), then if you also have a proof of (Q → R), then you can derivea proof of R. The "or elimination" rule looked like this. You'll want to use that rule as part of your answer. However, the form of the proposition to be proved here is an implication, so a proof will have to be in the form of be a function. It will take the disjunction as an argument. Then just apply the or elimination rule in Lean, which is written as or.elim. -/ /- For fun and insight, check the type of orelim, the proposition we just proved. Notice how P, Q, and R are generalized to be *any* propositions at all. -/
8a5e77619f98fb9543df79a1ef257f0b03d1d070
4fa118f6209450d4e8d058790e2967337811b2b5
/src/sheaves/presheaf_of_topological_rings.lean
d441ddb31c3256caf801e7678c7945d06ee7cc92
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
2,075
lean
/- Presheaf of toplogical rings. -/ import topology.algebra.ring import sheaves.presheaf_of_rings universes u v open topological_space -- Definition of a presheaf of topological rings. structure presheaf_of_topological_rings (α : Type u) [topological_space α] extends presheaf_of_rings α := (Ftop : ∀ (U), topological_space (F U)) (Ftop_ring : ∀ (U), topological_ring (F U)) (res_continuous : ∀ (U V) (HVU : V ⊆ U), continuous (res U V HVU)) instance presheaf_of_topological_rings.has_coe {α : Type u} [topological_space α] : has_coe (presheaf_of_topological_rings α) (presheaf α) := ⟨λ F, F.to_presheaf⟩ instance presheaf_of_topological_rings.topological_space_sections {α : Type u} [topological_space α] (F : presheaf_of_topological_rings α) (U : opens α) : topological_space (F U) := F.Ftop U attribute [instance] presheaf_of_topological_rings.Ftop attribute [instance] presheaf_of_topological_rings.Ftop_ring instance presheaf_of_topological_rings.comm_ring {X : Type u} [topological_space X] (F : presheaf_of_topological_rings X) (U : opens X) : comm_ring (F U) := F.Fring U namespace presheaf_of_topological_rings variables {α : Type u} {β : Type v} [topological_space α] [topological_space β] -- Morphism of presheaf of topological rings. structure morphism (F G : presheaf_of_topological_rings α) extends presheaf.morphism F.to_presheaf G.to_presheaf := (ring_homs : ∀ (U), is_ring_hom (map U)) (continuous_homs : ∀ (U), continuous (map U)) local infix `⟶`:80 := morphism def identity (F : presheaf_of_topological_rings α) : F ⟶ F := { ring_homs := λ U, is_ring_hom.id, continuous_homs := λ U, continuous_id, ..presheaf.id F.to_presheaf } -- Isomorphic presheaves of rings. local infix `⊚`:80 := presheaf.comp structure iso (F G : presheaf_of_topological_rings α) := (mor : F ⟶ G) (inv : G ⟶ F) (mor_inv_id : mor.to_morphism ⊚ inv.to_morphism = presheaf.id F.to_presheaf) (inv_mor_id : inv.to_morphism ⊚ mor.to_morphism = presheaf.id G.to_presheaf) end presheaf_of_topological_rings
22e216e8255f58c448e761e5b91fcf1d13805fa4
4727251e0cd73359b15b664c3170e5d754078599
/src/computability/turing_machine.lean
05d26c6f167eff3f48162b256b9ae322da624abc
[ "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
109,678
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import data.pfun import logic.function.iterate import order.basic import tactic.apply_fun /-! # Turing machines This file defines a sequence of simple machine languages, starting with Turing machines and working up to more complex languages based on Wang B-machines. ## Naming conventions Each model of computation in this file shares a naming convention for the elements of a model of computation. These are the parameters for the language: * `Γ` is the alphabet on the tape. * `Λ` is the set of labels, or internal machine states. * `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and later models achieve this by mixing it into `Λ`. * `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks. All of these variables denote "essentially finite" types, but for technical reasons it is convenient to allow them to be infinite anyway. When using an infinite type, we will be interested to prove that only finitely many values of the type are ever interacted with. Given these parameters, there are a few common structures for the model that arise: * `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is finite, and for later models it is an infinite inductive type representing "possible program texts". * `cfg` is the set of instantaneous configurations, that is, the state of the machine together with its environment. * `machine` is the set of all machines in the model. Usually this is approximately a function `Λ → stmt`, although different models have different ways of halting and other actions. * `step : cfg → option cfg` is the function that describes how the state evolves over one step. If `step c = none`, then `c` is a terminal state, and the result of the computation is read off from `c`. Because of the type of `step`, these models are all deterministic by construction. * `init : input → cfg` sets up the initial state. The type `input` depends on the model; in most cases it is `list Γ`. * `eval : machine → input → part output`, given a machine `M` and input `i`, starts from `init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to the final state to obtain the result. The type `output` depends on the model. * `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when convenient, and prove that only finitely many of these states are actually accessible. This formalizes "essentially finite" mentioned above. -/ open relation open nat (iterate) open function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply' iterate_zero_apply) namespace turing /-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding blanks (`default : Γ`) to the end of `l₁`. -/ def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := ∃ n, l₂ = l₁ ++ list.repeat default n @[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l := ⟨0, by simp⟩ @[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ := by { rintro ⟨i, rfl⟩ ⟨j, rfl⟩, exact ⟨i+j, by simp [list.repeat_add]⟩ } theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l l₁ → blank_extends l l₂ → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i, simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h, simp only [← list.repeat_add, add_tsub_cancel_of_le h, list.append_assoc], end /-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the longer of `l₁` and `l₂`). -/ def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} (h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) : {l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} := if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩ theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l₁ l → blank_extends l₂ l → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j, refine list.append_right_cancel (e.symm.trans _), rw [list.append_assoc, ← list.repeat_add, tsub_add_cancel_of_le], apply_fun list.length at e, simp only [list.length_append, list.length_repeat] at e, rwa [← add_le_add_iff_left, e, add_le_add_iff_right] end /-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/ def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := blank_extends l₁ l₂ ∨ blank_extends l₂ l₁ @[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l := or.inl (blank_extends.refl _) @[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm @[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ := begin rintro (h₁|h₁) (h₂|h₂), { exact or.inl (h₁.trans h₂) }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.above_of_le h₂ h) }, { exact or.inr (h₂.above_of_le h₁ h) } }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.below_of_le h₂ h) }, { exact or.inr (h₂.below_of_le h₁ h) } }, { exact or.inr (h₂.trans h₁) }, end /-- Given two `blank_rel` lists, there exists (constructively) a common join. -/ def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l₁ l ∧ blank_extends l₂ l} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end /-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/ def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l l₁ ∧ blank_extends l l₂} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩ else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) := ⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩ /-- Construct a setoid instance for `blank_rel`. -/ def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩ /-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to represent half-tapes of a Turing machine, so that we can pretend that the list continues infinitely with blanks. -/ def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ) instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩ instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩ /-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger precondition `blank_extends` instead of `blank_rel`. -/ @[elab_as_eliminator, reducible] protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α) (H : ∀ a b, blank_extends a b → f a = f b) : α := l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm] /-- The quotient map turning a `list` into a `list_blank`. -/ def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk' @[elab_as_eliminator] protected lemma list_blank.induction_on {Γ} [inhabited Γ] {p : list_blank Γ → Prop} (q : list_blank Γ) (h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h /-- The head of a `list_blank` is well defined. -/ def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ := l.lift_on list.head begin rintro _ _ ⟨i, rfl⟩, cases a, {cases i; refl}, refl end @[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.head (list_blank.mk l) = l.head := rfl /-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/ def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk l.tail) begin rintro _ _ ⟨i, rfl⟩, refine quotient.sound' (or.inl _), cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩] end @[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl /-- We can cons an element onto a `list_blank`. -/ def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk (list.cons a l)) begin rintro _ _ ⟨i, rfl⟩, exact quotient.sound' (or.inl ⟨i, rfl⟩), end @[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl @[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).head = a := quotient.ind' $ by exact λ l, rfl @[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).tail = l := quotient.ind' $ by exact λ l, rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ @[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] : ∀ (l : list_blank Γ), l.tail.cons l.head = l := quotient.ind' begin refine (λ l, quotient.sound' (or.inr _)), cases l, {exact ⟨1, rfl⟩}, {refl}, end /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) : ∃ a l', l = list_blank.cons a l' := ⟨_, _, (list_blank.cons_head_tail _).symm⟩ /-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/ def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ := l.lift_on (λ l, list.inth l n) begin rintro l _ ⟨i, rfl⟩, simp only [list.inth], cases lt_or_le _ _ with h h, {rw list.nth_append h}, rw list.nth_len_le h, cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂}, rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat] end @[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) : (list_blank.mk l).nth n = l.inth n := rfl @[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : l.nth (n + 1) = l.tail.nth n := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} : (∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H, begin wlog h : l₁.length ≤ l₂.length using l₁ l₂, swap, { exact (this $ λ i, (H i).symm).symm }, refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩), refine list.ext_le _ (λ i h h₂, eq.symm _), { simp only [add_tsub_cancel_of_le h, list.length_append, list.length_repeat] }, simp at H, cases lt_or_le i l₁.length with h' h', { simpa only [list.nth_le_append _ h', list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i }, { simpa only [list.nth_le_append_right h', list.nth_le_repeat, list.nth_le_nth h, list.nth_len_le h', option.iget] using H i }, end /-- Apply a function to a value stored at the nth position of the list. -/ @[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ | 0 L := L.tail.cons (f L.head) | (n+1) L := (L.tail.modify_nth n).cons L.head theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) : (L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i := begin induction n with n IH generalizing i L, { cases i; simp only [list_blank.nth_zero, if_true, list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true, list_blank.nth_succ, if_false, list_blank.tail_cons] }, { cases i, { rw if_neg (nat.succ_ne_zero _).symm, simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] }, { simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons] } } end /-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/ structure {u v} pointed_map (Γ : Type u) (Γ' : Type v) [inhabited Γ] [inhabited Γ'] : Type (max u v) := (f : Γ → Γ') (map_pt' : f default = default) instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') := ⟨⟨λ _, default, rfl⟩⟩ instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') (λ _, Γ → Γ') := ⟨pointed_map.f⟩ @[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl @[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : f default = default := pointed_map.map_pt' _ @[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head := by cases l; [exact (pointed_map.map_pt f).symm, refl] /-- The `map` function on lists is well defined on `list_blank`s provided that the map is pointed. -/ def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.map f l)) begin rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩), simp only [pointed_map.map_pt, list.map_append, list.map_repeat], end @[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl @[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := begin refine (list_blank.cons_head_tail _).symm.trans _, simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons] end @[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := l.induction_on begin intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth], cases l.nth n, {exact f.2.symm}, {refl} end /-- The `i`-th projection as a pointed map. -/ def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) : pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩ theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) (L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by rw list_blank.nth_map; refl theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ'] (F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) : (L.modify_nth f n).map F = (L.map F).modify_nth f' n := by induction n with n IH generalizing L; simp only [*, list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map] /-- Append a list on the left side of a list_blank. -/ @[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ | [] L := L | (a :: l) L := list_blank.cons a (list_blank.append l L) @[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) := by induction l₁; simp only [*, list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk] theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) : list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) := l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc] /-- The `bind` function on lists is well defined on `list_blank`s provided that the default element is sent to a sequence of default elements. -/ def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list_blank Γ) (f : Γ → list Γ') (hf : ∃ n, f default = list.repeat default n) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.bind l f)) begin rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩), rw [list.bind_append, mul_comm], congr, induction i with i IH, refl, simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind], end @[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list Γ) (f : Γ → list Γ') (hf) : (list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl @[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) : (l.cons a).bind f hf = (l.bind f hf).append (f a) := l.induction_on $ by intro; simp only [list_blank.append_mk, list_blank.bind_mk, list_blank.cons_mk, list.cons_bind] /-- The tape of a Turing machine is composed of a head element (which we imagine to be the current position of the head), together with two `list_blank`s denoting the portions of the tape going off to the left and right. When the Turing machine moves right, an element is pulled from the right side and becomes the new head, while the head element is consed onto the left side. -/ structure tape (Γ : Type*) [inhabited Γ] := (head : Γ) (left : list_blank Γ) (right : list_blank Γ) instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) := ⟨by constructor; apply default⟩ /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq, derive inhabited] inductive dir | left | right /-- The "inclusive" left side of the tape, including both `left` and `head`. -/ def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head /-- The "inclusive" right side of the tape, including both `right` and `head`. -/ def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head /-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes `T.left` smaller; the Turing machine is moving left and the tape is moving right. -/ def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩ | dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩ @[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.left).move dir.right = T := by cases T; simp [tape.move] @[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.right).move dir.left = T := by cases T; simp [tape.move] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩ @[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).left = L := rfl @[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).head = R.head := rfl @[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right = R.tail := rfl @[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right₀ = R := list_blank.cons_head_tail _ @[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) : tape.mk' T.left T.right₀ = T := by cases T; simp only [tape.right₀, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) : ∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩ @[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] @[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := tape.mk' (list_blank.mk L) (list_blank.mk R) /-- Construct a tape from a list, with the head of the list at the TM head and the rest going to the right. -/ def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ := tape.mk₂ [] l /-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes on the left and positive indexes on the right. (Picture a number line.) -/ def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ | 0 := T.head | (n+1:ℕ) := T.right.nth n | -[1+ n] := T.left.nth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero, list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons] @[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) : (tape.mk' L R).nth n = R.nth n := by rw [← tape.right₀_nth, tape.mk'_right₀] @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm | ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm | ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _) | ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin rw add_sub_cancel, change (R.cons a).nth (n+1) = R.nth n, rw [list_blank.nth_succ, list_blank.tail_cons] end @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) : (T.move dir.right).nth i = T.nth (i+1) := by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel] @[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) : ((tape.move dir.right)^[i] T).head = T.nth i := by induction i generalizing T; [refl, simp only [*, tape.move_right_nth, int.coe_nat_succ, iterate_succ]] /-- Replace the current value of the head on the tape. -/ def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T} @[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T := by rintro ⟨⟩; refl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | ⟨a, L, R⟩ 0 := rfl | ⟨a, L, R⟩ (n+1:ℕ) := rfl | ⟨a, L, R⟩ -[1+ n] := rfl @[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) : (tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) := by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] /-- Apply a pointed map to a tape to change the alphabet. -/ def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' := ⟨f T.1, T.2.map f, T.3.map f⟩ @[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 := by rintro ⟨⟩; refl @[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) := by rintro ⟨⟩; refl @[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) : ((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) = ((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) := begin induction n with n IH generalizing L R, { simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply], rw [← tape.write_mk', list_blank.cons_head_tail] }, simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth, tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH] end theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d := by cases T; cases d; simp only [tape.move, tape.map, list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map] theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) := by simp only [tape.mk', tape.map, list_blank.head_map, eq_self_iff_true, and_self, list_blank.tail_map] theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) := by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk] theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _ /-- Run a state transition function `σ → option σ` "to completion". The return value is the last state returned before a `none` result. If the state transition function always returns `some`, then the computation diverges, returning `part.none`. -/ def eval {σ} (f : σ → option σ) : σ → part σ := pfun.fix (λ s, part.some $ (f s).elim (sum.inl s) sum.inr) /-- The reflexive transitive closure of a state transition function. `reaches f a b` means there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation permits zero steps of the state transition function. -/ def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) /-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation does not permit zero steps of the state transition function. -/ def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} (hab : reaches f a b) (hac : reaches f a c) : reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique (λ _ _ _, option.mem_unique) hab hac theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end /-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then `reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with equivalent states without taking a step. -/ def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) /-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b` which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if `eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/ @[elab_as_eliminator] def eval_induction {σ} {f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', f a = some a' → C a') → C a) : C a := pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' e, h' _ $ part.mem_some_iff.2 $ by rw e; refl) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine eval_induction h (λ a h IH, _), cases e : f a with a', { rw part.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ part.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, _⟩; rw e at h; cases part.mem_some_iff.1 h, cases IH a' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply part.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply part.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := part.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ /-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions `f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates. Such a relation `tr` is also known as a refinement. -/ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ /-- A simpler version of `respects` when the state transition relation `tr` is a function. -/ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := part.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (part.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (part.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ /-! ## The TM0 model A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory. A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function `Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a` for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the `step` function: * If `M q T.head = none`, then the machine halts. * If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions to state `q'`. The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head of the tape and the rest of the list extends to the right, with the left side all blank. The final state takes the entire right side of the tape right or equal to the current position of the machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level of generality, where the output ends. If equality to `default : Γ` is decidable we can trim the list to remove the infinite tail of blanks.) -/ namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move : dir → stmt | write : Γ → stmt instance stmt.inhabited : inhabited stmt := ⟨stmt.write default⟩ /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ @[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment def machine := Λ → Γ → option (Λ × stmt) instance machine.inhabited : inhabited machine := by unfold machine; apply_instance /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) instance cfg.inhabited : inhabited cfg := ⟨⟨default, default⟩⟩ parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default, tape.mk₁ l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : part (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] /-- Map a TM statement across a function. This does nothing to move statements and maps the write values. -/ def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) /-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and `g : Λ → Λ'` a map of the machine states. -/ def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) /-- Because the state transition function uses the alphabet and machine states in both the input and output, to map a machine from one alphabet and machine state space to another we need functions in both directions, essentially an `equiv` without the laws. -/ def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S : set Λ} (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _) theorem machine.map_respects (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ) {S} (ss : supports M S) (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 /-! ## The TM1 model The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local variables and the value `T.head` on the tape to calculate what to write or how to change local state, but the statements themselves have a fixed structure. The `stmt`s can be as follows: * `move d q`: move left or right, and then do `q` * `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q` * `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head` * `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse` * `goto (f : Γ → σ → Λ)`: Go to label `f a T.head` * `halt`: Transition to the halting state, which halts on the following step Note that here most statements do not have labels; `goto` commands can only go to a new function. Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on statements and so take 0 steps. (There is a uniform bound on many statements can be executed before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.) The `halt` command has a one step stutter before actually halting so that any changes made before the halt have a chance to be "committed", since the `eval` relation uses the final configuration before the halt as the output, and `move` and `write` etc. take 0 steps in this model. -/ namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto : (Γ → σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default, default, default⟩⟩ parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ /-- The state transition function. -/ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) /-- A set `S` of labels supports the statement `q` if all the `goto` statements in `q` refer only to other functions in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true open_locale classical /-- The subterm closure of a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end /-- The set of all statements in a turing machine, plus one extra value `none` representing the halt state. This is used in the TM1 to TM0 reduction. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state, given a finite input that is placed on the tape starting at the TM head and going to the right. -/ def init (l : list Γ) : cfg := ⟨some default, default, tape.mk₁ l⟩ /-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate number of blanks on the end). -/ def eval (M : Λ → stmt) (l : list Γ) : part (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) end end TM1 /-! ## TM1 emulator in TM0 To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a TM0 program. So suppose a TM1 program is given. We take the following: * The alphabet `Γ` is the same for both TM1 and TM0 * The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none` representing halt, and the possible settings of the internal variables. Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume that from the initial TM1 state, only finitely many other labels are reachable, and there are only finitely many statements that appear in all of these functions. Even though `stmt₁` contains a statement called `halt`, we must separate it from `none` (`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the TM1 semantics. -/ namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M /-- The base machine state space is a pair of an `option stmt₁` representing the current program to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM, not the tape). Because there are an infinite number of programs, this state space is infinite, but for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are reachable. -/ @[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption -- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here. -- But they are parameters so we cannot easily skip them for just this definition. def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M default), default)⟩ open TM0.stmt /-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the `stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the latter case we emit a dummy `write s` step and transition to the new target location. -/ def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' /-- The translated TM0 machine (given the TM1 machine input). -/ def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) /-- Translate configurations from TM1 to TM0. -/ def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [part.map_eq_map, part.map_map, TM1.eval], congr' with ⟨⟩, refl end variables [fintype σ] /-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible machine states in the target (even though the type `Λ'` is infinite). -/ noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ open_locale classical local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ end end TM1to0 /-! ## TM1(Γ) emulator in TM1(bool) The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`. Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly. The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine wants to read a symbol from the tape, it traverses over the block, performing `n` `branch` instructions to each any of the `2^n` results. For the `write` instruction, we have to use a `goto` because we need to follow a different code path depending on the local state, which is not available in the TM1 model, so instead we jump to a label computed using the read value and the local state, which performs the writing and returns to normal execution. Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are exploiting the 0-step behavior of regular commands to avoid taking steps, but there are nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are finitely long. -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc default = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin letI := classical.dec_eq Γ, let n := fintype.card Γ, obtain ⟨F⟩ := fintype.trunc_equiv_fin Γ, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, classical, let enc := H.set_value default (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ /-- The configuration state of the TM. -/ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal default⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ /-- Read a vector of length `n` from the tape. -/ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v))) (stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) /-- A move left or right corresponds to `n` moves across the super-cell. -/ def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q /-- To read a symbol from the tape, we use `read_aux` to traverse the symbol, then return to the original position with `n` moves to the left. -/ def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) /-- Write a list of bools on the tape. -/ def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q /-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that we can access the current value of the tape. -/ def tr_normal : stmt₁ → stmt' | (stmt.move d q) := move d $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s) | stmt.halt := stmt.halt theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [iterate_succ', step_aux, IH, iterate_succ] end theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end parameter (enc0 : enc default = vector.repeat ff n) section parameter {enc} include enc0 /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape' (L R : list_blank Γ) : tape bool := begin refine tape.mk' (L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩) (R.bind (λ x, (enc x).to_list) ⟨n, _⟩); simp only [enc0, vector.repeat, list.reverse_repeat, bool.default_bool, vector.to_list_mk] end /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀ theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R := by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀] end parameters (M : Λ → stmt₁) /-- The top level program. -/ def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q /-- The machine configuration translation. -/ def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ parameter {enc} include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (R.cons L.head)) := begin obtain ⟨a, L, rfl⟩ := L.exists_cons, simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons], suffices : ∀ {L' R' l₁ l₂} (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), tape.move dir.left^[l₁.length] (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'), { simpa only [list.length_reverse, vector.to_list_length] using this (list.reverse_reverse _).symm }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, iterate_succ_apply], convert IH e, simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons] end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (L.cons R.head) R.tail) := begin suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L, { refine (eq.symm _).trans (this n _), simp only [tr_tape'_move_left, list_blank.cons_head_tail, list_blank.head_cons, list_blank.tail_cons] }, intros, induction i with i IH, {refl}, rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH] end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) = step_aux q v (tr_tape' (list_blank.cons a L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) = step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'), { convert this [] _ _ ((enc b).2.trans (enc a).2.symm); rw list_blank.cons_bind; refl }, clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, dunfold write step_aux, convert IH _ _ e using 1, simp only [list_blank.head_cons, list_blank.tail_cons, list_blank.append, tape.move_right_mk', tape.write_mk'] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L R) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc0 L R) = step_aux (f (enc R.head)) v (tr_tape' enc0 (L.cons R.head) R.tail), { rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0], simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] }, obtain ⟨a, R, rfl⟩ := R.exists_cons, simp only [list_blank.head_cons, list_blank.tail_cons, tr_tape', list_blank.cons_bind, list_blank.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, transitivity step_aux (read_aux l₂.length (λ v, f (a ::ᵥ v))) v (tape.mk' ((L'.append l₁).cons a) (R'.append l₂)), { dsimp [read_aux, step_aux], simp, cases a; refl }, rw [← list_blank.append, IH], refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin obtain ⟨L, R, rfl⟩ := T.exists_mk', cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc0 L R)) (tr_cfg enc0 (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, iterate, step_aux_move, step_aux, list_blank.head_cons, tape.move_left_mk', list_blank.cons_head_tail, list_blank.tail_cons, tr_tape'_move_left enc0, tr_tape'_move_right enc0]; apply IH }, case TM1.stmt.write : f q IH { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, obtain ⟨a, R, rfl⟩ := R.exists_cons, rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons, step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons, list_blank.tail_cons, tape.write_mk'], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move, tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'], apply refl_trans_gen.refl } end omit enc0 encdec open_locale classical parameters [fintype Γ] /-- The set of accessible `Λ'.write` machine states. -/ noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ /-- The set of accessible machine states, assuming that the input machine is supported on `S`, are the normal states embedded from `S`, plus all write states accessible from these states. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (Λ'.normal l) (writes (M l))) theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 /-! ## TM0 emulator in TM1 To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator in TM1. The main complication here is that TM0 allows an action to depend on the value at the head and local state, while TM1 doesn't (in order to have more programming language-like semantics). So we use a computed `goto` to go to a state that performes the desired action and then returns to normal execution. One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an unreachable branch). -/ namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] /-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded as `normal q` states, but the actual operation is split into two parts, a jump to `act s q` followed by the action and a jump to the next `normal` state. -/ inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal default⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt /-- The program. -/ def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default -- unreachable | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) /-- The configuration translation. -/ def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 /-! ## The TM2 model The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks, each with elements of different types (the alphabet of stack `k : K` is `Γ k`). The statements are: * `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`. * `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, and removes this element from the stack, then does `q`. * `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, then does `q`. * `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`. * `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`. * `goto (f : σ → Λ)` jumps to label `f a`. * `halt` halts on the next step. The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or `none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)` is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not `list_blank`s, they have definite ends that can be detected by the `pop` command.) Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the stacks empty except the designated "input" stack; in `eval` this designated stack also functions as the output stack. -/ namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push : ∀ k, (σ → Γ k) → stmt → stmt | peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto : (σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite size.) -/ structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default, default, default⟩⟩ parameters {Γ Λ σ K} /-- The step function for the TM2 model. -/ @[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (update S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ /-- The step function for the TM2 model. -/ @[simp] def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) /-- The (reflexive) reachability relation for the TM2 model. -/ def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true open_locale classical /-- The set of subtree statements in a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end /-- The set of statements accessible from initial set `S` of labels. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in `S` jump only to other states in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state of the TM2 model. The input is provided on a designated stack. -/ def init (k) (L : list (Γ k)) : cfg := ⟨some default, default, update (λ _, []) k L⟩ /-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : part (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k end end TM2 /-! ## TM2 emulator in TM1 To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack 1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this: ``` bottom: ... | _ | T | _ | _ | _ | _ | ... stack 1: ... | _ | b | a | _ | _ | _ | ... stack 2: ... | _ | f | e | d | c | _ | ... ``` where a tape element is a vertical slice through the diagram. Here the alphabet is `Γ' := bool × ∀ k, option (Γ k)`, where: * `bottom : bool` is marked only in one place, the initial position of the TM, and represents the tail of all stacks. It is never modified. * `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is the blank value). Note that the head of the stack is at the far end; this is so that push and pop don't have to do any shifting. In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions, it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the end of the appropriate stack, make its changes, and then return to the bottom. So the states are: * `normal (l : Λ)`: waiting at `bottom` to execute function `l` * `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in order to perform stack action `s`, and later continue with executing `q` * `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing `q` once we arrive Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)` steps to run when emulated in TM1, where `m` is the length of the input. -/ namespace TM2to1 -- A displaced lemma proved in unnecessary generality theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n) (hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) : L.nth n k = S.reverse.nth n := begin rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map], cases S.reverse.nth n; refl end section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ /-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom, plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/ @[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip -- the decidable_eq assumption, and this is a local definition anyway so it's not important. def Γ' := bool × ∀ k, option (Γ k) instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩ instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := prod.fintype _ _ /-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function to express the program state in terms of a tape with only the stacks themselves. -/ def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' := list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩) theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L := begin simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _, generalize : list_blank.tail L = L', refine L'.induction_on (λ l, _), simp end theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) : (add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) := begin cases n; simp only [add_bottom, list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons], congr, symmetry, apply list_blank.map_modify_nth, intro, refl end theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n := by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff := by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt := by rw [add_bottom, list_blank.head_cons]; refl /-- A stack action is a command that interacts with the top of a stack. Our default position is at the bottom of all the stacks, so we have to hold on to this action while going to the end to modify the stack. -/ inductive st_act (k : K) | push : (σ → Γ k) → st_act | peek : (σ → option (Γ k) → σ) → st_act | pop : (σ → option (Γ k) → σ) → st_act instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩ section open st_act /-- The TM2 statement corresponding to a stack action. -/ @[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than -- it is worth to omit the typeclass assumption without breaking the parameters def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (peek f) := TM2.stmt.peek k f | (pop f) := TM2.stmt.pop k f /-- The effect of a stack action on the local variables, given the value of the stack. -/ def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (peek f) := f v l.head' | (pop f) := f v l.head' /-- The effect of a stack action on the stack. -/ def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (peek f) := l | (pop f) := l.tail /-- We have partitioned the TM2 statements into "stack actions", which require going to the end of the stack, and all other actions, which do not. This is a modified recursor which lumps the stack actions into one. -/ @[elab_as_eliminator] def {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end /-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and return to the bottom, respectively. -/ inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret : stmt₂ → Λ' open Λ' instance Λ'.inhabited : inhabited Λ' := ⟨normal default⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt /-- The program corresponding to state transitions at the end of a stack. Here we start out just after the top of the stack, and should end just after the new top of the stack. -/ def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q | (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q | (st_act.pop f) := branch (λ a _, a.1) ( load (λ a s, f s none) q ) ( move dir.left $ load (λ a s, f s (a.2 k)) $ write (λ a s, (a.1, update a.2 k none)) q ) /-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty except for the input stack, and the stack bottom mark is set at the head. -/ def tr_init (k) (L : list (Γ k)) : list Γ' := let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in (tt, L'.head.2) :: L'.tail theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl | (st_act.pop f) := rfl /-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents, but stack actions are deferred by going to the corresponding `go` state, so that we can find the appropriate stack top. -/ def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl open_locale classical /-- The set of machine states accessible from an initial TM2 statement. -/ noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | (TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q | (TM2.stmt.load a q) := tr_stmts₁ q | (TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' := update S k Sk' in ∃ (L' : list_blank (∀ k, option (Γ k))), (∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧ TM1.step_aux (tr_st_act q o) v ((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) = TM1.step_aux q v' ((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) := begin dsimp only, simp, cases o; simp only [st_write, st_var, tr_st_act, TM1.step_aux], case TM2to1.st_act.push : f { have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))), dsimp only at this, refine ⟨_, λ k', _, by rw [ tape.move_right_n_head, list.length, tape.mk'_nth_nat, this, add_bottom_modify_nth (λ a, update a k (some (f v))), nat.add_one, iterate_succ']⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [list.reverse_cons, function.update_same, list_blank.nth_mk, list.inth, list.map], { rw [list.nth_le_nth, list.nth_le_append_right]; simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos', list.length_append, lt_add_iff_pos_right, list.length] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth], cases lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at h, rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } }, case TM2to1.st_act.peek : f { rw function.update_eq_self, use [L, hL], rw [tape.move_left_right], congr, cases e : S k, {refl}, rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e, list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl }, case TM2to1.st_act.pop : f { cases e : S k, { simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk', list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil], rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ }, { refine ⟨_, λ k', _, by rw [ list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)), add_bottom_modify_nth (λ a, update a k none), add_bottom_nth_snd, stk_nth_val _ (hL k), e, show (list.cons hd tl).reverse.nth tl.length = some hd, by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl, list.head', list.tail]⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [ function.update_same, list_blank.nth_mk, list.tail, list.inth], { rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons], cases lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw gt_iff_lt at h, rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } } }, end parameters (M : Λ → stmt₂) include M /-- The TM2 emulator machine states written as a TM1 program. This handles the `go` and `ret` states, which shuttle to and from a stack top. -/ def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret q) := branch (λ a s, a.1) (tr_normal q) (move dir.left $ goto (λ _ _, ret q)) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg /-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/ inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) : (∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩ theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) : reaches₀ (TM1.step tr) ⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩ ⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, apply (IH (le_of_lt H)).tail, rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr, tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd, option.mem_def], rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse end theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) : reaches₀ (TM1.step tr) ⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ ⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, refine reaches₀.head _ IH, rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl, end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))}, (∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b := begin simp only [tr_normal_run, step_run], have hgo := tr_respects_aux₁ M o q v (hT k) _ le_rfl, obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o, have hret := tr_respects_aux₃ M _, have := hgo.tail' rfl, rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)), option.is_none, cond, hrun, TM1.step_aux] at this, obtain ⟨c, gc, rc⟩ := IH hT', refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩, rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst], exact rc, end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH _ hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := begin rw (_ : TM1.init _ = _), { refine ⟨list_blank.mk (L.reverse.map $ λ a, update default k (some a)), λ k', _⟩, refine list_blank.ext (λ i, _), rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘), list.nth_map, proj, pointed_map.mk_val], by_cases k' = k, { subst k', simp only [function.update_same], rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] }, { simp only [function.update_noteq h], rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth], cases L.reverse.nth i; refl } }, { rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl}, simp only [list.map_map, list.tail_cons, list.map], refl } end theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))), add_bottom L' = L₁ ∧ (∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧ S k = L₂ := begin obtain ⟨c₁, h₁, rfl⟩ := (part.mem_map_iff _).1 H₁, obtain ⟨c₂, h₂, rfl⟩ := (part.mem_map_iff _).1 H₂, obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂, cases part.mem_unique h₁ h₃, exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩ end /-- The support of a set of TM2 states in the TM2 emulator. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l))) theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inl rfl), have hret := sub _ (or.inl $ or.inr rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
5a129dd6b1a4f3f9445c40bfc59c2654e2914c5d
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/eq_to_hom.lean
c7a18834f100c69b23d82b75e675ac3b6dcfa629
[ "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
5,116
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison -/ import category_theory.opposites universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. namespace category_theory open opposite variables {C : Type u₁} [category.{v₁} C] /-- An equality `X = Y` gives us a morphism `X ⟶ Y`. It is typically better to use this, rather than rewriting by the equality then using `𝟙 _` which usually leads to dependent type theory hell. -/ def eq_to_hom {X Y : C} (p : X = Y) : X ⟶ Y := by rw p; exact 𝟙 _ @[simp] lemma eq_to_hom_refl (X : C) (p : X = X) : eq_to_hom p = 𝟙 X := rfl @[simp, reassoc] lemma eq_to_hom_trans {X Y Z : C} (p : X = Y) (q : Y = Z) : eq_to_hom p ≫ eq_to_hom q = eq_to_hom (p.trans q) := by { cases p, cases q, simp, } /-- If we (perhaps unintentionally) perform equational rewriting on the source object of a morphism, we can replace the resulting `_.mpr f` term by a composition with an `eq_to_hom`. It may be advisable to introduce any necessary `eq_to_hom` morphisms manually, rather than relying on this lemma firing. -/ @[simp] lemma congr_arg_mpr_hom_left {X Y Z : C} (p : X = Y) (q : Y ⟶ Z) : (congr_arg (λ W : C, W ⟶ Z) p).mpr q = eq_to_hom p ≫ q := by { cases p, simp, } /-- If we (perhaps unintentionally) perform equational rewriting on the target object of a morphism, we can replace the resulting `_.mpr f` term by a composition with an `eq_to_hom`. It may be advisable to introduce any necessary `eq_to_hom` morphisms manually, rather than relying on this lemma firing. -/ @[simp] lemma congr_arg_mpr_hom_right {X Y Z : C} (p : X ⟶ Y) (q : Z = Y) : (congr_arg (λ W : C, X ⟶ W) q).mpr p = p ≫ eq_to_hom q.symm := by { cases q, simp, } /-- An equality `X = Y` gives us a morphism `X ⟶ Y`. It is typically better to use this, rather than rewriting by the equality then using `iso.refl _` which usually leads to dependent type theory hell. -/ def eq_to_iso {X Y : C} (p : X = Y) : X ≅ Y := ⟨eq_to_hom p, eq_to_hom p.symm, by simp, by simp⟩ @[simp] lemma eq_to_iso.hom {X Y : C} (p : X = Y) : (eq_to_iso p).hom = eq_to_hom p := rfl @[simp] lemma eq_to_iso.inv {X Y : C} (p : X = Y) : (eq_to_iso p).inv = eq_to_hom p.symm := rfl @[simp] lemma eq_to_iso_refl {X : C} (p : X = X) : eq_to_iso p = iso.refl X := rfl @[simp] lemma eq_to_iso_trans {X Y Z : C} (p : X = Y) (q : Y = Z) : eq_to_iso p ≪≫ eq_to_iso q = eq_to_iso (p.trans q) := by ext; simp @[simp] lemma eq_to_hom_op {X Y : C} (h : X = Y) : (eq_to_hom h).op = eq_to_hom (congr_arg op h.symm) := by { cases h, refl, } @[simp] lemma eq_to_hom_unop {X Y : Cᵒᵖ} (h : X = Y) : (eq_to_hom h).unop = eq_to_hom (congr_arg unop h.symm) := by { cases h, refl, } instance {X Y : C} (h : X = Y) : is_iso (eq_to_hom h) := is_iso.of_iso (eq_to_iso h) @[simp] lemma inv_eq_to_hom {X Y : C} (h : X = Y) : inv (eq_to_hom h) = eq_to_hom h.symm := by { ext, simp, } variables {D : Type u₂} [category.{v₂} D] namespace functor /-- Proving equality between functors. This isn't an extensionality lemma, because usually you don't really want to do this. -/ lemma ext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ X Y f, F.map f = eq_to_hom (h_obj X) ≫ G.map f ≫ eq_to_hom (h_obj Y).symm) : F = G := begin cases F with F_obj _ _ _, cases G with G_obj _ _ _, have : F_obj = G_obj, by ext X; apply h_obj, subst this, congr, funext X Y f, simpa using h_map X Y f end /-- Proving equality between functors using heterogeneous equality. -/ lemma hext {F G : C ⥤ D} (h_obj : ∀ X, F.obj X = G.obj X) (h_map : ∀ X Y (f : X ⟶ Y), F.map f == G.map f) : F = G := begin cases F with F_obj _ _ _, cases G with G_obj _ _ _, have : F_obj = G_obj, by ext X; apply h_obj, subst this, congr, funext X Y f, exact eq_of_heq (h_map X Y f) end -- Using equalities between functors. lemma congr_obj {F G : C ⥤ D} (h : F = G) (X) : F.obj X = G.obj X := by subst h lemma congr_hom {F G : C ⥤ D} (h : F = G) {X Y} (f : X ⟶ Y) : F.map f = eq_to_hom (congr_obj h X) ≫ G.map f ≫ eq_to_hom (congr_obj h Y).symm := by subst h; simp end functor @[simp] lemma eq_to_hom_map (F : C ⥤ D) {X Y : C} (p : X = Y) : F.map (eq_to_hom p) = eq_to_hom (congr_arg F.obj p) := by cases p; simp @[simp] lemma eq_to_iso_map (F : C ⥤ D) {X Y : C} (p : X = Y) : F.map_iso (eq_to_iso p) = eq_to_iso (congr_arg F.obj p) := by ext; cases p; simp @[simp] lemma eq_to_hom_app {F G : C ⥤ D} (h : F = G) (X : C) : (eq_to_hom h : F ⟶ G).app X = eq_to_hom (functor.congr_obj h X) := by subst h; refl lemma nat_trans.congr {F G : C ⥤ D} (α : F ⟶ G) {X Y : C} (h : X = Y) : α.app X = F.map (eq_to_hom h) ≫ α.app Y ≫ G.map (eq_to_hom h.symm) := by { rw [α.naturality_assoc], simp } lemma eq_conj_eq_to_hom {X Y : C} (f : X ⟶ Y) : f = eq_to_hom rfl ≫ f ≫ eq_to_hom rfl := by simp only [category.id_comp, eq_to_hom_refl, category.comp_id] end category_theory
dd90ab58aea3843461b8daaaeff3fd97bf3743d3
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/library/tools/super/cdcl_solver.lean
acd8b16311b889c04209097618c570aa3af85535
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,976
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause open tactic expr monad super namespace cdcl @[reducible] meta def prop_var := expr @[reducible] meta def proof_term := expr @[reducible] meta def proof_hyp := expr meta inductive trail_elem | dec : prop_var → bool → proof_hyp → trail_elem | propg : prop_var → bool → proof_term → proof_hyp → trail_elem | dbl_neg_propg : prop_var → bool → proof_term → proof_hyp → trail_elem namespace trail_elem meta def var : trail_elem → prop_var | (dec v _ _) := v | (propg v _ _ _) := v | (dbl_neg_propg v _ _ _) := v meta def phase : trail_elem → bool | (dec _ ph _) := ph | (propg _ ph _ _) := ph | (dbl_neg_propg _ ph _ _) := ph meta def hyp : trail_elem → proof_hyp | (dec _ _ h) := h | (propg _ _ _ h) := h | (dbl_neg_propg _ _ _ h) := h meta def is_decision : trail_elem → bool | (dec _ _ _) := tt | (propg _ _ _ _) := ff | (dbl_neg_propg _ _ _ _) := ff end trail_elem meta structure var_state := (phase : bool) (assigned : option proof_hyp) meta structure learned_clause := (c : clause) (actual_proof : proof_term) meta inductive prop_lit | neg : prop_var → prop_lit | pos : prop_var → prop_lit namespace prop_lit meta instance prop_lit.has_ordering : has_ordering prop_lit := ⟨λl₁ l₂, match l₁, l₂ with | pos _, neg _ := ordering.gt | neg _, pos _ := ordering.lt | pos v₁, pos v₂ := has_ordering.cmp v₁ v₂ | neg v₁, neg v₂ := has_ordering.cmp v₁ v₂ end⟩ meta def of_cls_lit : clause.literal → prop_lit | (clause.literal.left v) := neg v | (clause.literal.right v) := pos v meta def of_var_and_phase (v : prop_var) : bool → prop_lit | tt := pos v | ff := neg v end prop_lit meta def watch_map := rb_map name (ℕ × ℕ × clause) meta structure state := (trail : list trail_elem) (vars : rb_map prop_var var_state) (unassigned : rb_map prop_var prop_var) (clauses : list clause) (learned : list learned_clause) (watches : rb_map prop_lit watch_map) (conflict : option proof_term) (unitp_queue : list prop_var) (local_false : expr) namespace state meta def initial (local_false : expr) : state := { trail := [], vars := rb_map.mk _ _, unassigned := rb_map.mk _ _, clauses := [], learned := [], watches := rb_map.mk _ _, conflict := none, unitp_queue := [], local_false := local_false } meta def watches_for (st : state) (pl : prop_lit) : watch_map := (st.watches.find pl).get_or_else (rb_map.mk _ _) end state meta def solver := state_t state tactic meta instance : monad solver := state_t.monad _ _ meta instance : has_monad_lift tactic solver := monad.monad_transformer_lift (state_t state) tactic meta instance (α : Type) : has_coe (tactic α) (solver α) := ⟨monad.monad_lift⟩ meta def fail {A B} [has_to_format B] (b : B) : solver A := @tactic.fail A B _ b meta def get_local_false : solver expr := do st ← state_t.read, return st.local_false meta def mk_var_core (v : prop_var) (ph : bool) : solver unit := do state_t.modify $ λst, match st.vars.find v with | (some _) := st | none := { st with vars := st.vars.insert v ⟨ph, none⟩, unassigned := st.unassigned.insert v v } end meta def mk_var (v : prop_var) : solver unit := mk_var_core v ff meta def set_conflict (proof : proof_term) : solver unit := state_t.modify $ λst, { st with conflict := some proof } meta def has_conflict : solver bool := do st ← state_t.read, return st.conflict.is_some meta def push_trail (elem : trail_elem) : solver unit := do st ← state_t.read, match st.vars.find elem.var with | none := fail $ "unknown variable: " ++ elem.var.to_string | some ⟨_, some _⟩ := fail $ "adding already assigned variable to trail: " ++ elem.var.to_string | some ⟨_, none⟩ := state_t.write { st with vars := st.vars.insert elem.var ⟨elem.phase, some elem.hyp⟩, unassigned := st.unassigned.erase elem.var, trail := elem :: st.trail, unitp_queue := elem.var :: st.unitp_queue } end meta def pop_trail_core : solver (option trail_elem) := do st ← state_t.read, match st.trail with | elem :: rest := do state_t.write { st with trail := rest, vars := st.vars.insert elem.var ⟨elem.phase, none⟩, unassigned := st.unassigned.insert elem.var elem.var, unitp_queue := [] }, return $ some elem | [] := return none end meta def is_decision_level_zero : solver bool := do st ← state_t.read, return $ st.trail.for_all $ λelem, ¬elem.is_decision meta def revert_to_decision_level_zero : unit → solver unit | () := do is_dl0 ← is_decision_level_zero, if is_dl0 then return () else do pop_trail_core, revert_to_decision_level_zero () meta def formula_of_lit (local_false : expr) (v : prop_var) (ph : bool) := if ph then v else imp v local_false meta def lookup_var (v : prop_var) : solver (option var_state) := do st ← state_t.read, return $ st.vars.find v meta def add_propagation (v : prop_var) (ph : bool) (just : proof_term) (just_is_dn : bool) : solver unit := do v_st ← lookup_var v, local_false ← get_local_false, match v_st with | none := fail $ "propagating unknown variable: " ++ v.to_string | some ⟨assg_ph, some proof⟩ := if ph = assg_ph then return () else if assg_ph ∧ ¬just_is_dn then set_conflict (app just proof) else set_conflict (app proof just) | some ⟨_, none⟩ := do hyp_name ← mk_fresh_name, hyp ← return $ local_const hyp_name hyp_name binder_info.default (formula_of_lit local_false v ph), if just_is_dn then do push_trail $ trail_elem.dbl_neg_propg v ph just hyp else do push_trail $ trail_elem.propg v ph just hyp end meta def add_decision (v : prop_var) (ph : bool) : solver unit := do hyp_name ← mk_fresh_name, local_false ← get_local_false, hyp ← return $ local_const hyp_name hyp_name binder_info.default (formula_of_lit local_false v ph), push_trail $ trail_elem.dec v ph hyp meta def lookup_lit (l : clause.literal) : solver (option (bool × proof_hyp)) := do var_st_opt ← lookup_var l.formula, match var_st_opt with | none := return none | some ⟨ph, none⟩ := return none | some ⟨ph, some proof⟩ := return $ some (if l.is_neg then bnot ph else ph, proof) end meta def lit_is_false (l : clause.literal) : solver bool := do s ← lookup_lit l, return $ match s with | some (ff, _) := tt | _ := ff end meta def lit_is_not_false (l : clause.literal) : solver bool := do isf ← lit_is_false l, return $ bnot isf meta def cls_is_false (c : clause) : solver bool := lift list.band $ mapm lit_is_false c.get_lits private meta def unit_propg_cls' : clause → solver (option prop_var) | c := if c.num_lits = 0 then return (some c.proof) else let hd := c.get_lit 0 in do lit_st ← lookup_lit hd, match lit_st with | some (ff, isf_prf) := unit_propg_cls' (c.inst isf_prf) | _ := return none end meta def unit_propg_cls : clause → solver unit | c := do has_confl ← has_conflict, if has_confl then return () else if c.num_lits = 0 then do set_conflict c.proof else let hd := c.get_lit 0 in do lit_st ← lookup_lit hd, match lit_st with | some (ff, isf_prf) := unit_propg_cls (c.inst isf_prf) | some (tt, _) := return () | none := do fls_prf_opt ← unit_propg_cls' (c.inst (expr.mk_var 0)), match fls_prf_opt with | some fls_prf := do fls_prf' ← return $ lam `H binder_info.default c.type.binding_domain fls_prf, if hd.is_neg then add_propagation hd.formula ff fls_prf' ff else add_propagation hd.formula tt fls_prf' tt | none := return () end end private meta def modify_watches_for (pl : prop_lit) (f : watch_map → watch_map) : solver unit := state_t.modify $ λst, { st with watches := st.watches.insert pl $ f $ st.watches_for pl } private meta def add_watch (n : name) (c : clause) (i j : ℕ) : solver unit := let l := c.get_lit i, pl := prop_lit.of_cls_lit l in modify_watches_for pl $ λw, w.insert n (i,j,c) private meta def remove_watch (n : name) (c : clause) (i : ℕ) : solver unit := let l := c.get_lit i, pl := prop_lit.of_cls_lit l in modify_watches_for pl $ λw, w.erase n private meta def set_watches (n : name) (c : clause) : solver unit := if c.num_lits = 0 then set_conflict c.proof else if c.num_lits = 1 then unit_propg_cls c else do not_false_lits ← filter (λi, lit_is_not_false (c.get_lit i)) (list.range c.num_lits), match not_false_lits with | [] := do add_watch n c 0 1, add_watch n c 1 0, unit_propg_cls c | [i] := let j := if i = 0 then 1 else 0 in do add_watch n c i j, add_watch n c j i, unit_propg_cls c | (i::j::_) := do add_watch n c i j, add_watch n c j i end meta def update_watches (n : name) (c : clause) (i₁ i₂ : ℕ) : solver unit := do remove_watch n c i₁, remove_watch n c i₂, set_watches n c meta def mk_clause (c : clause) : solver unit := do c : clause ← c.distinct, for c.get_lits (λl, mk_var l.formula), revert_to_decision_level_zero (), state_t.modify $ λst, { st with clauses := c :: st.clauses }, c_name ← mk_fresh_name, set_watches c_name c meta def unit_propg_var (v : prop_var) : solver unit := do st ← state_t.read, if st.conflict.is_some then return () else match st.vars.find v with | some ⟨ph, none⟩ := fail $ "propagating unassigned variable: " ++ v.to_string | none := fail $ "unknown variable: " ++ v.to_string | some ⟨ph, some _⟩ := let watches := st.watches_for $ prop_lit.of_var_and_phase v (bnot ph) in for' watches.to_list $ λw, update_watches w.1 w.2.2.2 w.2.1 w.2.2.1 end meta def analyze_conflict' (local_false : expr) : proof_term → list trail_elem → clause | proof (trail_elem.dec v ph hyp :: es) := let abs_prf := abstract_local proof hyp.local_uniq_name in if has_var abs_prf then clause.close_const (analyze_conflict' proof es) hyp else analyze_conflict' proof es | proof (trail_elem.propg v ph l_prf hyp :: es) := let abs_prf := abstract_local proof hyp.local_uniq_name in if has_var abs_prf then analyze_conflict' (app (lam hyp.local_pp_name binder_info.default (formula_of_lit local_false v ph) abs_prf) l_prf) es else analyze_conflict' proof es | proof (trail_elem.dbl_neg_propg v ph l_prf hyp :: es) := let abs_prf := abstract_local proof hyp.local_uniq_name in if has_var abs_prf then analyze_conflict' (app l_prf (lambdas [hyp] proof)) es else analyze_conflict' proof es | proof [] := ⟨0, 0, proof, local_false, local_false⟩ meta def analyze_conflict (proof : proof_term) : solver clause := do st ← state_t.read, return $ analyze_conflict' st.local_false proof st.trail meta def add_learned (c : clause) : solver unit := do prf_abbrev_name ← mk_fresh_name, c' ← return { c with proof := local_const prf_abbrev_name prf_abbrev_name binder_info.default c.type }, state_t.modify $ λst, { st with learned := ⟨c', c.proof⟩ :: st.learned }, c_name ← mk_fresh_name, set_watches c_name c' meta def backtrack_with : clause → solver unit | conflict_clause := do isf ← cls_is_false conflict_clause, if ¬isf then state_t.modify (λst, { st with conflict := none }) else do removed_elem ← pop_trail_core, if removed_elem.is_some then backtrack_with conflict_clause else return () meta def replace_learned_clauses' : proof_term → list learned_clause → proof_term | proof [] := proof | proof (⟨c, actual_proof⟩ :: lcs) := let abs_prf := abstract_local proof c.proof.local_uniq_name in if has_var abs_prf then replace_learned_clauses' (elet c.proof.local_pp_name c.type actual_proof abs_prf) lcs else replace_learned_clauses' proof lcs meta def replace_learned_clauses (proof : proof_term) : solver proof_term := do st ← state_t.read, return $ replace_learned_clauses' proof st.learned meta inductive result | unsat : proof_term → result | sat : rb_map prop_var bool → result variable theory_solver : solver (option proof_term) meta def unit_propg : unit → solver unit | () := do st ← state_t.read, if st.conflict.is_some then return () else match st.unitp_queue with | [] := return () | (v::vs) := do state_t.write { st with unitp_queue := vs }, unit_propg_var v, unit_propg () end private meta def run' : unit → solver result | () := do unit_propg (), st ← state_t.read, match st.conflict with | some conflict := do conflict_clause ← analyze_conflict conflict, if conflict_clause.num_lits = 0 then do proof ← replace_learned_clauses conflict_clause.proof, return (result.unsat proof) else do backtrack_with conflict_clause, add_learned conflict_clause, run' () | none := match st.unassigned.min with | none := do theory_conflict ← theory_solver, match theory_conflict with | some conflict := do set_conflict conflict, run' () | none := return $ result.sat (st.vars.map (λvar_st, var_st.phase)) end | some unassigned := match st.vars.find unassigned with | some ⟨ph, none⟩ := do add_decision unassigned ph, run' () | _ := fail $ "unassigned variable is assigned: " ++ unassigned.to_string end end end meta def run : solver result := run' theory_solver () meta def solve (local_false : expr) (clauses : list clause) : tactic result := do res ← (do for clauses mk_clause, run theory_solver) (state.initial local_false), return res.1 meta def theory_solver_of_tactic (th_solver : tactic unit) : cdcl.solver (option cdcl.proof_term) := do s ← state_t.read, ↑do hyps ← return $ s.trail.map (λe, e.hyp), subgoal ← mk_meta_var s.local_false, goals ← get_goals, set_goals [subgoal], hvs ← for hyps (λhyp, assertv hyp.local_pp_name hyp.local_type hyp), solved ← (do th_solver, now, return tt) <|> return ff, set_goals goals, if solved then do proof ← instantiate_mvars subgoal, proof' ← whnf proof, -- gets rid of the unnecessary asserts return $ some proof' else return none end cdcl
3ac314a274111ac7a7e236b13c16d5ff54217180
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/algebra/category/Module/basic.lean
e53b48f7d24a92e6dedcc728eca95f7a06402cb2
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
5,619
lean
/- Copyright (c) 2019 Robert A. Spencer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert A. Spencer, Markus Himmel -/ import algebra.category.Group.basic import category_theory.concrete_category import category_theory.limits.shapes.kernels import category_theory.preadditive import linear_algebra.basic open category_theory open category_theory.limits open category_theory.limits.walking_parallel_pair universe u variables (R : Type u) [ring R] /-- The category of R-modules and their morphisms. -/ structure Module := (carrier : Type u) [is_add_comm_group : add_comm_group carrier] [is_module : module R carrier] attribute [instance] Module.is_add_comm_group Module.is_module namespace Module -- TODO revisit this after #1438 merges, to check coercions and instances are handled consistently instance : has_coe_to_sort (Module R) := { S := Type u, coe := Module.carrier } instance : category (Module R) := { hom := λ M N, M →ₗ[R] N, id := λ M, 1, comp := λ A B C f g, g.comp f } instance : concrete_category (Module R) := { forget := { obj := λ R, R, map := λ R S f, (f : R → S) }, forget_faithful := { } } instance has_forget_to_AddCommGroup : has_forget₂ (Module R) AddCommGroup := { forget₂ := { obj := λ M, AddCommGroup.of M, map := λ M₁ M₂ f, linear_map.to_add_monoid_hom f } } /-- The object in the category of R-modules associated to an R-module -/ def of (X : Type u) [add_comm_group X] [module R X] : Module R := ⟨X⟩ instance : inhabited (Module R) := ⟨of R punit⟩ @[simp] lemma of_apply (X : Type u) [add_comm_group X] [module R X] : (of R X : Type u) = X := rfl variables {R} /-- Forgetting to the underlying type and then building the bundled object returns the original module. -/ @[simps] def of_self_iso (M : Module R) : Module.of R M ≅ M := { hom := 𝟙 M, inv := 𝟙 M } instance : subsingleton (of R punit) := by { rw of_apply R punit, apply_instance } instance : has_zero_object (Module R) := { zero := of R punit, unique_to := λ X, { default := (0 : punit →ₗ[R] X), uniq := λ _, linear_map.ext $ λ x, have h : x = 0, from subsingleton.elim _ _, by simp only [h, linear_map.map_zero]}, unique_from := λ X, { default := (0 : X →ₗ[R] punit), uniq := λ _, linear_map.ext $ λ x, subsingleton.elim _ _ } } variables {R} {M N U : Module R} @[simp] lemma id_apply (m : M) : (𝟙 M : M → M) m = m := rfl @[simp] lemma coe_comp (f : M ⟶ N) (g : N ⟶ U) : ((f ≫ g) : M → U) = g ∘ f := rfl end Module variables {R} variables {X₁ X₂ : Type u} /-- Build an isomorphism in the category `Module R` from a `linear_equiv` between `module`s. -/ @[simps] def linear_equiv.to_Module_iso {g₁ : add_comm_group X₁} {g₂ : add_comm_group X₂} {m₁ : module R X₁} {m₂ : module R X₂} (e : X₁ ≃ₗ[R] X₂) : Module.of R X₁ ≅ Module.of R X₂ := { hom := (e : X₁ →ₗ[R] X₂), inv := (e.symm : X₂ →ₗ[R] X₁), hom_inv_id' := begin ext, exact e.left_inv x, end, inv_hom_id' := begin ext, exact e.right_inv x, end, } namespace category_theory.iso /-- Build a `linear_equiv` from an isomorphism in the category `Module R`. -/ @[simps] def to_linear_equiv {X Y : Module R} (i : X ≅ Y) : X ≃ₗ[R] Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := by tidy, right_inv := by tidy, map_add' := by tidy, map_smul' := by tidy, }. end category_theory.iso /-- linear equivalences between `module`s are the same as (isomorphic to) isomorphisms in `Module` -/ @[simps] def linear_equiv_iso_Module_iso {X Y : Type u} [add_comm_group X] [add_comm_group Y] [module R X] [module R Y] : (X ≃ₗ[R] Y) ≅ (Module.of R X ≅ Module.of R Y) := { hom := λ e, e.to_Module_iso, inv := λ i, i.to_linear_equiv, } namespace Module section preadditive instance : preadditive (Module R) := { add_comp' := λ P Q R f f' g, show (f + f') ≫ g = f ≫ g + f' ≫ g, by { ext, simp }, comp_add' := λ P Q R f g g', show f ≫ (g + g') = f ≫ g + f ≫ g', by { ext, simp } } end preadditive section kernel variables {R} {M N : Module R} (f : M ⟶ N) /-- The cone on the equalizer diagram of f and 0 induced by the kernel of f -/ def kernel_cone : cone (parallel_pair f 0) := { X := of R f.ker, π := { app := λ j, match j with | zero := f.ker.subtype | one := 0 end, naturality' := λ j j' g, by { cases j; cases j'; cases g; tidy } } } /-- The kernel of a linear map is a kernel in the categorical sense -/ def kernel_is_limit : is_limit (kernel_cone f) := { lift := λ s, linear_map.cod_restrict f.ker (fork.ι s) (λ c, linear_map.mem_ker.2 $ by { erw [←@function.comp_apply _ _ _ f (fork.ι s) c, ←coe_comp, fork.condition, has_zero_morphisms.comp_zero (fork.ι s) N], refl }), fac' := λ s j, linear_map.ext $ λ x, begin rw [coe_comp, function.comp_app, ←linear_map.comp_apply], cases j, { erw @linear_map.subtype_comp_cod_restrict _ _ _ _ _ _ _ _ (fork.ι s) f.ker _ }, { rw [←fork.app_zero_left, ←fork.app_zero_left], refl } end, uniq' := λ s m h, linear_map.ext $ λ x, subtype.ext_iff_val.2 $ have h₁ : (m ≫ (kernel_cone f).π.app zero).to_fun = (s.π.app zero).to_fun, by { congr, exact h zero }, by convert @congr_fun _ _ _ _ h₁ x } end kernel instance : has_kernels (Module R) := ⟨λ _ _ f, ⟨kernel_cone f, kernel_is_limit f⟩⟩ end Module instance (M : Type u) [add_comm_group M] [module R M] : has_coe (submodule R M) (Module R) := ⟨ λ N, Module.of R N ⟩