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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a8066395d07175272c7bf47e4011411fe3526349 | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/cc_lemmas.lean | 5da07f56a108bab1cafc8861a9dd9b789a574aaf | [
"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 | 4,638 | 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
-/
prelude
import init.propext init.classical
/-! Lemmas use by the congruence closure module -/
lemma iff_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ↔ b) = b :=
h.symm ▸ propext (true_iff _)
lemma iff_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ↔ b) = a :=
h.symm ▸ propext (iff_true _)
lemma iff_eq_true_of_eq {a b : Prop} (h : a = b) : (a ↔ b) = true :=
h ▸ propext (iff_self _)
lemma and_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ∧ b) = b :=
h.symm ▸ propext (true_and _)
lemma and_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ∧ b) = a :=
h.symm ▸ propext (and_true _)
lemma and_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a ∧ b) = false :=
h.symm ▸ propext (false_and _)
lemma and_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a ∧ b) = false :=
h.symm ▸ propext (and_false _)
lemma and_eq_of_eq {a b : Prop} (h : a = b) : (a ∧ b) = a :=
h ▸ propext (and_self _)
lemma or_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a ∨ b) = true :=
h.symm ▸ propext (true_or _)
lemma or_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a ∨ b) = true :=
h.symm ▸ propext (or_true _)
lemma or_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a ∨ b) = b :=
h.symm ▸ propext (false_or _)
lemma or_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a ∨ b) = a :=
h.symm ▸ propext (or_false _)
lemma or_eq_of_eq {a b : Prop} (h : a = b) : (a ∨ b) = a :=
h ▸ propext (or_self _)
lemma imp_eq_of_eq_true_left {a b : Prop} (h : a = true) : (a → b) = b :=
h.symm ▸ propext (iff.intro (λ h, h trivial) (λ h₁ h₂, h₁))
lemma imp_eq_of_eq_true_right {a b : Prop} (h : b = true) : (a → b) = true :=
h.symm ▸ propext (iff.intro (λ h, trivial) (λ h₁ h₂, h₁))
lemma imp_eq_of_eq_false_left {a b : Prop} (h : a = false) : (a → b) = true :=
h.symm ▸ propext (iff.intro (λ h, trivial) (λ h₁ h₂, false.elim h₂))
lemma imp_eq_of_eq_false_right {a b : Prop} (h : b = false) : (a → b) = not a :=
h.symm ▸ propext (iff.intro (λ h, h) (λ hna ha, hna ha))
/-- Remark: the congruence closure module will only use this lemma if
cc_config.em is tt. -/
lemma not_imp_eq_of_eq_false_right {a b : Prop} (h : b = false) : (not a → b) = a :=
h.symm ▸ propext (iff.intro (λ h', classical.by_contradiction (λ hna, h' hna)) (λ ha hna, hna ha))
lemma imp_eq_true_of_eq {a b : Prop} (h : a = b) : (a → b) = true :=
h ▸ propext (iff.intro (λ h, trivial) (λ h ha, ha))
lemma not_eq_of_eq_true {a : Prop} (h : a = true) : (not a) = false :=
h.symm ▸ propext not_true
lemma not_eq_of_eq_false {a : Prop} (h : a = false) : (not a) = true :=
h.symm ▸ propext not_false_iff
lemma false_of_a_eq_not_a {a : Prop} (h : a = not a) : false :=
have not a, from λ ha, absurd ha (eq.mp h ha),
absurd (eq.mpr h this) this
universes u
lemma if_eq_of_eq_true {c : Prop} [d : decidable c] {α : Sort u} (t e : α) (h : c = true) : (@ite α c d t e) = t :=
if_pos (of_eq_true h)
lemma if_eq_of_eq_false {c : Prop} [d : decidable c] {α : Sort u} (t e : α) (h : c = false) : (@ite α c d t e) = e :=
if_neg (not_of_eq_false h)
lemma if_eq_of_eq (c : Prop) [d : decidable c] {α : Sort u} {t e : α} (h : t = e) : (@ite α c d t e) = t :=
match d with
| (is_true hc) := rfl
| (is_false hnc) := eq.symm h
end
lemma eq_true_of_and_eq_true_left {a b : Prop} (h : (a ∧ b) = true) : a = true :=
eq_true_intro (and.left (of_eq_true h))
lemma eq_true_of_and_eq_true_right {a b : Prop} (h : (a ∧ b) = true) : b = true :=
eq_true_intro (and.right (of_eq_true h))
lemma eq_false_of_or_eq_false_left {a b : Prop} (h : (a ∨ b) = false) : a = false :=
eq_false_intro (λ ha, false.elim (eq.mp h (or.inl ha)))
lemma eq_false_of_or_eq_false_right {a b : Prop} (h : (a ∨ b) = false) : b = false :=
eq_false_intro (λ hb, false.elim (eq.mp h (or.inr hb)))
lemma eq_false_of_not_eq_true {a : Prop} (h : (not a) = true) : a = false :=
eq_false_intro (λ ha, absurd ha (eq.mpr h trivial))
/-- Remark: the congruence closure module will only use this lemma if
cc_config.em is tt. -/
lemma eq_true_of_not_eq_false {a : Prop} (h : (not a) = false) : a = true :=
eq_true_intro (classical.by_contradiction (λ hna, eq.mp h hna))
lemma ne_of_eq_of_ne {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b ≠ c) : a ≠ c :=
h₁.symm ▸ h₂
lemma ne_of_ne_of_eq {α : Sort u} {a b c : α} (h₁ : a ≠ b) (h₂ : b = c) : a ≠ c :=
h₂ ▸ h₁
|
07b01c3ab3c9054724d1c7e102c34aa42a98c1be | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/tidy.lean | dffbc908fe5a94d14378021fd70f751d60ac3cb8 | [
"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 | 1,006 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.tidy
open tactic
namespace tidy.test
meta def interactive_simp := `[simp]
def tidy_test_1 (a : string) : ∀ x : unit, x = unit.star :=
begin
tidy -- intros x, exact dec_trivial
end
structure A :=
(z : ℕ)
structure B :=
(a : A)
(aa : a.z = 0)
structure C :=
(a : A)
(b : B)
(ab : a.z = b.a.z)
structure D :=
(a : B)
(b : C)
(ab : a.a.z = b.a.z)
open tactic
def d : D :=
begin
tidy,
-- Try this: fsplit, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { refl }
-- }, work_on_goal 0 { fsplit, work_on_goal 0 { fsplit }, work_on_goal 1 { fsplit, work_on_goal 0
-- { fsplit }, work_on_goal 1 { refl } }, work_on_goal 1 { refl } }, refl
end.
def f : unit → unit → unit := by tidy -- intros a a_1, cases a_1, cases a, fsplit
def g (P Q : Prop) (p : P) (h : P ↔ Q) : Q := by tidy
end tidy.test
|
3e349280446056fc0d21bf999aba8810a63d6a12 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /09_Type_Classes.org.19.lean | bbd3ad832fac6680ca8fb68132edc773109531ee | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 722 | lean | import standard
import standard
inductive has_add [class] (A : Type) : Type :=
mk : (A → A → A) → has_add A
definition add {A : Type} [s : has_add A] :=
has_add.rec (λ x, x) s
notation a `+` b := add a b
definition has_add_nat [instance] : has_add nat :=
has_add.mk nat.add
definition has_add_int [instance] : has_add int :=
has_add.mk int.add
definition has_add_bool [instance] : has_add bool :=
has_add.mk bool.bor
-- BEGIN
definition has_add_prod [instance] {A B : Type} [sA : has_add A] [sB : has_add B] :
has_add (A × B) :=
has_add.mk (take p q, (add (prod.pr1 p) (prod.pr1 q), add (prod.pr2 p) (prod.pr2 q)))
open nat
check (1, 2) + (3, 4) -- ℕ × ℕ
eval (1, 2) + (3, 4) -- (4, 6)
-- END
|
62f1d22208e4e2c66c545fbc3f008a7947be7f16 | 367134ba5a65885e863bdc4507601606690974c1 | /src/combinatorics/simple_graph/adj_matrix.lean | 272685834594b9c03fbe1a9f49fa158a7eb4f6ce | [
"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 | 3,155 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Aaron Anderson, Jalex Stark.
-/
import linear_algebra.matrix
import data.rel
import combinatorics.simple_graph.basic
/-!
# Adjacency Matrices
This module defines the adjacency matrix of a graph, and provides theorems connecting graph
properties to computational properties of the matrix.
## Main definitions
* `adj_matrix` is the adjacency matrix of a `simple_graph` with coefficients in a given semiring.
-/
open_locale big_operators matrix
open finset matrix simple_graph
universes u v
variables {α : Type u} [fintype α]
variables (R : Type v) [semiring R]
namespace simple_graph
variables (G : simple_graph α) (R) [decidable_rel G.adj]
/-- `adj_matrix G R` is the matrix `A` such that `A i j = (1 : R)` if `i` and `j` are
adjacent in the simple graph `G`, and otherwise `A i j = 0`. -/
def adj_matrix : matrix α α R
| i j := if (G.adj i j) then 1 else 0
variable {R}
@[simp]
lemma adj_matrix_apply (v w : α) : G.adj_matrix R v w = if (G.adj v w) then 1 else 0 := rfl
@[simp]
theorem transpose_adj_matrix : (G.adj_matrix R)ᵀ = G.adj_matrix R :=
by { ext, simp [edge_symm] }
@[simp]
lemma adj_matrix_dot_product (v : α) (vec : α → R) :
dot_product (G.adj_matrix R v) vec = ∑ u in G.neighbor_finset v, vec u :=
by simp [neighbor_finset_eq_filter, dot_product, sum_filter]
@[simp]
lemma dot_product_adj_matrix (v : α) (vec : α → R) :
dot_product vec (G.adj_matrix R v) = ∑ u in G.neighbor_finset v, vec u :=
by simp [neighbor_finset_eq_filter, dot_product, sum_filter, sum_apply]
@[simp]
lemma adj_matrix_mul_vec_apply (v : α) (vec : α → R) :
((G.adj_matrix R).mul_vec vec) v = ∑ u in G.neighbor_finset v, vec u :=
by rw [mul_vec, adj_matrix_dot_product]
@[simp]
lemma adj_matrix_vec_mul_apply (v : α) (vec : α → R) :
((G.adj_matrix R).vec_mul vec) v = ∑ u in G.neighbor_finset v, vec u :=
begin
rw [← dot_product_adj_matrix, vec_mul],
refine congr rfl _, ext,
rw [← transpose_apply (adj_matrix R G) x v, transpose_adj_matrix],
end
@[simp]
lemma adj_matrix_mul_apply (M : matrix α α R) (v w : α) :
(G.adj_matrix R ⬝ M) v w = ∑ u in G.neighbor_finset v, M u w :=
by simp [mul_apply, neighbor_finset_eq_filter, sum_filter]
@[simp]
lemma mul_adj_matrix_apply (M : matrix α α R) (v w : α) :
(M ⬝ G.adj_matrix R) v w = ∑ u in G.neighbor_finset w, M v u :=
by simp [mul_apply, neighbor_finset_eq_filter, sum_filter, edge_symm]
variable (R)
theorem trace_adj_matrix : matrix.trace α R R (G.adj_matrix R) = 0 := by simp
variable {R}
theorem adj_matrix_mul_self_apply_self (i : α) :
((G.adj_matrix R) ⬝ (G.adj_matrix R)) i i = degree G i :=
by simp [degree]
variable {G}
@[simp]
lemma adj_matrix_mul_vec_const_apply {r : R} {v : α} :
(G.adj_matrix R).mul_vec (function.const _ r) v = G.degree v * r :=
by simp [degree]
lemma adj_matrix_mul_vec_const_apply_of_regular {d : ℕ} {r : R} (hd : G.is_regular_of_degree d)
{v : α} :
(G.adj_matrix R).mul_vec (function.const _ r) v = (d * r) :=
by simp [hd v]
end simple_graph
|
a80d192f6567f5abaed20c2b214978cc1e7ad70a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/function/ess_sup.lean | 101cfc27943174c300f3bb5d7f0f03a5d31d184c | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 11,516 | 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 measure_theory.constructions.borel_space.basic
import order.filter.ennreal
/-!
# Essential supremum and infimum
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the essential supremum and infimum of a function `f : α → β` with respect to a measure
`μ` on `α`. The essential supremum is the infimum of the constants `c : β` such that `f x ≤ c`
almost everywhere.
TODO: The essential supremum of functions `α → ℝ≥0∞` is used in particular to define the norm in
the `L∞` space (see measure_theory/lp_space.lean).
There is a different quantity which is sometimes also called essential supremum: the least
upper-bound among measurable functions of a family of measurable functions (in an almost-everywhere
sense). We do not define that quantity here, which is simply the supremum of a map with values in
`α →ₘ[μ] β` (see measure_theory/ae_eq_fun.lean).
## Main definitions
* `ess_sup f μ := μ.ae.limsup f`
* `ess_inf f μ := μ.ae.liminf f`
-/
open measure_theory filter set topological_space
open_locale ennreal measure_theory nnreal
variables {α β : Type*} {m : measurable_space α} {μ ν : measure α}
section conditionally_complete_lattice
variable [conditionally_complete_lattice β]
/-- Essential supremum of `f` with respect to measure `μ`: the smallest `c : β` such that
`f x ≤ c` a.e. -/
def ess_sup {m : measurable_space α} (f : α → β) (μ : measure α) := μ.ae.limsup f
/-- Essential infimum of `f` with respect to measure `μ`: the greatest `c : β` such that
`c ≤ f x` a.e. -/
def ess_inf {m : measurable_space α} (f : α → β) (μ : measure α) := μ.ae.liminf f
lemma ess_sup_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_sup f μ = ess_sup g μ :=
limsup_congr hfg
lemma ess_inf_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_inf f μ = ess_inf g μ :=
@ess_sup_congr_ae α βᵒᵈ _ _ _ _ _ hfg
@[simp] lemma ess_sup_const' [μ.ae.ne_bot] (c : β) : ess_sup (λ x : α, c) μ = c := limsup_const _
@[simp] lemma ess_inf_const' [μ.ae.ne_bot] (c : β) : ess_inf (λ x : α, c) μ = c := liminf_const _
lemma ess_sup_const (c : β) (hμ : μ ≠ 0) : ess_sup (λ x : α, c) μ = c :=
by { rw ←ae_ne_bot at hμ, exactI ess_sup_const' _ }
lemma ess_inf_const (c : β) (hμ : μ ≠ 0) : ess_inf (λ x : α, c) μ = c :=
by { rw ←ae_ne_bot at hμ, exactI ess_inf_const' _ }
end conditionally_complete_lattice
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order β] {x : β} {f : α → β}
lemma ess_sup_eq_Inf {m : measurable_space α} (μ : measure α) (f : α → β) :
ess_sup f μ = Inf {a | μ {x | a < f x} = 0} :=
by { dsimp [ess_sup, limsup, Limsup], simp only [ae_iff, not_le] }
lemma ess_inf_eq_Sup {m : measurable_space α} (μ : measure α) (f : α → β) :
ess_inf f μ = Sup {a | μ {x | f x < a} = 0} :=
by { dsimp [ess_inf, liminf, Liminf], simp only [ae_iff, not_le] }
lemma ae_lt_of_ess_sup_lt (hx : ess_sup f μ < x)
(hf : is_bounded_under (≤) μ.ae f . is_bounded_default) : ∀ᵐ y ∂μ, f y < x :=
eventually_lt_of_limsup_lt hx hf
lemma ae_lt_of_lt_ess_inf (hx : x < ess_inf f μ)
(hf : is_bounded_under (≥) μ.ae f . is_bounded_default) : ∀ᵐ y ∂μ, x < f y :=
eventually_lt_of_lt_liminf hx hf
variables [topological_space β] [first_countable_topology β] [order_topology β]
lemma ae_le_ess_sup (hf : is_bounded_under (≤) μ.ae f . is_bounded_default) :
∀ᵐ y ∂μ, f y ≤ ess_sup f μ :=
eventually_le_limsup hf
lemma ae_ess_inf_le (hf : is_bounded_under (≥) μ.ae f . is_bounded_default) :
∀ᵐ y ∂μ, ess_inf f μ ≤ f y :=
eventually_liminf_le hf
lemma meas_ess_sup_lt (hf : is_bounded_under (≤) μ.ae f . is_bounded_default) :
μ {y | ess_sup f μ < f y} = 0 :=
by { simp_rw ←not_le, exact ae_le_ess_sup hf }
lemma meas_lt_ess_inf (hf : is_bounded_under (≥) μ.ae f . is_bounded_default) :
μ {y | f y < ess_inf f μ} = 0 :=
by { simp_rw ←not_le, exact ae_ess_inf_le hf }
end conditionally_complete_linear_order
section complete_lattice
variable [complete_lattice β]
@[simp] lemma ess_sup_measure_zero {m : measurable_space α} {f : α → β} :
ess_sup f (0 : measure α) = ⊥ :=
le_bot_iff.mp (Inf_le (by simp [set.mem_set_of_eq, eventually_le, ae_iff]))
@[simp] lemma ess_inf_measure_zero {m : measurable_space α} {f : α → β} :
ess_inf f (0 : measure α) = ⊤ :=
@ess_sup_measure_zero α βᵒᵈ _ _ _
lemma ess_sup_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_sup f μ ≤ ess_sup g μ :=
limsup_le_limsup hfg
lemma ess_inf_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_inf f μ ≤ ess_inf g μ :=
liminf_le_liminf hfg
lemma ess_sup_le_of_ae_le {f : α → β} (c : β) (hf : f ≤ᵐ[μ] (λ _, c)) : ess_sup f μ ≤ c :=
begin
refine (ess_sup_mono_ae hf).trans _,
by_cases hμ : μ = 0,
{ simp [hμ], },
{ rwa ess_sup_const, },
end
lemma le_ess_inf_of_ae_le {f : α → β} (c : β) (hf : (λ _, c) ≤ᵐ[μ] f) : c ≤ ess_inf f μ :=
@ess_sup_le_of_ae_le α βᵒᵈ _ _ _ _ c hf
lemma ess_sup_const_bot : ess_sup (λ x : α, (⊥ : β)) μ = (⊥ : β) :=
limsup_const_bot
lemma ess_inf_const_top : ess_inf (λ x : α, (⊤ : β)) μ = (⊤ : β) :=
liminf_const_top
lemma order_iso.ess_sup_apply {m : measurable_space α} {γ} [complete_lattice γ]
(f : α → β) (μ : measure α) (g : β ≃o γ) :
g (ess_sup f μ) = ess_sup (λ x, g (f x)) μ :=
begin
refine order_iso.limsup_apply g _ _ _ _,
all_goals { is_bounded_default, },
end
lemma order_iso.ess_inf_apply {m : measurable_space α} {γ} [complete_lattice γ]
(f : α → β) (μ : measure α) (g : β ≃o γ) :
g (ess_inf f μ) = ess_inf (λ x, g (f x)) μ :=
@order_iso.ess_sup_apply α βᵒᵈ _ _ γᵒᵈ _ _ _ g.dual
lemma ess_sup_mono_measure {f : α → β} (hμν : ν ≪ μ) : ess_sup f ν ≤ ess_sup f μ :=
begin
refine limsup_le_limsup_of_le (measure.ae_le_iff_absolutely_continuous.mpr hμν) _ _,
all_goals { is_bounded_default, },
end
lemma ess_sup_mono_measure' {α : Type*} {β : Type*} {m : measurable_space α}
{μ ν : measure_theory.measure α} [complete_lattice β] {f : α → β} (hμν : ν ≤ μ) :
ess_sup f ν ≤ ess_sup f μ := ess_sup_mono_measure (measure.absolutely_continuous_of_le hμν)
lemma ess_inf_antitone_measure {f : α → β} (hμν : μ ≪ ν) : ess_inf f ν ≤ ess_inf f μ :=
begin
refine liminf_le_liminf_of_le (measure.ae_le_iff_absolutely_continuous.mpr hμν) _ _,
all_goals { is_bounded_default, },
end
lemma ess_sup_smul_measure {f : α → β} {c : ℝ≥0∞} (hc : c ≠ 0) :
ess_sup f (c • μ) = ess_sup f μ :=
begin
simp_rw ess_sup,
suffices h_smul : (c • μ).ae = μ.ae, by rw h_smul,
ext1,
simp_rw mem_ae_iff,
simp [hc],
end
section topological_space
variables {γ : Type*} {mγ : measurable_space γ} {f : α → γ} {g : γ → β}
include mγ
lemma ess_sup_comp_le_ess_sup_map_measure (hf : ae_measurable f μ) :
ess_sup (g ∘ f) μ ≤ ess_sup g (measure.map f μ) :=
begin
refine Limsup_le_Limsup_of_le (λ t, _) (by is_bounded_default) (by is_bounded_default),
simp_rw filter.mem_map,
have : (g ∘ f) ⁻¹' t = f ⁻¹' (g ⁻¹' t), by { ext1 x, simp_rw set.mem_preimage, },
rw this,
exact λ h, mem_ae_of_mem_ae_map hf h,
end
lemma _root_.measurable_embedding.ess_sup_map_measure (hf : measurable_embedding f) :
ess_sup g (measure.map f μ) = ess_sup (g ∘ f) μ :=
begin
refine le_antisymm _ (ess_sup_comp_le_ess_sup_map_measure hf.measurable.ae_measurable),
refine Limsup_le_Limsup (by is_bounded_default) (by is_bounded_default) (λ c h_le, _),
rw eventually_map at h_le ⊢,
exact hf.ae_map_iff.mpr h_le,
end
variables [measurable_space β] [topological_space β] [second_countable_topology β]
[order_closed_topology β] [opens_measurable_space β]
lemma ess_sup_map_measure_of_measurable (hg : measurable g) (hf : ae_measurable f μ) :
ess_sup g (measure.map f μ) = ess_sup (g ∘ f) μ :=
begin
refine le_antisymm _ (ess_sup_comp_le_ess_sup_map_measure hf),
refine Limsup_le_Limsup (by is_bounded_default) (by is_bounded_default) (λ c h_le, _),
rw eventually_map at h_le ⊢,
rw ae_map_iff hf (measurable_set_le hg measurable_const),
exact h_le,
end
lemma ess_sup_map_measure (hg : ae_measurable g (measure.map f μ)) (hf : ae_measurable f μ) :
ess_sup g (measure.map f μ) = ess_sup (g ∘ f) μ :=
begin
rw [ess_sup_congr_ae hg.ae_eq_mk, ess_sup_map_measure_of_measurable hg.measurable_mk hf],
refine ess_sup_congr_ae _,
have h_eq := ae_of_ae_map hf hg.ae_eq_mk,
rw ← eventually_eq at h_eq,
exact h_eq.symm,
end
omit mγ
end topological_space
end complete_lattice
section complete_linear_order
variable [complete_linear_order β]
lemma ess_sup_indicator_eq_ess_sup_restrict [has_zero β] {s : set α}
{f : α → β} (hf : 0 ≤ᵐ[μ.restrict s] f) (hs : measurable_set s) (hs_not_null : μ s ≠ 0) :
ess_sup (s.indicator f) μ = ess_sup f (μ.restrict s) :=
begin
refine le_antisymm _ (Limsup_le_Limsup_of_le (map_restrict_ae_le_map_indicator_ae hs)
(by is_bounded_default) (by is_bounded_default)),
refine Limsup_le_Limsup (by is_bounded_default) (by is_bounded_default) (λ c h_restrict_le, _),
rw eventually_map at h_restrict_le ⊢,
rw ae_restrict_iff' hs at h_restrict_le,
have hc : 0 ≤ c,
{ rsuffices ⟨x, hx⟩ : ∃ x, 0 ≤ f x ∧ f x ≤ c, from hx.1.trans hx.2,
refine frequently.exists _,
{ exact μ.ae, },
rw [eventually_le, ae_restrict_iff' hs] at hf,
have hs' : ∃ᵐ x ∂μ, x ∈ s,
{ contrapose! hs_not_null,
rw [not_frequently, ae_iff] at hs_not_null,
suffices : {a : α | ¬a ∉ s} = s, by rwa ← this,
simp, },
refine hs'.mp (hf.mp (h_restrict_le.mono (λ x hxs_imp_c hxf_nonneg hxs, _))),
rw pi.zero_apply at hxf_nonneg,
exact ⟨hxf_nonneg hxs, hxs_imp_c hxs⟩, },
refine h_restrict_le.mono (λ x hxc, _),
by_cases hxs : x ∈ s,
{ simpa [hxs] using hxc hxs, },
{ simpa [hxs] using hc, },
end
end complete_linear_order
namespace ennreal
variables {f : α → ℝ≥0∞}
lemma ae_le_ess_sup (f : α → ℝ≥0∞) : ∀ᵐ y ∂μ, f y ≤ ess_sup f μ :=
eventually_le_limsup f
@[simp] lemma ess_sup_eq_zero_iff : ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 :=
limsup_eq_zero_iff
lemma ess_sup_const_mul {a : ℝ≥0∞} : ess_sup (λ (x : α), a * (f x)) μ = a * ess_sup f μ :=
limsup_const_mul
lemma ess_sup_mul_le (f g : α → ℝ≥0∞) : ess_sup (f * g) μ ≤ ess_sup f μ * ess_sup g μ :=
limsup_mul_le f g
lemma ess_sup_add_le (f g : α → ℝ≥0∞) : ess_sup (f + g) μ ≤ ess_sup f μ + ess_sup g μ :=
limsup_add_le f g
lemma ess_sup_liminf_le {ι} [countable ι] [linear_order ι] (f : ι → α → ℝ≥0∞) :
ess_sup (λ x, at_top.liminf (λ n, f n x)) μ ≤ at_top.liminf (λ n, ess_sup (λ x, f n x) μ) :=
by { simp_rw ess_sup, exact ennreal.limsup_liminf_le_liminf_limsup (λ a b, f b a), }
lemma coe_ess_sup {f : α → ℝ≥0} (hf : is_bounded_under (≤) μ.ae f) :
(↑(ess_sup f μ) : ℝ≥0∞) = ess_sup (λ x, f x) μ :=
(ennreal.coe_Inf $ by exact hf).trans $ eq_of_forall_le_iff $ λ r,
by simp [ess_sup, limsup, Limsup, eventually_map, ennreal.forall_ennreal]
end ennreal
|
5ebd1a01d7e0c5ef15e2788ea320067d27881829 | bb31430994044506fa42fd667e2d556327e18dfe | /src/group_theory/perm/support.lean | f8aac0b2bf1e768f3737372f6872642d05c185ea | [
"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 | 20,953 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Aaron Anderson, Yakov Pechersky
-/
import data.finset.card
import data.fintype.basic
import group_theory.perm.basic
/-!
# Support of a permutation
## Main definitions
In the following, `f g : equiv.perm α`.
* `equiv.perm.disjoint`: two permutations `f` and `g` are `disjoint` if every element is fixed
either by `f`, or by `g`.
Equivalently, `f` and `g` are `disjoint` iff their `support` are disjoint.
* `equiv.perm.is_swap`: `f = swap x y` for `x ≠ y`.
* `equiv.perm.support`: the elements `x : α` that are not fixed by `f`.
-/
open equiv finset
namespace equiv.perm
variables {α : Type*}
section disjoint
/-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e.,
every element is fixed either by `f`, or by `g`. -/
def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x
variables {f g h : perm α}
@[symm] lemma disjoint.symm : disjoint f g → disjoint g f :=
by simp only [disjoint, or.comm, imp_self]
lemma disjoint.symmetric : symmetric (@disjoint α) :=
λ _ _, disjoint.symm
instance : is_symm (perm α) disjoint := ⟨disjoint.symmetric⟩
lemma disjoint_comm : disjoint f g ↔ disjoint g f :=
⟨disjoint.symm, disjoint.symm⟩
lemma disjoint.commute (h : disjoint f g) : commute f g :=
equiv.ext $ λ x, (h x).elim
(λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg])
(λ hg, by simp [mul_apply, hf, g.injective hg]))
(λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg])
(λ hf, by simp [mul_apply, hf, hg]))
@[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl
@[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl
lemma disjoint_iff_eq_or_eq : disjoint f g ↔ ∀ (x : α), f x = x ∨ g x = x := iff.rfl
@[simp] lemma disjoint_refl_iff : disjoint f f ↔ f = 1 :=
begin
refine ⟨λ h, _, λ h, h.symm ▸ disjoint_one_left 1⟩,
ext x,
cases h x with hx hx;
simp [hx]
end
lemma disjoint.inv_left (h : disjoint f g) : disjoint f⁻¹ g :=
begin
intro x,
rw [inv_eq_iff_eq, eq_comm],
exact h x
end
lemma disjoint.inv_right (h : disjoint f g) : disjoint f g⁻¹ :=
h.symm.inv_left.symm
@[simp] lemma disjoint_inv_left_iff : disjoint f⁻¹ g ↔ disjoint f g :=
begin
refine ⟨λ h, _, disjoint.inv_left⟩,
convert h.inv_left,
exact (inv_inv _).symm
end
@[simp] lemma disjoint_inv_right_iff : disjoint f g⁻¹ ↔ disjoint f g :=
by rw [disjoint_comm, disjoint_inv_left_iff, disjoint_comm]
lemma disjoint.mul_left (H1 : disjoint f h) (H2 : disjoint g h) :
disjoint (f * g) h :=
λ x, by cases H1 x; cases H2 x; simp *
lemma disjoint.mul_right (H1 : disjoint f g) (H2 : disjoint f h) :
disjoint f (g * h) :=
by { rw disjoint_comm, exact H1.symm.mul_left H2.symm }
lemma disjoint_prod_right (l : list (perm α))
(h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod :=
begin
induction l with g l ih,
{ exact disjoint_one_right _ },
{ rw list.prod_cons,
exact (h _ (list.mem_cons_self _ _)).mul_right (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) }
end
lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint)
(hp : l₁ ~ l₂) : l₁.prod = l₂.prod :=
hp.prod_eq' $ hl.imp $ λ f g, disjoint.commute
lemma nodup_of_pairwise_disjoint {l : list (perm α)} (h1 : (1 : perm α) ∉ l)
(h2 : l.pairwise disjoint) : l.nodup :=
begin
refine list.pairwise.imp_of_mem _ h2,
rintros σ - h_mem - h_disjoint rfl,
suffices : σ = 1,
{ rw this at h_mem,
exact h1 h_mem },
exact ext (λ a, (or_self _).mp (h_disjoint a)),
end
lemma pow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) :
∀ n : ℕ, (f ^ n) x = x
| 0 := rfl
| (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self]
lemma zpow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) :
∀ n : ℤ, (f ^ n) x = x
| (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n
| -[1+ n] := by rw [zpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx]
lemma pow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) :
∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x
| 0 := or.inl rfl
| (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim
(λ h, or.inr (by rw [pow_succ, mul_apply, h]))
(λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx]))
lemma zpow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) :
∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x
| (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n
| -[1+ n] := by { rw [zpow_neg_succ_of_nat, inv_eq_iff_eq, ← f.injective.eq_iff, ← mul_apply,
← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm],
exact pow_apply_eq_of_apply_apply_eq_self hffx _ }
lemma disjoint.mul_apply_eq_iff {σ τ : perm α} (hστ : disjoint σ τ) {a : α} :
(σ * τ) a = a ↔ σ a = a ∧ τ a = a :=
begin
refine ⟨λ h, _, λ h, by rw [mul_apply, h.2, h.1]⟩,
cases hστ a with hσ hτ,
{ exact ⟨hσ, σ.injective (h.trans hσ.symm)⟩ },
{ exact ⟨(congr_arg σ hτ).symm.trans h, hτ⟩ },
end
lemma disjoint.mul_eq_one_iff {σ τ : perm α} (hστ : disjoint σ τ) :
σ * τ = 1 ↔ σ = 1 ∧ τ = 1 :=
by simp_rw [ext_iff, one_apply, hστ.mul_apply_eq_iff, forall_and_distrib]
lemma disjoint.zpow_disjoint_zpow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℤ) :
disjoint (σ ^ m) (τ ^ n) :=
λ x, or.imp (λ h, zpow_apply_eq_self_of_apply_eq_self h m)
(λ h, zpow_apply_eq_self_of_apply_eq_self h n) (hστ x)
lemma disjoint.pow_disjoint_pow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℕ) :
disjoint (σ ^ m) (τ ^ n) :=
hστ.zpow_disjoint_zpow m n
end disjoint
section is_swap
variable [decidable_eq α]
/-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/
def is_swap (f : perm α) : Prop := ∃ x y, x ≠ y ∧ f = swap x y
@[simp] lemma of_subtype_swap_eq {p : α → Prop} [decidable_pred p]
(x y : subtype p) :
(equiv.swap x y).of_subtype = equiv.swap ↑x ↑y :=
equiv.ext $ λ z, begin
by_cases hz : p z,
{ rw [swap_apply_def, of_subtype_apply_of_mem _ hz],
split_ifs with hzx hzy,
{ simp_rw [hzx, subtype.coe_eta, swap_apply_left], },
{ simp_rw [hzy, subtype.coe_eta, swap_apply_right], },
{ rw swap_apply_of_ne_of_ne, refl,
intro h, apply hzx, rw ← h, refl,
intro h, apply hzy, rw ← h, refl, } },
{ rw [of_subtype_apply_of_not_mem _ hz, swap_apply_of_ne_of_ne],
intro h, apply hz, rw h, exact subtype.prop x,
intro h, apply hz, rw h, exact subtype.prop y, }
end
lemma is_swap.of_subtype_is_swap {p : α → Prop} [decidable_pred p]
{f : perm (subtype p)} (h : f.is_swap) : (of_subtype f).is_swap :=
let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in
⟨x, y, by { simp only [ne.def] at hxy, exact hxy.1 },
by { simp only [hxy.2, of_subtype_swap_eq], refl, }⟩
lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α}
(hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x :=
begin
simp only [swap_apply_def, mul_apply, f.injective.eq_iff] at *,
by_cases h : f y = x,
{ split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * },
{ split_ifs at hy; cc }
end
end is_swap
section support
section set
variables (p q : perm α)
lemma set_support_inv_eq :
{x | p⁻¹ x ≠ x} = {x | p x ≠ x} :=
begin
ext x,
simp only [set.mem_set_of_eq, ne.def],
rw [inv_def, symm_apply_eq, eq_comm]
end
lemma set_support_apply_mem {p : perm α} {a : α} :
p a ∈ {x | p x ≠ x} ↔ a ∈ {x | p x ≠ x} :=
by simp
lemma set_support_zpow_subset (n : ℤ) :
{x | (p ^ n) x ≠ x} ⊆ {x | p x ≠ x} :=
begin
intros x,
simp only [set.mem_set_of_eq, ne.def],
intros hx H,
simpa [zpow_apply_eq_self_of_apply_eq_self H] using hx
end
lemma set_support_mul_subset :
{x | (p * q) x ≠ x} ⊆ {x | p x ≠ x} ∪ {x | q x ≠ x} :=
begin
intro x,
simp only [perm.coe_mul, function.comp_app, ne.def, set.mem_union, set.mem_set_of_eq],
by_cases hq : q x = x;
simp [hq]
end
end set
variables [decidable_eq α] [fintype α] {f g : perm α}
/-- The `finset` of nonfixed points of a permutation. -/
def support (f : perm α) : finset α := univ.filter (λ x, f x ≠ x)
@[simp] lemma mem_support {x : α} : x ∈ f.support ↔ f x ≠ x :=
by rw [support, mem_filter, and_iff_right (mem_univ x)]
lemma not_mem_support {x : α} : x ∉ f.support ↔ f x = x := by simp
lemma coe_support_eq_set_support (f : perm α) :
(f.support : set α) = {x | f x ≠ x} :=
by { ext, simp }
@[simp] lemma support_eq_empty_iff {σ : perm α} : σ.support = ∅ ↔ σ = 1 :=
by simp_rw [finset.ext_iff, mem_support, finset.not_mem_empty, iff_false, not_not,
equiv.perm.ext_iff, one_apply]
@[simp] lemma support_one : (1 : perm α).support = ∅ :=
by rw support_eq_empty_iff
@[simp] lemma support_refl : support (equiv.refl α) = ∅ := support_one
lemma support_congr (h : f.support ⊆ g.support)
(h' : ∀ x ∈ g.support, f x = g x) : f = g :=
begin
ext x,
by_cases hx : x ∈ g.support,
{ exact h' x hx },
{ rw [not_mem_support.mp hx, ←not_mem_support],
exact λ H, hx (h H) }
end
lemma support_mul_le (f g : perm α) :
(f * g).support ≤ f.support ⊔ g.support :=
λ x, begin
rw [sup_eq_union, mem_union, mem_support, mem_support,
mem_support, mul_apply, ←not_and_distrib, not_imp_not],
rintro ⟨hf, hg⟩,
rw [hg, hf]
end
lemma exists_mem_support_of_mem_support_prod {l : list (perm α)} {x : α}
(hx : x ∈ l.prod.support) :
∃ f : perm α, f ∈ l ∧ x ∈ f.support :=
begin
contrapose! hx,
simp_rw [mem_support, not_not] at hx ⊢,
induction l with f l ih generalizing hx,
{ refl },
{ rw [list.prod_cons, mul_apply, ih (λ g hg, hx g (or.inr hg)), hx f (or.inl rfl)] },
end
lemma support_pow_le (σ : perm α) (n : ℕ) :
(σ ^ n).support ≤ σ.support :=
λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (pow_apply_eq_self_of_apply_eq_self h2 n))
@[simp] lemma support_inv (σ : perm α) : support (σ⁻¹) = σ.support :=
by simp_rw [finset.ext_iff, mem_support, not_iff_not,
(inv_eq_iff_eq).trans eq_comm, iff_self, imp_true_iff]
@[simp]
lemma apply_mem_support {x : α} :
f x ∈ f.support ↔ x ∈ f.support :=
by rw [mem_support, mem_support, ne.def, ne.def, not_iff_not, apply_eq_iff_eq]
@[simp]
lemma pow_apply_mem_support {n : ℕ} {x : α} :
(f ^ n) x ∈ f.support ↔ x ∈ f.support :=
begin
induction n with n ih,
{ refl },
rw [pow_succ, perm.mul_apply, apply_mem_support, ih]
end
@[simp]
lemma zpow_apply_mem_support {n : ℤ} {x : α} :
(f ^ n) x ∈ f.support ↔ x ∈ f.support :=
begin
cases n,
{ rw [int.of_nat_eq_coe, zpow_coe_nat, pow_apply_mem_support] },
{ rw [zpow_neg_succ_of_nat, ← support_inv, ← inv_pow, pow_apply_mem_support] }
end
lemma pow_eq_on_of_mem_support (h : ∀ (x ∈ f.support ∩ g.support), f x = g x)
(k : ℕ) : ∀ (x ∈ f.support ∩ g.support), (f ^ k) x = (g ^ k) x :=
begin
induction k with k hk,
{ simp },
{ intros x hx,
rw [pow_succ', mul_apply, pow_succ', mul_apply, h _ hx, hk],
rwa [mem_inter, apply_mem_support, ←h _ hx, apply_mem_support, ←mem_inter] }
end
lemma disjoint_iff_disjoint_support :
disjoint f g ↔ _root_.disjoint f.support g.support :=
by simp [disjoint_iff_eq_or_eq, disjoint_iff, finset.ext_iff, not_and_distrib]
lemma disjoint.disjoint_support (h : disjoint f g) :
_root_.disjoint f.support g.support :=
disjoint_iff_disjoint_support.1 h
lemma disjoint.support_mul (h : disjoint f g) :
(f * g).support = f.support ∪ g.support :=
begin
refine le_antisymm (support_mul_le _ _) (λ a, _),
rw [mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not],
exact (h a).elim (λ hf h, ⟨hf, f.apply_eq_iff_eq.mp (h.trans hf.symm)⟩)
(λ hg h, ⟨(congr_arg f hg).symm.trans h, hg⟩),
end
lemma support_prod_of_pairwise_disjoint (l : list (perm α)) (h : l.pairwise disjoint) :
l.prod.support = (l.map support).foldr (⊔) ⊥ :=
begin
induction l with hd tl hl,
{ simp },
{ rw [list.pairwise_cons] at h,
have : disjoint hd tl.prod := disjoint_prod_right _ h.left,
simp [this.support_mul, hl h.right] }
end
lemma support_prod_le (l : list (perm α)) :
l.prod.support ≤ (l.map support).foldr (⊔) ⊥ :=
begin
induction l with hd tl hl,
{ simp },
{ rw [list.prod_cons, list.map_cons, list.foldr_cons],
refine (support_mul_le hd tl.prod).trans _,
exact sup_le_sup le_rfl hl }
end
lemma support_zpow_le (σ : perm α) (n : ℤ) :
(σ ^ n).support ≤ σ.support :=
λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (zpow_apply_eq_self_of_apply_eq_self h2 n))
@[simp] lemma support_swap {x y : α} (h : x ≠ y) : support (swap x y) = {x, y} :=
begin
ext z,
by_cases hx : z = x,
any_goals { simpa [hx] using h.symm },
by_cases hy : z = y;
{ simp [swap_apply_of_ne_of_ne, hx, hy]; cc }
end
lemma support_swap_iff (x y : α) :
support (swap x y) = {x, y} ↔ x ≠ y :=
begin
refine ⟨λ h H, _, support_swap⟩,
subst H,
simp only [swap_self, support_refl, pair_eq_singleton] at h,
have : x ∈ ∅,
{ rw h,
exact mem_singleton.mpr rfl },
simpa
end
lemma support_swap_mul_swap {x y z : α} (h : list.nodup [x, y, z]) :
support (swap x y * swap y z) = {x, y, z} :=
begin
simp only [list.not_mem_nil, and_true, list.mem_cons_iff, not_false_iff, list.nodup_cons,
list.mem_singleton, and_self, list.nodup_nil] at h,
push_neg at h,
apply le_antisymm,
{ convert support_mul_le _ _,
rw [support_swap h.left.left, support_swap h.right],
ext,
simp [or.comm, or.left_comm] },
{ intro,
simp only [mem_insert, mem_singleton],
rintro (rfl | rfl | rfl | _);
simp [swap_apply_of_ne_of_ne, h.left.left, h.left.left.symm, h.left.right, h.left.right.symm,
h.right.symm] }
end
lemma support_swap_mul_ge_support_diff (f : perm α) (x y : α) :
f.support \ {x, y} ≤ (swap x y * f).support :=
begin
intro,
simp only [and_imp, perm.coe_mul, function.comp_app, ne.def, mem_support, mem_insert, mem_sdiff,
mem_singleton],
push_neg,
rintro ha ⟨hx, hy⟩ H,
rw [swap_apply_eq_iff, swap_apply_of_ne_of_ne hx hy] at H,
exact ha H
end
lemma support_swap_mul_eq (f : perm α) (x : α) (h : f (f x) ≠ x) :
(swap x (f x) * f).support = f.support \ {x} :=
begin
by_cases hx : f x = x,
{ simp [hx, sdiff_singleton_eq_erase, not_mem_support.mpr hx, erase_eq_of_not_mem] },
ext z,
by_cases hzx : z = x,
{ simp [hzx] },
by_cases hzf : z = f x,
{ simp [hzf, hx, h, swap_apply_of_ne_of_ne], },
by_cases hzfx : f z = x,
{ simp [ne.symm hzx, hzx, ne.symm hzf, hzfx] },
{ simp [ne.symm hzx, hzx, ne.symm hzf, hzfx, f.injective.ne hzx, swap_apply_of_ne_of_ne] }
end
lemma mem_support_swap_mul_imp_mem_support_ne {x y : α}
(hy : y ∈ support (swap x (f x) * f)) : y ∈ support f ∧ y ≠ x :=
begin
simp only [mem_support, swap_apply_def, mul_apply, f.injective.eq_iff] at *,
by_cases h : f y = x,
{ split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * },
{ split_ifs at hy; cc }
end
lemma disjoint.mem_imp (h : disjoint f g) {x : α} (hx : x ∈ f.support) :
x ∉ g.support :=
disjoint_left.mp h.disjoint_support hx
lemma eq_on_support_mem_disjoint {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) :
∀ (x ∈ f.support), f x = l.prod x :=
begin
induction l with hd tl IH,
{ simpa using h },
{ intros x hx,
rw list.pairwise_cons at hl,
rw list.mem_cons_iff at h,
rcases h with rfl|h,
{ rw [list.prod_cons, mul_apply, not_mem_support.mp
((disjoint_prod_right tl hl.left).mem_imp hx)] },
{ rw [list.prod_cons, mul_apply, ←IH h hl.right _ hx, eq_comm, ←not_mem_support],
refine (hl.left _ h).symm.mem_imp _,
simpa using hx } }
end
lemma disjoint.mono {x y : perm α} (h : disjoint f g)
(hf : x.support ≤ f.support) (hg : y.support ≤ g.support) :
disjoint x y :=
begin
rw disjoint_iff_disjoint_support at h ⊢,
exact h.mono hf hg,
end
lemma support_le_prod_of_mem {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) :
f.support ≤ l.prod.support :=
begin
intros x hx,
rwa [mem_support, ←eq_on_support_mem_disjoint h hl _ hx, ←mem_support],
end
section extend_domain
variables {β : Type*} [decidable_eq β] [fintype β] {p : β → Prop} [decidable_pred p]
@[simp]
lemma support_extend_domain (f : α ≃ subtype p) {g : perm α} :
support (g.extend_domain f) = g.support.map f.as_embedding :=
begin
ext b,
simp only [exists_prop, function.embedding.coe_fn_mk, to_embedding_apply, mem_map, ne.def,
function.embedding.trans_apply, mem_support],
by_cases pb : p b,
{ rw [extend_domain_apply_subtype _ _ pb],
split,
{ rintro h,
refine ⟨f.symm ⟨b, pb⟩, _, by simp⟩,
contrapose! h,
simp [h] },
{ rintro ⟨a, ha, hb⟩,
contrapose! ha,
obtain rfl : a = f.symm ⟨b, pb⟩,
{ rw eq_symm_apply,
exact subtype.coe_injective hb },
rw eq_symm_apply,
exact subtype.coe_injective ha } },
{ rw [extend_domain_apply_not_subtype _ _ pb],
simp only [not_exists, false_iff, not_and, eq_self_iff_true, not_true],
rintros a ha rfl,
exact pb (subtype.prop _) }
end
lemma card_support_extend_domain (f : α ≃ subtype p) {g : perm α} :
(g.extend_domain f).support.card = g.support.card :=
by simp
end extend_domain
section card
@[simp]
lemma card_support_eq_zero {f : perm α} :
f.support.card = 0 ↔ f = 1 :=
by rw [finset.card_eq_zero, support_eq_empty_iff]
lemma one_lt_card_support_of_ne_one {f : perm α} (h : f ≠ 1) :
1 < f.support.card :=
begin
simp_rw [one_lt_card_iff, mem_support, ←not_or_distrib],
contrapose! h,
ext a,
specialize h (f a) a,
rwa [apply_eq_iff_eq, or_self, or_self] at h,
end
lemma card_support_ne_one (f : perm α) : f.support.card ≠ 1 :=
begin
by_cases h : f = 1,
{ exact ne_of_eq_of_ne (card_support_eq_zero.mpr h) zero_ne_one },
{ exact ne_of_gt (one_lt_card_support_of_ne_one h) },
end
@[simp] lemma card_support_le_one {f : perm α} : f.support.card ≤ 1 ↔ f = 1 :=
by rw [le_iff_lt_or_eq, nat.lt_succ_iff, le_zero_iff, card_support_eq_zero,
or_iff_not_imp_right, imp_iff_right f.card_support_ne_one]
lemma two_le_card_support_of_ne_one {f : perm α} (h : f ≠ 1) :
2 ≤ f.support.card :=
one_lt_card_support_of_ne_one h
lemma card_support_swap_mul {f : perm α} {x : α}
(hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card :=
finset.card_lt_card
⟨λ z hz, (mem_support_swap_mul_imp_mem_support_ne hz).left,
λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩
lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 :=
show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩,
from congr_arg card $ by simp [support_swap hxy, *, finset.ext_iff]
@[simp]
lemma card_support_eq_two {f : perm α} : f.support.card = 2 ↔ is_swap f :=
begin
split; intro h,
{ obtain ⟨x, t, hmem, hins, ht⟩ := card_eq_succ.1 h,
obtain ⟨y, rfl⟩ := card_eq_one.1 ht,
rw mem_singleton at hmem,
refine ⟨x, y, hmem, _⟩,
ext a,
have key : ∀ b, f b ≠ b ↔ _ := λ b, by rw [←mem_support, ←hins, mem_insert, mem_singleton],
by_cases ha : f a = a,
{ have ha' := not_or_distrib.mp (mt (key a).mpr (not_not.mpr ha)),
rw [ha, swap_apply_of_ne_of_ne ha'.1 ha'.2] },
{ have ha' := (key (f a)).mp (mt f.apply_eq_iff_eq.mp ha),
obtain rfl | rfl := ((key a).mp ha),
{ rw [or.resolve_left ha' ha, swap_apply_left] },
{ rw [or.resolve_right ha' ha, swap_apply_right] } } },
{ obtain ⟨x, y, hxy, rfl⟩ := h,
exact card_support_swap hxy }
end
lemma disjoint.card_support_mul (h : disjoint f g) :
(f * g).support.card = f.support.card + g.support.card :=
begin
rw ←finset.card_disjoint_union,
{ congr,
ext,
simp [h.support_mul] },
{ simpa using h.disjoint_support }
end
lemma card_support_prod_list_of_pairwise_disjoint {l : list (perm α)}
(h : l.pairwise disjoint) :
l.prod.support.card = (l.map (finset.card ∘ support)).sum :=
begin
induction l with a t ih,
{ exact card_support_eq_zero.mpr rfl, },
{ obtain ⟨ha, ht⟩ := list.pairwise_cons.1 h,
rw [list.prod_cons, list.map_cons, list.sum_cons, ←ih ht],
exact (disjoint_prod_right _ ha).card_support_mul }
end
end card
end support
@[simp] lemma support_subtype_perm [decidable_eq α] {s : finset α} (f : perm α) (h) :
(f.subtype_perm h : perm {x // x ∈ s}).support = s.attach.filter (λ x, f x ≠ x) :=
by { ext, simp [subtype.ext_iff] }
end equiv.perm
|
a8c58ddd084f8c1e012a7af9c911b77337e509ce | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/buffer/parser/numeral.lean | 050b505ee8b8f2cee2d682ec2ae2e7c19e4145d1 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,207 | lean | /-
Copyright (c) 2020 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import data.buffer.parser.basic
/-!
# Numeral parsers
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file expands on the existing `nat : parser ℕ` to provide parsers into any type `α` that
can be represented by a numeral, which relies on `α` having a 0, 1, and addition operation.
There are also convenience parsers that ensure that the numeral parsed in is not larger than
the cardinality of the type `α` , if it is known that `fintype α`. Additionally, there are
convenience parsers that parse in starting from "1", which can be useful for positive ordinals;
or parser from a given character or character range.
## Main definitions
* `parser.numeral` : The parser which uses `nat.cast`
to map the result of `parser.nat` to the desired `α`
* `parser.numeral.of_fintype` : The parser which `guard`s to make sure the parsed
numeral is within the cardinality of the target `fintype` type `α`.
## Implementation details
When the `parser.numeral` or related parsers are invoked, the desired type is provided explicitly.
In many cases, it can be inferred, so one can write, for example
```lean
def get_fin : string → fin 5 :=
sum.elim (λ _, 0) id ∘ parser.run_string (parser.numeral.of_fintype _)
```
In the definitions of the parsers (except for `parser.numeral`), there is an
explicit `nat.bin_cast` instead an explicit or implicit `nat.cast`.
-/
open parser parse_result
namespace parser
variables (α : Type) [has_zero α] [has_one α] [has_add α]
/--
Parse a string of digits as a numeral while casting it to target type `α`.
-/
@[derive [mono, bounded, prog]]
def numeral : parser α :=
nat.bin_cast <$> nat
/--
Parse a string of digits as a numeral while casting it to target type `α`,
which has a `[fintype α]` constraint. The parser ensures that the numeral parsed in
is within the cardinality of the type `α`.
-/
@[derive [mono, bounded, prog]]
def numeral.of_fintype [fintype α] : parser α :=
do
c ← nat,
decorate_error (sformat!"<numeral less than {to_string (fintype.card α)}>")
(guard (c < fintype.card α)),
pure $ nat.bin_cast c
/--
Parse a string of digits as a numeral while casting it to target type `α`. The parsing starts
at "1", so `"1"` is parsed in as `nat.cast 0`. Providing `"0"` to the parser causes a failure.
-/
@[derive [mono, bounded, prog]]
def numeral.from_one : parser α :=
do
c ← nat,
decorate_error ("<positive numeral>")
(guard (0 < c)),
pure $ nat.bin_cast (c - 1)
/--
Parse a string of digits as a numeral while casting it to target type `α`,
which has a `[fintype α]` constraint. The parser ensures that the numeral parsed in
is within the cardinality of the type `α`. The parsing starts
at "1", so `"1"` is parsed in as `nat.cast 0`. Providing `"0"` to the parser causes a failure.
-/
@[derive [mono, bounded, prog]]
def numeral.from_one.of_fintype [fintype α] : parser α :=
do
c ← nat,
decorate_error (sformat!"<positive numeral less than or equal to {to_string (fintype.card α)}>")
(guard (0 < c ∧ c ≤ fintype.card α)),
pure $ nat.bin_cast (c - 1)
/--
Parse a character as a numeral while casting it to target type `α`,
The parser ensures that the character parsed in is within the bounds set by `fromc` and `toc`,
and subtracts the value of `fromc` from the parsed in character.
-/
@[derive [mono, bounded, err_static, step]]
def numeral.char (fromc toc : char) : parser α :=
do
c ← decorate_error
(sformat!"<char between '{fromc.to_string}' to '{toc.to_string}' inclusively>")
(sat (λ c, fromc ≤ c ∧ c ≤ toc)),
pure $ nat.bin_cast (c.to_nat - fromc.to_nat)
/--
Parse a character as a numeral while casting it to target type `α`,
which has a `[fintype α]` constraint.
The parser ensures that the character parsed in is greater or equal to `fromc` and
and subtracts the value of `fromc` from the parsed in character. There is also a check
that the resulting value is within the cardinality of the type `α`.
-/
@[derive [mono, bounded, err_static, step]]
def numeral.char.of_fintype [fintype α] (fromc : char) : parser α :=
do
c ← decorate_error
(sformat!"<char from '{fromc.to_string}' to '
{ (char.of_nat (fromc.to_nat + fintype.card α - 1)).to_string}' inclusively>")
(sat (λ c, fromc ≤ c ∧ c.to_nat - fintype.card α < fromc.to_nat)),
pure $ nat.bin_cast (c.to_nat - fromc.to_nat)
/-! ## Specific numeral types -/
/--
Matches an integer, like `43` or `-2`.
Large numbers may cause performance issues, so don't run this parser on untrusted input.
-/
def int : parser int :=
(coe <$> nat) <|> (ch '-' >> has_neg.neg <$> coe <$> nat)
/--
Matches an rational number, like `43/1` or `-2/3`.
Requires that the negation is in the numerator,
and that both a numerator and denominator are provided (e.g. will not match `43`).
Large numbers may cause performance issues, so don't run this parser on untrusted input.
-/
def rat : parser rat :=
(λ x y, ↑x / ↑y) <$> int <*> (ch '/' >> nat)
end parser
|
7ec309fa4cbedc4c75f2eaf86e76f180d0028d63 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Meta/Check.lean | ea05f613ae953b4b1d3162af0347505c4a4d8d93 | [
"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 | 7,226 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.InferType
/-!
This is not the Kernel type checker, but an auxiliary method for checking
whether terms produced by tactics and `isDefEq` are type correct.
-/
namespace Lean.Meta
private def ensureType (e : Expr) : MetaM Unit := do
discard <| getLevel e
def throwLetTypeMismatchMessage {α} (fvarId : FVarId) : MetaM α := do
let lctx ← getLCtx
match lctx.find? fvarId with
| some (LocalDecl.ldecl _ _ _ t v _) => do
let vType ← inferType v
throwError "invalid let declaration, term{indentExpr v}\nhas type{indentExpr vType}\nbut is expected to have type{indentExpr t}"
| _ => unreachable!
private def checkConstant (constName : Name) (us : List Level) : MetaM Unit := do
let cinfo ← getConstInfo constName
unless us.length == cinfo.levelParams.length do
throwIncorrectNumberOfLevels constName us
private def getFunctionDomain (f : Expr) : MetaM (Expr × BinderInfo) := do
let fType ← inferType f
let fType ← whnfD fType
match fType with
| Expr.forallE _ d _ c => return (d, c)
| _ => throwFunctionExpected f
/--
Given two expressions `a` and `b`, this method tries to annotate terms with `pp.explicit := true` to
expose "implicit" differences. For example, suppose `a` and `b` are of the form
```lean
@HashMap Nat Nat eqInst hasInst1
@HashMap Nat Nat eqInst hasInst2
```
By default, the pretty printer formats both of them as `HashMap Nat Nat`.
So, counterintuitive error messages such as
```lean
error: application type mismatch
HashMap.insert m
argument
m
has type
HashMap Nat Nat
but is expected to have type
HashMap Nat Nat
```
would be produced.
By adding `pp.explicit := true`, we can generate the more informative error
```lean
error: application type mismatch
HashMap.insert m
argument
m
has type
@HashMap Nat Nat eqInst hasInst1
but is expected to have type
@HashMap Nat Nat eqInst hasInst2
```
Remark: this method implements a simple heuristic, we should extend it as we find other counterintuitive
error messages.
-/
partial def addPPExplicitToExposeDiff (a b : Expr) : MetaM (Expr × Expr) := do
if (← getOptions).getBool `pp.all false || (← getOptions).getBool `pp.explicit false then
return (a, b)
else
visit (← instantiateMVars a) (← instantiateMVars b)
where
visit (a b : Expr) : MetaM (Expr × Expr) := do
try
if !a.isApp || !b.isApp then
return (a, b)
else if a.getAppNumArgs != b.getAppNumArgs then
return (a, b)
else if not (← isDefEq a.getAppFn b.getAppFn) then
return (a, b)
else
let fType ← inferType a.getAppFn
forallBoundedTelescope fType a.getAppNumArgs fun xs _ => do
let mut as := a.getAppArgs
let mut bs := b.getAppArgs
if let some (as', bs') ← hasExplicitDiff? xs as bs then
return (mkAppN a.getAppFn as', mkAppN b.getAppFn bs')
else
for i in [:as.size] do
unless (← isDefEq as[i]! bs[i]!) do
let (ai, bi) ← visit as[i]! bs[i]!
as := as.set! i ai
bs := bs.set! i bi
let a := mkAppN a.getAppFn as
let b := mkAppN b.getAppFn bs
return (a.setAppPPExplicit, b.setAppPPExplicit)
catch _ =>
return (a, b)
hasExplicitDiff? (xs as bs : Array Expr) : MetaM (Option (Array Expr × Array Expr)) := do
for i in [:xs.size] do
let localDecl ← xs[i]!.fvarId!.getDecl
if localDecl.binderInfo.isExplicit then
unless (← isDefEq as[i]! bs[i]!) do
let (ai, bi) ← visit as[i]! bs[i]!
return some (as.set! i ai, bs.set! i bi)
return none
/--
Return error message "has type{givenType}\nbut is expected to have type{expectedType}"
-/
def mkHasTypeButIsExpectedMsg (givenType expectedType : Expr) : MetaM MessageData := do
try
let givenTypeType ← inferType givenType
let expectedTypeType ← inferType expectedType
let (givenType, expectedType) ← addPPExplicitToExposeDiff givenType expectedType
let (givenTypeType, expectedTypeType) ← addPPExplicitToExposeDiff givenTypeType expectedTypeType
return m!"has type{indentD m!"{givenType} : {givenTypeType}"}\nbut is expected to have type{indentD m!"{expectedType} : {expectedTypeType}"}"
catch _ =>
let (givenType, expectedType) ← addPPExplicitToExposeDiff givenType expectedType
return m!"has type{indentExpr givenType}\nbut is expected to have type{indentExpr expectedType}"
def throwAppTypeMismatch (f a : Expr) : MetaM α := do
let (expectedType, binfo) ← getFunctionDomain f
let mut e := mkApp f a
unless binfo.isExplicit do
e := e.setAppPPExplicit
let aType ← inferType a
throwError "application type mismatch{indentExpr e}\nargument{indentExpr a}\n{← mkHasTypeButIsExpectedMsg aType expectedType}"
def checkApp (f a : Expr) : MetaM Unit := do
let fType ← inferType f
let fType ← whnf fType
match fType with
| Expr.forallE _ d _ _ =>
let aType ← inferType a
unless (← isDefEq d aType) do
throwAppTypeMismatch f a
| _ => throwFunctionExpected (mkApp f a)
private partial def checkAux (e : Expr) : MetaM Unit := do
check e |>.run
where
check (e : Expr) : MonadCacheT ExprStructEq Unit MetaM Unit :=
checkCache { val := e : ExprStructEq } fun _ => do
match e with
| .forallE .. => checkForall e
| .lam .. => checkLambdaLet e
| .letE .. => checkLambdaLet e
| .const c lvls => checkConstant c lvls
| .app f a => check f; check a; checkApp f a
| .mdata _ e => check e
| .proj _ _ e => check e
| _ => return ()
checkLambdaLet (e : Expr) : MonadCacheT ExprStructEq Unit MetaM Unit :=
lambdaLetTelescope e fun xs b => do
xs.forM fun x => do
let xDecl ← getFVarLocalDecl x;
match xDecl with
| .cdecl (type := t) .. =>
ensureType t
check t
| .ldecl (type := t) (value := v) .. =>
ensureType t
check t
let vType ← inferType v
unless (← isDefEq t vType) do throwLetTypeMismatchMessage x.fvarId!
check v
check b
checkForall (e : Expr) : MonadCacheT ExprStructEq Unit MetaM Unit :=
forallTelescope e fun xs b => do
xs.forM fun x => do
let xDecl ← getFVarLocalDecl x
ensureType xDecl.type
check xDecl.type
ensureType b
check b
/--
Throw an exception if `e` is not type correct.
-/
def check (e : Expr) : MetaM Unit :=
withTraceNode `Meta.check (fun res =>
return m!"{if res.isOk then checkEmoji else crossEmoji} {e}") do
try
withTransparency TransparencyMode.all $ checkAux e
catch ex =>
trace[Meta.check] ex.toMessageData
throw ex
/--
Return true if `e` is type correct.
-/
def isTypeCorrect (e : Expr) : MetaM Bool := do
try
check e
pure true
catch _ =>
pure false
builtin_initialize
registerTraceClass `Meta.check
end Lean.Meta
|
e9d7bc0144d9238de443ebc6ea71a06f4637bc84 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/alg_rw.lean | a88d36ec3590381d4249de282c4a33338aab1809 | [
"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 | 315 | lean | import algebra.group
open algebra
section
variable {A : Type}
variable [s : comm_monoid A]
include s
theorem one_mul_one : 1 * 1 = (1:A) :=
mul_one 1
end
section
variable {A : Type}
variable [s : comm_group A]
include s
theorem one_mul_one2 : (one : A) * 1 = 1 :=
by rewrite one_mul_one
end
|
95128fbbc9964894f023c05e96d17318f70b2eff | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/normed_space/hahn_banach/extension.lean | 80ab1610e970db4f132aafbeb33cbb9489dc7086 | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 6,772 | lean | /-
Copyright (c) 2020 Yury Kudryashov All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Heather Macbeth
-/
import analysis.convex.cone.basic
import analysis.normed_space.is_R_or_C
import analysis.normed_space.extend
/-!
# Extension Hahn-Banach theorem
In this file we prove the analytic Hahn-Banach theorem. For any continuous linear function on a
subspace, we can extend it to a function on the entire space without changing its norm.
We prove
* `real.exists_extension_norm_eq`: Hahn-Banach theorem for continuous linear functions on normed
spaces over `ℝ`.
* `exists_extension_norm_eq`: Hahn-Banach theorem for continuous linear functions on normed spaces
over `ℝ` or `ℂ`.
In order to state and prove the corollaries uniformly, we prove the statements for a field `𝕜`
satisfying `is_R_or_C 𝕜`.
In this setting, `exists_dual_vector` states that, for any nonzero `x`, there exists a continuous
linear form `g` of norm `1` with `g x = ‖x‖` (where the norm has to be interpreted as an element
of `𝕜`).
-/
universes u v
namespace real
variables {E : Type*} [seminormed_add_comm_group E] [normed_space ℝ E]
/-- Hahn-Banach theorem for continuous linear functions over `ℝ`. -/
theorem exists_extension_norm_eq (p : subspace ℝ E) (f : p →L[ℝ] ℝ) :
∃ g : E →L[ℝ] ℝ, (∀ x : p, g x = f x) ∧ ‖g‖ = ‖f‖ :=
begin
rcases exists_extension_of_le_sublinear ⟨p, f⟩ (λ x, ‖f‖ * ‖x‖)
(λ c hc x, by simp only [norm_smul c x, real.norm_eq_abs, abs_of_pos hc, mul_left_comm])
(λ x y, _) (λ x, le_trans (le_abs_self _) (f.le_op_norm _))
with ⟨g, g_eq, g_le⟩,
set g' := g.mk_continuous (‖f‖)
(λ x, abs_le.2 ⟨neg_le.1 $ g.map_neg x ▸ norm_neg x ▸ g_le (-x), g_le x⟩),
{ refine ⟨g', g_eq, _⟩,
{ apply le_antisymm (g.mk_continuous_norm_le (norm_nonneg f) _),
refine f.op_norm_le_bound (norm_nonneg _) (λ x, _),
dsimp at g_eq,
rw ← g_eq,
apply g'.le_op_norm } },
{ simp only [← mul_add],
exact mul_le_mul_of_nonneg_left (norm_add_le x y) (norm_nonneg f) }
end
end real
section is_R_or_C
open is_R_or_C
variables {𝕜 : Type*} [is_R_or_C 𝕜] {F : Type*} [seminormed_add_comm_group F] [normed_space 𝕜 F]
/-- Hahn-Banach theorem for continuous linear functions over `𝕜` satisyfing `is_R_or_C 𝕜`. -/
theorem exists_extension_norm_eq (p : subspace 𝕜 F) (f : p →L[𝕜] 𝕜) :
∃ g : F →L[𝕜] 𝕜, (∀ x : p, g x = f x) ∧ ‖g‖ = ‖f‖ :=
begin
letI : module ℝ F := restrict_scalars.module ℝ 𝕜 F,
letI : is_scalar_tower ℝ 𝕜 F := restrict_scalars.is_scalar_tower _ _ _,
letI : normed_space ℝ F := normed_space.restrict_scalars _ 𝕜 _,
-- Let `fr: p →L[ℝ] ℝ` be the real part of `f`.
let fr := re_clm.comp (f.restrict_scalars ℝ),
have fr_apply : ∀ x, fr x = re (f x), by { assume x, refl },
-- Use the real version to get a norm-preserving extension of `fr`, which
-- we'll call `g : F →L[ℝ] ℝ`.
rcases real.exists_extension_norm_eq (p.restrict_scalars ℝ) fr with ⟨g, ⟨hextends, hnormeq⟩⟩,
-- Now `g` can be extended to the `F →L[𝕜] 𝕜` we need.
refine ⟨g.extend_to_𝕜, _⟩,
-- It is an extension of `f`.
have h : ∀ x : p, g.extend_to_𝕜 x = f x,
{ assume x,
rw [continuous_linear_map.extend_to_𝕜_apply, ←submodule.coe_smul, hextends, hextends],
have : (fr x : 𝕜) - I * ↑(fr (I • x)) = (re (f x) : 𝕜) - (I : 𝕜) * (re (f ((I : 𝕜) • x))),
by refl,
rw this,
apply ext,
{ simp only [add_zero, algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add,
zero_sub, I_im', zero_mul, of_real_re, eq_self_iff_true, sub_zero, mul_neg,
of_real_neg, mul_re, mul_zero, sub_neg_eq_add, continuous_linear_map.map_smul] },
{ simp only [algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im',
zero_mul, of_real_re, mul_neg, mul_im, zero_add, of_real_neg, mul_re,
sub_neg_eq_add, continuous_linear_map.map_smul] } },
-- And we derive the equality of the norms by bounding on both sides.
refine ⟨h, le_antisymm _ _⟩,
{ calc ‖g.extend_to_𝕜‖
= ‖g‖ : g.norm_extend_to_𝕜
... = ‖fr‖ : hnormeq
... ≤ ‖re_clm‖ * ‖f‖ : continuous_linear_map.op_norm_comp_le _ _
... = ‖f‖ : by rw [re_clm_norm, one_mul] },
{ exact f.op_norm_le_bound g.extend_to_𝕜.op_norm_nonneg (λ x, h x ▸ g.extend_to_𝕜.le_op_norm x) }
end
end is_R_or_C
section dual_vector
variables (𝕜 : Type v) [is_R_or_C 𝕜]
variables {E : Type u} [normed_add_comm_group E] [normed_space 𝕜 E]
open continuous_linear_equiv submodule
open_locale classical
lemma coord_norm' {x : E} (h : x ≠ 0) : ‖(‖x‖ : 𝕜) • coord 𝕜 x h‖ = 1 :=
by rw [norm_smul, is_R_or_C.norm_coe_norm, coord_norm, mul_inv_cancel (mt norm_eq_zero.mp h)]
/-- Corollary of Hahn-Banach. Given a nonzero element `x` of a normed space, there exists an
element of the dual space, of norm `1`, whose value on `x` is `‖x‖`. -/
theorem exists_dual_vector (x : E) (h : x ≠ 0) : ∃ g : E →L[𝕜] 𝕜, ‖g‖ = 1 ∧ g x = ‖x‖ :=
begin
let p : submodule 𝕜 E := 𝕜 ∙ x,
let f := (‖x‖ : 𝕜) • coord 𝕜 x h,
obtain ⟨g, hg⟩ := exists_extension_norm_eq p f,
refine ⟨g, _, _⟩,
{ rw [hg.2, coord_norm'] },
{ calc g x = g (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw coe_mk
... = ((‖x‖ : 𝕜) • coord 𝕜 x h) (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw ← hg.1
... = ‖x‖ : by simp }
end
/-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, and choosing
the dual element arbitrarily when `x = 0`. -/
theorem exists_dual_vector' [nontrivial E] (x : E) :
∃ g : E →L[𝕜] 𝕜, ‖g‖ = 1 ∧ g x = ‖x‖ :=
begin
by_cases hx : x = 0,
{ obtain ⟨y, hy⟩ := exists_ne (0 : E),
obtain ⟨g, hg⟩ : ∃ g : E →L[𝕜] 𝕜, ‖g‖ = 1 ∧ g y = ‖y‖ := exists_dual_vector 𝕜 y hy,
refine ⟨g, hg.left, _⟩,
simp [hx] },
{ exact exists_dual_vector 𝕜 x hx }
end
/-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, but only ensuring that
the dual element has norm at most `1` (this can not be improved for the trivial
vector space). -/
theorem exists_dual_vector'' (x : E) :
∃ g : E →L[𝕜] 𝕜, ‖g‖ ≤ 1 ∧ g x = ‖x‖ :=
begin
by_cases hx : x = 0,
{ refine ⟨0, by simp, _⟩,
symmetry,
simp [hx], },
{ rcases exists_dual_vector 𝕜 x hx with ⟨g, g_norm, g_eq⟩,
exact ⟨g, g_norm.le, g_eq⟩ }
end
end dual_vector
|
eae035da58d12f126c89743cad7743addc3e5d27 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/1951.lean | ca6c1364e6b339640929097f132d6b72530ba86e | [
"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 | 175 | lean | instance my_pow : has_pow ℕ ℕ :=
⟨λ x n, nat.rec_on n 1 (λ _ ih, ih * x)⟩
#eval 2 ^ (3 ^ 2)
#eval 2 ^ 3 ^ 2
example (a b c : nat) : a ^ (b ^ c) = a ^ b ^ c :=
rfl
|
9a40058b3cf76e9d83a589814993cd2bb5702d19 | 61c3861020ef87c6c325fc3c3dcbabf5d6b07985 | /arity.lean | cab58afee0292d078ff6206c12abcd6e7ffc98cc | [
"Apache-2.0"
] | permissive | jonas-frey/hott3 | a623be2959e8a713c03fa1b0f34bf76a561dfa87 | a944051b4eb5919bdc70978ee15fcbb48a824811 | refs/heads/master | 1,628,408,720,559 | 1,510,267,042,000 | 1,510,267,042,000 | 106,760,764 | 0 | 0 | null | 1,507,856,238,000 | 1,507,856,238,000 | null | UTF-8 | Lean | false | false | 12,464 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about functions with multiple arguments
-/
import .init
universes u v w
hott_theory
namespace hott
variables {A : Type _} {U : Type _} {V : Type _} {W : Type _}
{X : Type _} {Y : Type _} {Z : Type _}
{B : A → Type _} {C : Πa, B a → Type _} {D : Πa b, C a b → Type _}
{E : Πa b c, D a b c → Type _} {F : Πa b c d, E a b c d → Type _}
{G : Πa b c d e, F a b c d e → Type _} {H : Πa b c d e f, G a b c d e f → Type _}
variables {a a' : A} {u u' : U} {v v' : V} {w w' : W} {x x' x'' : X} {y y' : Y} {z z' : Z}
{b : B a} {b' : B a'}
{c : C a b} {c' : C a' b'}
{d : D a b c} {d' : D a' b' c'}
{e : E a b c d} {e' : E a' b' c' d'}
{ff : F a b c d e} {f' : F a' b' c' d' e'}
{g : G a b c d e ff} {g' : G a' b' c' d' e' f'}
{h : H a b c d e ff g} {h' : H a' b' c' d' e' f' g'}
namespace eq
/-
Naming convention:
The theorem which states how to construct an path between two function applications is
api₀i₁...iₙ.
Here i₀, ... iₙ are digits, n is the arity of the function(s),
and iⱼ specifies the dimension of the path between the jᵗʰ argument
(i₀ specifies the dimension of the path between the functions).
A value iⱼ ≡ 0 means that the jᵗʰ arguments are definitionaly equal
The functions are non-dependent, except when the theorem name contains trailing zeroes
(where the function is dependent only in the arguments where it doesn't result in any
transports in the theorem statement).
For the fully-dependent versions (except that the conclusion doesn't contain a transport)
we write
apdi₀i₁...iₙ.
For versions where only some arguments depend on some other arguments,
or for versions with transport in the conclusion (like apdt), we don't have a
consistent naming scheme (yet).
We don't prove each theorem systematically, but prove only the ones which we actually need.
-/
@[hott, reducible] def homotopy2 (f g : Πa b, C a b) : Type _ :=
Πa b, f a b = g a b
@[hott, reducible] def homotopy3 (f g : Πa b c, D a b c) : Type _ :=
Πa b c, f a b c = g a b c
@[hott, reducible] def homotopy4 (f g : Πa b c d, E a b c d) : Type _ :=
Πa b c d, f a b c d = g a b c d
infix ` ~2 `:50 := homotopy2
infix ` ~3 `:50 := homotopy3
infix ` ~4 `:50 := homotopy4
@[refl] def homotopy2.refl (f : Π a b, C a b) : f ~2 f := by intros _ _; refl
@[refl] def homotopy3.refl (f : Π a b c, D a b c) : f ~3 f := by intros _ _ _; refl
@[refl] def homotopy4.refl (f : Π a b c d, E a b c d) : f ~4 f := by intros _ _ _ _; refl
@[hott] def ap0111 (f : U → V → W → X) (Hu : u = u') (Hv : v = v') (Hw : w = w')
: f u v w = f u' v' w' :=
by induction Hu; hsimp *
@[hott] def ap01111 (f : U → V → W → X → Y)
(Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x')
: f u v w x = f u' v' w' x' :=
by induction Hu; hsimp *
@[hott] def ap011111 (f : U → V → W → X → Y → Z)
(Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y')
: f u v w x y = f u' v' w' x' y' :=
by induction Hu; hsimp *
@[hott] def ap0111111 (f : U → V → W → X → Y → Z → A)
(Hu : u = u') (Hv : v = v') (Hw : w = w') (Hx : x = x') (Hy : y = y') (Hz : z = z')
: f u v w x y z = f u' v' w' x' y' z' :=
by induction Hu; hsimp *
@[hott, elab_simple] def ap010 (f : X → Πa, B a) (Hx : x = x') : f x ~ f x' :=
λ b, ap (λa, f a b) Hx
@[hott] def ap0100 (f : X → Πa b, C a b) (Hx : x = x') : f x ~2 f x' :=
by intros; induction Hx; reflexivity
@[hott] def ap01000 (f : X → Πa b c, D a b c) (Hx : x = x') : f x ~3 f x' :=
by intros; induction Hx; reflexivity
@[hott] def apdt011 (f : Πa, B a → Z) (Ha : a = a') (Hb : transport B Ha b = b')
: f a b = f a' b' :=
by induction Ha; induction Hb; reflexivity
@[hott] def apdt0111 (f : Πa b, C a b → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apdt011 C Ha Hb) c = c')
: f a b c = f a' b' c' :=
by induction Ha; induction Hb; induction Hc; reflexivity
@[hott] def apdt01111 (f : Πa b c, D a b c → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d')
: f a b c d = f a' b' c' d' :=
by induction Ha; induction Hb; induction Hc; induction Hd; reflexivity
@[hott] def apdt011111 (f : Πa b c d, E a b c d → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d')
(He : cast (apdt01111 E Ha Hb Hc Hd) e = e')
: f a b c d e = f a' b' c' d' e' :=
by induction Ha; induction Hb; induction Hc; induction Hd; induction He; reflexivity
@[hott] def apdt0111111 (f : Πa b c d e, F a b c d e → Z) (Ha : a = a') (Hb : transport B Ha b = b')
(Hc : cast (apdt011 C Ha Hb) c = c') (Hd : cast (apdt0111 D Ha Hb Hc) d = d')
(He : cast (apdt01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apdt011111 F Ha Hb Hc Hd He) ff = f')
: f a b c d e ff = f a' b' c' d' e' f' :=
begin induction Ha, induction Hb, induction Hc, induction Hd, induction He, induction Hf, reflexivity end
-- @[hott] def apd0111111 (f : Πa b c d e ff, G a b c d e ff → Z) (Ha : a = a') (Hb : transport B Ha b = b')
-- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
-- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f')
-- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g')
-- : f a b c d e ff g = f a' b' c' d' e' f' g' :=
-- by induction Ha; induction Hb; induction Hc; induction Hd; induction He; induction Hf; induction Hg; reflexivity
-- @[hott] def apd01111111 (f : Πa b c d e ff g, G a b c d e ff g → Z) (Ha : a = a') (Hb : transport B Ha b = b')
-- (Hc : cast (apd011 C Ha Hb) c = c') (Hd : cast (apd0111 D Ha Hb Hc) d = d')
-- (He : cast (apd01111 E Ha Hb Hc Hd) e = e') (Hf : cast (apd011111 F Ha Hb Hc Hd He) ff = f')
-- (Hg : cast (apd0111111 G Ha Hb Hc Hd He Hf) g = g') (Hh : cast (apd01111111 H Ha Hb Hc Hd He Hf Hg) h = h')
-- : f a b c d e ff g h = f a' b' c' d' e' f' g' h' :=
-- by induction Ha; induction Hb; induction Hc; induction Hd; induction He; induction Hf; induction Hg; induction Hh; reflexivity
@[hott] def apd100 {f g : Πa b, C a b} (p : f = g) : f ~2 g :=
λa b, apd10 (apd10 p a) b
@[hott] def apd1000 {f g : Πa b c, D a b c} (p : f = g) : f ~3 g :=
λa b c, apd100 (apd10 p a) b c
/- some properties of these variants of ap -/
-- we only prove what we currently need
@[hott] def ap010_con (f : X → Πa, B a) (p : x = x') (q : x' = x'') :
ap010 f (p ⬝ q) a = ap010 f p a ⬝ ap010 f q a :=
eq.rec_on q (eq.rec_on p idp)
@[hott] def ap010_ap (f : X → Πa, B a) (g : Y → X) (p : y = y') :
ap010 f (ap g p) a = (ap010 (f ∘ g) p) a :=
eq.rec_on p idp
@[hott] def ap_eq_ap010 {A B C : Type _} (f : A → B → C) {a a' : A} (p : a = a') (b : B) :
ap (λa, f a b) p = ap010 f p b :=
idp
@[hott] def ap011_idp {A B C : Type _} (f : A → B → C) {a a' : A} (p : a = a') (b : B) :
ap011 f p idp = ap010 f p b :=
by reflexivity
@[hott] def ap011_flip {A B C : Type _} (f : A → B → C) {a a' : A} {b b' : B} (p : a = a') (q : b = b') :
ap011 f p q = (ap011 (λb a, f a b) q) p :=
by induction q; induction p; reflexivity
/- the following theorems are function extentionality for functions with multiple arguments -/
@[hott] def eq_of_homotopy2 {f g : Πa b, C a b} (H : f ~2 g) : f = g :=
eq_of_homotopy (λa, eq_of_homotopy (H a))
@[hott] def eq_of_homotopy3 {f g : Πa b c, D a b c} (H : f ~3 g) : f = g :=
eq_of_homotopy (λa, eq_of_homotopy2 (H a))
@[hott] def eq_of_homotopy2_id (f : Πa b, C a b)
: eq_of_homotopy2 (λa b, idpath (f a b)) = idpath f :=
begin
transitivity eq_of_homotopy (λ a, idpath (f a)),
{apply (ap eq_of_homotopy), apply eq_of_homotopy, intro, apply eq_of_homotopy_idp},
apply eq_of_homotopy_idp
end
@[hott] def eq_of_homotopy3_id (f : Πa b c, D a b c)
: eq_of_homotopy3 (λa b c, idpath (f a b c)) = idpath f :=
begin
transitivity _,
{apply (ap eq_of_homotopy), apply eq_of_homotopy, intro, apply eq_of_homotopy2_id},
apply eq_of_homotopy_idp
end
@[hott] def eq_of_homotopy2_inv {f g : Πa b, C a b} (H : f ~2 g)
: eq_of_homotopy2 (λa b, (H a b).inverse) = (eq_of_homotopy2 H)⁻¹ :=
begin
transitivity,
{dsimp [eq_of_homotopy2], apply ap, apply eq_of_homotopy, intro, apply eq_of_homotopy_inv},
{apply eq_of_homotopy_inv}
end
@[hott] def eq_of_homotopy3_inv {f g : Πa b c, D a b c} (H : f ~3 g)
: eq_of_homotopy3 (λa b c, (H a b c).inverse) = (eq_of_homotopy3 H)⁻¹ :=
begin
transitivity,
{dsimp [eq_of_homotopy3], apply ap, apply eq_of_homotopy, intro, apply eq_of_homotopy2_inv},
{apply eq_of_homotopy_inv}
end
@[hott] def eq_of_homotopy2_con {f g h : Πa b, C a b} (H1 : f ~2 g) (H2 : g ~2 h)
: eq_of_homotopy2 (λa b, H1 a b ⬝ H2 a b) = eq_of_homotopy2 H1 ⬝ eq_of_homotopy2 H2 :=
begin
transitivity,
{dsimp [eq_of_homotopy2], apply ap, apply eq_of_homotopy, intro, apply eq_of_homotopy_con},
{apply eq_of_homotopy_con}
end
@[hott] def eq_of_homotopy3_con {f g h : Πa b c, D a b c} (H1 : f ~3 g) (H2 : g ~3 h)
: eq_of_homotopy3 (λa b c, H1 a b c ⬝ H2 a b c) = eq_of_homotopy3 H1 ⬝ eq_of_homotopy3 H2 :=
begin
transitivity,
{dsimp [eq_of_homotopy3], apply ap, apply eq_of_homotopy, intro, apply eq_of_homotopy2_con},
{apply eq_of_homotopy_con}
end
end eq
open hott.eq equiv is_equiv
namespace funext
@[hott, instance] def is_equiv_apd100 (f g : Πa b, C a b)
: is_equiv (@apd100 A B C f g) :=
adjointify _
eq_of_homotopy2
begin
intro H, dsimp [apd100, eq_of_homotopy2],
apply eq_of_homotopy, intro a,
apply concat, apply (ap (λx : Π a, f a = g a, apd10 (x a))), apply (right_inv apd10),
apply (right_inv apd10)
end
begin
intro p, induction p, apply eq_of_homotopy2_id
end
@[hott, instance] def is_equiv_apd1000 (f g : Πa b c, D a b c)
: is_equiv (@apd1000 A B C D f g) :=
adjointify _
eq_of_homotopy3
begin
intro H, dsimp,
apply eq_of_homotopy, intro a,
transitivity apd100 (eq_of_homotopy2 (H a)),
{apply ap (λ x : Π a, f a = g a, apd100 (x a)),
apply right_inv apd10},
apply right_inv apd100
end
begin
intro p, induction p, apply eq_of_homotopy3_id
end
end funext
namespace eq
open funext
local attribute [instance] funext.is_equiv_apd100
@[hott] protected def homotopy2.rec_on {f g : Πa b, C a b} {P : (f ~2 g) → Type _}
(p : f ~2 g) (H : Π(q : f = g), P (apd100 q)) : P p :=
right_inv apd100 p ▸ H (eq_of_homotopy2 p)
@[hott] protected def homotopy3.rec_on {f g : Πa b c, D a b c} {P : (f ~3 g) → Type _}
(p : f ~3 g) (H : Π(q : f = g), P (apd1000 q)) : P p :=
right_inv apd1000 p ▸ H (eq_of_homotopy3 p)
@[hott] def eq_equiv_homotopy2 (f g : Πa b, C a b) : (f = g) ≃ (f ~2 g) :=
equiv.mk apd100 (by apply_instance)
@[hott] def eq_equiv_homotopy3 (f g : Πa b c, D a b c) : (f = g) ≃ (f ~3 g) :=
equiv.mk apd1000 (by apply_instance)
@[hott] def apd10_ap (f : X → Πa, B a) (p : x = x')
: apd10 (ap f p) = ap010 f p :=
eq.rec_on p idp
@[hott] def eq_of_homotopy_ap010 (f : X → Πa, B a) (p : x = x')
: eq_of_homotopy (ap010 f p) = ap f p :=
inv_eq_of_eq (apd10_ap _ _)⁻¹
@[hott] def ap_eq_ap_of_homotopy {f : X → Πa, B a} {p q : x = x'} (H : ap010 f p ~ ap010 f q)
: ap f p = ap f q :=
calc
ap f p = eq_of_homotopy (ap010 f p) : by symmetry; apply eq_of_homotopy_ap010
... = eq_of_homotopy (ap010 f q) : by apply ap; apply eq_of_homotopy H
... = ap f q : by apply eq_of_homotopy_ap010
end eq
end hott |
3a1a7466f34dab2754d05c813d8b06c553b48214 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/nat/cast.lean | 8283d0dab77b1cb6088e62576592fe305f173634 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 8,724 | lean | /-
Copyright (c) 2014 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.nat.basic
import data.nat.cast.defs
import algebra.group.pi
import tactic.pi_instances
import data.sum.basic
/-!
# Cast of natural numbers (additional theorems)
This file proves additional properties about the *canonical* homomorphism from
the natural numbers into an additive monoid with a one (`nat.cast`).
## Main declarations
* `cast_add_monoid_hom`: `cast` bundled as an `add_monoid_hom`.
* `cast_ring_hom`: `cast` bundled as a `ring_hom`.
-/
variables {α β : Type*}
namespace nat
/-- `coe : ℕ → α` as an `add_monoid_hom`. -/
def cast_add_monoid_hom (α : Type*) [add_monoid_with_one α] : ℕ →+ α :=
{ to_fun := coe,
map_add' := cast_add,
map_zero' := cast_zero }
@[simp] lemma coe_cast_add_monoid_hom [add_monoid_with_one α] :
(cast_add_monoid_hom α : ℕ → α) = coe := rfl
@[simp, norm_cast] theorem cast_mul [non_assoc_semiring α] (m n : ℕ) :
((m * n : ℕ) : α) = m * n :=
by induction n; simp [mul_succ, mul_add, *]
/-- `coe : ℕ → α` as a `ring_hom` -/
def cast_ring_hom (α : Type*) [non_assoc_semiring α] : ℕ →+* α :=
{ to_fun := coe,
map_one' := cast_one,
map_mul' := cast_mul,
.. cast_add_monoid_hom α }
@[simp] lemma coe_cast_ring_hom [non_assoc_semiring α] : (cast_ring_hom α : ℕ → α) = coe := rfl
lemma cast_commute [non_assoc_semiring α] (n : ℕ) (x : α) : commute ↑n x :=
nat.rec_on n (by rw [cast_zero]; exact commute.zero_left x) $
λ n ihn, by rw [cast_succ]; exact ihn.add_left (commute.one_left x)
lemma cast_comm [non_assoc_semiring α] (n : ℕ) (x : α) : (n : α) * x = x * n :=
(cast_commute n x).eq
lemma commute_cast [non_assoc_semiring α] (x : α) (n : ℕ) : commute x n :=
(n.cast_commute x).symm
section
variables [ordered_semiring α]
@[mono] theorem mono_cast : monotone (coe : ℕ → α) :=
monotone_nat_of_le_succ $ λ n, by rw [nat.cast_succ]; exact le_add_of_nonneg_right zero_le_one
@[simp] theorem cast_nonneg (n : ℕ) : 0 ≤ (n : α) :=
@nat.cast_zero α _ ▸ mono_cast (nat.zero_le n)
variable [nontrivial α]
@[simp, norm_cast] theorem cast_le {m n : ℕ} :
(m : α) ≤ n ↔ m ≤ n :=
strict_mono_cast.le_iff_le
@[simp, norm_cast, mono] theorem cast_lt {m n : ℕ} : (m : α) < n ↔ m < n :=
strict_mono_cast.lt_iff_lt
@[simp] theorem cast_pos {n : ℕ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
lemma cast_add_one_pos (n : ℕ) : 0 < (n : α) + 1 :=
add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one
@[simp, norm_cast] theorem one_lt_cast {n : ℕ} : 1 < (n : α) ↔ 1 < n :=
by rw [← cast_one, cast_lt]
@[simp, norm_cast] theorem one_le_cast {n : ℕ} : 1 ≤ (n : α) ↔ 1 ≤ n :=
by rw [← cast_one, cast_le]
@[simp, norm_cast] theorem cast_lt_one {n : ℕ} : (n : α) < 1 ↔ n = 0 :=
by rw [← cast_one, cast_lt, lt_succ_iff, le_zero_iff]
@[simp, norm_cast] theorem cast_le_one {n : ℕ} : (n : α) ≤ 1 ↔ n ≤ 1 :=
by rw [← cast_one, cast_le]
end
@[simp, norm_cast] theorem cast_min [linear_ordered_semiring α] {a b : ℕ} :
(↑(min a b) : α) = min a b :=
(@mono_cast α _).map_min
@[simp, norm_cast] theorem cast_max [linear_ordered_semiring α] {a b : ℕ} :
(↑(max a b) : α) = max a b :=
(@mono_cast α _).map_max
@[simp, norm_cast] theorem abs_cast [linear_ordered_ring α] (a : ℕ) :
|(a : α)| = a :=
abs_of_nonneg (cast_nonneg a)
lemma coe_nat_dvd [semiring α] {m n : ℕ} (h : m ∣ n) : (m : α) ∣ (n : α) :=
map_dvd (nat.cast_ring_hom α) h
alias coe_nat_dvd ← _root_.has_dvd.dvd.nat_cast
end nat
namespace prod
variables [add_monoid_with_one α] [add_monoid_with_one β]
instance : add_monoid_with_one (α × β) :=
{ nat_cast := λ n, (n, n),
nat_cast_zero := congr_arg2 prod.mk nat.cast_zero nat.cast_zero,
nat_cast_succ := λ n, congr_arg2 prod.mk (nat.cast_succ _) (nat.cast_succ _),
.. prod.add_monoid, .. prod.has_one }
@[simp] lemma fst_nat_cast (n : ℕ) : (n : α × β).fst = n :=
by induction n; simp *
@[simp] lemma snd_nat_cast (n : ℕ) : (n : α × β).snd = n :=
by induction n; simp *
end prod
section add_monoid_hom_class
variables {A B F : Type*} [add_monoid_with_one B]
lemma ext_nat' [add_monoid A] [add_monoid_hom_class F ℕ A] (f g : F) (h : f 1 = g 1) : f = g :=
fun_like.ext f g $ begin
apply nat.rec,
{ simp only [nat.nat_zero_eq_zero, map_zero] },
simp [nat.succ_eq_add_one, h] {contextual := tt}
end
@[ext] lemma add_monoid_hom.ext_nat [add_monoid A] : ∀ {f g : ℕ →+ A}, ∀ h : f 1 = g 1, f = g :=
ext_nat'
variable [add_monoid_with_one A]
-- these versions are primed so that the `ring_hom_class` versions aren't
lemma eq_nat_cast' [add_monoid_hom_class F ℕ A] (f : F) (h1 : f 1 = 1) :
∀ n : ℕ, f n = n
| 0 := by simp
| (n+1) := by rw [map_add, h1, eq_nat_cast' n, nat.cast_add_one]
lemma map_nat_cast' {A} [add_monoid_with_one A] [add_monoid_hom_class F A B]
(f : F) (h : f 1 = 1) : ∀ (n : ℕ), f n = n
| 0 := by simp
| (n+1) := by rw [nat.cast_add, map_add, nat.cast_add, map_nat_cast', nat.cast_one, h, nat.cast_one]
end add_monoid_hom_class
section monoid_with_zero_hom_class
variables {A F : Type*} [mul_zero_one_class A]
/-- If two `monoid_with_zero_hom`s agree on the positive naturals they are equal. -/
theorem ext_nat'' [monoid_with_zero_hom_class F ℕ A] (f g : F)
(h_pos : ∀ {n : ℕ}, 0 < n → f n = g n) : f = g :=
begin
apply fun_like.ext,
rintro (_|n),
{ simp },
exact h_pos n.succ_pos
end
@[ext] theorem monoid_with_zero_hom.ext_nat :
∀ {f g : ℕ →*₀ A}, (∀ {n : ℕ}, 0 < n → f n = g n) → f = g := ext_nat''
end monoid_with_zero_hom_class
section ring_hom_class
variables {R S F : Type*} [non_assoc_semiring R] [non_assoc_semiring S]
@[simp] lemma eq_nat_cast [ring_hom_class F ℕ R] (f : F) : ∀ n, f n = n :=
eq_nat_cast' f $ map_one f
@[simp] lemma map_nat_cast [ring_hom_class F R S] (f : F) : ∀ n : ℕ, f (n : R) = n :=
map_nat_cast' f $ map_one f
lemma ext_nat [ring_hom_class F ℕ R] (f g : F) : f = g :=
ext_nat' f g $ by simp only [map_one]
end ring_hom_class
namespace ring_hom
/-- This is primed to match `eq_int_cast'`. -/
lemma eq_nat_cast' {R} [non_assoc_semiring R] (f : ℕ →+* R) : f = nat.cast_ring_hom R :=
ring_hom.ext $ eq_nat_cast f
end ring_hom
@[simp, norm_cast] theorem nat.cast_id (n : ℕ) : ↑n = n :=
rfl
@[simp] lemma nat.cast_ring_hom_nat : nat.cast_ring_hom ℕ = ring_hom.id ℕ := rfl
@[simp] theorem nat.cast_with_bot (n : ℕ) :
@coe ℕ (with_bot ℕ) (@coe_to_lift _ _ nat.cast_coe) n = n := rfl
-- I don't think `ring_hom_class` is good here, because of the `subsingleton` TC slowness
instance nat.unique_ring_hom {R : Type*} [non_assoc_semiring R] : unique (ℕ →+* R) :=
{ default := nat.cast_ring_hom R, uniq := ring_hom.eq_nat_cast' }
namespace mul_opposite
variables [add_monoid_with_one α]
@[simp, norm_cast] lemma op_nat_cast (n : ℕ) : op (n : α) = n := rfl
@[simp, norm_cast] lemma unop_nat_cast (n : ℕ) : unop (n : αᵐᵒᵖ) = n := rfl
end mul_opposite
namespace pi
variables {π : α → Type*} [Π a, has_nat_cast (π a)]
instance : has_nat_cast (Π a, π a) :=
by refine_struct { .. }; tactic.pi_instance_derive_field
lemma nat_apply (n : ℕ) (a : α) : (n : Π a, π a) a = n := rfl
@[simp] lemma coe_nat (n : ℕ) : (n : Π a, π a) = λ _, n := rfl
end pi
lemma sum.elim_nat_cast_nat_cast {α β γ : Type*} [has_nat_cast γ] (n : ℕ) :
sum.elim (n : α → γ) (n : β → γ) = n :=
@sum.elim_lam_const_lam_const α β γ n
namespace pi
variables {π : α → Type*} [Π a, add_monoid_with_one (π a)]
instance : add_monoid_with_one (Π a, π a) :=
by refine_struct { .. }; tactic.pi_instance_derive_field
end pi
/-! ### Order dual -/
open order_dual
instance [h : has_nat_cast α] : has_nat_cast αᵒᵈ := h
instance [h : add_monoid_with_one α] : add_monoid_with_one αᵒᵈ := h
instance [h : add_comm_monoid_with_one α] : add_comm_monoid_with_one αᵒᵈ := h
@[simp] lemma to_dual_nat_cast [has_nat_cast α] (n : ℕ) : to_dual (n : α) = n := rfl
@[simp] lemma of_dual_nat_cast [has_nat_cast α] (n : ℕ) : (of_dual n : α) = n := rfl
/-! ### Lexicographic order -/
instance [h : has_nat_cast α] : has_nat_cast (lex α) := h
instance [h : add_monoid_with_one α] : add_monoid_with_one (lex α) := h
instance [h : add_comm_monoid_with_one α] : add_comm_monoid_with_one (lex α) := h
@[simp] lemma to_lex_nat_cast [has_nat_cast α] (n : ℕ) : to_lex (n : α) = n := rfl
@[simp] lemma of_lex_nat_cast [has_nat_cast α] (n : ℕ) : (of_lex n : α) = n := rfl
|
514dfd0ae04f9918fe53588a796542c8678b1087 | 75c54c8946bb4203e0aaf196f918424a17b0de99 | /src/compactness.lean | 5944964caa007d8af9b9c10f1be8d842e6d44c94 | [
"Apache-2.0"
] | permissive | urkud/flypitch | 261e2a45f1038130178575406df8aea78255ba77 | 2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c | refs/heads/master | 1,653,266,469,246 | 1,577,819,679,000 | 1,577,819,679,000 | 259,862,235 | 1 | 0 | Apache-2.0 | 1,588,147,244,000 | 1,588,147,244,000 | null | UTF-8 | Lean | false | false | 5,414 | lean | /-
Copyright (c) 2019 The Flypitch Project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jesse Han, Floris van Doorn
-/
import .fol
open fol set
universes u v
/-- Given an xs : list α, an x : α, a set T on α such that everything in xs which is not x is in T, return the sublist which excludes x, a proof that this list is now a subset of T, and a proof that everything in this list was not the forbidden element x. --/
def list_except {α : Type u} [decidable_eq α] (xs : list α) (x : α) (T : set α)
(h : ∀ y ∈ xs, y ≠ x → y ∈ T) :
Σ' ys : list α, ({ϕ | ϕ ∈ ys} ⊆ T ∧ (∀ y ∈ ys, y ≠ x)) ∧ (∀ y ∈ xs, y ≠ x → y ∈ ys) :=
begin
existsi xs.filter (≠ x),
refine ⟨⟨_, _⟩, _⟩,
{ intros y hy, apply h y (list.mem_of_mem_filter hy), apply list.of_mem_filter hy },
{ intros y hy, apply list.of_mem_filter hy },
{ intros y hy hxy, apply list.mem_filter_of_mem hy hxy }
end
open classical
/- Couldn't find this def in set.basic... sure it's around somewhere-/
/-- Given x ∈ f '' S, choose a lift x' in the preimage of x; return x' and a proof that x' is a lift --/
noncomputable def image_lift {α : Type u} {β : Type v} {f : α → β} {S : set α} (x ∈ f '' S) : Σ' (x' : α), x' ∈ S ∧ f x' = x :=
begin
apply psigma_of_exists, apply (set.mem_image _ _ _).mp H
end
/-- Given a list xs : list β, a set S : set α, a proof that {x | x ∈ xs} ⊆ f '' S, return a list of lifts ys : list α, a proof that ys ⊆ S and a proof that f '' ys = xs --/
noncomputable def image_lift_list {α : Type u} {β : Type v} {f : α → β} {S : set α} {xs : list β} (h_sub : {x | x ∈ xs} ⊆ f '' S) : Σ' (ys : list α), ({y' | y' ∈ ys} ⊆ S) ∧ f '' {y | y ∈ ys} = {x | x ∈ xs} :=
begin
apply psigma_of_exists,
rcases list.exists_of_to_set_subset_image h_sub with ⟨ys, hys, hys'⟩,
refine ⟨ys, hys, _⟩, subst hys', ext,
apply list.mem_map.symm
end
/-- Any proof from a set of formulas is provable from a finset of subformulas. --/
lemma proof_compactness {L : Language.{u}} {ψ : formula L} {T : set $ formula L} :
(T ⊢' ψ) → ∃Γ : finset (formula L), ↑Γ ⊢' ψ ∧ ↑Γ ⊆ T :=
begin
haveI : decidable_eq (formula L) := λx y, classical.prop_decidable _,
intro P, induction P with P, induction P,
{ exact ⟨{P_A}, ⟨axm1⟩, set.singleton_subset_iff.mpr P_h⟩ },
{ rcases P_ih with ⟨Γ, H, K⟩, refine ⟨Γ \ {P_A}, impI' $ weakening' (by simp) H, by simp [K]⟩ },
{ rcases P_ih_h₁ with ⟨Γ₁, H₁, K₁⟩, rcases P_ih_h₂ with ⟨Γ₂, H₂, K₂⟩,
refine ⟨Γ₁ ∪ Γ₂, impE' _ (weakening' (by simp) H₁) (weakening' (by simp) H₂), by simp [K₁, K₂]⟩ },
{ rcases P_ih with ⟨Γ, H, K⟩, refine ⟨Γ \ {∼P_A}, falsumE' $ weakening' (by simp) H, by simp [K]⟩ },
{ rcases P_ih with ⟨Γ, H, K⟩, rcases finset.subset_image_iff.mp K with ⟨Γ', K', hΓ⟩,
subst hΓ, simp only [finset.coe_image] at H K,
exact ⟨Γ', allI' H, K'⟩ },
{ rcases P_ih with ⟨Γ, H, K⟩, exact ⟨Γ, allE₂' H, K⟩ },
{ exact ⟨∅, ref' _ _, empty_subset _⟩ },
{ rcases P_ih_h₁ with ⟨Γ₁, H₁, K₁⟩, rcases P_ih_h₂ with ⟨Γ₂, H₂, K₂⟩,
refine ⟨Γ₁ ∪ Γ₂, subst₂' _ _ _ (weakening' (by simp) H₁) (weakening' (by simp) H₂), by simp [K₁, K₂]⟩ }
end
lemma theory_proof_compactness {L : Language} {T : Theory L} {ψ : sentence L} (hψ : T ⊢' ψ) :
∃Γ : finset (sentence L), ↑Γ ⊢' ψ ∧ ↑Γ ⊆ T :=
begin
haveI : decidable_eq (sentence L) := λx y, classical.prop_decidable _,
haveI : decidable_eq (formula L) := λx y, classical.prop_decidable _,
rcases proof_compactness hψ with ⟨Γ, H, K⟩,
rcases finset.subset_image_iff.mp K with ⟨Γ', K', hΓ⟩,
subst hΓ, simp only [finset.coe_image] at H K,
exact ⟨Γ', H, K'⟩
end
lemma theory_proof_compactness_iff {L : Language} {T : Theory L} {ψ : sentence L} :
T ⊢' ψ ↔ ∃Γ : finset (sentence L), ↑Γ ⊢' ψ ∧ ↑Γ ⊆ T :=
⟨theory_proof_compactness, λ⟨Γ, H, K⟩, weakening' (image_subset _ K) H⟩
lemma is_consistent_union {L : Language} {T₁ T₂ : Theory L} (h₁ : is_consistent T₁)
(h₂ : ∀ψ ∈ T₂, insert (∼ψ) T₁ ⊢' (⊥ : sentence L)) : is_consistent (T₁ ∪ T₂) :=
begin
haveI : decidable_eq (sentence L) := λx y, classical.prop_decidable _,
have lem : ∀(T₀ : finset (sentence L)), ↑T₀ ⊆ T₂ → is_consistent (T₁ ∪ ↑T₀),
{ refine finset.induction _ _,
{ intro hT, rw [finset.coe_empty, union_empty], exact h₁ },
{ intros ψ s hψ ih hs hT, simp [insert_subset] at hs,
apply ih hs.2, apply sprf_by_cases ψ,
{ simp at hT, exact hT },
{ apply weakening' _ (h₂ _ hs.1),
apply image_subset, apply insert_subset_insert, apply subset_union_left }}},
intro h, rcases theory_proof_compactness h with ⟨T₀, h₀, hT⟩,
have : decidable_pred (∈ T₁) := λx, classical.prop_decidable _,
let T₀' := T₀.filter (∉ T₁),
refine lem T₀' _ _,
{ intros x hx, simp [T₀'] at hx, exact (hT hx.1).resolve_left hx.2 },
{ apply weakening' _ h₀, apply image_subset, rw [←inter_union_diff (↑T₀) T₁],
apply union_subset_union, apply inter_subset_right,
intros x hx, rw [finset.mem_coe, finset.mem_filter], exact hx }
end
|
06e2daa97983277cf8e59c660dbf89ca35c14a30 | 35b83be3126daae10419b573c55e1fed009d3ae8 | /_target/deps/mathlib/data/fintype.lean | 54d80cb04b2cdbc9a358fc104ca16ed3feb26289 | [] | no_license | AHassan1024/Lean_Playground | ccb25b72029d199c0d23d002db2d32a9f2689ebc | a00b004c3a2eb9e3e863c361aa2b115260472414 | refs/heads/master | 1,586,221,905,125 | 1,544,951,310,000 | 1,544,951,310,000 | 157,934,290 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,516 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Finite types.
-/
import data.finset algebra.big_operators data.array.lemmas data.vector2
universes u v
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `fintype α` means that `α` is finite, i.e. there are only
finitely many distinct elements of type `α`. The evidence of this
is a finset `elems` (a list up to permutation without duplicates),
together with a proof that everything of type `α` is in the list. -/
class fintype (α : Type*) :=
(elems : finset α)
(complete : ∀ x : α, x ∈ elems)
namespace finset
variable [fintype α]
/-- `univ` is the universal finite set of type `finset α` implied from
the assumption `fintype α`. -/
def univ : finset α := fintype.elems α
@[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) :=
fintype.complete x
@[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ
@[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) :=
by ext; simp
theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a
theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s :=
by simp [ext]
end finset
open finset function
namespace fintype
instance decidable_pi_fintype {α} {β : α → Type*} [fintype α] [∀a, decidable_eq (β a)] :
decidable_eq (Πa, β a) :=
assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a)
(by simp [function.funext_iff, fintype.complete])
instance decidable_forall_fintype [fintype α] {p : α → Prop} [decidable_pred p] :
decidable (∀ a, p a) :=
decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp)
instance decidable_exists_fintype [fintype α] {p : α → Prop} [decidable_pred p] :
decidable (∃ a, p a) :=
decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp)
instance decidable_eq_equiv_fintype [fintype α] [decidable_eq β] :
decidable_eq (α ≃ β) :=
λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext _ _ (congr_fun h), congr_arg _⟩
instance decidable_injective_fintype [fintype α] [decidable_eq α] [decidable_eq β] :
decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance
instance decidable_surjective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] :
decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance
instance decidable_bijective_fintype [fintype α] [decidable_eq α] [fintype β] [decidable_eq β] :
decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance
/-- Construct a proof of `fintype α` from a universal multiset -/
def of_multiset [decidable_eq α] (s : multiset α)
(H : ∀ x : α, x ∈ s) : fintype α :=
⟨s.to_finset, by simpa using H⟩
/-- Construct a proof of `fintype α` from a universal list -/
def of_list [decidable_eq α] (l : list α)
(H : ∀ x : α, x ∈ l) : fintype α :=
⟨l.to_finset, by simpa using H⟩
theorem exists_univ_list (α) [fintype α] :
∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l :=
let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in
by have := and.intro univ.2 mem_univ_val;
exact ⟨_, by rwa ← e at this⟩
/-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/
def card (α) [fintype α] : ℕ := (@univ α _).card
/-- There is (computably) a bijection between `α` and `fin n` where
`n = card α`. Since it is not unique, and depends on which permutation
of the universe list is used, the bijection is wrapped in `trunc` to
preserve computability. -/
def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) :=
by unfold card finset.card; exact
quot.rec_on_subsingleton (@univ α _).1
(λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk
⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩,
λ i, l.nth_le i.1 i.2,
λ a, by simp,
λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _
(list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩)
mem_univ_val univ.2
theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) :=
by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩
instance (α : Type*) : subsingleton (fintype α) :=
⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext, h₁, h₂]⟩
protected def subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} :=
⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1),
multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩,
λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩
theorem subtype_card {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) :
@card {x // p x} (fintype.subtype s H) = s.card :=
multiset.card_pmap _ _ _
theorem card_of_subtype {p : α → Prop} (s : finset α)
(H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] :
card {x // p x} = s.card :=
by rw ← subtype_card s H; congr
/-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/
def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β :=
⟨univ.map ⟨f, H.1⟩,
λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩
/-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/
def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β :=
⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩
/-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/
def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective
theorem of_equiv_card [fintype α] (f : α ≃ β) :
@card β (of_equiv α f) = card α :=
multiset.card_map _ _
theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β :=
by rw ← of_equiv_card f; congr
theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) :=
⟨λ e, match F, G, e with ⟨⟨s, nd⟩, h⟩, ⟨⟨s', nd'⟩, h'⟩, e' := begin
change multiset.card s = multiset.card s' at e',
revert nd nd' h h' e',
refine quotient.induction_on₂ s s' (λ l₁ l₂
(nd₁ : l₁.nodup) (nd₂ : l₂.nodup)
(h₁ : ∀ x, x ∈ l₁) (h₂ : ∀ x, x ∈ l₂)
(e' : l₁.length = l₂.length), _),
haveI := classical.dec_eq α,
refine ⟨equiv.of_bijective ⟨_, _⟩⟩,
{ refine λ a, l₂.nth_le (l₁.index_of a) _,
rw ← e', exact list.index_of_lt_length.2 (h₁ a) },
{ intros a b h, simpa [h₁] using congr_arg l₁.nth
(list.nodup_iff_nth_le_inj.1 nd₂ _ _ _ _ h) },
{ have := classical.dec_eq β,
refine λ b, ⟨l₁.nth_le (l₂.index_of b) _, _⟩,
{ rw e', exact list.index_of_lt_length.2 (h₂ b) },
{ simp [nd₁] } }
end end, λ ⟨f⟩, card_congr f⟩
end fintype
instance (n : ℕ) : fintype (fin n) :=
⟨⟨list.pmap fin.mk (list.range n) (λ a, list.mem_range.1),
list.nodup_pmap (λ a _ b _, congr_arg fin.val) (list.nodup_range _)⟩,
λ ⟨m, h⟩, list.mem_pmap.2 ⟨m, list.mem_range.2 h, rfl⟩⟩
@[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n :=
by rw [fin.fintype]; simp [fintype.card, card, univ]
instance : fintype empty := ⟨∅, empty.rec _⟩
@[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl
@[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl
instance : fintype pempty := ⟨∅, pempty.rec _⟩
@[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl
@[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl
instance : fintype unit := ⟨⟨()::0, by simp⟩, λ ⟨⟩, by simp⟩
@[simp] theorem fintype.univ_unit : @univ unit _ = {()} := rfl
@[simp] theorem fintype.card_unit : fintype.card unit = 1 := rfl
instance : fintype punit := ⟨⟨punit.star::0, by simp⟩, λ ⟨⟩, by simp⟩
@[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl
@[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl
instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩
@[simp] theorem fintype.univ_bool : @univ bool _ = {ff, tt} := rfl
instance units_int.fintype : fintype (units ℤ) :=
⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩
@[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl
@[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl
def finset.insert_none (s : finset α) : finset (option α) :=
⟨none :: s.1.map some, multiset.nodup_cons.2
⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩
@[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α},
o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s
| none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h)
| (some a) := multiset.mem_cons.trans $ by simp; refl
theorem finset.some_mem_insert_none {s : finset α} {a : α} :
some a ∈ s.insert_none ↔ a ∈ s := by simp
instance {α : Type*} [fintype α] : fintype (option α) :=
⟨univ.insert_none, λ a, by simp⟩
@[simp] theorem fintype.card_option {α : Type*} [fintype α] :
fintype.card (option α) = fintype.card α + 1 :=
(multiset.card_cons _ _).trans (by rw multiset.card_map; refl)
instance {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] : fintype (sigma β) :=
⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩
@[simp] theorem fintype.card_sigma {α : Type*} (β : α → Type*)
[fintype α] [∀ a, fintype (β a)] :
fintype.card (sigma β) = univ.sum (λ a, fintype.card (β a)) :=
card_sigma _ _
instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) :=
⟨univ.product univ, λ ⟨a, b⟩, by simp⟩
@[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] :
fintype.card (α × β) = fintype.card α * fintype.card β :=
card_product _ _
def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α :=
⟨(fintype.elems (α × β)).image prod.fst,
assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩
def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β :=
⟨(fintype.elems (α × β)).image prod.snd,
assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩
instance (α : Type*) [fintype α] : fintype (ulift α) :=
fintype.of_equiv _ equiv.ulift.symm
@[simp] theorem fintype.card_ulift (α : Type*) [fintype α] :
fintype.card (ulift α) = fintype.card α :=
fintype.of_equiv_card _
instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) :=
@fintype.of_equiv _ _ (@sigma.fintype _
(λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _
(λ b, by cases b; apply ulift.fintype))
((equiv.sum_equiv_sigma_bool _ _).symm.trans
(equiv.sum_congr equiv.ulift equiv.ulift))
@[simp] theorem fintype.card_sum (α β : Type*) [fintype α] [fintype β] :
fintype.card (α ⊕ β) = fintype.card α + fintype.card β :=
by rw [sum.fintype, fintype.of_equiv_card]; simp
lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β)
(hf : function.injective f) : fintype.card α ≤ fintype.card β :=
by haveI := classical.prop_decidable; exact
finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h)
lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) :=
by rw [← fintype.card_unit, fintype.card_eq]; exact
⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.bijective.1 (subsingleton.elim _ _)⟩,
λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm,
λ _, subsingleton.elim _ _⟩⟩⟩
lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) :=
⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim,
λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩,
by simp [fintype.card_congr e]⟩
lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α :=
⟨λ h, classical.by_contradiction (λ h₁,
have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩),
lt_irrefl 0 $ by rwa this at h),
λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩
lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) :=
let n := fintype.card α in
have hn : n = fintype.card α := rfl,
match n, hn with
| 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩
| 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in
by rw [hx a, hx b],
λ _, ha ▸ le_refl _⟩
| (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial,
(λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ())
(λ _ _ _, h _ _))⟩
end
lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f :=
by haveI := classical.prop_decidable; exact
have ∀ {f : α → α}, injective f → surjective f,
from λ f hinj x,
have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _)
((card_image_of_injective univ hinj).symm ▸ le_refl _),
have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _,
exists_of_bex (mem_image.1 h₂),
⟨this,
λ hsurj, injective_of_has_left_inverse
⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse
(this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩
lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f :=
by simp [bijective, fintype.injective_iff_surjective]
lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f :=
by simp [bijective, fintype.injective_iff_surjective]
lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) :
injective f ↔ surjective f :=
have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective,
⟨λ hinj, by simpa [function.comp] using
surjective_comp e.bijective.2 (this.1 (injective_comp e.symm.bijective.1 hinj)),
λ hsurj, by simpa [function.comp] using
injective_comp e.bijective.1 (this.2 (surjective_comp e.symm.bijective.2 hsurj))⟩
instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} :=
fintype.of_list l.attach l.mem_attach
instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} :=
fintype.of_multiset s.attach s.mem_attach
instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} :=
⟨s.attach, s.mem_attach⟩
instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) :=
finset.subtype.fintype s
@[simp] lemma fintype.card_coe (s : finset α) :
fintype.card (↑s : set α) = s.card := card_attach
instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) :=
⟨if h : p then finset.singleton ⟨h⟩ else ∅, λ ⟨h⟩, by simp [h]⟩
instance Prop.fintype : fintype Prop :=
⟨⟨true::false::0, by simp [true_ne_false]⟩,
classical.cases (by simp) (by simp)⟩
def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s :=
fintype.subtype (univ.filter (∈ s)) (by simp)
instance pi.fintype {α : Type*} {β : α → Type*}
[fintype α] [decidable_eq α] [∀a, fintype (β a)] : fintype (Πa, β a) :=
@fintype.of_equiv _ _
⟨univ.pi $ λa:α, @univ (β a) _,
λ f, finset.mem_pi.2 $ λ a ha, mem_univ _⟩
⟨λ f a, f a (mem_univ _), λ f a _, f a, λ f, rfl, λ f, rfl⟩
@[simp] lemma fintype.card_pi {β : α → Type*} [fintype α] [decidable_eq α]
[f : Π a, fintype (β a)] : fintype.card (Π a, β a) = univ.prod (λ a, fintype.card (β a)) :=
by letI f' : fintype (Πa∈univ, β a) :=
⟨(univ.pi $ λa, univ), assume f, finset.mem_pi.2 $ assume a ha, mem_univ _⟩;
exact calc fintype.card (Π a, β a) = fintype.card (Π a ∈ univ, β a) : fintype.card_congr
⟨λ f a ha, f a, λ f a, f a (mem_univ a), λ _, rfl, λ _, rfl⟩
... = univ.prod (λ a, fintype.card (β a)) : finset.card_pi _ _
@[simp] lemma fintype.card_fun [fintype α] [decidable_eq α] [fintype β] :
fintype.card (α → β) = fintype.card β ^ fintype.card α :=
by rw [fintype.card_pi, finset.prod_const, nat.pow_eq_pow]; refl
instance d_array.fintype {n : ℕ} {α : fin n → Type*}
[∀n, fintype (α n)] : fintype (d_array n α) :=
fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm
instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) :=
d_array.fintype
instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) :=
fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm
instance quotient.fintype [fintype α] (s : setoid α)
[decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) :=
fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩))
instance finset.fintype [fintype α] : fintype (finset α) :=
⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩
instance subtype.fintype [fintype α] (p : α → Prop) [decidable_pred p] : fintype {x // p x} :=
set_fintype _
instance set.fintype [fintype α] [decidable_eq α] : fintype (set α) :=
pi.fintype
instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*)
[Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) :=
if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩
else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩
def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance)
| [] f := ⟦λ i, false.elim⟧
| (i::l) f := begin
refine quotient.lift_on₂ (f i (list.mem_cons_self _ _))
(quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h)))
_ _,
exact λ a l, ⟦λ j h,
if e : j = i then by rw e; exact a else
l _ (h.resolve_left e)⟧,
refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
{ subst j, exact h₁ },
{ exact h₂ _ _ }
end
theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)] :
∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧
| [] f := quotient.sound (λ i h, h.elim)
| (i::l) f := begin
simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l],
refine quotient.sound (λ j h, _),
by_cases e : j = i; simp [e],
subst j, refl
end
def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι]
{α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι,
@quotient (Π i ∈ l, α i) (by apply_instance))
finset.univ.1
(λ l, quotient.fin_choice_aux l (λ i _, f i))
(λ a b h, begin
have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)),
simp [quotient.out_eq] at this,
simp [this],
let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧,
refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)),
congr' 1, exact quotient.sound h,
end))
(λ f, ⟦λ i, f i (finset.mem_univ _)⟧)
(λ a b h, quotient.sound $ λ i, h _ _)
theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι]
{α : ι → Type*} [∀ i, setoid (α i)]
(f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
begin
let q, swap, change quotient.lift_on q _ _ = _,
have : q = ⟦λ i h, f i⟧,
{ dsimp [q],
exact quotient.induction_on
(@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) },
simp [this], exact setoid.refl _
end
@[simp, to_additive finset.sum_attach_univ]
lemma finset.prod_attach_univ [fintype α] [comm_monoid β] (f : {a : α // a ∈ @univ α _} → β) :
univ.attach.prod (λ x, f x) = univ.prod (λ x, f ⟨x, (mem_univ _)⟩) :=
prod_bij (λ x _, x.1) (λ _ _, mem_univ _) (λ _ _ , by simp) (by simp) (λ b _, ⟨⟨b, mem_univ _⟩, by simp⟩)
section equiv
open list equiv equiv.perm
variables [decidable_eq α] [decidable_eq β]
def perms_of_list : list α → list (perm α)
| [] := [1]
| (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f))
lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact
| [] := rfl
| (a :: l) := by rw [length_cons, nat.fact_succ];
simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul]
lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l
| [] f h := list.mem_singleton.2 $ equiv.ext _ _$ λ x, by simp [imp_false, *] at *
| (a::l) f h :=
if hfa : f a = a
then
mem_append_left _ $ mem_perms_of_list_of_mem
(λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx))
else
have hfa' : f (f a) ≠ f a, from mt (λ h, f.bijective.1 h) hfa,
have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l,
from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx,
have hfxa : f x ≠ f a, from mt (λ h, f.bijective.1 h) hxa,
list.mem_of_ne_of_mem hxa
(h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)),
suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f,
by simpa [perms_of_list],
(@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2
(λ hfl, ⟨f a,
if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.bijective.1 h) hfa))
else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc,
⟨swap a (f a) * f, mem_perms_of_list_of_mem this,
by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← one_def, one_mul]⟩⟩)
lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l
| [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp
| (a::l) f h :=
(mem_append.1 h).elim
(λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx))
(λ h x hx,
let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in
let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in
if hxa : x = a then by simp [hxa]
else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy
else mem_cons_of_mem _ $
mem_of_mem_perms_of_list hg₁ $
by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def];
split_ifs; cc)
lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l :=
⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩
lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup
| [] hl := by simp [perms_of_list]
| (a::l) hl :=
have hl' : l.nodup, from nodup_of_nodup_cons hl,
have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl',
have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a,
from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1),
by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact
⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_left_inj _).1) hln',
λ i j hj hij x hx₁ hx₂,
let ⟨f, hf⟩ := list.mem_map.1 hx₁ in
let ⟨g, hg⟩ := list.mem_map.1 hx₂ in
have hix : x a = nth_le l i (lt_trans hij hj),
by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left],
have hiy : x a = nth_le l j hj,
by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left],
absurd (hf.2.trans (hg.2.symm)) $
λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $
by rw [← hix, hiy]⟩,
λ f hf₁ hf₂,
let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in
let ⟨g, hg⟩ := list.mem_map.1 hx' in
have hgxa : g⁻¹ x = a, from f.bijective.1 $
by rw [hmeml hf₁, ← hg.2]; simp,
have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx),
(list.nodup_cons.1 hl).1 $
hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩
def perms_of_finset (s : finset α) : finset (perm α) :=
quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩)
(λ a b hab, hfunext (congr_arg _ (quotient.sound hab))
(λ ha hb _, heq_of_eq $ finset.ext.2 $
by simp [mem_perms_of_list_iff,mem_of_perm hab]))
s.2
lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α},
f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s :=
by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff
lemma card_perms_of_finset : ∀ (s : finset α),
(perms_of_finset s).card = s.card.fact :=
by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l
def fintype_perm [fintype α] : fintype (perm α) :=
⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩
instance [fintype α] [fintype β] : fintype (α ≃ β) :=
if h : fintype.card β = fintype.card α
then trunc.rec_on_subsingleton (fintype.equiv_fin α)
(λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β)
(λ eβ, @fintype.of_equiv _ (perm α) fintype_perm
(equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β))))
else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩
lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact :=
subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸
card_perms_of_finset _
lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) :
fintype.card (α ≃ β) = (fintype.card α).fact :=
fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm
end equiv
|
77f37b5282bb264c92da8cff4e183212f28e1584 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/normed_space/mazur_ulam.lean | c49febd0adffba1cb46818fedc545f67d61ee9bd | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,685 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.instances.real_vector_space
import Mathlib.analysis.normed_space.add_torsor
import Mathlib.linear_algebra.affine_space.midpoint
import Mathlib.analysis.normed_space.linear_isometry
import Mathlib.PostPort
universes u_1 u_2 u_3 u_4
namespace Mathlib
/-!
# Mazur-Ulam Theorem
Mazur-Ulam theorem states that an isometric bijection between two normed affine spaces over `ℝ` is
affine. We formalize it in three definitions:
* `isometric.to_real_linear_isometry_equiv_of_map_zero` : given `E ≃ᵢ F` sending `0` to `0`,
returns `E ≃ₗᵢ[ℝ] F` with the same `to_fun` and `inv_fun`;
* `isometric.to_real_linear_isometry_equiv` : given `f : E ≃ᵢ F`,
returns `g : E ≃ₗᵢ[ℝ] F` with `g x = f x - f 0`.
* `isometric.to_affine_equiv` : given `PE ≃ᵢ PF`, returns `g : PE ≃ᵃ[ℝ] PF` with the same
`to_equiv`.
The formalization is based on [Jussi Väisälä, *A Proof of the Mazur-Ulam Theorem*][Vaisala_2003].
## Tags
isometry, affine map, linear map
-/
namespace isometric
/-- If an isometric self-homeomorphism of a normed vector space over `ℝ` fixes `x` and `y`,
then it fixes the midpoint of `[x, y]`. This is a lemma for a more general Mazur-Ulam theorem,
see below. -/
theorem midpoint_fixed {E : Type u_1} {PE : Type u_2} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {x : PE} {y : PE} (e : PE ≃ᵢ PE) : coe_fn e x = x → coe_fn e y = y → coe_fn e (midpoint ℝ x y) = midpoint ℝ x y := sorry
/-- A bijective isometry sends midpoints to midpoints. -/
theorem map_midpoint {E : Type u_1} {PE : Type u_2} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {F : Type u_3} {PF : Type u_4} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF] (f : PE ≃ᵢ PF) (x : PE) (y : PE) : coe_fn f (midpoint ℝ x y) = midpoint ℝ (coe_fn f x) (coe_fn f y) := sorry
/-!
Since `f : PE ≃ᵢ PF` sends midpoints to midpoints, it is an affine map.
We define a conversion to a `continuous_linear_equiv` first, then a conversion to an `affine_map`.
-/
/-- Mazur-Ulam Theorem: if `f` is an isometric bijection between two normed vector spaces
over `ℝ` and `f 0 = 0`, then `f` is a linear equivalence. -/
def to_real_linear_isometry_equiv_of_map_zero {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (h0 : coe_fn f 0 = 0) : linear_isometry_equiv ℝ E F :=
linear_isometry_equiv.mk
(linear_equiv.mk
(linear_map.to_fun
(continuous_linear_map.to_linear_map
(add_monoid_hom.to_real_linear_map (add_monoid_hom.of_map_midpoint ℝ ℝ (⇑f) h0 sorry) sorry)))
sorry sorry (equiv.inv_fun (to_equiv f)) sorry sorry)
sorry
@[simp] theorem coe_to_real_linear_equiv_of_map_zero {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (h0 : coe_fn f 0 = 0) : ⇑(to_real_linear_isometry_equiv_of_map_zero f h0) = ⇑f :=
rfl
@[simp] theorem coe_to_real_linear_equiv_of_map_zero_symm {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (h0 : coe_fn f 0 = 0) : ⇑(linear_isometry_equiv.symm (to_real_linear_isometry_equiv_of_map_zero f h0)) = ⇑(isometric.symm f) :=
rfl
/-- Mazur-Ulam Theorem: if `f` is an isometric bijection between two normed vector spaces
over `ℝ`, then `x ↦ f x - f 0` is a linear equivalence. -/
def to_real_linear_isometry_equiv {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) : linear_isometry_equiv ℝ E F :=
to_real_linear_isometry_equiv_of_map_zero (isometric.trans f (isometric.symm (isometric.add_right (coe_fn f 0)))) sorry
@[simp] theorem to_real_linear_equiv_apply {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (x : E) : coe_fn (to_real_linear_isometry_equiv f) x = coe_fn f x - coe_fn f 0 :=
Eq.symm (sub_eq_add_neg (coe_fn f x) (coe_fn f 0))
@[simp] theorem to_real_linear_isometry_equiv_symm_apply {E : Type u_1} [normed_group E] [normed_space ℝ E] {F : Type u_3} [normed_group F] [normed_space ℝ F] (f : E ≃ᵢ F) (y : F) : coe_fn (linear_isometry_equiv.symm (to_real_linear_isometry_equiv f)) y = coe_fn (isometric.symm f) (y + coe_fn f 0) :=
rfl
/-- Convert an isometric equivalence between two affine spaces to an `affine_map`. -/
def to_affine_equiv {E : Type u_1} {PE : Type u_2} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {F : Type u_3} {PF : Type u_4} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF] (f : PE ≃ᵢ PF) : affine_equiv ℝ PE PF :=
affine_equiv.mk' (to_equiv f)
(linear_isometry_equiv.to_linear_equiv
(to_real_linear_isometry_equiv
(isometric.trans (vadd_const (classical.arbitrary PE))
(isometric.trans f (isometric.symm (vadd_const (coe_fn f (classical.arbitrary PE))))))))
(classical.arbitrary PE) sorry
@[simp] theorem coe_to_affine_equiv {E : Type u_1} {PE : Type u_2} [normed_group E] [normed_space ℝ E] [metric_space PE] [normed_add_torsor E PE] {F : Type u_3} {PF : Type u_4} [normed_group F] [normed_space ℝ F] [metric_space PF] [normed_add_torsor F PF] (f : PE ≃ᵢ PF) : ⇑(to_affine_equiv f) = ⇑f :=
rfl
|
0f44d81424bf197cad6511babe0bc481e6276398 | e94d3f31e48d06d252ee7307fe71efe1d500f274 | /library/theories/analysis/metric_space.lean | ec45a736dd6c67dd3f2910c6c31d91bfbc20c919 | [
"Apache-2.0"
] | permissive | GallagherCommaJack/lean | e4471240a069d82f97cb361d2bf1a029de3f4256 | 226f8bafeb9baaa5a2ac58000c83d6beb29991e2 | refs/heads/master | 1,610,725,100,482 | 1,459,194,829,000 | 1,459,195,377,000 | 55,377,224 | 0 | 0 | null | 1,459,731,701,000 | 1,459,731,700,000 | null | UTF-8 | Lean | false | false | 27,519 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Metric spaces.
-/
import data.real.complete data.pnat data.list.sort ..topology.basic data.set
open nat real eq.ops classical
structure metric_space [class] (M : Type) : Type :=
(dist : M → M → ℝ)
(dist_self : ∀ x : M, dist x x = 0)
(eq_of_dist_eq_zero : ∀ {x y : M}, dist x y = 0 → x = y)
(dist_comm : ∀ x y : M, dist x y = dist y x)
(dist_triangle : ∀ x y z : M, dist x z ≤ dist x y + dist y z)
namespace analysis
section metric_space_M
variables {M : Type} [metric_space M]
definition dist (x y : M) : ℝ := metric_space.dist x y
proposition dist_self (x : M) : dist x x = 0 := metric_space.dist_self x
proposition eq_of_dist_eq_zero {x y : M} (H : dist x y = 0) : x = y :=
metric_space.eq_of_dist_eq_zero H
proposition dist_comm (x y : M) : dist x y = dist y x := metric_space.dist_comm x y
proposition dist_eq_zero_iff (x y : M) : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (suppose x = y, this ▸ !dist_self)
proposition dist_triangle (x y z : M) : dist x z ≤ dist x y + dist y z :=
metric_space.dist_triangle x y z
proposition dist_nonneg (x y : M) : 0 ≤ dist x y :=
have dist x y + dist y x ≥ 0, by rewrite -(dist_self x); apply dist_triangle,
have 2 * dist x y ≥ 0,
by krewrite [-real.one_add_one, right_distrib, +one_mul, dist_comm at {2}]; apply this,
nonneg_of_mul_nonneg_left this two_pos
proposition dist_pos_of_ne {x y : M} (H : x ≠ y) : dist x y > 0 :=
lt_of_le_of_ne !dist_nonneg (suppose 0 = dist x y, H (iff.mp !dist_eq_zero_iff this⁻¹))
proposition ne_of_dist_pos {x y : M} (H : dist x y > 0) : x ≠ y :=
suppose x = y,
have H1 : dist x x > 0, by rewrite this at {2}; exact H,
by rewrite dist_self at H1; apply not_lt_self _ H1
proposition eq_of_forall_dist_le {x y : M} (H : ∀ ε, ε > 0 → dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_zero_of_nonneg_of_forall_le !dist_nonneg H)
/- convergence of a sequence -/
definition converges_to_seq (X : ℕ → M) (y : M) : Prop :=
∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ ⦃n⦄, n ≥ N → dist (X n) y < ε
-- the same, with ≤ in place of <; easier to prove, harder to use
definition converges_to_seq.intro {X : ℕ → M} {y : M}
(H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → dist (X n) y ≤ ε) :
converges_to_seq X y :=
take ε, assume epos : ε > 0,
have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos,
obtain N HN, from H e2pos,
exists.intro N
(take n, suppose n ≥ N,
calc
dist (X n) y ≤ ε / 2 : HN _ `n ≥ N`
... < ε : div_two_lt_of_pos epos)
notation X `⟶` y `in` `ℕ` := converges_to_seq X y
definition converges_seq [class] (X : ℕ → M) : Prop := ∃ y, X ⟶ y in ℕ
noncomputable definition limit_seq (X : ℕ → M) [H : converges_seq X] : M := some H
proposition converges_to_limit_seq (X : ℕ → M) [H : converges_seq X] :
(X ⟶ limit_seq X in ℕ) :=
some_spec H
proposition converges_to_seq_unique {X : ℕ → M} {y₁ y₂ : M}
(H₁ : X ⟶ y₁ in ℕ) (H₂ : X ⟶ y₂ in ℕ) : y₁ = y₂ :=
eq_of_forall_dist_le
(take ε, suppose ε > 0,
have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos,
obtain N₁ (HN₁ : ∀ {n}, n ≥ N₁ → dist (X n) y₁ < ε / 2), from H₁ e2pos,
obtain N₂ (HN₂ : ∀ {n}, n ≥ N₂ → dist (X n) y₂ < ε / 2), from H₂ e2pos,
let N := max N₁ N₂ in
have dN₁ : dist (X N) y₁ < ε / 2, from HN₁ !le_max_left,
have dN₂ : dist (X N) y₂ < ε / 2, from HN₂ !le_max_right,
have dist y₁ y₂ < ε, from calc
dist y₁ y₂ ≤ dist y₁ (X N) + dist (X N) y₂ : dist_triangle
... = dist (X N) y₁ + dist (X N) y₂ : dist_comm
... < ε / 2 + ε / 2 : add_lt_add dN₁ dN₂
... = ε : add_halves,
show dist y₁ y₂ ≤ ε, from le_of_lt this)
proposition eq_limit_of_converges_to_seq {X : ℕ → M} {y : M} (H : X ⟶ y in ℕ) :
y = @limit_seq M _ X (exists.intro y H) :=
converges_to_seq_unique H (@converges_to_limit_seq M _ X (exists.intro y H))
proposition converges_to_seq_constant (y : M) : (λn, y) ⟶ y in ℕ :=
take ε, assume egt0 : ε > 0,
exists.intro 0
(take n, suppose n ≥ 0,
calc
dist y y = 0 : !dist_self
... < ε : egt0)
proposition converges_to_seq_offset {X : ℕ → M} {y : M} (k : ℕ) (H : X ⟶ y in ℕ) :
(λ n, X (n + k)) ⟶ y in ℕ :=
take ε, suppose ε > 0,
obtain N HN, from H `ε > 0`,
exists.intro N
(take n : ℕ, assume ngtN : n ≥ N,
show dist (X (n + k)) y < ε, from HN (n + k) (le.trans ngtN !le_add_right))
proposition converges_to_seq_offset_left {X : ℕ → M} {y : M} (k : ℕ) (H : X ⟶ y in ℕ) :
(λ n, X (k + n)) ⟶ y in ℕ :=
have aux : (λ n, X (k + n)) = (λ n, X (n + k)), from funext (take n, by rewrite add.comm),
by rewrite aux; exact converges_to_seq_offset k H
proposition converges_to_seq_offset_succ {X : ℕ → M} {y : M} (H : X ⟶ y in ℕ) :
(λ n, X (succ n)) ⟶ y in ℕ :=
converges_to_seq_offset 1 H
proposition converges_to_seq_of_converges_to_seq_offset
{X : ℕ → M} {y : M} {k : ℕ} (H : (λ n, X (n + k)) ⟶ y in ℕ) :
X ⟶ y in ℕ :=
take ε, suppose ε > 0,
obtain N HN, from H `ε > 0`,
exists.intro (N + k)
(take n : ℕ, assume nge : n ≥ N + k,
have n - k ≥ N, from nat.le_sub_of_add_le nge,
have dist (X (n - k + k)) y < ε, from HN (n - k) this,
show dist (X n) y < ε,
by rewrite [(nat.sub_add_cancel (le.trans !le_add_left nge)) at this]; exact this)
proposition converges_to_seq_of_converges_to_seq_offset_left
{X : ℕ → M} {y : M} {k : ℕ} (H : (λ n, X (k + n)) ⟶ y in ℕ) :
X ⟶ y in ℕ :=
have aux : (λ n, X (k + n)) = (λ n, X (n + k)), from funext (take n, by rewrite add.comm),
by rewrite aux at H; exact converges_to_seq_of_converges_to_seq_offset H
proposition converges_to_seq_of_converges_to_seq_offset_succ
{X : ℕ → M} {y : M} (H : (λ n, X (succ n)) ⟶ y in ℕ) :
X ⟶ y in ℕ :=
@converges_to_seq_of_converges_to_seq_offset M _ X y 1 H
proposition converges_to_seq_offset_iff (X : ℕ → M) (y : M) (k : ℕ) :
((λ n, X (n + k)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) :=
iff.intro converges_to_seq_of_converges_to_seq_offset !converges_to_seq_offset
proposition converges_to_seq_offset_left_iff (X : ℕ → M) (y : M) (k : ℕ) :
((λ n, X (k + n)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) :=
iff.intro converges_to_seq_of_converges_to_seq_offset_left !converges_to_seq_offset_left
proposition converges_to_seq_offset_succ_iff (X : ℕ → M) (y : M) :
((λ n, X (succ n)) ⟶ y in ℕ) ↔ (X ⟶ y in ℕ) :=
iff.intro converges_to_seq_of_converges_to_seq_offset_succ !converges_to_seq_offset_succ
section
open list
definition r_trans : transitive (@le ℝ _) := λ a b c, !le.trans
definition r_refl : reflexive (@le ℝ _) := λ a, !le.refl
theorem dec_prf_eq (P : Prop) (H1 H2 : decidable P) : H1 = H2 :=
begin
induction H1,
induction H2,
reflexivity,
apply absurd a a_1,
induction H2,
apply absurd a_1 a,
reflexivity
end
-- there's a very ugly part of this proof.
proposition bounded_of_converges_seq {X : ℕ → M} {x : M} (H : X ⟶ x in ℕ) :
∃ K : ℝ, ∀ n : ℕ, dist (X n) x ≤ K :=
begin
cases H zero_lt_one with N HN,
cases em (N = 0),
existsi 1,
intro n,
apply le_of_lt,
apply HN,
rewrite a,
apply zero_le,
let l := map (λ n : ℕ, -dist (X n) x) (upto N),
have Hnenil : l ≠ nil, from (map_ne_nil_of_ne_nil _ (upto_ne_nil_of_ne_zero a)),
existsi max (-list.min (λ a b : ℝ, le a b) l Hnenil) 1,
intro n,
have Hsmn : ∀ m : ℕ, m < N → dist (X m) x ≤ max (-list.min (λ a b : ℝ, le a b) l Hnenil) 1, begin
intro m Hm,
apply le.trans,
rotate 1,
apply le_max_left,
note Hall := min_lemma real.le_total r_trans r_refl Hnenil,
have Hmem : -dist (X m) x ∈ (map (λ (n : ℕ), -dist (X n) x) (upto N)), from mem_map _ (mem_upto_of_lt Hm),
note Hallm' := of_mem_of_all Hmem Hall,
apply le_neg_of_le_neg,
esimp, esimp at Hallm',
/-
have Heqs : (λ (a b : real), classical.prop_decidable (@le.{1} real real.real_has_le a b))
=
(@decidable_le.{1} real
(@decidable_linear_ordered_comm_group.to_decidable_linear_order.{1} real
(@decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_comm_group.{1} real
(@discrete_linear_ordered_field.to_decidable_linear_ordered_comm_ring.{1} real
real.discrete_linear_ordered_field)))),
begin
apply funext, intro, apply funext, intro,
apply dec_prf_eq
end,
rewrite -Heqs,
-/
exact Hallm'
end,
cases em (n < N) with Elt Ege,
apply Hsmn,
exact Elt,
apply le_of_lt,
apply lt_of_lt_of_le,
apply HN,
apply le_of_not_gt Ege,
apply le_max_right
end
end
/- cauchy sequences -/
definition cauchy (X : ℕ → M) : Prop :=
∀ ε : ℝ, ε > 0 → ∃ N, ∀ m n, m ≥ N → n ≥ N → dist (X m) (X n) < ε
proposition cauchy_of_converges_seq (X : ℕ → M) [H : converges_seq X] : cauchy X :=
take ε, suppose ε > 0,
obtain y (Hy : converges_to_seq X y), from H,
have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos,
obtain N₁ (HN₁ : ∀ {n}, n ≥ N₁ → dist (X n) y < ε / 2), from Hy e2pos,
obtain N₂ (HN₂ : ∀ {n}, n ≥ N₂ → dist (X n) y < ε / 2), from Hy e2pos,
let N := max N₁ N₂ in
exists.intro N
(take m n, suppose m ≥ N, suppose n ≥ N,
have m ≥ N₁, from le.trans !le_max_left `m ≥ N`,
have n ≥ N₂, from le.trans !le_max_right `n ≥ N`,
have dN₁ : dist (X m) y < ε / 2, from HN₁ `m ≥ N₁`,
have dN₂ : dist (X n) y < ε / 2, from HN₂ `n ≥ N₂`,
show dist (X m) (X n) < ε, from calc
dist (X m) (X n) ≤ dist (X m) y + dist y (X n) : dist_triangle
... = dist (X m) y + dist (X n) y : dist_comm
... < ε / 2 + ε / 2 : add_lt_add dN₁ dN₂
... = ε : add_halves)
end metric_space_M
/- convergence of a function at a point -/
section metric_space_M_N
variables {M N : Type} [strucM : metric_space M] [strucN : metric_space N]
include strucM strucN
definition converges_to_at (f : M → N) (y : N) (x : M) :=
∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ ⦃x'⦄, x' ≠ x ∧ dist x' x < δ → dist (f x') y < ε
notation f `⟶` y `at` x := converges_to_at f y x
definition converges_at [class] (f : M → N) (x : M) :=
∃ y, converges_to_at f y x
noncomputable definition limit_at (f : M → N) (x : M) [H : converges_at f x] : N :=
some H
proposition converges_to_limit_at (f : M → N) (x : M) [H : converges_at f x] :
(f ⟶ limit_at f x at x) :=
some_spec H
section
omit strucN
set_option pp.coercions true
--set_option pp.all true
open pnat rat
section
omit strucM
private lemma of_rat_rat_of_pnat_eq_of_nat_nat_of_pnat (p : pnat) :
of_rat (rat_of_pnat p) = of_nat (nat_of_pnat p) :=
rfl
end
theorem cnv_real_of_cnv_nat {X : ℕ → M} {c : M} (H : ∀ n : ℕ, dist (X n) c < 1 / (real.of_nat n + 1)) :
∀ ε : ℝ, ε > 0 → ∃ N : ℕ, ∀ n : ℕ, n ≥ N → dist (X n) c < ε :=
begin
intros ε Hε,
cases ex_rat_pos_lower_bound_of_pos Hε with q Hq,
cases Hq with Hq1 Hq2,
cases pnat_bound Hq1 with p Hp,
existsi nat_of_pnat p,
intros n Hn,
apply lt_of_lt_of_le,
apply H,
apply le.trans,
rotate 1,
apply Hq2,
have Hrat : of_rat (inv p) ≤ of_rat q, from of_rat_le_of_rat_of_le Hp,
apply le.trans,
rotate 1,
exact Hrat,
change 1 / (of_nat n + 1) ≤ of_rat ((1 : ℚ) / (rat_of_pnat p)),
rewrite [of_rat_divide, of_rat_one],
eapply one_div_le_one_div_of_le,
krewrite -of_rat_zero,
apply of_rat_lt_of_rat_of_lt,
apply rat_of_pnat_is_pos,
krewrite [of_rat_rat_of_pnat_eq_of_nat_nat_of_pnat, -real.of_nat_add],
apply real.of_nat_le_of_nat_of_le,
apply le_add_of_le_right,
assumption
end
end
theorem all_conv_seqs_of_converges_to_at {f : M → N} {c : M} {l : N} (Hconv : f ⟶ l at c) :
∀ X : ℕ → M, ((∀ n : ℕ, ((X n) ≠ c) ∧ (X ⟶ c in ℕ)) → ((λ n : ℕ, f (X n)) ⟶ l in ℕ)) :=
begin
intros X HX,
rewrite [↑converges_to_at at Hconv, ↑converges_to_seq],
intros ε Hε,
cases Hconv Hε with δ Hδ,
cases Hδ with Hδ1 Hδ2,
cases HX 0 with _ HXlim,
cases HXlim Hδ1 with N1 HN1,
existsi N1,
intro n Hn,
apply Hδ2,
split,
apply and.left (HX _),
exact HN1 Hn
end
theorem converges_to_at_of_all_conv_seqs {f : M → N} (c : M) (l : N)
(Hseq : ∀ X : ℕ → M, ((∀ n : ℕ, ((X n) ≠ c) ∧ (X ⟶ c in ℕ)) → ((λ n : ℕ, f (X n)) ⟶ l in ℕ)))
: f ⟶ l at c :=
by_contradiction
(assume Hnot : ¬ (f ⟶ l at c),
obtain ε Hε, from exists_not_of_not_forall Hnot,
let Hε' := and_not_of_not_implies Hε in
obtain (H1 : ε > 0) H2, from Hε',
have H3 : ∀ δ : ℝ, (δ > 0 → ∃ x' : M, x' ≠ c ∧ dist x' c < δ ∧ dist (f x') l ≥ ε), begin -- tedious!!
intros δ Hδ,
note Hε'' := forall_not_of_not_exists H2,
note H4 := forall_not_of_not_exists H2 δ,
have ¬ (∀ x' : M, x' ≠ c ∧ dist x' c < δ → dist (f x') l < ε), from λ H', H4 (and.intro Hδ H'),
note H5 := exists_not_of_not_forall this,
cases H5 with x' Hx',
existsi x',
note H6 := and_not_of_not_implies Hx',
rewrite and.assoc at H6,
cases H6,
split,
assumption,
cases a_1,
split,
assumption,
apply le_of_not_gt,
assumption
end,
let S : ℕ → M → Prop := λ n x, 0 < dist x c ∧ dist x c < 1 / (of_nat n + 1) ∧ dist (f x) l ≥ ε in
have HS : ∀ n : ℕ, ∃ m : M, S n m, begin
intro k,
have Hpos : 0 < of_nat k + 1, from of_nat_succ_pos k,
cases H3 (1 / (k + 1)) (one_div_pos_of_pos Hpos) with x' Hx',
cases Hx' with Hne Hx',
cases Hx' with Hdistl Hdistg,
existsi x',
esimp,
split,
apply dist_pos_of_ne,
assumption,
split,
repeat assumption
end,
let X : ℕ → M := λ n, some (HS n) in
have H4 : ∀ n : ℕ, ((X n) ≠ c) ∧ (X ⟶ c in ℕ), from
(take n, and.intro
(begin
note Hspec := some_spec (HS n),
esimp, esimp at Hspec,
cases Hspec,
apply ne_of_dist_pos,
assumption
end)
(begin
apply cnv_real_of_cnv_nat,
intro m,
note Hspec := some_spec (HS m),
esimp, esimp at Hspec,
cases Hspec with Hspec1 Hspec2,
cases Hspec2,
assumption
end)),
have H5 : (λ n : ℕ, f (X n)) ⟶ l in ℕ, from Hseq X H4,
begin
note H6 := H5 H1,
cases H6 with Q HQ,
note HQ' := HQ !le.refl,
esimp at HQ',
apply absurd HQ',
apply not_lt_of_ge,
note H7 := some_spec (HS Q),
esimp at H7,
cases H7 with H71 H72,
cases H72,
assumption
end)
end metric_space_M_N
section topology
/- A metric space is a topological space. -/
open set prod topology
variables {V : Type} [Vmet : metric_space V]
include Vmet
definition open_ball (x : V) (ε : ℝ) := {y ∈ univ | dist x y < ε}
theorem open_ball_empty_of_nonpos (x : V) {ε : ℝ} (Hε : ε ≤ 0) : open_ball x ε = ∅ :=
begin
apply eq_empty_of_forall_not_mem,
intro y Hy,
note Hlt := and.right Hy,
apply not_lt_of_ge (dist_nonneg x y),
apply lt_of_lt_of_le Hlt Hε
end
theorem radius_pos_of_nonempty {x : V} {ε : ℝ} {u : V} (Hu : u ∈ open_ball x ε) : ε > 0 :=
begin
apply lt_of_not_ge,
intro Hge,
note Hop := open_ball_empty_of_nonpos x Hge,
rewrite Hop at Hu,
apply not_mem_empty _ Hu
end
theorem mem_open_ball (x : V) {ε : ℝ} (H : ε > 0) : x ∈ open_ball x ε :=
suffices x ∈ univ ∧ dist x x < ε, from this,
and.intro !mem_univ (by rewrite dist_self; assumption)
definition closed_ball (x : V) (ε : ℝ) := {y ∈ univ | dist x y ≤ ε}
theorem closed_ball_eq_compl (x : V) (ε : ℝ) : closed_ball x ε = -{y ∈ univ | dist x y > ε} :=
begin
apply ext,
intro y,
apply iff.intro,
intro Hx,
apply mem_compl,
intro Hxmem,
cases Hxmem with _ Hgt,
cases Hx with _ Hle,
apply not_le_of_gt Hgt Hle,
intro Hx,
note Hx' := not_mem_of_mem_compl Hx,
split,
apply mem_univ,
apply le_of_not_gt,
intro Hgt,
apply Hx',
split,
apply mem_univ,
assumption
end
omit Vmet
definition open_sets_basis (V : Type) [metric_space V] :=
image (λ pair : V × ℝ, open_ball (pr1 pair) (pr2 pair)) univ
definition metric_topology [instance] (V : Type) [metric_space V] : topology V :=
topology.generated_by (open_sets_basis V)
include Vmet
theorem open_ball_mem_open_sets_basis (x : V) (ε : ℝ) : (open_ball x ε) ∈ (open_sets_basis V) :=
mem_image !mem_univ rfl
theorem open_ball_open (x : V) (ε : ℝ) : Open (open_ball x ε) :=
by apply generators_mem_topology_generated_by; apply open_ball_mem_open_sets_basis
theorem closed_ball_closed (x : V) {ε : ℝ} (H : ε > 0) : closed (closed_ball x ε) :=
begin
apply iff.mpr !closed_iff_Open_compl,
rewrite closed_ball_eq_compl,
rewrite compl_compl,
apply Open_of_forall_exists_Open_nbhd,
intro y Hy,
cases Hy with _ Hxy,
existsi open_ball y (dist x y - ε),
split,
apply open_ball_open,
split,
apply mem_open_ball,
apply sub_pos_of_lt Hxy,
intros y' Hy',
cases Hy' with _ Hxy'd,
rewrite dist_comm at Hxy'd,
split,
apply mem_univ,
apply lt_of_not_ge,
intro Hxy',
apply not_lt_self (dist x y),
exact calc
dist x y ≤ dist x y' + dist y' y : dist_triangle
... ≤ ε + dist y' y : add_le_add_right Hxy'
... < ε + (dist x y - ε) : add_lt_add_left Hxy'd
... = dist x y : by rewrite [add.comm, sub_add_cancel]
end
private theorem not_mem_open_basis_of_boundary_pt {s : set V} (a : s ∈ open_sets_basis V) {x : V}
(Hbd : ∀ ε : ℝ, ε > 0 → ∃ v : V, v ∉ s ∧ dist x v < ε) : ¬ x ∈ s :=
begin
intro HxU,
cases a with pr Hpr,
cases pr with y r,
cases Hpr with _ Hs,
rewrite -Hs at HxU,
have H : dist y x < r, from and.right HxU,
cases Hbd _ (sub_pos_of_lt H) with v Hv,
cases Hv with Hv Hvdist,
apply Hv,
rewrite -Hs,
apply and.intro,
apply mem_univ,
apply lt_of_le_of_lt,
apply dist_triangle,
exact x,
esimp,
exact calc
dist y x + dist x v < dist y x + (r - dist y x) : add_lt_add_left Hvdist
... = r : by rewrite [add.comm, sub_add_cancel]
end
private theorem not_mem_intersect_of_boundary_pt {s t : set V} (a : Open s) (a_1 : Open t) {x : V}
(v_0 : (x ∈ s → ¬ (∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ s ∧ dist x v < ε))))
(v_1 : (x ∈ t → ¬ (∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ t ∧ dist x v < ε))))
(Hbd : ∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ s ∩ t ∧ dist x v < ε)) : ¬ (x ∈ s ∩ t) :=
begin
intro HxU,
have Hxs : x ∈ s, from mem_of_mem_inter_left HxU,
have Hxt : x ∈ t, from mem_of_mem_inter_right HxU,
note Hsih := exists_not_of_not_forall (v_0 Hxs),
note Htih := exists_not_of_not_forall (v_1 Hxt),
cases Hsih with ε1 Hε1,
cases Htih with ε2 Hε2,
note Hε1' := and_not_of_not_implies Hε1,
note Hε2' := and_not_of_not_implies Hε2,
cases Hε1' with Hε1p Hε1',
cases Hε2' with Hε2p Hε2',
note Hε1'' := forall_not_of_not_exists Hε1',
note Hε2'' := forall_not_of_not_exists Hε2',
have Hmin : min ε1 ε2 > 0, from lt_min Hε1p Hε2p,
cases Hbd _ Hmin with v Hv,
cases Hv with Hvint Hvdist,
note Hε1v := Hε1'' v,
note Hε2v := Hε2'' v,
cases em (v ∉ s) with Hnm Hmem,
apply Hε1v,
split,
exact Hnm,
apply lt_of_lt_of_le Hvdist,
apply min_le_left,
apply Hε2v,
have Hmem' : v ∈ s, from not_not_elim Hmem,
note Hnm := not_mem_of_mem_of_not_mem_inter_left Hmem' Hvint,
split,
exact Hnm,
apply lt_of_lt_of_le Hvdist,
apply min_le_right
end
private theorem not_mem_sUnion_of_boundary_pt {S : set (set V)} (a : ∀₀ s ∈ S, Open s) {x : V}
(v_0 : ∀ ⦃x_1 : set V⦄,
x_1 ∈ S → x ∈ x_1 → ¬ (∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ x_1 ∧ dist x v < ε)))
(Hbd : ∀ (ε : ℝ), ε > 0 → (∃ (v : V), v ∉ ⋃₀ S ∧ dist x v < ε)) : ¬ x ∈ ⋃₀ S :=
begin
intro HxU,
have Hex : ∃₀ s ∈ S, x ∈ s, from HxU,
cases Hex with s Hs,
cases Hs with Hs Hxs,
cases exists_not_of_not_forall (v_0 Hs Hxs) with ε Hε,
cases and_not_of_not_implies Hε with Hεp Hv,
cases Hbd _ Hεp with v Hv',
cases Hv' with Hvnm Hdist,
apply Hv,
existsi v,
split,
apply not_mem_of_not_mem_sUnion Hvnm Hs,
exact Hdist
end
/-
this should be doable by showing that the open-ball boundary definition
is equivalent to topology.on_boundary, and applying topology.not_open_of_on_boundary.
But the induction hypotheses don't work out nicely.
-/
theorem not_open_of_ex_boundary_pt {U : set V} {x : V} (HxU : x ∈ U)
(Hbd : ∀ ε : ℝ, ε > 0 → ∃ v : V, v ∉ U ∧ dist x v < ε) : ¬ Open U :=
begin
intro HUopen,
induction HUopen,
{apply not_mem_open_basis_of_boundary_pt a Hbd HxU},
{cases Hbd 1 zero_lt_one with v Hv,
cases Hv with Hv _,
exact Hv !mem_univ},
{apply not_mem_intersect_of_boundary_pt a a_1 v_0 v_1 Hbd HxU},
{apply not_mem_sUnion_of_boundary_pt a v_0 Hbd HxU}
end
theorem ex_Open_ball_subset_of_Open_of_nonempty {U : set V} (HU : Open U) {x : V} (Hx : x ∈ U) :
∃ (r : ℝ), r > 0 ∧ open_ball x r ⊆ U :=
begin
let balloon := {r ∈ univ | r > 0 ∧ open_ball x r ⊆ U},
cases em (balloon = ∅),
have H : ∀ r : ℝ, r > 0 → ∃ v : V, v ∉ U ∧ dist x v < r, begin
intro r Hr,
note Hor := not_or_not_of_not_and (forall_not_of_sep_empty a (mem_univ r)),
note Hor' := or.neg_resolve_left Hor Hr,
apply exists_of_not_forall_not,
intro Hall,
apply Hor',
intro y Hy,
cases not_or_not_of_not_and (Hall y) with Hmem Hge,
apply not_not_elim Hmem,
apply absurd (and.right Hy) Hge
end,
apply absurd HU,
apply not_open_of_ex_boundary_pt Hx H,
cases exists_mem_of_ne_empty a with r Hr,
cases Hr with _ Hr,
cases Hr with Hrpos HxrU,
existsi r,
split,
repeat assumption
end
end topology
section continuity
variables {M N : Type} [Hm : metric_space M] [Hn : metric_space N]
include Hm Hn
open topology set
/- continuity at a point -/
-- the ε - δ definition of continuity is equivalent to the topological definition
theorem continuous_at_intro {f : M → N} {x : M}
(H : ∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ ⦃x'⦄, dist x' x < δ → dist (f x') (f x) < ε) :
continuous_at f x :=
begin
rewrite ↑continuous_at,
intros U HfU Uopen,
cases ex_Open_ball_subset_of_Open_of_nonempty Uopen HfU with r Hr,
cases Hr with Hr HUr,
cases H Hr with δ Hδ,
cases Hδ with Hδ Hx'δ,
existsi open_ball x δ,
split,
apply mem_open_ball,
exact Hδ,
split,
apply open_ball_open,
intro y Hy,
apply HUr,
cases Hy with y' Hy',
cases Hy' with Hy' Hfy',
cases Hy' with _ Hy',
rewrite dist_comm at Hy',
note Hy'' := Hx'δ Hy',
apply and.intro !mem_univ,
rewrite [-Hfy', dist_comm],
exact Hy''
end
theorem continuous_at_elim {f : M → N} {x : M} (Hfx : continuous_at f x) :
∀ ⦃ε⦄, ε > 0 → ∃ δ, δ > 0 ∧ ∀ ⦃x'⦄, dist x' x < δ → dist (f x') (f x) < ε :=
begin
intros ε Hε,
rewrite [↑continuous_at at Hfx],
cases Hfx (open_ball (f x) ε) (mem_open_ball _ Hε) !open_ball_open with V HV,
cases HV with HVx HV,
cases HV with HV HVf,
cases ex_Open_ball_subset_of_Open_of_nonempty HV HVx with δ Hδ,
cases Hδ with Hδ Hδx,
existsi δ,
split,
exact Hδ,
intro x' Hx',
rewrite dist_comm,
apply and.right,
apply HVf,
existsi x',
split,
apply Hδx,
apply and.intro !mem_univ,
rewrite dist_comm,
apply Hx',
apply rfl
end
theorem continuous_at_of_converges_to_at {f : M → N} {x : M} (Hf : f ⟶ f x at x) :
continuous_at f x :=
continuous_at_intro
(take ε, suppose ε > 0,
obtain δ Hδ, from Hf this,
exists.intro δ (and.intro
(and.left Hδ)
(take x', suppose dist x' x < δ,
if Heq : x' = x then
by rewrite [-Heq, dist_self]; assumption
else
(suffices dist x' x < δ, from and.right Hδ x' (and.intro Heq this),
this))))
theorem converges_to_at_of_continuous_at {f : M → N} {x : M} (Hf : continuous_at f x) :
f ⟶ f x at x :=
take ε, suppose ε > 0,
obtain δ Hδ, from continuous_at_elim Hf this,
exists.intro δ (and.intro
(and.left Hδ)
(take x',
assume H : x' ≠ x ∧ dist x' x < δ,
show dist (f x') (f x) < ε, from and.right Hδ x' (and.right H)))
definition continuous (f : M → N) : Prop := ∀ x, continuous_at f x
theorem converges_seq_comp_of_converges_seq_of_cts [instance] (X : ℕ → M) [HX : converges_seq X] {f : M → N}
(Hf : continuous f) :
converges_seq (λ n, f (X n)) :=
begin
cases HX with xlim Hxlim,
existsi f xlim,
rewrite ↑converges_to_seq at *,
intros ε Hε,
let Hcont := (continuous_at_elim (Hf xlim)) Hε,
cases Hcont with δ Hδ,
cases Hxlim (and.left Hδ) with B HB,
existsi B,
intro n Hn,
apply and.right Hδ,
apply HB Hn
end
omit Hn
theorem id_continuous : continuous (λ x : M, x) :=
begin
intros x,
apply continuous_at_intro,
intro ε Hε,
existsi ε,
split,
assumption,
intros,
assumption
end
end continuity
end analysis
/- complete metric spaces -/
structure complete_metric_space [class] (M : Type) extends metricM : metric_space M : Type :=
(complete : ∀ X, @analysis.cauchy M metricM X → @analysis.converges_seq M metricM X)
namespace analysis
proposition complete (M : Type) [cmM : complete_metric_space M] {X : ℕ → M} (H : cauchy X) :
converges_seq X :=
complete_metric_space.complete X H
end analysis
/- the reals form a metric space -/
noncomputable definition metric_space_real [instance] : metric_space ℝ :=
⦃ metric_space,
dist := λ x y, abs (x - y),
dist_self := λ x, abstract by rewrite [sub_self, abs_zero] end,
eq_of_dist_eq_zero := λ x y, eq_of_abs_sub_eq_zero,
dist_comm := abs_sub,
dist_triangle := abs_sub_le
⦄
|
fdd9dcba71bd9a6eae669c9468217e2d4d9523ab | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/connected.lean | ca16b2792a06f45a4d3278896ca22d0437db4b58 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,726 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.shapes.pullbacks
import Mathlib.category_theory.limits.shapes.equalizers
import Mathlib.category_theory.limits.preserves.basic
import Mathlib.category_theory.is_connected
import Mathlib.PostPort
universes v₁ u_1 u₂ v₂
namespace Mathlib
/-!
# Connected limits
A connected limit is a limit whose shape is a connected category.
We give examples of connected categories, and prove that the functor given
by `(X × -)` preserves any connected limit. That is, any limit of shape `J`
where `J` is a connected category is preserved by the functor `(X × -)`.
-/
namespace category_theory
protected instance wide_pullback_shape_connected (J : Type v₁) : is_connected (limits.wide_pullback_shape J) :=
is_connected.of_induct
fun (p : set (limits.wide_pullback_shape J)) (hp : none ∈ p)
(t : ∀ {j₁ j₂ : limits.wide_pullback_shape J}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.wide_pullback_shape J) =>
option.cases_on j hp
fun (j : J) =>
eq.mpr (id (Eq._oldrec (Eq.refl (some j ∈ p)) (propext (t (limits.wide_pullback_shape.hom.term j))))) hp
protected instance wide_pushout_shape_connected (J : Type v₁) : is_connected (limits.wide_pushout_shape J) :=
is_connected.of_induct
fun (p : set (limits.wide_pushout_shape J)) (hp : none ∈ p)
(t : ∀ {j₁ j₂ : limits.wide_pushout_shape J}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.wide_pushout_shape J) =>
option.cases_on j hp
fun (j : J) =>
eq.mpr (id (Eq._oldrec (Eq.refl (some j ∈ p)) (Eq.symm (propext (t (limits.wide_pushout_shape.hom.init j))))))
hp
protected instance parallel_pair_inhabited : Inhabited limits.walking_parallel_pair :=
{ default := limits.walking_parallel_pair.one }
protected instance parallel_pair_connected : is_connected limits.walking_parallel_pair :=
is_connected.of_induct
fun (p : set limits.walking_parallel_pair) (ᾰ : limits.walking_parallel_pair.one ∈ p)
(t : ∀ {j₁ j₂ : limits.walking_parallel_pair}, (j₁ ⟶ j₂) → (j₁ ∈ p ↔ j₂ ∈ p)) (j : limits.walking_parallel_pair) =>
limits.walking_parallel_pair.cases_on j
(eq.mpr
(id
(Eq._oldrec (Eq.refl (limits.walking_parallel_pair.zero ∈ p))
(propext (t limits.walking_parallel_pair_hom.left))))
ᾰ)
ᾰ
namespace prod_preserves_connected_limits
/-- (Impl). The obvious natural transformation from (X × K -) to K. -/
def γ₂ {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {K : J ⥤ C} (X : C) : K ⋙ functor.obj limits.prod.functor X ⟶ K :=
nat_trans.mk fun (Y : J) => limits.prod.snd
/-- (Impl). The obvious natural transformation from (X × K -) to X -/
@[simp] theorem γ₁_app {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {K : J ⥤ C} (X : C) (Y : J) : nat_trans.app (γ₁ X) Y = limits.prod.fst :=
Eq.refl (nat_trans.app (γ₁ X) Y)
/-- (Impl). Given a cone for (X × K -), produce a cone for K using the natural transformation `γ₂` -/
@[simp] theorem forget_cone_π {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] {X : C} {K : J ⥤ C} (s : limits.cone (K ⋙ functor.obj limits.prod.functor X)) : limits.cone.π (forget_cone s) = limits.cone.π s ≫ γ₂ X :=
Eq.refl (limits.cone.π (forget_cone s))
end prod_preserves_connected_limits
/--
The functor `(X × -)` preserves any connected limit.
Note that this functor does not preserve the two most obvious disconnected limits - that is,
`(X × -)` does not preserve products or terminal object, eg `(X ⨯ A) ⨯ (X ⨯ B)` is not isomorphic to
`X ⨯ (A ⨯ B)` and `X ⨯ 1` is not isomorphic to `1`.
-/
def prod_preserves_connected_limits {C : Type u₂} [category C] [limits.has_binary_products C] {J : Type v₂} [small_category J] [is_connected J] (X : C) : limits.preserves_limits_of_shape J (functor.obj limits.prod.functor X) :=
limits.preserves_limits_of_shape.mk
fun (K : J ⥤ C) =>
limits.preserves_limit.mk
fun (c : limits.cone K) (l : limits.is_limit c) =>
limits.is_limit.mk
fun (s : limits.cone (K ⋙ functor.obj limits.prod.functor X)) =>
limits.prod.lift (nat_trans.app (limits.cone.π s) (classical.arbitrary J) ≫ limits.prod.fst)
(limits.is_limit.lift l sorry)
|
f51e4ee64ff14be636599b9380d3b6c8f3a9a379 | 47181b4ef986292573c77e09fcb116584d37ea8a | /src/for_mathlib/hom.lean | 293e31c47e36a779b3202556e939f0c7a980851c | [
"MIT"
] | permissive | RaitoBezarius/berkovich-spaces | 87662a2bdb0ac0beed26e3338b221e3f12107b78 | 0a49f75a599bcb20333ec86b301f84411f04f7cf | refs/heads/main | 1,690,520,666,912 | 1,629,328,012,000 | 1,629,328,012,000 | 332,238,095 | 4 | 0 | MIT | 1,629,312,085,000 | 1,611,414,506,000 | Lean | UTF-8 | Lean | false | false | 478 | lean | import algebra.group_with_zero.basic
import algebra.group.hom
-- Deserves its place in matlib, as `monoid_with_zero_hom.map_inv`
theorem monoid_with_zero_hom.map_inv {G₁ G₂: Type} [group_with_zero G₁] [group_with_zero G₂]
(φ: monoid_with_zero_hom G₁ G₂) (a: G₁) (a_ne_zero: a ≠ 0): φ a⁻¹ = (φ a)⁻¹ :=
begin
apply eq_inv_of_mul_left_eq_one,
rw ← monoid_with_zero_hom.map_mul,
rw inv_mul_cancel a_ne_zero,
rw monoid_with_zero_hom.map_one,
end |
0fbcaa1815904c207f39656d8c3520e2cb48bb68 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/blast_cc_missed.lean | c91cce5759866543f74ba4310f26f495121e04b6 | [
"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 | 414 | lean | set_option blast.strategy "cc"
example (C : nat → Type) (f : Π n, C n → C n) (n m : nat) (c : C n) (d : C m) :
f n == f m → c == d → n == m → f n c == f m d :=
by blast
example (f : nat → nat → nat) (a b c d : nat) :
c = d → f a = f b → f a c = f b d :=
by blast
example (f : nat → nat → nat) (a b c d : nat) :
c == d → f a == f b → f a c == f b d :=
by blast
|
6a959f78ce11ae2c540ef269506035d042991bc8 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/data/sum.lean | 7a22cbdf76b31df7d3052f8581db972459c513b6 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,998 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.sum
Authors: Leonardo de Moura, Jeremy Avigad
The sum type, aka disjoint union.
-/
import logic.connectives
open inhabited eq.ops
notation A ⊎ B := sum A B
namespace sum
notation A + B := sum A B
namespace low_precedence_plus
reserve infixr `+`:25 -- conflicts with notation for addition
infixr `+` := sum
end low_precedence_plus
variables {A B : Type}
definition inl_ne_inr (a : A) (b : B) : inl a ≠ inr b :=
assume H, sum.no_confusion H
definition inr_ne_inl (b : B) (a : A) : inr b ≠ inl a :=
assume H, sum.no_confusion H
definition inl_inj {a₁ a₂ : A} : intro_left B a₁ = intro_left B a₂ → a₁ = a₂ :=
assume H, sum.no_confusion H (λe, e)
definition inr_inj {b₁ b₂ : B} : intro_right A b₁ = intro_right A b₂ → b₁ = b₂ :=
assume H, sum.no_confusion H (λe, e)
protected definition is_inhabited_left [instance] [h : inhabited A] : inhabited (A + B) :=
inhabited.mk (inl (default A))
protected definition is_inhabited_right [instance] [h : inhabited B] : inhabited (A + B) :=
inhabited.mk (inr (default B))
protected definition has_decidable_eq [instance] [h₁ : decidable_eq A] [h₂ : decidable_eq B] : ∀ s₁ s₂ : A + B, decidable (s₁ = s₂)
| has_decidable_eq (inl a₁) (inl a₂) :=
match h₁ a₁ a₂ with
| decidable.inl hp := decidable.inl (hp ▸ rfl)
| decidable.inr hn := decidable.inr (λ he, absurd (inl_inj he) hn)
end
| has_decidable_eq (inl a₁) (inr b₂) := decidable.inr (λ e, sum.no_confusion e)
| has_decidable_eq (inr b₁) (inl a₂) := decidable.inr (λ e, sum.no_confusion e)
| has_decidable_eq (inr b₁) (inr b₂) :=
match h₂ b₁ b₂ with
| decidable.inl hp := decidable.inl (hp ▸ rfl)
| decidable.inr hn := decidable.inr (λ he, absurd (inr_inj he) hn)
end
end sum
|
933132ff49206407277410386f2c34fc47bb0eda | 7bc35d4fbdda0c01e9b22a949940ee5cbb9800d0 | /manifold/differentiable.lean | 10ef6a64f6f615a5da9d30be643a884ca912ba7c | [] | no_license | truonghoangle/manifolds | e6c2534dd46579f56ba99a48e2eb7ce51640e7c0 | dcf4815b29ad363ec9712fd00b7756c36cfa7c1c | refs/heads/main | 1,638,501,090,139 | 1,636,918,550,000 | 1,636,918,550,000 | 185,779,631 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,996 | lean | import manifold.basis
import analysis.normed_space.deriv analysis.normed_space.bounded_linear_maps
open pfun
local attribute [instance] classical.prop_decidable
noncomputable theory
universes u v w
variables {α : Type} {β : Type} {γ : Type w} {n : ℕ}
variable [normed_field α]
namespace differentiable
variables {E : euclidean α }
variables {F : euclidean α }
def ext_by_zero (f : E →. α ) (z:E ): α :=
if h:z ∈ f.dom then f.fn z h else 0
def is_differentiable_at (f : E →. α ) (x : E) : Prop := ∃g, @has_fderiv_at α _ _ _ _ _ (ext_by_zero f) g x
def is_differentiable (f : E →. α ) : Prop := (∀ x:f.dom, is_differentiable_at f x) ∧ (is_open f.dom)
def is_differentiable_map (f : E →. F ) : Prop := ∀ i: fin (F.dim), is_differentiable (pfun.lift (euclidean.proj F i) ∘. f )
def differentiable_on (f : E →. α ) (U:set E) : Prop := ∀ x:U, is_differentiable_at f x
instance : normed_space α (E →L[α] F) := bounded_linear_map.to_normed_space
lemma exists_diff (f:E →. α ) (h:@is_differentiable α _ E f ) :∀ (x:E)( H:x∈ f.dom), ∃ g, @has_fderiv_at α _ _ _ _ _ (ext_by_zero f) g x :=
by {
simp [is_differentiable,is_differentiable_at] at h,
cases h with h h1,
repeat {intro},
have h2:= @h x H,
exact h2
}
def diff (f:E →. α ) [h:@is_differentiable α _ E f ]: E →. euclidean.dual E:=
λ x, { dom:= x ∈ f.dom,
get:=λ y,
let g:=classical.some (@exists_diff α _ E f h x y) in @is_bounded_linear_map.to_linear_map α _ E _ _ _ g (bounded_linear_map.is_bounded_linear_map g)}
def is_diff (f:E →. α ) [h:@is_differentiable α _ E f ]:Prop := @is_differentiable_map α _ E (@euclidean.dual α _ E) (@diff α _ E f h)
structure C1_diff_map (f : E →. F ) :=
(has_diff: ∀ i: fin (F.dim), (is_differentiable (pfun.lift ⇑(euclidean.proj F i) ∘. f)) )
(cont: ∀ i: fin (F.dim), is_continuous (@diff α _ E (pfun.lift (euclidean.proj F i) ∘. f ) (has_diff i)))
structure C2_diff_map (f : E →. F ) :=
(has_diff: ∀ i: fin (F.dim), (is_differentiable (pfun.lift ⇑(euclidean.proj F i) ∘. f)) )
(has_C1_diff: ∀ i: fin (F.dim), @is_diff α _ E (pfun.lift (euclidean.proj F i) ∘. f ) (has_diff i) )
(cont: ∀ i: fin (F.dim), is_continuous (@diff α _ E (pfun.lift (euclidean.proj F i) ∘. f ) (has_diff i)))
def has_diff (f : (E →. α )) (i:fin E.dim) : roption(E →. α ) :=
{dom:= @is_differentiable α _ E f,
get:=λ y, (pfun.lift (euclidean.proj (euclidean.dual E) i) ∘. (@diff α _ E f y ))}
def C:list(fin E.dim) → (E→. α )→ Prop
| []:= λ f, is_continuous f
| (a::l):=λ f, C l f → ∃g , g= @has_diff α _ E f a ∧ (∀ x, is_continuous (g.get x))
def 𝒞_n:ℕ → (E→. F )→ Prop :=
λ n, λ f, ∀ (l: list(fin E.dim)) (i:fin F.dim), list.length l=n → C l (pfun.lift (euclidean.proj F i) ∘. f)
def 𝒞_infinity: (E→. F )→ Prop :=
λ f, ∀ n:ℕ, 𝒞_n n f
end differentiable
|
0d81fb8eb0fd215d2c3bdcfe0ffb01244510ec72 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/normed_space/units.lean | 81dbba4a8e261ea7e7e38c3188ec401eec654a16 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 11,962 | lean | /-
Copyright (c) 2020 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import analysis.specific_limits.normed
/-!
# The group of units of a complete normed ring
This file contains the basic theory for the group of units (invertible elements) of a complete
normed ring (Banach algebras being a notable special case).
## Main results
The constructions `one_sub`, `add` and `unit_of_nearby` state, in varying forms, that perturbations
of a unit are units. The latter two are not stated in their optimal form; more precise versions
would use the spectral radius.
The first main result is `is_open`: the group of units of a complete normed ring is an open subset
of the ring.
The function `inverse` (defined in `algebra.ring`), for a ring `R`, sends `a : R` to `a⁻¹` if `a` is
a unit and 0 if not. The other major results of this file (notably `inverse_add`,
`inverse_add_norm` and `inverse_add_norm_diff_nth_order`) cover the asymptotic properties of
`inverse (x + t)` as `t → 0`.
-/
noncomputable theory
open_locale topological_space
variables {R : Type*} [normed_ring R] [complete_space R]
namespace units
/-- In a complete normed ring, a perturbation of `1` by an element `t` of distance less than `1`
from `1` is a unit. Here we construct its `units` structure. -/
@[simps coe]
def one_sub (t : R) (h : ∥t∥ < 1) : Rˣ :=
{ val := 1 - t,
inv := ∑' n : ℕ, t ^ n,
val_inv := mul_neg_geom_series t h,
inv_val := geom_series_mul_neg t h }
/-- In a complete normed ring, a perturbation of a unit `x` by an element `t` of distance less than
`∥x⁻¹∥⁻¹` from `x` is a unit. Here we construct its `units` structure. -/
@[simps coe]
def add (x : Rˣ) (t : R) (h : ∥t∥ < ∥(↑x⁻¹ : R)∥⁻¹) : Rˣ :=
units.copy -- to make `coe_add` true definitionally, for convenience
(x * (units.one_sub (-(↑x⁻¹ * t)) begin
nontriviality R using [zero_lt_one],
have hpos : 0 < ∥(↑x⁻¹ : R)∥ := units.norm_pos x⁻¹,
calc ∥-(↑x⁻¹ * t)∥
= ∥↑x⁻¹ * t∥ : by { rw norm_neg }
... ≤ ∥(↑x⁻¹ : R)∥ * ∥t∥ : norm_mul_le ↑x⁻¹ _
... < ∥(↑x⁻¹ : R)∥ * ∥(↑x⁻¹ : R)∥⁻¹ : by nlinarith only [h, hpos]
... = 1 : mul_inv_cancel (ne_of_gt hpos)
end))
(x + t) (by simp [mul_add]) _ rfl
/-- In a complete normed ring, an element `y` of distance less than `∥x⁻¹∥⁻¹` from `x` is a unit.
Here we construct its `units` structure. -/
@[simps coe]
def unit_of_nearby (x : Rˣ) (y : R) (h : ∥y - x∥ < ∥(↑x⁻¹ : R)∥⁻¹) : Rˣ :=
units.copy (x.add (y - x : R) h) y (by simp) _ rfl
/-- The group of units of a complete normed ring is an open subset of the ring. -/
protected lemma is_open : is_open {x : R | is_unit x} :=
begin
nontriviality R,
apply metric.is_open_iff.mpr,
rintros x' ⟨x, rfl⟩,
refine ⟨∥(↑x⁻¹ : R)∥⁻¹, _root_.inv_pos.mpr (units.norm_pos x⁻¹), _⟩,
intros y hy,
rw [metric.mem_ball, dist_eq_norm] at hy,
exact (x.unit_of_nearby y hy).is_unit
end
protected lemma nhds (x : Rˣ) : {x : R | is_unit x} ∈ 𝓝 (x : R) :=
is_open.mem_nhds units.is_open x.is_unit
end units
namespace normed_ring
open_locale classical big_operators
open asymptotics filter metric finset ring
lemma inverse_one_sub (t : R) (h : ∥t∥ < 1) : inverse (1 - t) = ↑(units.one_sub t h)⁻¹ :=
by rw [← inverse_unit (units.one_sub t h), units.coe_one_sub]
/-- The formula `inverse (x + t) = inverse (1 + x⁻¹ * t) * x⁻¹` holds for `t` sufficiently small. -/
lemma inverse_add (x : Rˣ) :
∀ᶠ t in (𝓝 0), inverse ((x : R) + t) = inverse (1 + ↑x⁻¹ * t) * ↑x⁻¹ :=
begin
nontriviality R,
rw [eventually_iff, metric.mem_nhds_iff],
have hinv : 0 < ∥(↑x⁻¹ : R)∥⁻¹, by cancel_denoms,
use [∥(↑x⁻¹ : R)∥⁻¹, hinv],
intros t ht,
simp only [mem_ball, dist_zero_right] at ht,
have ht' : ∥-↑x⁻¹ * t∥ < 1,
{ refine lt_of_le_of_lt (norm_mul_le _ _) _,
rw norm_neg,
refine lt_of_lt_of_le (mul_lt_mul_of_pos_left ht x⁻¹.norm_pos) _,
cancel_denoms },
have hright := inverse_one_sub (-↑x⁻¹ * t) ht',
have hleft := inverse_unit (x.add t ht),
simp only [neg_mul, sub_neg_eq_add] at hright,
simp only [units.coe_add] at hleft,
simp [hleft, hright, units.add]
end
lemma inverse_one_sub_nth_order (n : ℕ) :
∀ᶠ t in (𝓝 0), inverse ((1:R) - t) = (∑ i in range n, t ^ i) + (t ^ n) * inverse (1 - t) :=
begin
simp only [eventually_iff, metric.mem_nhds_iff],
use [1, by norm_num],
intros t ht,
simp only [mem_ball, dist_zero_right] at ht,
simp only [inverse_one_sub t ht, set.mem_set_of_eq],
have h : 1 = ((range n).sum (λ i, t ^ i)) * (units.one_sub t ht) + t ^ n,
{ simp only [units.coe_one_sub],
rw [geom_sum_mul_neg],
simp },
rw [← one_mul ↑(units.one_sub t ht)⁻¹, h, add_mul],
congr,
{ rw [mul_assoc, (units.one_sub t ht).mul_inv],
simp },
{ simp only [units.coe_one_sub],
rw [← add_mul, geom_sum_mul_neg],
simp }
end
/-- The formula
`inverse (x + t) = (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹ + (- x⁻¹ * t) ^ n * inverse (x + t)`
holds for `t` sufficiently small. -/
lemma inverse_add_nth_order (x : Rˣ) (n : ℕ) :
∀ᶠ t in (𝓝 0), inverse ((x : R) + t)
= (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹ + (- ↑x⁻¹ * t) ^ n * inverse (x + t) :=
begin
refine (inverse_add x).mp _,
have hzero : tendsto (λ (t : R), - ↑x⁻¹ * t) (𝓝 0) (𝓝 0),
{ convert ((mul_left_continuous (- (↑x⁻¹ : R))).tendsto 0).comp tendsto_id,
simp },
refine (hzero.eventually (inverse_one_sub_nth_order n)).mp (eventually_of_forall _),
simp only [neg_mul, sub_neg_eq_add],
intros t h1 h2,
have h := congr_arg (λ (a : R), a * ↑x⁻¹) h1,
dsimp at h,
convert h,
rw [add_mul, mul_assoc],
simp [h2.symm]
end
lemma inverse_one_sub_norm : (λ t : R, inverse (1 - t)) =O[𝓝 0] (λ t, 1 : R → ℝ) :=
begin
simp only [is_O, is_O_with, eventually_iff, metric.mem_nhds_iff],
refine ⟨∥(1:R)∥ + 1, (2:ℝ)⁻¹, by norm_num, _⟩,
intros t ht,
simp only [ball, dist_zero_right, set.mem_set_of_eq] at ht,
have ht' : ∥t∥ < 1,
{ have : (2:ℝ)⁻¹ < 1 := by cancel_denoms,
linarith },
simp only [inverse_one_sub t ht', norm_one, mul_one, set.mem_set_of_eq],
change ∥∑' n : ℕ, t ^ n∥ ≤ _,
have := normed_ring.tsum_geometric_of_norm_lt_1 t ht',
have : (1 - ∥t∥)⁻¹ ≤ 2,
{ rw ← inv_inv (2:ℝ),
refine inv_le_inv_of_le (by norm_num) _,
have : (2:ℝ)⁻¹ + (2:ℝ)⁻¹ = 1 := by ring,
linarith },
linarith
end
/-- The function `λ t, inverse (x + t)` is O(1) as `t → 0`. -/
lemma inverse_add_norm (x : Rˣ) : (λ t : R, inverse (↑x + t)) =O[𝓝 0] (λ t, (1:ℝ)) :=
begin
simp only [is_O_iff, norm_one, mul_one],
cases is_O_iff.mp (@inverse_one_sub_norm R _ _) with C hC,
use C * ∥((x⁻¹:Rˣ):R)∥,
have hzero : tendsto (λ t, - (↑x⁻¹ : R) * t) (𝓝 0) (𝓝 0),
{ convert ((mul_left_continuous (-↑x⁻¹ : R)).tendsto 0).comp tendsto_id,
simp },
refine (inverse_add x).mp ((hzero.eventually hC).mp (eventually_of_forall _)),
intros t bound iden,
rw iden,
simp at bound,
have hmul := norm_mul_le (inverse (1 + ↑x⁻¹ * t)) ↑x⁻¹,
nlinarith [norm_nonneg (↑x⁻¹ : R)]
end
/-- The function
`λ t, inverse (x + t) - (∑ i in range n, (- x⁻¹ * t) ^ i) * x⁻¹`
is `O(t ^ n)` as `t → 0`. -/
lemma inverse_add_norm_diff_nth_order (x : Rˣ) (n : ℕ) :
(λ t : R, inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹) =O[𝓝 (0:R)]
(λ t, ∥t∥ ^ n) :=
begin
by_cases h : n = 0,
{ simpa [h] using inverse_add_norm x },
have hn : 0 < n := nat.pos_of_ne_zero h,
simp [is_O_iff],
cases (is_O_iff.mp (inverse_add_norm x)) with C hC,
use C * ∥(1:ℝ)∥ * ∥(↑x⁻¹ : R)∥ ^ n,
have h : eventually_eq (𝓝 (0:R))
(λ t, inverse (↑x + t) - (∑ i in range n, (- ↑x⁻¹ * t) ^ i) * ↑x⁻¹)
(λ t, ((- ↑x⁻¹ * t) ^ n) * inverse (x + t)),
{ refine (inverse_add_nth_order x n).mp (eventually_of_forall _),
intros t ht,
convert congr_arg (λ a, a - (range n).sum (pow (-↑x⁻¹ * t)) * ↑x⁻¹) ht,
simp },
refine h.mp (hC.mp (eventually_of_forall _)),
intros t _ hLHS,
simp only [neg_mul] at hLHS,
rw hLHS,
refine le_trans (norm_mul_le _ _ ) _,
have h' : ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n,
{ calc ∥(-(↑x⁻¹ * t)) ^ n∥ ≤ ∥(-(↑x⁻¹ * t))∥ ^ n : norm_pow_le' _ hn
... = ∥↑x⁻¹ * t∥ ^ n : by rw norm_neg
... ≤ (∥(↑x⁻¹ : R)∥ * ∥t∥) ^ n : _
... = ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n : mul_pow _ _ n,
exact pow_le_pow_of_le_left (norm_nonneg _) (norm_mul_le ↑x⁻¹ t) n },
have h'' : 0 ≤ ∥(↑x⁻¹ : R)∥ ^ n * ∥t∥ ^ n,
{ refine mul_nonneg _ _;
exact pow_nonneg (norm_nonneg _) n },
nlinarith [norm_nonneg (inverse (↑x + t))],
end
/-- The function `λ t, inverse (x + t) - x⁻¹` is `O(t)` as `t → 0`. -/
lemma inverse_add_norm_diff_first_order (x : Rˣ) :
(λ t : R, inverse (↑x + t) - ↑x⁻¹) =O[𝓝 0] (λ t, ∥t∥) :=
by simpa using inverse_add_norm_diff_nth_order x 1
/-- The function
`λ t, inverse (x + t) - x⁻¹ + x⁻¹ * t * x⁻¹`
is `O(t ^ 2)` as `t → 0`. -/
lemma inverse_add_norm_diff_second_order (x : Rˣ) :
(λ t : R, inverse (↑x + t) - ↑x⁻¹ + ↑x⁻¹ * t * ↑x⁻¹) =O[𝓝 0] (λ t, ∥t∥ ^ 2) :=
begin
convert inverse_add_norm_diff_nth_order x 2,
ext t,
simp only [range_succ, range_one, sum_insert, mem_singleton, sum_singleton, not_false_iff,
one_ne_zero, pow_zero, add_mul, pow_one, one_mul, neg_mul,
sub_add_eq_sub_sub_swap, sub_neg_eq_add],
end
/-- The function `inverse` is continuous at each unit of `R`. -/
lemma inverse_continuous_at (x : Rˣ) : continuous_at inverse (x : R) :=
begin
have h_is_o : (λ t : R, inverse (↑x + t) - ↑x⁻¹) =o[𝓝 0] (λ _, 1 : R → ℝ) :=
(inverse_add_norm_diff_first_order x).trans_is_o (is_o.norm_left $ is_o_id_const one_ne_zero),
have h_lim : tendsto (λ (y:R), y - x) (𝓝 x) (𝓝 0),
{ refine tendsto_zero_iff_norm_tendsto_zero.mpr _,
exact tendsto_iff_norm_tendsto_zero.mp tendsto_id },
rw [continuous_at, tendsto_iff_norm_tendsto_zero, inverse_unit],
simpa [(∘)] using h_is_o.norm_left.tendsto_div_nhds_zero.comp h_lim
end
end normed_ring
namespace units
open mul_opposite filter normed_ring
/-- In a normed ring, the coercion from `Rˣ` (equipped with the induced topology from the
embedding in `R × R`) to `R` is an open map. -/
lemma is_open_map_coe : is_open_map (coe : Rˣ → R) :=
begin
rw is_open_map_iff_nhds_le,
intros x s,
rw [mem_map, mem_nhds_induced],
rintros ⟨t, ht, hts⟩,
obtain ⟨u, hu, v, hv, huvt⟩ :
∃ (u : set R), u ∈ 𝓝 ↑x ∧ ∃ (v : set Rᵐᵒᵖ), v ∈ 𝓝 (op ↑x⁻¹) ∧ u ×ˢ v ⊆ t,
{ simpa [embed_product, mem_nhds_prod_iff] using ht },
have : u ∩ (op ∘ ring.inverse) ⁻¹' v ∩ (set.range (coe : Rˣ → R)) ∈ 𝓝 ↑x,
{ refine inter_mem (inter_mem hu _) (units.nhds x),
refine (continuous_op.continuous_at.comp (inverse_continuous_at x)).preimage_mem_nhds _,
simpa using hv },
refine mem_of_superset this _,
rintros _ ⟨⟨huy, hvy⟩, ⟨y, rfl⟩⟩,
have : embed_product R y ∈ u ×ˢ v := ⟨huy, by simpa using hvy⟩,
simpa using hts (huvt this)
end
/-- In a normed ring, the coercion from `Rˣ` (equipped with the induced topology from the
embedding in `R × R`) to `R` is an open embedding. -/
lemma open_embedding_coe : open_embedding (coe : Rˣ → R) :=
open_embedding_of_continuous_injective_open continuous_coe ext is_open_map_coe
end units
|
dc8920dcc10d22da4ead9279df7facc6a7c3fa37 | 48eee836fdb5c613d9a20741c17db44c8e12e61c | /src/universal/substitution.lean | 2bae5b67cf9aa5fa877a0ac356b2b6c1046a7e9f | [
"Apache-2.0"
] | permissive | fgdorais/lean-universal | 06430443a4abe51e303e602684c2977d1f5c0834 | 9259b0f7fb3aa83a9e0a7a3eaa44c262e42cc9b1 | refs/heads/master | 1,592,479,744,136 | 1,589,473,399,000 | 1,589,473,399,000 | 196,287,552 | 1 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 4,114 | lean | -- Copyright © 2019 François G. Dorais. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
import .basic
namespace universal
variables {τ : Type} {σ : Type*} (sig : signature τ σ)
abbreviation substitution (dom₁ dom₂ : list τ) := Π (i : index dom₁), term sig dom₂ i.val
namespace substitution
variables {sig} {dom₁ dom₂ dom₃ : list τ} (sub : substitution sig dom₁ dom₂)
abbreviation to_valuation : algebra.valuation (term_algebra sig dom₂) dom₁ := sub
abbreviation apply {cod} (t : term sig dom₁ cod) : term sig dom₂ cod :=
algebra.eval (term_algebra sig dom₂) t sub
theorem apply_def {cod} (t : term sig dom₁ cod) : sub.apply t = (term_algebra sig dom₂).eval t sub := rfl
theorem apply_proj {i : index dom₁} : sub.apply (term.proj i) = sub i := rfl
theorem apply_func {f} (ts : Π (i : sig.index f), term sig dom₁ i.val) :
sub.apply (term.func f ts) = term.func f (λ i, sub.apply (ts i)) := rfl
theorem eval (alg : algebra sig) : ∀ {cod} (t : term sig dom₁ cod) (val : Π (i : index dom₂), alg.sort i.val),
alg.eval (sub.apply t) val = alg.eval t (λ i, alg.eval (sub i) val)
| _ (term.proj i) val := rfl
| _ (term.func f ts) val :=
have IH : (λ i, alg.eval (sub.apply (ts i)) val) = (λ i, alg.eval (ts i) (λ i, alg.eval (sub i) val)),
from funext $ λ i, eval (ts i) val,
calc alg.eval (sub.apply (term.func f ts)) val
= alg.func f (λ i, alg.eval (sub.apply (ts i)) val) : rfl ...
= alg.func f (λ i, alg.eval (ts i) (λ i, alg.eval (sub i) val)) : by rw IH ...
= alg.eval (term.func f ts) (λ (i : index dom₁), alg.eval (sub i) val) : by reflexivity
abbreviation id {dom : list τ} : substitution sig dom dom := term.proj
@[simp] theorem id_apply {dom : list τ} : ∀ {cod} (t : term sig dom cod), substitution.id.apply t = t
| _ (term.proj _) := rfl
| _ (term.func f ts) :=
have (λ i, apply id (ts i)) = ts,
from funext $ λ i, id_apply (ts i),
calc apply id (term.func f ts)
= term.func f (λ i, apply id (ts i)) : rfl ...
= term.func f ts : by rw this
abbreviation comp : substitution sig dom₂ dom₃ → substitution sig dom₁ dom₂ → substitution sig dom₁ dom₃ :=
λ sub₂₃ sub₁₂ i, sub₂₃.apply (sub₁₂ i)
@[simp] theorem comp_apply (sub₂₃ : substitution sig dom₂ dom₃) (sub₁₂ : substitution sig dom₁ dom₂) :
∀ {cod} (t : term sig dom₁ cod), (comp sub₂₃ sub₁₂).apply t = sub₂₃.apply (sub₁₂.apply t)
| _ (term.proj _) := rfl
| _ (term.func f ts) :=
have (λ i, (comp sub₂₃ sub₁₂).apply (ts i)) = (λ i, sub₂₃.apply (sub₁₂.apply (ts i))),
from funext $ λ i, comp_apply (ts i),
calc (comp sub₂₃ sub₁₂).apply (term.func f ts)
= term.func f (λ i, (comp sub₂₃ sub₁₂).apply (ts i)) : rfl ...
= term.func f (λ i, sub₂₃.apply (sub₁₂.apply (ts i))) : by rw this ...
= sub₂₃.apply (term.func f (λ i, sub₁₂.apply (ts i))) : by rw apply_func sub₂₃ ...
= sub₂₃.apply (apply sub₁₂ (term.func f ts)) : by rw apply_func sub₁₂
end substitution
section subst
variables {sig} {dom₁ dom₂ : list τ} (sub : substitution sig dom₁ dom₂)
abbreviation term.subst {{cod}} : term sig dom₁ cod → term sig dom₂ cod := sub.apply
abbreviation equation.subst {{cod}} : equation sig dom₁ cod → equation sig dom₂ cod :=
λ e, ⟨sub.apply e.lhs, sub.apply e.rhs⟩
theorem equation.subst_lhs {cod} (e : equation sig dom₁ cod) : (e.subst sub).lhs = e.lhs.subst sub := rfl
theorem equation.subst_rhs {cod} (e : equation sig dom₁ cod) : (e.subst sub).rhs = e.rhs.subst sub := rfl
theorem subst_subst {dom₁ dom₂ dom₃ : list τ} (sub₂₃ : substitution sig dom₂ dom₃) (sub₁₂ : substitution sig dom₁ dom₂) {cod} (t : term sig dom₁ cod) :
t.subst (λ i, (sub₁₂ i).subst sub₂₃) = (t.subst sub₁₂).subst sub₂₃ := substitution.comp_apply sub₂₃ sub₁₂ t
@[simp] theorem subst_proj {dom} {cod} (t : term sig dom cod) : t.subst term.proj = t := substitution.id_apply t
end subst
end universal
|
f6ebdd7c9749b726940ba4bdb83b31f783ec4de1 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/whnfProj.lean | 27256d98302b93b9e3e0336cdafeed54847c137b | [
"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 | 523 | lean | import Lean
def h (x : Nat) := x
def f (x : Nat) := x + 1
def g (x : Nat) := (x, x+1).fst
open Lean
open Lean.Meta
def tst (declName : Name) : MetaM Unit := do
let c ← getConstInfo declName
lambdaTelescope c.value! fun _ b => do
trace[Meta.debug] "1. {b}"
trace[Meta.debug] "2. {← withReducible <| whnf b}"
trace[Meta.debug] "3. {← withReducibleAndInstances <| whnf b}"
trace[Meta.debug] "4. {← withDefault <| whnf b}"
pure ()
set_option trace.Meta.debug true
#eval tst `f
#eval tst `g
|
1e3eeba21173f538eb8c0c0c4667d4034342a665 | a9fe717b93ccfa4b2e64faeb24f96dfefb390240 | /int.lean | 0e144d212e6bbf50d03d448cec55cec4dad4ec17 | [] | no_license | skbaek/omega | ab1f4a6daadfc8c855f14c39d9459ab841527141 | 715e384ed14e8eb177a326700066e7c98269e078 | refs/heads/master | 1,588,000,876,352 | 1,552,645,917,000 | 1,552,645,917,000 | 174,442,914 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,775 | lean | import .list data.int.basic .logic
namespace int
lemma add_div {a b c : int} :
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 eq_of_mul_eq_mul_right h3,
rw add_mul, repeat {rw [int.div_mul_cancel]};
try {apply dvd_add}; assumption }
end
end int
def ints.gcd : list int → nat
| [] := 0
| (i::is) := nat.gcd i.nat_abs (ints.gcd is)
lemma forall_mem_nil_eq_zero : ∀ x : int, x ∈ ([] : list int) → x = (0 : int) :=
begin intros x h1, cases h1 end
lemma forall_mem_cons_eq_zero (i : int) (is : list int) :
(i = (0 : int)) →
(∀ x : int, x ∈ is → x = (0 : int)) →
(∀ x : int, x ∈ (i::is) → x = (0 : int)) :=
begin
intros h1 h2, rw list.forall_mem_cons,
constructor; assumption
end
meta instance int.has_reflect : has_reflect int := by tactic.mk_has_reflect_instance
def symdiv (i j : int) : int :=
if (2 * (i % j)) < j
then i / j
else (i / j) + 1
def symmod (i j : int) : int :=
if (2 * (i % j)) < j
then i % j
else (i % j) - j
lemma symmod_add_one {i} :
0 < i → symmod i (i+1) = -1 :=
begin
intro h1,
simp only [symmod],
rw int.mod_eq_of_lt (le_of_lt h1) (lt_add_one _),
rw if_neg, simp,
have h2 : 2 * i = (1 + 1) * i := rfl,
simp [h2, add_mul], apply h1
end
lemma mul_symdiv_eq {i j} :
j * (symdiv i j) = i - (symmod i j) :=
begin
simp only [symdiv, symmod],
by_cases h1 : (2 * (i % j)) < j,
{ repeat {rw if_pos h1},
rw [int.mod_def, sub_sub_cancel] },
{ repeat {rw if_neg h1},
rw [int.mod_def, sub_sub, sub_sub_cancel,
mul_add, mul_one] }
end
lemma symmod_eq {i j} :
symmod i j = i - j * (symdiv i j) :=
by rw [mul_symdiv_eq, sub_sub_cancel] |
95de1ad57d65b846e89e32aa8587b8b3bb1ed809 | e5c11e5a7d990ce404047c2bd848eeafac3c0a85 | /src/class_group.lean | f3f307dd66ee3de87fbefade3c48ad7f4e1dfc6b | [
"LPPL-1.3c"
] | permissive | lean-forward/class-number | 9ec63c24845e46efc8fa8b15324d0815918292c7 | 4fccf36d5e0e16accae84c16df77a3839ad964e4 | refs/heads/main | 1,686,927,014,542 | 1,624,886,724,000 | 1,624,886,724,000 | 327,319,245 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,894 | lean | /-
Copyright (c) 2021 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Anne Baanen
-/
import group_theory.quotient_group
import ring_theory.dedekind_domain
/-!
# The ideal class group
This file defines the ideal class group `class_group f` of fractional ideals
with respect to the fraction map `f`.
## Main definitions
- `to_principal_ideal` sends an invertible `x : f.codomain` to an invertible fractional ideal
- `class_group` is the quotient of invertible fractional ideals modulo `to_principal_ideal.range`
- `class_group.mk0` sends a nonzero integral ideal in a Dedekind domain to its class
## Main results
- `class_group.mk0_eq_mk0_iff` shows the equivalence with the "classical" definition,
where `I ~ J` iff `x I = y J` for `x y ≠ (0 : R)`
-/
open ring
open ring.fractional_ideal
section integral_domain
variables {R K L : Type*} [integral_domain R]
variables [field K] [field L] [decidable_eq L]
variables (f : fraction_map R K)
variables [algebra f.codomain L] [finite_dimensional f.codomain L]
variables [algebra R L] [is_scalar_tower R f.codomain L]
open ring.fractional_ideal units
section
/-- `to_principal_ideal x` sends `x ≠ 0 : K` to the fractional ideal generated by `x` -/
@[irreducible]
def to_principal_ideal : units f.codomain →* units (fractional_ideal f) :=
{ to_fun := λ x,
⟨ span_singleton x,
span_singleton x⁻¹,
by simp only [span_singleton_one, units.mul_inv', span_singleton_mul_span_singleton],
by simp only [span_singleton_one, units.inv_mul', span_singleton_mul_span_singleton]⟩,
map_mul' := λ x y, ext
(by simp only [units.coe_mk, units.coe_mul, span_singleton_mul_span_singleton]),
map_one' := ext (by simp only [span_singleton_one, units.coe_mk, units.coe_one]) }
local attribute [semireducible] to_principal_ideal
variables {f}
@[simp] lemma coe_to_principal_ideal (x : units f.codomain) :
(to_principal_ideal f x : fractional_ideal f) = span_singleton x :=
rfl
@[simp] lemma to_principal_ideal_eq_iff {I : units (fractional_ideal f)} {x : units f.codomain} :
to_principal_ideal f x = I ↔ span_singleton (x : f.codomain) = I :=
units.ext_iff
end
instance principal_ideals.normal : (to_principal_ideal f).range.normal :=
subgroup.normal_of_comm _
section
/-- The class group with respect to `f : fraction_map R K`
is the group of invertible fractional ideals modulo the principal ideals. -/
@[derive(comm_group)]
def class_group := quotient_group.quotient (to_principal_ideal f).range
instance : inhabited (class_group f) := ⟨1⟩
@[simp] lemma fractional_ideal.coe_to_fractional_ideal_top :
((⊤ : ideal R) : fractional_ideal f) = 1 :=
by { rw [← ideal.one_eq_top], refl }
@[simp] lemma units.mk0_one {M : Type*} [group_with_zero M] (h) :
units.mk0 (1 : M) h = 1 :=
by { ext, refl }
@[simp] lemma units.mk0_map {M : Type*} [group_with_zero M] (x y : M) (hxy) :
mk0 (x * y) hxy = mk0 x (mul_ne_zero_iff.mp hxy).1 * mk0 y (mul_ne_zero_iff.mp hxy).2 :=
by { ext, refl }
/-- The monoid of nonzero ideals. -/
def nonzero_ideal (R : Type*) [integral_domain R] : submonoid (ideal R) :=
{ carrier := {I | I ≠ ⊥},
one_mem' := show (1 : ideal R) ≠ ⊥, by { rw ideal.one_eq_top, exact submodule.bot_ne_top.symm },
mul_mem' := λ I J (hI : I ≠ ⊥) (hJ : J ≠ ⊥), show I * J ≠ ⊥,
by { obtain ⟨x, x_mem, x_ne⟩ := I.ne_bot_iff.mp hI,
obtain ⟨y, y_mem, y_ne⟩ := J.ne_bot_iff.mp hJ,
exact (submodule.ne_bot_iff _).mpr
⟨x * y, ideal.mul_mem_mul x_mem y_mem, mul_ne_zero x_ne y_ne⟩ } }
/-- Send a nonzero ideal to the corresponding class in the class group. -/
noncomputable def class_group.mk0 [is_dedekind_domain R] :
nonzero_ideal R →* class_group f :=
(quotient_group.mk' _).comp
{ to_fun := λ I, units.mk0 I
((fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors R))).mpr I.2),
map_one' := by simp,
map_mul' := λ x y, by simp }
lemma quotient_group.mk'_eq_mk' {G : Type*} [group G] {N : subgroup G} [hN : N.normal] {x y : G} :
quotient_group.mk' N x = quotient_group.mk' N y ↔ ∃ z ∈ N, x * z = y :=
(@quotient.eq _ (quotient_group.left_rel _) _ _).trans
⟨λ (h : x⁻¹ * y ∈ N), ⟨_, h, by rw [← mul_assoc, mul_right_inv, one_mul]⟩,
λ ⟨z, z_mem, eq_y⟩,
by { rw ← eq_y, show x⁻¹ * (x * z) ∈ N, rwa [← mul_assoc, mul_left_inv, one_mul] }⟩
lemma ideal.mem_mul_span_singleton {x y : R} {I : ideal R} :
x ∈ I * ideal.span {y} ↔ ∃ z ∈ I, z * y = x :=
submodule.mem_smul_span_singleton
lemma ideal.mem_span_singleton_mul {x y : R} {I : ideal R} :
x ∈ ideal.span {y} * I ↔ ∃ z ∈ I, y * z = x :=
by simp only [mul_comm, ideal.mem_mul_span_singleton]
lemma ideal.le_span_singleton_mul_iff {x : R} {I J : ideal R} :
I ≤ ideal.span {x} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI :=
show (∀ {zI} (hzI : zI ∈ I), zI ∈ ideal.span {x} * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI,
by simp only [ideal.mem_span_singleton_mul]
lemma ideal.span_singleton_mul_le_iff {x : R} {I J : ideal R} :
ideal.span {x} * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J :=
begin
simp only [ideal.mul_le, ideal.mem_span_singleton_mul, ideal.mem_span_singleton],
split,
{ intros h zI hzI,
exact h x (dvd_refl x) zI hzI },
{ rintros h _ ⟨z, rfl⟩ zI hzI,
rw [mul_comm x z, mul_assoc],
exact J.mul_mem_left _ (h zI hzI) },
end
lemma ideal.span_singleton_mul_le_span_singleton_mul {x y : R} {I J : ideal R} :
ideal.span {x} * I ≤ ideal.span {y} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ :=
by simp only [ideal.span_singleton_mul_le_iff, ideal.mem_span_singleton_mul, eq_comm]
lemma ideal.eq_singleton_mul {x : R} (I J : ideal R) :
I = ideal.span {x} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ (∀ z ∈ J, x * z ∈ I)) :=
by simp only [le_antisymm_iff, ideal.le_span_singleton_mul_iff, ideal.span_singleton_mul_le_iff]
lemma ideal.singleton_mul_eq_singleton_mul {x y : R} (I J : ideal R) :
ideal.span {x} * I = ideal.span {y} * J ↔
((∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ) ∧
(∀ zJ ∈ J, ∃ zI ∈ I, x * zI = y * zJ)) :=
by simp only [le_antisymm_iff, ideal.span_singleton_mul_le_span_singleton_mul, eq_comm]
lemma fractional_ideal.le_span_singleton_mul_iff {x : f.codomain} {I J : fractional_ideal f} :
I ≤ span_singleton x * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI :=
show (∀ {zI} (hzI : zI ∈ I), zI ∈ span_singleton x * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI,
by { simp only [fractional_ideal.mem_singleton_mul, eq_comm], refl }
lemma fractional_ideal.span_singleton_mul_le_iff {x : f.codomain} {I J : fractional_ideal f} :
span_singleton x * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J :=
begin
simp only [fractional_ideal.mul_le, fractional_ideal.mem_singleton_mul,
fractional_ideal.mem_span_singleton],
split,
{ intros h zI hzI,
exact h x ⟨1, one_smul _ _⟩ zI hzI },
{ rintros h _ ⟨z, rfl⟩ zI hzI,
rw [algebra.smul_mul_assoc],
exact submodule.smul_mem J.1 _ (h zI hzI) },
end
lemma fractional_ideal.eq_span_singleton_mul {x : f.codomain} {I J : fractional_ideal f} :
I = span_singleton x * J ↔ (∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ ∀ z ∈ J, x * z ∈ I :=
by simp only [le_antisymm_iff, fractional_ideal.le_span_singleton_mul_iff,
fractional_ideal.span_singleton_mul_le_iff]
lemma class_group.mk0_eq_mk0_iff [is_dedekind_domain R]
(I J : nonzero_ideal R) :
class_group.mk0 f I = class_group.mk0 f J ↔
∃ (x y : R) (hx : x ≠ 0) (hy : y ≠ 0), ideal.span {x} * (I : ideal R) = ideal.span {y} * J :=
begin
simp only [class_group.mk0, monoid_hom.comp_apply, monoid_hom.coe_mk, quotient_group.mk'_eq_mk',
exists_prop, monoid_hom.mem_range, ideal.singleton_mul_eq_singleton_mul],
split,
{ rintros ⟨z, ⟨xy, hxy, rfl⟩, eq_J⟩,
have : (J : fractional_ideal f) = (span_singleton xy * I),
{ simpa only [mul_comm, eq_comm, coe_mk0, monoid_hom.to_fun_eq_coe, coe_to_principal_ideal,
units.coe_mul]
using congr_arg (coe : _ → fractional_ideal f) eq_J },
obtain ⟨hJI, hIJ⟩ := (fractional_ideal.eq_span_singleton_mul _).mp this,
have hx : (f.to_localization_map.sec (xy : f.codomain)).1 ≠ 0,
{ suffices : f.to_map (f.to_localization_map.sec (xy : f.codomain)).1 ≠ 0,
{ refine mt (λ h, _) this,
rw [h, ring_hom.map_zero] },
rw [ne.def, ← localization_map.sec_spec (xy : f.codomain), mul_eq_zero],
push_neg,
use xy.ne_zero,
exact f.to_map_ne_zero_of_mem_non_zero_divisors _ },
use [(f.to_localization_map.sec (xy : f.codomain)).1,
(f.to_localization_map.sec (xy : f.codomain)).2,
hx,
non_zero_divisors.ne_zero_of_mem (f.to_localization_map.sec (xy : f.codomain)).2.2],
have x_eq : (xy * f.to_map (f.to_localization_map.sec (xy : f.codomain)).2 : f.codomain) =
f.to_map (f.to_localization_map.sec (xy : f.codomain)).1 :=
localization_map.sec_spec (xy : f.codomain),
split,
{ intros zI hzI,
obtain ⟨zJ, hzJ, (zJ_eq : f.to_map zJ = _ * f.to_map _)⟩ := hIJ (f.to_map zI) _,
{ use [zJ, hzJ],
apply f.injective,
rw [f.to_map.map_mul, f.to_map.map_mul, zJ_eq, ← x_eq],
ac_refl },
{ simpa only [exists_prop, mem_coe_ideal, exists_mem_to_map_eq, coe_coe] using hzI } },
{ intros zJ hzJ,
obtain ⟨zI', hzI', eq_zJ⟩ := hJI (f.to_map zJ) _,
obtain ⟨zI, hzI, rfl⟩ := fractional_ideal.mem_coe_ideal.mp hzI',
{ use [zI, hzI],
apply f.injective,
rw [f.to_map.map_mul, f.to_map.map_mul, ← eq_zJ, ← x_eq],
ac_refl },
{ simpa only [exists_prop, mem_coe_ideal, exists_mem_to_map_eq, coe_coe] using hzJ } } },
{ rintros ⟨x, y, hx, hy, hIJ, hJI⟩,
have hy' := mem_non_zero_divisors_iff_ne_zero.mpr hy,
refine ⟨_, ⟨units.mk0 (f.mk' x ⟨y, hy'⟩) _, rfl⟩, _⟩,
{ rw [ne.def, f.mk'_eq_iff_eq_mul, zero_mul],
exact mt (f.to_map.injective_iff.mp f.injective _) hx },
suffices : (J : fractional_ideal f) = span_singleton (f.mk' x ⟨y, _⟩) * I,
{ apply units.ext,
simpa only [mul_comm, eq_comm, coe_mk0, coe_to_principal_ideal, units.coe_mul] using this },
refine (fractional_ideal.eq_span_singleton_mul _).mpr ⟨_, _⟩,
{ intros zJ' hzJ',
obtain ⟨zJ, hzJ, rfl⟩ := mem_coe_ideal.mp hzJ',
obtain ⟨zI, hzI, x_mul_eq_y_mul⟩ := hJI zJ hzJ,
refine ⟨f.to_map zI, mem_coe_ideal.mpr ⟨zI, hzI, rfl⟩, _⟩,
apply mul_left_cancel' (f.to_map_ne_zero_of_mem_non_zero_divisors ⟨y, hy'⟩),
rw [← mul_assoc, localization_map.mk'_spec', ← ring_hom.map_mul, ← ring_hom.map_mul,
x_mul_eq_y_mul, subtype.coe_mk] },
{ intros zI' hzI',
obtain ⟨zI, hzI, rfl⟩ := mem_coe_ideal.mp hzI',
obtain ⟨zJ, hzJ, x_mul_eq_y_mul⟩ := hIJ zI hzI,
refine mem_coe_ideal.mpr ⟨zJ, hzJ, _⟩,
apply mul_left_cancel' (f.to_map_ne_zero_of_mem_non_zero_divisors ⟨y, hy'⟩),
rw [← mul_assoc, localization_map.mk'_spec', ← ring_hom.map_mul, ← ring_hom.map_mul,
x_mul_eq_y_mul, subtype.coe_mk] } },
end
lemma class_group.mk0_surjective [is_dedekind_domain R] : function.surjective (class_group.mk0 f) :=
begin
rintros ⟨I⟩,
obtain ⟨a, a_ne_zero', ha⟩ := I.1.2,
have a_ne_zero := non_zero_divisors.ne_zero_of_mem a_ne_zero',
have fa_ne_zero : f.to_map a ≠ 0 := f.to_map_ne_zero_of_mem_non_zero_divisors ⟨a, a_ne_zero'⟩,
refine ⟨⟨{ carrier := { x | (f.to_map a)⁻¹ * f.to_map x ∈ I.1 }, .. }, _⟩, _⟩,
{ simp only [ring_hom.map_zero, set.mem_set_of_eq, mul_zero, ring_hom.map_mul],
exact submodule.zero_mem I },
{ simp only [ring_hom.map_add, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add],
exact λ _ _ ha hb, submodule.add_mem I ha hb },
{ simp only [smul_eq_mul, set.mem_set_of_eq, mul_zero, ring_hom.map_mul, mul_add,
mul_left_comm (f.to_map a)⁻¹],
exact λ c _ hb, submodule.smul_mem I c hb },
{ apply (submodule.ne_bot_iff _).mpr,
obtain ⟨x, x_ne, x_mem⟩ := exists_ne_zero_mem_is_integer I.ne_zero,
refine ⟨a * x, _, mul_ne_zero a_ne_zero x_ne⟩,
change (f.to_map a)⁻¹ * f.to_map (a * x) ∈ I.1,
rwa [ring_hom.map_mul, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] },
{ symmetry,
apply quotient.sound,
refine ⟨units.mk0 (f.to_map a) fa_ne_zero, _⟩,
apply @mul_left_cancel _ _ I,
rw [← mul_assoc, mul_right_inv, one_mul, eq_comm, mul_comm I],
simp only [monoid_hom.coe_mk, subtype.coe_mk, ring_hom.map_mul, coe_coe],
apply units.ext,
simp only [units.coe_mul, coe_to_principal_ideal, coe_mk0,
fractional_ideal.eq_span_singleton_mul],
split,
{ intros zJ' hzJ',
obtain ⟨zJ, hzJ : (f.to_map a)⁻¹ * f.to_map zJ ∈ (I : fractional_ideal f), rfl⟩ :=
mem_coe_ideal.mp hzJ',
refine ⟨_, hzJ, _⟩,
rw [← mul_assoc, mul_inv_cancel fa_ne_zero, one_mul] },
{ intros zI' hzI',
rw mem_coe_ideal,
obtain ⟨y, hy⟩ := ha zI' hzI',
refine ⟨y, _, hy⟩,
show (f.to_map a)⁻¹ * f.to_map y ∈ (I : fractional_ideal f),
rwa [hy, ← mul_assoc, inv_mul_cancel fa_ne_zero, one_mul] } }
end
end
instance submodule.is_principal_bot {R M : Type*} [ring R] [add_comm_group M] [module R M] :
(⊥ : submodule R M).is_principal :=
⟨⟨0, submodule.span_zero_singleton.symm⟩⟩
lemma class_group.mk_eq_one_iff [is_dedekind_domain R]
{I : units (fractional_ideal f)} :
quotient_group.mk' (to_principal_ideal f).range I = 1 ↔
(I : submodule R f.codomain).is_principal :=
begin
rw [← (quotient_group.mk' _).map_one, eq_comm, quotient_group.mk'_eq_mk'],
simp only [exists_prop, one_mul, exists_eq_right, to_principal_ideal_eq_iff,
monoid_hom.mem_range, coe_coe],
refine ⟨λ ⟨x, hx⟩, ⟨⟨x, by rw [← hx, coe_span_singleton]⟩⟩, _⟩,
unfreezingI { intros hI },
obtain ⟨x, hx⟩ := @submodule.is_principal.principal _ _ _ _ _ _ hI,
have hx' : (I : fractional_ideal f) = span_singleton x,
{ apply subtype.coe_injective, rw [hx, coe_span_singleton] },
refine ⟨units.mk0 x _, _⟩,
{ intro x_eq, apply units.ne_zero I, simp [hx', x_eq] },
simp [hx']
end
@[simp] lemma localization_map.to_map_mem_coe_submodule {I : ideal R} {x : R} :
f.to_map x ∈ f.coe_submodule I ↔ x ∈ I :=
(localization_map.mem_coe_submodule _).trans
⟨λ ⟨y, hy, y_eq⟩, by rwa ← f.injective y_eq,
λ hx, ⟨x, hx, rfl⟩⟩
@[simp]
lemma localization_map.coe_submodule_injective : function.injective f.coe_submodule :=
λ I J h, submodule.ext (λ x, by simp only [← f.to_map_mem_coe_submodule, h])
@[simp]
lemma localization_map.coe_submodule_le {I : ideal R} {J : submodule R f.codomain} :
f.coe_submodule I ≤ J ↔ submodule.map f.lin_coe I ≤ J :=
iff.rfl
@[simp]
lemma localization_map.coe_submodule_span_singleton (x : R) :
f.coe_submodule (submodule.span R {x}) = submodule.span R {f.to_map x} :=
by rw [localization_map.coe_submodule, submodule.map_span, set.image_singleton,
localization_map.lin_coe_apply]
@[simp]
lemma localization_map.coe_submodule_is_principal {I : ideal R} :
(f.coe_submodule I).is_principal ↔ I.is_principal :=
begin
split;
unfreezingI { intros hI };
obtain ⟨x, hx⟩ := @submodule.is_principal.principal _ _ _ _ _ _ hI,
{ have x_mem : x ∈ f.coe_submodule I := hx.symm ▸ submodule.mem_span_singleton_self x,
obtain ⟨x, x_mem, rfl⟩ := (localization_map.mem_coe_submodule _).mp x_mem,
refine ⟨⟨x, localization_map.coe_submodule_injective f _⟩⟩,
rw [hx, localization_map.coe_submodule_span_singleton] },
{ refine ⟨⟨f.to_map x, _⟩⟩,
rw [hx, f.coe_submodule_span_singleton] }
end
lemma class_group.mk0_eq_one_iff [is_dedekind_domain R]
{I : ideal R} (hI : I ≠ 0) :
class_group.mk0 f ⟨I, hI⟩ = 1 ↔ I.is_principal :=
(class_group.mk_eq_one_iff _).trans f.coe_submodule_is_principal
/-- The class number is `1` iff the ring of integers is a principal ideal domain. -/
lemma card_class_group_eq_one_iff [is_dedekind_domain R] [fintype (class_group f)] :
fintype.card (class_group f) = 1 ↔ is_principal_ideal_ring R :=
begin
rw fintype.card_eq_one_iff,
split,
{ rintros ⟨I, hI⟩,
have eq_one : ∀ J : class_group f, J = 1 := λ J, trans (hI J) (hI 1).symm,
refine ⟨λ I, _⟩,
by_cases hI : I = ⊥,
{ rw hI, exact submodule.is_principal_bot },
exact (class_group.mk0_eq_one_iff f hI).mp (eq_one _) },
{ unfreezingI { intros hpid },
use 1,
rintros ⟨I⟩,
exact (class_group.mk_eq_one_iff f).mpr (I : fractional_ideal f).is_principal }
end
end integral_domain
|
bd611b67b31b81afe5e689f5f5facb8a17fe3c0e | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/order/filter/lift.lean | e2fafe9d12e8e23c6ac14e231585bcdc004e977f | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 18,013 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Lift filters along filter and set functions.
-/
import order.filter.basic
open lattice set
open_locale classical
namespace filter
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Sort*}
section lift
/-- A variant on `bind` using a function `g` taking a set instead of a member of `α`.
This is essentially a push-forward along a function mapping each set to a filter. -/
protected def lift (f : filter α) (g : set α → filter β) :=
⨅s ∈ f.sets, g s
variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β}
lemma lift_sets_eq (hg : monotone g) : (f.lift g).sets = (⋃t∈f.sets, (g t).sets) :=
binfi_sets_eq
(assume s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht,
hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩)
⟨univ, univ_mem_sets⟩
lemma mem_lift_iff (hg : monotone g) {s : set β} : s ∈ f.lift g ↔ s ∈ ⋃t∈f.sets, (g t).sets :=
show s ∈ (f.lift g).sets ↔ _, by rw lift_sets_eq hg
lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f.sets) (hs : s ∈ (g t).sets) :
s ∈ (f.lift g).sets :=
le_principal_iff.mp $ show f.lift g ≤ principal s,
from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs
lemma mem_lift_sets (hg : monotone g) {s : set β} :
s ∈ (f.lift g).sets ↔ (∃t∈f.sets, s ∈ (g t).sets) :=
by rw [lift_sets_eq hg]; simp only [mem_Union]
lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α}
(hs : s ∈ f.sets) (hg : g s ≤ h) : f.lift g ≤ h :=
infi_le_of_le s $ infi_le_of_le hs $ hg
lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β}
(hh : ∀s∈f.sets, h ≤ g s) : h ≤ f.lift g :=
le_infi $ assume s, le_infi $ assume hs, hh s hs
lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi2 $ assume hs, ⟨hf hs, hg s⟩
lemma lift_mono' (hg : ∀s∈f.sets, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, hg s hs
lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) :=
have monotone (map m ∘ g),
from map_mono.comp hg,
filter_eq $ set.ext $
by simp only [mem_lift_sets, hg, @mem_lift_sets _ _ f _ this, exists_prop, forall_const, mem_map, iff_self, function.comp_app]
lemma comap_lift_eq {m : γ → β} (hg : monotone g) : comap m (f.lift g) = f.lift (comap m ∘ g) :=
have monotone (comap m ∘ g),
from comap_mono.comp hg,
filter_eq $ set.ext begin
simp only [hg, @mem_lift_sets _ _ f _ this, comap, mem_lift_sets, mem_set_of_eq, exists_prop,
function.comp_apply],
exact λ s,
⟨λ ⟨b, ⟨a, ha, hb⟩, hs⟩, ⟨a, ha, b, hb, hs⟩,
λ ⟨a, ha, b, hb, hs⟩, ⟨b, ⟨a, ha, hb⟩, hs⟩⟩
end
theorem comap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) :
(comap m f).lift g = f.lift (g ∘ preimage m) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs,
infi_le_of_le (preimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩)
(le_infi $ assume s, le_infi $ assume ⟨s', hs', (h_sub : preimage m s' ⊆ s)⟩,
infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub)
lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) :
(map m f).lift g = f.lift (g ∘ image m) :=
le_antisymm
(infi_le_infi2 $ assume s, ⟨image m s,
infi_le_infi2 $ assume hs, ⟨
f.sets_of_superset hs $ assume a h, mem_image_of_mem _ h,
le_refl _⟩⟩)
(infi_le_infi2 $ assume t, ⟨preimage m t,
infi_le_infi2 $ assume ht, ⟨ht,
hg $ assume x, assume h : x ∈ m '' preimage m t,
let ⟨y, hy, h_eq⟩ := h in
show x ∈ t, from h_eq ▸ hy⟩⟩)
lemma lift_comm {g : filter β} {h : set α → set β → filter γ} :
f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
(le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
lemma lift_assoc {h : set β → filter γ} (hg : monotone g) :
(f.lift g).lift h = f.lift (λs, (g s).lift h) :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩)
(le_infi $ assume t, le_infi $ assume ht,
let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in
infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h')
lemma lift_lift_same_le_lift {g : set α → set α → filter β} :
f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) :=
le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs
lemma lift_lift_same_eq_lift {g : set α → set α → filter β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) :
f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) :=
le_antisymm
lift_lift_same_le_lift
(le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le (s ∩ t) $
infi_le_of_le (inter_mem_sets hs ht) $
calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _)
... ≤ g s t : hg₁ s (inter_subset_right _ _))
lemma lift_principal {s : set α} (hg : monotone g) :
(principal s).lift g = g s :=
le_antisymm
(infi_le_of_le s $ infi_le _ $ subset.refl _)
(le_infi $ assume t, le_infi $ assume hi, hg hi)
theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) :=
assume a b h, lift_mono (hf h) (hg h)
lemma lift_neq_bot_iff (hm : monotone g) : (f.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) :=
classical.by_cases
(assume hn : nonempty β,
calc f.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f.sets}, g s.val) ≠ ⊥ :
by simp only [filter.lift, infi_subtype, iff_self, ne.def]
... ↔ (∀s:{ s // s ∈ f.sets}, g s.val ≠ ⊥) :
infi_neq_bot_iff_of_directed hn
(assume ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩,
hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩)
... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨assume h s hs, h ⟨s, hs⟩, assume h ⟨s, hs⟩, h s hs⟩)
(assume hn : ¬ nonempty β,
have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn,
have h₂ : ∀s, g s = ⊥, from assume s, filter_eq_bot_of_not_nonempty hn,
calc (f.lift g ≠ ⊥) ↔ false : by simp only [h₁, iff_self, eq_self_iff_true, not_true, ne.def]
... ↔ (∀s∈f.sets, false) : ⟨false.elim, assume h, h univ univ_mem_sets⟩
... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp only [h₂, iff_self, eq_self_iff_true, not_true, ne.def])
@[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g :=
le_antisymm (lift_le univ_mem_sets $ le_refl g) (le_lift $ assume s hs, le_refl g)
@[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} :
f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h :=
by simp only [filter.lift, infi_inf_eq, eq_self_iff_true]
@[simp] lemma lift_principal2 {f : filter α} : f.lift principal = f :=
le_antisymm
(assume s hs, mem_lift hs (mem_principal_self s))
(le_infi $ assume s, le_infi $ assume hs, by simp only [hs, le_principal_iff])
lemma lift_infi {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
have g_mono : monotone g,
from assume s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h,
have ∀t∈(infi f).sets, (⨅ (i : ι), filter.lift (f i) g) ≤ g t,
from assume t ht, infi_sets_induct ht
(let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets)
(assume i s₁ s₂ hs₁ hs₂,
@hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂)
(assume s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁),
begin
simp only [mem_lift_iff g_mono, mem_Union, exists_imp_distrib],
exact assume t ht hs, this t ht hs
end)
end lift
section lift'
/-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `map`.
This is essentially a push-forward along a function mapping each set to a set. -/
protected def lift' (f : filter α) (h : set α → set β) :=
f.lift (principal ∘ h)
variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β}
lemma mem_lift' {t : set α} (ht : t ∈ f.sets) : h t ∈ (f.lift' h).sets :=
le_principal_iff.mp $ show f.lift' h ≤ principal (h t),
from infi_le_of_le t $ infi_le_of_le ht $ le_refl _
lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ (f.lift' h).sets ↔ (∃t∈f.sets, h t ⊆ s) :=
have monotone (principal ∘ h),
from assume a b h, principal_mono.mpr $ hh h,
by simp only [filter.lift', @mem_lift_sets α β f _ this, exists_prop, iff_self, mem_principal_sets, function.comp_app]
lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α}
(hs : s ∈ f.sets) (hg : principal (g s) ≤ h) : f.lift' g ≤ h :=
lift_le hs hg
lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ :=
lift_mono hf $ assume s, principal_mono.mpr $ hh s
lemma lift'_mono' (hh : ∀s∈f.sets, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ :=
infi_le_infi $ assume s, infi_le_infi $ assume hs, principal_mono.mpr $ hh s hs
lemma lift'_cong (hh : ∀s∈f.sets, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ :=
le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm)
lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) :=
calc map m (f.lift' h) = f.lift (map m ∘ principal ∘ h) :
map_lift_eq $ monotone_principal.comp hh
... = f.lift' (image m ∘ h) : by simp only [(∘), filter.lift', map_principal, eq_self_iff_true]
lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) :
(map m f).lift' g = f.lift' (g ∘ image m) :=
map_lift_eq2 $ monotone_principal.comp hg
theorem comap_lift'_eq {m : γ → β} (hh : monotone h) :
comap m (f.lift' h) = f.lift' (preimage m ∘ h) :=
calc comap m (f.lift' h) = f.lift (comap m ∘ principal ∘ h) :
comap_lift_eq $ monotone_principal.comp hh
... = f.lift' (preimage m ∘ h) : by simp only [(∘), filter.lift', comap_principal, eq_self_iff_true]
theorem comap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) :
(comap m f).lift' g = f.lift' (g ∘ preimage m) :=
comap_lift_eq2 $ monotone_principal.comp hg
lemma lift'_principal {s : set α} (hh : monotone h) :
(principal s).lift' h = principal (h s) :=
lift_principal $ monotone_principal.comp hh
lemma principal_le_lift' {t : set β} (hh : ∀s∈f.sets, t ⊆ h s) :
principal t ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, principal_mono.mpr (hh s hs)
theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) :=
assume a b h, lift'_mono (hf h) (hg h)
lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift h = f.lift (λs, h (g s)) :=
calc (f.lift' g).lift h = f.lift (λs, (principal (g s)).lift h) :
lift_assoc (monotone_principal.comp hg)
... = f.lift (λs, h (g s)) : by simp only [lift_principal, hh, eq_self_iff_true]
lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ}
(hg : monotone g) (hh : monotone h) :
(f.lift' g).lift' h = f.lift' (λs, h (g s)) :=
lift_lift'_assoc hg (monotone_principal.comp hh)
lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ}
(hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) :=
lift_assoc hg
lemma lift_lift'_same_le_lift' {g : set α → set α → set β} :
f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) :=
lift_lift_same_le_lift
lemma lift_lift'_same_eq_lift' {g : set α → set α → set β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) :
f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) :=
lift_lift_same_eq_lift
(assume s, monotone_principal.comp (hg₁ s))
(assume t, monotone_principal.comp (hg₂ t))
lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} :
f.lift' h ⊓ principal s = f.lift' (λt, h t ∩ s) :=
le_antisymm
(le_infi $ assume t, le_infi $ assume ht,
calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s :
inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _)
... = _ : by simp only [principal_eq_iff_eq, inf_principal, eq_self_iff_true, function.comp_app])
(le_inf
(le_infi $ assume t, le_infi $ assume ht,
infi_le_of_le t $ infi_le_of_le ht $
by simp only [le_principal_iff, inter_subset_left, mem_principal_sets, function.comp_app]; exact inter_subset_right _ _)
(infi_le_of_le univ $ infi_le_of_le univ_mem_sets $
by simp only [le_principal_iff, inter_subset_right, mem_principal_sets, function.comp_app]; exact inter_subset_left _ _))
lemma lift'_neq_bot_iff (hh : monotone h) : (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) :=
calc (f.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) :
lift_neq_bot_iff (monotone_principal.comp hh)
... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp only [principal_eq_bot_iff, iff_self, ne.def, principal_eq_bot_iff]
@[simp] lemma lift'_id {f : filter α} : f.lift' id = f :=
lift_principal2
lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β}
(h_le : ∀s∈f.sets, h s ∈ g.sets) : g ≤ f.lift' h :=
le_infi $ assume s, le_infi $ assume hs, by simp only [h_le, le_principal_iff, function.comp_app]; exact h_le s hs
lemma lift_infi' {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hf : directed (≥) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ assume i, lift_mono (infi_le _ _) (le_refl _))
(assume s,
begin
rw mem_lift_iff hg,
simp only [mem_Union, exists_imp_distrib, infi_sets_eq hf hι],
exact assume t i ht hs, mem_infi_sets i $ mem_lift ht hs
end)
lemma lift'_infi {f : ι → filter α} {g : set α → set β}
(hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f).lift' g = (⨅i, (f i).lift' g) :=
lift_infi hι $ by simp only [principal_eq_iff_eq, inf_principal, function.comp_app]; apply assume s t, hg
theorem comap_eq_lift' {f : filter β} {m : α → β} :
comap m f = f.lift' (preimage m) :=
filter_eq $ set.ext $ by simp only [mem_lift'_sets, monotone_preimage, comap, exists_prop, forall_const, iff_self, mem_set_of_eq]
end lift'
section prod
variables {f : filter α}
lemma prod_def {f : filter α} {g : filter β} : f.prod g = (f.lift $ λs, g.lift' $ set.prod s) :=
have ∀(s:set α) (t : set β),
principal (set.prod s t) = (principal s).comap prod.fst ⊓ (principal t).comap prod.snd,
by simp only [principal_eq_iff_eq, comap_principal, inf_principal]; intros; refl,
begin
simp only [filter.lift', function.comp, this, -comap_principal, lift_inf, lift_const, lift_inf],
rw [← comap_lift_eq monotone_principal, ← comap_lift_eq monotone_principal],
simp only [filter.prod, lift_principal2, eq_self_iff_true]
end
lemma prod_same_eq : filter.prod f f = f.lift' (λt, set.prod t t) :=
by rw [prod_def];
from lift_lift'_same_eq_lift'
(assume s, set.monotone_prod monotone_const monotone_id)
(assume t, set.monotone_prod monotone_id monotone_const)
lemma mem_prod_same_iff {s : set (α×α)} :
s ∈ (filter.prod f f).sets ↔ (∃t∈f.sets, set.prod t t ⊆ s) :=
by rw [prod_same_eq, mem_lift'_sets]; exact set.monotone_prod monotone_id monotone_id
lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} :
filter.tendsto f (filter.prod x x) y ↔
∀ W ∈ y.sets, ∃ U ∈ x.sets, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W :=
by simp only [tendsto_def, mem_prod_same_iff, prod_sub_preimage_iff, exists_prop, iff_self]
variables {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
lemma prod_lift_lift
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) :=
begin
simp only [prod_def],
rw [lift_assoc],
apply congr_arg, funext x,
rw [lift_comm],
apply congr_arg, funext y,
rw [lift'_lift_assoc],
exact hg₂,
exact hg₁
end
lemma prod_lift'_lift'
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) :=
begin
rw [prod_def, lift_lift'_assoc],
apply congr_arg, funext x,
rw [lift'_lift'_assoc],
exact hg₂,
exact set.monotone_prod monotone_const monotone_id,
exact hg₁,
exact (monotone_lift' monotone_const $ monotone_lam $
assume x, set.monotone_prod monotone_id monotone_const)
end
end prod
end filter
|
50559f588f74c9135a786b575e1fc25b135dc32f | c777c32c8e484e195053731103c5e52af26a25d1 | /src/data/dfinsupp/interval.lean | e010360860147d9dcae673a70a58623258f13c2f | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 6,802 | lean | /-
Copyright (c) 2021 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finset.locally_finite
import data.finset.pointwise
import data.fintype.big_operators
import data.dfinsupp.order
/-!
# Finite intervals of finitely supported functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides the `locally_finite_order` instance for `Π₀ i, α i` when `α` itself is locally
finite and calculates the cardinality of its finite intervals.
-/
open dfinsupp finset
open_locale big_operators pointwise
variables {ι : Type*} {α : ι → Type*}
namespace finset
variables [decidable_eq ι] [Π i, has_zero (α i)] {s : finset ι} {f : Π₀ i, α i}
{t : Π i, finset (α i)}
/-- Finitely supported product of finsets. -/
def dfinsupp (s : finset ι) (t : Π i, finset (α i)) : finset (Π₀ i, α i) :=
(s.pi t).map ⟨λ f, dfinsupp.mk s $ λ i, f i i.2, begin
refine (mk_injective _).comp (λ f g h, _),
ext i hi,
convert congr_fun h ⟨i, hi⟩,
end⟩
@[simp] lemma card_dfinsupp (s : finset ι) (t : Π i, finset (α i)) :
(s.dfinsupp t).card = ∏ i in s, (t i).card :=
(card_map _).trans $ card_pi _ _
variables [Π i, decidable_eq (α i)]
lemma mem_dfinsupp_iff : f ∈ s.dfinsupp t ↔ f.support ⊆ s ∧ ∀ i ∈ s, f i ∈ t i :=
begin
refine mem_map.trans ⟨_, _⟩,
{ rintro ⟨f, hf, rfl⟩,
refine ⟨support_mk_subset, λ i hi, _⟩,
convert mem_pi.1 hf i hi,
exact mk_of_mem hi },
{ refine λ h, ⟨λ i _, f i, mem_pi.2 h.2, _⟩,
ext i,
dsimp,
exact ite_eq_left_iff.2 (λ hi, (not_mem_support_iff.1 $ λ H, hi $ h.1 H).symm) }
end
/-- When `t` is supported on `s`, `f ∈ s.dfinsupp t` precisely means that `f` is pointwise in `t`.
-/
@[simp] lemma mem_dfinsupp_iff_of_support_subset {t : Π₀ i, finset (α i)} (ht : t.support ⊆ s) :
f ∈ s.dfinsupp t ↔ ∀ i, f i ∈ t i :=
begin
refine mem_dfinsupp_iff.trans (forall_and_distrib.symm.trans $ forall_congr $ λ i, ⟨λ h, _,
λ h, ⟨λ hi, ht $ mem_support_iff.2 $ λ H, mem_support_iff.1 hi _, λ _, h⟩⟩),
{ by_cases hi : i ∈ s,
{ exact h.2 hi },
{ rw [not_mem_support_iff.1 (mt h.1 hi), not_mem_support_iff.1 (not_mem_mono ht hi)],
exact zero_mem_zero } },
{ rwa [H, mem_zero] at h }
end
end finset
open finset
namespace dfinsupp
section bundled_singleton
variables [Π i, has_zero (α i)] {f : Π₀ i, α i} {i : ι} {a : α i}
/-- Pointwise `finset.singleton` bundled as a `dfinsupp`. -/
def singleton (f : Π₀ i, α i) : Π₀ i, finset (α i) :=
{ to_fun := λ i, {f i},
support' := f.support'.map $ λ s, ⟨s, λ i, (s.prop i).imp id (congr_arg _) ⟩ }
lemma mem_singleton_apply_iff : a ∈ f.singleton i ↔ a = f i := mem_singleton
end bundled_singleton
section bundled_Icc
variables [Π i, has_zero (α i)] [Π i, partial_order (α i)] [Π i, locally_finite_order (α i)]
{f g : Π₀ i, α i} {i : ι} {a : α i}
/-- Pointwise `finset.Icc` bundled as a `dfinsupp`. -/
def range_Icc (f g : Π₀ i, α i) : Π₀ i, finset (α i) :=
{ to_fun := λ i, Icc (f i) (g i),
support' := f.support'.bind $ λ fs, g.support'.map $ λ gs,
⟨fs + gs, λ i, or_iff_not_imp_left.2 $ λ h, begin
have hf : f i = 0 := (fs.prop i).resolve_left
(multiset.not_mem_mono (multiset.le.subset $ multiset.le_add_right _ _) h),
have hg : g i = 0 := (gs.prop i).resolve_left
(multiset.not_mem_mono (multiset.le.subset $ multiset.le_add_left _ _) h),
rw [hf, hg],
exact Icc_self _,
end⟩ }
@[simp] lemma range_Icc_apply (f g : Π₀ i, α i) (i : ι) : f.range_Icc g i = Icc (f i) (g i) := rfl
lemma mem_range_Icc_apply_iff : a ∈ f.range_Icc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc
lemma support_range_Icc_subset [decidable_eq ι] [Π i, decidable_eq (α i)] :
(f.range_Icc g).support ⊆ f.support ∪ g.support :=
begin
refine λ x hx, _,
by_contra,
refine not_mem_support_iff.2 _ hx,
rw [range_Icc_apply,
not_mem_support_iff.1 (not_mem_mono (subset_union_left _ _) h),
not_mem_support_iff.1 (not_mem_mono (subset_union_right _ _) h)],
exact Icc_self _,
end
end bundled_Icc
section pi
variables [Π i, has_zero (α i)] [decidable_eq ι] [Π i, decidable_eq (α i)]
/-- Given a finitely supported function `f : Π₀ i, finset (α i)`, one can define the finset
`f.pi` of all finitely supported functions whose value at `i` is in `f i` for all `i`. -/
def pi (f : Π₀ i, finset (α i)) : finset (Π₀ i, α i) := f.support.dfinsupp f
@[simp] lemma mem_pi {f : Π₀ i, finset (α i)} {g : Π₀ i, α i} : g ∈ f.pi ↔ ∀ i, g i ∈ f i :=
mem_dfinsupp_iff_of_support_subset $ subset.refl _
@[simp] lemma card_pi (f : Π₀ i, finset (α i)) : f.pi.card = f.prod (λ i, (f i).card) :=
begin
rw [pi, card_dfinsupp],
exact finset.prod_congr rfl (λ i _, by simp only [pi.nat_apply, nat.cast_id]),
end
end pi
section locally_finite
variables [decidable_eq ι] [Π i, decidable_eq (α i)]
variables [Π i, partial_order (α i)] [Π i, has_zero (α i)] [Π i, locally_finite_order (α i)]
instance : locally_finite_order (Π₀ i, α i) :=
locally_finite_order.of_Icc (Π₀ i, α i)
(λ f g, (f.support ∪ g.support).dfinsupp $ f.range_Icc g)
(λ f g x, begin
refine (mem_dfinsupp_iff_of_support_subset $ support_range_Icc_subset).trans _,
simp_rw [mem_range_Icc_apply_iff, forall_and_distrib],
refl,
end)
variables (f g : Π₀ i, α i)
lemma Icc_eq : Icc f g = (f.support ∪ g.support).dfinsupp (f.range_Icc g) := rfl
lemma card_Icc : (Icc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card :=
card_dfinsupp _ _
lemma card_Ico : (Ico f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 :=
by rw [card_Ico_eq_card_Icc_sub_one, card_Icc]
lemma card_Ioc : (Ioc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 :=
by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc]
lemma card_Ioo : (Ioo f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 2 :=
by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc]
end locally_finite
section canonically_ordered
variables [decidable_eq ι] [Π i, decidable_eq (α i)]
variables [Π i, canonically_ordered_add_monoid (α i)] [Π i, locally_finite_order (α i)]
variables (f : Π₀ i, α i)
lemma card_Iic : (Iic f).card = ∏ i in f.support, (Iic (f i)).card :=
by simp_rw [Iic_eq_Icc, card_Icc, dfinsupp.bot_eq_zero, support_zero, empty_union, zero_apply,
bot_eq_zero]
lemma card_Iio : (Iio f).card = ∏ i in f.support, (Iic (f i)).card - 1 :=
by rw [card_Iio_eq_card_Iic_sub_one, card_Iic]
end canonically_ordered
end dfinsupp
|
75f4116e4f19c04b3c0991a15466a3df2cf475fe | 274748215b6d042f0d9c9a505f9551fa8e0c5f38 | /src/for_mathlib/mv_polynomial.lean | 8c8905d9318cacbef58803802289dc407aeef296 | [
"Apache-2.0"
] | permissive | ImperialCollegeLondon/M4P33 | 878ecb515c77d20cc799ff1ebd78f1bf4fd65c12 | 1a179372db71ad6802d11eacbc1f02f327d55f8f | refs/heads/master | 1,607,519,867,193 | 1,583,344,297,000 | 1,583,344,297,000 | 233,316,107 | 59 | 4 | Apache-2.0 | 1,579,285,778,000 | 1,578,788,367,000 | Lean | UTF-8 | Lean | false | false | 15,646 | lean | import data.mv_polynomial
-- workaround for the "open_locale at top of file" issue in Lean 3
example : ℕ := 37
open_locale classical
lemma sum.rec_comp_left (X : Type*) (Y : Type*) (β : Type*) (γ : Type*)
(i : β → X) (j : γ → X) (f : X → Y) (x : β ⊕ γ) :
f (sum.rec i j x) = sum.rec (f ∘ i) (f ∘ j) x := by cases x; refl
namespace mv_polynomial
/-- Evaluating the constant polynomial 1 anywhere gives 1 -/
theorem eval_one {X : Type*} {R : Type*} [comm_semiring R]
(x : X → R) : eval x 1 = 1 := eval_C _
-- this must be done somewhere else because the analogue is
-- in the polynomial namespace
theorem eval_pow {X : Type*} {R : Type*} [comm_semiring R]
(f : mv_polynomial X R) (m : ℕ) (x : X → R) :
eval x (f ^ m) = (eval x f)^m :=
begin
induction m with d hd,
rw pow_zero,
rw pow_zero,
rw eval_one,
rw pow_succ,
rw pow_succ,
rw eval_mul,
rw hd,
end
end mv_polynomial
namespace polynomial
-- Thanks to Johan Commelin for doing a bunch of the eval stuff below.
/-- Over an infinite integral domain a polynomial f is zero if it
evaluates to zero everywhere -/
lemma eval_eq_zero
{k : Type*} [integral_domain k] [infinite k] {f : polynomial k}
(H : ∀ x, polynomial.eval x f = 0) : f = 0 :=
begin
rcases infinite.exists_not_mem_finset (roots f) with ⟨x, hx⟩,
contrapose! hx with hf,
rw mem_roots hf,
apply H,
end
/-- Over an infinite integral domain a polynomial f is zero iff it
evaluates to zero everywhere -/
lemma eval_eq_zero_iff
{k : Type*} [integral_domain k] [infinite k] {f : polynomial k} :
(∀ x, polynomial.eval x f = 0) ↔ f = 0 :=
⟨polynomial.eval_eq_zero, by { rintro rfl x, exact rfl }⟩
end polynomial
def fin.equiv_empty : fin 0 ≃ empty :=
{ to_fun := λ i, false.elim $ nat.not_lt_zero _ i.2,
inv_fun := empty.elim,
left_inv := λ i, false.elim $ nat.not_lt_zero _ i.2,
right_inv := λ x, x.elim }
def fin.equiv_pempty : fin 0 ≃ pempty :=
{ to_fun := λ i, false.elim $ nat.not_lt_zero _ i.2,
inv_fun := pempty.elim,
left_inv := λ i, false.elim $ nat.not_lt_zero _ i.2,
right_inv := λ x, x.elim }
namespace mv_polynomial
@[simp] lemma eval_rename
{k : Type*} [comm_semiring k]
{m : Type*} {n : Type*} (e : m → n) (f : mv_polynomial m k) (x) :
eval x (rename e f) = eval (x ∘ e) f :=
by apply f.induction_on; { intros, simp * }
lemma equiv_eval_eq_zero
{k : Type*} [comm_semiring k]
{m : Type*} {n : Type*} (e : m ≃ n)
(H : (∀ f : mv_polynomial m k, (∀ x, eval x f = 0) → f = 0))
(f : mv_polynomial n k) (hf : ∀ x, eval x f = 0) : f = 0 :=
begin
let φ := ring_equiv_of_equiv k e,
suffices h : φ.symm f = 0, { simpa using congr_arg φ h },
apply H,
intro x,
show eval x (rename e.symm f) = 0,
simp [hf],
end
end mv_polynomial
universe variables u v
def equiv.option {X : Type u} {Y : Type v} (e : X ≃ Y) : option X ≃ option Y :=
{ to_fun := option.map e,
inv_fun := option.map e.symm,
left_inv := λ x, by { cases x, refl, simp },
right_inv := λ x, by { cases x, refl, simp } }
/-- n ↦ none -/
def fin_succ_equiv_option' (n : ℕ) : fin (n+1) ≃ option (fin n) :=
{ to_fun := λ x, if h : x.1 < n then some ⟨_, h⟩ else none,
inv_fun := λ x, option.rec_on x ⟨n, nat.lt_succ_self _⟩ $
λ x, ⟨x.1, lt_trans x.2 $ nat.lt_succ_self _⟩,
left_inv := λ x,
begin
cases x with x hx,
rw [nat.lt_succ_iff, le_iff_lt_or_eq] at hx,
cases hx with hx hx,
{ dsimp, rw dif_pos hx},
{ dsimp, rw dif_neg _, cases hx, refl, apply not_lt_of_le, cases hx, refl}
end,
right_inv := begin
intro x,
cases x with x,
{ dsimp, rw dif_neg, apply lt_irrefl},
dsimp,
cases x with x hx,
rw dif_pos hx,
end }
/-- 0 ↦ none-/
def fin_succ_equiv_option (n : ℕ) : fin (n+1) ≃ option (fin n) :=
{ to_fun := λ x, if h : x.1 = 0 then none else some ⟨x.1 - 1, begin
rw nat.sub_lt_left_iff_lt_add,
convert x.2 using 1, apply add_comm,
exact nat.pos_of_ne_zero h,
end⟩,
inv_fun := λ x, option.rec ⟨0, nat.zero_lt_succ _⟩
(λ y, ⟨y.1 + 1, add_lt_add_right y.2 1⟩) x,
left_inv :=
begin
rintro ⟨⟨x⟩, hx⟩,
refl,
dsimp,
rw dif_neg,
simp,
apply nat.succ_ne_zero
end,
right_inv := begin
rintro (_ | ⟨x, h⟩),
refl,
dsimp,
rw dif_neg,
simp,
apply nat.succ_ne_zero
end }
lemma fintype.induction {P : Π (X : Type*) [fintype X], Prop}
(h0 : P pempty) (hs : ∀ (X : Type*) [fintype X], P X → P (option X))
(he : ∀ {X Y : Type*} [fintype X] [fintype Y] (e : X ≃ Y), P X → P Y)
(X : Type*) [fintype X] : P X :=
begin
rcases fintype.exists_equiv_fin X with ⟨n, ⟨e⟩⟩,
apply he (equiv.ulift.trans e.symm), clear e,
induction n with n ih,
{ exact he (equiv.ulift.trans fin.equiv_pempty).symm h0 },
{ specialize hs _ ih,
apply he _ hs,
refine (equiv.ulift.trans _).symm,
refine (fin_succ_equiv_option n).trans _,
refine equiv.ulift.option.symm }
end
/-
mv_polynomial.option_equiv_right :
-- mv_polynomial (option β) α ≃+* mv_polynomial β (polynomial α)
it's built from
. mv_polynomial.ring_equiv_of_equiv
. mv_polynomial.sum_ring_equiv
. mv_polynomial.ring_equiv_congr
glued together with
. ring_equiv.trans
-/
namespace mv_polynomial
attribute [simp] sum_to_iter_Xr sum_to_iter_Xl sum_to_iter_C
@[simp] theorem option_equiv_right_X_none {α β} [comm_semiring α] :
option_equiv_right α β (X none) = C polynomial.X :=
show map (eval₂ polynomial.C (λu:punit, polynomial.X))
(sum_to_iter α β unit
(rename (equiv.option_equiv_sum_punit._match_1 β)
(X none))) = C polynomial.X,
by simp
@[simp] theorem option_equiv_right_X_some {α β} [comm_semiring α] (b : β) :
option_equiv_right α β (X (some b)) = X b :=
show map (eval₂ polynomial.C (λu:punit, polynomial.X))
(sum_to_iter α β unit
(rename (equiv.option_equiv_sum_punit._match_1 β)
(X (some b)))) = X b,
by simp
@[simp] theorem option_equiv_right_C {α β} [comm_semiring α] (a : α) :
option_equiv_right α β (C a) = C (polynomial.C a) :=
show map (eval₂ polynomial.C (λu:punit, polynomial.X))
(sum_to_iter α β unit
(rename (equiv.option_equiv_sum_punit._match_1 β)
(C a))) = C (polynomial.C a),
by simp
/-
Mario Carneiro: I also brute forced my way through several other definitions
here, that should have definitional lemmas: ring_equiv_of_equiv,
option_equiv_sum_punit (the definition should not be simp), sum_comm (ditto),
sum_ring_equiv, punit_ring_equiv
Mario Carneiro: Ideally this proof should be dunfold option_equiv_right; simp
-/
theorem eval₂_eval₂ (R : Type*) [comm_semiring R] (β : Type*) (γ : Type*)
(S : Type*) [comm_semiring S] (f : R → S) [is_semiring_hom f]
(i : β → S) (j : γ → S) (p : mv_polynomial β (mv_polynomial γ R)) :
eval₂ (eval₂ f j) i p = eval i (map (eval₂ f j) p) :=
hom_eq_hom _ _ (by apply_instance) (by apply_instance)
(λ _, by rw [eval₂_C, map_C, eval_C]) (λ _, by rw [eval₂_X, map_X, eval_X]) p
set_option class.instance_max_depth 100
theorem map_eval₂' {R : Type*} [comm_semiring R] {β : Type*} {γ : Type*}
{S : Type*} [comm_semiring S] {f : R → S} [is_semiring_hom f]
{j : γ → S} {p : mv_polynomial β (mv_polynomial γ R)} :
map (eval₂ f j) p = eval₂ (C ∘ f) (λ n, sum.rec X (C ∘ j) n) (iter_to_sum _ _ _ p) :=
begin
rw iter_to_sum,
rw eval₂_eval₂,
rw ←eval₂_eq_eval_map,
apply hom_eq_hom, apply_instance, apply_instance,
{ intro b,
suffices : (C (eval₂ f j b) : mv_polynomial β S) =
eval₂ (C ∘ f) (λ n, sum.rec X (C ∘ j) n) (eval₂ C (X ∘ sum.inr) b),
simpa using this,
rw ←rename,
rw eval₂_rename,
rw [show ((λ (n : β ⊕ γ), sum.rec X (C ∘ j) n) ∘ sum.inr : γ → mv_polynomial β S) = C ∘ j,
by funext b; refl],
apply eval₂_comp_left},
{ intro b,
simp},
end
theorem eval₂_eval₂' (R : Type*) [comm_semiring R] (β : Type*) (γ : Type*)
(S : Type*) [comm_semiring S] (f : R → S) [is_semiring_hom f]
(i : β → S) (j : γ → S) (p : mv_polynomial β (mv_polynomial γ R)) :
eval₂ (eval₂ f j) i p = eval₂ f (λ n, sum.rec i j n) (iter_to_sum _ _ _ p) :=
begin
rw eval₂_eval₂,
rw map_eval₂',
generalize : iter_to_sum _ _ _ p = p',
apply hom_eq_hom _ _ _ _ _ _ p',
apply_instance, apply_instance, apply_instance,
{ intro r,
rw [eval₂_C, eval₂_C, eval_C]},
{ rintro (b | c),
{ simp},
{ simp},
}
end
/-- Over an infinite integral domain a polynomial f in finitely many
variables is zero if it evaluates to zero everywhere -/
lemma fin_eval_eq_zero
{k : Type*} [int : integral_domain k] [inf : infinite k]
{n : Type*} [fin : fintype n] :
∀ {f : mv_polynomial n k}, (∀ x, eval x f = 0) → f = 0 :=
begin
unfreezeI,
revert inf int k,
revert fin n,
refine fintype.induction _ _ _,
{ intros k int inf f H,
have h : (pempty_ring_equiv k) f = 0 := H _,
replace h := congr_arg (pempty_ring_equiv k).symm h,
rw [ring_equiv.symm_apply_apply] at h,
convert h, symmetry, exact ring_equiv.map_zero _ },
{ intros n _ ih k int inf f hf,
set φ := option_equiv_right k n with hφ,
suffices h : φ f = 0, { simpa using congr_arg φ.symm h },
apply ih,
{ intro x,
apply polynomial.eval_eq_zero,
intro xoo,
let xo : option n → k :=
λ j, option.rec xoo (λ i, polynomial.eval xoo (x i)) j,
convert hf xo,
rw hφ,
apply hom_eq_hom _ _ _ _ _ _ f,
apply_instance, apply_instance, apply_instance,
{ intro a,
rw eval_C,
simp},
{ intro xn,
cases xn with xn hxn,
{ simp },
{ simp },
}
},
{ resetI,
apply infinite.of_injective polynomial.C,
swap, assumption,
intros x y h, exact polynomial.C_inj.1 h,
} },
{ intros m n _ _ e H k int inf f,
apply mv_polynomial.equiv_eval_eq_zero e,
apply @H }
end
.
-- no longer sure if I even care about `vars`.
lemma mem_vars_iff_mem_degrees {R : Type*} [comm_semiring R] {σ : Type*}
{p : mv_polynomial σ R} {n : σ} : n ∈ vars p ↔ n ∈ degrees p :=
multiset.mem_to_finset
-- Chris Hughes' alternative definition of `mv_polynomial.vars` using `bind`.
-- I have no idea whether this should be noncomputable.
/-- `vars' p` is the set of variables appearing in the polynomial `p`.
It's probably the same as `vars p`. -/
noncomputable def vars' {R : Type*} {σ : Type*} [comm_semiring R]
(p : mv_polynomial σ R) :
finset σ :=
p.support.bind finsupp.support
-- things which might need proving?
-- I will need to learn the interface for finsupp to do this one
-- Remark: I think only need φ 0 = 0, not semiring hom, but coeff_map wanted it.
lemma vars_map_sub {R : Type*} [comm_semiring R] {S : Type*} [comm_semiring S]
{σ : Type*} {φ : R → S} [is_semiring_hom φ] {p : mv_polynomial σ R} :
vars' (map φ p) ⊆ vars' p :=
begin
intros i hi,
unfold vars' at hi ⊢,
rw finset.mem_bind at hi ⊢,
rcases hi with ⟨s, hs, his⟩,
use s,
existsi _, exact his, clear his i,
simp,
intro hps,
dunfold mv_polynomial at p,
have hps' : φ (p.to_fun s) = 0,
convert is_semiring_hom.map_zero _, assumption,
revert hs,
simp,
intro h1,
apply h1,
convert hps',
change mv_polynomial σ R at p,
change (map φ p).coeff s = φ (p.coeff s),
apply coeff_map,
end
-- Thanks to Chris for this one
lemma eval₂_eq_of_eq_on_vars {R : Type*} [comm_semiring R]
{S : Type*} [comm_semiring S] {σ : Type*}
(f g : σ → S) (φ : R → S) (p : mv_polynomial σ R)
[is_semiring_hom φ] -- do we need this??
(h : ∀ i ∈ vars' p, f i = g i) :
eval₂ φ f p = eval₂ φ g p :=
begin
unfold eval₂,
unfold finsupp.sum finsupp.prod,
refine finset.sum_congr rfl _,
intros x hx,
congr' 1,
refine finset.prod_congr rfl _,
intros i hi,
simp only [vars', finset.mem_bind, exists_imp_distrib] at h,
have := h i x hx hi,
rw this,
end
-- KB practicing.
example {R : Type*} [comm_semiring R]
{S : Type*} [comm_semiring S] {σ : Type*}
(f g : σ → S) (φ : R → S) (p : mv_polynomial σ R)
[is_semiring_hom φ] -- do we need this??
(h : ∀ i ∈ vars' p, f i = g i) :
eval₂ φ f p = eval₂ φ g p :=
begin
unfold eval₂,
unfold finsupp.prod finsupp.sum,
rw finset.sum_congr rfl,
intros x hx,
congr' 1,
rw finset.prod_congr rfl,
intros i hi,
rw h,
unfold vars',
rw finset.mem_bind,
use x,
use hx,
assumption,
end
def eq_sum_monomial_coeff {R : Type*} [comm_semiring R] {σ : Type*}
{p : mv_polynomial σ R} :
finset.sum p.support (λ s, monomial s (p.coeff s)) = p :=
begin
apply mv_polynomial.ext,
intro s,
rw coeff_sum,
simp only [coeff_monomial],
by_cases hs : s ∈ p.support,
{ rw ←finset.sum_subset (show {s} ⊆ p.support, begin
intros i hi,
convert hs,
cases hi, assumption, cases hi
end),
swap,
{ intros t ht hts,
rw if_neg,
intro hts2,
apply hts,
rw hts2,
apply set.mem_singleton,
},
convert finset.sum_singleton,
rw if_pos,
refl
},
{ rw ←finset.sum_subset (finset.empty_subset p.support),
swap,
{ intros t ht1 ht2,
rw if_neg,
intro hts,
apply hs,
rwa hts at ht1,
},
rw finset.sum_empty,
rw finsupp.not_mem_support_iff at hs,
exact hs.symm
}
end
/- Is this a sensible thing to prove?
lemma mem_rename_range {R : Type*} [comm_semiring R]
{σ τ : Type*} {g : σ → τ} (p : mv_polynomial τ R)
(h : (vars' p).to_set ⊆ set.range g) :
∃ q : mv_polynomial σ R, rename g q = p := sorry
-/
lemma preimage_subtype_range {R : Type*} [comm_semiring R]
{σ : Type*} (p : mv_polynomial σ R) :
∃ q : mv_polynomial {i : σ // i ∈ p.vars'} R, rename subtype.val q = p :=
begin
use finset.sum p.support
(λ s,
monomial (finsupp.comap_domain subtype.val s (λ _ _ _ _, subtype.eq))
(p.coeff s)),
apply mv_polynomial.ext,
intro s,
rw ←finset.sum_hom p.support (rename subtype.val),
all_goals {try {apply_instance}},
rw coeff_sum,
conv begin to_rhs,
rw ←@eq_sum_monomial_coeff _ _ _ p,
end,
rw coeff_sum,
apply finset.sum_congr rfl,
intros t ht,
rw coeff_monomial,
rw rename_monomial,
rw coeff_monomial,
congr',
rw finsupp.map_domain_comap_domain, intros i j, exact subtype.eq,
suffices : t.support ⊆ vars' p, by simpa,
unfold vars',
intros i hi,
rw finset.mem_bind,
use t,
use ht,
assumption,
end
-- We know `fin_eval_eq_zero` from above, which is the below
-- theorem in the special case where `n` is finite.
-- We now use it to prove the general case.
/-- Over an infinite integral domain a polynomial f is zero iff it
evaluates to zero everywhere -/
lemma eval_eq_zero {k : Type*} [integral_domain k] [infinite k]
{σ : Type*} {p : mv_polynomial σ k} :
(∀ x, eval x p = 0) ↔ p = 0 :=
begin
split, swap, intros hf x, rw [hf, eval_zero], -- easy direction
intro hev,
cases preimage_subtype_range p with q hq,
suffices : q = 0,
rw this at hq, rw ←hq, apply is_semiring_hom.map_zero,
apply fin_eval_eq_zero,
intro s₀,
set s : σ → k := λ i, if hi : i ∈ p.vars' then s₀ ⟨i, hi⟩ else 0 with hs,
have hs₀ : s₀ = s ∘ subtype.val,
ext i,
rw hs,
dsimp, split_ifs, simp, cases i, contradiction,
rw hs₀,
rw ←eval_rename,
rw hq,
apply hev,
end
-- finset.sum p.support (λ s, monomial s (p.coeff s)) = p :=
end mv_polynomial |
fd3daaa6c45986c6b2a3eeb8dcb4b69326f00415 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/monoidal/of_has_finite_products.lean | 593daf66b24e13fe99bc59061023bb44ecf9c3f5 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 6,383 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Simon Hudon
-/
import category_theory.monoidal.braided
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.terminal
/-!
# The natural monoidal structure on any category with finite (co)products.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A category with a monoidal structure provided in this way
is sometimes called a (co)cartesian category,
although this is also sometimes used to mean a finitely complete category.
(See <https://ncatlab.org/nlab/show/cartesian+category>.)
As this works with either products or coproducts,
and sometimes we want to think of a different monoidal structure entirely,
we don't set up either construct as an instance.
## Implementation
We had previously chosen to rely on `has_terminal` and `has_binary_products` instead of
`has_finite_products`, because we were later relying on the definitional form of the tensor product.
Now that `has_limit` has been refactored to be a `Prop`,
this issue is irrelevant and we could simplify the construction here.
See `category_theory.monoidal.of_chosen_finite_products` for a variant of this construction
which allows specifying a particular choice of terminal object and binary products.
-/
universes v u
noncomputable theory
namespace category_theory
variables (C : Type u) [category.{v} C] {X Y : C}
open category_theory.limits
section
local attribute [tidy] tactic.case_bash
/-- A category with a terminal object and binary products has a natural monoidal structure. -/
def monoidal_of_has_finite_products [has_terminal C] [has_binary_products C] :
monoidal_category C :=
{ tensor_unit := ⊤_ C,
tensor_obj := λ X Y, X ⨯ Y,
tensor_hom := λ _ _ _ _ f g, limits.prod.map f g,
associator := prod.associator,
left_unitor := λ P, prod.left_unitor P,
right_unitor := λ P, prod.right_unitor P,
pentagon' := prod.pentagon,
triangle' := prod.triangle,
associator_naturality' := @prod.associator_naturality _ _ _, }
end
section
local attribute [instance] monoidal_of_has_finite_products
open monoidal_category
/--
The monoidal structure coming from finite products is symmetric.
-/
@[simps]
def symmetric_of_has_finite_products [has_terminal C] [has_binary_products C] :
symmetric_category C :=
{ braiding := λ X Y, limits.prod.braiding X Y,
braiding_naturality' := λ X X' Y Y' f g,
by { dsimp [tensor_hom], simp, },
hexagon_forward' := λ X Y Z,
by { dsimp [monoidal_of_has_finite_products], simp },
hexagon_reverse' := λ X Y Z,
by { dsimp [monoidal_of_has_finite_products], simp },
symmetry' := λ X Y, by { dsimp, simp, refl, }, }
end
namespace monoidal_of_has_finite_products
variables [has_terminal C] [has_binary_products C]
local attribute [instance] monoidal_of_has_finite_products
@[simp]
lemma tensor_obj (X Y : C) : X ⊗ Y = (X ⨯ Y) := rfl
@[simp]
lemma tensor_hom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : f ⊗ g = limits.prod.map f g := rfl
@[simp]
lemma left_unitor_hom (X : C) : (λ_ X).hom = limits.prod.snd := rfl
@[simp]
lemma left_unitor_inv (X : C) : (λ_ X).inv = prod.lift (terminal.from X) (𝟙 _) := rfl
@[simp]
lemma right_unitor_hom (X : C) : (ρ_ X).hom = limits.prod.fst := rfl
@[simp]
lemma right_unitor_inv (X : C) : (ρ_ X).inv = prod.lift (𝟙 _) (terminal.from X) := rfl
-- We don't mark this as a simp lemma, even though in many particular
-- categories the right hand side will simplify significantly further.
-- For now, we'll plan to create specialised simp lemmas in each particular category.
lemma associator_hom (X Y Z : C) :
(α_ X Y Z).hom =
prod.lift
(limits.prod.fst ≫ limits.prod.fst)
(prod.lift (limits.prod.fst ≫ limits.prod.snd) limits.prod.snd) := rfl
end monoidal_of_has_finite_products
section
local attribute [tidy] tactic.case_bash
/-- A category with an initial object and binary coproducts has a natural monoidal structure. -/
def monoidal_of_has_finite_coproducts [has_initial C] [has_binary_coproducts C] :
monoidal_category C :=
{ tensor_unit := ⊥_ C,
tensor_obj := λ X Y, X ⨿ Y,
tensor_hom := λ _ _ _ _ f g, limits.coprod.map f g,
associator := coprod.associator,
left_unitor := coprod.left_unitor,
right_unitor := coprod.right_unitor,
pentagon' := coprod.pentagon,
triangle' := coprod.triangle,
associator_naturality' := @coprod.associator_naturality _ _ _, }
end
section
local attribute [instance] monoidal_of_has_finite_coproducts
open monoidal_category
/--
The monoidal structure coming from finite coproducts is symmetric.
-/
@[simps]
def symmetric_of_has_finite_coproducts [has_initial C] [has_binary_coproducts C] :
symmetric_category C :=
{ braiding := limits.coprod.braiding,
braiding_naturality' := λ X X' Y Y' f g,
by { dsimp [tensor_hom], simp, },
hexagon_forward' := λ X Y Z,
by { dsimp [monoidal_of_has_finite_coproducts], simp },
hexagon_reverse' := λ X Y Z,
by { dsimp [monoidal_of_has_finite_coproducts], simp },
symmetry' := λ X Y, by { dsimp, simp, refl, }, }
end
namespace monoidal_of_has_finite_coproducts
variables [has_initial C] [has_binary_coproducts C]
local attribute [instance] monoidal_of_has_finite_coproducts
@[simp]
lemma tensor_obj (X Y : C) : X ⊗ Y = (X ⨿ Y) := rfl
@[simp]
lemma tensor_hom {W X Y Z : C} (f : W ⟶ X) (g : Y ⟶ Z) : f ⊗ g = limits.coprod.map f g := rfl
@[simp]
lemma left_unitor_hom (X : C) : (λ_ X).hom = coprod.desc (initial.to X) (𝟙 _) := rfl
@[simp]
lemma right_unitor_hom (X : C) : (ρ_ X).hom = coprod.desc (𝟙 _) (initial.to X) := rfl
@[simp]
lemma left_unitor_inv (X : C) : (λ_ X).inv = limits.coprod.inr := rfl
@[simp]
lemma right_unitor_inv (X : C) : (ρ_ X).inv = limits.coprod.inl := rfl
-- We don't mark this as a simp lemma, even though in many particular
-- categories the right hand side will simplify significantly further.
-- For now, we'll plan to create specialised simp lemmas in each particular category.
lemma associator_hom (X Y Z : C) :
(α_ X Y Z).hom =
coprod.desc
(coprod.desc coprod.inl (coprod.inl ≫ coprod.inr))
(coprod.inr ≫ coprod.inr) := rfl
end monoidal_of_has_finite_coproducts
end category_theory
|
08bec1aa6eb83aca1a4fb562b5e8da50af181ca2 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/category/basic.lean | 64bbb6dcfc1145eb8b611f7828e73a57a602f709 | [
"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 | 6,996 | 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
Extends the theory on functors, applicatives and monads.
-/
universes u v w
variables {α β γ : Type u}
notation a ` $< `:1 f:1 := f a
section functor
variables {f : Type u → Type v} [functor f] [is_lawful_functor f]
run_cmd mk_simp_attr `functor_norm
@[functor_norm] protected theorem map_map (m : α → β) (g : β → γ) (x : f α) :
g <$> (m <$> x) = (g ∘ m) <$> x :=
(comp_map _ _ _).symm
@[simp] theorem id_map' (x : f α) : (λa, a) <$> x = x := id_map _
end functor
section applicative
variables {F : Type u → Type v} [applicative F]
def mzip_with
{α₁ α₂ φ : Type u}
(f : α₁ → α₂ → F φ) :
Π (ma₁ : list α₁) (ma₂: list α₂), F (list φ)
| (x :: xs) (y :: ys) := (::) <$> f x y <*> mzip_with xs ys
| _ _ := pure []
def mzip_with' (f : α → β → F γ) : list α → list β → F punit
| (x :: xs) (y :: ys) := f x y *> mzip_with' xs ys
| [] _ := pure punit.star
| _ [] := pure punit.star
protected def option.traverse {α β : Type*} (f : α → F β) : option α → F (option β)
| none := pure none
| (some x) := some <$> f x
protected def list.traverse {α β : Type*} (f : α → F β) : list α → F (list β)
| [] := pure []
| (x :: xs) := list.cons <$> f x <*> list.traverse xs
variables [is_lawful_applicative F]
attribute [functor_norm] seq_assoc pure_seq_eq_map
@[simp] theorem pure_id'_seq (x : F α) : pure (λx, x) <*> x = x :=
pure_id_seq x
variables [is_lawful_applicative F]
attribute [functor_norm] seq_assoc pure_seq_eq_map
@[functor_norm] theorem seq_map_assoc (x : F (α → β)) (f : γ → α) (y : F γ) :
(x <*> (f <$> y)) = (λ(m:α→β), m ∘ f) <$> x <*> y :=
begin
simp [(pure_seq_eq_map _ _).symm],
simp [seq_assoc, (comp_map _ _ _).symm, (∘)],
simp [pure_seq_eq_map]
end
@[functor_norm] theorem map_seq (f : β → γ) (x : F (α → β)) (y : F α) :
(f <$> (x <*> y)) = ((∘) f) <$> x <*> y :=
by simp [(pure_seq_eq_map _ _).symm]; simp [seq_assoc]
end applicative
-- TODO: setup `functor_norm` for `monad` laws
attribute [functor_norm] pure_bind bind_assoc bind_pure
section monad
variables {m : Type u → Type v} [monad m] [is_lawful_monad m]
open list
def list.mpartition {f : Type → Type} [monad f] {α : Type} (p : α → f bool) :
list α → f (list α × list α)
| [] := pure ([],[])
| (x :: xs) :=
mcond (p x) (prod.map (cons x) id <$> list.mpartition xs)
(prod.map id (cons x) <$> list.mpartition xs)
lemma map_bind (x : m α) {g : α → m β} {f : β → γ} : f <$> (x >>= g) = (x >>= λa, f <$> g a) :=
by rw [← bind_pure_comp_eq_map,bind_assoc]; simp [bind_pure_comp_eq_map]
lemma seq_bind_eq (x : m α) {g : β → m γ} {f : α → β} : (f <$> x) >>= g = (x >>= g ∘ f) :=
show bind (f <$> x) g = bind x (g ∘ f),
by rw [← bind_pure_comp_eq_map, bind_assoc]; simp [pure_bind]
lemma seq_eq_bind_map {x : m α} {f : m (α → β)} : f <*> x = (f >>= (<$> x)) :=
(bind_map_eq_seq m f x).symm
/-- This is the Kleisli composition -/
@[reducible] def fish {m} [monad m] {α β γ} (f : α → m β) (g : β → m γ) := λ x, f x >>= g
-- >=> is already defined in the core library but it is unusable
-- because of its precedence (it is defined with precedence 2) and
-- because it is defined as a lambda instead of having a named
-- function
infix ` >=> `:55 := fish
@[functor_norm]
lemma fish_pure {α β} (f : α → m β) : f >=> pure = f :=
by simp only [(>=>)] with functor_norm
@[functor_norm]
lemma fish_pipe {α β} (f : α → m β) : pure >=> f = f :=
by simp only [(>=>)] with functor_norm
@[functor_norm]
lemma fish_assoc {α β γ φ} (f : α → m β) (g : β → m γ) (h : γ → m φ) :
(f >=> g) >=> h = f >=> (g >=> h) :=
by simp only [(>=>)] with functor_norm
variables {β' γ' : Type v}
variables {m' : Type v → Type w} [monad m']
def list.mmap_accumr (f : α → β' → m' (β' × γ')) : β' → list α → m' (β' × list γ')
| a [] := pure (a,[])
| a (x :: xs) :=
do (a',ys) ← list.mmap_accumr a xs,
(a'',y) ← f x a',
pure (a'',y::ys)
def list.mmap_accuml (f : β' → α → m' (β' × γ')) : β' → list α → m' (β' × list γ')
| a [] := pure (a,[])
| a (x :: xs) :=
do (a',y) ← f a x,
(a'',ys) ← list.mmap_accuml a' xs,
pure (a'',y :: ys)
end monad
section
variables {m : Type u → Type u} [monad m] [is_lawful_monad m]
lemma mjoin_map_map {α β : Type u} (f : α → β) (a : m (m α)) :
mjoin (functor.map f <$> a) = f <$> (mjoin a) :=
by simp only [mjoin, (∘), id.def,
(bind_pure_comp_eq_map _ _ _).symm, bind_assoc, map_bind, pure_bind]
lemma mjoin_map_mjoin {α : Type u} (a : m (m (m α))) :
mjoin (mjoin <$> a) = mjoin (mjoin a) :=
by simp only [mjoin, (∘), id.def,
map_bind, (bind_pure_comp_eq_map _ _ _).symm, bind_assoc, pure_bind]
@[simp] lemma mjoin_map_pure {α : Type u} (a : m α) :
mjoin (pure <$> a) = a :=
by simp only [mjoin, (∘), id.def,
map_bind, (bind_pure_comp_eq_map _ _ _).symm, bind_assoc, pure_bind, bind_pure]
@[simp] lemma mjoin_pure {α : Type u} (a : m α) : mjoin (pure a) = a :=
is_lawful_monad.pure_bind a id
end
section alternative
variables {F : Type → Type v} [alternative F]
def succeeds {α} (x : F α) : F bool := (x $> tt) <|> pure ff
def mtry {α} (x : F α) : F unit := (x $> ()) <|> pure ()
@[simp] theorem guard_true {h : decidable true} :
@guard F _ true h = pure () := by simp [guard]
@[simp] theorem guard_false {h : decidable false} :
@guard F _ false h = failure := by simp [guard]
end alternative
namespace sum
variables {e : Type v}
protected def bind {α β} : e ⊕ α → (α → e ⊕ β) → e ⊕ β
| (inl x) _ := inl x
| (inr x) f := f x
instance : monad (sum.{v u} e) :=
{ pure := @sum.inr e,
bind := @sum.bind e }
instance : is_lawful_functor (sum.{v u} e) :=
by refine { .. }; intros; casesm _ ⊕ _; refl
instance : is_lawful_monad (sum.{v u} e) :=
{ bind_assoc := by { intros, casesm _ ⊕ _; refl },
pure_bind := by { intros, refl },
bind_pure_comp_eq_map := by { intros, casesm _ ⊕ _; refl },
bind_map_eq_seq := by { intros, cases f; refl } }
end sum
class is_comm_applicative (m : Type* → Type*) [applicative m] extends is_lawful_applicative m : Prop :=
(commutative_prod : ∀{α β} (a : m α) (b : m β), prod.mk <$> a <*> b = (λb a, (a, b)) <$> b <*> a)
lemma is_comm_applicative.commutative_map
{m : Type* → Type*} [applicative m] [is_comm_applicative m]
{α β γ} (a : m α) (b : m β) {f : α → β → γ} :
f <$> a <*> b = flip f <$> b <*> a :=
calc f <$> a <*> b = (λp:α×β, f p.1 p.2) <$> (prod.mk <$> a <*> b) :
by simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map]
... = (λb a, f a b) <$> b <*> a :
by rw [is_comm_applicative.commutative_prod];
simp [seq_map_assoc, map_seq, seq_assoc, seq_pure, map_map]
|
7a8d1f244c46d13170164e75772d534b820b29f7 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/data/mv_polynomial/rename.lean | 9ae3d932c369a9093ae324c50dac12259ba4f2ab | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 9,070 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro
-/
import data.mv_polynomial.basic
/-!
# Renaming variables of polynomials
This file establishes the `rename` operation on multivariate polynomials,
which modifies the set of variables.
## Main declarations
* `mv_polynomial.rename`
* `mv_polynomial.rename_equiv`
## Notation
As in other polynomial files, we typically use the notation:
+ `σ τ α : Type*` (indexing the variables)
+ `R S : Type*` `[comm_semiring R]` `[comm_semiring S]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `r : R` elements of the coefficient ring
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ α`
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
variables {σ τ α R S : Type*} [comm_semiring R] [comm_semiring S]
namespace mv_polynomial
section rename
/-- Rename all the variables in a multivariable polynomial. -/
def rename (f : σ → τ) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R :=
aeval (X ∘ f)
@[simp] lemma rename_C (f : σ → τ) (r : R) : rename f (C r) = C r :=
eval₂_C _ _ _
@[simp] lemma rename_X (f : σ → τ) (i : σ) : rename f (X i : mv_polynomial σ R) = X (f i) :=
eval₂_X _ _ _
lemma map_rename (f : R →+* S) (g : σ → τ) (p : mv_polynomial σ R) :
map f (rename g p) = rename g (map f p) :=
mv_polynomial.induction_on p
(λ a, by simp only [map_C, rename_C])
(λ p q hp hq, by simp only [hp, hq, alg_hom.map_add, ring_hom.map_add])
(λ p n hp, by simp only [hp, rename_X, map_X, ring_hom.map_mul, alg_hom.map_mul])
@[simp] lemma rename_rename (f : σ → τ) (g : τ → α) (p : mv_polynomial σ R) :
rename g (rename f p) = rename (g ∘ f) p :=
show rename g (eval₂ C (X ∘ f) p) = _,
begin
simp only [rename, aeval_eq_eval₂_hom],
simp [eval₂_comp_left _ C (X ∘ f) p, (∘), eval₂_C, eval_X],
apply eval₂_hom_congr _ rfl rfl,
ext1, simp only [comp_app, ring_hom.coe_comp, eval₂_hom_C],
end
@[simp] lemma rename_id (p : mv_polynomial σ R) : rename id p = p :=
eval₂_eta p
lemma rename_monomial (f : σ → τ) (d : σ →₀ ℕ) (r : R) :
rename f (monomial d r) = monomial (d.map_domain f) r :=
begin
rw [rename, aeval_monomial, monomial_eq, finsupp.prod_map_domain_index],
{ refl },
{ exact assume n, pow_zero _ },
{ exact assume n i₁ i₂, pow_add _ _ _ }
end
lemma rename_eq (f : σ → τ) (p : mv_polynomial σ R) :
rename f p = finsupp.map_domain (finsupp.map_domain f) p :=
begin
simp only [rename, aeval_def, eval₂, finsupp.map_domain],
congr' with s a : 2,
rw [← monomial, monomial_eq, finsupp.prod_sum_index],
congr' with n i : 2,
rw [finsupp.prod_single_index],
exact pow_zero _,
exact assume a, pow_zero _,
exact assume a b c, pow_add _ _ _
end
lemma rename_injective (f : σ → τ) (hf : function.injective f) :
function.injective (rename f : mv_polynomial σ R → mv_polynomial τ R) :=
have (rename f : mv_polynomial σ R → mv_polynomial τ R) =
finsupp.map_domain (finsupp.map_domain f) := funext (rename_eq f),
begin
rw this,
exact finsupp.map_domain_injective (finsupp.map_domain_injective hf)
end
section
variables (R)
/-- `mv_polynomial.rename e` is an equivalence when `e` is. -/
@[simps apply]
def rename_equiv (f : σ ≃ τ) : mv_polynomial σ R ≃ₐ[R] mv_polynomial τ R :=
{ to_fun := rename f,
inv_fun := rename f.symm,
left_inv := λ p, by rw [rename_rename, f.symm_comp_self, rename_id],
right_inv := λ p, by rw [rename_rename, f.self_comp_symm, rename_id],
..rename f}
@[simp] lemma rename_equiv_refl :
rename_equiv R (equiv.refl σ) = alg_equiv.refl :=
alg_equiv.ext rename_id
@[simp] lemma rename_equiv_symm (f : σ ≃ τ) :
(rename_equiv R f).symm = rename_equiv R f.symm := rfl
@[simp] lemma rename_equiv_trans (e : σ ≃ τ) (f : τ ≃ α):
(rename_equiv R e).trans (rename_equiv R f) = rename_equiv R (e.trans f) :=
alg_equiv.ext (rename_rename e f)
end
section
variables (f : R →+* S) (k : σ → τ) (g : τ → S) (p : mv_polynomial σ R)
lemma eval₂_rename : (rename k p).eval₂ f g = p.eval₂ f (g ∘ k) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval₂_hom_rename : eval₂_hom f g (rename k p) = eval₂_hom f (g ∘ k) p :=
eval₂_rename _ _ _ _
lemma aeval_rename [algebra R S] : aeval g (rename k p) = aeval (g ∘ k) p :=
eval₂_hom_rename _ _ _ _
lemma rename_eval₂ (g : τ → mv_polynomial σ R) :
rename k (p.eval₂ C (g ∘ k)) = (rename k p).eval₂ C (rename k ∘ g) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma rename_prodmk_eval₂ (j : τ) (g : σ → mv_polynomial σ R) :
rename (prod.mk j) (p.eval₂ C g) = p.eval₂ C (λ x, rename (prod.mk j) (g x)) :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval₂_rename_prodmk (g : σ × τ → S) (i : σ) (p : mv_polynomial τ R) :
(rename (prod.mk i) p).eval₂ f g = eval₂ f (λ j, g (i, j)) p :=
by apply mv_polynomial.induction_on p; { intros, simp [*] }
lemma eval_rename_prodmk (g : σ × τ → R) (i : σ) (p : mv_polynomial τ R) :
eval g (rename (prod.mk i) p) = eval (λ j, g (i, j)) p :=
eval₂_rename_prodmk (ring_hom.id _) _ _ _
end
/-- Every polynomial is a polynomial in finitely many variables. -/
theorem exists_finset_rename (p : mv_polynomial σ R) :
∃ (s : finset σ) (q : mv_polynomial {x // x ∈ s} R), p = rename coe q :=
begin
apply induction_on p,
{ intro r, exact ⟨∅, C r, by rw rename_C⟩ },
{ rintro p q ⟨s, p, rfl⟩ ⟨t, q, rfl⟩,
refine ⟨s ∪ t, ⟨_, _⟩⟩,
{ refine rename (subtype.map id _) p + rename (subtype.map id _) q;
simp only [id.def, true_or, or_true, finset.mem_union, forall_true_iff] {contextual := tt}, },
{ simp only [rename_rename, alg_hom.map_add], refl, }, },
{ rintro p n ⟨s, p, rfl⟩,
refine ⟨insert n s, ⟨_, _⟩⟩,
{ refine rename (subtype.map id _) p * X ⟨n, s.mem_insert_self n⟩,
simp only [id.def, or_true, finset.mem_insert, forall_true_iff] {contextual := tt}, },
{ simp only [rename_rename, rename_X, subtype.coe_mk, alg_hom.map_mul], refl, }, },
end
/-- Every polynomial is a polynomial in finitely many variables. -/
theorem exists_fin_rename (p : mv_polynomial σ R) :
∃ (n : ℕ) (f : fin n → σ) (hf : injective f) (q : mv_polynomial (fin n) R), p = rename f q :=
begin
obtain ⟨s, q, rfl⟩ := exists_finset_rename p,
let n := fintype.card {x // x ∈ s},
let e := fintype.equiv_fin {x // x ∈ s},
refine ⟨n, coe ∘ e.symm, subtype.val_injective.comp e.symm.injective, rename e q, _⟩,
rw [← rename_rename, rename_rename e],
simp only [function.comp, equiv.symm_apply_apply, rename_rename]
end
end rename
lemma eval₂_cast_comp (f : σ → τ) (c : ℤ →+* R) (g : τ → R) (p : mv_polynomial σ ℤ) :
eval₂ c (g ∘ f) p = eval₂ c g (rename f p) :=
mv_polynomial.induction_on p
(λ n, by simp only [eval₂_C, rename_C])
(λ p q hp hq, by simp only [hp, hq, rename, eval₂_add, alg_hom.map_add])
(λ p n hp, by simp only [hp, rename, aeval_def, eval₂_X, eval₂_mul])
section coeff
@[simp]
lemma coeff_rename_map_domain (f : σ → τ) (hf : injective f) (φ : mv_polynomial σ R) (d : σ →₀ ℕ) :
(rename f φ).coeff (d.map_domain f) = φ.coeff d :=
begin
apply induction_on' φ,
{ intros u r,
rw [rename_monomial, coeff_monomial, coeff_monomial],
simp only [(finsupp.map_domain_injective hf).eq_iff],
split_ifs; refl, },
{ intros, simp only [*, alg_hom.map_add, coeff_add], }
end
lemma coeff_rename_eq_zero (f : σ → τ) (φ : mv_polynomial σ R) (d : τ →₀ ℕ)
(h : ∀ u : σ →₀ ℕ, u.map_domain f = d → φ.coeff u = 0) :
(rename f φ).coeff d = 0 :=
begin
rw [rename_eq, ← not_mem_support_iff],
intro H,
replace H := map_domain_support H,
rw [finset.mem_image] at H,
obtain ⟨u, hu, rfl⟩ := H,
specialize h u rfl,
simp at h hu,
contradiction
end
lemma coeff_rename_ne_zero (f : σ → τ) (φ : mv_polynomial σ R) (d : τ →₀ ℕ)
(h : (rename f φ).coeff d ≠ 0) :
∃ u : σ →₀ ℕ, u.map_domain f = d ∧ φ.coeff u ≠ 0 :=
by { contrapose! h, apply coeff_rename_eq_zero _ _ _ h }
@[simp] lemma constant_coeff_rename {τ : Type*} (f : σ → τ) (φ : mv_polynomial σ R) :
constant_coeff (rename f φ) = constant_coeff φ :=
begin
apply φ.induction_on,
{ intro a, simp only [constant_coeff_C, rename_C]},
{ intros p q hp hq, simp only [hp, hq, ring_hom.map_add, alg_hom.map_add] },
{ intros p n hp, simp only [hp, rename_X, constant_coeff_X, ring_hom.map_mul, alg_hom.map_mul] }
end
end coeff
end mv_polynomial
|
18c91178efb8cde0381e6e3d3b01bc8e30f558b6 | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/data/polynomial/basic.lean | f498ee4c3ae0c76644c7db546a8f788b3e8d2be4 | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 5,317 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import tactic.ring_exp
import tactic.chain
import data.monoid_algebra
import data.finset.sort
/-!
# Theory of univariate polynomials
Polynomials are represented as `add_monoid_algebra R ℕ`, where `R` is a commutative semiring.
In this file, we define `polynomial`, provide basic instances, and prove an `ext` lemma.
-/
noncomputable theory
/-- `polynomial R` is the type of univariate polynomials over `R`.
Polynomials should be seen as (semi-)rings with the additional constructor `X`.
The embedding from `R` is called `C`. -/
def polynomial (R : Type*) [semiring R] := add_monoid_algebra R ℕ
open finsupp finset add_monoid_algebra
open_locale big_operators
namespace polynomial
universes u
variables {R : Type u} {a : R} {m n : ℕ}
section semiring
variables [semiring R] {p q : polynomial R}
instance : inhabited (polynomial R) := finsupp.inhabited
instance : semiring (polynomial R) := add_monoid_algebra.semiring
instance : has_scalar R (polynomial R) := add_monoid_algebra.has_scalar
instance : semimodule R (polynomial R) := add_monoid_algebra.semimodule
instance subsingleton [subsingleton R] : subsingleton (polynomial R) :=
⟨λ _ _, ext (λ _, subsingleton.elim _ _)⟩
@[simp] lemma support_zero : (0 : polynomial R).support = ∅ := rfl
/-- `monomial s a` is the monomial `a * X^s` -/
def monomial (n : ℕ) (a : R) : polynomial R := finsupp.single n a
@[simp] lemma monomial_zero_right (n : ℕ) :
monomial n (0 : R) = 0 :=
by simp [monomial]
lemma monomial_add (n : ℕ) (r s : R) :
monomial n (r + s) = monomial n r + monomial n s :=
by simp [monomial]
lemma monomial_mul_monomial (n m : ℕ) (r s : R) :
monomial n r * monomial m s = monomial (n + m) (r * s) :=
by simp only [monomial, single_mul_single]
/-- `X` is the polynomial variable (aka indeterminant). -/
def X : polynomial R := monomial 1 1
/-- `X` commutes with everything, even when the coefficients are noncommutative. -/
lemma X_mul : X * p = p * X :=
begin
ext,
simp [X, monomial, add_monoid_algebra.mul_apply, sum_single_index, add_comm],
end
lemma X_pow_mul {n : ℕ} : X^n * p = p * X^n :=
begin
induction n with n ih,
{ simp, },
{ conv_lhs { rw pow_succ', },
rw [mul_assoc, X_mul, ←mul_assoc, ih, mul_assoc, ←pow_succ'], }
end
lemma X_pow_mul_assoc {n : ℕ} : (p * X^n) * q = (p * q) * X^n :=
by rw [mul_assoc, X_pow_mul, ←mul_assoc]
/-- coeff p n is the coefficient of X^n in p -/
def coeff (p : polynomial R) := p.to_fun
@[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial R) = f := rfl
lemma coeff_monomial : coeff (monomial n a) m = if n = m then a else 0 :=
by { dsimp [monomial, single, finsupp.single], congr, }
/--
This lemma is needed for occasions when we break through the abstraction from
`polynomial` to `finsupp`; ideally it wouldn't be necessary at all.
-/
lemma coeff_single : coeff (single n a) m = if n = m then a else 0 :=
coeff_monomial
@[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial R) n = 0 := rfl
@[simp] lemma coeff_one_zero : coeff (1 : polynomial R) 0 = 1 := coeff_monomial
@[simp] lemma coeff_X_one : coeff (X : polynomial R) 1 = 1 := coeff_monomial
@[simp] lemma coeff_X_zero : coeff (X : polynomial R) 0 = 0 := coeff_monomial
lemma coeff_X : coeff (X : polynomial R) n = if 1 = n then 1 else 0 := coeff_monomial
theorem ext_iff {p q : polynomial R} : p = q ↔ ∀ n, coeff p n = coeff q n :=
⟨λ h n, h ▸ rfl, finsupp.ext⟩
@[ext] lemma ext {p q : polynomial R} : (∀ n, coeff p n = coeff q n) → p = q :=
(@ext_iff _ _ p q).2
-- this has the same content as the subsingleton
lemma eq_zero_of_eq_zero (h : (0 : R) = (1 : R)) (p : polynomial R) : p = 0 :=
by rw [←one_smul R p, ←h, zero_smul]
end semiring
section ring
variables [ring R]
instance : ring (polynomial R) := add_monoid_algebra.ring
@[simp] lemma coeff_neg (p : polynomial R) (n : ℕ) : coeff (-p) n = -coeff p n := rfl
@[simp]
lemma coeff_sub (p q : polynomial R) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl
end ring
instance [comm_semiring R] : comm_semiring (polynomial R) := add_monoid_algebra.comm_semiring
instance [comm_ring R] : comm_ring (polynomial R) := add_monoid_algebra.comm_ring
section nonzero_semiring
variables [semiring R] [nontrivial R]
instance : nontrivial (polynomial R) :=
begin
refine nontrivial_of_ne 0 1 _, intro h,
have := coeff_zero 0, revert this, rw h, simp,
end
lemma X_ne_zero : (X : polynomial R) ≠ 0 :=
mt (congr_arg (λ p, coeff p 1)) (by simp)
end nonzero_semiring
section repr
variables [semiring R]
local attribute [instance, priority 100] classical.prop_decidable
instance [has_repr R] : has_repr (polynomial R) :=
⟨λ p, if p = 0 then "0"
else (p.support.sort (≤)).foldr
(λ n a, a ++ (if a = "" then "" else " + ") ++
if n = 0
then "C (" ++ repr (coeff p n) ++ ")"
else if n = 1
then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X"
else if (coeff p n) = 1 then "X ^ " ++ repr n
else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩
end repr
end polynomial
|
62d2c9bbd525d07fb001276b2c9164d73abddd3b | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /tests/lean/unsolvedIndCases.lean | c0e55ce21e23da513c6044536a7cad0190b66249 | [
"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 | 860 | lean | theorem ex1 (x : Nat) : 0 + x = x := by
cases x with
| zero => skip -- Error: unsolved goals
| succ y => skip -- Error: unsolved goals
theorem ex2 (x : Nat) : 0 + x = x := by
induction x with
| zero => skip -- Error: unsolved goals
| succ y ih => skip -- Error: unsolved goals
theorem ex3 (x : Nat) : 0 + x = x := by
cases x with
| zero => rfl
| succ y => skip -- Error: unsolved goals
theorem ex4 (x : Nat) {y : Nat} (h : y > 0) : x % y < y := by
induction x, y using Nat.mod.inductionOn generalizing h with
| ind x y h₁ ih => skip -- Error: unsolved goals
| base x y h₁ => skip -- Error: unsolved goals
theorem ex5 (x : Nat) {y : Nat} (h : y > 0) : x % y < y := by
cases x, y using Nat.mod.inductionOn with
| ind x y h₁ ih => skip -- Error: unsolved goals
| base x y h₁ => skip -- Error: unsolved goals
|
48cc376b836945313167bc1a6ca3a8f4d71f2924 | 3f48345ac9bbaa421714efc9872a0409379bb4ae | /src/examples/terminal_automata.lean | dcb2f088ae4bd42345bc9fcf2719a3bd5977c90e | [] | no_license | QaisHamarneh/Coalgebra-in-Lean | b4318ee6d83780e5c734eb78fed98b1fe8016f7e | bd0452df98bc64b608e5dfd7babc42c301bb6a46 | refs/heads/master | 1,663,371,200,241 | 1,661,004,695,000 | 1,661,004,695,000 | 209,798,828 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,427 | lean | import examples.automata
namespace Automata
variables {Sigma : Type} -- The alphabet
{D : Type} -- Output
open word
structure Automaton :=
(State : Type) -- Set of States
(δ : State → Sigma → State) -- δ: S × Σ → S
(γ : State → D) -- Output of a state
/-
Given a morphism τ between two Automates A and B
determines if τ is a homomorphism
-/
def is_homomorphism_Automaton
{A B : @Automaton Sigma D} (τ : A.State → B.State) : Prop :=
∀ a : A.State , -- ∀ states (a) in A
A.γ a = B.γ (τ a) ∧ -- a ∈ T_A iff τ(a) ∈ T_B
∀ e : Sigma , -- and ∀ e ∈ Σ
τ (A.δ a e) = (B.δ (τ a) e) -- τ(δ_A(a , e)) = δ_B(τ(a) , e)
def deltaStar {A : @Automaton Sigma D} (s : A.State): word Sigma → A.State
| ε := s
| (e•v) := A.δ (deltaStar v) e
def state_output
{A : Automaton}
(s : A.State)
(w : @word Sigma) : D :=
A.γ (deltaStar s w)
inductive T_tree : Type
| node : D → (Sigma → T_tree) → T_tree
notation d ` - ` φ := T_tree.node d φ
def delta : @T_tree Sigma D → Sigma → @T_tree Sigma D
| (d - φ) e := φ e
def gamma : @T_tree Sigma D → D
| (d - φ) := d
def Tree_Automaton : Automaton :=
{
State := @T_tree Sigma D,
δ := delta ,
γ := gamma
}
def Terminal_Automaton : Automaton :=
{
State := word Sigma → D ,
δ := λ τ e , λ w , τ (e • w) ,
γ := λ τ , τ word.ε
}
def φ (A : @Automaton Sigma D) :
A.State → (@Terminal_Automaton Sigma D).State
| a word.ε := A.γ a
| a (e • w) := φ (A.δ a e) w
theorem Terminal_is_Automaton (A : @Automaton Sigma D) :
is_homomorphism_Automaton (φ A) :=
assume a : A.State ,
and.intro
begin
apply rfl,
end
begin
intro e,
apply rfl
end
end Automata
|
87ada2327d72d615484c5b2c09d58d3b1ca71f55 | a338c3e75cecad4fb8d091bfe505f7399febfd2b | /src/ring_theory/dedekind_domain.lean | 5079e8f45fe06bb7a5c046ab1104cea8d8c4552d | [
"Apache-2.0"
] | permissive | bacaimano/mathlib | 88eb7911a9054874fba2a2b74ccd0627c90188af | f2edc5a3529d95699b43514d6feb7eb11608723f | refs/heads/master | 1,686,410,075,833 | 1,625,497,070,000 | 1,625,497,070,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,082 | lean | /-
Copyright (c) 2020 Kenji Nakagawa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio
-/
import ring_theory.discrete_valuation_ring
import ring_theory.fractional_ideal
import ring_theory.ideal.over
/-!
# Dedekind domains
This file defines the notion of a Dedekind domain (or Dedekind ring),
giving three equivalent definitions (TODO: and shows that they are equivalent).
## Main definitions
- `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is not a field,
Noetherian, integrally closed in its field of fractions and has Krull dimension exactly one.
`is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions.
- `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that
is not a field, Noetherian, and the localization at every nonzero prime ideal is a DVR.
- `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain that
is not a field, and every nonzero fractional ideal is invertible.
- `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of
fractions.
## Implementation notes
The definitions that involve a field of fractions choose a canonical field of fractions,
but are independent of that choice. The `..._iff` lemmas express this independence.
## References
* [D. Marcus, *Number Fields*][marcus1977number]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
## Tags
dedekind domain, dedekind ring
-/
variables (R A K : Type*) [comm_ring R] [integral_domain A] [field K]
local notation R`⁰`:9000 := non_zero_divisors R
/-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/
def ring.dimension_le_one : Prop :=
∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal
open ideal ring
namespace ring
lemma dimension_le_one.principal_ideal_ring
[is_principal_ideal_ring A] : dimension_le_one A :=
λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero }
lemma dimension_le_one.integral_closure [nontrivial R] [algebra R A]
(h : dimension_le_one R) : dimension_le_one (integral_closure R A) :=
λ p ne_bot prime, by exactI
integral_closure.is_maximal_of_is_maximal_comap p
(h _ (integral_closure.comap_ne_bot ne_bot) infer_instance)
end ring
/--
A Dedekind domain is an integral domain that is Noetherian, integrally closed, and
has Krull dimension exactly one (`not_is_field` and `dimension_le_one`).
The integral closure condition is independent of the choice of field of fractions:
use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`.
This is the default implementation, but there are equivalent definitions,
`is_dedekind_domain_dvr` and `is_dedekind_domain_inv`.
TODO: Prove that these are actually equivalent definitions.
-/
class is_dedekind_domain : Prop :=
(not_is_field : ¬ is_field A)
(is_noetherian_ring : is_noetherian_ring A)
(dimension_le_one : dimension_le_one A)
(is_integrally_closed : integral_closure A (fraction_ring A) = ⊥)
/-- An integral domain is a Dedekind domain iff and only if it is not a field, is
Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field.
In particular, this definition does not depend on the choice of this fraction field. -/
lemma is_dedekind_domain_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] :
is_dedekind_domain A ↔
(¬ is_field A) ∧ is_noetherian_ring A ∧ dimension_le_one A ∧
integral_closure A K = ⊥ :=
⟨λ ⟨hf, hr, hd, hi⟩, ⟨hf, hr, hd,
by rw [←integral_closure_map_alg_equiv (fraction_ring.alg_equiv A K), hi, algebra.map_bot]⟩,
λ ⟨hf, hr, hd, hi⟩, ⟨hf, hr, hd,
by rw [←integral_closure_map_alg_equiv (fraction_ring.alg_equiv A K).symm, hi, algebra.map_bot]⟩⟩
/--
A Dedekind domain is an integral domain that is not a field, is Noetherian, and the
localization at every nonzero prime is a discrete valuation ring.
This is equivalent to `is_dedekind_domain`.
TODO: prove the equivalence.
-/
structure is_dedekind_domain_dvr : Prop :=
(not_is_field : ¬ is_field A)
(is_noetherian_ring : is_noetherian_ring A)
(is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime →
discrete_valuation_ring (localization.at_prime P))
section inverse
open_locale classical
variables {R₁ : Type*} [integral_domain R₁] [algebra R₁ K] [is_fraction_ring R₁ K]
variables {I J : fractional_ideal R₁⁰ K}
noncomputable instance : has_inv (fractional_ideal R₁⁰ K) := ⟨λ I, 1 / I⟩
lemma inv_eq : I⁻¹ = 1 / I := rfl
lemma inv_zero' : (0 : fractional_ideal R₁⁰ K)⁻¹ = 0 := fractional_ideal.div_zero
lemma inv_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) :
J⁻¹ = ⟨(1 : fractional_ideal R₁⁰ K) / J, fractional_ideal.fractional_div_of_nonzero h⟩ :=
fractional_ideal.div_nonzero _
lemma coe_inv_of_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) :
(↑J⁻¹ : submodule R₁ K) = is_localization.coe_submodule K 1 / J :=
by { rwa inv_nonzero _, refl, assumption}
/-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/
theorem right_inverse_eq (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) :
J = I⁻¹ :=
begin
have hI : I ≠ 0 := fractional_ideal.ne_zero_of_mul_eq_one I J h,
suffices h' : I * (1 / I) = 1,
{ exact (congr_arg units.inv $
@units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) },
apply le_antisymm,
{ apply fractional_ideal.mul_le.mpr _,
intros x hx y hy,
rw mul_comm,
exact (fractional_ideal.mem_div_iff_of_nonzero hI).mp hy x hx },
rw ← h,
apply fractional_ideal.mul_left_mono I,
apply (fractional_ideal.le_div_iff_of_nonzero hI).mpr _,
intros y hy x hx,
rw mul_comm,
exact fractional_ideal.mul_mem_mul hx hy
end
theorem mul_inv_cancel_iff {I : fractional_ideal R₁⁰ K} :
I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 :=
⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa ← right_inverse_eq K I J hJ⟩
variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K']
@[simp] lemma map_inv (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') :
(I⁻¹).map (h : K →ₐ[R₁] K') = (I.map h)⁻¹ :=
by rw [inv_eq, fractional_ideal.map_div, fractional_ideal.map_one, inv_eq]
open_locale classical
open submodule submodule.is_principal
@[simp] lemma span_singleton_inv (x : K) :
(fractional_ideal.span_singleton R₁⁰ x)⁻¹ = fractional_ideal.span_singleton _ (x⁻¹) :=
fractional_ideal.one_div_span_singleton x
lemma mul_generator_self_inv (I : fractional_ideal R₁⁰ K)
[submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) :
I * fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹ = 1 :=
begin
-- Rewrite only the `I` that appears alone.
conv_lhs { congr, rw fractional_ideal.eq_span_singleton_of_principal I },
rw [fractional_ideal.span_singleton_mul_span_singleton, mul_inv_cancel,
fractional_ideal.span_singleton_one],
intro generator_I_eq_zero,
apply h,
rw [fractional_ideal.eq_span_singleton_of_principal I, generator_I_eq_zero,
fractional_ideal.span_singleton_zero]
end
lemma invertible_of_principal (I : fractional_ideal R₁⁰ K)
[submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) :
I * I⁻¹ = 1 :=
(fractional_ideal.mul_div_self_cancel_iff).mpr
⟨fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹,
mul_generator_self_inv _ I h⟩
lemma invertible_iff_generator_nonzero (I : fractional_ideal R₁⁰ K)
[submodule.is_principal (I : submodule R₁ K)] :
I * I⁻¹ = 1 ↔ generator (I : submodule R₁ K) ≠ 0 :=
begin
split,
{ intros hI hg,
apply fractional_ideal.ne_zero_of_mul_eq_one _ _ hI,
rw [fractional_ideal.eq_span_singleton_of_principal I, hg,
fractional_ideal.span_singleton_zero] },
{ intro hg,
apply invertible_of_principal,
rw [fractional_ideal.eq_span_singleton_of_principal I],
intro hI,
have := fractional_ideal.mem_span_singleton_self _ (generator (I : submodule R₁ K)),
rw [hI, fractional_ideal.mem_zero_iff] at this,
contradiction }
end
lemma is_principal_inv (I : fractional_ideal R₁⁰ K)
[submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) :
submodule.is_principal (I⁻¹).1 :=
begin
rw [fractional_ideal.val_eq_coe, fractional_ideal.is_principal_iff],
use (generator (I : submodule R₁ K))⁻¹,
have hI : I * fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹) = 1,
apply mul_generator_self_inv _ I h,
exact (right_inverse_eq _ I (fractional_ideal.span_singleton _
((generator (I : submodule R₁ K))⁻¹)) hI).symm
end
/--
A Dedekind domain is an integral domain that is not a field such that every fractional ideal
has an inverse.
This is equivalent to `is_dedekind_domain`.
TODO: prove the equivalence.
-/
structure is_dedekind_domain_inv : Prop :=
(not_is_field : ¬ is_field A)
(mul_inv_cancel : ∀ I ≠ (⊥ : fractional_ideal A⁰ (fraction_ring A)), I * (1 / I) = 1)
open ring.fractional_ideal
lemma is_dedekind_domain_inv_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] :
is_dedekind_domain_inv A ↔
(¬ is_field A) ∧ (∀ I ≠ (⊥ : fractional_ideal A⁰ K), I * I⁻¹ = 1) :=
begin
set h : fraction_ring A ≃ₐ[A] K := fraction_ring.alg_equiv A K,
split; rintros ⟨hf, hi⟩; use hf; intros I hI,
{ have := hi (map ↑h.symm I) (map_ne_zero _ hI),
convert congr_arg (map (h : fraction_ring A →ₐ[A] K)) this;
simp only [map_symm_map, map_one, fractional_ideal.map_mul, fractional_ideal.map_div,
inv_eq] },
{ have := hi (map ↑h I) (map_ne_zero _ hI),
convert congr_arg (map (h.symm : K →ₐ[A] fraction_ring A)) this;
simp only [map_map_symm, map_one, fractional_ideal.map_mul, fractional_ideal.map_div,
inv_eq] },
end
end inverse
|
2d3ece686241745e6e7d9df8292f9c8cb29e41ed | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/algebra/big_operators/ring.lean | 93fa58912ba23c6c29696e4624a3057ee6faaba6 | [
"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 | 6,889 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.big_operators.basic
import data.finset.pi
import data.finset.powerset
/-!
# Results about big operators with values in a (semi)ring
We prove results about big operators that involve some interaction between
multiplicative and additive structures on the values being combined.
-/
universes u v w
open_locale big_operators
variables {α : Type u} {β : Type v} {γ : Type w}
namespace finset
variables {s s₁ s₂ : finset α} {a : α} {b : β} {f g : α → β}
section semiring
variables [semiring β]
lemma sum_mul : (∑ x in s, f x) * b = ∑ x in s, f x * b :=
(s.sum_hom (λ x, x * b)).symm
lemma mul_sum : b * (∑ x in s, f x) = ∑ x in s, b * f x :=
(s.sum_hom _).symm
lemma sum_mul_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (f x * ite (a = x) 1 0)) = ite (a ∈ s) (f a) 0 :=
by simp
lemma sum_boole_mul [decidable_eq α] (s : finset α) (f : α → β) (a : α) :
(∑ x in s, (ite (a = x) 1 0) * f x) = ite (a ∈ s) (f a) 0 :=
by simp
end semiring
lemma sum_div [division_ring β] {s : finset α} {f : α → β} {b : β} :
(∑ x in s, f x) / b = ∑ x in s, f x / b :=
by simp only [div_eq_mul_inv, sum_mul]
section comm_semiring
variables [comm_semiring β]
/-- The product over a sum can be written as a sum over the product of sets, `finset.pi`.
`finset.prod_univ_sum` is an alternative statement when the product is over `univ`. -/
lemma prod_sum {δ : α → Type*} [decidable_eq α] [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} :
(∏ a in s, ∑ b in (t a), f a b) =
∑ p in (s.pi t), ∏ x in s.attach, f x.1 (p x.1 x.2) :=
begin
induction s using finset.induction with a s ha ih,
{ rw [pi_empty, sum_singleton], refl },
{ have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y,
disjoint (image (pi.cons s a x) (pi s t)) (image (pi.cons s a y) (pi s t)),
{ assume x hx y hy h,
simp only [disjoint_iff_ne, mem_image],
rintros _ ⟨p₂, hp, eq₂⟩ _ ⟨p₃, hp₃, eq₃⟩ eq,
have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _),
{ rw [eq₂, eq₃, eq] },
rw [pi.cons_same, pi.cons_same] at this,
exact h this },
rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bUnion h₁],
refine sum_congr rfl (λ b _, _),
have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from
assume p₁ h₁ p₂ h₂ eq, pi_cons_injective ha eq,
rw [sum_image h₂, mul_sum],
refine sum_congr rfl (λ g _, _),
rw [attach_insert, prod_insert, prod_image],
{ simp only [pi.cons_same],
congr' with ⟨v, hv⟩, congr',
exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm },
{ exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj },
{ simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } }
end
lemma sum_mul_sum {ι₁ : Type*} {ι₂ : Type*} (s₁ : finset ι₁) (s₂ : finset ι₂)
(f₁ : ι₁ → β) (f₂ : ι₂ → β) :
(∑ x₁ in s₁, f₁ x₁) * (∑ x₂ in s₂, f₂ x₂) = ∑ p in s₁.product s₂, f₁ p.1 * f₂ p.2 :=
by { rw [sum_product, sum_mul, sum_congr rfl], intros, rw mul_sum }
open_locale classical
/-- The product of `f a + g a` over all of `s` is the sum
over the powerset of `s` of the product of `f` over a subset `t` times
the product of `g` over the complement of `t` -/
lemma prod_add (f g : α → β) (s : finset α) :
∏ a in s, (f a + g a) = ∑ t in s.powerset, ((∏ a in t, f a) * (∏ a in (s \ t), g a)) :=
calc ∏ a in s, (f a + g a)
= ∏ a in s, ∑ p in ({true, false} : finset Prop), if p then f a else g a : by simp
... = ∑ p in (s.pi (λ _, {true, false}) : finset (Π a ∈ s, Prop)),
∏ a in s.attach, if p a.1 a.2 then f a.1 else g a.1 : prod_sum
... = ∑ t in s.powerset, (∏ a in t, f a) * (∏ a in (s \ t), g a) : begin
refine eq.symm (sum_bij (λ t _ a _, a ∈ t) _ _ _ _),
{ simp [subset_iff]; tauto },
{ intros t ht,
erw [prod_ite (λ a : {a // a ∈ s}, f a.1) (λ a : {a // a ∈ s}, g a.1)],
refine congr_arg2 _
(prod_bij (λ (a : α) (ha : a ∈ t), ⟨a, mem_powerset.1 ht ha⟩)
_ _ _
(λ b hb, ⟨b, by cases b; finish⟩))
(prod_bij (λ (a : α) (ha : a ∈ s \ t), ⟨a, by simp * at *⟩)
_ _ _
(λ b hb, ⟨b, by cases b; finish⟩));
intros; simp * at *; simp * at * },
{ finish [function.funext_iff, finset.ext_iff, subset_iff] },
{ assume f hf,
exact ⟨s.filter (λ a : α, ∃ h : a ∈ s, f a h),
by simp, by funext; intros; simp *⟩ }
end
/-- Summing `a^s.card * b^(n-s.card)` over all finite subsets `s` of a `finset`
gives `(a + b)^s.card`.-/
lemma sum_pow_mul_eq_add_pow
{α R : Type*} [comm_semiring R] (a b : R) (s : finset α) :
(∑ t in s.powerset, a ^ t.card * b ^ (s.card - t.card)) = (a + b) ^ s.card :=
begin
rw [← prod_const, prod_add],
refine finset.sum_congr rfl (λ t ht, _),
rw [prod_const, prod_const, ← card_sdiff (mem_powerset.1 ht)]
end
lemma prod_pow_eq_pow_sum {x : β} {f : α → ℕ} :
∀ {s : finset α}, (∏ i in s, x ^ (f i)) = x ^ (∑ x in s, f x) :=
begin
apply finset.induction,
{ simp },
{ assume a s has H,
rw [finset.prod_insert has, finset.sum_insert has, pow_add, H] }
end
theorem dvd_sum {b : β} {s : finset α} {f : α → β}
(h : ∀ x ∈ s, b ∣ f x) : b ∣ ∑ x in s, f x :=
multiset.dvd_sum (λ y hy, by rcases multiset.mem_map.1 hy with ⟨x, hx, rfl⟩; exact h x hx)
@[norm_cast]
lemma prod_nat_cast (s : finset α) (f : α → ℕ) :
↑(∏ x in s, f x : ℕ) = (∏ x in s, (f x : β)) :=
(nat.cast_ring_hom β).map_prod f s
end comm_semiring
/-- A product over all subsets of `s ∪ {x}` is obtained by multiplying the product over all subsets
of `s`, and over all subsets of `s` to which one adds `x`. -/
@[to_additive]
lemma prod_powerset_insert [decidable_eq α] [comm_monoid β] {s : finset α} {x : α} (h : x ∉ s)
(f : finset α → β) :
(∏ a in (insert x s).powerset, f a) =
(∏ a in s.powerset, f a) * (∏ t in s.powerset, f (insert x t)) :=
begin
rw [powerset_insert, finset.prod_union, finset.prod_image],
{ assume t₁ h₁ t₂ h₂ heq,
rw [← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₁ h),
← finset.erase_insert (not_mem_of_mem_powerset_of_not_mem h₂ h), heq] },
{ rw finset.disjoint_iff_ne,
assume t₁ h₁ t₂ h₂,
rcases finset.mem_image.1 h₂ with ⟨t₃, h₃, H₃₂⟩,
rw ← H₃₂,
exact ne_insert_of_not_mem _ _ (not_mem_of_mem_powerset_of_not_mem h₁ h) }
end
end finset
|
7b8d9c112be1f064d0028998e8566c8eea64b712 | a46d86797f98e604c71128429409acba8288c1f8 | /algebra/lattice/complete_lattice/powerset.lean | dee72d258e29b1ea6d77b681b1027c120b4ab1cb | [] | no_license | tizmd/lean-abstract-interpretation | 655213d76e84e093910bb6378796cdb4e1ae3565 | ad69622adc082e7009f12b17568662a599779260 | refs/heads/master | 1,610,518,429,734 | 1,498,128,216,000 | 1,498,128,216,000 | 94,891,623 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,794 | lean | import algebra.lattice.complete_lattice
import data.set
universe u
open lattice
variables {α : Type u}
def set.as_type (s : set α) := {a // s a}
instance powerset_complete_lattice (s : set α) : complete_lattice (𝒫 s).as_type
:=
{
le := λ a b, a.1 ⊆ b.1,
le_refl := λ a, set.subset.refl a.1,
le_trans := λ a b c, assume hab hbc, set.subset.trans hab hbc,
le_antisymm := λ a b, assume hab hba, subtype.eq (set.subset.antisymm hab hba),
bot := ⟨∅, take x, false.elim⟩,
bot_le := λ a, take x, false.elim,
top := ⟨s, take x, id⟩,
le_top := λ a, take x, assume h, a.property h,
sup := λ a b, ⟨a.1 ∪ b.1, take x, assume h, or.elim h (assume h, a.property h) (assume h, b.property h)⟩,
le_sup_left := λ a b, take x, or.inl,
le_sup_right := λ a b, take x, or.inr,
sup_le := λ a b c, assume hac hbc, take x, assume h, or.elim h (assume h, hac h) (assume h, hbc h),
inf := λ a b, ⟨a.1 ∩ b.1, take x, assume h, a.property h.left⟩,
inf_le_left := λ a b, take x, and.left,
inf_le_right := λ a b, take x, and.right,
le_inf := λ a b c, assume hab hac, take x, assume xa, ⟨hab xa, hac xa⟩,
Sup := λ p, ⟨λ x, ∃t : (𝒫 s).as_type, t ∈ p ∧ x ∈ t.val, take x, assume ⟨t, ht⟩ , t.property ht.right⟩,
le_Sup := take p t, assume ht, take x, assume xt, ⟨t, ht, xt⟩,
Sup_le := take p t, assume h, take x, assume ⟨st, hstp, xst⟩ , h _ hstp xst,
Inf := λ p, ⟨λ x, x ∈ s ∧ (∀t : (𝒫 s).as_type, t ∈ p → x ∈ t.val), take x, assume h, h.left⟩,
Inf_le := take p t, assume ht, take x, assume ⟨xs, hx⟩, hx _ ht,
le_Inf := take p t, assume h, take x, assume xt, ⟨t.property xt, take b, assume hb, h _ hb xt⟩
}
|
fdd52502391d130cafff76c0a6b3499ca3cb0f24 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/doLetElse.lean | 24435474c14ea8dadcf4fb234752976aaa7fb68d | [
"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 | 274 | lean | def foo (x? : Option Nat) : IO Nat := do
let some x := x? | return 0
IO.println s!"x: {x}"
return x
def test (input : Option Nat) (expected : Nat) : IO Unit := do
assert! (← foo input) == expected
#eval test (some 10) 10
#eval test none 0
#eval test (some 1) 1
|
649631d0b4db8648ff96be39385fa2980a4da231 | 5412d79aa1dc0b521605c38bef9f0d4557b5a29d | /src/Lean/Environment.lean | 1130d3a6d8b367b01c2b21cd0b48e776d3f209fa | [
"Apache-2.0"
] | permissive | smunix/lean4 | a450ec0927dc1c74816a1bf2818bf8600c9fc9bf | 3407202436c141e3243eafbecb4b8720599b970a | refs/heads/master | 1,676,334,875,188 | 1,610,128,510,000 | 1,610,128,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 28,657 | 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 Std.Data.HashMap
import Lean.Data.SMap
import Lean.Declaration
import Lean.LocalContext
import Lean.Util.Path
import Lean.Util.FindExpr
import Lean.Util.Profile
namespace Lean
/- Opaque environment extension state. -/
constant EnvExtensionStateSpec : PointedType.{0}
def EnvExtensionState : Type := EnvExtensionStateSpec.type
instance : Inhabited EnvExtensionState where
default := EnvExtensionStateSpec.val
def ModuleIdx := Nat
instance : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat)
abbrev ConstMap := SMap Name ConstantInfo
structure Import where
module : Name
runtimeOnly : Bool := false
instance : ToString Import := ⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩
/--
A compacted region holds multiple Lean objects in a contiguous memory region, which can be read/written to/from disk.
Objects inside the region do not have reference counters and cannot be freed individually. The contents of .olean
files are compacted regions. -/
def CompactedRegion := USize
/-- Free a compacted region and its contents. No live references to the contents may exist at the time of invocation. -/
@[extern 2 "lean_compacted_region_free"]
unsafe constant CompactedRegion.free : CompactedRegion → IO Unit
/- Environment fields that are not used often. -/
structure EnvironmentHeader where
trustLevel : UInt32 := 0
quotInit : Bool := false
mainModule : Name := arbitrary
imports : Array Import := #[] -- direct imports
regions : Array CompactedRegion := #[] -- compacted regions of all imported modules
moduleNames : Array Name := #[] -- names of all imported modules
deriving Inhabited
open Std (HashMap)
structure Environment where
const2ModIdx : HashMap Name ModuleIdx
constants : ConstMap
extensions : Array EnvExtensionState
header : EnvironmentHeader := {}
deriving Inhabited
namespace Environment
def addAux (env : Environment) (cinfo : ConstantInfo) : Environment :=
{ env with constants := env.constants.insert cinfo.name cinfo }
@[export lean_environment_find]
def find? (env : Environment) (n : Name) : Option ConstantInfo :=
/- It is safe to use `find'` because we never overwrite imported declarations. -/
env.constants.find?' n
def contains (env : Environment) (n : Name) : Bool :=
env.constants.contains n
def imports (env : Environment) : Array Import :=
env.header.imports
def allImportedModuleNames (env : Environment) : Array Name :=
env.header.moduleNames
@[export lean_environment_set_main_module]
def setMainModule (env : Environment) (m : Name) : Environment :=
{ env with header := { env.header with mainModule := m } }
@[export lean_environment_main_module]
def mainModule (env : Environment) : Name :=
env.header.mainModule
@[export lean_environment_mark_quot_init]
private def markQuotInit (env : Environment) : Environment :=
{ env with header := { env.header with quotInit := true } }
@[export lean_environment_quot_init]
private def isQuotInit (env : Environment) : Bool :=
env.header.quotInit
@[export lean_environment_trust_level]
private def getTrustLevel (env : Environment) : UInt32 :=
env.header.trustLevel
def getModuleIdxFor? (env : Environment) (c : Name) : Option ModuleIdx :=
env.const2ModIdx.find? c
def isConstructor (env : Environment) (c : Name) : Bool :=
match env.find? c with
| ConstantInfo.ctorInfo _ => true
| _ => false
end Environment
inductive KernelException where
| unknownConstant (env : Environment) (name : Name)
| alreadyDeclared (env : Environment) (name : Name)
| declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr)
| declHasMVars (env : Environment) (name : Name) (expr : Expr)
| declHasFVars (env : Environment) (name : Name) (expr : Expr)
| funExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr)
| exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr)
| appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr)
| invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr)
| other (msg : String)
namespace Environment
/- Type check given declaration and add it to the environment -/
@[extern "lean_add_decl"]
constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment
/- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/
@[extern "lean_compile_decl"]
constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment
def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do
let env ← addDecl env decl
compileDecl env opt decl
end Environment
/- Interface for managing environment extensions. -/
structure EnvExtensionInterface where
ext : Type → Type
inhabitedExt {σ} : Inhabited σ → Inhabited (ext σ)
registerExt {σ} (mkInitial : IO σ) : IO (ext σ)
setState {σ} (e : ext σ) (env : Environment) : σ → Environment
modifyState {σ} (e : ext σ) (env : Environment) : (σ → σ) → Environment
getState {σ} (e : ext σ) (env : Environment) : σ
mkInitialExtStates : IO (Array EnvExtensionState)
instance : Inhabited EnvExtensionInterface where
default := {
ext := id,
inhabitedExt := id,
registerExt := fun mk => mk,
setState := fun _ env _ => env,
modifyState := fun _ env _ => env,
getState := fun ext _ => ext,
mkInitialExtStates := pure #[]
}
/- Unsafe implementation of `EnvExtensionInterface` -/
namespace EnvExtensionInterfaceUnsafe
structure Ext (σ : Type) where
idx : Nat
mkInitial : IO σ
deriving Inhabited
private def mkEnvExtensionsRef : IO (IO.Ref (Array (Ext EnvExtensionState))) := IO.mkRef #[]
@[builtinInit mkEnvExtensionsRef] private constant envExtensionsRef : IO.Ref (Array (Ext EnvExtensionState))
unsafe def setState {σ} (ext : Ext σ) (env : Environment) (s : σ) : Environment :=
{ env with extensions := env.extensions.set! ext.idx (unsafeCast s) }
@[inline] unsafe def modifyState {σ : Type} (ext : Ext σ) (env : Environment) (f : σ → σ) : Environment :=
{ env with
extensions := env.extensions.modify ext.idx fun s =>
let s : σ := unsafeCast s;
let s : σ := f s;
unsafeCast s }
unsafe def getState {σ} (ext : Ext σ) (env : Environment) : σ :=
let s : EnvExtensionState := env.extensions.get! ext.idx
unsafeCast s
unsafe def registerExt {σ} (mkInitial : IO σ) : IO (Ext σ) := do
let initializing ← IO.initializing
unless initializing do throw (IO.userError "failed to register environment, extensions can only be registered during initialization")
let exts ← envExtensionsRef.get
let idx := exts.size
let ext : Ext σ := {
idx := idx,
mkInitial := mkInitial,
}
envExtensionsRef.modify fun exts => exts.push (unsafeCast ext)
pure ext
def mkInitialExtStates : IO (Array EnvExtensionState) := do
let exts ← envExtensionsRef.get
exts.mapM fun ext => ext.mkInitial
unsafe def imp : EnvExtensionInterface := {
ext := Ext,
inhabitedExt := fun _ => ⟨arbitrary⟩,
registerExt := registerExt,
setState := setState,
modifyState := modifyState,
getState := getState,
mkInitialExtStates := mkInitialExtStates
}
end EnvExtensionInterfaceUnsafe
@[implementedBy EnvExtensionInterfaceUnsafe.imp]
constant EnvExtensionInterfaceImp : EnvExtensionInterface
def EnvExtension (σ : Type) : Type := EnvExtensionInterfaceImp.ext σ
namespace EnvExtension
instance {σ} [s : Inhabited σ] : Inhabited (EnvExtension σ) := EnvExtensionInterfaceImp.inhabitedExt s
def setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := EnvExtensionInterfaceImp.setState ext env s
def modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := EnvExtensionInterfaceImp.modifyState ext env f
def getState {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := EnvExtensionInterfaceImp.getState ext env
end EnvExtension
/- Environment extensions can only be registered during initialization.
Reasons:
1- Our implementation assumes the number of extensions does not change after an environment object is created.
2- We do not use any synchronization primitive to access `envExtensionsRef`. -/
def registerEnvExtension {σ : Type} (mkInitial : IO σ) : IO (EnvExtension σ) := EnvExtensionInterfaceImp.registerExt mkInitial
private def mkInitialExtensionStates : IO (Array EnvExtensionState) := EnvExtensionInterfaceImp.mkInitialExtStates
@[export lean_mk_empty_environment]
def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do
let initializing ← IO.initializing
if initializing then throw (IO.userError "environment objects cannot be created during initialization")
let exts ← mkInitialExtensionStates
pure {
const2ModIdx := {},
constants := {},
header := { trustLevel := trustLevel },
extensions := exts
}
structure PersistentEnvExtensionState (α : Type) (σ : Type) where
importedEntries : Array (Array α) -- entries per imported module
state : σ
structure ImportM.Context where
env : Environment
opts : Options
abbrev ImportM := ReaderT Lean.ImportM.Context IO
/- An environment extension with support for storing/retrieving entries from a .olean file.
- α is the type of the entries that are stored in .olean files.
- β is the type of values used to update the state.
- σ is the actual state.
Remark: for most extensions α and β coincide.
Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as
```
def addAlias (env : Environment) (a : Name) (e : Name) : Environment :=
aliasExtension.addEntry env (a, e)
```
without using `IO`. We have many functions like `addAlias`.
`α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example,
closures which we currently cannot store in files. -/
structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) where
toEnvExtension : EnvExtension (PersistentEnvExtensionState α σ)
name : Name
addImportedFn : Array (Array α) → ImportM σ
addEntryFn : σ → β → σ
exportEntriesFn : σ → Array α
statsFn : σ → Format
/- Opaque persistent environment extension entry. -/
constant EnvExtensionEntrySpec : PointedType.{0}
def EnvExtensionEntry : Type := EnvExtensionEntrySpec.type
instance : Inhabited EnvExtensionEntry := ⟨EnvExtensionEntrySpec.val⟩
instance {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) :=
⟨{importedEntries := #[], state := arbitrary }⟩
instance {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) where
default := {
toEnvExtension := arbitrary,
name := arbitrary,
addImportedFn := fun _ => arbitrary,
addEntryFn := fun s _ => s,
exportEntriesFn := fun _ => #[],
statsFn := fun _ => Format.nil
}
namespace PersistentEnvExtension
def getModuleEntries {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α :=
(ext.toEnvExtension.getState env).importedEntries.get! m
def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment :=
ext.toEnvExtension.modifyState env fun s =>
let state := ext.addEntryFn s.state b;
{ s with state := state }
def getState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) : σ :=
(ext.toEnvExtension.getState env).state
def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment :=
ext.toEnvExtension.modifyState env $ fun ps => { ps with state := s }
def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment :=
ext.toEnvExtension.modifyState env $ fun ps => { ps with state := f (ps.state) }
end PersistentEnvExtension
builtin_initialize persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[]
structure PersistentEnvExtensionDescr (α β σ : Type) where
name : Name
mkInitial : IO σ
addImportedFn : Array (Array α) → ImportM σ
addEntryFn : σ → β → σ
exportEntriesFn : σ → Array α
statsFn : σ → Format := fun _ => Format.nil
unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do
let pExts ← persistentEnvExtensionsRef.get
if pExts.any (fun ext => ext.name == descr.name) then throw (IO.userError s!"invalid environment extension, '{descr.name}' has already been used")
let ext ← registerEnvExtension do
let initial ← descr.mkInitial
let s : PersistentEnvExtensionState α σ := {
importedEntries := #[],
state := initial
}
pure s
let pExt : PersistentEnvExtension α β σ := {
toEnvExtension := ext,
name := descr.name,
addImportedFn := descr.addImportedFn,
addEntryFn := descr.addEntryFn,
exportEntriesFn := descr.exportEntriesFn,
statsFn := descr.statsFn
}
persistentEnvExtensionsRef.modify fun pExts => pExts.push (unsafeCast pExt)
return pExt
@[implementedBy registerPersistentEnvExtensionUnsafe]
constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ)
/- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/
def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ)
@[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ :=
as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState
structure SimplePersistentEnvExtensionDescr (α σ : Type) where
name : Name
addEntryFn : σ → α → σ
addImportedFn : Array (Array α) → σ
toArrayFn : List α → Array α := fun es => es.toArray
def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) :=
registerPersistentEnvExtension {
name := descr.name,
mkInitial := pure ([], descr.addImportedFn #[]),
addImportedFn := fun as => pure ([], descr.addImportedFn as),
addEntryFn := fun s e => match s with
| (entries, s) => (e::entries, descr.addEntryFn s e),
exportEntriesFn := fun s => descr.toArrayFn s.1.reverse,
statsFn := fun s => format "number of local entries: " ++ format s.1.length
}
namespace SimplePersistentEnvExtension
instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) :=
inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ)))
def getEntries {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α :=
(PersistentEnvExtension.getState ext env).1
def getState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ :=
(PersistentEnvExtension.getState ext env).2
def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s))
def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s))
end SimplePersistentEnvExtension
/-- Environment extension for tagging declarations.
Declarations must only be tagged in the module where they were declared. -/
def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet
def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension :=
registerSimplePersistentEnvExtension {
name := name,
addImportedFn := fun as => {},
addEntryFn := fun s n => s.insert n,
toArrayFn := fun es => es.toArray.qsort Name.quickLt
}
namespace TagDeclarationExtension
instance : Inhabited TagDeclarationExtension :=
inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet))
def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment :=
ext.addEntry env n
def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool :=
match env.getModuleIdxFor? n with
| some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt
| none => (ext.getState env).contains n
end TagDeclarationExtension
/- Content of a .olean file.
We use `compact.cpp` to generate the image of this object in disk. -/
structure ModuleData where
imports : Array Import
constants : Array ConstantInfo
entries : Array (Name × Array EnvExtensionEntry)
instance : Inhabited ModuleData :=
⟨{imports := arbitrary, constants := arbitrary, entries := arbitrary }⟩
@[extern 3 "lean_save_module_data"]
constant saveModuleData (fname : @& String) (m : ModuleData) : IO Unit
@[extern 2 "lean_read_module_data"]
constant readModuleData (fname : @& String) : IO (ModuleData × CompactedRegion)
/--
Free compacted regions of imports. No live references to imported objects may exist at the time of invocation; in
particular, `env` should be the last reference to any `Environment` derived from these imports. -/
@[noinline, export lean_environment_free_regions]
unsafe def Environment.freeRegions (env : Environment) : IO Unit :=
/-
NOTE: This assumes `env` is not inferred as a borrowed parameter, and is freed after extracting the `header` field.
Otherwise, we would encounter undefined behavior when the constant map in `env`, which may reference objects in
compacted regions, is freed after the regions.
In the currently produced IR, we indeed see:
```
def Lean.Environment.freeRegions (x_1 : obj) (x_2 : obj) : obj :=
let x_3 : obj := proj[3] x_1;
inc x_3;
dec x_1;
...
```
TODO: statically check for this. -/
env.header.regions.forM CompactedRegion.free
def mkModuleData (env : Environment) : IO ModuleData := do
let pExts ← persistentEnvExtensionsRef.get
let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold
(fun i result =>
let state := (pExts.get! i).getState env
let exportEntriesFn := (pExts.get! i).exportEntriesFn
let extName := (pExts.get! i).name
result.push (extName, exportEntriesFn state))
#[]
pure {
imports := env.header.imports,
constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[],
entries := entries
}
@[export lean_write_module]
def writeModule (env : Environment) (fname : String) : IO Unit := do
let modData ← mkModuleData env; saveModuleData fname modData
private partial def getEntriesFor (mod : ModuleData) (extId : Name) (i : Nat) : Array EnvExtensionEntry :=
if i < mod.entries.size then
let curr := mod.entries.get! i;
if curr.1 == extId then curr.2 else getEntriesFor mod extId (i+1)
else
#[]
private def setImportedEntries (env : Environment) (mods : Array ModuleData) : IO Environment := do
let mut env := env
let pExtDescrs ← persistentEnvExtensionsRef.get
for mod in mods do
for extDescr in pExtDescrs do
let entries := getEntriesFor mod extDescr.name 0
env ← extDescr.toEnvExtension.modifyState env fun s => { s with importedEntries := s.importedEntries.push entries }
return env
private def finalizePersistentExtensions (env : Environment) (opts : Options) : IO Environment := do
let mut env := env
let pExtDescrs ← persistentEnvExtensionsRef.get
for extDescr in pExtDescrs do
let s := extDescr.toEnvExtension.getState env
let newState ← extDescr.addImportedFn s.importedEntries { env := env, opts := opts }
env ← extDescr.toEnvExtension.setState env { s with state := newState }
return env
structure ImportState where
moduleNameSet : NameSet := {}
moduleNames : Array Name := #[]
moduleData : Array ModuleData := #[]
regions : Array CompactedRegion := #[]
@[export lean_import_modules]
partial def importModules (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) : IO Environment := profileitIO "import" ⟨0, 0⟩ do
let (_, s) ← importMods imports |>.run {}
-- (moduleNames, mods, regions)
let mut modIdx : Nat := 0
let mut const2ModIdx : HashMap Name ModuleIdx := {}
let mut constants : ConstMap := SMap.empty
for mod in s.moduleData do
for cinfo in mod.constants do
const2ModIdx := const2ModIdx.insert cinfo.name modIdx
if constants.contains cinfo.name then throw (IO.userError s!"import failed, environment already contains '{cinfo.name}'")
constants := constants.insert cinfo.name cinfo
modIdx := modIdx + 1
constants := constants.switch
let exts ← mkInitialExtensionStates
let env : Environment := {
const2ModIdx := const2ModIdx,
constants := constants,
extensions := exts,
header := {
quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module
trustLevel := trustLevel,
imports := imports.toArray,
regions := s.regions,
moduleNames := s.moduleNames
}
}
let env ← setImportedEntries env s.moduleData
let env ← finalizePersistentExtensions env opts
pure env
where
importMods : List Import → StateRefT ImportState IO Unit
| [] => pure ()
| i::is => do
if i.runtimeOnly || (← get).moduleNameSet.contains i.module then
importMods is
else do
modify fun s => { s with moduleNameSet := s.moduleNameSet.insert i.module }
let mFile ← findOLean i.module
unless (← IO.fileExists mFile) do
throw $ IO.userError s!"object file '{mFile}' of module {i.module} does not exist"
let (mod, region) ← readModuleData mFile
importMods mod.imports.toList
modify fun s => { s with
moduleData := s.moduleData.push mod
regions := s.regions.push region
moduleNames := s.moduleNames.push i.module
}
importMods is
/--
Create environment object from imports and free compacted regions after calling `act`. No live references to the
environment object or imported objects may exist after `act` finishes. -/
unsafe def withImportModules {α : Type} (imports : List Import) (opts : Options) (trustLevel : UInt32 := 0) (x : Environment → IO α) : IO α := do
let env ← importModules imports opts trustLevel
try x env finally env.freeRegions
builtin_initialize namespacesExt : SimplePersistentEnvExtension Name NameSet ←
registerSimplePersistentEnvExtension {
name := `namespaces,
addImportedFn := fun as => mkStateFromImportedEntries NameSet.insert {} as,
addEntryFn := fun s n => s.insert n
}
namespace Environment
def registerNamespace (env : Environment) (n : Name) : Environment :=
if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n
def isNamespace (env : Environment) (n : Name) : Bool :=
(namespacesExt.getState env).contains n
def getNamespaceSet (env : Environment) : NameSet :=
namespacesExt.getState env
private def isNamespaceName : Name → Bool
| Name.str Name.anonymous _ _ => true
| Name.str p _ _ => isNamespaceName p
| _ => false
private def registerNamePrefixes : Environment → Name → Environment
| env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env
| env, _ => env
@[export lean_environment_add]
def add (env : Environment) (cinfo : ConstantInfo) : Environment :=
let env := registerNamePrefixes env cinfo.name
env.addAux cinfo
@[export lean_display_stats]
def displayStats (env : Environment) : IO Unit := do
let pExtDescrs ← persistentEnvExtensionsRef.get
let numModules := ((pExtDescrs.get! 0).toEnvExtension.getState env).importedEntries.size;
IO.println ("direct imports: " ++ toString env.header.imports);
IO.println ("number of imported modules: " ++ toString numModules);
IO.println ("number of consts: " ++ toString env.constants.size);
IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1);
IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2);
IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets);
IO.println ("trust level: " ++ toString env.header.trustLevel);
IO.println ("number of extensions: " ++ toString env.extensions.size);
pExtDescrs.forM $ fun extDescr => do
IO.println ("extension '" ++ toString extDescr.name ++ "'")
let s := extDescr.toEnvExtension.getState env
let fmt := extDescr.statsFn s.state
unless fmt.isNil do IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state)))
IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0))
@[extern "lean_eval_const"]
unsafe constant evalConst (α) (env : @& Environment) (opts : @& Options) (constName : @& Name) : Except String α
private def throwUnexpectedType {α} (typeName : Name) (constName : Name) : ExceptT String Id α :=
throw ("unexpected type at '" ++ toString constName ++ "', `" ++ toString typeName ++ "` expected")
/-- Like `evalConst`, but first check that `constName` indeed is a declaration of type `typeName`.
This function is still unsafe because it cannot guarantee that `typeName` is in fact the name of the type `α`. -/
unsafe def evalConstCheck (α) (env : Environment) (opts : Options) (typeName : Name) (constName : Name) : ExceptT String Id α :=
match env.find? constName with
| none => throw ("unknow constant '" ++ toString constName ++ "'")
| some info =>
match info.type with
| Expr.const c _ _ =>
if c != typeName then throwUnexpectedType typeName constName
else env.evalConst α opts constName
| _ => throwUnexpectedType typeName constName
def hasUnsafe (env : Environment) (e : Expr) : Bool :=
let c? := e.find? $ fun e => match e with
| Expr.const c _ _ =>
match env.find? c with
| some cinfo => cinfo.isUnsafe
| none => false
| _ => false;
c?.isSome
end Environment
namespace Kernel
/- Kernel API -/
/--
Kernel isDefEq predicate. We use it mainly for debugging purposes.
Recall that the Kernel type checker does not support metavariables.
When implementing automation, consider using the `MetaM` methods. -/
@[extern "lean_kernel_is_def_eq"]
constant isDefEq (env : Environment) (lctx : LocalContext) (a b : Expr) : Bool
/--
Kernel WHNF function. We use it mainly for debugging purposes.
Recall that the Kernel type checker does not support metavariables.
When implementing automation, consider using the `MetaM` methods. -/
@[extern "lean_kernel_whnf"]
constant whnf (env : Environment) (lctx : LocalContext) (a : Expr) : Expr
end Kernel
class MonadEnv (m : Type → Type) where
getEnv : m Environment
modifyEnv : (Environment → Environment) → m Unit
export MonadEnv (getEnv modifyEnv)
instance (m n) [MonadEnv m] [MonadLift m n] : MonadEnv n := {
getEnv := liftM (getEnv : m Environment),
modifyEnv := fun f => liftM (modifyEnv f : m Unit)
}
end Lean
|
110007c6e3c679dd15865ccbc3a42ccc3f45fc1a | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/LetRec.lean | 73e49fe7df8dd37277d8b99d02f3d9573cfb46af | [
"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 | 5,137 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Attributes
import Lean.Elab.Binders
import Lean.Elab.DeclModifiers
import Lean.Elab.SyntheticMVars
import Lean.Elab.DeclarationRange
namespace Lean.Elab.Term
open Meta
structure LetRecDeclView where
ref : Syntax
attrs : Array Attribute
shortDeclName : Name
declName : Name
binderIds : Array Syntax
type : Expr
mvar : Expr -- auxiliary metavariable used to lift the 'let rec'
valStx : Syntax
structure LetRecView where
decls : Array LetRecDeclView
body : Syntax
/- group ("let " >> nonReservedSymbol "rec ") >> sepBy1 (group (optional «attributes» >> letDecl)) ", " >> "; " >> termParser -/
private def mkLetRecDeclView (letRec : Syntax) : TermElabM LetRecView := do
let decls ← letRec[1][0].getSepArgs.mapM fun (attrDeclStx : Syntax) => do
let docStr? ← expandOptDocComment? attrDeclStx[0]
let attrOptStx := attrDeclStx[1]
let attrs ← if attrOptStx.isNone then pure #[] else elabDeclAttrs attrOptStx[0]
let decl := attrDeclStx[2][0]
if decl.isOfKind `Lean.Parser.Term.letPatDecl then
throwErrorAt decl "patterns are not allowed in 'let rec' expressions"
else if decl.isOfKind `Lean.Parser.Term.letIdDecl || decl.isOfKind `Lean.Parser.Term.letEqnsDecl then
let declId := decl[0]
unless declId.isIdent do
throwErrorAt declId "'let rec' expressions must be named"
let shortDeclName := declId.getId
let currDeclName? ← getDeclName?
let declName := currDeclName?.getD Name.anonymous ++ shortDeclName
checkNotAlreadyDeclared declName
applyAttributesAt declName attrs AttributeApplicationTime.beforeElaboration
addDocString' declName docStr?
addAuxDeclarationRanges declName decl declId
let binders := decl[1].getArgs
let typeStx := expandOptType declId decl[2]
let (type, binderIds) ← elabBindersEx binders fun xs => do
let type ← elabType typeStx
registerCustomErrorIfMVar type typeStx "failed to infer 'let rec' declaration type"
let (binderIds, xs) := xs.unzip
let type ← mkForallFVars xs type
pure (type, binderIds)
let mvar ← mkFreshExprMVar type MetavarKind.syntheticOpaque
let valStx ← if decl.isOfKind `Lean.Parser.Term.letIdDecl then
pure decl[4]
else
liftMacroM <| expandMatchAltsIntoMatch decl decl[3]
pure { ref := declId, attrs, shortDeclName, declName, binderIds, type, mvar, valStx : LetRecDeclView }
else
throwUnsupportedSyntax
return { decls, body := letRec[3] }
private partial def withAuxLocalDecls {α} (views : Array LetRecDeclView) (k : Array Expr → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α :=
if h : i < views.size then
let view := views.get ⟨i, h⟩
withAuxDecl view.shortDeclName view.type view.declName fun fvar => loop (i+1) (fvars.push fvar)
else
k fvars
loop 0 #[]
private def elabLetRecDeclValues (view : LetRecView) : TermElabM (Array Expr) :=
view.decls.mapM fun view => do
forallBoundedTelescope view.type view.binderIds.size fun xs type => do
-- Add new info nodes for new fvars. The server will detect all fvars of a binder by the binder's source location.
for i in [0:view.binderIds.size] do
addLocalVarInfo view.binderIds[i]! xs[i]!
withDeclName view.declName do
let value ← elabTermEnsuringType view.valStx type
mkLambdaFVars xs value
private def registerLetRecsToLift (views : Array LetRecDeclView) (fvars : Array Expr) (values : Array Expr) : TermElabM Unit := do
let letRecsToLiftCurr := (← get).letRecsToLift
for view in views do
if letRecsToLiftCurr.any fun toLift => toLift.declName == view.declName then
withRef view.ref do
throwError "'{view.declName}' has already been declared"
let lctx ← getLCtx
let localInstances ← getLocalInstances
let toLift := views.mapIdx fun i view => {
ref := view.ref
fvarId := fvars[i]!.fvarId!
attrs := view.attrs
shortDeclName := view.shortDeclName
declName := view.declName
lctx
localInstances
type := view.type
val := values[i]!
mvarId := view.mvar.mvarId!
: LetRecToLift }
modify fun s => { s with letRecsToLift := toLift.toList ++ s.letRecsToLift }
@[builtin_term_elab «letrec»] def elabLetRec : TermElab := fun stx expectedType? => do
let view ← mkLetRecDeclView stx
withAuxLocalDecls view.decls fun fvars => do
for decl in view.decls, fvar in fvars do
addLocalVarInfo decl.ref fvar
let values ← elabLetRecDeclValues view
let body ← elabTermEnsuringType view.body expectedType?
registerLetRecsToLift view.decls fvars values
let mvars := view.decls.map (·.mvar)
return mkAppN (← mkLambdaFVars fvars body) mvars
end Lean.Elab.Term
|
131bdc90c3682b4ea2251beac31ab32e79483364 | 618003631150032a5676f229d13a079ac875ff77 | /src/control/bitraversable/lemmas.lean | d33c4dae02094af8c084d00d3407e08742579907 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 3,325 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Simon Hudon
-/
import control.bitraversable.basic
/-!
# Bitraversable Lemmas
## Main definitions
* tfst - traverse on first functor argument
* tsnd - traverse on second functor argument
## Lemmas
Combination of
* bitraverse
* tfst
* tsnd
with the applicatives `id` and `comp`
## References
* Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html>
## Tags
traversable bitraversable functor bifunctor applicative
-/
universes u
variables {t : Type u → Type u → Type u} [bitraversable t]
variables {β : Type u}
namespace bitraversable
open functor is_lawful_applicative
variables {F G : Type u → Type u}
[applicative F] [applicative G]
/-- traverse on the first functor argument -/
@[reducible] def tfst {α α'} (f : α → F α') : t α β → F (t α' β) :=
bitraverse f pure
/-- traverse on the second functor argument -/
@[reducible] def tsnd {α α'} (f : α → F α') : t β α → F (t β α') :=
bitraverse pure f
variables [is_lawful_bitraversable t]
[is_lawful_applicative F]
[is_lawful_applicative G]
@[higher_order tfst_id]
lemma id_tfst : Π {α β} (x : t α β), tfst id.mk x = id.mk x :=
@id_bitraverse _ _ _
@[higher_order tsnd_id]
lemma id_tsnd : Π {α β} (x : t α β), tsnd id.mk x = id.mk x :=
@id_bitraverse _ _ _
@[higher_order tfst_comp_tfst]
lemma comp_tfst {α₀ α₁ α₂ β}
(f : α₀ → F α₁) (f' : α₁ → G α₂) (x : t α₀ β) :
comp.mk (tfst f' <$> tfst f x) = tfst (comp.mk ∘ map f' ∘ f) x :=
by rw ← comp_bitraverse; simp [tfst,map_comp_pure,has_pure.pure]
@[higher_order tfst_comp_tsnd]
lemma tfst_tsnd {α₀ α₁ β₀ β₁}
(f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) :
comp.mk (tfst f <$> tsnd f' x) =
bitraverse (comp.mk ∘ pure ∘ f) (comp.mk ∘ map pure ∘ f') x :=
by rw ← comp_bitraverse; simp [tfst,tsnd]
@[higher_order tsnd_comp_tfst]
lemma tsnd_tfst {α₀ α₁ β₀ β₁}
(f : α₀ → F α₁) (f' : β₀ → G β₁) (x : t α₀ β₀) :
comp.mk (tsnd f' <$> tfst f x) =
bitraverse (comp.mk ∘ map pure ∘ f) (comp.mk ∘ pure ∘ f') x :=
by rw ← comp_bitraverse; simp [tfst,tsnd]
@[higher_order tsnd_comp_tsnd]
lemma comp_tsnd {α β₀ β₁ β₂}
(g : β₀ → F β₁) (g' : β₁ → G β₂) (x : t α β₀) :
comp.mk (tsnd g' <$> tsnd g x) = tsnd (comp.mk ∘ map g' ∘ g) x :=
by rw ← comp_bitraverse; simp [tsnd]; refl
open bifunctor
private lemma pure_eq_id_mk_comp_id {α} :
pure = id.mk ∘ @id α := rfl
open function
@[higher_order]
lemma tfst_eq_fst_id {α α' β} (f : α → α') (x : t α β) :
tfst (id.mk ∘ f) x = id.mk (fst f x) :=
by simp [tfst,fst,pure_eq_id_mk_comp_id,-comp.right_id,bitraverse_eq_bimap_id]
@[higher_order]
lemma tsnd_eq_snd_id {α β β'} (f : β → β') (x : t α β) :
tsnd (id.mk ∘ f) x = id.mk (snd f x) :=
by simp [tsnd,snd,pure_eq_id_mk_comp_id,-comp.right_id,bitraverse_eq_bimap_id]
attribute [functor_norm] comp_bitraverse comp_tsnd comp_tfst
tsnd_comp_tsnd tsnd_comp_tfst tfst_comp_tsnd tfst_comp_tfst
bitraverse_comp bitraverse_id_id tfst_id tsnd_id
end bitraversable
|
4ccb6bd2a22cf8da564a5807e8751c4325eeb45f | 592ee40978ac7604005a4e0d35bbc4b467389241 | /Library/generated/mathscheme-lean/Quandle.lean | a8383acd7d165005a7b09332d100e700310dd0d8 | [] | no_license | ysharoda/Deriving-Definitions | 3e149e6641fae440badd35ac110a0bd705a49ad2 | dfecb27572022de3d4aa702cae8db19957523a59 | refs/heads/master | 1,679,127,857,700 | 1,615,939,007,000 | 1,615,939,007,000 | 229,785,731 | 4 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,124 | lean | import init.data.nat.basic
import init.data.fin.basic
import data.vector
import .Prelude
open Staged
open nat
open fin
open vector
section Quandle
structure Quandle (A : Type) : Type :=
(linv : (A → (A → A)))
(rinv : (A → (A → A)))
(leftDistributive : (∀ {x y z : A} , (linv x (linv y z)) = (linv (linv x y) (linv x z))))
(rightDistributive : (∀ {x y z : A} , (rinv (rinv y z) x) = (rinv (rinv y x) (rinv z x))))
(leftInverse : (∀ {x y : A} , (rinv (linv x y) x) = y))
(rightInverse : (∀ {x y : A} , (linv x (rinv y x)) = y))
(idempotent_linv : (∀ {x : A} , (linv x x) = x))
(idempotent_rinv : (∀ {x : A} , (rinv x x) = x))
open Quandle
structure Sig (AS : Type) : Type :=
(linvS : (AS → (AS → AS)))
(rinvS : (AS → (AS → AS)))
structure Product (A : Type) : Type :=
(linvP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(rinvP : ((Prod A A) → ((Prod A A) → (Prod A A))))
(leftDistributiveP : (∀ {xP yP zP : (Prod A A)} , (linvP xP (linvP yP zP)) = (linvP (linvP xP yP) (linvP xP zP))))
(rightDistributiveP : (∀ {xP yP zP : (Prod A A)} , (rinvP (rinvP yP zP) xP) = (rinvP (rinvP yP xP) (rinvP zP xP))))
(leftInverseP : (∀ {xP yP : (Prod A A)} , (rinvP (linvP xP yP) xP) = yP))
(rightInverseP : (∀ {xP yP : (Prod A A)} , (linvP xP (rinvP yP xP)) = yP))
(idempotent_linvP : (∀ {xP : (Prod A A)} , (linvP xP xP) = xP))
(idempotent_rinvP : (∀ {xP : (Prod A A)} , (rinvP xP xP) = xP))
structure Hom {A1 : Type} {A2 : Type} (Qu1 : (Quandle A1)) (Qu2 : (Quandle A2)) : Type :=
(hom : (A1 → A2))
(pres_linv : (∀ {x1 x2 : A1} , (hom ((linv Qu1) x1 x2)) = ((linv Qu2) (hom x1) (hom x2))))
(pres_rinv : (∀ {x1 x2 : A1} , (hom ((rinv Qu1) x1 x2)) = ((rinv Qu2) (hom x1) (hom x2))))
structure RelInterp {A1 : Type} {A2 : Type} (Qu1 : (Quandle A1)) (Qu2 : (Quandle A2)) : Type 1 :=
(interp : (A1 → (A2 → Type)))
(interp_linv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((linv Qu1) x1 x2) ((linv Qu2) y1 y2))))))
(interp_rinv : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((rinv Qu1) x1 x2) ((rinv Qu2) y1 y2))))))
inductive QuandleTerm : Type
| linvL : (QuandleTerm → (QuandleTerm → QuandleTerm))
| rinvL : (QuandleTerm → (QuandleTerm → QuandleTerm))
open QuandleTerm
inductive ClQuandleTerm (A : Type) : Type
| sing : (A → ClQuandleTerm)
| linvCl : (ClQuandleTerm → (ClQuandleTerm → ClQuandleTerm))
| rinvCl : (ClQuandleTerm → (ClQuandleTerm → ClQuandleTerm))
open ClQuandleTerm
inductive OpQuandleTerm (n : ℕ) : Type
| v : ((fin n) → OpQuandleTerm)
| linvOL : (OpQuandleTerm → (OpQuandleTerm → OpQuandleTerm))
| rinvOL : (OpQuandleTerm → (OpQuandleTerm → OpQuandleTerm))
open OpQuandleTerm
inductive OpQuandleTerm2 (n : ℕ) (A : Type) : Type
| v2 : ((fin n) → OpQuandleTerm2)
| sing2 : (A → OpQuandleTerm2)
| linvOL2 : (OpQuandleTerm2 → (OpQuandleTerm2 → OpQuandleTerm2))
| rinvOL2 : (OpQuandleTerm2 → (OpQuandleTerm2 → OpQuandleTerm2))
open OpQuandleTerm2
def simplifyCl {A : Type} : ((ClQuandleTerm A) → (ClQuandleTerm A))
| (linvCl x1 x2) := (linvCl (simplifyCl x1) (simplifyCl x2))
| (rinvCl x1 x2) := (rinvCl (simplifyCl x1) (simplifyCl x2))
| (sing x1) := (sing x1)
def simplifyOpB {n : ℕ} : ((OpQuandleTerm n) → (OpQuandleTerm n))
| (linvOL x1 x2) := (linvOL (simplifyOpB x1) (simplifyOpB x2))
| (rinvOL x1 x2) := (rinvOL (simplifyOpB x1) (simplifyOpB x2))
| (v x1) := (v x1)
def simplifyOp {n : ℕ} {A : Type} : ((OpQuandleTerm2 n A) → (OpQuandleTerm2 n A))
| (linvOL2 x1 x2) := (linvOL2 (simplifyOp x1) (simplifyOp x2))
| (rinvOL2 x1 x2) := (rinvOL2 (simplifyOp x1) (simplifyOp x2))
| (v2 x1) := (v2 x1)
| (sing2 x1) := (sing2 x1)
def evalB {A : Type} : ((Quandle A) → (QuandleTerm → A))
| Qu (linvL x1 x2) := ((linv Qu) (evalB Qu x1) (evalB Qu x2))
| Qu (rinvL x1 x2) := ((rinv Qu) (evalB Qu x1) (evalB Qu x2))
def evalCl {A : Type} : ((Quandle A) → ((ClQuandleTerm A) → A))
| Qu (sing x1) := x1
| Qu (linvCl x1 x2) := ((linv Qu) (evalCl Qu x1) (evalCl Qu x2))
| Qu (rinvCl x1 x2) := ((rinv Qu) (evalCl Qu x1) (evalCl Qu x2))
def evalOpB {A : Type} {n : ℕ} : ((Quandle A) → ((vector A n) → ((OpQuandleTerm n) → A)))
| Qu vars (v x1) := (nth vars x1)
| Qu vars (linvOL x1 x2) := ((linv Qu) (evalOpB Qu vars x1) (evalOpB Qu vars x2))
| Qu vars (rinvOL x1 x2) := ((rinv Qu) (evalOpB Qu vars x1) (evalOpB Qu vars x2))
def evalOp {A : Type} {n : ℕ} : ((Quandle A) → ((vector A n) → ((OpQuandleTerm2 n A) → A)))
| Qu vars (v2 x1) := (nth vars x1)
| Qu vars (sing2 x1) := x1
| Qu vars (linvOL2 x1 x2) := ((linv Qu) (evalOp Qu vars x1) (evalOp Qu vars x2))
| Qu vars (rinvOL2 x1 x2) := ((rinv Qu) (evalOp Qu vars x1) (evalOp Qu vars x2))
def inductionB {P : (QuandleTerm → Type)} : ((∀ (x1 x2 : QuandleTerm) , ((P x1) → ((P x2) → (P (linvL x1 x2))))) → ((∀ (x1 x2 : QuandleTerm) , ((P x1) → ((P x2) → (P (rinvL x1 x2))))) → (∀ (x : QuandleTerm) , (P x))))
| plinvl prinvl (linvL x1 x2) := (plinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2))
| plinvl prinvl (rinvL x1 x2) := (prinvl _ _ (inductionB plinvl prinvl x1) (inductionB plinvl prinvl x2))
def inductionCl {A : Type} {P : ((ClQuandleTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClQuandleTerm A)) , ((P x1) → ((P x2) → (P (linvCl x1 x2))))) → ((∀ (x1 x2 : (ClQuandleTerm A)) , ((P x1) → ((P x2) → (P (rinvCl x1 x2))))) → (∀ (x : (ClQuandleTerm A)) , (P x)))))
| psing plinvcl prinvcl (sing x1) := (psing x1)
| psing plinvcl prinvcl (linvCl x1 x2) := (plinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2))
| psing plinvcl prinvcl (rinvCl x1 x2) := (prinvcl _ _ (inductionCl psing plinvcl prinvcl x1) (inductionCl psing plinvcl prinvcl x2))
def inductionOpB {n : ℕ} {P : ((OpQuandleTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpQuandleTerm n)) , ((P x1) → ((P x2) → (P (linvOL x1 x2))))) → ((∀ (x1 x2 : (OpQuandleTerm n)) , ((P x1) → ((P x2) → (P (rinvOL x1 x2))))) → (∀ (x : (OpQuandleTerm n)) , (P x)))))
| pv plinvol prinvol (v x1) := (pv x1)
| pv plinvol prinvol (linvOL x1 x2) := (plinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2))
| pv plinvol prinvol (rinvOL x1 x2) := (prinvol _ _ (inductionOpB pv plinvol prinvol x1) (inductionOpB pv plinvol prinvol x2))
def inductionOp {n : ℕ} {A : Type} {P : ((OpQuandleTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpQuandleTerm2 n A)) , ((P x1) → ((P x2) → (P (linvOL2 x1 x2))))) → ((∀ (x1 x2 : (OpQuandleTerm2 n A)) , ((P x1) → ((P x2) → (P (rinvOL2 x1 x2))))) → (∀ (x : (OpQuandleTerm2 n A)) , (P x))))))
| pv2 psing2 plinvol2 prinvol2 (v2 x1) := (pv2 x1)
| pv2 psing2 plinvol2 prinvol2 (sing2 x1) := (psing2 x1)
| pv2 psing2 plinvol2 prinvol2 (linvOL2 x1 x2) := (plinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2))
| pv2 psing2 plinvol2 prinvol2 (rinvOL2 x1 x2) := (prinvol2 _ _ (inductionOp pv2 psing2 plinvol2 prinvol2 x1) (inductionOp pv2 psing2 plinvol2 prinvol2 x2))
def stageB : (QuandleTerm → (Staged QuandleTerm))
| (linvL x1 x2) := (stage2 linvL (codeLift2 linvL) (stageB x1) (stageB x2))
| (rinvL x1 x2) := (stage2 rinvL (codeLift2 rinvL) (stageB x1) (stageB x2))
def stageCl {A : Type} : ((ClQuandleTerm A) → (Staged (ClQuandleTerm A)))
| (sing x1) := (Now (sing x1))
| (linvCl x1 x2) := (stage2 linvCl (codeLift2 linvCl) (stageCl x1) (stageCl x2))
| (rinvCl x1 x2) := (stage2 rinvCl (codeLift2 rinvCl) (stageCl x1) (stageCl x2))
def stageOpB {n : ℕ} : ((OpQuandleTerm n) → (Staged (OpQuandleTerm n)))
| (v x1) := (const (code (v x1)))
| (linvOL x1 x2) := (stage2 linvOL (codeLift2 linvOL) (stageOpB x1) (stageOpB x2))
| (rinvOL x1 x2) := (stage2 rinvOL (codeLift2 rinvOL) (stageOpB x1) (stageOpB x2))
def stageOp {n : ℕ} {A : Type} : ((OpQuandleTerm2 n A) → (Staged (OpQuandleTerm2 n A)))
| (sing2 x1) := (Now (sing2 x1))
| (v2 x1) := (const (code (v2 x1)))
| (linvOL2 x1 x2) := (stage2 linvOL2 (codeLift2 linvOL2) (stageOp x1) (stageOp x2))
| (rinvOL2 x1 x2) := (stage2 rinvOL2 (codeLift2 rinvOL2) (stageOp x1) (stageOp x2))
structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type :=
(linvT : ((Repr A) → ((Repr A) → (Repr A))))
(rinvT : ((Repr A) → ((Repr A) → (Repr A))))
end Quandle |
d8122bb02212e703474f08d4781744bceef5880c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/group/integration.lean | 258cf46be347d58fb5ae1fb7dc83ab83ce27ee5e | [
"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,119 | lean | /-
Copyright (c) 2022 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.integral.bochner
import measure_theory.group.measure
import measure_theory.group.action
/-!
# Integration on Groups
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We develop properties of integrals with a group as domain.
This file contains properties about integrability, Lebesgue integration and Bochner integration.
-/
namespace measure_theory
open measure topological_space
open_locale ennreal
variables {𝕜 M α G E F : Type*} [measurable_space G]
variables [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] [normed_add_comm_group F]
variables {μ : measure G} {f : G → E} {g : G}
section measurable_inv
variables [group G] [has_measurable_inv G]
@[to_additive]
lemma integrable.comp_inv [is_inv_invariant μ] {f : G → F} (hf : integrable f μ) :
integrable (λ t, f t⁻¹) μ :=
(hf.mono_measure (map_inv_eq_self μ).le).comp_measurable measurable_inv
@[to_additive]
lemma integral_inv_eq_self (f : G → E) (μ : measure G) [is_inv_invariant μ] :
∫ x, f (x⁻¹) ∂μ = ∫ x, f x ∂μ :=
begin
have h : measurable_embedding (λ x : G, x⁻¹) :=
(measurable_equiv.inv G).measurable_embedding,
rw [← h.integral_map, map_inv_eq_self]
end
end measurable_inv
section measurable_mul
variables [group G] [has_measurable_mul G]
/-- Translating a function by left-multiplication does not change its `measure_theory.lintegral`
with respect to a left-invariant measure. -/
@[to_additive "Translating a function by left-addition does not change its
`measure_theory.lintegral` with respect to a left-invariant measure."]
lemma lintegral_mul_left_eq_self [is_mul_left_invariant μ] (f : G → ℝ≥0∞) (g : G) :
∫⁻ x, f (g * x) ∂μ = ∫⁻ x, f x ∂μ :=
begin
convert (lintegral_map_equiv f $ measurable_equiv.mul_left g).symm,
simp [map_mul_left_eq_self μ g]
end
/-- Translating a function by right-multiplication does not change its `measure_theory.lintegral`
with respect to a right-invariant measure. -/
@[to_additive "Translating a function by right-addition does not change its
`measure_theory.lintegral` with respect to a right-invariant measure."]
lemma lintegral_mul_right_eq_self [is_mul_right_invariant μ] (f : G → ℝ≥0∞) (g : G) :
∫⁻ x, f (x * g) ∂μ = ∫⁻ x, f x ∂μ :=
begin
convert (lintegral_map_equiv f $ measurable_equiv.mul_right g).symm,
simp [map_mul_right_eq_self μ g]
end
@[simp, to_additive]
lemma lintegral_div_right_eq_self [is_mul_right_invariant μ] (f : G → ℝ≥0∞) (g : G) :
∫⁻ x, f (x / g) ∂μ = ∫⁻ x, f x ∂μ :=
by simp_rw [div_eq_mul_inv, lintegral_mul_right_eq_self f g⁻¹]
/-- Translating a function by left-multiplication does not change its integral with respect to a
left-invariant measure. -/
@[simp, to_additive "Translating a function by left-addition does not change its integral with
respect to a left-invariant measure."]
lemma integral_mul_left_eq_self [is_mul_left_invariant μ] (f : G → E) (g : G) :
∫ x, f (g * x) ∂μ = ∫ x, f x ∂μ :=
begin
have h_mul : measurable_embedding (λ x, g * x) :=
(measurable_equiv.mul_left g).measurable_embedding,
rw [← h_mul.integral_map, map_mul_left_eq_self]
end
/-- Translating a function by right-multiplication does not change its integral with respect to a
right-invariant measure. -/
@[simp, to_additive "Translating a function by right-addition does not change its integral with
respect to a right-invariant measure."]
lemma integral_mul_right_eq_self [is_mul_right_invariant μ] (f : G → E) (g : G) :
∫ x, f (x * g) ∂μ = ∫ x, f x ∂μ :=
begin
have h_mul : measurable_embedding (λ x, x * g) :=
(measurable_equiv.mul_right g).measurable_embedding,
rw [← h_mul.integral_map, map_mul_right_eq_self]
end
@[simp, to_additive]
lemma integral_div_right_eq_self [is_mul_right_invariant μ] (f : G → E) (g : G) :
∫ x, f (x / g) ∂μ = ∫ x, f x ∂μ :=
by simp_rw [div_eq_mul_inv, integral_mul_right_eq_self f g⁻¹]
/-- If some left-translate of a function negates it, then the integral of the function with respect
to a left-invariant measure is 0. -/
@[to_additive "If some left-translate of a function negates it, then the integral of the function
with respect to a left-invariant measure is 0."]
lemma integral_eq_zero_of_mul_left_eq_neg [is_mul_left_invariant μ] (hf' : ∀ x, f (g * x) = - f x) :
∫ x, f x ∂μ = 0 :=
by simp_rw [← self_eq_neg ℝ E, ← integral_neg, ← hf', integral_mul_left_eq_self]
/-- If some right-translate of a function negates it, then the integral of the function with respect
to a right-invariant measure is 0. -/
@[to_additive "If some right-translate of a function negates it, then the integral of the function
with respect to a right-invariant measure is 0."]
lemma integral_eq_zero_of_mul_right_eq_neg [is_mul_right_invariant μ]
(hf' : ∀ x, f (x * g) = - f x) : ∫ x, f x ∂μ = 0 :=
by simp_rw [← self_eq_neg ℝ E, ← integral_neg, ← hf', integral_mul_right_eq_self]
@[to_additive]
lemma integrable.comp_mul_left {f : G → F} [is_mul_left_invariant μ] (hf : integrable f μ)
(g : G) : integrable (λ t, f (g * t)) μ :=
(hf.mono_measure (map_mul_left_eq_self μ g).le).comp_measurable $ measurable_const_mul g
@[to_additive]
lemma integrable.comp_mul_right {f : G → F} [is_mul_right_invariant μ] (hf : integrable f μ)
(g : G) : integrable (λ t, f (t * g)) μ :=
(hf.mono_measure (map_mul_right_eq_self μ g).le).comp_measurable $ measurable_mul_const g
@[to_additive]
lemma integrable.comp_div_right {f : G → F} [is_mul_right_invariant μ] (hf : integrable f μ)
(g : G) : integrable (λ t, f (t / g)) μ :=
by { simp_rw [div_eq_mul_inv], exact hf.comp_mul_right g⁻¹ }
variables [has_measurable_inv G]
@[to_additive]
lemma integrable.comp_div_left {f : G → F}
[is_inv_invariant μ] [is_mul_left_invariant μ] (hf : integrable f μ) (g : G) :
integrable (λ t, f (g / t)) μ :=
((measure_preserving_div_left μ g).integrable_comp hf.ae_strongly_measurable).mpr hf
@[simp, to_additive]
lemma integrable_comp_div_left (f : G → F)
[is_inv_invariant μ] [is_mul_left_invariant μ] (g : G) :
integrable (λ t, f (g / t)) μ ↔ integrable f μ :=
begin
refine ⟨λ h, _, λ h, h.comp_div_left g⟩,
convert h.comp_inv.comp_mul_left g⁻¹,
simp_rw [div_inv_eq_mul, mul_inv_cancel_left]
end
@[simp, to_additive]
lemma integral_div_left_eq_self (f : G → E) (μ : measure G) [is_inv_invariant μ]
[is_mul_left_invariant μ] (x' : G) : ∫ x, f (x' / x) ∂μ = ∫ x, f x ∂μ :=
by simp_rw [div_eq_mul_inv, integral_inv_eq_self (λ x, f (x' * x)) μ,
integral_mul_left_eq_self f x']
end measurable_mul
section smul
variables [group G] [measurable_space α] [mul_action G α] [has_measurable_smul G α]
@[simp, to_additive]
lemma integral_smul_eq_self {μ : measure α} [smul_invariant_measure G α μ] (f : α → E) {g : G} :
∫ x, f (g • x) ∂μ = ∫ x, f x ∂μ :=
begin
have h : measurable_embedding (λ x : α, g • x) :=
(measurable_equiv.smul g).measurable_embedding,
rw [← h.integral_map, map_smul]
end
end smul
section topological_group
variables [topological_space G] [group G] [topological_group G] [borel_space G]
[is_mul_left_invariant μ]
/-- For nonzero regular left invariant measures, the integral of a continuous nonnegative function
`f` is 0 iff `f` is 0. -/
@[to_additive "For nonzero regular left invariant measures, the integral of a continuous nonnegative
function `f` is 0 iff `f` is 0."]
lemma lintegral_eq_zero_of_is_mul_left_invariant [regular μ] (hμ : μ ≠ 0)
{f : G → ℝ≥0∞} (hf : continuous f) :
∫⁻ x, f x ∂μ = 0 ↔ f = 0 :=
begin
haveI := is_open_pos_measure_of_mul_left_invariant_of_regular hμ,
rw [lintegral_eq_zero_iff hf.measurable, hf.ae_eq_iff_eq μ continuous_zero]
end
end topological_group
end measure_theory
|
3d9d9a931d835916fae52614e2d83446df02ee82 | f1a12d4db0f46eee317d703e3336d33950a2fe7e | /common/logic.lean | 42bbc6869ab6561286de72e6851ccf0e6d7f940e | [
"Apache-2.0"
] | permissive | avigad/qelim | bce89b79c717b7649860d41a41a37e37c982624f | b7d22864f1f0a2d21adad0f4fb3fc7ba665f8e60 | refs/heads/master | 1,584,548,938,232 | 1,526,773,708,000 | 1,526,773,708,000 | 134,967,693 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,775 | lean | import .list
inductive fm (α : Type) : Type
| true : fm
| false : fm
| atom : α → fm
| and : fm → fm → fm
| or : fm → fm → fm
| not : fm → fm
| ex : fm → fm
notation `⊤'` := fm.true _
notation `⊥'` := fm.false _
notation `A'` a := fm.atom a
notation `¬'` p := fm.not p
notation p `∧'` q := fm.and p q
notation p `∨'` q := fm.or p q
notation `∃'` p := fm.ex p
-- | ⊤' := sorry
-- | ⊥' := sorry
-- | (A' a) := sorry
-- | (p ∧' q) := sorry
-- | (p ∨' q) := sorry
-- | (¬' p) := sorry
-- | (∃' p) := sorry
variables {α β : Type}
meta def fm_to_format [has_to_format α] : fm α → format
| (fm.true α) := "⊤"
| (fm.false α) := "⊥"
| (fm.atom a) := to_fmt a
| (fm.and p q) := "(" ++ (fm_to_format p) ++ " ∧ " ++ (fm_to_format q) ++ ")"
| (fm.or p q) := "(" ++ (fm_to_format p) ++ " ∨ " ++ (fm_to_format q) ++ ")"
| (fm.not p) := "¬(" ++ (fm_to_format p) ++ ")"
| (fm.ex p) := "∃(" ++ (fm_to_format p) ++ ")"
meta instance [has_to_format α] : has_to_format (fm α) := ⟨fm_to_format⟩
meta instance [has_to_format α] : has_to_tactic_format (fm α) :=
has_to_format_to_has_to_tactic_format _
def top_or_not (p : fm α) : p = ⊤' ∨ p ≠ ⊤' :=
by cases p; {{apply or.inl, refl} <|> {apply or.inr, intro HC, cases HC}}
def bot_or_not (p : fm α) : p = ⊥' ∨ p ≠ ⊥' :=
by cases p; {{apply or.inl, refl} <|> {apply or.inr, intro HC, cases HC}}
def and_o : fm α → fm α → fm α
| (fm.true α) q' := q'
| p' (fm.true α) := p'
| (fm.false α) q' := fm.false α
| p' (fm.false α) := fm.false α
| p' q' := fm.and p' q'
-- Q : Why can't I prove this with refl?
lemma exp_top_and_o (p : fm α) : (@and_o α ⊤' p) = p :=
by induction p; {intro_refl}
lemma exp_and_o_top (p : fm α) : (@and_o α p ⊤') = p :=
by induction p; {intro_refl}
lemma exp_bot_and_o (p : fm α) : (@and_o α ⊥' p) = ⊥' :=
by induction p; {intro_refl}
lemma exp_and_o_bot (p : fm α) : (@and_o α p ⊥') = ⊥' :=
by induction p; {intro_refl}
lemma exp_and_o_nc (p q : fm α) :
(p ≠ ⊤') → (p ≠ ⊥') → (q ≠ ⊤') → (q ≠ ⊥') → (@and_o α p q) = (p ∧' q) :=
by intros H1 H2 H3 H4; cases p; cases q; {refl <|> contradiction}
lemma cases_and_o (P : fm α → Prop) (p q : fm α)
(HB : P ⊥') (Hp : P p) (Hq : P q) (Hpq : P (p ∧' q)) : P (and_o p q) :=
begin
cases (top_or_not p) with H1 H1, rewrite H1,
rewrite exp_top_and_o, apply Hq,
cases (bot_or_not p) with H2 H2, rewrite H2,
rewrite exp_bot_and_o, apply HB,
cases (top_or_not q) with H3 H3, rewrite H3,
rewrite exp_and_o_top, apply Hp,
cases (bot_or_not q) with H4 H4, rewrite H4,
rewrite exp_and_o_bot, apply HB,
rewrite exp_and_o_nc _ _ H1 H2 H3 H4,
apply Hpq
end
lemma cases_and_o' (P : fm α → fm α → fm α → Prop) (p q : fm α)
(HTq : P ⊤' q q) (HBq : P ⊥' q ⊥')
(HpT : P p ⊤' p) (HpB : P p ⊥' ⊥')
(Hpq : P p q (p ∧' q)) : P p q (and_o p q) :=
begin
cases (top_or_not p) with H1 H1, rewrite H1,
rewrite exp_top_and_o, apply HTq,
cases (bot_or_not p) with H2 H2, rewrite H2,
rewrite exp_bot_and_o, apply HBq,
cases (top_or_not q) with H3 H3, rewrite H3,
rewrite exp_and_o_top, apply HpT,
cases (bot_or_not q) with H4 H4, rewrite H4,
rewrite exp_and_o_bot, apply HpB,
rewrite exp_and_o_nc _ _ H1 H2 H3 H4,
apply Hpq
end
def or_o : fm α → fm α → fm α
| (fm.true α) _ := ⊤'
| _ (fm.true α) := ⊤'
| (fm.false α) q := q
| p (fm.false α) := p
| p q := fm.or p q
lemma exp_top_or_o (p : fm α) : (@or_o α ⊤' p) = ⊤' :=
by induction p; {intro_refl}
lemma exp_bot_or_o (p : fm α) : (@or_o α ⊥' p) = p :=
by induction p; {intro_refl}
lemma exp_or_o_top (p : fm α) : (@or_o α p ⊤') = ⊤' :=
by induction p; {intro_refl}
lemma exp_or_o_bot (p : fm α) : (@or_o α p ⊥') = p :=
by induction p; {intro_refl}
lemma exp_or_o_nc (p q : fm α) :
(p ≠ ⊤') → (p ≠ ⊥') → (q ≠ ⊤') → (q ≠ ⊥') → (@or_o α p q) = (p ∨' q) :=
by intros H1 H2 H3 H4; cases p; cases q; {refl <|> contradiction}
lemma cases_or_o (P : fm α → Prop) (p q : fm α)
(HT : P ⊤') (Hp : P p) (Hq : P q) (Hpq : P (p ∨' q)) : P (or_o p q) :=
begin
cases (top_or_not p) with H1 H1, rewrite H1,
rewrite exp_top_or_o, apply HT,
cases (bot_or_not p) with H2 H2, rewrite H2,
rewrite exp_bot_or_o, apply Hq,
cases (top_or_not q) with H3 H3, rewrite H3,
rewrite exp_or_o_top, apply HT,
cases (bot_or_not q) with H4 H4, rewrite H4,
rewrite exp_or_o_bot, apply Hp,
rewrite exp_or_o_nc _ _ H1 H2 H3 H4,
apply Hpq
end
lemma cases_or_o' (P : fm α → fm α → fm α → Prop) (p q : fm α)
(HTq : P ⊤' q ⊤') (HBq : P ⊥' q q)
(HpT : P p ⊤' ⊤') (HpB : P p ⊥' p)
(Hpq : P p q (p ∨' q)) : P p q (or_o p q) :=
begin
cases (top_or_not p) with H1 H1, rewrite H1,
rewrite exp_top_or_o, apply HTq,
cases (bot_or_not p) with H2 H2, rewrite H2,
rewrite exp_bot_or_o, apply HBq,
cases (top_or_not q) with H3 H3, rewrite H3,
rewrite exp_or_o_top, apply HpT,
cases (bot_or_not q) with H4 H4, rewrite H4,
rewrite exp_or_o_bot, apply HpB,
rewrite exp_or_o_nc _ _ H1 H2 H3 H4,
apply Hpq
end
def not_o : fm α → fm α
| ⊤' := ⊥'
| ⊥' := ⊤'
| p := ¬' p
lemma cases_not_o_core (P : fm α → fm α → Prop) (p : fm α)
(ht : P p ⊤' ) (hb : P p ⊥') (hnp : P p (¬' p)) : P p (not_o p) :=
begin cases p, apply hb, apply ht, repeat {apply hnp}, end
lemma cases_not_o (P : fm α → Prop) (p : fm α)
(ht : P ⊤' ) (hb : P ⊥') (hnp : P (¬' p)) : P (not_o p) :=
cases_not_o_core (λ _ q, P q) p ht hb hnp
lemma exp_not_o_top : not_o ⊤' = (fm.false α) := eq.refl _
lemma exp_not_o_bot : not_o ⊥' = (fm.true α) := eq.refl _
lemma exp_not_o_nc (p : fm α) :
(p ≠ ⊤') → (p ≠ ⊥') → (@not_o α p) = ¬' p :=
by intros H1 H2; cases p; {refl <|> contradiction}
def list_conj : list (fm α) → fm α
| [] := ⊤'
| (p::ps) := and_o p $ list_conj ps
def list_disj : list (fm α) → fm α
| [] := ⊥'
| (p::ps) := or_o p $ list_disj ps
def disj (bs : list β) (f : β → fm α) := list_disj (list.map f bs)
def dnf_to_fm (ls : list (list α)) (f : list α → fm α) := list_disj (list.map f ls)
-- def nfree : fm α → bool
-- | ⊤' := tt
-- | ⊥' := tt
-- | A' a := tt
-- | (¬' p) := ff
-- | (p ∨' q) := nfree p && nfree q
-- | (p ∧' q) := nfree p && nfree q
-- | (∃' p) := nfree p
def qfree : fm α → Prop
| ⊤' := true
| ⊥' := true
| A' a := true
| (¬' p) := qfree p
| (p ∨' q) := qfree p ∧ qfree q
| (p ∧' q) := qfree p ∧ qfree q
| (∃' p) := false
def nqfree : fm α → Prop
| ⊤' := true
| ⊥' := true
| A' a := true
| (¬' p) := false
| (p ∨' q) := nqfree p ∧ nqfree q
| (p ∧' q) := nqfree p ∧ nqfree q
| (∃' p) := false
lemma qfree_of_nqfree : ∀ (p : fm α), nqfree p → qfree p
| ⊤' _ := trivial
| ⊥' _ := trivial
| (A' a) _ := trivial
| (¬' p) h := by cases h
| (p ∨' q) h :=
begin
cases h with hp hq, apply and.intro;
apply qfree_of_nqfree; assumption
end
| (p ∧' q) h :=
begin
cases h with hp hq, apply and.intro;
apply qfree_of_nqfree; assumption
end
| (∃' p) h := by cases h
inductive down : fm α → fm α → Prop
| andl : ∀ p q, down (p ∧' q) p
| andr : ∀ p q, down (p ∧' q) q
| orl : ∀ p q, down (p ∨' q) p
| orr : ∀ p q, down (p ∨' q) q
| not : ∀ p, down (¬' p) p
| ex : ∀ p, down (∃' p) p
def down_closed (P : fm α → Prop) : Prop :=
∀ (p q : fm α), down p q → P p → P q
def of_subformulas (P : fm α → Prop) : fm α → Prop
| ⊤' := P ⊤'
| ⊥' := P ⊥'
| (A' a) := true
| (p ∧' q) := P p → P q → P (p ∧' q)
| (p ∨' q) := P p → P q → P (p ∨' q)
| (¬' p) := P p → P (¬' p)
| (∃' p) := P p → P (∃' p)
def of_prop_subformulas (P : fm α → Prop) : fm α → Prop
| ⊤' := P ⊤'
| ⊥' := P ⊥'
| (A' a) := true
| (p ∧' q) := P p → P q → P (p ∧' q)
| (p ∨' q) := P p → P q → P (p ∨' q)
| (¬' p) := P p → P (¬' p)
| (∃' p) := true
def up_closed (P : fm α → Prop) : Prop :=
∀ (p : fm α), of_subformulas P p
def prop_up_closed (P : fm α → Prop) : Prop :=
∀ (p : fm α), of_prop_subformulas P p
lemma pred_and_o (P : fm α → Prop) (hup : prop_up_closed P) :
∀ (p q : fm α), P p → P q → P (and_o p q) :=
begin
intros p q hp hq, apply cases_and_o;
try {apply hup ⊥' <|> assumption},
apply hup (p ∧' q); assumption
end
lemma pred_or_o (P : fm α → Prop) (hup : prop_up_closed P) :
∀ (p q : fm α), P p → P q → P (or_o p q) :=
begin
intros p q hp hq, apply cases_or_o;
try {apply hup ⊤' <|> assumption},
apply hup (p ∨' q); assumption
end
lemma pred_list_disj (P : fm α → Prop) (hup : prop_up_closed P) :
∀ (ps : list (fm α)), (∀ p ∈ ps, P p) → P (list_disj ps)
| [] h := hup ⊥'
| (p::ps) h :=
begin
unfold list_disj, apply pred_or_o _ hup,
apply h, apply or.inl rfl,
apply pred_list_disj,
apply list.forall_mem_of_forall_mem_cons h
end
lemma pred_disj (P : fm α → Prop) (hup : prop_up_closed P)
(bs : list β) (f : β → fm α) : (∀ b ∈ bs, P (f b)) → P (disj bs f) :=
begin
intro h, unfold disj, apply pred_list_disj _ hup,
intros p hp, rewrite list.mem_map at hp,
cases hp with b hb, cases hb with hb1 hb2,
subst hb2, apply h, apply hb1
end
lemma down_closed_qfree : @down_closed α qfree
| ⊤' _ hd _ := by cases hd
| ⊥' _ hd _ := by cases hd
| (A' a) _ hd _ := by cases hd
| (p ∧' q) r hd hn :=
begin cases hn with hnp hnq, cases hd; assumption end
| (p ∨' q) r hd hn :=
begin cases hn with hnp hnq, cases hd; assumption end
-- by {unfold fnormal at hn, cases hn, cases hd; assumption}
| (¬' p) r hd hn := begin cases hd, apply hn end
| (∃' p) r hd hn := by cases hn
lemma prop_up_closed_qfree : @prop_up_closed α qfree
| ⊤' := trivial
| ⊥' := trivial
| (A' a) := trivial
| (p ∧' q) := begin intros hp hq, apply and.intro hp hq end
| (p ∨' q) := begin intros hp hq, apply and.intro hp hq end
| (¬' p) := id
| (∃' p) := trivial
lemma qfree_and_o : ∀ {p q : fm α}, qfree p → qfree q → qfree (and_o p q) :=
pred_and_o _ prop_up_closed_qfree
lemma qfree_or_o : ∀ {p q : fm α}, qfree p → qfree q → qfree (or_o p q) :=
pred_or_o _ prop_up_closed_qfree
lemma qfree_list_disj : ∀ (ps : list (fm α)), (∀ p ∈ ps, qfree p) → qfree (list_disj ps) :=
pred_list_disj _ prop_up_closed_qfree
lemma qfree_disj : ∀ (bs : list β) (f : β → fm α), (∀ b ∈ bs, qfree (f b)) → qfree (disj bs f) :=
pred_disj _ prop_up_closed_qfree
lemma qfree_list_conj : ∀ (ps : list (fm α)), (∀ p ∈ ps, qfree p) → qfree (list_conj ps)
| [] _ := trivial
| (p::ps) h :=
begin
unfold list_conj, apply cases_and_o, trivial,
apply h, simp, apply qfree_list_conj,
intros q Hq, apply h, apply or.inr, apply Hq,
unfold qfree, apply and.intro,
apply h, simp, apply qfree_list_conj,
intros q Hq, apply h, apply or.inr, apply Hq
end
lemma qfree_dnf_to_fm (f : list α → fm α) (H : ∀ l, qfree (f l)) : ∀ (ls : list (list α)), qfree (dnf_to_fm ls f)
| [] := trivial
| (l::ls) :=
begin
unfold dnf_to_fm, unfold list.map, unfold list_disj,
apply cases_or_o qfree _ _ trivial,
apply H, apply qfree_dnf_to_fm,
unfold qfree, apply and.intro,
apply H, apply qfree_dnf_to_fm
end
/-
Requires : qfree arg-0
-/
def map_fm (f : α → β) : fm α → fm β
| ⊤' := ⊤'
| ⊥' := ⊥'
| A' a := A' (f a)
| (¬' p) := ¬' (map_fm p)
| (p ∨' q) := (map_fm p) ∨' (map_fm q)
| (p ∧' q) := (map_fm p) ∧' (map_fm q)
| (∃' p) := ⊥'
/-
Requires : qfree arg-0
-/
def amap (f : α → fm β) : fm α → fm β
| ⊤' := ⊤'
| ⊥' := ⊥'
| A' a := f a
| (¬' p) := not_o (amap p)
| (p ∨' q) := or_o (amap p) (amap q)
| (p ∧' q) := and_o (amap p) (amap q)
| (∃' p) := ⊥'
def atoms [decidable_eq α] : fm α → list α
| ⊤' := []
| ⊥' := []
| A' a := [a]
| (¬' p) := atoms p
| (p ∨' q) := (atoms p) ∪ (atoms q)
| (p ∧' q) := (atoms p) ∪ (atoms q)
| (∃' p) := atoms p
meta def map_fm_prsv_tac :=
`[unfold map_fm, unfold atoms,
rewrite list.forall_mem_union, unfold atoms at h,
rewrite list.forall_mem_union at h, cases h with hp hq,
apply and.intro; apply map_fm_prsv; assumption]
lemma map_fm_prsv [decidable_eq α] [decidable_eq β] (P : α → Prop) {Q : β → Prop}
{f : α → β} (hf : ∀ a, P a → Q (f a)) :
∀ {p} {hp : ∀ a ∈ (atoms p), P a}, ∀ a ∈ (atoms (map_fm f p)), Q a
| ⊤' h := begin apply list.forall_mem_nil end
| ⊥' h := begin apply list.forall_mem_nil end
| (A' a) h :=
begin
unfold map_fm, unfold atoms, intros b hb,
rewrite list.mem_singleton at hb, subst hb,
apply hf, apply h, unfold atoms, apply or.inl rfl
end
| (¬' p) h :=
begin
unfold map_fm, unfold atoms, unfold atoms at h,
apply map_fm_prsv, apply h
end
| (p ∧' q) h := by map_fm_prsv_tac
| (p ∨' q) h := by map_fm_prsv_tac
| (∃' p) h :=
begin unfold map_fm, unfold atoms, apply list.forall_mem_nil end
lemma atoms_map_fm [decidable_eq α] [decidable_eq β] (f : α → β) :
∀ (p : fm α), nqfree p → list.equiv (atoms (map_fm f p)) (list.map f (atoms p))
| ⊤' _ := by apply list.equiv.refl
| ⊥' _ := by apply list.equiv.refl
| (A' a) _ := by apply list.equiv.refl
| (p ∧' q) hf :=
begin
cases hf with hfp hfq, unfold map_fm,
unfold atoms, apply list.equiv.trans,
apply list.union_equiv_union_of_equiv
(atoms_map_fm p hfp),
apply list.equiv.trans list.union_comm,
apply list.equiv.trans,
apply list.union_equiv_union_of_equiv
(atoms_map_fm q hfq),
apply list.equiv.trans list.union_comm,
apply list.equiv.symm, apply list.map_union
end
| (p ∨' q) hf :=
begin
cases hf with hfp hfq, unfold map_fm,
unfold atoms, apply list.equiv.trans,
apply list.union_equiv_union_of_equiv
(atoms_map_fm p hfp),
apply list.equiv.trans list.union_comm,
apply list.equiv.trans,
apply list.union_equiv_union_of_equiv
(atoms_map_fm q hfq),
apply list.equiv.trans list.union_comm,
apply list.equiv.symm, apply list.map_union
end
| (¬' p) hf := by cases hf
| (∃' p) hf := by cases hf
def interp (h : list β → α → Prop) : list β → fm α → Prop
| xs ⊤' := true
| xs ⊥' := false
| xs (A' a) := h xs a
| xs (¬' p) := ¬ (interp xs p)
| xs (p ∨' q) := (interp xs p) ∨ (interp xs q)
| xs (p ∧' q) := (interp xs p) ∧ (interp xs q)
| xs ∃' p := exists (x : β), interp (x::xs) p
|
17a389c801b2c22c38ef5268d8261ecb8cc46982 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Parser/Basic.lean | 26c1f91dc54f3a00369bc169ee26e1af7e436646 | [
"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 | 65,460 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
/-!
# Basic Lean parser infrastructure
The Lean parser was developed with the following primary goals in mind:
* flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be
possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach.
* extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this
to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens.
* losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token"
information for the use in tooling.
* performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity
input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be
necessary for this.
Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent
parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate
flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar
with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the
basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding
constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers
push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their
output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and
wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we
usually use the macro `parser! p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the
declaration being defined.
The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies
detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent
one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the
first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in
the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token
parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by
zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser`
for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace.
The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information:
`collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST"
token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information
in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel.
If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator.
This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these
parallel parsers apart from the first token, though we might change this in the future if the need arises.
Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero
or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators
running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly.
Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips
tokens until the next command keyword on error.
-/
import Lean.Data.Trie
import Lean.Data.Position
import Lean.Syntax
import Lean.ToExpr
import Lean.Environment
import Lean.Attributes
import Lean.Message
import Lean.Compiler.InitAttr
namespace Lean
def quotedSymbolKind := `quotedSymbol
namespace Parser
def isLitKind (k : SyntaxNodeKind) : Bool :=
k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind
abbrev mkAtom (info : SourceInfo) (val : String) : Syntax :=
Syntax.atom info val
abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax :=
Syntax.ident info rawVal val []
/- Return character after position `pos` -/
def getNext (input : String) (pos : Nat) : Char :=
input.get (input.next pos)
/- Maximal (and function application) precedence.
In the standard lean language, no parser has precedence higher than `maxPrec`.
Note that nothing prevents users from using a higher precedence, but we strongly
discourage them from doing it. -/
def maxPrec : Nat := 1024
def leadPrec := maxPrec - 1
abbrev Token := String
structure TokenCacheEntry :=
(startPos stopPos : String.Pos := 0)
(token : Syntax := Syntax.missing)
structure ParserCache :=
(tokenCache : TokenCacheEntry)
def initCacheForInput (input : String) : ParserCache :=
{ tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} }
abbrev TokenTable := Trie Token
abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit
def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet :=
s.insert k ()
/-
Input string and related data. Recall that the `FileMap` is a helper structure for mapping
`String.Pos` in the input string to line/column information. -/
structure InputContext :=
(input : String)
(fileName : String)
(fileMap : FileMap)
instance InputContext.inhabited : Inhabited InputContext :=
⟨{ input := "", fileName := "", fileMap := arbitrary _ }⟩
structure ParserContext extends InputContext :=
(prec : Nat)
(env : Environment)
(tokens : TokenTable)
(insideQuot : Bool := false)
(savedPos? : Option Position := none)
structure Error :=
(unexpected : String := "")
(expected : List String := [])
namespace Error
instance : Inhabited Error := ⟨{}⟩
private def expectedToString : List String → String
| [] => ""
| [e] => e
| [e1, e2] => e1 ++ " or " ++ e2
| e::es => e ++ ", " ++ expectedToString es
protected def toString (e : Error) : String :=
let unexpected := if e.unexpected == "" then [] else [e.unexpected];
let expected := if e.expected == [] then [] else
let expected := e.expected.toArray.qsort (fun e e' => e < e');
let expected := expected.toList.eraseReps;
["expected " ++ expectedToString expected];
"; ".intercalate $ unexpected ++ expected
instance : HasToString Error := ⟨Error.toString⟩
protected def beq (e₁ e₂ : Error) : Bool :=
e₁.unexpected == e₂.unexpected && e₁.expected == e₂.expected
instance : HasBeq Error := ⟨Error.beq⟩
def merge (e₁ e₂ : Error) : Error :=
match e₂ with
| { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected }
end Error
structure ParserState :=
(stxStack : Array Syntax := #[])
(pos : String.Pos := 0)
(cache : ParserCache)
(errorMsg : Option Error := none)
namespace ParserState
@[inline] def hasError (s : ParserState) : Bool :=
s.errorMsg != none
@[inline] def stackSize (s : ParserState) : Nat :=
s.stxStack.size
def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos }
def setPos (s : ParserState) (pos : Nat) : ParserState :=
{ s with pos := pos }
def setCache (s : ParserState) (cache : ParserCache) : ParserState :=
{ s with cache := cache }
def pushSyntax (s : ParserState) (n : Syntax) : ParserState :=
{ s with stxStack := s.stxStack.push n }
def popSyntax (s : ParserState) : ParserState :=
{ s with stxStack := s.stxStack.pop }
def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState :=
{ s with stxStack := s.stxStack.shrink iniStackSz }
def next (s : ParserState) (input : String) (pos : Nat) : ParserState :=
{ s with pos := input.next pos }
def toErrorMsg (ctx : ParserContext) (s : ParserState) : String :=
match s.errorMsg with
| none => ""
| some msg =>
let pos := ctx.fileMap.toPosition s.pos;
mkErrorStringWithPos ctx.fileName pos.line pos.column (toString msg)
def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
if err != none && stack.size == iniStackSz then
-- If there is an error but there are no new nodes on the stack, we just return `s`
s
else
let newNode := Syntax.node k (stack.extract iniStackSz stack.size);
let stack := stack.shrink iniStackSz;
let stack := stack.push newNode;
⟨stack, pos, cache, err⟩
def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ =>
let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size);
let stack := stack.shrink iniStackSz;
let stack := stack.push newNode;
⟨stack, pos, cache, err⟩
def mkError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkUnexpectedError (s : ParserState) (msg : String) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
def mkEOIError (s : ParserState) : ParserState :=
s.mkUnexpectedError "end of input"
def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩
def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := ex }⟩
def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩
end ParserState
def ParserFn := ParserContext → ParserState → ParserState
instance ParserFn.inhabited : Inhabited ParserFn := ⟨fun _ => id⟩
inductive FirstTokens
| epsilon : FirstTokens
| unknown : FirstTokens
| tokens : List Token → FirstTokens
| optTokens : List Token → FirstTokens
namespace FirstTokens
def seq : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => tks
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| tks, _ => tks
def toOptional : FirstTokens → FirstTokens
| tokens tks => optTokens tks
| tks => tks
def merge : FirstTokens → FirstTokens → FirstTokens
| epsilon, tks => toOptional tks
| tks, epsilon => toOptional tks
| tokens s₁, tokens s₂ => tokens (s₁ ++ s₂)
| optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂)
| optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂)
| _, _ => unknown
def toStr : FirstTokens → String
| epsilon => "epsilon"
| unknown => "unknown"
| tokens tks => toString tks
| optTokens tks => "?" ++ toString tks
instance : HasToString FirstTokens := ⟨toStr⟩
end FirstTokens
structure ParserInfo :=
(collectTokens : List Token → List Token := id)
(collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id)
(firstTokens : FirstTokens := FirstTokens.unknown)
structure Parser :=
(info : ParserInfo := {})
(fn : ParserFn)
instance Parser.inhabited : Inhabited Parser :=
⟨{ fn := fun _ s => s }⟩
abbrev TrailingParser := Parser
@[noinline] def epsilonInfo : ParserInfo :=
{ firstTokens := FirstTokens.epsilon }
@[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn :=
fun c s =>
if p s.stxStack.back then s
else s.mkUnexpectedError msg
@[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser :=
{ info := epsilonInfo,
fn := checkStackTopFn p msg }
@[inline] def andthenFn (p q : ParserFn) : ParserFn :=
fun c s =>
let s := p c s;
if s.hasError then s else q c s
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.seq q.firstTokens }
@[inline] def andthen (p q : Parser) : Parser :=
{ info := andthenInfo p.info q.info,
fn := andthenFn p.fn q.fn }
instance hasAndthen : HasAndthen Parser :=
⟨andthen⟩
@[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let s := p c s;
s.mkNode n iniSz
@[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let s := p c s;
s.mkTrailingNode n iniSz
@[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := fun s => (p.collectKinds s).insert n,
firstTokens := p.firstTokens }
@[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser :=
{ info := nodeInfo n p.info,
fn := nodeFn n p.fn }
def errorFn (msg : String) : ParserFn :=
fun _ s => s.mkUnexpectedError msg
@[inline] def error (msg : String) : Parser :=
{ info := epsilonInfo,
fn := errorFn msg }
/- Succeeds if `c.prec <= prec` -/
def checkPrecFn (prec : Nat) : ParserFn :=
fun c s =>
if c.prec <= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
@[inline] def checkPrec (prec : Nat) : Parser :=
{ info := epsilonInfo,
fn := checkPrecFn prec }
def checkInsideQuotFn : ParserFn :=
fun c s =>
if c.insideQuot then s
else s.mkUnexpectedError "unexpected syntax outside syntax quotation"
@[inline] def checkInsideQuot : Parser :=
{ info := epsilonInfo,
fn := checkInsideQuotFn }
def checkOutsideQuotFn : ParserFn :=
fun c s =>
if !c.insideQuot then s
else s.mkUnexpectedError "unexpected syntax inside syntax quotation"
@[inline] def checkOutsideQuot : Parser :=
{ info := epsilonInfo,
fn := checkOutsideQuotFn }
def toggleInsideQuotFn (p : ParserFn) : ParserFn :=
fun c s => p { c with insideQuot := !c.insideQuot } s
@[inline] def toggleInsideQuot (p : Parser) : Parser :=
{ info := epsilonInfo,
fn := toggleInsideQuotFn p.fn }
@[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser :=
checkPrec prec >> node n p
@[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser :=
{ info := nodeInfo n p.info,
fn := trailingNodeFn n p.fn }
@[inline] def trailingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : TrailingParser :=
checkPrec prec >> trailingNodeAux n p
@[inline] def group (p : Parser) : Parser :=
node nullKind p
def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState :=
match s with
| ⟨stack, pos, cache, some error2⟩ =>
if pos == iniPos then ⟨stack, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩
else s
| other => other
@[inline] def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
match s.errorMsg with
| some errorMsg =>
if s.pos == iniPos then
mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos mergeErrors
else
s
| none => s
@[inline] def orelseFn (p q : ParserFn) : ParserFn :=
orelseFnCore p q true
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.merge q.firstTokens }
@[inline] def orelse (p q : Parser) : Parser :=
{ info := orelseInfo p.info q.info,
fn := orelseFn p.fn q.fn }
instance hashOrelse : HasOrelse Parser :=
⟨orelse⟩
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo :=
{ collectTokens := info.collectTokens,
collectKinds := info.collectKinds }
@[inline] def tryFn (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
match p c s with
| ⟨stack, _, cache, some msg⟩ => ⟨stack.shrink iniSz, iniPos, cache, some msg⟩
| other => other
@[inline] def try (p : Parser) : Parser :=
{ info := p.info,
fn := tryFn p.fn }
@[inline] def optionalFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s;
s.mkNode nullKind iniSz
@[noinline] def optionaInfo (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := p.collectKinds,
firstTokens := p.firstTokens.toOptional }
@[inline] def optional (p : Parser) : Parser :=
{ info := optionaInfo p.info,
fn := optionalFn p.fn }
@[inline] def lookaheadFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then s else s.restore iniSz iniPos
@[inline] def lookahead (p : Parser) : Parser :=
{ info := p.info,
fn := lookaheadFn p.fn }
@[inline] def notFollowedByFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then
s.restore iniSz iniPos
else
let s := s.restore iniSz iniPos;
s.mkError "notFollowedBy"
@[inline] def notFollowedBy (p : Parser) : Parser :=
{ fn := notFollowedByFn p.fn }
@[specialize] partial def manyAux (p : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := p c s;
if s.hasError then
if iniPos == s.pos then s.restore iniSz iniPos else s
else if iniPos == s.pos then s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything"
else manyAux c s
@[inline] def manyFn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let s := manyAux p c s;
s.mkNode nullKind iniSz
@[inline] def many (p : Parser) : Parser :=
{ info := noFirstTokenInfo p.info,
fn := manyFn p.fn }
@[inline] def many1Fn (p : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let s := andthenFn p (manyAux p) c s;
s.mkNode nullKind iniSz
@[inline] def many1 (p : Parser) : Parser :=
{ info := p.info,
fn := many1Fn p.fn }
@[specialize] private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool)
(iniSz : Nat) : Bool → ParserFn
| pOpt, c, s =>
let sz := s.stackSize;
let pos := s.pos;
let s := p c s;
if s.hasError then
if s.pos > pos then s
else if pOpt then
let s := s.restore sz pos;
s.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
let s := s.pushSyntax Syntax.missing;
s.mkNode nullKind iniSz
else
let sz := s.stackSize;
let pos := s.pos;
let s := sep c s;
if s.hasError then
let s := s.restore sz pos;
s.mkNode nullKind iniSz
else
sepByFnAux allowTrailingSep c s
@[specialize] def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
sepByFnAux p sep allowTrailingSep iniSz true c s
@[specialize] def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn
| c, s =>
let iniSz := s.stackSize;
sepByFnAux p sep allowTrailingSep iniSz false c s
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds }
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens ∘ sep.collectTokens,
collectKinds := p.collectKinds ∘ sep.collectKinds,
firstTokens := p.firstTokens }
@[inline] def sepBy (p sep : Parser) (allowTrailingSep : Bool := false) : Parser :=
{ info := sepByInfo p.info sep.info,
fn := sepByFn allowTrailingSep p.fn sep.fn }
@[inline] def sepBy1 (p sep : Parser) (allowTrailingSep : Bool := false) : Parser :=
{ info := sepBy1Info p.info sep.info,
fn := sepBy1Fn allowTrailingSep p.fn sep.fn }
/- Apply `f` to the syntax object produced by `p` -/
@[inline] def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn :=
fun c s =>
let s := p c s;
if s.hasError then s
else
let stx := s.stxStack.back;
s.popSyntax.pushSyntax (f stx)
@[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo :=
{ collectTokens := p.collectTokens,
collectKinds := p.collectKinds }
@[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser :=
{ info := withResultOfInfo p.info,
fn := withResultOfFn p.fn f }
@[inline] def many1Unbox (p : Parser) : Parser :=
withResultOf (many1 p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx
@[inline] def nodeSepBy1Unbox (k : SyntaxNodeKind) (p sep : Parser) (allowTrailingSep := false) : Parser :=
withResultOf (node k (sepBy1 p sep allowTrailingSep)) fun stx =>
if (stx.getArg 0).getNumArgs < 2 then
(stx.getArg 0).getArg 0
else
stx
@[specialize] partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn
| c, s =>
let i := s.pos;
if c.input.atEnd i then s.mkEOIError
else if p (c.input.get i) then s.next c.input i
else s.mkUnexpectedError errorMsg
@[specialize] partial def takeUntilFn (p : Char → Bool) : ParserFn
| c, s =>
let i := s.pos;
if c.input.atEnd i then s
else if p (c.input.get i) then s
else takeUntilFn c (s.next c.input i)
@[specialize] def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (fun c => !p c)
@[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
partial def finishCommentBlock : Nat → ParserFn
| nesting, c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let i := input.next i;
if curr == '-' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '/' then -- "-/" end of comment
if nesting == 1 then s.next input i
else finishCommentBlock (nesting-1) c (s.next input i)
else
finishCommentBlock nesting c (s.next input i)
else if curr == '/' then
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i)
else finishCommentBlock nesting c (s.setPos i)
else finishCommentBlock nesting c (s.setPos i)
/- Consume whitespace and comments -/
partial def whitespace : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s
else
let curr := input.get i;
if curr.isWhitespace then whitespace c (s.next input i)
else if curr == '-' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i)
else s
else if curr == '/' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then
let i := input.next i;
let curr := input.get i;
if curr == '-' then s -- "/--" doc comment is an actual token
else andthenFn (finishCommentBlock 1) whitespace c (s.next input i)
else s
else s
def mkEmptySubstringAt (s : String) (p : Nat) : Substring :=
{str := s, startPos := p, stopPos := p }
private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn
| c, s =>
let input := c.input;
let stopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let val := input.extract startPos stopPos;
if trailingWs then
let s := whitespace c s;
let stopPos' := s.pos;
let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring };
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
else
let trailing := mkEmptySubstringAt input stopPos;
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } val;
s.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
@[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn
| c, s =>
let startPos := s.pos;
let s := p c s;
if s.hasError then s else rawAux startPos trailingWs c s
@[inline] def chFn (c : Char) (trailingWs := false) : ParserFn :=
rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs
def rawCh (c : Char) (trailingWs := false) : Parser :=
{ fn := chFn c trailingWs }
def hexDigitFn : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let i := input.next i;
if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i
else s.mkUnexpectedError "invalid hexadecimal numeral"
@[specialize] def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if isQuotable curr then
s.next input i
else if curr == 'x' then
andthenFn hexDigitFn hexDigitFn c (s.next input i)
else if curr == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i)
else
s.mkUnexpectedError "invalid escape sequence"
def isQuotableCharDefault (c : Char) : Bool :=
c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't'
def quotedCharFn : ParserFn :=
quotedCharCoreFn isQuotableCharDefault
/-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/
def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn :=
fun c s =>
let input := c.input;
let stopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let val := input.extract startPos stopPos;
let s := whitespace c s;
let wsStopPos := s.pos;
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring };
let info := { leading := leading, pos := startPos, trailing := trailing : SourceInfo };
s.pushSyntax (mkStxLit n val info)
def charLitFnAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let s := s.setPos (input.next i);
let s := if curr == '\\' then quotedCharFn c s else s;
if s.hasError then s
else
let i := s.pos;
let curr := input.get i;
let s := s.setPos (input.next i);
if curr == '\'' then mkNodeToken charLitKind startPos c s
else s.mkUnexpectedError "missing end of character literal"
partial def strLitFnAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
let s := s.setPos (input.next i);
if curr == '\"' then
mkNodeToken strLitKind startPos c s
else if curr == '\\' then andthenFn quotedCharFn strLitFnAux c s
else strLitFnAux c s
def decimalNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhileFn (fun c => c.isDigit) c s;
let input := c.input;
let i := s.pos;
let curr := input.get i;
let s :=
/- TODO(Leo): should we use a different kind for numerals containing decimal points? -/
if curr == '.' then
let i := input.next i;
let curr := input.get i;
if curr.isDigit then
takeWhileFn (fun c => c.isDigit) c (s.setPos i)
else s
else s;
mkNodeToken numLitKind startPos c s
def binNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s;
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s;
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : Nat) : ParserFn :=
fun c s =>
let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s;
mkNodeToken numLitKind startPos c s
def numberFnAux : ParserFn :=
fun c s =>
let input := c.input;
let startPos := s.pos;
if input.atEnd startPos then s.mkEOIError
else
let curr := input.get startPos;
if curr == '0' then
let i := input.next startPos;
let curr := input.get i;
if curr == 'b' || curr == 'B' then
binNumberFn startPos c (s.next input i)
else if curr == 'o' || curr == 'O' then
octalNumberFn startPos c (s.next input i)
else if curr == 'x' || curr == 'X' then
hexNumberFn startPos c (s.next input i)
else
decimalNumberFn startPos c (s.setPos i)
else if curr.isDigit then
decimalNumberFn startPos c (s.next input startPos)
else
s.mkError "numeral"
def isIdCont : String → ParserState → Bool
| input, s =>
let i := s.pos;
let curr := input.get i;
if curr == '.' then
let i := input.next i;
if input.atEnd i then
false
else
let curr := input.get i;
isIdFirst curr || isIdBeginEscape curr
else
false
private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool :=
match tk with
| none => false
| some tk =>
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.bsize ≥ idStopPos - idStartPos
def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn :=
fun c s =>
match tk with
| none => s.mkErrorAt "token" startPos
| some tk =>
let input := c.input;
let leading := mkEmptySubstringAt input startPos;
let stopPos := startPos + tk.bsize;
let s := s.setPos stopPos;
let s := whitespace c s;
let wsStopPos := s.pos;
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring };
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } tk;
s.pushSyntax atom
def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn :=
fun c s =>
let stopPos := s.pos;
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk c s
else
let input := c.input;
let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring };
let s := whitespace c s;
let trailingStopPos := s.pos;
let leading := mkEmptySubstringAt input startPos;
let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring };
let info := { leading := leading, trailing := trailing, pos := startPos : SourceInfo };
let atom := mkIdent info rawVal val;
s.pushSyntax atom
partial def identFnAux (startPos : Nat) (tk : Option Token) : Name → ParserFn
| r, c, s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let curr := input.get i;
if isIdBeginEscape curr then
let startPart := input.next i;
let s := takeUntilFn isIdEndEscape c (s.setPos startPart);
let stopPart := s.pos;
let s := satisfyFn isIdEndEscape "missing end of escaped identifier" c s;
if s.hasError then s
else
let r := mkNameStr r (input.extract startPart stopPart);
if isIdCont input s then
let s := s.next input s.pos;
identFnAux r c s
else
mkIdResult startPos tk r c s
else if isIdFirst curr then
let startPart := i;
let s := takeWhileFn isIdRest c (s.next input i);
let stopPart := s.pos;
let r := mkNameStr r (input.extract startPart stopPart);
if isIdCont input s then
let s := s.next input s.pos;
identFnAux r c s
else
mkIdResult startPos tk r c s
else
mkTokenAndFixPos startPos tk c s
private def isIdFirstOrBeginEscape (c : Char) : Bool :=
isIdFirst c || isIdBeginEscape c
private def nameLitAux (startPos : Nat) : ParserFn
| c, s =>
let input := c.input;
let s := identFnAux startPos none Name.anonymous c (s.next input startPos);
if s.hasError then
s.mkErrorAt "invalid Name literal" startPos
else
let stx := s.stxStack.back;
match stx with
| Syntax.ident _ rawStr _ _ =>
let s := s.popSyntax;
s.pushSyntax (Syntax.node nameLitKind #[mkAtomFrom stx rawStr.toString])
| _ => s.mkError "invalid Name literal"
private def tokenFnAux : ParserFn
| c, s =>
let input := c.input;
let i := s.pos;
let curr := input.get i;
if curr == '\"' then
strLitFnAux i c (s.next input i)
else if curr == '\'' then
charLitFnAux i c (s.next input i)
else if curr.isDigit then
numberFnAux c s
else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then
nameLitAux i c s
else
let (_, tk) := c.tokens.matchPrefix input i;
identFnAux i tk Name.anonymous c s
private def updateCache (startPos : Nat) (s : ParserState) : ParserState :=
match s with
| ⟨stack, pos, cache, none⟩ =>
if stack.size == 0 then s
else
let tk := stack.back;
⟨stack, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩
| other => other
def tokenFn : ParserFn :=
fun c s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else
let tkc := s.cache.tokenCache;
if tkc.startPos == i then
let s := s.pushSyntax tkc.token;
s.setPos tkc.stopPos
else
let s := tokenFnAux c s;
updateCache i s
def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError then (s.restore iniSz iniPos, none)
else
let stx := s.stxStack.back;
(s.restore iniSz iniPos, some stx)
@[inline] def peekToken (c : ParserContext) (s : ParserState) : ParserState × Option Syntax :=
let tkc := s.cache.tokenCache;
if tkc.startPos == s.pos then
(s, some tkc.token)
else
peekTokenAux c s
/- Treat keywords as identifiers. -/
def rawIdentFn : ParserFn :=
fun c s =>
let input := c.input;
let i := s.pos;
if input.atEnd i then s.mkEOIError
else identFnAux i none Name.anonymous c s
@[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn :=
fun c s =>
let startPos := s.pos;
let s := tokenFn c s;
if s.hasError then
s.mkErrorsAt expected startPos
else
match s.stxStack.back with
| Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos
| _ => s.mkErrorsAt expected startPos
@[inline] def symbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
satisfySymbolFn (fun s => s == sym) [errorMsg]
def symbolInfo (sym : String) : ParserInfo :=
{ collectTokens := fun tks => sym :: tks,
firstTokens := FirstTokens.tokens [ sym ] }
@[inline] def symbolFn (sym : String) : ParserFn :=
symbolFnAux sym ("'" ++ sym ++ "'")
@[inline] def symbol (sym : String) : Parser :=
let sym := sym.trim;
{ info := symbolInfo sym,
fn := symbolFn sym }
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this combinator so that
it can still be used as an identifier outside of universes (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
fun c s =>
let startPos := s.pos;
let s := tokenFn c s;
if s.hasError then s.mkErrorAt errorMsg startPos
else
match s.stxStack.back with
| Syntax.atom _ sym' =>
if sym == sym' then s else s.mkErrorAt errorMsg startPos
| Syntax.ident info rawVal _ _ =>
if sym == rawVal.toString then
let s := s.popSyntax;
s.pushSyntax (Syntax.atom info sym)
else
s.mkErrorAt errorMsg startPos
| _ => s.mkErrorAt errorMsg startPos
@[inline] def nonReservedSymbolFn (sym : String) : ParserFn :=
nonReservedSymbolFnAux sym ("'" ++ sym ++ "'")
def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo :=
{ firstTokens :=
if includeIdent then
FirstTokens.tokens [ sym, "ident" ]
else
FirstTokens.tokens [ sym ] }
@[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser :=
let sym := sym.trim;
{ info := nonReservedSymbolInfo sym includeIdent,
fn := nonReservedSymbolFn sym }
partial def strAux (sym : String) (errorMsg : String) : Nat → ParserFn
| j, c, s =>
if sym.atEnd j then s
else
let i := s.pos;
let input := c.input;
if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg
else strAux (sym.next j) c (s.next input i)
def checkTailWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some { trailing := some trailing, .. } => trailing.stopPos > trailing.startPos
| _ => false
def checkWsBeforeFn (errorMsg : String) : ParserFn :=
fun c s =>
let prev := s.stxStack.back;
if checkTailWs prev then s else s.mkError errorMsg
def checkWsBefore (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkWsBeforeFn errorMsg }
def checkTailNoWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| some { trailing := some trailing, .. } => trailing.stopPos == trailing.startPos
| _ => false
private def pickNonNone (stack : Array Syntax) : Syntax :=
match stack.findRev? $ fun stx => !stx.isNone with
| none => Syntax.missing
| some stx => stx
def checkNoWsBeforeFn (errorMsg : String) : ParserFn :=
fun c s =>
let prev := pickNonNone s.stxStack;
if checkTailNoWs prev then s else s.mkError errorMsg
def checkNoWsBefore (errorMsg : String) : Parser :=
{ info := epsilonInfo,
fn := checkNoWsBeforeFn errorMsg }
def symbolNoWsInfo (sym : String) : ParserInfo :=
{ collectTokens := fun tks => sym :: tks,
firstTokens := FirstTokens.tokens [ sym ] }
@[inline] def symbolNoWsFnAux (sym : String) (errorMsg : String) : ParserFn :=
fun c s =>
let left := s.stxStack.back;
if checkTailNoWs left then
let startPos := s.pos;
let input := c.input;
let s := strAux sym errorMsg 0 c s;
if s.hasError then s
else
let leading := mkEmptySubstringAt input startPos;
let stopPos := startPos + sym.bsize;
let trailing := mkEmptySubstringAt input stopPos;
let atom := mkAtom { leading := leading, pos := startPos, trailing := trailing } sym;
s.pushSyntax atom
else
s.mkError errorMsg
@[inline] def symbolNoWsFn (sym : String) : ParserFn :=
symbolNoWsFnAux sym ("'" ++ sym ++ "' without whitespace around it")
/- Similar to `symbol`, but succeeds only if there is no space whitespace after leading term and after `sym`. -/
@[inline] def symbolNoWs (sym : String) : Parser :=
let sym := sym.trim;
{ info := symbolNoWsInfo sym,
fn := symbolNoWsFn sym }
def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn :=
satisfySymbolFn (fun s => s == sym || s == asciiSym) expected
def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo :=
{ collectTokens := fun tks => sym :: asciiSym :: tks,
firstTokens := FirstTokens.tokens [ sym, asciiSym ] }
@[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn :=
unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"]
@[inline] def unicodeSymbol (sym asciiSym : String) : Parser :=
let sym := sym.trim;
let asciiSym := asciiSym.trim;
{ info := unicodeSymbolInfo sym asciiSym,
fn := unicodeSymbolFn sym asciiSym }
def mkAtomicInfo (k : String) : ParserInfo :=
{ firstTokens := FirstTokens.tokens [ k ] }
def numLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos else s
@[inline] def numLitNoAntiquot : Parser :=
{ fn := numLitFn,
info := mkAtomicInfo "numLit" }
def strLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos else s
@[inline] def strLitNoAntiquot : Parser :=
{ fn := strLitFn,
info := mkAtomicInfo "strLit" }
def charLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos else s
@[inline] def charLitNoAntiquot : Parser :=
{ fn := charLitFn,
info := mkAtomicInfo "charLit" }
def nameLitFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos else s
@[inline] def nameLitNoAntiquot : Parser :=
{ fn := nameLitFn,
info := mkAtomicInfo "nameLit" }
def identFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos else s
@[inline] def identNoAntiquot : Parser :=
{ fn := identFn,
info := mkAtomicInfo "ident" }
@[inline] def rawIdentNoAntiquot : Parser :=
{ fn := rawIdentFn }
def identEqFn (id : Name) : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError then
s.mkErrorAt "identifier" iniPos
else match s.stxStack.back with
| Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos else s
| _ => s.mkErrorAt "identifier" iniPos
@[inline] def identEq (id : Name) : Parser :=
{ fn := identEqFn id,
info := mkAtomicInfo "ident" }
def quotedSymbolFn : ParserFn :=
nodeFn quotedSymbolKind (andthenFn (andthenFn (chFn '`') (rawFn (takeUntilFn (fun c => c == '`')))) (chFn '`' true))
-- TODO: remove after old frontend is gone
def quotedSymbol : Parser :=
{ fn := quotedSymbolFn }
def unquotedSymbolFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let s := tokenFn c s;
if s.hasError || s.stxStack.back.isIdent || isLitKind s.stxStack.back.getKind then
s.mkErrorAt "symbol" iniPos
else
s
def unquotedSymbol : Parser :=
{ fn := unquotedSymbolFn }
instance stringToParserCoeOld : HasCoe String Parser := ⟨fun s => symbol s ⟩
instance stringToParserCoe : Coe String Parser := ⟨fun s => symbol s ⟩
namespace ParserState
def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, err⟩ => ⟨stack.shrink oldStackSize, pos, cache, err⟩
def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState :=
match s with
| ⟨stack, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩
def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState :=
match s with
| ⟨stack, pos, cache, some err⟩ =>
if oldError == err then s
else ⟨stack.shrink oldStackSize, pos, cache, some (oldError.merge err)⟩
| other => other
def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState :=
match s with
| ⟨stack, pos, cache, _⟩ =>
let node := stack.back;
let stack := stack.shrink startStackSize;
let stack := stack.push node;
⟨stack, pos, cache, none⟩
def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState :=
s.keepLatest startStackSize
end ParserState
def invalidLongestMatchParser (s : ParserState) : ParserState :=
s.mkError "longestMatch parsers must generate exactly one Syntax node"
/--
Auxiliary function used to execute parsers provided to `longestMatchFn`.
Push `left?` into the stack if it is not `none`, and execute `p`.
After executing `p`, remove `left`.
Remark: `p` must produce exactly one syntax node.
Remark: the `left?` is not none when we are processing trailing parsers. -/
@[inline] def runLongestMatchParser (left? : Option Syntax) (p : ParserFn) : ParserFn :=
fun c s =>
let startSize := s.stackSize;
match left? with
| none =>
let s := p c s;
if s.hasError then s
else
-- stack contains `[..., result ]`
if s.stackSize == startSize + 1 then
s
else
invalidLongestMatchParser s
| some left =>
let s := s.pushSyntax left;
let s := p c s;
if s.hasError then s
else
-- stack contains `[..., left, result ]` we must remove `left`
if s.stackSize == startSize + 2 then
-- `p` created one node, then we just remove `left` and keep it
let r := s.stxStack.back;
let s := s.shrinkStack startSize; -- remove `r` and `left`
s.pushSyntax r -- add `r` back
else
invalidLongestMatchParser s
def longestMatchStep (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn)
: ParserContext → ParserState → ParserState × Nat :=
fun c s =>
let prevErrorMsg := s.errorMsg;
let prevStopPos := s.pos;
let prevSize := s.stackSize;
let s := s.restore prevSize startPos;
let s := runLongestMatchParser left? p c s;
match prevErrorMsg, s.errorMsg with
| none, none => -- both succeeded
if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio)
else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.restore prevSize prevStopPos, prevPrio) -- keep prev
else (s, prio)
| none, some _ => -- prev succeeded, current failed
(s.restore prevSize prevStopPos, prevPrio)
| some oldError, some _ => -- both failed
if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError prevSize, prio)
else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio)
else (s.mergeErrors prevSize oldError, prio)
| some _, none => -- prev failed, current succeeded
let successNode := s.stxStack.back;
let s := s.shrinkStack startSize; -- restore stack to initial size to make sure (failure) nodes are removed from the stack
(s.pushSyntax successNode, prio) -- put successNode back on the stack
def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState :=
if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s
def longestMatchFnAux (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) : Nat → List (Parser × Nat) → ParserFn
| prevPrio, [] => fun _ s => longestMatchMkResult startSize s
| prevPrio, p::ps => fun c s =>
let (s, prevPrio) := longestMatchStep left? startSize startPos prevPrio p.2 p.1.fn c s;
longestMatchFnAux prevPrio ps c s
def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn
| [] => fun _ s => s.mkError "longestMatch: empty list"
| [p] => runLongestMatchParser left? p.1.fn
| p::ps => fun c s =>
let startSize := s.stackSize;
let startPos := s.pos;
let s := runLongestMatchParser left? p.1.fn c s;
if s.hasError then
let s := s.shrinkStack startSize;
longestMatchFnAux left? startSize startPos p.2 ps c s
else
longestMatchFnAux left? startSize startPos p.2 ps c s
def anyOfFn : List Parser → ParserFn
| [], _, s => s.mkError "anyOf: empty list"
| [p], c, s => p.fn c s
| p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s
@[inline] def checkColGeFn (errorMsg : String) : ParserFn :=
fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let pos := c.fileMap.toPosition s.pos;
if pos.column ≥ savedPos.column then s
else s.mkError errorMsg
@[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser :=
{ fn := checkColGeFn errorMsg }
@[inline] def checkColGtFn (errorMsg : String) : ParserFn :=
fun c s =>
match c.savedPos? with
| none => s
| some savedPos =>
let pos := c.fileMap.toPosition s.pos;
if pos.column > savedPos.column then s
else s.mkError errorMsg
@[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser :=
{ fn := checkColGtFn errorMsg }
@[inline] def withPosition (p : Parser) : Parser :=
{ info := p.info,
fn := fun c s =>
let pos := c.fileMap.toPosition s.pos;
p.fn { c with savedPos? := pos } s }
@[inline] def withoutPosition (p : Parser) : Parser :=
{ info := p.info,
fn := fun c s =>
let pos := c.fileMap.toPosition s.pos;
p.fn { c with savedPos? := none } s }
def eoiFn : ParserFn :=
fun c s =>
let i := s.pos;
if c.input.atEnd i then s
else s.mkError "expected end of file"
@[inline] def eoi : Parser :=
{ fn := eoiFn }
@[inline] def many1Indent (p : Parser) : Parser :=
withPosition $ many1 (checkColGe "irrelevant" >> p)
@[inline] def manyIndent (p : Parser) : Parser :=
withPosition $ many (checkColGe "irrelevant" >> p)
open Std (RBMap RBMap.empty)
/-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/
def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt
namespace TokenMap
def insert {α : Type} (map : TokenMap α) (k : Name) (v : α) : TokenMap α :=
match map.find? k with
| none => map.insert k [v]
| some vs => map.insert k (v::vs)
instance {α : Type} : Inhabited (TokenMap α) := ⟨RBMap.empty⟩
instance {α : Type} : HasEmptyc (TokenMap α) := ⟨RBMap.empty⟩
end TokenMap
structure PrattParsingTables :=
(leadingTable : TokenMap (Parser × Nat) := {})
(leadingParsers : List (Parser × Nat) := []) -- for supporting parsers we cannot obtain first token
(trailingTable : TokenMap (Parser × Nat) := {})
(trailingParsers : List (Parser × Nat) := []) -- for supporting parsers such as function application
instance PrattParsingTables.inhabited : Inhabited PrattParsingTables := ⟨{}⟩
/--
Each parser category is implemented using a Pratt's parser.
The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`.
Users and plugins may define extra categories.
The field `leadingIdentAsSymbol` specifies how the parsing table
lookup function behaves for identifiers. The function `prattParser`
uses two tables `leadingTable` and `trailingTable`. They map tokens
to parsers. If `leadingIdentAsSymbol == false` and the leading token
is an identifier, then `prattParser` just executes the parsers
associated with the auxiliary token "ident". If
`leadingIdentAsSymbol == true` and the leading token is an
identifier `<foo>`, then `prattParser` combines the parsers
associated with the token `<foo>` with the parsers associated with
the auxiliary token "ident". We use this feature and the
`nonReservedSymbol` parser to implement the `tactic` parsers. We
use this approach to avoid creating a reserved symbol for each
builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users
may still use these symbols as identifiers (e.g., naming a
function).
The method
```
categoryParser `term prec
```
executes the Pratt's parser for category `term` with precedence `prec`.
That is, only parsers with precedence at least `prec` are considered.
The method `termParser prec` is equivalent to the method above.
-/
structure ParserCategory :=
(tables : PrattParsingTables) (leadingIdentAsSymbol : Bool)
instance ParserCategory.inhabited : Inhabited ParserCategory := ⟨{ tables := {}, leadingIdentAsSymbol := false }⟩
abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory
def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (leadingIdentAsSymbol : Bool) : ParserState × List α :=
let (s, stx) := peekToken c s;
let find (n : Name) : ParserState × List α :=
match map.find? n with
| some as => (s, as)
| _ => (s, []);
match stx with
| some (Syntax.atom _ sym) => find (mkNameSimple sym)
| some (Syntax.ident _ _ val _) =>
if leadingIdentAsSymbol then
match map.find? val with
| some as => match map.find? identKind with
| some as' => (s, as ++ as')
| _ => (s, as)
| none => find identKind
else
find identKind
| some (Syntax.node k _) => find k
| _ => (s, [])
abbrev CategoryParserFn := Name → ParserFn
def mkCategoryParserFnRef : IO (IO.Ref CategoryParserFn) :=
IO.mkRef $ fun _ => whitespace
@[init mkCategoryParserFnRef]
constant categoryParserFnRef : IO.Ref CategoryParserFn := arbitrary _
def mkCategoryParserFnExtension : IO (EnvExtension CategoryParserFn) :=
registerEnvExtension $ categoryParserFnRef.get
@[init mkCategoryParserFnExtension]
def categoryParserFnExtension : EnvExtension CategoryParserFn := arbitrary _
def categoryParserFn (catName : Name) : ParserFn :=
fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s
def categoryParser (catName : Name) (prec : Nat) : Parser :=
{ fn := fun c s => categoryParserFn catName { c with prec := prec } s }
-- Define `termParser` here because we need it for antiquotations
@[inline] def termParser (prec : Nat := 0) : Parser :=
categoryParser `term prec
/- ============== -/
/- Antiquotations -/
/- ============== -/
def dollarSymbol : Parser := symbol "$"
/-- Fail if previous token is immediately followed by ':'. -/
def checkNoImmediateColon : Parser :=
{ fn := fun c s =>
let prev := s.stxStack.back;
if checkTailNoWs prev then
let input := c.input;
let i := s.pos;
if input.atEnd i then s
else
let curr := input.get i;
if curr == ':' then
s.mkUnexpectedError "unexpected ':'"
else s
else s
}
def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn :=
fun c s => match p c s with
| s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } }
| s' => s'
def setExpected (expected : List String) (p : Parser) : Parser :=
{ fn := setExpectedFn expected p.fn, info := p.info }
def pushNone : Parser :=
{ fn := fun c s => s.pushSyntax mkNullNode }
-- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term.
def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbol "(" >> toggleInsideQuot termParser >> ")")
def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr
/--
Define parser for `$e` (if anonymous == true) and `$e:name`. Both
forms can also be used with an appended `*` to turn them into an
antiquotation "splice". If `kind` is given, it will additionally be checked
when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which
produces the syntax tree for `$e`. -/
def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser :=
let kind := (kind.getD Name.anonymous) ++ `antiquot;
let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name;
-- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different
-- antiquotation kind via `noImmediateColon`
let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP;
-- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error
node kind $ try $
setExpected [] dollarSymbol >>
many (checkNoWsBefore "" >> dollarSymbol) >>
checkNoWsBefore "no space before spliced term" >> antiquotExpr >>
nameP >>
optional (checkNoWsBefore "" >> symbol "*")
def tryAnti (c : ParserContext) (s : ParserState) : Bool :=
let (s, stx?) := peekToken c s;
match stx? with
| some stx@(Syntax.atom _ sym) => sym == "$"
| _ => false
@[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn :=
fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s
/-- Optimized version of `mkAntiquot ... <|> p`. -/
@[inline] def withAntiquot (antiquotP p : Parser) : Parser :=
{ fn := withAntiquotFn antiquotP.fn p.fn,
info := orelseInfo antiquotP.info p.info }
/- ===================== -/
/- End of Antiquotations -/
/- ===================== -/
def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) : Parser :=
withAntiquot (mkAntiquot name kind false) $ node kind p
def ident : Parser :=
withAntiquot (mkAntiquot "ident" identKind) identNoAntiquot
-- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name
def rawIdent : Parser :=
withAntiquot (mkAntiquot "ident" identKind) rawIdentNoAntiquot
def numLit : Parser :=
withAntiquot (mkAntiquot "numLit" numLitKind) numLitNoAntiquot
def strLit : Parser :=
withAntiquot (mkAntiquot "strLit" strLitKind) strLitNoAntiquot
def charLit : Parser :=
withAntiquot (mkAntiquot "charLit" charLitKind) charLitNoAntiquot
def nameLit : Parser :=
withAntiquot (mkAntiquot "nameLit" nameLitKind) nameLitNoAntiquot
def categoryParserOfStackFn (offset : Nat) : ParserFn :=
fun ctx s =>
let stack := s.stxStack;
if stack.size < offset + 1 then
s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small")
else
match stack.get! (stack.size - offset - 1) with
| Syntax.ident _ _ catName _ => categoryParserFn catName ctx s
| _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier")
def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser :=
{ fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s }
private def mkResult (s : ParserState) (iniSz : Nat) : ParserState :=
if s.stackSize == iniSz + 1 then s
else s.mkNode nullKind iniSz -- throw error instead?
def leadingParserAux (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let (s, ps) := indexed tables.leadingTable c s leadingIdentAsSymbol;
let ps := tables.leadingParsers ++ ps;
if ps.isEmpty then
s.mkError (toString kind)
else
let s := longestMatchFn none ps c s;
mkResult s iniSz
@[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
withAntiquotFn antiquotParser (leadingParserAux kind tables leadingIdentAsSymbol)
def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn :=
fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s
private def mkTrailingResult (s : ParserState) (iniSz : Nat) : ParserState :=
let s := mkResult s iniSz;
-- Stack contains `[..., left, result]`
-- We must remove `left`
let result := s.stxStack.back;
let s := s.popSyntax.popSyntax;
s.pushSyntax result
partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) : ParserState → ParserState
| s =>
let identAsSymbol := false;
let (s, ps) := indexed tables.trailingTable c s identAsSymbol;
if ps.isEmpty && tables.trailingParsers.isEmpty then
s -- no available trailing parser
else
let left := s.stxStack.back;
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := trailingLoopStep tables left ps c s;
if s.hasError then
if s.pos == iniPos then s.restore iniSz iniPos else s
else
let s := mkTrailingResult s iniSz;
trailingLoop s
/--
Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power.
In our implementation, parsers have precedence instead. This method selects a parser (or more, via
`longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers
are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example:
```
syntax term:51 "≤" ident "<" term "|" term : index
```
Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set
is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`.
After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence
at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`.
Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our
implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible,
modular and easier to understand.
`antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers.
It should not be added to the regular leading parsers because it would heavily
overlap with antiquotation parsers nested inside them. -/
@[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (leadingIdentAsSymbol : Bool) (antiquotParser : ParserFn) : ParserFn :=
fun c s =>
let iniSz := s.stackSize;
let iniPos := s.pos;
let s := leadingParser kind tables leadingIdentAsSymbol antiquotParser c s;
if s.hasError then
s
else
trailingLoop tables c s
def fieldIdxFn : ParserFn :=
fun c s =>
let iniPos := s.pos;
let curr := c.input.get iniPos;
if curr.isDigit && curr != '0' then
let s := takeWhileFn (fun c => c.isDigit) c s;
mkNodeToken fieldIdxKind iniPos c s
else
s.mkErrorAt "field index" iniPos
@[inline] def fieldIdx : Parser :=
withAntiquot (mkAntiquot "fieldIdx" `fieldIdx)
{ fn := fieldIdxFn,
info := mkAtomicInfo "fieldIdx" }
@[inline] def skip : Parser :=
{ fn := fun c s => s,
info := epsilonInfo }
/-- No-op parser that advises the pretty printer to emit a non-breaking space. -/
@[inline] def ppHardSpace : Parser := skip
/-- No-op parser that advises the pretty printer to emit a space/soft line break. -/
@[inline] def ppSpace : Parser := skip
/-- No-op parser that advises the pretty printer to emit a hard line break. -/
@[inline] def ppLine : Parser := skip
/--
No-op parser combinator that advises the pretty printer to group and indent the given syntax.
By default, only syntax categories are grouped. -/
@[inline] def ppGroup : Parser → Parser := id
end Parser
namespace Syntax
section
variables {β : Type} {m : Type → Type} [Monad m]
@[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlM (flip f) b
@[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldArgsM f b)
@[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldArgsM (fun s _ => f s) ()
@[inline] def foldSepArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β :=
s.getArgs.foldlStepM (flip f) b 2
@[inline] def foldSepArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run (s.foldSepArgsM f b)
@[inline] def forSepArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit :=
s.foldSepArgsM (fun s _ => f s) ()
@[inline] def foldSepRevArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := do
let args := foldSepArgs s (fun arg (args : Array Syntax) => args.push arg) #[];
args.foldrM f b
@[inline] def foldSepRevArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := do
Id.run $ foldSepRevArgsM s f b
end
end Syntax
end Lean
section
variables {β : Type} {m : Type → Type} [Monad m]
open Lean
open Lean.Syntax
@[inline] def Array.foldSepByM (args : Array Syntax) (f : Syntax → β → m β) (b : β) : m β :=
args.foldlStepM (flip f) b 2
@[inline] def Array.foldSepBy (args : Array Syntax) (f : Syntax → β → β) (b : β) : β :=
Id.run $ args.foldSepByM f b
end
|
828a5753683d0c273bab3302c1e6249700424b6e | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Init/NotationExtra.lean | 81d75c53983730b92536fbe832af83e896c5c3e4 | [
"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 | 8,607 | 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
Extra notation that depends on Init/Meta
-/
prelude
import Init.Meta
import Init.Data.Array.Subarray
import Init.Data.ToString
namespace Lean
macro "Macro.trace[" id:ident "]" s:interpolatedStr(term) : term =>
`(Macro.trace $(quote id.getId.eraseMacroScopes) (s! $s))
-- Auxiliary parsers and functions for declaring notation with binders
syntax binderIdent := ident <|> "_"
syntax unbracketedExplicitBinders := binderIdent+ (" : " term)?
syntax bracketedExplicitBinders := "(" binderIdent+ " : " term ")"
syntax explicitBinders := bracketedExplicitBinders+ <|> unbracketedExplicitBinders
def expandExplicitBindersAux (combinator : Syntax) (idents : Array Syntax) (type? : Option Syntax) (body : Syntax) : MacroM Syntax :=
let rec loop (i : Nat) (acc : Syntax) := do
match i with
| 0 => pure acc
| i+1 =>
let ident := idents[i][0]
let acc ← match ident.isIdent, type? with
| true, none => `($combinator fun $ident => $acc)
| true, some type => `($combinator fun $ident:ident : $type => $acc)
| false, none => `($combinator fun _ => $acc)
| false, some type => `($combinator fun _ : $type => $acc)
loop i acc
loop idents.size body
def expandBrackedBindersAux (combinator : Syntax) (binders : Array Syntax) (body : Syntax) : MacroM Syntax :=
let rec loop (i : Nat) (acc : Syntax) := do
match i with
| 0 => pure acc
| i+1 =>
let idents := binders[i][1].getArgs
let type := binders[i][3]
loop i (← expandExplicitBindersAux combinator idents (some type) acc)
loop binders.size body
def expandExplicitBinders (combinatorDeclName : Name) (explicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do
let combinator := mkIdentFrom (← getRef) combinatorDeclName
let explicitBinders := explicitBinders[0]
if explicitBinders.getKind == ``Lean.unbracketedExplicitBinders then
let idents := explicitBinders[0].getArgs
let type? := if explicitBinders[1].isNone then none else some explicitBinders[1][1]
expandExplicitBindersAux combinator idents type? body
else if explicitBinders.getArgs.all (·.getKind == ``Lean.bracketedExplicitBinders) then
expandBrackedBindersAux combinator explicitBinders.getArgs body
else
Macro.throwError "unexpected explicit binder"
def expandBrackedBinders (combinatorDeclName : Name) (bracketedExplicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do
let combinator := mkIdentFrom (← getRef) combinatorDeclName
expandBrackedBindersAux combinator #[bracketedExplicitBinders] body
syntax unifConstraint := term (" =?= " <|> " ≟ ") term
syntax unifConstraintElem := colGe unifConstraint ", "?
syntax attrKind "unif_hint " (ident)? bracketedBinder* " where " withPosition(unifConstraintElem*) ("|-" <|> "⊢ ") unifConstraint : command
private def mkHintBody (cs : Array Syntax) (p : Syntax) : MacroM Syntax := do
let mut body ← `($(p[0]) = $(p[2]))
for c in cs.reverse do
body ← `($(c[0][0]) = $(c[0][2]) → $body)
return body
macro_rules
| `($kind:attrKind unif_hint $bs:explicitBinder* where $cs* |- $p) => do
let body ← mkHintBody cs p
`(@[$kind:attrKind unificationHint] def hint $bs:explicitBinder* : Sort _ := $body)
| `($kind:attrKind unif_hint $n:ident $bs* where $cs* |- $p) => do
let body ← mkHintBody cs p
`(@[$kind:attrKind unificationHint] def $n:ident $bs:explicitBinder* : Sort _ := $body)
end Lean
open Lean
macro "∃ " xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Exists xs b
macro "exists" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Exists xs b
macro "Σ" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``Sigma xs b
macro "Σ'" xs:explicitBinders ", " b:term : term => expandExplicitBinders ``PSigma xs b
macro:35 xs:bracketedExplicitBinders " × " b:term:35 : term => expandBrackedBinders ``Sigma xs b
macro:35 xs:bracketedExplicitBinders " ×' " b:term:35 : term => expandBrackedBinders ``PSigma xs b
-- enforce indentation of calc steps so we know when to stop parsing them
syntax calcStep := ppIndent(colGe term " := " withPosition(term))
syntax (name := calc) "calc" ppLine withPosition((calcStep ppLine)+) : term
macro "calc " steps:withPosition(calcStep+) : tactic => `(exact calc $(steps.getArgs)*)
@[appUnexpander Unit.unit] def unexpandUnit : Lean.PrettyPrinter.Unexpander
| `($(_)) => `(())
| _ => throw ()
@[appUnexpander List.nil] def unexpandListNil : Lean.PrettyPrinter.Unexpander
| `($(_)) => `([])
| _ => throw ()
@[appUnexpander List.cons] def unexpandListCons : Lean.PrettyPrinter.Unexpander
| `($(_) $x []) => `([$x])
| `($(_) $x [$xs,*]) => `([$x, $xs,*])
| _ => throw ()
@[appUnexpander List.toArray] def unexpandListToArray : Lean.PrettyPrinter.Unexpander
| `($(_) [$xs,*]) => `(#[$xs,*])
| _ => throw ()
@[appUnexpander Prod.mk] def unexpandProdMk : Lean.PrettyPrinter.Unexpander
| `($(_) $x ($y, $ys,*)) => `(($x, $y, $ys,*))
| `($(_) $x $y) => `(($x, $y))
| _ => throw ()
@[appUnexpander ite] def unexpandIte : Lean.PrettyPrinter.Unexpander
| `($(_) $c $t $e) => `(if $c then $t else $e)
| _ => throw ()
@[appUnexpander sorryAx] def unexpandSorryAx : Lean.PrettyPrinter.Unexpander
| `($(_) _) => `(sorry)
| `($(_) _ _) => `(sorry)
| _ => throw ()
@[appUnexpander Eq.ndrec] def unexpandEqNDRec : Lean.PrettyPrinter.Unexpander
| `($(_) $m $h) => `($h ▸ $m)
| _ => throw ()
@[appUnexpander Eq.rec] def unexpandEqRec : Lean.PrettyPrinter.Unexpander
| `($(_) $m $h) => `($h ▸ $m)
| _ => throw ()
@[appUnexpander Exists] def unexpandExists : Lean.PrettyPrinter.Unexpander
| `($(_) fun $x:ident => ∃ $xs:binderIdent*, $b) => `(∃ $x:ident $xs:binderIdent*, $b)
| `($(_) fun $x:ident => $b) => `(∃ $x:ident, $b)
| `($(_) fun ($x:ident : $t) => $b) => `(∃ ($x:ident : $t), $b)
| _ => throw ()
@[appUnexpander Sigma] def unexpandSigma : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) × $b)
| _ => throw ()
@[appUnexpander PSigma] def unexpandPSigma : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $t) => $b) => `(($x:ident : $t) ×' $b)
| _ => throw ()
@[appUnexpander Subtype] def unexpandSubtype : Lean.PrettyPrinter.Unexpander
| `($(_) fun ($x:ident : $type) => $p) => `({ $x : $type // $p })
| `($(_) fun $x:ident => $p) => `({ $x // $p })
| _ => throw ()
syntax "funext " (colGt term:max)+ : tactic
macro_rules
| `(tactic|funext $xs*) =>
if xs.size == 1 then
`(tactic| apply funext; intro $(xs[0]):term)
else
`(tactic| apply funext; intro $(xs[0]):term; funext $(xs[1:])*)
macro_rules
| `(%[ $[$x],* | $k ]) =>
if x.size < 8 then
x.foldrM (init := k) fun x k =>
`(List.cons $x $k)
else
let m := x.size / 2
let y := x[m:]
let z := x[:m]
`(let y := %[ $[$y],* | $k ]
%[ $[$z],* | y ])
/-
Expands
```
class abbrev C <params> := D_1, ..., D_n
```
into
```
class C <params> extends D_1, ..., D_n
attribute [instance] C.mk
```
-/
syntax declModifiers "class " "abbrev " declId bracketedBinder* (":" term)?
":=" withPosition(group(colGe term ","?)*) : command
macro_rules
| `($mods:declModifiers class abbrev $id $params* $[: $ty:term]? := $[ $parents:term $[,]? ]*) =>
let name := id[0]
let ctor := mkIdentFrom name <| name.getId.modifyBase (. ++ `mk)
`($mods:declModifiers class $id $params* extends $[$parents:term],* $[: $ty]?
attribute [instance] $ctor)
/-- `· tac` focuses on the main goal and tries to solve it using `tac`, or else fails. -/
syntax ("·" <|> ".") ppHardSpace many1Indent(group(tactic ";"? ppLine)) : tactic
macro_rules
| `(tactic| ·%$dot $[$tacs:tactic $[;]?]*) => `(tactic| {%$dot $[$tacs:tactic]*})
/-
Similar to `first`, but succeeds only if one the given tactics solves the current goal.
-/
syntax (name := solve) "solve " withPosition((group(colGe "|" tacticSeq))+) : tactic
macro_rules
| `(tactic| solve $[| $ts]* ) => `(tactic| focus first $[| ($ts); done]*)
|
fd9e2b20c18dc69f3d6cc714d871adacab23647a | df561f413cfe0a88b1056655515399c546ff32a5 | /7-advanced-multiplication-world/l2.lean | 30822cd3543ea5e548375bed26597e5fd79e0a18 | [] | no_license | nicholaspun/natural-number-game-solutions | 31d5158415c6f582694680044c5c6469032c2a06 | 1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0 | refs/heads/main | 1,675,123,625,012 | 1,607,633,548,000 | 1,607,633,548,000 | 318,933,860 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 202 | lean | theorem eq_zero_or_eq_zero_of_mul_eq_zero (a b : mynat) (h : a * b = 0) :
a = 0 ∨ b = 0 :=
begin
cases b with n,
right, refl,
rw mul_succ at h,
rw add_comm at h,
left,
exact add_right_eq_zero h,
end |
a67d8b395149e915af47773c51e75ba2b0e068c9 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/group_theory/transfer.lean | 431458421f488628c186829796ed486f19149c31 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 7,385 | lean | /-
Copyright (c) 2022 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import group_theory.complement
import group_theory.group_action.basic
import group_theory.index
/-!
# The Transfer Homomorphism
In this file we construct the transfer homomorphism.
## Main definitions
- `diff ϕ S T` : The difference of two left transversals `S` and `T` under the homomorphism `ϕ`.
- `transfer ϕ` : The transfer homomorphism induced by `ϕ`.
- `transfer_center_pow`: The transfer homomorphism `G →* center G`.
-/
open_locale big_operators
variables {G : Type*} [group G] {H : subgroup G} {A : Type*} [comm_group A] (ϕ : H →* A)
namespace subgroup
namespace left_transversals
open finset mul_action
open_locale pointwise
variables (R S T : left_transversals (H : set G)) [fintype (G ⧸ H)]
/-- The difference of two left transversals -/
@[to_additive "The difference of two left transversals"]
noncomputable def diff : A :=
let α := mem_left_transversals.to_equiv S.2, β := mem_left_transversals.to_equiv T.2 in
∏ q, ϕ ⟨(α q)⁻¹ * β q, quotient_group.left_rel_apply.mp $
quotient.exact' ((α.symm_apply_apply q).trans (β.symm_apply_apply q).symm)⟩
@[to_additive] lemma diff_mul_diff : diff ϕ R S * diff ϕ S T = diff ϕ R T :=
prod_mul_distrib.symm.trans (prod_congr rfl (λ q hq, (ϕ.map_mul _ _).symm.trans (congr_arg ϕ
(by simp_rw [subtype.ext_iff, coe_mul, coe_mk, mul_assoc, mul_inv_cancel_left]))))
@[to_additive] lemma diff_self : diff ϕ T T = 1 :=
mul_right_eq_self.mp (diff_mul_diff ϕ T T T)
@[to_additive] lemma diff_inv : (diff ϕ S T)⁻¹ = diff ϕ T S :=
inv_eq_of_mul_eq_one_right $ (diff_mul_diff ϕ S T S).trans $ diff_self ϕ S
@[to_additive] lemma smul_diff_smul (g : G) : diff ϕ (g • S) (g • T) = diff ϕ S T :=
prod_bij' (λ q _, g⁻¹ • q) (λ _ _, mem_univ _) (λ _ _, congr_arg ϕ (by simp_rw [coe_mk,
smul_apply_eq_smul_apply_inv_smul, smul_eq_mul, mul_inv_rev, mul_assoc, inv_mul_cancel_left]))
(λ q _, g • q) (λ _ _, mem_univ _) (λ q _, smul_inv_smul g q) (λ q _, inv_smul_smul g q)
end left_transversals
end subgroup
namespace monoid_hom
open mul_action subgroup subgroup.left_transversals
/-- Given `ϕ : H →* A` from `H : subgroup G` to a commutative group `A`,
the transfer homomorphism is `transfer ϕ : G →* A`. -/
@[to_additive "Given `ϕ : H →+ A` from `H : add_subgroup G` to an additive commutative group `A`,
the transfer homomorphism is `transfer ϕ : G →+ A`."]
noncomputable def transfer [fintype (G ⧸ H)] : G →* A :=
let T : left_transversals (H : set G) := inhabited.default in
{ to_fun := λ g, diff ϕ T (g • T),
map_one' := by rw [one_smul, diff_self],
map_mul' := λ g h, by rw [mul_smul, ←diff_mul_diff, smul_diff_smul] }
variables (T : left_transversals (H : set G))
@[to_additive] lemma transfer_def [fintype (G ⧸ H)] (g : G) : transfer ϕ g = diff ϕ T (g • T) :=
by rw [transfer, ←diff_mul_diff, ←smul_diff_smul, mul_comm, diff_mul_diff]; refl
/-- Explicit computation of the transfer homomorphism. -/
lemma transfer_eq_prod_quotient_orbit_rel_zpowers_quot [fintype (G ⧸ H)]
(g : G) [fintype (quotient (orbit_rel (zpowers g) (G ⧸ H)))] :
transfer ϕ g = ∏ (q : quotient (orbit_rel (zpowers g) (G ⧸ H))),
ϕ ⟨q.out'.out'⁻¹ * g ^ function.minimal_period ((•) g) q.out' * q.out'.out',
quotient_group.out'_conj_pow_minimal_period_mem H g q.out'⟩ :=
begin
classical,
calc transfer ϕ g = ∏ (q : G ⧸ H), _ : transfer_def ϕ (transfer_transversal H g) g
... = _ : ((quotient_equiv_sigma_zmod H g).symm.prod_comp _).symm
... = _ : finset.prod_sigma _ _ _
... = _ : fintype.prod_congr _ _ (λ q, _),
simp only [quotient_equiv_sigma_zmod_symm_apply,
transfer_transversal_apply', transfer_transversal_apply''],
rw fintype.prod_eq_single (0 : zmod (function.minimal_period ((•) g) q.out')) (λ k hk, _),
{ simp only [if_pos, zmod.cast_zero, zpow_zero, one_mul, mul_assoc] },
{ simp only [if_neg hk, inv_mul_self],
exact map_one ϕ },
end
/-- Auxillary lemma in order to state `transfer_eq_pow`. -/
lemma transfer_eq_pow_aux (g : G)
(key : ∀ (k : ℕ) (g₀ : G), g₀⁻¹ * g ^ k * g₀ ∈ H → g₀⁻¹ * g ^ k * g₀ = g ^ k) :
g ^ H.index ∈ H :=
begin
by_cases hH : H.index = 0,
{ rw [hH, pow_zero],
exact H.one_mem },
haveI := fintype_of_index_ne_zero hH,
classical,
replace key : ∀ (k : ℕ) (g₀ : G), g₀⁻¹ * g ^ k * g₀ ∈ H → g ^ k ∈ H :=
λ k g₀ hk, (_root_.congr_arg (∈ H) (key k g₀ hk)).mp hk,
replace key : ∀ q : G ⧸ H, g ^ function.minimal_period ((•) g) q ∈ H :=
λ q, key (function.minimal_period ((•) g) q) q.out'
(quotient_group.out'_conj_pow_minimal_period_mem H g q),
let f : quotient (orbit_rel (zpowers g) (G ⧸ H)) → zpowers g :=
λ q, (⟨g, mem_zpowers g⟩ : zpowers g) ^ function.minimal_period ((•) g) q.out',
have hf : ∀ q, f q ∈ H.subgroup_of (zpowers g) := λ q, key q.out',
replace key := subgroup.prod_mem (H.subgroup_of (zpowers g)) (λ q (hq : q ∈ finset.univ), hf q),
simpa only [minimal_period_eq_card, finset.prod_pow_eq_pow_sum, fintype.card_sigma,
fintype.card_congr (self_equiv_sigma_orbits (zpowers g) (G ⧸ H)), index_eq_card] using key,
end
lemma transfer_eq_pow [fintype (G ⧸ H)] (g : G)
(key : ∀ (k : ℕ) (g₀ : G), g₀⁻¹ * g ^ k * g₀ ∈ H → g₀⁻¹ * g ^ k * g₀ = g ^ k) :
transfer ϕ g = ϕ ⟨g ^ H.index, transfer_eq_pow_aux g key⟩ :=
begin
classical,
change ∀ k g₀ (hk : g₀⁻¹ * g ^ k * g₀ ∈ H), ↑(⟨g₀⁻¹ * g ^ k * g₀, hk⟩ : H) = g ^ k at key,
rw [transfer_eq_prod_quotient_orbit_rel_zpowers_quot, ←finset.prod_to_list, list.prod_map_hom],
refine congr_arg ϕ (subtype.coe_injective _),
rw [H.coe_mk, ←(zpowers g).coe_mk g (mem_zpowers g), ←(zpowers g).coe_pow, (zpowers g).coe_mk,
index_eq_card, fintype.card_congr (self_equiv_sigma_orbits (zpowers g) (G ⧸ H)),
fintype.card_sigma, ←finset.prod_pow_eq_pow_sum, ←finset.prod_to_list],
simp only [coe_list_prod, list.map_map, ←minimal_period_eq_card],
congr' 2,
funext,
apply key,
end
lemma transfer_center_eq_pow [fintype (G ⧸ center G)] (g : G) :
transfer (monoid_hom.id (center G)) g = ⟨g ^ (center G).index, (center G).pow_index_mem g⟩ :=
transfer_eq_pow (id (center G)) g (λ k _ hk, by rw [←mul_right_inj, hk, mul_inv_cancel_right])
/-- The transfer homomorphism `G →* center G`. -/
noncomputable def transfer_center_pow [fintype (G ⧸ center G)] : G →* center G :=
{ to_fun := λ g, ⟨g ^ (center G).index, (center G).pow_index_mem g⟩,
map_one' := subtype.ext (one_pow (center G).index),
map_mul' := λ a b, by simp_rw [←show ∀ g, (_ : center G) = _,
from transfer_center_eq_pow, map_mul] }
@[simp] lemma transfer_center_pow_apply [fintype (G ⧸ center G)] (g : G) :
↑(transfer_center_pow g) = g ^ (center G).index :=
rfl
/-- The transfer homomorphism `G →* center G`. -/
noncomputable def transfer_center_pow' (h : (center G).index ≠ 0) : G →* center G :=
@transfer_center_pow G _ (fintype_of_index_ne_zero h)
@[simp] lemma transfer_center_pow'_apply (h : (center G).index ≠ 0) (g : G) :
↑(transfer_center_pow' h g) = g ^ (center G).index :=
rfl
end monoid_hom
|
fabf012d4f15f39561c76319c6d87fbf6e580649 | bae21755a4a03bbe0a5c22e258db8633407711ad | /library/init/core.lean | a9dd83025c2bafd9d6a60812af9c0be535ceae89 | [
"Apache-2.0"
] | permissive | nor-code/lean | f437357a8f85db0f06f186fa50fcb1bc75f6b122 | aa306af3d7c47de3c7937c98d3aa919eb8da6f34 | refs/heads/master | 1,662,613,329,886 | 1,586,696,014,000 | 1,586,696,014,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,551 | 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
/- Reserving notation. We do this sot that the precedence of all of the operators
can be seen in one place and to prevent core notation being accidentally overloaded later. -/
/- Notation for logical operations and relations -/
reserve prefix `¬`:40
reserve prefix `~`:40 -- not used
reserve infixr ` ∧ `:35
reserve infixr ` /\ `:35
reserve infixr ` \/ `:30
reserve infixr ` ∨ `:30
reserve infix ` <-> `:20
reserve infix ` ↔ `:20
reserve infix ` = `:50 -- eq
reserve infix ` == `:50 -- heq
reserve infix ` ≠ `:50
reserve infix ` ≈ `:50 -- has_equiv.equiv
reserve infix ` ~ `:50 -- used as local notation for relations
reserve infix ` ≡ `:50 -- not used
reserve infixl ` ⬝ `:75 -- not used
reserve infixr ` ▸ `:75 -- eq.subst
reserve infixr ` ▹ `:75 -- not used
/- types and type constructors -/
reserve infixr ` ⊕ `:30 -- sum (defined in init/data/sum/basic.lean)
reserve infixr ` × `:35
/- 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 -- function composition
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 ` ⊂ `:50
reserve infix ` ⊃ `:50
reserve infix ` \ `:70 -- symmetric difference
/- other symbols -/
reserve infix ` ∣ `:50 -- has_dvd.dvd. Note this is different to `|`.
reserve infixl ` ++ `:65 -- has_append.append
reserve infixr ` :: `:67 -- list.cons
reserve infixl `; `:1 -- has_andthen.andthen
universes u v w
/--
The kernel definitional equality test (t =?= s) has special support for id_delta applications.
It implements the following rules
1) (id_delta t) =?= t
2) t =?= (id_delta t)
3) (id_delta t) =?= s IF (unfold_of t) =?= s
4) t =?= id_delta s IF t =?= (unfold_of s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use id_delta applications to address performance problems when type checking
lemmas generated by the equation compiler.
-/
@[inline] def id_delta {α : Sort u} (a : α) : α :=
a
/-- Gadget for optional parameter support. -/
@[reducible] def opt_param (α : Sort u) (default : α) : Sort u :=
α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def out_param (α : Sort u) : Sort u := α
/-
id_rhs is an auxiliary declaration used in the equation compiler to address performance
issues when proving equational lemmas. The equation compiler uses it as a marker.
-/
abbreviation id_rhs (α : Sort u) (a : α) : α := a
inductive punit : Sort u
| star : punit
/-- An abbreviation for `punit.{0}`, its most common instantiation.
This type should be preferred over `punit` where possible to avoid
unnecessary universe parameters. -/
abbreviation unit : Type := punit
@[pattern] abbreviation unit.star : unit := punit.star
/--
Gadget for defining thunks, thunk parameters have special treatment.
Example: given
def f (s : string) (t : thunk nat) : nat
an application
f "hello" 10
is converted into
f "hello" (λ _, 10)
-/
@[reducible] def thunk (α : Type u) : Type u :=
unit → α
inductive true : Prop
| intro : true
inductive false : Prop
inductive empty : Type
def not (a : Prop) := a → false
prefix `¬` := not
inductive eq {α : Sort u} (a : α) : α → Prop
| refl [] : eq a
/-
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
Also the reduction rule:
quot.lift f _ (quot.mk a) ~~> f a
-/
init_quotient
/-- Heterogeneous equality.
It's purpose is to write down equalities between terms whose types are not definitionally equal.
For example, given `x : vector α n` and `y : vector α (0+n)`, `x = y` doesn't typecheck but `x == y` does.
-/
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 brec_on recursor. -/
structure pprod (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
structure and (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
def and.elim_left {a b : Prop} (h : and a b) : a := h.1
def and.elim_right {a b : Prop} (h : and a b) : b := h.2
/- eq basic support -/
infix = := eq
attribute [refl] eq.refl
@[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a
@[elab_as_eliminator, subst]
lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b :=
eq.rec h₂ h₁
notation h1 ▸ h2 := eq.subst h1 h2
@[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
@[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a :=
h ▸ rfl
infix == := heq
@[pattern] def heq.rfl {α : Sort u} {a : α} : a == a := heq.refl a
lemma eq_of_heq {α : Sort u} {a a' : α} (h : a == a') : a = a' :=
have ∀ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a') (h₂ : α = α'), (eq.rec_on h₂ a : α') = a', from
λ (α' : Sort u) (a' : α') (h₁ : @heq α a α' a'), heq.rec_on h₁ (λ h₂ : α = α, rfl),
show (eq.rec_on (eq.refl α) a : α) = a', from
this α a' h (eq.refl α)
/- The following four lemmas could not be automatically generated when the
structures were declared, so we prove them manually here. -/
lemma prod.mk.inj {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → and (x₁ = x₂) (y₁ = y₂) :=
λ h, prod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma prod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
lemma pprod.mk.inj {α : Sort u} {β : Sort v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: pprod.mk x₁ y₁ = pprod.mk x₂ y₂ → and (x₁ = x₂) (y₁ = y₂) :=
λ h, pprod.no_confusion h (λ h₁ h₂, ⟨h₁, h₂⟩)
lemma pprod.mk.inj_arrow {α : Type u} {β : Type v} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β}
: (x₁, y₁) = (x₂, y₂) → Π ⦃P : Sort w⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
λ h₁ _ h₂, prod.no_confusion h₁ h₂
inductive sum (α : Type u) (β : Type v)
| inl (val : α) : sum
| inr (val : β) : sum
inductive psum (α : Sort u) (β : Sort v)
| inl (val : α) : psum
| inr (val : β) : psum
inductive or (a b : Prop) : Prop
| inl (h : a) : or
| inr (h : b) : or
def or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b :=
or.inl ha
def or.intro_right (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
| ff : bool
| tt : bool
/- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/
structure subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
attribute [pp_using_anonymous_constructor] sigma psigma subtype pprod and
class inductive decidable (p : Prop)
| is_false (h : ¬p) : decidable
| is_true (h : p) : decidable
@[reducible]
def decidable_pred {α : Sort u} (r : α → Prop) :=
Π (a : α), decidable (r a)
@[reducible]
def decidable_rel {α : Sort u} (r : α → α → Prop) :=
Π (a b : α), decidable (r a b)
@[reducible]
def decidable_eq (α : Sort u) :=
decidable_rel (@eq α)
inductive option (α : Type u)
| none : option
| some (val : α) : option
export option (none some)
export bool (ff tt)
inductive list (T : Type u)
| nil : list
| cons (hd : T) (tl : list) : list
notation h :: t := list.cons h t
notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l
inductive nat
| zero : nat
| succ (n : nat) : nat
structure unification_constraint :=
{α : Type u} (lhs : α) (rhs : α)
infix ` ≟ `:50 := unification_constraint.mk
infix ` =?= `:50 := unification_constraint.mk
structure unification_hint :=
(pattern : unification_constraint)
(constraints : list unification_constraint)
/- Declare builtin and reserved notation -/
class has_zero (α : Type u) := (zero : α)
class has_one (α : Type u) := (one : α)
class has_add (α : Type u) := (add : α → α → α)
class has_mul (α : Type u) := (mul : α → α → α)
class has_inv (α : Type u) := (inv : α → α)
class has_neg (α : Type u) := (neg : α → α)
class has_sub (α : Type u) := (sub : α → α → α)
class has_div (α : Type u) := (div : α → α → α)
class has_dvd (α : Type u) := (dvd : α → α → Prop)
class has_mod (α : Type u) := (mod : α → α → α)
class has_le (α : Type u) := (le : α → α → Prop)
class has_lt (α : Type u) := (lt : α → α → Prop)
class has_append (α : Type u) := (append : α → α → α)
class has_andthen (α : Type u) (β : Type v) (σ : out_param $ Type w) := (andthen : α → β → σ)
class has_union (α : Type u) := (union : α → α → α)
class has_inter (α : Type u) := (inter : α → α → α)
class has_sdiff (α : Type u) := (sdiff : α → α → α)
class has_equiv (α : Sort u) := (equiv : α → α → Prop)
class has_subset (α : Type u) := (subset : α → α → Prop)
class has_ssubset (α : Type u) := (ssubset : α → α → Prop)
/- Type classes has_emptyc and has_insert are
used to implement polymorphic notation for collections.
Example: {a, b, c}. -/
class has_emptyc (α : Type u) := (emptyc : α)
class has_insert (α : out_param $ Type u) (γ : Type v) := (insert : α → γ → γ)
/- Type class used to implement the notation { a ∈ c | p a } -/
class has_sep (α : out_param $ Type u) (γ : Type v) :=
(sep : (α → Prop) → γ → γ)
/- Type class for set-like membership -/
class has_mem (α : out_param $ Type u) (γ : Type v) := (mem : α → γ → Prop)
class has_pow (α : Type u) (β : Type v) :=
(pow : α → β → α)
export has_andthen (andthen)
export has_pow (pow)
infix ∈ := has_mem.mem
notation a ∉ s := ¬ has_mem.mem a s
infix + := has_add.add
infix * := has_mul.mul
infix - := has_sub.sub
infix / := has_div.div
infix ∣ := has_dvd.dvd
infix % := has_mod.mod
prefix - := has_neg.neg
infix <= := has_le.le
infix ≤ := has_le.le
infix < := has_lt.lt
infix ++ := has_append.append
infix ; := andthen
notation `∅` := has_emptyc.emptyc
infix ∪ := has_union.union
infix ∩ := has_inter.inter
infix ⊆ := has_subset.subset
infix ⊂ := has_ssubset.ssubset
infix \ := has_sdiff.sdiff
infix ≈ := has_equiv.equiv
infixr ^ := has_pow.pow
export has_append (append)
@[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := has_le.le b a
@[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := has_lt.lt b a
infix >= := ge
infix ≥ := ge
infix > := gt
@[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := has_subset.subset b a
@[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := has_ssubset.ssubset b a
infix ⊇ := superset
infix ⊃ := ssuperset
def bit0 {α : Type u} [s : has_add α] (a : α) : α := a + a
def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := (bit0 a) + 1
attribute [pattern] has_zero.zero has_one.one bit0 bit1 has_add.add has_neg.neg
export has_insert (insert)
/-- The singleton collection -/
def singleton {α : Type u} {γ : Type v} [has_emptyc γ] [has_insert α γ] (a : α) : γ :=
insert a ∅
/- nat basic instances -/
namespace nat
protected def add : nat → nat → nat
| a zero := a
| a (succ b) := succ (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 [pattern] nat.add nat.add._main
end nat
instance : has_zero nat := ⟨nat.zero⟩
instance : has_one nat := ⟨nat.succ (nat.zero)⟩
instance : has_add nat := ⟨nat.add⟩
def std.priority.default : nat := 1000
def std.priority.max : nat := 0xFFFFFFFF
namespace nat
protected def prio := std.priority.default + 100
end nat
/-
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.max_plus : nat := std.prec.max + 10
reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv
postfix ⁻¹ := has_inv.inv
notation α × β := prod α β
-- notation for n-ary tuples
/- sizeof -/
class has_sizeof (α : Sort u) :=
(sizeof : α → nat)
def sizeof {α : Sort u} [s : has_sizeof α] : α → 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 `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → nat
| a := 0
instance default_has_sizeof (α : Sort u) : has_sizeof α :=
⟨default.sizeof α⟩
protected def nat.sizeof : nat → nat
| n := n
instance : has_sizeof nat :=
⟨nat.sizeof⟩
protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) :=
⟨prod.sizeof⟩
protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat
| (sum.inl a) := 1 + sizeof a
| (sum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) :=
⟨sum.sizeof⟩
protected def psum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (psum α β) → nat
| (psum.inl a) := 1 + sizeof a
| (psum.inr b) := 1 + sizeof b
instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (psum α β) :=
⟨psum.sizeof⟩
protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) :=
⟨sigma.sizeof⟩
protected def psigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : psigma β → nat
| ⟨a, b⟩ := 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (psigma β) :=
⟨psigma.sizeof⟩
protected def punit.sizeof : punit → nat
| u := 1
instance : has_sizeof punit := ⟨punit.sizeof⟩
protected def bool.sizeof : bool → nat
| b := 1
instance : has_sizeof bool := ⟨bool.sizeof⟩
protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat
| none := 1
| (some a) := 1 + sizeof a
instance (α : Type u) [has_sizeof α] : has_sizeof (option α) :=
⟨option.sizeof⟩
protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat
| list.nil := 1
| (list.cons a l) := 1 + sizeof a + list.sizeof l
instance (α : Type u) [has_sizeof α] : has_sizeof (list α) :=
⟨list.sizeof⟩
protected def subtype.sizeof {α : Type u} [has_sizeof α] {p : α → Prop} : subtype p → nat
| ⟨a, _⟩ := sizeof a
instance {α : Type u} [has_sizeof α] (p : α → Prop) : has_sizeof (subtype p) :=
⟨subtype.sizeof⟩
lemma nat_add_zero (n : nat) : n + 0 = n := rfl
/- Combinator calculus -/
namespace combinator
universes u₁ u₂ u₃
def I {α : Type u₁} (a : α) := a
def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a
def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z)
end combinator
/-- Auxiliary datatype for #[ ... ] notation.
#[1, 2, 3, 4] is notation for
bin_tree.node
(bin_tree.node (bin_tree.leaf 1) (bin_tree.leaf 2))
(bin_tree.node (bin_tree.leaf 3) (bin_tree.leaf 4))
We use this notation to input long sequences without exhausting the system stack space.
Later, we define a coercion from `bin_tree` into `list`.
-/
inductive bin_tree (α : Type u)
| empty : bin_tree
| leaf (val : α) : bin_tree
| node (left right : bin_tree) : bin_tree
attribute [elab_simple] bin_tree.node bin_tree.leaf
/- Basic unification hints -/
@[unify] def add_succ_defeq_succ_add_hint (x y z : nat) : unification_hint :=
{ pattern := x + nat.succ y ≟ nat.succ z,
constraints := [z ≟ x + y] }
/-- Like `by apply_instance`, but not dependent on the tactic framework. -/
@[reducible] def infer_instance {α : Type u} [i : α] : α := i
|
066e173ca10bf7532398577df960078b0ec74810 | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/universal/complete/functor_category.lean | bd684acd4486550aac06c344dfce81f30a0733b2 | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 1,906 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.functor_categories.whiskering
import category_theory.universal.comparisons
open category_theory
open category_theory.prod
namespace category_theory.limits
universes u v
variables {J : Type v} [small_category J] {C : Type v} [small_category C] {D : Type u} [𝒟 : category.{u v} D]
include 𝒟
def switched (F : J ⥤ (C ⥤ D)) : C ⥤ (J ⥤ D) :=
{ obj := λ c, { obj := λ j, (F j) c, map' := λ j j' f, (F.map f) c },
map' := λ c c' f, { app := λ j, (F j).map f }}.
-- section
-- local attribute [back] category.id
-- def switched_twice (F : J ⥤ (C ⥤ D)) : switched (switched F) ≅ F := by obviously
-- end
def introduce_switch (F : J ⥤ (C ⥤ D)) {j j' : J} (f : j ⟶ j') (X : C) : (F.map f) X = ((switched F) X).map f := sorry
def limit_cone_in_functor_category [has_limits.{u v} D] (F : J ⥤ (C ⥤ D)) : cone F :=
{ X := ((switched F) ⋙ lim),
π := λ j, { app := λ X : C, (limit.cone (switched F X)).π j },
w := λ j j' f, begin ext1, dsimp at *, rw introduce_switch, obviously, end }.
instance [has_limits.{u v} D] : has_limits.{(max u v) v} (C ⥤ D) :=
{ limit := λ J 𝒥 F, begin resetI, exact limit_cone_in_functor_category F end,
is_limit := λ J 𝒥 F, begin resetI, exact
{ lift := λ s, { app := λ X, (limit.cone_morphism (switched F X) { X := s.X X, π := λ j, (s.π j) X }).hom,
naturality' := begin tidy, dsimp [limit_cone_in_functor_category],
-- FIXME why does this rw fail? I wanted to apply this to both sides, then use naturality.
-- rw limit.pullback_lift (switched F Y),
sorry
end, },
fac' := sorry,
uniq' := sorry } end
}
end category_theory.limits |
94ee743ee03920ef39010d416d1ab59a65261ccf | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/set_theory/ordinal_notation.lean | 768fc2d372d69ce7bbc16a350b9e3e3cc7144954 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 35,964 | 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 set_theory.ordinal_arithmetic
/-!
# Ordinal notation
Constructive ordinal arithmetic for ordinals below `ε₀`.
We define a type `onote`, with constructors `0 : onote` and `onote.oadd e n a` representing
`ω ^ e * n + a`.
We say that `o` is in Cantor normal form - `onote.NF o` - if either `o = 0` or
`o = ω ^ e * n + a` with `a < ω ^ e` and `a` in Cantor normal form.
The type `nonote` is the type of ordinals below `ε₀` in Cantor normal form.
Various operations (addition, subtraction, multiplication, power function)
are defined on `onote` and `nonote`.
-/
open ordinal
open_locale ordinal -- get notation for `ω`
/-- Recursive definition of an ordinal notation. `zero` denotes the
ordinal 0, and `oadd e n a` is intended to refer to `ω^e * n + a`.
For this to be valid Cantor normal form, we must have the exponents
decrease to the right, but we can't state this condition until we've
defined `repr`, so it is a separate definition `NF`. -/
@[derive decidable_eq]
inductive onote : Type
| zero : onote
| oadd : onote → ℕ+ → onote → onote
namespace onote
/-- Notation for 0 -/
instance : has_zero onote := ⟨zero⟩
@[simp] theorem zero_def : zero = 0 := rfl
instance : inhabited onote := ⟨0⟩
/-- Notation for 1 -/
instance : has_one onote := ⟨oadd 0 1 0⟩
/-- Notation for ω -/
def omega : onote := oadd 1 1 0
/-- The ordinal denoted by a notation -/
@[simp] noncomputable def repr : onote → ordinal.{0}
| 0 := 0
| (oadd e n a) := ω ^ repr e * n + repr a
/-- Auxiliary definition to print an ordinal notation -/
def to_string_aux1 (e : onote) (n : ℕ) (s : string) : string :=
if e = 0 then _root_.to_string n else
(if e = 1 then "ω" else "ω^(" ++ s ++ ")") ++
if n = 1 then "" else "*" ++ _root_.to_string n
/-- Print an ordinal notation -/
def to_string : onote → string
| zero := "0"
| (oadd e n 0) := to_string_aux1 e n (to_string e)
| (oadd e n a) := to_string_aux1 e n (to_string e) ++ " + " ++ to_string a
/-- Print an ordinal notation -/
def repr' : onote → string
| zero := "0"
| (oadd e n a) := "(oadd " ++ repr' e ++ " " ++ _root_.to_string (n:ℕ) ++ " " ++ repr' a ++ ")"
instance : has_to_string onote := ⟨to_string⟩
instance : has_repr onote := ⟨repr'⟩
instance : preorder onote :=
{ le := λ x y, repr x ≤ repr y,
lt := λ x y, repr x < repr y,
le_refl := λ a, @le_refl ordinal _ _,
le_trans := λ a b c, @le_trans ordinal _ _ _ _,
lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ }
theorem lt_def {x y : onote} : x < y ↔ repr x < repr y := iff.rfl
theorem le_def {x y : onote} : x ≤ y ↔ repr x ≤ repr y := iff.rfl
/-- Convert a `nat` into an ordinal -/
@[simp] def of_nat : ℕ → onote
| 0 := 0
| (nat.succ n) := oadd 0 n.succ_pnat 0
@[simp] theorem of_nat_one : of_nat 1 = 1 := rfl
@[simp] theorem repr_of_nat (n : ℕ) : repr (of_nat n) = n :=
by cases n; simp
@[simp] theorem repr_one : repr 1 = 1 :=
by simpa using repr_of_nat 1
theorem omega_le_oadd (e n a) : ω ^ repr e ≤ repr (oadd e n a) :=
begin
unfold repr,
refine le_trans _ (le_add_right _ _),
simpa using (mul_le_mul_iff_left $ power_pos (repr e) omega_pos).2 (nat_cast_le.2 n.2)
end
theorem oadd_pos (e n a) : 0 < oadd e n a :=
@lt_of_lt_of_le _ _ _ _ _ (power_pos _ omega_pos)
(omega_le_oadd _ _ _)
/-- Compare ordinal notations -/
def cmp : onote → onote → ordering
| 0 0 := ordering.eq
| _ 0 := ordering.gt
| 0 _ := ordering.lt
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) :=
(cmp e₁ e₂).or_else $ (_root_.cmp (n₁:ℕ) n₂).or_else (cmp a₁ a₂)
theorem eq_of_cmp_eq : ∀ {o₁ o₂}, cmp o₁ o₂ = ordering.eq → o₁ = o₂
| 0 0 h := rfl
| (oadd e n a) 0 h := by injection h
| 0 (oadd e n a) h := by injection h
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h := begin
revert h, simp [cmp],
cases h₁ : cmp e₁ e₂; intro h; try {cases h},
have := eq_of_cmp_eq h₁, subst e₂,
revert h, cases h₂ : _root_.cmp (n₁:ℕ) n₂; intro h; try {cases h},
have := eq_of_cmp_eq h, subst a₂,
rw [_root_.cmp, cmp_using_eq_eq] at h₂,
have := subtype.eq (eq_of_incomp h₂), subst n₂, simp
end
theorem zero_lt_one : (0 : onote) < 1 :=
by rw [lt_def, repr, repr_one]; exact zero_lt_one
/-- `NF_below o b` says that `o` is a normal form ordinal notation
satisfying `repr o < ω ^ b`. -/
inductive NF_below : onote → ordinal.{0} → Prop
| zero {b} : NF_below 0 b
| oadd' {e n a eb b} : NF_below e eb →
NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b
/-- A normal form ordinal notation has the form
ω ^ a₁ * n₁ + ω ^ a₂ * n₂ + ... ω ^ aₖ * nₖ
where `a₁ > a₂ > ... > aₖ` and all the `aᵢ` are
also in normal form.
We will essentially only be interested in normal form
ordinal notations, but to avoid complicating the algorithms
we define everything over general ordinal notations and
only prove correctness with normal form as an invariant. -/
class NF (o : onote) : Prop := (out : Exists (NF_below o))
attribute [pp_nodot] NF
instance NF.zero : NF 0 := ⟨⟨0, NF_below.zero⟩⟩
theorem NF_below.oadd {e n a b} : NF e →
NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b
| ⟨⟨eb, h⟩⟩ := NF_below.oadd' h
theorem NF_below.fst {e n a b} (h : NF_below (oadd e n a) b) : NF e :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact ⟨⟨_, h₁⟩⟩
theorem NF.fst {e n a} : NF (oadd e n a) → NF e
| ⟨⟨b, h⟩⟩ := h.fst
theorem NF_below.snd {e n a b} (h : NF_below (oadd e n a) b) : NF_below a (repr e) :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₂
theorem NF.snd' {e n a} : NF (oadd e n a) → NF_below a (repr e)
| ⟨⟨b, h⟩⟩ := h.snd
theorem NF.snd {e n a} (h : NF (oadd e n a)) : NF a :=
⟨⟨_, h.snd'⟩⟩
theorem NF.oadd {e a} (h₁ : NF e) (n)
(h₂ : NF_below a (repr e)) : NF (oadd e n a) :=
⟨⟨_, NF_below.oadd h₁ h₂ (ordinal.lt_succ_self _)⟩⟩
instance NF.oadd_zero (e n) [h : NF e] : NF (oadd e n 0) :=
h.oadd _ NF_below.zero
theorem NF_below.lt {e n a b} (h : NF_below (oadd e n a) b) : repr e < b :=
by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₃
theorem NF_below_zero : ∀ {o}, NF_below o 0 ↔ o = 0
| 0 := ⟨λ _, rfl, λ _, NF_below.zero⟩
| (oadd e n a) := ⟨λ h, (not_le_of_lt h.lt).elim (ordinal.zero_le _),
λ e, e.symm ▸ NF_below.zero⟩
theorem NF.zero_of_zero {e n a} (h : NF (oadd e n a)) (e0 : e = 0) : a = 0 :=
by simpa [e0, NF_below_zero] using h.snd'
theorem NF_below.repr_lt {o b} (h : NF_below o b) : repr o < ω ^ b :=
begin
induction h with _ e n a eb b h₁ h₂ h₃ _ IH,
{ exact power_pos _ omega_pos },
{ rw repr,
refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 IH) _,
rw ← mul_succ,
refine le_trans (mul_le_mul_left _ $ ordinal.succ_le.2 $ nat_lt_omega _) _,
rw ← power_succ,
exact power_le_power_right omega_pos (ordinal.succ_le.2 h₃) }
end
theorem NF_below.mono {o b₁ b₂} (bb : b₁ ≤ b₂) (h : NF_below o b₁) : NF_below o b₂ :=
begin
induction h with _ e n a eb b h₁ h₂ h₃ _ IH; constructor,
exacts [h₁, h₂, lt_of_lt_of_le h₃ bb]
end
theorem NF.below_of_lt {e n a b} (H : repr e < b) : NF (oadd e n a) → NF_below (oadd e n a) b
| ⟨⟨b', h⟩⟩ := by cases h with _ _ _ _ eb _ h₁ h₂ h₃;
exact NF_below.oadd' h₁ h₂ H
theorem NF.below_of_lt' : ∀ {o b}, repr o < ω ^ b → NF o → NF_below o b
| 0 b H _ := NF_below.zero
| (oadd e n a) b H h := h.below_of_lt $ (power_lt_power_iff_right one_lt_omega).1 $
(lt_of_le_of_lt (omega_le_oadd _ _ _) H)
theorem NF_below_of_nat : ∀ n, NF_below (of_nat n) 1
| 0 := NF_below.zero
| (nat.succ n) := NF_below.oadd NF.zero NF_below.zero ordinal.zero_lt_one
instance NF_of_nat (n) : NF (of_nat n) := ⟨⟨_, NF_below_of_nat n⟩⟩
instance NF_one : NF 1 := by rw ← of_nat_one; apply_instance
theorem oadd_lt_oadd_1 {e₁ n₁ o₁ e₂ n₂ o₂} (h₁ : NF (oadd e₁ n₁ o₁)) (h : e₁ < e₂) :
oadd e₁ n₁ o₁ < oadd e₂ n₂ o₂ :=
@lt_of_lt_of_le _ _ _ _ _ ((h₁.below_of_lt h).repr_lt) (omega_le_oadd _ _ _)
theorem oadd_lt_oadd_2 {e o₁ o₂ : onote} {n₁ n₂ : ℕ+}
(h₁ : NF (oadd e n₁ o₁)) (h : (n₁:ℕ) < n₂) : oadd e n₁ o₁ < oadd e n₂ o₂ :=
begin
simp [lt_def],
refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 h₁.snd'.repr_lt)
(le_trans _ (le_add_right _ _)),
rwa [← mul_succ, mul_le_mul_iff_left (power_pos _ omega_pos),
ordinal.succ_le, nat_cast_lt]
end
theorem oadd_lt_oadd_3 {e n a₁ a₂} (h : a₁ < a₂) :
oadd e n a₁ < oadd e n a₂ :=
begin
rw lt_def, unfold repr,
exact (ordinal.add_lt_add_iff_left _).2 h
end
theorem cmp_compares : ∀ (a b : onote) [NF a] [NF b], (cmp a b).compares a b
| 0 0 h₁ h₂ := rfl
| (oadd e n a) 0 h₁ h₂ := oadd_pos _ _ _
| 0 (oadd e n a) h₁ h₂ := oadd_pos _ _ _
| o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h₁ h₂ := begin
rw cmp,
have IHe := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂,
case ordering.lt { exact oadd_lt_oadd_1 h₁ IHe },
case ordering.gt { exact oadd_lt_oadd_1 h₂ IHe },
change e₁ = e₂ at IHe, subst IHe,
unfold _root_.cmp, cases nh : cmp_using (<) (n₁:ℕ) n₂,
case ordering.lt {
rw cmp_using_eq_lt at nh, exact oadd_lt_oadd_2 h₁ nh },
case ordering.gt {
rw cmp_using_eq_gt at nh, exact oadd_lt_oadd_2 h₂ nh },
rw cmp_using_eq_eq at nh,
have := subtype.eq (eq_of_incomp nh), subst n₂,
have IHa := @cmp_compares _ _ h₁.snd h₂.snd,
cases cmp a₁ a₂,
case ordering.lt { exact oadd_lt_oadd_3 IHa },
case ordering.gt { exact oadd_lt_oadd_3 IHa },
change a₁ = a₂ at IHa, subst IHa, exact rfl
end
theorem repr_inj {a b} [NF a] [NF b] : repr a = repr b ↔ a = b :=
⟨match cmp a b, cmp_compares a b with
| ordering.lt, (h : repr a < repr b), e := (ne_of_lt h e).elim
| ordering.gt, (h : repr a > repr b), e := (ne_of_gt h e).elim
| ordering.eq, h, e := h
end, congr_arg _⟩
theorem NF.of_dvd_omega_power {b e n a} (h : NF (oadd e n a)) (d : ω ^ b ∣ repr (oadd e n a)) :
b ≤ repr e ∧ ω ^ b ∣ repr a :=
begin
have := mt repr_inj.1 (λ h, by injection h : oadd e n a ≠ 0),
have L := le_of_not_lt (λ l, not_le_of_lt (h.below_of_lt l).repr_lt (le_of_dvd this d)),
simp at d,
exact ⟨L, (dvd_add_iff $ (power_dvd_power _ L).mul_right _).1 d⟩
end
theorem NF.of_dvd_omega {e n a} (h : NF (oadd e n a)) :
ω ∣ repr (oadd e n a) → repr e ≠ 0 ∧ ω ∣ repr a :=
by rw [← power_one ω, ← one_le_iff_ne_zero]; exact h.of_dvd_omega_power
/-- `top_below b o` asserts that the largest exponent in `o`, if
it exists, is less than `b`. This is an auxiliary definition
for decidability of `NF`. -/
def top_below (b) : onote → Prop
| 0 := true
| (oadd e n a) := cmp e b = ordering.lt
instance decidable_top_below : decidable_rel top_below :=
by intros b o; cases o; delta top_below; apply_instance
theorem NF_below_iff_top_below {b} [NF b] : ∀ {o},
NF_below o (repr b) ↔ NF o ∧ top_below b o
| 0 := ⟨λ h, ⟨⟨⟨_, h⟩⟩, trivial⟩, λ _, NF_below.zero⟩
| (oadd e n a) :=
⟨λ h, ⟨⟨⟨_, h⟩⟩, (@cmp_compares _ b h.fst _).eq_lt.2 h.lt⟩,
λ ⟨h₁, h₂⟩, h₁.below_of_lt $ (@cmp_compares _ b h₁.fst _).eq_lt.1 h₂⟩
instance decidable_NF : decidable_pred NF
| 0 := is_true NF.zero
| (oadd e n a) := begin
have := decidable_NF e,
have := decidable_NF a, resetI,
apply decidable_of_iff (NF e ∧ NF a ∧ top_below e a),
abstract {
rw ← and_congr_right (λ h, @NF_below_iff_top_below _ h _),
exact ⟨λ ⟨h₁, h₂⟩, NF.oadd h₁ n h₂, λ h, ⟨h.fst, h.snd'⟩⟩ },
end
/-- Addition of ordinal notations (correct only for normal input) -/
def add : onote → onote → onote
| 0 o := o
| (oadd e n a) o := match add a o with
| 0 := oadd e n 0
| o'@(oadd e' n' a') := match cmp e e' with
| ordering.lt := o'
| ordering.eq := oadd e (n + n') a'
| ordering.gt := oadd e n o'
end
end
instance : has_add onote := ⟨add⟩
@[simp] theorem zero_add (o : onote) : 0 + o = o := rfl
theorem oadd_add (e n a o) : oadd e n a + o = add._match_1 e n (a + o) := rfl
/-- Subtraction of ordinal notations (correct only for normal input) -/
def sub : onote → onote → onote
| 0 o := 0
| o 0 := o
| o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := match cmp e₁ e₂ with
| ordering.lt := 0
| ordering.gt := o₁
| ordering.eq := match (n₁:ℕ) - n₂ with
| 0 := if n₁ = n₂ then sub a₁ a₂ else 0
| (nat.succ k) := oadd e₁ k.succ_pnat a₁
end
end
instance : has_sub onote := ⟨sub⟩
theorem add_NF_below {b} : ∀ {o₁ o₂}, NF_below o₁ b → NF_below o₂ b → NF_below (o₁ + o₂) b
| 0 o h₁ h₂ := h₂
| (oadd e n a) o h₁ h₂ := begin
have h' := add_NF_below (h₁.snd.mono $ le_of_lt h₁.lt) h₂,
simp [oadd_add], cases a + o with e' n' a',
{ exact NF_below.oadd h₁.fst NF_below.zero h₁.lt },
simp [add], have := @cmp_compares _ _ h₁.fst h'.fst,
cases cmp e e'; simp [add],
{ exact h' },
{ simp at this, subst e',
exact NF_below.oadd h'.fst h'.snd h'.lt },
{ exact NF_below.oadd h₁.fst (NF.below_of_lt this ⟨⟨_, h'⟩⟩) h₁.lt }
end
instance add_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ + o₂)
| ⟨⟨b₁, h₁⟩⟩ ⟨⟨b₂, h₂⟩⟩ := ⟨(b₁.le_total b₂).elim
(λ h, ⟨b₂, add_NF_below (h₁.mono h) h₂⟩)
(λ h, ⟨b₁, add_NF_below h₁ (h₂.mono h)⟩)⟩
@[simp] theorem repr_add : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ + o₂) = repr o₁ + repr o₂
| 0 o h₁ h₂ := by simp
| (oadd e n a) o h₁ h₂ := begin
haveI := h₁.snd, have h' := repr_add a o,
conv at h' in (_+o) {simp [(+)]},
have nf := onote.add_NF a o,
conv at nf in (_+o) {simp [(+)]},
conv in (_+o) {simp [(+), add]},
cases add a o with e' n' a'; simp [add, h'.symm, add_assoc],
have := h₁.fst, haveI := nf.fst, have ee := cmp_compares e e',
cases cmp e e'; simp [add],
{ rw [← add_assoc, @add_absorp _ (repr e') (ω ^ repr e' * (n':ℕ))],
{ have := (h₁.below_of_lt ee).repr_lt, unfold repr at this,
exact lt_of_le_of_lt (le_add_right _ _) this },
{ simpa using (mul_le_mul_iff_left $
power_pos (repr e') omega_pos).2 (nat_cast_le.2 n'.pos) } },
{ change e = e' at ee, substI e',
rw [← add_assoc, ← ordinal.mul_add, ← nat.cast_add] }
end
theorem sub_NF_below : ∀ {o₁ o₂ b}, NF_below o₁ b → NF o₂ → NF_below (o₁ - o₂) b
| 0 o b h₁ h₂ := by cases o; exact NF_below.zero
| (oadd e n a) 0 b h₁ h₂ := h₁
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) b h₁ h₂ := begin
have h' := sub_NF_below h₁.snd h₂.snd,
simp [has_sub.sub, sub] at h' ⊢,
have := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂; simp [sub],
{ apply NF_below.zero },
{ simp at this, subst e₂,
cases mn : (n₁:ℕ) - n₂; simp [sub],
{ by_cases en : n₁ = n₂; simp [en],
{ exact h'.mono (le_of_lt h₁.lt) },
{ exact NF_below.zero } },
{ exact NF_below.oadd h₁.fst h₁.snd h₁.lt } },
{ exact h₁ }
end
instance sub_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ - o₂)
| ⟨⟨b₁, h₁⟩⟩ h₂ := ⟨⟨b₁, sub_NF_below h₁ h₂⟩⟩
@[simp] theorem repr_sub : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ - o₂) = repr o₁ - repr o₂
| 0 o h₁ h₂ := by cases o; exact (ordinal.zero_sub _).symm
| (oadd e n a) 0 h₁ h₂ := (ordinal.sub_zero _).symm
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin
haveI := h₁.snd, haveI := h₂.snd, have h' := repr_sub a₁ a₂,
conv at h' in (a₁-a₂) {simp [has_sub.sub]},
have nf := onote.sub_NF a₁ a₂,
conv at nf in (a₁-a₂) {simp [has_sub.sub]},
conv in (_-oadd _ _ _) {simp [has_sub.sub, sub]},
have ee := @cmp_compares _ _ h₁.fst h₂.fst,
cases cmp e₁ e₂,
{ rw [ordinal.sub_eq_zero_iff_le.2], {refl},
exact le_of_lt (oadd_lt_oadd_1 h₁ ee) },
{ change e₁ = e₂ at ee, substI e₂, unfold sub._match_1,
cases mn : (n₁:ℕ) - n₂; dsimp only [sub._match_2],
{ by_cases en : n₁ = n₂,
{ simp [en], rwa [add_sub_add_cancel] },
{ simp [en, -repr],
exact (ordinal.sub_eq_zero_iff_le.2 $ le_of_lt $ oadd_lt_oadd_2 h₁ $
lt_of_le_of_ne (nat.sub_eq_zero_iff_le.1 mn) (mt pnat.eq en)).symm } },
{ simp [nat.succ_pnat, -nat.cast_succ],
rw [(nat.sub_eq_iff_eq_add $ le_of_lt $ nat.lt_of_sub_eq_succ mn).1 mn,
add_comm, nat.cast_add, ordinal.mul_add, add_assoc, add_sub_add_cancel],
refine (ordinal.sub_eq_of_add_eq $ add_absorp h₂.snd'.repr_lt $
le_trans _ (le_add_right _ _)).symm,
simpa using mul_le_mul_left _ (nat_cast_le.2 $ nat.succ_pos _) } },
{ exact (ordinal.sub_eq_of_add_eq $ add_absorp (h₂.below_of_lt ee).repr_lt $
omega_le_oadd _ _ _).symm }
end
/-- Multiplication of ordinal notations (correct only for normal input) -/
def mul : onote → onote → onote
| 0 _ := 0
| _ 0 := 0
| o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) :=
if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else
oadd (e₁ + e₂) n₂ (mul o₁ a₂)
instance : has_mul onote := ⟨mul⟩
@[simp] theorem zero_mul (o : onote) : 0 * o = 0 := by cases o; refl
@[simp] theorem mul_zero (o : onote) : o * 0 = 0 := by cases o; refl
theorem oadd_mul (e₁ n₁ a₁ e₂ n₂ a₂) : oadd e₁ n₁ a₁ * oadd e₂ n₂ a₂ =
if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else
oadd (e₁ + e₂) n₂ (oadd e₁ n₁ a₁ * a₂) := rfl
theorem oadd_mul_NF_below {e₁ n₁ a₁ b₁} (h₁ : NF_below (oadd e₁ n₁ a₁) b₁) :
∀ {o₂ b₂}, NF_below o₂ b₂ → NF_below (oadd e₁ n₁ a₁ * o₂) (repr e₁ + b₂)
| 0 b₂ h₂ := NF_below.zero
| (oadd e₂ n₂ a₂) b₂ h₂ := begin
have IH := oadd_mul_NF_below h₂.snd,
by_cases e0 : e₂ = 0; simp [e0, oadd_mul],
{ apply NF_below.oadd h₁.fst h₁.snd,
simpa using (add_lt_add_iff_left (repr e₁)).2
(lt_of_le_of_lt (ordinal.zero_le _) h₂.lt) },
{ haveI := h₁.fst, haveI := h₂.fst,
apply NF_below.oadd, apply_instance,
{ rwa repr_add },
{ rw [repr_add, ordinal.add_lt_add_iff_left], exact h₂.lt } }
end
instance mul_NF : ∀ o₁ o₂ [NF o₁] [NF o₂], NF (o₁ * o₂)
| 0 o h₁ h₂ := by cases o; exact NF.zero
| (oadd e n a) o ⟨⟨b₁, hb₁⟩⟩ ⟨⟨b₂, hb₂⟩⟩ :=
⟨⟨_, oadd_mul_NF_below hb₁ hb₂⟩⟩
@[simp] theorem repr_mul : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ * o₂) = repr o₁ * repr o₂
| 0 o h₁ h₂ := by cases o; exact (ordinal.zero_mul _).symm
| (oadd e₁ n₁ a₁) 0 h₁ h₂ := (ordinal.mul_zero _).symm
| (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin
have IH : repr (mul _ _) = _ := @repr_mul _ _ h₁ h₂.snd,
conv {to_lhs, simp [(*)]},
have ao : repr a₁ + ω ^ repr e₁ * (n₁:ℕ) = ω ^ repr e₁ * (n₁:ℕ),
{ apply add_absorp h₁.snd'.repr_lt,
simpa using (mul_le_mul_iff_left $ power_pos _ omega_pos).2
(nat_cast_le.2 n₁.2) },
by_cases e0 : e₂ = 0; simp [e0, mul],
{ cases nat.exists_eq_succ_of_ne_zero n₂.ne_zero with x xe,
simp [h₂.zero_of_zero e0, xe, -nat.cast_succ],
rw [← nat_cast_succ x, add_mul_succ _ ao, mul_assoc] },
{ haveI := h₁.fst, haveI := h₂.fst,
simp [IH, repr_add, power_add, ordinal.mul_add],
rw ← mul_assoc, congr' 2,
have := mt repr_inj.1 e0,
rw [add_mul_limit ao (power_is_limit_left omega_is_limit this),
mul_assoc, mul_omega_dvd (nat_cast_pos.2 n₁.pos) (nat_lt_omega _)],
simpa using power_dvd_power ω (one_le_iff_ne_zero.2 this) },
end
/-- Calculate division and remainder of `o` mod ω.
`split' o = (a, n)` means `o = ω * a + n`. -/
def split' : onote → onote × ℕ
| 0 := (0, 0)
| (oadd e n a) := if e = 0 then (0, n) else
let (a', m) := split' a in (oadd (e - 1) n a', m)
/-- Calculate division and remainder of `o` mod ω.
`split o = (a, n)` means `o = a + n`, where `ω ∣ a`. -/
def split : onote → onote × ℕ
| 0 := (0, 0)
| (oadd e n a) := if e = 0 then (0, n) else
let (a', m) := split a in (oadd e n a', m)
/-- `scale x o` is the ordinal notation for `ω ^ x * o`. -/
def scale (x : onote) : onote → onote
| 0 := 0
| (oadd e n a) := oadd (x + e) n (scale a)
/-- `mul_nat o n` is the ordinal notation for `o * n`. -/
def mul_nat : onote → ℕ → onote
| 0 m := 0
| _ 0 := 0
| (oadd e n a) (m+1) := oadd e (n * m.succ_pnat) a
/-- Auxiliary definition to compute the ordinal notation for the ordinal
exponentiation in `power` -/
def power_aux (e a0 a : onote) : ℕ → ℕ → onote
| _ 0 := 0
| 0 (m+1) := oadd e m.succ_pnat 0
| (k+1) m := scale (e + mul_nat a0 k) a + power_aux k m
/-- `power o₁ o₂` calculates the ordinal notation for
the ordinal exponential `o₁ ^ o₂`. -/
def power (o₁ o₂ : onote) : onote :=
match split o₁ with
| (0, 0) := if o₂ = 0 then 1 else 0
| (0, 1) := 1
| (0, m+1) := let (b', k) := split' o₂ in
oadd b' (@has_pow.pow ℕ+ _ _ m.succ_pnat k) 0
| (a@(oadd a0 _ _), m) := match split o₂ with
| (b, 0) := oadd (a0 * b) 1 0
| (b, k+1) := let eb := a0*b in
scale (eb + mul_nat a0 k) a + power_aux eb a0 (mul_nat a m) k m
end
end
instance : has_pow onote onote := ⟨power⟩
theorem power_def (o₁ o₂ : onote) : o₁ ^ o₂ = power._match_1 o₂ (split o₁) := rfl
theorem split_eq_scale_split' : ∀ {o o' m} [NF o], split' o = (o', m) → split o = (scale 1 o', m)
| 0 o' m h p := by injection p; substs o' m; refl
| (oadd e n a) o' m h p := begin
by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢,
{ rcases p with ⟨rfl, rfl⟩, exact ⟨rfl, rfl⟩ },
{ revert p, cases h' : split' a with a' m',
haveI := h.fst, haveI := h.snd,
simp [split_eq_scale_split' h', split, split'],
have : 1 + (e - 1) = e,
{ refine repr_inj.1 _, simp,
have := mt repr_inj.1 e0,
exact ordinal.add_sub_cancel_of_le (one_le_iff_ne_zero.2 this) },
intros, substs o' m, simp [scale, this] }
end
theorem NF_repr_split' : ∀ {o o' m} [NF o], split' o = (o', m) → NF o' ∧ repr o = ω * repr o' + m
| 0 o' m h p := by injection p; substs o' m; simp [NF.zero]
| (oadd e n a) o' m h p := begin
by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢,
{ rcases p with ⟨rfl, rfl⟩,
simp [h.zero_of_zero e0, NF.zero] },
{ revert p, cases h' : split' a with a' m',
haveI := h.fst, haveI := h.snd,
cases NF_repr_split' h' with IH₁ IH₂,
simp [IH₂, split'],
intros, substs o' m,
have : ω ^ repr e = ω ^ (1 : ordinal.{0}) * ω ^ (repr e - 1),
{ have := mt repr_inj.1 e0,
rw [← power_add, ordinal.add_sub_cancel_of_le (one_le_iff_ne_zero.2 this)] },
refine ⟨NF.oadd (by apply_instance) _ _, _⟩,
{ simp at this ⊢,
refine IH₁.below_of_lt' ((mul_lt_mul_iff_left omega_pos).1 $
lt_of_le_of_lt (le_add_right _ m') _),
rw [← this, ← IH₂], exact h.snd'.repr_lt },
{ rw this, simp [ordinal.mul_add, mul_assoc, add_assoc] } }
end
theorem scale_eq_mul (x) [NF x] : ∀ o [NF o], scale x o = oadd x 1 0 * o
| 0 h := rfl
| (oadd e n a) h := begin
simp [(*)], simp [mul, scale],
haveI := h.snd,
by_cases e0 : e = 0,
{ rw scale_eq_mul, simp [e0, h.zero_of_zero, show x + 0 = x, from repr_inj.1 (by simp)] },
{ simp [e0, scale_eq_mul, (*)] }
end
instance NF_scale (x) [NF x] (o) [NF o] : NF (scale x o) :=
by rw scale_eq_mul; apply_instance
@[simp] theorem repr_scale (x) [NF x] (o) [NF o] : repr (scale x o) = ω ^ repr x * repr o :=
by simp [scale_eq_mul]
theorem NF_repr_split {o o' m} [NF o] (h : split o = (o', m)) : NF o' ∧ repr o = repr o' + m :=
begin
cases e : split' o with a n,
cases NF_repr_split' e with s₁ s₂, resetI,
rw split_eq_scale_split' e at h,
injection h, substs o' n,
simp [repr_scale, s₂.symm],
apply_instance
end
theorem split_dvd {o o' m} [NF o] (h : split o = (o', m)) : ω ∣ repr o' :=
begin
cases e : split' o with a n,
rw split_eq_scale_split' e at h,
injection h, subst o',
cases NF_repr_split' e, resetI, simp
end
theorem split_add_lt {o e n a m} [NF o] (h : split o = (oadd e n a, m)) : repr a + m < ω ^ repr e :=
begin
cases NF_repr_split h with h₁ h₂,
cases h₁.of_dvd_omega (split_dvd h) with e0 d,
have := h₁.fst, have := h₁.snd,
refine add_lt_omega_power h₁.snd'.repr_lt (lt_of_lt_of_le (nat_lt_omega _) _),
simpa using power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0),
end
@[simp] theorem mul_nat_eq_mul (n o) : mul_nat o n = o * of_nat n :=
by cases o; cases n; refl
instance NF_mul_nat (o) [NF o] (n) : NF (mul_nat o n) :=
by simp; apply_instance
instance NF_power_aux (e a0 a) [NF e] [NF a0] [NF a] : ∀ k m, NF (power_aux e a0 a k m)
| k 0 := by cases k; exact NF.zero
| 0 (m+1) := NF.oadd_zero _ _
| (k+1) (m+1) := by haveI := NF_power_aux k;
simp [power_aux, nat.succ_ne_zero]; apply_instance
instance NF_power (o₁ o₂) [NF o₁] [NF o₂] : NF (o₁ ^ o₂) :=
begin
cases e₁ : split o₁ with a m,
have na := (NF_repr_split e₁).1,
cases e₂ : split' o₂ with b' k,
haveI := (NF_repr_split' e₂).1,
casesI a with a0 n a',
{ cases m with m,
{ by_cases o₂ = 0; simp [pow, power, *]; apply_instance },
{ by_cases m = 0,
{ simp only [pow, power, *, zero_def], apply_instance },
{ simp [pow, power, *, - npow_eq_pow], apply_instance } } },
{ simp [pow, power, e₁, e₂, split_eq_scale_split' e₂],
have := na.fst,
cases k with k; simp [succ_eq_add_one, power]; resetI; apply_instance }
end
theorem scale_power_aux (e a0 a : onote) [NF e] [NF a0] [NF a] :
∀ k m, repr (power_aux e a0 a k m) = ω ^ repr e * repr (power_aux 0 a0 a k m)
| 0 m := by cases m; simp [power_aux]
| (k+1) m := by by_cases m = 0; simp [h, power_aux,
ordinal.mul_add, power_add, mul_assoc, scale_power_aux]
theorem repr_power_aux₁ {e a} [Ne : NF e] [Na : NF a] {a' : ordinal}
(e0 : repr e ≠ 0) (h : a' < ω ^ repr e) (aa : repr a = a') (n : ℕ+) :
(ω ^ repr e * (n:ℕ) + a') ^ ω = (ω ^ repr e) ^ ω :=
begin
subst aa,
have No := Ne.oadd n (Na.below_of_lt' h),
have := omega_le_oadd e n a, unfold repr at this,
refine le_antisymm _ (power_le_power_left _ this),
apply (power_le_of_limit
(ne_of_gt $ lt_of_lt_of_le (power_pos _ omega_pos) this) omega_is_limit).2,
intros b l,
have := (No.below_of_lt (lt_succ_self _)).repr_lt, unfold repr at this,
apply le_trans (power_le_power_left b $ le_of_lt this),
rw [← power_mul, ← power_mul],
apply power_le_power_right omega_pos,
cases le_or_lt ω (repr e) with h h,
{ apply le_trans (mul_le_mul_left _ $ le_of_lt $ lt_succ_self _),
rw [succ, add_mul_succ _ (one_add_of_omega_le h), ← succ,
succ_le, mul_lt_mul_iff_left (ordinal.pos_iff_ne_zero.2 e0)],
exact omega_is_limit.2 _ l },
{ refine le_trans (le_of_lt $ mul_lt_omega (omega_is_limit.2 _ h) l) _,
simpa using mul_le_mul_right ω (one_le_iff_ne_zero.2 e0) }
end
section
local infixr ^ := @pow ordinal.{0} ordinal ordinal.has_pow
theorem repr_power_aux₂ {a0 a'} [N0 : NF a0] [Na' : NF a'] (m : ℕ)
(d : ω ∣ repr a')
(e0 : repr a0 ≠ 0) (h : repr a' + m < ω ^ repr a0) (n : ℕ+) (k : ℕ) :
let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m) in
(k ≠ 0 → R < (ω ^ repr a0) ^ succ k) ∧
(ω ^ repr a0) ^ k * (ω ^ repr a0 * (n:ℕ) + repr a') + R =
(ω ^ repr a0 * (n:ℕ) + repr a' + m) ^ succ k :=
begin
intro,
haveI No : NF (oadd a0 n a') :=
N0.oadd n (Na'.below_of_lt' $ lt_of_le_of_lt (le_add_right _ _) h),
induction k with k IH, {cases m; simp [power_aux, R]},
rename R R', let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m),
let ω0 := ω ^ repr a0, let α' := ω0 * n + repr a',
change (k ≠ 0 → R < ω0 ^ succ k) ∧ ω0 ^ k * α' + R = (α' + m) ^ succ k at IH,
have RR : R' = ω0 ^ k * (α' * m) + R,
{ by_cases m = 0; simp [h, R', power_aux, R, power_mul],
{ cases k; simp [power_aux] }, { refl } },
have α0 : 0 < α', {simpa [α', lt_def, repr] using oadd_pos a0 n a'},
have ω00 : 0 < ω0 ^ k := power_pos _ (power_pos _ omega_pos),
have Rl : R < ω ^ (repr a0 * succ ↑k),
{ by_cases k0 : k = 0,
{ simp [k0],
refine lt_of_lt_of_le _ (power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0)),
cases m with m; simp [k0, R, power_aux, omega_pos],
rw [← nat.cast_succ], apply nat_lt_omega },
{ rw power_mul, exact IH.1 k0 } },
refine ⟨λ_, _, _⟩,
{ rw [RR, ← power_mul _ _ (succ k.succ)],
have e0 := ordinal.pos_iff_ne_zero.2 e0,
have rr0 := lt_of_lt_of_le e0 (le_add_left _ _),
apply add_lt_omega_power,
{ simp [power_mul, ω0, power_add, mul_assoc],
rw [mul_lt_mul_iff_left ω00, ← ordinal.power_add],
have := (No.below_of_lt _).repr_lt, unfold repr at this,
refine mul_lt_omega_power rr0 this (nat_lt_omega _),
simpa using (add_lt_add_iff_left (repr a0)).2 e0 },
{ refine lt_of_lt_of_le Rl (power_le_power_right omega_pos $
mul_le_mul_left _ $ succ_le_succ.2 $ nat_cast_le.2 $ le_of_lt k.lt_succ_self) } },
refine calc
ω0 ^ k.succ * α' + R'
= ω0 ^ succ k * α' + (ω0 ^ k * α' * m + R) : by rw [nat_cast_succ, RR, ← mul_assoc]
... = (ω0 ^ k * α' + R) * α' + (ω0 ^ k * α' + R) * m : _
... = (α' + m) ^ succ k.succ : by rw [← ordinal.mul_add, ← nat_cast_succ, power_succ, IH.2],
congr' 1,
{ have αd : ω ∣ α' := dvd_add (dvd_mul_of_dvd_left
(by simpa using power_dvd_power ω (one_le_iff_ne_zero.2 e0)) _) d,
rw [ordinal.mul_add (ω0 ^ k), add_assoc, ← mul_assoc, ← power_succ,
add_mul_limit _ (is_limit_iff_omega_dvd.2 ⟨ne_of_gt α0, αd⟩), mul_assoc,
@mul_omega_dvd n (nat_cast_pos.2 n.pos) (nat_lt_omega _) _ αd],
apply @add_absorp _ (repr a0 * succ k),
{ refine add_lt_omega_power _ Rl,
rw [power_mul, power_succ, mul_lt_mul_iff_left ω00],
exact No.snd'.repr_lt },
{ have := mul_le_mul_left (ω0 ^ succ k) (one_le_iff_pos.2 $ nat_cast_pos.2 n.pos),
rw power_mul, simpa [-power_succ] } },
{ cases m,
{ have : R = 0, {cases k; simp [R, power_aux]}, simp [this] },
{ rw [← nat_cast_succ, add_mul_succ],
apply add_absorp Rl,
rw [power_mul, power_succ],
apply ordinal.mul_le_mul_left,
simpa [α', repr] using omega_le_oadd a0 n a' } }
end
end
theorem repr_power (o₁ o₂) [NF o₁] [NF o₂] : repr (o₁ ^ o₂) = repr o₁ ^ repr o₂ :=
begin
cases e₁ : split o₁ with a m,
cases NF_repr_split e₁ with N₁ r₁,
cases a with a0 n a',
{ cases m with m,
{ by_cases o₂ = 0; simp [power_def, power, e₁, h, r₁],
have := mt repr_inj.1 h, rw zero_power this },
{ cases e₂ : split' o₂ with b' k,
cases NF_repr_split' e₂ with _ r₂,
by_cases m = 0; simp [power_def, power, e₁, h, r₁, e₂, r₂, -nat.cast_succ],
rw [power_add, power_mul, power_omega _ (nat_lt_omega _)],
simpa using nat_cast_lt.2 (nat.succ_lt_succ $ pos_iff_ne_zero.2 h) } },
{ haveI := N₁.fst, haveI := N₁.snd,
cases N₁.of_dvd_omega (split_dvd e₁) with a00 ad,
have al := split_add_lt e₁,
have aa : repr (a' + of_nat m) = repr a' + m, {simp},
cases e₂ : split' o₂ with b' k,
cases NF_repr_split' e₂ with _ r₂,
simp [power_def, power, e₁, r₁, split_eq_scale_split' e₂],
cases k with k; resetI,
{ simp [power, r₂, power_mul, repr_power_aux₁ a00 al aa, add_assoc] },
{ simp [succ_eq_add_one, power, r₂, power_add, power_mul, mul_assoc, add_assoc],
rw [repr_power_aux₁ a00 al aa, scale_power_aux], simp [power_mul],
rw [← ordinal.mul_add, ← add_assoc (ω ^ repr a0 * (n:ℕ))], congr' 1,
rw [← power_succ],
exact (repr_power_aux₂ _ ad a00 al _ _).2 } }
end
end onote
/-- The type of normal ordinal notations. (It would have been
nicer to define this right in the inductive type, but `NF o`
requires `repr` which requires `onote`, so all these things
would have to be defined at once, which messes up the VM
representation.) -/
def nonote := {o : onote // o.NF}
instance : decidable_eq nonote := by unfold nonote; apply_instance
namespace nonote
open onote
instance NF (o : nonote) : NF o.1 := o.2
/-- Construct a `nonote` from an ordinal notation
(and infer normality) -/
def mk (o : onote) [h : NF o] : nonote := ⟨o, h⟩
/-- The ordinal represented by an ordinal notation.
(This function is noncomputable because ordinal
arithmetic is noncomputable. In computational applications
`nonote` can be used exclusively without reference
to `ordinal`, but this function allows for correctness
results to be stated.) -/
noncomputable def repr (o : nonote) : ordinal := o.1.repr
instance : has_to_string nonote := ⟨λ x, x.1.to_string⟩
instance : has_repr nonote := ⟨λ x, x.1.repr'⟩
instance : preorder nonote :=
{ le := λ x y, repr x ≤ repr y,
lt := λ x y, repr x < repr y,
le_refl := λ a, @le_refl ordinal _ _,
le_trans := λ a b c, @le_trans ordinal _ _ _ _,
lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ }
instance : has_zero nonote := ⟨⟨0, NF.zero⟩⟩
instance : inhabited nonote := ⟨0⟩
/-- Convert a natural number to an ordinal notation -/
def of_nat (n : ℕ) : nonote := ⟨of_nat n, ⟨⟨_, NF_below_of_nat _⟩⟩⟩
/-- Compare ordinal notations -/
def cmp (a b : nonote) : ordering :=
cmp a.1 b.1
theorem cmp_compares : ∀ a b : nonote, (cmp a b).compares a b
| ⟨a, ha⟩ ⟨b, hb⟩ := begin
resetI,
dsimp [cmp], have := onote.cmp_compares a b,
cases onote.cmp a b; try {exact this},
exact subtype.mk_eq_mk.2 this
end
instance : linear_order nonote := linear_order_of_compares cmp cmp_compares
/-- Asserts that `repr a < ω ^ repr b`. Used in `nonote.rec_on` -/
def below (a b : nonote) : Prop := NF_below a.1 (repr b)
/-- The `oadd` pseudo-constructor for `nonote` -/
def oadd (e : nonote) (n : ℕ+) (a : nonote) (h : below a e) : nonote := ⟨_, NF.oadd e.2 n h⟩
/-- This is a recursor-like theorem for `nonote` suggesting an
inductive definition, which can't actually be defined this
way due to conflicting dependencies. -/
@[elab_as_eliminator] def rec_on {C : nonote → Sort*} (o : nonote)
(H0 : C 0)
(H1 : ∀ e n a h, C e → C a → C (oadd e n a h)) : C o :=
begin
cases o with o h, induction o with e n a IHe IHa,
{ exact H0 },
{ exact H1 ⟨e, h.fst⟩ n ⟨a, h.snd⟩ h.snd' (IHe _) (IHa _) }
end
/-- Addition of ordinal notations -/
instance : has_add nonote := ⟨λ x y, mk (x.1 + y.1)⟩
theorem repr_add (a b) : repr (a + b) = repr a + repr b :=
onote.repr_add a.1 b.1
/-- Subtraction of ordinal notations -/
instance : has_sub nonote := ⟨λ x y, mk (x.1 - y.1)⟩
theorem repr_sub (a b) : repr (a - b) = repr a - repr b :=
onote.repr_sub a.1 b.1
/-- Multiplication of ordinal notations -/
instance : has_mul nonote := ⟨λ x y, mk (x.1 * y.1)⟩
theorem repr_mul (a b) : repr (a * b) = repr a * repr b :=
onote.repr_mul a.1 b.1
/-- Exponentiation of ordinal notations -/
def power (x y : nonote) := mk (x.1.power y.1)
theorem repr_power (a b) : repr (power a b) = (repr a).power (repr b) :=
onote.repr_power a.1 b.1
end nonote
|
42370370f9121bef4b46d75617583283117ad20e | 8cb37a089cdb4af3af9d8bf1002b417e407a8e9e | /library/init/data/array/basic.lean | d1080b25d301d5094d498b7b0a4c049be0deadca | [
"Apache-2.0"
] | permissive | kbuzzard/lean | ae3c3db4bb462d750dbf7419b28bafb3ec983ef7 | ed1788fd674bb8991acffc8fca585ec746711928 | refs/heads/master | 1,620,983,366,617 | 1,618,937,600,000 | 1,618,937,600,000 | 359,886,396 | 1 | 0 | Apache-2.0 | 1,618,936,987,000 | 1,618,936,987,000 | null | UTF-8 | Lean | false | false | 10,357 | 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, Mario Carneiro
-/
prelude
import init.data.nat init.data.bool init.ite_simp
universes u v w
/-- In the VM, d_array is implemented as a persistent array. -/
structure d_array (n : nat) (α : fin n → Type u) :=
(data : Π i : fin n, α i)
namespace d_array
variables {n : nat} {α : fin n → Type u} {α' : fin n → Type v} {β : Type w}
/-- The empty array. -/
def nil {α} : d_array 0 α :=
{data := λ ⟨x, h⟩, absurd h (nat.not_lt_zero x)}
/-- `read a i` reads the `i`th member of `a`. Has builtin VM implementation. -/
def read (a : d_array n α) (i : fin n) : α i :=
a.data i
/-- `write a i v` sets the `i`th member of `a` to be `v`. Has builtin VM implementation. -/
def write (a : d_array n α) (i : fin n) (v : α i) : d_array n α :=
{data := λ j, if h : i = j then eq.rec_on h v else a.read j}
def iterate_aux (a : d_array n α) (f : Π i : fin n, α i → β → β) : Π (i : nat), i ≤ n → β → β
| 0 h b := b
| (j+1) h b :=
let i : fin n := ⟨j, h⟩ in
f i (a.read i) (iterate_aux j (le_of_lt h) b)
/-- Fold over the elements of the given array in ascending order. Has builtin VM implementation. -/
def iterate (a : d_array n α) (b : β) (f : Π i : fin n, α i → β → β) : β :=
iterate_aux a f n (le_refl _) b
/-- Map the array. Has builtin VM implementation. -/
def foreach (a : d_array n α) (f : Π i : fin n, α i → α' i) : d_array n α' :=
⟨λ i, f _ (a.read i)⟩
def map (f : Π i : fin n, α i → α' i) (a : d_array n α) : d_array n α' :=
foreach a f
def map₂ {α'' : fin n → Type w} (f : Π i : fin n, α i → α' i → α'' i) (a : d_array n α) (b : d_array n α') :
d_array n α'' :=
foreach b (λ i, f i (a.read i))
def foldl (a : d_array n α) (b : β) (f : Π i : fin n, α i → β → β) : β :=
iterate a b f
def rev_iterate_aux (a : d_array n α) (f : Π i : fin n, α i → β → β) : Π (i : nat), i ≤ n → β → β
| 0 h b := b
| (j+1) h b :=
let i : fin n := ⟨j, h⟩ in
rev_iterate_aux j (le_of_lt h) (f i (a.read i) b)
def rev_iterate (a : d_array n α) (b : β) (f : Π i : fin n, α i → β → β) : β :=
rev_iterate_aux a f n (le_refl _) b
@[simp] lemma read_write (a : d_array n α) (i : fin n) (v : α i) : read (write a i v) i = v :=
by simp [read, write]
@[simp] lemma read_write_of_ne (a : d_array n α) {i j : fin n} (v : α i) : i ≠ j → read (write a i v) j = read a j :=
by intro h; simp [read, write, h]
protected lemma ext {a b : d_array n α} (h : ∀ i, read a i = read b i) : a = b :=
by cases a; cases b; congr; exact funext h
protected lemma ext' {a b : d_array n α} (h : ∀ (i : nat) (h : i < n), read a ⟨i, h⟩ = read b ⟨i, h⟩) : a = b :=
begin cases a, cases b, congr, funext i, cases i, apply h end
protected def beq_aux [∀ i, decidable_eq (α i)] (a b : d_array n α) : Π (i : nat), i ≤ n → bool
| 0 h := tt
| (i+1) h := if a.read ⟨i, h⟩ = b.read ⟨i, h⟩ then beq_aux i (le_of_lt h) else ff
/-- Boolean element-wise equality check. -/
protected def beq [∀ i, decidable_eq (α i)] (a b : d_array n α) : bool :=
d_array.beq_aux a b n (le_refl _)
lemma of_beq_aux_eq_tt [∀ i, decidable_eq (α i)] {a b : d_array n α} : ∀ (i : nat) (h : i ≤ n), d_array.beq_aux a b i h = tt →
∀ (j : nat) (h' : j < i), a.read ⟨j, lt_of_lt_of_le h' h⟩ = b.read ⟨j, lt_of_lt_of_le h' h⟩
| 0 h₁ h₂ j h₃ := absurd h₃ (nat.not_lt_zero _)
| (i+1) h₁ h₂ j h₃ :=
begin
have h₂' : read a ⟨i, h₁⟩ = read b ⟨i, h₁⟩ ∧ d_array.beq_aux a b i _ = tt, {simp [d_array.beq_aux] at h₂, assumption},
have h₁' : i ≤ n, from le_of_lt h₁,
have ih : ∀ (j : nat) (h' : j < i), a.read ⟨j, lt_of_lt_of_le h' h₁'⟩ = b.read ⟨j, lt_of_lt_of_le h' h₁'⟩, from of_beq_aux_eq_tt i h₁' h₂'.2,
by_cases hji : j = i,
{ subst hji, exact h₂'.1 },
{ have j_lt_i : j < i, from lt_of_le_of_ne (nat.le_of_lt_succ h₃) hji,
exact ih j j_lt_i }
end
lemma of_beq_eq_tt [∀ i, decidable_eq (α i)] {a b : d_array n α} : d_array.beq a b = tt → a = b :=
begin
unfold d_array.beq,
intro h,
have : ∀ (j : nat) (h : j < n), a.read ⟨j, h⟩ = b.read ⟨j, h⟩, from
of_beq_aux_eq_tt n (le_refl _) h,
apply d_array.ext' this
end
lemma of_beq_aux_eq_ff [∀ i, decidable_eq (α i)] {a b : d_array n α} : ∀ (i : nat) (h : i ≤ n), d_array.beq_aux a b i h = ff →
∃ (j : nat) (h' : j < i), a.read ⟨j, lt_of_lt_of_le h' h⟩ ≠ b.read ⟨j, lt_of_lt_of_le h' h⟩
| 0 h₁ h₂ := begin simp [d_array.beq_aux] at h₂, contradiction end
| (i+1) h₁ h₂ :=
begin
have h₂' : read a ⟨i, h₁⟩ ≠ read b ⟨i, h₁⟩ ∨ d_array.beq_aux a b i _ = ff, {simp [d_array.beq_aux] at h₂, assumption},
cases h₂' with h h,
{ existsi i, existsi (nat.lt_succ_self _), exact h },
{ have h₁' : i ≤ n, from le_of_lt h₁,
have ih : ∃ (j : nat) (h' : j < i), a.read ⟨j, lt_of_lt_of_le h' h₁'⟩ ≠ b.read ⟨j, lt_of_lt_of_le h' h₁'⟩, from of_beq_aux_eq_ff i h₁' h,
cases ih with j ih,
cases ih with h' ih,
existsi j, existsi (nat.lt_succ_of_lt h'),
exact ih }
end
lemma of_beq_eq_ff [∀ i, decidable_eq (α i)] {a b : d_array n α} : d_array.beq a b = ff → a ≠ b :=
begin
unfold d_array.beq,
intros h hne,
have : ∃ (j : nat) (h' : j < n), a.read ⟨j, h'⟩ ≠ b.read ⟨j, h'⟩, from of_beq_aux_eq_ff n (le_refl _) h,
cases this with j this,
cases this with h' this,
subst hne,
contradiction
end
instance [∀ i, decidable_eq (α i)] : decidable_eq (d_array n α) :=
λ a b, if h : d_array.beq a b = tt then is_true (of_beq_eq_tt h) else is_false (of_beq_eq_ff (eq_ff_of_not_eq_tt h))
end d_array
/-- A non-dependent array (see `d_array`). Implemented in the VM as a persistent array. -/
def array (n : nat) (α : Type u) : Type u :=
d_array n (λ _, α)
/-- `mk_array n v` creates a new array of length `n` where each element is `v`. Has builtin VM implementation. -/
def mk_array {α} (n) (v : α) : array n α :=
{data := λ _, v}
namespace array
variables {n : nat} {α : Type u} {β : Type v}
def nil {α} : array 0 α :=
d_array.nil
@[inline]
def read (a : array n α) (i : fin n) : α :=
d_array.read a i
@[inline]
def write (a : array n α) (i : fin n) (v : α) : array n α :=
d_array.write a i v
/-- Fold array starting from 0, folder function includes an index argument. -/
@[inline]
def iterate (a : array n α) (b : β) (f : fin n → α → β → β) : β :=
d_array.iterate a b f
/-- Map each element of the given array with an index argument. -/
@[inline]
def foreach (a : array n α) (f : fin n → α → β) : array n β :=
d_array.foreach a f
@[inline]
def map₂ (f : α → α → α) (a b : array n α) : array n α :=
foreach b (λ i, f (a.read i))
@[inline]
def foldl (a : array n α) (b : β) (f : α → β → β) : β :=
iterate a b (λ _, f)
def rev_list (a : array n α) : list α :=
a.foldl [] (::)
def rev_iterate (a : array n α) (b : β) (f : fin n → α → β → β) : β :=
d_array.rev_iterate a b f
def rev_foldl (a : array n α) (b : β) (f : α → β → β) : β :=
rev_iterate a b (λ _, f)
def to_list (a : array n α) : list α :=
a.rev_foldl [] (::)
lemma push_back_idx {j n} (h₁ : j < n + 1) (h₂ : j ≠ n) : j < n :=
nat.lt_of_le_and_ne (nat.le_of_lt_succ h₁) h₂
/-- `push_back a v` pushes value `v` to the end of the array. Has builtin VM implementation. -/
def push_back (a : array n α) (v : α) : array (n+1) α :=
{data := λ ⟨j, h₁⟩, if h₂ : j = n then v else a.read ⟨j, push_back_idx h₁ h₂⟩}
lemma pop_back_idx {j n} (h : j < n) : j < n + 1 :=
nat.lt.step h
/-- Discard _last_ element in the array. Has builtin VM implementation. -/
def pop_back (a : array (n+1) α) : array n α :=
{data := λ ⟨j, h⟩, a.read ⟨j, pop_back_idx h⟩}
/-- Auxilliary function for monadically mapping a function over an array. -/
@[inline]
def mmap_core {β : Type v} {m : Type v → Type w} [monad m] (a : array n α) (f : α → m β) :
∀ i ≤ n, m (array i β)
| 0 _ := pure d_array.nil
| (i+1) h := do
bs ← mmap_core i (le_of_lt h),
b ← f (a.read ⟨i, h⟩),
pure $ bs.push_back b
/-- Monadically map a function over the array. -/
@[inline]
def mmap {β : Type v} {m} [monad m] (a : array n α) (f : α → m β) : m (array n β) :=
a.mmap_core f _ (le_refl _)
/-- Map a function over the array. -/
@[inline]
def map {β : Type v} (a : array n α) (f : α → β) : array n β :=
a.map (λ _, f)
protected def mem (v : α) (a : array n α) : Prop :=
∃ i : fin n, read a i = v
instance : has_mem α (array n α) := ⟨array.mem⟩
theorem read_mem (a : array n α) (i) : read a i ∈ a :=
exists.intro i rfl
instance [has_repr α] : has_repr (array n α) :=
⟨repr ∘ to_list⟩
meta instance [has_to_format α] : has_to_format (array n α) :=
⟨to_fmt ∘ to_list⟩
meta instance [has_to_tactic_format α] : has_to_tactic_format (array n α) :=
⟨tactic.pp ∘ to_list⟩
@[simp] lemma read_write (a : array n α) (i : fin n) (v : α) : read (write a i v) i = v :=
d_array.read_write a i v
@[simp] lemma read_write_of_ne (a : array n α) {i j : fin n} (v : α) : i ≠ j → read (write a i v) j = read a j :=
d_array.read_write_of_ne a v
def read' [inhabited β] (a : array n β) (i : nat) : β :=
if h : i < n then a.read ⟨i,h⟩ else default β
def write' (a : array n α) (i : nat) (v : α) : array n α :=
if h : i < n then a.write ⟨i, h⟩ v else a
lemma read_eq_read' [inhabited α] (a : array n α) {i : nat} (h : i < n) : read a ⟨i, h⟩ = read' a i :=
by simp [read', h]
lemma write_eq_write' (a : array n α) {i : nat} (h : i < n) (v : α) : write a ⟨i, h⟩ v = write' a i v :=
by simp [write', h]
protected lemma ext {a b : array n α} (h : ∀ i, read a i = read b i) : a = b :=
d_array.ext h
protected lemma ext' {a b : array n α} (h : ∀ (i : nat) (h : i < n), read a ⟨i, h⟩ = read b ⟨i, h⟩) : a = b :=
d_array.ext' h
instance [decidable_eq α] : decidable_eq (array n α) :=
begin unfold array, apply_instance end
end array
|
4c36ab358367cdf9ce608cb70a500a330901083b | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/geometry/manifold/algebra/monoid.lean | ce893551579e51be34acd24feb07e9bfc22a7454 | [
"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 | 15,140 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Nicolò Cavalleri
-/
import geometry.manifold.cont_mdiff_map
/-!
# Smooth monoid
A smooth monoid is a monoid that is also a smooth manifold, in which multiplication is a smooth map
of the product manifold `G` × `G` into `G`.
In this file we define the basic structures to talk about smooth monoids: `has_smooth_mul` and its
additive counterpart `has_smooth_add`. These structures are general enough to also talk about smooth
semigroups.
-/
open_locale manifold
/--
1. All smooth algebraic structures on `G` are `Prop`-valued classes that extend
`smooth_manifold_with_corners I G`. This way we save users from adding both
`[smooth_manifold_with_corners I G]` and `[has_smooth_mul I G]` to the assumptions. While many API
lemmas hold true without the `smooth_manifold_with_corners I G` assumption, we're not aware of a
mathematically interesting monoid on a topological manifold such that (a) the space is not a
`smooth_manifold_with_corners`; (b) the multiplication is smooth at `(a, b)` in the charts
`ext_chart_at I a`, `ext_chart_at I b`, `ext_chart_at I (a * b)`.
2. Because of `model_prod` we can't assume, e.g., that a `lie_group` is modelled on `𝓘(𝕜, E)`. So,
we formulate the definitions and lemmas for any model.
3. While smoothness of an operation implies its continuity, lemmas like
`has_continuous_mul_of_smooth` can't be instances becausen otherwise Lean would have to search for
`has_smooth_mul I G` with unknown `𝕜`, `E`, `H`, and `I : model_with_corners 𝕜 E H`. If users needs
`[has_continuous_mul G]` in a proof about a smooth monoid, then they need to either add
`[has_continuous_mul G]` as an assumption (worse) or use `haveI` in the proof (better). -/
library_note "Design choices about smooth algebraic structures"
/-- Basic hypothesis to talk about a smooth (Lie) additive monoid or a smooth additive
semigroup. A smooth additive monoid over `α`, for example, is obtained by requiring both the
instances `add_monoid α` and `has_smooth_add α`. -/
-- See note [Design choices about smooth algebraic structures]
@[ancestor smooth_manifold_with_corners]
class has_smooth_add {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H)
(G : Type*) [has_add G] [topological_space G] [charted_space H G]
extends smooth_manifold_with_corners I G : Prop :=
(smooth_add : smooth (I.prod I) I (λ p : G×G, p.1 + p.2))
/-- Basic hypothesis to talk about a smooth (Lie) monoid or a smooth semigroup.
A smooth monoid over `G`, for example, is obtained by requiring both the instances `monoid G`
and `has_smooth_mul I G`. -/
-- See note [Design choices about smooth algebraic structures]
@[ancestor smooth_manifold_with_corners, to_additive]
class has_smooth_mul {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] (I : model_with_corners 𝕜 E H)
(G : Type*) [has_mul G] [topological_space G] [charted_space H G]
extends smooth_manifold_with_corners I G : Prop :=
(smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2))
section has_smooth_mul
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H}
{G : Type*} [has_mul G] [topological_space G] [charted_space H G] [has_smooth_mul I G]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{M : Type*} [topological_space M] [charted_space H' M]
section
variables (I)
@[to_additive]
lemma smooth_mul : smooth (I.prod I) I (λ p : G×G, p.1 * p.2) :=
has_smooth_mul.smooth_mul
/-- If the multiplication is smooth, then it is continuous. This is not an instance for technical
reasons, see note [Design choices about smooth algebraic structures]. -/
@[to_additive
"If the addition is smooth, then it is continuous. This is not an instance for technical reasons,
see note [Design choices about smooth algebraic structures]."]
lemma has_continuous_mul_of_smooth : has_continuous_mul G :=
⟨(smooth_mul I).continuous⟩
end
section
variables {f g : M → G} {s : set M} {x : M} {n : with_top ℕ}
@[to_additive]
lemma cont_mdiff_within_at.mul (hf : cont_mdiff_within_at I' I n f s x)
(hg : cont_mdiff_within_at I' I n g s x) : cont_mdiff_within_at I' I n (f * g) s x :=
((smooth_mul I).smooth_at.of_le le_top).comp_cont_mdiff_within_at x (hf.prod_mk hg)
@[to_additive]
lemma cont_mdiff_at.mul (hf : cont_mdiff_at I' I n f x) (hg : cont_mdiff_at I' I n g x) :
cont_mdiff_at I' I n (f * g) x :=
hf.mul hg
@[to_additive]
lemma cont_mdiff_on.mul (hf : cont_mdiff_on I' I n f s) (hg : cont_mdiff_on I' I n g s) :
cont_mdiff_on I' I n (f * g) s :=
λ x hx, (hf x hx).mul (hg x hx)
@[to_additive]
lemma cont_mdiff.mul (hf : cont_mdiff I' I n f) (hg : cont_mdiff I' I n g) :
cont_mdiff I' I n (f * g) :=
λ x, (hf x).mul (hg x)
@[to_additive]
lemma smooth_within_at.mul (hf : smooth_within_at I' I f s x)
(hg : smooth_within_at I' I g s x) : smooth_within_at I' I (f * g) s x :=
hf.mul hg
@[to_additive]
lemma smooth_at.mul (hf : smooth_at I' I f x) (hg : smooth_at I' I g x) :
smooth_at I' I (f * g) x :=
hf.mul hg
@[to_additive]
lemma smooth_on.mul (hf : smooth_on I' I f s) (hg : smooth_on I' I g s) :
smooth_on I' I (f * g) s :=
hf.mul hg
@[to_additive]
lemma smooth.mul (hf : smooth I' I f) (hg : smooth I' I g) :
smooth I' I (f * g) :=
hf.mul hg
@[to_additive]
lemma smooth_mul_left {a : G} : smooth I I (λ b : G, a * b) :=
smooth_const.mul smooth_id
@[to_additive]
lemma smooth_mul_right {a : G} : smooth I I (λ b : G, b * a) :=
smooth_id.mul smooth_const
end
variables (I) (g h : G)
/-- Left multiplication by `g`. It is meant to mimic the usual notation in Lie groups.
Lemmas involving `smooth_left_mul` with the notation `𝑳` usually use `L` instead of `𝑳` in the
names. -/
def smooth_left_mul : C^∞⟮I, G; I, G⟯ := ⟨(left_mul g), smooth_mul_left⟩
/-- Right multiplication by `g`. It is meant to mimic the usual notation in Lie groups.
Lemmas involving `smooth_right_mul` with the notation `𝑹` usually use `R` instead of `𝑹` in the
names. -/
def smooth_right_mul : C^∞⟮I, G; I, G⟯ := ⟨(right_mul g), smooth_mul_right⟩
/- Left multiplication. The abbreviation is `MIL`. -/
localized "notation `𝑳` := smooth_left_mul" in lie_group
/- Right multiplication. The abbreviation is `MIR`. -/
localized "notation `𝑹` := smooth_right_mul" in lie_group
open_locale lie_group
@[simp] lemma L_apply : (𝑳 I g) h = g * h := rfl
@[simp] lemma R_apply : (𝑹 I g) h = h * g := rfl
@[simp] lemma L_mul {G : Type*} [semigroup G] [topological_space G] [charted_space H G]
[has_smooth_mul I G] (g h : G) : 𝑳 I (g * h) = (𝑳 I g).comp (𝑳 I h) :=
by { ext, simp only [cont_mdiff_map.comp_apply, L_apply, mul_assoc] }
@[simp] lemma R_mul {G : Type*} [semigroup G] [topological_space G] [charted_space H G]
[has_smooth_mul I G] (g h : G) : 𝑹 I (g * h) = (𝑹 I h).comp (𝑹 I g) :=
by { ext, simp only [cont_mdiff_map.comp_apply, R_apply, mul_assoc] }
section
variables {G' : Type*} [monoid G'] [topological_space G'] [charted_space H G']
[has_smooth_mul I G'] (g' : G')
lemma smooth_left_mul_one : (𝑳 I g') 1 = g' := mul_one g'
lemma smooth_right_mul_one : (𝑹 I g') 1 = g' := one_mul g'
end
/- Instance of product -/
@[to_additive]
instance has_smooth_mul.prod {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H)
(G : Type*) [topological_space G] [charted_space H G]
[has_mul G] [has_smooth_mul I G]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] (I' : model_with_corners 𝕜 E' H')
(G' : Type*) [topological_space G'] [charted_space H' G']
[has_mul G'] [has_smooth_mul I' G'] :
has_smooth_mul (I.prod I') (G×G') :=
{ smooth_mul := ((smooth_fst.comp smooth_fst).smooth.mul (smooth_fst.comp smooth_snd)).prod_mk
((smooth_snd.comp smooth_fst).smooth.mul (smooth_snd.comp smooth_snd)),
.. smooth_manifold_with_corners.prod G G' }
end has_smooth_mul
section monoid
variables {𝕜 : Type*} [nontrivially_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H}
{G : Type*} [monoid G] [topological_space G] [charted_space H G] [has_smooth_mul I G]
{H' : Type*} [topological_space H']
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E'] {I' : model_with_corners 𝕜 E' H'}
{G' : Type*} [monoid G'] [topological_space G'] [charted_space H' G'] [has_smooth_mul I' G']
lemma smooth_pow : ∀ n : ℕ, smooth I I (λ a : G, a ^ n)
| 0 := by { simp only [pow_zero], exact smooth_const }
| (k+1) := by simpa [pow_succ] using smooth_id.mul (smooth_pow _)
/-- Morphism of additive smooth monoids. -/
structure smooth_add_monoid_morphism
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H')
(G : Type*) [topological_space G] [charted_space H G] [add_monoid G] [has_smooth_add I G]
(G' : Type*) [topological_space G'] [charted_space H' G'] [add_monoid G'] [has_smooth_add I' G']
extends G →+ G' :=
(smooth_to_fun : smooth I I' to_fun)
/-- Morphism of smooth monoids. -/
@[to_additive] structure smooth_monoid_morphism
(I : model_with_corners 𝕜 E H) (I' : model_with_corners 𝕜 E' H')
(G : Type*) [topological_space G] [charted_space H G] [monoid G] [has_smooth_mul I G]
(G' : Type*) [topological_space G'] [charted_space H' G'] [monoid G'] [has_smooth_mul I' G']
extends G →* G' :=
(smooth_to_fun : smooth I I' to_fun)
@[to_additive]
instance : has_one (smooth_monoid_morphism I I' G G') :=
⟨{ smooth_to_fun := smooth_const, to_monoid_hom := 1 }⟩
@[to_additive]
instance : inhabited (smooth_monoid_morphism I I' G G') := ⟨1⟩
@[to_additive]
instance : has_coe_to_fun (smooth_monoid_morphism I I' G G') (λ _, G → G') := ⟨λ a, a.to_fun⟩
end monoid
section comm_monoid
open_locale big_operators
variables {ι 𝕜 : Type*} [nontrivially_normed_field 𝕜]
{H : Type*} [topological_space H]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] {I : model_with_corners 𝕜 E H}
{G : Type*} [comm_monoid G] [topological_space G] [charted_space H G] [has_smooth_mul I G]
{E' : Type*} [normed_add_comm_group E'] [normed_space 𝕜 E']
{H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'}
{M : Type*} [topological_space M] [charted_space H' M] {s : set M} {x : M}
{t : finset ι} {f : ι → M → G} {n : with_top ℕ} {p : ι → Prop}
@[to_additive]
lemma cont_mdiff_within_at_finset_prod' (h : ∀ i ∈ t, cont_mdiff_within_at I' I n (f i) s x) :
cont_mdiff_within_at I' I n (∏ i in t, f i) s x :=
finset.prod_induction f (λ f, cont_mdiff_within_at I' I n f s x)
(λ f g hf hg, hf.mul hg) cont_mdiff_within_at_const h
@[to_additive]
lemma cont_mdiff_at_finset_prod' (h : ∀ i ∈ t, cont_mdiff_at I' I n (f i) x) :
cont_mdiff_at I' I n (∏ i in t, f i) x :=
cont_mdiff_within_at_finset_prod' h
@[to_additive]
lemma cont_mdiff_on_finset_prod' (h : ∀ i ∈ t, cont_mdiff_on I' I n (f i) s) :
cont_mdiff_on I' I n (∏ i in t, f i) s :=
λ x hx, cont_mdiff_within_at_finset_prod' $ λ i hi, h i hi x hx
@[to_additive]
lemma cont_mdiff_finset_prod' (h : ∀ i ∈ t, cont_mdiff I' I n (f i)) :
cont_mdiff I' I n (∏ i in t, f i) :=
λ x, cont_mdiff_at_finset_prod' $ λ i hi, h i hi x
@[to_additive]
lemma cont_mdiff_within_at_finset_prod (h : ∀ i ∈ t, cont_mdiff_within_at I' I n (f i) s x) :
cont_mdiff_within_at I' I n (λ x, ∏ i in t, f i x) s x :=
by { simp only [← finset.prod_apply], exact cont_mdiff_within_at_finset_prod' h }
@[to_additive]
lemma cont_mdiff_at_finset_prod (h : ∀ i ∈ t, cont_mdiff_at I' I n (f i) x) :
cont_mdiff_at I' I n (λ x, ∏ i in t, f i x) x :=
cont_mdiff_within_at_finset_prod h
@[to_additive]
lemma cont_mdiff_on_finset_prod (h : ∀ i ∈ t, cont_mdiff_on I' I n (f i) s) :
cont_mdiff_on I' I n (λ x, ∏ i in t, f i x) s :=
λ x hx, cont_mdiff_within_at_finset_prod $ λ i hi, h i hi x hx
@[to_additive]
lemma cont_mdiff_finset_prod (h : ∀ i ∈ t, cont_mdiff I' I n (f i)) :
cont_mdiff I' I n (λ x, ∏ i in t, f i x) :=
λ x, cont_mdiff_at_finset_prod $ λ i hi, h i hi x
@[to_additive]
lemma smooth_within_at_finset_prod' (h : ∀ i ∈ t, smooth_within_at I' I (f i) s x) :
smooth_within_at I' I (∏ i in t, f i) s x :=
cont_mdiff_within_at_finset_prod' h
@[to_additive]
lemma smooth_at_finset_prod' (h : ∀ i ∈ t, smooth_at I' I (f i) x) :
smooth_at I' I (∏ i in t, f i) x :=
cont_mdiff_at_finset_prod' h
@[to_additive]
lemma smooth_on_finset_prod' (h : ∀ i ∈ t, smooth_on I' I (f i) s) :
smooth_on I' I (∏ i in t, f i) s :=
cont_mdiff_on_finset_prod' h
@[to_additive]
lemma smooth_finset_prod' (h : ∀ i ∈ t, smooth I' I (f i)) : smooth I' I (∏ i in t, f i) :=
cont_mdiff_finset_prod' h
@[to_additive]
lemma smooth_within_at_finset_prod (h : ∀ i ∈ t, smooth_within_at I' I (f i) s x) :
smooth_within_at I' I (λ x, ∏ i in t, f i x) s x :=
cont_mdiff_within_at_finset_prod h
@[to_additive]
lemma smooth_at_finset_prod (h : ∀ i ∈ t, smooth_at I' I (f i) x) :
smooth_at I' I (λ x, ∏ i in t, f i x) x :=
cont_mdiff_at_finset_prod h
@[to_additive]
lemma smooth_on_finset_prod (h : ∀ i ∈ t, smooth_on I' I (f i) s) :
smooth_on I' I (λ x, ∏ i in t, f i x) s :=
cont_mdiff_on_finset_prod h
@[to_additive]
lemma smooth_finset_prod (h : ∀ i ∈ t, smooth I' I (f i)) :
smooth I' I (λ x, ∏ i in t, f i x) :=
cont_mdiff_finset_prod h
open function filter
@[to_additive]
lemma cont_mdiff_finprod (h : ∀ i, cont_mdiff I' I n (f i))
(hfin : locally_finite (λ i, mul_support (f i))) :
cont_mdiff I' I n (λ x, ∏ᶠ i, f i x) :=
begin
intro x,
rcases finprod_eventually_eq_prod hfin x with ⟨s, hs⟩,
exact (cont_mdiff_finset_prod (λ i hi, h i) x).congr_of_eventually_eq hs,
end
@[to_additive]
lemma cont_mdiff_finprod_cond (hc : ∀ i, p i → cont_mdiff I' I n (f i))
(hf : locally_finite (λ i, mul_support (f i))) :
cont_mdiff I' I n (λ x, ∏ᶠ i (hi : p i), f i x) :=
begin
simp only [← finprod_subtype_eq_finprod_cond],
exact cont_mdiff_finprod (λ i, hc i i.2) (hf.comp_injective subtype.coe_injective)
end
@[to_additive]
lemma smooth_finprod (h : ∀ i, smooth I' I (f i)) (hfin : locally_finite (λ i, mul_support (f i))) :
smooth I' I (λ x, ∏ᶠ i, f i x) :=
cont_mdiff_finprod h hfin
@[to_additive]
lemma smooth_finprod_cond (hc : ∀ i, p i → smooth I' I (f i))
(hf : locally_finite (λ i, mul_support (f i))) :
smooth I' I (λ x, ∏ᶠ i (hi : p i), f i x) :=
cont_mdiff_finprod_cond hc hf
end comm_monoid
|
d5f8ce8fd4bbf37c07d832b5bec7dd3413d906a7 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/order/order_dual.lean | ae320472037223e56620dcafcd8dfa6d7cb51bc0 | [
"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,376 | lean | /-
Copyright (c) 2020 Johan Commelin, Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Damiano Testa
-/
import order.basic
import data.equiv.basic
/-!
# Initial lemmas to work with the `order_dual`
## Definitions
`to_dual` and `of_dual` the order reversing identity maps, bundled as equivalences.
## Basic Lemmas to convert between an order and its dual
This file is similar to algebra/group/type_tags.lean
-/
open function
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop}
namespace order_dual
instance [nontrivial α] : nontrivial (order_dual α) := by delta order_dual; assumption
/-- `to_dual` is the identity function to the `order_dual` of a linear order. -/
def to_dual : α ≃ order_dual α := ⟨id, id, λ h, rfl, λ h, rfl⟩
/-- `of_dual` is the identity function from the `order_dual` of a linear order. -/
def of_dual : order_dual α ≃ α := to_dual.symm
@[simp] lemma to_dual_symm_eq : (@to_dual α).symm = of_dual := rfl
@[simp] lemma of_dual_symm_eq : (@of_dual α).symm = to_dual := rfl
@[simp] lemma to_dual_of_dual (a : order_dual α) : to_dual (of_dual a) = a := rfl
@[simp] lemma of_dual_to_dual (a : α) : of_dual (to_dual a) = a := rfl
@[simp] lemma to_dual_inj {a b : α} :
to_dual a = to_dual b ↔ a = b := iff.rfl
@[simp] lemma to_dual_le_to_dual [has_le α] {a b : α} :
to_dual a ≤ to_dual b ↔ b ≤ a := iff.rfl
@[simp] lemma to_dual_lt_to_dual [has_lt α] {a b : α} :
to_dual a < to_dual b ↔ b < a := iff.rfl
@[simp] lemma of_dual_inj {a b : order_dual α} :
of_dual a = of_dual b ↔ a = b := iff.rfl
@[simp] lemma of_dual_le_of_dual [has_le α] {a b : order_dual α} :
of_dual a ≤ of_dual b ↔ b ≤ a := iff.rfl
@[simp] lemma of_dual_lt_of_dual [has_lt α] {a b : order_dual α} :
of_dual a < of_dual b ↔ b < a := iff.rfl
lemma le_to_dual [has_le α] {a : order_dual α} {b : α} :
a ≤ to_dual b ↔ b ≤ of_dual a := iff.rfl
lemma lt_to_dual [has_lt α] {a : order_dual α} {b : α} :
a < to_dual b ↔ b < of_dual a := iff.rfl
lemma to_dual_le [has_le α] {a : α} {b : order_dual α} :
to_dual a ≤ b ↔ of_dual b ≤ a := iff.rfl
lemma to_dual_lt [has_lt α] {a : α} {b : order_dual α} :
to_dual a < b ↔ of_dual b < a := iff.rfl
end order_dual
|
83a297bdf0f406aec9279560a3983a05a52a636d | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Lean/Elab/Util.lean | cab1a6f614e6ea8b7dd28d2b2671e92e6123252a | [
"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 | 5,483 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Lean.Util.Trace
import Init.Lean.Parser
import Init.Lean.KeyedDeclsAttribute
namespace Lean
def Syntax.prettyPrint (stx : Syntax) : Format :=
match stx.truncateTrailing.reprint with -- TODO use syntax pretty printer
| some str => format str.toFormat
| none => format stx
def MacroScopesView.format (view : MacroScopesView) (mainModule : Name) : Format :=
format $
if view.scopes.isEmpty then view.name
else if view.mainModule == mainModule then
view.scopes.foldl mkNameNum (view.name ++ view.imported)
else
view.scopes.foldl mkNameNum (view.name ++ view.imported ++ view.mainModule)
namespace Elab
structure MacroStackElem :=
(before : Syntax) (after : Syntax)
abbrev MacroStack := List MacroStackElem
/- If `ref` does not have position information, then try to use macroStack -/
def getBetterRef (ref : Syntax) (macroStack : MacroStack) : Syntax :=
match ref.getPos with
| some _ => ref
| none =>
match macroStack.find? $ fun (elem : MacroStackElem) => elem.before.getPos != none with
| some elem => elem.before
| none => ref
def addMacroStack (msgData : MessageData) (macroStack : MacroStack) : MessageData :=
match macroStack with
| [] => msgData
| stack@(top::_) =>
let topFmt := top.after.prettyPrint;
let msgData := msgData ++ Format.line ++ "with resulting expansion" ++ MessageData.nest 2 (Format.line ++ topFmt);
stack.foldl
(fun (msgData : MessageData) (elem : MacroStackElem) =>
let macroFmt := elem.before.prettyPrint;
msgData ++ Format.line ++ "while expanding" ++ MessageData.nest 2 (Format.line ++ macroFmt))
msgData
def checkSyntaxNodeKind (env : Environment) (k : Name) : ExceptT String Id Name :=
if Parser.isValidSyntaxNodeKind env k then pure k
else throw "failed"
def checkSyntaxNodeKindAtNamespaces (env : Environment) (k : Name) : List Name → ExceptT String Id Name
| [] => throw "failed"
| n::ns => checkSyntaxNodeKind env (n ++ k) <|> checkSyntaxNodeKindAtNamespaces ns
def syntaxNodeKindOfAttrParam (env : Environment) (defaultParserNamespace : Name) (arg : Syntax) : ExceptT String Id SyntaxNodeKind :=
match attrParamSyntaxToIdentifier arg with
| some k =>
checkSyntaxNodeKind env k
<|>
checkSyntaxNodeKindAtNamespaces env k env.getNamespaces
<|>
checkSyntaxNodeKind env (defaultParserNamespace ++ k)
<|>
throw ("invalid syntax node kind '" ++ toString k ++ "'")
| none => throw ("syntax node kind is missing")
private unsafe def evalSyntaxConstantUnsafe (env : Environment) (constName : Name) : ExceptT String Id Syntax :=
env.evalConstCheck Syntax `Lean.Syntax constName
@[implementedBy evalSyntaxConstantUnsafe]
constant evalSyntaxConstant (env : Environment) (constName : Name) : ExceptT String Id Syntax := throw ""
private constant evalConstant (γ : Type) (env : Environment) (typeName : Name) (constName : Name) : ExceptT String Id γ := throw ""
unsafe def mkElabAttribute (γ) (attrDeclName attrBuiltinName attrName : Name) (parserNamespace : Name) (typeName : Name) (kind : String)
: IO (KeyedDeclsAttribute γ) :=
KeyedDeclsAttribute.init {
builtinName := attrBuiltinName,
name := attrName,
descr := kind ++ " elaborator",
valueTypeName := typeName,
evalKey := fun env arg => syntaxNodeKindOfAttrParam env parserNamespace arg,
} attrDeclName
unsafe def mkMacroAttribute : IO (KeyedDeclsAttribute Macro) :=
mkElabAttribute Macro `Lean.Elab.macroAttribute `builtinMacro `macro Name.anonymous `Lean.Macro "macro"
@[init mkMacroAttribute] constant macroAttribute : KeyedDeclsAttribute Macro := arbitrary _
private def expandMacroFns (stx : Syntax) : List Macro → MacroM Syntax
| [] => throw Macro.Exception.unsupportedSyntax
| m::ms => m stx <|> expandMacroFns ms
def getMacros (env : Environment) : Macro :=
fun stx =>
let k := stx.getKind;
let table := (macroAttribute.ext.getState env).table;
match table.find? k with
| some macroFns => expandMacroFns stx macroFns
| none => throw Macro.Exception.unsupportedSyntax
class MonadMacroAdapter (m : Type → Type) :=
(getEnv {} : m Environment)
(getCurrMacroScope {} : m MacroScope)
(getNextMacroScope {} : m MacroScope)
(setNextMacroScope {} : MacroScope → m Unit)
(throwError {} {α : Type} : Syntax → MessageData → m α)
(throwUnsupportedSyntax {} {α : Type} : m α)
@[inline] def liftMacroM {α} {m : Type → Type} [Monad m] [MonadMacroAdapter m] (x : MacroM α) : m α := do
scp ← MonadMacroAdapter.getCurrMacroScope;
env ← MonadMacroAdapter.getEnv;
next ← MonadMacroAdapter.getNextMacroScope;
match x { currMacroScope := scp, mainModule := env.mainModule } next with
| EStateM.Result.error Macro.Exception.unsupportedSyntax _ => MonadMacroAdapter.throwUnsupportedSyntax
| EStateM.Result.error (Macro.Exception.error ref msg) _ => MonadMacroAdapter.throwError ref msg
| EStateM.Result.ok a nextMacroScope => do MonadMacroAdapter.setNextMacroScope nextMacroScope; pure a
@[inline] def adaptMacro {m : Type → Type} [Monad m] [MonadMacroAdapter m] (x : Macro) (stx : Syntax) : m Syntax :=
liftMacroM (x stx)
@[init] private def regTraceClasses : IO Unit := do
registerTraceClass `Elab;
registerTraceClass `Elab.step
end Elab
end Lean
|
3ad32afa16b0ee7e79fc33386a9dc130367e9bee | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/blast_ematch9.lean | 44963cb84a2229d0fad424e2033af7674c64e2c5 | [
"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 | 194 | lean | constant P : nat → Prop
definition h [reducible] (n : nat) := n
definition foo [forward] : ∀ x, P (h x) := sorry
set_option blast.strategy "ematch"
example (n : nat) : P (h n) :=
by blast
|
61329d56693d9804a7a490409d97ba9681632882 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/topology/tactic.lean | 3d300977c637ddb088ae3cb262d0977102235a3b | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 4,222 | lean | /-
Copyright (c) 2020 Reid Barton. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton
-/
import tactic.auto_cases
import tactic.tidy
import tactic.with_local_reducibility
import tactic.show_term
import topology.basic
/-!
# Tactics for topology
Currently we have one domain-specific tactic for topology: `continuity`.
-/
/-!
### `continuity` tactic
Automatically solve goals of the form `continuous f`.
Mark lemmas with `@[continuity]` to add them to the set of lemmas
used by `continuity`. Note: `to_additive` doesn't know yet how to
copy the attribute to the additive version.
-/
/-- User attribute used to mark tactics used by `continuity`. -/
@[user_attribute]
meta def continuity : user_attribute :=
{ name := `continuity,
descr := "lemmas usable to prove continuity" }
-- Mark some continuity lemmas already defined in `topology.basic`
attribute [continuity]
continuous_id
continuous_const
-- As we will be using `apply_rules` with `md := semireducible`,
-- we need another version of `continuous_id`.
@[continuity] lemma continuous_id' {α : Type*} [topological_space α] : continuous (λ a : α, a) :=
continuous_id
namespace tactic
/--
Tactic to apply `continuous.comp` when appropriate.
Applying `continuous.comp` is not always a good idea, so we have some
extra logic here to try to avoid bad cases.
* If the function we're trying to prove continuous is actually
constant, and that constant is a function application `f z`, then
continuous.comp would produce new goals `continuous f`, `continuous
(λ _, z)`, which is silly. We avoid this by failing if we could
apply continuous_const.
* continuous.comp will always succeed on `continuous (λ x, f x)` and
produce new goals `continuous (λ x, x)`, `continuous f`. We detect
this by failing if a new goal can be closed by applying
continuous_id.
-/
meta def apply_continuous.comp : tactic unit :=
`[fail_if_success { exact continuous_const };
refine continuous.comp _ _;
fail_if_success { exact continuous_id }]
/-- List of tactics used by `continuity` internally. -/
meta def continuity_tactics (md : transparency := reducible) : list (tactic string) :=
[
intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate (ns.map (λ e, e.to_string)))),
apply_rules [``(continuity)] 50 { md := md }
>> pure "apply_rules continuity",
apply_continuous.comp >> pure "refine continuous.comp _ _"
]
namespace interactive
setup_tactic_parser
/--
Solve goals of the form `continuous f`. `continuity?` reports back the proof term it found.
-/
meta def continuity
(bang : parse $ optional (tk "!")) (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) : tactic unit :=
with_local_reducibility `continuous decl_reducibility.irreducible $
let md := if bang.is_some then semireducible else reducible,
continuity_core := tactic.tidy { tactics := continuity_tactics md, ..cfg },
trace_fn := if trace.is_some then show_term else id in
trace_fn continuity_core
/-- Version of `continuity` for use with auto_param. -/
meta def continuity' : tactic unit := continuity none none {}
/--
`continuity` solves goals of the form `continuous f` by applying lemmas tagged with the
`continuity` user attribute.
```
example {X Y : Type*} [topological_space X] [topological_space Y]
(f₁ f₂ : X → Y) (hf₁ : continuous f₁) (hf₂ : continuous f₂)
(g : Y → ℝ) (hg : continuous g) : continuous (λ x, (max (g (f₁ x)) (g (f₂ x))) + 1) :=
by continuity
```
will discharge the goal, generating a proof term like
`((continuous.comp hg hf₁).max (continuous.comp hg hf₂)).add continuous_const`
You can also use `continuity!`, which applies lemmas with `{ md := semireducible }`.
The default behaviour is more conservative, and only unfolds `reducible` definitions
when attempting to match lemmas with the goal.
`continuity?` reports back the proof term it found.
-/
add_tactic_doc
{ name := "continuity / continuity'",
category := doc_category.tactic,
decl_names := [`tactic.interactive.continuity, `tactic.interactive.continuity'],
tags := ["lemma application"]
}
end interactive
end tactic
|
4d8b04b9f7f4a6a92565bd7f2bb898ac0b251461 | e61a235b8468b03aee0120bf26ec615c045005d2 | /src/Init/Lean/Elab/DeclModifiers.lean | cb5b01666d9072fe146083010cf791b430de79b6 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,285 | 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, Sebastian Ullrich
-/
prelude
import Init.Lean.Elab.Command
namespace Lean
namespace Elab
namespace Command
structure Attribute :=
(name : Name) (args : Syntax := Syntax.missing)
instance Attribute.hasFormat : HasFormat Attribute :=
⟨fun attr => Format.bracket "@[" (toString attr.name ++ (if attr.args.isMissing then "" else toString attr.args)) "]"⟩
inductive Visibility
| regular | «protected» | «private»
instance Visibility.hasToString : HasToString Visibility :=
⟨fun v => match v with
| Visibility.regular => "regular"
| Visibility.private => "private"
| Visibility.protected => "protected"⟩
structure Modifiers :=
(docString : Option String := none)
(visibility : Visibility := Visibility.regular)
(isNoncomputable : Bool := false)
(isPartial : Bool := false)
(isUnsafe : Bool := false)
(attrs : Array Attribute := #[])
def Modifiers.addAttribute (modifiers : Modifiers) (attr : Attribute) : Modifiers :=
{ modifiers with attrs := modifiers.attrs.push attr }
instance Modifiers.hasFormat : HasFormat Modifiers :=
⟨fun m =>
let components : List Format :=
(match m.docString with
| some str => ["/--" ++ str ++ "-/"]
| none => [])
++ (match m.visibility with
| Visibility.regular => []
| Visibility.protected => ["protected"]
| Visibility.private => ["private"])
++ (if m.isNoncomputable then ["noncomputable"] else [])
++ (if m.isPartial then ["partial"] else [])
++ (if m.isUnsafe then ["unsafe"] else [])
++ m.attrs.toList.map (fun attr => fmt attr);
Format.bracket "{" (Format.joinSep components ("," ++ Format.line)) "}"⟩
instance Modifiers.hasToString : HasToString Modifiers := ⟨toString ∘ format⟩
def elabAttr (stx : Syntax) : CommandElabM Attribute := do
-- rawIdent >> many attrArg
let nameStx := stx.getArg 0;
attrName ← match nameStx.isIdOrAtom? with
| none => throwError nameStx "identifier expected"
| some str => pure $ mkNameSimple str;
env ← getEnv;
unless (isAttribute env attrName) $
throwError stx ("unknown attribute [" ++ attrName ++ "]");
let args := stx.getArg 1;
pure { name := attrName, args := args }
def elabAttrs (stx : Syntax) : CommandElabM (Array Attribute) :=
(stx.getArg 1).foldSepArgsM
(fun stx attrs => do
attr ← elabAttr stx;
pure $ attrs.push attr)
#[]
def elabModifiers (stx : Syntax) : CommandElabM Modifiers := do
let docCommentStx := stx.getArg 0;
let attrsStx := stx.getArg 1;
let visibilityStx := stx.getArg 2;
let noncompStx := stx.getArg 3;
let unsafeStx := stx.getArg 4;
let partialStx := stx.getArg 5;
docString ← match docCommentStx.getOptional? with
| none => pure none
| some s => match s.getArg 1 with
| Syntax.atom _ val => pure (some (val.extract 0 (val.bsize - 2)))
| _ => throwError s ("unexpected doc string " ++ toString (s.getArg 1));
visibility ← match visibilityStx.getOptional? with
| none => pure Visibility.regular
| some v =>
let kind := v.getKind;
if kind == `Lean.Parser.Command.private then pure Visibility.private
else if kind == `Lean.Parser.Command.protected then pure Visibility.protected
else throwError v "unexpected visibility modifier";
attrs ← match attrsStx.getOptional? with
| none => pure #[]
| some attrs => elabAttrs attrs;
pure {
docString := docString,
visibility := visibility,
isPartial := !partialStx.isNone,
isUnsafe := !unsafeStx.isNone,
isNoncomputable := !noncompStx.isNone,
attrs := attrs
}
def mkDeclName (modifiers : Modifiers) (atomicName : Name) : CommandElabM Name := do
currNamespace ← getCurrNamespace;
let declName := currNamespace ++ atomicName;
match modifiers.visibility with
| Visibility.private => do
env ← getEnv;
pure $ mkPrivateName env declName
| _ => pure declName
def checkNotAlreadyDeclared (ref : Syntax) (declName : Name) : CommandElabM Unit := do
env ← getEnv;
when (env.contains declName) $
match privateToUserName? declName with
| none => throwError ref ("'" ++ declName ++ "' has already been declared")
| some declName => throwError ref ("private declaration '" ++ declName ++ "' has already been declared");
when (env.contains (mkPrivateName env declName)) $
throwError ref ("a private declaration '" ++ declName ++ "' has already been declared");
match privateToUserName? declName with
| none => pure ()
| some declName =>
when (env.contains declName) $
throwError ref ("a non-private declaration '" ++ declName ++ "' has already been declared")
def applyAttributes (ref : Syntax) (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : CommandElabM Unit :=
attrs.forM $ fun attr => do
env ← getEnv;
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError ref errMsg
| Except.ok attrImpl =>
when (attrImpl.applicationTime == applicationTime) $ do
env ← getEnv;
env ← liftIO ref $ attrImpl.add env declName attr.args true;
setEnv env
end Command
end Elab
end Lean
|
f7ccaa2a97fb21b3b03bf90922b701ffa672a44c | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/PrettyPrinter.lean | 05f5fc9f78b38ef14e250f51b8037292865a5e3a | [
"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,432 | lean | /-
Copyright (c) 2020 Sebastian Ullrich. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Lean.PrettyPrinter.Delaborator
import Lean.PrettyPrinter.Parenthesizer
import Lean.PrettyPrinter.Formatter
import Lean.Parser.Module
import Lean.ParserCompiler
namespace Lean
def PPContext.runCoreM {α : Type} (ppCtx : PPContext) (x : CoreM α) : IO α :=
Prod.fst <$> x.toIO { options := ppCtx.opts, currNamespace := ppCtx.currNamespace, openDecls := ppCtx.openDecls }
{ env := ppCtx.env, ngen := { namePrefix := `_pp_uniq } }
def PPContext.runMetaM {α : Type} (ppCtx : PPContext) (x : MetaM α) : IO α :=
ppCtx.runCoreM <| x.run' { lctx := ppCtx.lctx } { mctx := ppCtx.mctx }
namespace PrettyPrinter
def ppTerm (stx : Syntax) : CoreM Format := do
let opts ← getOptions
let stx := (sanitizeSyntax stx).run' { options := opts }
parenthesizeTerm stx >>= formatTerm
def ppExpr (currNamespace : Name) (openDecls : List OpenDecl) (e : Expr) : MetaM Format := do
let lctx ← getLCtx
let opts ← getOptions
let lctx := lctx.sanitizeNames.run' { options := opts }
Meta.withLCtx lctx #[] do
let stx ← delab currNamespace openDecls e
ppTerm stx
@[export lean_pp_expr]
def ppExprLegacy (env : Environment) (mctx : MetavarContext) (lctx : LocalContext) (opts : Options) (e : Expr) : IO Format :=
Prod.fst <$> ((ppExpr Name.anonymous [] e).run' { lctx := lctx } { mctx := mctx }).toIO { options := opts } { env := env }
def ppCommand (stx : Syntax) : CoreM Format :=
parenthesizeCommand stx >>= formatCommand
def ppModule (stx : Syntax) : CoreM Format := do
parenthesize Lean.Parser.Module.module.parenthesizer stx >>= format Lean.Parser.Module.module.formatter
private partial def noContext : MessageData → MessageData
| MessageData.withContext ctx msg => noContext msg
| MessageData.withNamingContext ctx msg => MessageData.withNamingContext ctx (noContext msg)
| MessageData.nest n msg => MessageData.nest n (noContext msg)
| MessageData.group msg => MessageData.group (noContext msg)
| MessageData.compose msg₁ msg₂ => MessageData.compose (noContext msg₁) (noContext msg₂)
| MessageData.tagged tag msg => MessageData.tagged tag (noContext msg)
| MessageData.node msgs => MessageData.node (msgs.map noContext)
| msg => msg
-- strip context (including environments with registered pretty printers) to prevent infinite recursion when pretty printing pretty printer error
private def withoutContext {m} [MonadExcept Exception m] (x : m Format) : m Format :=
tryCatch x fun
| Exception.error ref msg => throw $ Exception.error ref (noContext msg)
| ex => throw ex
builtin_initialize
ppFnsRef.set {
ppExpr := fun ctx e => ctx.runMetaM $ withoutContext $ ppExpr ctx.currNamespace ctx.openDecls e,
ppTerm := fun ctx stx => ctx.runCoreM $ withoutContext $ ppTerm stx,
ppGoal := fun ctx mvarId => ctx.runMetaM $ withoutContext $ Meta.ppGoal mvarId
}
builtin_initialize
registerTraceClass `PrettyPrinter
@[builtinInit]
unsafe def registerParserCompilers : IO Unit := do
ParserCompiler.registerParserCompiler ⟨`parenthesizer, parenthesizerAttribute, combinatorParenthesizerAttribute⟩
ParserCompiler.registerParserCompiler ⟨`formatter, formatterAttribute, combinatorFormatterAttribute⟩
end PrettyPrinter
end Lean
|
c34108f95b1b12fab7c61b3a847bf599afe153a4 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/category_theory/opposites.lean | 8cad18c8815e75b55df48592676652fef7255ef6 | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 7,725 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Stephen Morgan, Scott Morrison
-/
import category_theory.types
import category_theory.natural_isomorphism
import data.opposite
universes v₁ v₂ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
namespace category_theory
open opposite
variables {C : Type u₁}
section has_hom
variables [𝒞 : has_hom.{v₁} C]
include 𝒞
/-- The hom types of the opposite of a category (or graph).
As with the objects, we'll make this irreducible below.
Use `f.op` and `f.unop` to convert between morphisms of C
and morphisms of Cᵒᵖ.
-/
instance has_hom.opposite : has_hom Cᵒᵖ :=
{ hom := λ X Y, unop Y ⟶ unop X }
def has_hom.hom.op {X Y : C} (f : X ⟶ Y) : op Y ⟶ op X := f
def has_hom.hom.unop {X Y : Cᵒᵖ} (f : X ⟶ Y) : unop Y ⟶ unop X := f
attribute [irreducible] has_hom.opposite
lemma has_hom.hom.op_inj {X Y : C} :
function.injective (has_hom.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) :=
λ _ _ H, congr_arg has_hom.hom.unop H
lemma has_hom.hom.unop_inj {X Y : Cᵒᵖ} :
function.injective (has_hom.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) :=
λ _ _ H, congr_arg has_hom.hom.op H
@[simp] lemma has_hom.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl
@[simp] lemma has_hom.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl
end has_hom
variables [𝒞 : category.{v₁} C]
include 𝒞
instance category.opposite : category.{v₁} Cᵒᵖ :=
{ comp := λ _ _ _ f g, (g.unop ≫ f.unop).op,
id := λ X, (𝟙 (unop X)).op }
@[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).op = g.op ≫ f.op := rfl
@[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl
@[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).unop = g.unop ≫ f.unop := rfl
@[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl
@[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl
@[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl
def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C :=
{ obj := λ X, unop (unop X),
map := λ X Y f, f.unop.unop }
-- TODO this is an equivalence
def is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f :=
{ inv := (inv (f.op)).unop,
hom_inv_id' := has_hom.hom.op_inj (by simp),
inv_hom_id' := has_hom.hom.op_inj (by simp) }
namespace functor
section
variables {D : Type u₂} [𝒟 : category.{v₂} D]
include 𝒟
variables {C D}
protected definition op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ :=
{ obj := λ X, op (F.obj (unop X)),
map := λ X Y f, (F.map f.unop).op }
@[simp] lemma op_obj (F : C ⥤ D) (X : Cᵒᵖ) : (F.op).obj X = op (F.obj (unop X)) := rfl
@[simp] lemma op_map (F : C ⥤ D) {X Y : Cᵒᵖ} (f : X ⟶ Y) : (F.op).map f = (F.map f.unop).op := rfl
protected definition unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D :=
{ obj := λ X, unop (F.obj (op X)),
map := λ X Y f, (F.map f.op).unop }
@[simp] lemma unop_obj (F : Cᵒᵖ ⥤ Dᵒᵖ) (X : C) : (F.unop).obj X = unop (F.obj (op X)) := rfl
@[simp] lemma unop_map (F : Cᵒᵖ ⥤ Dᵒᵖ) {X Y : C} (f : X ⟶ Y) : (F.unop).map f = (F.map f.op).unop := rfl
variables (C D)
definition op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) :=
{ obj := λ F, (unop F).op,
map := λ F G α,
{ app := λ X, (α.unop.app (unop X)).op,
naturality' := λ X Y f, has_hom.hom.unop_inj $ eq.symm (α.unop.naturality f.unop) } }
@[simp] lemma op_hom.obj (F : (C ⥤ D)ᵒᵖ) : (op_hom C D).obj F = (unop F).op := rfl
@[simp] lemma op_hom.map_app {F G : (C ⥤ D)ᵒᵖ} (α : F ⟶ G) (X : Cᵒᵖ) :
((op_hom C D).map α).app X = (α.unop.app (unop X)).op := rfl
definition op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ :=
{ obj := λ F, op F.unop,
map := λ F G α, has_hom.hom.op
{ app := λ X, (α.app (op X)).unop,
naturality' := λ X Y f, has_hom.hom.op_inj $ eq.symm (α.naturality f.op) } }
@[simp] lemma op_inv.obj (F : Cᵒᵖ ⥤ Dᵒᵖ) : (op_inv C D).obj F = op F.unop := rfl
@[simp] lemma op_inv.map_app {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) (X : C) :
(((op_inv C D).map α).unop).app X = (α.app (op X)).unop := rfl
-- TODO show these form an equivalence
variables {C D}
protected definition left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D :=
{ obj := λ X, unop (F.obj (unop X)),
map := λ X Y f, (F.map f.unop).unop }
@[simp] lemma left_op_obj (F : C ⥤ Dᵒᵖ) (X : Cᵒᵖ) : (F.left_op).obj X = unop (F.obj (unop X)) := rfl
@[simp] lemma left_op_map (F : C ⥤ Dᵒᵖ) {X Y : Cᵒᵖ} (f : X ⟶ Y) :
(F.left_op).map f = (F.map f.unop).unop :=
rfl
protected definition right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ :=
{ obj := λ X, op (F.obj (op X)),
map := λ X Y f, (F.map f.op).op }
@[simp] lemma right_op_obj (F : Cᵒᵖ ⥤ D) (X : C) : (F.right_op).obj X = op (F.obj (op X)) := rfl
@[simp] lemma right_op_map (F : Cᵒᵖ ⥤ D) {X Y : C} (f : X ⟶ Y) :
(F.right_op).map f = (F.map f.op).op :=
rfl
-- TODO show these form an equivalence
instance {F : C ⥤ D} [full F] : full F.op :=
{ preimage := λ X Y f, (F.preimage f.unop).op }
instance {F : C ⥤ D} [faithful F] : faithful F.op :=
{ injectivity' := λ X Y f g h,
has_hom.hom.unop_inj $ by simpa using injectivity F (has_hom.hom.op_inj h) }
end
end functor
namespace nat_trans
variables {D : Type u₂} [𝒟 : category.{v₂} D]
include 𝒟
section
variables {F G : C ⥤ D}
@[simps] protected definition op (α : F ⟶ G) : G.op ⟶ F.op :=
{ app := λ X, (α.app (unop X)).op,
naturality' := begin tidy, erw α.naturality, refl, end }
@[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl
@[simps] protected definition unop (α : F.op ⟶ G.op) : G ⟶ F :=
{ app := λ X, (α.app (op X)).unop,
naturality' := begin tidy, erw α.naturality, refl, end }
@[simp] lemma unop_id (F : C ⥤ D) : nat_trans.unop (𝟙 F.op) = 𝟙 F := rfl
end
section
variables {F G : C ⥤ Dᵒᵖ}
protected definition left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op :=
{ app := λ X, (α.app (unop X)).unop,
naturality' := begin tidy, erw α.naturality, refl, end }
@[simp] lemma left_op_app (α : F ⟶ G) (X) :
(nat_trans.left_op α).app X = (α.app (unop X)).unop :=
rfl
protected definition right_op (α : F.left_op ⟶ G.left_op) : G ⟶ F :=
{ app := λ X, (α.app (op X)).op,
naturality' := begin tidy, erw α.naturality, refl, end }
@[simp] lemma right_op_app (α : F.left_op ⟶ G.left_op) (X) :
(nat_trans.right_op α).app X = (α.app (op X)).op :=
rfl
end
end nat_trans
namespace iso
variables {X Y : C}
protected definition op (α : X ≅ Y) : op Y ≅ op X :=
{ hom := α.hom.op,
inv := α.inv.op,
hom_inv_id' := has_hom.hom.unop_inj α.inv_hom_id,
inv_hom_id' := has_hom.hom.unop_inj α.hom_inv_id }
@[simp] lemma op_hom {α : X ≅ Y} : α.op.hom = α.hom.op := rfl
@[simp] lemma op_inv {α : X ≅ Y} : α.op.inv = α.inv.op := rfl
end iso
namespace nat_iso
variables {D : Type u₂} [𝒟 : category.{v₂} D]
include 𝒟
variables {F G : C ⥤ D}
protected definition op (α : F ≅ G) : G.op ≅ F.op :=
{ hom := nat_trans.op α.hom,
inv := nat_trans.op α.inv,
hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw inv_hom_id_app, refl, end,
inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw hom_inv_id_app, refl, end }
@[simp] lemma op_hom (α : F ≅ G) : (nat_iso.op α).hom = nat_trans.op α.hom := rfl
@[simp] lemma op_inv (α : F ≅ G) : (nat_iso.op α).inv = nat_trans.op α.inv := rfl
end nat_iso
end category_theory
|
226ec2f987708fc86aa5fd4295ead17556dc1f8b | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/ns1.lean | f1e40bb8385254018772b1485fe65f208a20f277 | [
"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 | 99 | lean | namespace foo
namespace boo
theorem tst : true := trivial
end boo
end foo
open foo
#check boo.tst
|
14bfeaf8636a3bc53f0bb17491db272231a3d5ed | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/monoidal/internal/Module.lean | ab44dea7c2393f61b4a61209c9b8021fdef76d5f | [
"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,279 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.Module.monoidal
import algebra.category.Algebra.basic
import category_theory.monoidal.Mon_
/-!
# `Mon_ (Module R) ≌ Algebra R`
The category of internal monoid objects in `Module R`
is equivalent to the category of "native" bundled `R`-algebras.
Moreover, this equivalence is compatible with the forgetful functors to `Module R`.
-/
universes v u
open category_theory
open linear_map
open_locale tensor_product
namespace Module
variables {R : Type u} [comm_ring R]
namespace Mon_Module_equivalence_Algebra
@[simps]
instance (A : Mon_ (Module.{u} R)) : ring A.X :=
{ one := A.one (1 : R),
mul := λ x y, A.mul (x ⊗ₜ y),
one_mul := λ x, by { convert linear_map.congr_fun A.one_mul ((1 : R) ⊗ₜ x), simp, },
mul_one := λ x, by { convert linear_map.congr_fun A.mul_one (x ⊗ₜ (1 : R)), simp, },
mul_assoc := λ x y z, by convert linear_map.congr_fun A.mul_assoc ((x ⊗ₜ y) ⊗ₜ z),
left_distrib := λ x y z,
begin
convert A.mul.map_add (x ⊗ₜ y) (x ⊗ₜ z),
rw ←tensor_product.tmul_add,
refl,
end,
right_distrib := λ x y z,
begin
convert A.mul.map_add (x ⊗ₜ z) (y ⊗ₜ z),
rw ←tensor_product.add_tmul,
refl,
end,
..(by apply_instance : add_comm_group A.X) }
instance (A : Mon_ (Module.{u} R)) : algebra R A.X :=
{ map_zero' := A.one.map_zero,
map_one' := rfl,
map_mul' := λ x y,
begin
have h := linear_map.congr_fun A.one_mul.symm (x ⊗ₜ (A.one y)),
rwa [monoidal_category.left_unitor_hom_apply, ←A.one.map_smul] at h,
end,
commutes' := λ r a,
begin dsimp,
have h₁ := linear_map.congr_fun A.one_mul (r ⊗ₜ a),
have h₂ := linear_map.congr_fun A.mul_one (a ⊗ₜ r),
exact h₁.trans h₂.symm,
end,
smul_def' := λ r a, by { convert (linear_map.congr_fun A.one_mul (r ⊗ₜ a)).symm, simp, },
..A.one }
@[simp] lemma algebra_map (A : Mon_ (Module.{u} R)) (r : R) : algebra_map R A.X r = A.one r := rfl
/--
Converting a monoid object in `Module R` to a bundled algebra.
-/
@[simps]
def functor : Mon_ (Module.{u} R) ⥤ Algebra R :=
{ obj := λ A, Algebra.of R A.X,
map := λ A B f,
{ to_fun := f.hom,
map_one' := linear_map.congr_fun f.one_hom (1 : R),
map_mul' := λ x y, linear_map.congr_fun f.mul_hom (x ⊗ₜ y),
commutes' := λ r, linear_map.congr_fun f.one_hom r,
..(f.hom.to_add_monoid_hom) }, }.
/--
Converting a bundled algebra to a monoid object in `Module R`.
-/
@[simps]
def inverse_obj (A : Algebra.{u} R) : Mon_ (Module.{u} R) :=
{ X := Module.of R A,
one := algebra.linear_map R A,
mul := @algebra.lmul' R A _ _ _,
one_mul' :=
begin
ext x,
dsimp,
rw [algebra.lmul'_apply, monoidal_category.left_unitor_hom_apply, algebra.smul_def],
refl,
end,
mul_one' :=
begin
ext x,
dsimp,
rw [algebra.lmul'_apply, monoidal_category.right_unitor_hom_apply,
←algebra.commutes, algebra.smul_def],
refl,
end,
mul_assoc' :=
begin
ext x y z,
dsimp,
simp only [mul_assoc, algebra.lmul'_apply],
end }
/--
Converting a bundled algebra to a monoid object in `Module R`.
-/
@[simps]
def inverse : Algebra.{u} R ⥤ Mon_ (Module.{u} R) :=
{ obj := inverse_obj,
map := λ A B f,
{ hom := f.to_linear_map, }, }.
end Mon_Module_equivalence_Algebra
open Mon_Module_equivalence_Algebra
/--
The category of internal monoid objects in `Module R`
is equivalent to the category of "native" bundled `R`-algebras.
-/
def Mon_Module_equivalence_Algebra : Mon_ (Module.{u} R) ≌ Algebra R :=
{ functor := functor,
inverse := inverse,
unit_iso := nat_iso.of_components
(λ A,
{ hom := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, },
mul_hom' := by { ext, dsimp at *,
simp only [algebra.lmul'_apply, Mon_.X.ring_mul] } },
inv := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, },
mul_hom' := by { ext, dsimp at *,
simp only [algebra.lmul'_apply, Mon_.X.ring_mul]} } })
(by tidy),
counit_iso := nat_iso.of_components (λ A,
{ hom :=
{ to_fun := id,
map_zero' := rfl,
map_add' := λ x y, rfl,
map_one' := (algebra_map R A).map_one,
map_mul' := λ x y, algebra.lmul'_apply,
commutes' := λ r, rfl, },
inv :=
{ to_fun := id,
map_zero' := rfl,
map_add' := λ x y, rfl,
map_one' := (algebra_map R A).map_one.symm,
map_mul' := λ x y, algebra.lmul'_apply.symm,
commutes' := λ r, rfl } }) (by { intros, refl }), }.
/--
The equivalence `Mon_ (Module R) ≌ Algebra R`
is naturally compatible with the forgetful functors to `Module R`.
-/
def Mon_Module_equivalence_Algebra_forget :
Mon_Module_equivalence_Algebra.functor ⋙ forget₂ (Algebra.{u} R) (Module.{u} R) ≅
Mon_.forget (Module.{u} R):=
nat_iso.of_components (λ A,
{ hom :=
{ to_fun := id,
map_add' := λ x y, rfl,
map_smul' := λ c x, rfl },
inv :=
{ to_fun := id,
map_add' := λ x y, rfl,
map_smul' := λ c x, rfl }, }) (by tidy)
end Module
|
6fdf0cfef3a9856515c9726be14e7aee218dbc96 | 5ee26964f602030578ef0159d46145dd2e357ba5 | /src/for_mathlib/function.lean | d4a606475835465f60afa6526e6afbd358380cf3 | [
"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 | 417 | lean |
-- This file is PR'd to mathlib in #993
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
def function.comp₂ (f : α → β → γ) (g : γ → δ) : α → β → δ := λ x y, g (f x y)
notation g `∘₂` f := function.comp₂ f g
lemma function.uncurry_comp₂ (f : α → β → γ) (g : γ → δ) :
function.uncurry (g ∘₂ f) = (g ∘ function.uncurry f) :=
funext $ λ ⟨p, q⟩, rfl
|
93d76112b951bdcd44d0528dd7931bff0900e84c | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /src/Lean/Elab/Deriving/Repr.lean | e83b60bbb8e5d1a6327cb7363dfd4905cd4409cc | [
"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 | 5,144 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Transform
import Lean.Meta.Inductive
import Lean.Elab.Deriving.Basic
import Lean.Elab.Deriving.Util
namespace Lean.Elab.Deriving.Repr
open Lean.Parser.Term
open Meta
open Std
def mkReprHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do
let prec ← `(prec)
let header ← mkHeader ctx `Repr 1 indVal
return { header with
binders := header.binders.push (← `(explicitBinderF| (prec : Nat)))
}
def mkBodyForStruct (ctx : Context) (header : Header) (indVal : InductiveVal) : TermElabM Syntax := do
let ctorVal ← getConstInfoCtor indVal.ctors.head!
let fieldNames ← getStructureFields (← getEnv) indVal.name
let numParams := indVal.numParams
let target := mkIdent header.targetNames[0]
forallTelescopeReducing ctorVal.type fun xs _ => do
let mut fields : Syntax ← `(Format.nil)
let mut first := true
if xs.size != numParams + fieldNames.size then
throwError! "'deriving Repr' failed, unexpected number of fields in structure"
for i in [:fieldNames.size] do
let fieldName := fieldNames[i]
let fieldNameLit := Syntax.mkStrLit (toString fieldName)
let x := xs[numParams + i]
if first then
first := false
else
fields ← `($fields ++ "," ++ Format.line)
if (← isType x <||> isProof x) then
fields ← `($fields ++ $fieldNameLit ++ " := " ++ "_")
else
fields ← `($fields ++ $fieldNameLit ++ " := " ++ repr ($target.$(mkIdent fieldName):ident))
`(Format.bracket "{ " $fields:term " }")
def mkBodyForInduct (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Syntax := do
let discrs ← mkDiscrs header indVal
let alts ← mkAlts
`(match $[$discrs],* with $alts:matchAlt*)
where
mkAlts : TermElabM (Array Syntax) := do
let mut alts := #[]
for ctorName in indVal.ctors do
let ctorInfo ← getConstInfoCtor ctorName
let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do
let mut patterns := #[]
-- add `_` pattern for indices
for i in [:indVal.numIndices] do
patterns := patterns.push (← `(_))
let mut ctorArgs := #[]
let mut rhs := Syntax.mkStrLit (toString ctorInfo.name)
let mut rhs ← `(Format.text $rhs)
-- add `_` for inductive parameters, they are inaccessible
for i in [:indVal.numParams] do
ctorArgs := ctorArgs.push (← `(_))
for i in [:ctorInfo.numFields] do
let x := xs[indVal.numParams + i]
let a := mkIdent (← mkFreshUserName `a)
ctorArgs := ctorArgs.push a
if (← inferType x).isAppOf indVal.name then
rhs ← `($rhs ++ Format.line ++ $(mkIdent auxFunName):ident $a:ident maxPrec!)
else
rhs ← `($rhs ++ Format.line ++ reprArg $a)
patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*))
`(matchAltExpr| | $[$patterns:term],* => Repr.addAppParen (Format.group (Format.nest (if prec >= maxPrec! then 1 else 2) ($rhs:term))) prec)
alts := alts.push alt
return alts
def mkBody (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Syntax := do
if isStructureLike (← getEnv) indVal.name then
mkBodyForStruct ctx header indVal
else
mkBodyForInduct ctx header indVal auxFunName
def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do
let auxFunName ← ctx.auxFunNames[i]
let indVal ← ctx.typeInfos[i]
let header ← mkReprHeader ctx indVal
let mut body ← mkBody ctx header indVal auxFunName
if ctx.usePartial then
let letDecls ← mkLocalInstanceLetDecls ctx `Repr header.argNames
body ← mkLet letDecls body
let binders := header.binders
if ctx.usePartial then
`(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : Format := $body:term)
else
`(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : Format := $body:term)
def mkMutualBlock (ctx : Context) : TermElabM Syntax := do
let mut auxDefs := #[]
for i in [:ctx.typeInfos.size] do
auxDefs := auxDefs.push (← mkAuxFunction ctx i)
`(mutual
$auxDefs:command*
end)
private def mkReprInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do
let ctx ← mkContext "repr" declNames[0]
let cmds := #[← mkMutualBlock ctx] ++ (← mkInstanceCmds ctx `Repr declNames)
trace[Elab.Deriving.repr]! "\n{cmds}"
return cmds
open Command
def mkReprInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if (← declNames.allM isInductive) && declNames.size > 0 then
let cmds ← liftTermElabM none <| mkReprInstanceCmds declNames
cmds.forM elabCommand
return true
else
return false
builtin_initialize
registerBuiltinDerivingHandler `Repr mkReprInstanceHandler
registerTraceClass `Elab.Deriving.repr
end Lean.Elab.Deriving.Repr
|
7fd1fda8580a60fe1807f7c16206516cc7595196 | 5b0c53e5aaa0e60538d10f6b619a464aaf463815 | /ch6.hlean | e14d657827e5c46604477723fe3239ad4564901b | [
"Apache-2.0"
] | permissive | bbentzen/hott-book-in-lean | f845a19ef09d48d2fb813624b4650d5832a47e10 | 9e262e633e653280b9cde5d287631fcec8501f64 | refs/heads/master | 1,586,430,679,994 | 1,519,975,089,000 | 1,519,975,089,000 | 50,330,220 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,310 | hlean | /-
Copyright (c) 2016 Bruno Bentzen. All rights reserved.
Released under the Apache License 2.0 (see "License");
Theorems and exercises of the HoTT book (Chapter 6)
-/
import .ch1 .ch2 .ch3 .ch4 init.hit
open eq prod unit bool sum sigma ua funext nat lift quotient
/- ************************************** -/
/- Ch.6 Higher Inductive Types -/
/- ************************************** -/
variables {A B C X Z: Type}
universe variables i l
/- §6.1 (Introduction) -/
-- Definition of S¹
namespace circle
definition S1 : Type₀ := quotient (λ (x y : 𝟭), 𝟭)
definition base : S1 := class_of (λ (x y : 𝟭), 𝟭) ⋆
definition loop : base = base := eq_of_rel (λ (x y : 𝟭), 𝟭) ⋆
-- Notation for S¹
notation `S¹` := S1
--
/- §6.2 (Induction principles and dependent paths) -/
-- Induction principle for S¹
definition rec {P : S¹ → Type.{i}} (b : P base) (l : b =⟨loop⟩ b) (x : S¹) : P x :=
@quotient.rec 𝟭 (λ (x y : 𝟭), 𝟭) P (λ (a : 𝟭), unit.rec_on a b)
(λ a a' H, unit.rec_on H (unit.rec_on a (unit.rec_on a' (pathover_of_tr_eq l)))) x
definition apd_rec_eq_loop {P : S¹ → Type} (b : P base) (l : b =⟨loop⟩ b) :
apd (λ x, rec b l x) loop = l :=
have H : apdo (λ x, rec b l x) loop = (pathover_of_tr_eq l), from
(@quotient.rec_eq_of_rel 𝟭 (λ (x y : 𝟭), 𝟭) P (λ (a : 𝟭), unit.rec_on a b)
(λ a a' H, unit.rec_on H (unit.rec_on a (unit.rec_on a' (pathover_of_tr_eq l))))) ⋆ ⋆ ⋆,
(apdo_to_apd (λ x, rec b l x) loop)⁻¹ ⬝ ap tr_eq_of_pathover H ⬝
(@cancel_tr_pathover S¹ base base P loop b b l)
definition rec_on {P : S¹ → Type.{i}} (x : S¹) (b : P base) (l : b =⟨loop⟩ b) : P x :=
rec b l x
definition apd_rec_on_eq_loop {P : S¹ → Type} (b : P base) (l : b =⟨loop⟩ b) :
apd (λ x, rec_on x b l) loop = l :=
apd_rec_eq_loop b l
-- Lemma 6.2.5 (Non-dependent recursor)
definition ndrec (a : A) (p : a = a) (x : S¹) : A :=
@circle.rec_on (λ x, A) x a (concat (trans_const loop a) p)
definition ndrec_ap (a : A) (p : a = a) :
ap (ndrec a p) loop = p :=
have H : trans_const loop a ⬝ ap (ndrec a p) loop = trans_const loop a ⬝ p, from
(apd_eq_trans_const_ap (λ x, A) (ndrec a p) loop)⁻¹ ⬝
(@apd_rec_on_eq_loop (λ x, A) a (trans_const loop a ⬝ p)),
unwhisker_left (trans_const loop a) H
-- Lemma 6.2.8 (Uniqueness principle)
definition uniq (f g : S¹ → A) (p : f base = g base) (q : ap f loop =⟨p⟩ ap g loop) :
Π (x : S¹), f x = g x :=
λ x, rec_on x p (id_trans_fun f g loop p -- thm 2.11.3
⬝ ( (conc_assoc _ _ _)⁻¹ ⬝ (( (ap f loop)⁻¹ ⬝ₗ -- associativity
(pr1 (id_trans_equiv p (ap f loop) (ap g loop)) q)⁻¹) ⬝ -- thm 2.11.5
conc_assoc _ _ _ ⬝ (left_inv (ap f loop) ⬝ᵣ p) ⬝ (lu p)⁻¹)) ) -- cancellation (ap f loop)⁻¹
-- Universal property
definition fun_to_sig {A : Type} :
(S¹ → A) → (Σ (x : A), x = x) :=
λ g, ⟨ g base, ap g loop ⟩
definition sig_to_fun {A : Type} :
(Σ (x : A), x = x) → (S¹ → A) :=
λ w x, ndrec (pr1 w) (pr2 w) x
definition upcomp {A : Type} (w : Σ (x : A), x = x) :
fun_to_sig (sig_to_fun w) = w :=
sigma_eq ⟨ idp, ndrec_ap _ _⟩
definition upuniq {A : Type} (f : S¹ → A) :
sig_to_fun (fun_to_sig f) = f :=
funext (λ x, rec_on x idp
(show (idp =⟨loop⟩ idp), from
id_trans_fun (sig_to_fun (fun_to_sig f)) f loop idp -- thm 2.11.3
⬝ (conc_assoc (ap (sig_to_fun (fun_to_sig f)) loop)⁻¹ idp (ap f loop))⁻¹ --} cancel idp
⬝ ((ap (sig_to_fun (fun_to_sig f)) loop)⁻¹ ⬝ₗ (lu (ap f loop))⁻¹) ⬝ --}
(ap path_inv (ndrec_ap (f base) (ap f loop)) ⬝ᵣ (ap f loop)) ⬝ -- since sig_to_fun (fun_to_sig f) ▻ ndrec (f base) (ap f loop)
left_inv (ap f loop) -- _⁻¹ ⬝ _ = idp
))
-- Lemma 6.2.9 (Universal property)
definition up (A : Type) :
(S¹ → A) ≃ (Σ (x : A), x = x) :=
⟨fun_to_sig, ( ⟨sig_to_fun, upcomp⟩ , ⟨sig_to_fun, upuniq⟩ ) ⟩
end circle
--
/- §6.3 (The interval) -/
namespace interval
definition I : Type₀ := quotient (λ (x y : 𝟮), x=ff × y=tt)
definition zero : I := class_of (λ (x y : 𝟮), x=ff × y=tt) ff
definition one : I := class_of (λ (x y : 𝟮), x=ff × y=tt) tt
definition seg : zero = one := eq_of_rel (λ (x y : 𝟮), x=ff × y=tt) (idp,idp)
-- Induction principle
definition rec {P : I → Type.{i}} (b₀ : P zero) (b₁ : P one) (s : b₀ =⟨seg⟩ b₁) (x : I) : P x :=
@quotient.rec 𝟮 (λ (x y : 𝟮), x=ff × y=tt) P (λ (a : 𝟮), bool.rec_on a b₀ b₁)
(λ a a', (bool.rec_on a (bool.rec_on a' (λ H, prod.rec_on H (λ H₁ H₂, empty.rec _ (ff_ne_tt H₂)))
(λ H, prod.rec_on H (λ H₁ H₂, change_path ((λ p q, eq.rec (eq.rec (refl seg) q) p)
(bool_is_set ff ff (refl ff) H₁) (bool_is_set tt tt (refl tt) H₂)) (pathover_of_tr_eq s) ) ))
(bool.rec_on a' (λ H, prod.rec_on H (λ H₁ H₂, empty.rec _ (ff_ne_tt H₂)))
(λ H, prod.rec_on H (λ H₁ H₂, empty.rec _ (ff_ne_tt H₁⁻¹)))) ) ) x
definition apdo_rec_eq_seg {P : I → Type.{i}} (b₀ : P zero) (b₁ : P one) (s : b₀ =⟨seg⟩ b₁) :
apdo (λ x, rec b₀ b₁ s x) seg = (pathover_of_tr_eq s) :=
(@quotient.rec_eq_of_rel 𝟮 (λ (x y : 𝟮), x=ff × y=tt) P (λ (a : 𝟮), bool.rec_on a b₀ b₁)
(λ a a', (bool.rec_on a (bool.rec_on a' (λ H, prod.rec_on H (λ H₁ H₂, empty.rec _ (ff_ne_tt H₂)))
(λ H, prod.rec_on H (λ H₁ H₂, change_path ((λ p q, eq.rec (eq.rec (refl seg) q) p)
(bool_is_set ff ff (refl ff) H₁) (bool_is_set tt tt (refl tt) H₂)) (pathover_of_tr_eq s) ) ))
(bool.rec_on a' (λ H, prod.rec_on H (λ H₁ H₂, empty.rec _ (ff_ne_tt H₂)))
(λ H, prod.rec_on H (λ H₁ H₂, empty.rec _ (ff_ne_tt H₁⁻¹)))) ) ) ff tt (refl ff,refl tt)) ⬝ -- concat
(show _ = pathover_of_tr_eq s, from
(transport _ (ua (pathover_pathover_path _ _ _) )
((λ H₁ H₂, (change_path (transport _
(show refl seg = (eq.rec (refl seg) (bool_is_set tt tt (refl tt) (refl tt))), from
eq.rec_on H₁ idp)
(transport _ H₂ idp) )))
(set_is_1_type bool_is_set tt tt (refl tt) (refl tt) (refl (refl tt)) (bool_is_set tt tt (refl tt) (refl tt))) -- H₁
(set_is_1_type bool_is_set ff ff (refl ff) (refl ff) (refl (refl ff)) (bool_is_set ff ff (refl ff) (refl ff))) -- H₂
(@pathover.idpatho (zero = one) seg (λ (a : zero = one), pathover P b₀ a b₁) (pathover_of_tr_eq s)) )) )
definition apd_rec_eq_seg {P : I → Type} (b₀ : P zero) (b₁ : P one) (s : b₀ =⟨seg⟩ b₁) :
apd (λ x, rec b₀ b₁ s x) seg = s :=
(apdo_to_apd (λ x, rec b₀ b₁ s x) seg)⁻¹ ⬝ ap tr_eq_of_pathover (apdo_rec_eq_seg b₀ b₁ s) ⬝
(@cancel_tr_pathover I zero one P seg b₀ b₁ s)
definition rec_on {P : I → Type.{i}} (x : I) (b₀ : P zero) (b₁ : P one) (s : b₀ =⟨seg⟩ b₁) : P x :=
rec b₀ b₁ s x
definition apd_rec_on_eq_loop {P : I → Type} (b₀ : P zero) (b₁ : P one) (s : b₀ =⟨seg⟩ b₁) :
apd (λ x, rec_on x b₀ b₁ s) seg = s :=
apd_rec_eq_seg b₀ b₁ s
-- Lemma 6.3.1 (Interval is contractible)
definition is_contr :
isContr I :=
⟨ zero , λ x, rec_on x (refl zero) seg (eq.rec_on seg (refl (refl zero))) ⟩
-- Lemma 6.3.2
definition to_funext (f g : A → B) (p : Π (x : A), f x = g x) :
f = g :=
let p_tilde := λ x i, rec_on i (f x) (g x) (trans_const seg (f x) ⬝ p x) in
let q := λ i, rec_on i (λ x, p_tilde x i) (λ x, p_tilde x i) (trans_const seg _) in
ap q seg
-- Non-dependent recursor
definition ndrec (a₀ a₁ : A) (s : a₀ = a₁) (x : I) : A :=
@interval.rec_on (λ x, A) x a₀ a₁ (concat (trans_const seg a₀) s)
definition ndrec_ap (a₀ a₁ : A) (s : a₀ = a₁) (x : I) :
ap (ndrec a₀ a₁ s) seg = s :=
have H : trans_const seg a₀ ⬝ ap (ndrec a₀ a₁ s) seg = trans_const seg a₀ ⬝ s, from
(apd_eq_trans_const_ap (λ x, A) (ndrec a₀ a₁ s) seg)⁻¹ ⬝
((@apd_rec_on_eq_seg (λ x, A) a₀ a₁ (trans_const seg a₀ ⬝ s))),
unwhisker_left (trans_const seg a₀) H
end interval
--
/- §6.4 (Circles and spheres) -/
open circle
-- Lemma 6.4.1
definition loop_neq_refl :
loop ≠ refl base :=
begin
intro f,
apply universe_not_set,
intro A B p q,
induction q,
exact ((transport _ f (ndrec_ap A p))⁻¹ ⬝ idp)
end
-- Lemma 6.4.2
definition neq_refl :
Σ (f : Π (x : S¹), x = x), f ≠ (λ x, refl x) :=
⟨ λ x, circle.rec_on x loop (id_trans_iii loop loop ⬝ ((left_inv loop ⬝ᵣ loop) ⬝ (lu loop)⁻¹)),
λ f, loop_neq_refl ((happly f) base)⟩
-- Corollary 6.4.3
-- Due to the lack of cumulative hierarchy of universes, we will need a few lemmas about lifting
definition lift_eq (A : Type) :
A ≃ (lift A) :=
⟨up, (⟨down,up_down⟩,⟨down,down_up⟩)⟩
definition univalence_of_ua (A B : Type.{i}) :
(A = B) = (lift (A ≃ B)) :=
ua ((lift_eq (A ≃ B))⁻¹ ∘ (⟨idtoeqv, @univalence A B⟩)⁻¹)⁻¹
definition isSet_to_lift_isSet (A : Type) :
(isSet A) → (isSet (lift A)) :=
have get_ap : Π (f : isSet A) (a b : A) (p q : up a = up b), ap (up ∘ down) p = ap (up ∘ down) q, from
(λ f a b p q, (ap_func_iii down up p)⁻¹ ⬝
((ap (ap up) (f (down (up a)) (down (up b))
(ap down p) (ap down q))) ⬝ (ap_func_iii down up q) )),
λ f x y, lift.rec_on x (λ a, lift.rec_on y
(λ b p q, (ap_func_iv p)⁻¹ ⬝ (transport (λ (a : lift A → lift A), ap a p = ap a q)
(funext up_down) (get_ap f a b p q)) ⬝ (ap_func_iv q) ))
definition lift_isSet_to_isSet (A : Type) :
(isSet (lift A)) → (isSet A) :=
have get_ap : Π (f : isSet (lift A)) (x y : A) (p q : x = y), ap (down ∘ up) p = ap (down ∘ up) q, from
(λ f x y p q, (ap_func_iii up down p)⁻¹ ⬝
ap (ap down) (f (up x) (up y) (ap up p) (ap up q)) ⬝
(ap_func_iii up down q)),
λ f x y p q, (ap_func_iv p)⁻¹ ⬝ transport (λ (a : A → A), ap a p = ap a q)
(funext down_up) (get_ap f x y p q) ⬝ (ap_func_iv q)
definition neg_set_to_lift (A : Type) :
¬ (isSet A) → ¬ (isSet (lift A)) :=
λ g f, g (lift_isSet_to_isSet A f)
-- We start the proof showing the following:
definition id_circle_not_prop :
¬ isProp (id S¹ = id S¹) :=
transport (λ X, ¬ (isProp X)) (ua (⟨happly, fun_extensionality⟩)⁻¹)
(show ¬ isProp (Π (x : S¹), x = x), from
(λ f, (pr2 neq_refl) (f (pr1 neq_refl) (λ x, refl x))))
-- Lemma used below (The first projection of the dependent pair given by
-- the identity of equivalences induced by identity of functions (first projection) equals itself)
definition pr1_prop_sigma_eq_on_eqv_eq {A B : Type.{i}} (e₁ e₂ : Σ (f : A → B), isequiv f) (p : pr1 e₁ = pr1 e₂) :
pr1 (ap_sigma ((prop_sigma_eq biinv_is_prop e₁ e₂ ) p)) = p :=
begin
induction e₁ with f e, induction e₂, esimp at *,
induction (ua ⟨f,e⟩), induction p,
exact (ap pr1 (sigma_comp _))
end
definition eqv_circle_not_Set :
¬ isSet (S¹ ≃ S¹) :=
λ f, (λ g, id_circle_not_prop
(show isProp (id S¹ = id S¹), from
(λ p q,
let H := (g ((prop_sigma_eq biinv_is_prop (idtoeqv (refl S¹)) (idtoeqv (refl S¹))) p)
((prop_sigma_eq biinv_is_prop (idtoeqv (refl S¹)) (idtoeqv (refl S¹))) q)) in
let α := pr1_prop_sigma_eq_on_eqv_eq (idtoeqv (refl S¹)) (idtoeqv (refl S¹)) in
calc
p = pr1 (ap_sigma (prop_sigma_eq biinv_is_prop _ _ p)) : α p
... = pr1 (ap_sigma (prop_sigma_eq biinv_is_prop _ _ q)) : pr1 (transport (λ x, x) (ua (path_sigma _ _)) H)
... = q : α q )
) )
(f (idtoeqv (refl S¹)) (idtoeqv (refl S¹)))
-- The universe is not an 1 type
definition universe_not_1_type :
¬ is_1_Type (Type₀) :=
λ f, (transport (λ X, ¬ (isSet X)) (univalence_of_ua S¹ S¹)⁻¹ (neg_set_to_lift _ eqv_circle_not_Set)) (f S¹ S¹)
-- We define the 2-sphere using suspensions, defined in the next section,
-- For now we define ap2 and transport2
-- Lemma 6.4.4
definition ap2 (f : A → B) {x y : A} {p q : x = y} (r : p = q) :
ap f p = ap f q :=
eq.rec idp r
definition transport2 (P : A → Type) {x y : A} {p q : x = y} (r : p = q) :
transport P p = transport P q :=
eq.rec idp r
--
/- §6.5 (Suspensions) -/
namespace suspension
definition susp (A : Type) : Type := quotient (λ (x y : 𝟭+𝟭), A × (x=(@inl 𝟭 𝟭 ⋆) × y=(@inr 𝟭 𝟭 ⋆)) ) --(λ (x y : 𝟮), (x=ff × y=tt) )
definition n {A : Type} : susp A := class_of (λ (x y : 𝟭+𝟭), A × (x=(inl ⋆) × y=(inr ⋆)) ) (@inl 𝟭 𝟭 ⋆)
definition s {A : Type} : susp A := class_of (λ (x y : 𝟭+𝟭), A × (x=(inl ⋆) × y=(inr ⋆)) ) (@inr 𝟭 𝟭 ⋆)
definition merid {A : Type} (a : A) : @n A = @s A := --eq_of_rel (λ (x y : 𝟮), x=ff × y=tt) (refl ff, refl tt)
eq_of_rel (λ (x y : 𝟭+𝟭), A × (x=(inl ⋆) × y=(inr ⋆)) ) (a, (refl (inl ⋆),refl (inr ⋆)))
-- Induction principle for suspensions
definition rec {A : Type} {P : susp A → Type.{i}} (bₙ : P n) (bₛ : P s) (m : Π (a : A), bₙ =⟨merid a⟩ bₛ) (x : susp A) : P x :=
@quotient.rec (𝟭+𝟭) (λ (x y : 𝟭+𝟭), A × (x=(inl ⋆) × y=(inr ⋆)) ) P
(λ (a : 𝟭+𝟭), sum.rec_on a (λ u, unit.rec_on u bₙ) (λ u, unit.rec_on u bₛ))
begin
intro a a' H, induction H with H₁ H₂, induction a, induction a' with a',
esimp at *, induction a, induction a',
exact (empty.rec_on _ (down (pr1 (sum_equiv (inr ⋆)) (pr2 (H₂))))),
esimp at *, induction a, induction a_1,
begin
apply change_path,
exact (transport (λ (a : A × inl ⋆ = inl ⋆ × inr ⋆ = inr ⋆),
merid H₁ = eq_of_rel (λ (x y : 𝟭 + 𝟭), A × x = inl ⋆ × y = inr ⋆) a) (show (H₁, (refl (inl ⋆),refl (inr ⋆))) = (H₁,H₂),
from
pair_eq (refl H₁, (pair_eq (transport isSet (ua bool_eq_unit_unit) bool_is_set (inl ⋆) (inl ⋆) (refl (inl ⋆)) (pr1 H₂),
transport isSet (ua bool_eq_unit_unit) bool_is_set (inr ⋆) (inr ⋆) (refl (inr ⋆)) (pr2 H₂))) )
) idp),
exact (pathover_of_tr_eq (m H₁))
end,
esimp at *, induction a, induction a', induction a, esimp at *,
exact (empty.rec_on _ (down (pr1 (sum_equiv (inr ⋆)) (pr2 (H₂))))),
induction a, esimp at *,
exact (empty.rec_on _ (down (pr1 (sum_equiv (inr ⋆)) (pr1 (H₂))⁻¹ )))
end x
definition apdo_rec_eq_merid {P : susp A → Type} (bₙ : P n) (bₛ : P s) (m : Π (a : A), bₙ =⟨merid a⟩ bₛ) (a : A) :
apdo (λ x, rec bₙ bₛ m x) (merid a) = (pathover_of_tr_eq (m a)) :=
let idp_eq_pair_etc :=
pr1 (typeq_sym (path_pair idp _))
(set_is_1_type (transport isSet (ua.ua bool_eq_unit_unit) bool_is_set) (@inl 𝟭 𝟭 ⋆) (inl ⋆) (refl (inl ⋆)) (refl (inl ⋆)) idp
(transport isSet (ua bool_eq_unit_unit) bool_is_set (inl star) (inl star) (refl (inl star)) (refl (inl star)))
⬝ (prod_beta1 _)⁻¹ ,
set_is_1_type (transport isSet (ua.ua bool_eq_unit_unit) bool_is_set) (@inr 𝟭 𝟭 ⋆) (inr ⋆) (refl (inr ⋆)) (refl (inr ⋆)) idp
(transport isSet (ua bool_eq_unit_unit) bool_is_set (inr ⋆) (inr ⋆) (refl (inr ⋆)) (refl (inr ⋆))) ⬝ (prod_beta2 _)⁻¹) in
(@quotient.rec_eq_of_rel (𝟭+𝟭) (λ (x y : 𝟭+𝟭), A × (x=(inl ⋆) × y=(inr ⋆)) ) P
(λ (a : 𝟭+𝟭), sum.rec_on a (λ u, unit.rec_on u bₙ) (λ u, unit.rec_on u bₛ))
_ (@inl 𝟭 𝟭 ⋆) (@inr 𝟭 𝟭 ⋆) (a,(refl (inl ⋆), refl (inr ⋆))) ) ⬝ -- concat
(show _ = pathover_of_tr_eq (m a), from
(transport _ (ua (pathover_pathover_path _ _ _) )
(change_path
(show refl (merid a) = _, from
transport _ (idp_eq_pair_etc) idp
)
(pathover.idpatho (pathover_of_tr_eq (m a)))) )
)
definition apd_rec_eq_merid {P : susp A → Type} (bₙ : P n) (bₛ : P s) (m : Π (a : A), bₙ =⟨merid a⟩ bₛ) (a : A) :
apd (λ x, rec bₙ bₛ m x) (merid a) = m a :=
(apdo_to_apd (λ x, rec bₙ bₛ m x) (merid a))⁻¹ ⬝ ap tr_eq_of_pathover (apdo_rec_eq_merid bₙ bₛ m a) ⬝
(@cancel_tr_pathover (susp A) n s P (merid a) bₙ bₛ (m a))
definition rec_on {A : Type} {P : susp A → Type.{i}} (x : susp A) (bₙ : P n) (bₛ : P s) (m : Π (a : A), bₙ =⟨merid a⟩ bₛ) : P x :=
rec bₙ bₛ m x
definition apd_rec_on_eq_merid {P : susp A → Type} (bₙ : P n) (bₛ : P s) (m : Π (a : A), bₙ =⟨merid a⟩ bₛ) (a : A) :
apd (λ x, rec_on x bₙ bₛ m) (merid a) = m a :=
apd_rec_eq_merid bₙ bₛ m a
-- Non-dependent recursor
definition ndrec (b₀ b₁ : B) (m : Π (a : A), b₀ = b₁) (x : susp A) : B :=
@suspension.rec_on A (λ x, B) x b₀ b₁ (λ a, concat (trans_const (merid a) b₀) (m a))
definition ndrec_ap (b₀ b₁ : B) (m : Π (a : A), b₀ = b₁) (a : A) :
ap (ndrec b₀ b₁ m) (merid a) = m a :=
have H : trans_const (merid a) b₀ ⬝ ap (ndrec b₀ b₁ m) (merid a) = trans_const (merid a) b₀ ⬝ m a, from
(apd_eq_trans_const_ap (λ x, B) (ndrec b₀ b₁ m) (merid a))⁻¹ ⬝
((@apd_rec_on_eq_merid A (λ x, B) b₀ b₁ (λ a, trans_const (merid a) b₀ ⬝ m a)) a),
unwhisker_left (trans_const (merid a) b₀) H
-- Lemma 6.5.1
definition susp_bool_to_circle :
susp 𝟮 → S¹ :=
λ x, suspension.ndrec base base (λ a : 𝟮, bool.rec_on a loop (refl base)) x
definition circle_to_susp_bool :
S¹ → susp 𝟮 :=
λ x, circle.ndrec n (concat (merid ff) (merid tt)⁻¹) x
definition susp_bool_to_circle_eq :
susp 𝟮 ≃ S¹ :=
⟨susp_bool_to_circle,
(⟨circle_to_susp_bool, λ x, circle.rec_on x (refl base)
((id_trans_fun (susp_bool_to_circle ∘ circle_to_susp_bool) (id S¹) loop (refl base)) ⬝
(conc_assoc _ _ _)⁻¹ ⬝ ((ap (susp_bool_to_circle ∘ circle_to_susp_bool) loop)⁻¹ ⬝ₗ
(refl base ⬝ₗ (ap_func_iv loop)) ⬝ (lu loop)⁻¹) ⬝
((ap path_inv (((ap_func_iii circle_to_susp_bool susp_bool_to_circle loop)⁻¹ ⬝
(ap (ap susp_bool_to_circle) (circle.ndrec_ap n (merid ff ⬝ (merid tt)⁻¹))) ⬝
(ap_func_i susp_bool_to_circle (merid ff) (merid tt)⁻¹)) ⬝
((ap susp_bool_to_circle (merid ff) ⬝ₗ (ap_func_ii susp_bool_to_circle (merid tt)) ⬝
(ap path_inv (suspension.ndrec_ap base base (λ a, bool.rec_on a loop (refl base)) tt))) ⬝
(suspension.ndrec_ap base base (λ a, bool.rec_on a loop (refl base)) ff)))) ⬝ᵣ loop) ⬝ left_inv loop )
⟩,
⟨circle_to_susp_bool,
λ x, suspension.rec_on x (refl n) (merid tt) (λ b, bool.rec_on b
((id_trans_fun (circle_to_susp_bool ∘ susp_bool_to_circle) (id (susp 𝟮)) (merid ff) (refl n)) ⬝ -- ff
((((ap path_inv ((ap_func_iii susp_bool_to_circle circle_to_susp_bool (merid ff))⁻¹ ⬝
(ap (ap circle_to_susp_bool) (suspension.ndrec_ap base base (λ a, bool.rec_on a loop (refl base)) ff)) ⬝
(circle.ndrec_ap n (concat (merid ff) (merid tt)⁻¹))) ⬝
(con_inv (merid ff) (merid tt)⁻¹) ⬝ (inv_canc (merid tt) ⬝ᵣ (merid ff)⁻¹)) ⬝ᵣ (refl n)) ⬝ᵣ
(ap (id (susp 𝟮)) (merid ff))) ⬝
((ru (concat (merid tt) (merid ff)⁻¹)) ⬝ᵣ (ap (id (susp 𝟮)) (merid ff)))⁻¹ ⬝
(conc_assoc (merid tt) (merid ff)⁻¹ (ap (id (susp 𝟮)) (merid ff)))⁻¹ ⬝
((merid tt) ⬝ₗ ((merid ff)⁻¹ ⬝ₗ (ap_func_iv (merid ff)))) ⬝
(merid tt ⬝ₗ (left_inv (merid ff)))) )
((id_trans_fun (circle_to_susp_bool ∘ susp_bool_to_circle) (id (susp 𝟮)) (merid tt) (refl n)) ⬝ -- tt
((((((ap path_inv ((ap_func_iii susp_bool_to_circle circle_to_susp_bool (merid tt))⁻¹ ⬝
(ap (ap circle_to_susp_bool) (suspension.ndrec_ap base base
(λ a, bool.rec_on a loop (refl base)) tt)))) ⬝ᵣ (refl n)) ⬝
(lu (refl n))⁻¹) ⬝ᵣ (ap (id (susp 𝟮)) (merid tt)))) ⬝
(lu (ap (id (susp 𝟮)) (merid tt)))⁻¹ ⬝
ap_func_iv (merid tt)) )
) ⟩)⟩
-- n-Spheres definition
definition n_sphere : ℕ → Type₀
| n_sphere zero := 𝟮
| n_sphere (succ k) := susp (n_sphere k)
-- Lemma 6.5.3
definition Map (A : Type) (a₀ : A) (B : Type) (b₀ : B) : Type :=
Σ (f : A → B), f (a₀) = b₀
definition map_to_fun (A : Type) (B : Type) (b₀ : B) :
Map (A + 𝟭) (inr ⋆) B b₀ → (A → B) :=
λ m a, (pr1 m) (inl a)
definition fun_to_map (A : Type) (B : Type) (b₀ : B) :
(A → B) → (Map (A + 𝟭) (inr ⋆) B b₀) :=
λ f, ⟨λ x, @sum.rec_on A 𝟭 (λ (x : A + 𝟭), B) x f (λ u, b₀), (refl b₀) ⟩
definition map_eq_fun (A : Type) (B : Type) (b₀ : B) :
Map (A + 𝟭) (inr ⋆) B b₀ ≃ (A → B) :=
⟨map_to_fun A B b₀, (⟨fun_to_map A B b₀,(λ f, refl f)⟩ ,
⟨fun_to_map A B b₀ ,
λ m, sigma.rec_on m (λ f p,
sigma_eq ⟨funext (λ x, @sum.rec_on A 𝟭 (λ (x : A + 𝟭),
@sum.rec_on A 𝟭 (λ (x : A + 𝟭), B) x (λ a, f (inl a)) (λ u, b₀) = f x)
x (λ a, refl (f (inl a)) ) (λ u, unit.rec_on u p⁻¹)),
eq.rec_on p
(show (transport (λ (f' : A + 𝟭 → B), f' (inr ⋆) = f (inr ⋆))
(funext (λ (x : A + 𝟭), @sum.rec_on A 𝟭 (λ (x : A + 𝟭),
@sum.rec_on A 𝟭 (λ (x : A + 𝟭), B) x (λ a, f (inl a)) (λ u, f (inr ⋆)) = f x)
x (λ (a : A), refl (f (inl a))) (λ (u : 𝟭), unit.rec_on u (refl (f (inr star)))⁻¹ )))
(refl (f (inr ⋆)))) = refl (f (inr ⋆)), from
transport _ (show (λ (x : A + 𝟭), @sum.rec_on A 𝟭 (λ (x : A + 𝟭), B) x (λ a, f (inl a)) (λ u, f (inr ⋆)) ) = f, from
begin apply funext, intro x, cases x, esimp at *, esimp at *, induction a, reflexivity end)
(transport _ ((funext_uniq (refl _))⁻¹ ⬝
(ap funext (begin apply funext, intro x, cases x, esimp at *, induction a, esimp at * end))) idp)
)
⟩)
⟩ ) ⟩
end suspension
---------
namespace two_sphere
definition S2 : Type₀ := quotient (λ (x y : 𝟭), S¹)
definition base : S2 := class_of (λ (x y : 𝟭), S¹) ⋆
definition reflb : base = base := eq_of_rel (λ (x y : 𝟭), S¹) circle.base
definition surf_fun : S¹ → base = base := λ (x : S¹), eq_of_rel (λ (x y : 𝟭), S¹) x --(circle.ndrec circle.base loop x)
definition surf : reflb = reflb := ap surf_fun loop
-- Notation for S²
notation `S²` := S2
-- Lemma 6.4.4
definition ap2 {x y : A} (f : A → B) {p q : x = y} (r : p = q) :
ap f p = ap f q :=
eq.rec idp r
definition transport2 (P : A → Type) {x y : A} {p q : x = y} (r : p = q) :
transport P p = transport P q :=
eq.rec idp r
definition apd2 {x y : A} {P : A → Type} (f : Π (x : A), P(x)) {p q : x = y} (r : p = q) :
transport (λ (p : x = y), f x =⟨p⟩ f y) r (apd f p) = apd f q :=
eq.rec (eq.rec idp p) r
-- Induction principle for S²
definition change_fam {x y : A} {P : A → Type.{i}} {Q : A → Type.{i}} (p : x = y) (u : P x) (v : P y) (f : Π (x : A), P x → Q x)
(α : P = Q) (H : transport P p u = v) : transport Q p (f x u) = (f y v) :=
by induction p; induction α; esimp at *; apply (ap (f x) H)
definition rec {P : S² → Type.{i}} (b : P base) (l : b =⟨reflb⟩ b) (s : l =⟨surf⟩ l) (x : S²) : P x :=
@quotient.rec 𝟭 (λ (x y : 𝟭), S¹) P (λ (a : 𝟭), unit.rec_on a b)
(λ a a' H, unit.rec_on a (unit.rec_on a' (circle.rec_on H
(show pathover P b (eq_of_rel (λ (x y : 𝟭), S¹) circle.base) b, from (pathover_of_tr_eq l))
(change_fam loop l l (λ x, pathover_of_tr_eq)
(funext (λ (a : S¹), (ua (@pathover_equiv_tr_eq S² P base base (eq_of_rel (λ (x y : 𝟭), S¹) a) b b))⁻¹))
(transport (λ α, α = l) (trans_ap_fun surf_fun (λ (p : base = base), (transport P p b) = b) loop l)⁻¹ s) ) )
)) x
--
|
ada6053e28b8d2b9d89ebd4426ce9a0bde06969d | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/nat/sqrt.lean | 7a8db90724389b27a31aa5b4c672930b94d32b27 | [
"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,611 | 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, Johannes Hölzl, Mario Carneiro
-/
import data.int.basic
/-!
# Square root of natural numbers
This file defines an efficient binary implementation of the square root function that returns the
unique `r` such that `r * r ≤ n < (r + 1) * (r + 1)`. It takes advantage of the binary
representation by replacing the multiplication by 2 appearing in
`(a + b)^2 = a^2 + 2 * a * b + b^2` by a bitmask manipulation.
## Reference
See [Wikipedia, *Methods of computing square roots*]
[https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)].
-/
namespace nat
theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b :=
begin
simp only [shiftr_eq_div_pow],
apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2,
have := nat.mul_lt_mul_of_pos_left
(dec_trivial : 1 < 4) (nat.pos_of_ne_zero h),
rwa mul_one at this
end
/-- Auxiliary function for `nat.sqrt`. See e.g.
<https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)> -/
def sqrt_aux : ℕ → ℕ → ℕ → ℕ
| b r n := if b0 : b = 0 then r else
let b' := shiftr b 2 in
have b' < b, from sqrt_aux_dec b0,
match (n - (r + b : ℕ) : ℤ) with
| (n' : ℕ) := sqrt_aux b' (div2 r + b) n'
| _ := sqrt_aux b' (div2 r) n
end
/-- `sqrt n` is the square root of a natural number `n`. If `n` is not a
perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/
@[pp_nodot] def sqrt (n : ℕ) : ℕ :=
match size n with
| 0 := 0
| succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n
end
theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r :=
by rw sqrt_aux; simp
local attribute [simp] sqrt_aux_0
theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) :
sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' :=
by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false];
rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1]
theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) :
sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n :=
begin
rw sqrt_aux; simp only [h, h₂, if_false],
cases int.eq_neg_succ_of_lt_zero
(sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e,
rw [e, sqrt_aux._match_1]
end
private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1)
local attribute [-simp] mul_eq_mul_left_iff mul_eq_mul_right_iff
private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ)
(h₁ : r*r ≤ n)
(m') (hm : shiftr (2^m * 2^m) 2 = m')
(H1 : n < (r + 2^m) * (r + 2^m) →
is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r)))
(H2 : (r + 2^m) * (r + 2^m) ≤ n →
is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) :
is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) :=
begin
have b0 :=
have b0:_, from ne_of_gt (pow_pos (show 0 < 2, from dec_trivial) m),
nat.mul_ne_zero b0 b0,
have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔
n < (r+2^m)*(r+2^m), {
rw [tsub_lt_iff_right h₁],
simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc,
add_comm, add_assoc, add_left_comm] },
have re : div2 (2 * r * 2^m) = r * 2^m, {
rw [div2_val, mul_assoc,
nat.mul_div_cancel_left _ (dec_trivial:2>0)] },
cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl,
{ rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl },
{ cases le.dest hl with n' e,
rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)),
hm, re, ← right_distrib],
{ apply H2 hl },
apply eq.symm, apply tsub_eq_of_eq_add_rev,
rw [← add_assoc, (_ : r*r + _ = _)],
exact (add_tsub_cancel_of_le hl).symm,
simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_assoc] },
end
private lemma sqrt_aux_is_sqrt (n) : ∀ m r,
r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) →
is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r))
| 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl;
intro h; simp; [exact ⟨h₁, h⟩, exact ⟨h, h₂⟩]
| (m+1) r h₁ h₂ := begin
apply sqrt_aux_is_sqrt_lemma
(m+1) r n h₁ (2^m * 2^m)
(by simp [shiftr, pow_succ, div2_val, mul_comm, mul_left_comm];
repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial});
intro h,
{ have := sqrt_aux_is_sqrt m r h₁ h,
simpa [pow_succ, mul_comm, mul_assoc] },
{ rw [pow_succ', mul_two, ← add_assoc] at h₂,
have := sqrt_aux_is_sqrt m (r + 2^(m+1)) h h₂,
rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m,
by simp [pow_succ, mul_comm, mul_left_comm] }
end
private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) :=
begin
generalize e : size n = s, cases s with s; simp [e, sqrt],
{ rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial },
{ have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _),
simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by {
generalize: div2 s = x,
change bit0 x with x+x,
rw [one_shiftl, pow_add] }] at this,
apply this,
rw [← pow_add, ← mul_two], apply size_le.1,
rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1,
rw [div2_val], apply lt_succ_self }
end
theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n :=
(sqrt_is_sqrt n).left
theorem sqrt_le' (n : ℕ) : (sqrt n) ^ 2 ≤ n :=
eq.trans_le (sq (sqrt n)) (sqrt_le n)
theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) :=
(sqrt_is_sqrt n).right
theorem lt_succ_sqrt' (n : ℕ) : n < (succ (sqrt n)) ^ 2 :=
trans_rel_left (λ i j, i < j) (lt_succ_sqrt n) (sq (succ (sqrt n))).symm
theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n :=
by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n)
theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n :=
⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n),
λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $
lt_of_le_of_lt h (lt_succ_sqrt n)⟩
theorem le_sqrt' {m n : ℕ} : m ≤ sqrt n ↔ m ^ 2 ≤ n :=
by simpa only [pow_two] using le_sqrt
theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n :=
lt_iff_lt_of_le_iff_le le_sqrt
theorem sqrt_lt' {m n : ℕ} : sqrt m < n ↔ m < n ^ 2 :=
lt_iff_lt_of_le_iff_le le_sqrt'
theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n :=
le_trans (le_mul_self _) (sqrt_le n)
theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n :=
le_sqrt.2 (le_trans (sqrt_le _) h)
@[simp] lemma sqrt_zero : sqrt 0 = 0 :=
by rw [sqrt, size_zero, sqrt._match_1]
theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 :=
⟨λ h, nat.eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $
by rw [h]; exact dec_trivial,
by { rintro rfl, simp }⟩
theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) :=
⟨λ e, e.symm ▸ sqrt_is_sqrt n,
λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩
theorem eq_sqrt' {n q} : q = sqrt n ↔ q ^ 2 ≤ n ∧ n < (q+1) ^ 2 :=
by simpa only [pow_two] using eq_sqrt
theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 :=
le_of_lt_succ $ (@sqrt_lt n 2).1 $
by rw [h]; exact dec_trivial
theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n :=
sqrt_lt.2 $ by
have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h);
rwa [mul_one] at this
theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt
theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n :=
le_antisymm
(le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc];
exact lt_succ_of_le (nat.add_le_add_left h _))
(le_sqrt.2 $ nat.le_add_right _ _)
theorem sqrt_add_eq' (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n ^ 2 + a) = n :=
(congr_arg (λ i, sqrt (i + a)) (sq n)).trans (sqrt_add_eq n h)
theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n :=
sqrt_add_eq n (zero_le _)
theorem sqrt_eq' (n : ℕ) : sqrt (n ^ 2) = n :=
sqrt_add_eq' n (zero_le _)
theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ :=
le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $
le_trans (sqrt_le_add n) $ add_le_add_right
(by refine add_le_add
(nat.mul_le_mul_right _ _) _; exact nat.le_add_right _ 2) _
theorem exists_mul_self (x : ℕ) :
(∃ n, n * n = x) ↔ sqrt x * sqrt x = x :=
⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩
theorem exists_mul_self' (x : ℕ) :
(∃ n, n ^ 2 = x) ↔ (sqrt x) ^ 2 = x :=
by simpa only [pow_two] using exists_mul_self x
theorem sqrt_mul_sqrt_lt_succ (n : ℕ) : sqrt n * sqrt n < n + 1 :=
lt_succ_iff.mpr (sqrt_le _)
theorem sqrt_mul_sqrt_lt_succ' (n : ℕ) : (sqrt n) ^ 2 < n + 1 :=
lt_succ_iff.mpr (sqrt_le' _)
theorem succ_le_succ_sqrt (n : ℕ) : n + 1 ≤ (sqrt n + 1) * (sqrt n + 1) :=
le_of_pred_lt (lt_succ_sqrt _)
theorem succ_le_succ_sqrt' (n : ℕ) : n + 1 ≤ (sqrt n + 1) ^ 2 :=
le_of_pred_lt (lt_succ_sqrt' _)
/-- There are no perfect squares strictly between m² and (m+1)² -/
theorem not_exists_sq {n m : ℕ} (hl : m * m < n) (hr : n < (m + 1) * (m + 1)) :
¬ ∃ t, t * t = n :=
begin
rintro ⟨t, rfl⟩,
have h1 : m < t, from nat.mul_self_lt_mul_self_iff.mpr hl,
have h2 : t < m + 1, from nat.mul_self_lt_mul_self_iff.mpr hr,
exact (not_lt_of_ge $ le_of_lt_succ h2) h1
end
theorem not_exists_sq' {n m : ℕ} (hl : m ^ 2 < n) (hr : n < (m + 1) ^ 2) :
¬ ∃ t, t ^ 2 = n :=
by simpa only [pow_two]
using not_exists_sq (by simpa only [pow_two] using hl) (by simpa only [pow_two] using hr)
end nat
|
dbaf56a468dc8710aaa4ea11186a1f90941940e8 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/algebra/lie/submodule.lean | c540682b4aefdd4287880ccba84d414d7e0a07e3 | [
"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 | 33,328 | lean | /-
Copyright (c) 2021 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import algebra.lie.subalgebra
import ring_theory.noetherian
/-!
# Lie submodules of a Lie algebra
In this file we define Lie submodules and Lie ideals, we construct the lattice structure on Lie
submodules and we use it to define various important operations, notably the Lie span of a subset
of a Lie module.
## Main definitions
* `lie_submodule`
* `lie_submodule.well_founded_of_noetherian`
* `lie_submodule.lie_span`
* `lie_submodule.map`
* `lie_submodule.comap`
* `lie_ideal`
* `lie_ideal.map`
* `lie_ideal.comap`
## Tags
lie algebra, lie submodule, lie ideal, lattice structure
-/
universes u v w w₁ w₂
section lie_submodule
variables (R : Type u) (L : Type v) (M : Type w)
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
set_option old_structure_cmd true
/-- A Lie submodule of a Lie module is a submodule that is closed under the Lie bracket.
This is a sufficient condition for the subset itself to form a Lie module. -/
structure lie_submodule extends submodule R M :=
(lie_mem : ∀ {x : L} {m : M}, m ∈ carrier → ⁅x, m⁆ ∈ carrier)
attribute [nolint doc_blame] lie_submodule.to_submodule
namespace lie_submodule
variables {R L M} (N N' : lie_submodule R L M)
/-- The zero module is a Lie submodule of any Lie module. -/
instance : has_zero (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, by { rw ((submodule.mem_bot R).1 h), apply lie_zero, },
..(0 : submodule R M)}⟩
instance : inhabited (lie_submodule R L M) := ⟨0⟩
instance coe_submodule : has_coe (lie_submodule R L M) (submodule R M) := ⟨to_submodule⟩
@[norm_cast]
lemma coe_to_submodule : ((N : submodule R M) : set M) = N := rfl
instance has_mem : has_mem M (lie_submodule R L M) := ⟨λ x N, x ∈ (N : set M)⟩
@[simp] lemma mem_carrier {x : M} : x ∈ N.carrier ↔ x ∈ (N : set M) :=
iff.rfl
@[simp] lemma mem_mk_iff (S : set M) (h₁ h₂ h₃ h₄) {x : M} :
x ∈ (⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) ↔ x ∈ S :=
iff.rfl
@[simp] lemma mem_coe_submodule {x : M} : x ∈ (N : submodule R M) ↔ x ∈ N := iff.rfl
lemma mem_coe {x : M} : x ∈ (N : set M) ↔ x ∈ N := iff.rfl
@[simp] lemma zero_mem : (0 : M) ∈ N := (N : submodule R M).zero_mem
@[simp] lemma coe_to_set_mk (S : set M) (h₁ h₂ h₃ h₄) :
((⟨S, h₁, h₂, h₃, h₄⟩ : lie_submodule R L M) : set M) = S := rfl
@[simp] lemma coe_to_submodule_mk (p : submodule R M) (h) :
(({lie_mem := h, ..p} : lie_submodule R L M) : submodule R M) = p :=
by { cases p, refl, }
@[ext] lemma ext (h : ∀ m, m ∈ N ↔ m ∈ N') : N = N' :=
by { cases N, cases N', simp only [], ext m, exact h m, }
@[simp] lemma coe_to_submodule_eq_iff : (N : submodule R M) = (N' : submodule R M) ↔ N = N' :=
begin
split; intros h,
{ ext, rw [← mem_coe_submodule, h], simp, },
{ rw h, },
end
/-- Copy of a lie_submodule with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (s : set M) (hs : s = ↑N) : lie_submodule R L M :=
{ carrier := s,
zero_mem' := hs.symm ▸ N.zero_mem',
add_mem' := hs.symm ▸ N.add_mem',
smul_mem' := hs.symm ▸ N.smul_mem',
lie_mem := hs.symm ▸ N.lie_mem, }
instance : lie_ring_module L N :=
{ bracket := λ (x : L) (m : N), ⟨⁅x, m.val⁆, N.lie_mem m.property⟩,
add_lie := by { intros x y m, apply set_coe.ext, apply add_lie, },
lie_add := by { intros x m n, apply set_coe.ext, apply lie_add, },
leibniz_lie := by { intros x y m, apply set_coe.ext, apply leibniz_lie, }, }
instance : lie_module R L N :=
{ lie_smul := by { intros t x y, apply set_coe.ext, apply lie_smul, },
smul_lie := by { intros t x y, apply set_coe.ext, apply smul_lie, }, }
@[simp, norm_cast] lemma coe_zero : ((0 : N) : M) = (0 : M) := rfl
@[simp, norm_cast] lemma coe_add (m m' : N) : (↑(m + m') : M) = (m : M) + (m' : M) := rfl
@[simp, norm_cast] lemma coe_neg (m : N) : (↑(-m) : M) = -(m : M) := rfl
@[simp, norm_cast] lemma coe_sub (m m' : N) : (↑(m - m') : M) = (m : M) - (m' : M) := rfl
@[simp, norm_cast] lemma coe_smul (t : R) (m : N) : (↑(t • m) : M) = t • (m : M) := rfl
@[simp, norm_cast] lemma coe_bracket (x : L) (m : N) : (↑⁅x, m⁆ : M) = ⁅x, ↑m⁆ := rfl
end lie_submodule
section lie_ideal
variables (L)
/-- An ideal of a Lie algebra is a Lie submodule of the Lie algebra as a Lie module over itself. -/
abbreviation lie_ideal := lie_submodule R L L
lemma lie_mem_right (I : lie_ideal R L) (x y : L) (h : y ∈ I) : ⁅x, y⁆ ∈ I := I.lie_mem h
lemma lie_mem_left (I : lie_ideal R L) (x y : L) (h : x ∈ I) : ⁅x, y⁆ ∈ I :=
by { rw [←lie_skew, ←neg_lie], apply lie_mem_right, assumption, }
/-- An ideal of a Lie algebra is a Lie subalgebra. -/
def lie_ideal_subalgebra (I : lie_ideal R L) : lie_subalgebra R L :=
{ lie_mem' := by { intros x y hx hy, apply lie_mem_right, exact hy, },
..I.to_submodule, }
instance : has_coe (lie_ideal R L) (lie_subalgebra R L) := ⟨λ I, lie_ideal_subalgebra R L I⟩
@[norm_cast] lemma lie_ideal.coe_to_subalgebra (I : lie_ideal R L) :
((I : lie_subalgebra R L) : set L) = I := rfl
@[norm_cast] lemma lie_ideal.coe_to_lie_subalgebra_to_submodule (I : lie_ideal R L) :
((I : lie_subalgebra R L) : submodule R L) = I := rfl
end lie_ideal
variables {R M}
lemma submodule.exists_lie_submodule_coe_eq_iff (p : submodule R M) :
(∃ (N : lie_submodule R L M), ↑N = p) ↔ ∀ (x : L) (m : M), m ∈ p → ⁅x, m⁆ ∈ p :=
begin
split,
{ rintros ⟨N, rfl⟩, exact N.lie_mem, },
{ intros h, use { lie_mem := h, ..p }, exact lie_submodule.coe_to_submodule_mk p _, },
end
namespace lie_subalgebra
variables {L}
/-- Given a Lie subalgebra `K ⊆ L`, if we view `L` as a `K`-module by restriction, it contains
a distinguished Lie submodule for the action of `K`, namely `K` itself. -/
def to_lie_submodule (K : lie_subalgebra R L) : lie_submodule R K L :=
{ lie_mem := λ x y hy, K.lie_mem x.property hy,
.. (K : submodule R L) }
@[simp] lemma coe_to_lie_submodule (K : lie_subalgebra R L) :
(K.to_lie_submodule : submodule R L) = K :=
rfl
@[simp] lemma mem_to_lie_submodule {K : lie_subalgebra R L} (x : L) :
x ∈ K.to_lie_submodule ↔ x ∈ K :=
iff.rfl
lemma exists_lie_ideal_coe_eq_iff (K : lie_subalgebra R L) :
(∃ (I : lie_ideal R L), ↑I = K) ↔ ∀ (x y : L), y ∈ K → ⁅x, y⁆ ∈ K :=
begin
simp only [← coe_to_submodule_eq_iff, lie_ideal.coe_to_lie_subalgebra_to_submodule,
submodule.exists_lie_submodule_coe_eq_iff L],
exact iff.rfl,
end
lemma exists_nested_lie_ideal_coe_eq_iff {K K' : lie_subalgebra R L} (h : K ≤ K') :
(∃ (I : lie_ideal R K'), ↑I = of_le h) ↔ ∀ (x y : L), x ∈ K' → y ∈ K → ⁅x, y⁆ ∈ K :=
begin
simp only [exists_lie_ideal_coe_eq_iff, coe_bracket, mem_of_le],
split,
{ intros h' x y hx hy, exact h' ⟨x, hx⟩ ⟨y, h hy⟩ hy, },
{ rintros h' ⟨x, hx⟩ ⟨y, hy⟩ hy', exact h' x y hx hy', },
end
end lie_subalgebra
end lie_submodule
namespace lie_submodule
variables {R : Type u} {L : Type v} {M : Type w}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M]
variables [lie_ring_module L M] [lie_module R L M]
variables (N N' : lie_submodule R L M) (I J : lie_ideal R L)
section lattice_structure
open set
lemma coe_injective : function.injective (coe : lie_submodule R L M → set M) :=
λ N N' h, by { cases N, cases N', simp only, exact h, }
lemma coe_submodule_injective : function.injective (coe : lie_submodule R L M → submodule R M) :=
λ N N' h, by { ext, rw [← mem_coe_submodule, h], refl, }
instance : partial_order (lie_submodule R L M) :=
{ le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq.
..partial_order.lift (coe : lie_submodule R L M → set M) coe_injective }
lemma le_def : N ≤ N' ↔ (N : set M) ⊆ N' := iff.rfl
@[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (N : submodule R M) ≤ N' ↔ N ≤ N' :=
iff.rfl
instance : has_bot (lie_submodule R L M) := ⟨0⟩
@[simp] lemma bot_coe : ((⊥ : lie_submodule R L M) : set M) = {0} := rfl
@[simp] lemma bot_coe_submodule : ((⊥ : lie_submodule R L M) : submodule R M) = ⊥ := rfl
@[simp] lemma mem_bot (x : M) : x ∈ (⊥ : lie_submodule R L M) ↔ x = 0 := mem_singleton_iff
instance : has_top (lie_submodule R L M) :=
⟨{ lie_mem := λ x m h, mem_univ ⁅x, m⁆,
..(⊤ : submodule R M) }⟩
@[simp] lemma top_coe : ((⊤ : lie_submodule R L M) : set M) = univ := rfl
@[simp] lemma top_coe_submodule : ((⊤ : lie_submodule R L M) : submodule R M) = ⊤ := rfl
@[simp] lemma mem_top (x : M) : x ∈ (⊤ : lie_submodule R L M) := mem_univ x
instance : has_inf (lie_submodule R L M) :=
⟨λ N N', { lie_mem := λ x m h, mem_inter (N.lie_mem h.1) (N'.lie_mem h.2),
..(N ⊓ N' : submodule R M) }⟩
instance : has_Inf (lie_submodule R L M) :=
⟨λ S, { lie_mem := λ x m h, by
{ simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq,
forall_apply_eq_imp_iff₂, exists_imp_distrib] at *,
intros N hN, apply N.lie_mem (h N hN), },
..Inf {(s : submodule R M) | s ∈ S} }⟩
@[simp] theorem inf_coe : (↑(N ⊓ N') : set M) = N ∩ N' := rfl
@[simp] lemma Inf_coe_to_submodule (S : set (lie_submodule R L M)) :
(↑(Inf S) : submodule R M) = Inf {(s : submodule R M) | s ∈ S} := rfl
@[simp] lemma Inf_coe (S : set (lie_submodule R L M)) : (↑(Inf S) : set M) = ⋂ s ∈ S, (s : set M) :=
begin
rw [← lie_submodule.coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe],
ext m,
simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib],
end
lemma Inf_glb (S : set (lie_submodule R L M)) : is_glb S (Inf S) :=
begin
have h : ∀ (N N' : lie_submodule R L M), (N : set M) ≤ N' ↔ N ≤ N', { intros, refl },
apply is_glb.of_image h,
simp only [Inf_coe],
exact is_glb_binfi
end
/-- The set of Lie submodules of a Lie module form a complete lattice.
We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions
than we would otherwise obtain from `complete_lattice_of_Inf`. -/
instance : complete_lattice (lie_submodule R L M) :=
{ bot := ⊥,
bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', },
top := ⊤,
le_top := λ _ _ _, trivial,
inf := (⊓),
le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩,
inf_le_left := λ _ _ _, and.left,
inf_le_right := λ _ _ _, and.right,
..complete_lattice_of_Inf _ Inf_glb }
instance : add_comm_monoid (lie_submodule R L M) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm, }
@[simp] lemma add_eq_sup : N + N' = N ⊔ N' := rfl
@[norm_cast, simp] lemma sup_coe_to_submodule :
(↑(N ⊔ N') : submodule R M) = (N : submodule R M) ⊔ (N' : submodule R M) :=
begin
have aux : ∀ (x : L) m, m ∈ (N ⊔ N' : submodule R M) → ⁅x,m⁆ ∈ (N ⊔ N' : submodule R M),
{ simp only [submodule.mem_sup],
rintro x m ⟨y, hy, z, hz, rfl⟩,
refine ⟨⁅x, y⁆, N.lie_mem hy, ⁅x, z⁆, N'.lie_mem hz, (lie_add _ _ _).symm⟩ },
refine le_antisymm (Inf_le ⟨{ lie_mem := aux, ..(N ⊔ N' : submodule R M) }, _⟩) _,
{ simp only [exists_prop, and_true, mem_set_of_eq, eq_self_iff_true, coe_to_submodule_mk,
← coe_submodule_le_coe_submodule, and_self, le_sup_left, le_sup_right] },
{ simp, },
end
@[norm_cast, simp] lemma inf_coe_to_submodule :
(↑(N ⊓ N') : submodule R M) = (N : submodule R M) ⊓ (N' : submodule R M) := rfl
@[simp] lemma mem_inf (x : M) : x ∈ N ⊓ N' ↔ x ∈ N ∧ x ∈ N' :=
by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule,
submodule.mem_inf]
lemma mem_sup (x : M) : x ∈ N ⊔ N' ↔ ∃ (y ∈ N) (z ∈ N'), y + z = x :=
by { rw [← mem_coe_submodule, sup_coe_to_submodule, submodule.mem_sup], exact iff.rfl, }
lemma eq_bot_iff : N = ⊥ ↔ ∀ (m : M), m ∈ N → m = 0 :=
by { rw eq_bot_iff, exact iff.rfl, }
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_submodule R L ↥(⊥ : lie_submodule R L M)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
instance : is_modular_lattice (lie_submodule R L M) :=
{ sup_inf_le_assoc_of_le := λ N₁ N₂ N₃,
by { simp only [← coe_submodule_le_coe_submodule, sup_coe_to_submodule, inf_coe_to_submodule],
exact is_modular_lattice.sup_inf_le_assoc_of_le ↑N₂, }, }
variables (R L M)
lemma well_founded_of_noetherian [is_noetherian R M] :
well_founded ((>) : lie_submodule R L M → lie_submodule R L M → Prop) :=
begin
let f : ((>) : lie_submodule R L M → lie_submodule R L M → Prop) →r
((>) : submodule R M → submodule R M → Prop) :=
{ to_fun := coe,
map_rel' := λ N N' h, h, },
apply f.well_founded, rw ← is_noetherian_iff_well_founded, apply_instance,
end
@[simp] lemma subsingleton_iff : subsingleton (lie_submodule R L M) ↔ subsingleton M :=
have h : subsingleton (lie_submodule R L M) ↔ subsingleton (submodule R M),
{ rw [← subsingleton_iff_bot_eq_top, ← subsingleton_iff_bot_eq_top, ← coe_to_submodule_eq_iff,
top_coe_submodule, bot_coe_submodule], },
h.trans $ submodule.subsingleton_iff R
@[simp] lemma nontrivial_iff : nontrivial (lie_submodule R L M) ↔ nontrivial M :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R L M).trans
not_nontrivial_iff_subsingleton.symm)
instance [nontrivial M] : nontrivial (lie_submodule R L M) := (nontrivial_iff R L M).mpr ‹_›
variables {R L M}
section inclusion_maps
/-- The inclusion of a Lie submodule into its ambient space is a morphism of Lie modules. -/
def incl : N →ₗ⁅R,L⁆ M :=
{ map_lie' := λ x m, rfl,
..submodule.subtype (N : submodule R M) }
@[simp] lemma incl_apply (m : N) : N.incl m = m := rfl
lemma incl_eq_val : (N.incl : N → M) = subtype.val := rfl
variables {N N'} (h : N ≤ N')
/-- Given two nested Lie submodules `N ⊆ N'`, the inclusion `N ↪ N'` is a morphism of Lie modules.-/
def hom_of_le : N →ₗ⁅R,L⁆ N' :=
{ map_lie' := λ x m, rfl,
..submodule.of_le h }
@[simp] lemma coe_hom_of_le (m : N) : (hom_of_le h m : M) = m := rfl
lemma hom_of_le_apply (m : N) : hom_of_le h m = ⟨m.1, h m.2⟩ := rfl
lemma hom_of_le_injective : function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
end inclusion_maps
section lie_span
variables (R L) (s : set M)
/-- The `lie_span` of a set `s ⊆ M` is the smallest Lie submodule of `M` that contains `s`. -/
def lie_span : lie_submodule R L M := Inf {N | s ⊆ N}
variables {R L s}
lemma mem_lie_span {x : M} : x ∈ lie_span R L s ↔ ∀ N : lie_submodule R L M, s ⊆ N → x ∈ N :=
by { change x ∈ (lie_span R L s : set M) ↔ _, erw Inf_coe, exact mem_bInter_iff, }
lemma subset_lie_span : s ⊆ lie_span R L s :=
by { intros m hm, erw mem_lie_span, intros N hN, exact hN hm, }
lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s :=
by { rw submodule.span_le, apply subset_lie_span, }
lemma lie_span_le {N} : lie_span R L s ≤ N ↔ s ⊆ N :=
begin
split,
{ exact subset.trans subset_lie_span, },
{ intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, },
end
lemma lie_span_mono {t : set M} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t :=
by { rw lie_span_le, exact subset.trans h subset_lie_span, }
lemma lie_span_eq : lie_span R L (N : set M) = N :=
le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span
lemma coe_lie_span_submodule_eq_iff {p : submodule R M} :
(lie_span R L (p : set M) : submodule R M) = p ↔ ∃ (N : lie_submodule R L M), ↑N = p :=
begin
rw p.exists_lie_submodule_coe_eq_iff L, split; intros h,
{ intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), },
{ rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], },
end
variables (R L M)
/-- `lie_span` forms a Galois insertion with the coercion from `lie_submodule` to `set`. -/
protected def gi : galois_insertion (lie_span R L : set M → lie_submodule R L M) coe :=
{ choice := λ s _, lie_span R L s,
gc := λ s t, lie_span_le,
le_l_u := λ s, subset_lie_span,
choice_eq := λ s h, rfl }
@[simp] lemma span_empty : lie_span R L (∅ : set M) = ⊥ :=
(lie_submodule.gi R L M).gc.l_bot
@[simp] lemma span_univ : lie_span R L (set.univ : set M) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span
variables {M}
lemma span_union (s t : set M) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t :=
(lie_submodule.gi R L M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) :=
(lie_submodule.gi R L M).gc.l_supr
end lie_span
end lattice_structure
end lie_submodule
section lie_submodule_map_and_comap
variables {R : Type u} {L : Type v} {L' : Type w₂} {M : Type w} {M' : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L] [lie_ring L'] [lie_algebra R L']
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group M'] [module R M'] [lie_ring_module L M'] [lie_module R L M']
namespace lie_submodule
variables (f : M →ₗ⁅R,L⁆ M') (N N₂ : lie_submodule R L M) (N' : lie_submodule R L M')
/-- A morphism of Lie modules `f : M → M'` pushes forward Lie submodules of `M` to Lie submodules
of `M'`. -/
def map : lie_submodule R L M' :=
{ lie_mem := λ x m' h, by
{ rcases h with ⟨m, hm, hfm⟩, use ⁅x, m⁆, split,
{ apply N.lie_mem hm, },
{ norm_cast at hfm, simp [hfm], }, },
..(N : submodule R M).map (f : M →ₗ[R] M') }
/-- A morphism of Lie modules `f : M → M'` pulls back Lie submodules of `M'` to Lie submodules of
`M`. -/
def comap : lie_submodule R L M :=
{ lie_mem := λ x m h, by { suffices : ⁅x, f m⁆ ∈ N', { simp [this], }, apply N'.lie_mem h, },
..(N' : submodule R M').comap (f : M →ₗ[R] M') }
variables {f N N₂ N'}
lemma map_le_iff_le_comap : map f N ≤ N' ↔ N ≤ comap f N' :=
set.image_subset_iff
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ N N', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (N ⊔ N₂).map f = N.map f ⊔ N₂.map f :=
(gc_map_comap f).l_sup
lemma mem_map (m' : M') : m' ∈ N.map f ↔ ∃ m, m ∈ N ∧ f m = m' :=
submodule.mem_map
@[simp] lemma mem_comap {m : M} : m ∈ comap f N' ↔ f m ∈ N' := iff.rfl
end lie_submodule
namespace lie_ideal
variables (f : L →ₗ⁅R⁆ L') (I I₂ : lie_ideal R L) (J : lie_ideal R L')
@[simp] lemma top_coe_lie_subalgebra : ((⊤ : lie_ideal R L) : lie_subalgebra R L) = ⊤ := rfl
/-- A morphism of Lie algebras `f : L → L'` pushes forward Lie ideals of `L` to Lie ideals of `L'`.
Note that unlike `lie_submodule.map`, we must take the `lie_span` of the image. Mathematically
this is because although `f` makes `L'` into a Lie module over `L`, in general the `L` submodules of
`L'` are not the same as the ideals of `L'`. -/
def map : lie_ideal R L' := lie_submodule.lie_span R L' $ (I : submodule R L).map (f : L →ₗ[R] L')
/-- A morphism of Lie algebras `f : L → L'` pulls back Lie ideals of `L'` to Lie ideals of `L`.
Note that `f` makes `L'` into a Lie module over `L` (turning `f` into a morphism of Lie modules)
and so this is a special case of `lie_submodule.comap` but we do not exploit this fact. -/
def comap : lie_ideal R L :=
{ lie_mem := λ x y h, by { suffices : ⁅f x, f y⁆ ∈ J, { simp [this], }, apply J.lie_mem h, },
..(J : submodule R L').comap (f : L →ₗ[R] L') }
@[simp] lemma map_coe_submodule (h : ↑(map f I) = f '' I) :
(map f I : submodule R L') = (I : submodule R L).map f :=
by { rw [set_like.ext'_iff, lie_submodule.coe_to_submodule, h, submodule.map_coe], refl, }
@[simp] lemma comap_coe_submodule : (comap f J : submodule R L) = (J : submodule R L').comap f :=
rfl
lemma map_le : map f I ≤ J ↔ f '' I ⊆ J := lie_submodule.lie_span_le
variables {f I I₂ J}
lemma mem_map {x : L} (hx : x ∈ I) : f x ∈ map f I :=
by { apply lie_submodule.subset_lie_span, use x, exact ⟨hx, rfl⟩, }
@[simp] lemma mem_comap {x : L} : x ∈ comap f J ↔ f x ∈ J := iff.rfl
lemma map_le_iff_le_comap : map f I ≤ J ↔ I ≤ comap f J :=
by { rw map_le, exact set.image_subset_iff, }
variables (f)
lemma gc_map_comap : galois_connection (map f) (comap f) :=
λ I I', map_le_iff_le_comap
variables {f}
@[simp] lemma map_sup : (I ⊔ I₂).map f = I.map f ⊔ I₂.map f :=
(gc_map_comap f).l_sup
lemma map_comap_le : map f (comap f J) ≤ J :=
by { rw map_le_iff_le_comap, apply le_refl _, }
/-- See also `lie_ideal.map_comap_eq`. -/
lemma comap_map_le : I ≤ comap f (map f I) :=
by { rw ← map_le_iff_le_comap, apply le_refl _, }
@[mono] lemma map_mono : monotone (map f) :=
λ I₁ I₂ h,
by { rw lie_submodule.le_def at h, apply lie_submodule.lie_span_mono (set.image_subset ⇑f h), }
@[mono] lemma comap_mono : monotone (comap f) :=
λ J₁ J₂ h, by { rw lie_submodule.le_def at h ⊢, exact set.preimage_mono h, }
lemma map_of_image (h : f '' I = J) : I.map f = J :=
begin
apply le_antisymm,
{ erw [lie_submodule.lie_span_le, submodule.map_coe, h], },
{ rw [lie_submodule.le_def, ← h], exact lie_submodule.subset_lie_span, },
end
/-- Note that this is not a special case of `lie_submodule.subsingleton_of_bot`. Indeed, given
`I : lie_ideal R L`, in general the two lattices `lie_ideal R I` and `lie_submodule R L I` are
different (though the latter does naturally inject into the former).
In other words, in general, ideals of `I`, regarded as a Lie algebra in its own right, are not the
same as ideals of `L` contained in `I`. -/
-- TODO[gh-6025]: make this an instance once safe to do so
lemma subsingleton_of_bot : subsingleton (lie_ideal R ↥(⊥ : lie_ideal R L)) :=
begin
apply subsingleton_of_bot_eq_top,
ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx,
simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, lie_submodule.mem_bot],
end
end lie_ideal
namespace lie_hom
variables (f : L →ₗ⁅R⁆ L') (I : lie_ideal R L) (J : lie_ideal R L')
/-- The kernel of a morphism of Lie algebras, as an ideal in the domain. -/
def ker : lie_ideal R L := lie_ideal.comap f ⊥
/-- The range of a morphism of Lie algebras as an ideal in the codomain. -/
def ideal_range : lie_ideal R L' := lie_submodule.lie_span R L' f.range
lemma ideal_range_eq_lie_span_range :
f.ideal_range = lie_submodule.lie_span R L' f.range := rfl
lemma ideal_range_eq_map :
f.ideal_range = lie_ideal.map f ⊤ :=
by { ext, simp only [ideal_range, range_eq_map], refl }
/-- The condition that the image of a morphism of Lie algebras is an ideal. -/
def is_ideal_morphism : Prop := (f.ideal_range : lie_subalgebra R L') = f.range
@[simp] lemma is_ideal_morphism_def :
f.is_ideal_morphism ↔ (f.ideal_range : lie_subalgebra R L') = f.range := iff.rfl
lemma is_ideal_morphism_iff :
f.is_ideal_morphism ↔ ∀ (x : L') (y : L), ∃ (z : L), ⁅x, f y⁆ = f z :=
begin
simp only [is_ideal_morphism_def, ideal_range_eq_lie_span_range,
← lie_subalgebra.coe_to_submodule_eq_iff, ← f.range.coe_to_submodule,
lie_ideal.coe_to_lie_subalgebra_to_submodule, lie_submodule.coe_lie_span_submodule_eq_iff,
lie_subalgebra.mem_coe_submodule, mem_range, exists_imp_distrib,
submodule.exists_lie_submodule_coe_eq_iff],
split,
{ intros h x y, obtain ⟨z, hz⟩ := h x (f y) y rfl, use z, exact hz.symm, },
{ intros h x y z hz, obtain ⟨w, hw⟩ := h x z, use w, rw [← hw, hz], },
end
lemma range_subset_ideal_range : (f.range : set L') ⊆ f.ideal_range := lie_submodule.subset_lie_span
lemma map_le_ideal_range : I.map f ≤ f.ideal_range :=
begin
rw f.ideal_range_eq_map,
exact lie_ideal.map_mono le_top,
end
lemma ker_le_comap : f.ker ≤ J.comap f := lie_ideal.comap_mono bot_le
@[simp] lemma ker_coe_submodule : (ker f : submodule R L) = (f : L →ₗ[R] L').ker := rfl
@[simp] lemma mem_ker {x : L} : x ∈ ker f ↔ f x = 0 :=
show x ∈ (f.ker : submodule R L) ↔ _,
by simp only [ker_coe_submodule, linear_map.mem_ker, coe_to_linear_map]
lemma mem_ideal_range {x : L} : f x ∈ ideal_range f :=
begin
rw ideal_range_eq_map,
exact lie_ideal.mem_map (lie_submodule.mem_top x)
end
@[simp] lemma mem_ideal_range_iff (h : is_ideal_morphism f) {y : L'} :
y ∈ ideal_range f ↔ ∃ (x : L), f x = y :=
begin
rw f.is_ideal_morphism_def at h,
rw [← lie_submodule.mem_coe, ← lie_ideal.coe_to_subalgebra, h, f.range_coe, set.mem_range],
end
lemma le_ker_iff : I ≤ f.ker ↔ ∀ x, x ∈ I → f x = 0 :=
begin
split; intros h x hx,
{ specialize h hx, rw mem_ker at h, exact h, },
{ rw mem_ker, apply h x hx, },
end
lemma ker_eq_bot : f.ker = ⊥ ↔ function.injective f :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, ker_coe_submodule, lie_submodule.bot_coe_submodule,
linear_map.ker_eq_bot, coe_to_linear_map]
@[simp] lemma range_coe_submodule : (f.range : submodule R L') = (f : L →ₗ[R] L').range := rfl
lemma range_eq_top : f.range = ⊤ ↔ function.surjective f :=
begin
rw [← lie_subalgebra.coe_to_submodule_eq_iff, range_coe_submodule,
lie_subalgebra.top_coe_submodule],
exact linear_map.range_eq_top,
end
@[simp] lemma ideal_range_eq_top_of_surjective (h : function.surjective f) : f.ideal_range = ⊤ :=
begin
rw ← f.range_eq_top at h,
rw [ideal_range_eq_lie_span_range, h, ← lie_subalgebra.coe_to_submodule,
← lie_submodule.coe_to_submodule_eq_iff, lie_submodule.top_coe_submodule,
lie_subalgebra.top_coe_submodule, lie_submodule.coe_lie_span_submodule_eq_iff],
use ⊤,
exact lie_submodule.top_coe_submodule,
end
lemma is_ideal_morphism_of_surjective (h : function.surjective f) : f.is_ideal_morphism :=
by rw [is_ideal_morphism_def, f.ideal_range_eq_top_of_surjective h, f.range_eq_top.mpr h,
lie_ideal.top_coe_lie_subalgebra]
end lie_hom
namespace lie_ideal
variables {f : L →ₗ⁅R⁆ L'} {I : lie_ideal R L} {J : lie_ideal R L'}
@[simp] lemma map_eq_bot_iff : I.map f = ⊥ ↔ I ≤ f.ker :=
by { rw ← le_bot_iff, exact lie_ideal.map_le_iff_le_comap }
lemma coe_map_of_surjective (h : function.surjective f) :
(I.map f : submodule R L') = (I : submodule R L).map f :=
begin
let J : lie_ideal R L' :=
{ lie_mem := λ x y hy,
begin
have hy' : ∃ (x : L), x ∈ I ∧ f x = y, { simpa [hy], },
obtain ⟨z₂, hz₂, rfl⟩ := hy',
obtain ⟨z₁, rfl⟩ := h x,
simp only [lie_hom.coe_to_linear_map, set_like.mem_coe, set.mem_image,
lie_submodule.mem_coe_submodule, submodule.mem_carrier, submodule.map_coe],
use ⁅z₁, z₂⁆,
exact ⟨I.lie_mem hz₂, f.map_lie z₁ z₂⟩,
end,
..(I : submodule R L).map (f : L →ₗ[R] L'), },
erw lie_submodule.coe_lie_span_submodule_eq_iff,
use J,
apply lie_submodule.coe_to_submodule_mk,
end
lemma mem_map_of_surjective {y : L'} (h₁ : function.surjective f) (h₂ : y ∈ I.map f) :
∃ (x : I), f x = y :=
begin
rw [← lie_submodule.mem_coe_submodule, coe_map_of_surjective h₁, submodule.mem_map] at h₂,
obtain ⟨x, hx, rfl⟩ := h₂,
use ⟨x, hx⟩,
refl,
end
lemma bot_of_map_eq_bot {I : lie_ideal R L} (h₁ : function.injective f) (h₂ : I.map f = ⊥) :
I = ⊥ :=
begin
rw ← f.ker_eq_bot at h₁, change comap f ⊥ = ⊥ at h₁,
rw [eq_bot_iff, map_le_iff_le_comap, h₁] at h₂,
rw eq_bot_iff, exact h₂,
end
/-- Given two nested Lie ideals `I₁ ⊆ I₂`, the inclusion `I₁ ↪ I₂` is a morphism of Lie algebras. -/
def hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) : I₁ →ₗ⁅R⁆ I₂ :=
{ map_lie' := λ x y, rfl,
..submodule.of_le h, }
@[simp] lemma coe_hom_of_le {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
(hom_of_le h x : L) = x := rfl
lemma hom_of_le_apply {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) (x : I₁) :
hom_of_le h x = ⟨x.1, h x.2⟩ := rfl
lemma hom_of_le_injective {I₁ I₂ : lie_ideal R L} (h : I₁ ≤ I₂) :
function.injective (hom_of_le h) :=
λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe,
subtype.val_eq_coe]
@[simp] lemma map_sup_ker_eq_map : lie_ideal.map f (I ⊔ f.ker) = lie_ideal.map f I :=
begin
suffices : lie_ideal.map f (I ⊔ f.ker) ≤ lie_ideal.map f I,
{ exact le_antisymm this (lie_ideal.map_mono le_sup_left), },
apply lie_submodule.lie_span_mono,
rintros x ⟨y, hy₁, hy₂⟩, rw ← hy₂,
erw lie_submodule.mem_sup at hy₁, obtain ⟨z₁, hz₁, z₂, hz₂, hy⟩ := hy₁, rw ← hy,
rw [f.coe_to_linear_map, f.map_add, f.mem_ker.mp hz₂, add_zero], exact ⟨z₁, hz₁, rfl⟩,
end
@[simp] lemma map_comap_eq (h : f.is_ideal_morphism) : map f (comap f J) = f.ideal_range ⊓ J :=
begin
apply le_antisymm,
{ rw le_inf_iff, exact ⟨f.map_le_ideal_range _, map_comap_le⟩, },
{ rw f.is_ideal_morphism_def at h,
rw [lie_submodule.le_def, lie_submodule.inf_coe, ← coe_to_subalgebra, h],
rintros y ⟨⟨x, h₁⟩, h₂⟩, rw ← h₁ at h₂ ⊢, exact mem_map h₂, },
end
@[simp] lemma comap_map_eq (h : ↑(map f I) = f '' I) : comap f (map f I) = I ⊔ f.ker :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, comap_coe_submodule, I.map_coe_submodule f h,
lie_submodule.sup_coe_to_submodule, f.ker_coe_submodule, submodule.comap_map_eq]
variables (f I J)
/-- Regarding an ideal `I` as a subalgebra, the inclusion map into its ambient space is a morphism
of Lie algebras. -/
def incl : I →ₗ⁅R⁆ L := (I : lie_subalgebra R L).incl
@[simp] lemma incl_range : I.incl.range = I := (I : lie_subalgebra R L).incl_range
@[simp] lemma incl_apply (x : I) : I.incl x = x := rfl
@[simp] lemma incl_coe : (I.incl : I →ₗ[R] L) = (I : submodule R L).subtype := rfl
@[simp] lemma comap_incl_self : comap I.incl I = ⊤ :=
by { rw ← lie_submodule.coe_to_submodule_eq_iff, exact submodule.comap_subtype_self _, }
@[simp] lemma ker_incl : I.incl.ker = ⊥ :=
by rw [← lie_submodule.coe_to_submodule_eq_iff, I.incl.ker_coe_submodule,
lie_submodule.bot_coe_submodule, incl_coe, submodule.ker_subtype]
@[simp] lemma incl_ideal_range : I.incl.ideal_range = I :=
begin
rw [lie_hom.ideal_range_eq_lie_span_range, ← lie_subalgebra.coe_to_submodule,
← lie_submodule.coe_to_submodule_eq_iff, incl_range, coe_to_lie_subalgebra_to_submodule,
lie_submodule.coe_lie_span_submodule_eq_iff],
use I,
end
lemma incl_is_ideal_morphism : I.incl.is_ideal_morphism :=
begin
rw [I.incl.is_ideal_morphism_def, incl_ideal_range],
exact (I : lie_subalgebra R L).incl_range.symm,
end
end lie_ideal
end lie_submodule_map_and_comap
namespace lie_module_hom
variables {R : Type u} {L : Type v} {M : Type w} {N : Type w₁}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M]
variables [add_comm_group N] [module R N] [lie_ring_module L N] [lie_module R L N]
variables (f : M →ₗ⁅R,L⁆ N)
/-- The range of a morphism of Lie modules `f : M → N` is a Lie submodule of `N`.
See Note [range copy pattern]. -/
def range : lie_submodule R L N :=
(lie_submodule.map f ⊤).copy (set.range f) set.image_univ.symm
@[simp] lemma coe_range : (f.range : set N) = set.range f := rfl
@[simp] lemma coe_submodule_range : (f.range : submodule R N) = (f : M →ₗ[R] N).range := rfl
@[simp] lemma mem_range (n : N) : n ∈ f.range ↔ ∃ m, f m = n :=
iff.rfl
lemma map_top : lie_submodule.map f ⊤ = f.range :=
by { ext, simp [lie_submodule.mem_map], }
end lie_module_hom
section top_equiv_self
variables {R : Type u} {L : Type v}
variables [comm_ring R] [lie_ring L] [lie_algebra R L]
/-- The natural equivalence between the 'top' Lie subalgebra and the enclosing Lie algebra. -/
def lie_subalgebra.top_equiv_self : (⊤ : lie_subalgebra R L) ≃ₗ⁅R⁆ L :=
{ inv_fun := λ x, ⟨x, set.mem_univ x⟩,
left_inv := λ x, by { ext, refl, },
right_inv := λ x, rfl,
..(⊤ : lie_subalgebra R L).incl, }
@[simp] lemma lie_subalgebra.top_equiv_self_apply (x : (⊤ : lie_subalgebra R L)) :
lie_subalgebra.top_equiv_self x = x := rfl
/-- The natural equivalence between the 'top' Lie ideal and the enclosing Lie algebra. -/
def lie_ideal.top_equiv_self : (⊤ : lie_ideal R L) ≃ₗ⁅R⁆ L :=
lie_subalgebra.top_equiv_self
@[simp] lemma lie_ideal.top_equiv_self_apply (x : (⊤ : lie_ideal R L)) :
lie_ideal.top_equiv_self x = x := rfl
end top_equiv_self
|
a96dc2956cb12f7a600e4277b1c28eaa4d4a3738 | ee8cdbabf07f77e7be63a449b8483ce308d37218 | /lean/src/test/mathd-algebra-139.lean | eb7900b95de551f3073cc938c40e22bc0aaeffd8 | [
"MIT",
"Apache-2.0"
] | permissive | zeta1999/miniF2F | 6d66c75d1c18152e224d07d5eed57624f731d4b7 | c1ba9629559c5273c92ec226894baa0c1ce27861 | refs/heads/main | 1,681,897,460,642 | 1,620,646,361,000 | 1,620,646,361,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 298 | lean | /-
Copyright (c) 2021 OpenAI. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kunhao Zheng
-/
import data.real.basic
example (s : ℝ → ℝ → ℝ) (h₀ : ∀ x≠0, ∀y≠0, s x y = (1/y - 1/x) / (x-y) ) : s 3 11 = 1/33 :=
begin
sorry
end
|
6173da71bab1c4f16e7b50da940d7b94e9b563b8 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/order/directed.lean | 82202a1e553e6aa5e4adb77a27c7b0c0a7cba045 | [
"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 | 3,655 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import order.lattice
import data.set.basic
/-!
# Directed indexed families and sets
This file defines directed indexed families and directed sets. An indexed family/set is
directed iff each pair of elements has a shared upper bound.
## Main declarations
* `directed r f`: Predicate stating that the indexed family `f` is `r`-directed.
* `directed_on r s`: Predicate stating that the set `s` is `r`-directed.
* `directed_order α`: Typeclass extending `preorder` for stating that `α` is `≤`-directed.
-/
universes u v w
variables {α : Type u} {β : Type v} {ι : Sort w} (r : α → α → Prop)
local infix ` ≼ ` : 50 := r
/-- A family of elements of α is directed (with respect to a relation `≼` on α)
if there is a member of the family `≼`-above any pair in the family. -/
def directed (f : ι → α) := ∀ x y, ∃ z, f x ≼ f z ∧ f y ≼ f z
/-- A subset of α is directed if there is an element of the set `≼`-above any
pair of elements in the set. -/
def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃ z ∈ s, x ≼ z ∧ y ≼ z
variables {r}
theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) :=
by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl)
alias directed_on_iff_directed ↔ directed_on.directed_coe _
theorem directed_on_image {s} {f : β → α} :
directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s :=
by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage]
theorem directed_on.mono {s : set α} (h : directed_on r s)
{r' : α → α → Prop} (H : ∀ {a b}, r a b → r' a b) :
directed_on r' s :=
λ x hx y hy, let ⟨z, zs, xz, yz⟩ := h x hx y hy in ⟨z, zs, H xz, H yz⟩
theorem directed_comp {ι} {f : ι → β} {g : β → α} :
directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl
theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α}
(H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f :=
λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩
theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α}
(hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) :
directed rb (g ∘ f) :=
directed_comp.2 $ hf.mono hg
/-- A monotone function on a sup-semilattice is directed. -/
lemma directed_of_sup [semilattice_sup α] {f : α → β} {r : β → β → Prop}
(H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : directed r f :=
λ a b, ⟨a ⊔ b, H le_sup_left, H le_sup_right⟩
lemma monotone.directed_le [semilattice_sup α] [preorder β] {f : α → β} :
monotone f → directed (≤) f :=
directed_of_sup
/-- An antimonotone function on an inf-semilattice is directed. -/
lemma directed_of_inf [semilattice_inf α] {r : β → β → Prop} {f : α → β}
(hf : ∀ a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f :=
λ x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩
/-- A `preorder` is a `directed_order` if for any two elements `i`, `j`
there is an element `k` such that `i ≤ k` and `j ≤ k`. -/
class directed_order (α : Type u) extends preorder α :=
(directed : ∀ i j : α, ∃ k, i ≤ k ∧ j ≤ k)
@[priority 100] -- see Note [lower instance priority]
instance linear_order.to_directed_order (α) [linear_order α] : directed_order α :=
⟨λ i j, or.cases_on (le_total i j) (λ hij, ⟨j, hij, le_refl j⟩) (λ hji, ⟨i, le_refl i, hji⟩)⟩
|
cbccd5b6f2bddf919bc997fb50adbab7b075fd4f | 1fd908b06e3f9c1252cb2285ada1102623a67f72 | /init/meta/support.lean | 3798ade6bb8d844e3184e35921717fbd02937731 | [
"Apache-2.0"
] | permissive | avigad/hott3 | 609a002849182721e7c7ae536d9f1e2956d6d4d3 | f64750cd2de7a81e87d4828246d1369d59f16f43 | refs/heads/master | 1,629,027,243,322 | 1,510,946,717,000 | 1,510,946,717,000 | 103,570,461 | 0 | 0 | null | 1,505,415,620,000 | 1,505,415,620,000 | null | UTF-8 | Lean | false | false | 4,379 | lean | /-
Copyright (c) 2017 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
open expr tactic native
@[inline] instance (α) [decidable_eq α] (a b : α): decidable (a == b) :=
if h : a = b then is_true (heq_of_eq h) else is_false (h ∘ eq_of_heq)
meta def expr.constants_core (e : expr) (ns : rb_set name) : rb_set name :=
e.fold ns $ λ e _ ns, match e with
| (expr.const n _) := ns.insert n
| _ := ns
end
meta def expr.constants (e : expr) : list name :=
(e.constants_core (rb_map.mk _ _)).keys
namespace hott
private meta def inst_args : expr → tactic expr | e := do
t ← infer_type e >>= whnf,
if ¬ t.is_pi then return e else do
x ← mk_local' t.binding_name t.binding_info t.binding_domain,
inst_args $ e.app x
meta def has_large_elim (ind : name) : tactic bool := do
type_former_is_prop ← mk_const ind >>= inst_args >>= is_prop,
elim_is_prop ← mk_const (ind <.> "rec") >>= inst_args >>= is_proof,
return (type_former_is_prop ∧ ¬ elim_is_prop)
meta def is_large_elim (n : name) : tactic bool := do
env ← get_env,
match env.recursor_of n with
| some ind := has_large_elim ind
| none := return ff
end
run_cmd
let unsafe := [`eq.rec, `heq.rec, `false.rec] in
unsafe.mmap' $ λ n, is_large_elim n >>= guardb
meta def has_attr (attr decl : name) : tactic bool :=
option.is_some <$> try_core (has_attribute attr decl)
private meta def check_not_nothott (n : name) : tactic unit := do
is_nothott ← has_attr `nothott n,
when is_nothott $ fail $ "not hott: marked as [nothott]: " ++ n.to_string
private meta def check_not_large_elim (n : name) : tactic unit := do
n_is_large_elim ← is_large_elim n,
when n_is_large_elim $ fail $ "not hott: uses large eliminator " ++ n.to_string
private meta def check_decl (n : name) := do
check_not_nothott n,
check_not_large_elim n,
-- TODO(gabriel): can't use unfold_all_macros since it throws an exception...
d ← get_decl n, return (d.type.constants ++ d.value.constants)
private meta def check_hott_core : ∀ (to_do : list name) (done : rb_set name), tactic unit
| [] done := return ()
| (n::to_do) done :=
if done.contains n then
check_hott_core to_do done
else do
let done := done.insert n,
is_hott ← has_attr `hott n,
if is_hott then
check_hott_core to_do done
else do
refd_consts ← check_decl n,
check_hott_core (refd_consts ++ to_do) done
meta def check_hott (ns : list name) : tactic unit :=
check_hott_core ns (rb_map.mk _ _)
@[user_attribute]
meta def hott_attribute : user_attribute := {
name := `hott,
descr := "Marks a definition that can be safely used in HoTT",
after_set := some (λ n _ _, check_decl n >>= check_hott),
before_unset := some $ λ _ _, skip,
}
@[user_attribute]
meta def nothott_attribute : user_attribute := {
name := `nothott,
descr := "Permanently marks a definition as unsafe for HoTT",
after_set := some (λ _ _ _, skip), -- make [nothott] non-removable
}
attribute [nothott] classical.choice
open lean lean.parser interactive
private meta def exec_cmd (cmd : string) : parser unit :=
with_input command_like cmd >> return ()
@[user_attribute]
private meta def hott_theory_cmd_attr : user_attribute := {
name := `_hott_theory_cmd,
descr := "(internal) command that is automatically executed with hott_theory",
}
private meta def get_hott_theory_cmds : tactic (list string) := do
decls ← attribute.get_instances hott_theory_cmd_attr.name,
decls.mmap $ λ d, mk_const d >>= eval_expr string
@[user_command]
private meta def hott_theory (meta_info : decl_meta_info) (_ : parse $ tk "hott_theory") : parser unit := do
exec_cmd "noncomputable theory",
cmds ← get_hott_theory_cmds, cmds.mmap' exec_cmd
private def string_hash (s : string) : ℕ :=
s.fold 1 (λ h c, (33*h + c.val) % unsigned_sz)
@[user_command]
private meta def hott_theory_cmd (meta_info : decl_meta_info) (_ : parse $ tk "hott_theory_cmd") : parser unit := do
cmd ← lean.parser.pexpr, cmd ← i_to_expr cmd, cmd ← eval_expr string cmd,
exec_cmd cmd,
let dummy_decl_name := mk_num_name `_hott_theory_cmd_decl (string_hash cmd),
add_decl (declaration.defn dummy_decl_name [] `(string) (reflect cmd) (reducibility_hints.regular 1 tt) ff),
hott_theory_cmd_attr.set dummy_decl_name () tt
end hott
|
f14aeebc2897e5de61579cb4042c861891d90d79 | 4e3bf8e2b29061457a887ac8889e88fa5aa0e34c | /lean/love10_denotational_semantics_exercise_sheet.lean | 71553717bec5c0c9c1424a84f1ad2cc8c1ef45a2 | [] | no_license | mukeshtiwari/logical_verification_2019 | 9f964c067a71f65eb8884743273fbeef99e6503d | 16f62717f55ed5b7b87e03ae0134791a9bef9b9a | refs/heads/master | 1,619,158,844,208 | 1,585,139,500,000 | 1,585,139,500,000 | 249,906,380 | 0 | 0 | null | 1,585,118,728,000 | 1,585,118,727,000 | null | UTF-8 | Lean | false | false | 3,943 | lean | /- LoVe Exercise 10: Denotational Semantics -/
import .love10_denotational_semantics_demo
namespace LoVe
/- Question 1: Monotonicity -/
/- Prove the following two lemmas from the lecture. -/
lemma monotone_comp {α β : Type} [partial_order α] (f g : α → set (β × β))
(hf : monotone f) (hg : monotone g) :
monotone (λa, f a ◯ g a) :=
sorry
lemma monotone_restrict {α β : Type} [partial_order α] (f : α → set (β × β))
(p : β → Prop) (hf : monotone f) :
monotone (λa, f a ⇃ p) :=
sorry
/- Question 2: Kleene's Theorem -/
/- We can compute the fixpoint by iteration by taking the union of all finite
iterations of `f`:
lfp f = ⋃n, f^^[n] ∅
where
f^^[n] = f ∘ ⋯ ∘ f ∘ id
iterates the function `f` `n` times. However, the above characterization of
`lfp` only holds for continuous functions, a concept we will introduce below. -/
def iterate {α : Type} (f : α → α) : ℕ → α → α
| 0 a := a
| (n + 1) a := f (iterate n a)
notation f`^^[`n`]` := iterate f n
/- 2.1. Fill in the missing proofs below. -/
def Union {α : Type} (s : ℕ → set α) : set α :=
{a | ∃n, a ∈ s n}
lemma Union_le {α : Type} {s : ℕ → set α} (a : set α) (h : ∀i, s i ≤ a) :
Union s ≤ a :=
sorry
/- A continuous function `f` is a function that commutes with the union of any
monotone sequence `s`: -/
def continuous {α : Type} (f : set α → set α) : Prop :=
∀s : ℕ → set α, monotone s → f (Union s) = Union (λn, f (s n))
/- We need to prove that each continuous function is monotone. To achieve this,
we will need the following sequence: -/
def bi_seq {α : Type} (a₁ a₂ : set α) : ℕ → set α
| 0 := a₁
| (n + 1) := a₂
/- For example, `bi_seq 0 1` is the sequence 0, 1, 1, 1, etc. -/
lemma monotone_bi_seq {α : Type} (a₁ a₂ : set α) (h : a₁ ≤ a₂) :
monotone (bi_seq a₁ a₂)
| 0 0 _ := le_refl _
| 0 (n + 1) _ := h
| (n + 1) (m + 1) _ := le_refl _
lemma Union_bi_seq {α : Type} (a₁ a₂ : set α) (ha : a₁ ≤ a₂) :
Union (bi_seq a₁ a₂) = a₂ :=
sorry
lemma monotone_of_continuous {α : Type} (f : set α → set α)
(hf : continuous f) :
monotone f :=
sorry
/- 2.2. Provide the following proof, using a similar case distinction as for
`monotone_bi_seq` above. -/
lemma monotone_iterate {α : Type} (f : set α → set α) (hf : monotone f) :
monotone (λn, f^^[n] ∅)
:= sorry
/- 2.3. Prove the main theorem. A proof sketch is given below.
We break the proof into two proofs of inclusion.
Case 1. lfp f ≤ Union (λn, f^[n] ∅): The key is to use the lemma `lfp_le`
together with continuity of `f`.
Case 2. Union (λn, f^[n] ∅) ≤ lfp f: The lemma `Union_le` gives us a natural
number `i`, on which you can perform induction. You will also need the lemma
`lfp_eq` to unfold one iteration of `lfp f`. -/
lemma lfp_Kleene {α : Type} (f : set α → set α) (hf : continuous f) :
complete_lattice.lfp f = Union (λn, f^^[n] ∅) :=
sorry
/- Question 3 (**optional**): Regular Expressions -/
inductive regex (α : Type) : Type
| empty {} : regex
| nothing {} : regex
| atom (a : α) : regex
| concat : regex → regex → regex
| alt : regex → regex → regex
| star : regex → regex
/- 3.1 (**optional**). Define a translation of regular expressions to relations.
The idea is that an atom corresponds to a relation, concatenation corresponds to
composition of relations, and alternation is union. -/
def rel_of_regex {α : Type} : regex (set (α × α)) → set (α × α)
| regex.empty := Id α
| _ := sorry
/- 3.2 (**optional**). Prove the following recursive equation about your
definition. -/
lemma rel_of_regex_star {α : Type} (r : regex (set (α × α))) :
rel_of_regex (regex.star r) =
rel_of_regex (regex.alt (regex.concat r (regex.star r)) regex.empty) :=
sorry
end LoVe
|
44646526ace14141c5f4db1a5916a0dcdcf11a2d | ec040be767d27b10d2f864ddcfdf756aeb7a9a0a | /src/assignments/assignment_5.lean | c2dc81d9b5d286b205707392518c3d2c36ed60e9 | [] | no_license | RoboticPanda77/complogic-s21 | b26a9680dfb98ac650e40539296c0cafc86f5cb4 | 93c5bcc0139c0926cc261075f50a8b1ead6aa40c | refs/heads/master | 1,682,196,614,558 | 1,620,625,035,000 | 1,620,625,035,000 | 337,230,148 | 0 | 0 | null | 1,620,625,036,000 | 1,612,824,240,000 | Lean | UTF-8 | Lean | false | false | 1,821 | lean | -- Nathaniel Monahan / ncm5jv
----------------------------------
universes u₁ u₂
def foldr
{α : Type u₁}
{β : Type u₂}
:
β →
(α → β → β) →
(list α → β)
| b f list.nil := b
| b f (h::t) := f h (foldr b f t)
-----------------------------------
inductive dihedral_actions : Type
| r_0
| r_270
| r_180
| r_90
| H
| D'
| V
| D
open dihedral_actions
def Cayley_actions : dihedral_actions → dihedral_actions → dihedral_actions
| r_0 action := action
| action r_0 := action
| r_270 r_90 := r_0
| r_90 r_270 := r_0
| r_180 r_180 := r_0
| D D := r_0
| H H := r_0
| D' D' := r_0
| V V := r_0
| r_90 r_180 := r_270
| r_180 r_90 := r_270
| H D' := r_270
| D' H := r_270
| D V := r_270
| V D := r_270
| r_270 r_180 := r_90
| r_180 r_270 := r_90
| H D := r_90
| D H := r_90
| D' V := r_90
| V D' := r_90
| r_270 r_270 := r_180
| r_90 r_90 := r_180
| H V := r_180
| V H := r_180
| D' D := r_180
| D D' := r_180
| r_270 V := D
| V r_270 := D
| r_180 D' := D
| D' r_180 := D
| r_90 H := D
| H r_90 := D
| r_270 D' := V
| D' r_270 := V
| r_180 H := V
| H r_180 := V
| r_90 D := V
| D r_90 := V
| r_270 D := H
| D r_270 := H
| r_180 V := H
| V r_180 := H
| r_90 D' := H
| D' r_90 := H
| D r_180 := D'
| r_180 D := D'
| V r_90 := D'
| r_90 V := D'
| r_270 H := D'
| H r_270 := D'
def comp : list dihedral_actions → dihedral_actions
| list.nil := r_0
| l := foldr r_0 Cayley_actions l |
e591d85919d3e4b73aef33a1c5413c854f16541f | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/special_functions/trigonometric/angle.lean | 6cad43780acac3ae8130b92cb8eb57269ed13c30 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 8,198 | lean | /-
Copyright (c) 2019 Calle Sönne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Calle Sönne
-/
import analysis.special_functions.trigonometric.basic
import algebra.char_zero.quotient
/-!
# The type of angles
In this file we define `real.angle` to be the quotient group `ℝ/2πℤ` and prove a few simple lemmas
about trigonometric functions and angles.
-/
open_locale real
noncomputable theory
namespace real
/-- The type of angles -/
@[derive [add_comm_group, topological_space, topological_add_group]]
def angle : Type :=
ℝ ⧸ (add_subgroup.zmultiples (2 * π))
namespace angle
instance : inhabited angle := ⟨0⟩
instance : has_coe ℝ angle := ⟨quotient_add_group.mk' _⟩
@[continuity] lemma continuous_coe : continuous (coe : ℝ → angle) :=
continuous_quotient_mk
/-- Coercion `ℝ → angle` as an additive homomorphism. -/
def coe_hom : ℝ →+ angle := quotient_add_group.mk' _
@[simp] lemma coe_coe_hom : (coe_hom : ℝ → angle) = coe := rfl
/-- An induction principle to deduce results for `angle` from those for `ℝ`, used with
`induction θ using real.angle.induction_on`. -/
@[elab_as_eliminator]
protected lemma induction_on {p : angle → Prop} (θ : angle) (h : ∀ x : ℝ, p x) : p θ :=
quotient.induction_on' θ h
@[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
lemma coe_nsmul (n : ℕ) (x : ℝ) : ↑(n • x : ℝ) = (n • ↑x : angle) := rfl
lemma coe_zsmul (z : ℤ) (x : ℝ) : ↑(z • x : ℝ) = (z • ↑x : angle) := rfl
@[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) :
↑((n : ℝ) * x) = n • (↑x : angle) :=
by simpa only [nsmul_eq_mul] using coe_hom.map_nsmul x n
@[simp, norm_cast] lemma coe_int_mul_eq_zsmul (x : ℝ) (n : ℤ) :
↑((n : ℝ) * x : ℝ) = n • (↑x : angle) :=
by simpa only [zsmul_eq_mul] using coe_hom.map_zsmul x n
lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k :=
by simp only [quotient_add_group.eq, add_subgroup.zmultiples_eq_closure,
add_subgroup.mem_closure_singleton, zsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm]
@[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) :=
angle_eq_iff_two_pi_dvd_sub.2 ⟨1, by rw [sub_zero, int.cast_one, mul_one]⟩
@[simp] lemma neg_coe_pi : -(π : angle) = π :=
begin
rw [←coe_neg, angle_eq_iff_two_pi_dvd_sub],
use -1,
simp [two_mul, sub_eq_add_neg]
end
lemma sub_coe_pi_eq_add_coe_pi (θ : angle) : θ - π = θ + π :=
by rw [sub_eq_add_neg, neg_coe_pi]
@[simp] lemma two_nsmul_coe_pi : (2 : ℕ) • (π : angle) = 0 :=
by simp [←coe_nat_mul_eq_nsmul]
@[simp] lemma two_zsmul_coe_pi : (2 : ℤ) • (π : angle) = 0 :=
by simp [←coe_int_mul_eq_zsmul]
@[simp] lemma coe_pi_add_coe_pi : (π : real.angle) + π = 0 :=
by rw [←two_nsmul, two_nsmul_coe_pi]
lemma zsmul_eq_iff {ψ θ : angle} {z : ℤ} (hz : z ≠ 0) :
z • ψ = z • θ ↔ (∃ k : fin z.nat_abs, ψ = θ + (k : ℕ) • (2 * π / z : ℝ)) :=
quotient_add_group.zmultiples_zsmul_eq_zsmul_iff hz
lemma nsmul_eq_iff {ψ θ : angle} {n : ℕ} (hz : n ≠ 0) :
n • ψ = n • θ ↔ (∃ k : fin n, ψ = θ + (k : ℕ) • (2 * π / n : ℝ)) :=
quotient_add_group.zmultiples_nsmul_eq_nsmul_iff hz
lemma two_zsmul_eq_iff {ψ θ : angle} : (2 : ℤ) • ψ = (2 : ℤ) • θ ↔ (ψ = θ ∨ ψ = θ + π) :=
by rw [zsmul_eq_iff two_ne_zero, int.nat_abs_bit0, int.nat_abs_one,
fin.exists_fin_two, fin.coe_zero, fin.coe_one, zero_smul, add_zero, one_smul,
int.cast_two, mul_div_cancel_left (_ : ℝ) two_ne_zero]
lemma two_nsmul_eq_iff {ψ θ : angle} : (2 : ℕ) • ψ = (2 : ℕ) • θ ↔ (ψ = θ ∨ ψ = θ + π) :=
by simp_rw [←coe_nat_zsmul, int.coe_nat_bit0, int.coe_nat_one, two_zsmul_eq_iff]
lemma two_nsmul_eq_zero_iff {θ : angle} : (2 : ℕ) • θ = 0 ↔ (θ = 0 ∨ θ = π) :=
by convert two_nsmul_eq_iff; simp
lemma two_zsmul_eq_zero_iff {θ : angle} : (2 : ℤ) • θ = 0 ↔ (θ = 0 ∨ θ = π) :=
by simp_rw [two_zsmul, ←two_nsmul, two_nsmul_eq_zero_iff]
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_zsmul, mul_comm, coe_two_pi, zsmul_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_zsmul, mul_comm, coe_two_pi, zsmul_zero, zero_add] },
apply_instance, },
{ 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, 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, 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, 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, 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, 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,
obtain ⟨n, hn⟩ : ∃ n, n • _ = _ := quotient_add_group.left_rel_apply.mp (quotient.exact' hc),
rw [← neg_one_mul, add_zero, ← sub_eq_zero, zsmul_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
/-- The sine of a `real.angle`. -/
def sin (θ : angle) : ℝ := sin_periodic.lift θ
@[simp] lemma sin_coe (x : ℝ) : sin (x : angle) = real.sin x :=
rfl
@[continuity] lemma continuous_sin : continuous sin :=
continuous_quotient_lift_on' _ real.continuous_sin
/-- The cosine of a `real.angle`. -/
def cos (θ : angle) : ℝ := cos_periodic.lift θ
@[simp] lemma cos_coe (x : ℝ) : cos (x : angle) = real.cos x :=
rfl
@[continuity] lemma continuous_cos : continuous cos :=
continuous_quotient_lift_on' _ real.continuous_cos
end angle
end real
|
1e11820b30ac9442349deaa5b7a23d2628ab6898 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /src/Lean/Data/SMap.lean | e6c61d62b8180242a6578ec99b668f8f58292720 | [
"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 | 3,093 | 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 Std.Data.HashMap
import Std.Data.PersistentHashMap
universes u v w w'
namespace Lean
open Std (HashMap PHashMap)
/- Staged map for implementing the Environment. The idea is to store
imported entries into a hashtable and local entries into a persistent hashtable.
Hypotheses:
- The number of entries (i.e., declarations) coming from imported files is much bigger than
the number of entries in the current file.
- HashMap is faster than PersistentHashMap.
- When we are reading imported files, we have exclusive access to the map, and efficient
destructive updates are performed.
Remarks:
- We never remove declarations from the Environment. In principle, we could support
deletion by using `(PHashMap α (Option β))` where the value `none` would indicate
that an entry was "removed" from the hashtable.
- We do not need additional bookkeeping for extracting the local entries.
-/
structure SMap (α : Type u) (β : Type v) [HasBeq α] [Hashable α] :=
(stage₁ : Bool := true)
(map₁ : HashMap α β := {})
(map₂ : PHashMap α β := {})
namespace SMap
variables {α : Type u} {β : Type v} [HasBeq α] [Hashable α]
instance : Inhabited (SMap α β) := ⟨{}⟩
def empty : SMap α β := {}
instance : HasEmptyc (SMap α β) := ⟨SMap.empty⟩
@[specialize] def insert : SMap α β → α → β → SMap α β
| ⟨true, m₁, m₂⟩, k, v => ⟨true, m₁.insert k v, m₂⟩
| ⟨false, m₁, m₂⟩, k, v => ⟨false, m₁, m₂.insert k v⟩
@[specialize] def find? : SMap α β → α → Option β
| ⟨true, m₁, _⟩, k => m₁.find? k
| ⟨false, m₁, m₂⟩, k => (m₂.find? k).orelse (m₁.find? k)
@[inline] def findD (m : SMap α β) (a : α) (b₀ : β) : β :=
(m.find? a).getD b₀
@[inline] def find! [Inhabited β] (m : SMap α β) (a : α) : β :=
match m.find? a with
| some b => b
| none => panic! "key is not in the map"
@[specialize] def contains : SMap α β → α → Bool
| ⟨true, m₁, _⟩, k => m₁.contains k
| ⟨false, m₁, m₂⟩, k => m₁.contains k || m₂.contains k
/- Similar to `find?`, but searches for result in the hashmap first.
So, the result is correct only if we never "overwrite" `map₁` entries using `map₂`. -/
@[specialize] def find?' : SMap α β → α → Option β
| ⟨true, m₁, _⟩, k => m₁.find? k
| ⟨false, m₁, m₂⟩, k => (m₁.find? k).orelse (m₂.find? k)
/- Move from stage 1 into stage 2. -/
def switch (m : SMap α β) : SMap α β :=
if m.stage₁ then { m with stage₁ := false } else m
@[inline] def foldStage2 {σ : Type w} (f : σ → α → β → σ) (s : σ) (m : SMap α β) : σ :=
m.map₂.foldl f s
def size (m : SMap α β) : Nat :=
m.map₁.size + m.map₂.size
def stageSizes (m : SMap α β) : Nat × Nat :=
(m.map₁.size, m.map₂.size)
def numBuckets (m : SMap α β) : Nat :=
m.map₁.numBuckets
end SMap
end Lean
|
88de979d94e915c7f031699bef0dff83d68b83c7 | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /test/to_additive.lean | 6307ce9e8620dd6ff69fe3ecf895cd24785f1fea | [
"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 | 2,550 | lean | import algebra.group.to_additive
@[to_additive bar0]
def foo0 {α} [has_mul α] [has_one α] (x y : α) : α := x * y * 1
class {u v} my_has_pow (α : Type u) (β : Type v) :=
(pow : α → β → α)
class my_has_scalar (M : Type*) (α : Type*) := (smul : M → α → α)
attribute [to_additive_reorder 1] my_has_pow
attribute [to_additive_reorder 1 4] my_has_pow.pow
attribute [to_additive my_has_scalar] my_has_pow
attribute [to_additive my_has_scalar.smul] my_has_pow.pow
-- set_option pp.universes true
-- set_option pp.implicit true
-- set_option pp.notation false
@[priority 10000]
local infix ` ^ `:80 := my_has_pow.pow
@[to_additive bar1]
def foo1 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) : α := @my_has_pow.pow α ℕ _ x n
instance dummy : my_has_pow ℕ $ plift ℤ := ⟨λ _ _, 0⟩
set_option pp.universes true
@[to_additive bar2]
def foo2 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) (m : plift ℤ) : α := x ^ (n ^ m)
@[to_additive bar3]
def foo3 {α} [my_has_pow α ℕ] (x : α) : ℕ → α := @my_has_pow.pow α ℕ _ x
@[to_additive bar4]
def {a b} foo4 {α : Type a} : Type b → Type (max a b) := @my_has_pow α
@[to_additive bar4_test]
lemma foo4_test {α β : Type*} : @foo4 α β = @my_has_pow α β := rfl
@[to_additive bar5]
def foo5 {α} [my_has_pow α ℕ] [my_has_pow ℕ ℤ] : true := trivial
@[to_additive bar6]
def foo6 {α} [my_has_pow α ℕ] : α → ℕ → α := @my_has_pow.pow α ℕ _
@[to_additive bar7]
def foo7 := @my_has_pow.pow
open tactic
/- test the eta-expansion applied on `foo6`. -/
run_cmd do
env ← get_env,
reorder ← to_additive.reorder_attr.get_cache,
d ← get_decl `foo6,
let e := d.value.eta_expand env reorder,
let t := d.type.eta_expand env reorder,
let decl := declaration.defn `barr6 d.univ_params t e d.reducibility_hints d.is_trusted,
add_decl decl,
skip
/-! Test the namespace bug (#8733). This code should *not* generate a lemma
`add_some_def.in_namespace`. -/
def some_def.in_namespace : bool := ff
def some_def {α : Type*} [has_mul α] (x : α) : α :=
if some_def.in_namespace then x * x else x
-- cannot apply `@[to_additive]` to `some_def` if `some_def.in_namespace` doesn't have the attribute
run_cmd do
dict ← to_additive.aux_attr.get_cache,
success_if_fail
(transform_decl_with_prefix_dict dict ff tt mk_name_map mk_name_map `some_def `add_some_def []),
skip
attribute [to_additive some_other_name] some_def.in_namespace
attribute [to_additive add_some_def] some_def
run_cmd success_if_fail (get_decl `add_some_def.in_namespace)
|
11a1820d10dcf0989ec557527f1801c060accd3d | 649957717d58c43b5d8d200da34bf374293fe739 | /src/linear_algebra/basic.lean | fc07066177675a6a153b53304bfdcd9d0b1ea890 | [
"Apache-2.0"
] | permissive | Vtec234/mathlib | b50c7b21edea438df7497e5ed6a45f61527f0370 | fb1848bbbfce46152f58e219dc0712f3289d2b20 | refs/heads/master | 1,592,463,095,113 | 1,562,737,749,000 | 1,562,737,749,000 | 196,202,858 | 0 | 0 | Apache-2.0 | 1,562,762,338,000 | 1,562,762,337,000 | null | UTF-8 | Lean | false | false | 62,572 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard
Basics of linear algebra. This sets up the "categorical/lattice structure" of
modules, submodules, and linear maps.
-/
import algebra.pi_instances data.finsupp data.equiv.algebra order.order_iso
open function lattice
reserve infix `≃ₗ` : 50
universes u v w x y z
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type y} {ε : Type z} {ι : Type x}
namespace finset
lemma smul_sum [ring γ] [add_comm_group β] [module γ β]
{s : finset α} {a : γ} {f : α → β} :
a • (s.sum f) = s.sum (λc, a • f c) :=
(finset.sum_hom ((•) a)).symm
end finset
namespace finsupp
lemma smul_sum [has_zero β] [ring γ] [add_comm_group δ] [module γ δ]
{v : α →₀ β} {c : γ} {h : α → β → δ} :
c • (v.sum h) = v.sum (λa b, c • h a b) :=
finset.smul_sum
end finsupp
namespace linear_map
section
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ] [add_comm_group ε]
variables [module α β] [module α γ] [module α δ] [module α ε]
variables (f g : β →ₗ[α] γ)
include α
@[simp] theorem comp_id : f.comp id = f :=
linear_map.ext $ λ x, rfl
@[simp] theorem id_comp : id.comp f = f :=
linear_map.ext $ λ x, rfl
theorem comp_assoc (g : γ →ₗ[α] δ) (h : δ →ₗ[α] ε) : (h.comp g).comp f = h.comp (g.comp f) :=
rfl
def cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (h : ∀c, f c ∈ p) : γ →ₗ[α] p :=
by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp
@[simp] theorem cod_restrict_apply (p : submodule α β) (f : γ →ₗ[α] β) {h} (x : γ) :
(cod_restrict p f h x : β) = f x := rfl
@[simp] lemma comp_cod_restrict (p : submodule α γ) (h : ∀b, f b ∈ p) (g : δ →ₗ[α] β) :
(cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) :=
ext $ assume b, rfl
@[simp] lemma subtype_comp_cod_restrict (p : submodule α γ) (h : ∀b, f b ∈ p) :
p.subtype.comp (cod_restrict p f h) = f :=
ext $ assume b, rfl
def inverse (g : γ → β) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : γ →ₗ[α] β :=
by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact
⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂],
λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩
instance : has_zero (β →ₗ[α] γ) := ⟨⟨λ _, 0, by simp, by simp⟩⟩
@[simp] lemma zero_apply (x : β) : (0 : β →ₗ[α] γ) x = 0 := rfl
instance : has_neg (β →ₗ[α] γ) := ⟨λ f, ⟨λ b, - f b, by simp, by simp⟩⟩
@[simp] lemma neg_apply (x : β) : (- f) x = - f x := rfl
instance : has_add (β →ₗ[α] γ) := ⟨λ f g, ⟨λ b, f b + g b, by simp, by simp [smul_add]⟩⟩
@[simp] lemma add_apply (x : β) : (f + g) x = f x + g x := rfl
instance : add_comm_group (β →ₗ[α] γ) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
intros; ext; simp
instance linear_map.is_add_group_hom : is_add_group_hom f :=
{ map_add := f.add }
instance linear_map_apply_is_add_group_hom (a : β) :
is_add_group_hom (λ f : β →ₗ[α] γ, f a) :=
{ map_add := λ f g, linear_map.add_apply f g a }
lemma sum_apply [decidable_eq δ] (t : finset δ) (f : δ → β →ₗ[α] γ) (b : β) :
t.sum f b = t.sum (λd, f d b) :=
(@finset.sum_hom _ _ _ t f _ _ (λ g : β →ₗ[α] γ, g b) _).symm
@[simp] lemma sub_apply (x : β) : (f - g) x = f x - g x := rfl
def smul_right (f : γ →ₗ[α] α) (x : β) : γ →ₗ[α] β :=
⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩.
@[simp] theorem smul_right_apply (f : γ →ₗ[α] α) (x : β) (c : γ) :
(smul_right f x : γ → β) c = f c • x := rfl
instance : has_one (β →ₗ[α] β) := ⟨linear_map.id⟩
instance : has_mul (β →ₗ[α] β) := ⟨linear_map.comp⟩
@[simp] lemma one_app (x : β) : (1 : β →ₗ[α] β) x = x := rfl
@[simp] lemma mul_app (A B : β →ₗ[α] β) (x : β) : (A * B) x = A (B x) := rfl
@[simp] theorem comp_zero : f.comp (0 : δ →ₗ[α] β) = 0 :=
ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero]
@[simp] theorem zero_comp : (0 : γ →ₗ[α] δ).comp f = 0 :=
rfl
section
variables (α β)
include β
instance endomorphism_ring : ring (β →ₗ[α] β) :=
by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..};
{ intros, apply linear_map.ext, simp }
end
section
variables (α β γ)
def fst : β × γ →ₗ[α] β := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩
def snd : β × γ →ₗ[α] γ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩
end
@[simp] theorem fst_apply (x : β × γ) : fst α β γ x = x.1 := rfl
@[simp] theorem snd_apply (x : β × γ) : snd α β γ x = x.2 := rfl
def pair (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) : β →ₗ[α] γ × δ :=
⟨λ x, (f x, g x), λ x y, by simp, λ x y, by simp⟩
@[simp] theorem pair_apply (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) (x : β) :
pair f g x = (f x, g x) := rfl
@[simp] theorem fst_pair (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) :
(fst α γ δ).comp (pair f g) = f := by ext; refl
@[simp] theorem snd_pair (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) :
(snd α γ δ).comp (pair f g) = g := by ext; refl
@[simp] theorem pair_fst_snd : pair (fst α β γ) (snd α β γ) = linear_map.id :=
by ext; refl
section
variables (α β γ)
def inl : β →ₗ[α] β × γ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl]
def inr : γ →ₗ[α] β × γ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr]
end
@[simp] theorem inl_apply (x : β) : inl α β γ x = (x, 0) := rfl
@[simp] theorem inr_apply (x : γ) : inr α β γ x = (0, x) := rfl
def copair (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) : β × γ →ₗ[α] δ :=
⟨λ x, f x.1 + g x.2, λ x y, by simp, λ x y, by simp [smul_add]⟩
@[simp] theorem copair_apply (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) (x : β) (y : γ) :
copair f g (x, y) = f x + g y := rfl
@[simp] theorem copair_inl (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) :
(copair f g).comp (inl α β γ) = f := by ext; simp
@[simp] theorem copair_inr (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) :
(copair f g).comp (inr α β γ) = g := by ext; simp
@[simp] theorem copair_inl_inr : copair (inl α β γ) (inr α β γ) = linear_map.id :=
by ext ⟨x, y⟩; simp
theorem fst_eq_copair : fst α β γ = copair linear_map.id 0 := by ext ⟨x, y⟩; simp
theorem snd_eq_copair : snd α β γ = copair 0 linear_map.id := by ext ⟨x, y⟩; simp
theorem inl_eq_pair : inl α β γ = pair linear_map.id 0 := rfl
theorem inr_eq_pair : inr α β γ = pair 0 linear_map.id := rfl
end
section comm_ring
variables [comm_ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variables (f g : β →ₗ[α] γ)
include α
instance : has_scalar α (β →ₗ[α] γ) := ⟨λ a f,
⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩
@[simp] lemma smul_apply (a : α) (x : β) : (a • f) x = a • f x := rfl
instance : module α (β →ₗ[α] γ) :=
module.of_core $ by refine { smul := (•), ..};
intros; ext; simp [smul_add, add_smul, smul_smul]
def congr_right (f : γ →ₗ[α] δ) : (β →ₗ[α] γ) →ₗ[α] (β →ₗ[α] δ) :=
⟨linear_map.comp f,
λ _ _, linear_map.ext $ λ _, f.2 _ _,
λ _ _, linear_map.ext $ λ _, f.3 _ _⟩
theorem smul_comp (g : γ →ₗ[α] δ) (a : α) : (a • g).comp f = a • (g.comp f) :=
rfl
theorem comp_smul (g : γ →ₗ[α] δ) (a : α) : g.comp (a • f) = a • (g.comp f) :=
ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl
end comm_ring
end linear_map
namespace submodule
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variables (p p' : submodule α β) (q q' : submodule α γ)
variables {r : α} {x y : β}
open set lattice
instance : partial_order (submodule α β) :=
partial_order.lift (coe : submodule α β → set β) (λ a b, ext') (by apply_instance)
lemma le_def {p p' : submodule α β} : p ≤ p' ↔ (p : set β) ⊆ p' := iff.rfl
lemma le_def' {p p' : submodule α β} : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl
def of_le {p p' : submodule α β} (h : p ≤ p') : p →ₗ[α] p' :=
linear_map.cod_restrict _ p.subtype $ λ ⟨x, hx⟩, h hx
@[simp] theorem of_le_apply {p p' : submodule α β} (h : p ≤ p')
(x : p) : (of_le h x : β) = x := rfl
lemma subtype_comp_of_le (p q : submodule α β) (h : p ≤ q) :
(submodule.subtype q).comp (of_le h) = submodule.subtype p :=
by ext ⟨b, hb⟩; simp
instance : has_bot (submodule α β) :=
⟨by split; try {exact {0}}; simp {contextual := tt}⟩
@[simp] lemma bot_coe : ((⊥ : submodule α β) : set β) = {0} := rfl
section
variables (α)
@[simp] lemma mem_bot : x ∈ (⊥ : submodule α β) ↔ x = 0 := mem_singleton_iff
end
instance : order_bot (submodule α β) :=
{ bot := ⊥,
bot_le := λ p x, by simp {contextual := tt},
..submodule.partial_order }
instance : has_top (submodule α β) :=
⟨by split; try {exact set.univ}; simp⟩
@[simp] lemma top_coe : ((⊤ : submodule α β) : set β) = univ := rfl
@[simp] lemma mem_top : x ∈ (⊤ : submodule α β) := trivial
lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : α) = 1) : p = ⊥ :=
by ext x; simp [semimodule.eq_zero_of_zero_eq_one _ x zero_eq_one]
instance : order_top (submodule α β) :=
{ top := ⊤,
le_top := λ p x _, trivial,
..submodule.partial_order }
instance : has_Inf (submodule α β) :=
⟨λ S, {
carrier := ⋂ s ∈ S, ↑s,
zero := by simp,
add := by simp [add_mem] {contextual := tt},
smul := by simp [smul_mem] {contextual := tt} }⟩
private lemma Inf_le' {S : set (submodule α β)} {p} : p ∈ S → Inf S ≤ p :=
bInter_subset_of_mem
private lemma le_Inf' {S : set (submodule α β)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S :=
subset_bInter
instance : has_inf (submodule α β) :=
⟨λ p p', {
carrier := p ∩ p',
zero := by simp,
add := by simp [add_mem] {contextual := tt},
smul := by simp [smul_mem] {contextual := tt} }⟩
instance : complete_lattice (submodule α β) :=
{ sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha,
le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb,
sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c, subset_inter,
inf_le_left := λ a b, inter_subset_left _ _,
inf_le_right := λ a b, inter_subset_right _ _,
Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t},
le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs,
Sup_le := λ s p hs, Inf_le' hs,
Inf := Inf,
le_Inf := λ s a, le_Inf',
Inf_le := λ s a, Inf_le',
..submodule.lattice.order_top,
..submodule.lattice.order_bot }
instance : add_comm_monoid (submodule α β) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm }
@[simp] lemma add_eq_sup (M N : submodule α β) : M + N = M ⊔ N := rfl
@[simp] lemma zero_eq_bot : (0 : submodule α β) = ⊥ := rfl
lemma eq_top_iff' {p : submodule α β} : p = ⊤ ↔ ∀ x, x ∈ p :=
eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩
@[simp] theorem inf_coe : (p ⊓ p' : set β) = p ∩ p' := rfl
@[simp] theorem mem_inf {p p' : submodule α β} :
x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[simp] theorem Inf_coe (P : set (submodule α β)) : (↑(Inf P) : set β) = ⋂ p ∈ P, ↑p := rfl
@[simp] theorem infi_coe {ι} (p : ι → submodule α β) :
(↑⨅ i, p i : set β) = ⋂ i, ↑(p i) :=
by rw [infi, Inf_coe]; ext a; simp; exact
⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩
@[simp] theorem mem_infi {ι} (p : ι → submodule α β) :
x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i :=
by rw [← mem_coe, infi_coe, mem_Inter]; refl
theorem disjoint_def {p p' : submodule α β} :
disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:β) :=
show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set β)) ↔ _, by simp
/-- The pushforward -/
def map (f : β →ₗ[α] γ) (p : submodule α β) : submodule α γ :=
{ carrier := f '' p,
zero := ⟨0, p.zero_mem, f.map_zero⟩,
add := by rintro _ _ ⟨b₁, hb₁, rfl⟩ ⟨b₂, hb₂, rfl⟩;
exact ⟨_, p.add_mem hb₁ hb₂, f.map_add _ _⟩,
smul := by rintro a _ ⟨b, hb, rfl⟩;
exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩ }
lemma map_coe (f : β →ₗ[α] γ) (p : submodule α β) :
(map f p : set γ) = f '' p := rfl
@[simp] lemma mem_map {f : β →ₗ[α] γ} {p : submodule α β} {x : γ} :
x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl
theorem mem_map_of_mem {f : β →ₗ[α] γ} {p : submodule α β} {r} (h : r ∈ p) : f r ∈ map f p :=
set.mem_image_of_mem _ h
lemma map_id : map linear_map.id p = p :=
submodule.ext $ λ a, by simp
lemma map_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) (p : submodule α β) :
map (g.comp f) p = map g (map f p) :=
submodule.ext' $ by simp [map_coe]; rw ← image_comp
lemma map_mono {f : β →ₗ[α] γ} {p p' : submodule α β} : p ≤ p' → map f p ≤ map f p' :=
image_subset _
@[simp] lemma map_zero : map (0 : β →ₗ[α] γ) p = ⊥ :=
have ∃ (x : β), x ∈ p := ⟨0, p.zero_mem⟩,
ext $ by simp [this, eq_comm]
/-- The pullback -/
def comap (f : β →ₗ[α] γ) (p : submodule α γ) : submodule α β :=
{ carrier := f ⁻¹' p,
zero := by simp,
add := λ x y h₁ h₂, by simp [p.add_mem h₁ h₂],
smul := λ a x h, by simp [p.smul_mem _ h] }
@[simp] lemma comap_coe (f : β →ₗ[α] γ) (p : submodule α γ) :
(comap f p : set β) = f ⁻¹' p := rfl
@[simp] lemma mem_comap {f : β →ₗ[α] γ} {p : submodule α γ} :
x ∈ comap f p ↔ f x ∈ p := iff.rfl
lemma comap_id : comap linear_map.id p = p :=
submodule.ext' rfl
lemma comap_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) (p : submodule α δ) :
comap (g.comp f) p = comap f (comap g p) := rfl
lemma comap_mono {f : β →ₗ[α] γ} {q q' : submodule α γ} : q ≤ q' → comap f q ≤ comap f q' :=
preimage_mono
lemma map_le_iff_le_comap {f : β →ₗ[α] γ} {p : submodule α β} {q : submodule α γ} :
map f p ≤ q ↔ p ≤ comap f q := image_subset_iff
lemma gc_map_comap (f : β →ₗ[α] γ) : galois_connection (map f) (comap f)
| p q := map_le_iff_le_comap
@[simp] lemma map_bot (f : β →ₗ[α] γ) : map f ⊥ = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma map_sup (f : β →ₗ[α] γ) : map f (p ⊔ p') = map f p ⊔ map f p' :=
(gc_map_comap f).l_sup
@[simp] lemma map_supr {ι : Sort*} (f : β →ₗ[α] γ) (p : ι → submodule α β) :
map f (⨆i, p i) = (⨆i, map f (p i)) :=
(gc_map_comap f).l_supr
@[simp] lemma comap_top (f : β →ₗ[α] γ) : comap f ⊤ = ⊤ := rfl
@[simp] lemma comap_inf (f : β →ₗ[α] γ) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl
@[simp] lemma comap_infi {ι : Sort*} (f : β →ₗ[α] γ) (p : ι → submodule α γ) :
comap f (⨅i, p i) = (⨅i, comap f (p i)) :=
(gc_map_comap f).u_infi
@[simp] lemma comap_zero : comap (0 : β →ₗ[α] γ) q = ⊤ :=
ext $ by simp
lemma map_comap_le (f : β →ₗ[α] γ) (q : submodule α γ) : map f (comap f q) ≤ q :=
(gc_map_comap f).l_u_le _
lemma le_comap_map (f : β →ₗ[α] γ) (p : submodule α β) : p ≤ comap f (map f p) :=
(gc_map_comap f).le_u_l _
--TODO(Mario): is there a way to prove this from order properties?
lemma map_inf_eq_map_inf_comap {f : β →ₗ[α] γ}
{p : submodule α β} {p' : submodule α γ} :
map f p ⊓ p' = map f (p ⊓ comap f p') :=
le_antisymm
(by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩)
(le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right))
lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' :=
ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩
lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule α β)), b = 0
| ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot α).1 hb
section
variables (α)
def span (s : set β) : submodule α β := Inf {p | s ⊆ p}
end
variables {s t : set β}
lemma mem_span : x ∈ span α s ↔ ∀ p : submodule α β, s ⊆ p → x ∈ p :=
mem_bInter_iff
lemma subset_span : s ⊆ span α s :=
λ x h, mem_span.2 $ λ p hp, hp h
lemma span_le {p} : span α s ≤ p ↔ s ⊆ p :=
⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩
lemma span_mono (h : s ⊆ t) : span α s ≤ span α t :=
span_le.2 $ subset.trans h subset_span
lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span α s) : span α s = p :=
le_antisymm (span_le.2 h₁) h₂
@[simp] lemma span_eq : span α (p : set β) = p :=
span_eq_of_le _ (subset.refl _) subset_span
@[elab_as_eliminator] lemma span_induction {p : β → Prop} (h : x ∈ span α s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ (a:α) x, p x → p (a • x)) : p x :=
(@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h
section
variables (α β)
protected def gi : galois_insertion (@span α β _ _ _) coe :=
{ choice := λ s _, span α s,
gc := λ s t, span_le,
le_l_u := λ s, subset_span,
choice_eq := λ s h, rfl }
end
@[simp] lemma span_empty : span α (∅ : set β) = ⊥ :=
(submodule.gi α β).gc.l_bot
@[simp] lemma span_univ : span α (univ : set β) = ⊤ :=
eq_top_iff.2 $ le_def.2 $ subset_span
lemma span_union (s t : set β) : span α (s ∪ t) = span α s ⊔ span α t :=
(submodule.gi α β).gc.l_sup
lemma span_Union {ι} (s : ι → set β) : span α (⋃ i, s i) = ⨆ i, span α (s i) :=
(submodule.gi α β).gc.l_supr
@[simp] theorem Union_coe_of_directed {ι} (hι : nonempty ι)
(S : ι → submodule α β)
(H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) :
((supr S : submodule α β) : set β) = ⋃ i, S i :=
begin
refine subset.antisymm _ (Union_subset $ le_supr S),
rw [show supr S = ⨆ i, span α (S i), by simp, ← span_Union],
unfreezeI,
refine λ x hx, span_induction hx (λ _, id) _ _ _,
{ cases hι with i, exact mem_Union.2 ⟨i, by simp⟩ },
{ simp, intros x y i hi j hj,
rcases H i j with ⟨k, ik, jk⟩,
exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ },
{ simp [-mem_coe]; exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ },
end
lemma mem_supr_of_mem {ι : Sort*} {b : β} (p : ι → submodule α β) (i : ι) (h : b ∈ p i) :
b ∈ (⨆i, p i) :=
have p i ≤ (⨆i, p i) := le_supr p i,
@this b h
@[simp] theorem mem_supr_of_directed {ι} (hι : nonempty ι)
(S : ι → submodule α β)
(H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) {x} :
x ∈ supr S ↔ ∃ i, x ∈ S i :=
by rw [← mem_coe, Union_coe_of_directed hι S H, mem_Union]; refl
theorem mem_Sup_of_directed {s : set (submodule α β)}
{z} (hzs : z ∈ Sup s) (x ∈ s)
(hdir : ∀ i ∈ s, ∀ j ∈ s, ∃ k ∈ s, i ≤ k ∧ j ≤ k) :
∃ y ∈ s, z ∈ y :=
begin
haveI := classical.dec, rw Sup_eq_supr at hzs,
have : ∃ (i : submodule α β), z ∈ ⨆ (H : i ∈ s), i,
{ refine (mem_supr_of_directed ⟨⊥⟩ _ (λ i j, _)).1 hzs,
by_cases his : i ∈ s; by_cases hjs : j ∈ s,
{ rcases hdir i his j hjs with ⟨k, hks, hik, hjk⟩,
exact ⟨k, le_supr_of_le hks (supr_le $ λ _, hik),
le_supr_of_le hks (supr_le $ λ _, hjk)⟩ },
{ exact ⟨i, le_refl _, supr_le $ hjs.elim⟩ },
{ exact ⟨j, supr_le $ his.elim, le_refl _⟩ },
{ exact ⟨⊥, supr_le $ his.elim, supr_le $ hjs.elim⟩ } },
cases this with N hzn, by_cases hns : N ∈ s,
{ have : (⨆ (H : N ∈ s), N) ≤ N := supr_le (λ _, le_refl _),
exact ⟨N, hns, this hzn⟩ },
{ have : (⨆ (H : N ∈ s), N) ≤ ⊥ := supr_le hns.elim,
cases (mem_bot α).1 (this hzn), exact ⟨x, H, x.zero_mem⟩ }
end
section
variables {p p'}
lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x :=
⟨λ h, begin
rw [← span_eq p, ← span_eq p', ← span_union] at h,
apply span_induction h,
{ rintro y (h | h),
{ exact ⟨y, h, 0, by simp, by simp⟩ },
{ exact ⟨0, by simp, y, h, by simp⟩ } },
{ exact ⟨0, by simp, 0, by simp⟩ },
{ rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩,
exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp⟩ },
{ rintro a _ ⟨y, hy, z, hz, rfl⟩,
exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ }
end,
by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _
((le_sup_left : p ≤ p ⊔ p') hy)
((le_sup_right : p' ≤ p ⊔ p') hz)⟩
end
lemma mem_span_singleton {y : β} : x ∈ span α ({y} : set β) ↔ ∃ a:α, a • y = x :=
⟨λ h, begin
apply span_induction h,
{ rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ },
{ exact ⟨0, by simp⟩ },
{ rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩,
exact ⟨a + b, by simp [add_smul]⟩ },
{ rintro a _ ⟨b, rfl⟩,
exact ⟨a * b, by simp [smul_smul]⟩ }
end,
by rintro ⟨a, y, rfl⟩; exact
smul_mem _ _ (subset_span $ by simp)⟩
lemma span_singleton_eq_range (y : β) : (span α ({y} : set β) : set β) = range ((• y) : α → β) :=
set.ext $ λ x, mem_span_singleton
lemma mem_span_insert {y} : x ∈ span α (insert y s) ↔ ∃ (a:α) (z ∈ span α s), x = a • y + z :=
begin
rw [← union_singleton, span_union, mem_sup],
simp [mem_span_singleton], split,
{ rintro ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩, exact ⟨a, z, hz, rfl⟩ },
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩ }
end
lemma mem_span_insert' {y} : x ∈ span α (insert y s) ↔ ∃(a:α), x + a • y ∈ span α s :=
begin
rw mem_span_insert, split,
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz]⟩ },
{ rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp⟩ }
end
lemma span_insert_eq_span (h : x ∈ span α s) : span α (insert x s) = span α s :=
span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _)
lemma span_span : span α (span α s : set β) = span α s := span_eq _
lemma span_eq_bot : span α (s : set β) = ⊥ ↔ ∀ x ∈ s, (x:β) = 0 :=
eq_bot_iff.trans ⟨
λ H x h, (mem_bot α).1 $ H $ subset_span h,
λ H, span_le.2 (λ x h, (mem_bot α).2 $ H x h)⟩
lemma span_singleton_eq_bot : span α ({x} : set β) = ⊥ ↔ x = 0 :=
span_eq_bot.trans $ by simp
@[simp] lemma span_image (f : β →ₗ[α] γ) : span α (f '' s) = map f (span α s) :=
span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $
span_le.2 $ image_subset_iff.1 subset_span
lemma linear_eq_on (s : set β) {f g : β →ₗ[α] γ} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span α s) :
f x = g x :=
by apply span_induction h H; simp {contextual := tt}
def prod : submodule α (β × γ) :=
{ carrier := set.prod p q,
zero := ⟨zero_mem _, zero_mem _⟩,
add := by rintro ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ ⟨hx₁, hy₁⟩ ⟨hx₂, hy₂⟩;
exact ⟨add_mem _ hx₁ hx₂, add_mem _ hy₁ hy₂⟩,
smul := by rintro a ⟨x, y⟩ ⟨hx, hy⟩;
exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩ }
@[simp] lemma prod_coe :
(prod p q : set (β × γ)) = set.prod p q := rfl
@[simp] lemma mem_prod {p : submodule α β} {q : submodule α γ} {x : β × γ} :
x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod
lemma span_prod_le (s : set β) (t : set γ) :
span α (set.prod s t) ≤ prod (span α s) (span α t) :=
span_le.2 $ set.prod_mono subset_span subset_span
@[simp] lemma prod_top : (prod ⊤ ⊤ : submodule α (β × γ)) = ⊤ :=
by ext; simp
@[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule α (β × γ)) = ⊥ :=
by ext ⟨x, y⟩; simp [prod.zero_eq_mk]
lemma prod_mono {p p' : submodule α β} {q q' : submodule α γ} :
p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono
@[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') :=
ext' set.prod_inter_prod
@[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') :=
begin
refine le_antisymm (sup_le
(prod_mono le_sup_left le_sup_left)
(prod_mono le_sup_right le_sup_right)) _,
simp [le_def'], intros xx yy hxx hyy,
rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩,
rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩,
refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩
end
-- TODO(Mario): Factor through add_subgroup
def quotient_rel : setoid β :=
⟨λ x y, x - y ∈ p, λ x, by simp,
λ x y h, by simpa using neg_mem _ h,
λ x y z h₁ h₂, by simpa using add_mem _ h₁ h₂⟩
def quotient : Type* := quotient (quotient_rel p)
namespace quotient
def mk {p : submodule α β} : β → quotient p := quotient.mk'
@[simp] theorem mk_eq_mk {p : submodule α β} (x : β) : (quotient.mk x : quotient p) = mk x := rfl
@[simp] theorem mk'_eq_mk {p : submodule α β} (x : β) : (quotient.mk' x : quotient p) = mk x := rfl
@[simp] theorem quot_mk_eq_mk {p : submodule α β} (x : β) : (quot.mk _ x : quotient p) = mk x := rfl
protected theorem eq {x y : β} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq'
instance : has_zero (quotient p) := ⟨mk 0⟩
@[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl
@[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p :=
by simpa using (quotient.eq p : mk x = 0 ↔ _)
instance : has_add (quotient p) :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa using add_mem p h₁ h₂⟩
@[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl
instance : has_neg (quotient p) :=
⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $
λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩
@[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl
instance : add_comm_group (quotient p) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
repeat {rintro ⟨⟩};
simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]
instance : has_scalar α (quotient p) :=
⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $
λ x y h, (quotient.eq p).2 $ by simpa [smul_add] using smul_mem p a h⟩
@[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl
instance : module α (quotient p) :=
module.of_core $ by refine {smul := (•), ..};
repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul,
-mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm]
instance {α β} {R:discrete_field α} [add_comm_group β] [vector_space α β]
(p : submodule α β) : vector_space α (quotient p) := {}
end quotient
end submodule
namespace submodule
variables [discrete_field α]
variables [add_comm_group β] [vector_space α β]
variables [add_comm_group γ] [vector_space α γ]
lemma comap_smul (f : β →ₗ[α] γ) (p : submodule α γ) (a : α) (h : a ≠ 0) :
p.comap (a • f) = p.comap f :=
by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply]
lemma map_smul (f : β →ₗ[α] γ) (p : submodule α β) (a : α) (h : a ≠ 0) :
p.map (a • f) = p.map f :=
le_antisymm
begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end
begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end
set_option class.instance_max_depth 40
lemma comap_smul' (f : β →ₗ[α] γ) (p : submodule α γ) (a : α) :
p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) :=
by by_cases a = 0; simp [h, comap_smul]
lemma map_smul' (f : β →ₗ[α] γ) (p : submodule α β) (a : α) :
p.map (a • f) = (⨆ h : a ≠ 0, p.map f) :=
by by_cases a = 0; simp [h, map_smul]
end submodule
namespace linear_map
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
include α
open submodule
@[simp] lemma finsupp_sum {α β γ δ} [ring α] [add_comm_group β] [module α β]
[add_comm_group γ] [module α γ] [has_zero δ]
(f : β →ₗ[α] γ) {t : ι →₀ δ} {g : ι → δ → β} :
f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum
theorem map_cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (h p') :
submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) :=
submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext]
theorem comap_cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (hf p') :
submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') :=
submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩
def range (f : β →ₗ[α] γ) : submodule α γ := map f ⊤
theorem range_coe (f : β →ₗ[α] γ) : (range f : set γ) = set.range f := set.image_univ
@[simp] theorem mem_range {f : β →ₗ[α] γ} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x :=
(set.ext_iff _ _).1 (range_coe f).
@[simp] theorem range_id : range (linear_map.id : β →ₗ[α] β) = ⊤ := map_id _
theorem range_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) : range (g.comp f) = map g (range f) :=
map_comp _ _ _
theorem range_comp_le_range (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) : range (g.comp f) ≤ range g :=
by rw range_comp; exact map_mono le_top
theorem range_eq_top {f : β →ₗ[α] γ} : range f = ⊤ ↔ surjective f :=
by rw [← submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective]
lemma range_le_iff_comap {f : β →ₗ[α] γ} {p : submodule α γ} : range f ≤ p ↔ comap f p = ⊤ :=
by rw [range, map_le_iff_le_comap, eq_top_iff]
lemma map_le_range {f : β →ₗ[α] γ} {p : submodule α β} : map f p ≤ range f :=
map_mono le_top
lemma sup_range_inl_inr :
(inl α β γ).range ⊔ (inr α β γ).range = ⊤ :=
begin
refine eq_top_iff'.2 (λ x, mem_sup.2 _),
rcases x with ⟨x₁, x₂⟩ ,
have h₁ : prod.mk x₁ (0 : γ) ∈ (inl α β γ).range,
by simp,
have h₂ : prod.mk (0 : β) x₂ ∈ (inr α β γ).range,
by simp,
use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂],
simp
end
def ker (f : β →ₗ[α] γ) : submodule α β := comap f ⊥
@[simp] theorem mem_ker {f : β →ₗ[α] γ} {y} : y ∈ ker f ↔ f y = 0 := mem_bot α
@[simp] theorem ker_id : ker (linear_map.id : β →ₗ[α] β) = ⊥ := rfl
theorem ker_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) : ker (g.comp f) = comap f (ker g) := rfl
theorem ker_le_ker_comp (f : β →ₗ[α] γ) (g : γ →ₗ[α] δ) : ker f ≤ ker (g.comp f) :=
by rw ker_comp; exact comap_mono bot_le
theorem sub_mem_ker_iff {f : β →ₗ[α] γ} {x y} : x - y ∈ f.ker ↔ f x = f y :=
by rw [mem_ker, map_sub, sub_eq_zero]
theorem disjoint_ker {f : β →ₗ[α] γ} {p : submodule α β} :
disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 :=
by simp [disjoint_def]
theorem disjoint_ker' {f : β →ₗ[α] γ} {p : submodule α β} :
disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y :=
disjoint_ker.trans
⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]),
λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩
theorem inj_of_disjoint_ker {f : β →ₗ[α] γ} {p : submodule α β}
{s : set β} (h : s ⊆ p) (hd : disjoint p (ker f)) :
∀ x y ∈ s, f x = f y → x = y :=
λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy)
lemma disjoint_inl_inr : disjoint (inl α β γ).range (inr α β γ).range :=
by simp [disjoint_def, @eq_comm β 0, @eq_comm γ 0] {contextual := tt}; intros; refl
theorem ker_eq_bot {f : β →ₗ[α] γ} : ker f = ⊥ ↔ injective f :=
by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤
theorem ker_eq_bot' {f : β →ₗ[α] γ} :
ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) :=
have h : (∀ m ∈ (⊤ : submodule α β), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0),
from ⟨λ h m, h m mem_top, λ h m _, h m⟩,
by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤
lemma le_ker_iff_map {f : β →ₗ[α] γ} {p : submodule α β} : p ≤ ker f ↔ map f p = ⊥ :=
by rw [ker, eq_bot_iff, map_le_iff_le_comap]
lemma ker_cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (hf) :
ker (cod_restrict p f hf) = ker f :=
by rw [ker, comap_cod_restrict, map_bot]; refl
lemma range_cod_restrict (p : submodule α β) (f : γ →ₗ[α] β) (hf) :
range (cod_restrict p f hf) = comap p.subtype f.range :=
map_cod_restrict _ _ _ _
lemma map_comap_eq (f : β →ₗ[α] γ) (q : submodule α γ) :
map f (comap f q) = range f ⊓ q :=
le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $
by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩
lemma map_comap_eq_self {f : β →ₗ[α] γ} {q : submodule α γ} (h : q ≤ range f) :
map f (comap f q) = q :=
by rw [map_comap_eq, inf_of_le_right h]
lemma comap_map_eq (f : β →ₗ[α] γ) (p : submodule α β) :
comap f (map f p) = p ⊔ ker f :=
begin
refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)),
rintro x ⟨y, hy, e⟩,
exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩
end
lemma comap_map_eq_self {f : β →ₗ[α] γ} {p : submodule α β} (h : ker f ≤ p) :
comap f (map f p) = p :=
by rw [comap_map_eq, sup_of_le_left h]
@[simp] theorem ker_zero : ker (0 : β →ₗ[α] γ) = ⊤ :=
eq_top_iff'.2 $ λ x, by simp
@[simp] theorem range_zero : range (0 : β →ₗ[α] γ) = ⊥ :=
submodule.map_zero _
theorem ker_eq_top {f : β →ₗ[α] γ} : ker f = ⊤ ↔ f = 0 :=
⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩
lemma range_le_bot_iff (f : β →ₗ[α] γ) : range f ≤ ⊥ ↔ f = 0 :=
by rw [range_le_iff_comap]; exact ker_eq_top
theorem map_le_map_iff {f : β →ₗ[α] γ} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' :=
⟨λ H x hx, let ⟨y, hy, e⟩ := H ⟨x, hx, rfl⟩ in ker_eq_bot.1 hf e ▸ hy, map_mono⟩
theorem map_injective {f : β →ₗ[α] γ} (hf : ker f = ⊥) : injective (map f) :=
λ p p' h, le_antisymm ((map_le_map_iff hf).1 (le_of_eq h)) ((map_le_map_iff hf).1 (ge_of_eq h))
theorem comap_le_comap_iff {f : β →ₗ[α] γ} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' :=
⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩
theorem comap_injective {f : β →ₗ[α] γ} (hf : range f = ⊤) : injective (comap f) :=
λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h))
theorem map_copair_prod (f : β →ₗ[α] δ) (g : γ →ₗ[α] δ) (p : submodule α β) (q : submodule α γ) :
map (copair f g) (p.prod q) = map f p ⊔ map g q :=
begin
refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)),
{ rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩,
exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ },
{ exact λ x hx, ⟨(x, 0), by simp [hx]⟩ },
{ exact λ x hx, ⟨(0, x), by simp [hx]⟩ }
end
theorem comap_pair_prod (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) (p : submodule α γ) (q : submodule α δ) :
comap (pair f g) (p.prod q) = comap f p ⊓ comap g q :=
submodule.ext $ λ x, iff.rfl
theorem prod_eq_inf_comap (p : submodule α β) (q : submodule α γ) :
p.prod q = p.comap (linear_map.fst α β γ) ⊓ q.comap (linear_map.snd α β γ) :=
submodule.ext $ λ x, iff.rfl
theorem prod_eq_sup_map (p : submodule α β) (q : submodule α γ) :
p.prod q = p.map (linear_map.inl α β γ) ⊔ q.map (linear_map.inr α β γ) :=
by rw [← map_copair_prod, copair_inl_inr, map_id]
lemma span_inl_union_inr {s : set β} {t : set γ} :
span α (prod.inl '' s ∪ prod.inr '' t) = (span α s).prod (span α t) :=
by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl
lemma ker_pair (f : β →ₗ[α] γ) (g : β →ₗ[α] δ) :
ker (pair f g) = ker f ⊓ ker g :=
by rw [ker, ← prod_bot, comap_pair_prod]; refl
end linear_map
namespace linear_map
variables [discrete_field α]
variables [add_comm_group β] [vector_space α β]
variables [add_comm_group γ] [vector_space α γ]
lemma ker_smul (f : β →ₗ[α] γ) (a : α) (h : a ≠ 0) : ker (a • f) = ker f :=
submodule.comap_smul f _ a h
lemma ker_smul' (f : β →ₗ[α] γ) (a : α) : ker (a • f) = ⨅(h : a ≠ 0), ker f :=
submodule.comap_smul' f _ a
lemma range_smul (f : β →ₗ[α] γ) (a : α) (h : a ≠ 0) : range (a • f) = range f :=
submodule.map_smul f _ a h
lemma range_smul' (f : β →ₗ[α] γ) (a : α) : range (a • f) = ⨆(h : a ≠ 0), range f :=
submodule.map_smul' f _ a
end linear_map
namespace is_linear_map
lemma is_linear_map_add {α β : Type*} [ring α] [add_comm_group β] [module α β]:
is_linear_map α (λ (x : β × β), x.1 + x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp },
{ intros x y,
simp [smul_add] }
end
lemma is_linear_map_sub {α β : Type*} [ring α] [add_comm_group β] [module α β]:
is_linear_map α (λ (x : β × β), x.1 - x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp },
{ intros x y,
simp [smul_add] }
end
end is_linear_map
namespace submodule
variables {R:ring α} [add_comm_group β] [add_comm_group γ] [module α β] [module α γ]
variables (p p' : submodule α β) (q : submodule α γ)
include R
open linear_map
@[simp] theorem map_top (f : β →ₗ[α] γ) : map f ⊤ = range f := rfl
@[simp] theorem comap_bot (f : β →ₗ[α] γ) : comap f ⊥ = ker f := rfl
@[simp] theorem ker_subtype : p.subtype.ker = ⊥ :=
ker_eq_bot.2 $ λ x y, subtype.eq'
@[simp] theorem range_subtype : p.subtype.range = p :=
by simpa using map_comap_subtype p ⊤
lemma map_subtype_le (p' : submodule α p) : map p.subtype p' ≤ p :=
by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range)
@[simp] theorem ker_of_le (p p' : submodule α β) (h : p ≤ p') : (of_le h).ker = ⊥ :=
by rw [of_le, ker_cod_restrict, ker_subtype]
lemma range_of_le (p q : submodule α β) (h : p ≤ q) : (of_le h).range = comap q.subtype p :=
by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype]
lemma disjoint_iff_comap_eq_bot (p q : submodule α β) :
disjoint p q ↔ comap p.subtype q = ⊥ :=
by rw [eq_bot_iff, ← map_le_map_iff p.ker_subtype, map_bot, map_comap_subtype]; refl
/-- If N ⊆ M then submodules of N are the same as submodules of M contained in N -/
def map_subtype.order_iso :
((≤) : submodule α p → submodule α p → Prop) ≃o
((≤) : {p' : submodule α β // p' ≤ p} → {p' : submodule α β // p' ≤ p} → Prop) :=
{ to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩,
inv_fun := λ q, comap p.subtype q,
left_inv := λ p', comap_map_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq],
ord := λ p₁ p₂, (map_le_map_iff $ ker_subtype _).symm }
def map_subtype.le_order_embedding :
((≤) : submodule α p → submodule α p → Prop) ≼o ((≤) : submodule α β → submodule α β → Prop) :=
(order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _)
@[simp] lemma map_subtype_embedding_eq (p' : submodule α p) :
map_subtype.le_order_embedding p p' = map p.subtype p' := rfl
def map_subtype.lt_order_embedding :
((<) : submodule α p → submodule α p → Prop) ≼o ((<) : submodule α β → submodule α β → Prop) :=
(map_subtype.le_order_embedding p).lt_embedding_of_le_embedding
@[simp] theorem map_inl : p.map (inl α β γ) = prod p ⊥ :=
by ext ⟨x, y⟩; simp [and.left_comm, eq_comm]
@[simp] theorem map_inr : q.map (inr α β γ) = prod ⊥ q :=
by ext ⟨x, y⟩; simp [and.left_comm, eq_comm]
@[simp] theorem comap_fst : p.comap (fst α β γ) = prod p ⊤ :=
by ext ⟨x, y⟩; simp
@[simp] theorem comap_snd : q.comap (snd α β γ) = prod ⊤ q :=
by ext ⟨x, y⟩; simp
@[simp] theorem prod_comap_inl : (prod p q).comap (inl α β γ) = p := by ext; simp
@[simp] theorem prod_comap_inr : (prod p q).comap (inr α β γ) = q := by ext; simp
@[simp] theorem prod_map_fst : (prod p q).map (fst α β γ) = p :=
by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)]
@[simp] theorem prod_map_snd : (prod p q).map (snd α β γ) = q :=
by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)]
@[simp] theorem ker_inl : (inl α β γ).ker = ⊥ :=
by rw [ker, ← prod_bot, prod_comap_inl]
@[simp] theorem ker_inr : (inr α β γ).ker = ⊥ :=
by rw [ker, ← prod_bot, prod_comap_inr]
@[simp] theorem range_fst : (fst α β γ).range = ⊤ :=
by rw [range, ← prod_top, prod_map_fst]
@[simp] theorem range_snd : (snd α β γ).range = ⊤ :=
by rw [range, ← prod_top, prod_map_snd]
def mkq : β →ₗ[α] p.quotient := ⟨quotient.mk, by simp, by simp⟩
@[simp] theorem mkq_apply (x : β) : p.mkq x = quotient.mk x := rfl
def liftq (f : β →ₗ[α] γ) (h : p ≤ f.ker) : p.quotient →ₗ[α] γ :=
⟨λ x, _root_.quotient.lift_on' x f $
λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab,
by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y,
by rintro a ⟨x⟩; exact f.map_smul a x⟩
@[simp] theorem liftq_apply (f : β →ₗ[α] γ) {h} (x : β) :
p.liftq f h (quotient.mk x) = f x := rfl
@[simp] theorem liftq_mkq (f : β →ₗ[α] γ) (h) : (p.liftq f h).comp p.mkq = f :=
by ext; refl
@[simp] theorem range_mkq : p.mkq.range = ⊤ :=
eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩
@[simp] theorem ker_mkq : p.mkq.ker = p :=
by ext; simp
lemma le_comap_mkq (p' : submodule α p.quotient) : p ≤ comap p.mkq p' :=
by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p')
@[simp] theorem mkq_map_self : map p.mkq p = ⊥ :=
by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _
@[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' :=
by simp [comap_map_eq, sup_comm]
def mapq (f : β →ₗ[α] γ) (h : p ≤ comap f q) : p.quotient →ₗ[α] q.quotient :=
p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h
@[simp] theorem mapq_apply (f : β →ₗ[α] γ) {h} (x : β) :
mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl
theorem mapq_mkq (f : β →ₗ[α] γ) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f :=
by ext x; refl
theorem comap_liftq (f : β →ₗ[α] γ) (h) :
q.comap (p.liftq f h) = (q.comap f).map (mkq p) :=
le_antisymm
(by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩)
(by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _)
theorem map_liftq (f : β →ₗ[α] γ) (h) (q : submodule α (quotient p)) :
q.map (p.liftq f h) = (q.comap p.mkq).map f :=
le_antisymm
(by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩)
(by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩)
theorem ker_liftq (f : β →ₗ[α] γ) (h) :
ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _
theorem range_liftq (f : β →ₗ[α] γ) (h) :
range (p.liftq f h) = range f := map_liftq _ _ _ _
theorem ker_liftq_eq_bot (f : β →ₗ[α] γ) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ :=
by rw [ker_liftq, le_antisymm h h', mkq_map_self]
/-- Correspondence Theorem -/
def comap_mkq.order_iso :
((≤) : submodule α p.quotient → submodule α p.quotient → Prop) ≃o
((≤) : {p' : submodule α β // p ≤ p'} → {p' : submodule α β // p ≤ p'} → Prop) :=
{ to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩,
inv_fun := λ q, map p.mkq q,
left_inv := λ p', map_comap_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [comap_map_mkq p, sup_of_le_right hq],
ord := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm }
def comap_mkq.le_order_embedding :
((≤) : submodule α p.quotient → submodule α p.quotient → Prop) ≼o ((≤) : submodule α β → submodule α β → Prop) :=
(order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _)
@[simp] lemma comap_mkq_embedding_eq (p' : submodule α p.quotient) :
comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl
def comap_mkq.lt_order_embedding :
((<) : submodule α p.quotient → submodule α p.quotient → Prop) ≼o ((<) : submodule α β → submodule α β → Prop) :=
(comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding
end submodule
section
set_option old_structure_cmd true
structure linear_equiv (α : Type u) (β : Type v) (γ : Type w)
[ring α] [add_comm_group β] [add_comm_group γ] [module α β] [module α γ]
extends β →ₗ[α] γ, β ≃ γ
end
infix ` ≃ₗ ` := linear_equiv _
notation β ` ≃ₗ[`:50 α `] ` γ := linear_equiv α β γ
namespace linear_equiv
section ring
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
include α
instance : has_coe (β ≃ₗ[α] γ) (β →ₗ[α] γ) := ⟨to_linear_map⟩
@[simp] theorem coe_apply (e : β ≃ₗ[α] γ) (b : β) : (e : β →ₗ[α] γ) b = e b := rfl
lemma to_equiv_injective : function.injective (to_equiv : (β ≃ₗ[α] γ) → β ≃ γ) :=
λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h)
@[extensionality] lemma ext {f g : β ≃ₗ[α] γ} (h : (f : β → γ) = g) : f = g :=
to_equiv_injective (equiv.eq_of_to_fun_eq h)
section
variable (β)
def refl : β ≃ₗ[α] β := { .. linear_map.id, .. equiv.refl β }
end
def symm (e : β ≃ₗ[α] γ) : γ ≃ₗ[α] β :=
{ .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv,
.. e.to_equiv.symm }
def trans (e₁ : β ≃ₗ[α] γ) (e₂ : γ ≃ₗ[α] δ) : β ≃ₗ[α] δ :=
{ .. e₂.to_linear_map.comp e₁.to_linear_map,
.. e₁.to_equiv.trans e₂.to_equiv }
@[simp] theorem apply_symm_apply (e : β ≃ₗ[α] γ) (c : γ) : e (e.symm c) = c := e.6 c
@[simp] theorem symm_apply_apply (e : β ≃ₗ[α] γ) (b : β) : e.symm (e b) = b := e.5 b
noncomputable def of_bijective
(f : β →ₗ[α] γ) (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : β ≃ₗ[α] γ :=
{ ..f, ..@equiv.of_bijective _ _ f
⟨linear_map.ker_eq_bot.1 hf₁, linear_map.range_eq_top.1 hf₂⟩ }
@[simp] theorem of_bijective_apply (f : β →ₗ[α] γ) {hf₁ hf₂} (x : β) :
of_bijective f hf₁ hf₂ x = f x := rfl
def of_linear (f : β →ₗ[α] γ) (g : γ →ₗ[α] β)
(h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : β ≃ₗ[α] γ :=
{ inv_fun := g,
left_inv := linear_map.ext_iff.1 h₂,
right_inv := linear_map.ext_iff.1 h₁,
..f }
@[simp] theorem of_linear_apply (f : β →ₗ[α] γ) (g : γ →ₗ[α] β) {h₁ h₂}
(x : β) : of_linear f g h₁ h₂ x = f x := rfl
@[simp] theorem of_linear_symm_apply (f : β →ₗ[α] γ) (g : γ →ₗ[α] β) {h₁ h₂}
(x : γ) : (of_linear f g h₁ h₂).symm x = g x := rfl
@[simp] protected theorem ker (f : β ≃ₗ[α] γ) : (f : β →ₗ[α] γ).ker = ⊥ :=
linear_map.ker_eq_bot.2 f.to_equiv.injective
@[simp] protected theorem range (f : β ≃ₗ[α] γ) : (f : β →ₗ[α] γ).range = ⊤ :=
linear_map.range_eq_top.2 f.to_equiv.surjective
def of_top (p : submodule α β) (h : p = ⊤) : p ≃ₗ[α] β :=
{ inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩,
left_inv := λ ⟨x, h⟩, rfl,
right_inv := λ x, rfl,
.. p.subtype }
@[simp] theorem of_top_apply (p : submodule α β) {h} (x : p) :
of_top p h x = x := rfl
@[simp] theorem of_top_symm_apply (p : submodule α β) {h} (x : β) :
↑((of_top p h).symm x) = x := rfl
lemma eq_bot_of_equiv (p : submodule α β) (e : p ≃ₗ[α] (⊥ : submodule α γ)) :
p = ⊥ :=
begin
refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot α).2 _),
have := e.symm_apply_apply ⟨b, hb⟩,
rw [← e.coe_apply, submodule.eq_zero_of_bot_submodule ((e : p →ₗ[α] (⊥ : submodule α γ)) ⟨b, hb⟩),
← e.symm.coe_apply, linear_map.map_zero] at this,
exact congr_arg (coe : p → β) this.symm
end
end ring
section comm_ring
variables [comm_ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
include α
open linear_map
set_option class.instance_max_depth 39
def smul_of_unit (a : units α) : β ≃ₗ[α] β :=
of_linear ((a:α) • 1 : β →ₗ β) (((a⁻¹ : units α) : α) • 1 : β →ₗ β)
(by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl)
(by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl)
def congr_right (f : γ ≃ₗ[α] δ) : (β →ₗ[α] γ) ≃ₗ (β →ₗ δ) :=
of_linear
f.to_linear_map.congr_right
f.symm.to_linear_map.congr_right
(linear_map.ext $ λ _, linear_map.ext $ λ _, f.6 _)
(linear_map.ext $ λ _, linear_map.ext $ λ _, f.5 _)
end comm_ring
section field
variables [field α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variable (β)
open linear_map
def smul_of_ne_zero (a : α) (ha : a ≠ 0) : β ≃ₗ[α] β :=
smul_of_unit $ units.mk0 a ha
end field
end linear_equiv
namespace equiv
variables [ring α] [add_comm_group β] [module α β] [add_comm_group γ] [module α γ]
def to_linear_equiv (e : β ≃ γ) (h : is_linear_map α (e : β → γ)) : β ≃ₗ[α] γ :=
{ add := h.add, smul := h.smul, .. e}
end equiv
namespace linear_map
variables [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
variables [module α β] [module α γ] [module α δ]
variables (f : β →ₗ[α] γ)
/-- First Isomorphism Law -/
noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[α] f.range :=
have hr : ∀ x : f.range, ∃ y, f y = ↑x := λ x, x.2.imp $ λ _, and.right,
let F : f.ker.quotient →ₗ[α] f.range :=
f.ker.liftq (cod_restrict f.range f $ λ x, ⟨x, trivial, rfl⟩)
(λ x hx, by simp; apply subtype.coe_ext.2; simpa using hx) in
{ inv_fun := λx, submodule.quotient.mk (classical.some (hr x)),
left_inv := by rintro ⟨x⟩; exact
(submodule.quotient.eq _).2 (sub_mem_ker_iff.2 $
classical.some_spec $ hr $ F $ submodule.quotient.mk x),
right_inv := λ x : range f, subtype.eq $ classical.some_spec (hr x),
.. F }
open submodule
def sup_quotient_to_quotient_inf (p p' : submodule α β) :
(comap p.subtype (p ⊓ p')).quotient →ₗ[α] (comap (p ⊔ p').subtype p').quotient :=
(comap p.subtype (p ⊓ p')).liftq
((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin
rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype],
exact comap_mono (inf_le_inf le_sup_left (le_refl _)) end
set_option class.instance_max_depth 41
/-- Second Isomorphism Law -/
noncomputable def sup_quotient_equiv_quotient_inf (p p' : submodule α β) :
(comap p.subtype (p ⊓ p')).quotient ≃ₗ[α] (comap (p ⊔ p').subtype p').quotient :=
{ .. sup_quotient_to_quotient_inf p p',
.. show (comap p.subtype (p ⊓ p')).quotient ≃ (comap (p ⊔ p').subtype p').quotient, from
@equiv.of_bijective _ _ (sup_quotient_to_quotient_inf p p') begin
constructor,
{ rw [← ker_eq_bot, sup_quotient_to_quotient_inf, ker_liftq_eq_bot],
rw [ker_comp, ker_mkq],
rintros ⟨x, hx1⟩ hx2, exact ⟨hx1, hx2⟩ },
rw [← range_eq_top, sup_quotient_to_quotient_inf, range_liftq, eq_top_iff'],
rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩,
use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2,
change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff]
end }
section prod
def prod {α β γ δ : Type*} [ring α] [add_comm_group β] [add_comm_group γ] [add_comm_group δ]
[module α β] [module α γ] [module α δ]
(f₁ : β →ₗ[α] γ) (f₂ : β →ₗ[α] δ) : β →ₗ[α] (γ × δ) :=
{ to_fun := λx, (f₁ x, f₂ x),
add := λx y, begin
change (f₁ (x + y), f₂ (x+y)) = (f₁ x, f₂ x) + (f₁ y, f₂ y),
simp only [linear_map.map_add],
refl
end,
smul := λc x, by simp only [linear_map.map_smul] }
lemma is_linear_map_prod_iso {α β γ δ : Type*} [comm_ring α] [add_comm_group β] [add_comm_group γ]
[add_comm_group δ] [module α β] [module α γ] [module α δ] :
is_linear_map α (λ(p : (β →ₗ[α] γ) × (β →ₗ[α] δ)), (linear_map.prod p.1 p.2 : (β →ₗ[α] (γ × δ)))) :=
⟨λu v, rfl, λc u, rfl⟩
def scalar_prod_space_iso {α β γ : Type*} [comm_ring α] [add_comm_group β] [add_comm_group γ]
[module α β] [module α γ] (c : β →ₗ[α] α) (f : γ) : β →ₗ[α] γ :=
{ to_fun := λx, (c x) • f,
add := λx y, begin
change c (x + y) • f = (c x) • f + (c y) • f,
simp [add_smul],
end,
smul := λa x, by simp [smul_smul] }
end prod
section pi
universe i
variables {φ : ι → Type i}
variables [∀i, add_comm_group (φ i)] [∀i, module α (φ i)]
/-- `pi` construction for linear functions. From a family of linear functions it produces a linear
function into a family of modules. -/
def pi (f : Πi, γ →ₗ[α] φ i) : γ →ₗ[α] (Πi, φ i) :=
⟨λc i, f i c,
assume c d, funext $ assume i, (f i).add _ _, assume c d, funext $ assume i, (f i).smul _ _⟩
@[simp] lemma pi_apply (f : Πi, γ →ₗ[α] φ i) (c : γ) (i : ι) :
pi f c i = f i c := rfl
lemma ker_pi (f : Πi, γ →ₗ[α] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) :=
by ext c; simp [funext_iff]; refl
lemma pi_eq_zero (f : Πi, γ →ₗ[α] φ i) : pi f = 0 ↔ (∀i, f i = 0) :=
by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩
lemma pi_zero : pi (λi, 0 : Πi, γ →ₗ[α] φ i) = 0 :=
by ext; refl
lemma pi_comp (f : Πi, γ →ₗ[α] φ i) (g : δ →ₗ[α] γ) : (pi f).comp g = pi (λi, (f i).comp g) :=
rfl
/-- Linear projection -/
def proj (i : ι) : (Πi, φ i) →ₗ[α] φ i :=
⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩
@[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[α] φ i) b = b i := rfl
lemma proj_pi (f : Πi, γ →ₗ[α] φ i) (i : ι) : (proj i).comp (pi f) = f i :=
ext $ assume c, rfl
lemma infi_ker_proj : (⨅i, ker (proj i) : submodule α (Πi, φ i)) = ⊥ :=
bot_unique $ submodule.le_def'.2 $ assume a h,
begin
simp only [mem_infi, mem_ker, proj_apply] at h,
exact (mem_bot _).2 (funext $ assume i, h i)
end
section
variables (α φ)
def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)]
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) :
(⨅i ∈ J, ker (proj i) : submodule α (Πi, φ i)) ≃ₗ[α] (Πi:I, φ i) :=
begin
refine linear_equiv.of_linear
(pi $ λi, (proj (i:ι)).comp (submodule.subtype _))
(cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _,
{ assume b,
simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply],
assume j hjJ,
have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩,
rw [dif_neg this, zero_apply] },
{ simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.val_prop'],
ext b ⟨j, hj⟩, refl },
{ ext ⟨b, hb⟩,
apply subtype.coe_ext.2,
ext j,
have hb : ∀i ∈ J, b i = 0,
{ simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb },
simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply],
split_ifs,
{ rw [dif_pos h], refl },
{ rw [dif_neg h],
exact (hb _ $ (hu trivial).resolve_left h).symm } }
end
end
section
variable [decidable_eq ι]
/-- `diag i j` is the identity map if `i = j` otherwise it is the constant 0 map. -/
def diag (i j : ι) : φ i →ₗ[α] φ j :=
@function.update ι (λj, φ i →ₗ[α] φ j) _ 0 i id j
lemma update_apply (f : Πi, γ →ₗ[α] φ i) (c : γ) (i j : ι) (b : γ →ₗ[α] φ i) :
(update f i b j) c = update (λi, f i c) i (b c) j :=
begin
by_cases j = i,
{ rw [h, update_same, update_same] },
{ rw [update_noteq h, update_noteq h] }
end
end
section
variable [decidable_eq ι]
variables (α φ)
/-- Standard basis -/
def std_basis (i : ι) : φ i →ₗ[α] (Πi, φ i) := pi (diag i)
lemma std_basis_apply (i : ι) (b : φ i) : std_basis α φ i b = update 0 i b :=
by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl
@[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis α φ i b i = b :=
by rw [std_basis_apply, update_same]
lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis α φ i b j = 0 :=
by rw [std_basis_apply, update_noteq h]; refl
lemma ker_std_basis (i : ι) : ker (std_basis α φ i) = ⊥ :=
ker_eq_bot.2 $ assume f g hfg,
have std_basis α φ i f i = std_basis α φ i g i := hfg ▸ rfl,
by simpa only [std_basis_same]
lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis α φ j) = diag j i :=
by rw [std_basis, proj_pi]
lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis α φ i) = id :=
by ext b; simp
lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis α φ j) = 0 :=
by ext b; simp [std_basis_ne α φ _ _ h]
lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) :
(⨆i∈I, range (std_basis α φ i)) ≤ (⨅i∈J, ker (proj i)) :=
begin
refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb j hj,
have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩,
rw [proj_std_basis_ne α φ j i this.symm, zero_apply]
end
lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) :
(⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis α φ i)) :=
submodule.le_def'.2
begin
assume b hb,
simp only [mem_infi, mem_ker, proj_apply] at hb,
rw ← show I.sum (λi, std_basis α φ i (b i)) = b,
{ ext i,
rw [pi.finset_sum_apply, ← std_basis_same α φ i (b i)],
refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _,
assume hiI,
rw [std_basis_same],
exact hb _ ((hu trivial).resolve_left hiI) },
exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $
linear_map.mem_range.2 ⟨_, rfl⟩)
end
lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι}
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) :
(⨆i∈I, range (std_basis α φ i)) = (⨅i∈J, ker (proj i)) :=
begin
refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _,
have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [finset.coe_to_finset] },
refine le_trans (infi_ker_proj_le_supr_range_std_basis α φ this) (supr_le_supr $ assume i, _),
rw [← finset.mem_coe, finset.coe_to_finset],
exact le_refl _
end
lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis α φ i)) = ⊤ :=
have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty],
begin
apply top_unique,
convert (infi_ker_proj_le_supr_range_std_basis α φ this),
exact infi_emptyset.symm,
exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis α φ i)) $ finset.mem_univ i).symm)
end
lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) :
disjoint (⨆i∈I, range (std_basis α φ i)) (⨆i∈J, range (std_basis α φ i)) :=
begin
refine disjoint_mono
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I)
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _,
simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply,
funext_iff],
rintros b ⟨hI, hJ⟩ i,
classical,
by_cases hiI : i ∈ I,
{ by_cases hiJ : i ∈ J,
{ exact (h ⟨hiI, hiJ⟩).elim },
{ exact hJ i hiJ } },
{ exact hI i hiI }
end
end
end pi
variables (α β)
instance automorphism_group : group (β ≃ₗ[α] β) :=
{ mul := λ f g, g.trans f,
one := linear_equiv.refl β,
inv := λ f, f.symm,
mul_assoc := λ f g h, by {ext, refl},
mul_one := λ f, by {ext, refl},
one_mul := λ f, by {ext, refl},
mul_left_inv := λ f, by {ext, exact f.left_inv x} }
instance automorphism_group.to_linear_map_is_monoid_hom :
is_monoid_hom (linear_equiv.to_linear_map : (β ≃ₗ[α] β) → (β →ₗ[α] β)) :=
{ map_one := rfl,
map_mul := λ f g, rfl }
/-- The group of invertible linear maps from `β` to itself -/
def general_linear_group := units (β →ₗ[α] β)
namespace general_linear_group
variables {α β}
instance : group (general_linear_group α β) := by delta general_linear_group; apply_instance
def to_linear_equiv (f : general_linear_group α β) : (β ≃ₗ[α] β) :=
{ inv_fun := f.inv.to_fun,
left_inv := λ m, show (f.inv * f.val) m = m,
by erw f.inv_val; simp,
right_inv := λ m, show (f.val * f.inv) m = m,
by erw f.val_inv; simp,
..f.val }
def of_linear_equiv (f : (β ≃ₗ[α] β)) : general_linear_group α β :=
{ val := f,
inv := f.symm,
val_inv := linear_map.ext $ λ _, f.apply_symm_apply _,
inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ }
variables (α β)
def general_linear_equiv : general_linear_group α β ≃* (β ≃ₗ[α] β) :=
{ to_fun := to_linear_equiv,
inv_fun := of_linear_equiv,
left_inv := λ f,
begin
delta to_linear_equiv of_linear_equiv,
cases f with f f_inv, cases f, cases f_inv,
congr
end,
right_inv := λ f,
begin
delta to_linear_equiv of_linear_equiv,
cases f,
congr
end,
hom := ⟨λ x y, by {ext, refl}⟩ }
@[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group α β) :
((general_linear_equiv α β).to_equiv f).to_linear_map = f.val :=
by {ext, refl}
end general_linear_group
end linear_map
|
fd902128f73a79e195fa4c7821762eaa6f42ad6b | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/attribute_auto.lean | 3a0e6ab26ccca0b83356a456b1c4f19f6e985645 | [] | 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 | 708 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.meta.tactic
import Mathlib.Lean3Lib.init.meta.rb_map
import Mathlib.Lean3Lib.init.meta.has_reflect
import Mathlib.Lean3Lib.init.meta.lean.parser
namespace Mathlib
/-- Get all of the declaration names that have the given attribute.
Eg. ``get_instances `simp`` returns a list with the names of all of the lemmas in the environment tagged with the `@[simp]` attribute.
-/
/-- Returns a hash of `get_instances`. You can use this to tell if your attribute instances have changed. -/
end Mathlib |
933c06d7c684238c07a7012186359e7ac73dd0a7 | efce24474b28579aba3272fdb77177dc2b11d7aa | /src/category_theory/colimit_lemmas.lean | 098f3af996801949e0c9ce8bdc2ecde06391418e | [
"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 | 21,732 | lean | import category_theory.isomorphism
import .colimits
/-
* Notation and lemmas for categories with `has_coproducts`.
* Construction of pushouts in terms of coproducts and coequalizers.
-/
open set
open category_theory.category
local notation f ` ∘ `:80 g:80 := g ≫ f
namespace category_theory
universes v u
section initial
variables {C : Type u} [category.{v} C]
variable [has_initial_object.{v} C]
def initial : C := has_initial_object.initial_object.{v}.ob
instance : has_emptyc C := ⟨initial⟩
def initial.induced (a : C) : ∅ ⟶ a :=
has_initial_object.initial_object.is_initial_object.induced
notation `!` a := initial.induced a
def initial.uniqueness {a : C} (k k' : ∅ ⟶ a) : k = k' :=
has_initial_object.initial_object.is_initial_object.uniqueness k k'
-- This instance tends not to be very useful because `congr` generates
-- a congruence lemma which is too general, and does not "know" that
-- the domain is ∅.
instance initial_hom.subsingleton (a : C) : subsingleton (∅ ⟶ a) := ⟨initial.uniqueness⟩
end initial
section coproduct
variables {C : Type u} [category.{v} C]
variable [has_coproducts.{v} C]
-- The (chosen) coproduct of two objects.
def coprod (a₀ a₁ : C) :=
(has_coproducts.coproduct.{v} a₀ a₁).ob
infix ` ⊔ ` := coprod
-- The "left" inclusion.
def i₀ {a₀ a₁ : C} : a₀ ⟶ a₀ ⊔ a₁ :=
(has_coproducts.coproduct.{v} a₀ a₁).map₀
-- The "right" inclusion.
def i₁ {a₀ a₁ : C} : a₁ ⟶ a₀ ⊔ a₁ :=
(has_coproducts.coproduct.{v} a₀ a₁).map₁
-- The map out of a coproduct induced by a map on each summand.
def coprod.induced {a₀ a₁ b : C} (f₀ : a₀ ⟶ b) (f₁ : a₁ ⟶ b) : a₀ ⊔ a₁ ⟶ b :=
(has_coproducts.coproduct.{v} a₀ a₁).is_coproduct.induced f₀ f₁
def coprod.induced_Is_equiv {a₀ a₁ b : C} :
Is_equiv (λ p : (a₀ ⟶ b) × (a₁ ⟶ b), coprod.induced p.1 p.2) :=
{ e := ((has_coproducts.coproduct a₀ a₁).is_coproduct.universal b).e.symm,
h := by funext p; cases p; refl }
@[simp] lemma coprod.induced_commutes₀ {a₀ a₁ b : C} (f₀ : a₀ ⟶ b) (f₁ : a₁ ⟶ b) :
coprod.induced f₀ f₁ ∘ i₀ = f₀ :=
(has_coproducts.coproduct.{v} a₀ a₁).is_coproduct.induced_commutes₀ f₀ f₁
@[simp] lemma coprod.induced_commutes₁ {a₀ a₁ b : C} (f₀ : a₀ ⟶ b) (f₁ : a₁ ⟶ b) :
coprod.induced f₀ f₁ ∘ i₁ = f₁ :=
(has_coproducts.coproduct.{v} a₀ a₁).is_coproduct.induced_commutes₁ f₀ f₁
def coprod.fold (a : C) : a ⊔ a ⟶ a :=
coprod.induced (𝟙 a) (𝟙 a)
@[simp] lemma coprod.fold_i₀ {a : C} : coprod.fold a ∘ i₀ = 𝟙 a :=
coprod.induced_commutes₀ _ _
@[simp] lemma coprod.fold_i₁ {a : C} : coprod.fold a ∘ i₁ = 𝟙 a :=
coprod.induced_commutes₁ _ _
-- This is a kind of "co-extensionality" lemma; does that count?
@[ext] lemma coprod.uniqueness {a₀ a₁ b : C} {k k' : a₀ ⊔ a₁ ⟶ b}
(e₀ : k ∘ i₀ = k' ∘ i₀) (e₁ : k ∘ i₁ = k' ∘ i₁) : k = k' :=
(has_coproducts.coproduct.{v} a₀ a₁).is_coproduct.uniqueness e₀ e₁
lemma coprod.ext {a₀ a₁ b : C} {k k' : a₀ ⊔ a₁ ⟶ b} :
k = k' ↔ k ∘ i₀ = k' ∘ i₀ ∧ k ∘ i₁ = k' ∘ i₁ :=
iff.intro (assume h, by rw h; simp) (assume ⟨h₀, h₁⟩, coprod.uniqueness h₀ h₁)
-- Similarly, this is a "co-eta reduction".
@[simp] lemma coprod.eta {a₀ a₁ b : C} {k : a₀ ⊔ a₁ ⟶ b} :
coprod.induced (k ∘ i₀) (k ∘ i₁) = k :=
coprod.uniqueness (by simp) (by simp)
def coprod_of_maps {a₀ a₁ b₀ b₁ : C} (f₀ : a₀ ⟶ b₀) (f₁ : a₁ ⟶ b₁) : a₀ ⊔ a₁ ⟶ b₀ ⊔ b₁ :=
coprod.induced (i₀ ∘ f₀) (i₁ ∘ f₁)
@[simp] lemma coprod_of_maps_commutes₀ {a₀ a₁ b₀ b₁ : C} {f₀ : a₀ ⟶ b₀} {f₁ : a₁ ⟶ b₁} :
coprod_of_maps f₀ f₁ ∘ i₀ = i₀ ∘ f₀ :=
coprod.induced_commutes₀ _ _
@[simp] lemma coprod_of_maps_commutes₁ {a₀ a₁ b₀ b₁ : C} {f₀ : a₀ ⟶ b₀} {f₁ : a₁ ⟶ b₁} :
coprod_of_maps f₀ f₁ ∘ i₁ = i₁ ∘ f₁ :=
coprod.induced_commutes₁ _ _
def isomorphic_coprod_of_Is_coproduct {a₀ a₁ b : C} {f₀ : a₀ ⟶ b} {f₁ : a₁ ⟶ b}
(h : Is_coproduct f₀ f₁) : iso (a₀ ⊔ a₁) b :=
{ hom := coprod.induced f₀ f₁,
inv := h.induced i₀ i₁,
hom_inv_id' := by apply coprod.uniqueness; { rw ←assoc, simp },
inv_hom_id' := by apply h.uniqueness; { rw ←assoc, simp } }
def coprod_of_isomorphisms {a₀ a₁ b₀ b₁ : C} (j₀ : iso a₀ b₀) (j₁ : iso a₁ b₁) :
iso (a₀ ⊔ a₁) (b₀ ⊔ b₁) :=
{ hom := coprod_of_maps j₀.hom j₁.hom,
inv := coprod_of_maps j₀.inv j₁.inv,
hom_inv_id' := by apply coprod.uniqueness; rw ←assoc; simp,
inv_hom_id' := by apply coprod.uniqueness; rw ←assoc; simp }
variables [has_initial_object.{v} C]
def coprod_initial_right (a : C) : a ≅ a ⊔ ∅ :=
{ hom := i₀,
inv := coprod.induced (𝟙 a) (! a),
hom_inv_id' := by simp,
inv_hom_id' :=
by apply coprod.uniqueness; try { apply initial.uniqueness };
rw ←assoc; simp }
@[simp] lemma coprod_initial_right_hom {a : C} : (coprod_initial_right a).hom = i₀ :=
rfl
def coprod_initial_left (a : C) : a ≅ ∅ ⊔ a :=
{ hom := i₁,
inv := coprod.induced (! a) (𝟙 a),
hom_inv_id' := by simp,
inv_hom_id' :=
by apply coprod.uniqueness; try { apply initial.uniqueness };
rw ←assoc; simp }
@[simp] lemma coprod_initial_left_hom {a : C} : (coprod_initial_left a).hom = i₁ :=
rfl
end coproduct
section pushout_induced_eq
parameters {C : Type u} [category.{v} C]
parameters {a b₀ b₁ c c' : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁}
parameters {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c} (po : Is_pushout f₀ f₁ g₀ g₁)
lemma pushout_induced_eq_iff {x : C} {h₀ : b₀ ⟶ x} {h₁ : b₁ ⟶ x} {k : c ⟶ x} {e}
(H₀ : h₀ = g₀ ≫ k) (H₁ : h₁ = g₁ ≫ k) : po.induced h₀ h₁ e = k :=
by apply po.uniqueness; simp [H₀, H₁]
end pushout_induced_eq
section pushout_induced_comp
parameters {C : Type u} [category.{v} C]
parameters {a b₀ b₁ c c' : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁}
parameters {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c} (po : Is_pushout f₀ f₁ g₀ g₁)
lemma pushout_induced_comp {x y : C} {h₀ : b₀ ⟶ x} {h₁ : b₁ ⟶ x} {k : x ⟶ y} {e} :
k ∘ po.induced h₀ h₁ e = po.induced (k ∘ h₀) (k ∘ h₁)
(by rw [←assoc, ←assoc, e]) :=
by apply po.uniqueness; rw ←assoc; simp
end pushout_induced_comp
section pushouts_from_coequalizers
parameters {C : Type u} [category.{v} C] [has_coproducts.{v} C]
section construction
parameters {a b₀ b₁ b c : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁} {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c}
def Is_pushout_of_Is_coequalizer
(H : Is_coequalizer (i₀ ∘ f₀) (i₁ ∘ f₁) (coprod.induced g₀ g₁)) :
Is_pushout f₀ f₁ g₀ g₁ :=
Is_pushout.mk'
(begin convert H.commutes using 1; rw assoc; simp end)
(λ x h₀ h₁ e, H.induced (coprod.induced h₀ h₁)
(begin rw [assoc, assoc], simpa using e end))
(assume x h₀ h₁ e,
-- Weird trick to avoid repeating the proof argument
(λ p, let K := H.induced (coprod.induced h₀ h₁) p in calc
K ∘ g₀ = K ∘ (coprod.induced g₀ g₁ ∘ i₀) : by simp
... = (K ∘ coprod.induced g₀ g₁) ∘ i₀ : by rw assoc
... = h₀ : by simp) _)
(assume x h₀ h₁ e,
(λ p, let K := H.induced (coprod.induced h₀ h₁) p in calc
K ∘ g₁ = K ∘ (coprod.induced g₀ g₁ ∘ i₁) : by simp
... = (K ∘ coprod.induced g₀ g₁) ∘ i₁ : by rw assoc
... = h₁ : by simp) _)
(assume x k k' e₀ e₁, H.uniqueness $ coprod.uniqueness
(by rw [←assoc, ←assoc]; simpa using e₀)
(by rw [←assoc, ←assoc]; simpa using e₁))
def pushout_of_coequalizer (E : coequalizer (i₀ ∘ f₀) (i₁ ∘ f₁)) : pushout f₀ f₁ :=
{ ob := E.ob,
map₀ := E.map ∘ i₀,
map₁ := E.map ∘ i₁,
is_pushout := by
apply Is_pushout_of_Is_coequalizer; convert E.is_coequalizer; simp }
end construction
def has_pushouts_of_has_coequalizers_and_coproducts [has_coequalizers.{v} C] :
has_pushouts.{v} C :=
{ pushout := λ a b₀ b₁ f₀ f₁,
pushout_of_coequalizer $ has_coequalizers.coequalizer (i₀ ∘ f₀) (i₁ ∘ f₁) }
end pushouts_from_coequalizers
section uniqueness_of_initial_objects
parameters {C : Type u} [category.{v} C]
parameters {a : C} (init : Is_initial_object.{v} a)
parameters {a' : C} (init' : Is_initial_object.{v} a')
def initial_object.unique : iso a a' :=
{ hom := init.induced,
inv := init'.induced,
hom_inv_id' := init.uniqueness _ _,
inv_hom_id' := init'.uniqueness _ _ }
end uniqueness_of_initial_objects
section uniqueness_of_pushouts
parameters {C : Type u} [category.{v} C]
parameters {a b₀ b₁ c c' : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁}
parameters {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c} (po : Is_pushout f₀ f₁ g₀ g₁)
parameters {g'₀ : b₀ ⟶ c'} {g'₁ : b₁ ⟶ c'} (po' : Is_pushout f₀ f₁ g'₀ g'₁)
@[reducible] private def h : c ⟶ c' := po.induced g'₀ g'₁ po'.commutes
@[reducible] private def h' : c' ⟶ c := po'.induced g₀ g₁ po.commutes
def pushout.unique : iso c c' :=
{ hom := h,
inv := h',
hom_inv_id' := by apply po.uniqueness; {rw ←category.assoc, simp},
inv_hom_id' := by apply po'.uniqueness; {rw ←category.assoc, simp} }
@[simp] lemma pushout.unique_commutes₀ : pushout.unique.hom ∘ g₀ = g'₀ :=
by apply po.induced_commutes₀
@[simp] lemma pushout.unique_commutes₁ : pushout.unique.hom ∘ g₁ = g'₁ :=
by apply po.induced_commutes₁
end uniqueness_of_pushouts
local notation [parsing_only] a ` ~~ ` b := Bij_on _ a b
section refl
parameters {C : Type u} [category.{v} C]
parameters {a b : C} (f : a ⟶ b)
def Is_pushout.refl : Is_pushout f (𝟙 a) (𝟙 b) f :=
Is_pushout.mk $ λ x,
Bij_on.mk
{ to_fun := λ h, ⟨(h ∘ 𝟙 b, h ∘ f), by simp⟩,
inv_fun := λ p, ⟨p.val.1, trivial⟩,
left_inv := assume h, by simp,
right_inv := assume ⟨⟨pv1, pv2⟩, pp⟩, by simpa using pp }
(assume h, rfl)
end refl
section isomorphic
parameters {C : Type u} [category.{v} C]
-- TODO: Move this somewhere?
def precomposition_bij {a' a x : C} (i : iso a' a) :
Bij_on (λ (k : a ⟶ x), (k ∘ i.hom : a' ⟶ x)) univ univ :=
Bij_on.of_equiv $ show (a ⟶ x) ≃ (a' ⟶ x), from
{ to_fun := λ k, k ∘ i.hom,
inv_fun := λ k', k' ∘ i.inv,
left_inv := λ k, by simp,
right_inv := λ k', by simp }
parameters {a b₀ b₁ c : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁}
parameters {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c} (po : Is_pushout f₀ f₁ g₀ g₁)
parameters {a' b'₀ b'₁ : C} (f'₀ : a' ⟶ b'₀) (f'₁ : a' ⟶ b'₁)
parameters (i : iso a' a) (j₀ : iso b'₀ b₀) (j₁ : iso b'₁ b₁)
parameters (e₀ : f₀ ∘ i.hom = j₀.hom ∘ f'₀) (e₁ : f₁ ∘ i.hom = j₁.hom ∘ f'₁)
include e₀ e₁
def Is_pushout_of_isomorphic : Is_pushout f'₀ f'₁ (g₀ ∘ j₀.hom) (g₁ ∘ j₁.hom) :=
Is_pushout.mk $ λ x,
have _ := calc
univ ~~ {p : (b₀ ⟶ x) × (b₁ ⟶ x) | p.1 ∘ f₀ = p.2 ∘ f₁}
: po.universal x
... ~~ {p : (b₀ ⟶ x) × (b₁ ⟶ x) | (p.1 ∘ j₀.hom) ∘ f'₀ = (p.2 ∘ j₁.hom) ∘ f'₁}
: begin
convert Bij_on.refl _, funext p, apply propext,
rw [←assoc, ←assoc, ←e₀, ←e₁], simp [cancel_epi],
end
... ~~ {p : (b'₀ ⟶ x) × (b'₁ ⟶ x) | p.1 ∘ f'₀ = p.2 ∘ f'₁}
: Bij_on.restrict''
(Bij_on.prod' (precomposition_bij j₀) (precomposition_bij j₁))
{p | p.1 ∘ f'₀ = p.2 ∘ f'₁},
by convert this; funext; simp
omit e₀ e₁
parameters {c' : C} (k : iso c c')
def Is_pushout_of_isomorphic' : Is_pushout f₀ f₁ (k.hom ∘ g₀) (k.hom ∘ g₁) :=
Is_pushout.mk $ λ x,
have _ := calc
univ ~~ univ
: precomposition_bij k
... ~~ {p : (b₀ ⟶ x) × (b₁ ⟶ x) | p.1 ∘ f₀ = p.2 ∘ f₁ }
: po.universal x,
by convert this; funext; simp
end isomorphic
section pushout_tranpose
parameters {C : Type u} [category.{v} C]
parameters {a b₀ b₁ c : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁}
parameters {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c} (po : Is_pushout f₀ f₁ g₀ g₁)
def Is_pushout.transpose : Is_pushout f₁ f₀ g₁ g₀ :=
Is_pushout.mk $ λ x, calc
univ ~~ {p : (b₀ ⟶ x) × (b₁ ⟶ x) | p.1 ∘ f₀ = p.2 ∘ f₁}
: po.universal x
... ~~ {p : (b₀ ⟶ x) × (b₁ ⟶ x) | p.2 ∘ f₁ = p.1 ∘ f₀}
: begin convert Bij_on.refl _; ext p; split; exact eq.symm, end
... ~~ {p' : (b₁ ⟶ x) × (b₀ ⟶ x) | p'.1 ∘ f₁ = p'.2 ∘ f₀}
: Bij_on.restrict_equiv (equiv.prod_comm _ _)
{p' | p'.1 ∘ f₁ = p'.2 ∘ f₀}
parameters {c' : C} {g₀' : b₀ ⟶ c'} {g₁' : b₁ ⟶ c'}
parameters (po' : Is_pushout f₁ f₀ g₁' g₀')
def Is_pushout.iso_transpose : c ≅ c' :=
pushout.unique po.transpose po'
@[simp] lemma Is_pushout.iso_transpose_map₀ : g₀ ≫ (po.iso_transpose po').hom = g₀' :=
by apply pushout.unique_commutes₁
@[simp] lemma Is_pushout.iso_transpose_map₁ : g₁ ≫ (po.iso_transpose po').hom = g₁' :=
by apply pushout.unique_commutes₀
lemma Is_pushout.transpose_induced {x : C} {h₀ : b₀ ⟶ x} {h₁ : b₁ ⟶ x} {e : f₀ ≫ h₀ = f₁ ≫ h₁} :
(po.iso_transpose po').hom ≫ po'.induced h₁ h₀ e.symm = po.induced h₀ h₁ e :=
begin
symmetry,
apply pushout_induced_eq_iff; rw ←assoc; simp
end
end pushout_tranpose
section pushout_initial
parameters {C : Type u} [category.{v} C]
parameters {a b₀ b₁ c : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁}
parameters {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c}
-- TODO: Somehow prove these two simultaneously?
def Is_pushout_of_Is_coproduct_of_Is_initial (copr : Is_coproduct g₀ g₁)
(h : Is_initial_object.{v} a) : Is_pushout f₀ f₁ g₀ g₁ :=
Is_pushout.mk $ λ x, calc
univ ~~ {p : (b₀ ⟶ x) × (b₁ ⟶ x) | true}
: Bij_on.of_Is_equiv (copr.universal x)
... ~~ {p : (b₀ ⟶ x) × (b₁ ⟶ x) | p.1 ∘ f₀ = p.2 ∘ f₁}
: by convert Bij_on.refl _; ext p; change (_ = _) ↔ true;
simp; apply h.uniqueness
def Is_coproduct_of_Is_pushout_of_Is_initial (po : Is_pushout f₀ f₁ g₀ g₁)
(h : Is_initial_object.{v} a) : Is_coproduct g₀ g₁ :=
have _ := λ x, calc
univ ~~ {p : (b₀ ⟶ x) × (b₁ ⟶ x) | p.1 ∘ f₀ = p.2 ∘ f₁}
: po.universal x
... ~~ (univ : set ((b₀ ⟶ x) × (b₁ ⟶ x)))
: begin
convert Bij_on.refl _, symmetry, rw ←univ_subset_iff,
intros p _, apply h.uniqueness
end,
Is_coproduct.mk $ λ x, (this x).Is_equiv
end pushout_initial
section coprod_of_pushouts
parameters {C : Type u} [category.{v} C] [has_coproducts.{v} C]
parameters {a b₀ b₁ c : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁}
parameters {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c} (po : Is_pushout f₀ f₁ g₀ g₁)
parameters {a' b₀' b₁' c' : C} {f₀' : a' ⟶ b₀'} {f₁' : a' ⟶ b₁'}
parameters {g₀' : b₀' ⟶ c'} {g₁' : b₁' ⟶ c'} (po' : Is_pushout f₀' f₁' g₀' g₁')
include po po'
def Is_pushout_coprod :
Is_pushout
(coprod_of_maps f₀ f₀') (coprod_of_maps f₁ f₁')
(coprod_of_maps g₀ g₀') (coprod_of_maps g₁ g₁') :=
Is_pushout.mk $ λ x,
have _ := calc
univ ~~ (univ : set ((c ⟶ x) × (c' ⟶ x)))
: Bij_on.of_Is_equiv ((has_coproducts.coproduct c c').is_coproduct.universal x)
... ~~ {pp : ((b₀ ⟶ x) × (b₁ ⟶ x)) × ((b₀' ⟶ x) × (b₁' ⟶ x))
| pp.1.1 ∘ f₀ = pp.1.2 ∘ f₁ ∧ pp.2.1 ∘ f₀' = pp.2.2 ∘ f₁'}
:
begin
convert Bij_on.prod (po.universal x) (po'.universal x),
ext p, simp
end
... ~~ {qq : ((b₀ ⟶ x) × (b₀' ⟶ x)) × ((b₁ ⟶ x) × (b₁' ⟶ x))
| qq.1.1 ∘ f₀ = qq.2.1 ∘ f₁ ∧ qq.1.2 ∘ f₀' = qq.2.2 ∘ f₁'}
: Bij_on.restrict_equiv
{ to_fun := λ (pp : ((b₀ ⟶ x) × (b₁ ⟶ x)) × ((b₀' ⟶ x) × (b₁' ⟶ x))), ((pp.1.1, pp.2.1), (pp.1.2, pp.2.2)),
inv_fun := λ qq, ⟨⟨qq.1.1, qq.2.1⟩, ⟨qq.1.2, qq.2.2⟩⟩,
left_inv := assume ⟨⟨_,_⟩,⟨_,_⟩⟩, rfl,
right_inv := assume ⟨⟨_,_⟩,⟨_,_⟩⟩, rfl }
{qq : ((b₀ ⟶ x) × (b₀' ⟶ x)) × ((b₁ ⟶ x) × (b₁' ⟶ x))
| qq.1.1 ∘ f₀ = qq.2.1 ∘ f₁ ∧ qq.1.2 ∘ f₀' = qq.2.2 ∘ f₁'}
... ~~ {qq : ((b₀ ⟶ x) × (b₀' ⟶ x)) × ((b₁ ⟶ x) × (b₁' ⟶ x))
| coprod.induced qq.1.1 qq.1.2 ∘ coprod_of_maps f₀ f₀' =
coprod.induced qq.2.1 qq.2.2 ∘ coprod_of_maps f₁ f₁' }
:
begin
convert Bij_on.refl _,
ext qq, change _ = _ ↔ _ = _ ∧ _ = _,
rw [coprod.ext, ←assoc, ←assoc, ←assoc, ←assoc],
simp
end
... ~~ {qq : (b₀ ⊔ b₀' ⟶ x) × (b₁ ⊔ b₁' ⟶ x)
| qq.1 ∘ coprod_of_maps f₀ f₀' = qq.2 ∘ coprod_of_maps f₁ f₁'}
: Bij_on.restrict''
(Bij_on.prod'
(Bij_on.of_Is_equiv coprod.induced_Is_equiv)
(Bij_on.of_Is_equiv coprod.induced_Is_equiv))
{qq : (b₀ ⊔ b₀' ⟶ x) × (b₁ ⊔ b₁' ⟶ x)
| qq.1 ∘ coprod_of_maps f₀ f₀' = qq.2 ∘ coprod_of_maps f₁ f₁'},
begin
convert this,
funext k, apply prod.ext; apply coprod.uniqueness;
{ change _ ∘ _ ∘ _ = _ ∘ _, simp [coproduct_comparison],
rw ←assoc, simp, refl },
end
end coprod_of_pushouts
section pushout_i
parameters {C : Type u} [category.{v} C] [has_coproducts.{v} C]
-- Obviously we shouldn't really need C to have an initial object here, but oh well
parameters [has_initial_object.{v} C]
parameters {a b c : C} (f : a ⟶ b)
/-
a → a ⊔ c
↓ ↓
b → b ⊔ c
-/
def Is_pushout_i₀ : Is_pushout f i₀ i₀ (coprod_of_maps f (𝟙 c)) :=
let po := Is_pushout_coprod (Is_pushout.refl f) (Is_pushout.refl (! c)).transpose in
by convert Is_pushout_of_isomorphic po f i₀
(coprod_initial_right a) (coprod_initial_right b) (iso.refl _) _ _; simp
/-
a → c ⊔ a
↓ ↓
b → c ⊔ b
-/
def Is_pushout_i₁ : Is_pushout f i₁ i₁ (coprod_of_maps (𝟙 c) f) :=
let po := Is_pushout_coprod (Is_pushout.refl (! c)).transpose (Is_pushout.refl f) in
by convert Is_pushout_of_isomorphic po f i₁
(coprod_initial_left a) (coprod_initial_left b) (iso.refl _) _ _; simp
end pushout_i
section pushout_swap
parameters {C : Type u} [category.{v} C]
parameters {a b c : C} {f : a ⟶ b} {g₀ g₁ : b ⟶ c} (po : Is_pushout f f g₀ g₁)
def Is_pushout.swap : c ⟶ c := po.induced g₁ g₀ po.commutes.symm
def Is_pushout.swap_iso : c ≅ c :=
{ hom := po.swap,
inv := po.swap,
hom_inv_id' := by apply po.uniqueness; unfold Is_pushout.swap; rw ←assoc; simp,
inv_hom_id' := by apply po.uniqueness; unfold Is_pushout.swap; rw ←assoc; simp }
@[simp] def Is_pushout.induced_swap {x} {h₀ h₁ : b ⟶ x} {p p'} :
po.induced h₀ h₁ p ∘ po.swap = po.induced h₁ h₀ p' :=
by apply po.uniqueness; unfold Is_pushout.swap; rw ←assoc; simp
end pushout_swap
section pushout_of_maps
parameters {C : Type u} [category.{v} C]
variables {a b₀ b₁ c : C} {f₀ : a ⟶ b₀} {f₁ : a ⟶ b₁}
variables {g₀ : b₀ ⟶ c} {g₁ : b₁ ⟶ c} (po : Is_pushout f₀ f₁ g₀ g₁)
variables {a' b₀' b₁' c' : C} {f₀' : a' ⟶ b₀'} {f₁' : a' ⟶ b₁'}
variables {g₀' : b₀' ⟶ c'} {g₁' : b₁' ⟶ c'} (po' : Is_pushout f₀' f₁' g₀' g₁')
variables {a'' b₀'' b₁'' c'' : C} {f₀'' : a'' ⟶ b₀''} {f₁'' : a'' ⟶ b₁''}
variables {g₀'' : b₀'' ⟶ c''} {g₁'' : b₁'' ⟶ c''} (po'' : Is_pushout f₀'' f₁'' g₀'' g₁'')
variables (ha : a ⟶ a') (hb₀ : b₀ ⟶ b₀') (hb₁ : b₁ ⟶ b₁')
variables (h₀ : hb₀ ∘ f₀ = f₀' ∘ ha) (h₁ : hb₁ ∘ f₁ = f₁' ∘ ha)
variables (ka : a' ⟶ a'') (kb₀ : b₀' ⟶ b₀'') (kb₁ : b₁' ⟶ b₁'')
variables (k₀ : kb₀ ∘ f₀' = f₀'' ∘ ka) (k₁ : kb₁ ∘ f₁' = f₁'' ∘ ka)
include po po' h₀ h₁
def pushout_of_maps : c ⟶ c' :=
po.induced (g₀' ∘ hb₀) (g₁' ∘ hb₁)
(by rw [←assoc, ←assoc, h₀, h₁]; simp [po'.commutes])
omit po po' h₀ h₁
lemma induced_pushout_of_maps {x : C} {k₀ : b₀' ⟶ x} {k₁ : b₁' ⟶ x} {e} :
po'.induced k₀ k₁ e ∘ pushout_of_maps po po' ha hb₀ hb₁ h₀ h₁ = po.induced (k₀ ∘ hb₀) (k₁ ∘ hb₁)
(by rw [←assoc, ←assoc, h₀, h₁]; simp [e]) :=
begin
unfold pushout_of_maps,
apply po.uniqueness; { rw ←assoc, simp }
end
@[simp] lemma pushout_of_maps_commutes₀ : pushout_of_maps po po' ha hb₀ hb₁ h₀ h₁ ∘ g₀ = g₀' ∘ hb₀ :=
by simp [pushout_of_maps]
@[simp] lemma pushout_of_maps_commutes₁ : pushout_of_maps po po' ha hb₀ hb₁ h₀ h₁ ∘ g₁ = g₁' ∘ hb₁ :=
by simp [pushout_of_maps]
lemma pushout_of_maps_id : pushout_of_maps po po (𝟙 a) (𝟙 b₀) (𝟙 b₁) (by simp) (by simp) = 𝟙 _ :=
by apply pushout_induced_eq_iff; simp
lemma pushout_of_maps_comp :
pushout_of_maps po po'' (ha ≫ ka) (hb₀ ≫ kb₀) (hb₁ ≫ kb₁)
(by rw [←assoc, h₀, assoc, k₀, ←assoc]) (by rw [←assoc, h₁, assoc, k₁, ←assoc]) =
pushout_of_maps po po' ha hb₀ hb₁ h₀ h₁ ≫ pushout_of_maps po' po'' ka kb₀ kb₁ k₀ k₁ :=
by apply pushout_induced_eq_iff; rw ←assoc; simp
end pushout_of_maps
end category_theory
|
87eac40a8806d505d329a72d6bd7235a867ca2a9 | e953c38599905267210b87fb5d82dcc3e52a4214 | /hott/types/eq.hlean | d4281124c4885c431ac13d23d4a5a00a5a1486dd | [
"Apache-2.0"
] | permissive | c-cube/lean | 563c1020bff98441c4f8ba60111fef6f6b46e31b | 0fb52a9a139f720be418dafac35104468e293b66 | refs/heads/master | 1,610,753,294,113 | 1,440,451,356,000 | 1,440,499,588,000 | 41,748,334 | 0 | 0 | null | 1,441,122,656,000 | 1,441,122,656,000 | null | UTF-8 | Lean | false | false | 19,344 | hlean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Partially ported from Coq HoTT
Theorems about path types (identity types)
-/
open eq sigma sigma.ops equiv is_equiv equiv.ops
-- TODO: Rename transport_eq_... and pathover_eq_... to eq_transport_... and eq_pathover_...
namespace eq
/- Path spaces -/
variables {A B : Type} {a a₁ a₂ a₃ a₄ a' : A} {b b1 b2 : B} {f g : A → B} {h : B → A}
{p p' p'' : a₁ = a₂}
/- The path spaces of a path space are not, of course, determined; they are just the
higher-dimensional structure of the original space. -/
/- some lemmas about whiskering or other higher paths -/
theorem whisker_left_con_right (p : a₁ = a₂) {q q' q'' : a₂ = a₃} (r : q = q') (s : q' = q'')
: whisker_left p (r ⬝ s) = whisker_left p r ⬝ whisker_left p s :=
begin
induction p, induction r, induction s, reflexivity
end
theorem whisker_right_con_right (q : a₂ = a₃) (r : p = p') (s : p' = p'')
: whisker_right (r ⬝ s) q = whisker_right r q ⬝ whisker_right s q :=
begin
induction q, induction r, induction s, reflexivity
end
theorem whisker_left_con_left (p : a₁ = a₂) (p' : a₂ = a₃) {q q' : a₃ = a₄} (r : q = q')
: whisker_left (p ⬝ p') r = !con.assoc ⬝ whisker_left p (whisker_left p' r) ⬝ !con.assoc' :=
begin
induction p', induction p, induction r, induction q, reflexivity
end
theorem whisker_right_con_left {p p' : a₁ = a₂} (q : a₂ = a₃) (q' : a₃ = a₄) (r : p = p')
: whisker_right r (q ⬝ q') = !con.assoc' ⬝ whisker_right (whisker_right r q) q' ⬝ !con.assoc :=
begin
induction q', induction q, induction r, induction p, reflexivity
end
theorem whisker_left_inv_left (p : a₂ = a₁) {q q' : a₂ = a₃} (r : q = q')
: !con_inv_cancel_left⁻¹ ⬝ whisker_left p (whisker_left p⁻¹ r) ⬝ !con_inv_cancel_left = r :=
begin
induction p, induction r, induction q, reflexivity
end
theorem whisker_left_inv (p : a₁ = a₂) {q q' : a₂ = a₃} (r : q = q')
: whisker_left p r⁻¹ = (whisker_left p r)⁻¹ :=
by induction r; reflexivity
theorem whisker_right_inv {p p' : a₁ = a₂} (q : a₂ = a₃) (r : p = p')
: whisker_right r⁻¹ q = (whisker_right r q)⁻¹ :=
by induction r; reflexivity
theorem ap_eq_ap10 {f g : A → B} (p : f = g) (a : A) : ap (λh, h a) p = ap10 p a :=
by induction p;reflexivity
theorem inverse2_right_inv (r : p = p') : r ◾ inverse2 r ⬝ con.right_inv p' = con.right_inv p :=
by induction r;induction p;reflexivity
theorem inverse2_left_inv (r : p = p') : inverse2 r ◾ r ⬝ con.left_inv p' = con.left_inv p :=
by induction r;induction p;reflexivity
theorem ap_con_right_inv (f : A → B) (p : a₁ = a₂)
: ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p) ⬝ con.right_inv (ap f p)
= ap (ap f) (con.right_inv p) :=
by induction p;reflexivity
theorem ap_con_left_inv (f : A → B) (p : a₁ = a₂)
: ap_con f p⁻¹ p ⬝ whisker_right (ap_inv f p) _ ⬝ con.left_inv (ap f p)
= ap (ap f) (con.left_inv p) :=
by induction p;reflexivity
theorem idp_con_whisker_left {q q' : a₂ = a₃} (r : q = q') :
!idp_con⁻¹ ⬝ whisker_left idp r = r ⬝ !idp_con⁻¹ :=
by induction r;induction q;reflexivity
theorem whisker_left_idp_con {q q' : a₂ = a₃} (r : q = q') :
whisker_left idp r ⬝ !idp_con = !idp_con ⬝ r :=
by induction r;induction q;reflexivity
theorem idp_con_idp {p : a = a} (q : p = idp) : idp_con p ⬝ q = ap (λp, idp ⬝ p) q :=
by cases q;reflexivity
definition ap_weakly_constant [unfold 8] {A B : Type} {f : A → B} {b : B} (p : Πx, f x = b)
{x y : A} (q : x = y) : ap f q = p x ⬝ (p y)⁻¹ :=
by induction q;exact !con.right_inv⁻¹
definition inv2_inv {p q : a = a'} (r : p = q) : inverse2 r⁻¹ = (inverse2 r)⁻¹ :=
by induction r;reflexivity
definition inv2_con {p p' p'' : a = a'} (r : p = p') (r' : p' = p'')
: inverse2 (r ⬝ r') = inverse2 r ⬝ inverse2 r' :=
by induction r';induction r;reflexivity
definition con2_inv {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂)
: (r₁ ◾ r₂)⁻¹ = r₁⁻¹ ◾ r₂⁻¹ :=
by induction r₁;induction r₂;reflexivity
theorem eq_con_inv_of_con_eq_whisker_left {A : Type} {a a₂ a₃ : A}
{p : a = a₂} {q q' : a₂ = a₃} {r : a = a₃} (s' : q = q') (s : p ⬝ q' = r) :
eq_con_inv_of_con_eq (whisker_left p s' ⬝ s)
= eq_con_inv_of_con_eq s ⬝ whisker_left r (inverse2 s')⁻¹ :=
by induction s';induction q;induction s;reflexivity
theorem right_inv_eq_idp {A : Type} {a : A} {p : a = a} (r : p = idpath a) :
con.right_inv p = r ◾ inverse2 r :=
by cases r;reflexivity
/- Transporting in path spaces.
There are potentially a lot of these lemmas, so we adopt a uniform naming scheme:
- `l` means the left endpoint varies
- `r` means the right endpoint varies
- `F` means application of a function to that (varying) endpoint.
-/
definition transport_eq_l (p : a₁ = a₂) (q : a₁ = a₃)
: transport (λx, x = a₃) p q = p⁻¹ ⬝ q :=
by induction p; induction q; reflexivity
definition transport_eq_r (p : a₂ = a₃) (q : a₁ = a₂)
: transport (λx, a₁ = x) p q = q ⬝ p :=
by induction p; induction q; reflexivity
definition transport_eq_lr (p : a₁ = a₂) (q : a₁ = a₁)
: transport (λx, x = x) p q = p⁻¹ ⬝ q ⬝ p :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_Fl (p : a₁ = a₂) (q : f a₁ = b)
: transport (λx, f x = b) p q = (ap f p)⁻¹ ⬝ q :=
by induction p; induction q; reflexivity
definition transport_eq_Fr (p : a₁ = a₂) (q : b = f a₁)
: transport (λx, b = f x) p q = q ⬝ (ap f p) :=
by induction p; reflexivity
definition transport_eq_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁)
: transport (λx, f x = g x) p q = (ap f p)⁻¹ ⬝ q ⬝ (ap g p) :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_FlFr_D {B : A → Type} {f g : Πa, B a}
(p : a₁ = a₂) (q : f a₁ = g a₁)
: transport (λx, f x = g x) p q = (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) :=
by induction p; rewrite [▸*,idp_con,ap_id]
definition transport_eq_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁)
: transport (λx, h (f x) = x) p q = (ap h (ap f p))⁻¹ ⬝ q ⬝ p :=
by induction p; rewrite [▸*,idp_con]
definition transport_eq_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁))
: transport (λx, x = h (f x)) p q = p⁻¹ ⬝ q ⬝ (ap h (ap f p)) :=
by induction p; rewrite [▸*,idp_con]
/- Pathovers -/
-- In the comment we give the fibration of the pathover
-- we should probably try to do everything just with pathover_eq (defined in cubical.square),
-- the following definitions may be removed in future.
definition pathover_eq_l (p : a₁ = a₂) (q : a₁ = a₃) : q =[p] p⁻¹ ⬝ q := /-(λx, x = a₃)-/
by induction p; induction q; exact idpo
definition pathover_eq_r (p : a₂ = a₃) (q : a₁ = a₂) : q =[p] q ⬝ p := /-(λx, a₁ = x)-/
by induction p; induction q; exact idpo
definition pathover_eq_lr (p : a₁ = a₂) (q : a₁ = a₁) : q =[p] p⁻¹ ⬝ q ⬝ p := /-(λx, x = x)-/
by induction p; rewrite [▸*,idp_con]; exact idpo
definition pathover_eq_Fl (p : a₁ = a₂) (q : f a₁ = b) : q =[p] (ap f p)⁻¹ ⬝ q := /-(λx, f x = b)-/
by induction p; induction q; exact idpo
definition pathover_eq_Fr (p : a₁ = a₂) (q : b = f a₁) : q =[p] q ⬝ (ap f p) := /-(λx, b = f x)-/
by induction p; exact idpo
definition pathover_eq_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p] (ap f p)⁻¹ ⬝ q ⬝ (ap g p) :=
/-(λx, f x = g x)-/
by induction p; rewrite [▸*,idp_con]; exact idpo
definition pathover_eq_FlFr_D {B : A → Type} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁)
: q =[p] (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) := /-(λx, f x = g x)-/
by induction p; rewrite [▸*,idp_con,ap_id];exact idpo
definition pathover_eq_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : q =[p] (ap h (ap f p))⁻¹ ⬝ q ⬝ p :=
/-(λx, h (f x) = x)-/
by induction p; rewrite [▸*,idp_con];exact idpo
definition pathover_eq_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : q =[p] p⁻¹ ⬝ q ⬝ (ap h (ap f p)) :=
/-(λx, x = h (f x))-/
by induction p; rewrite [▸*,idp_con];exact idpo
definition pathover_eq_r_idp (p : a₁ = a₂) : idp =[p] p := /-(λx, a₁ = x)-/
by induction p; exact idpo
definition pathover_eq_l_idp (p : a₁ = a₂) : idp =[p] p⁻¹ := /-(λx, x = a₁)-/
by induction p; exact idpo
definition pathover_eq_l_idp' (p : a₁ = a₂) : idp =[p⁻¹] p := /-(λx, x = a₂)-/
by induction p; exact idpo
-- The Functorial action of paths is [ap].
/- Equivalences between path spaces -/
/- [ap_closed] is in init.equiv -/
definition equiv_ap (f : A → B) [H : is_equiv f] (a₁ a₂ : A)
: (a₁ = a₂) ≃ (f a₁ = f a₂) :=
equiv.mk (ap f) _
/- Path operations are equivalences -/
definition is_equiv_eq_inverse (a₁ a₂ : A) : is_equiv (inverse : a₁ = a₂ → a₂ = a₁) :=
is_equiv.mk inverse inverse inv_inv inv_inv (λp, eq.rec_on p idp)
local attribute is_equiv_eq_inverse [instance]
definition eq_equiv_eq_symm (a₁ a₂ : A) : (a₁ = a₂) ≃ (a₂ = a₁) :=
equiv.mk inverse _
definition is_equiv_concat_left [constructor] [instance] (p : a₁ = a₂) (a₃ : A)
: is_equiv (concat p : a₂ = a₃ → a₁ = a₃) :=
is_equiv.mk (concat p) (concat p⁻¹)
(con_inv_cancel_left p)
(inv_con_cancel_left p)
(λq, by induction p;induction q;reflexivity)
local attribute is_equiv_concat_left [instance]
definition equiv_eq_closed_left [constructor] (a₃ : A) (p : a₁ = a₂) : (a₁ = a₃) ≃ (a₂ = a₃) :=
equiv.mk (concat p⁻¹) _
definition is_equiv_concat_right [constructor] [instance] (p : a₂ = a₃) (a₁ : A)
: is_equiv (λq : a₁ = a₂, q ⬝ p) :=
is_equiv.mk (λq, q ⬝ p) (λq, q ⬝ p⁻¹)
(λq, inv_con_cancel_right q p)
(λq, con_inv_cancel_right q p)
(λq, by induction p;induction q;reflexivity)
local attribute is_equiv_concat_right [instance]
definition equiv_eq_closed_right [constructor] (a₁ : A) (p : a₂ = a₃) : (a₁ = a₂) ≃ (a₁ = a₃) :=
equiv.mk (λq, q ⬝ p) _
definition eq_equiv_eq_closed [constructor] (p : a₁ = a₂) (q : a₃ = a₄) : (a₁ = a₃) ≃ (a₂ = a₄) :=
equiv.trans (equiv_eq_closed_left a₃ p) (equiv_eq_closed_right a₂ q)
definition is_equiv_whisker_left [constructor] (p : a₁ = a₂) (q r : a₂ = a₃)
: is_equiv (whisker_left p : q = r → p ⬝ q = p ⬝ r) :=
begin
fapply adjointify,
{intro s, apply (!cancel_left s)},
{intro s,
apply concat, {apply whisker_left_con_right},
apply concat, rotate_left 1, apply (whisker_left_inv_left p s),
apply concat2,
{apply concat, {apply whisker_left_con_right},
apply concat2,
{induction p, induction q, reflexivity},
{reflexivity}},
{induction p, induction r, reflexivity}},
{intro s, induction s, induction q, induction p, reflexivity}
end
definition eq_equiv_con_eq_con_left [constructor] (p : a₁ = a₂) (q r : a₂ = a₃)
: (q = r) ≃ (p ⬝ q = p ⬝ r) :=
equiv.mk _ !is_equiv_whisker_left
definition is_equiv_whisker_right [constructor] {p q : a₁ = a₂} (r : a₂ = a₃)
: is_equiv (λs, whisker_right s r : p = q → p ⬝ r = q ⬝ r) :=
begin
fapply adjointify,
{intro s, apply (!cancel_right s)},
{intro s, induction r, cases s, induction q, reflexivity},
{intro s, induction s, induction r, induction p, reflexivity}
end
definition eq_equiv_con_eq_con_right [constructor] (p q : a₁ = a₂) (r : a₂ = a₃)
: (p = q) ≃ (p ⬝ r = q ⬝ r) :=
equiv.mk _ !is_equiv_whisker_right
/-
The following proofs can be simplified a bit by concatenating previous equivalences.
However, these proofs have the advantage that the inverse is definitionally equal to
what we would expect
-/
definition is_equiv_con_eq_of_eq_inv_con [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_eq_of_eq_inv_con : p = r⁻¹ ⬝ q → r ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_inv_con_of_con_eq},
{ intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq],
con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]},
{ intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq],
con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] },
end
definition eq_inv_con_equiv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: (p = r⁻¹ ⬝ q) ≃ (r ⬝ p = q) :=
equiv.mk _ !is_equiv_con_eq_of_eq_inv_con
definition is_equiv_con_eq_of_eq_con_inv [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_eq_of_eq_con_inv : r = q ⬝ p⁻¹ → r ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_con_inv_of_con_eq},
{ intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]]},
{ intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]] },
end
definition eq_con_inv_equiv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: (r = q ⬝ p⁻¹) ≃ (r ⬝ p = q) :=
equiv.mk _ !is_equiv_con_eq_of_eq_con_inv
definition is_equiv_inv_con_eq_of_eq_con [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂)
: is_equiv (inv_con_eq_of_eq_con : p = r ⬝ q → r⁻¹ ⬝ p = q) :=
begin
fapply adjointify,
{ apply eq_con_of_inv_con_eq},
{ intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq],
con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]},
{ intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq],
con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] },
end
definition eq_con_equiv_inv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂)
: (p = r ⬝ q) ≃ (r⁻¹ ⬝ p = q) :=
equiv.mk _ !is_equiv_inv_con_eq_of_eq_con
definition is_equiv_con_inv_eq_of_eq_con [constructor] (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (con_inv_eq_of_eq_con : r = q ⬝ p → r ⬝ p⁻¹ = q) :=
begin
fapply adjointify,
{ apply eq_con_of_con_inv_eq},
{ intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]]},
{ intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]] },
end
definition eq_con_equiv_con_inv_eq (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁)
: (r = q ⬝ p) ≃ (r ⬝ p⁻¹ = q) :=
equiv.mk _ !is_equiv_con_inv_eq_of_eq_con
local attribute is_equiv_inv_con_eq_of_eq_con
is_equiv_con_inv_eq_of_eq_con
is_equiv_con_eq_of_eq_con_inv
is_equiv_con_eq_of_eq_inv_con [instance]
definition is_equiv_eq_con_of_inv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_of_inv_con_eq : r⁻¹ ⬝ q = p → q = r ⬝ p) :=
is_equiv_inv inv_con_eq_of_eq_con
definition is_equiv_eq_con_of_con_inv_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_of_con_inv_eq : q ⬝ p⁻¹ = r → q = r ⬝ p) :=
is_equiv_inv con_inv_eq_of_eq_con
definition is_equiv_eq_con_inv_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_con_inv_of_con_eq : r ⬝ p = q → r = q ⬝ p⁻¹) :=
is_equiv_inv con_eq_of_eq_con_inv
definition is_equiv_eq_inv_con_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁)
: is_equiv (eq_inv_con_of_con_eq : r ⬝ p = q → p = r⁻¹ ⬝ q) :=
is_equiv_inv con_eq_of_eq_inv_con
definition is_equiv_con_inv_eq_idp [constructor] (p q : a₁ = a₂)
: is_equiv (con_inv_eq_idp : p = q → p ⬝ q⁻¹ = idp) :=
begin
fapply adjointify,
{ apply eq_of_con_inv_eq_idp},
{ intro s, induction q, esimp at *, cases s, reflexivity},
{ intro s, induction s, induction p, reflexivity},
end
definition is_equiv_inv_con_eq_idp [constructor] (p q : a₁ = a₂)
: is_equiv (inv_con_eq_idp : p = q → q⁻¹ ⬝ p = idp) :=
begin
fapply adjointify,
{ apply eq_of_inv_con_eq_idp},
{ intro s, induction q, esimp [eq_of_inv_con_eq_idp] at *,
eapply is_equiv_rect (eq_equiv_con_eq_con_left idp p idp), clear s,
intro s, cases s, reflexivity},
{ intro s, induction s, induction p, reflexivity},
end
definition eq_equiv_con_inv_eq_idp [constructor] (p q : a₁ = a₂) : (p = q) ≃ (p ⬝ q⁻¹ = idp) :=
equiv.mk _ !is_equiv_con_inv_eq_idp
definition eq_equiv_inv_con_eq_idp [constructor] (p q : a₁ = a₂) : (p = q) ≃ (q⁻¹ ⬝ p = idp) :=
equiv.mk _ !is_equiv_inv_con_eq_idp
/- Pathover Equivalences -/
definition pathover_eq_equiv_l (p : a₁ = a₂) (q : a₁ = a₃) (r : a₂ = a₃) : q =[p] r ≃ q = p ⬝ r :=
/-(λx, x = a₃)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_r (p : a₂ = a₃) (q : a₁ = a₂) (r : a₁ = a₃) : q =[p] r ≃ q ⬝ p = r :=
/-(λx, a₁ = x)-/
by induction p; apply pathover_idp
definition pathover_eq_equiv_lr (p : a₁ = a₂) (q : a₁ = a₁) (r : a₂ = a₂)
: q =[p] r ≃ q ⬝ p = p ⬝ r := /-(λx, x = x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_Fl (p : a₁ = a₂) (q : f a₁ = b) (r : f a₂ = b)
: q =[p] r ≃ q = ap f p ⬝ r := /-(λx, f x = b)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_Fr (p : a₁ = a₂) (q : b = f a₁) (r : b = f a₂)
: q =[p] r ≃ q ⬝ ap f p = r := /-(λx, b = f x)-/
by induction p; apply pathover_idp
definition pathover_eq_equiv_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) (r : f a₂ = g a₂)
: q =[p] r ≃ q ⬝ ap g p = ap f p ⬝ r := /-(λx, f x = g x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) (r : h (f a₂) = a₂)
: q =[p] r ≃ q ⬝ p = ap h (ap f p) ⬝ r :=
/-(λx, h (f x) = x)-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
definition pathover_eq_equiv_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) (r : a₂ = h (f a₂))
: q =[p] r ≃ q ⬝ ap h (ap f p) = p ⬝ r :=
/-(λx, x = h (f x))-/
by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹
-- a lot of this library still needs to be ported from Coq HoTT
end eq
|
4a32fb51dbd9fc655aea11a1c1ef81a16b6c4889 | 36c7a18fd72e5b57229bd8ba36493daf536a19ce | /tests/lean/run/local_ctx_bug.lean | 5a78c928cd4a017398578395f8f48a12742965d7 | [
"Apache-2.0"
] | permissive | YHVHvx/lean | 732bf0fb7a298cd7fe0f15d82f8e248c11db49e9 | 038369533e0136dd395dc252084d3c1853accbf2 | refs/heads/master | 1,610,701,080,210 | 1,449,128,595,000 | 1,449,128,595,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 899 | lean | import data.finset data.finset.card data.finset.equiv
open nat nat.finset decidable
namespace finset
variable {A : Type}
open finset (to_nat)
open finset (of_nat)
private lemma of_nat_eq_insert : ∀ {n s : nat}, n ∉ of_nat s → of_nat (2^n + s) = insert n (of_nat s)
| 0 s h := sorry
| (succ n) s h :=
have n ∉ of_nat s, from sorry,
assert of_nat s = insert n (of_nat s), from sorry,
finset.ext (λ x,
have gen : ∀ m, m ∈ of_nat (2^(succ n) + s) ↔ m ∈ insert (succ n) (of_nat s)
| zero :=
assert aux₁ : odd (2^(succ n) + s) ↔ odd s, from sorry,
calc
0 ∈ of_nat (2^(succ n) + s) ↔ odd (2^(succ n) + s) : sorry
... ↔ odd s : aux₁
... ↔ 0 ∈ insert (succ n) (of_nat s) : sorry
| (succ m) := sorry,
gen x)
end finset
|
b410dacd1efc8b11456d98dd8a9562fdbb815cff | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/order/lattice.lean | fcb07725b9742d3c3495532e414a8dbe73ad2f1a | [
"Apache-2.0"
] | permissive | rmitta/mathlib | 8d90aee30b4db2b013e01f62c33f297d7e64a43d | 883d974b608845bad30ae19e27e33c285200bf84 | refs/heads/master | 1,585,776,832,544 | 1,576,874,096,000 | 1,576,874,096,000 | 153,663,165 | 0 | 2 | Apache-2.0 | 1,544,806,490,000 | 1,539,884,365,000 | Lean | UTF-8 | Lean | false | false | 16,418 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Defines the inf/sup (semi)-lattice with optionally top/bot type class hierarchy.
-/
import order.basic
set_option old_structure_cmd true
universes u v w
-- TODO: move this eventually, if we decide to use them
attribute [ematch] le_trans lt_of_le_of_lt lt_of_lt_of_le lt_trans
section
variable {α : Type u}
-- TODO: this seems crazy, but it also seems to work reasonably well
@[ematch] theorem le_antisymm' [partial_order α] : ∀ {a b : α}, (: a ≤ b :) → b ≤ a → a = b :=
@le_antisymm _ _
end
/- TODO: automatic construction of dual definitions / theorems -/
namespace lattice
reserve infixl ` ⊓ `:70
reserve infixl ` ⊔ `:65
/-- Typeclass for the `⊔` (`\lub`) notation -/
class has_sup (α : Type u) := (sup : α → α → α)
/-- Typeclass for the `⊓` (`\glb`) notation -/
class has_inf (α : Type u) := (inf : α → α → α)
infix ⊔ := has_sup.sup
infix ⊓ := has_inf.inf
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_sup` is a join-semilattice, that is, a partial order
with a join (a.k.a. lub / least upper bound, sup / supremum) operation
`⊔` which is the least element larger than both factors. -/
class semilattice_sup (α : Type u) extends has_sup α, partial_order α :=
(le_sup_left : ∀ a b : α, a ≤ a ⊔ b)
(le_sup_right : ∀ a b : α, b ≤ a ⊔ b)
(sup_le : ∀ a b c : α, a ≤ c → b ≤ c → a ⊔ b ≤ c)
end prio
section semilattice_sup
variables {α : Type u} [semilattice_sup α] {a b c d : α}
@[simp] theorem le_sup_left : a ≤ a ⊔ b :=
semilattice_sup.le_sup_left a b
@[ematch] theorem le_sup_left' : a ≤ (: a ⊔ b :) :=
semilattice_sup.le_sup_left a b
@[simp] theorem le_sup_right : b ≤ a ⊔ b :=
semilattice_sup.le_sup_right a b
@[ematch] theorem le_sup_right' : b ≤ (: a ⊔ b :) :=
semilattice_sup.le_sup_right a b
theorem le_sup_left_of_le (h : c ≤ a) : c ≤ a ⊔ b :=
by finish
theorem le_sup_right_of_le (h : c ≤ b) : c ≤ a ⊔ b :=
by finish
theorem sup_le : a ≤ c → b ≤ c → a ⊔ b ≤ c :=
semilattice_sup.sup_le a b c
@[simp] theorem sup_le_iff : a ⊔ b ≤ c ↔ a ≤ c ∧ b ≤ c :=
⟨assume h : a ⊔ b ≤ c, ⟨le_trans le_sup_left h, le_trans le_sup_right h⟩,
assume ⟨h₁, h₂⟩, sup_le h₁ h₂⟩
-- TODO: if we just write le_antisymm, Lean doesn't know which ≤ we want to use
-- Can we do anything about that?
theorem sup_of_le_left (h : b ≤ a) : a ⊔ b = a :=
by apply le_antisymm; finish
theorem sup_of_le_right (h : a ≤ b) : a ⊔ b = b :=
by apply le_antisymm; finish
theorem sup_le_sup (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊔ c ≤ b ⊔ d :=
by finish
theorem sup_le_sup_left (h₁ : a ≤ b) (c) : c ⊔ a ≤ c ⊔ b :=
by finish
theorem sup_le_sup_right (h₁ : a ≤ b) (c) : a ⊔ c ≤ b ⊔ c :=
by finish
theorem le_of_sup_eq (h : a ⊔ b = b) : a ≤ b :=
by finish
@[simp] lemma sup_lt_iff [is_total α (≤)] {a b c : α} : b ⊔ c < a ↔ b < a ∧ c < a :=
begin
cases (is_total.total (≤) b c) with h,
{ simp [sup_of_le_right h], exact ⟨λI, ⟨lt_of_le_of_lt h I, I⟩, λH, H.2⟩ },
{ simp [sup_of_le_left h], exact ⟨λI, ⟨I, lt_of_le_of_lt h I⟩, λH, H.1⟩ }
end
@[simp] theorem sup_idem : a ⊔ a = a :=
by apply le_antisymm; finish
instance sup_is_idempotent : is_idempotent α (⊔) := ⟨@sup_idem _ _⟩
theorem sup_comm : a ⊔ b = b ⊔ a :=
by apply le_antisymm; finish
instance sup_is_commutative : is_commutative α (⊔) := ⟨@sup_comm _ _⟩
theorem sup_assoc : a ⊔ b ⊔ c = a ⊔ (b ⊔ c) :=
by apply le_antisymm; finish
instance sup_is_associative : is_associative α (⊔) := ⟨@sup_assoc _ _⟩
lemma sup_left_comm (a b c : α) : a ⊔ (b ⊔ c) = b ⊔ (a ⊔ c) :=
by rw [← sup_assoc, ← sup_assoc, @sup_comm α _ a]
lemma forall_le_or_exists_lt_sup (a : α) : (∀b, b ≤ a) ∨ (∃b, a < b) :=
suffices (∃b, ¬b ≤ a) → (∃b, a < b),
by rwa [classical.or_iff_not_imp_left, classical.not_forall],
assume ⟨b, hb⟩,
have a ≠ a ⊔ b, from assume eq, hb $ eq.symm ▸ le_sup_right,
⟨a ⊔ b, lt_of_le_of_ne le_sup_left ‹a ≠ a ⊔ b›⟩
theorem semilattice_sup.ext_sup {α} {A B : semilattice_sup α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y)
(x y : α) : (by haveI := A; exact (x ⊔ y)) = x ⊔ y :=
eq_of_forall_ge_iff $ λ c,
by simp only [sup_le_iff]; rw [← H, @sup_le_iff α A, H, H]
theorem semilattice_sup.ext {α} {A B : semilattice_sup α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
haveI this := partial_order.ext H,
have ss := funext (λ x, funext $ semilattice_sup.ext_sup H x),
cases A; cases B; injection this; congr'
end
lemma directed_of_sup {β : Type*} {r : β → β → Prop} {f : α → β}
(hf : ∀a₁ a₂, a₁ ≤ a₂ → r (f a₁) (f a₂)) : directed r f :=
assume x y, ⟨x ⊔ y, hf _ _ le_sup_left, hf _ _ le_sup_right⟩
end semilattice_sup
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A `semilattice_inf` is a meet-semilattice, that is, a partial order
with a meet (a.k.a. glb / greatest lower bound, inf / infimum) operation
`⊓` which is the greatest element smaller than both factors. -/
class semilattice_inf (α : Type u) extends has_inf α, partial_order α :=
(inf_le_left : ∀ a b : α, a ⊓ b ≤ a)
(inf_le_right : ∀ a b : α, a ⊓ b ≤ b)
(le_inf : ∀ a b c : α, a ≤ b → a ≤ c → a ≤ b ⊓ c)
end prio
section semilattice_inf
variables {α : Type u} [semilattice_inf α] {a b c d : α}
@[simp] theorem inf_le_left : a ⊓ b ≤ a :=
semilattice_inf.inf_le_left a b
@[ematch] theorem inf_le_left' : (: a ⊓ b :) ≤ a :=
semilattice_inf.inf_le_left a b
@[simp] theorem inf_le_right : a ⊓ b ≤ b :=
semilattice_inf.inf_le_right a b
@[ematch] theorem inf_le_right' : (: a ⊓ b :) ≤ b :=
semilattice_inf.inf_le_right a b
theorem le_inf : a ≤ b → a ≤ c → a ≤ b ⊓ c :=
semilattice_inf.le_inf a b c
theorem inf_le_left_of_le (h : a ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_left h
theorem inf_le_right_of_le (h : b ≤ c) : a ⊓ b ≤ c :=
le_trans inf_le_right h
@[simp] theorem le_inf_iff : a ≤ b ⊓ c ↔ a ≤ b ∧ a ≤ c :=
⟨assume h : a ≤ b ⊓ c, ⟨le_trans h inf_le_left, le_trans h inf_le_right⟩,
assume ⟨h₁, h₂⟩, le_inf h₁ h₂⟩
theorem inf_of_le_left (h : a ≤ b) : a ⊓ b = a :=
by apply le_antisymm; finish
theorem inf_of_le_right (h : b ≤ a) : a ⊓ b = b :=
by apply le_antisymm; finish
theorem inf_le_inf (h₁ : a ≤ b) (h₂ : c ≤ d) : a ⊓ c ≤ b ⊓ d :=
by finish
theorem le_of_inf_eq (h : a ⊓ b = a) : a ≤ b :=
by finish
@[simp] lemma lt_inf_iff [is_total α (≤)] {a b c : α} : a < b ⊓ c ↔ a < b ∧ a < c :=
begin
cases (is_total.total (≤) b c) with h,
{ simp [inf_of_le_left h], exact ⟨λI, ⟨I, lt_of_lt_of_le I h⟩, λH, H.1⟩ },
{ simp [inf_of_le_right h], exact ⟨λI, ⟨lt_of_lt_of_le I h, I⟩, λH, H.2⟩ }
end
@[simp] theorem inf_idem : a ⊓ a = a :=
by apply le_antisymm; finish
instance inf_is_idempotent : is_idempotent α (⊓) := ⟨@inf_idem _ _⟩
theorem inf_comm : a ⊓ b = b ⊓ a :=
by apply le_antisymm; finish
instance inf_is_commutative : is_commutative α (⊓) := ⟨@inf_comm _ _⟩
theorem inf_assoc : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) :=
by apply le_antisymm; finish
instance inf_is_associative : is_associative α (⊓) := ⟨@inf_assoc _ _⟩
lemma inf_left_comm (a b c : α) : a ⊓ (b ⊓ c) = b ⊓ (a ⊓ c) :=
by rw [← inf_assoc, ← inf_assoc, @inf_comm α _ a]
lemma forall_le_or_exists_lt_inf (a : α) : (∀b, a ≤ b) ∨ (∃b, b < a) :=
suffices (∃b, ¬a ≤ b) → (∃b, b < a),
by rwa [classical.or_iff_not_imp_left, classical.not_forall],
assume ⟨b, hb⟩,
have a ⊓ b ≠ a, from assume eq, hb $ eq ▸ inf_le_right,
⟨a ⊓ b, lt_of_le_of_ne inf_le_left ‹a ⊓ b ≠ a›⟩
theorem semilattice_inf.ext_inf {α} {A B : semilattice_inf α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y)
(x y : α) : (by haveI := A; exact (x ⊓ y)) = x ⊓ y :=
eq_of_forall_le_iff $ λ c,
by simp only [le_inf_iff]; rw [← H, @le_inf_iff α A, H, H]
theorem semilattice_inf.ext {α} {A B : semilattice_inf α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
haveI this := partial_order.ext H,
have ss := funext (λ x, funext $ semilattice_inf.ext_inf H x),
cases A; cases B; injection this; congr'
end
lemma directed_of_inf {β : Type*} {r : β → β → Prop} {f : α → β}
(hf : ∀a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f :=
assume x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩
end semilattice_inf
/- Lattices -/
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A lattice is a join-semilattice which is also a meet-semilattice. -/
-- TODO(lint): Fix double namespace issue
@[nolint] class lattice (α : Type u) extends semilattice_sup α, semilattice_inf α
end prio
section lattice
variables {α : Type u} [lattice α] {a b c d : α}
/- Distributivity laws -/
/- TODO: better names? -/
theorem sup_inf_le : a ⊔ (b ⊓ c) ≤ (a ⊔ b) ⊓ (a ⊔ c) :=
by finish
theorem le_inf_sup : (a ⊓ b) ⊔ (a ⊓ c) ≤ a ⊓ (b ⊔ c) :=
by finish
theorem inf_sup_self : a ⊓ (a ⊔ b) = a :=
le_antisymm (by finish) (by finish)
theorem sup_inf_self : a ⊔ (a ⊓ b) = a :=
le_antisymm (by finish) (by finish)
theorem ext {α} {A B : lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have SS : @lattice.to_semilattice_sup α A =
@lattice.to_semilattice_sup α B := semilattice_sup.ext H,
have II := semilattice_inf.ext H,
resetI, cases A; cases B; injection SS; injection II; congr'
end
end lattice
variables {α : Type u} {x y z w : α}
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A distributive lattice is a lattice that satisfies any of four
equivalent distribution properties (of sup over inf or inf over sup,
on the left or right). A classic example of a distributive lattice
is the lattice of subsets of a set, and in fact this example is
generic in the sense that every distributive lattice is realizable
as a sublattice of a powerset lattice. -/
class distrib_lattice α extends lattice α :=
(le_sup_inf : ∀x y z : α, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z))
end prio
section distrib_lattice
variables [distrib_lattice α]
theorem le_sup_inf : ∀{x y z : α}, (x ⊔ y) ⊓ (x ⊔ z) ≤ x ⊔ (y ⊓ z) :=
distrib_lattice.le_sup_inf
theorem sup_inf_left : x ⊔ (y ⊓ z) = (x ⊔ y) ⊓ (x ⊔ z) :=
le_antisymm sup_inf_le le_sup_inf
theorem sup_inf_right : (y ⊓ z) ⊔ x = (y ⊔ x) ⊓ (z ⊔ x) :=
by simp only [sup_inf_left, λy:α, @sup_comm α _ y x, eq_self_iff_true]
theorem inf_sup_left : x ⊓ (y ⊔ z) = (x ⊓ y) ⊔ (x ⊓ z) :=
calc x ⊓ (y ⊔ z) = (x ⊓ (x ⊔ z)) ⊓ (y ⊔ z) : by rw [inf_sup_self]
... = x ⊓ ((x ⊓ y) ⊔ z) : by simp only [inf_assoc, sup_inf_right, eq_self_iff_true]
... = (x ⊔ (x ⊓ y)) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_inf_self]
... = ((x ⊓ y) ⊔ x) ⊓ ((x ⊓ y) ⊔ z) : by rw [sup_comm]
... = (x ⊓ y) ⊔ (x ⊓ z) : by rw [sup_inf_left]
theorem inf_sup_right : (y ⊔ z) ⊓ x = (y ⊓ x) ⊔ (z ⊓ x) :=
by simp only [inf_sup_left, λy:α, @inf_comm α _ y x, eq_self_iff_true]
lemma eq_of_sup_eq_inf_eq {α : Type u} [distrib_lattice α] {a b c : α}
(h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c :=
le_antisymm
(calc b ≤ (c ⊓ a) ⊔ b : le_sup_right
... = (c ⊔ b) ⊓ (a ⊔ b) : sup_inf_right
... = c ⊔ (c ⊓ a) : by rw [←h₁, sup_inf_left, ←h₂]; simp only [sup_comm, eq_self_iff_true]
... = c : sup_inf_self)
(calc c ≤ (b ⊓ a) ⊔ c : le_sup_right
... = (b ⊔ c) ⊓ (a ⊔ c) : sup_inf_right
... = b ⊔ (b ⊓ a) : by rw [h₁, sup_inf_left, h₂]; simp only [sup_comm, eq_self_iff_true]
... = b : sup_inf_self)
end distrib_lattice
/- Lattices derived from linear orders -/
@[priority 100] -- see Note [lower instance priority]
instance lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : lattice α :=
{ sup := max,
le_sup_left := le_max_left,
le_sup_right := le_max_right,
sup_le := assume a b c, max_le,
inf := min,
inf_le_left := min_le_left,
inf_le_right := min_le_right,
le_inf := assume a b c, le_min,
..o }
theorem sup_eq_max [decidable_linear_order α] : x ⊔ y = max x y := rfl
theorem inf_eq_min [decidable_linear_order α] : x ⊓ y = min x y := rfl
@[priority 100] -- see Note [lower instance priority]
instance distrib_lattice_of_decidable_linear_order {α : Type u} [o : decidable_linear_order α] : distrib_lattice α :=
{ le_sup_inf := assume a b c,
match le_total b c with
| or.inl h := inf_le_left_of_le $ sup_le_sup_left (le_inf (le_refl b) h) _
| or.inr h := inf_le_right_of_le $ sup_le_sup_left (le_inf h (le_refl c)) _
end,
..lattice.lattice_of_decidable_linear_order }
instance nat.distrib_lattice : distrib_lattice ℕ :=
by apply_instance
end lattice
namespace monotone
open lattice
variables {α : Type u} {β : Type v}
lemma le_map_sup [semilattice_sup α] [semilattice_sup β]
{f : α → β} (h : monotone f) (x y : α) :
f x ⊔ f y ≤ f (x ⊔ y) :=
sup_le (h le_sup_left) (h le_sup_right)
lemma map_inf_le [semilattice_inf α] [semilattice_inf β]
{f : α → β} (h : monotone f) (x y : α) :
f (x ⊓ y) ≤ f x ⊓ f y :=
le_inf (h inf_le_left) (h inf_le_right)
end monotone
namespace order_dual
open lattice
variable (α : Type*)
instance [has_inf α] : has_sup (order_dual α) := ⟨((⊓) : α → α → α)⟩
instance [has_sup α] : has_inf (order_dual α) := ⟨((⊔) : α → α → α)⟩
instance [semilattice_inf α] : semilattice_sup (order_dual α) :=
{ le_sup_left := @inf_le_left α _,
le_sup_right := @inf_le_right α _,
sup_le := assume a b c hca hcb, @le_inf α _ _ _ _ hca hcb,
.. order_dual.partial_order α, .. order_dual.lattice.has_sup α }
instance [semilattice_sup α] : semilattice_inf (order_dual α) :=
{ inf_le_left := @le_sup_left α _,
inf_le_right := @le_sup_right α _,
le_inf := assume a b c hca hcb, @sup_le α _ _ _ _ hca hcb,
.. order_dual.partial_order α, .. order_dual.lattice.has_inf α }
instance [lattice α] : lattice (order_dual α) :=
{ .. order_dual.lattice.semilattice_sup α, .. order_dual.lattice.semilattice_inf α }
instance [distrib_lattice α] : distrib_lattice (order_dual α) :=
{ le_sup_inf := assume x y z, le_of_eq inf_sup_left.symm,
.. order_dual.lattice.lattice α }
end order_dual
namespace prod
open lattice
variables (α : Type u) (β : Type v)
instance [has_sup α] [has_sup β] : has_sup (α × β) := ⟨λp q, ⟨p.1 ⊔ q.1, p.2 ⊔ q.2⟩⟩
instance [has_inf α] [has_inf β] : has_inf (α × β) := ⟨λp q, ⟨p.1 ⊓ q.1, p.2 ⊓ q.2⟩⟩
instance [semilattice_sup α] [semilattice_sup β] : semilattice_sup (α × β) :=
{ sup_le := assume a b c h₁ h₂, ⟨sup_le h₁.1 h₂.1, sup_le h₁.2 h₂.2⟩,
le_sup_left := assume a b, ⟨le_sup_left, le_sup_left⟩,
le_sup_right := assume a b, ⟨le_sup_right, le_sup_right⟩,
.. prod.partial_order α β, .. prod.lattice.has_sup α β }
instance [semilattice_inf α] [semilattice_inf β] : semilattice_inf (α × β) :=
{ le_inf := assume a b c h₁ h₂, ⟨le_inf h₁.1 h₂.1, le_inf h₁.2 h₂.2⟩,
inf_le_left := assume a b, ⟨inf_le_left, inf_le_left⟩,
inf_le_right := assume a b, ⟨inf_le_right, inf_le_right⟩,
.. prod.partial_order α β, .. prod.lattice.has_inf α β }
instance [lattice α] [lattice β] : lattice (α × β) :=
{ .. prod.lattice.semilattice_inf α β, .. prod.lattice.semilattice_sup α β }
instance [distrib_lattice α] [distrib_lattice β] : distrib_lattice (α × β) :=
{ le_sup_inf := assume a b c, ⟨le_sup_inf, le_sup_inf⟩,
.. prod.lattice.lattice α β }
end prod
|
76b34f7a3d9083535bd4fc309071a8936d371720 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Config/Script.lean | f0cbd7cb91baae0b092257adf968447c8a10027f | [
"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 | 880 | lean | /-
Copyright (c) 2021 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Util.Exit
import Lake.Config.Context
namespace Lake
/--
The type of a `Script`'s monad.
`IO` equipped information about the Lake configuration.
-/
abbrev ScriptM := LakeT IO
/--
The type of a `Script`'s function.
Similar to the `main` function's signature, except that its monad is
also equipped with information about the Lake configuration.
-/
abbrev ScriptFn := (args : List String) → ScriptM ExitCode
/--
A package `Script` is a `ScriptFn` definition that is
indexed by a `String` key and can be be run by `lake run <key> [-- <args>]`.
-/
structure Script where
fn : ScriptFn
doc? : Option String
deriving Inhabited
def Script.run (args : List String) (self : Script) : ScriptM ExitCode :=
self.fn args
|
fd25bceba5eb03b52ef79747ffb332657038de3b | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/topology/algebra/ordered/compact.lean | 479311def485518e09c3e96605baa5b5e90be43d | [
"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 | 11,124 | lean | /-
Copyright (c) 2021 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Yury Kudryashov
-/
import topology.algebra.ordered.intermediate_value
/-!
# Compactness of a closed interval
In this file we prove that a closed interval in a conditionally complete linear ordered type with
order topology (or a product of such types) is compact. We also prove the extreme value theorem
(`is_compact.exists_forall_le`, `is_compact.exists_forall_ge`): a continuous function on a compact
set takes its minimum and maximum values.
We also prove that the image of a closed interval under a continuous map is a closed interval, see
`continuous_on.image_Icc`.
## Tags
compact, extreme value theorem
-/
open classical filter order_dual topological_space function set
/-!
### Compactness of a closed interval
In this section we define a typeclass `compact_Icc_space α` saying that all closed intervals in `α`
are compact. Then we provide an instance for a `conditionally_complete_linear_order` and prove that
the product (both `α × β` and an indexed product) of spaces with this property inherits the
property.
We also prove some simple lemmas about spaces with this property.
-/
/-- This typeclass says that all closed intervals in `α` are compact. This is true for all
conditionally complete linear orders with order topology and products (finite or infinite)
of such spaces. -/
class compact_Icc_space (α : Type*) [topological_space α] [preorder α] : Prop :=
(is_compact_Icc : ∀ {a b : α}, is_compact (Icc a b))
export compact_Icc_space (is_compact_Icc)
/-- A closed interval in a conditionally complete linear order is compact. -/
@[priority 100]
instance conditionally_complete_linear_order.to_compact_Icc_space
(α : Type*) [conditionally_complete_linear_order α] [topological_space α] [order_topology α] :
compact_Icc_space α :=
begin
refine ⟨λ a b, _⟩,
cases le_or_lt a b with hab hab, swap, { simp [hab] },
refine is_compact_iff_ultrafilter_le_nhds.2 (λ f hf, _),
contrapose! hf,
rw [le_principal_iff],
have hpt : ∀ x ∈ Icc a b, {x} ∉ f,
from λ x hx hxf, hf x hx ((le_pure_iff.2 hxf).trans (pure_le_nhds x)),
set s := {x ∈ Icc a b | Icc a x ∉ f},
have hsb : b ∈ upper_bounds s, from λ x hx, hx.1.2,
have sbd : bdd_above s, from ⟨b, hsb⟩,
have ha : a ∈ s, by simp [hpt, hab],
rcases hab.eq_or_lt with rfl|hlt, { exact ha.2 },
set c := Sup s,
have hsc : is_lub s c, from is_lub_cSup ⟨a, ha⟩ sbd,
have hc : c ∈ Icc a b, from ⟨hsc.1 ha, hsc.2 hsb⟩,
specialize hf c hc,
have hcs : c ∈ s,
{ cases hc.1.eq_or_lt with heq hlt, { rwa ← heq },
refine ⟨hc, λ hcf, hf (λ U hU, _)⟩,
rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' hlt).1 (mem_nhds_within_of_mem_nhds hU)
with ⟨x, hxc, hxU⟩,
rcases ((hsc.frequently_mem ⟨a, ha⟩).and_eventually
(Ioc_mem_nhds_within_Iic ⟨hxc, le_rfl⟩)).exists
with ⟨y, ⟨hyab, hyf⟩, hy⟩,
refine mem_of_superset(f.diff_mem_iff.2 ⟨hcf, hyf⟩) (subset.trans _ hxU),
rw diff_subset_iff,
exact subset.trans Icc_subset_Icc_union_Ioc
(union_subset_union subset.rfl $ Ioc_subset_Ioc_left hy.1.le) },
cases hc.2.eq_or_lt with heq hlt, { rw ← heq, exact hcs.2 },
contrapose! hf,
intros U hU,
rcases (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hlt).1 (mem_nhds_within_of_mem_nhds hU)
with ⟨y, hxy, hyU⟩,
refine mem_of_superset _ hyU, clear_dependent U,
have hy : y ∈ Icc a b, from ⟨hc.1.trans hxy.1.le, hxy.2⟩,
by_cases hay : Icc a y ∈ f,
{ refine mem_of_superset (f.diff_mem_iff.2 ⟨f.diff_mem_iff.2 ⟨hay, hcs.2⟩, hpt y hy⟩) _,
rw [diff_subset_iff, union_comm, Ico_union_right hxy.1.le, diff_subset_iff],
exact Icc_subset_Icc_union_Icc },
{ exact ((hsc.1 ⟨hy, hay⟩).not_lt hxy.1).elim },
end
instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)]
[Π i, compact_Icc_space (α i)] : compact_Icc_space (Π i, α i) :=
⟨λ a b, pi_univ_Icc a b ▸ is_compact_univ_pi $ λ i, is_compact_Icc⟩
instance pi.compact_Icc_space' {α β : Type*} [preorder β] [topological_space β]
[compact_Icc_space β] : compact_Icc_space (α → β) :=
pi.compact_Icc_space
instance {α β : Type*} [preorder α] [topological_space α] [compact_Icc_space α]
[preorder β] [topological_space β] [compact_Icc_space β] :
compact_Icc_space (α × β) :=
⟨λ a b, (Icc_prod_eq a b).symm ▸ is_compact_Icc.prod is_compact_Icc⟩
/-- An unordered closed interval in a conditionally complete linear order is compact. -/
lemma is_compact_interval {α : Type*} [conditionally_complete_linear_order α]
[topological_space α] [order_topology α]{a b : α} : is_compact (interval a b) :=
is_compact_Icc
/-- A complete linear order is a compact space.
We do not register an instance for a `[compact_Icc_space α]` because this would only add instances
for products (indexed or not) of complete linear orders, and we have instances with higher priority
that cover these cases. -/
@[priority 100] -- See note [lower instance priority]
instance compact_space_of_complete_linear_order {α : Type*} [complete_linear_order α]
[topological_space α] [order_topology α] :
compact_space α :=
⟨by simp only [← Icc_bot_top, is_compact_Icc]⟩
section
variables {α : Type*} [preorder α] [topological_space α] [compact_Icc_space α]
instance compact_space_Icc (a b : α) : compact_space (Icc a b) :=
is_compact_iff_compact_space.mp is_compact_Icc
end
/-!
### Min and max elements of a compact set
-/
variables {α β : Type*} [conditionally_complete_linear_order α] [topological_space α]
[order_topology α] [topological_space β]
lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Inf s ∈ s :=
hs.is_closed.cInf_mem ne_s hs.bdd_below
lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
Sup s ∈ s :=
@is_compact.Inf_mem (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_glb s (Inf s) :=
is_glb_cInf ne_s hs.bdd_below
lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_lub s (Sup s) :=
@is_compact.is_glb_Inf (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_least s (Inf s) :=
⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩
lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
is_greatest s (Sup s) :=
@is_compact.is_least_Inf (order_dual α) _ _ _ _ hs ne_s
lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_least s x :=
⟨_, hs.is_least_Inf ne_s⟩
lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x, is_greatest s x :=
⟨_, hs.is_greatest_Sup ne_s⟩
lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_glb s x :=
⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩
lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) :
∃ x ∈ s, is_lub s x :=
⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩
lemma is_compact.exists_Inf_image_eq {s : set β} (hs : is_compact s) (ne_s : s.nonempty)
{f : β → α} (hf : continuous_on f s) :
∃ x ∈ s, Inf (f '' s) = f x :=
let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f)
in ⟨x, hxs, hx.symm⟩
lemma is_compact.exists_Sup_image_eq :
∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s →
∃ x ∈ s, Sup (f '' s) = f x :=
@is_compact.exists_Inf_image_eq (order_dual α) _ _ _ _ _
lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) :
s = Icc (Inf s) (Sup s) :=
eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed
/-!
### Extreme value theorem
-/
/-- The **extreme value theorem**: a continuous function realizes its minimum on a compact set. -/
lemma is_compact.exists_forall_le {s : set β} (hs : is_compact s) (ne_s : s.nonempty)
{f : β → α} (hf : continuous_on f s) :
∃x∈s, ∀y∈s, f x ≤ f y :=
begin
rcases (hs.image_of_continuous_on hf).exists_is_least (ne_s.image f)
with ⟨_, ⟨x, hxs, rfl⟩, hx⟩,
exact ⟨x, hxs, ball_image_iff.1 hx⟩
end
/-- The **extreme value theorem**: a continuous function realizes its maximum on a compact set. -/
lemma is_compact.exists_forall_ge :
∀ {s : set β}, is_compact s → s.nonempty → ∀ {f : β → α}, continuous_on f s →
∃x∈s, ∀y∈s, f y ≤ f x :=
@is_compact.exists_forall_le (order_dual α) _ _ _ _ _
/-- The **extreme value theorem**: if a continuous function `f` tends to infinity away from compact
sets, then it has a global minimum. -/
lemma continuous.exists_forall_le [nonempty β] {f : β → α}
(hf : continuous f) (hlim : tendsto f (cocompact β) at_top) :
∃ x, ∀ y, f x ≤ f y :=
begin
inhabit β,
obtain ⟨s : set β, hsc : is_compact s, hsf : ∀ x ∉ s, f default ≤ f x⟩ :=
(has_basis_cocompact.tendsto_iff at_top_basis).1 hlim (f default) trivial,
obtain ⟨x, -, hx⟩ : ∃ x ∈ insert default s, ∀ y ∈ insert default s, f x ≤ f y :=
(hsc.insert default).exists_forall_le (nonempty_insert _ _) hf.continuous_on,
refine ⟨x, λ y, _⟩,
by_cases hy : y ∈ s,
exacts [hx y (or.inr hy), (hx _ (or.inl rfl)).trans (hsf y hy)]
end
/-- The **extreme value theorem**: if a continuous function `f` tends to negative infinity away from
compact sets, then it has a global maximum. -/
lemma continuous.exists_forall_ge [nonempty β] {f : β → α}
(hf : continuous f) (hlim : tendsto f (cocompact β) at_bot) :
∃ x, ∀ y, f y ≤ f x :=
@continuous.exists_forall_le (order_dual α) _ _ _ _ _ _ _ hf hlim
/-!
### Image of a closed interval
-/
variables [densely_ordered α] [conditionally_complete_linear_order β] [order_topology β]
{f : α → β} {a b x y : α}
open_locale interval
lemma continuous_on.image_Icc (hab : a ≤ b) (h : continuous_on f $ Icc a b) :
f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) :=
eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩
(is_compact_Icc.image_of_continuous_on h)
lemma continuous_on.image_interval_eq_Icc (h : continuous_on f $ [a, b]) :
f '' [a, b] = Icc (Inf (f '' [a, b])) (Sup (f '' [a, b])) :=
begin
cases le_total a b with h2 h2,
{ simp_rw [interval_of_le h2] at h ⊢, exact h.image_Icc h2 },
{ simp_rw [interval_of_ge h2] at h ⊢, exact h.image_Icc h2 },
end
lemma continuous_on.image_interval (h : continuous_on f $ [a, b]) :
f '' [a, b] = [Inf (f '' [a, b]), Sup (f '' [a, b])] :=
begin
refine h.image_interval_eq_Icc.trans (interval_of_le _).symm,
refine cInf_le_cSup _ _ (nonempty_interval.image _); rw h.image_interval_eq_Icc,
exacts [bdd_below_Icc, bdd_above_Icc]
end
|
0ae01f3efe01ae68020df3cc04609517dc3ff05f | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/number_theory/number_field/class_number.lean | 9b1bb64056c76284abea50c1afb2994edb48050f | [
"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,676 | 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 number_theory.class_number.admissible_abs
import number_theory.class_number.finite
import number_theory.number_field.basic
/-!
# Class numbers of number fields
This file defines the class number of a number field as the (finite) cardinality of
the class group of its ring of integers. It also proves some elementary results
on the class number.
## Main definitions
- `number_field.class_number`: the class number of a number field is the (finite)
cardinality of the class group of its ring of integers
-/
namespace number_field
variables (K : Type*) [field K] [number_field K]
namespace ring_of_integers
noncomputable instance : fintype (class_group (ring_of_integers K)) :=
class_group.fintype_of_admissible_of_finite ℚ K absolute_value.abs_is_admissible
end ring_of_integers
/-- The class number of a number field is the (finite) cardinality of the class group. -/
noncomputable def class_number : ℕ := fintype.card (class_group (ring_of_integers K))
variables {K}
/-- The class number of a number field is `1` iff the ring of integers is a PID. -/
theorem class_number_eq_one_iff :
class_number K = 1 ↔ is_principal_ideal_ring (ring_of_integers K) :=
card_class_group_eq_one_iff
end number_field
namespace rat
open number_field
theorem class_number_eq : number_field.class_number ℚ = 1 :=
class_number_eq_one_iff.mpr $ by convert is_principal_ideal_ring.of_surjective
(rat.ring_of_integers_equiv.symm : ℤ →+* ring_of_integers ℚ)
(rat.ring_of_integers_equiv.symm.surjective)
end rat
|
0c658846890ee5c8631df78dbc081e4df6fa2ea6 | 618003631150032a5676f229d13a079ac875ff77 | /src/topology/category/Top/limits.lean | 802c9ef52c1519d2311a921936eb20d639845ba6 | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 2,695 | lean | /-
Copyright (c) 2017 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Scott Morrison, Mario Carneiro
-/
import topology.category.Top.basic
import category_theory.limits.types
open topological_space
open category_theory
open category_theory.limits
universe u
namespace Top
variables {J : Type u} [small_category J]
local notation `forget` := forget Top
def limit (F : J ⥤ Top.{u}) : cone F :=
{ X := ⟨limit (F ⋙ forget), ⨅j, (F.obj j).str.induced (limit.π (F ⋙ forget) j)⟩,
π :=
{ app := λ j, ⟨limit.π (F ⋙ forget) j, continuous_iff_le_induced.mpr (infi_le _ _)⟩,
naturality' := λ j j' f, subtype.eq ((limit.cone (F ⋙ forget)).π.naturality f) } }
def limit_is_limit (F : J ⥤ Top.{u}) : is_limit (limit F) :=
by { refine is_limit.of_faithful forget (limit.is_limit _) (λ s, ⟨_, _⟩) (λ s, rfl),
exact continuous_iff_coinduced_le.mpr (le_infi $ λ j,
coinduced_le_iff_le_induced.mp $ continuous_iff_coinduced_le.mp (s.π.app j).property) }
instance Top_has_limits : has_limits.{u} Top.{u} :=
{ has_limits_of_shape := λ J 𝒥,
{ has_limit := λ F, by exactI { cone := limit F, is_limit := limit_is_limit F } } }
instance forget_preserves_limits : preserves_limits (forget : Top.{u} ⥤ Type u) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F,
by exactI preserves_limit_of_preserves_limit_cone
(limit.is_limit F) (limit.is_limit (F ⋙ forget)) } }
def colimit (F : J ⥤ Top.{u}) : cocone F :=
{ X := ⟨colimit (F ⋙ forget), ⨆ j, (F.obj j).str.coinduced (colimit.ι (F ⋙ forget) j)⟩,
ι :=
{ app := λ j, ⟨colimit.ι (F ⋙ forget) j, continuous_iff_coinduced_le.mpr (le_supr _ j)⟩,
naturality' := λ j j' f, subtype.eq ((colimit.cocone (F ⋙ forget)).ι.naturality f) } }
def colimit_is_colimit (F : J ⥤ Top.{u}) : is_colimit (colimit F) :=
by { refine is_colimit.of_faithful forget (colimit.is_colimit _) (λ s, ⟨_, _⟩) (λ s, rfl),
exact continuous_iff_le_induced.mpr (supr_le $ λ j,
coinduced_le_iff_le_induced.mp $ continuous_iff_coinduced_le.mp (s.ι.app j).property) }
instance Top_has_colimits : has_colimits.{u} Top.{u} :=
{ has_colimits_of_shape := λ J 𝒥,
{ has_colimit := λ F, by exactI { cocone := colimit F, is_colimit := colimit_is_colimit F } } }
instance forget_preserves_colimits : preserves_colimits (forget : Top.{u} ⥤ Type u) :=
{ preserves_colimits_of_shape := λ J 𝒥,
{ preserves_colimit := λ F,
by exactI preserves_colimit_of_preserves_colimit_cocone
(colimit.is_colimit F) (colimit.is_colimit (F ⋙ forget)) } }
end Top
|
ca486f1aad60eb6bd7a34b07a91eea562ffdbddb | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/combinatorics/set_family/compression/down.lean | df9d79b4c574a6632ffd2ccac2fab88bd27e7420 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 7,588 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import data.finset.card
import data.fintype.basic
/-!
# Down-compressions
This file defines down-compression.
Down-compressing `𝒜 : finset (finset α)` along `a : α` means removing `a` from the elements of `𝒜`,
when the resulting set is not already in `𝒜`.
## Main declarations
* `finset.non_member_subfamily`: `𝒜.non_member_subfamily a` is the subfamily of sets not containing
`a`.
* `finset.member_subfamily`: `𝒜.member_subfamily a` is the image of the subfamily of sets containing
`a` under removing `a`.
* `down.compression`: Down-compression.
## Notation
`𝓓 a 𝒜` is notation for `down.compress a 𝒜` in locale `set_family`.
## References
* https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf
## Tags
compression, down-compression
-/
variables {α : Type*} [decidable_eq α] {𝒜 ℬ : finset (finset α)} {s : finset α} {a : α}
namespace finset
/-- Elements of `𝒜` that do not contain `a`. -/
def non_member_subfamily (a : α) (𝒜 : finset (finset α)) : finset (finset α) :=
𝒜.filter $ λ s, a ∉ s
/-- Image of the elements of `𝒜` which contain `a` under removing `a`. Finsets that do not contain
`a` such that `insert a s ∈ 𝒜`. -/
def member_subfamily (a : α) (𝒜 : finset (finset α)) : finset (finset α) :=
(𝒜.filter $ λ s, a ∈ s).image $ λ s, erase s a
@[simp] lemma mem_non_member_subfamily : s ∈ 𝒜.non_member_subfamily a ↔ s ∈ 𝒜 ∧ a ∉ s := mem_filter
@[simp] lemma mem_member_subfamily : s ∈ 𝒜.member_subfamily a ↔ insert a s ∈ 𝒜 ∧ a ∉ s :=
begin
simp_rw [member_subfamily, mem_image, mem_filter],
refine ⟨_, λ h, ⟨insert a s, ⟨h.1, mem_insert_self _ _⟩, erase_insert h.2⟩⟩,
rintro ⟨s, hs, rfl⟩,
rw insert_erase hs.2,
exact ⟨hs.1, not_mem_erase _ _⟩,
end
lemma non_member_subfamily_inter (a : α) (𝒜 ℬ : finset (finset α)) :
(𝒜 ∩ ℬ).non_member_subfamily a = 𝒜.non_member_subfamily a ∩ ℬ.non_member_subfamily a :=
filter_inter_distrib _ _ _
lemma member_subfamily_inter (a : α) (𝒜 ℬ : finset (finset α)) :
(𝒜 ∩ ℬ).member_subfamily a = 𝒜.member_subfamily a ∩ ℬ.member_subfamily a :=
begin
unfold member_subfamily,
rw [filter_inter_distrib, image_inter_of_inj_on _ _ ((erase_inj_on' _).mono _)],
rw [←coe_union, ←filter_union, coe_filter],
exact set.inter_subset_right _ _,
end
lemma non_member_subfamily_union (a : α) (𝒜 ℬ : finset (finset α)) :
(𝒜 ∪ ℬ).non_member_subfamily a = 𝒜.non_member_subfamily a ∪ ℬ.non_member_subfamily a :=
filter_union _ _ _
lemma member_subfamily_union (a : α) (𝒜 ℬ : finset (finset α)) :
(𝒜 ∪ ℬ).member_subfamily a = 𝒜.member_subfamily a ∪ ℬ.member_subfamily a :=
by simp_rw [member_subfamily, filter_union, image_union]
lemma card_member_subfamily_add_card_non_member_subfamily (a : α) (𝒜 : finset (finset α)) :
(𝒜.member_subfamily a).card + (𝒜.non_member_subfamily a).card = 𝒜.card :=
begin
rw [member_subfamily, non_member_subfamily, card_image_of_inj_on,
filter_card_add_filter_neg_card_eq_card],
exact (erase_inj_on' _).mono (λ s hs, (mem_filter.1 hs).2),
end
lemma member_subfamily_union_non_member_subfamily (a : α) (𝒜 : finset (finset α)) :
𝒜.member_subfamily a ∪ 𝒜.non_member_subfamily a = 𝒜.image (λ s, s.erase a) :=
begin
ext s,
simp only [mem_union, mem_member_subfamily, mem_non_member_subfamily, mem_image, exists_prop],
split,
{ rintro (h | h),
{ exact ⟨_, h.1, erase_insert h.2⟩ },
{ exact ⟨_, h.1, erase_eq_of_not_mem h.2⟩ } },
{ rintro ⟨s, hs, rfl⟩,
by_cases ha : a ∈ s,
{ exact or.inl ⟨by rwa insert_erase ha, not_mem_erase _ _⟩ },
{ exact or.inr ⟨by rwa erase_eq_of_not_mem ha, not_mem_erase _ _⟩ } }
end
@[simp] lemma member_subfamily_member_subfamily : (𝒜.member_subfamily a).member_subfamily a = ∅ :=
by { ext, simp }
@[simp] lemma member_subfamily_non_member_subfamily :
(𝒜.non_member_subfamily a).member_subfamily a = ∅ :=
by { ext, simp }
@[simp] lemma non_member_subfamily_member_subfamily :
(𝒜.member_subfamily a).non_member_subfamily a = 𝒜.member_subfamily a :=
by { ext, simp }
@[simp] lemma non_member_subfamily_non_member_subfamily :
(𝒜.non_member_subfamily a).non_member_subfamily a = 𝒜.non_member_subfamily a :=
by { ext, simp }
end finset
open finset
-- The namespace is here to distinguish from other compressions.
namespace down
/-- `a`-down-compressing `𝒜` means removing `a` from the elements of `𝒜` that contain it, when the
resulting finset is not already in `𝒜`. -/
def compression (a : α) (𝒜 : finset (finset α)) : finset (finset α) :=
(𝒜.filter $ λ s, erase s a ∈ 𝒜).disj_union ((𝒜.image $ λ s, erase s a).filter $ λ s, s ∉ 𝒜) $
λ s h₁ h₂, (mem_filter.1 h₂).2 (mem_filter.1 h₁).1
localized "notation (name := down.compression) `𝓓 ` := down.compression" in finset_family
/-- `a` is in the down-compressed family iff it's in the original and its compression is in the
original, or it's not in the original but it's the compression of something in the original. -/
lemma mem_compression : s ∈ 𝓓 a 𝒜 ↔ s ∈ 𝒜 ∧ s.erase a ∈ 𝒜 ∨ s ∉ 𝒜 ∧ insert a s ∈ 𝒜 :=
begin
simp_rw [compression, mem_disj_union, mem_filter, mem_image, and_comm (s ∉ 𝒜)],
refine or_congr_right' (and_congr_left $ λ hs,
⟨_, λ h, ⟨_, h, erase_insert $ insert_ne_self.1 $ ne_of_mem_of_not_mem h hs⟩⟩),
rintro ⟨t, ht, rfl⟩,
rwa insert_erase (erase_ne_self.1 (ne_of_mem_of_not_mem ht hs).symm),
end
lemma erase_mem_compression (hs : s ∈ 𝒜) : s.erase a ∈ 𝓓 a 𝒜 :=
begin
simp_rw [mem_compression, erase_idem, and_self],
refine (em _).imp_right (λ h, ⟨h, _⟩),
rwa insert_erase (erase_ne_self.1 (ne_of_mem_of_not_mem hs h).symm),
end
-- This is a special case of `erase_mem_compression` once we have `compression_idem`.
lemma erase_mem_compression_of_mem_compression : s ∈ 𝓓 a 𝒜 → s.erase a ∈ 𝓓 a 𝒜 :=
begin
simp_rw [mem_compression, erase_idem],
refine or.imp (λ h, ⟨h.2, h.2⟩) (λ h, _),
rwa [erase_eq_of_not_mem (insert_ne_self.1 $ ne_of_mem_of_not_mem h.2 h.1)],
end
lemma mem_compression_of_insert_mem_compression (h : insert a s ∈ 𝓓 a 𝒜) : s ∈ 𝓓 a 𝒜 :=
begin
by_cases ha : a ∈ s,
{ rwa insert_eq_of_mem ha at h },
{ rw ←erase_insert ha,
exact erase_mem_compression_of_mem_compression h }
end
/-- Down-compressing a family is idempotent. -/
@[simp] lemma compression_idem (a : α) (𝒜 : finset (finset α)) : 𝓓 a (𝓓 a 𝒜) = 𝓓 a 𝒜 :=
begin
ext s,
refine mem_compression.trans ⟨_, λ h, or.inl ⟨h, erase_mem_compression_of_mem_compression h⟩⟩,
rintro (h | h),
{ exact h.1 },
{ cases h.1 (mem_compression_of_insert_mem_compression h.2) }
end
/-- Down-compressing a family doesn't change its size. -/
@[simp] lemma card_compression (a : α) (𝒜 : finset (finset α)) : (𝓓 a 𝒜).card = 𝒜.card :=
begin
rw [compression, card_disj_union, image_filter, card_image_of_inj_on ((erase_inj_on' _).mono $
λ s hs, _), ←card_disjoint_union, filter_union_filter_neg_eq],
{ exact disjoint_filter_filter_neg _ _ },
rw [mem_coe, mem_filter] at hs,
exact not_imp_comm.1 erase_eq_of_not_mem (ne_of_mem_of_not_mem hs.1 hs.2).symm,
end
end down
|
71771d5e34fbfeb3b280ed6e041bfb9dd3939ce7 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/num4.lean | f10cf0fc77eca8dc11b28a3ac0a6b48f7ee37fdd | [
"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 | 266 | lean | --
set_option pp.notation false
set_option pp.implicit true
namespace foo
constant N : Type.{1}
constant z : N
constant o : N
constant a : N
notation 0 := z
notation 1 := o
check a = 0
end foo
check (2:nat) = 1
check foo.a = 1
open foo
check a = 1
|
305f754dac0f7e3137ab7acb7f4d6ee9b42afe95 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/241.lean | 195ca3db00e1bd792e6178f1f9f5e1476c2110be | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,757 | lean | def ex1 : IO Unit := do
let mut xs : Array Nat := #[]
let xs := xs -- Error
xs := xs.push 0
IO.println xs
def ex2 : IO Unit := do
let mut xs : Array Nat := #[]
let (xs, _) := (xs, 4) -- Error
xs := xs.push 0
IO.println xs
def ex3 : IO Unit := do
let mut xs : Array Nat := #[]
match (1, 2) with
| (xs, ys) => -- Error
xs := xs.push 0
IO.println xs
def ex4 : IO Unit := do
let mut xs : Array Nat := #[]
let (xs, _) ← pure (xs, 4) -- Error
xs := xs.push 0
IO.println xs
def ex5 : IO Unit := do
let mut xs : Array Nat := #[]
let xs ← pure xs -- Error
xs := xs.push 0
IO.println xs
def ex6 : IO Unit := do
let mut xs : Array Nat := #[]
if let some xs ← pure (some 4) then -- Error
IO.println xs
else
pure ()
def ex7 : IO Unit := do
let mut xs : Array Nat := #[]
if let some xs := some 4 then -- Error
IO.println xs
else
pure ()
def ex8 : IO Unit := do
let mut xs : Array Nat := #[]
if let some xs ← pure (some 4) then -- Error
IO.println xs
else
pure ()
def ex9 : IO Unit := do
let mut xs : Array Nat := #[]
try
IO.println xs
catch
| IO.Error.userError xs => -- Error
pure ()
| _ =>
pure ()
def ex10 : IO Unit := do
let mut xs : Array Nat := #[]
try
IO.println xs
catch xs => -- Error
pure ()
def ex11 : IO Unit := do
let mut xs : Array (Nat × Nat) := #[(1,2)]
for (xs, y) in xs do -- Error
xs := xs.push (0, 0)
IO.println xs
def ex12 : IO Unit := do
let mut xs : Array Nat := #[1,2,3]
for xs in xs do -- Error
xs := xs.push 0
IO.println xs
def ex13 : IO Unit := do
let mut xs : Array Nat := #[1,2,3]
for a in [:10], xs in [1,2,3] do -- Error
xs := xs.push 0
IO.println xs
|
1c02db178fed0a55995bf8ff0f339bc352d90f93 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/analysis/calculus/specific_functions.lean | 5c15034e568537941639139fedc2d1abf814ebc7 | [
"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,676 | 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.extend_deriv
import analysis.calculus.iterated_deriv
import analysis.special_functions.exp_log
/-!
# Smoothness of specific functions
The real function `exp_neg_inv_glue` given by `x ↦ exp (-1/x)` for `x > 0` and `0`
for `x ≤ 0` is a basic building block to construct smooth partitions of unity. We prove that it
is `C^∞` in `exp_neg_inv_glue.smooth`.
-/
noncomputable theory
open_locale classical topological_space
open polynomial real filter set
/-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0`
for `x ≤ 0`. is a basic building block to construct smooth partitions of unity. Its main property
is that it vanishes for `x ≤ 0`, it is positive for `x > 0`, and the junction between the two
behaviors is flat enough to retain smoothness. The fact that this function is `C^∞` is proved in
`exp_neg_inv_glue.smooth`. -/
def exp_neg_inv_glue (x : ℝ) : ℝ := if x ≤ 0 then 0 else exp (-x⁻¹)
namespace exp_neg_inv_glue
/-- Our goal is to prove that `exp_neg_inv_glue` is `C^∞`. For this, we compute its successive
derivatives for `x > 0`. The `n`-th derivative is of the form `P_aux n (x) exp(-1/x) / x^(2 n)`,
where `P_aux n` is computed inductively. -/
noncomputable def P_aux : ℕ → polynomial ℝ
| 0 := 1
| (n+1) := X^2 * (P_aux n).derivative + (1 - C ↑(2 * n) * X) * (P_aux n)
/-- Formula for the `n`-th derivative of `exp_neg_inv_glue`, as an auxiliary function `f_aux`. -/
def f_aux (n : ℕ) (x : ℝ) : ℝ :=
if x ≤ 0 then 0 else (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)
/-- The `0`-th auxiliary function `f_aux 0` coincides with `exp_neg_inv_glue`, by definition. -/
lemma f_aux_zero_eq : f_aux 0 = exp_neg_inv_glue :=
begin
ext x,
by_cases h : x ≤ 0,
{ simp [exp_neg_inv_glue, f_aux, h] },
{ simp [h, exp_neg_inv_glue, f_aux, ne_of_gt (not_le.1 h), P_aux] }
end
/-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n`
(given in this statement in unfolded form) is the `n+1`-th auxiliary function, since
the polynomial `P_aux (n+1)` was chosen precisely to ensure this. -/
lemma f_aux_deriv (n : ℕ) (x : ℝ) (hx : x ≠ 0) :
has_deriv_at (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n))
((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x :=
begin
have A : ∀k:ℕ, 2 * (k + 1) - 1 = 2 * k + 1, by omega,
convert (((P_aux n).has_deriv_at x).mul
(((has_deriv_at_exp _).comp x (has_deriv_at_inv hx).neg))).div
(has_deriv_at_pow (2 * n) x) (pow_ne_zero _ hx) using 1,
field_simp [hx, P_aux],
cases n; simp [nat.succ_eq_add_one, A]; ring_exp
end
/-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n`
is the `n+1`-th auxiliary function. -/
lemma f_aux_deriv_pos (n : ℕ) (x : ℝ) (hx : 0 < x) :
has_deriv_at (f_aux n) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x :=
begin
apply (f_aux_deriv n x (ne_of_gt hx)).congr_of_eventually_eq,
have : Ioi (0 : ℝ) ∈ 𝓝 x := lt_mem_nhds hx,
filter_upwards [this],
assume y hy,
have : ¬(y ≤ 0), by simpa using hy,
simp [f_aux, this]
end
/-- To get differentiability at `0` of the auxiliary functions, we need to know that their limit
is `0`, to be able to apply general differentiability extension theorems. This limit is checked in
this lemma. -/
lemma f_aux_limit (n : ℕ) :
tendsto (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) (𝓝[Ioi 0] 0) (𝓝 0) :=
begin
have A : tendsto (λx, (P_aux n).eval x) (𝓝[Ioi 0] 0) (𝓝 ((P_aux n).eval 0)) :=
(P_aux n).continuous_within_at,
have B : tendsto (λx, exp (-x⁻¹) / x^(2 * n)) (𝓝[Ioi 0] 0) (𝓝 0),
{ convert (tendsto_pow_mul_exp_neg_at_top_nhds_0 (2 * n)).comp tendsto_inv_zero_at_top,
ext x,
field_simp },
convert A.mul B;
simp [mul_div_assoc]
end
/-- Deduce from the limiting behavior at `0` of its derivative and general differentiability
extension theorems that the auxiliary function `f_aux n` is differentiable at `0`,
with derivative `0`. -/
lemma f_aux_deriv_zero (n : ℕ) : has_deriv_at (f_aux n) 0 0 :=
begin
-- we check separately differentiability on the left and on the right
have A : has_deriv_within_at (f_aux n) (0 : ℝ) (Iic 0) 0,
{ apply (has_deriv_at_const (0 : ℝ) (0 : ℝ)).has_deriv_within_at.congr,
{ assume y hy,
simp at hy,
simp [f_aux, hy] },
{ simp [f_aux, le_refl] } },
have B : has_deriv_within_at (f_aux n) (0 : ℝ) (Ici 0) 0,
{ have diff : differentiable_on ℝ (f_aux n) (Ioi 0) :=
λx hx, (f_aux_deriv_pos n x hx).differentiable_at.differentiable_within_at,
-- next line is the nontrivial bit of this proof, appealing to differentiability
-- extension results.
apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff _ self_mem_nhds_within,
{ refine (f_aux_limit (n+1)).congr' _,
apply mem_sets_of_superset self_mem_nhds_within (λx hx, _),
simp [(f_aux_deriv_pos n x hx).deriv] },
{ have : f_aux n 0 = 0, by simp [f_aux, le_refl],
simp only [continuous_within_at, this],
refine (f_aux_limit n).congr' _,
apply mem_sets_of_superset self_mem_nhds_within (λx hx, _),
have : ¬(x ≤ 0), by simpa using hx,
simp [f_aux, this] } },
simpa using A.union B,
end
/-- At every point, the auxiliary function `f_aux n` has a derivative which is
equal to `f_aux (n+1)`. -/
lemma f_aux_has_deriv_at (n : ℕ) (x : ℝ) : has_deriv_at (f_aux n) (f_aux (n+1) x) x :=
begin
-- check separately the result for `x < 0`, where it is trivial, for `x > 0`, where it is done
-- in `f_aux_deriv_pos`, and for `x = 0`, done in
-- `f_aux_deriv_zero`.
rcases lt_trichotomy x 0 with hx|hx|hx,
{ have : f_aux (n+1) x = 0, by simp [f_aux, le_of_lt hx],
rw this,
apply (has_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq,
have : Iio (0 : ℝ) ∈ 𝓝 x := gt_mem_nhds hx,
filter_upwards [this],
assume y hy,
simp [f_aux, le_of_lt hy] },
{ have : f_aux (n + 1) 0 = 0, by simp [f_aux, le_refl],
rw [hx, this],
exact f_aux_deriv_zero n },
{ have : f_aux (n+1) x = (P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n+1)),
by simp [f_aux, not_le_of_gt hx],
rw this,
exact f_aux_deriv_pos n x hx },
end
/-- The successive derivatives of the auxiliary function `f_aux 0` are the
functions `f_aux n`, by induction. -/
lemma f_aux_iterated_deriv (n : ℕ) : iterated_deriv n (f_aux 0) = f_aux n :=
begin
induction n with n IH,
{ simp },
{ simp [iterated_deriv_succ, IH],
ext x,
exact (f_aux_has_deriv_at n x).deriv }
end
/-- The function `exp_neg_inv_glue` is smooth. -/
theorem smooth : times_cont_diff ℝ ⊤ (exp_neg_inv_glue) :=
begin
rw ← f_aux_zero_eq,
apply times_cont_diff_of_differentiable_iterated_deriv (λ m hm, _),
rw f_aux_iterated_deriv m,
exact λ x, (f_aux_has_deriv_at m x).differentiable_at
end
/-- The function `exp_neg_inv_glue` vanishes on `(-∞, 0]`. -/
lemma zero_of_nonpos {x : ℝ} (hx : x ≤ 0) : exp_neg_inv_glue x = 0 :=
by simp [exp_neg_inv_glue, hx]
/-- The function `exp_neg_inv_glue` is positive on `(0, +∞)`. -/
lemma pos_of_pos {x : ℝ} (hx : 0 < x) : 0 < exp_neg_inv_glue x :=
by simp [exp_neg_inv_glue, not_le.2 hx, exp_pos]
/-- The function exp_neg_inv_glue` is nonnegative. -/
lemma nonneg (x : ℝ) : 0 ≤ exp_neg_inv_glue x :=
begin
cases le_or_gt x 0,
{ exact ge_of_eq (zero_of_nonpos h) },
{ exact le_of_lt (pos_of_pos h) }
end
end exp_neg_inv_glue
|
35eac4be29ff820699722b914d340dd6f48d449a | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/ns2.lean | e00d4ea83ffb266159b9a45ce90d58905d9504dc | [
"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 | 509 | lean | definition foo.id {A : Type} (a : A) := a
constant foo.T : Type.{1}
check foo.id
check foo.T
inductive foo.v.I | unit : foo.v.I
check foo.v.I
check foo.v.I.unit
namespace foo
check id
check T
check v.I
end foo
namespace bla
definition vvv.pr {A : Type} (a b : A) := a
check vvv.pr
end bla
check bla.vvv.pr
namespace bla
namespace vvv
check pr
inductive my.empty : Type
end vvv
end bla
check bla.vvv.my.empty
namespace foo.bla
structure vvv.xyz := mk
end foo.bla
check foo.bla.vvv.xyz.mk
|
bb573d93c238554a9fc00c2d0e164ba688004cef | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/filtered.lean | 8216dbc434c28fe1bef7d7ac5431e87d5dfd8054 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 28,578 | lean | /-
Copyright (c) 2019 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.fin_category
import category_theory.limits.cones
import category_theory.adjunction.basic
import category_theory.category.preorder
import category_theory.category.ulift
import order.bounded_order
/-!
# Filtered categories
A category is filtered if every finite diagram admits a cocone.
We give a simple characterisation of this condition as
1. for every pair of objects there exists another object "to the right",
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal, and
3. there exists some object.
Filtered colimits are often better behaved than arbitrary colimits.
See `category_theory/limits/types` for some details.
Filtered categories are nice because colimits indexed by filtered categories tend to be
easier to describe than general colimits (and more often preserved by functors).
In this file we show that any functor from a finite category to a filtered category admits a cocone:
* `cocone_nonempty [fin_category J] [is_filtered C] (F : J ⥤ C) : nonempty (cocone F)`
More generally,
for any finite collection of objects and morphisms between them in a filtered category
(even if not closed under composition) there exists some object `Z` receiving maps from all of them,
so that all the triangles (one edge from the finite set, two from morphisms to `Z`) commute.
This formulation is often more useful in practice and is available via `sup_exists`,
which takes a finset of objects, and an indexed family (indexed by source and target)
of finsets of morphisms.
Furthermore, we give special support for two diagram categories: The `bowtie` and the `tulip`.
This is because these shapes show up in the proofs that forgetful functors of algebraic categories
(e.g. `Mon`, `CommRing`, ...) preserve filtered colimits.
All of the above API, except for the `bowtie` and the `tulip`, is also provided for cofiltered
categories.
## See also
In `category_theory.limits.filtered_colimit_commutes_finite_limit` we show that filtered colimits
commute with finite limits.
-/
open function
-- declare the `v`'s first; see `category_theory.category` for an explanation
universes w v v₁ u u₁ u₂
namespace category_theory
variables (C : Type u) [category.{v} C]
/--
A category `is_filtered_or_empty` if
1. for every pair of objects there exists another object "to the right", and
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal.
-/
class is_filtered_or_empty : Prop :=
(cocone_objs : ∀ (X Y : C), ∃ Z (f : X ⟶ Z) (g : Y ⟶ Z), true)
(cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ Z (h : Y ⟶ Z), f ≫ h = g ≫ h)
/--
A category `is_filtered` if
1. for every pair of objects there exists another object "to the right",
2. for every pair of parallel morphisms there exists a morphism to the right so the compositions
are equal, and
3. there exists some object.
See <https://stacks.math.columbia.edu/tag/002V>. (They also define a diagram being filtered.)
-/
class is_filtered extends is_filtered_or_empty C : Prop :=
[nonempty : nonempty C]
@[priority 100]
instance is_filtered_or_empty_of_semilattice_sup
(α : Type u) [semilattice_sup α] : is_filtered_or_empty α :=
{ cocone_objs := λ X Y, ⟨X ⊔ Y, hom_of_le le_sup_left, hom_of_le le_sup_right, trivial⟩,
cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, (by ext)⟩, }
@[priority 100]
instance is_filtered_of_semilattice_sup_nonempty
(α : Type u) [semilattice_sup α] [nonempty α] : is_filtered α := {}
@[priority 100]
instance is_filtered_or_empty_of_directed_le (α : Type u) [preorder α] [is_directed α (≤)] :
is_filtered_or_empty α :=
{ cocone_objs := λ X Y, let ⟨Z, h1, h2⟩ := exists_ge_ge X Y in
⟨Z, hom_of_le h1, hom_of_le h2, trivial⟩,
cocone_maps := λ X Y f g, ⟨Y, 𝟙 _, by simp⟩ }
@[priority 100]
instance is_filtered_of_directed_le_nonempty (α : Type u) [preorder α] [is_directed α (≤)]
[nonempty α] :
is_filtered α := {}
-- Sanity checks
example (α : Type u) [semilattice_sup α] [order_bot α] : is_filtered α := by apply_instance
example (α : Type u) [semilattice_sup α] [order_top α] : is_filtered α := by apply_instance
instance : is_filtered (discrete punit) :=
{ cocone_objs := λ X Y, ⟨⟨punit.star⟩, ⟨⟨dec_trivial⟩⟩, ⟨⟨dec_trivial⟩⟩, trivial⟩,
cocone_maps := λ X Y f g, ⟨⟨punit.star⟩, ⟨⟨dec_trivial⟩⟩, dec_trivial⟩,
nonempty := ⟨⟨punit.star⟩⟩ }
namespace is_filtered
variables {C} [is_filtered C]
/--
`max j j'` is an arbitrary choice of object to the right of both `j` and `j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def max (j j' : C) : C :=
(is_filtered_or_empty.cocone_objs j j').some
/--
`left_to_max j j'` is an arbitrarily choice of morphism from `j` to `max j j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def left_to_max (j j' : C) : j ⟶ max j j' :=
(is_filtered_or_empty.cocone_objs j j').some_spec.some
/--
`right_to_max j j'` is an arbitrarily choice of morphism from `j'` to `max j j'`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def right_to_max (j j' : C) : j' ⟶ max j j' :=
(is_filtered_or_empty.cocone_objs j j').some_spec.some_spec.some
/--
`coeq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object
which admits a morphism `coeq_hom f f' : j' ⟶ coeq f f'` such that
`coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq {j j' : C} (f f' : j ⟶ j') : C :=
(is_filtered_or_empty.cocone_maps f f').some
/--
`coeq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism
`coeq_hom f f' : j' ⟶ coeq f f'` such that
`coeq_condition : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq_hom {j j' : C} (f f' : j ⟶ j') : j' ⟶ coeq f f' :=
(is_filtered_or_empty.cocone_maps f f').some_spec.some
/--
`coeq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that
`f ≫ coeq_hom f f' = f' ≫ coeq_hom f f'`.
-/
@[simp, reassoc]
lemma coeq_condition {j j' : C} (f f' : j ⟶ j') : f ≫ coeq_hom f f' = f' ≫ coeq_hom f f' :=
(is_filtered_or_empty.cocone_maps f f').some_spec.some_spec
open category_theory.limits
/--
Any finite collection of objects in a filtered category has an object "to the right".
-/
lemma sup_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (X ⟶ S) :=
begin
classical,
apply finset.induction_on O,
{ exact ⟨is_filtered.nonempty.some, (by rintros - ⟨⟩)⟩, },
{ rintros X O' nm ⟨S', w'⟩,
use max X S',
rintros Y mY,
obtain rfl|h := eq_or_ne Y X,
{ exact ⟨left_to_max _ _⟩, },
{ exact ⟨(w' (finset.mem_of_mem_insert_of_ne mY h)).some ≫ right_to_max _ _⟩, }, }
end
variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y))
/--
Given any `finset` of objects `{X, ...}` and
indexed collection of `finset`s of morphisms `{f, ...}` in `C`,
there exists an object `S`, with a morphism `T X : X ⟶ S` from each `X`,
such that the triangles commute: `f ≫ T Y = T X`, for `f : X ⟶ Y` in the `finset`.
-/
lemma sup_exists :
∃ (S : C) (T : Π {X : C}, X ∈ O → (X ⟶ S)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y},
(⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → f ≫ T mY = T mX :=
begin
classical,
apply finset.induction_on H,
{ obtain ⟨S, f⟩ := sup_objs_exists O,
refine ⟨S, λ X mX, (f mX).some, _⟩,
rintros - - - - - ⟨⟩, },
{ rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩,
refine ⟨coeq (f ≫ T' mY) (T' mX), λ Z mZ, T' mZ ≫ coeq_hom (f ≫ T' mY) (T' mX), _⟩,
intros X' Y' mX' mY' f' mf',
rw [←category.assoc],
by_cases h : X = X' ∧ Y = Y',
{ rcases h with ⟨rfl, rfl⟩,
by_cases hf : f = f',
{ subst hf,
apply coeq_condition, },
{ rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, },
{ rw @w' _ _ mX' mY' f' _,
apply finset.mem_of_mem_insert_of_ne mf',
contrapose! h,
obtain ⟨rfl, h⟩ := h,
rw [heq_iff_eq, psigma.mk.inj_iff] at h,
exact ⟨rfl, h.1.symm⟩ }, },
end
/--
An arbitrary choice of object "to the right"
of a finite collection of objects `O` and morphisms `H`,
making all the triangles commute.
-/
noncomputable
def sup : C :=
(sup_exists O H).some
/--
The morphisms to `sup O H`.
-/
noncomputable
def to_sup {X : C} (m : X ∈ O) :
X ⟶ sup O H :=
(sup_exists O H).some_spec.some m
/--
The triangles of consisting of a morphism in `H` and the maps to `sup O H` commute.
-/
lemma to_sup_commutes
{X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}
(mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) :
f ≫ to_sup O H mY = to_sup O H mX :=
(sup_exists O H).some_spec.some_spec mX mY mf
variables {J : Type v} [small_category J] [fin_category J]
/--
If we have `is_filtered C`, then for any functor `F : J ⥤ C` with `fin_category J`,
there exists a cocone over `F`.
-/
lemma cocone_nonempty (F : J ⥤ C) : _root_.nonempty (cocone F) :=
begin
classical,
let O := (finset.univ.image F.obj),
let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y,
⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))),
obtain ⟨Z, f, w⟩ := sup_exists O H,
refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩,
intros j j' g,
dsimp,
simp only [category.comp_id],
apply w,
simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left,
exists_prop_of_true, finset.mem_image],
exact ⟨j, rfl, j', g, (by simp)⟩,
end
/--
An arbitrary choice of cocone over `F : J ⥤ C`, for `fin_category J` and `is_filtered C`.
-/
noncomputable def cocone (F : J ⥤ C) : cocone F :=
(cocone_nonempty F).some
variables {D : Type u₁} [category.{v₁} D]
/--
If `C` is filtered, and we have a functor `R : C ⥤ D` with a left adjoint, then `D` is filtered.
-/
lemma of_right_adjoint {L : D ⥤ C} {R : C ⥤ D} (h : L ⊣ R) : is_filtered D :=
{ cocone_objs := λ X Y,
⟨_, h.hom_equiv _ _ (left_to_max _ _), h.hom_equiv _ _ (right_to_max _ _), ⟨⟩⟩,
cocone_maps := λ X Y f g,
⟨_, h.hom_equiv _ _ (coeq_hom _ _),
by rw [← h.hom_equiv_naturality_left, ← h.hom_equiv_naturality_left, coeq_condition]⟩,
nonempty := is_filtered.nonempty.map R.obj }
/-- If `C` is filtered, and we have a right adjoint functor `R : C ⥤ D`, then `D` is filtered. -/
lemma of_is_right_adjoint (R : C ⥤ D) [is_right_adjoint R] : is_filtered D :=
of_right_adjoint (adjunction.of_right_adjoint R)
/-- Being filtered is preserved by equivalence of categories. -/
lemma of_equivalence (h : C ≌ D) : is_filtered D :=
of_right_adjoint h.symm.to_adjunction
section special_shapes
/--
`max₃ j₁ j₂ j₃` is an arbitrary choice of object to the right of `j₁`, `j₂` and `j₃`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def max₃ (j₁ j₂ j₃ : C) : C := max (max j₁ j₂) j₃
/--
`first_to_max₃ j₁ j₂ j₃` is an arbitrarily choice of morphism from `j₁` to `max₃ j₁ j₂ j₃`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def first_to_max₃ (j₁ j₂ j₃ : C) : j₁ ⟶ max₃ j₁ j₂ j₃ :=
left_to_max j₁ j₂ ≫ left_to_max (max j₁ j₂) j₃
/--
`second_to_max₃ j₁ j₂ j₃` is an arbitrarily choice of morphism from `j₂` to `max₃ j₁ j₂ j₃`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def second_to_max₃ (j₁ j₂ j₃ : C) : j₂ ⟶ max₃ j₁ j₂ j₃ :=
right_to_max j₁ j₂ ≫ left_to_max (max j₁ j₂) j₃
/--
`third_to_max₃ j₁ j₂ j₃` is an arbitrarily choice of morphism from `j₃` to `max₃ j₁ j₂ j₃`,
whose existence is ensured by `is_filtered`.
-/
noncomputable def third_to_max₃ (j₁ j₂ j₃ : C) : j₃ ⟶ max₃ j₁ j₂ j₃ :=
right_to_max (max j₁ j₂) j₃
/--
`coeq₃ f g h`, for morphisms `f g h : j₁ ⟶ j₂`, is an arbitrary choice of object
which admits a morphism `coeq₃_hom f g h : j₂ ⟶ coeq₃ f g h` such that
`coeq₃_condition₁`, `coeq₃_condition₂` and `coeq₃_condition₃` are satisfied.
Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq₃ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : C :=
coeq (coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h))
(coeq_hom g h ≫ right_to_max (coeq f g) (coeq g h))
/--
`coeq₃_hom f g h`, for morphisms `f g h : j₁ ⟶ j₂`, is an arbitrary choice of morphism
`j₂ ⟶ coeq₃ f g h` such that `coeq₃_condition₁`, `coeq₃_condition₂` and `coeq₃_condition₃`
are satisfied. Its existence is ensured by `is_filtered`.
-/
noncomputable def coeq₃_hom {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) : j₂ ⟶ coeq₃ f g h :=
coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h) ≫
coeq_hom (coeq_hom f g ≫ left_to_max (coeq f g) (coeq g h))
(coeq_hom g h ≫ right_to_max (coeq f g) (coeq g h))
lemma coeq₃_condition₁ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) :
f ≫ coeq₃_hom f g h = g ≫ coeq₃_hom f g h :=
begin
dsimp [coeq₃_hom],
slice_lhs 1 2 { rw coeq_condition f g },
simp only [category.assoc],
end
lemma coeq₃_condition₂ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) :
g ≫ coeq₃_hom f g h = h ≫ coeq₃_hom f g h :=
begin
dsimp [coeq₃_hom],
slice_lhs 2 4 { rw [← category.assoc, coeq_condition _ _] },
slice_rhs 2 4 { rw [← category.assoc, coeq_condition _ _] },
slice_lhs 1 3 { rw [← category.assoc, coeq_condition _ _] },
simp only [category.assoc],
end
lemma coeq₃_condition₃ {j₁ j₂ : C} (f g h : j₁ ⟶ j₂) :
f ≫ coeq₃_hom f g h = h ≫ coeq₃_hom f g h :=
eq.trans (coeq₃_condition₁ f g h) (coeq₃_condition₂ f g h)
/--
Given a "bowtie" of morphisms
```
j₁ j₂
|\ /|
| \/ |
| /\ |
|/ \∣
vv vv
k₁ k₂
```
in a filtered category, we can construct an object `s` and two morphisms from `k₁` and `k₂` to `s`,
making the resulting squares commute.
-/
lemma bowtie {j₁ j₂ k₁ k₂ : C}
(f₁ : j₁ ⟶ k₁) (g₁ : j₁ ⟶ k₂) (f₂ : j₂ ⟶ k₁) (g₂ : j₂ ⟶ k₂) :
∃ (s : C) (α : k₁ ⟶ s) (β : k₂ ⟶ s), f₁ ≫ α = g₁ ≫ β ∧ f₂ ≫ α = g₂ ≫ β :=
begin
let sa := max k₁ k₂,
let sb := coeq (f₁ ≫ left_to_max _ _) (g₁ ≫ right_to_max _ _),
let sc := coeq (f₂ ≫ left_to_max _ _) (g₂ ≫ right_to_max _ _),
let sd := max sb sc,
let s := coeq ((coeq_hom _ _ : sa ⟶ sb) ≫ left_to_max _ _)
((coeq_hom _ _ : sa ⟶ sc) ≫ right_to_max _ _),
use s,
fsplit,
exact left_to_max k₁ k₂ ≫ coeq_hom _ _ ≫ left_to_max sb sc ≫ coeq_hom _ _,
fsplit,
exact right_to_max k₁ k₂ ≫ coeq_hom _ _ ≫ right_to_max sb sc ≫ coeq_hom _ _,
fsplit,
{ slice_lhs 1 3 { rw [←category.assoc, coeq_condition], },
slice_lhs 3 5 { rw [←category.assoc, coeq_condition], },
simp only [category.assoc], },
{ slice_lhs 3 5 { rw [←category.assoc, coeq_condition], },
slice_lhs 1 3 { rw [←category.assoc, coeq_condition], },
simp only [category.assoc], }
end
/--
Given a "tulip" of morphisms
```
j₁ j₂ j₃
|\ / \ / |
| \ / \ / |
| vv vv |
\ k₁ k₂ /
\ /
\ /
\ /
\ /
v v
l
```
in a filtered category, we can construct an object `s` and three morphisms from `k₁`, `k₂` and `l`
to `s`, making the resulting sqaures commute.
-/
lemma tulip {j₁ j₂ j₃ k₁ k₂ l : C} (f₁ : j₁ ⟶ k₁) (f₂ : j₂ ⟶ k₁) (f₃ : j₂ ⟶ k₂) (f₄ : j₃ ⟶ k₂)
(g₁ : j₁ ⟶ l) (g₂ : j₃ ⟶ l) :
∃ (s : C) (α : k₁ ⟶ s) (β : l ⟶ s) (γ : k₂ ⟶ s),
f₁ ≫ α = g₁ ≫ β ∧ f₂ ≫ α = f₃ ≫ γ ∧ f₄ ≫ γ = g₂ ≫ β :=
begin
let sa := max₃ k₁ l k₂,
let sb := coeq (f₁ ≫ first_to_max₃ k₁ l k₂) (g₁ ≫ second_to_max₃ k₁ l k₂),
let sc := coeq (f₂ ≫ first_to_max₃ k₁ l k₂) (f₃ ≫ third_to_max₃ k₁ l k₂),
let sd := coeq (f₄ ≫ third_to_max₃ k₁ l k₂) (g₂ ≫ second_to_max₃ k₁ l k₂),
let se := max₃ sb sc sd,
let sf := coeq₃ (coeq_hom _ _ ≫ first_to_max₃ sb sc sd)
(coeq_hom _ _ ≫ second_to_max₃ sb sc sd) (coeq_hom _ _ ≫ third_to_max₃ sb sc sd),
use sf,
use first_to_max₃ k₁ l k₂ ≫ coeq_hom _ _ ≫ first_to_max₃ sb sc sd ≫ coeq₃_hom _ _ _,
use second_to_max₃ k₁ l k₂ ≫ coeq_hom _ _ ≫ second_to_max₃ sb sc sd ≫ coeq₃_hom _ _ _,
use third_to_max₃ k₁ l k₂ ≫ coeq_hom _ _ ≫ third_to_max₃ sb sc sd ≫ coeq₃_hom _ _ _,
fsplit,
slice_lhs 1 3 { rw [← category.assoc, coeq_condition] },
slice_lhs 3 6 { rw [← category.assoc, coeq₃_condition₁] },
simp only [category.assoc],
fsplit,
slice_lhs 3 6 { rw [← category.assoc, coeq₃_condition₁] },
slice_lhs 1 3 { rw [← category.assoc, coeq_condition] },
slice_rhs 3 6 { rw [← category.assoc, ← coeq₃_condition₂] },
simp only [category.assoc],
slice_rhs 3 6 { rw [← category.assoc, coeq₃_condition₂] },
slice_rhs 1 3 { rw [← category.assoc, ← coeq_condition] },
simp only [category.assoc],
end
end special_shapes
end is_filtered
/--
A category `is_cofiltered_or_empty` if
1. for every pair of objects there exists another object "to the left", and
2. for every pair of parallel morphisms there exists a morphism to the left so the compositions
are equal.
-/
class is_cofiltered_or_empty : Prop :=
(cocone_objs : ∀ (X Y : C), ∃ W (f : W ⟶ X) (g : W ⟶ Y), true)
(cocone_maps : ∀ ⦃X Y : C⦄ (f g : X ⟶ Y), ∃ W (h : W ⟶ X), h ≫ f = h ≫ g)
/--
A category `is_cofiltered` if
1. for every pair of objects there exists another object "to the left",
2. for every pair of parallel morphisms there exists a morphism to the left so the compositions
are equal, and
3. there exists some object.
See <https://stacks.math.columbia.edu/tag/04AZ>.
-/
class is_cofiltered extends is_cofiltered_or_empty C : Prop :=
[nonempty : nonempty C]
@[priority 100]
instance is_cofiltered_or_empty_of_semilattice_inf
(α : Type u) [semilattice_inf α] : is_cofiltered_or_empty α :=
{ cocone_objs := λ X Y, ⟨X ⊓ Y, hom_of_le inf_le_left, hom_of_le inf_le_right, trivial⟩,
cocone_maps := λ X Y f g, ⟨X, 𝟙 _, (by ext)⟩, }
@[priority 100]
instance is_cofiltered_of_semilattice_inf_nonempty
(α : Type u) [semilattice_inf α] [nonempty α] : is_cofiltered α := {}
@[priority 100]
instance is_cofiltered_or_empty_of_directed_ge (α : Type u) [preorder α]
[is_directed α (≥)] :
is_cofiltered_or_empty α :=
{ cocone_objs := λ X Y, let ⟨Z, hX, hY⟩ := exists_le_le X Y in
⟨Z, hom_of_le hX, hom_of_le hY, trivial⟩,
cocone_maps := λ X Y f g, ⟨X, 𝟙 _, by simp⟩ }
@[priority 100]
instance is_cofiltered_of_directed_ge_nonempty (α : Type u) [preorder α] [is_directed α (≥)]
[nonempty α] :
is_cofiltered α := {}
-- Sanity checks
example (α : Type u) [semilattice_inf α] [order_bot α] : is_cofiltered α := by apply_instance
example (α : Type u) [semilattice_inf α] [order_top α] : is_cofiltered α := by apply_instance
instance : is_cofiltered (discrete punit) :=
{ cocone_objs := λ X Y, ⟨⟨punit.star⟩, ⟨⟨dec_trivial⟩⟩, ⟨⟨dec_trivial⟩⟩, trivial⟩,
cocone_maps := λ X Y f g, ⟨⟨punit.star⟩, ⟨⟨dec_trivial⟩⟩, dec_trivial⟩,
nonempty := ⟨⟨punit.star⟩⟩ }
namespace is_cofiltered
variables {C} [is_cofiltered C]
/--
`min j j'` is an arbitrary choice of object to the left of both `j` and `j'`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min (j j' : C) : C :=
(is_cofiltered_or_empty.cocone_objs j j').some
/--
`min_to_left j j'` is an arbitrarily choice of morphism from `min j j'` to `j`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min_to_left (j j' : C) : min j j' ⟶ j :=
(is_cofiltered_or_empty.cocone_objs j j').some_spec.some
/--
`min_to_right j j'` is an arbitrarily choice of morphism from `min j j'` to `j'`,
whose existence is ensured by `is_cofiltered`.
-/
noncomputable def min_to_right (j j' : C) : min j j' ⟶ j' :=
(is_cofiltered_or_empty.cocone_objs j j').some_spec.some_spec.some
/--
`eq f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of object
which admits a morphism `eq_hom f f' : eq f f' ⟶ j` such that
`eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
Its existence is ensured by `is_cofiltered`.
-/
noncomputable def eq {j j' : C} (f f' : j ⟶ j') : C :=
(is_cofiltered_or_empty.cocone_maps f f').some
/--
`eq_hom f f'`, for morphisms `f f' : j ⟶ j'`, is an arbitrary choice of morphism
`eq_hom f f' : eq f f' ⟶ j` such that
`eq_condition : eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
Its existence is ensured by `is_cofiltered`.
-/
noncomputable def eq_hom {j j' : C} (f f' : j ⟶ j') : eq f f' ⟶ j :=
(is_cofiltered_or_empty.cocone_maps f f').some_spec.some
/--
`eq_condition f f'`, for morphisms `f f' : j ⟶ j'`, is the proof that
`eq_hom f f' ≫ f = eq_hom f f' ≫ f'`.
-/
@[simp, reassoc]
lemma eq_condition {j j' : C} (f f' : j ⟶ j') : eq_hom f f' ≫ f = eq_hom f f' ≫ f' :=
(is_cofiltered_or_empty.cocone_maps f f').some_spec.some_spec
open category_theory.limits
/--
Any finite collection of objects in a cofiltered category has an object "to the left".
-/
lemma inf_objs_exists (O : finset C) : ∃ (S : C), ∀ {X}, X ∈ O → _root_.nonempty (S ⟶ X) :=
begin
classical,
apply finset.induction_on O,
{ exact ⟨is_cofiltered.nonempty.some, (by rintros - ⟨⟩)⟩, },
{ rintros X O' nm ⟨S', w'⟩,
use min X S',
rintros Y mY,
obtain rfl|h := eq_or_ne Y X,
{ exact ⟨min_to_left _ _⟩, },
{ exact ⟨min_to_right _ _ ≫ (w' (finset.mem_of_mem_insert_of_ne mY h)).some⟩, }, }
end
variables (O : finset C) (H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y))
/--
Given any `finset` of objects `{X, ...}` and
indexed collection of `finset`s of morphisms `{f, ...}` in `C`,
there exists an object `S`, with a morphism `T X : S ⟶ X` from each `X`,
such that the triangles commute: `T X ≫ f = T Y`, for `f : X ⟶ Y` in the `finset`.
-/
lemma inf_exists :
∃ (S : C) (T : Π {X : C}, X ∈ O → (S ⟶ X)), ∀ {X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y},
(⟨X, Y, mX, mY, f⟩ : (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H → T mX ≫ f = T mY :=
begin
classical,
apply finset.induction_on H,
{ obtain ⟨S, f⟩ := inf_objs_exists O,
refine ⟨S, λ X mX, (f mX).some, _⟩,
rintros - - - - - ⟨⟩, },
{ rintros ⟨X, Y, mX, mY, f⟩ H' nmf ⟨S', T', w'⟩,
refine ⟨eq (T' mX ≫ f) (T' mY), λ Z mZ, eq_hom (T' mX ≫ f) (T' mY) ≫ T' mZ, _⟩,
intros X' Y' mX' mY' f' mf',
rw [category.assoc],
by_cases h : X = X' ∧ Y = Y',
{ rcases h with ⟨rfl, rfl⟩,
by_cases hf : f = f',
{ subst hf,
apply eq_condition, },
{ rw @w' _ _ mX mY f' (by simpa [hf ∘ eq.symm] using mf') }, },
{ rw @w' _ _ mX' mY' f' _,
apply finset.mem_of_mem_insert_of_ne mf',
contrapose! h,
obtain ⟨rfl, h⟩ := h,
rw [heq_iff_eq, psigma.mk.inj_iff] at h,
exact ⟨rfl, h.1.symm⟩ }, },
end
/--
An arbitrary choice of object "to the left"
of a finite collection of objects `O` and morphisms `H`,
making all the triangles commute.
-/
noncomputable
def inf : C :=
(inf_exists O H).some
/--
The morphisms from `inf O H`.
-/
noncomputable
def inf_to {X : C} (m : X ∈ O) :
inf O H ⟶ X :=
(inf_exists O H).some_spec.some m
/--
The triangles consisting of a morphism in `H` and the maps from `inf O H` commute.
-/
lemma inf_to_commutes
{X Y : C} (mX : X ∈ O) (mY : Y ∈ O) {f : X ⟶ Y}
(mf : (⟨X, Y, mX, mY, f⟩ : Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) ∈ H) :
inf_to O H mX ≫ f = inf_to O H mY :=
(inf_exists O H).some_spec.some_spec mX mY mf
variables {J : Type w} [small_category J] [fin_category J]
/--
If we have `is_cofiltered C`, then for any functor `F : J ⥤ C` with `fin_category J`,
there exists a cone over `F`.
-/
lemma cone_nonempty (F : J ⥤ C) : _root_.nonempty (cone F) :=
begin
classical,
let O := (finset.univ.image F.obj),
let H : finset (Σ' (X Y : C) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
finset.univ.bUnion (λ X : J, finset.univ.bUnion (λ Y : J, finset.univ.image (λ f : X ⟶ Y,
⟨F.obj X, F.obj Y, by simp, by simp, F.map f⟩))),
obtain ⟨Z, f, w⟩ := inf_exists O H,
refine ⟨⟨Z, ⟨λ X, f (by simp), _⟩⟩⟩,
intros j j' g,
dsimp,
simp only [category.id_comp],
symmetry,
apply w,
simp only [finset.mem_univ, finset.mem_bUnion, exists_and_distrib_left,
exists_prop_of_true, finset.mem_image],
exact ⟨j, rfl, j', g, (by simp)⟩,
end
/--
An arbitrary choice of cone over `F : J ⥤ C`, for `fin_category J` and `is_cofiltered C`.
-/
noncomputable def cone (F : J ⥤ C) : cone F :=
(cone_nonempty F).some
variables {D : Type u₁} [category.{v₁} D]
/--
If `C` is cofiltered, and we have a functor `L : C ⥤ D` with a right adjoint,
then `D` is cofiltered.
-/
lemma of_left_adjoint {L : C ⥤ D} {R : D ⥤ C} (h : L ⊣ R) : is_cofiltered D :=
{ cocone_objs := λ X Y,
⟨L.obj (min (R.obj X) (R.obj Y)),
(h.hom_equiv _ X).symm (min_to_left _ _), (h.hom_equiv _ Y).symm (min_to_right _ _), ⟨⟩⟩,
cocone_maps := λ X Y f g,
⟨L.obj (eq (R.map f) (R.map g)), (h.hom_equiv _ _).symm (eq_hom _ _),
by rw [← h.hom_equiv_naturality_right_symm, ← h.hom_equiv_naturality_right_symm,
eq_condition]⟩,
nonempty := is_cofiltered.nonempty.map L.obj }
/-- If `C` is cofiltered, and we have a left adjoint functor `L : C ⥤ D`, then `D` is cofiltered. -/
lemma of_is_left_adjoint (L : C ⥤ D) [is_left_adjoint L] : is_cofiltered D :=
of_left_adjoint (adjunction.of_left_adjoint L)
/-- Being cofiltered is preserved by equivalence of categories. -/
lemma of_equivalence (h : C ≌ D) : is_cofiltered D :=
of_left_adjoint h.to_adjunction
end is_cofiltered
section opposite
open opposite
instance is_cofiltered_op_of_is_filtered [is_filtered C] : is_cofiltered Cᵒᵖ :=
{ cocone_objs := λ X Y, ⟨op (is_filtered.max X.unop Y.unop),
(is_filtered.left_to_max _ _).op, (is_filtered.right_to_max _ _).op, trivial⟩,
cocone_maps := λ X Y f g, ⟨op (is_filtered.coeq f.unop g.unop),
(is_filtered.coeq_hom _ _).op, begin
rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp),
← op_comp, ← op_comp],
congr' 1,
exact is_filtered.coeq_condition f.unop g.unop,
end⟩,
nonempty := ⟨op is_filtered.nonempty.some⟩ }
instance is_filtered_op_of_is_cofiltered [is_cofiltered C] : is_filtered Cᵒᵖ :=
{ cocone_objs := λ X Y, ⟨op (is_cofiltered.min X.unop Y.unop),
(is_cofiltered.min_to_left X.unop Y.unop).op,
(is_cofiltered.min_to_right X.unop Y.unop).op, trivial⟩,
cocone_maps := λ X Y f g, ⟨op (is_cofiltered.eq f.unop g.unop),
(is_cofiltered.eq_hom f.unop g.unop).op, begin
rw [(show f = f.unop.op, by simp), (show g = g.unop.op, by simp),
← op_comp, ← op_comp],
congr' 1,
exact is_cofiltered.eq_condition f.unop g.unop,
end⟩,
nonempty := ⟨op is_cofiltered.nonempty.some⟩ }
end opposite
section ulift
instance [is_filtered C] : is_filtered (ulift.{u₂} C) :=
is_filtered.of_equivalence ulift.equivalence
instance [is_cofiltered C] : is_cofiltered (ulift.{u₂} C) :=
is_cofiltered.of_equivalence ulift.equivalence
instance [is_filtered C] : is_filtered (ulift_hom C) :=
is_filtered.of_equivalence ulift_hom.equiv
instance [is_cofiltered C] : is_cofiltered (ulift_hom C) :=
is_cofiltered.of_equivalence ulift_hom.equiv
instance [is_filtered C] : is_filtered (as_small C) :=
is_filtered.of_equivalence as_small.equiv
instance [is_cofiltered C] : is_cofiltered (as_small C) :=
is_cofiltered.of_equivalence as_small.equiv
end ulift
end category_theory
|
31ed1d01a22c3e8083cce056a9870ee02d0a277a | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/number_theory/class_number/admissible_absolute_value.lean | 745d6a7b62df4e265442cbd1a9394588ea35d823 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,861 | 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.real.basic
import combinatorics.pigeonhole
import algebra.order.euclidean_absolute_value
/-!
# Admissible absolute values
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines a structure `absolute_value.is_admissible` which we use to show the class number
of the ring of integers of a global field is finite.
## Main definitions
* `absolute_value.is_admissible abv` states the absolute value `abv : R → ℤ`
respects the Euclidean domain structure on `R`, and that a large enough set
of elements of `R^n` contains a pair of elements whose remainders are
pointwise close together.
## Main results
* `absolute_value.abs_is_admissible` shows the "standard" absolute value on `ℤ`,
mapping negative `x` to `-x`, is admissible.
* `polynomial.card_pow_degree_is_admissible` shows `card_pow_degree`,
mapping `p : polynomial 𝔽_q` to `q ^ degree p`, is admissible
-/
local infix ` ≺ `:50 := euclidean_domain.r
namespace absolute_value
variables {R : Type*} [euclidean_domain R]
variables (abv : absolute_value R ℤ)
/-- An absolute value `R → ℤ` is admissible if it respects the Euclidean domain
structure and a large enough set of elements in `R^n` will contain a pair of
elements whose remainders are pointwise close together. -/
structure is_admissible extends is_euclidean abv :=
(card : ℝ → ℕ)
(exists_partition' : ∀ (n : ℕ) {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0) (A : fin n → R),
∃ (t : fin n → fin (card ε)),
∀ i₀ i₁, t i₀ = t i₁ → (abv (A i₁ % b - A i₀ % b) : ℝ) < abv b • ε)
attribute [protected] is_admissible.card
namespace is_admissible
variables {abv}
/-- For all `ε > 0` and finite families `A`, we can partition the remainders of `A` mod `b`
into `abv.card ε` sets, such that all elements in each part of remainders are close together. -/
lemma exists_partition {ι : Type*} [fintype ι] {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0)
(A : ι → R) (h : abv.is_admissible) :
∃ (t : ι → fin (h.card ε)),
∀ i₀ i₁, t i₀ = t i₁ → (abv (A i₁ % b - A i₀ % b) : ℝ) < abv b • ε :=
begin
let e := fintype.equiv_fin ι,
obtain ⟨t, ht⟩ := h.exists_partition' (fintype.card ι) hε hb (A ∘ e.symm),
refine ⟨t ∘ e, λ i₀ i₁ h, _⟩,
convert ht (e i₀) (e i₁) h; simp only [e.symm_apply_apply]
end
/-- Any large enough family of vectors in `R^n` has a pair of elements
whose remainders are close together, pointwise. -/
lemma exists_approx_aux (n : ℕ) (h : abv.is_admissible) :
∀ {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0) (A : fin (h.card ε ^ n).succ → (fin n → R)),
∃ (i₀ i₁), (i₀ ≠ i₁) ∧ ∀ k, (abv (A i₁ k % b - A i₀ k % b) : ℝ) < abv b • ε :=
begin
haveI := classical.dec_eq R,
induction n with n ih,
{ intros ε hε b hb A,
refine ⟨0, 1, _, _⟩,
{ simp },
rintros ⟨i, ⟨⟩⟩ },
intros ε hε b hb A,
set M := h.card ε with hM,
-- By the "nicer" pigeonhole principle, we can find a collection `s`
-- of more than `M^n` remainders where the first components lie close together:
obtain ⟨s, s_inj, hs⟩ : ∃ s : fin (M ^ n).succ → fin (M ^ n.succ).succ,
function.injective s ∧
∀ i₀ i₁, (abv (A (s i₁) 0 % b - A (s i₀) 0 % b) : ℝ) < abv b • ε,
{ -- We can partition the `A`s into `M` subsets where
-- the first components lie close together:
obtain ⟨t, ht⟩ : ∃ (t : fin (M ^ n.succ).succ → fin M),
∀ i₀ i₁, t i₀ = t i₁ → (abv (A i₁ 0 % b - A i₀ 0 % b) : ℝ) < abv b • ε :=
h.exists_partition hε hb (λ x, A x 0),
-- Since the `M` subsets contain more than `M * M^n` elements total,
-- there must be a subset that contains more than `M^n` elements.
obtain ⟨s, hs⟩ := @fintype.exists_lt_card_fiber_of_mul_lt_card _ _ _ _ _ t (M ^ n)
(by simpa only [fintype.card_fin, pow_succ] using nat.lt_succ_self (M ^ n.succ) ),
refine ⟨λ i, (finset.univ.filter (λ x, t x = s)).to_list.nth_le i _, _, λ i₀ i₁, ht _ _ _⟩,
{ refine i.2.trans_le _, rwa finset.length_to_list },
{ intros i j h, ext, exact list.nodup_iff_nth_le_inj.mp (finset.nodup_to_list _) _ _ _ _ h },
have : ∀ i h, (finset.univ.filter (λ x, t x = s)).to_list.nth_le i h ∈
finset.univ.filter (λ x, t x = s),
{ intros i h, exact finset.mem_to_list.mp (list.nth_le_mem _ _ _) },
obtain ⟨_, h₀⟩ := finset.mem_filter.mp (this i₀ _),
obtain ⟨_, h₁⟩ := finset.mem_filter.mp (this i₁ _),
exact h₀.trans h₁.symm },
-- Since `s` is large enough, there are two elements of `A ∘ s`
-- where the second components lie close together.
obtain ⟨k₀, k₁, hk, h⟩ := ih hε hb (λ x, fin.tail (A (s x))),
refine ⟨s k₀, s k₁, λ h, hk (s_inj h), λ i, fin.cases _ (λ i, _) i⟩,
{ exact hs k₀ k₁ },
{ exact h i },
end
/-- Any large enough family of vectors in `R^ι` has a pair of elements
whose remainders are close together, pointwise. -/
lemma exists_approx {ι : Type*} [fintype ι] {ε : ℝ} (hε : 0 < ε) {b : R} (hb : b ≠ 0)
(h : abv.is_admissible)
(A : fin (h.card ε ^ fintype.card ι).succ → ι → R) :
∃ (i₀ i₁), (i₀ ≠ i₁) ∧ ∀ k, (abv (A i₁ k % b - A i₀ k % b) : ℝ) < abv b • ε :=
begin
let e := fintype.equiv_fin ι,
obtain ⟨i₀, i₁, ne, h⟩ := h.exists_approx_aux (fintype.card ι) hε hb (λ x y, A x (e.symm y)),
refine ⟨i₀, i₁, ne, λ k, _⟩,
convert h (e k); simp only [e.symm_apply_apply]
end
end is_admissible
end absolute_value
|
e6e3e53c2e85e7c2d0aa932c12bfaad25ac0f250 | 367134ba5a65885e863bdc4507601606690974c1 | /src/measure_theory/ess_sup.lean | 0418a7b3712f5f9d6d4988d79ec8884c78ea607f | [
"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 | 4,804 | 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 measure_theory.measure_space
import order.filter.ennreal
/-!
# Essential supremum and infimum
We define the essential supremum and infimum of a function `f : α → β` with respect to a measure
`μ` on `α`. The essential supremum is the infimum of the constants `c : β` such that `f x ≤ c`
almost everywhere.
TODO: The essential supremum of functions `α → ℝ≥0∞` is used in particular to define the norm in
the `L∞` space (see measure_theory/lp_space.lean).
There is a different quantity which is sometimes also called essential supremum: the least
upper-bound among measurable functions of a family of measurable functions (in an almost-everywhere
sense). We do not define that quantity here, which is simply the supremum of a map with values in
`α →ₘ[μ] β` (see measure_theory/ae_eq_fun.lean).
## Main definitions
* `ess_sup f μ := μ.ae.limsup f`
* `ess_inf f μ := μ.ae.liminf f`
-/
open measure_theory
open_locale ennreal
variables {α β : Type*} [measurable_space α] {μ : measure α}
section conditionally_complete_lattice
variable [conditionally_complete_lattice β]
/-- Essential supremum of `f` with respect to measure `μ`: the smallest `c : β` such that
`f x ≤ c` a.e. -/
def ess_sup (f : α → β) (μ : measure α) := μ.ae.limsup f
/-- Essential infimum of `f` with respect to measure `μ`: the greatest `c : β` such that
`c ≤ f x` a.e. -/
def ess_inf (f : α → β) (μ : measure α) := μ.ae.liminf f
lemma ess_sup_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_sup f μ = ess_sup g μ :=
filter.limsup_congr hfg
lemma ess_inf_congr_ae {f g : α → β} (hfg : f =ᵐ[μ] g) : ess_inf f μ = ess_inf g μ :=
@ess_sup_congr_ae α (order_dual β) _ _ _ _ _ hfg
end conditionally_complete_lattice
section complete_lattice
variable [complete_lattice β]
@[simp] lemma ess_sup_measure_zero {f : α → β} : ess_sup f 0 = ⊥ :=
le_bot_iff.mp (Inf_le (by simp [set.mem_set_of_eq, filter.eventually_le, ae_iff]))
@[simp] lemma ess_inf_measure_zero {f : α → β} : ess_inf f 0 = ⊤ :=
@ess_sup_measure_zero α (order_dual β) _ _ _
lemma ess_sup_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_sup f μ ≤ ess_sup g μ :=
filter.limsup_le_limsup hfg
lemma ess_inf_mono_ae {f g : α → β} (hfg : f ≤ᵐ[μ] g) : ess_inf f μ ≤ ess_inf g μ :=
filter.liminf_le_liminf hfg
lemma ess_sup_const (c : β) (hμ : μ ≠ 0) : ess_sup (λ x : α, c) μ = c :=
begin
haveI hμ_ne_bot : μ.ae.ne_bot := by rwa [filter.ne_bot_iff, ne.def, ae_eq_bot],
exact filter.limsup_const c,
end
lemma ess_inf_const (c : β) (hμ : μ ≠ 0) : ess_inf (λ x : α, c) μ = c :=
@ess_sup_const α (order_dual β) _ _ _ _ hμ
lemma ess_sup_const_bot : ess_sup (λ x : α, (⊥ : β)) μ = (⊥ : β) :=
filter.limsup_const_bot
lemma ess_inf_const_top : ess_inf (λ x : α, (⊤ : β)) μ = (⊤ : β) :=
filter.liminf_const_top
lemma order_iso.ess_sup_apply {γ} [complete_lattice γ] (f : α → β) (μ : measure α)
(g : β ≃o γ) :
g (ess_sup f μ) = ess_sup (λ x, g (f x)) μ :=
begin
refine order_iso.limsup_apply g _ _ _ _,
all_goals { by filter.is_bounded_default},
end
lemma order_iso.ess_inf_apply {γ} [complete_lattice γ] (f : α → β) (μ : measure α)
(g : β ≃o γ) :
g (ess_inf f μ) = ess_inf (λ x, g (f x)) μ :=
@order_iso.ess_sup_apply α (order_dual β) _ _ (order_dual γ) _ _ _ g.dual
end complete_lattice
section complete_linear_order
variable [complete_linear_order β]
lemma ae_lt_of_ess_sup_lt {f : α → β} {x : β} (hf : ess_sup f μ < x) : ∀ᵐ y ∂μ, f y < x :=
filter.eventually_lt_of_limsup_lt hf
lemma ae_lt_of_lt_ess_inf {f : α → β} {x : β} (hf : x < ess_inf f μ) : ∀ᵐ y ∂μ, x < f y :=
@ae_lt_of_ess_sup_lt α (order_dual β) _ _ _ _ _ hf
end complete_linear_order
namespace ennreal
lemma ae_le_ess_sup (f : α → ℝ≥0∞) : ∀ᵐ y ∂μ, f y ≤ ess_sup f μ :=
eventually_le_limsup f
@[simp] lemma ess_sup_eq_zero_iff {f : α → ℝ≥0∞} : ess_sup f μ = 0 ↔ f =ᵐ[μ] 0 :=
limsup_eq_zero_iff
lemma ess_sup_const_mul {f : α → ℝ≥0∞} {a : ℝ≥0∞} :
ess_sup (λ (x : α), a * (f x)) μ = a * ess_sup f μ :=
limsup_const_mul
lemma ess_sup_add_le (f g : α → ℝ≥0∞) : ess_sup (f + g) μ ≤ ess_sup f μ + ess_sup g μ :=
limsup_add_le f g
lemma ess_sup_liminf_le {ι} [encodable ι] [linear_order ι] (f : ι → α → ℝ≥0∞) :
ess_sup (λ x, filter.at_top.liminf (λ n, f n x)) μ
≤ filter.at_top.liminf (λ n, ess_sup (λ x, f n x) μ) :=
by { simp_rw ess_sup, exact ennreal.limsup_liminf_le_liminf_limsup (λ a b, f b a), }
end ennreal
|
946c0e4b7801262808188704000f507a707dc9e3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/protec_proj.lean | 136316a4596d8204945bb115de2a066efe1e4036 | [
"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 | 559 | 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 tactic.protected
open tactic
@[protect_proj without baz bar] structure foo : Type :=
(bar : unit) (baz : unit) (qux : unit)
open foo
run_cmd resolve_name `bar
run_cmd resolve_name `foo.qux
run_cmd success_if_fail $ resolve_name `qux
@[protect_proj] structure X : Type :=
(n : nat) (i : fin n)
open X
run_cmd resolve_name `X.i
run_cmd resolve_name `X.n
run_cmd success_if_fail $ resolve_name `n
|
e9cbb24f0cbe5bc744187b905552885e591669a5 | 69bc7d0780be17e452d542a93f9599488f1c0c8e | /10-31-2019.lean | f23244b91eb70e63b647d93532eb85d122a64b4e | [] | no_license | joek13/cs2102-notes | b7352285b1d1184fae25594f89f5926d74e6d7b4 | 25bb18788641b20af9cf3c429afe1da9b2f5eafb | refs/heads/master | 1,673,461,162,867 | 1,575,561,090,000 | 1,575,561,090,000 | 207,573,549 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,235 | lean | -- Notes for 10/31/2019: boooooolean
inductive fuckitwe (α : Type) : Type
| fuckitwe : α → fuckitwe
def harsh := fuckitwe bool
/-
Propositions can be formalized as types, and proofs are just values of those types
-/
/-
Review we define day to be a type.
-/
inductive day : Type
| mon
| tue
| wed
| thu
| fri
| sat
| sun
/-
This is a *computational*, its constructoras define the possible values that we can build of this type
-/
/-
Introducing the begin-end pair
The begin-end pair allows us to incrementally build values
-/
def d : day :=
begin
-- lean is in "scripting mode"
exact day.mon, -- exact must be given an argument which is *exactly* the type of
end
/-
The defenition d is an assertion that there exists a value of type day
-/
/-
Propositions are formalized as types deriving from Prop.
Constuctors define the values, which we accept as proofs of the proposition
Proofs in Lean are values of logical types
-/
inductive emily_is_from_cville : Prop
| drivers_license
| passport
| utility_bill
inductive false_prop : Prop
open emily_is_from_cville
theorem proof: emily_is_from_cville :=
begin
exact utility_bill,
end
/-
We can generalize from a specific proposition,
such as the prop that emily is from charlottesville, to
one that allows us to assert that any given person is from
Charlottesville by adding a parameter.
-/
inductive person
| mari
| jose
| jane
| bill
open person
inductive is_from_cville : person → Prop
| proof_for :
∀ (p : person), -- for any person p,
(p = mari) → is_from_cville mari -- if p is mari, then a proof that the person is from charlottesville exists
/-
Proposition with a parameter: a function that returns a proposition.
is_from_cville is a PREDICATE.
Predicates can be thought of as defining properties that apply to the arguments
-/
#check is_from_cville -- function from person → Prop
#check (is_from_cville mari) -- Prop
#check is_from_cville jane
#check is_from_cville bill
/-
Let's create a proof that mari is from cville.
-/
#check is_from_cville.proof_for mari
#check is_from_cville.proof_for jose
theorem mari_is_from_cville: is_from_cville mari :=
begin
apply is_from_cville.proof_for _ _,
exact mari,
exact eq.refl mari -- reflexive equality proof (x = x)
end
/-
Our proof_for constructor effectively allows us to derive a proof that someone is from charlottesville if we have a proof that p = mari
-/
/-
Relations
- can be reflexive (a = a, so an equality relation is reflexive)
- can be symmetric (if a = b, then b = a, so the equality relation is reflexive)
"If I accept a 'likes request' on Facebook, I have to 'like' you back"
"That doesn't exist"
-/
/-
Predicaates are often used to express properties of objects.
-/
inductive is_zero : ℕ → Prop
| zmk : ∀ (n : ℕ), n = 0 → is_zero n
#check is_zero.zmk
theorem zero_is_zero : is_zero 0 :=
begin
apply is_zero.zmk 0 (eq.refl 0)
end
/-
Inductively defined proof
-/
inductive is_even : ℕ → Prop
| pf_zero_is_even : (is_even 0)
| pf_n_minus_two_is_even :
∀ (n : ℕ), is_even n → is_even (nat.succ (nat.succ n))
open is_even
theorem zero_is_even : is_even 0 := pf_zero_is_even
theorem two_even : is_even 2 :=
begin
end |
5c26647a4064731bdf7b2e2c0811f233e3a38355 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/omega/clause_auto.lean | ff51472b175667a4a42da8c54fc321ffe246d99d | [] | 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,714 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Seul Baek
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.omega.term
import Mathlib.PostPort
namespace Mathlib
/-
Definition of linear constrain clauses.
-/
namespace omega
/-- (([t₁,...tₘ],[s₁,...,sₙ]) : clause) encodes the constraints
0 = ⟦t₁⟧ ∧ ... ∧ 0 = ⟦tₘ⟧ ∧ 0 ≤ ⟦s₁⟧ ∧ ... ∧ 0 ≤ ⟦sₙ⟧, where
⟦t⟧ is the value of (t : term). -/
def clause := List term × List term
namespace clause
/-- holds v c := clause c holds under valuation v -/
def holds (v : ℕ → ℤ) : clause → Prop := sorry
/-- sat c := there exists a valuation v under which c holds -/
def sat (c : clause) := ∃ (v : ℕ → ℤ), holds v c
/-- unsat c := there is no valuation v under which c holds -/
def unsat (c : clause) := ¬sat c
/-- append two clauses by elementwise appending -/
def append (c1 : clause) (c2 : clause) : clause :=
(prod.fst c1 ++ prod.fst c2, prod.snd c1 ++ prod.snd c2)
theorem holds_append {v : ℕ → ℤ} {c1 : clause} {c2 : clause} :
holds v c1 → holds v c2 → holds v (append c1 c2) :=
sorry
end clause
/-- There exists a satisfiable clause c in argument -/
def clauses.sat (cs : List clause) := ∃ (c : clause), ∃ (H : c ∈ cs), clause.sat c
/-- There is no satisfiable clause c in argument -/
def clauses.unsat (cs : List clause) := ¬clauses.sat cs
theorem clauses.unsat_nil : clauses.unsat [] := sorry
theorem clauses.unsat_cons (c : clause) (cs : List clause) :
clause.unsat c → clauses.unsat cs → clauses.unsat (c :: cs) :=
sorry
end Mathlib |
9214773cbbe155fec0dd7a75a6c3db95962db13c | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/e4.lean | 6a0cff2a71819c50be08c291f03228aa570c0aac | [
"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 | 626 | lean | definition Prop := Type.{0}
definition false : Prop := ∀x : Prop, x
check false
theorem false_elim (C : Prop) (H : false) : C
:= H C
definition eq {A : Type} (a b : A)
:= ∀ P : A → Prop, P a → P b
check eq
infix `=`:50 := eq
theorem refl {A : Type} (a : A) : a = a
:= λ P H, H
definition true : Prop
:= false = false
theorem trivial : true
:= refl false
theorem subst {A : Type} {P : A -> Prop} {a b : A} (H1 : a = b) (H2 : P a) : P b
:= H1 _ H2
theorem symm {A : Type} {a b : A} (H : a = b) : b = a
:= subst H (refl a)
theorem trans {A : Type} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c
:= subst H2 H1
|
a46800e7c758be18c1c1f55c80b003fd3a63ef13 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/algebra/free_algebra.lean | 45ba4b973db2df5b89239c1a887d91473b55a7a6 | [
"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 | 17,147 | lean | /-
Copyright (c) 2020 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Adam Topaz
-/
import algebra.algebra.subalgebra
import algebra.monoid_algebra.basic
import linear_algebra
/-!
# Free Algebras
Given a commutative semiring `R`, and a type `X`, we construct the free unital, associative
`R`-algebra on `X`.
## Notation
1. `free_algebra R X` is the free algebra itself. It is endowed with an `R`-algebra structure.
2. `free_algebra.ι R` is the function `X → free_algebra R X`.
3. Given a function `f : X → A` to an R-algebra `A`, `lift R f` is the lift of `f` to an
`R`-algebra morphism `free_algebra R X → A`.
## Theorems
1. `ι_comp_lift` states that the composition `(lift R f) ∘ (ι R)` is identical to `f`.
2. `lift_unique` states that whenever an R-algebra morphism `g : free_algebra R X → A` is
given whose composition with `ι R` is `f`, then one has `g = lift R f`.
3. `hom_ext` is a variant of `lift_unique` in the form of an extensionality theorem.
4. `lift_comp_ι` is a combination of `ι_comp_lift` and `lift_unique`. It states that the lift
of the composition of an algebra morphism with `ι` is the algebra morphism itself.
5. `equiv_monoid_algebra_free_monoid : free_algebra R X ≃ₐ[R] monoid_algebra R (free_monoid X)`
6. An inductive principle `induction`.
## Implementation details
We construct the free algebra on `X` as a quotient of an inductive type `free_algebra.pre` by an
inductively defined relation `free_algebra.rel`. Explicitly, the construction involves three steps:
1. We construct an inductive type `free_algebra.pre R X`, the terms of which should be thought
of as representatives for the elements of `free_algebra R X`.
It is the free type with maps from `R` and `X`, and with two binary operations `add` and `mul`.
2. We construct an inductive relation `free_algebra.rel R X` on `free_algebra.pre R X`.
This is the smallest relation for which the quotient is an `R`-algebra where addition resp.
multiplication are induced by `add` resp. `mul` from 1., and for which the map from `R` is the
structure map for the algebra.
3. The free algebra `free_algebra R X` is the quotient of `free_algebra.pre R X` by
the relation `free_algebra.rel R X`.
-/
variables (R : Type*) [comm_semiring R]
variables (X : Type*)
namespace free_algebra
/--
This inductive type is used to express representatives of the free algebra.
-/
inductive pre
| of : X → pre
| of_scalar : R → pre
| add : pre → pre → pre
| mul : pre → pre → pre
namespace pre
instance : inhabited (pre R X) := ⟨of_scalar 0⟩
-- Note: These instances are only used to simplify the notation.
/-- Coercion from `X` to `pre R X`. Note: Used for notation only. -/
def has_coe_generator : has_coe X (pre R X) := ⟨of⟩
/-- Coercion from `R` to `pre R X`. Note: Used for notation only. -/
def has_coe_semiring : has_coe R (pre R X) := ⟨of_scalar⟩
/-- Multiplication in `pre R X` defined as `pre.mul`. Note: Used for notation only. -/
def has_mul : has_mul (pre R X) := ⟨mul⟩
/-- Addition in `pre R X` defined as `pre.add`. Note: Used for notation only. -/
def has_add : has_add (pre R X) := ⟨add⟩
/-- Zero in `pre R X` defined as the image of `0` from `R`. Note: Used for notation only. -/
def has_zero : has_zero (pre R X) := ⟨of_scalar 0⟩
/-- One in `pre R X` defined as the image of `1` from `R`. Note: Used for notation only. -/
def has_one : has_one (pre R X) := ⟨of_scalar 1⟩
/--
Scalar multiplication defined as multiplication by the image of elements from `R`.
Note: Used for notation only.
-/
def has_scalar : has_scalar R (pre R X) := ⟨λ r m, mul (of_scalar r) m⟩
end pre
local attribute [instance]
pre.has_coe_generator pre.has_coe_semiring pre.has_mul pre.has_add pre.has_zero
pre.has_one pre.has_scalar
/--
Given a function from `X` to an `R`-algebra `A`, `lift_fun` provides a lift of `f` to a function
from `pre R X` to `A`. This is mainly used in the construction of `free_algebra.lift`.
-/
def lift_fun {A : Type*} [semiring A] [algebra R A] (f : X → A) : pre R X → A :=
λ t, pre.rec_on t f (algebra_map _ _) (λ _ _, (+)) (λ _ _, (*))
/--
An inductively defined relation on `pre R X` used to force the initial algebra structure on
the associated quotient.
-/
inductive rel : (pre R X) → (pre R X) → Prop
-- force `of_scalar` to be a central semiring morphism
| add_scalar {r s : R} : rel ↑(r + s) (↑r + ↑s)
| mul_scalar {r s : R} : rel ↑(r * s) (↑r * ↑s)
| central_scalar {r : R} {a : pre R X} : rel (r * a) (a * r)
-- commutative additive semigroup
| add_assoc {a b c : pre R X} : rel (a + b + c) (a + (b + c))
| add_comm {a b : pre R X} : rel (a + b) (b + a)
| zero_add {a : pre R X} : rel (0 + a) a
-- multiplicative monoid
| mul_assoc {a b c : pre R X} : rel (a * b * c) (a * (b * c))
| one_mul {a : pre R X} : rel (1 * a) a
| mul_one {a : pre R X} : rel (a * 1) a
-- distributivity
| left_distrib {a b c : pre R X} : rel (a * (b + c)) (a * b + a * c)
| right_distrib {a b c : pre R X} : rel ((a + b) * c) (a * c + b * c)
-- other relations needed for semiring
| zero_mul {a : pre R X} : rel (0 * a) 0
| mul_zero {a : pre R X} : rel (a * 0) 0
-- compatibility
| add_compat_left {a b c : pre R X} : rel a b → rel (a + c) (b + c)
| add_compat_right {a b c : pre R X} : rel a b → rel (c + a) (c + b)
| mul_compat_left {a b c : pre R X} : rel a b → rel (a * c) (b * c)
| mul_compat_right {a b c : pre R X} : rel a b → rel (c * a) (c * b)
end free_algebra
/--
The free algebra for the type `X` over the commutative semiring `R`.
-/
def free_algebra := quot (free_algebra.rel R X)
namespace free_algebra
local attribute [instance]
pre.has_coe_generator pre.has_coe_semiring pre.has_mul pre.has_add pre.has_zero
pre.has_one pre.has_scalar
instance : semiring (free_algebra R X) :=
{ add := quot.map₂ (+) (λ _ _ _, rel.add_compat_right) (λ _ _ _, rel.add_compat_left),
add_assoc := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.add_assoc },
zero := quot.mk _ 0,
zero_add := by { rintro ⟨⟩, exact quot.sound rel.zero_add },
add_zero := begin
rintros ⟨⟩,
change quot.mk _ _ = _,
rw [quot.sound rel.add_comm, quot.sound rel.zero_add],
end,
add_comm := by { rintros ⟨⟩ ⟨⟩, exact quot.sound rel.add_comm },
mul := quot.map₂ (*) (λ _ _ _, rel.mul_compat_right) (λ _ _ _, rel.mul_compat_left),
mul_assoc := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.mul_assoc },
one := quot.mk _ 1,
one_mul := by { rintros ⟨⟩, exact quot.sound rel.one_mul },
mul_one := by { rintros ⟨⟩, exact quot.sound rel.mul_one },
left_distrib := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.left_distrib },
right_distrib := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact quot.sound rel.right_distrib },
zero_mul := by { rintros ⟨⟩, exact quot.sound rel.zero_mul },
mul_zero := by { rintros ⟨⟩, exact quot.sound rel.mul_zero } }
instance : inhabited (free_algebra R X) := ⟨0⟩
instance : has_scalar R (free_algebra R X) :=
{ smul := λ r, quot.map ((*) ↑r) (λ a b, rel.mul_compat_right) }
instance : algebra R (free_algebra R X) :=
{ to_fun := λ r, quot.mk _ r,
map_one' := rfl,
map_mul' := λ _ _, quot.sound rel.mul_scalar,
map_zero' := rfl,
map_add' := λ _ _, quot.sound rel.add_scalar,
commutes' := λ _, by { rintros ⟨⟩, exact quot.sound rel.central_scalar },
smul_def' := λ _ _, rfl }
instance {S : Type*} [comm_ring S] : ring (free_algebra S X) := algebra.semiring_to_ring S
variables {X}
/--
The canonical function `X → free_algebra R X`.
-/
def ι : X → free_algebra R X := λ m, quot.mk _ m
@[simp] lemma quot_mk_eq_ι (m : X) : quot.mk (free_algebra.rel R X) m = ι R m := rfl
variables {A : Type*} [semiring A] [algebra R A]
/-- Internal definition used to define `lift` -/
private def lift_aux (f : X → A) : (free_algebra R X →ₐ[R] A) :=
{ to_fun := λ a, quot.lift_on a (lift_fun _ _ f) $ λ a b h,
begin
induction h,
{ exact (algebra_map R A).map_add h_r h_s, },
{ exact (algebra_map R A).map_mul h_r h_s },
{ apply algebra.commutes },
{ change _ + _ + _ = _ + (_ + _),
rw add_assoc },
{ change _ + _ = _ + _,
rw add_comm, },
{ change (algebra_map _ _ _) + lift_fun R X f _ = lift_fun R X f _,
simp, },
{ change _ * _ * _ = _ * (_ * _),
rw mul_assoc },
{ change (algebra_map _ _ _) * lift_fun R X f _ = lift_fun R X f _,
simp, },
{ change lift_fun R X f _ * (algebra_map _ _ _) = lift_fun R X f _,
simp, },
{ change _ * (_ + _) = _ * _ + _ * _,
rw left_distrib, },
{ change (_ + _) * _ = _ * _ + _ * _,
rw right_distrib, },
{ change (algebra_map _ _ _) * _ = algebra_map _ _ _,
simp },
{ change _ * (algebra_map _ _ _) = algebra_map _ _ _,
simp },
repeat { change lift_fun R X f _ + lift_fun R X f _ = _,
rw h_ih,
refl, },
repeat { change lift_fun R X f _ * lift_fun R X f _ = _,
rw h_ih,
refl, },
end,
map_one' := by { change algebra_map _ _ _ = _, simp },
map_mul' := by { rintros ⟨⟩ ⟨⟩, refl },
map_zero' := by { change algebra_map _ _ _ = _, simp },
map_add' := by { rintros ⟨⟩ ⟨⟩, refl },
commutes' := by tauto }
/--
Given a function `f : X → A` where `A` is an `R`-algebra, `lift R f` is the unique lift
of `f` to a morphism of `R`-algebras `free_algebra R X → A`.
-/
def lift : (X → A) ≃ (free_algebra R X →ₐ[R] A) :=
{ to_fun := lift_aux R,
inv_fun := λ F, F ∘ (ι R),
left_inv := λ f, by {ext, refl},
right_inv := λ F, by {
ext x,
rcases x,
induction x,
case pre.of : {
change ((F : free_algebra R X → A) ∘ (ι R)) _ = _,
refl },
case pre.of_scalar : {
change algebra_map _ _ x = F (algebra_map _ _ x),
rw alg_hom.commutes F x, },
case pre.add : a b ha hb {
change lift_aux R (F ∘ ι R) (quot.mk _ _ + quot.mk _ _) = F (quot.mk _ _ + quot.mk _ _),
rw [alg_hom.map_add, alg_hom.map_add, ha, hb], },
case pre.mul : a b ha hb {
change lift_aux R (F ∘ ι R) (quot.mk _ _ * quot.mk _ _) = F (quot.mk _ _ * quot.mk _ _),
rw [alg_hom.map_mul, alg_hom.map_mul, ha, hb], }, }, }
@[simp] lemma lift_aux_eq (f : X → A) : lift_aux R f = lift R f := rfl
@[simp]
lemma lift_symm_apply (F : free_algebra R X →ₐ[R] A) : (lift R).symm F = F ∘ (ι R) := rfl
variables {R X}
@[simp]
theorem ι_comp_lift (f : X → A) :
(lift R f : free_algebra R X → A) ∘ (ι R) = f := by {ext, refl}
@[simp]
theorem lift_ι_apply (f : X → A) (x) :
lift R f (ι R x) = f x := rfl
@[simp]
theorem lift_unique (f : X → A) (g : free_algebra R X →ₐ[R] A) :
(g : free_algebra R X → A) ∘ (ι R) = f ↔ g = lift R f :=
(lift R).symm_apply_eq
/-!
At this stage we set the basic definitions as `@[irreducible]`, so from this point onwards one
should only use the universal properties of the free algebra, and consider the actual implementation
as a quotient of an inductive type as completely hidden.
Of course, one still has the option to locally make these definitions `semireducible` if so desired,
and Lean is still willing in some circumstances to do unification based on the underlying
definition.
-/
attribute [irreducible] ι lift
-- Marking `free_algebra` irreducible makes `ring` instances inaccessible on quotients.
-- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241
-- For now, we avoid this by not marking it irreducible.
@[simp]
theorem lift_comp_ι (g : free_algebra R X →ₐ[R] A) :
lift R ((g : free_algebra R X → A) ∘ (ι R)) = g :=
by { rw ←lift_symm_apply, exact (lift R).apply_symm_apply g }
/-- See note [partially-applied ext lemmas]. -/
@[ext]
theorem hom_ext {f g : free_algebra R X →ₐ[R] A}
(w : ((f : free_algebra R X → A) ∘ (ι R)) = ((g : free_algebra R X → A) ∘ (ι R))) : f = g :=
begin
rw [←lift_symm_apply, ←lift_symm_apply] at w,
exact (lift R).symm.injective w,
end
/--
The free algebra on `X` is "just" the monoid algebra on the free monoid on `X`.
This would be useful when constructing linear maps out of a free algebra,
for example.
-/
noncomputable
def equiv_monoid_algebra_free_monoid : free_algebra R X ≃ₐ[R] monoid_algebra R (free_monoid X) :=
alg_equiv.of_alg_hom
(lift R (λ x, (monoid_algebra.of R (free_monoid X)) (free_monoid.of x)))
((monoid_algebra.lift R (free_monoid X) (free_algebra R X)) (free_monoid.lift (ι R)))
begin
apply monoid_algebra.alg_hom_ext, intro x,
apply free_monoid.rec_on x,
{ simp, refl, },
{ intros x y ih, simp at ih, simp [ih], }
end
(by { ext, simp, })
instance [nontrivial R] : nontrivial (free_algebra R X) :=
equiv_monoid_algebra_free_monoid.surjective.nontrivial
section
open_locale classical
/-- The left-inverse of `algebra_map`. -/
def algebra_map_inv : free_algebra R X →ₐ[R] R :=
lift R (0 : X → R)
lemma algebra_map_left_inverse :
function.left_inverse algebra_map_inv (algebra_map R $ free_algebra R X) :=
λ x, by simp [algebra_map_inv]
@[simp] lemma algebra_map_inj (x y : R) :
algebra_map R (free_algebra R X) x = algebra_map R (free_algebra R X) y ↔ x = y :=
algebra_map_left_inverse.injective.eq_iff
@[simp] lemma algebra_map_eq_zero_iff (x : R) : algebra_map R (free_algebra R X) x = 0 ↔ x = 0 :=
algebra_map_inj x 0
@[simp] lemma algebra_map_eq_one_iff (x : R) : algebra_map R (free_algebra R X) x = 1 ↔ x = 1 :=
algebra_map_inj x 1
-- this proof is copied from the approach in `free_abelian_group.of_injective`
lemma ι_injective [nontrivial R] : function.injective (ι R : X → free_algebra R X) :=
λ x y hoxy, classical.by_contradiction $ assume hxy : x ≠ y,
let f : free_algebra R X →ₐ[R] R := lift R (λ z, if x = z then (1 : R) else 0) in
have hfx1 : f (ι R x) = 1, from (lift_ι_apply _ _).trans $ if_pos rfl,
have hfy1 : f (ι R y) = 1, from hoxy ▸ hfx1,
have hfy0 : f (ι R y) = 0, from (lift_ι_apply _ _).trans $ if_neg hxy,
one_ne_zero $ hfy1.symm.trans hfy0
@[simp] lemma ι_inj [nontrivial R] (x y : X) : ι R x = ι R y ↔ x = y :=
ι_injective.eq_iff
@[simp] lemma ι_ne_algebra_map [nontrivial R] (x : X) (r : R) : ι R x ≠ algebra_map R _ r :=
λ h,
let f0 : free_algebra R X →ₐ[R] R := lift R 0 in
let f1 : free_algebra R X →ₐ[R] R := lift R 1 in
have hf0 : f0 (ι R x) = 0, from lift_ι_apply _ _,
have hf1 : f1 (ι R x) = 1, from lift_ι_apply _ _,
begin
rw [h, f0.commutes, algebra.id.map_eq_self] at hf0,
rw [h, f1.commutes, algebra.id.map_eq_self] at hf1,
exact zero_ne_one (hf0.symm.trans hf1),
end
@[simp] lemma ι_ne_zero [nontrivial R] (x : X) : ι R x ≠ 0 :=
ι_ne_algebra_map x 0
@[simp] lemma ι_ne_one [nontrivial R] (x : X) : ι R x ≠ 1 :=
ι_ne_algebra_map x 1
end
end free_algebra
/- There is something weird in the above namespace that breaks the typeclass resolution of
`has_coe_to_sort` below. Closing it and reopening it fixes it... -/
namespace free_algebra
/-- An induction principle for the free algebra.
If `C` holds for the `algebra_map` of `r : R` into `free_algebra R X`, the `ι` of `x : X`, and is
preserved under addition and muliplication, then it holds for all of `free_algebra R X`.
-/
@[elab_as_eliminator]
lemma induction {C : free_algebra R X → Prop}
(h_grade0 : ∀ r, C (algebra_map R (free_algebra R X) r))
(h_grade1 : ∀ x, C (ι R x))
(h_mul : ∀ a b, C a → C b → C (a * b))
(h_add : ∀ a b, C a → C b → C (a + b))
(a : free_algebra R X) :
C a :=
begin
-- the arguments are enough to construct a subalgebra, and a mapping into it from X
let s : subalgebra R (free_algebra R X) := {
carrier := C,
mul_mem' := h_mul,
add_mem' := h_add,
algebra_map_mem' := h_grade0, },
let of : X → s := subtype.coind (ι R) h_grade1,
-- the mapping through the subalgebra is the identity
have of_id : alg_hom.id R (free_algebra R X) = s.val.comp (lift R of),
{ ext,
simp [of, subtype.coind], },
-- finding a proof is finding an element of the subalgebra
convert subtype.prop (lift R of a),
simp [alg_hom.ext_iff] at of_id,
exact of_id a,
end
/-- The star ring formed by reversing the elements of products -/
instance : star_ring (free_algebra R X) :=
{ star := opposite.unop ∘ lift R (opposite.op ∘ ι R),
star_involutive := λ x, by {
unfold has_star.star,
simp only [function.comp_apply],
refine free_algebra.induction R X _ _ _ _ x; intros; simp [*] },
star_mul := λ a b, by simp,
star_add := λ a b, by simp }
@[simp]
lemma star_ι (x : X) : star (ι R x) = (ι R x) :=
by simp [star, has_star.star]
@[simp]
lemma star_algebra_map (r : R) : star (algebra_map R (free_algebra R X) r) = (algebra_map R _ r) :=
by simp [star, has_star.star]
/-- `star` as an `alg_equiv` -/
def star_hom : free_algebra R X ≃ₐ[R] (free_algebra R X)ᵒᵖ :=
{ commutes' := λ r, by simp [star_algebra_map],
..star_ring_equiv }
end free_algebra
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.